@godmode-team/godmode 1.8.1 → 1.8.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./work-tab-DOrlU-Ge.js","./lit-core-CTInmNPB.js","./workspaces-C8dKMKC1.js","./ctrl-settings-niym-WgY.js","./views-settings-nvLQdpIB.js","./markdown-i_gIkIP3.js","./today-tab-BExVN_cu.js","./team-tab-DE4DvNCS.js","./brain-tab-Z-Uwg6EX.js","./second-brain-tab-BINrzjjx.js","./dashboards-tab-D22kRTMW.js","./connections-tab-DhJWQQBw.js"])))=>i.map(i=>d[i]);
2
- import{s as Fi,l as H,w as Ui,e as Wi,g as dt,h as oe,t as qi,i as Ye,j as Bi,k as ji,m as Hi,n as zi,o as Vi,p as Gi,q as Fe,r as Ue,u as K,_,v as se,x as xt,y as We,z as Pt,A as ss,B as Qi,C as ut,D as is,E as pt,F as as,G as Yi,H as os,I as Ji,J as Je,K as Xi,L as Zi,M as ea,N as ta,O as na,P as sa,Q as ia,R as aa,S as oa,T as ra,U as la,V as ca,W as da,X as ua,Y as pa,Z as ha,$ as fa,a0 as $e,a1 as on,a2 as ma,a3 as rn,a4 as ga,a5 as ya,a6 as va,a7 as ba,a8 as wa,a9 as Sa,aa as _a}from"./ctrl-settings-niym-WgY.js";import{n as ka,b as d,A as v,o as re,c as qe,i as Ta,a as Be,d as rs,t as ls,e as Aa,f as $a,r as f}from"./lit-core-CTInmNPB.js";import{c as Ca,t as X,a as B,i as $,e as xa,g as Pa,u as La,r as Ma,b as cs,n as ds,d as Ia,f as us,h as ln,p as Lt,E as Ra,j as ps,l as Ea,k as Da,T as Oa,P as Ka,s as Na,m as Fa,o as Ua,q as Wa,v as qa,w as Ba,x as ja,y as Ha,z as za,A as Va,B as Ga,C as Qa,D as Ya,F as Ja}from"./views-settings-nvLQdpIB.js";import"./markdown-i_gIkIP3.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))s(i);new MutationObserver(i=>{for(const a of i)if(a.type==="childList")for(const o of a.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&s(o)}).observe(document,{childList:!0,subtree:!0});function n(i){const a={};return i.integrity&&(a.integrity=i.integrity),i.referrerPolicy&&(a.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?a.credentials="include":i.crossOrigin==="anonymous"?a.credentials="omit":a.credentials="same-origin",a}function s(i){if(i.ep)return;i.ep=!0;const a=n(i);fetch(i.href,a)}})();const Xa=ka(Symbol("app-context")),Ce=()=>{},Za=()=>Promise.resolve(void 0);function eo(){return{connected:!1,reconnecting:!1,sessionKey:"main",assistantName:"Assistant",assistantAvatar:null,userName:"",userAvatar:null,theme:"system",themeResolved:"dark",settings:{gatewayUrl:"",token:"",sessionKey:"main",lastActiveSessionKey:"",theme:"system",chatFocusMode:!1,chatShowThinking:!1,splitRatio:.6,navCollapsed:!1,navGroupsCollapsed:{},openTabs:[],tabLastViewed:{},userName:"",userAvatar:"",chatParallelView:!1,parallelLanes:[null,null,null,null]},basePath:"",gateway:null,send:Za,setTab:Ce,addToast:Ce,openSidebar:Ce,closeSidebar:Ce}}class to{constructor(){this.listeners=new Map}on(t,n){this.listeners.has(t)||this.listeners.set(t,new Set);const s=this.listeners.get(t);return s.add(n),()=>{s.delete(n)}}emit(t,...n){const s=this.listeners.get(t);if(!s)return;const i=n[0];for(const a of s)try{a(i)}catch(o){console.error(`[event-bus] Error in handler for "${t}":`,o)}}clear(){this.listeners.clear()}}const z=new to;async function no(e,t){await Fi(e,t),await H(e,!0)}async function so(e){await Ui(e),await H(e,!0)}async function io(e){await Wi(e),await H(e,!0)}async function ao(e){await dt(e),await oe(e),await H(e,!0)}async function oo(e){await oe(e),await H(e,!0)}function ro(e){if(!Array.isArray(e))return{};const t={};for(const n of e){if(typeof n!="string")continue;const[s,...i]=n.split(":");if(!s||i.length===0)continue;const a=s.trim(),o=i.join(":").trim();a&&o&&(t[a]=o)}return t}function hs(e){return(e.channelsSnapshot?.channelAccounts?.nostr??[])[0]?.accountId??e.nostrProfileAccountId??"default"}function fs(e,t=""){return`/api/channels/nostr/${encodeURIComponent(e)}/profile${t}`}function lo(e,t,n){e.nostrProfileAccountId=t,e.nostrProfileFormState=Ca(n??void 0)}function co(e){e.nostrProfileFormState=null,e.nostrProfileAccountId=null}function uo(e,t,n){const s=e.nostrProfileFormState;s&&(e.nostrProfileFormState={...s,values:{...s.values,[t]:n},fieldErrors:{...s.fieldErrors,[t]:""}})}function po(e){const t=e.nostrProfileFormState;t&&(e.nostrProfileFormState={...t,showAdvanced:!t.showAdvanced})}async function ho(e){const t=e.nostrProfileFormState;if(!t||t.saving)return;const n=hs(e);e.nostrProfileFormState={...t,saving:!0,error:null,success:null,fieldErrors:{}};try{const s=await fetch(fs(n),{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(t.values)}),i=await s.json().catch(()=>null);if(!s.ok||i?.ok===!1||!i){const a=i?.error??`Profile update failed (${s.status})`;e.nostrProfileFormState={...t,saving:!1,error:a,success:null,fieldErrors:ro(i?.details)};return}if(!i.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 H(e,!0)}catch(s){e.nostrProfileFormState={...t,saving:!1,error:`Profile update failed: ${String(s)}`,success:null}}}async function fo(e){const t=e.nostrProfileFormState;if(!t||t.importing)return;const n=hs(e);e.nostrProfileFormState={...t,importing:!0,error:null,success:null};try{const s=await fetch(fs(n,"/import"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({autoMerge:!0})}),i=await s.json().catch(()=>null);if(!s.ok||i?.ok===!1||!i){const c=i?.error??`Profile import failed (${s.status})`;e.nostrProfileFormState={...t,importing:!1,error:c,success:null};return}const a=i.merged??i.imported??null,o=a?{...t.values,...a}:t.values,l=!!(o.banner||o.website||o.nip05||o.lud16);e.nostrProfileFormState={...t,importing:!1,values:o,error:null,success:i.saved?"Profile imported from relays. Review and publish.":"Profile imported. Review and publish.",showAdvanced:l},i.saved&&await H(e,!0)}catch(s){e.nostrProfileFormState={...t,importing:!1,error:`Profile import failed: ${String(s)}`,success:null}}}function ms(e){const t=(e??"").trim();if(!t)return null;const n=t.split(":").filter(Boolean);if(n.length<3||n[0]!=="agent")return null;const s=n[1]?.trim(),i=n.slice(2).join(":");return!s||!i?null:{agentId:s,rest:i}}function ht(e){const t=(e??"").trim();if(!t)return!1;if(t==="main")return!0;const n=t.toLowerCase();return!!(n==="agent:main:main"||n.endsWith(":main"))}function ft(e){const t=(e??"").trim();return t?!!(ht(t)||t.toLowerCase().startsWith("agent:main:")):!1}function gs(e,t){return!!(e===t||ft(e)&&ft(t)&&(ht(e)||ht(t)))}const mo=80;function ge(e){const t=e.querySelector(".chat-thread");if(t){const n=getComputedStyle(t).overflowY;if(n==="auto"||n==="scroll"||t.scrollHeight-t.clientHeight>1)return t}return null}function xe(e,t){e.chatIsAutoScrolling=!0,t.scrollTop=t.scrollHeight,e.chatNewMessagesBelow=!1,requestAnimationFrame(()=>{e.chatIsAutoScrolling=!1})}let cn=0;function F(e,t=!1){e.chatScrollFrame&&cancelAnimationFrame(e.chatScrollFrame),e.chatScrollTimeout!=null&&(clearTimeout(e.chatScrollTimeout),e.chatScrollTimeout=null);const n=t?++cn:0;e.updateComplete.then(()=>{e.chatScrollFrame=requestAnimationFrame(()=>{e.chatScrollFrame=null;const s=ge(e);if(!s){if(t){let o=0;const l=()=>{const c=ge(e);c?xe(e,c):++o<4&&setTimeout(l,80*o)};requestAnimationFrame(l)}else requestAnimationFrame(()=>{const o=ge(e);o&&(o.scrollTop=o.scrollHeight)});return}if(!(t||e.chatUserNearBottom)){e.chatNewMessagesBelow=!0;return}t&&(e.chatHasAutoScrolled=!0),xe(e,s);const a=t?150:120;e.chatScrollTimeout=window.setTimeout(()=>{e.chatScrollTimeout=null;const o=ge(e);!o||!(t||e.chatUserNearBottom)||xe(e,o)},a)})}),t&&setTimeout(()=>{if(n!==cn)return;const s=ge(e);s&&xe(e,s)},400)}function Mt(e,t=!1){e.logsScrollFrame&&cancelAnimationFrame(e.logsScrollFrame),e.updateComplete.then(()=>{e.logsScrollFrame=requestAnimationFrame(()=>{e.logsScrollFrame=null;const n=e.querySelector(".log-stream");if(!n)return;const s=n.scrollHeight-n.scrollTop-n.clientHeight;(t||s<80)&&(n.scrollTop=n.scrollHeight)})})}function ys(e,t){const n=t.currentTarget;if(!n||e.chatIsAutoScrolling)return;const s=n.scrollHeight-n.scrollTop-n.clientHeight;s<2?(e.chatUserNearBottom=!0,e.chatNewMessagesBelow=!1):s<mo?e.chatUserNearBottom=!0:e.chatUserNearBottom=!1}function vs(e,t){const n=t.currentTarget;if(!n)return;const s=n.scrollHeight-n.scrollTop-n.clientHeight;e.logsAtBottom=s<80}function ke(e){e.chatHasAutoScrolled=!1,e.chatUserNearBottom=!0,e.chatNewMessagesBelow=!1}function bs(e,t){if(e.length===0)return;const n=new Blob([`${e.join(`
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./work-tab-DwU559Bx.js","./lit-core-CTInmNPB.js","./workspaces-vzpIVgdl.js","./ctrl-settings-COfcdhha.js","./views-settings-B2UFEtoi.js","./markdown-i_gIkIP3.js","./today-tab-C6lIMzgY.js","./team-tab-Q3icI_Q-.js","./brain-tab-B1CYwAJ7.js","./second-brain-tab-DkFatLwl.js","./dashboards-tab-7hHXzWPp.js","./connections-tab-Cuv4eW0d.js"])))=>i.map(i=>d[i]);
2
+ import{s as Fi,l as H,w as Ui,e as Wi,g as dt,h as oe,t as qi,i as Ye,j as Bi,k as ji,m as Hi,n as zi,o as Vi,p as Gi,q as Fe,r as Ue,u as K,_,v as se,x as xt,y as We,z as Pt,A as ss,B as Qi,C as ut,D as is,E as pt,F as as,G as Yi,H as os,I as Ji,J as Je,K as Xi,L as Zi,M as ea,N as ta,O as na,P as sa,Q as ia,R as aa,S as oa,T as ra,U as la,V as ca,W as da,X as ua,Y as pa,Z as ha,$ as fa,a0 as $e,a1 as on,a2 as ma,a3 as rn,a4 as ga,a5 as ya,a6 as va,a7 as ba,a8 as wa,a9 as Sa,aa as _a}from"./ctrl-settings-COfcdhha.js";import{n as ka,b as d,A as v,o as re,c as qe,i as Ta,a as Be,d as rs,t as ls,e as Aa,f as $a,r as f}from"./lit-core-CTInmNPB.js";import{c as Ca,t as X,a as B,i as $,e as xa,g as Pa,u as La,r as Ma,b as cs,n as ds,d as Ia,f as us,h as ln,p as Lt,E as Ra,j as ps,l as Ea,k as Da,T as Oa,P as Ka,s as Na,m as Fa,o as Ua,q as Wa,v as qa,w as Ba,x as ja,y as Ha,z as za,A as Va,B as Ga,C as Qa,D as Ya,F as Ja}from"./views-settings-B2UFEtoi.js";import"./markdown-i_gIkIP3.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))s(i);new MutationObserver(i=>{for(const a of i)if(a.type==="childList")for(const o of a.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&s(o)}).observe(document,{childList:!0,subtree:!0});function n(i){const a={};return i.integrity&&(a.integrity=i.integrity),i.referrerPolicy&&(a.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?a.credentials="include":i.crossOrigin==="anonymous"?a.credentials="omit":a.credentials="same-origin",a}function s(i){if(i.ep)return;i.ep=!0;const a=n(i);fetch(i.href,a)}})();const Xa=ka(Symbol("app-context")),Ce=()=>{},Za=()=>Promise.resolve(void 0);function eo(){return{connected:!1,reconnecting:!1,sessionKey:"main",assistantName:"Assistant",assistantAvatar:null,userName:"",userAvatar:null,theme:"system",themeResolved:"dark",settings:{gatewayUrl:"",token:"",sessionKey:"main",lastActiveSessionKey:"",theme:"system",chatFocusMode:!1,chatShowThinking:!1,splitRatio:.6,navCollapsed:!1,navGroupsCollapsed:{},openTabs:[],tabLastViewed:{},userName:"",userAvatar:"",chatParallelView:!1,parallelLanes:[null,null,null,null]},basePath:"",gateway:null,send:Za,setTab:Ce,addToast:Ce,openSidebar:Ce,closeSidebar:Ce}}class to{constructor(){this.listeners=new Map}on(t,n){this.listeners.has(t)||this.listeners.set(t,new Set);const s=this.listeners.get(t);return s.add(n),()=>{s.delete(n)}}emit(t,...n){const s=this.listeners.get(t);if(!s)return;const i=n[0];for(const a of s)try{a(i)}catch(o){console.error(`[event-bus] Error in handler for "${t}":`,o)}}clear(){this.listeners.clear()}}const z=new to;async function no(e,t){await Fi(e,t),await H(e,!0)}async function so(e){await Ui(e),await H(e,!0)}async function io(e){await Wi(e),await H(e,!0)}async function ao(e){await dt(e),await oe(e),await H(e,!0)}async function oo(e){await oe(e),await H(e,!0)}function ro(e){if(!Array.isArray(e))return{};const t={};for(const n of e){if(typeof n!="string")continue;const[s,...i]=n.split(":");if(!s||i.length===0)continue;const a=s.trim(),o=i.join(":").trim();a&&o&&(t[a]=o)}return t}function hs(e){return(e.channelsSnapshot?.channelAccounts?.nostr??[])[0]?.accountId??e.nostrProfileAccountId??"default"}function fs(e,t=""){return`/api/channels/nostr/${encodeURIComponent(e)}/profile${t}`}function lo(e,t,n){e.nostrProfileAccountId=t,e.nostrProfileFormState=Ca(n??void 0)}function co(e){e.nostrProfileFormState=null,e.nostrProfileAccountId=null}function uo(e,t,n){const s=e.nostrProfileFormState;s&&(e.nostrProfileFormState={...s,values:{...s.values,[t]:n},fieldErrors:{...s.fieldErrors,[t]:""}})}function po(e){const t=e.nostrProfileFormState;t&&(e.nostrProfileFormState={...t,showAdvanced:!t.showAdvanced})}async function ho(e){const t=e.nostrProfileFormState;if(!t||t.saving)return;const n=hs(e);e.nostrProfileFormState={...t,saving:!0,error:null,success:null,fieldErrors:{}};try{const s=await fetch(fs(n),{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(t.values)}),i=await s.json().catch(()=>null);if(!s.ok||i?.ok===!1||!i){const a=i?.error??`Profile update failed (${s.status})`;e.nostrProfileFormState={...t,saving:!1,error:a,success:null,fieldErrors:ro(i?.details)};return}if(!i.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 H(e,!0)}catch(s){e.nostrProfileFormState={...t,saving:!1,error:`Profile update failed: ${String(s)}`,success:null}}}async function fo(e){const t=e.nostrProfileFormState;if(!t||t.importing)return;const n=hs(e);e.nostrProfileFormState={...t,importing:!0,error:null,success:null};try{const s=await fetch(fs(n,"/import"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({autoMerge:!0})}),i=await s.json().catch(()=>null);if(!s.ok||i?.ok===!1||!i){const c=i?.error??`Profile import failed (${s.status})`;e.nostrProfileFormState={...t,importing:!1,error:c,success:null};return}const a=i.merged??i.imported??null,o=a?{...t.values,...a}:t.values,l=!!(o.banner||o.website||o.nip05||o.lud16);e.nostrProfileFormState={...t,importing:!1,values:o,error:null,success:i.saved?"Profile imported from relays. Review and publish.":"Profile imported. Review and publish.",showAdvanced:l},i.saved&&await H(e,!0)}catch(s){e.nostrProfileFormState={...t,importing:!1,error:`Profile import failed: ${String(s)}`,success:null}}}function ms(e){const t=(e??"").trim();if(!t)return null;const n=t.split(":").filter(Boolean);if(n.length<3||n[0]!=="agent")return null;const s=n[1]?.trim(),i=n.slice(2).join(":");return!s||!i?null:{agentId:s,rest:i}}function ht(e){const t=(e??"").trim();if(!t)return!1;if(t==="main")return!0;const n=t.toLowerCase();return!!(n==="agent:main:main"||n.endsWith(":main"))}function ft(e){const t=(e??"").trim();return t?!!(ht(t)||t.toLowerCase().startsWith("agent:main:")):!1}function gs(e,t){return!!(e===t||ft(e)&&ft(t)&&(ht(e)||ht(t)))}const mo=80;function ge(e){const t=e.querySelector(".chat-thread");if(t){const n=getComputedStyle(t).overflowY;if(n==="auto"||n==="scroll"||t.scrollHeight-t.clientHeight>1)return t}return null}function xe(e,t){e.chatIsAutoScrolling=!0,t.scrollTop=t.scrollHeight,e.chatNewMessagesBelow=!1,requestAnimationFrame(()=>{e.chatIsAutoScrolling=!1})}let cn=0;function F(e,t=!1){e.chatScrollFrame&&cancelAnimationFrame(e.chatScrollFrame),e.chatScrollTimeout!=null&&(clearTimeout(e.chatScrollTimeout),e.chatScrollTimeout=null);const n=t?++cn:0;e.updateComplete.then(()=>{e.chatScrollFrame=requestAnimationFrame(()=>{e.chatScrollFrame=null;const s=ge(e);if(!s){if(t){let o=0;const l=()=>{const c=ge(e);c?xe(e,c):++o<4&&setTimeout(l,80*o)};requestAnimationFrame(l)}else requestAnimationFrame(()=>{const o=ge(e);o&&(o.scrollTop=o.scrollHeight)});return}if(!(t||e.chatUserNearBottom)){e.chatNewMessagesBelow=!0;return}t&&(e.chatHasAutoScrolled=!0),xe(e,s);const a=t?150:120;e.chatScrollTimeout=window.setTimeout(()=>{e.chatScrollTimeout=null;const o=ge(e);!o||!(t||e.chatUserNearBottom)||xe(e,o)},a)})}),t&&setTimeout(()=>{if(n!==cn)return;const s=ge(e);s&&xe(e,s)},400)}function Mt(e,t=!1){e.logsScrollFrame&&cancelAnimationFrame(e.logsScrollFrame),e.updateComplete.then(()=>{e.logsScrollFrame=requestAnimationFrame(()=>{e.logsScrollFrame=null;const n=e.querySelector(".log-stream");if(!n)return;const s=n.scrollHeight-n.scrollTop-n.clientHeight;(t||s<80)&&(n.scrollTop=n.scrollHeight)})})}function ys(e,t){const n=t.currentTarget;if(!n||e.chatIsAutoScrolling)return;const s=n.scrollHeight-n.scrollTop-n.clientHeight;s<2?(e.chatUserNearBottom=!0,e.chatNewMessagesBelow=!1):s<mo?e.chatUserNearBottom=!0:e.chatUserNearBottom=!1}function vs(e,t){const n=t.currentTarget;if(!n)return;const s=n.scrollHeight-n.scrollTop-n.clientHeight;e.logsAtBottom=s<80}function ke(e){e.chatHasAutoScrolled=!1,e.chatUserNearBottom=!0,e.chatNewMessagesBelow=!1}function bs(e,t){if(e.length===0)return;const n=new Blob([`${e.join(`
3
3
  `)}
4
4
  `],{type:"text/plain"}),s=URL.createObjectURL(n),i=document.createElement("a"),a=new Date().toISOString().slice(0,19).replace(/[:T]/g,"-");i.href=s,i.download=`godmode-logs-${t}-${a}.log`,i.click(),URL.revokeObjectURL(s)}function ws(e){if(typeof ResizeObserver>"u")return;const t=e.querySelector(".topbar");if(!t)return;const n=()=>{const{height:s}=t.getBoundingClientRect();e.style.setProperty("--topbar-height",`${s}px`)};n(),e.topbarObserver=new ResizeObserver(()=>n()),e.topbarObserver.observe(t)}const go=Object.freeze(Object.defineProperty({__proto__:null,exportLogs:bs,handleChatScroll:ys,handleLogsScroll:vs,observeTopbar:ws,resetChatScroll:ke,scheduleChatScroll:F,scheduleLogsScroll:Mt},Symbol.toStringTag,{value:"Module"})),O="main";function yo(e){const t=[`viewing ${X(e.tab)} tab`];return e.tab==="dashboards"&&e.activeDashboard&&t.push(`dashboard: ${e.activeDashboard.title}`),e.tab==="workspaces"&&e.selectedWorkspace&&t.push(`workspace: ${e.selectedWorkspace.name}`),e.sidebarOpen&&e.sidebarFilePath&&t.push(`viewing file: ${e.sidebarFilePath}`),`[GodMode Context: ${t.join(", ")}]`}const dn=50,vo=80,bo=12e4;function R(e,t){if(!e)return"";const n=e.trim().replace(/\n/g," ");return n.length<=t?n:n.slice(0,t-1)+"…"}function I(e){return typeof e=="string"?e:e==null?"":JSON.stringify(e)}function un(e,t){if(!t||typeof t!="object")return"";const n=t;switch(e.toLowerCase()){case"exec":return n.command?`\`${R(I(n.command),60)}\``:"";case"read":return n.path||n.file_path?`\`${R(I(n.path||n.file_path),50)}\``:"";case"write":return n.path||n.file_path?`→ \`${R(I(n.path||n.file_path),50)}\``:"";case"edit":return n.path||n.file_path?`\`${R(I(n.path||n.file_path),50)}\``:"";case"web_search":return n.query?`"${R(I(n.query),45)}"`:"";case"web_fetch":try{const m=new URL(I(n.url));return m.hostname+(m.pathname!=="/"?m.pathname.slice(0,30):"")}catch{return R(I(n.url||""),50)}case"memory_search":case"honcho_query":return n.query||n.question?`"${R(I(n.query||n.question),45)}"`:"";case"browser":const s=I(n.action),i=n.ref?` #${I(n.ref)}`:"",a=n.targetUrl?` ${R(I(n.targetUrl),30)}`:"";return`${s}${i}${a}`;case"message":return n.action?`${I(n.action)}${n.target?` → ${R(I(n.target),25)}`:""}`:"";case"sessions_spawn":return n.task?`"${R(I(n.task),40)}"`:"";case"cron":return n.action?I(n.action):"";case"files_read":return n.fileId?`file:${R(I(n.fileId),20)}`:"";case"image":return n.image?R(I(n.image),40):"";default:const o=Object.keys(n).filter(m=>!["timeout","timeoutMs"].includes(m));if(o.length===0)return"";const l=o[0],c=n[l];return typeof c=="string"?`${l}: ${R(c,35)}`:""}}function pn(e,t){if(!t)return"";const n=e.toLowerCase(),s=t.split(`
5
5
  `),i=s.length,a=t.length;if(["read","files_read"].includes(n))return`${a.toLocaleString()} chars${i>1?`, ${i} lines`:""}`;if(n==="exec")return i>1?`${i} lines`:R(s[0],50);if(["web_search","memory_search","honcho_query"].includes(n))try{const o=JSON.parse(t),l=o.results?.length??o.count??0;return`${l} result${l!==1?"s":""}`}catch{return R(t,40)}return n==="browser"?t.includes("snapshot")?"snapshot captured":t.includes("success")?"success":R(t,40):a>100?`${a.toLocaleString()} chars`:R(t,50)}function hn(e){if(!e)return!0;const t=e.toLowerCase();return!(t.includes("error:")||t.includes("failed")||t.includes("exception")||t.includes("not found"))}function wo(e){if(!e||typeof e!="object")return null;const t=e;if(typeof t.text=="string")return t.text;const n=t.content;if(!Array.isArray(n))return null;const s=n.map(i=>{if(!i||typeof i!="object")return null;const a=i;return a.type==="text"&&typeof a.text=="string"?a.text:null}).filter(i=>!!i);return s.length===0?null:s.join(`
@@ -254,13 +254,13 @@ ${g.content}
254
254
 
255
255
  `)}
256
256
 
257
- ${i}`),m.length>0){const p=e.chatMessages.length-1,g=e.sessionKey,y=e.client.request("images.cache",{images:m.map(b=>({data:b.content,mimeType:b.mimeType,fileName:b.fileName})),sessionKey:g}).then(b=>{if(b?.cached&&b.cached.length>0){const A=b.cached.map((P,U)=>({messageIndex:p,imageIndex:U,hash:P.hash,mimeType:P.mimeType,bytes:P.bytes,role:"user",timestamp:o}));return e.client.request("images.updateIndex",{sessionKey:g,images:A}).catch(()=>{})}}).catch(()=>{});Re=y,y.finally(()=>{Re===y&&(Re=null)})}}try{return await e.client.request("chat.send",{sessionKey:e.sessionKey,message:i,deliver:!1,idempotencyKey:l,attachments:c}),!0}catch(m){const r=String(m);return e.chatRunId=null,e.chatStream=null,e.chatStreamStartedAt=null,e.lastError=r,e.chatMessages=[...e.chatMessages,{role:"assistant",content:[{type:"text",text:"Error: "+r}],timestamp:Date.now()}],!1}finally{e.chatSending=!1,e.chatSendingSessionKey=null}}async function Nt(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 Us(e,t){if(!t||!gs(t.sessionKey,e.sessionKey))return null;if(t.runId&&e.chatRunId&&t.runId!==e.chatRunId)return t.state==="final"?e.chatStream!==null?(e.refreshSessionsAfterChat=!0,null):"final":null;if(t.state!=="delta"&&_s(),t.state==="delta"){!e.chatRunId&&t.runId&&(e.chatRunId=t.runId,e.chatStreamStartedAt??=Date.now());const n=me(t.message);if(typeof n=="string"){const s=e.chatStream??"";(!s||n.length>=s.length)&&(e.chatStream=n)}}else if(t.state==="final")e.chatRunId=null,e.chatStreamStartedAt=null;else if(t.state==="aborted")e.chatStream&&e.chatStream.trim().length>0&&(e.chatMessages=[...e.chatMessages,{role:"assistant",content:[{type:"text",text:e.chatStream}],timestamp:e.chatStreamStartedAt??Date.now(),isAborted:!0}]),e.chatStream=null,e.chatRunId=null,e.chatStreamStartedAt=null;else if(t.state==="error"){e.chatStream=null,e.chatRunId=null,e.chatStreamStartedAt=null;const n=t.errorMessage??"chat error";e.lastError=n;let s=n;if(n.includes("prompt is too long")||n.includes("tokens >")){const a=n.match(/(\d+)\s*tokens?\s*>\s*(\d+)/);if(a){const o=parseInt(a[1]).toLocaleString(),l=parseInt(a[2]).toLocaleString();s=`⚠️ Context overflow: ${o} tokens exceeds ${l} limit. Use /compact to free up space.`}else s="⚠️ Context overflow: The conversation is too long. Use /compact to free up space."}e.chatMessages=[...e.chatMessages,{role:"assistant",content:[{type:"text",text:s}],timestamp:Date.now(),isError:!0}]}return t.state}const fe=Object.freeze(Object.defineProperty({__proto__:null,abortChatRun:Nt,getPendingImageCache:Ds,handleChatEvent:Us,laneMessageCache:Z,loadChatHistory:N,loadChatHistoryAfterFinal:Ns,loadLaneHistory:Ks,sendChatMessage:Fs,sessionTurnCounts:Os},Symbol.toStringTag,{value:"Module"}));function St(e){return typeof e=="object"&&e!==null}function Jr(e){if(!St(e))return null;const t=typeof e.id=="string"?e.id.trim():"",n=e.request;if(!t||!St(n))return null;const s=typeof n.command=="string"?n.command.trim():"";if(!s)return null;const i=typeof e.createdAtMs=="number"?e.createdAtMs:0,a=typeof e.expiresAtMs=="number"?e.expiresAtMs:0;return!i||!a?null:{id:t,request:{command:s,cwd:typeof n.cwd=="string"?n.cwd:null,host:typeof n.host=="string"?n.host:null,security:typeof n.security=="string"?n.security:null,ask:typeof n.ask=="string"?n.ask:null,agentId:typeof n.agentId=="string"?n.agentId:null,resolvedPath:typeof n.resolvedPath=="string"?n.resolvedPath:null,sessionKey:typeof n.sessionKey=="string"?n.sessionKey:null},createdAtMs:i,expiresAtMs:a}}function Xr(e){if(!St(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 Ws(e){const t=Date.now();return e.filter(n=>n.expiresAtMs>t)}function Zr(e,t){const n=Ws(e).filter(s=>s.id!==t.id);return n.push(t),n}function Pn(e,t){return Ws(e).filter(n=>n.id!==t)}const el=14400*1e3;function qs(e){return{openclawVersion:e.openclaw.version,openclawLatest:e.openclaw.latest,openclawUpdateAvailable:e.openclaw.updateAvailable,openclawInstallKind:e.openclaw.installKind,openclawChannel:e.openclaw.channel,pluginVersion:e.plugin.version,pluginLatest:e.plugin.latest,pluginUpdateAvailable:e.plugin.updateAvailable,pendingDeploy:e.pendingDeploy??null,fetchOk:e.fetchOk}}function Bs(e){const t=typeof e.behind=="number"?e.behind:null;return{openclawVersion:String(e.version??"unknown"),openclawLatest:null,openclawUpdateAvailable:(t??0)>0,openclawInstallKind:"unknown",openclawChannel:null,pluginVersion:"unknown",pluginLatest:null,pluginUpdateAvailable:!1,pendingDeploy:null,fetchOk:e.fetchOk}}async function js(e){if(!(!e.client||!e.connected)){e.updateLoading=!0,e.updateError=null;try{const t=await e.client.request("godmode.update.check",{});e.updateStatus=qs(t),e.updateLastChecked=Date.now()}catch{try{const t=await e.client.request("system.checkUpdates",{fetch:!0});t.error&&(e.updateError=String(t.error)),e.updateStatus=Bs(t),e.updateLastChecked=Date.now()}catch(t){e.updateError=String(t)}}finally{e.updateLoading=!1}}}async function Ln(e){if(!(!e.client||!e.connected))try{const t=await e.client.request("godmode.update.check",{});e.updateStatus=qs(t),e.updateLastChecked=Date.now()}catch{try{const t=await e.client.request("system.checkUpdates",{fetch:!0});e.updateStatus=Bs(t),e.updateLastChecked=Date.now()}catch{}}}function Hs(e){e.updatePollInterval==null&&(Ln(e),e.updatePollInterval=window.setInterval(()=>{Ln(e)},el))}function zs(e){const t=e;t.updatePollInterval!=null&&(clearInterval(t.updatePollInterval),t.updatePollInterval=null)}async function Vs(e){if(!(!e.client||!e.connected))try{const t=await e.client.request("godmode.update.postStatus",{});if(!t)return;const n=t.overallStatus,s=t.summary;if(!s)return;const i=n==="healthy"?"success":n==="degraded"?"error":"warning";typeof e.showToast=="function"&&e.showToast(s,i),js(e)}catch{}}const tl=Object.freeze(Object.defineProperty({__proto__:null,checkForUpdates:js,checkPostUpdateStatus:Vs,startUpdatePolling:Hs,stopUpdatePolling:zs},Symbol.toStringTag,{value:"Module"})),Gs={WEBCHAT_UI:"webchat-ui",CONTROL_UI:"openclaw-control-ui",GODMODE_WEBCHAT:"godmode-webchat",WEBCHAT:"webchat",CLI:"cli",GATEWAY_CLIENT:"gateway-client",MACOS_APP:"openclaw-macos",IOS_APP:"openclaw-ios",ANDROID_APP:"openclaw-android",MOLTBOT_MACOS:"moltbot-macos",MOLTBOT_IOS:"moltbot-ios",MOLTBOT_ANDROID:"moltbot-android",MOLTBOT_PROBE:"moltbot-probe",NODE_HOST:"node-host",TEST:"test",FINGERPRINT:"fingerprint",PROBE:"openclaw-probe"},Mn=Gs,_t={WEBCHAT:"webchat",CLI:"cli",UI:"ui",BACKEND:"backend",NODE:"node",PROBE:"probe",TEST:"test"};new Set(Object.values(Gs));new Set(Object.values(_t));function nl(e){const t=e.version??(e.nonce?"v2":"v1"),n=e.scopes.join(","),s=e.token??"",i=[t,e.deviceId,e.clientId,e.clientMode,e.role,n,String(e.signedAtMs),s];return t==="v2"&&i.push(e.nonce??""),i.join("|")}const sl=4008;class il{constructor(t){this.opts=t,this.ws=null,this.pending=new Map,this.closed=!1,this.lastSeq=null,this.connectNonce=null,this.connectSent=!1,this.connectTimer=null,this.backoffMs=800}start(){this.closed=!1,this.connect()}stop(){this.closed=!0,this.ws?.close(),this.ws=null,this.flushPending(new Error("gateway client stopped"))}get connected(){return this.ws?.readyState===WebSocket.OPEN}connect(){this.closed||(this.ws=new WebSocket(this.opts.url),this.ws.addEventListener("open",()=>this.queueConnect()),this.ws.addEventListener("message",t=>this.handleMessage(String(t.data??""))),this.ws.addEventListener("close",t=>{const n=String(t.reason??"");this.ws=null,this.flushPending(new Error(`gateway closed (${t.code}): ${n}`)),this.opts.onClose?.({code:t.code,reason:n}),this.scheduleReconnect()}),this.ws.addEventListener("error",()=>{}))}scheduleReconnect(){if(this.closed)return;const t=this.backoffMs;this.backoffMs=Math.min(this.backoffMs*1.7,15e3),window.setTimeout(()=>this.connect(),t)}flushPending(t){for(const[,n]of this.pending)n.reject(t);this.pending.clear()}async sendConnect(){if(this.connectSent)return;this.connectSent=!0,this.connectTimer!==null&&(window.clearTimeout(this.connectTimer),this.connectTimer=null);const t=typeof crypto<"u"&&!!crypto.subtle,n=["operator.admin","operator.read","operator.write","operator.approvals","operator.pairing"],s="operator";let i=null,a=!1,o=this.opts.token;if(t){i=await Bi();const r=ji({deviceId:i.deviceId,role:s})?.token;o=r??this.opts.token,a=!!(r&&this.opts.token)}const l=o||this.opts.password?{token:o,password:this.opts.password}:void 0;let c;if(t&&i){const r=Date.now(),p=this.connectNonce??void 0,g=nl({deviceId:i.deviceId,clientId:this.opts.clientName??Mn.CONTROL_UI,clientMode:this.opts.mode??_t.WEBCHAT,role:s,scopes:n,signedAtMs:r,token:o??null,nonce:p}),y=await Hi(i.privateKey,g);c={id:i.deviceId,publicKey:i.publicKey,signature:y,signedAt:r,nonce:p}}const m={minProtocol:3,maxProtocol:3,client:{id:this.opts.clientName??Mn.CONTROL_UI,version:this.opts.clientVersion??"dev",platform:this.opts.platform??navigator.platform??"web",mode:this.opts.mode??_t.WEBCHAT,instanceId:this.opts.instanceId},role:s,scopes:n,device:c,caps:[],auth:l,userAgent:navigator.userAgent,locale:navigator.language};this.request("connect",m).then(r=>{r?.auth?.deviceToken&&i&&zi({deviceId:i.deviceId,role:r.auth.role??s,token:r.auth.deviceToken,scopes:r.auth.scopes??[]}),this.backoffMs=800,this.opts.onHello?.(r)}).catch(()=>{a&&i&&Vi({deviceId:i.deviceId,role:s}),this.ws?.close(sl,"connect failed")})}handleMessage(t){let n;try{n=JSON.parse(t)}catch{return}const s=n;if(s.type==="event"){const i=n;if(i.event==="connect.challenge"){const o=i.payload,l=o&&typeof o.nonce=="string"?o.nonce:null;l&&(this.connectNonce=l,this.sendConnect());return}const a=typeof i.seq=="number"?i.seq:null;a!==null&&(this.lastSeq!==null&&a>this.lastSeq+1&&this.opts.onGap?.({expected:this.lastSeq+1,received:a}),this.lastSeq=a);try{this.opts.onEvent?.(i)}catch(o){console.error("[gateway] event handler error:",o)}return}if(s.type==="res"){const i=n,a=this.pending.get(i.id);if(!a)return;this.pending.delete(i.id),i.ok?a.resolve(i.payload):a.reject(new Error(i.error?.message??"request failed"));return}}request(t,n,s=1e4){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)return Promise.reject(new Error("gateway not connected"));const i=He(),a={type:"req",id:i,method:t,params:n};let o=null;const l=new Promise((m,r)=>{this.pending.set(i,{resolve:p=>{o&&clearTimeout(o),m(p)},reject:p=>{o&&clearTimeout(o),r(p)}})});this.ws.send(JSON.stringify(a));const c=new Promise((m,r)=>{o=setTimeout(()=>{this.pending.delete(i),r(new Error(`RPC timeout: ${t} (${s}ms)`))},s)});return Promise.race([l,c])}queueConnect(){this.connectNonce=null,this.connectSent=!1,this.connectTimer!==null&&window.clearTimeout(this.connectTimer),this.connectTimer=window.setTimeout(()=>{this.sendConnect()},750)}}const Qs={displayName:"label",sessionKey:"conversationId"},Ys={};for(const[e,t]of Object.entries(Qs))Ys[t]=e;const al={"sessions.autoTitle":["sessions.patch"],"sessions.rename":["sessions.patch"]},le=new Map;function ol(){try{const e=sessionStorage.getItem("godmode:healing-cache");if(e){const t=JSON.parse(e);for(const[n,s]of Object.entries(t))le.set(n,s)}}catch{}}function In(){try{const e={};for(const[t,n]of le)e[t]=n;sessionStorage.setItem("godmode:healing-cache",JSON.stringify(e))}catch{}}ol();function rl(e,t){const n=le.get(e);if(!n)return{method:e,params:t};const s=n.resolvedMethod;if(t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(n.fieldRenames).length>0){const i={...t};for(const[a,o]of Object.entries(n.fieldRenames))a in i&&!(o in i)&&(i[o]=i[a],delete i[a]);return{method:s,params:i}}return{method:s,params:t}}function ll(e,t,n){const s=n.toLowerCase(),i=n.match(/unexpected property[:\s]*['"]?(\w+)['"]?/i);if(i){const a=i[1],o=Qs[a];if(o&&t&&typeof t=="object"){const l={...t};if(a in l)return l[o]=l[a],delete l[a],console.log(`[safe-request] Self-heal: ${e} — rewrote "${a}" → "${o}"`),{method:e,params:l,renames:{[a]:o}}}}if(s.includes("unknown method")||s.includes("method not found")){const a=al[e];if(a&&a.length>0){const o=a[0];return console.log(`[safe-request] Self-heal: ${e} not found — falling back to ${o}`),{method:o,params:t,renames:{}}}}if((s.includes("unexpected property")||s.includes("unknown field"))&&t&&typeof t=="object"){const a={...t};let o=!1;const l={};for(const[c,m]of Object.entries(Ys))c in a&&(a[m]=a[c],delete a[c],l[c]=m,o=!0,console.log(`[safe-request] Self-heal: ${e} — reverse alias "${c}" → "${m}"`));if(o)return{method:e,params:a,renames:l}}return null}async function cl(e,t,n,s){const i=s?.timeout??3e4;let{method:a,params:o}=s?.raw?{method:t,params:n}:rl(t,n);const l=async(c,m)=>Promise.race([e.request(c,m),new Promise((r,p)=>setTimeout(()=>p(new Error(`Request timeout (${i}ms): ${c}`)),i))]);try{return{ok:!0,data:await l(a,o),method:a,healed:a!==t}}catch(c){const m=String(c instanceof Error?c.message:c);if(s?.raw)return{ok:!1,error:m,method:t};const r=ll(a,o,m);if(r)try{const p=await l(r.method,r.params);return le.set(t,{resolvedMethod:r.method,fieldRenames:r.renames,ts:Date.now()}),In(),{ok:!0,data:p,method:r.method,healed:!0}}catch(p){return{ok:!1,error:String(p instanceof Error?p.message:p),method:r.method,healed:!0}}if(s?.fallbacks)for(const p of s.fallbacks)try{const g=await l(p,o);return le.set(t,{resolvedMethod:p,fieldRenames:{},ts:Date.now()}),In(),{ok:!0,data:g,method:p,healed:!0}}catch{continue}return{ok:!1,error:m,method:a}}}function Js(){le.clear();try{sessionStorage.removeItem("godmode:healing-cache")}catch{}}function dl(){const e={};for(const[t,n]of le)e[t]=n;return e}const _u=Object.freeze(Object.defineProperty({__proto__:null,clearHealingCache:Js,getHealingEntries:dl,safeRequest:cl},Symbol.toStringTag,{value:"Module"}));let G=null;function ul(e,t){Js();const n=String(e.version??e.serverVersion??e.gatewayVersion??"unknown"),s=typeof e.protocol=="number"?e.protocol:void 0;G={hostVersion:n,protocolVersion:s,methods:{},initializedAt:Date.now(),probing:!0};try{const i=sessionStorage.getItem("godmode:host-compat");if(i){const a=JSON.parse(i);if(a.hostVersion===n&&a.methods)return G.methods=a.methods,G.probing=!1,G}}catch{}return pl(t).catch(()=>{}),G}async function pl(e){if(!G)return;const t=[{method:"sessions.list",params:{limit:1}},{method:"sessions.patch",params:{key:"__compat_probe__"}},{method:"sessions.autoTitle",params:{sessionKey:"__compat_probe__"}},{method:"config.get",params:{}}];for(const n of t){const s={available:!1,testedAt:Date.now()};try{await e.request(n.method,n.params),s.available=!0}catch(i){const a=String(i instanceof Error?i.message:i),o=a.toLowerCase(),l=o.includes("unknown method")||o.includes("not found")&&o.includes("method");s.available=!l,l&&(s.error="method not available");const c=a.match(/(?:expected|valid|accepted) (?:fields?|properties?)[:\s]*\[([^\]]+)\]/i);c&&(s.fields=c[1].split(",").map(m=>m.trim().replace(/['"]/g,"")))}G.methods[n.method]=s}G.probing=!1;try{sessionStorage.setItem("godmode:host-compat",JSON.stringify(G))}catch{}}const kt=new Map;let Rn=null,nt=!1;function Xs(e,t,n){return kt.get(`${e}:${t}:${n}`)??null}async function Zs(e){if(!e.client||!e.chatMessages?.length)return;const t=e.sessionKey,n=[];for(let s=0;s<e.chatMessages.length;s++){const i=e.chatMessages[s],a=vt(i);for(let o=0;o<a.length;o++)if(a[o].url&&!a[o].omitted){const l=/^data:([^;]+);base64,(.+)$/.exec(a[o].url);l&&n.push({data:l[2],mimeType:l[1],messageIndex:s,imageIndex:o,role:i.role||"unknown",timestamp:typeof i.timestamp=="number"?i.timestamp:void 0})}}if(n.length>0)try{const s=await e.client.request("images.cache",{images:n.map(i=>({data:i.data,mimeType:i.mimeType})),sessionKey:t});if(s?.cached){const i=n.map((a,o)=>({messageIndex:a.messageIndex,imageIndex:a.imageIndex,hash:s.cached[o]?.hash,mimeType:a.mimeType,bytes:s.cached[o]?.bytes??0,role:a.role,timestamp:a.timestamp})).filter(a=>!!a.hash);i.length>0&&await e.client.request("images.updateIndex",{sessionKey:t,images:i})}}catch{}if(!nt){nt=!0;try{const s=Ds();s&&await s.catch(()=>{});const i=async()=>{const o=await e.client.request("images.resolve",{sessionKey:t});if(o?.images&&Object.keys(o.images).length>0){Rn!==t&&kt.clear();for(const[l,c]of Object.entries(o.images))kt.set(`${t}:${l}`,c);return Rn=t,e.chatMessages=[...e.chatMessages],!0}return!1};if(!await i()&&e.chatMessages?.some(o=>vt(o).some(c=>c.omitted||!c.url))){for(const o of[500,1500,3e3])if(await new Promise(l=>setTimeout(l,o)),await i()||e.sessionKey!==t)break}}catch{}finally{nt=!1}}}let En=null;function hl(e){if(!e.chatMessages?.length)return;const t=e.chatMessages.slice(-5);for(const n of t){const s=n,i=Array.isArray(s.content)?s.content:[];for(const a of i){const o=a,l=typeof o.text=="string"?o.text:typeof o.content=="string"?o.content:null;if(l)try{const c=JSON.parse(l);if(c._sidebarAction?.type==="proof"&&c._sidebarAction.slug){const m=c._sidebarAction.slug;if(m===En)return;En=m,e.handleOpenProofDoc(m);return}}catch{}}}}function _e(e){Zs(e)}const we=[];function ei(){return[...we]}let Y=null;const fl=10,ml=1e3,j=new Map;function st(e,t){const n=(e??"").trim(),s=t.mainSessionKey?.trim();if(!s)return n;if(!n)return s;const i=t.mainKey?.trim()||"main",a=t.defaultAgentId?.trim();return n==="main"||n===i||a&&(n===`agent:${a}:main`||n===`agent:${a}:${i}`)?s:n}function gl(e,t){if(!t?.mainSessionKey)return;const n="main",s=r=>(r??"").trim()===n||(r??"").trim()==="",i=s(e.sessionKey)?e.sessionKey:st(e.sessionKey,t),a=s(e.settings.sessionKey)?e.settings.sessionKey:st(e.settings.sessionKey,t),o=s(e.settings.lastActiveSessionKey)?e.settings.lastActiveSessionKey:st(e.settings.lastActiveSessionKey,t),l=i||a||e.sessionKey,c={...e.settings,sessionKey:a||l,lastActiveSessionKey:o||l},m=c.sessionKey!==e.settings.sessionKey||c.lastActiveSessionKey!==e.settings.lastActiveSessionKey;l!==e.sessionKey&&(e.sessionKey=l),m&&te(e,c)}function yl(e){Y&&(clearTimeout(Y),Y=null);const t=(e.reconnectAttempt??0)+1;e.reconnectAttempt=t,e.reconnecting=!0;const n=t<=fl?Math.min(ml*Math.pow(2,t-1),3e4):6e4;Y=setTimeout(()=>{Y=null,e.connected||ze(e)},n)}async function vl(e){if(!e.client)return;const t=e;try{if(t.setupQuickDone){t.workspaceNeedsSetup=!1;return}try{if((await e.client.request("onboarding.status",{}))?.identity?.name){t.workspaceNeedsSetup=!1;return}}catch{}const n=await e.client.request("projects.list",{});t.workspaceNeedsSetup=!n?.projects||n.projects.length===0}catch{}}async function bl(e){if(!e.client)return;if(e.workspaceNeedsSetup===!1){try{const n=await e.client.request("onboarding.status",{});n&&!n.completedAt&&await e.client.request("onboarding.complete",{summary:null})}catch{}return}try{const n=await e.client.request("onboarding.status",{}),s=e;if(n&&!n.completedAt){s.onboardingActive=!0,s.onboardingPhase=n.phase??0,s.onboardingData=n;const i=e;i.showSetupTab=!0;try{const a=await e.client.request("onboarding.setupProgress",{});e.setupProgress=a}catch{}if(n.identity?.name){i.setupQuickDone=!0;const a=e;a.settings.userName||(a.userName=n.identity.name,a.applySettings({...a.settings,userName:n.identity.name}))}}else if(s.onboardingActive=!1,s.onboardingData=n??null,n?.identity?.name){const i=e;i.settings.userName||(i.userName=n.identity.name,i.applySettings({...i.settings,userName:n.identity.name}))}}catch{}}function wl(e,t){if(!e.sessionsResult?.sessions)return;const n=e.sessionsResult.sessions.map(s=>s.key===t?{...s,updatedAt:Date.now()}:s);e.sessionsResult={...e.sessionsResult,sessions:n}}const ti=new Set;function ni(){ti.clear()}async function Sl(e,t){}function ze(e){e.lastError=null,e.hello=null,e.connected=!1,e.execApprovalQueue=[],e.execApprovalError=null,ni();const t=e;"sessionsLoading"in t&&(t.sessionsLoading=!1),"agentsLoading"in t&&(t.agentsLoading=!1),"nodesLoading"in t&&(t.nodesLoading=!1),"devicesLoading"in t&&(t.devicesLoading=!1),"channelsLoading"in t&&(t.channelsLoading=!1),"configLoading"in t&&(t.configLoading=!1),"presenceLoading"in t&&(t.presenceLoading=!1),"cronLoading"in t&&(t.cronLoading=!1),"skillsLoading"in t&&(t.skillsLoading=!1),"debugLoading"in t&&(t.debugLoading=!1),"logsLoading"in t&&(t.logsLoading=!1),Y&&(clearTimeout(Y),Y=null),e.client?.stop(),e.client=new il({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:async n=>{const s=e.reconnecting;if(e.connected=!0,e.lastError=null,e.hello=n,e.reconnecting=!1,e.reconnectAttempt=0,s){const a=e;let o="Gateway reconnected";try{const l=await e.client.request("godmode.health",{});l?.crashRecovery&&(o=`Recovered from crash (${Math.round((l.crashRecovery.downtimeMs??0)/1e3)}s downtime). Everything is back online.`)}catch{}typeof a.showToast=="function"&&a.showToast(o,"success",6e3),e.lastError="✓ Reconnected",setTimeout(()=>{e.lastError==="✓ Reconnected"&&(e.lastError=null)},3e3),e.chatRunId=null,e.workingSessions.clear(),e.requestUpdate?.();for(const l of j.values())clearTimeout(l);j.clear()}const i=n.features;document.title=i?.hermes?"Hermes - GodMode":"OC - GodMode",ul(n,e.client),ri(e,n),Es(e),Tl(e),Gi(e),Fe(e,{quiet:!0}),Ue(e,{quiet:!0}),K(e),Ge(e),vl(e).then(()=>bl(e)),Hs(e),Vs(e),$l(e),li(e)},onClose:({code:n,reason:s})=>{e.connected=!1,zs(e);const i=e;"chatSending"in i&&(i.chatSending=!1),"chatSendingSessionKey"in i&&(i.chatSendingSessionKey=null),"chatRunId"in i&&(i.chatRunId=null);const a=e;"sessionsLoading"in a&&(a.sessionsLoading=!1),"agentsLoading"in a&&(a.agentsLoading=!1),"nodesLoading"in a&&(a.nodesLoading=!1),"devicesLoading"in a&&(a.devicesLoading=!1),"channelsLoading"in a&&(a.channelsLoading=!1),"presenceLoading"in a&&(a.presenceLoading=!1),n!==1012&&(e.lastError=`disconnected (${n}): ${s||"no reason"}`),yl(e)},onEvent:n=>si(e,n),onGap:({expected:n,received:s})=>{e.lastError=`event gap detected (expected seq ${n}, got ${s}); refresh recommended`}}),e.client.start()}function Dn(e,t){if(!e.chatMessages)return;const n=t.outputPreview?`
257
+ ${i}`),m.length>0){const p=e.chatMessages.length-1,g=e.sessionKey,y=e.client.request("images.cache",{images:m.map(b=>({data:b.content,mimeType:b.mimeType,fileName:b.fileName})),sessionKey:g}).then(b=>{if(b?.cached&&b.cached.length>0){const A=b.cached.map((P,U)=>({messageIndex:p,imageIndex:U,hash:P.hash,mimeType:P.mimeType,bytes:P.bytes,role:"user",timestamp:o}));return e.client.request("images.updateIndex",{sessionKey:g,images:A}).catch(()=>{})}}).catch(()=>{});Re=y,y.finally(()=>{Re===y&&(Re=null)})}}try{return await e.client.request("chat.send",{sessionKey:e.sessionKey,message:i,deliver:!1,idempotencyKey:l,attachments:c}),!0}catch(m){const r=String(m);return e.chatRunId=null,e.chatStream=null,e.chatStreamStartedAt=null,e.lastError=r,e.chatMessages=[...e.chatMessages,{role:"assistant",content:[{type:"text",text:"Error: "+r}],timestamp:Date.now()}],!1}finally{e.chatSending=!1,e.chatSendingSessionKey=null}}async function Nt(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 Us(e,t){if(!t||!gs(t.sessionKey,e.sessionKey))return null;if(t.runId&&e.chatRunId&&t.runId!==e.chatRunId)return t.state==="final"?e.chatStream!==null?(e.refreshSessionsAfterChat=!0,null):"final":null;if(t.state!=="delta"&&_s(),t.state==="delta"){!e.chatRunId&&t.runId&&(e.chatRunId=t.runId,e.chatStreamStartedAt??=Date.now());const n=me(t.message);if(typeof n=="string"){const s=e.chatStream??"";(!s||n.length>=s.length)&&(e.chatStream=n)}}else if(t.state==="final")e.chatRunId=null,e.chatStreamStartedAt=null;else if(t.state==="aborted")e.chatStream&&e.chatStream.trim().length>0&&(e.chatMessages=[...e.chatMessages,{role:"assistant",content:[{type:"text",text:e.chatStream}],timestamp:e.chatStreamStartedAt??Date.now(),isAborted:!0}]),e.chatStream=null,e.chatRunId=null,e.chatStreamStartedAt=null;else if(t.state==="error"){e.chatStream=null,e.chatRunId=null,e.chatStreamStartedAt=null;const n=t.errorMessage??"chat error";e.lastError=n;let s=n;if(n.includes("prompt is too long")||n.includes("tokens >")){const a=n.match(/(\d+)\s*tokens?\s*>\s*(\d+)/);if(a){const o=parseInt(a[1]).toLocaleString(),l=parseInt(a[2]).toLocaleString();s=`⚠️ Context overflow: ${o} tokens exceeds ${l} limit. Use /compact to free up space.`}else s="⚠️ Context overflow: The conversation is too long. Use /compact to free up space."}e.chatMessages=[...e.chatMessages,{role:"assistant",content:[{type:"text",text:s}],timestamp:Date.now(),isError:!0}]}return t.state}const fe=Object.freeze(Object.defineProperty({__proto__:null,abortChatRun:Nt,getPendingImageCache:Ds,handleChatEvent:Us,laneMessageCache:Z,loadChatHistory:N,loadChatHistoryAfterFinal:Ns,loadLaneHistory:Ks,sendChatMessage:Fs,sessionTurnCounts:Os},Symbol.toStringTag,{value:"Module"}));function St(e){return typeof e=="object"&&e!==null}function Jr(e){if(!St(e))return null;const t=typeof e.id=="string"?e.id.trim():"",n=e.request;if(!t||!St(n))return null;const s=typeof n.command=="string"?n.command.trim():"";if(!s)return null;const i=typeof e.createdAtMs=="number"?e.createdAtMs:0,a=typeof e.expiresAtMs=="number"?e.expiresAtMs:0;return!i||!a?null:{id:t,request:{command:s,cwd:typeof n.cwd=="string"?n.cwd:null,host:typeof n.host=="string"?n.host:null,security:typeof n.security=="string"?n.security:null,ask:typeof n.ask=="string"?n.ask:null,agentId:typeof n.agentId=="string"?n.agentId:null,resolvedPath:typeof n.resolvedPath=="string"?n.resolvedPath:null,sessionKey:typeof n.sessionKey=="string"?n.sessionKey:null},createdAtMs:i,expiresAtMs:a}}function Xr(e){if(!St(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 Ws(e){const t=Date.now();return e.filter(n=>n.expiresAtMs>t)}function Zr(e,t){const n=Ws(e).filter(s=>s.id!==t.id);return n.push(t),n}function Pn(e,t){return Ws(e).filter(n=>n.id!==t)}const el=14400*1e3;function qs(e){return{openclawVersion:e.openclaw.version,openclawLatest:e.openclaw.latest,openclawUpdateAvailable:e.openclaw.updateAvailable,openclawInstallKind:e.openclaw.installKind,openclawChannel:e.openclaw.channel,pluginVersion:e.plugin.version,pluginLatest:e.plugin.latest,pluginUpdateAvailable:e.plugin.updateAvailable,pendingDeploy:e.pendingDeploy??null,fetchOk:e.fetchOk}}function Bs(e){const t=typeof e.behind=="number"?e.behind:null;return{openclawVersion:String(e.version??"unknown"),openclawLatest:null,openclawUpdateAvailable:(t??0)>0,openclawInstallKind:"unknown",openclawChannel:null,pluginVersion:"unknown",pluginLatest:null,pluginUpdateAvailable:!1,pendingDeploy:null,fetchOk:e.fetchOk}}async function js(e){if(!(!e.client||!e.connected)){e.updateLoading=!0,e.updateError=null;try{const t=await e.client.request("godmode.update.check",{});e.updateStatus=qs(t),e.updateLastChecked=Date.now()}catch{try{const t=await e.client.request("system.checkUpdates",{fetch:!0});t.error&&(e.updateError=String(t.error)),e.updateStatus=Bs(t),e.updateLastChecked=Date.now()}catch(t){e.updateError=String(t)}}finally{e.updateLoading=!1}}}async function Ln(e){if(!(!e.client||!e.connected))try{const t=await e.client.request("godmode.update.check",{});e.updateStatus=qs(t),e.updateLastChecked=Date.now()}catch{try{const t=await e.client.request("system.checkUpdates",{fetch:!0});e.updateStatus=Bs(t),e.updateLastChecked=Date.now()}catch{}}}function Hs(e){e.updatePollInterval==null&&(Ln(e),e.updatePollInterval=window.setInterval(()=>{Ln(e)},el))}function zs(e){const t=e;t.updatePollInterval!=null&&(clearInterval(t.updatePollInterval),t.updatePollInterval=null)}async function Vs(e){if(!(!e.client||!e.connected))try{const t=await e.client.request("godmode.update.postStatus",{});if(!t)return;const n=t.overallStatus,s=t.summary;if(!s)return;const i=n==="healthy"?"success":n==="degraded"?"error":"warning";typeof e.showToast=="function"&&e.showToast(s,i),js(e)}catch{}}const tl=Object.freeze(Object.defineProperty({__proto__:null,checkForUpdates:js,checkPostUpdateStatus:Vs,startUpdatePolling:Hs,stopUpdatePolling:zs},Symbol.toStringTag,{value:"Module"})),Gs={WEBCHAT_UI:"webchat-ui",CONTROL_UI:"openclaw-control-ui",GODMODE_WEBCHAT:"godmode-webchat",WEBCHAT:"webchat",CLI:"cli",GATEWAY_CLIENT:"gateway-client",MACOS_APP:"openclaw-macos",IOS_APP:"openclaw-ios",ANDROID_APP:"openclaw-android",MOLTBOT_MACOS:"moltbot-macos",MOLTBOT_IOS:"moltbot-ios",MOLTBOT_ANDROID:"moltbot-android",MOLTBOT_PROBE:"moltbot-probe",NODE_HOST:"node-host",TEST:"test",FINGERPRINT:"fingerprint",PROBE:"openclaw-probe"},Mn=Gs,_t={WEBCHAT:"webchat",CLI:"cli",UI:"ui",BACKEND:"backend",NODE:"node",PROBE:"probe",TEST:"test"};new Set(Object.values(Gs));new Set(Object.values(_t));function nl(e){const t=e.version??(e.nonce?"v2":"v1"),n=e.scopes.join(","),s=e.token??"",i=[t,e.deviceId,e.clientId,e.clientMode,e.role,n,String(e.signedAtMs),s];return t==="v2"&&i.push(e.nonce??""),i.join("|")}const sl=4008;class il{constructor(t){this.opts=t,this.ws=null,this.pending=new Map,this.closed=!1,this.lastSeq=null,this.connectNonce=null,this.connectSent=!1,this.connectTimer=null,this.backoffMs=800}start(){this.closed=!1,this.connect()}stop(){this.closed=!0,this.ws?.close(),this.ws=null,this.flushPending(new Error("gateway client stopped"))}get connected(){return this.ws?.readyState===WebSocket.OPEN}connect(){this.closed||(this.ws=new WebSocket(this.opts.url),this.ws.addEventListener("open",()=>this.queueConnect()),this.ws.addEventListener("message",t=>this.handleMessage(String(t.data??""))),this.ws.addEventListener("close",t=>{const n=String(t.reason??"");this.ws=null,this.flushPending(new Error(`gateway closed (${t.code}): ${n}`)),this.opts.onClose?.({code:t.code,reason:n}),this.scheduleReconnect()}),this.ws.addEventListener("error",()=>{}))}scheduleReconnect(){if(this.closed)return;const t=this.backoffMs;this.backoffMs=Math.min(this.backoffMs*1.7,15e3),window.setTimeout(()=>this.connect(),t)}flushPending(t){for(const[,n]of this.pending)n.reject(t);this.pending.clear()}async sendConnect(){if(this.connectSent)return;this.connectSent=!0,this.connectTimer!==null&&(window.clearTimeout(this.connectTimer),this.connectTimer=null);const t=typeof crypto<"u"&&!!crypto.subtle,n=["operator.admin","operator.read","operator.write","operator.approvals","operator.pairing"],s="operator";let i=null,a=!1,o=this.opts.token;if(t){i=await Bi();const r=ji({deviceId:i.deviceId,role:s})?.token;o=r??this.opts.token,a=!!(r&&this.opts.token)}const l=o||this.opts.password?{token:o,password:this.opts.password}:void 0;let c;if(t&&i){const r=Date.now(),p=this.connectNonce??void 0,g=nl({deviceId:i.deviceId,clientId:this.opts.clientName??Mn.CONTROL_UI,clientMode:this.opts.mode??_t.WEBCHAT,role:s,scopes:n,signedAtMs:r,token:o??null,nonce:p}),y=await Hi(i.privateKey,g);c={id:i.deviceId,publicKey:i.publicKey,signature:y,signedAt:r,nonce:p}}const m={minProtocol:3,maxProtocol:3,client:{id:this.opts.clientName??Mn.CONTROL_UI,version:this.opts.clientVersion??"dev",platform:this.opts.platform??navigator.platform??"web",mode:this.opts.mode??_t.WEBCHAT,instanceId:this.opts.instanceId},role:s,scopes:n,device:c,caps:[],auth:l,userAgent:navigator.userAgent,locale:navigator.language};this.request("connect",m).then(r=>{r?.auth?.deviceToken&&i&&zi({deviceId:i.deviceId,role:r.auth.role??s,token:r.auth.deviceToken,scopes:r.auth.scopes??[]}),this.backoffMs=800,this.opts.onHello?.(r)}).catch(()=>{a&&i&&Vi({deviceId:i.deviceId,role:s}),this.ws?.close(sl,"connect failed")})}handleMessage(t){let n;try{n=JSON.parse(t)}catch{return}const s=n;if(s.type==="event"){const i=n;if(i.event==="connect.challenge"){const o=i.payload,l=o&&typeof o.nonce=="string"?o.nonce:null;l&&(this.connectNonce=l,this.sendConnect());return}const a=typeof i.seq=="number"?i.seq:null;a!==null&&(this.lastSeq!==null&&a>this.lastSeq+1&&this.opts.onGap?.({expected:this.lastSeq+1,received:a}),this.lastSeq=a);try{this.opts.onEvent?.(i)}catch(o){console.error("[gateway] event handler error:",o)}return}if(s.type==="res"){const i=n,a=this.pending.get(i.id);if(!a)return;this.pending.delete(i.id),i.ok?a.resolve(i.payload):a.reject(new Error(i.error?.message??"request failed"));return}}request(t,n,s=1e4){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)return Promise.reject(new Error("gateway not connected"));const i=He(),a={type:"req",id:i,method:t,params:n};let o=null;const l=new Promise((m,r)=>{this.pending.set(i,{resolve:p=>{o&&clearTimeout(o),m(p)},reject:p=>{o&&clearTimeout(o),r(p)}})});this.ws.send(JSON.stringify(a));const c=new Promise((m,r)=>{o=setTimeout(()=>{this.pending.delete(i),r(new Error(`RPC timeout: ${t} (${s}ms)`))},s)});return Promise.race([l,c])}queueConnect(){this.connectNonce=null,this.connectSent=!1,this.connectTimer!==null&&window.clearTimeout(this.connectTimer),this.connectTimer=window.setTimeout(()=>{this.sendConnect()},750)}}const Qs={displayName:"label",sessionKey:"conversationId"},Ys={};for(const[e,t]of Object.entries(Qs))Ys[t]=e;const al={"sessions.autoTitle":["sessions.patch"],"sessions.rename":["sessions.patch"]},le=new Map;function ol(){try{const e=sessionStorage.getItem("godmode:healing-cache");if(e){const t=JSON.parse(e);for(const[n,s]of Object.entries(t))le.set(n,s)}}catch{}}function In(){try{const e={};for(const[t,n]of le)e[t]=n;sessionStorage.setItem("godmode:healing-cache",JSON.stringify(e))}catch{}}ol();function rl(e,t){const n=le.get(e);if(!n)return{method:e,params:t};const s=n.resolvedMethod;if(t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(n.fieldRenames).length>0){const i={...t};for(const[a,o]of Object.entries(n.fieldRenames))a in i&&!(o in i)&&(i[o]=i[a],delete i[a]);return{method:s,params:i}}return{method:s,params:t}}function ll(e,t,n){const s=n.toLowerCase(),i=n.match(/unexpected property[:\s]*['"]?(\w+)['"]?/i);if(i){const a=i[1],o=Qs[a];if(o&&t&&typeof t=="object"){const l={...t};if(a in l)return l[o]=l[a],delete l[a],console.log(`[safe-request] Self-heal: ${e} — rewrote "${a}" → "${o}"`),{method:e,params:l,renames:{[a]:o}}}}if(s.includes("unknown method")||s.includes("method not found")){const a=al[e];if(a&&a.length>0){const o=a[0];return console.log(`[safe-request] Self-heal: ${e} not found — falling back to ${o}`),{method:o,params:t,renames:{}}}}if((s.includes("unexpected property")||s.includes("unknown field"))&&t&&typeof t=="object"){const a={...t};let o=!1;const l={};for(const[c,m]of Object.entries(Ys))c in a&&(a[m]=a[c],delete a[c],l[c]=m,o=!0,console.log(`[safe-request] Self-heal: ${e} — reverse alias "${c}" → "${m}"`));if(o)return{method:e,params:a,renames:l}}return null}async function cl(e,t,n,s){const i=s?.timeout??3e4;let{method:a,params:o}=s?.raw?{method:t,params:n}:rl(t,n);const l=async(c,m)=>Promise.race([e.request(c,m),new Promise((r,p)=>setTimeout(()=>p(new Error(`Request timeout (${i}ms): ${c}`)),i))]);try{return{ok:!0,data:await l(a,o),method:a,healed:a!==t}}catch(c){const m=String(c instanceof Error?c.message:c);if(s?.raw)return{ok:!1,error:m,method:t};const r=ll(a,o,m);if(r)try{const p=await l(r.method,r.params);return le.set(t,{resolvedMethod:r.method,fieldRenames:r.renames,ts:Date.now()}),In(),{ok:!0,data:p,method:r.method,healed:!0}}catch(p){return{ok:!1,error:String(p instanceof Error?p.message:p),method:r.method,healed:!0}}if(s?.fallbacks)for(const p of s.fallbacks)try{const g=await l(p,o);return le.set(t,{resolvedMethod:p,fieldRenames:{},ts:Date.now()}),In(),{ok:!0,data:g,method:p,healed:!0}}catch{continue}return{ok:!1,error:m,method:a}}}function Js(){le.clear();try{sessionStorage.removeItem("godmode:healing-cache")}catch{}}function dl(){const e={};for(const[t,n]of le)e[t]=n;return e}const _u=Object.freeze(Object.defineProperty({__proto__:null,clearHealingCache:Js,getHealingEntries:dl,safeRequest:cl},Symbol.toStringTag,{value:"Module"}));let G=null;function ul(e,t){Js();const n=String(e.version??e.serverVersion??e.gatewayVersion??"unknown"),s=typeof e.protocol=="number"?e.protocol:void 0;G={hostVersion:n,protocolVersion:s,methods:{},initializedAt:Date.now(),probing:!0};try{const i=sessionStorage.getItem("godmode:host-compat");if(i){const a=JSON.parse(i);if(a.hostVersion===n&&a.methods)return G.methods=a.methods,G.probing=!1,G}}catch{}return pl(t).catch(()=>{}),G}async function pl(e){if(!G)return;const t=[{method:"sessions.list",params:{limit:1}},{method:"sessions.patch",params:{key:"__compat_probe__"}},{method:"sessions.autoTitle",params:{sessionKey:"__compat_probe__"}},{method:"config.get",params:{}}];for(const n of t){const s={available:!1,testedAt:Date.now()};try{await e.request(n.method,n.params),s.available=!0}catch(i){const a=String(i instanceof Error?i.message:i),o=a.toLowerCase(),l=o.includes("unknown method")||o.includes("not found")&&o.includes("method");s.available=!l,l&&(s.error="method not available");const c=a.match(/(?:expected|valid|accepted) (?:fields?|properties?)[:\s]*\[([^\]]+)\]/i);c&&(s.fields=c[1].split(",").map(m=>m.trim().replace(/['"]/g,"")))}G.methods[n.method]=s}G.probing=!1;try{sessionStorage.setItem("godmode:host-compat",JSON.stringify(G))}catch{}}const kt=new Map;let Rn=null,nt=!1;function Xs(e,t,n){return kt.get(`${e}:${t}:${n}`)??null}async function Zs(e){if(!e.client||!e.chatMessages?.length)return;const t=e.sessionKey,n=[];for(let s=0;s<e.chatMessages.length;s++){const i=e.chatMessages[s],a=vt(i);for(let o=0;o<a.length;o++)if(a[o].url&&!a[o].omitted){const l=/^data:([^;]+);base64,(.+)$/.exec(a[o].url);l&&n.push({data:l[2],mimeType:l[1],messageIndex:s,imageIndex:o,role:i.role||"unknown",timestamp:typeof i.timestamp=="number"?i.timestamp:void 0})}}if(n.length>0)try{const s=await e.client.request("images.cache",{images:n.map(i=>({data:i.data,mimeType:i.mimeType})),sessionKey:t});if(s?.cached){const i=n.map((a,o)=>({messageIndex:a.messageIndex,imageIndex:a.imageIndex,hash:s.cached[o]?.hash,mimeType:a.mimeType,bytes:s.cached[o]?.bytes??0,role:a.role,timestamp:a.timestamp})).filter(a=>!!a.hash);i.length>0&&await e.client.request("images.updateIndex",{sessionKey:t,images:i})}}catch{}if(!nt){nt=!0;try{const s=Ds();s&&await s.catch(()=>{});const i=async()=>{const o=await e.client.request("images.resolve",{sessionKey:t});if(o?.images&&Object.keys(o.images).length>0){Rn!==t&&kt.clear();for(const[l,c]of Object.entries(o.images))kt.set(`${t}:${l}`,c);return Rn=t,e.chatMessages=[...e.chatMessages],!0}return!1};if(!await i()&&e.chatMessages?.some(o=>vt(o).some(c=>c.omitted||!c.url))){for(const o of[500,1500,3e3])if(await new Promise(l=>setTimeout(l,o)),await i()||e.sessionKey!==t)break}}catch{}finally{nt=!1}}}let En=null;function hl(e){if(!e.chatMessages?.length)return;const t=e.chatMessages.slice(-5);for(const n of t){const s=n,i=Array.isArray(s.content)?s.content:[];for(const a of i){const o=a,l=typeof o.text=="string"?o.text:typeof o.content=="string"?o.content:null;if(l)try{const c=JSON.parse(l);if(c._sidebarAction?.type==="proof"&&c._sidebarAction.slug){const m=c._sidebarAction.slug;if(m===En)return;En=m,e.handleOpenProofDoc(m);return}}catch{}}}}function _e(e){Zs(e)}const we=[];function ei(){return[...we]}let Y=null;const fl=10,ml=1e3,j=new Map;function st(e,t){const n=(e??"").trim(),s=t.mainSessionKey?.trim();if(!s)return n;if(!n)return s;const i=t.mainKey?.trim()||"main",a=t.defaultAgentId?.trim();return n==="main"||n===i||a&&(n===`agent:${a}:main`||n===`agent:${a}:${i}`)?s:n}function gl(e,t){if(!t?.mainSessionKey)return;const n="main",s=r=>(r??"").trim()===n||(r??"").trim()==="",i=s(e.sessionKey)?e.sessionKey:st(e.sessionKey,t),a=s(e.settings.sessionKey)?e.settings.sessionKey:st(e.settings.sessionKey,t),o=s(e.settings.lastActiveSessionKey)?e.settings.lastActiveSessionKey:st(e.settings.lastActiveSessionKey,t),l=i||a||e.sessionKey,c={...e.settings,sessionKey:a||l,lastActiveSessionKey:o||l},m=c.sessionKey!==e.settings.sessionKey||c.lastActiveSessionKey!==e.settings.lastActiveSessionKey;l!==e.sessionKey&&(e.sessionKey=l),m&&te(e,c)}function yl(e){Y&&(clearTimeout(Y),Y=null);const t=(e.reconnectAttempt??0)+1;e.reconnectAttempt=t,e.reconnecting=!0;const n=t<=fl?Math.min(ml*Math.pow(2,t-1),3e4):6e4;Y=setTimeout(()=>{Y=null,e.connected||ze(e)},n)}async function vl(e){if(!e.client)return;const t=e;try{if(t.setupQuickDone){t.workspaceNeedsSetup=!1;return}try{if((await e.client.request("onboarding.status",{}))?.identity?.name){t.workspaceNeedsSetup=!1;return}}catch{}const n=await e.client.request("projects.list",{});t.workspaceNeedsSetup=!n?.projects||n.projects.length===0}catch{}}async function bl(e){if(!e.client)return;if(e.workspaceNeedsSetup===!1){try{const n=await e.client.request("onboarding.status",{});n&&!n.completedAt&&await e.client.request("onboarding.complete",{summary:null})}catch{}return}try{const n=await e.client.request("onboarding.status",{}),s=e;if(n&&!n.completedAt){s.onboardingActive=!0,s.onboardingPhase=n.phase??0,s.onboardingData=n;const i=e;i.showSetupTab=!0;try{const a=await e.client.request("onboarding.setupProgress",{});e.setupProgress=a}catch{}if(n.identity?.name){i.setupQuickDone=!0;const a=e;a.settings.userName||(a.userName=n.identity.name,a.applySettings({...a.settings,userName:n.identity.name}))}}else if(s.onboardingActive=!1,s.onboardingData=n??null,n?.identity?.name){const i=e;i.settings.userName||(i.userName=n.identity.name,i.applySettings({...i.settings,userName:n.identity.name}))}}catch{}}function wl(e,t){if(!e.sessionsResult?.sessions)return;const n=e.sessionsResult.sessions.map(s=>s.key===t?{...s,updatedAt:Date.now()}:s);e.sessionsResult={...e.sessionsResult,sessions:n}}const ti=new Set;function ni(){ti.clear()}async function Sl(e,t){}function ze(e){e.lastError=null,e.hello=null,e.connected=!1,e.execApprovalQueue=[],e.execApprovalError=null,ni();const t=e;"sessionsLoading"in t&&(t.sessionsLoading=!1),"agentsLoading"in t&&(t.agentsLoading=!1),"nodesLoading"in t&&(t.nodesLoading=!1),"devicesLoading"in t&&(t.devicesLoading=!1),"channelsLoading"in t&&(t.channelsLoading=!1),"configLoading"in t&&(t.configLoading=!1),"presenceLoading"in t&&(t.presenceLoading=!1),"cronLoading"in t&&(t.cronLoading=!1),"skillsLoading"in t&&(t.skillsLoading=!1),"debugLoading"in t&&(t.debugLoading=!1),"logsLoading"in t&&(t.logsLoading=!1),Y&&(clearTimeout(Y),Y=null),e.client?.stop(),e.client=new il({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:async n=>{const s=e.reconnecting;if(e.connected=!0,e.lastError=null,e.hello=n,e.reconnecting=!1,e.reconnectAttempt=0,s){const i=e;let a="Gateway reconnected";try{const o=await e.client.request("godmode.health",{});o?.crashRecovery&&(a=`Recovered from crash (${Math.round((o.crashRecovery.downtimeMs??0)/1e3)}s downtime). Everything is back online.`)}catch{}typeof i.showToast=="function"&&i.showToast(a,"success",6e3),e.lastError="✓ Reconnected",setTimeout(()=>{e.lastError==="✓ Reconnected"&&(e.lastError=null)},3e3),e.chatRunId=null,e.workingSessions.clear(),e.requestUpdate?.();for(const o of j.values())clearTimeout(o);j.clear()}document.title="GodMode",ul(n,e.client),ri(e,n),Es(e),Tl(e),Gi(e),Fe(e,{quiet:!0}),Ue(e,{quiet:!0}),K(e),Ge(e),vl(e).then(()=>bl(e)),Hs(e),Vs(e),$l(e),li(e)},onClose:({code:n,reason:s})=>{e.connected=!1,zs(e);const i=e;"chatSending"in i&&(i.chatSending=!1),"chatSendingSessionKey"in i&&(i.chatSendingSessionKey=null),"chatRunId"in i&&(i.chatRunId=null);const a=e;"sessionsLoading"in a&&(a.sessionsLoading=!1),"agentsLoading"in a&&(a.agentsLoading=!1),"nodesLoading"in a&&(a.nodesLoading=!1),"devicesLoading"in a&&(a.devicesLoading=!1),"channelsLoading"in a&&(a.channelsLoading=!1),"presenceLoading"in a&&(a.presenceLoading=!1),n!==1012&&(e.lastError=`disconnected (${n}): ${s||"no reason"}`),yl(e)},onEvent:n=>si(e,n),onGap:({expected:n,received:s})=>{e.lastError=`event gap detected (expected seq ${n}, got ${s}); refresh recommended`}}),e.client.start()}function Dn(e,t){if(!e.chatMessages)return;const n=t.outputPreview?`
258
258
 
259
259
  ${t.outputPreview.slice(0,800)}${t.outputPreview.length>800?"…":""}`:"",s=t.outputPath?`
260
260
 
261
261
  Full output: \`${t.outputPath}\``:"";e.chatMessages=[...e.chatMessages,{role:"assistant",content:`**Agent completed: "${t.title||"Queue item"}"**${n}${s}
262
262
 
263
- _Reply to review, approve, or ask follow-up questions._`,timestamp:Date.now(),isNotification:!0}],e.requestUpdate?.()}function si(e,t){try{_l(e,t)}catch(n){console.error("[gateway] handleGatewayEvent error:",t.event,n)}}function _l(e,t){if(we.unshift({ts:Date.now(),event:t.event,payload:t.payload}),we.length>250&&(we.length=250),e.tab==="debug"&&(e.eventLog=[...we]),t.event==="agent"){if(e.onboarding)return;const n=t.payload,s=n?.sessionKey;s&&n?.stream==="tool"&&n.data?.phase==="start"&&(e.workingSessions.has(s)||(e.workingSessions.add(s),e.requestUpdate?.())),Co(e,n);return}if(t.event==="chat"){const n=t.payload;if(n?.sessionKey){if(mi(e,n.sessionKey),n.state==="delta"){const a=j.get(n.sessionKey);a&&(clearTimeout(a),j.delete(n.sessionKey)),e.workingSessions.has(n.sessionKey)||(e.workingSessions.add(n.sessionKey),e.requestUpdate?.());const o=`safety:${n.sessionKey}`,l=j.get(o);l&&clearTimeout(l),j.set(o,setTimeout(()=>{j.delete(o),e.workingSessions.has(n.sessionKey)&&e.workingSessions.delete(n.sessionKey);const c=e;gs(n.sessionKey,c.sessionKey)&&c.chatStream!==null&&c.chatRunId===null&&(c.chatStream=null,c.chatStreamStartedAt=null),c.requestUpdate?.()},9e4))}else if((n.state==="final"||n.state==="error"||n.state==="aborted")&&e.workingSessions.has(n.sessionKey)){const a=j.get(n.sessionKey);a&&(clearTimeout(a),j.delete(n.sessionKey));const o=`safety:${n.sessionKey}`,l=j.get(o);l&&(clearTimeout(l),j.delete(o)),e.workingSessions.delete(n.sessionKey),e.requestUpdate?.()}}n.state==="final"&&wl(e,n.sessionKey);const s=Us(e,n),i=ft(n?.sessionKey);if(n&&i){const a=e,o=e.tab==="chat"&&e.sessionKey===O;if(n.state==="delta"){const l=me(n.message);if(!o){if(typeof l=="string"){const c=a.allyStream??"";(!c||l.length>=c.length)&&(a.allyStream=l)}a.allyWorking=!0,a.requestUpdate?.()}}else if(n.state==="final"){a.allyStream=null,a.allyWorking=!1,!a.allyPanelOpen&&e.tab!=="chat"&&(a.allyUnread=(a.allyUnread??0)+1);const l=e;l._loadAllyHistory().then(()=>{a.allyPanelOpen&&l._scrollAllyToBottom(),a.requestUpdate?.()})}else if(n.state==="error"||n.state==="aborted"){const l=me(n.message),c=n.state==="aborted"?"Response was stopped.":l||"Something went wrong — try again.";a.allyMessages=[...a.allyMessages??[],{role:"assistant",content:`*${c}*`,timestamp:Date.now()}],a.allyStream=null,a.allyWorking=!1,a.requestUpdate?.()}}if(n.state==="final"&&(async()=>{await Sl(e,n.sessionKey);try{await K(e,{activeMinutes:0})}catch{}})(),(s==="final"||s==="error"||s==="aborted")&&(It(e),ki(e),s==="final"&&e.compactionStatus?.active&&(e.compactionStatus={active:!1,startedAt:e.compactionStatus.startedAt??null,completedAt:Date.now()},e.showToast?.("Compaction complete","info",2e3)),(s==="error"||s==="aborted")&&e.compactionStatus?.active&&(e.compactionStatus=null),e.refreshSessionsAfterChat=!1),s==="final"){const a=!!e.compactionStatus?.completedAt;Ns(e,{allowShrink:a}).then(()=>{F(e,!0),Zs(e),e.loadSessionResources?.(),hl(e)}),e.tab==="dashboards"&&z.emit("refresh-requested",{target:"dashboards",sessionKey:n.sessionKey})}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"&&Gt(e),(t.event==="device.pair.requested"||t.event==="device.pair.resolved")&&Ue(e,{quiet:!0}),t.event==="exec.approval.requested"){const n=Jr(t.payload);if(n){e.execApprovalQueue=Zr(e.execApprovalQueue,n),e.execApprovalError=null;const s=Math.max(0,n.expiresAtMs-Date.now()+500);window.setTimeout(()=>{e.execApprovalQueue=Pn(e.execApprovalQueue,n.id)},s)}return}if(t.event==="exec.process.completed"){const n=t.payload;if(n?.sessionId){const s=n.exitSignal?`signal ${n.exitSignal}`:`exit ${n.exitCode??0}`,i=n.status==="completed"?"✓":"✗",a=n.status==="completed"?"success":"warning",o=n.sessionId.slice(0,8),l=e;typeof l.showToast=="function"&&l.showToast(`${i} Process ${o} ${n.status} (${s})`,a,5e3)}return}if(t.event==="exec.approval.resolved"){const n=Xr(t.payload);n&&(e.execApprovalQueue=Pn(e.execApprovalQueue,n.id))}if(t.event==="daily-brief:update"){z.emit("refresh-requested",{target:"today"});return}if(t.event==="ui.slot.update"){const n=t.payload;if(n?.tabId){const s=n.mode??"replace";if(n.html)s==="append"?e.dynamicSlots={...e.dynamicSlots,[n.tabId]:(e.dynamicSlots[n.tabId]??"")+n.html}:e.dynamicSlots={...e.dynamicSlots,[n.tabId]:n.html};else{const a={...e.dynamicSlots};delete a[n.tabId],e.dynamicSlots=a}e.requestUpdate?.()}return}if(t.event==="guardrails:update"){const n=e;typeof n.handleGuardrailsLoad=="function"&&n.handleGuardrailsLoad();return}if(t.event==="fathom:meeting-processed"){const n=t.payload;if(n?.title){const s=e;typeof s.showToast=="function"&&s.showToast(`Meeting processed: ${n.title}`,"success",6e3);const i=n.message??`Meeting "${n.title}" has been processed.`;s.allyMessages=[...s.allyMessages??[],{role:"assistant",content:i,timestamp:Date.now()}],!s.allyPanelOpen&&s.tab!=="chat"&&(s.allyUnread=(s.allyUnread??0)+1),s.sessionKey===O&&s.chatMessages&&(s.chatMessages=[...s.chatMessages,{role:"assistant",content:i,timestamp:Date.now()}]),s.requestUpdate?.()}return}if(t.event==="onboarding:update"){const n=t.payload;if(n){const s=e;if(typeof n.phase=="number"&&(s.onboardingPhase=n.phase),s.onboardingData=n,n.completedAt&&(s.onboardingActive=!1),n.identity?.name){const i=e;(!i.userName||!i.settings.userName)&&(i.userName=n.identity.name,i.applySettings({...i.settings,userName:n.identity.name}))}s.requestUpdate?.()}return}if(t.event==="inbox:update"){z.emit("refresh-requested",{target:"today"});return}if(t.event==="hitl:checkpoint"){const n=t.payload;if(n?.id){const s=e;s.hitlCheckpoints=[...s.hitlCheckpoints??[],n],s.requestUpdate?.();const i=e,a={role:"assistant",content:n.summary||`Agent checkpoint: ${n.agentName??"Agent"} is awaiting approval.`,timestamp:Date.now(),isNotification:!0,hitlCheckpoint:n,actions:[{label:"Review",action:"navigate",target:"today"}]};i.allyMessages=[...i.allyMessages??[],a],!i.allyPanelOpen&&e.tab!=="chat"&&(i.allyUnread=(i.allyUnread??0)+1)}z.emit("refresh-requested",{target:"today"});return}if(t.event==="queue:update"){const n=t.payload;n?.status==="processing"&&n.proofDocSlug&&e.handleOpenProofDoc?.(n.proofDocSlug).catch(()=>{}),z.emit("refresh-requested",{target:"today"});return}if(t.event==="ally:notification"){const n=t.payload;if(n){const s=e,i={role:"assistant",content:n.summary||n.message||"Notification received.",timestamp:Date.now(),isNotification:!0,actions:n.actions??[]};s.allyMessages=[...s.allyMessages??[],i],!s.allyPanelOpen&&e.tab!=="chat"&&(s.allyUnread=(s.allyUnread??0)+1);const a=["queue-complete","queue-needs-review","queue-failed","cron-result","paperclip-completion"];n.type&&a.includes(n.type)&&z.emit("refresh-requested",{target:"today"});const o=["queue-complete","queue-needs-review","paperclip-completion"];if(n.type&&o.includes(n.type)){const l=n,c=e;i.content=l.message||i.content,l.sessionKey&&c.sessionKey===l.sessionKey?Dn(c,l):l.sessionKey||Dn(c,l)}s.requestUpdate?.()}return}if(t.event==="sessions:updated"){const n=t.payload;n?.sessionKey&&n?.title&&(e.sessionsResult?.sessions&&(e.sessionsResult={...e.sessionsResult,sessions:e.sessionsResult.sessions.map(s=>s.key===n.sessionKey||s.key?.endsWith(`:${n.sessionKey?.split(":").pop()}`)||n.sessionKey?.endsWith(`:${s.key?.split(":").pop()}`)?{...s,displayName:n.title,label:n.title}:s)}),se.set(n.sessionKey,n.title),ti.add(n.sessionKey),e.requestUpdate?.());return}if(t.event==="session:auto-compact"){const n=t.payload;if(n?.sessionKey){const s=e;n.sessionKey===s.sessionKey&&!s.compactionStatus?.active&&s.connected&&(s.showToast?.("Context near limit — auto-compacting...","info",3e3),s.handleCompactChat?.())}return}}const kl=300*1e3;async function Tl(e){if(!e.client)return;const t=e;if(!(t.availableModels.length>0&&Date.now()-t.modelCacheTs<kl))try{const n=await e.client.request("godmode.config.model",{});n?.primary&&(t.currentModel=n.primary),Array.isArray(n?.available)&&(t.availableModels=n.available),t.modelCacheTs=Date.now()}catch{}}async function Al(e,t){if(!e.client)return;const n=e;try{await e.client.request("godmode.config.model.set",{primary:t}),n.currentModel=t,n.modelPickerOpen=!1,e.modelCacheTs=0}catch(s){console.error("[model-switch]",s)}}async function $l(e){if(typeof window>"u")return;const t=new URLSearchParams(window.location.search),n=t.get("openTask");if(!n||!e.client)return;t.delete("openTask");const s=t.toString()?`${window.location.pathname}?${t.toString()}`:window.location.pathname;window.history.replaceState({},"",s);try{const i=await e.client.request("tasks.openSession",{taskId:n});if(i?.sessionKey){e.sessionKey=i.sessionKey,e.tab="chat";const{loadChatHistory:a}=await _(async()=>{const{loadChatHistory:o}=await Promise.resolve().then(()=>fe);return{loadChatHistory:o}},void 0,import.meta.url);await a(e,i.sessionKey)}}catch(i){console.error("[GodMode] Failed to open task session:",i)}}async function ii(e){if(!e.client)return;const t=e;t.secretsLoading=!0;try{const n=await e.client.request("godmode.secrets.list",{});t.secrets=n?.keys??[]}catch{t.secrets=[]}finally{t.secretsLoading=!1}}async function ai(e,t){if(!e.client)return;const n=e;try{await e.client.request("godmode.config.webfetch.set",{provider:t}),n.webFetchProvider=t}catch(s){console.error("[webfetch-set]",s)}}async function oi(e,t){if(!e.client)return;const n=e;try{await e.client.request("godmode.config.search.set",{defaultProvider:t}),n.searchProvider=t}catch(s){console.error("[search-set]",s)}}function ri(e,t){const n=t.snapshot;n?.presence&&Array.isArray(n.presence)&&(e.presenceEntries=n.presence),n?.health&&(e.debugHealth=n.health),n?.sessionDefaults&&gl(e,n.sessionDefaults)}async function li(e){if(e.client)try{const n=(await e.client.request("customTabs.list",{}))?.tabs??[];for(const s of Pa())La(s);for(const s of n)Ma(s.slug);e.customTabs=n}catch{e.customTabs=[]}}async function ci(e,t){if(!e.client)return;e.customTabLoading=!0,e.customTabErrors={};const n={},s={};for(const i of t.dataSources)try{if(i.type==="static")n[i.id]=i.data;else if(i.type==="rpc"&&i.method){const a=await e.client.request(i.method,i.params??{});n[i.id]=a}}catch(a){s[i.id]=a instanceof Error?a.message:String(a)}e.customTabData=n,e.customTabErrors=s,e.customTabLoading=!1}const di=Object.freeze(Object.defineProperty({__proto__:null,applySnapshot:ri,connectGateway:ze,fetchCustomTabData:ci,getEventLogSnapshot:ei,getResolvedImageUrl:Xs,handleGatewayEvent:si,loadCustomTabs:li,loadSecrets:ii,resetAutoTitleState:ni,setSearchProvider:oi,setWebFetchProvider:ai,switchModelFromChat:Al,triggerImageResolve:_e},Symbol.toStringTag,{value:"Module"}));function Ft(e){e.nodesPollInterval==null&&(e.nodesPollInterval=window.setInterval(()=>{Fe(e,{quiet:!0})},5e3))}function Ut(e){e.nodesPollInterval!=null&&(clearInterval(e.nodesPollInterval),e.nodesPollInterval=null)}function Wt(e){e.logsPollInterval==null&&(e.logsPollInterval=window.setInterval(()=>{e.tab==="logs"&&xt(e,{quiet:!0})},2e3))}function qt(e){e.logsPollInterval!=null&&(clearInterval(e.logsPollInterval),e.logsPollInterval=null)}function Bt(e){e.debugPollInterval==null&&(e.debugPollInterval=window.setInterval(()=>{e.tab==="debug"&&We(e)},3e3))}function jt(e){e.debugPollInterval!=null&&(clearInterval(e.debugPollInterval),e.debugPollInterval=null)}function Ve(e,t=Date.now()){if(typeof e=="number"&&Number.isFinite(e))return new Date(e);if(typeof e=="string"){const n=Date.parse(e);if(Number.isFinite(n))return new Date(n)}return new Date(t)}function Ht(e){return{id:e.id,name:e.name,emoji:e.emoji||"📁",type:e.type,path:e.path,artifactCount:e.artifactCount??0,sessionCount:e.sessionCount??0,connectionCount:e.connectionCount??0,feedCount:e.feedCount??0,lastUpdated:Ve(e.lastUpdated,e.lastScanned)}}function it(e){return{path:e.path,name:e.name,type:e.type,size:e.size,modified:Ve(e.modified),isDirectory:e.isDirectory,searchText:e.searchText}}function On(e){return{id:e.id,key:e.key,title:e.title,created:Ve(e.created),status:e.status,workspaceSubfolder:e.workspaceSubfolder}}function Te(e){return{id:e.id,title:e.title,status:e.status,project:e.project,dueDate:e.dueDate,priority:e.priority,createdAt:e.createdAt,completedAt:e.completedAt}}function ui(e){return e.map(t=>({name:t.name,path:t.path,type:t.type,fileType:t.fileType,size:t.size,modified:t.modified?Ve(t.modified):void 0,children:t.children?ui(t.children):void 0}))}function Cl(e,t){return{...t,id:e.id,name:e.name,emoji:e.emoji,type:e.type,path:e.path,artifactCount:e.artifactCount,sessionCount:e.sessionCount,lastUpdated:e.lastUpdated}}async function xl(e){if(!e.client||!e.connected){e.workspaces?.length||(e.workspaces=[],e.workspacesError="Connect to gateway to see workspaces"),e.workspacesLoading=!1;return}e.workspacesLoading=!0,e.workspacesError=null;try{const t=await e.client.request("workspaces.list",{});if(e.workspaces=(t.workspaces??[]).map(Ht),e.selectedWorkspace){const n=e.workspaces.find(s=>s.id===e.selectedWorkspace?.id);n&&(e.selectedWorkspace=Cl(n,e.selectedWorkspace))}}catch(t){console.error("[Workspaces] load failed:",t),e.workspacesError=t instanceof Error?t.message:"Failed to load workspaces",e.workspaces?.length||(e.workspaces=[])}finally{e.workspacesLoading=!1}}async function zt(e,t){if(!e.client||!e.connected)return null;try{const n=await e.client.request("workspaces.get",{id:t});if(!n.workspace)return null;const s={...Ht(n.workspace),pinned:(n.pinned??[]).map(it),pinnedSessions:(n.pinnedSessions??[]).map(On),outputs:(n.outputs??[]).map(it),folderTree:n.folderTree?ui(n.folderTree):void 0,sessions:(n.sessions??[]).map(On),tasks:(n.tasks??[]).map(Te),memory:(n.memory??[]).map(it)};try{const[i,a]=await Promise.all([Ll(e,t).catch(()=>[]),Ml(e,t).catch(()=>[])]);s.feedEntries=i,s.connections=a,s.feedCount=i.length,s.connectionCount=a.length}catch{}return s}catch(n){return console.error("[Workspaces] get failed:",n),null}}async function ku(e,t,n){if(!e.client||!e.connected)return null;try{const s=await e.client.request("workspaces.readFile",n?{workspaceId:n,filePath:t}:{path:t});return s.content?{content:s.content,mime:s.contentType??s.mime??"text/plain"}:(s.error&&console.warn("[Workspaces] readFile failed:",s.error),null)}catch(s){return console.error("[Workspaces] readFile error:",s),null}}async function Tu(e,t){if(!t){e.selectedWorkspace=null;return}const n=await zt(e,t.id);e.selectedWorkspace=n||{...t,pinned:[],pinnedSessions:[],outputs:[],sessions:[],tasks:[]}}async function Au(e,t,n,s){if(!e.client||!e.connected)return!1;try{if(await e.client.request(s?"workspaces.unpin":"workspaces.pin",{workspaceId:t,filePath:n}),e.selectedWorkspace?.id===t){const i=await zt(e,t);i&&(e.selectedWorkspace=i)}return!0}catch(i){return console.error("[Workspaces] pin toggle failed:",i),!1}}async function $u(e,t,n,s){if(!e.client||!e.connected)return!1;try{if(await e.client.request(s?"workspaces.unpinSession":"workspaces.pinSession",{workspaceId:t,sessionKey:n}),e.selectedWorkspace?.id===t){const i=await zt(e,t);i&&(e.selectedWorkspace=i)}return!0}catch(i){return console.error("[Workspaces] session pin toggle failed:",i),!1}}async function Cu(e,t){if(!e.client||!e.connected)return null;const n=String(t.name??"").trim();if(!n)return e.workspacesError="Workspace name is required",null;const s=t.type??"project",i=String(t.path??"").trim();try{const a=await e.client.request("workspaces.create",{name:n,type:s,...i?{path:i}:{}});if(!a.workspace)return e.workspacesError="Workspace creation returned no workspace",null;const o=Ht(a.workspace),l=e.workspaces??[],c=new Map(l.map(m=>[m.id,m]));return c.set(o.id,o),e.workspaces=Array.from(c.values()).toSorted((m,r)=>r.lastUpdated.getTime()-m.lastUpdated.getTime()),e.workspacesError=null,o}catch(a){return console.error("[Workspaces] create failed:",a),e.workspacesError=a instanceof Error?a.message:"Failed to create workspace",null}}async function xu(e,t){if(!e.client||!e.connected)return!1;try{return await e.client.request("workspaces.delete",{id:t}),e.workspaces=(e.workspaces??[]).filter(n=>n.id!==t),e.selectedWorkspace?.id===t&&(e.selectedWorkspace=null),e.workspacesError=null,!0}catch(n){return console.error("[Workspaces] delete failed:",n),e.workspacesError=n instanceof Error?n.message:"Failed to delete workspace",!1}}function Pu(e,t){const n=new Set(e);return n.has(t)?n.delete(t):n.add(t),n}const Pl={coding:"Builder",research:"Researcher",analysis:"Analyst",creative:"Creative",review:"Reviewer",ops:"Ops",task:"Agent",url:"Reader",idea:"Explorer"};async function Lu(e){if(!e.client||!e.connected)return[];try{const[t,n]=await Promise.all([e.client.request("tasks.list",{}),e.client.request("queue.list",{limit:100}).catch(()=>({items:[]}))]),s=new Map;for(const i of n.items)i.sourceTaskId&&(i.status==="processing"||i.status==="review"||i.status==="needs-review"||i.status==="failed")&&s.set(i.sourceTaskId,{status:i.status==="needs-review"?"review":i.status,type:i.type,roleName:Pl[i.type]??i.type,queueItemId:i.id});return(t.tasks??[]).map(i=>({...Te(i),queueStatus:s.get(i.id)??null}))}catch(t){return console.error("[Workspaces] loadAllTasksWithQueueStatus failed:",t),[]}}async function Mu(e,t,n){if(!e.client||!e.connected)return null;const s=n==="complete"?"pending":"complete";try{const i=await e.client.request("tasks.update",{id:t,status:s});return Te(i)}catch(i){return console.error("[Workspaces] toggleTaskComplete failed:",i),null}}async function Iu(e,t,n){if(!e.client||!e.connected)return null;try{const s=await e.client.request("tasks.update",{id:t,...n});return Te(s)}catch(s){return console.error("[Workspaces] updateTask failed:",s),null}}async function Ru(e,t){if(!e.client||!e.connected)return null;try{return await e.client.request("tasks.openSession",{taskId:t})}catch(n){return console.error("[Workspaces] startTask failed:",n),null}}async function Eu(e,t,n){if(!e.client||!e.connected)return null;try{const s=await e.client.request("tasks.create",{title:t,project:n,source:"chat"});return Te(s)}catch(s){return console.error("[Workspaces] createTask failed:",s),null}}async function Du(e,t,n){if(!e.client||!e.connected)return null;try{return await e.client.request("workspaces.browseFolder",{workspaceId:t,folderPath:n})}catch(s){return console.error("[Workspaces] browseFolder failed:",s),null}}async function Ou(e,t,n,s=50){if(!e.client||!e.connected)return[];try{return(await e.client.request("workspaces.search",{workspaceId:t,query:n,limit:s})).results??[]}catch(i){return console.error("[Workspaces] search failed:",i),[]}}async function Ku(e,t,n){if(!e.client||!e.connected)return!1;try{return await e.client.request("workspaces.createFolder",{workspaceId:t,folderPath:n}),!0}catch(s){return console.error("[Workspaces] createFolder failed:",s),!1}}async function Ll(e,t,n=50,s){if(!e.client||!e.connected)return[];try{return(await e.client.request("workspace.feed.read",{workspaceId:t,limit:n,before:s})).entries??[]}catch(i){return console.error("[Workspaces] loadFeed failed:",i),[]}}async function Nu(e,t,n,s="update"){if(!e.client||!e.connected)return null;try{return(await e.client.request("workspace.feed.post",{workspaceId:t,text:n,type:s,author:"user"})).entry??null}catch(i){return console.error("[Workspaces] postToFeed failed:",i),null}}async function Ml(e,t){if(!e.client||!e.connected)return[];try{return(await e.client.request("workspace.connections.list",{workspaceId:t})).connections??[]}catch(n){return console.error("[Workspaces] loadConnections failed:",n),[]}}async function Fu(e,t,n){if(!e.client||!e.connected)return{ok:!1,error:"Not connected"};try{return await e.client.request("workspace.connections.test",{workspaceId:t,connectionId:n})}catch(s){return console.error("[Workspaces] testConnection failed:",s),{ok:!1,error:s instanceof Error?s.message:"Failed"}}}async function Uu(e,t,n){if(!e.client||!e.connected)return!1;try{return await e.client.request("workspace.connections.remove",{workspaceId:t,connectionId:n}),!0}catch(s){return console.error("[Workspaces] removeConnection failed:",s),!1}}const pi="godmode.ui.settings.v1";function Il(){const e=new URLSearchParams(location.search),t=(()=>{const i=e.get("gatewayUrl");return i||(typeof window.__GODMODE_DEV__<"u"?"/ws":`${location.protocol==="https:"?"wss:":"ws:"}//${location.host}`)})(),n=e.get("token")||"",s={gatewayUrl:t,token:n,sessionKey:"main",lastActiveSessionKey:"main",theme:"system",chatFocusMode:!1,chatShowThinking:!0,splitRatio:.6,navCollapsed:!1,navGroupsCollapsed:{System:!0,__missionControl__:!1},openTabs:[],tabLastViewed:{},userName:"",userAvatar:"",chatParallelView:!1,parallelLanes:[null,null,null,null]};try{const i=localStorage.getItem(pi);if(!i)return s;const a=JSON.parse(i);return{gatewayUrl:e.get("gatewayUrl")||(typeof window.__GODMODE_DEV__<"u"?"/ws":typeof a.gatewayUrl=="string"&&a.gatewayUrl.trim()?a.gatewayUrl.trim():s.gatewayUrl),token:n||(typeof a.token=="string"?a.token:""),sessionKey:typeof a.sessionKey=="string"&&a.sessionKey.trim()?a.sessionKey.trim():s.sessionKey,lastActiveSessionKey:typeof a.lastActiveSessionKey=="string"&&a.lastActiveSessionKey.trim()?a.lastActiveSessionKey.trim():typeof a.sessionKey=="string"&&a.sessionKey.trim()||s.lastActiveSessionKey,theme:a.theme==="light"||a.theme==="dark"||a.theme==="system"||a.theme==="lifetrack"?a.theme:s.theme,chatFocusMode:typeof a.chatFocusMode=="boolean"?a.chatFocusMode:s.chatFocusMode,chatShowThinking:typeof a.chatShowThinking=="boolean"?a.chatShowThinking:s.chatShowThinking,splitRatio:typeof a.splitRatio=="number"&&a.splitRatio>=.4&&a.splitRatio<=.7?a.splitRatio:s.splitRatio,navCollapsed:typeof a.navCollapsed=="boolean"?a.navCollapsed:s.navCollapsed,navGroupsCollapsed:typeof a.navGroupsCollapsed=="object"&&a.navGroupsCollapsed!==null?a.navGroupsCollapsed:s.navGroupsCollapsed,openTabs:Array.isArray(a.openTabs)&&a.openTabs.every(o=>typeof o=="string")?a.openTabs:s.openTabs,tabLastViewed:typeof a.tabLastViewed=="object"&&a.tabLastViewed!==null?a.tabLastViewed:s.tabLastViewed,userName:typeof a.userName=="string"?a.userName.trim().slice(0,50):s.userName,userAvatar:typeof a.userAvatar=="string"?a.userAvatar.trim():s.userAvatar,chatParallelView:typeof a.chatParallelView=="boolean"?a.chatParallelView:s.chatParallelView,parallelLanes:Array.isArray(a.parallelLanes)&&a.parallelLanes.length===4?a.parallelLanes.map(o=>typeof o=="string"?o:null):s.parallelLanes}}catch{return s}}function Rl(e){localStorage.setItem(pi,JSON.stringify(e))}const El=56,Dl="quantum-particles",Ol="quantum-particle";let J=null,Se=null;function q(e,t){return Math.random()*(t-e)+e}function hi(){if(fi(),typeof document>"u")return;const e=document.querySelector(".shell");if(!e){Se=requestAnimationFrame(()=>{Se=null,hi()});return}J=document.createElement("div"),J.className=Dl,Object.assign(J.style,{position:"fixed",inset:"0",pointerEvents:"none",zIndex:"1",overflow:"hidden"});for(let t=0;t<El;t++){const n=document.createElement("div");n.className=Ol;const s=q(2,5),i=q(.3,.65),a=q(15,35),o=q(0,12),l=q(5,95),c=q(5,95),m=q(-150,150),r=q(-200,200),p=q(-250,250),g=q(-350,350),y=q(.8,1.5);Object.assign(n.style,{position:"absolute",left:`${l}%`,top:`${c}%`,width:`${s}px`,height:`${s}px`,borderRadius:"50%",background:`rgba(235, 158, 15, ${q(.7,1)})`,boxShadow:`0 0 ${s*3}px rgba(235, 158, 15, ${i*.7})`,opacity:"0",willChange:"transform, opacity",animation:`quantum-float ${a}s ${o}s ease-in-out infinite`}),n.style.setProperty("--particle-opacity",String(i)),n.style.setProperty("--drift-x",`${m}px`),n.style.setProperty("--drift-y",`${r}px`),n.style.setProperty("--drift-end-x",`${p}px`),n.style.setProperty("--drift-end-y",`${g}px`),n.style.setProperty("--particle-scale-mid",String(y)),J.appendChild(n)}e.prepend(J)}function fi(){Se!==null&&(cancelAnimationFrame(Se),Se=null),J&&(J.remove(),J=null)}function Kl(){return typeof window>"u"||typeof window.matchMedia!="function"||window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"lifetrack"}function Vt(e){return e==="system"?Kl():e==="light"?"lifetrack":e}const Le=e=>Number.isNaN(e)?.5:e<=0?0:e>=1?1:e,Nl=()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches??!1,ve=e=>{e.classList.remove("theme-transition"),e.style.removeProperty("--theme-switch-x"),e.style.removeProperty("--theme-switch-y")},Fl=({nextTheme:e,applyTheme:t,context:n,currentTheme:s})=>{if(s===e)return;const i=globalThis.document??null;if(!i){t();return}const a=i.documentElement,o=i,l=Nl();if(!!o.startViewTransition&&!l){let m=.5,r=.5;if(n?.pointerClientX!==void 0&&n?.pointerClientY!==void 0&&typeof window<"u")m=Le(n.pointerClientX/window.innerWidth),r=Le(n.pointerClientY/window.innerHeight);else if(n?.element){const g=n.element.getBoundingClientRect();g.width>0&&g.height>0&&typeof window<"u"&&(m=Le((g.left+g.width/2)/window.innerWidth),r=Le((g.top+g.height/2)/window.innerHeight))}a.style.setProperty("--theme-switch-x",`${m*100}%`),a.style.setProperty("--theme-switch-y",`${r*100}%`),a.classList.add("theme-transition");const p=setTimeout(()=>{ve(a)},1e3);try{const g=o.startViewTransition?.(()=>{t()});g?.finished?g.finished.finally(()=>{clearTimeout(p),ve(a)}):(clearTimeout(p),ve(a))}catch{clearTimeout(p),ve(a),t()}return}t(),ve(a)};function Ul(e,t){const n=Array.isArray(e)?[...new Set(e.map(s=>s.trim()).filter(s=>s.length>0))]:[];if(n.length===0&&t){const s=t.toLowerCase();s==="main"||s==="agent:main:main"||s.endsWith(":main")||n.push(t)}return n}function Wl(e){const t={};if(!e||typeof e!="object")return t;for(const[n,s]of Object.entries(e)){const i=n.trim();!i||typeof s!="number"||!Number.isFinite(s)||(t[i]=Math.max(t[i]??0,s))}return t}function te(e,t){const n=t.sessionKey.trim()||"main",s=Ul(t.openTabs,n),i=Wl(t.tabLastViewed),a={...t,sessionKey:n,openTabs:s,tabLastViewed:i,lastActiveSessionKey:t.lastActiveSessionKey?.trim()||n};e.settings=a,Rl(a),a.theme!==e.theme&&(e.theme=a.theme,Qe(e,Vt(a.theme))),e.applySessionKey=e.settings.lastActiveSessionKey}function mi(e,t){const n=t.trim();n&&e.settings.lastActiveSessionKey!==n&&te(e,{...e.settings,lastActiveSessionKey:n})}function ql(e){if(!window.location.search)return;const t=new URLSearchParams(window.location.search),n=t.get("token"),s=t.get("password"),i=t.get("session"),a=t.get("gatewayUrl");let o=!1;if(n!=null){const c=n.trim();c&&c!==e.settings.token&&te(e,{...e.settings,token:c}),t.delete("token"),o=!0}if(s!=null){const c=s.trim();c&&(e.password=c),t.delete("password"),o=!0}if(i!=null){const c=i.trim();if(c){e.sessionKey=c;const m=c.toLowerCase(),p=m==="main"||m==="agent:main:main"||m.endsWith(":main")||e.settings.openTabs.includes(c)?e.settings.openTabs:[...e.settings.openTabs,c];te(e,{...e.settings,sessionKey:c,lastActiveSessionKey:c,openTabs:p})}}if(a!=null){const c=a.trim();c&&c!==e.settings.gatewayUrl&&(e.pendingGatewayUrl=c),t.delete("gatewayUrl"),o=!0}if(!o)return;const l=new URL(window.location.href);l.search=t.toString(),window.history.replaceState({},"",l.toString())}function Bl(e,t){const n=e.tab;if(n!==t&&(e.tab=t),n==="chat"&&t!=="chat"&&e.sessionKey===O&&e._loadAllyHistory?.(),n==="dashboards"&&t!=="dashboards"){const s=e;if(s.dashboardPreviousSessionKey&&s.activeDashboardId){const i=s.dashboardPreviousSessionKey;s.dashboardPreviousSessionKey=null,s.activeDashboardId=null,s.activeDashboardManifest=null,s.activeDashboardHtml=null,s.dashboardChatOpen=!1,e.sessionKey=i}}t==="chat"&&(e.chatHasAutoScrolled=!1),t==="nodes"?Ft(e):Ut(e),t==="logs"?Wt(e):qt(e),t==="debug"?Bt(e):jt(e),Ge(e),yi(e,t,!1)}function jl(e,t,n){Fl({nextTheme:t,applyTheme:()=>{e.theme=t,te(e,{...e.settings,theme:t}),Qe(e,Vt(t))},context:n,currentTheme:e.theme})}async function Ge(e){if(e.tab==="overview"&&await vi(e),(e.tab==="today"||e.tab==="my-day")&&z.emit("refresh-requested",{target:"today"}),e.tab==="workspaces"&&await xl(e),e.tab==="channels"&&await Yl(e),e.tab==="instances"&&await Pt(e),e.tab==="sessions"&&(await K(e),await ut(e)),e.tab==="cron"&&await Gt(e),e.tab==="skills"&&(await is(e),await pt(e)),e.tab==="agents"){const{loadRoster:t}=await _(async()=>{const{loadRoster:n}=await import("./ctrl-settings-niym-WgY.js").then(s=>s.ac);return{loadRoster:n}},[],import.meta.url);await t(e)}if(e.tab==="nodes"&&(await Fe(e),await Ue(e),await oe(e),await as(e)),e.tab==="chat"&&(await Jt(e),F(e,!e.chatHasAutoScrolled),e.loadSessionResources?.()),e.tab==="trust"){const t=e,n=[];typeof t.handleTrustLoad=="function"&&n.push(t.handleTrustLoad()),n.push(Yi(t)),n.push(K(t)),await Promise.all(n)}if(e.tab==="guardrails"){const t=e;typeof t.handleGuardrailsLoad=="function"&&await t.handleGuardrailsLoad()}if(e.tab==="setup"){const t=e;typeof t.handleLoadCapabilities=="function"&&t.handleLoadCapabilities()}if(e.tab==="dashboards"){const t=e;typeof t.handleDashboardsRefresh=="function"&&await t.handleDashboardsRefresh()}if(e.tab==="memory"||e.tab==="second-brain"){const t=e;typeof t.handleSecondBrainRefresh=="function"&&await t.handleSecondBrainRefresh()}if(e.tab==="config"&&(await os(e),await oe(e)),e.tab==="debug"&&(await We(e),e.eventLog=ei()),e.tab==="logs"&&(e.logsAtBottom=!0,await xt(e,{reset:!0}),Mt(e,!0)),us(e.tab)){const t=e,n=(t.customTabs??[]).find(s=>s.slug===e.tab);if(n){const{fetchCustomTabData:s}=await _(async()=>{const{fetchCustomTabData:i}=await Promise.resolve().then(()=>di);return{fetchCustomTabData:i}},void 0,import.meta.url);await s(t,n)}}}function Hl(){if(typeof window>"u")return"";const e=window.__OPENCLAW_CONTROL_UI_BASE_PATH__;return typeof e=="string"&&e.trim()?ds(e):Ia(window.location.pathname)}function zl(e){e.theme=e.settings.theme??"system",Qe(e,Vt(e.theme))}function Qe(e,t){if(e.themeResolved=t,typeof document>"u")return;const n=document.documentElement;n.dataset.theme=t,n.style.colorScheme=t==="dark"?"dark":"light",t==="lifetrack"?hi():fi()}function Vl(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"&&Qe(e,n.matches?"dark":"lifetrack")},typeof e.themeMedia.addEventListener=="function"){e.themeMedia.addEventListener("change",e.themeMediaHandler);return}e.themeMedia.addListener(e.themeMediaHandler)}function Gl(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 Kn(e,t){if(typeof window>"u")return;const n=cs(window.location.pathname,e.basePath)??"chat";gi(e,n),yi(e,n,t)}function Ql(e){if(typeof window>"u")return;const t=cs(window.location.pathname,e.basePath);if(!t)return;const s=new URL(window.location.href).searchParams.get("session")?.trim();if(s){e.sessionKey=s;const i=e.settings.openTabs.includes(s)?e.settings.openTabs:[...e.settings.openTabs,s];te(e,{...e.settings,sessionKey:s,lastActiveSessionKey:s,openTabs:i})}gi(e,t)}function gi(e,t){e.tab!==t&&(e.tab=t),t==="chat"&&(e.chatHasAutoScrolled=!1),t==="nodes"?Ft(e):Ut(e),t==="logs"?Wt(e):qt(e),t==="debug"?Bt(e):jt(e),e.connected&&Ge(e)}function yi(e,t,n){if(typeof window>"u")return;const s=ln(Lt(t,e.basePath)),i=ln(window.location.pathname),a=new URL(window.location.href);t==="chat"&&e.sessionKey?a.searchParams.set("session",e.sessionKey):a.searchParams.delete("session"),i!==s&&(a.pathname=s),n?window.history.replaceState({},"",a.toString()):window.history.pushState({},"",a.toString())}function V(e,t,n){if(typeof window>"u")return;const s=new URL(window.location.href);s.searchParams.set("session",t),window.history.replaceState({},"",s.toString())}async function vi(e){await Promise.all([H(e,!1),Pt(e),K(e),ss(e),We(e)])}async function Yl(e){await Promise.all([H(e,!0),os(e),oe(e)])}async function Gt(e){await Promise.all([H(e,!1),ss(e),Qi(e)])}function Ke(e){return e.chatSending||!!e.chatRunId}function ee(e,t){const n=t??e.sessionKey,s=e.chatMessage.trim();if(s)e.chatDrafts={...e.chatDrafts,[n]:s};else{const{[n]:i,...a}=e.chatDrafts;e.chatDrafts=a}}function ie(e,t){const n=t??e.sessionKey;e.chatMessage=e.chatDrafts[n]??""}function bi(e,t){const n=e.sessionKey,{[n]:s,...i}=e.chatDrafts;e.chatDrafts=i,n===e.sessionKey&&(e.chatMessage="")}function wi(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 Jl(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 Qt(e){e.connected&&(e.chatMessage="",await Nt(e))}function Xl(e,t,n){const s=t.trim(),i=!!(n&&n.length>0);if(!s&&!i)return;const a=Date.now();e.chatQueue=[...e.chatQueue,{id:He(),text:s,createdAt:a,attachments:i?n?.map(l=>({...l})):void 0}];const o=[];if(s&&o.push({type:"text",text:s}),i&&n)for(const l of n)o.push({type:"image",source:{type:"base64",media_type:l.mimeType,data:l.dataUrl}});e.chatMessages=[...e.chatMessages,{role:"user",content:o,timestamp:a}],F(e,!0)}async function Tt(e,t,n){It(e);const s=e;s.sessionKey&&s.workingSessions&&(s.workingSessions=new Set([...s.workingSessions,s.sessionKey])),n?.skipOptimisticUpdate||queueMicrotask(()=>{F(e,!0)});const i=await Fs(e,t,n?.attachments,{skipOptimisticUpdate:n?.skipOptimisticUpdate});return!i&&n?.previousDraft!=null&&(e.chatMessage=n.previousDraft),!i&&n?.previousAttachments&&(e.chatAttachments=n.previousAttachments),i&&(mi(e,e.sessionKey),e.chatAttachments=[]),i&&n?.restoreDraft&&n.previousDraft?.trim()&&(e.chatMessage=n.previousDraft),i&&n?.restoreAttachments&&n.previousAttachments?.length&&(e.chatAttachments=n.previousAttachments),F(e,!0),i&&!e.chatRunId&&Yt(e),i&&n?.refreshSessions&&(e.refreshSessionsAfterChat=!0),i}async function Yt(e){if(!e.connected||Ke(e))return;const[t,...n]=e.chatQueue;if(!t)return;e.chatQueue=n,await Tt(e,t.text,{attachments:t.attachments,skipOptimisticUpdate:!0})||(e.chatQueue=[t,...e.chatQueue])}function Si(e,t){e.chatQueue=e.chatQueue.filter(n=>n.id!==t)}async function _i(e,t,n){if(!e.connected)return;const s=e.chatMessage,i=(t??e.chatMessage).trim(),a=e.chatAttachments??[],o=t==null?a:[],l=o.length>0;if(!i&&!l)return;if(wi(i)){await Qt(e);return}const c=Jl(i);if(t==null&&(e.chatMessage="",bi(e)),n?.queue){Xl(e,i,o),Ke(e)||await Yt(e);return}if(Ke(e)){await Nt(e),await new Promise(m=>setTimeout(m,50)),await Tt(e,i,{attachments:l?o:void 0,refreshSessions:c});return}await Tt(e,i,{previousDraft:t==null?s:void 0,restoreDraft:!!(t&&n?.restoreDraft),attachments:l?o:void 0,previousAttachments:t==null?a:void 0,restoreAttachments:!!(t&&n?.restoreDraft),refreshSessions:c})}async function Jt(e){await Promise.all([N(e),K(e,{activeMinutes:0}),Ne(e)]),F(e,!0)}const ki=Yt;function Zl(e){const t=ms(e.sessionKey);return t?.agentId?t.agentId:e.hello?.snapshot?.sessionDefaults?.defaultAgentId?.trim()||"main"}function ec(e,t){const n=ds(e),s=encodeURIComponent(t);return n?`${n}/avatar/${s}?meta=1`:`/avatar/${s}?meta=1`}async function Ne(e){if(!e.connected){e.chatAvatarUrl=null;return}const t=Zl(e);if(!t){e.chatAvatarUrl=null;return}e.chatAvatarUrl=null;const n=ec(e.basePath,t);try{const s=await fetch(n,{method:"GET"});if(!s.ok){e.chatAvatarUrl=null;return}const i=await s.json(),a=typeof i.avatarUrl=="string"?i.avatarUrl.trim():"";e.chatAvatarUrl=a||null}catch{e.chatAvatarUrl=null}}const tc=Object.freeze(Object.defineProperty({__proto__:null,clearDraft:bi,flushChatQueueForEvent:ki,handleAbortChat:Qt,handleSendChat:_i,isChatBusy:Ke,isChatStopCommand:wi,refreshChat:Jt,refreshChatAvatar:Ne,removeQueuedMessage:Si,restoreDraft:ie,saveDraft:ee},Symbol.toStringTag,{value:"Module"})),nc={trace:!0,debug:!0,info:!0,warn:!0,error:!0,fatal:!0},sc={name:"",description:"",agentId:"",enabled:!0,scheduleKind:"every",scheduleAt:"",everyAmount:"30",everyUnit:"minutes",cronExpr:"0 7 * * *",cronTz:"",sessionTarget:"main",wakeMode:"next-heartbeat",payloadKind:"systemEvent",payloadText:"",deliver:!1,channel:"last",to:"",timeoutSeconds:"",postToMainPrefix:""};function Ti(e){return new Date(e).toLocaleString("en-US",{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function ic(e,t){const n=Ot(e),s=je(n.role);if(s==="system")return null;if(s==="tool"){const l=[];for(const c of n.content)if(c.name&&l.push(`**Tool:** ${c.name}`),c.text){const m=c.text.length>2e3?c.text.slice(0,2e3)+`
263
+ _Reply to review, approve, or ask follow-up questions._`,timestamp:Date.now(),isNotification:!0}],e.requestUpdate?.()}function si(e,t){try{_l(e,t)}catch(n){console.error("[gateway] handleGatewayEvent error:",t.event,n)}}function _l(e,t){if(we.unshift({ts:Date.now(),event:t.event,payload:t.payload}),we.length>250&&(we.length=250),e.tab==="debug"&&(e.eventLog=[...we]),t.event==="agent"){if(e.onboarding)return;const n=t.payload,s=n?.sessionKey;s&&n?.stream==="tool"&&n.data?.phase==="start"&&(e.workingSessions.has(s)||(e.workingSessions.add(s),e.requestUpdate?.())),Co(e,n);return}if(t.event==="chat"){const n=t.payload;if(n?.sessionKey){if(mi(e,n.sessionKey),n.state==="delta"){const a=j.get(n.sessionKey);a&&(clearTimeout(a),j.delete(n.sessionKey)),e.workingSessions.has(n.sessionKey)||(e.workingSessions.add(n.sessionKey),e.requestUpdate?.());const o=`safety:${n.sessionKey}`,l=j.get(o);l&&clearTimeout(l),j.set(o,setTimeout(()=>{j.delete(o),e.workingSessions.has(n.sessionKey)&&e.workingSessions.delete(n.sessionKey);const c=e;gs(n.sessionKey,c.sessionKey)&&c.chatStream!==null&&c.chatRunId===null&&(c.chatStream=null,c.chatStreamStartedAt=null),c.requestUpdate?.()},9e4))}else if((n.state==="final"||n.state==="error"||n.state==="aborted")&&e.workingSessions.has(n.sessionKey)){const a=j.get(n.sessionKey);a&&(clearTimeout(a),j.delete(n.sessionKey));const o=`safety:${n.sessionKey}`,l=j.get(o);l&&(clearTimeout(l),j.delete(o)),e.workingSessions.delete(n.sessionKey),e.requestUpdate?.()}}n.state==="final"&&wl(e,n.sessionKey);const s=Us(e,n),i=ft(n?.sessionKey);if(n&&i){const a=e,o=e.tab==="chat"&&e.sessionKey===O;if(n.state==="delta"){const l=me(n.message);if(!o){if(typeof l=="string"){const c=a.allyStream??"";(!c||l.length>=c.length)&&(a.allyStream=l)}a.allyWorking=!0,a.requestUpdate?.()}}else if(n.state==="final"){a.allyStream=null,a.allyWorking=!1,!a.allyPanelOpen&&e.tab!=="chat"&&(a.allyUnread=(a.allyUnread??0)+1);const l=e;l._loadAllyHistory().then(()=>{a.allyPanelOpen&&l._scrollAllyToBottom(),a.requestUpdate?.()})}else if(n.state==="error"||n.state==="aborted"){const l=me(n.message),c=n.state==="aborted"?"Response was stopped.":l||"Something went wrong — try again.";a.allyMessages=[...a.allyMessages??[],{role:"assistant",content:`*${c}*`,timestamp:Date.now()}],a.allyStream=null,a.allyWorking=!1,a.requestUpdate?.()}}if(n.state==="final"&&(async()=>{await Sl(e,n.sessionKey);try{await K(e,{activeMinutes:0})}catch{}})(),(s==="final"||s==="error"||s==="aborted")&&(It(e),ki(e),s==="final"&&e.compactionStatus?.active&&(e.compactionStatus={active:!1,startedAt:e.compactionStatus.startedAt??null,completedAt:Date.now()},e.showToast?.("Compaction complete","info",2e3)),(s==="error"||s==="aborted")&&e.compactionStatus?.active&&(e.compactionStatus=null),e.refreshSessionsAfterChat=!1),s==="final"){const a=!!e.compactionStatus?.completedAt;Ns(e,{allowShrink:a}).then(()=>{F(e,!0),Zs(e),e.loadSessionResources?.(),hl(e)}),e.tab==="dashboards"&&z.emit("refresh-requested",{target:"dashboards",sessionKey:n.sessionKey})}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"&&Gt(e),(t.event==="device.pair.requested"||t.event==="device.pair.resolved")&&Ue(e,{quiet:!0}),t.event==="exec.approval.requested"){const n=Jr(t.payload);if(n){e.execApprovalQueue=Zr(e.execApprovalQueue,n),e.execApprovalError=null;const s=Math.max(0,n.expiresAtMs-Date.now()+500);window.setTimeout(()=>{e.execApprovalQueue=Pn(e.execApprovalQueue,n.id)},s)}return}if(t.event==="exec.process.completed"){const n=t.payload;if(n?.sessionId){const s=n.exitSignal?`signal ${n.exitSignal}`:`exit ${n.exitCode??0}`,i=n.status==="completed"?"✓":"✗",a=n.status==="completed"?"success":"warning",o=n.sessionId.slice(0,8),l=e;typeof l.showToast=="function"&&l.showToast(`${i} Process ${o} ${n.status} (${s})`,a,5e3)}return}if(t.event==="exec.approval.resolved"){const n=Xr(t.payload);n&&(e.execApprovalQueue=Pn(e.execApprovalQueue,n.id))}if(t.event==="daily-brief:update"){z.emit("refresh-requested",{target:"today"});return}if(t.event==="ui.slot.update"){const n=t.payload;if(n?.tabId){const s=n.mode??"replace";if(n.html)s==="append"?e.dynamicSlots={...e.dynamicSlots,[n.tabId]:(e.dynamicSlots[n.tabId]??"")+n.html}:e.dynamicSlots={...e.dynamicSlots,[n.tabId]:n.html};else{const a={...e.dynamicSlots};delete a[n.tabId],e.dynamicSlots=a}e.requestUpdate?.()}return}if(t.event==="guardrails:update"){const n=e;typeof n.handleGuardrailsLoad=="function"&&n.handleGuardrailsLoad();return}if(t.event==="fathom:meeting-processed"){const n=t.payload;if(n?.title){const s=e;typeof s.showToast=="function"&&s.showToast(`Meeting processed: ${n.title}`,"success",6e3);const i=n.message??`Meeting "${n.title}" has been processed.`;s.allyMessages=[...s.allyMessages??[],{role:"assistant",content:i,timestamp:Date.now()}],!s.allyPanelOpen&&s.tab!=="chat"&&(s.allyUnread=(s.allyUnread??0)+1),s.sessionKey===O&&s.chatMessages&&(s.chatMessages=[...s.chatMessages,{role:"assistant",content:i,timestamp:Date.now()}]),s.requestUpdate?.()}return}if(t.event==="onboarding:update"){const n=t.payload;if(n){const s=e;if(typeof n.phase=="number"&&(s.onboardingPhase=n.phase),s.onboardingData=n,n.completedAt&&(s.onboardingActive=!1),n.identity?.name){const i=e;(!i.userName||!i.settings.userName)&&(i.userName=n.identity.name,i.applySettings({...i.settings,userName:n.identity.name}))}s.requestUpdate?.()}return}if(t.event==="inbox:update"){z.emit("refresh-requested",{target:"today"});return}if(t.event==="hitl:checkpoint"){const n=t.payload;if(n?.id){const s=e;s.hitlCheckpoints=[...s.hitlCheckpoints??[],n],s.requestUpdate?.();const i=e,a={role:"assistant",content:n.summary||`Agent checkpoint: ${n.agentName??"Agent"} is awaiting approval.`,timestamp:Date.now(),isNotification:!0,hitlCheckpoint:n,actions:[{label:"Review",action:"navigate",target:"today"}]};i.allyMessages=[...i.allyMessages??[],a],!i.allyPanelOpen&&e.tab!=="chat"&&(i.allyUnread=(i.allyUnread??0)+1)}z.emit("refresh-requested",{target:"today"});return}if(t.event==="queue:update"){const n=t.payload;n?.status==="processing"&&n.proofDocSlug&&e.handleOpenProofDoc?.(n.proofDocSlug).catch(()=>{}),z.emit("refresh-requested",{target:"today"});return}if(t.event==="ally:notification"){const n=t.payload;if(n){const s=e,i={role:"assistant",content:n.summary||n.message||"Notification received.",timestamp:Date.now(),isNotification:!0,actions:n.actions??[]};s.allyMessages=[...s.allyMessages??[],i],!s.allyPanelOpen&&e.tab!=="chat"&&(s.allyUnread=(s.allyUnread??0)+1);const a=["queue-complete","queue-needs-review","queue-failed","cron-result","paperclip-completion"];n.type&&a.includes(n.type)&&z.emit("refresh-requested",{target:"today"});const o=["queue-complete","queue-needs-review","paperclip-completion"];if(n.type&&o.includes(n.type)){const l=n,c=e;i.content=l.message||i.content,l.sessionKey&&c.sessionKey===l.sessionKey?Dn(c,l):l.sessionKey||Dn(c,l)}s.requestUpdate?.()}return}if(t.event==="sessions:updated"){const n=t.payload;n?.sessionKey&&n?.title&&(e.sessionsResult?.sessions&&(e.sessionsResult={...e.sessionsResult,sessions:e.sessionsResult.sessions.map(s=>s.key===n.sessionKey||s.key?.endsWith(`:${n.sessionKey?.split(":").pop()}`)||n.sessionKey?.endsWith(`:${s.key?.split(":").pop()}`)?{...s,displayName:n.title,label:n.title}:s)}),se.set(n.sessionKey,n.title),ti.add(n.sessionKey),e.requestUpdate?.());return}if(t.event==="session:auto-compact"){const n=t.payload;if(n?.sessionKey){const s=e;n.sessionKey===s.sessionKey&&!s.compactionStatus?.active&&s.connected&&(s.showToast?.("Context near limit — auto-compacting...","info",3e3),s.handleCompactChat?.())}return}}const kl=300*1e3;async function Tl(e){if(!e.client)return;const t=e;if(!(t.availableModels.length>0&&Date.now()-t.modelCacheTs<kl))try{const n=await e.client.request("godmode.config.model",{});n?.primary&&(t.currentModel=n.primary),Array.isArray(n?.available)&&(t.availableModels=n.available),t.modelCacheTs=Date.now()}catch{}}async function Al(e,t){if(!e.client)return;const n=e;try{await e.client.request("godmode.config.model.set",{primary:t}),n.currentModel=t,n.modelPickerOpen=!1,e.modelCacheTs=0}catch(s){console.error("[model-switch]",s)}}async function $l(e){if(typeof window>"u")return;const t=new URLSearchParams(window.location.search),n=t.get("openTask");if(!n||!e.client)return;t.delete("openTask");const s=t.toString()?`${window.location.pathname}?${t.toString()}`:window.location.pathname;window.history.replaceState({},"",s);try{const i=await e.client.request("tasks.openSession",{taskId:n});if(i?.sessionKey){e.sessionKey=i.sessionKey,e.tab="chat";const{loadChatHistory:a}=await _(async()=>{const{loadChatHistory:o}=await Promise.resolve().then(()=>fe);return{loadChatHistory:o}},void 0,import.meta.url);await a(e,i.sessionKey)}}catch(i){console.error("[GodMode] Failed to open task session:",i)}}async function ii(e){if(!e.client)return;const t=e;t.secretsLoading=!0;try{const n=await e.client.request("godmode.secrets.list",{});t.secrets=n?.keys??[]}catch{t.secrets=[]}finally{t.secretsLoading=!1}}async function ai(e,t){if(!e.client)return;const n=e;try{await e.client.request("godmode.config.webfetch.set",{provider:t}),n.webFetchProvider=t}catch(s){console.error("[webfetch-set]",s)}}async function oi(e,t){if(!e.client)return;const n=e;try{await e.client.request("godmode.config.search.set",{defaultProvider:t}),n.searchProvider=t}catch(s){console.error("[search-set]",s)}}function ri(e,t){const n=t.snapshot;n?.presence&&Array.isArray(n.presence)&&(e.presenceEntries=n.presence),n?.health&&(e.debugHealth=n.health),n?.sessionDefaults&&gl(e,n.sessionDefaults)}async function li(e){if(e.client)try{const n=(await e.client.request("customTabs.list",{}))?.tabs??[];for(const s of Pa())La(s);for(const s of n)Ma(s.slug);e.customTabs=n}catch{e.customTabs=[]}}async function ci(e,t){if(!e.client)return;e.customTabLoading=!0,e.customTabErrors={};const n={},s={};for(const i of t.dataSources)try{if(i.type==="static")n[i.id]=i.data;else if(i.type==="rpc"&&i.method){const a=await e.client.request(i.method,i.params??{});n[i.id]=a}}catch(a){s[i.id]=a instanceof Error?a.message:String(a)}e.customTabData=n,e.customTabErrors=s,e.customTabLoading=!1}const di=Object.freeze(Object.defineProperty({__proto__:null,applySnapshot:ri,connectGateway:ze,fetchCustomTabData:ci,getEventLogSnapshot:ei,getResolvedImageUrl:Xs,handleGatewayEvent:si,loadCustomTabs:li,loadSecrets:ii,resetAutoTitleState:ni,setSearchProvider:oi,setWebFetchProvider:ai,switchModelFromChat:Al,triggerImageResolve:_e},Symbol.toStringTag,{value:"Module"}));function Ft(e){e.nodesPollInterval==null&&(e.nodesPollInterval=window.setInterval(()=>{Fe(e,{quiet:!0})},5e3))}function Ut(e){e.nodesPollInterval!=null&&(clearInterval(e.nodesPollInterval),e.nodesPollInterval=null)}function Wt(e){e.logsPollInterval==null&&(e.logsPollInterval=window.setInterval(()=>{e.tab==="logs"&&xt(e,{quiet:!0})},2e3))}function qt(e){e.logsPollInterval!=null&&(clearInterval(e.logsPollInterval),e.logsPollInterval=null)}function Bt(e){e.debugPollInterval==null&&(e.debugPollInterval=window.setInterval(()=>{e.tab==="debug"&&We(e)},3e3))}function jt(e){e.debugPollInterval!=null&&(clearInterval(e.debugPollInterval),e.debugPollInterval=null)}function Ve(e,t=Date.now()){if(typeof e=="number"&&Number.isFinite(e))return new Date(e);if(typeof e=="string"){const n=Date.parse(e);if(Number.isFinite(n))return new Date(n)}return new Date(t)}function Ht(e){return{id:e.id,name:e.name,emoji:e.emoji||"📁",type:e.type,path:e.path,artifactCount:e.artifactCount??0,sessionCount:e.sessionCount??0,connectionCount:e.connectionCount??0,feedCount:e.feedCount??0,lastUpdated:Ve(e.lastUpdated,e.lastScanned)}}function it(e){return{path:e.path,name:e.name,type:e.type,size:e.size,modified:Ve(e.modified),isDirectory:e.isDirectory,searchText:e.searchText}}function On(e){return{id:e.id,key:e.key,title:e.title,created:Ve(e.created),status:e.status,workspaceSubfolder:e.workspaceSubfolder}}function Te(e){return{id:e.id,title:e.title,status:e.status,project:e.project,dueDate:e.dueDate,priority:e.priority,createdAt:e.createdAt,completedAt:e.completedAt}}function ui(e){return e.map(t=>({name:t.name,path:t.path,type:t.type,fileType:t.fileType,size:t.size,modified:t.modified?Ve(t.modified):void 0,children:t.children?ui(t.children):void 0}))}function Cl(e,t){return{...t,id:e.id,name:e.name,emoji:e.emoji,type:e.type,path:e.path,artifactCount:e.artifactCount,sessionCount:e.sessionCount,lastUpdated:e.lastUpdated}}async function xl(e){if(!e.client||!e.connected){e.workspaces?.length||(e.workspaces=[],e.workspacesError="Connect to gateway to see workspaces"),e.workspacesLoading=!1;return}e.workspacesLoading=!0,e.workspacesError=null;try{const t=await e.client.request("workspaces.list",{});if(e.workspaces=(t.workspaces??[]).map(Ht),e.selectedWorkspace){const n=e.workspaces.find(s=>s.id===e.selectedWorkspace?.id);n&&(e.selectedWorkspace=Cl(n,e.selectedWorkspace))}}catch(t){console.error("[Workspaces] load failed:",t),e.workspacesError=t instanceof Error?t.message:"Failed to load workspaces",e.workspaces?.length||(e.workspaces=[])}finally{e.workspacesLoading=!1}}async function zt(e,t){if(!e.client||!e.connected)return null;try{const n=await e.client.request("workspaces.get",{id:t});if(!n.workspace)return null;const s={...Ht(n.workspace),pinned:(n.pinned??[]).map(it),pinnedSessions:(n.pinnedSessions??[]).map(On),outputs:(n.outputs??[]).map(it),folderTree:n.folderTree?ui(n.folderTree):void 0,sessions:(n.sessions??[]).map(On),tasks:(n.tasks??[]).map(Te),memory:(n.memory??[]).map(it)};try{const[i,a]=await Promise.all([Ll(e,t).catch(()=>[]),Ml(e,t).catch(()=>[])]);s.feedEntries=i,s.connections=a,s.feedCount=i.length,s.connectionCount=a.length}catch{}return s}catch(n){return console.error("[Workspaces] get failed:",n),null}}async function ku(e,t,n){if(!e.client||!e.connected)return null;try{const s=await e.client.request("workspaces.readFile",n?{workspaceId:n,filePath:t}:{path:t});return s.content?{content:s.content,mime:s.contentType??s.mime??"text/plain"}:(s.error&&console.warn("[Workspaces] readFile failed:",s.error),null)}catch(s){return console.error("[Workspaces] readFile error:",s),null}}async function Tu(e,t){if(!t){e.selectedWorkspace=null;return}const n=await zt(e,t.id);e.selectedWorkspace=n||{...t,pinned:[],pinnedSessions:[],outputs:[],sessions:[],tasks:[]}}async function Au(e,t,n,s){if(!e.client||!e.connected)return!1;try{if(await e.client.request(s?"workspaces.unpin":"workspaces.pin",{workspaceId:t,filePath:n}),e.selectedWorkspace?.id===t){const i=await zt(e,t);i&&(e.selectedWorkspace=i)}return!0}catch(i){return console.error("[Workspaces] pin toggle failed:",i),!1}}async function $u(e,t,n,s){if(!e.client||!e.connected)return!1;try{if(await e.client.request(s?"workspaces.unpinSession":"workspaces.pinSession",{workspaceId:t,sessionKey:n}),e.selectedWorkspace?.id===t){const i=await zt(e,t);i&&(e.selectedWorkspace=i)}return!0}catch(i){return console.error("[Workspaces] session pin toggle failed:",i),!1}}async function Cu(e,t){if(!e.client||!e.connected)return null;const n=String(t.name??"").trim();if(!n)return e.workspacesError="Workspace name is required",null;const s=t.type??"project",i=String(t.path??"").trim();try{const a=await e.client.request("workspaces.create",{name:n,type:s,...i?{path:i}:{}});if(!a.workspace)return e.workspacesError="Workspace creation returned no workspace",null;const o=Ht(a.workspace),l=e.workspaces??[],c=new Map(l.map(m=>[m.id,m]));return c.set(o.id,o),e.workspaces=Array.from(c.values()).toSorted((m,r)=>r.lastUpdated.getTime()-m.lastUpdated.getTime()),e.workspacesError=null,o}catch(a){return console.error("[Workspaces] create failed:",a),e.workspacesError=a instanceof Error?a.message:"Failed to create workspace",null}}async function xu(e,t){if(!e.client||!e.connected)return!1;try{return await e.client.request("workspaces.delete",{id:t}),e.workspaces=(e.workspaces??[]).filter(n=>n.id!==t),e.selectedWorkspace?.id===t&&(e.selectedWorkspace=null),e.workspacesError=null,!0}catch(n){return console.error("[Workspaces] delete failed:",n),e.workspacesError=n instanceof Error?n.message:"Failed to delete workspace",!1}}function Pu(e,t){const n=new Set(e);return n.has(t)?n.delete(t):n.add(t),n}const Pl={coding:"Builder",research:"Researcher",analysis:"Analyst",creative:"Creative",review:"Reviewer",ops:"Ops",task:"Agent",url:"Reader",idea:"Explorer"};async function Lu(e){if(!e.client||!e.connected)return[];try{const[t,n]=await Promise.all([e.client.request("tasks.list",{}),e.client.request("queue.list",{limit:100}).catch(()=>({items:[]}))]),s=new Map;for(const i of n.items)i.sourceTaskId&&(i.status==="processing"||i.status==="review"||i.status==="needs-review"||i.status==="failed")&&s.set(i.sourceTaskId,{status:i.status==="needs-review"?"review":i.status,type:i.type,roleName:Pl[i.type]??i.type,queueItemId:i.id});return(t.tasks??[]).map(i=>({...Te(i),queueStatus:s.get(i.id)??null}))}catch(t){return console.error("[Workspaces] loadAllTasksWithQueueStatus failed:",t),[]}}async function Mu(e,t,n){if(!e.client||!e.connected)return null;const s=n==="complete"?"pending":"complete";try{const i=await e.client.request("tasks.update",{id:t,status:s});return Te(i)}catch(i){return console.error("[Workspaces] toggleTaskComplete failed:",i),null}}async function Iu(e,t,n){if(!e.client||!e.connected)return null;try{const s=await e.client.request("tasks.update",{id:t,...n});return Te(s)}catch(s){return console.error("[Workspaces] updateTask failed:",s),null}}async function Ru(e,t){if(!e.client||!e.connected)return null;try{return await e.client.request("tasks.openSession",{taskId:t})}catch(n){return console.error("[Workspaces] startTask failed:",n),null}}async function Eu(e,t,n){if(!e.client||!e.connected)return null;try{const s=await e.client.request("tasks.create",{title:t,project:n,source:"chat"});return Te(s)}catch(s){return console.error("[Workspaces] createTask failed:",s),null}}async function Du(e,t,n){if(!e.client||!e.connected)return null;try{return await e.client.request("workspaces.browseFolder",{workspaceId:t,folderPath:n})}catch(s){return console.error("[Workspaces] browseFolder failed:",s),null}}async function Ou(e,t,n,s=50){if(!e.client||!e.connected)return[];try{return(await e.client.request("workspaces.search",{workspaceId:t,query:n,limit:s})).results??[]}catch(i){return console.error("[Workspaces] search failed:",i),[]}}async function Ku(e,t,n){if(!e.client||!e.connected)return!1;try{return await e.client.request("workspaces.createFolder",{workspaceId:t,folderPath:n}),!0}catch(s){return console.error("[Workspaces] createFolder failed:",s),!1}}async function Ll(e,t,n=50,s){if(!e.client||!e.connected)return[];try{return(await e.client.request("workspace.feed.read",{workspaceId:t,limit:n,before:s})).entries??[]}catch(i){return console.error("[Workspaces] loadFeed failed:",i),[]}}async function Nu(e,t,n,s="update"){if(!e.client||!e.connected)return null;try{return(await e.client.request("workspace.feed.post",{workspaceId:t,text:n,type:s,author:"user"})).entry??null}catch(i){return console.error("[Workspaces] postToFeed failed:",i),null}}async function Ml(e,t){if(!e.client||!e.connected)return[];try{return(await e.client.request("workspace.connections.list",{workspaceId:t})).connections??[]}catch(n){return console.error("[Workspaces] loadConnections failed:",n),[]}}async function Fu(e,t,n){if(!e.client||!e.connected)return{ok:!1,error:"Not connected"};try{return await e.client.request("workspace.connections.test",{workspaceId:t,connectionId:n})}catch(s){return console.error("[Workspaces] testConnection failed:",s),{ok:!1,error:s instanceof Error?s.message:"Failed"}}}async function Uu(e,t,n){if(!e.client||!e.connected)return!1;try{return await e.client.request("workspace.connections.remove",{workspaceId:t,connectionId:n}),!0}catch(s){return console.error("[Workspaces] removeConnection failed:",s),!1}}const pi="godmode.ui.settings.v1";function Il(){const e=new URLSearchParams(location.search),t=(()=>{const i=e.get("gatewayUrl");return i||(typeof window.__GODMODE_DEV__<"u"?"/ws":`${location.protocol==="https:"?"wss:":"ws:"}//${location.host}`)})(),n=e.get("token")||"",s={gatewayUrl:t,token:n,sessionKey:"main",lastActiveSessionKey:"main",theme:"system",chatFocusMode:!1,chatShowThinking:!0,splitRatio:.6,navCollapsed:!1,navGroupsCollapsed:{System:!0,__missionControl__:!1},openTabs:[],tabLastViewed:{},userName:"",userAvatar:"",chatParallelView:!1,parallelLanes:[null,null,null,null]};try{const i=localStorage.getItem(pi);if(!i)return s;const a=JSON.parse(i);return{gatewayUrl:e.get("gatewayUrl")||(typeof window.__GODMODE_DEV__<"u"?"/ws":typeof a.gatewayUrl=="string"&&a.gatewayUrl.trim()?a.gatewayUrl.trim():s.gatewayUrl),token:n||(typeof a.token=="string"?a.token:""),sessionKey:typeof a.sessionKey=="string"&&a.sessionKey.trim()?a.sessionKey.trim():s.sessionKey,lastActiveSessionKey:typeof a.lastActiveSessionKey=="string"&&a.lastActiveSessionKey.trim()?a.lastActiveSessionKey.trim():typeof a.sessionKey=="string"&&a.sessionKey.trim()||s.lastActiveSessionKey,theme:a.theme==="light"||a.theme==="dark"||a.theme==="system"||a.theme==="lifetrack"?a.theme:s.theme,chatFocusMode:typeof a.chatFocusMode=="boolean"?a.chatFocusMode:s.chatFocusMode,chatShowThinking:typeof a.chatShowThinking=="boolean"?a.chatShowThinking:s.chatShowThinking,splitRatio:typeof a.splitRatio=="number"&&a.splitRatio>=.4&&a.splitRatio<=.7?a.splitRatio:s.splitRatio,navCollapsed:typeof a.navCollapsed=="boolean"?a.navCollapsed:s.navCollapsed,navGroupsCollapsed:typeof a.navGroupsCollapsed=="object"&&a.navGroupsCollapsed!==null?a.navGroupsCollapsed:s.navGroupsCollapsed,openTabs:Array.isArray(a.openTabs)&&a.openTabs.every(o=>typeof o=="string")?a.openTabs:s.openTabs,tabLastViewed:typeof a.tabLastViewed=="object"&&a.tabLastViewed!==null?a.tabLastViewed:s.tabLastViewed,userName:typeof a.userName=="string"?a.userName.trim().slice(0,50):s.userName,userAvatar:typeof a.userAvatar=="string"?a.userAvatar.trim():s.userAvatar,chatParallelView:typeof a.chatParallelView=="boolean"?a.chatParallelView:s.chatParallelView,parallelLanes:Array.isArray(a.parallelLanes)&&a.parallelLanes.length===4?a.parallelLanes.map(o=>typeof o=="string"?o:null):s.parallelLanes}}catch{return s}}function Rl(e){localStorage.setItem(pi,JSON.stringify(e))}const El=56,Dl="quantum-particles",Ol="quantum-particle";let J=null,Se=null;function q(e,t){return Math.random()*(t-e)+e}function hi(){if(fi(),typeof document>"u")return;const e=document.querySelector(".shell");if(!e){Se=requestAnimationFrame(()=>{Se=null,hi()});return}J=document.createElement("div"),J.className=Dl,Object.assign(J.style,{position:"fixed",inset:"0",pointerEvents:"none",zIndex:"1",overflow:"hidden"});for(let t=0;t<El;t++){const n=document.createElement("div");n.className=Ol;const s=q(2,5),i=q(.3,.65),a=q(15,35),o=q(0,12),l=q(5,95),c=q(5,95),m=q(-150,150),r=q(-200,200),p=q(-250,250),g=q(-350,350),y=q(.8,1.5);Object.assign(n.style,{position:"absolute",left:`${l}%`,top:`${c}%`,width:`${s}px`,height:`${s}px`,borderRadius:"50%",background:`rgba(235, 158, 15, ${q(.7,1)})`,boxShadow:`0 0 ${s*3}px rgba(235, 158, 15, ${i*.7})`,opacity:"0",willChange:"transform, opacity",animation:`quantum-float ${a}s ${o}s ease-in-out infinite`}),n.style.setProperty("--particle-opacity",String(i)),n.style.setProperty("--drift-x",`${m}px`),n.style.setProperty("--drift-y",`${r}px`),n.style.setProperty("--drift-end-x",`${p}px`),n.style.setProperty("--drift-end-y",`${g}px`),n.style.setProperty("--particle-scale-mid",String(y)),J.appendChild(n)}e.prepend(J)}function fi(){Se!==null&&(cancelAnimationFrame(Se),Se=null),J&&(J.remove(),J=null)}function Kl(){return typeof window>"u"||typeof window.matchMedia!="function"||window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"lifetrack"}function Vt(e){return e==="system"?Kl():e==="light"?"lifetrack":e}const Le=e=>Number.isNaN(e)?.5:e<=0?0:e>=1?1:e,Nl=()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches??!1,ve=e=>{e.classList.remove("theme-transition"),e.style.removeProperty("--theme-switch-x"),e.style.removeProperty("--theme-switch-y")},Fl=({nextTheme:e,applyTheme:t,context:n,currentTheme:s})=>{if(s===e)return;const i=globalThis.document??null;if(!i){t();return}const a=i.documentElement,o=i,l=Nl();if(!!o.startViewTransition&&!l){let m=.5,r=.5;if(n?.pointerClientX!==void 0&&n?.pointerClientY!==void 0&&typeof window<"u")m=Le(n.pointerClientX/window.innerWidth),r=Le(n.pointerClientY/window.innerHeight);else if(n?.element){const g=n.element.getBoundingClientRect();g.width>0&&g.height>0&&typeof window<"u"&&(m=Le((g.left+g.width/2)/window.innerWidth),r=Le((g.top+g.height/2)/window.innerHeight))}a.style.setProperty("--theme-switch-x",`${m*100}%`),a.style.setProperty("--theme-switch-y",`${r*100}%`),a.classList.add("theme-transition");const p=setTimeout(()=>{ve(a)},1e3);try{const g=o.startViewTransition?.(()=>{t()});g?.finished?g.finished.finally(()=>{clearTimeout(p),ve(a)}):(clearTimeout(p),ve(a))}catch{clearTimeout(p),ve(a),t()}return}t(),ve(a)};function Ul(e,t){const n=Array.isArray(e)?[...new Set(e.map(s=>s.trim()).filter(s=>s.length>0))]:[];if(n.length===0&&t){const s=t.toLowerCase();s==="main"||s==="agent:main:main"||s.endsWith(":main")||n.push(t)}return n}function Wl(e){const t={};if(!e||typeof e!="object")return t;for(const[n,s]of Object.entries(e)){const i=n.trim();!i||typeof s!="number"||!Number.isFinite(s)||(t[i]=Math.max(t[i]??0,s))}return t}function te(e,t){const n=t.sessionKey.trim()||"main",s=Ul(t.openTabs,n),i=Wl(t.tabLastViewed),a={...t,sessionKey:n,openTabs:s,tabLastViewed:i,lastActiveSessionKey:t.lastActiveSessionKey?.trim()||n};e.settings=a,Rl(a),a.theme!==e.theme&&(e.theme=a.theme,Qe(e,Vt(a.theme))),e.applySessionKey=e.settings.lastActiveSessionKey}function mi(e,t){const n=t.trim();n&&e.settings.lastActiveSessionKey!==n&&te(e,{...e.settings,lastActiveSessionKey:n})}function ql(e){if(!window.location.search)return;const t=new URLSearchParams(window.location.search),n=t.get("token"),s=t.get("password"),i=t.get("session"),a=t.get("gatewayUrl");let o=!1;if(n!=null){const c=n.trim();c&&c!==e.settings.token&&te(e,{...e.settings,token:c}),t.delete("token"),o=!0}if(s!=null){const c=s.trim();c&&(e.password=c),t.delete("password"),o=!0}if(i!=null){const c=i.trim();if(c){e.sessionKey=c;const m=c.toLowerCase(),p=m==="main"||m==="agent:main:main"||m.endsWith(":main")||e.settings.openTabs.includes(c)?e.settings.openTabs:[...e.settings.openTabs,c];te(e,{...e.settings,sessionKey:c,lastActiveSessionKey:c,openTabs:p})}}if(a!=null){const c=a.trim();c&&c!==e.settings.gatewayUrl&&(e.pendingGatewayUrl=c),t.delete("gatewayUrl"),o=!0}if(!o)return;const l=new URL(window.location.href);l.search=t.toString(),window.history.replaceState({},"",l.toString())}function Bl(e,t){const n=e.tab;if(n!==t&&(e.tab=t),n==="chat"&&t!=="chat"&&e.sessionKey===O&&e._loadAllyHistory?.(),n==="dashboards"&&t!=="dashboards"){const s=e;if(s.dashboardPreviousSessionKey&&s.activeDashboardId){const i=s.dashboardPreviousSessionKey;s.dashboardPreviousSessionKey=null,s.activeDashboardId=null,s.activeDashboardManifest=null,s.activeDashboardHtml=null,s.dashboardChatOpen=!1,e.sessionKey=i}}t==="chat"&&(e.chatHasAutoScrolled=!1),t==="nodes"?Ft(e):Ut(e),t==="logs"?Wt(e):qt(e),t==="debug"?Bt(e):jt(e),Ge(e),yi(e,t,!1)}function jl(e,t,n){Fl({nextTheme:t,applyTheme:()=>{e.theme=t,te(e,{...e.settings,theme:t}),Qe(e,Vt(t))},context:n,currentTheme:e.theme})}async function Ge(e){if(e.tab==="overview"&&await vi(e),(e.tab==="today"||e.tab==="my-day")&&z.emit("refresh-requested",{target:"today"}),e.tab==="workspaces"&&await xl(e),e.tab==="channels"&&await Yl(e),e.tab==="instances"&&await Pt(e),e.tab==="sessions"&&(await K(e),await ut(e)),e.tab==="cron"&&await Gt(e),e.tab==="skills"&&(await is(e),await pt(e)),e.tab==="agents"){const{loadRoster:t}=await _(async()=>{const{loadRoster:n}=await import("./ctrl-settings-COfcdhha.js").then(s=>s.ac);return{loadRoster:n}},[],import.meta.url);await t(e)}if(e.tab==="nodes"&&(await Fe(e),await Ue(e),await oe(e),await as(e)),e.tab==="chat"&&(await Jt(e),F(e,!e.chatHasAutoScrolled),e.loadSessionResources?.()),e.tab==="trust"){const t=e,n=[];typeof t.handleTrustLoad=="function"&&n.push(t.handleTrustLoad()),n.push(Yi(t)),n.push(K(t)),await Promise.all(n)}if(e.tab==="guardrails"){const t=e;typeof t.handleGuardrailsLoad=="function"&&await t.handleGuardrailsLoad()}if(e.tab==="setup"){const t=e;typeof t.handleLoadCapabilities=="function"&&t.handleLoadCapabilities()}if(e.tab==="dashboards"){const t=e;typeof t.handleDashboardsRefresh=="function"&&await t.handleDashboardsRefresh()}if(e.tab==="memory"||e.tab==="second-brain"){const t=e;typeof t.handleSecondBrainRefresh=="function"&&await t.handleSecondBrainRefresh()}if(e.tab==="config"&&(await os(e),await oe(e)),e.tab==="debug"&&(await We(e),e.eventLog=ei()),e.tab==="logs"&&(e.logsAtBottom=!0,await xt(e,{reset:!0}),Mt(e,!0)),us(e.tab)){const t=e,n=(t.customTabs??[]).find(s=>s.slug===e.tab);if(n){const{fetchCustomTabData:s}=await _(async()=>{const{fetchCustomTabData:i}=await Promise.resolve().then(()=>di);return{fetchCustomTabData:i}},void 0,import.meta.url);await s(t,n)}}}function Hl(){if(typeof window>"u")return"";const e=window.__OPENCLAW_CONTROL_UI_BASE_PATH__;return typeof e=="string"&&e.trim()?ds(e):Ia(window.location.pathname)}function zl(e){e.theme=e.settings.theme??"system",Qe(e,Vt(e.theme))}function Qe(e,t){if(e.themeResolved=t,typeof document>"u")return;const n=document.documentElement;n.dataset.theme=t,n.style.colorScheme=t==="dark"?"dark":"light",t==="lifetrack"?hi():fi()}function Vl(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"&&Qe(e,n.matches?"dark":"lifetrack")},typeof e.themeMedia.addEventListener=="function"){e.themeMedia.addEventListener("change",e.themeMediaHandler);return}e.themeMedia.addListener(e.themeMediaHandler)}function Gl(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 Kn(e,t){if(typeof window>"u")return;const n=cs(window.location.pathname,e.basePath)??"chat";gi(e,n),yi(e,n,t)}function Ql(e){if(typeof window>"u")return;const t=cs(window.location.pathname,e.basePath);if(!t)return;const s=new URL(window.location.href).searchParams.get("session")?.trim();if(s){e.sessionKey=s;const i=e.settings.openTabs.includes(s)?e.settings.openTabs:[...e.settings.openTabs,s];te(e,{...e.settings,sessionKey:s,lastActiveSessionKey:s,openTabs:i})}gi(e,t)}function gi(e,t){e.tab!==t&&(e.tab=t),t==="chat"&&(e.chatHasAutoScrolled=!1),t==="nodes"?Ft(e):Ut(e),t==="logs"?Wt(e):qt(e),t==="debug"?Bt(e):jt(e),e.connected&&Ge(e)}function yi(e,t,n){if(typeof window>"u")return;const s=ln(Lt(t,e.basePath)),i=ln(window.location.pathname),a=new URL(window.location.href);t==="chat"&&e.sessionKey?a.searchParams.set("session",e.sessionKey):a.searchParams.delete("session"),i!==s&&(a.pathname=s),n?window.history.replaceState({},"",a.toString()):window.history.pushState({},"",a.toString())}function V(e,t,n){if(typeof window>"u")return;const s=new URL(window.location.href);s.searchParams.set("session",t),window.history.replaceState({},"",s.toString())}async function vi(e){await Promise.all([H(e,!1),Pt(e),K(e),ss(e),We(e)])}async function Yl(e){await Promise.all([H(e,!0),os(e),oe(e)])}async function Gt(e){await Promise.all([H(e,!1),ss(e),Qi(e)])}function Ke(e){return e.chatSending||!!e.chatRunId}function ee(e,t){const n=t??e.sessionKey,s=e.chatMessage.trim();if(s)e.chatDrafts={...e.chatDrafts,[n]:s};else{const{[n]:i,...a}=e.chatDrafts;e.chatDrafts=a}}function ie(e,t){const n=t??e.sessionKey;e.chatMessage=e.chatDrafts[n]??""}function bi(e,t){const n=e.sessionKey,{[n]:s,...i}=e.chatDrafts;e.chatDrafts=i,n===e.sessionKey&&(e.chatMessage="")}function wi(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 Jl(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 Qt(e){e.connected&&(e.chatMessage="",await Nt(e))}function Xl(e,t,n){const s=t.trim(),i=!!(n&&n.length>0);if(!s&&!i)return;const a=Date.now();e.chatQueue=[...e.chatQueue,{id:He(),text:s,createdAt:a,attachments:i?n?.map(l=>({...l})):void 0}];const o=[];if(s&&o.push({type:"text",text:s}),i&&n)for(const l of n)o.push({type:"image",source:{type:"base64",media_type:l.mimeType,data:l.dataUrl}});e.chatMessages=[...e.chatMessages,{role:"user",content:o,timestamp:a}],F(e,!0)}async function Tt(e,t,n){It(e);const s=e;s.sessionKey&&s.workingSessions&&(s.workingSessions=new Set([...s.workingSessions,s.sessionKey])),n?.skipOptimisticUpdate||queueMicrotask(()=>{F(e,!0)});const i=await Fs(e,t,n?.attachments,{skipOptimisticUpdate:n?.skipOptimisticUpdate});return!i&&n?.previousDraft!=null&&(e.chatMessage=n.previousDraft),!i&&n?.previousAttachments&&(e.chatAttachments=n.previousAttachments),i&&(mi(e,e.sessionKey),e.chatAttachments=[]),i&&n?.restoreDraft&&n.previousDraft?.trim()&&(e.chatMessage=n.previousDraft),i&&n?.restoreAttachments&&n.previousAttachments?.length&&(e.chatAttachments=n.previousAttachments),F(e,!0),i&&!e.chatRunId&&Yt(e),i&&n?.refreshSessions&&(e.refreshSessionsAfterChat=!0),i}async function Yt(e){if(!e.connected||Ke(e))return;const[t,...n]=e.chatQueue;if(!t)return;e.chatQueue=n,await Tt(e,t.text,{attachments:t.attachments,skipOptimisticUpdate:!0})||(e.chatQueue=[t,...e.chatQueue])}function Si(e,t){e.chatQueue=e.chatQueue.filter(n=>n.id!==t)}async function _i(e,t,n){if(!e.connected)return;const s=e.chatMessage,i=(t??e.chatMessage).trim(),a=e.chatAttachments??[],o=t==null?a:[],l=o.length>0;if(!i&&!l)return;if(wi(i)){await Qt(e);return}const c=Jl(i);if(t==null&&(e.chatMessage="",bi(e)),n?.queue){Xl(e,i,o),Ke(e)||await Yt(e);return}if(Ke(e)){await Nt(e),await new Promise(m=>setTimeout(m,50)),await Tt(e,i,{attachments:l?o:void 0,refreshSessions:c});return}await Tt(e,i,{previousDraft:t==null?s:void 0,restoreDraft:!!(t&&n?.restoreDraft),attachments:l?o:void 0,previousAttachments:t==null?a:void 0,restoreAttachments:!!(t&&n?.restoreDraft),refreshSessions:c})}async function Jt(e){await Promise.all([N(e),K(e,{activeMinutes:0}),Ne(e)]),F(e,!0)}const ki=Yt;function Zl(e){const t=ms(e.sessionKey);return t?.agentId?t.agentId:e.hello?.snapshot?.sessionDefaults?.defaultAgentId?.trim()||"main"}function ec(e,t){const n=ds(e),s=encodeURIComponent(t);return n?`${n}/avatar/${s}?meta=1`:`/avatar/${s}?meta=1`}async function Ne(e){if(!e.connected){e.chatAvatarUrl=null;return}const t=Zl(e);if(!t){e.chatAvatarUrl=null;return}e.chatAvatarUrl=null;const n=ec(e.basePath,t);try{const s=await fetch(n,{method:"GET"});if(!s.ok){e.chatAvatarUrl=null;return}const i=await s.json(),a=typeof i.avatarUrl=="string"?i.avatarUrl.trim():"";e.chatAvatarUrl=a||null}catch{e.chatAvatarUrl=null}}const tc=Object.freeze(Object.defineProperty({__proto__:null,clearDraft:bi,flushChatQueueForEvent:ki,handleAbortChat:Qt,handleSendChat:_i,isChatBusy:Ke,isChatStopCommand:wi,refreshChat:Jt,refreshChatAvatar:Ne,removeQueuedMessage:Si,restoreDraft:ie,saveDraft:ee},Symbol.toStringTag,{value:"Module"})),nc={trace:!0,debug:!0,info:!0,warn:!0,error:!0,fatal:!0},sc={name:"",description:"",agentId:"",enabled:!0,scheduleKind:"every",scheduleAt:"",everyAmount:"30",everyUnit:"minutes",cronExpr:"0 7 * * *",cronTz:"",sessionTarget:"main",wakeMode:"next-heartbeat",payloadKind:"systemEvent",payloadText:"",deliver:!1,channel:"last",to:"",timeoutSeconds:"",postToMainPrefix:""};function Ti(e){return new Date(e).toLocaleString("en-US",{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function ic(e,t){const n=Ot(e),s=je(n.role);if(s==="system")return null;if(s==="tool"){const l=[];for(const c of n.content)if(c.name&&l.push(`**Tool:** ${c.name}`),c.text){const m=c.text.length>2e3?c.text.slice(0,2e3)+`
264
264
 
265
265
  ... (truncated)`:c.text;l.push(m)}return l.length===0?null:`<details>
266
266
  <summary>Tool result</summary>
@@ -781,12 +781,12 @@ Deletes the session entry and archives its transcript.`)&&(e.sessionsResult?.ses
781
781
  <div class="callout">
782
782
  PDF preview unavailable. Use "Open in Browser" to view.
783
783
  </div>
784
- `;if(t==="text/html"||t==="application/xhtml+xml"){const i=new Blob([n],{type:"text/html"}),a=URL.createObjectURL(i);return d`<iframe
784
+ `;if(t==="text/html"||t==="application/xhtml+xml")return d`<iframe
785
785
  class="sidebar-html-frame"
786
- src=${a}
786
+ .srcdoc=${n}
787
787
  sandbox="allow-same-origin allow-top-navigation-by-user-activation allow-popups"
788
- @load=${o=>{URL.revokeObjectURL(a);const l=o.target;try{const c=l.contentDocument?.documentElement?.scrollHeight;c&&(l.style.height=`${c}px`)}catch{}}}
789
- ></iframe>`}if(t==="text/markdown"||t==="text/x-markdown"){const i=Ea(n);return d`<div
788
+ @load=${i=>{const a=i.target;try{const o=a.contentDocument?.documentElement?.scrollHeight;o&&(a.style.height=`${o}px`)}catch{}}}
789
+ ></iframe>`;if(t==="text/markdown"||t==="text/x-markdown"){const i=Ea(n);return d`<div
790
790
  class="sidebar-markdown"
791
791
  @click=${a=>Uc(a,e.onOpenFile)}
792
792
  >${re(B(i))}</div>`}return d`<pre class="sidebar-plain">${n}</pre>`}function qc(e){const t=xi(e);return t==="text/html"||t==="application/xhtml+xml"}function Bc(e){const t=new Blob([e],{type:"text/html"}),n=URL.createObjectURL(t);window.open(n,"_blank","noopener,noreferrer")}function $t(e){const t=e.title?.trim()||"Tool Output",n=qc(e)&&e.content;return d`
@@ -1172,7 +1172,7 @@ Deletes the session entry and archives its transcript.`)&&(e.sessionsResult?.ses
1172
1172
  `})}
1173
1173
  </div>
1174
1174
  `}function Ld(e){return e.button===0&&!e.metaKey&&!e.ctrlKey&&!e.shiftKey&&!e.altKey}function Md(e){const t=e.href;if(t){if(e.target==="_blank"){window.open(t,"_blank","noopener,noreferrer");return}window.location.assign(t)}}function Id(e){const t=e.trim();return!t||t.includes(`
1175
- `)?null:t.startsWith("/")||t.startsWith("~/")||t.startsWith("./")||t.startsWith("../")||/^[a-z]:[\\/]/i.test(t)||/^[^:\s]+\/[^\s]+$/.test(t)&&/\.[a-z0-9]{1,12}$/i.test(t)||/^[^\s/\\:*?"<>|]+\.[a-z0-9]{1,12}$/i.test(t)&&t.length<=100?t:null}async function Rd(e,t){const n=e.target,s=n instanceof Element?n:n instanceof Node?n.parentElement:null;if(!s||!t.onMessageLinkClick||!Ld(e))return;const i=s.closest("a");if(i instanceof HTMLAnchorElement){if(i.hasAttribute("download"))return;const c=i.getAttribute("href");if(!c)return;if(t.onOpenProof)try{const r=c.match(/(?:proofeditor\.ai|127\.0\.0\.1:\d+|localhost:\d+)\/d\/([a-zA-Z0-9_-]+)/);if(r){e.preventDefault(),t.onOpenProof(r[1]);return}}catch{}try{const r=new URL(c,window.location.href);if(/^https?:$/.test(r.protocol)&&r.origin!==window.location.origin){e.preventDefault(),window.open(r.href,"_blank","noopener,noreferrer");return}}catch{}e.preventDefault(),e.stopPropagation(),await t.onMessageLinkClick(c)||Md(i);return}const a=s.closest("code");if(!(a instanceof HTMLElement))return;const o=(a.textContent??"").trim();if(/^https?:\/\/\S+$/i.test(o)){e.preventDefault(),window.open(o,"_blank","noopener,noreferrer");return}if(/^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*\.[a-z]{2,}(\/\S*)?$/i.test(o)){e.preventDefault(),window.open(`https://${o}`,"_blank","noopener,noreferrer");return}const l=Id(o);l&&(e.preventDefault(),e.stopPropagation(),await t.onMessageLinkClick(l))}function Ed(e){const t=e.sessionResources;if(!t||t.length===0)return v;const n=t.map(s=>({id:s.id,title:s.title,type:s.type,path:s.path,url:s.url}));return md({resources:n,collapsed:e.sessionResourcesCollapsed,onOpen:s=>e.onSessionResourceClick?.({path:s.path,url:s.url}),onToggleCollapse:()=>e.onToggleSessionResources?.(),onViewAll:()=>e.onViewAllResources?.()})}function Dd(e){const t=e.connected,n=e.sending||e.stream!==null,s=!!(e.canAbort&&e.onAbort),a=e.sessions?.sessions?.find(y=>y.key===e.sessionKey)?.reasoningLevel??"off",o=e.showThinking&&a!=="off",l={name:e.assistantName,avatar:e.assistantAvatar??e.assistantAvatarUrl??null},c=(e.attachments?.length??0)>0,m=e.connected?c?"Add a message or paste more images...":"Message (↩ to send, ⌘↩ to queue, Shift+↩ for line breaks)":"Connect to the gateway to start chatting…",r=e.splitRatio??.6,p=!!(e.sidebarOpen&&e.onCloseSidebar),g=d`
1175
+ `)?null:t.startsWith("/")||t.startsWith("~/")||t.startsWith("./")||t.startsWith("../")||/^[a-z]:[\\/]/i.test(t)||/^[^:\s]+\/[^\s]+$/.test(t)&&/\.[a-z0-9]{1,12}$/i.test(t)||/^[^\s/\\:*?"<>|]+\.[a-z0-9]{1,12}$/i.test(t)&&t.length<=100?t:null}async function Rd(e,t){const n=e.target,s=n instanceof Element?n:n instanceof Node?n.parentElement:null;if(!s||!t.onMessageLinkClick||!Ld(e))return;const i=s.closest("a");if(i instanceof HTMLAnchorElement){if(i.hasAttribute("download"))return;const c=i.getAttribute("href");if(!c)return;if(t.onOpenProof)try{const r=c.match(/(?:proofeditor\.ai|127\.0\.0\.1:\d+|localhost:\d+)\/d\/([a-zA-Z0-9_-]+)/);if(r){e.preventDefault(),t.onOpenProof(r[1]);return}}catch{}try{const r=new URL(c,window.location.href);if(/^https?:$/.test(r.protocol)){if(r.origin!==window.location.origin){e.preventDefault(),window.open(r.href,"_blank","noopener,noreferrer");return}if(/^\/godmode\/artifacts\//.test(r.pathname)){e.preventDefault(),window.open(r.href,"_blank","noopener,noreferrer");return}}}catch{}e.preventDefault(),e.stopPropagation(),await t.onMessageLinkClick(c)||Md(i);return}const a=s.closest("code");if(!(a instanceof HTMLElement))return;const o=(a.textContent??"").trim();if(/^https?:\/\/\S+$/i.test(o)){e.preventDefault(),window.open(o,"_blank","noopener,noreferrer");return}if(/^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*\.[a-z]{2,}(\/\S*)?$/i.test(o)){e.preventDefault(),window.open(`https://${o}`,"_blank","noopener,noreferrer");return}const l=Id(o);l&&(e.preventDefault(),e.stopPropagation(),await t.onMessageLinkClick(l))}function Ed(e){const t=e.sessionResources;if(!t||t.length===0)return v;const n=t.map(s=>({id:s.id,title:s.title,type:s.type,path:s.path,url:s.url}));return md({resources:n,collapsed:e.sessionResourcesCollapsed,onOpen:s=>e.onSessionResourceClick?.({path:s.path,url:s.url}),onToggleCollapse:()=>e.onToggleSessionResources?.(),onViewAll:()=>e.onViewAllResources?.()})}function Dd(e){const t=e.connected,n=e.sending||e.stream!==null,s=!!(e.canAbort&&e.onAbort),a=e.sessions?.sessions?.find(y=>y.key===e.sessionKey)?.reasoningLevel??"off",o=e.showThinking&&a!=="off",l={name:e.assistantName,avatar:e.assistantAvatar??e.assistantAvatarUrl??null},c=(e.attachments?.length??0)>0,m=e.connected?c?"Add a message or paste more images...":"Message (↩ to send, ⌘↩ to queue, Shift+↩ for line breaks)":"Connect to the gateway to start chatting…",r=e.splitRatio??.6,p=!!(e.sidebarOpen&&e.onCloseSidebar),g=d`
1176
1176
  <div
1177
1177
  class="chat-thread"
1178
1178
  role="log"
@@ -1604,7 +1604,7 @@ Deletes the session entry and archives its transcript.`)&&(e.sessionsResult?.ses
1604
1604
  </button>
1605
1605
  </div>
1606
1606
  </section>
1607
- `}const Xd={"gm-work":()=>_(()=>import("./work-tab-DOrlU-Ge.js"),__vite__mapDeps([0,1,2,3,4,5]),import.meta.url),"gm-today":()=>_(()=>import("./today-tab-BExVN_cu.js"),__vite__mapDeps([6,1,3,4,5,2]),import.meta.url),"gm-team":()=>_(()=>import("./team-tab-DE4DvNCS.js"),__vite__mapDeps([7,1,3,4,5]),import.meta.url),"gm-brain":()=>_(()=>import("./brain-tab-Z-Uwg6EX.js"),__vite__mapDeps([8,1,4,3,5]),import.meta.url),"gm-second-brain":()=>_(()=>import("./second-brain-tab-BINrzjjx.js"),__vite__mapDeps([9,1,4,3,5]),import.meta.url),"gm-dashboards":()=>_(()=>import("./dashboards-tab-D22kRTMW.js"),__vite__mapDeps([10,1,4,3,5]),import.meta.url),"gm-connections":()=>_(()=>import("./connections-tab-DhJWQQBw.js"),__vite__mapDeps([11,1,3,4,5]),import.meta.url)},Yn=new Set;function he(e){Yn.has(e)||(Yn.add(e),Xd[e]?.())}const Zd=/^data:/i,eu=/^https?:\/\//i;function tu(e){const t=e.agentsList?.agents??[],s=ms(e.sessionKey)?.agentId??e.agentsList?.defaultId??"main",a=t.find(l=>l.id===s)?.identity,o=a?.avatarUrl??a?.avatar;if(o)return Zd.test(o)||eu.test(o)?o:a?.avatarUrl}function Jn(e){const t=e.trim();if(!t)return t;const n=t.split(/\s+/);if(n.length>=2&&n.length%2===0){const l=n.length/2,c=n.slice(0,l).join(" "),m=n.slice(l).join(" ");if(c.toLowerCase()===m.toLowerCase())return c}const s=t.replace(/\s+/g," ").toLowerCase(),i=Math.floor(s.length/2),a=s.slice(0,i).trim(),o=s.slice(i).trim();return a&&a===o?t.slice(0,Math.ceil(t.length/2)).trim():t}function Ct(e,t){const n=t?.sessionId?.trim();return n?`session:${n}`:`key:${e.trim().toLowerCase()}`}function Xn(e){if(e===O)return!0;const t=e.toLowerCase();return!!(t==="agent:main:main"||t.endsWith(":main"))}function nu(e){const t=e.sessionsResult?.sessions,n=[...new Set(e.settings.openTabs.map(l=>l.trim()).filter(Boolean))].filter(l=>!Xn(l)),s=ae(t,e.sessionKey),i=Ct(e.sessionKey,s),a=new Map;for(const l of n){const c=ae(t,l),m=Ct(l,c);if(!a.has(m)){a.set(m,l);continue}l===e.sessionKey&&a.set(m,l)}const o=[...a.values()];if(o.length===0){const l=e.sessionKey.trim()||"main";Xn(l)||o.push(l)}return{tabKeys:o,activeIdentity:i}}function su(e){if(e.wizardActive&&e.wizardState)return Da(e.wizardState,{onStepChange:r=>{e.handleWizardStepChange?.(r)},onAnswerChange:(r,p)=>{e.handleWizardAnswerChange?.(r,p)},onPreview:()=>{e.handleWizardPreview?.()},onGenerate:()=>{e.handleWizardGenerate?.()},onClose:()=>{e.handleWizardClose?.()},onFileToggle:(r,p)=>{e.handleWizardFileToggle?.(r,p)},onConfigToggle:(r,p)=>{e.handleWizardConfigToggle?.(r,p)}});e.presenceEntries.length;const t=e.sessionsResult?.count??null;e.cronStatus?.nextWakeAtMs;const n=e.connected?null:"Disconnected from gateway.",s=e.tab==="chat",i=s&&(e.settings.chatFocusMode||e.onboarding),a=e.onboarding?!1:e.settings.chatShowThinking,o=tu(e),l=e.chatAvatarUrl??o??null,{tabKeys:c,activeIdentity:m}=nu(e);return d`
1607
+ `}const Xd={"gm-work":()=>_(()=>import("./work-tab-DwU559Bx.js"),__vite__mapDeps([0,1,2,3,4,5]),import.meta.url),"gm-today":()=>_(()=>import("./today-tab-C6lIMzgY.js"),__vite__mapDeps([6,1,3,4,5,2]),import.meta.url),"gm-team":()=>_(()=>import("./team-tab-Q3icI_Q-.js"),__vite__mapDeps([7,1,3,4,5]),import.meta.url),"gm-brain":()=>_(()=>import("./brain-tab-B1CYwAJ7.js"),__vite__mapDeps([8,1,4,3,5]),import.meta.url),"gm-second-brain":()=>_(()=>import("./second-brain-tab-DkFatLwl.js"),__vite__mapDeps([9,1,4,3,5]),import.meta.url),"gm-dashboards":()=>_(()=>import("./dashboards-tab-7hHXzWPp.js"),__vite__mapDeps([10,1,4,3,5]),import.meta.url),"gm-connections":()=>_(()=>import("./connections-tab-Cuv4eW0d.js"),__vite__mapDeps([11,1,3,4,5]),import.meta.url)},Yn=new Set;function he(e){Yn.has(e)||(Yn.add(e),Xd[e]?.())}const Zd=/^data:/i,eu=/^https?:\/\//i;function tu(e){const t=e.agentsList?.agents??[],s=ms(e.sessionKey)?.agentId??e.agentsList?.defaultId??"main",a=t.find(l=>l.id===s)?.identity,o=a?.avatarUrl??a?.avatar;if(o)return Zd.test(o)||eu.test(o)?o:a?.avatarUrl}function Jn(e){const t=e.trim();if(!t)return t;const n=t.split(/\s+/);if(n.length>=2&&n.length%2===0){const l=n.length/2,c=n.slice(0,l).join(" "),m=n.slice(l).join(" ");if(c.toLowerCase()===m.toLowerCase())return c}const s=t.replace(/\s+/g," ").toLowerCase(),i=Math.floor(s.length/2),a=s.slice(0,i).trim(),o=s.slice(i).trim();return a&&a===o?t.slice(0,Math.ceil(t.length/2)).trim():t}function Ct(e,t){const n=t?.sessionId?.trim();return n?`session:${n}`:`key:${e.trim().toLowerCase()}`}function Xn(e){if(e===O)return!0;const t=e.toLowerCase();return!!(t==="agent:main:main"||t.endsWith(":main"))}function nu(e){const t=e.sessionsResult?.sessions,n=[...new Set(e.settings.openTabs.map(l=>l.trim()).filter(Boolean))].filter(l=>!Xn(l)),s=ae(t,e.sessionKey),i=Ct(e.sessionKey,s),a=new Map;for(const l of n){const c=ae(t,l),m=Ct(l,c);if(!a.has(m)){a.set(m,l);continue}l===e.sessionKey&&a.set(m,l)}const o=[...a.values()];if(o.length===0){const l=e.sessionKey.trim()||"main";Xn(l)||o.push(l)}return{tabKeys:o,activeIdentity:i}}function su(e){if(e.wizardActive&&e.wizardState)return Da(e.wizardState,{onStepChange:r=>{e.handleWizardStepChange?.(r)},onAnswerChange:(r,p)=>{e.handleWizardAnswerChange?.(r,p)},onPreview:()=>{e.handleWizardPreview?.()},onGenerate:()=>{e.handleWizardGenerate?.()},onClose:()=>{e.handleWizardClose?.()},onFileToggle:(r,p)=>{e.handleWizardFileToggle?.(r,p)},onConfigToggle:(r,p)=>{e.handleWizardConfigToggle?.(r,p)}});e.presenceEntries.length;const t=e.sessionsResult?.count??null;e.cronStatus?.nextWakeAtMs;const n=e.connected?null:"Disconnected from gateway.",s=e.tab==="chat",i=s&&(e.settings.chatFocusMode||e.onboarding),a=e.onboarding?!1:e.settings.chatShowThinking,o=tu(e),l=e.chatAvatarUrl??o??null,{tabKeys:c,activeIdentity:m}=nu(e);return d`
1608
1608
  <div class="shell ${s?"shell--chat":""} ${i?"shell--chat-focus":""} ${e.settings.navCollapsed?"shell--nav-collapsed":""} ${e.onboarding?"shell--onboarding":""} ${window.innerWidth<=600?"shell--nav-drawer":""} ${e.navDrawerOpen?"shell--nav-drawer-open":""}">
1609
1609
  <div
1610
1610
  class="nav-drawer-backdrop ${e.navDrawerOpen?"nav-drawer-backdrop--visible":""}"
@@ -1975,14 +1975,14 @@ Deletes the session entry and archives its transcript.`)&&(e.sessionsResult?.ses
1975
1975
 
1976
1976
  ## `)===-1)return console.debug("[Ally] Filtered message:",t,n.substring(0,100)),null;if(/^##?\s*Persistence Protocol/i.test(n)||/^You are resourceful and thorough\.\s*Your job is to GET THE JOB DONE/i.test(n)||/^##?\s*Core (?:Behaviors|Principles)/i.test(n)||/^##?\s*Your Role as \w+/i.test(n))return console.debug("[Ally] Filtered message (persona leak):",t,n.substring(0,100)),null;const s=n.toLowerCase();if(["persistence protocol","core principles:","core behaviors","your role as ","be diligent first time","exhaust reasonable options","assume capability exists","elite executive assistant","consciousness context","working context","enforcement:","internal system context injected by godmode"].filter(o=>s.includes(o)).length>=2)return console.debug("[Ally] Filtered message (multi-signal system leak):",t,n.substring(0,100)),null;if(/^(?:ID\s+START\s+END\s+SUMMARY)/i.test(n))return console.debug("[Ally] Filtered message:",t,n.substring(0,100)),null;const a=n.match(/\b[\w.-]+\.(?:json\b|db\b|html\b|log\b|flag\b|jsonl\b|bak\b|css\b|js\b|ts\b|md\b|txt\b)/gi);return a&&a.length>=8&&a.join(" ").length>n.length*.4?(console.debug("[Ally] Filtered message (file listing dump):",t,n.substring(0,100)),null):n}const ns=new Set(["chat","today","workspaces","work","data","overview","channels","instances","sessions","cron","skills","nodes","config","debug","logs","my-day"]),yu=["path","filePath","file","workspacePath"];let u=class extends rs{constructor(){super(...arguments),this._ctx=eo(),this.settings=Il(),this.password="",this.tab="chat",this.onboarding=mu(),this.connected=!1,this.reconnecting=!1,this.reconnectAttempt=0,this.theme=this.settings.theme??"system",this.themeResolved="dark",this.hello=null,this.lastError=null,this.eventLog=[],this.toolStreamSyncTimer=null,this.sidebarCloseTimer=null,this.sessionPickerClickOutsideHandler=null,this.sessionSearchClickOutsideHandler=null,this.assistantName=ct().name,this.assistantAvatar=ct().avatar,this.assistantAgentId=ct().agentId??null,this.userName=Me().name,this.userAvatar=Me().avatar,this.currentModel=null,this.availableModels=[],this.modelPickerOpen=!1,this.modelCacheTs=0,this.sessionKey=this.settings.sessionKey,this.sessionPickerOpen=!1,this.sessionPickerPosition=null,this.sessionPickerSearch="",this.sessionSearchOpen=!1,this.sessionSearchPosition=null,this.sessionSearchQuery="",this.sessionSearchResults=[],this.sessionSearchLoading=!1,this.profilePopoverOpen=!1,this.profileEditName="",this.profileEditAvatar="",this.editingTabKey=null,this.navDrawerOpen=!1,this.closeNavDrawer=()=>{this.navDrawerOpen=!1},this.chatLoading=!1,this.chatSending=!1,this.chatSendingSessionKey=null,this.chatMessage="",this.chatDrafts={},this.chatMessages=[],this.chatToolMessages=[],this.chatStream=null,this.chatStreamStartedAt=null,this.chatRunId=null,this.currentToolName=null,this.currentToolInfo=null,this.workingSessions=new Set,this.compactionStatus=null,this.chatAvatarUrl=null,this.chatThinkingLevel=null,this.chatQueue=[],this.chatAttachments=[],this.sidebarOpen=!1,this.sidebarContent=null,this.sidebarError=null,this.sidebarMimeType=null,this.sidebarFilePath=null,this.sidebarTitle=null,this.sidebarMode="resource",this.sidebarProofSlug=null,this.sidebarProofUrl=null,this.sidebarProofHtml=null,this.splitRatio=this.settings.splitRatio,this.lightbox=Ri(),this.driveAccounts=[],this.showDrivePicker=!1,this.driveUploading=!1,this.updateStatus=null,this.updateLoading=!1,this.updateError=null,this.updateLastChecked=null,this.updatePollInterval=null,this.nodesLoading=!1,this.nodes=[],this.devicesLoading=!1,this.devicesError=null,this.devicesList=null,this.execApprovalsLoading=!1,this.execApprovalsSaving=!1,this.execApprovalsDirty=!1,this.execApprovalsSnapshot=null,this.execApprovalsForm=null,this.execApprovalsSelectedAgent=null,this.execApprovalsTarget="gateway",this.execApprovalsTargetNodeId=null,this.execApprovalQueue=[],this.execApprovalBusy=!1,this.execApprovalError=null,this.pendingGatewayUrl=null,this.gatewayRestartPending=!1,this.gatewayRestartBusy=!1,this.deployPanelOpen=!1,this.configLoading=!1,this.configRaw=`{
1977
1977
  }
1978
- `,this.configRawOriginal="",this.configValid=null,this.configIssues=[],this.configSaving=!1,this.configApplying=!1,this.updateRunning=!1,this.applySessionKey=this.settings.lastActiveSessionKey,this.configSnapshot=null,this.configSchema=null,this.configSchemaVersion=null,this.configSchemaLoading=!1,this.configUiHints={},this.configForm=null,this.configFormOriginal=null,this.configFormDirty=!1,this.configFormMode="form",this.configSearchQuery="",this.configActiveSection=null,this.configActiveSubsection=null,this.channelsLoading=!1,this.channelsSnapshot=null,this.channelsError=null,this.channelsLastSuccess=null,this.whatsappLoginMessage=null,this.whatsappLoginQrDataUrl=null,this.whatsappLoginConnected=null,this.whatsappBusy=!1,this.nostrProfileFormState=null,this.nostrProfileAccountId=null,this.presenceLoading=!1,this.presenceEntries=[],this.presenceError=null,this.presenceStatus=null,this.agentsLoading=!1,this.agentsList=null,this.agentsError=null,this.sessionsLoading=!1,this.sessionsResult=null,this.sessionsError=null,this.sessionsFilterActive="",this.sessionsFilterLimit="120",this.sessionsIncludeGlobal=!0,this.sessionsIncludeUnknown=!1,this.archivedSessions=[],this.archivedSessionsLoading=!1,this.archivedSessionsExpanded=!1,this.cronLoading=!1,this.cronJobs=[],this.cronStatus=null,this.cronError=null,this.cronForm={...sc},this.cronRunsJobId=null,this.cronRuns=[],this.cronBusy=!1,this.workspaceNeedsSetup=!1,this.onboardingPhase=0,this.onboardingData=null,this.onboardingActive=!1,this.wizardActive=!1,this.wizardState=null,this.showSetupTab=!1,this.setupBarDismissed=!1,this.setupProgress=null,this.setupCapabilities=null,this.setupCapabilitiesLoading=!1,this.setupQuickDone=!1,this.onboardingIntegrations=null,this.onboardingCoreProgress=null,this.onboardingExpandedCard=null,this.onboardingLoadingGuide=null,this.onboardingActiveGuide=null,this.onboardingTestingId=null,this.onboardingTestResult=null,this.onboardingConfigValues={},this.onboardingProgress=null,this.allyPanelOpen=!1,this.allyMessages=[],this.allyStream=null,this.allyDraft="",this.allyUnread=0,this.allySending=!1,this.allyWorking=!1,this.allyAttachments=[],this.chatPrivateMode=!1,this.privateSessions=new Map,this._privateSessionTimer=null,this.dynamicSlots={},this.sessionResources=[],this.sessionResourcesCollapsed=!1,this.skillsLoading=!1,this.skillsReport=null,this.skillsError=null,this.skillsFilter="",this.skillEdits={},this.skillsBusyKey=null,this.skillMessages={},this.skillsSubTab="godmode",this.godmodeSkills=null,this.godmodeSkillsLoading=!1,this.expandedSkills=new Set,this.rosterData=[],this.rosterLoading=!1,this.rosterError=null,this.rosterFilter="",this.expandedAgents=new Set,this.debugLoading=!1,this.debugStatus=null,this.debugHealth=null,this.debugModels=[],this.debugHeartbeat=null,this.debugCallMethod="",this.debugCallParams="{}",this.debugCallResult=null,this.debugCallError=null,this.logsLoading=!1,this.logsError=null,this.logsFile=null,this.logsEntries=[],this.logsFilterText="",this.logsLevelFilters={...nc},this.logsAutoFollow=!0,this.logsTruncated=!1,this.logsCursor=null,this.logsLastFetchAt=null,this.logsLimit=500,this.logsMaxBytes=25e4,this.logsAtBottom=!0,this.toasts=[],this.client=null,this.chatScrollFrame=null,this.chatScrollTimeout=null,this.chatUserNearBottom=!0,this.chatIsAutoScrolling=!1,this.chatNewMessagesBelow=!1,this.consciousnessStatus="idle",this.trustTrackerData=null,this.trustTrackerLoading=!1,this.guardrailsData=null,this.guardrailsLoading=!1,this.guardrailsShowAddForm=!1,this.secrets=[],this.secretsLoading=!1,this.webFetchProvider="default",this.webFetchLoading=!1,this.searchProvider="tavily",this.searchExaConfigured=!1,this.searchTavilyConfigured=!1,this.searchLoading=!1,this.customTabs=[],this.customTabData={},this.customTabLoading=!1,this.customTabErrors={},this.dashboardPreviousSessionKey=null,this.nodesPollInterval=null,this.logsPollInterval=null,this.debugPollInterval=null,this.logsScrollFrame=null,this.toolStreamById=new Map,this.toolStreamOrder=[],this.refreshSessionsAfterChat=!1,this.basePath="",this.popStateHandler=()=>Ql(this),this.keydownHandler=()=>{},this.themeMedia=null,this.themeMediaHandler=null,this.topbarObserver=null,this._eventBusUnsubs=[]}createRenderRoot(){return this}connectedCallback(){if(super.connectedCallback(),this.settings.userName)this.userName=this.settings.userName;else{const e=Me();this.userName=e.name}if(this.settings.userAvatar)this.userAvatar=this.settings.userAvatar;else{const e=Me();this.userAvatar=e.avatar}vc(this),lu(this),this._restorePrivateSessions(),this._eventBusUnsubs.push(z.on("chat-navigate",e=>{e.sessionKey&&e.sessionKey!==this.sessionKey&&(e.sessionKey==="new"?this.sessionKey=`webchat-${Date.now()}`:this.sessionKey=e.sessionKey),e.tab==="chat"&&this.setTab("chat"),e.message&&(this.chatMessage=e.message)}))}firstUpdated(){bc(this)}disconnectedCallback(){Di(),this._stopPrivateSessionTimer();for(const e of this._eventBusUnsubs)e();this._eventBusUnsubs=[],wc(this),super.disconnectedCallback()}updated(e){_c(this,e),this._syncContext()}_syncContext(){const e=this._ctx;e.connected===this.connected&&e.reconnecting===this.reconnecting&&e.sessionKey===this.sessionKey&&e.assistantName===this.assistantName&&e.assistantAvatar===this.assistantAvatar&&e.userName===this.userName&&e.userAvatar===this.userAvatar&&e.theme===this.theme&&e.themeResolved===this.themeResolved&&e.settings===this.settings&&e.basePath===this.basePath&&e.gateway===this.client||(this._ctx={connected:this.connected,reconnecting:this.reconnecting,sessionKey:this.sessionKey,assistantName:this.assistantName,assistantAvatar:this.assistantAvatar,userName:this.userName,userAvatar:this.userAvatar,theme:this.theme,themeResolved:this.themeResolved,settings:this.settings,basePath:this.basePath,gateway:this.client,send:(t,n)=>this.client?.request(t,n)??Promise.reject(new Error("Not connected")),setTab:t=>this.setTab(t),addToast:(t,n)=>this.showToast(t,n??"info"),openSidebar:t=>this.handleOpenSidebar(t.content,{title:t.title,mimeType:t.mimeType,filePath:t.filePath}),closeSidebar:()=>this.handleCloseSidebar()})}connect(){ze(this)}handleChatScroll(e){ys(this,e)}handleLogsScroll(e){vs(this,e)}exportLogs(e,t){bs(e,t)}resetToolStream(){It(this),this.sessionResources=[]}resetChatScroll(){ke(this)}async loadAssistantIdentity(){await Es(this)}applySettings(e){te(this,e)}setTab(e){Bl(this,e)}setTheme(e,t){jl(this,e,t)}async loadOverview(){await vi(this)}async loadCron(){await Gt(this)}async handleAbortChat(){await Qt(this)}async handleConsciousnessFlush(){if(!(!this.client||this.consciousnessStatus==="loading")){this.consciousnessStatus="loading";try{await this.client.request("godmode.consciousness.flush",{}),this.consciousnessStatus="ok"}catch{this.consciousnessStatus="error"}setTimeout(()=>{this.consciousnessStatus!=="loading"&&(this.consciousnessStatus="idle")},3e3)}}async handleTrustLoad(){await sn(this)}async handleTrustAddWorkflow(e){await iu(this,e)}async handleTrustRemoveWorkflow(e){await au(this,e)}async handleDailyRate(e,t){await ou(this,e,t)}async handleGuardrailsLoad(){const{loadGuardrails:e}=await _(async()=>{const{loadGuardrails:t}=await import("./ctrl-settings-niym-WgY.js").then(n=>n.ae);return{loadGuardrails:t}},[],import.meta.url);await e(this)}async handleGuardrailToggle(e,t){const{toggleGuardrail:n}=await _(async()=>{const{toggleGuardrail:s}=await import("./ctrl-settings-niym-WgY.js").then(i=>i.ae);return{toggleGuardrail:s}},[],import.meta.url);await n(this,e,t)}async handleGuardrailThresholdChange(e,t,n){const{updateGuardrailThreshold:s}=await _(async()=>{const{updateGuardrailThreshold:i}=await import("./ctrl-settings-niym-WgY.js").then(a=>a.ae);return{updateGuardrailThreshold:i}},[],import.meta.url);await s(this,e,t,n)}async handleCustomGuardrailToggle(e,t){const{toggleCustomGuardrail:n}=await _(async()=>{const{toggleCustomGuardrail:s}=await import("./ctrl-settings-niym-WgY.js").then(i=>i.ae);return{toggleCustomGuardrail:s}},[],import.meta.url);await n(this,e,t)}async handleCustomGuardrailDelete(e){const{deleteCustomGuardrail:t}=await _(async()=>{const{deleteCustomGuardrail:n}=await import("./ctrl-settings-niym-WgY.js").then(s=>s.ae);return{deleteCustomGuardrail:n}},[],import.meta.url);await t(this,e)}async handleCustomGuardrailAdd(e){const{addCustomGuardrailFromUI:t}=await _(async()=>{const{addCustomGuardrailFromUI:n}=await import("./ctrl-settings-niym-WgY.js").then(s=>s.ae);return{addCustomGuardrailFromUI:n}},[],import.meta.url);await t(this,e),this.guardrailsShowAddForm=!1}handleToggleGuardrailAddForm(){this.guardrailsShowAddForm=!this.guardrailsShowAddForm}async handleMissionControlOpenSession(e){const t=this.settings.openTabs.includes(e)?this.settings.openTabs:[...this.settings.openTabs,e];this.applySettings({...this.settings,openTabs:t,sessionKey:e,lastActiveSessionKey:e,tabLastViewed:{...this.settings.tabLastViewed,[e]:Date.now()}}),this.sessionKey=e,this.setTab("chat"),this.chatMessages=[],this.chatStream=null,this.chatStreamStartedAt=null,this.chatRunId=null,this.resetToolStream(),this.resetChatScroll(),this.loadAssistantIdentity();const{loadChatHistory:n}=await _(async()=>{const{loadChatHistory:s}=await Promise.resolve().then(()=>fe);return{loadChatHistory:s}},void 0,import.meta.url);await n(this),this.loadSessionResources()}async handleMissionControlOpenTaskSession(e){if(!(!this.client||!this.connected))try{const t=await this.client.request("tasks.openSession",{taskId:e});if(t?.sessionId){if(t.task?.title){const{autoTitleCache:n}=await _(async()=>{const{autoTitleCache:s}=await import("./ctrl-settings-niym-WgY.js").then(i=>i.ad);return{autoTitleCache:s}},[],import.meta.url);n.set(t.sessionId,t.task.title)}await this.handleMissionControlOpenSession(t.sessionId),t.queueOutput&&this.chatMessages.length===0&&await this.seedSessionWithAgentOutput(t.task?.title??"task",t.queueOutput,t.agentPrompt??void 0)}}catch(t){console.error("[MissionControl] Failed to open task session:",t),this.showToast("Failed to open session","error")}}async handleMissionControlStartQueueItem(e){await this.handleMissionControlOpenTaskSession(e)}async handleSwarmViewProofDoc(e){return this.handleOpenProofDoc(e)}async handleSwarmViewRunLog(e){if(!(!this.client||!this.connected))try{const t=await this.client.request("godmode.delegation.runLog",{queueItemId:e});t?.content?this.handleOpenSidebar(t.content,{mimeType:t.mimeType??"text/markdown",title:t.title??"Agent Logs"}):this.showToast("No logs available","error")}catch{this.showToast("Failed to load agent logs","error")}}async handleAllyAction(e,t,n,s){if(e==="navigate"&&t)this.setTab(t);else if(e==="rpc"&&n&&this.client)try{await this.client.request(n,s??{}),this.showToast("Done","success",2e3)}catch(i){console.error("[Ally] Action RPC failed:",i),this.showToast("Action failed","error")}}async handleHitlAction(e,t,n){if(this.client)try{await this.client.request("queue.hitl.respond",{checkpointId:e,action:t,modifiedInstructions:n});const s=this;s.hitlCheckpoints&&(s.hitlCheckpoints=s.hitlCheckpoints.filter(a=>a.id!==e));const i=t==="continue"?"Approved":t==="abort"?"Aborted":"Modified";this.showToast(`Checkpoint ${i.toLowerCase()}`,"success",2e3),this.requestUpdate()}catch(s){console.error("[HITL] Respond failed:",s),this.showToast("Failed to respond to checkpoint","error")}}handleAllyToggle(){this.allyPanelOpen=!this.allyPanelOpen,this.allyPanelOpen&&(this.allyUnread=0,this._loadAllyHistory().then(()=>{this._scrollAllyToBottom(),requestAnimationFrame(()=>this._scrollAllyToBottom())}))}handleAllyDraftChange(e){this.allyDraft=e}handleAllyAttachmentsChange(e){this.allyAttachments=e}async handleAllySend(){const e=this.allyDraft.trim(),t=this.allyAttachments;if(!e&&t.length===0||this.allySending)return;const n=yo(this);let s=e?`${n}
1978
+ `,this.configRawOriginal="",this.configValid=null,this.configIssues=[],this.configSaving=!1,this.configApplying=!1,this.updateRunning=!1,this.applySessionKey=this.settings.lastActiveSessionKey,this.configSnapshot=null,this.configSchema=null,this.configSchemaVersion=null,this.configSchemaLoading=!1,this.configUiHints={},this.configForm=null,this.configFormOriginal=null,this.configFormDirty=!1,this.configFormMode="form",this.configSearchQuery="",this.configActiveSection=null,this.configActiveSubsection=null,this.channelsLoading=!1,this.channelsSnapshot=null,this.channelsError=null,this.channelsLastSuccess=null,this.whatsappLoginMessage=null,this.whatsappLoginQrDataUrl=null,this.whatsappLoginConnected=null,this.whatsappBusy=!1,this.nostrProfileFormState=null,this.nostrProfileAccountId=null,this.presenceLoading=!1,this.presenceEntries=[],this.presenceError=null,this.presenceStatus=null,this.agentsLoading=!1,this.agentsList=null,this.agentsError=null,this.sessionsLoading=!1,this.sessionsResult=null,this.sessionsError=null,this.sessionsFilterActive="",this.sessionsFilterLimit="120",this.sessionsIncludeGlobal=!0,this.sessionsIncludeUnknown=!1,this.archivedSessions=[],this.archivedSessionsLoading=!1,this.archivedSessionsExpanded=!1,this.cronLoading=!1,this.cronJobs=[],this.cronStatus=null,this.cronError=null,this.cronForm={...sc},this.cronRunsJobId=null,this.cronRuns=[],this.cronBusy=!1,this.workspaceNeedsSetup=!1,this.onboardingPhase=0,this.onboardingData=null,this.onboardingActive=!1,this.wizardActive=!1,this.wizardState=null,this.showSetupTab=!1,this.setupBarDismissed=!1,this.setupProgress=null,this.setupCapabilities=null,this.setupCapabilitiesLoading=!1,this.setupQuickDone=!1,this.onboardingIntegrations=null,this.onboardingCoreProgress=null,this.onboardingExpandedCard=null,this.onboardingLoadingGuide=null,this.onboardingActiveGuide=null,this.onboardingTestingId=null,this.onboardingTestResult=null,this.onboardingConfigValues={},this.onboardingProgress=null,this.allyPanelOpen=!1,this.allyMessages=[],this.allyStream=null,this.allyDraft="",this.allyUnread=0,this.allySending=!1,this.allyWorking=!1,this.allyAttachments=[],this.chatPrivateMode=!1,this.privateSessions=new Map,this._privateSessionTimer=null,this.dynamicSlots={},this.sessionResources=[],this.sessionResourcesCollapsed=!1,this.skillsLoading=!1,this.skillsReport=null,this.skillsError=null,this.skillsFilter="",this.skillEdits={},this.skillsBusyKey=null,this.skillMessages={},this.skillsSubTab="godmode",this.godmodeSkills=null,this.godmodeSkillsLoading=!1,this.expandedSkills=new Set,this.rosterData=[],this.rosterLoading=!1,this.rosterError=null,this.rosterFilter="",this.expandedAgents=new Set,this.debugLoading=!1,this.debugStatus=null,this.debugHealth=null,this.debugModels=[],this.debugHeartbeat=null,this.debugCallMethod="",this.debugCallParams="{}",this.debugCallResult=null,this.debugCallError=null,this.logsLoading=!1,this.logsError=null,this.logsFile=null,this.logsEntries=[],this.logsFilterText="",this.logsLevelFilters={...nc},this.logsAutoFollow=!0,this.logsTruncated=!1,this.logsCursor=null,this.logsLastFetchAt=null,this.logsLimit=500,this.logsMaxBytes=25e4,this.logsAtBottom=!0,this.toasts=[],this.client=null,this.chatScrollFrame=null,this.chatScrollTimeout=null,this.chatUserNearBottom=!0,this.chatIsAutoScrolling=!1,this.chatNewMessagesBelow=!1,this.consciousnessStatus="idle",this.trustTrackerData=null,this.trustTrackerLoading=!1,this.guardrailsData=null,this.guardrailsLoading=!1,this.guardrailsShowAddForm=!1,this.secrets=[],this.secretsLoading=!1,this.webFetchProvider="default",this.webFetchLoading=!1,this.searchProvider="tavily",this.searchExaConfigured=!1,this.searchTavilyConfigured=!1,this.searchLoading=!1,this.customTabs=[],this.customTabData={},this.customTabLoading=!1,this.customTabErrors={},this.dashboardPreviousSessionKey=null,this.nodesPollInterval=null,this.logsPollInterval=null,this.debugPollInterval=null,this.logsScrollFrame=null,this.toolStreamById=new Map,this.toolStreamOrder=[],this.refreshSessionsAfterChat=!1,this.basePath="",this.popStateHandler=()=>Ql(this),this.keydownHandler=()=>{},this.themeMedia=null,this.themeMediaHandler=null,this.topbarObserver=null,this._eventBusUnsubs=[]}createRenderRoot(){return this}connectedCallback(){if(super.connectedCallback(),this.settings.userName)this.userName=this.settings.userName;else{const e=Me();this.userName=e.name}if(this.settings.userAvatar)this.userAvatar=this.settings.userAvatar;else{const e=Me();this.userAvatar=e.avatar}vc(this),lu(this),this._restorePrivateSessions(),this._eventBusUnsubs.push(z.on("chat-navigate",e=>{e.sessionKey&&e.sessionKey!==this.sessionKey&&(e.sessionKey==="new"?this.sessionKey=`webchat-${Date.now()}`:this.sessionKey=e.sessionKey),e.tab==="chat"&&this.setTab("chat"),e.message&&(this.chatMessage=e.message)}))}firstUpdated(){bc(this)}disconnectedCallback(){Di(),this._stopPrivateSessionTimer();for(const e of this._eventBusUnsubs)e();this._eventBusUnsubs=[],wc(this),super.disconnectedCallback()}updated(e){_c(this,e),this._syncContext()}_syncContext(){const e=this._ctx;e.connected===this.connected&&e.reconnecting===this.reconnecting&&e.sessionKey===this.sessionKey&&e.assistantName===this.assistantName&&e.assistantAvatar===this.assistantAvatar&&e.userName===this.userName&&e.userAvatar===this.userAvatar&&e.theme===this.theme&&e.themeResolved===this.themeResolved&&e.settings===this.settings&&e.basePath===this.basePath&&e.gateway===this.client||(this._ctx={connected:this.connected,reconnecting:this.reconnecting,sessionKey:this.sessionKey,assistantName:this.assistantName,assistantAvatar:this.assistantAvatar,userName:this.userName,userAvatar:this.userAvatar,theme:this.theme,themeResolved:this.themeResolved,settings:this.settings,basePath:this.basePath,gateway:this.client,send:(t,n)=>this.client?.request(t,n)??Promise.reject(new Error("Not connected")),setTab:t=>this.setTab(t),addToast:(t,n)=>this.showToast(t,n??"info"),openSidebar:t=>this.handleOpenSidebar(t.content,{title:t.title,mimeType:t.mimeType,filePath:t.filePath}),closeSidebar:()=>this.handleCloseSidebar()})}connect(){ze(this)}handleChatScroll(e){ys(this,e)}handleLogsScroll(e){vs(this,e)}exportLogs(e,t){bs(e,t)}resetToolStream(){It(this),this.sessionResources=[]}resetChatScroll(){ke(this)}async loadAssistantIdentity(){await Es(this)}applySettings(e){te(this,e)}setTab(e){Bl(this,e)}setTheme(e,t){jl(this,e,t)}async loadOverview(){await vi(this)}async loadCron(){await Gt(this)}async handleAbortChat(){await Qt(this)}async handleConsciousnessFlush(){if(!(!this.client||this.consciousnessStatus==="loading")){this.consciousnessStatus="loading";try{await this.client.request("godmode.consciousness.flush",{}),this.consciousnessStatus="ok"}catch{this.consciousnessStatus="error"}setTimeout(()=>{this.consciousnessStatus!=="loading"&&(this.consciousnessStatus="idle")},3e3)}}async handleTrustLoad(){await sn(this)}async handleTrustAddWorkflow(e){await iu(this,e)}async handleTrustRemoveWorkflow(e){await au(this,e)}async handleDailyRate(e,t){await ou(this,e,t)}async handleGuardrailsLoad(){const{loadGuardrails:e}=await _(async()=>{const{loadGuardrails:t}=await import("./ctrl-settings-COfcdhha.js").then(n=>n.ae);return{loadGuardrails:t}},[],import.meta.url);await e(this)}async handleGuardrailToggle(e,t){const{toggleGuardrail:n}=await _(async()=>{const{toggleGuardrail:s}=await import("./ctrl-settings-COfcdhha.js").then(i=>i.ae);return{toggleGuardrail:s}},[],import.meta.url);await n(this,e,t)}async handleGuardrailThresholdChange(e,t,n){const{updateGuardrailThreshold:s}=await _(async()=>{const{updateGuardrailThreshold:i}=await import("./ctrl-settings-COfcdhha.js").then(a=>a.ae);return{updateGuardrailThreshold:i}},[],import.meta.url);await s(this,e,t,n)}async handleCustomGuardrailToggle(e,t){const{toggleCustomGuardrail:n}=await _(async()=>{const{toggleCustomGuardrail:s}=await import("./ctrl-settings-COfcdhha.js").then(i=>i.ae);return{toggleCustomGuardrail:s}},[],import.meta.url);await n(this,e,t)}async handleCustomGuardrailDelete(e){const{deleteCustomGuardrail:t}=await _(async()=>{const{deleteCustomGuardrail:n}=await import("./ctrl-settings-COfcdhha.js").then(s=>s.ae);return{deleteCustomGuardrail:n}},[],import.meta.url);await t(this,e)}async handleCustomGuardrailAdd(e){const{addCustomGuardrailFromUI:t}=await _(async()=>{const{addCustomGuardrailFromUI:n}=await import("./ctrl-settings-COfcdhha.js").then(s=>s.ae);return{addCustomGuardrailFromUI:n}},[],import.meta.url);await t(this,e),this.guardrailsShowAddForm=!1}handleToggleGuardrailAddForm(){this.guardrailsShowAddForm=!this.guardrailsShowAddForm}async handleMissionControlOpenSession(e){const t=this.settings.openTabs.includes(e)?this.settings.openTabs:[...this.settings.openTabs,e];this.applySettings({...this.settings,openTabs:t,sessionKey:e,lastActiveSessionKey:e,tabLastViewed:{...this.settings.tabLastViewed,[e]:Date.now()}}),this.sessionKey=e,this.setTab("chat"),this.chatMessages=[],this.chatStream=null,this.chatStreamStartedAt=null,this.chatRunId=null,this.resetToolStream(),this.resetChatScroll(),this.loadAssistantIdentity();const{loadChatHistory:n}=await _(async()=>{const{loadChatHistory:s}=await Promise.resolve().then(()=>fe);return{loadChatHistory:s}},void 0,import.meta.url);await n(this),this.loadSessionResources()}async handleMissionControlOpenTaskSession(e){if(!(!this.client||!this.connected))try{const t=await this.client.request("tasks.openSession",{taskId:e});if(t?.sessionId){if(t.task?.title){const{autoTitleCache:n}=await _(async()=>{const{autoTitleCache:s}=await import("./ctrl-settings-COfcdhha.js").then(i=>i.ad);return{autoTitleCache:s}},[],import.meta.url);n.set(t.sessionId,t.task.title)}await this.handleMissionControlOpenSession(t.sessionId),t.queueOutput&&this.chatMessages.length===0&&await this.seedSessionWithAgentOutput(t.task?.title??"task",t.queueOutput,t.agentPrompt??void 0)}}catch(t){console.error("[MissionControl] Failed to open task session:",t),this.showToast("Failed to open session","error")}}async handleMissionControlStartQueueItem(e){await this.handleMissionControlOpenTaskSession(e)}async handleSwarmViewProofDoc(e){return this.handleOpenProofDoc(e)}async handleSwarmViewRunLog(e){if(!(!this.client||!this.connected))try{const t=await this.client.request("godmode.delegation.runLog",{queueItemId:e});t?.content?this.handleOpenSidebar(t.content,{mimeType:t.mimeType??"text/markdown",title:t.title??"Agent Logs"}):this.showToast("No logs available","error")}catch{this.showToast("Failed to load agent logs","error")}}async handleAllyAction(e,t,n,s){if(e==="navigate"&&t)this.setTab(t);else if(e==="rpc"&&n&&this.client)try{await this.client.request(n,s??{}),this.showToast("Done","success",2e3)}catch(i){console.error("[Ally] Action RPC failed:",i),this.showToast("Action failed","error")}}async handleHitlAction(e,t,n){if(this.client)try{await this.client.request("queue.hitl.respond",{checkpointId:e,action:t,modifiedInstructions:n});const s=this;s.hitlCheckpoints&&(s.hitlCheckpoints=s.hitlCheckpoints.filter(a=>a.id!==e));const i=t==="continue"?"Approved":t==="abort"?"Aborted":"Modified";this.showToast(`Checkpoint ${i.toLowerCase()}`,"success",2e3),this.requestUpdate()}catch(s){console.error("[HITL] Respond failed:",s),this.showToast("Failed to respond to checkpoint","error")}}handleAllyToggle(){this.allyPanelOpen=!this.allyPanelOpen,this.allyPanelOpen&&(this.allyUnread=0,this._loadAllyHistory().then(()=>{this._scrollAllyToBottom(),requestAnimationFrame(()=>this._scrollAllyToBottom())}))}handleAllyDraftChange(e){this.allyDraft=e}handleAllyAttachmentsChange(e){this.allyAttachments=e}async handleAllySend(){const e=this.allyDraft.trim(),t=this.allyAttachments;if(!e&&t.length===0||this.allySending)return;const n=yo(this);let s=e?`${n}
1979
1979
 
1980
1980
  ${e}`:n;this.allyDraft="",this.allyAttachments=[],this.allySending=!0,this.allyMessages=[...this.allyMessages,{role:"user",content:e||"(image)",timestamp:Date.now()}];try{let i;if(t.length>0){const c=[];for(const m of t){if(!m.dataUrl)continue;const r=m.dataUrl.match(/^data:([^;]+);base64,(.+)$/);if(!r)continue;const[,p,g]=r;p.startsWith("image/")&&c.push({type:"image",mimeType:p,content:g,fileName:m.fileName})}if(c.length>0){i=c;try{await this.client?.request("images.cache",{images:c.map(m=>({data:m.content,mimeType:m.mimeType,fileName:m.fileName})),sessionKey:O})}catch{}}}const a=`ally-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;try{await this.client?.request("sessions.patch",{key:O,lastChannel:"webchat"})}catch{}await this.client?.request("agent",{sessionKey:O,message:s,deliver:!1,channel:"webchat",idempotencyKey:a,attachments:i}),this.allyWorking=!0;const o=this.allyMessages[this.allyMessages.length-1]?.content,l=setInterval(async()=>{if(!this.allyWorking){clearInterval(l);return}try{await this._loadAllyHistory();const c=this.allyMessages[this.allyMessages.length-1];c&&c.role==="assistant"&&c.content!==o&&(this.allyWorking=!1,this.allyStream=null,clearInterval(l),this._scrollAllyToBottom())}catch{}},5e3);setTimeout(()=>clearInterval(l),12e4)}catch(i){const a=i instanceof Error?i.message:String(i);console.error("[Ally] Failed to send ally message:",a),this.allyMessages=[...this.allyMessages,{role:"assistant",content:`*Send failed: ${a}*`,timestamp:Date.now()}]}finally{this.allySending=!1}}handleAllyOpenFull(){this.allyPanelOpen=!1,this.setTab("chat"),this.applySettings({...this.settings,sessionKey:O,lastActiveSessionKey:O,tabLastViewed:{...this.settings.tabLastViewed,[O]:Date.now()}}),this.sessionKey=O,this.chatMessages=[],this.chatStream=null,this.chatStreamStartedAt=null,this.chatRunId=null,this.resetToolStream(),this.resetChatScroll(),this.loadAssistantIdentity(),_(async()=>{const{loadChatHistory:e}=await Promise.resolve().then(()=>fe);return{loadChatHistory:e}},void 0,import.meta.url).then(({loadChatHistory:e})=>e(this)),this.loadSessionResources()}_scrollAllyToBottom(){this.updateComplete.then(()=>{requestAnimationFrame(()=>{const e=this.renderRoot?.querySelector?.(".ally-panel, .ally-inline")??document.querySelector(".ally-panel, .ally-inline");if(!e)return;const t=e.querySelector(".ally-panel__messages");t&&(t.scrollTop=t.scrollHeight)})})}async _loadAllyHistory(){try{const e=await this.client?.request("chat.history",{sessionKey:O,limit:100});if(e?.messages){const{extractText:t,formatApiError:n}=await _(async()=>{const{extractText:i,formatApiError:a}=await Promise.resolve().then(()=>Yo);return{extractText:i,formatApiError:a}},void 0,import.meta.url);this.allyMessages=e.messages.map(i=>{const a=i.role??"assistant",o=a.toLowerCase();if(o==="tool"||o==="toolresult"||o==="tool_result"||o==="function"||o==="system")return null;const l=i;if(l.toolCallId||l.tool_call_id||l.toolName||l.tool_name)return null;if(Array.isArray(i.content)){const p=i.content;if(!p.some(y=>{const b=(typeof y.type=="string"?y.type:"").toLowerCase();return(b==="text"||b==="")&&typeof y.text=="string"&&y.text.trim().length>0})&&p.some(b=>{const A=(typeof b.type=="string"?b.type:"").toLowerCase();return A==="tool_use"||A==="tool_result"||A==="toolresult"||A==="tooluse"}))return null}let c=t(i);if(!c)return null;const m=n(c);if(m&&(c=m),c=c.replace(/^\[GodMode Context:[^\]]*\]\s*/i,"").trim(),!c)return null;const r=gu(c,a);return r?{role:o==="user"?"user":"assistant",content:r,timestamp:i.timestamp}:null}).filter(i=>i!==null);const s=[];for(const i of this.allyMessages){const a=s[s.length-1];a&&a.role===i.role&&a.content===i.content||s.push(i)}this.allyMessages=s}}catch{}}async seedSessionWithAgentOutput(e,t,n){if(!this.client||!this.connected)return;this.handleOpenSidebar(t,{title:`Agent Output: ${e}`,filePath:null,mimeType:null});const s=t.match(/## Summary\n([\s\S]*?)(?=\n## |$)/),i=s?s[1].trim().split(`
1981
1981
  `).slice(0,3).join(`
1982
1982
  `):"Output available in sidebar.",a=[`Agent completed **${e}**.`,"",i,"","Full output is in the sidebar. What would you like to do?"].join(`
1983
1983
  `);try{const{sendChatMessage:o}=await _(async()=>{const{sendChatMessage:l}=await Promise.resolve().then(()=>fe);return{sendChatMessage:l}},void 0,import.meta.url);await o(this,a)}catch(o){console.error("[Session] Failed to seed session with agent output:",o)}}async handleMissionControlAddToQueue(e,t){if(!(!this.client||!this.connected))try{await this.client.request("queue.add",{type:e,title:t,priority:"normal"}),this.showToast("Added to queue","success",2e3)}catch{this.showToast("Failed to add to queue","error")}}removeQueuedMessage(e){Si(this,e)}async handleSendChat(e,t){await _i(this,e,t)}handleToggleSessionPicker(){this.sessionPickerOpen=!this.sessionPickerOpen}handleToggleSessionSearch(e){if(!this.sessionSearchOpen&&e){const n=e.currentTarget.getBoundingClientRect();this.sessionSearchPosition={top:n.bottom+8,right:window.innerWidth-n.right}}this.sessionSearchOpen=!this.sessionSearchOpen,this.sessionSearchOpen||(this.sessionSearchQuery="",this.sessionSearchResults=[])}async handleSessionSearchQuery(e){if(this.sessionSearchQuery=e,!e.trim()){this.sessionSearchResults=[];return}if(this.client){this.sessionSearchLoading=!0;try{const t=await this.client.request("sessions.searchContent",{query:e.trim(),limit:20});this.sessionSearchResults=t.results}catch(t){console.error("Session search failed:",t),this.sessionSearchResults=[]}finally{this.sessionSearchLoading=!1}}}handleSelectSession(e){this.sessionPickerOpen=!1,this.sessionSearchOpen=!1,this.sessionSearchQuery="",this.sessionSearchResults=[]}async handleWhatsAppStart(e){await no(this,e)}async handleWhatsAppWait(){await so(this)}async handleWhatsAppLogout(){await io(this)}async handleChannelConfigSave(){await ao(this)}async handleChannelConfigReload(){await oo(this)}async handleCompactChat(){if(!this.connected){this.showToast("Cannot compact: not connected","error");return}if(!this.sessionKey){this.showToast("Cannot compact: no active session","error");return}this.compactionStatus={active:!0,startedAt:Date.now(),completedAt:null};try{await this.handleSendChat("/compact")}catch(e){this.compactionStatus=null,console.error("Compaction failed:",e),this.showToast("Compaction failed","error")}}injectCompactionSummary(e,t){const n={role:"system",content:e,timestamp:Date.now(),isCompactionSummary:!0,keptMessages:t};this.chatMessages=[n,...this.chatMessages]}handleNostrProfileEdit(e,t){lo(this,e,t)}handleNostrProfileCancel(){co(this)}handleNostrProfileFieldChange(e,t){uo(this,e,t)}async handleNostrProfileSave(){await ho(this)}async handleNostrProfileImport(){await fo(this)}handleNostrProfileToggleAdvanced(){po(this)}async handleExecApprovalDecision(e){const t=this.execApprovalQueue[0];if(!(!t||!this.client||this.execApprovalBusy)){this.execApprovalBusy=!0,this.execApprovalError=null;try{await this.client.request("exec.approval.resolve",{id:t.id,decision:e}),this.execApprovalQueue=this.execApprovalQueue.filter(n=>n.id!==t.id)}catch(n){this.execApprovalError=`Exec approval failed: ${String(n)}`}finally{this.execApprovalBusy=!1}}}handleGatewayUrlConfirm(){const e=this.pendingGatewayUrl;e&&(this.pendingGatewayUrl=null,te(this,{...this.settings,gatewayUrl:e}),this.connect())}handleGatewayUrlCancel(){this.pendingGatewayUrl=null}handleGatewayRestartClick(){this.gatewayRestartPending=!0}async handleGatewayRestartConfirm(){if(!(!this.client||this.gatewayRestartBusy)){this.gatewayRestartBusy=!0;try{await this.client.request("godmode.gateway.restart")}catch{}finally{this.gatewayRestartBusy=!1,this.gatewayRestartPending=!1}}}handleGatewayRestartCancel(){this.gatewayRestartPending=!1}handleDeployPanelToggle(){this.deployPanelOpen=!this.deployPanelOpen}async handleDeployDismiss(){if(this.client){try{await this.client.request("godmode.deploy.dismiss")}catch{}this.deployPanelOpen=!1,this.updateStatus&&(this.updateStatus={...this.updateStatus,pendingDeploy:null})}}handleOpenSidebar(e,t={}){this.sidebarCloseTimer!=null&&(window.clearTimeout(this.sidebarCloseTimer),this.sidebarCloseTimer=null),this.sidebarContent=e,this.sidebarError=null,this.sidebarMimeType=t.mimeType?.trim()||null,this.sidebarFilePath=t.filePath?.trim()||null,this.sidebarTitle=t.title?.trim()||null,this.sidebarMode="resource",this.sidebarProofSlug=null,this.sidebarProofUrl=null,this.sidebarOpen=!0}handleCloseSidebar(){this.sidebarOpen=!1,this.showDrivePicker=!1,this.sidebarCloseTimer!=null&&window.clearTimeout(this.sidebarCloseTimer),this.sidebarCloseTimer=window.setTimeout(()=>{this.sidebarOpen||(this.sidebarContent=null,this.sidebarError=null,this.sidebarMimeType=null,this.sidebarFilePath=null,this.sidebarTitle=null,this.sidebarMode!=="proof"&&(this.sidebarMode="resource",this.sidebarProofSlug=null,this.sidebarProofUrl=null),this.sidebarCloseTimer=null)},200)}async handleOpenFile(e,t){if(!this.client||!this.connected){if(t){const s=e.split(".").pop()?.toLowerCase()??"",a={md:"text/markdown",markdown:"text/markdown",mdx:"text/markdown",json:"application/json",json5:"application/json",yaml:"text/yaml",yml:"text/yaml",csv:"text/csv",tsv:"text/tab-separated-values",html:"text/html",htm:"text/html"}[s]??null,o=e.split("/").pop()??e;this.showToast("Opening cached version (gateway offline)","warning"),this.handleOpenSidebar(t,{mimeType:a,filePath:e,title:o});return}this.showToast("Not connected to gateway","error");return}let n=e;if(!e.includes("/")&&!e.includes("\\")&&!e.startsWith("~"))try{n=(await this.client.request("files.resolve",{filename:e})).path}catch{}try{const s=await this.client.request("files.read",{path:n}),i=n.split(".").pop()?.toLowerCase()??"",o={md:"text/markdown",markdown:"text/markdown",mdx:"text/markdown",json:"application/json",json5:"application/json",yaml:"text/yaml",yml:"text/yaml",csv:"text/csv",tsv:"text/tab-separated-values",html:"text/html",htm:"text/html"}[i]??s.contentType??s.mime??null,l=n.split("/").pop()??n;this.handleOpenSidebar(s.content,{mimeType:o,filePath:n,title:l}),s.truncated&&this.showToast(`Opened truncated file: ${l}`,"warning")}catch(s){console.error("[Chat] Failed to open file via gateway:",s);const i=n.match(/\/inbox\/([^/]+)$/);if(i)try{const a=await fetch(`${this.basePath}/godmode/artifacts/${encodeURIComponent(i[1])}`);if(a.ok){const o=await a.text(),l=n.split(".").pop()?.toLowerCase()??"",m={md:"text/markdown",markdown:"text/markdown",mdx:"text/markdown",json:"application/json",yaml:"text/yaml",yml:"text/yaml",csv:"text/csv",html:"text/html",htm:"text/html"}[l]??a.headers.get("content-type")??null,r=n.split("/").pop()??n;this.handleOpenSidebar(o,{mimeType:m,filePath:n,title:r});return}}catch{}if(t){const a=e.split(".").pop()?.toLowerCase()??"",l={md:"text/markdown",markdown:"text/markdown",mdx:"text/markdown",json:"application/json",yaml:"text/yaml",yml:"text/yaml",csv:"text/csv",html:"text/html",htm:"text/html"}[a]??null,c=e.split("/").pop()??e;this.showToast("Opening cached version (file read failed)","warning"),this.handleOpenSidebar(t,{mimeType:l,filePath:e,title:c});return}this.showToast(`Failed to open file: ${e}`,"error")}}async handleToggleDrivePicker(){if(this.showDrivePicker){this.showDrivePicker=!1;return}if(this.driveAccounts.length===0)try{const e=await this.client?.request("files.listDriveAccounts",{});this.driveAccounts=e?.accounts??[]}catch{this.driveAccounts=[]}this.showDrivePicker=!0}async handlePushToDrive(e,t){if(!this.driveUploading){if(this.showDrivePicker=!1,this._pendingBatchPaths&&this._pendingBatchPaths.length>0){const n=this._pendingBatchPaths;this._pendingBatchPaths=void 0,await this._executeBatchDrive(n,t);return}this.driveUploading=!0;try{const n={filePath:e};t&&(n.account=t);const s=await this.client?.request("files.pushToDrive",n),i=t?` to ${t.split("@")[0]}`:"",a=s?.message??`Uploaded${i} to Google Drive`,o=s?.driveUrl;this.showToast(a,"success",o?8e3:5e3,o?{label:"View in Drive",url:o}:void 0)}catch(n){console.error("Push to Drive failed:",n);const s=n instanceof Error?n.message:typeof n=="object"&&n!==null&&"message"in n?String(n.message):"Unknown error";s.includes("GOG_NOT_FOUND")||s.includes("gog CLI not found")?this.showToast("Google Drive not configured. Install gog CLI: npm install -g gog-cli, then run: gog auth add <email> --services drive","warning",1e4):s.includes("GOG_AUTH")||s.includes("auth")&&s.includes("expired")?this.showToast("Google Drive auth expired. Re-authenticate: gog auth add <email> --services drive","warning",8e3):this.showToast(`Drive upload failed: ${s}`,"error",8e3)}finally{this.driveUploading=!1}}}async handleBatchPushToDrive(e){if(this.driveUploading||e.length===0)return;if(!this.driveAccounts||this.driveAccounts.length===0)try{const n=await this.client?.request("files.listDriveAccounts");this.driveAccounts=n?.accounts??[]}catch{}if(this.driveAccounts&&this.driveAccounts.length>1){this._pendingBatchPaths=e,this.showDrivePicker=!0;return}const t=this.driveAccounts?.[0]?.email;await this._executeBatchDrive(e,t)}async _executeBatchDrive(e,t){this.driveUploading=!0,this.showToast(`Uploading ${e.length} files to Drive...`,"info",0);try{const n={filePaths:e};t&&(n.account=t);const s=await this.client?.request("files.batchPushToDrive",n);this.dismissAllToasts();const i=s?.results?.filter(o=>o.success).length??0,a=s?.results?.length??e.length;i===a?this.showToast(`Uploaded ${i} files to Google Drive`,"success",5e3):this.showToast(`Uploaded ${i}/${a} files (${a-i} failed)`,"warning",8e3)}catch(n){this.dismissAllToasts();const s=n instanceof Error?n.message:"Unknown error";this.showToast(`Batch Drive upload failed: ${s}`,"error",8e3)}finally{this.driveUploading=!1,this._pendingBatchPaths=void 0}}handleSplitRatioChange(e){const t=Math.max(.4,Math.min(.7,e));this.splitRatio=t,this.applySettings({...this.settings,splitRatio:t})}handleImageClick(e,t,n){this.lightbox=qd(e,t,n)}handleLightboxClose(){this.lightbox=Bd()}handleLightboxNav(e){this.lightbox=jd(this.lightbox,e)}normalizeWorkspacePathCandidate(e,t={}){let n=e.trim();if(!n||n.startsWith("#"))return null;for(;n.startsWith("./");)n=n.slice(2);if(n=n.replaceAll("\\","/"),!t.allowAbsolute)for(;n.startsWith("/");)n=n.slice(1);return!n||n.includes("\0")?null:n}isAbsoluteFilesystemPath(e){return e.startsWith("/")||e.startsWith("~/")||/^[a-z]:[\\/]/i.test(e)}inferMimeTypeFromPath(e){if(!e)return null;const t=e.trim().toLowerCase();if(!t)return null;const n=t.split(".").pop()??"";return n?n==="md"||n==="markdown"||n==="mdx"?"text/markdown":n==="html"||n==="htm"?"text/html":n==="json"||n==="json5"?"application/json":n==="txt"||n==="text"||n==="log"?"text/plain":n==="svg"||n==="svgz"?"image/svg+xml":n==="avif"||n==="bmp"||n==="gif"||n==="heic"||n==="heif"||n==="jpeg"||n==="jpg"||n==="png"||n==="webp"?`image/${n==="jpg"?"jpeg":n}`:null:null}sidebarTitleForPath(e){const t=e.replaceAll("\\","/").trim();if(!t)return"Document";const n=t.split("/");return n[n.length-1]||t}async listWorkspaceIdsForPathResolution(){const e=[],t=new Set,n=s=>{if(typeof s!="string")return;const i=s.trim();!i||t.has(i)||(t.add(i),e.push(i))};n(this.selectedWorkspace?.id);for(const s of this.workspaces??[])n(s.id);if(e.length>0||!this.client||!this.connected)return e;try{const s=await this.client.request("workspaces.list",{});for(const i of s.workspaces??[])n(i.id)}catch{}return e}async openWorkspaceRelativeFileInViewer(e){if(!this.client||!this.connected)return!1;const t=await this.listWorkspaceIdsForPathResolution();for(const n of t)try{const s=await this.client.request("workspaces.readFile",{workspaceId:n,filePath:e});if(typeof s.content!="string")continue;return this.handleOpenSidebar(s.content,{mimeType:s.contentType??s.mime??this.inferMimeTypeFromPath(e),filePath:s.path??e,title:this.sidebarTitleForPath(e)}),!0}catch{}return!1}extractWorkspacePathCandidatesFromHref(e){const t=e.trim();if(!t)return[];const n=[],s=t.toLowerCase();if(s.startsWith("mailto:")||s.startsWith("tel:")||s.startsWith("javascript:")||s.startsWith("data:"))return[];if(t.startsWith("godmode-file://")){let m=t.slice(15);try{m=decodeURIComponent(m)}catch{}return n.push(m),n}if(t.startsWith("file://")){let m=t.slice(7);m.startsWith("/~/")&&(m="~"+m.slice(2));try{m=decodeURIComponent(m)}catch{}n.push(m);const r=[],p=new Set;for(const g of n){const y=this.normalizeWorkspacePathCandidate(g,{allowAbsolute:!0});!y||p.has(y)||(p.add(y),r.push(y))}return r}const i=/^[a-z][a-z0-9+.-]*:/i.test(t),a=/^[a-z]:[\\/]/i.test(t);(!i||a)&&n.push(t);let o=null;try{o=new URL(t,window.location.href)}catch{o=null}if(o&&/^https?:$/.test(o.protocol)&&o.origin===window.location.origin){for(const b of yu){const A=o.searchParams.get(b);A&&n.push(A)}const r=(t.split("#")[0]??"").split("?")[0]??"";r.length>0&&!r.startsWith("/")&&!r.includes("://")&&n.push(r);let g=o.pathname;this.basePath&&g.startsWith(`${this.basePath}/`)?g=g.slice(this.basePath.length):this.basePath&&g===this.basePath&&(g="");const y=g.startsWith("/")?g.slice(1):g;if(y){n.push(y);const b=y.indexOf("/");if(b>0){const A=y.slice(0,b).toLowerCase();ns.has(A)&&n.push(y.slice(b+1))}}if(g.startsWith("/")&&y){const b=y.split("/")[0]?.toLowerCase()??"";ns.has(b)||n.push(g)}}const l=[],c=new Set;for(const m of n){let r=m;try{r=decodeURIComponent(m)}catch{}const p=this.normalizeWorkspacePathCandidate(r,{allowAbsolute:!0});!p||c.has(p)||(c.add(p),l.push(p))}return l}async openWorkspaceFileInViewer(e){if(!this.client||!this.connected)return!1;const t=this.isAbsoluteFilesystemPath(e);if(!t&&await this.openWorkspaceRelativeFileInViewer(e))return!0;try{const n=await this.client.request("workspaces.readFile",{path:e});if(typeof n.content=="string")return this.handleOpenSidebar(n.content,{mimeType:n.contentType??n.mime??this.inferMimeTypeFromPath(e),filePath:n.path??e,title:this.sidebarTitleForPath(e)}),!0}catch{}if(!t)return!1;try{const n=await this.client.request("files.read",{path:e,maxSize:1e6});return typeof n.content!="string"?!1:(this.handleOpenSidebar(n.content,{mimeType:this.inferMimeTypeFromPath(e),filePath:e,title:this.sidebarTitleForPath(e)}),!0)}catch{return!1}}async handleOpenMessageFileLink(e){const t=this.extractWorkspacePathCandidatesFromHref(e);if(t.length===0)return!1;for(const n of t)if(await this.openWorkspaceFileInViewer(n))return!0;return!1}showToast(e,t="info",n=5e3,s){const i=du(e,t,n,s);this.toasts=pu(this.toasts,i),n>0&&window.setTimeout(()=>{this.dismissToast(i.id)},n)}dismissToast(e){this.toasts=uu(this.toasts,e)}dismissAllToasts(){this.toasts=[]}handlePrivateModeToggle(){if(this.chatPrivateMode){const e=this.sessionKey;this.chatPrivateMode=!1,this._destroyPrivateSession(e),this.showToast("Private session destroyed","info",2e3);return}this.chatPrivateMode=!0,this.setTab("chat"),_(async()=>{const{createNewSession:e}=await Promise.resolve().then(()=>ot);return{createNewSession:e}},void 0,import.meta.url).then(({createNewSession:e})=>{e(this);const t=Date.now()+1440*60*1e3;this.privateSessions=new Map(this.privateSessions).set(this.sessionKey,t),this._persistPrivateSessions(),this._startPrivateSessionTimer(),this.client&&this.connected&&this.client.request("session.setPrivate",{sessionKey:this.sessionKey,enabled:!0}).catch(()=>{}),this.chatMessages=[{role:"assistant",content:`This is a **private session**. Nothing will be saved to memory or logs.
1984
1984
 
1985
- This session self-destructs when you close it or in **24 hours** — whichever comes first.`,timestamp:Date.now()}],this.requestUpdate()}),this.showToast("Private session created — 24h countdown started","info",3e3)}async _destroyPrivateSession(e){const t=new Map(this.privateSessions);if(t.delete(e),this.privateSessions=t,this._persistPrivateSessions(),this.sessionKey===e){this.chatPrivateMode=!1;const n=this.settings.openTabs.filter(a=>a!==e),s=n[0]||O;this.applySettings({...this.settings,openTabs:n,sessionKey:s,lastActiveSessionKey:s}),this.sessionKey=s,await(await _(async()=>{const{loadChatHistory:a}=await Promise.resolve().then(()=>fe);return{loadChatHistory:a}},void 0,import.meta.url)).loadChatHistory(this);const{scheduleChatScroll:i}=await _(async()=>{const{scheduleChatScroll:a}=await Promise.resolve().then(()=>go);return{scheduleChatScroll:a}},void 0,import.meta.url);i(this,!0)}else this.applySettings({...this.settings,openTabs:this.settings.openTabs.filter(n=>n!==e)});this.client&&this.connected&&(this.client.request("session.setPrivate",{sessionKey:e,enabled:!1}).catch(()=>{}),this.client.request("sessions.delete",{key:e,deleteTranscript:!0}).catch(()=>{})),this.privateSessions.size===0&&this._stopPrivateSessionTimer()}_persistPrivateSessions(){const e=Array.from(this.privateSessions.entries());e.length===0?localStorage.removeItem("godmode.privateSessions"):localStorage.setItem("godmode.privateSessions",JSON.stringify(e))}_restorePrivateSessions(){try{const e=localStorage.getItem("godmode.privateSessions");if(!e)return;const t=JSON.parse(e),n=Date.now(),s=t.filter(([,i])=>i>n);if(this.privateSessions=new Map(s),s.length!==t.length){const i=t.filter(([,a])=>a<=n);for(const[a]of i)this._destroyPrivateSession(a)}this.privateSessions.size>0&&(this.privateSessions.has(this.sessionKey)&&(this.chatPrivateMode=!0),this._startPrivateSessionTimer()),this._persistPrivateSessions()}catch{localStorage.removeItem("godmode.privateSessions")}}_startPrivateSessionTimer(){this._privateSessionTimer||(this._privateSessionTimer=setInterval(()=>{const e=Date.now();for(const[t,n]of this.privateSessions)n<=e&&(this._destroyPrivateSession(t),this.showToast("Private session expired and was destroyed","info",3e3));this.privateSessions.size>0&&this.requestUpdate()},3e4))}_stopPrivateSessionTimer(){this._privateSessionTimer&&(clearInterval(this._privateSessionTimer),this._privateSessionTimer=null)}handleResourceClick(e){e.path?this.handleWorkFileClick(e.path):e.url&&window.open(e.url,"_blank","noopener,noreferrer")}async loadSessionResources(){if(!(!this.client||!this.connected))try{const t=(await this.client.request("resources.list",{sessionKey:this.sessionKey,limit:20})).resources??[],n=new Set(t.filter(s=>s.proofSlug).map(s=>s.proofSlug));if(this.chatMessages?.length)for(const s of this.chatMessages){const i=s,a=Array.isArray(i.content)?i.content:[];for(const o of a){const l=typeof o.text=="string"?o.text:typeof o.content=="string"?o.content:null;if(l)try{const c=JSON.parse(l);c._sidebarAction?.type==="proof"&&c._sidebarAction.slug&&!n.has(c._sidebarAction.slug)&&(n.add(c._sidebarAction.slug),t.unshift({id:`proof:${c._sidebarAction.slug}`,title:c.title??"Proof Document",type:"doc",path:c.filePath,sessionKey:this.sessionKey,proofSlug:c._sidebarAction.slug}))}catch{}}}this.sessionResources=t}catch(e){console.warn("[SessionResources] load failed:",e),this.sessionResources=[]}}handleSessionResourceClick(e){e.proofSlug?this.handleOpenProofDoc(e.proofSlug):e.path?this.handleOpenFile(e.path):e.url&&window.open(e.url,"_blank","noopener,noreferrer")}handleToggleSessionResources(){this.sessionResourcesCollapsed=!this.sessionResourcesCollapsed}handleViewAllResources(){this.setTab("work")}async handleWorkFileClick(e){if(!this.client||!this.connected){this.showToast("Not connected to gateway","error");return}try{const t=await this.client.request("workspaces.readFile",{path:e});if(!t.content){this.showToast(t.error??"Failed to read file","error");return}this.handleOpenSidebar(t.content,{mimeType:t.contentType??t.mime??this.inferMimeTypeFromPath(e),filePath:t.path??e,title:this.sidebarTitleForPath(e)})}catch(t){console.error("[Work] Failed to read file:",t),this.showToast(`Failed to open: ${e}`,"error")}}handleWorkSkillClick(e,t){this.handleStartChatWithPrompt(`Tell me about the "${e}" skill and how it's used in the ${t} project.`)}handlePeopleImport(e){const t=e==="apple"?"Import my contacts from Apple Contacts and organize them into categories.":"Import my contacts from Google Contacts and organize them into categories.";this.handleStartChatWithPrompt(t)}handleOnboardingStart(){this.onboardingPhase=1,this.onboardingData&&(this.onboardingData={...this.onboardingData,phase:1}),this.client?.request("onboarding.update",{phase:1,completePhase:0})}async handleOnboardingIdentitySubmit(e){if(this.client)try{await this.client.request("onboarding.update",{phase:2,completePhase:1,identity:e}),this.onboardingPhase=2,this.onboardingData&&(this.onboardingData={...this.onboardingData,phase:2,identity:e}),this.userName=e.name,this.userAvatar=e.emoji,this.applySettings({...this.settings,userName:e.name,userAvatar:e.emoji}),this.setTab("chat"),_(async()=>{const{createNewSession:t}=await Promise.resolve().then(()=>ot);return{createNewSession:t}},void 0,import.meta.url).then(({createNewSession:t})=>{t(this);const n=`I just set up my GodMode identity. My name is ${e.name}${e.mission?` and my mission is: ${e.mission}`:""}. Let's set up my workspace.`;this.chatMessage=n,this.handleSendChat(n)})}catch(t){console.error("[Onboarding] Identity submit failed:",t),this.showToast("Failed to save identity","error")}}handleOnboardingSkipPhase(){if(!this.client)return;const e=Math.min(this.onboardingPhase+1,6);this.onboardingPhase=e,this.client.request("onboarding.update",{phase:e,completePhase:this.onboardingPhase})}handleOnboardingComplete(){this.onboardingActive=!1,this.onboardingPhase=6,this.onboardingData&&(this.onboardingData={...this.onboardingData,phase:6,completedAt:new Date().toISOString()}),this.client?.request("onboarding.complete",{summary:this.onboardingData?.summary??null}),this.showToast("Welcome to GodMode!","success",4e3)}handleStartChatWithPrompt(e){this.setTab("chat"),_(async()=>{const{createNewSession:t}=await Promise.resolve().then(()=>ot);return{createNewSession:t}},void 0,import.meta.url).then(({createNewSession:t})=>{t(this),this.chatMessage=e,this.requestUpdate()})}handleOpenSupportChat(){const e="agent:main:support";if(this.sessionKey===e){this.setTab("chat");return}_(async()=>{const{saveDraft:s}=await Promise.resolve().then(()=>tc);return{saveDraft:s}},void 0,import.meta.url).then(({saveDraft:s})=>s(this));const n=this.settings.openTabs.includes(e)?this.settings.openTabs:[...this.settings.openTabs,e];this.applySettings({...this.settings,openTabs:n,sessionKey:e,lastActiveSessionKey:e,tabLastViewed:{...this.settings.tabLastViewed,[e]:Date.now()}}),this.sessionKey=e,this.setTab("chat"),this.chatMessages=[],this.chatStream=null,this.chatStreamStartedAt=null,this.chatRunId=null,this.resetToolStream(),this.resetChatScroll(),this.loadAssistantIdentity(),_(async()=>{const{autoTitleCache:s}=await import("./ctrl-settings-niym-WgY.js").then(i=>i.ad);return{autoTitleCache:s}},[],import.meta.url).then(({autoTitleCache:s})=>{s.set(e,"Support")}),_(async()=>{const{loadChatHistory:s}=await Promise.resolve().then(()=>fe);return{loadChatHistory:s}},void 0,import.meta.url).then(({loadChatHistory:s})=>{s(this).then(()=>{this.loadSessionResources(),this.chatMessages.length===0&&this.sessionKey===e&&(this.chatMessages=[{role:"assistant",content:`**Welcome to GodMode Support**
1985
+ This session self-destructs when you close it or in **24 hours** — whichever comes first.`,timestamp:Date.now()}],this.requestUpdate()}),this.showToast("Private session created — 24h countdown started","info",3e3)}async _destroyPrivateSession(e){const t=new Map(this.privateSessions);if(t.delete(e),this.privateSessions=t,this._persistPrivateSessions(),this.sessionKey===e){this.chatPrivateMode=!1;const n=this.settings.openTabs.filter(a=>a!==e),s=n[0]||O;this.applySettings({...this.settings,openTabs:n,sessionKey:s,lastActiveSessionKey:s}),this.sessionKey=s,await(await _(async()=>{const{loadChatHistory:a}=await Promise.resolve().then(()=>fe);return{loadChatHistory:a}},void 0,import.meta.url)).loadChatHistory(this);const{scheduleChatScroll:i}=await _(async()=>{const{scheduleChatScroll:a}=await Promise.resolve().then(()=>go);return{scheduleChatScroll:a}},void 0,import.meta.url);i(this,!0)}else this.applySettings({...this.settings,openTabs:this.settings.openTabs.filter(n=>n!==e)});this.client&&this.connected&&(this.client.request("session.setPrivate",{sessionKey:e,enabled:!1}).catch(()=>{}),this.client.request("sessions.delete",{key:e,deleteTranscript:!0}).catch(()=>{})),this.privateSessions.size===0&&this._stopPrivateSessionTimer()}_persistPrivateSessions(){const e=Array.from(this.privateSessions.entries());e.length===0?localStorage.removeItem("godmode.privateSessions"):localStorage.setItem("godmode.privateSessions",JSON.stringify(e))}_restorePrivateSessions(){try{const e=localStorage.getItem("godmode.privateSessions");if(!e)return;const t=JSON.parse(e),n=Date.now(),s=t.filter(([,i])=>i>n);if(this.privateSessions=new Map(s),s.length!==t.length){const i=t.filter(([,a])=>a<=n);for(const[a]of i)this._destroyPrivateSession(a)}this.privateSessions.size>0&&(this.privateSessions.has(this.sessionKey)&&(this.chatPrivateMode=!0),this._startPrivateSessionTimer()),this._persistPrivateSessions()}catch{localStorage.removeItem("godmode.privateSessions")}}_startPrivateSessionTimer(){this._privateSessionTimer||(this._privateSessionTimer=setInterval(()=>{const e=Date.now();for(const[t,n]of this.privateSessions)n<=e&&(this._destroyPrivateSession(t),this.showToast("Private session expired and was destroyed","info",3e3));this.privateSessions.size>0&&this.requestUpdate()},3e4))}_stopPrivateSessionTimer(){this._privateSessionTimer&&(clearInterval(this._privateSessionTimer),this._privateSessionTimer=null)}handleResourceClick(e){e.path?this.handleWorkFileClick(e.path):e.url&&window.open(e.url,"_blank","noopener,noreferrer")}async loadSessionResources(){if(!(!this.client||!this.connected))try{const t=(await this.client.request("resources.list",{sessionKey:this.sessionKey,limit:20})).resources??[],n=new Set(t.filter(s=>s.proofSlug).map(s=>s.proofSlug));if(this.chatMessages?.length)for(const s of this.chatMessages){const i=s,a=Array.isArray(i.content)?i.content:[];for(const o of a){const l=typeof o.text=="string"?o.text:typeof o.content=="string"?o.content:null;if(l)try{const c=JSON.parse(l);c._sidebarAction?.type==="proof"&&c._sidebarAction.slug&&!n.has(c._sidebarAction.slug)&&(n.add(c._sidebarAction.slug),t.unshift({id:`proof:${c._sidebarAction.slug}`,title:c.title??"Proof Document",type:"doc",path:c.filePath,sessionKey:this.sessionKey,proofSlug:c._sidebarAction.slug}))}catch{}}}this.sessionResources=t}catch(e){console.warn("[SessionResources] load failed:",e),this.sessionResources=[]}}handleSessionResourceClick(e){e.proofSlug?this.handleOpenProofDoc(e.proofSlug):e.path?this.handleOpenFile(e.path):e.url&&window.open(e.url,"_blank","noopener,noreferrer")}handleToggleSessionResources(){this.sessionResourcesCollapsed=!this.sessionResourcesCollapsed}handleViewAllResources(){this.setTab("work")}async handleWorkFileClick(e){if(!this.client||!this.connected){this.showToast("Not connected to gateway","error");return}try{const t=await this.client.request("workspaces.readFile",{path:e});if(!t.content){this.showToast(t.error??"Failed to read file","error");return}this.handleOpenSidebar(t.content,{mimeType:t.contentType??t.mime??this.inferMimeTypeFromPath(e),filePath:t.path??e,title:this.sidebarTitleForPath(e)})}catch(t){console.error("[Work] Failed to read file:",t),this.showToast(`Failed to open: ${e}`,"error")}}handleWorkSkillClick(e,t){this.handleStartChatWithPrompt(`Tell me about the "${e}" skill and how it's used in the ${t} project.`)}handlePeopleImport(e){const t=e==="apple"?"Import my contacts from Apple Contacts and organize them into categories.":"Import my contacts from Google Contacts and organize them into categories.";this.handleStartChatWithPrompt(t)}handleOnboardingStart(){this.onboardingPhase=1,this.onboardingData&&(this.onboardingData={...this.onboardingData,phase:1}),this.client?.request("onboarding.update",{phase:1,completePhase:0})}async handleOnboardingIdentitySubmit(e){if(this.client)try{await this.client.request("onboarding.update",{phase:2,completePhase:1,identity:e}),this.onboardingPhase=2,this.onboardingData&&(this.onboardingData={...this.onboardingData,phase:2,identity:e}),this.userName=e.name,this.userAvatar=e.emoji,this.applySettings({...this.settings,userName:e.name,userAvatar:e.emoji}),this.setTab("chat"),_(async()=>{const{createNewSession:t}=await Promise.resolve().then(()=>ot);return{createNewSession:t}},void 0,import.meta.url).then(({createNewSession:t})=>{t(this);const n=`I just set up my GodMode identity. My name is ${e.name}${e.mission?` and my mission is: ${e.mission}`:""}. Let's set up my workspace.`;this.chatMessage=n,this.handleSendChat(n)})}catch(t){console.error("[Onboarding] Identity submit failed:",t),this.showToast("Failed to save identity","error")}}handleOnboardingSkipPhase(){if(!this.client)return;const e=Math.min(this.onboardingPhase+1,6);this.onboardingPhase=e,this.client.request("onboarding.update",{phase:e,completePhase:this.onboardingPhase})}handleOnboardingComplete(){this.onboardingActive=!1,this.onboardingPhase=6,this.onboardingData&&(this.onboardingData={...this.onboardingData,phase:6,completedAt:new Date().toISOString()}),this.client?.request("onboarding.complete",{summary:this.onboardingData?.summary??null}),this.showToast("Welcome to GodMode!","success",4e3)}handleStartChatWithPrompt(e){this.setTab("chat"),_(async()=>{const{createNewSession:t}=await Promise.resolve().then(()=>ot);return{createNewSession:t}},void 0,import.meta.url).then(({createNewSession:t})=>{t(this),this.chatMessage=e,this.requestUpdate()})}handleOpenSupportChat(){const e="agent:main:support";if(this.sessionKey===e){this.setTab("chat");return}_(async()=>{const{saveDraft:s}=await Promise.resolve().then(()=>tc);return{saveDraft:s}},void 0,import.meta.url).then(({saveDraft:s})=>s(this));const n=this.settings.openTabs.includes(e)?this.settings.openTabs:[...this.settings.openTabs,e];this.applySettings({...this.settings,openTabs:n,sessionKey:e,lastActiveSessionKey:e,tabLastViewed:{...this.settings.tabLastViewed,[e]:Date.now()}}),this.sessionKey=e,this.setTab("chat"),this.chatMessages=[],this.chatStream=null,this.chatStreamStartedAt=null,this.chatRunId=null,this.resetToolStream(),this.resetChatScroll(),this.loadAssistantIdentity(),_(async()=>{const{autoTitleCache:s}=await import("./ctrl-settings-COfcdhha.js").then(i=>i.ad);return{autoTitleCache:s}},[],import.meta.url).then(({autoTitleCache:s})=>{s.set(e,"Support")}),_(async()=>{const{loadChatHistory:s}=await Promise.resolve().then(()=>fe);return{loadChatHistory:s}},void 0,import.meta.url).then(({loadChatHistory:s})=>{s(this).then(()=>{this.loadSessionResources(),this.chatMessages.length===0&&this.sessionKey===e&&(this.chatMessages=[{role:"assistant",content:`**Welcome to GodMode Support**
1986
1986
 
1987
1987
  I have full access to your system diagnostics and GodMode knowledge base. I can help with:
1988
1988
 
@@ -1991,4 +1991,4 @@ I have full access to your system diagnostics and GodMode knowledge base. I can
1991
1991
  - Setup guidance
1992
1992
  - Escalation to the team if needed
1993
1993
 
1994
- What can I help you with?`,timestamp:Date.now()}],this.requestUpdate())}).catch(i=>{console.error("[Support] Failed to load chat history:",i)})})}handleWizardOpen(){_(async()=>{const{emptyWizardState:e}=await import("./views-settings-nvLQdpIB.js").then(t=>t.I);return{emptyWizardState:e}},__vite__mapDeps([4,1,3,5]),import.meta.url).then(({emptyWizardState:e})=>{this.wizardState=e(),this.wizardActive=!0,this.requestUpdate()})}handleWizardClose(){this.wizardActive=!1,this.wizardState=null,this.requestUpdate()}handleWizardStepChange(e){this.wizardState&&(this.wizardState={...this.wizardState,step:e},this.requestUpdate())}handleWizardAnswerChange(e,t){this.wizardState&&(this.wizardState={...this.wizardState,answers:{...this.wizardState.answers,[e]:t}},this.requestUpdate())}async handleWizardPreview(){if(!(!this.client||!this.wizardState))try{const[e,t]=await Promise.all([this.client.request("onboarding.wizard.preview",this.wizardState.answers),this.client.request("onboarding.wizard.diff",this.wizardState.answers).catch(()=>null)]),n={};for(const i of e.files??[])n[i.path]=i.wouldCreate;const s={};if(t){for(const i of t.additions)s[i.path]=!0;for(const i of t.changes)s[i.path]=!1}this.wizardState={...this.wizardState,preview:e.files??[],diff:t,fileSelections:n,configSelections:s},this.requestUpdate()}catch(e){console.error("[Wizard] Preview failed:",e)}}handleWizardFileToggle(e,t){this.wizardState&&(this.wizardState={...this.wizardState,fileSelections:{...this.wizardState.fileSelections,[e]:t}},this.requestUpdate())}handleWizardConfigToggle(e,t){this.wizardState&&(this.wizardState={...this.wizardState,configSelections:{...this.wizardState.configSelections,[e]:t}},this.requestUpdate())}async handleWizardGenerate(){if(!this.client||!this.wizardState)return;this.wizardState={...this.wizardState,generating:!0,error:null},this.requestUpdate();const e=[];for(const[n,s]of Object.entries(this.wizardState.fileSelections))s||e.push(n);const t=[];for(const[n,s]of Object.entries(this.wizardState.configSelections))s||t.push(n);try{const n=await this.client.request("onboarding.wizard.generate",{...this.wizardState.answers,skipFiles:e,skipKeys:t});this.wizardState={...this.wizardState,generating:!1,step:9,result:{filesCreated:n.filesCreated,filesSkipped:n.filesSkipped,configPatched:n.configPatched,workspacePath:n.workspacePath}},this.requestUpdate(),this.showToast("Memory system generated!","success",4e3)}catch(n){const s=n instanceof Error?n.message:"Failed to generate workspace";this.wizardState={...this.wizardState,generating:!1,error:s},this.requestUpdate(),this.showToast(s,"error")}}async handleQuickSetup(e){_(()=>import("./setup-BnLadXY9.js"),[],import.meta.url).then(async({quickSetup:t})=>{await t(this,e)&&(this.setTab("chat"),_(async()=>{const{loadCapabilities:s}=await import("./setup-BnLadXY9.js");return{loadCapabilities:s}},[],import.meta.url).then(({loadCapabilities:s})=>s(this)))})}handleLoadCapabilities(){_(async()=>{const{loadCapabilities:e}=await import("./setup-BnLadXY9.js");return{loadCapabilities:e}},[],import.meta.url).then(({loadCapabilities:e})=>e(this))}handleCapabilityAction(e){_(async()=>{const{capabilityAction:t}=await import("./setup-BnLadXY9.js");return{capabilityAction:t}},[],import.meta.url).then(({capabilityAction:t})=>t(this,e))}handleHideSetup(){_(async()=>{const{hideSetup:e}=await import("./setup-BnLadXY9.js");return{hideSetup:e}},[],import.meta.url).then(({hideSetup:e})=>e(this))}handleRunAssessment(){this.client&&this.client.request("onboarding.assess",{}).then(()=>{this.handleLoadCapabilities()})}continueSetup(){const e=this.setupProgress?.currentStep??"welcome";this._navigateToSetupStep(e)}dismissSetup(){this.setupBarDismissed=!0,_(async()=>{const{dismissSetupBar:e}=await import("./setup-BnLadXY9.js");return{dismissSetupBar:e}},[],import.meta.url).then(({dismissSetupBar:e})=>e(this))}handleSetupStepClick(e){this._navigateToSetupStep(e)}async loadSetupProgress(){await(await _(()=>import("./setup-BnLadXY9.js"),[],import.meta.url)).loadSetupProgress(this)}_navigateToSetupStep(e){const n={welcome:"Let's get started! What should I call you?","api-key":"Help me connect my Anthropic API key so you can work at full power.",memory:"Help me set up persistent memory with Honcho so you remember our conversations.",integrations:"Help me connect my tools via Composio — starting with Google and GitHub.",screenpipe:"Help me set up Screenpipe for ambient screen and audio recall.","second-brain":"Help me link my Obsidian vault to my Memory."}[e]??"Help me continue setting up GodMode.";this.handleStartChatWithPrompt(n)}handleUpdateUserProfile(e,t){const n=e.trim().slice(0,50),s=t.trim();this.userName=n||"You",this.userAvatar=s||null,this.applySettings({...this.settings,userName:n,userAvatar:s})}async handleLoadIntegrations(){await(await _(()=>import("./onboarding-setup-eq3R6nNk.js"),[],import.meta.url)).loadIntegrations(this)}handleExpandCard(e){_(()=>import("./onboarding-setup-eq3R6nNk.js"),[],import.meta.url).then(t=>t.expandCard(this,e))}async handleLoadGuide(e){await(await _(()=>import("./onboarding-setup-eq3R6nNk.js"),[],import.meta.url)).loadGuide(this,e)}async handleTestIntegration(e){await(await _(()=>import("./onboarding-setup-eq3R6nNk.js"),[],import.meta.url)).testIntegration(this,e)}async handleConfigureIntegration(e,t){await(await _(()=>import("./onboarding-setup-eq3R6nNk.js"),[],import.meta.url)).configureIntegration(this,e,t)}handleUpdateConfigValue(e,t){this.onboardingConfigValues={...this.onboardingConfigValues,[e]:t}}handleSkipIntegration(e){_(()=>import("./onboarding-setup-eq3R6nNk.js"),[],import.meta.url).then(t=>t.skipIntegration(this,e))}async handleMarkOnboardingComplete(){if(!(!this.client||!this.connected))try{await this.client.request("onboarding.complete",{}),this.showSetupTab=!1,this.setTab("chat")}catch(e){console.error("[onboarding] Failed to mark complete:",e)}}async handleOpenProofDoc(e){let t="Proof Document",n=null,s=null;if(this.client&&this.connected)try{const i=await this.client.request("proof.get",{slug:e});t=i.title?.trim()||t,n=i.filePath?.trim()||null,s=i.viewUrl?.trim()||null}catch(i){console.warn("[Proof] Failed to resolve document metadata:",i)}this.sidebarOpen=!0,this.sidebarMode="proof",this.sidebarProofSlug=e,this.sidebarProofUrl=s,this.sidebarProofHtml=null,this.sidebarFilePath=n,this.sidebarTitle=t}handleCloseProofDoc(){this.sidebarMode="resource",this.sidebarProofSlug=null,this.sidebarProofUrl=null,this.sidebarProofHtml=null,this.handleCloseSidebar()}render(){return su(this)}};h([$a({context:Xa}),f()],u.prototype,"_ctx",2);h([f()],u.prototype,"settings",2);h([f()],u.prototype,"password",2);h([f()],u.prototype,"tab",2);h([f()],u.prototype,"onboarding",2);h([f()],u.prototype,"connected",2);h([f()],u.prototype,"reconnecting",2);h([f()],u.prototype,"reconnectAttempt",2);h([f()],u.prototype,"theme",2);h([f()],u.prototype,"themeResolved",2);h([f()],u.prototype,"hello",2);h([f()],u.prototype,"lastError",2);h([f()],u.prototype,"eventLog",2);h([f()],u.prototype,"assistantName",2);h([f()],u.prototype,"assistantAvatar",2);h([f()],u.prototype,"assistantAgentId",2);h([f()],u.prototype,"userName",2);h([f()],u.prototype,"userAvatar",2);h([f()],u.prototype,"currentModel",2);h([f()],u.prototype,"availableModels",2);h([f()],u.prototype,"modelPickerOpen",2);h([f()],u.prototype,"modelCacheTs",2);h([f()],u.prototype,"sessionKey",2);h([f()],u.prototype,"sessionPickerOpen",2);h([f()],u.prototype,"sessionPickerPosition",2);h([f()],u.prototype,"sessionPickerSearch",2);h([f()],u.prototype,"sessionSearchOpen",2);h([f()],u.prototype,"sessionSearchPosition",2);h([f()],u.prototype,"sessionSearchQuery",2);h([f()],u.prototype,"sessionSearchResults",2);h([f()],u.prototype,"sessionSearchLoading",2);h([f()],u.prototype,"profilePopoverOpen",2);h([f()],u.prototype,"profileEditName",2);h([f()],u.prototype,"profileEditAvatar",2);h([f()],u.prototype,"editingTabKey",2);h([f()],u.prototype,"navDrawerOpen",2);h([f()],u.prototype,"chatLoading",2);h([f()],u.prototype,"chatSending",2);h([f()],u.prototype,"chatSendingSessionKey",2);h([f()],u.prototype,"chatMessage",2);h([f()],u.prototype,"chatDrafts",2);h([f()],u.prototype,"chatMessages",2);h([f()],u.prototype,"chatToolMessages",2);h([f()],u.prototype,"chatStream",2);h([f()],u.prototype,"chatStreamStartedAt",2);h([f()],u.prototype,"chatRunId",2);h([f()],u.prototype,"currentToolName",2);h([f()],u.prototype,"currentToolInfo",2);h([f()],u.prototype,"workingSessions",2);h([f()],u.prototype,"compactionStatus",2);h([f()],u.prototype,"chatAvatarUrl",2);h([f()],u.prototype,"chatThinkingLevel",2);h([f()],u.prototype,"chatQueue",2);h([f()],u.prototype,"chatAttachments",2);h([f()],u.prototype,"sidebarOpen",2);h([f()],u.prototype,"sidebarContent",2);h([f()],u.prototype,"sidebarError",2);h([f()],u.prototype,"sidebarMimeType",2);h([f()],u.prototype,"sidebarFilePath",2);h([f()],u.prototype,"sidebarTitle",2);h([f()],u.prototype,"sidebarMode",2);h([f()],u.prototype,"sidebarProofSlug",2);h([f()],u.prototype,"sidebarProofUrl",2);h([f()],u.prototype,"sidebarProofHtml",2);h([f()],u.prototype,"splitRatio",2);h([f()],u.prototype,"lightbox",2);h([f()],u.prototype,"driveAccounts",2);h([f()],u.prototype,"showDrivePicker",2);h([f()],u.prototype,"driveUploading",2);h([f()],u.prototype,"updateStatus",2);h([f()],u.prototype,"updateLoading",2);h([f()],u.prototype,"updateError",2);h([f()],u.prototype,"updateLastChecked",2);h([f()],u.prototype,"nodesLoading",2);h([f()],u.prototype,"nodes",2);h([f()],u.prototype,"devicesLoading",2);h([f()],u.prototype,"devicesError",2);h([f()],u.prototype,"devicesList",2);h([f()],u.prototype,"execApprovalsLoading",2);h([f()],u.prototype,"execApprovalsSaving",2);h([f()],u.prototype,"execApprovalsDirty",2);h([f()],u.prototype,"execApprovalsSnapshot",2);h([f()],u.prototype,"execApprovalsForm",2);h([f()],u.prototype,"execApprovalsSelectedAgent",2);h([f()],u.prototype,"execApprovalsTarget",2);h([f()],u.prototype,"execApprovalsTargetNodeId",2);h([f()],u.prototype,"execApprovalQueue",2);h([f()],u.prototype,"execApprovalBusy",2);h([f()],u.prototype,"execApprovalError",2);h([f()],u.prototype,"pendingGatewayUrl",2);h([f()],u.prototype,"gatewayRestartPending",2);h([f()],u.prototype,"gatewayRestartBusy",2);h([f()],u.prototype,"deployPanelOpen",2);h([f()],u.prototype,"configLoading",2);h([f()],u.prototype,"configRaw",2);h([f()],u.prototype,"configRawOriginal",2);h([f()],u.prototype,"configValid",2);h([f()],u.prototype,"configIssues",2);h([f()],u.prototype,"configSaving",2);h([f()],u.prototype,"configApplying",2);h([f()],u.prototype,"updateRunning",2);h([f()],u.prototype,"applySessionKey",2);h([f()],u.prototype,"configSnapshot",2);h([f()],u.prototype,"configSchema",2);h([f()],u.prototype,"configSchemaVersion",2);h([f()],u.prototype,"configSchemaLoading",2);h([f()],u.prototype,"configUiHints",2);h([f()],u.prototype,"configForm",2);h([f()],u.prototype,"configFormOriginal",2);h([f()],u.prototype,"configFormDirty",2);h([f()],u.prototype,"configFormMode",2);h([f()],u.prototype,"configSearchQuery",2);h([f()],u.prototype,"configActiveSection",2);h([f()],u.prototype,"configActiveSubsection",2);h([f()],u.prototype,"channelsLoading",2);h([f()],u.prototype,"channelsSnapshot",2);h([f()],u.prototype,"channelsError",2);h([f()],u.prototype,"channelsLastSuccess",2);h([f()],u.prototype,"whatsappLoginMessage",2);h([f()],u.prototype,"whatsappLoginQrDataUrl",2);h([f()],u.prototype,"whatsappLoginConnected",2);h([f()],u.prototype,"whatsappBusy",2);h([f()],u.prototype,"nostrProfileFormState",2);h([f()],u.prototype,"nostrProfileAccountId",2);h([f()],u.prototype,"presenceLoading",2);h([f()],u.prototype,"presenceEntries",2);h([f()],u.prototype,"presenceError",2);h([f()],u.prototype,"presenceStatus",2);h([f()],u.prototype,"agentsLoading",2);h([f()],u.prototype,"agentsList",2);h([f()],u.prototype,"agentsError",2);h([f()],u.prototype,"sessionsLoading",2);h([f()],u.prototype,"sessionsResult",2);h([f()],u.prototype,"sessionsError",2);h([f()],u.prototype,"sessionsFilterActive",2);h([f()],u.prototype,"sessionsFilterLimit",2);h([f()],u.prototype,"sessionsIncludeGlobal",2);h([f()],u.prototype,"sessionsIncludeUnknown",2);h([f()],u.prototype,"archivedSessions",2);h([f()],u.prototype,"archivedSessionsLoading",2);h([f()],u.prototype,"archivedSessionsExpanded",2);h([f()],u.prototype,"cronLoading",2);h([f()],u.prototype,"cronJobs",2);h([f()],u.prototype,"cronStatus",2);h([f()],u.prototype,"cronError",2);h([f()],u.prototype,"cronForm",2);h([f()],u.prototype,"cronRunsJobId",2);h([f()],u.prototype,"cronRuns",2);h([f()],u.prototype,"cronBusy",2);h([f()],u.prototype,"workspaceNeedsSetup",2);h([f()],u.prototype,"onboardingPhase",2);h([f()],u.prototype,"onboardingData",2);h([f()],u.prototype,"onboardingActive",2);h([f()],u.prototype,"wizardActive",2);h([f()],u.prototype,"wizardState",2);h([f()],u.prototype,"showSetupTab",2);h([f()],u.prototype,"setupBarDismissed",2);h([f()],u.prototype,"setupProgress",2);h([f()],u.prototype,"setupCapabilities",2);h([f()],u.prototype,"setupCapabilitiesLoading",2);h([f()],u.prototype,"setupQuickDone",2);h([f()],u.prototype,"onboardingIntegrations",2);h([f()],u.prototype,"onboardingCoreProgress",2);h([f()],u.prototype,"onboardingExpandedCard",2);h([f()],u.prototype,"onboardingLoadingGuide",2);h([f()],u.prototype,"onboardingActiveGuide",2);h([f()],u.prototype,"onboardingTestingId",2);h([f()],u.prototype,"onboardingTestResult",2);h([f()],u.prototype,"onboardingConfigValues",2);h([f()],u.prototype,"onboardingProgress",2);h([f()],u.prototype,"allyPanelOpen",2);h([f()],u.prototype,"allyMessages",2);h([f()],u.prototype,"allyStream",2);h([f()],u.prototype,"allyDraft",2);h([f()],u.prototype,"allyUnread",2);h([f()],u.prototype,"allySending",2);h([f()],u.prototype,"allyWorking",2);h([f()],u.prototype,"allyAttachments",2);h([f()],u.prototype,"chatPrivateMode",2);h([f()],u.prototype,"privateSessions",2);h([f()],u.prototype,"dynamicSlots",2);h([f()],u.prototype,"sessionResources",2);h([f()],u.prototype,"sessionResourcesCollapsed",2);h([f()],u.prototype,"skillsLoading",2);h([f()],u.prototype,"skillsReport",2);h([f()],u.prototype,"skillsError",2);h([f()],u.prototype,"skillsFilter",2);h([f()],u.prototype,"skillEdits",2);h([f()],u.prototype,"skillsBusyKey",2);h([f()],u.prototype,"skillMessages",2);h([f()],u.prototype,"skillsSubTab",2);h([f()],u.prototype,"godmodeSkills",2);h([f()],u.prototype,"godmodeSkillsLoading",2);h([f()],u.prototype,"expandedSkills",2);h([f()],u.prototype,"rosterData",2);h([f()],u.prototype,"rosterLoading",2);h([f()],u.prototype,"rosterError",2);h([f()],u.prototype,"rosterFilter",2);h([f()],u.prototype,"expandedAgents",2);h([f()],u.prototype,"debugLoading",2);h([f()],u.prototype,"debugStatus",2);h([f()],u.prototype,"debugHealth",2);h([f()],u.prototype,"debugModels",2);h([f()],u.prototype,"debugHeartbeat",2);h([f()],u.prototype,"debugCallMethod",2);h([f()],u.prototype,"debugCallParams",2);h([f()],u.prototype,"debugCallResult",2);h([f()],u.prototype,"debugCallError",2);h([f()],u.prototype,"logsLoading",2);h([f()],u.prototype,"logsError",2);h([f()],u.prototype,"logsFile",2);h([f()],u.prototype,"logsEntries",2);h([f()],u.prototype,"logsFilterText",2);h([f()],u.prototype,"logsLevelFilters",2);h([f()],u.prototype,"logsAutoFollow",2);h([f()],u.prototype,"logsTruncated",2);h([f()],u.prototype,"logsCursor",2);h([f()],u.prototype,"logsLastFetchAt",2);h([f()],u.prototype,"logsLimit",2);h([f()],u.prototype,"logsMaxBytes",2);h([f()],u.prototype,"logsAtBottom",2);h([f()],u.prototype,"toasts",2);h([f()],u.prototype,"chatUserNearBottom",2);h([f()],u.prototype,"chatNewMessagesBelow",2);h([f()],u.prototype,"consciousnessStatus",2);h([f()],u.prototype,"trustTrackerData",2);h([f()],u.prototype,"trustTrackerLoading",2);h([f()],u.prototype,"guardrailsData",2);h([f()],u.prototype,"guardrailsLoading",2);h([f()],u.prototype,"guardrailsShowAddForm",2);h([f()],u.prototype,"secrets",2);h([f()],u.prototype,"secretsLoading",2);h([f()],u.prototype,"webFetchProvider",2);h([f()],u.prototype,"webFetchLoading",2);h([f()],u.prototype,"searchProvider",2);h([f()],u.prototype,"searchExaConfigured",2);h([f()],u.prototype,"searchTavilyConfigured",2);h([f()],u.prototype,"searchLoading",2);h([f()],u.prototype,"customTabs",2);h([f()],u.prototype,"customTabData",2);h([f()],u.prototype,"customTabLoading",2);h([f()],u.prototype,"customTabErrors",2);u=h([ls("godmode-app")],u);export{z as a,Lu as b,$u as c,Cu as d,xu as e,Pu as f,Mu as g,zt as h,Eu as i,Ru as j,Du as k,xl as l,Ou as m,Ku as n,Fu as o,Nu as p,Ml as q,ku as r,Tu as s,Au as t,Iu as u,Uu as v,Xa as w,_u as x};
1994
+ What can I help you with?`,timestamp:Date.now()}],this.requestUpdate())}).catch(i=>{console.error("[Support] Failed to load chat history:",i)})})}handleWizardOpen(){_(async()=>{const{emptyWizardState:e}=await import("./views-settings-B2UFEtoi.js").then(t=>t.I);return{emptyWizardState:e}},__vite__mapDeps([4,1,3,5]),import.meta.url).then(({emptyWizardState:e})=>{this.wizardState=e(),this.wizardActive=!0,this.requestUpdate()})}handleWizardClose(){this.wizardActive=!1,this.wizardState=null,this.requestUpdate()}handleWizardStepChange(e){this.wizardState&&(this.wizardState={...this.wizardState,step:e},this.requestUpdate())}handleWizardAnswerChange(e,t){this.wizardState&&(this.wizardState={...this.wizardState,answers:{...this.wizardState.answers,[e]:t}},this.requestUpdate())}async handleWizardPreview(){if(!(!this.client||!this.wizardState))try{const[e,t]=await Promise.all([this.client.request("onboarding.wizard.preview",this.wizardState.answers),this.client.request("onboarding.wizard.diff",this.wizardState.answers).catch(()=>null)]),n={};for(const i of e.files??[])n[i.path]=i.wouldCreate;const s={};if(t){for(const i of t.additions)s[i.path]=!0;for(const i of t.changes)s[i.path]=!1}this.wizardState={...this.wizardState,preview:e.files??[],diff:t,fileSelections:n,configSelections:s},this.requestUpdate()}catch(e){console.error("[Wizard] Preview failed:",e)}}handleWizardFileToggle(e,t){this.wizardState&&(this.wizardState={...this.wizardState,fileSelections:{...this.wizardState.fileSelections,[e]:t}},this.requestUpdate())}handleWizardConfigToggle(e,t){this.wizardState&&(this.wizardState={...this.wizardState,configSelections:{...this.wizardState.configSelections,[e]:t}},this.requestUpdate())}async handleWizardGenerate(){if(!this.client||!this.wizardState)return;this.wizardState={...this.wizardState,generating:!0,error:null},this.requestUpdate();const e=[];for(const[n,s]of Object.entries(this.wizardState.fileSelections))s||e.push(n);const t=[];for(const[n,s]of Object.entries(this.wizardState.configSelections))s||t.push(n);try{const n=await this.client.request("onboarding.wizard.generate",{...this.wizardState.answers,skipFiles:e,skipKeys:t});this.wizardState={...this.wizardState,generating:!1,step:9,result:{filesCreated:n.filesCreated,filesSkipped:n.filesSkipped,configPatched:n.configPatched,workspacePath:n.workspacePath}},this.requestUpdate(),this.showToast("Memory system generated!","success",4e3)}catch(n){const s=n instanceof Error?n.message:"Failed to generate workspace";this.wizardState={...this.wizardState,generating:!1,error:s},this.requestUpdate(),this.showToast(s,"error")}}async handleQuickSetup(e){_(()=>import("./setup-BnLadXY9.js"),[],import.meta.url).then(async({quickSetup:t})=>{await t(this,e)&&(this.setTab("chat"),_(async()=>{const{loadCapabilities:s}=await import("./setup-BnLadXY9.js");return{loadCapabilities:s}},[],import.meta.url).then(({loadCapabilities:s})=>s(this)))})}handleLoadCapabilities(){_(async()=>{const{loadCapabilities:e}=await import("./setup-BnLadXY9.js");return{loadCapabilities:e}},[],import.meta.url).then(({loadCapabilities:e})=>e(this))}handleCapabilityAction(e){_(async()=>{const{capabilityAction:t}=await import("./setup-BnLadXY9.js");return{capabilityAction:t}},[],import.meta.url).then(({capabilityAction:t})=>t(this,e))}handleHideSetup(){_(async()=>{const{hideSetup:e}=await import("./setup-BnLadXY9.js");return{hideSetup:e}},[],import.meta.url).then(({hideSetup:e})=>e(this))}handleRunAssessment(){this.client&&this.client.request("onboarding.assess",{}).then(()=>{this.handleLoadCapabilities()})}continueSetup(){const e=this.setupProgress?.currentStep??"welcome";this._navigateToSetupStep(e)}dismissSetup(){this.setupBarDismissed=!0,_(async()=>{const{dismissSetupBar:e}=await import("./setup-BnLadXY9.js");return{dismissSetupBar:e}},[],import.meta.url).then(({dismissSetupBar:e})=>e(this))}handleSetupStepClick(e){this._navigateToSetupStep(e)}async loadSetupProgress(){await(await _(()=>import("./setup-BnLadXY9.js"),[],import.meta.url)).loadSetupProgress(this)}_navigateToSetupStep(e){const n={welcome:"Let's get started! What should I call you?","api-key":"Help me connect my Anthropic API key so you can work at full power.",memory:"Help me set up persistent memory with Honcho so you remember our conversations.",integrations:"Help me connect my tools via Composio — starting with Google and GitHub.",screenpipe:"Help me set up Screenpipe for ambient screen and audio recall.","second-brain":"Help me link my Obsidian vault to my Memory."}[e]??"Help me continue setting up GodMode.";this.handleStartChatWithPrompt(n)}handleUpdateUserProfile(e,t){const n=e.trim().slice(0,50),s=t.trim();this.userName=n||"You",this.userAvatar=s||null,this.applySettings({...this.settings,userName:n,userAvatar:s})}async handleLoadIntegrations(){await(await _(()=>import("./onboarding-setup-eq3R6nNk.js"),[],import.meta.url)).loadIntegrations(this)}handleExpandCard(e){_(()=>import("./onboarding-setup-eq3R6nNk.js"),[],import.meta.url).then(t=>t.expandCard(this,e))}async handleLoadGuide(e){await(await _(()=>import("./onboarding-setup-eq3R6nNk.js"),[],import.meta.url)).loadGuide(this,e)}async handleTestIntegration(e){await(await _(()=>import("./onboarding-setup-eq3R6nNk.js"),[],import.meta.url)).testIntegration(this,e)}async handleConfigureIntegration(e,t){await(await _(()=>import("./onboarding-setup-eq3R6nNk.js"),[],import.meta.url)).configureIntegration(this,e,t)}handleUpdateConfigValue(e,t){this.onboardingConfigValues={...this.onboardingConfigValues,[e]:t}}handleSkipIntegration(e){_(()=>import("./onboarding-setup-eq3R6nNk.js"),[],import.meta.url).then(t=>t.skipIntegration(this,e))}async handleMarkOnboardingComplete(){if(!(!this.client||!this.connected))try{await this.client.request("onboarding.complete",{}),this.showSetupTab=!1,this.setTab("chat")}catch(e){console.error("[onboarding] Failed to mark complete:",e)}}async handleOpenProofDoc(e){let t="Proof Document",n=null,s=null;if(this.client&&this.connected)try{const i=await this.client.request("proof.get",{slug:e});t=i.title?.trim()||t,n=i.filePath?.trim()||null,s=i.viewUrl?.trim()||null}catch(i){console.warn("[Proof] Failed to resolve document metadata:",i)}this.sidebarOpen=!0,this.sidebarMode="proof",this.sidebarProofSlug=e,this.sidebarProofUrl=s,this.sidebarProofHtml=null,this.sidebarFilePath=n,this.sidebarTitle=t}handleCloseProofDoc(){this.sidebarMode="resource",this.sidebarProofSlug=null,this.sidebarProofUrl=null,this.sidebarProofHtml=null,this.handleCloseSidebar()}render(){return su(this)}};h([$a({context:Xa}),f()],u.prototype,"_ctx",2);h([f()],u.prototype,"settings",2);h([f()],u.prototype,"password",2);h([f()],u.prototype,"tab",2);h([f()],u.prototype,"onboarding",2);h([f()],u.prototype,"connected",2);h([f()],u.prototype,"reconnecting",2);h([f()],u.prototype,"reconnectAttempt",2);h([f()],u.prototype,"theme",2);h([f()],u.prototype,"themeResolved",2);h([f()],u.prototype,"hello",2);h([f()],u.prototype,"lastError",2);h([f()],u.prototype,"eventLog",2);h([f()],u.prototype,"assistantName",2);h([f()],u.prototype,"assistantAvatar",2);h([f()],u.prototype,"assistantAgentId",2);h([f()],u.prototype,"userName",2);h([f()],u.prototype,"userAvatar",2);h([f()],u.prototype,"currentModel",2);h([f()],u.prototype,"availableModels",2);h([f()],u.prototype,"modelPickerOpen",2);h([f()],u.prototype,"modelCacheTs",2);h([f()],u.prototype,"sessionKey",2);h([f()],u.prototype,"sessionPickerOpen",2);h([f()],u.prototype,"sessionPickerPosition",2);h([f()],u.prototype,"sessionPickerSearch",2);h([f()],u.prototype,"sessionSearchOpen",2);h([f()],u.prototype,"sessionSearchPosition",2);h([f()],u.prototype,"sessionSearchQuery",2);h([f()],u.prototype,"sessionSearchResults",2);h([f()],u.prototype,"sessionSearchLoading",2);h([f()],u.prototype,"profilePopoverOpen",2);h([f()],u.prototype,"profileEditName",2);h([f()],u.prototype,"profileEditAvatar",2);h([f()],u.prototype,"editingTabKey",2);h([f()],u.prototype,"navDrawerOpen",2);h([f()],u.prototype,"chatLoading",2);h([f()],u.prototype,"chatSending",2);h([f()],u.prototype,"chatSendingSessionKey",2);h([f()],u.prototype,"chatMessage",2);h([f()],u.prototype,"chatDrafts",2);h([f()],u.prototype,"chatMessages",2);h([f()],u.prototype,"chatToolMessages",2);h([f()],u.prototype,"chatStream",2);h([f()],u.prototype,"chatStreamStartedAt",2);h([f()],u.prototype,"chatRunId",2);h([f()],u.prototype,"currentToolName",2);h([f()],u.prototype,"currentToolInfo",2);h([f()],u.prototype,"workingSessions",2);h([f()],u.prototype,"compactionStatus",2);h([f()],u.prototype,"chatAvatarUrl",2);h([f()],u.prototype,"chatThinkingLevel",2);h([f()],u.prototype,"chatQueue",2);h([f()],u.prototype,"chatAttachments",2);h([f()],u.prototype,"sidebarOpen",2);h([f()],u.prototype,"sidebarContent",2);h([f()],u.prototype,"sidebarError",2);h([f()],u.prototype,"sidebarMimeType",2);h([f()],u.prototype,"sidebarFilePath",2);h([f()],u.prototype,"sidebarTitle",2);h([f()],u.prototype,"sidebarMode",2);h([f()],u.prototype,"sidebarProofSlug",2);h([f()],u.prototype,"sidebarProofUrl",2);h([f()],u.prototype,"sidebarProofHtml",2);h([f()],u.prototype,"splitRatio",2);h([f()],u.prototype,"lightbox",2);h([f()],u.prototype,"driveAccounts",2);h([f()],u.prototype,"showDrivePicker",2);h([f()],u.prototype,"driveUploading",2);h([f()],u.prototype,"updateStatus",2);h([f()],u.prototype,"updateLoading",2);h([f()],u.prototype,"updateError",2);h([f()],u.prototype,"updateLastChecked",2);h([f()],u.prototype,"nodesLoading",2);h([f()],u.prototype,"nodes",2);h([f()],u.prototype,"devicesLoading",2);h([f()],u.prototype,"devicesError",2);h([f()],u.prototype,"devicesList",2);h([f()],u.prototype,"execApprovalsLoading",2);h([f()],u.prototype,"execApprovalsSaving",2);h([f()],u.prototype,"execApprovalsDirty",2);h([f()],u.prototype,"execApprovalsSnapshot",2);h([f()],u.prototype,"execApprovalsForm",2);h([f()],u.prototype,"execApprovalsSelectedAgent",2);h([f()],u.prototype,"execApprovalsTarget",2);h([f()],u.prototype,"execApprovalsTargetNodeId",2);h([f()],u.prototype,"execApprovalQueue",2);h([f()],u.prototype,"execApprovalBusy",2);h([f()],u.prototype,"execApprovalError",2);h([f()],u.prototype,"pendingGatewayUrl",2);h([f()],u.prototype,"gatewayRestartPending",2);h([f()],u.prototype,"gatewayRestartBusy",2);h([f()],u.prototype,"deployPanelOpen",2);h([f()],u.prototype,"configLoading",2);h([f()],u.prototype,"configRaw",2);h([f()],u.prototype,"configRawOriginal",2);h([f()],u.prototype,"configValid",2);h([f()],u.prototype,"configIssues",2);h([f()],u.prototype,"configSaving",2);h([f()],u.prototype,"configApplying",2);h([f()],u.prototype,"updateRunning",2);h([f()],u.prototype,"applySessionKey",2);h([f()],u.prototype,"configSnapshot",2);h([f()],u.prototype,"configSchema",2);h([f()],u.prototype,"configSchemaVersion",2);h([f()],u.prototype,"configSchemaLoading",2);h([f()],u.prototype,"configUiHints",2);h([f()],u.prototype,"configForm",2);h([f()],u.prototype,"configFormOriginal",2);h([f()],u.prototype,"configFormDirty",2);h([f()],u.prototype,"configFormMode",2);h([f()],u.prototype,"configSearchQuery",2);h([f()],u.prototype,"configActiveSection",2);h([f()],u.prototype,"configActiveSubsection",2);h([f()],u.prototype,"channelsLoading",2);h([f()],u.prototype,"channelsSnapshot",2);h([f()],u.prototype,"channelsError",2);h([f()],u.prototype,"channelsLastSuccess",2);h([f()],u.prototype,"whatsappLoginMessage",2);h([f()],u.prototype,"whatsappLoginQrDataUrl",2);h([f()],u.prototype,"whatsappLoginConnected",2);h([f()],u.prototype,"whatsappBusy",2);h([f()],u.prototype,"nostrProfileFormState",2);h([f()],u.prototype,"nostrProfileAccountId",2);h([f()],u.prototype,"presenceLoading",2);h([f()],u.prototype,"presenceEntries",2);h([f()],u.prototype,"presenceError",2);h([f()],u.prototype,"presenceStatus",2);h([f()],u.prototype,"agentsLoading",2);h([f()],u.prototype,"agentsList",2);h([f()],u.prototype,"agentsError",2);h([f()],u.prototype,"sessionsLoading",2);h([f()],u.prototype,"sessionsResult",2);h([f()],u.prototype,"sessionsError",2);h([f()],u.prototype,"sessionsFilterActive",2);h([f()],u.prototype,"sessionsFilterLimit",2);h([f()],u.prototype,"sessionsIncludeGlobal",2);h([f()],u.prototype,"sessionsIncludeUnknown",2);h([f()],u.prototype,"archivedSessions",2);h([f()],u.prototype,"archivedSessionsLoading",2);h([f()],u.prototype,"archivedSessionsExpanded",2);h([f()],u.prototype,"cronLoading",2);h([f()],u.prototype,"cronJobs",2);h([f()],u.prototype,"cronStatus",2);h([f()],u.prototype,"cronError",2);h([f()],u.prototype,"cronForm",2);h([f()],u.prototype,"cronRunsJobId",2);h([f()],u.prototype,"cronRuns",2);h([f()],u.prototype,"cronBusy",2);h([f()],u.prototype,"workspaceNeedsSetup",2);h([f()],u.prototype,"onboardingPhase",2);h([f()],u.prototype,"onboardingData",2);h([f()],u.prototype,"onboardingActive",2);h([f()],u.prototype,"wizardActive",2);h([f()],u.prototype,"wizardState",2);h([f()],u.prototype,"showSetupTab",2);h([f()],u.prototype,"setupBarDismissed",2);h([f()],u.prototype,"setupProgress",2);h([f()],u.prototype,"setupCapabilities",2);h([f()],u.prototype,"setupCapabilitiesLoading",2);h([f()],u.prototype,"setupQuickDone",2);h([f()],u.prototype,"onboardingIntegrations",2);h([f()],u.prototype,"onboardingCoreProgress",2);h([f()],u.prototype,"onboardingExpandedCard",2);h([f()],u.prototype,"onboardingLoadingGuide",2);h([f()],u.prototype,"onboardingActiveGuide",2);h([f()],u.prototype,"onboardingTestingId",2);h([f()],u.prototype,"onboardingTestResult",2);h([f()],u.prototype,"onboardingConfigValues",2);h([f()],u.prototype,"onboardingProgress",2);h([f()],u.prototype,"allyPanelOpen",2);h([f()],u.prototype,"allyMessages",2);h([f()],u.prototype,"allyStream",2);h([f()],u.prototype,"allyDraft",2);h([f()],u.prototype,"allyUnread",2);h([f()],u.prototype,"allySending",2);h([f()],u.prototype,"allyWorking",2);h([f()],u.prototype,"allyAttachments",2);h([f()],u.prototype,"chatPrivateMode",2);h([f()],u.prototype,"privateSessions",2);h([f()],u.prototype,"dynamicSlots",2);h([f()],u.prototype,"sessionResources",2);h([f()],u.prototype,"sessionResourcesCollapsed",2);h([f()],u.prototype,"skillsLoading",2);h([f()],u.prototype,"skillsReport",2);h([f()],u.prototype,"skillsError",2);h([f()],u.prototype,"skillsFilter",2);h([f()],u.prototype,"skillEdits",2);h([f()],u.prototype,"skillsBusyKey",2);h([f()],u.prototype,"skillMessages",2);h([f()],u.prototype,"skillsSubTab",2);h([f()],u.prototype,"godmodeSkills",2);h([f()],u.prototype,"godmodeSkillsLoading",2);h([f()],u.prototype,"expandedSkills",2);h([f()],u.prototype,"rosterData",2);h([f()],u.prototype,"rosterLoading",2);h([f()],u.prototype,"rosterError",2);h([f()],u.prototype,"rosterFilter",2);h([f()],u.prototype,"expandedAgents",2);h([f()],u.prototype,"debugLoading",2);h([f()],u.prototype,"debugStatus",2);h([f()],u.prototype,"debugHealth",2);h([f()],u.prototype,"debugModels",2);h([f()],u.prototype,"debugHeartbeat",2);h([f()],u.prototype,"debugCallMethod",2);h([f()],u.prototype,"debugCallParams",2);h([f()],u.prototype,"debugCallResult",2);h([f()],u.prototype,"debugCallError",2);h([f()],u.prototype,"logsLoading",2);h([f()],u.prototype,"logsError",2);h([f()],u.prototype,"logsFile",2);h([f()],u.prototype,"logsEntries",2);h([f()],u.prototype,"logsFilterText",2);h([f()],u.prototype,"logsLevelFilters",2);h([f()],u.prototype,"logsAutoFollow",2);h([f()],u.prototype,"logsTruncated",2);h([f()],u.prototype,"logsCursor",2);h([f()],u.prototype,"logsLastFetchAt",2);h([f()],u.prototype,"logsLimit",2);h([f()],u.prototype,"logsMaxBytes",2);h([f()],u.prototype,"logsAtBottom",2);h([f()],u.prototype,"toasts",2);h([f()],u.prototype,"chatUserNearBottom",2);h([f()],u.prototype,"chatNewMessagesBelow",2);h([f()],u.prototype,"consciousnessStatus",2);h([f()],u.prototype,"trustTrackerData",2);h([f()],u.prototype,"trustTrackerLoading",2);h([f()],u.prototype,"guardrailsData",2);h([f()],u.prototype,"guardrailsLoading",2);h([f()],u.prototype,"guardrailsShowAddForm",2);h([f()],u.prototype,"secrets",2);h([f()],u.prototype,"secretsLoading",2);h([f()],u.prototype,"webFetchProvider",2);h([f()],u.prototype,"webFetchLoading",2);h([f()],u.prototype,"searchProvider",2);h([f()],u.prototype,"searchExaConfigured",2);h([f()],u.prototype,"searchTavilyConfigured",2);h([f()],u.prototype,"searchLoading",2);h([f()],u.prototype,"customTabs",2);h([f()],u.prototype,"customTabData",2);h([f()],u.prototype,"customTabLoading",2);h([f()],u.prototype,"customTabErrors",2);u=h([ls("godmode-app")],u);export{z as a,Lu as b,$u as c,Cu as d,xu as e,Pu as f,Mu as g,zt as h,Eu as i,Ru as j,Du as k,xl as l,Ou as m,Ku as n,Fu as o,Nu as p,Ml as q,ku as r,Tu as s,Au as t,Iu as u,Uu as v,Xa as w,_u as x};