UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

1,923 lines • 350 kB
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./user-prefs-request-RcpLLvdA.js","./user-prefs-request-Y0ykMyQk.js","./control-ui-core-D-VUH4Gq.css","./composer-draft-store.runtime-v4vUYxIm.js","./control-ui-boot-shared-JlZTSJEC.js","./control-ui-boot-shared-3SP_aL-Y.js","./control-ui-boot-shared-90V688bk.js","./control-ui-boot-shared-BykNRHBP.js","./plugin-contracts-runtime-CsJ0WpAd.js","./markdown-runtime-Hc-lvqnn.js","./config-runtime-CgOgfOrG.js","./css-chat-Ckz95ikh.js","./chat-transcript-layout-w3EszKw8.js","./sidebar-update-runtime-B0vYzX3D.js","./control-ui-boot-shared-BJ_QKfFn.css","./css-chat-DCHf01mf.css","./css-chat-custodian-new-session-CEndYuO5.css","./sidebar-update-runtime-ah7rgQE7.css","./chat-native-runtime-recovery-ttYYPde6.js","./sidebar-DMrsq_Hl.js","./chat-detail-panel-dVq3CZO7.js"])))=>i.map(i=>d[i]);
import{n as e,r as t}from"./rolldown-runtime-8BhlS34s.js";import{At as n,Ba as r,Bi as i,Br as a,D as o,Da as s,Et as c,Fr as l,Ii as u,Ji as d,Li as f,Nr as p,Nt as m,Oi as h,Pa as g,Pr as _,Tt as v,Va as y,Vt as b,Wa as x,Wi as S,br as C,et as w,ii as T,k as ee,nn as te,qr as E,ro as D,yr as ne,zi as O,zr as re,zt as ie}from"./control-ui-foundation-ZY_Flbbd.js";import{Al as ae,Ar as oe,Di as se,El as ce,Et as le,F as ue,Fc as de,Fl as fe,Gl as pe,Il as me,Is as he,Jn as ge,Jt as _e,Lc as ve,Ml as ye,N as be,Ns as xe,Pc as Se,Pl as Ce,R as we,Rl as Te,Su as k,Ul as Ee,Vc as De,W as Oe,Wl as ke,Z as Ae,Zc as je,_t as Me,c as Ne,cc as Pe,hc as Fe,hu as A,jr as Ie,ks as Le,l as Re,lu as ze,nl as j,nn as Be,oc as Ve,ql as He,qn as Ue,qt as We,rc as Ge,s as Ke,sc as qe,su as Je,u as Ye,uu as M,vt as Xe,wt as Ze,xc as Qe,xt as $e,yt as et}from"./control-ui-core-3P365fbR.js";import{$i as N,$n as tt,Ai as nt,Bi as rt,Br as it,Ft as at,Gt as ot,Hn as st,Ii as ct,Kt as lt,Mi as ut,Nt as dt,Oi as ft,Ot as pt,Qi as mt,Sn as ht,Un as gt,Xi as P,Zi as F,_o as _t,_r as vt,co as yt,dr as bt,ei as xt,er as St,fn as Ct,fr as wt,gr as Tt,hi as Et,la as Dt,mi as Ot,mn as kt,ti as At,ua as jt,ur as Mt,vi as Nt,vr as Pt,wi as Ft,yi as It,zi as Lt}from"./control-ui-core-CFW9Qtjn.js";import{$ as I,C as Rt,F as zt,M as Bt,T as Vt,X as L,Y as R,c as Ht,ct as z,d as Ut,i as Wt,nt as Gt,o as Kt,s as qt,tt as B,u as Jt,ut as V}from"./lit-runtime-P5vbNq6b.js";import{D as Yt,St as Xt,T as Zt,ct as Qt,dt as $t,ft as en,ot as tn,st as nn}from"./control-ui-boot-shared-Rs4iS2kF.js";import{c as rn,d as an,l as on}from"./gateway-runtime-5YzSCmfV.js";import{$i as sn,Al as H,An as cn,Bc as ln,Cn as un,El as dn,Fn as fn,Fs as pn,G as mn,Hn as hn,Ji as gn,Ls as _n,Mt as vn,Nn as yn,Nr as bn,Ol as xn,Pn as Sn,Pr as Cn,Q as wn,Qo as Tn,Sl as En,Tn as Dn,U as On,Ui as kn,Vc as An,Vn as jn,Wi as Mn,X as Nn,Xi as Pn,Z as Fn,Zi as In,_l as Ln,_t as Rn,al as zn,as as Bn,bc as Vn,bl as Hn,cl as Un,ct as Wn,dc as Gn,ft as Kn,gc as qn,gl as Jn,jl as U,kl as Yn,kt as Xn,li as Zn,mt as Qn,os as $n,pt as er,ss as tr,st as nr,ts as rr,ui as ir,ut as ar,vl as or,wl as sr,wn as cr,xc as lr,xn as ur}from"./control-ui-boot-shared-DoKu-5Ju.js";import{L as dr,R as fr,V as pr,n as mr,t as hr,z as gr}from"./control-ui-boot-shared-DBJri5ri.js";import{A as _r,Ba as vr,Ga as yr,Ka as br,La as xr,Mr as Sr,Nr as Cr,Qa as wr,Ya as Tr,ao as Er,co as Dr,do as Or,dt as kr,ft as Ar,io as jr,it as Mr,k as Nr,lo as Pr,mt as Fr,no as Ir,oo as Lr,pt as Rr,qa as zr,ro as Br,rt as Vr,so as Hr,uo as Ur}from"./control-ui-boot-shared-CG9HtEG-.js";import{A as Wr,An as Gr,G as Kr,In as qr,R as Jr,Rn as Yr,W as Xr,_ as Zr,k as Qr,m as $r,p as ei,y as ti,z as ni}from"./control-ui-boot-shared-73R4ErOy.js";import{$ as ri,$n as ii,$r as ai,$t as oi,At as si,Bn as ci,Bt as li,Dr as ui,Er as di,F as fi,Ft as pi,G as mi,Gt as hi,Hr as gi,Ht as _i,I as vi,It as yi,J as bi,Jt as xi,K as Si,Kn as Ci,Kt as wi,L as Ti,Ln as Ei,Lr as Di,Lt as Oi,M as ki,Mr as Ai,N as ji,Nr as Mi,On as Ni,P as Pi,Q as Fi,Qn as Ii,Qr as W,R as Li,Rt as Ri,Tn as zi,Tr as Bi,U as Vi,Ut as Hi,Vt as Ui,W as Wi,Wt as Gi,X as Ki,Xr as qi,Xt as Ji,Y as Yi,Yt as Xi,Z as Zi,Zn as Qi,Zr as $i,an as ea,cn as ta,cr as na,dr as ra,ei as ia,en as aa,er as oa,et as sa,fn as ca,fr as la,hn as ua,hr as da,i as fa,in as pa,kt as ma,l as ha,lr as ga,mn as _a,mr as va,n as ya,ni as G,nr as ba,on as xa,pn as Sa,pr as Ca,q as wa,qn as Ta,qt as Ea,r as Da,ri as Oa,sn as ka,t as Aa,tn as ja,tr as Ma,u as Na,ur as Pa,wr as Fa,z as Ia,zn as La,zr as Ra,zt as za}from"./control-ui-boot-shared-CcmBeh0v.js";import{c as Ba,s as Va}from"./control-ui-boot-shared-BR12heUA.js";import{Ai as Ha,Hn as Ua,_ as Wa,b as Ga,h as Ka,ji as qa,ki as Ja,v as Ya,y as Xa}from"./control-ui-boot-shared-CApmg5ot.js";import"./css-cron-custodian-new-session-DdqVeFqw.js";import"./chat-transcript-styles-BVZgOT1t.js";import"./css-chat-custodian-new-session-B_euK-Vu.js";import"./css-new-session-BGJnpiJ5.js";import"./css-config-njfbfHBk.js";function Za(){return(Za=e((()=>{zr(),customElements.get(`openclaw-agent-select`)||customElements.define(`openclaw-agent-select`,br)})))()}var Qa;function $a(){return($a=e((()=>{bt(),Xe(),nr(),Qa=class{constructor(e,t={}){this.notify=e,this.options=t,this.pending=!1,this.failed=!1}get snapshot(){let e=this.binding;if(!e||!this.owns(e))return{models:[],hasSnapshot:!1,retired:!1};let t=ar(e.client,e.scope,{allowStale:!0});return{...t,models:t?.models??[],hasSnapshot:t!==void 0,retired:$e(e.client,e.scope)}}bind(e,t){let n=e.snapshot.client,r=this.binding;if(r&&this.owns(r)&&r.gateway===e&&Ze(le(r.scope))===Ze(le(t))||(this.clear(),!n))return!1;let i={gateway:e,client:n,scope:t,presentationKey:Mt(e).key};this.binding=i;let a=er(n,()=>{this.owns(i)&&(this.failed&&ar(n,t)&&(this.failed=!1),this.notify())}),o=Qn(e,()=>{this.owns(i)?this.read():this.notify()},t);return this.unsubscribe=()=>{a(),o()},!0}owns(e){return this.binding===e&&e.gateway.snapshot.client===e.client&&e.gateway.snapshot.phase===`connected`&&Mt(e.gateway).key===e.presentationKey}read(){let e=this.binding;if(!e||!this.owns(e))return Promise.resolve(void 0);this.controller?.abort(),this.controller=void 0;let t=ar(e.client,e.scope);if(t)return this.pending=!1,this.failed=!1,this.options.onResult?.(t),this.notify(),Promise.resolve(t);let n=new AbortController;return this.controller=n,this.pending=!0,this.failed=!1,this.notify(),Wn(e.client,{...e.scope,signal:n.signal,timeoutMs:this.options.timeoutMs}).then(t=>{if(this.owns(e)&&this.controller===n)return this.controller=void 0,this.pending=!1,this.options.onResult?.(t),this.notify(),t},()=>{this.owns(e)&&this.controller===n&&(this.controller=void 0,this.pending=!1,this.failed=!0,this.options.onError?.(),this.notify())})}clear(){this.binding=void 0,this.controller?.abort(),this.controller=void 0,this.unsubscribe?.(),this.unsubscribe=void 0,this.pending=!1,this.failed=!1}}})))()}function eo(e){return/^[A-Za-z0-9_/:=.,@%+-]+$/.test(e)?e:`'${e.replaceAll(`'`,`'\\''`)}'`}function to(e){if(!e.open)return L;let t=A(`newSession.connectMachineTitle`),n=e.setup?.joinUrl?.trim(),r=n?`npx openclaw connect ${eo(n)}`:null,i=e.setup?.expiresAtMs?ue(e.setup.expiresAtMs,{hour:`numeric`,minute:`2-digit`},``):``;return I`
    <openclaw-modal-dialog
      class="connect-machine-dialog"
      label=${t}
      description=${A(`newSession.connectMachineDescription`)}
      @modal-cancel=${e.onClose}
    >
      <section class="exec-approval-card connect-machine-dialog__card">
        <header class="exec-approval-header">
          <div>
            <h2 class="exec-approval-title">${t}</h2>
            <p class="exec-approval-sub">${A(`newSession.connectMachineDescription`)}</p>
          </div>
          <button
            class="btn btn--icon btn--ghost"
            type="button"
            aria-label=${A(`common.dismiss`)}
            @click=${e.onClose}
          >
            ${P.x}
          </button>
        </header>

        <div class="connect-machine-dialog__body">
          ${e.loading&&!r?I`<p class="connect-machine-dialog__status" role="status">
                  ${A(`newSession.connectMachineGenerating`)}
                </p>`:L}
          ${e.error?I`<p class="exec-approval-error" role="alert">
                  ${A(`newSession.connectMachineFailed`)} ${e.error}
                </p>`:L}
          ${r?I`
                  ${_r(r)}
                  <p class="connect-machine-dialog__hint">
                    ${A(`newSession.connectMachineTeamHint`)}
                  </p>
                  <p class="connect-machine-dialog__hint">
                    ${i?A(`newSession.connectMachineSingleUseExpires`,{time:i}):A(`newSession.connectMachineSingleUse`)}
                  </p>
                `:L}
        </div>

        <footer class="exec-approval-actions connect-machine-dialog__actions">
          ${r||e.error?I`<button
                  class="btn"
                  type="button"
                  ?disabled=${e.loading}
                  @click=${e.onRefresh}
                >
                  ${P.refresh}
                  ${e.loading?A(`newSession.connectMachineRefreshing`):A(`newSession.connectMachineFreshCode`)}
                </button>`:L}
          <button class="btn btn--ghost" type="button" @click=${e.onManageDevices}>
            ${A(`newSession.connectMachineManageDevices`)}
          </button>
        </footer>
      </section>
    </openclaw-modal-dialog>
  `}var no;function ro(){return(ro=e((()=>{R(),Nr(),F(),it(),M(),H(),Oe(),He(),we(),U(),no=class{constructor(e,t){this.gateway=e,this.requestUpdate=t,this.openValue=!1,this.loadingValue=!1,this.errorValue=null,this.setupValue=null,this.requestId=0}get open(){return this.openValue}get loading(){return this.loadingValue}get error(){return this.errorValue}get setup(){return this.setupValue}start(){this.openValue=!0,this.errorValue=null,this.setupValue=null,this.requestUpdate(),this.refresh()}close(){this.requestId+=1,this.openValue=!1,this.loadingValue=!1,this.errorValue=null,this.setupValue=null}async refresh(){if(!this.openValue||this.loadingValue)return;let{client:e,connected:t}=this.gateway();if(!t||!e){this.errorValue=A(`newSession.connectMachineUnavailable`),this.requestUpdate();return}let n=++this.requestId;this.loadingValue=!0,this.errorValue=null,this.requestUpdate();try{let t=await Ae(e);if(!this.stillCurrent(n,e))return;if(!t.joinUrl?.trim()){this.setupValue=null,this.errorValue=A(`newSession.connectMachineMissingUrl`);return}this.setupValue=t}catch(t){this.stillCurrent(n,e)&&(this.errorValue=pe(t))}finally{n===this.requestId&&(this.loadingValue=!1,this.requestUpdate())}}stillCurrent(e,t){let n=this.gateway();return e===this.requestId&&t===n.client&&n.connected&&this.openValue}}})))()}function io(e){if(!e||e.length>2048||Array.from(e).some(e=>{let t=e.charCodeAt(0);return t<32||t===127}))return;let t=l(e);return t?p(t.provider,t.modelId):void 0}function ao(e,t){let n=new URLSearchParams(ge(e)),r=io(t);return r&&n.set(`model`,r),n.size>0?`?${n.toString()}`:``}function oo(e){let t=Ue(e),n=t.catalogId?void 0:io(new URLSearchParams(e).get(`model`));return{...t,...n?{requestedModel:n}:{}}}function so(){return(so=e((()=>{_()})))()}function co(e,t,n,r){return JSON.stringify([e,t,n,...r?[r]:[]])}function lo(e){return co(e?.requestedAgentId??``,e?.catalogId??``,e?.group??``,e?.requestedModel)}function uo(e){let t=oo(e);return co(t.agentId,t.catalogId,t.group??``,t.requestedModel)}function fo(e,t){return!e?.requestedAgentId||g(e.requestedAgentId)===g(t)?e?.requestedModel:void 0}function K(e){return!!e?.catalogId}function po(e){return!!(e?.catalogId&&e.startTerminal&&e.catalogLabel)}function mo(e){return K(e)&&!po(e)||!!(e?.group&&e.groupStatus!==`resolved`)}function ho(e){return JSON.stringify([e?.groupStatus??``,e?.groupCwd??``,e?.groupWorktree===!0,e?.groupCatalogGeneration??-1,e?.groupDefaultsStatus??`idle`])}function go(e,t){let n=e?.group?.trim();if(!n)return!1;let r=t.groupsGeneration(),i=t.groupsStatus();if(e?.groupCatalogGeneration!==r||e.groupDefaultsStatus!==i)return!0;if(i!==`ready`)return!1;let a=t.state.groupSettings.find(e=>e.name===n);return a?e.groupStatus!==`resolved`||(e.groupCwd??``)!==(a.cwd??``)||e.groupWorktree!==(a.worktree===!0):e.groupStatus===`resolved`}function _o(e,t){let n=t.state.groupSettings.find(t=>t.name===e?.group);return JSON.stringify([e?.group??``,t.groupsGeneration(),t.groupsStatus(),!!n,n?.cwd??``,n?.worktree===!0])}function vo(e,t){return!(!e?.group||t&&!go(e,t))}function yo(e,t){return mo(e)||vo(e,t)}function bo(e,t){return e?.groupStatus===`resolved`&&!vo(e,t)?e.group:void 0}function xo(e,t,n){let r=e?.agentId?.trim();if(!r)return n&&g(n);let i=g(r);return t.some(e=>g(e.id)===i)?i:n&&g(n)}function So(e,t){return!K(e)||po(e)&&!!t}async function Co(e,t,n){try{let r=(await e.request(`sessions.catalog.list`,{...n?{agentId:n}:{},catalogId:t,limitPerHost:1})).catalogs.find(e=>e.id===t),i=r?.capabilities.startTerminal;return r&&i===!0?{model:``,catalogLabel:r.label,startTerminal:!0,terminalHosts:r.hosts.filter(e=>e.canStartTerminal===!0).map(({hostId:e,label:t})=>({hostId:e,label:t}))}:void 0}catch{return}}function wo(e){if(!K(e))return L;let t=po(e),n=e?.catalogLabel||e?.catalogId||``;return I`<span
    class="new-session-page__trigger new-session-page__runtime"
    title=${A(t?`newSession.nativeTerminalHint`:`newSession.catalogUnavailable`)}
  >
    <span class="new-session-page__target-icon" aria-hidden="true">${P.terminal}</span>
    <span class="new-session-page__trigger-label">${n}</span>
  </span>`}function To(e){let t=mo(e.data)||e.groupPending===!0;return I`
    <div class="new-session-page__triggers">
      ${wo(e.data)} ${K(e.data)?L:e.agentSelect}
      ${e.placeSelect}
      ${t?I`<span class="new-session-page__catalog-unavailable">
              ${A(`newSession.catalogUnavailable`)}
              <button
                class="btn btn--sm"
                type="button"
                ?disabled=${e.retrying}
                @click=${e.onRetry}
              >
                ${e.retrying?A(`common.loading`):A(`lazyView.retry`)}
              </button>
            </span>`:L}
    </div>
  `}var Eo,Do;function q(){return(q=e((()=>{R(),F(),M(),H(),on(),j(),so(),U(),Eo=class{constructor(e,t){this.readData=e,this.revalidate=t,this.pending=null,this.lastKey=``}synchronize(e){if(this.pending)return;let t=this.readData(),n=_o(t,e);if(this.lastKey===n||!go(t,e))return;let r=this.revalidate();r&&(this.lastKey=n,this.pending=r,r.catch(()=>void 0).finally(()=>{this.pending===r&&(this.pending=null,this.synchronize(e))}))}},Do=class{constructor(e){this.notify=e,this.requestId=0,this.state={status:`idle`}}clear(){let e=this.state;this.state={status:`idle`},this.requestId+=1,e.status===`loading`&&e.controller.abort(),e.status!==`idle`&&this.notify()}startRequest(e){let t=new AbortController,n=++this.requestId;this.state={status:`loading`,owner:e,controller:t,requestId:n},this.notify(),e.client.request(`sessions.catalog.list`,{agentId:e.agentId,metadataOnly:!0},{signal:t.signal}).then(t=>{let r=this.state;r.status===`loading`&&r.requestId===n&&(this.state={status:`ready`,owner:e,targets:t.catalogs.filter(e=>e.capabilities.startTerminal===!0).map(({id:e,label:t})=>({id:e,label:t}))},this.notify())},()=>{let t=this.state;t.status===`loading`&&t.requestId===n&&(this.state={status:`error`,owner:e},this.notify())})}load(e,t,n){let r=e?.gateway.snapshot,i=r?.client,a=t.trim()?g(t):``;if(!n||r?.phase!==`connected`||!i||!a||an(r,`sessions.catalog.list`)!==!0){this.clear();return}let o={agentId:a,client:i},s=this.state;(s.status===`idle`||s.owner.client!==o.client||s.owner.agentId!==o.agentId)&&(this.clear(),this.startRequest(o))}retry(e,t){let n=this.state;n.status===`error`&&n.owner.client===e&&n.owner.agentId===t&&this.startRequest(n.owner)}groups(){let e=this.state;if(!(e.status===`idle`||e.status===`ready`&&!e.targets.length))return[{errorLabel:A(`newSession.cliAgentsUnavailable`),id:`cliAgents`,label:A(`newSession.cliAgentsGroup`),options:e.status===`ready`?e.targets.map(({id:e,label:t})=>({value:e,label:t})):[],status:e.status}]}}})))()}var Oo;function ko(){return(ko=e((()=>{Oo=[1e3,3e3,1e4,3e4,6e4]})))()}function Ao(e){return typeof e==`number`&&Number.isFinite(e)&&e>=0?Math.trunc(e):void 0}function jo(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>0&&e<=65536?e:void 0}function Mo(e){let t=(Array.isArray(e)?e:[]).flatMap(e=>{if(!d(e))return[];if(e.code===`worker-host-unavailable`){let t=D(e.message);return t&&t.length<=1024?[{code:`worker-host-unavailable`,message:t}]:[]}return e.code===`update-required`&&e.action===`update-and-reconnect`&&e.updateCommand===`openclaw update`&&e.headlessReconnectCommand===`openclaw node restart`?[{code:e.code,action:e.action,updateCommand:e.updateCommand,headlessReconnectCommand:e.headlessReconnectCommand}]:[]});return t.length>0?t:void 0}function No(e){return Array.isArray(e)?e.length===1&&(e[0]===`worker-turn`||e[0]===`remote-exec`)?[e[0]]:e.length===2&&e[0]===`worker-turn`&&e[1]===`remote-exec`?[`worker-turn`,`remote-exec`]:[]:[]}function Po(e,t){return e.executionModes?.includes(t)===!0}function Fo(e){return(Array.isArray(e)?e:[]).flatMap(e=>{let t=S(e);if(!t)return[];let n=D(t.id),r=D(t.providerId);if(!n||!r)return[];let i=t.trust===`persistent`||t.trust===`disposable`?t.trust:void 0,a=Io(t.machines),o=Lo(t.operatingSystems);return[{id:n,providerId:r,...typeof t.providerDisplayId==`string`&&/^[a-z][a-z0-9-]{0,63}$/.test(t.providerDisplayId)&&t.providerDisplayId.trim()===t.providerDisplayId?{providerDisplayId:t.providerDisplayId}:{},trust:i,...Object.hasOwn(t,`executionModes`)?{executionModes:No(t.executionModes)}:{},...a.length>0?{machines:a}:{},...o.length>0?{operatingSystems:o}:{}}]}).toSorted((e,t)=>e.id.localeCompare(t.id))}function Io(e){let t=new Map;for(let n of(Array.isArray(e)?e:[]).slice(0,64)){if(!d(n))continue;let e=D(n.id),r=D(n.label),i=D(n.os),a=JSON.stringify([i,e]);if(!e||e.length>128||!r||r.length>128||t.has(a)||n.os!==void 0&&(!i||i.length>64))continue;let o=jo(n.cpu),s=jo(n.memoryGb);t.set(a,{id:e,label:r,...i?{os:i}:{},...o===void 0?{}:{cpu:o},...s===void 0?{}:{memoryGb:s},...typeof n.default==`boolean`?{default:n.default}:{}})}return[...t.values()]}function Lo(e){let t=new Map;for(let n of(Array.isArray(e)?e:[]).slice(0,8)){if(!d(n))continue;let e=D(n.id),r=D(n.label),i=D(n.disabledReason)?.slice(0,256);!e||e.length>64||!r||r.length>64||t.has(e)||t.set(e,{id:e,label:r,...typeof n.default==`boolean`?{default:n.default}:{},...i?{disabledReason:i}:{}})}return[...t.values()]}function Ro(e){return e.operatingSystems?.find(e=>e.default)?.id??e.operatingSystems?.[0]?.id??e.machines?.find(e=>e.os)?.os??``}function zo(e,t){return(e.machines??[]).filter(e=>!e.os||e.os===t)}function Bo(e,t=Ro(e)){let n=zo(e,t);return n.find(e=>e.default)??n[0]}function Vo(e){return typeof e==`string`&&Wo.has(e)}function Ho(e){if(!d(e)||Object.keys(e).some(e=>e!==`command`&&e!==`state`&&e!==`message`))return;let t=D(e.command),n=e.state,r=D(e.message);return t&&t.length<=128&&(n===`invocable`||n===`pending-approval`||n===`undeclared`||n===`unauthorized`)?{command:t,state:n,...r?{message:r}:{}}:void 0}function Uo(e){return(Array.isArray(e)?e:[]).flatMap(e=>{let t=S(e);if(!t)return[];let n=D(t.id),r=D(t.type);if(!n||r!==`local`&&r!==`node`&&r!==`worker`||!Vo(t.status))return[];let i=t.status,a=D(t.label),o=D(t.platform),s=t.trust===`persistent`||t.trust===`disposable`?t.trust:void 0,c=y(t.capabilities),l=Array.isArray(t.invocableCommands)?x(t.invocableCommands).filter(e=>e.length<=128).slice(0,128):void 0,u=Ho(t.requiredNodeCommand),d=Ao(t.lastConnectedAtMs),f=Ao(t.lastDisconnectedAtMs),p=Ao(t.lastSeenAtMs),m=D(t.lastSeenReason),h=Mo(t.issues),g=Qt(t.workerSlots);return[{id:n,type:r,status:i,...a?{label:a}:{},...o?{platform:o}:{},...typeof t.sessionHost==`boolean`?{sessionHost:t.sessionHost}:{},...g?{workerSlots:g}:{},...d===void 0?{}:{lastConnectedAtMs:d},...f===void 0?{}:{lastDisconnectedAtMs:f},...p===void 0?{}:{lastSeenAtMs:p},...m?{lastSeenReason:m}:{},...s?{trust:s}:{},...c?{capabilities:c}:{},...l?{invocableCommands:l}:{},...u?{requiredNodeCommand:u}:{},...h?{issues:h}:{}}]}).toSorted((e,t)=>e.id.localeCompare(t.id))}var Wo;function Go(){return(Go=e((()=>{r(),nn(),Wo=new Set([`available`,`unavailable`,`starting`,`stopping`,`error`])})))()}async function Ko(e,t){let n=await e.request(`environments.list`,t?{runtimeId:t}:{});return{profiles:Fo(n?.profiles),environments:Uo(n?.environments)}}function qo(e,t){return t===`enable-session-hosting`?I`<div>${A(`newSession.sessionHostingAction`)}</div>
      <code class="new-session-page__command">openclaw connect --service --session-host</code>`:t===`update-device`?I`<div>${A(`newSession.updateAction`)}</div>
      <code class="new-session-page__command">openclaw update</code>
      <div>${A(`newSession.reconnectAction`)}</div>
      <code class="new-session-page__command">openclaw node restart</code>`:e}function J(e,t){return I`<div class="new-session-page__card-row">
    <span class="new-session-page__card-icon" aria-hidden="true">${e}</span><span>${t}</span>
  </div>`}function Y(e,t){let n=e.disabled?e.title||e.description:void 0,r=e.compact?void 0:e.description,i=e.compact&&e.disabled&&!e.hideDetails,a=e.compact&&!e.disabled&&!e.hideDetails,o=[e.suggested?A(`newSession.machineDefault`):void 0,e.accessibleProvider?A(`newSession.cloudWorkerProvider`,{provider:e.accessibleProvider}):void 0].filter(Boolean).join(`, `),s=[o,e.accessibleProvider?n:void 0].filter(Boolean).join(`, `),c=I`
    <button
      type="button"
      class="session-menu__item ${r?`session-menu__item--described`:``} ${e.compact?`new-session-page__environment-option`:``}"
      data-suggested=${e.suggested?`true`:L}
      aria-description=${s||L}
      data-value=${e.value}
      data-popover=${e.keepOpen||i?L:`close`}
      aria-pressed=${String(e.checked)}
      title=${e.compact?L:e.title??L}
      ?disabled=${t||!!e.disabled&&!i}
      aria-disabled=${i?`true`:L}
      @click=${t=>{if(e.disabled){t.preventDefault(),t.stopPropagation();return}e.onSelect()}}
    >
      ${e.icon?I`<span class="session-menu__icon" aria-hidden="true">${e.icon}</span>`:L}
      <span class="session-menu__text">
        ${e.label}
        ${e.selectedSummary?I`<span class="new-session-page__selected-summary"
                >${e.selectedSummary}</span
              >`:L}
        ${r?I`<span class="session-menu__description">${r}</span>`:L}
      </span>
      ${!e.compact&&e.facts?.length?I`<span class="new-session-page__menu-meta">
              <span class="new-session-page__menu-facts">
                ${e.facts.map(e=>I`<span class="new-session-page__menu-fact">${e}</span>`)}
              </span>
            </span>`:L}
      ${!e.compact&&e.sub?I`<span class="session-menu__sub">${e.sub}</span>`:L}

      <span class="session-menu__check" aria-hidden="true"
        >${e.checked?P.check:L}</span
      >
      ${e.hasSubmenu?I`<span class="new-session-page__submenu-chevron" aria-hidden="true"
              >${P.chevronRight}</span
            >`:L}
    </button>
  `;return e.compact&&!e.hideDetails?I`<openclaw-tooltip
        class="new-session-page__environment-details"
        placement="right-start"
        ?open-on-click=${i||a}
      >
        <div class="new-session-page__environment-detail-trigger">
          ${c}
          ${a?I`<button
                  type="button"
                  class="new-session-page__touch-details"
                  aria-label=${A(`newSession.environmentDetails`,{name:e.label})}
                  ?disabled=${t}
                >
                  ${P.info}
                </button>`:L}
        </div>
        <div slot="content" class="new-session-page__environment-card">
          ${o?I`<span hidden>${o}, </span>`:L}
          ${n?I`<span>${qo(n,e.remediation)}</span>`:I`
                  <strong>${e.label}</strong>
                  ${e.summary?J(P.info,e.summary):L}
                  ${e.platform?J(P.layers,e.platform):L}
                  ${e.sub?J(P.info,e.sub):L}
                  ${e.capabilityLabels?.length?J(P.info,e.capabilityLabels.join(`, `)):L}
                  ${e.trust?J(e.trust===`persistent`?P.repeat:P.clock,A(e.trust===`persistent`?`newSession.persistentEnvironmentHint`:`newSession.disposableEnvironmentHint`)):L}
                  ${e.provider?J(P.server,e.provider):L}
                  ${e.hardware?J(P.info,e.hardware):L}
                  ${[...new Set([e.description,...e.facts??[],e.provider&&!e.disabled?void 0:e.title].filter(Boolean))].map(e=>J(P.info,e))}
                  ${e.capacityLabel?I`<div class="new-session-page__card-row">
                          <span class="new-session-page__card-icon" aria-hidden="true"
                            >${P.activity}</span
                          ><span class="new-session-page__capacity-caption"
                            >${e.capacityLabel}</span
                          >
                        </div>`:L}
                `}
        </div>
      </openclaw-tooltip>`:c}function Jo(e){return e.profiles.toSorted(xr).map(t=>{let n=yr(t),r=e.profileDisabledReason?.(t),i=e.selectedId===t.id,a=(i?e.selectedOs:void 0)||Ro(t),o=t.operatingSystems?.find(e=>e.id===a),s=zo(t,a),c=(i&&e.selectedMachine?s.find(t=>t.id===e.selectedMachine):void 0)??Bo(t,a),l=e.compact&&!e.disabled&&!r&&((t.operatingSystems?.some(e=>!e.disabledReason)??!1)||s.length>0),u=Y({value:`cloud:${t.id}`,label:e.compact?t.id:A(`newSession.cloudWorker`,{profile:t.id}),hasSubmenu:l,selectedSummary:e.compact&&i?[o?.label,c?.label].filter(Boolean).join(` · `):void 0,icon:n.icon,accessibleProvider:n.label,compact:e.compact,facts:!e.compact&&t.trust===`disposable`?[A(`newSession.environmentDisposable`)]:!e.compact&&t.trust===`persistent`?[A(`newSession.environmentPersistent`)]:void 0,trust:e.compact?t.trust:void 0,provider:e.compact?n.label:void 0,platform:e.compact?o?.label:void 0,hardware:e.compact&&c?Yo(c):void 0,hideDetails:e.compact&&!e.disabled&&!r,keepOpen:e.compact,checked:e.selectedId===t.id,disabled:e.disabled||!!r,title:(e.disabled?e.disabledReason:r)??A(`newSession.cloudWorkerProvider`,{provider:n.label}),onSelect:()=>e.compact&&!i?e.onSelect(t.id,!0):e.onSelect(t.id)},e.submitting);return l?I`<openclaw-tooltip
          class="new-session-page__environment-details new-session-page__cloud-config-card"
          placement="right"
          open-on-click
        >
          ${u}
          <div slot="content">
            <span hidden
              >${A(`newSession.cloudWorkerProvider`,{provider:n.label})}</span
            >
            ${Xo({profile:t,operatingSystems:t.operatingSystems??[],machines:s,suggested:!i,selectedOs:i?a:``,selectedMachine:i?c?.id??``:``,submitting:e.submitting,onSelectOs:n=>{i||e.onSelect(t.id,!0),e.onSelectOs?.(n)},onSelectMachine:n=>{i||e.onSelect(t.id,!0),e.onSelectMachine?.(n)}})}
          </div>
        </openclaw-tooltip>`:u})}function Yo(e){let t=e.cpu===void 0?void 0:String(e.cpu),n=e.memoryGb===void 0?void 0:String(e.memoryGb);return t&&n?A(`newSession.machineShape`,{cpu:t,memory:n}):t?A(`newSession.machineCpu`,{cpu:t}):n?A(`newSession.machineMemory`,{memory:n}):void 0}function Xo(e){let t=e.operatingSystems.filter(e=>!e.disabledReason),n=t.length===1?t[0]:void 0,r=e.machines.length===1?e.machines[0]:void 0,i=[[t.length,A(`newSession.operatingSystem`),()=>n?I`<span class="new-session-page__fixed-os" data-value=${`os:${n.id}`}
              >${n.label}</span
            >`:$o({operatingSystems:t,selectedId:e.selectedOs,suggestedId:e.suggested?Ro(e.profile):void 0,submitting:e.submitting,onSelect:e.onSelectOs})],[e.machines.length,A(`newSession.machine`),()=>r?Zo(r):Qo({machines:e.machines,selectedId:e.selectedMachine,suggestedId:e.suggested?Bo(e.profile,e.selectedOs)?.id:void 0,submitting:e.submitting,onSelect:e.onSelectMachine})]];return I`<section
    class="new-session-page__cloud-configuration"
    aria-label=${e.profile.id}
  >
    ${i.map(([e,t,n])=>e?I`<div class="new-session-page__environment-heading">${t}</div>
            <div class="new-session-page__cloud-choice-list" role="group" aria-label=${t}>
              ${n()}
            </div>`:L)}
  </section>`}function Zo(e){let t=Yo(e);return I`<span class="new-session-page__fixed-machine" data-value=${`machine:${e.id}`}>
    <span>${e.label}</span>${t?I`<span>${t}</span>`:L}
  </span>`}function Qo(e){return e.machines.map(t=>Y({suggested:e.suggestedId===t.id,value:`machine:${t.id}`,label:t.label,sub:Yo(t),checked:e.selectedId===t.id||!e.selectedId&&e.suggestedId===t.id,keepOpen:!0,onSelect:()=>e.onSelect(t.id)},e.submitting))}function $o(e){return e.operatingSystems.map(t=>Y({suggested:e.suggestedId===t.id,value:`os:${t.id}`,label:t.label,description:t.disabledReason,disabled:!!t.disabledReason,title:t.disabledReason,checked:e.selectedId===t.id||!e.selectedId&&e.suggestedId===t.id,keepOpen:!0,onSelect:()=>e.onSelect(t.id)},e.submitting))}function es(){return(es=e((()=>{R(),Ft(),F(),vr(),M(),H(),Go(),U()})))()}function ts(e){if(!d(e)||typeof e.agentId!=`string`||!e.agentId.trim())return null;let t=os(e.selection);if(!t||!d(e.selection))return null;for(let n of[`folder`,`projectId`,`baseRef`]){let r=e.selection[n];typeof r==`string`&&(t[n]=r.trim())}return delete t.model,delete t.agentRuntime,delete t.thinkingLevel,delete t.fastMode,delete t.worktreeName,{agentId:g(e.agentId),selection:t}}function ns(e){return e.cloudProfileId?{kind:`cloud`,id:e.cloudProfileId}:e.deviceId?{kind:`device`,id:e.deviceId}:e.autoDevice?{kind:`auto-device`}:{kind:`local`}}function rs(e){return!!(e?.model||e?.thinkingLevel||e?.fastMode!==void 0)}function is(e,t){let n=e?.folder??``,r=!!n&&n===e?.workspace&&e.workspace!==t,i=n&&!r?n:t;return{folder:i,workspaceMoved:r,freshWorkspace:e?.freshWorkspace??!(e?.worktree===!0||e?.projectId||i&&i!==t)}}function as(e){return`${ms}${te(e)}`}function os(e){if(!d(e))return null;let t={};for(let n of[`workspace`,`folder`,`projectId`,`baseRef`,`worktreeName`,`model`,`thinkingLevel`]){let r=D(e[n]);r&&(t[n]=r)}let n=D(e.agentRuntime);t.model&&n&&(t.agentRuntime=n),(typeof e.fastMode==`boolean`||e.fastMode===`auto`)&&(t.fastMode=e.fastMode),typeof e.worktree==`boolean`&&(t.worktree=e.worktree),typeof e.freshWorkspace==`boolean`?t.freshWorkspace=e.freshWorkspace:t.worktree===!0&&(t.freshWorkspace=!1);let r=ss(e.where);return r&&(t.where=r),Object.keys(t).length?t:null}function ss(e){if(!d(e)||typeof e.kind!=`string`)return;if(e.kind===`local`||e.kind===`auto-device`)return{kind:e.kind};let t=D(e.id);return t&&(e.kind===`device`||e.kind===`cloud`)?{kind:e.kind,id:t}:void 0}function cs(e,t){try{let n=JSON.parse(e.getItem(as(t))??`null`);return d(n)?n:{}}catch{return{}}}function ls(e,t){let n=k(),r=g(t);return!n||!e||!r?null:os(cs(n,e).agents?.[r])}function us(e){let t=k();if(!t||!e)return{};let n=Object.entries(cs(t,e).agents??{}).flatMap(([e,t])=>{let n=g(e),r=os(t);return n&&r?[[n,r]]:[]});return Object.fromEntries(n)}function ds(e){return Object.fromEntries(Object.entries(e).toSorted(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[`${hs}${e}`,t]))}function fs(e){return Object.fromEntries(Object.entries(e).flatMap(([e,t])=>{if(!e.startsWith(hs))return[];let n=g(e.slice(15)),r=os(t);return n&&r?[[n,r]]:[]}))}function ps(e,t,n){let r=k(),i=g(t);if(!r||!e||!i)return!1;let a=cs(r,e),o={...a.agents},s=os(n);s?o[i]=s:delete o[i];try{return r.setItem(as(e),JSON.stringify({...a,agents:o})),!0}catch{return!1}}var ms,hs,gs,_s;function vs(){return(vs=e((()=>{j(),ms=`openclaw.new-session.preferences.v1:`,hs=`new-session.v1:`,gs=`new-session.migration.v1`,_s=`new-session.palette.v1`})))()}var ys;function bs(){return(bs=e((()=>{Xt(),dt(),M(),H(),on(),j(),Ee(),q(),vs(),i(),U(),ys=class e{static{this.preferenceWriters=new WeakMap}constructor(e,t){this.read=e,this.callbacks=t,this.preferenceModeValue=`local`,this.identityPreferences={},this.preferenceLoad=Promise.resolve()}get loading(){return this.preferenceModeValue===`loading`}synchronize(){let e=this.read(),t=e.source;if(!t)return;let n={...e,profileId:t.snapshot.selfUser?.id};if(this.preferenceScope&&[`source`,`client`,`connected`,`recoveryScope`,`connectionEpoch`,`profileId`].every(e=>n[e]===this.preferenceScope?.[e]))return;this.disconnect(),this.preferenceScope=n,this.identityPreferences={};let{client:r,connected:i,recoveryScope:a,profileId:o}=n;if(i){let e=this.preferenceWrites(t).listeners,i=(e,i,s)=>{let c=t.snapshot;this.preferenceScope===n&&c.client===r&&c.hello?.auth?.recoveryScope===a&&c.selfUser?.id===o&&(this.identityPreferences={...this.identityPreferences,[e]:i},s?this.adoptPreferences():this.callbacks.requestUpdate())};e.add(i),this.stopPreferencePublication=()=>e.delete(i)}let s=i&&r&&o&&an(t.snapshot,`users.prefs.get`)===!0&&an(t.snapshot,`users.prefs.set`)===!0;this.preferenceModeValue=s?`loading`:`local`,this.preferenceLoad=s?this.loadIdentityPreferences({client:r,profileId:o,gatewayUrl:e.gatewayUrl,scope:n}):Promise.resolve()}disconnect(){this.stopPreferencePublication?.(),this.stopPreferencePublication=void 0,this.preferenceScope=void 0}adoptPreferences(){this.read().agentsHydrated&&this.callbacks.onAdoptAgentDefaults(),this.callbacks.requestUpdate()}readPreference(e){let t=this.read();return K(t.data)||t.data?.group||t.pendingPlacementSessionKey?null:this.preferenceModeValue===`remote`?this.identityPreferences[g(e)]??null:ls(this.read().gatewayUrl,e)}preferenceWrites(t){let n=e.preferenceWriters.get(t);return n||(n={agents:new Map,revision:{},listeners:new Set},e.preferenceWriters.set(t,n)),n}capturePreferenceConsumption(e,t,n){return this.preparePreferenceWrite(e,t,{worktreeName:``},n)}persistPreference(e,t,n){return this.preparePreferenceWrite(e,t,n)?.()}preparePreferenceWrite(e,t,n,r){let{source:i,client:a,gatewayUrl:o,recoveryScope:s,bootId:c,data:l,pendingPlacementSessionKey:u}=this.read(),d=r!==void 0,f=!K(l)&&!l?.group&&(d||!u);if(!f&&!d||!i)return;let p=this.preferenceScope,m=i.snapshot.selfUser?.id,h=this.preferenceLoad,_=g(e),v=this.preferenceWrites(i),y=v.agents.get(_);y||(y={selection:{},write:Promise.resolve()},v.agents.set(_,y));let b=y.selection,x=()=>!!(a&&i.snapshot.client===a&&i.snapshot.phase===`connected`&&i.connection.gatewayUrl===o&&a.recoveryScope===s&&(i.snapshot.hello?.auth?.recoveryScope??``)===s&&i.snapshot.hello?.server?.bootId===c&&i.snapshot.selfUser?.id===m),S=d?n:{workspace:t,...n},C=e=>r?!e||e.worktreeName!==r.worktreeName||e.worktree!==!0||(e.workspace??t)!==t||is(e,t).folder!==r.folder||(e.projectId??``)!==(r.projectId??``)?`superseded`:r.selectedBaseRef===void 0?!e.baseRef&&r.baseRef?`unconfirmed`:(e.baseRef??``)===(r.baseRef??``)?`match`:`superseded`:(e.baseRef??``)===r.selectedBaseRef?`match`:`superseded`:`match`;return async e=>{if(d&&(!x()||y.selection!==b))return;let t=Object.keys(n).some(e=>![`model`,`agentRuntime`,`thinkingLevel`,`fastMode`].includes(e))?{}:y.selection;if(y.selection=t,e?.(),!f)return;let r=()=>d?x()&&y.selection===t:x()&&this.preferenceScope===p,i=this.preferenceModeValue!==`local`,s=async()=>{if(!(i&&(await h,!a||!r())))try{for(let e=0;e<3;e+=1){let e;if(this.preferenceModeValue!==`local`){if(!a||!m||!r())return;let{loadUserPreferences:t}=await O(async()=>{let{loadUserPreferences:e}=await import(`./user-prefs-request-RcpLLvdA.js`);return{loadUserPreferences:e}},__vite__mapDeps([0,1,2]),import.meta.url),n=await t(a,m);if(!r())return;if(n.status!==`ok`)return!1;e=n.entries}let t=e?fs(e)[_]:ls(o,_),n=C(t);if(n!==`match`)return n===`superseded`;let i={...t,...S};if(e&&a){let t=ds({[_]:i}),n=await at(a,{entries:t,expectedEntries:Object.fromEntries(Object.keys(t).map(t=>[t,e[t]??null]))});if(!x()||n.status!==`ok`&&!r())return;if(n.status===`conflict`)continue;if(n.status!==`ok`)return!1;ps(o,_,i)}else{if(!ps(o,_,i))return!1;i=ls(o,_)??{}}v.revision={};for(let e of v.listeners)e(_,i,d);return e&&this.preferenceScope===p&&(this.identityPreferences={...this.identityPreferences,[_]:i},this.callbacks.requestUpdate()),!0}return!1}catch{return!1}},c=i?y.write.then(s,s):s();return y.write=c.then(e=>{e===!1&&r()&&ke({message:A(d?`newSession.worktreeNameClearUnconfirmed`:`newSession.preferenceSaveUnconfirmed`)})}),y.write}}async loadIdentityPreferences(e){let t=this.read().source,n=t?this.preferenceWrites(t):void 0,r=n?.revision,i=0;try{let{loadUserPreferences:t}=await O(async()=>{let{loadUserPreferences:e}=await import(`./user-prefs-request-RcpLLvdA.js`);return{loadUserPreferences:e}},__vite__mapDeps([0,1,2]),import.meta.url),a=async()=>{let n=await t(e.client,e.profileId);if(n.status!==`ok`)throw Error(`User preferences unavailable`);return n.entries};if(this.preferenceScope!==e.scope)return;let o=await a(),s=us(e.gatewayUrl);for(;this.preferenceScope===e.scope;){if(n?.revision!==r)return this.loadIdentityPreferences(e);let t=fs(o);if(o[`new-session.migration.v1`]!==!0&&i<3){let n=Object.fromEntries(Object.entries(s).filter(([e])=>!Object.hasOwn(t,e))),r=Object.entries(ds(n)),c=Object.fromEntries(r.slice(0,31));r.length<32&&(c[gs]=!0);let l=await at(e.client,{entries:c,expectedEntries:{...Object.fromEntries(Object.keys(c).map(e=>[e,o[e]??null])),[gs]:o[`new-session.migration.v1`]??null}}).catch(()=>null);if(this.preferenceScope!==e.scope)return;if(l?.status===`conflict`){i+=1,o=await a();continue}if(l?.status===`ok`){o={...o,...c};continue}i===0&&(t={...s,...t})}if(n?.revision!==r)return this.loadIdentityPreferences(e);this.identityPreferences=t,this.preferenceModeValue=`remote`;for(let[n,r]of Object.entries(t))ps(e.gatewayUrl,n,r);this.adoptPreferences();return}}catch{this.preferenceScope===e.scope&&(this.preferenceModeValue=i>0?`remote`:`local`,this.callbacks.requestUpdate())}}}})))()}async function xs(e,t,n){if(!e||!t)return``;try{let t=await e.request(`system.info`,{},{signal:n});return D(t.machineName)??D(t.hostname)?.split(`.`,1)[0]??``}catch{return``}}function Ss(){return(Ss=e((()=>{})))()}function Cs(e){let t=ws.get(e.client);t||(t=new WeakMap,ws.set(e.client,t));let n=t.get(e.hello);n||(n=new Map,t.set(e.hello,n));let r=JSON.stringify([e.gatewayUrl,e.profileId]),i=n.get(r);if(!i){let t=n,a=new Ts(e,()=>{t.get(r)===a&&t.delete(r)});i=a,n.set(r,i)}return i}var ws,Ts;function Es(){return(Es=e((()=>{dt(),vs(),i(),ws=new WeakMap,Ts=class{constructor(e,t){this.owner=e,this.release=t,this.mode=`loading`,this.palettePreference=null,this.listeners=new Map,this.writing=Promise.resolve(),this.pendingWrites=0,this.loading=this.load()}subscribe(e,t){return this.listeners.set(e,t),()=>{this.listeners.delete(e),this.releaseIfIdle()}}releaseIfIdle(){!this.listeners.size&&!this.pendingWrites&&this.release()}hasCurrentBinding(){return[...this.listeners.values()].some(e=>e())}setPalettePreference(e,t){if(!t())return Promise.resolve(!1);let n=async()=>{if(await this.loading,!this.hasCurrentBinding()||this.mode!==`remote`)return!1;try{return(await at(this.owner.client,{entries:{"new-session.palette.v1":e}})).status===`ok`&&(this.palettePreference=e,this.publish(`changed`),!0)}catch{return!1}};this.pendingWrites+=1;let r=this.writing.then(n,n);return this.writing=r.then(()=>{},()=>{}),r.finally(()=>{--this.pendingWrites,this.releaseIfIdle()})}publish(e){for(let[t,n]of this.listeners)n()&&t(e)}async load(){try{let{loadUserPreferences:e}=await O(async()=>{let{loadUserPreferences:e}=await import(`./user-prefs-request-RcpLLvdA.js`);return{loadUserPreferences:e}},__vite__mapDeps([0,1,2]),import.meta.url);if(!this.hasCurrentBinding())return;let t=await e(this.owner.client,this.owner.profileId);if(!this.hasCurrentBinding())return;if(t.status!==`ok`){this.mode=`local`;return}this.palettePreference=ts(t.entries[_s]),this.mode=`remote`}catch{this.mode=`local`}finally{this.publish(`loaded`)}}}})))()}function Ds(e){return e.gatewayIdentityChanged||!e.placementDraftOwned?`gateway-changed`:`placement-interrupted`}var Os,ks;function As(){return(As=e((()=>{Ln(),c(),Os=new WeakMap,ks=class{constructor(e){this.readOwner=e,this.sessionKey=``,this.messageId=``,this.message=``,this.target=null,this.agentId=``,this.gatewayUrl=``,this.recoveryScope=``,this.phase=`dispatching`,this.retryAllowed=!1,this.restored=!1,this.persistent=!0}releaseClaim(){this.claim?.owners.get(this.claim.key)===this&&this.claim.owners.delete(this.claim.key),this.claim=void 0}claimOwners(){let e=this.readOwner?.();if(!e)return;let t=Os.get(e);return t||(t=new Map,Os.set(e,t)),t}claimKey(e,t,n){return JSON.stringify([e,t,n])}clear(){this.persistent&&Jn(this.gatewayUrl,this.recoveryScope,this.sessionKey,this.messageId),this.reset()}hasOtherLiveOwner(e,t,n){let r=this.claimOwners()?.get(this.claimKey(e,t,n));return r!==void 0&&r!==this}owns(e,t,n){return!this.hasOtherLiveOwner(e,t,n)&&this.gatewayUrl===e&&this.recoveryScope===t&&this.sessionKey===n}reset(){this.releaseClaim(),this.sessionKey=``,this.messageId=``,this.message=``,this.mentions=void 0,this.attachments=void 0,this.target=null,this.agentId=``,this.gatewayUrl=``,this.recoveryScope=``,this.phase=`dispatching`,this.createParams=void 0,this.retryAllowed=!1,this.restored=!1,this.persistent=!0}restore(e,t){let n=this.claimOwners(),r=or(e,t).find(r=>{let i=n?.get(this.claimKey(e,t,r.sessionKey));return r.phase===`creating`&&(!i||i===this)});return!r||r.phase!==`creating`?null:(this.apply(r,!0,!0),r)}capture(){return this.snapshot(this.sessionKey,this.phase)}stageCreate(e){let t=`agent:${e.agentId}:dashboard:${v()}`,n=Hn({...e.createParams,key:t},t,e.agentId);if(!n)return null;let r=e.persistent!==!1;r||delete n.key;let i={sessionKey:t,messageId:v(),message:e.message,...e.mentions?.length?{mentions:e.mentions.map(e=>({...e}))}:{},attachments:e.attachments,target:e.target,agentId:e.agentId,gatewayUrl:e.gatewayUrl,recoveryScope:e.recoveryScope,phase:`creating`,createParams:n};return r&&!sr(i)?null:(this.apply(i,!1,r),n)}promoteToDispatching(e){let t=this.sessionKey,n=this.snapshot(e,`dispatching`);return!n||this.persistent&&!En(t,n)?!1:(this.releaseClaim(),this.sessionKey=e,this.phase=`dispatching`,this.createParams=void 0,!0)}snapshot(e,t){return!this.sessionKey||!this.messageId||!this.target||!this.agentId||t===`creating`&&!this.createParams?null:{sessionKey:e,messageId:this.messageId,message:this.message,...this.mentions?.length?{mentions:this.mentions.map(e=>({...e}))}:{},attachments:this.attachments?[...this.attachments]:void 0,target:{...this.target},agentId:this.agentId,gatewayUrl:this.gatewayUrl,recoveryScope:this.recoveryScope,phase:t,...t===`creating`&&this.createParams?{createParams:{...this.createParams}}:{}}}apply(e,t,n){this.releaseClaim();let r=this.claimOwners();if(r&&e.phase===`creating`){let t=this.claimKey(e.gatewayUrl,e.recoveryScope,e.sessionKey);r.set(t,this),this.claim={owners:r,key:t}}this.sessionKey=e.sessionKey,this.messageId=e.messageId,this.message=e.message,this.mentions=e.mentions,this.attachments=e.attachments,this.target={...e.target},this.agentId=e.agentId,this.gatewayUrl=e.gatewayUrl,this.recoveryScope=e.recoveryScope,this.phase=e.phase,this.createParams=e.createParams,this.retryAllowed=!0,this.restored=t,this.persistent=n}}})))()}var js,Ms;function Ns(){return(Ns=e((()=>{dr(),vt(),M(),H(),on(),j(),q(),ko(),es(),bs(),Ss(),Es(),As(),U(),js=[0,1e3,3e3],Ms=class{constructor(e,t,n){this.read=t,this.callbacks=n,this.cloudProfilesValue=[],this.environmentsValue=null,this.cloudProfilesReadyValue=!1,this.catalogRetryingValue=!1,this.catalogRevalidationPending=!1,this.gatewaySource=null,this.gatewayClientValue=null,this.gatewayUrlValue=``,this.gatewayBootIdValue=``,this.gatewayRecoveryScopeValue=``,this.gatewayRecoveryScopeReady=!1,this.gatewayConnectedValue=!1,this.gatewayConnectionEpochValue=0,this.catalogRetryScope=``,this.catalogRetryAttempt=0,this.cloudProfileRetryAttempt=0,this.cloudProfileRefresh=null,this.handleCatalogRetry=()=>{let{context:e,data:t}=this.read();if(!this.gatewayConnectedValue||t?.group&&e?.sessions.groupsStatus()===`loading`||!t?.startTerminal&&!yo(t,e?.sessions))return;if(this.catalogRetryingValue){this.catalogRevalidationPending=!0;return}t?.group&&e?.sessions.groupsInvalidate();let n=e?.revalidate(`new-session`);n&&(globalThis.clearTimeout(this.catalogRetryTimer),this.catalogRetryTimer=void 0,this.catalogRetryingValue=!0,this.callbacks.requestUpdate(),n.catch(()=>void 0).then(()=>this.callbacks.updateComplete()).finally(()=>{this.catalogRetryingValue=!1,this.catalogRevalidationPending?(this.catalogRevalidationPending=!1,this.handleCatalogRetry()):this.retryPendingCatalogTarget(),this.callbacks.requestUpdate()}))},this.preferences=new ys(()=>({source:this.gatewaySource,client:this.gatewayClientValue,gatewayUrl:this.gatewayUrlValue,recoveryScope:this.gatewayRecoveryScopeValue,bootId:this.gatewayBootIdValue,connected:this.gatewayConnectedValue,connectionEpoch:this.gatewayConnectionEpochValue,data:this.read().data,pendingPlacementSessionKey:this.read().pendingPlacement.sessionKey,agentsHydrated:this.read().agentsHydrated}),n),this.gatewayNameTask=new fr(e,{args:()=>[this.read().isConnected&&this.gatewayConnectedValue?this.gatewayClientValue:null,an(this.read().context?.gateway.snapshot??{},`system.info`)===!0,this.gatewayConnectionEpochValue],task:([e,t,n],{signal:r})=>xs(e,t,r)}),this.cloudProfileTask=new fr(e,{args:()=>[this.read().isConnected&&this.gatewayConnectedValue?this.gatewayClientValue:null,this.gatewayConnectionEpochValue,Tt(this.read().context?.gateway.snapshot.hello?.auth??null),this.read().isAdmin,this.gatewayRecoveryScopeValue,this.read().runtimeId],task:async([e,t,n,r,i,a])=>{if(!e)return gr;if(!n)return{profiles:[],environments:[]};let o=await Ko(e,a);return{...o,profiles:r?o.profiles:[]}},onComplete:e=>{this.resetCloudProfileRetry(),this.environmentsValue=e.environments,this.applyCloudProfiles(e.profiles),this.cloudProfilesReadyValue=!0},onError:()=>{this.scheduleCloudProfileRetry()}})}get gatewayName(){return this.gatewayNameTask.status===pr.COMPLETE?this.gatewayNameTask.value??``:``}get cloudProfiles(){return this.cloudProfilesValue}get environments(){return this.environmentsValue}get cloudProfilesReady(){return this.cloudProfilesReadyValue}get cloudProfilesPending(){return this.cloudProfileTask.status===pr.PENDING}get deviceCatalogDisabledReason(){return this.cloudProfilesReadyValue&&this.cloudProfileTask.status===pr.COMPLETE?void 0:A(`newSession.placementNotReady`)}get catalogRetrying(){return this.catalogRetryingValue}get client(){return this.gatewayClientValue}get gatewayUrl(){return this.gatewayUrlValue}get recoveryScope(){return this.gatewayRecoveryScopeValue}get sessionCreateScope(){let e=[this.gatewayUrlValue,this.gatewayRecoveryScopeValue,this.gatewayBootIdValue];return e.every(Boolean)?JSON.stringify(e):``}get connected(){return this.gatewayConnectedValue}get connectionEpoch(){return this.gatewayConnectionEpochValue}get preferenceLoading(){return this.preferences.loading||this.identityPreferences?.mode===`loading`}resolvedGroupCategory(){let e=this.read();return an(e.context?.gateway.snapshot??{},`sessions.groups.defaults`)===!0?bo(e.data,e.context?.sessions):void 0}refreshCloudProfiles(){if(this.cloudProfileTask.status===pr.PENDING){let e=this.cloudProfileRefresh??this.cloudProfileTask.taskComplete.catch(()=>void 0).then(()=>{if(this.cloudProfileRefresh===e)return this.cloudProfileRefresh=null,this.refreshCloudProfiles()});return this.cloudProfileRefresh=e,e}return globalThis.clearTimeout(this.cloudProfileRetryTimer),this.cloudProfileRetryTimer=void 0,this.cloudProfileTask.run()}synchronize(e){let t=e.snapshot,n=t.phase===`connected`,r=this.gatewaySource===null,i=n?t.hello?.server?.bootId?.trim()??``:this.gatewayBootIdValue,a=!r&&n&&!!this.gatewayBootIdValue&&i!==this.gatewayBootIdValue,o=!r&&this.gatewayUrlValue!==e.connection.gatewayUrl,s=!r&&this.gatewaySource!==e,c=!r&&(s||this.gatewayClientValue!==t.client),l=!r&&this.gatewayConnectedValue!==n,u=n&&(c||!this.gatewayConnectedValue),d=n&&t.client?.recoveryScopeReady===!0&&!this.gatewayRecoveryScopeReady,f=n?t.hello?.auth?.recoveryScope??``:this.gatewayRecoveryScopeValue,p=!r&&this.gatewayRecoveryScopeValue!==f;if(this.gatewaySource=e,this.gatewayClientValue=t.client,this.gatewayUrlValue=e.connection.gatewayUrl,this.gatewayBootIdValue=i,this.gatewayRecoveryScopeValue=f,this.gatewayRecoveryScopeReady=t.client?.recoveryScopeReady===!0,this.gatewayConnectedValue=n,this.read().visibility===`draft`&&!this.read().canStartAsDraft&&this.callbacks.onVisibilityRetired(),o||a||c||l||p){let e=s||o||p,t=o||p;this.invalidateDiscovery(e,Ds({gatewayIdentityChanged:t,placementDraftOwned:!!this.read().pendingPlacement.sessionKey}))}if(r||o||p||d||u){let e=this.read().pendingPlacement;e.gatewayUrl&&(e.gatewayUrl!==this.gatewayUrlValue||e.recoveryScope!==this.gatewayRecoveryScopeValue)&&this.callbacks.onPendingPlacementReset(),n&&t.client?.recoveryScopeReady&&this.callbacks.onRecoveryReady(this.gatewayUrlValue,this.gatewayRecoveryScopeValue)}u&&(this.gatewayConnectionEpochValue+=1,!r&&this.read().data?.startTerminal?this.handleCatalogRetry():this.retryPendingCatalogTarget()),this.preferences.synchronize(),this.synchronizeIdentityPreferences(t.selfUser?.id),this.callbacks.requestUpdate()}invalidateDiscovery(e,t){this.cloudProfileRefresh=null,this.cloudProfileTask.run([null,-1,!1,!1,``]),this.cloudProfilesValue=[],this.cloudProfilesReadyValue=!1,e&&(this.environmentsValue=null),this.resetCloudProfileRetry(),this.callbacks.onInvalidate(e,t),this.callbacks.requestUpdate()}retryPendingCatalogTarget(){let{context:e,data:t}=this.read();if(this.catalogRetryingValue)return;if(t?.group&&e?.sessions.groupsStatus()===`loading`){globalThis.clearTimeout(this.catalogRetryTimer),this.catalogRetryTimer=void 0;return}if(!this.gatewayConnectedValue||!yo(t,e?.sessions)){globalThis.clearTimeout(this.catalogRetryTimer),this.catalogRetryTimer=void 0,this.catalogRetryScope=``,this.catalogRetryAttempt=0;return}let n=`${this.gatewayConnectionEpochValue}:${lo(t)}`;if(this.catalogRetryScope!==n&&(globalThis.clearTimeout(this.catalogRetryTimer),this.catalogRetryTimer=void 0,this.catalogRetryScope=n,this.catalogRetryAttempt=0),this.catalogRetryTimer||this.catalogRetryAttempt>=js.length)return;let r=js[this.catalogRetryAttempt];this.catalogRetryAttempt+=1,this.catalogRetryTimer=globalThis.setTimeout(()=>{this.catalogRetryTimer=void 0;let e=this.read();if(this.catalogRetryScope!==n||!this.gatewayConnectedValue||e.data?.group&&e.context?.sessions.groupsStatus()===`loading`||!yo(e.data,e.context?.sessions))return;e.data?.group&&e.context?.sessions.groupsInvalidate();let t=e.context?.revalidate(`new-session`);t&&t.catch(()=>void 0).then(()=>this.callbacks.updateComplete()).then(()=>this.retryPendingCatalogTarget())},r)}get preferenceState(){return this.identityPreferences}savePalettePreference(e){let t=this.identityPreferences,n=this.read().context?.gateway.snapshot,r=n?.client,i=n?.hello,a=n?.selfUser?.id,o=this.gatewayUrlValue;return t?.setPalettePreference(e,()=>this.identityPreferences===t&&this.gatewayConnectedValue&&this.read().context?.gateway.snapshot.client===r&&this.read().context?.gateway.snapshot.hello===i&&this.read().context?.gateway.snapshot.selfUser?.id===a&&this.read().context?.gateway.connection.gatewayUrl===o)??Promise.resolve(!1)}readPreference(e){let t=this.read();if(K(t.data)||t.data?.group||t.pendingPlacement.sessionKey)return null;let n=this.preferences.readPreference(e);if(this.callbacks.preferenceScope!==`palette`)return n;let r=this.callbacks.readPalettePreference?.();return{...n,...r?.agentId===g(e)?r.selection:{},worktreeName:``}}capturePreferenceConsumption(e,t,n){if(this.callbacks.preferenceScope!==`palette`)return this.preferences.capturePreferenceConsumption(e,t,n)}persistPreference(e,t,n){if(this.callbacks.preferenceScope!==`palette`)return this.preferences.persistPreference(e,t,n)}disconnect(){this.preferences.disconnect(),this.stopPreferences?.(),this.stopPreferences=void 0,this.identityPreferences=void 0,this.cloudProfileRefresh=null,this.gatewaySource=null,this.gatewayClientValue=null,this.gatewayConnectedValue=!1,this.gatewayConnectionEpochValue=0,this.catalogRetryScope=``,this.catalogRetryAttempt=0,globalThis.clearTimeout(this.catalogRetryTimer),this.catalogRetryTimer=void 0,this.gatewayNameTask.run([null,!1,-1]),this.cloudProfileTask.run([null,-1,!1,!1,``]),this.resetCloudProfileRetry()}applyCloudProfiles(e){let t=e.length>0&&!this.gatewayRecoveryScopeValue;this.cloudProfilesValue=t?[]:e;let n=this.read(),r=!!n.pendingPlacement.sessionKey,i=Tt(n.context?.gateway.snapshot.hello?.auth??null);(!this.gatewayConnectedValue||!i)&&!r&&this.callbacks.onCloudProfileCleared(),!r&&n.cloudProfileId&&!e.some(e=>e.id===n.cloudProfileId)?this.callbacks.onCloudState(A(`newSession.catalogUnavailable`)):t?this.callbacks.onCloudState(A(`newSession.cloudRecoveryUnavailable`)):this.callbacks.onCloudState(null)}resetCloudProfileRetry(){globalThis.clearTimeout(this.cloudProfileRetryTimer),this.cloudProfileRetryTimer=void 0,this.cloudProfileRetryAttempt=0}scheduleCloudProfileRetry(){if(this.cloudProfileRetryTimer||!this.gatewayConnectedValue||!this.gatewayClientValue)return;if(this.cloudProfileRetryAttempt>=Oo.length){this.cloudProfilesReadyValue||=(this.applyCloudProfiles([]),!0);return}let e=Oo[this.cloudProfileRetryAttempt];this.cloudProfileRetryAttempt+=1,this.cloudProfileRetryTimer=globalThis.setTimeout(()=>{this.cloudProfileRetryTimer=void 0,this.gatewayConnectedValue&&this.cloudProfileTask.run()},e)}synchronizeIdentityPreferences(e){let t=this.gatewayConnectedValue?this.gatewayClientValue:null,n=this.read().context,r=n?.gateway.snapshot.hello,i=n&&an(n.gateway.snapshot,`users.prefs.get`)===!0&&an(n.gateway.snapshot,`users.prefs.set`)===!0,a=this.callbacks.preferenceScope===`palette`&&t&&r&&e&&i?Cs({client:t,hello:r,profileId:e,gatewayUrl:this.gatewayUrlValue}):void 0;if(a===this.identityPreferences||(this.stopPreferences?.(),this.stopPreferences=void 0,this.identityPreferences=a,!a))return;let o=()=>{this.identityPreferences===a&&this.callbacks.requestUpdate()};this.stopPreferences=a.subscribe(o,()=>this.identityPreferences===a&&this.gatewayConnectedValue&&this.read().context?.gateway.snapshot.client===t&&this.read().context?.gateway.snapshot.hello===r&&this.read().context?.gateway.connection.gatewayUrl===this.gatewayUrlValue),a.mode!==`loading`&&o()}}})))()}function Ps(e){if(!Wa(e))return null;let t=/^[A-Za-z]:[\\/]/u.test(e)?3:1,n=e.search(/[\\/]+$/u);if(n>=0)return{directory:e.slice(0,Math.max(t,n)),prefix:``};let r=Math.max(e.lastIndexOf(`/`),e.lastIndexOf(`\\`));return{directory:e.slice(0,Math.max(t,r)),prefix:e.slice(r+1)}}function Fs(e,t){if(!t)return[...e];let n=t.toLowerCase(),r=[],i=[],a=[],o=[];for(let s of e){if(s.hidden&&!t.startsWith(`.`))continue;let e=s.name.toLowerCase();s.name===t?r.push(s):e===n?i.push(s):e.startsWith(n)?a.push(s):e.includes(n)&&o.push(s)}return[...r,...i,...a,...o]}function Is(e){let{listing:t,draft:n,loading:r}=e,i=Ps(n);if(t&&Ga(n,t.path)||!i){let e=t?.entries??[];return{entries:e,empty:t&&e.length===0&&!r?`no-subfolders`:`none`}}if(t&&Ga(i.directory,t.path)){let e=Fs(t.entries,i.prefix);return{entries:e,empty:e.length===0&&!r?i.prefix?`no-matches`:`no-subfolders`:`none`}}return{entries:[],empty:r?`none`:`no-matches`}}function Ls(){return(Ls=e((()=>{})))()}var Rs;function zs(){return(zs=e((()=>{n(),M(),H(),Ls(),U(),Rs=class{constructor(e,t,n){this.listDirectory=e,this.requestUpdate=t,this.onListing=n,this.listing=null,this.draft=``,this.loading=!1,this.error=null,this.activeIndex=0,this.token=0,this.listingGenerationValue=0}get listingGeneration(){return this.listingGenerationValue}navigate(e){return this.cancelPending(),this.draft=e??``,this.error=null,this.loading=!0,this.requestUpdate(),this.load(e,!0,this.token)}setDraft(e){this.cancelPending(),this.draft=e,this.activeIndex=0,this.error=null;let t=Ps(e.trim());if(this.loading=!(!t||this.draftInLoadedDirectory()),t&&this.loading){let e=this.token;this.timer=globalThis.setTimeout(()=>{this.timer=void 0,this.load(t.directory,!1,e)},300)}this.requestUpdate()}draftInLoadedDirectory(){if(!this.listing)return!1;let e=this.draft.trim(),t=Ps(e);return!t||Ga(e,this.listing.path)||Ga(t.directory,this.listing.path)}moveHighlight(e){let t=this.view().entries.length;t!==0&&(this.activeIndex=(this.activeIndex+e+t)%t,this.requestUpdate())}highlightedEntry(){let e=this.view().entries;return this.activeIndex=Math.max(0,Math.min(this.activeIndex,e.length-1)),e[this.activeIndex]}completeHighlighted(){let e=this.highlightedEntry();return!e||this.draft.trim()===e.path?!1:(this.setDraft(e.path),!0)}async activate(){let e=this.highlightedEntry(),t=this.draft.trim();e?await this.navigate(e.path):(!t||Wa(t))&&await this.navigate(t||void 0)}usablePath(){let e=this.draft.trim();return!e||Wa(e)?e:null}reset(){this.cancelPending(),this.listing=null,this.listingGenerationValue+=1,this.draft=``,this.loading=!1,this.error=null,this.activeIndex=0}view(){let e=this.draft.trim();return Is({listing:this.listing,draft:e,loading:this.loading})}cancelPending(){this.token+=1,globalThis.clearTimeout(this.timer),this.timer=void 0}async load(e,t,n){let r=this.listing,i=this.draft;try{let r=await this.listDirectory(e);if(n!==this.token)return;this.listing=r,this.listingGenerationValue+=1,t&&this.draft===i&&(this.draft=r.path),this.activeIndex=0,this.onListing?.(r)}catch(i){if(n!==this.token)return;t&&(this.error??=m(i)?.missingScope?A(`newSession.browseRequiresAdmin`):A(`newSession.browserLoadFailed`),!r&&e&&(this.draft=``,await this.load(void 0,!0,n)))}finally{n===this.token&&(this.loading=!1,this.requestUpdate())}}}})))()}function Bs(e){let{browser:t,id:n}=e,{entries:r,empty:i}=t.view(),a=t.highlightedEntry(),o=t.usablePath(),s=e.registerProjectPath;return I`
    <div
      class="new-session-page__browser"
      @keydown=${t=>{t.key===`Escape`&&(t.preventDefault(),t.stopImmediatePropagation(),e.onBack())}}
    >
      <div class="new-session-page__browser-head">
        <button
          type="button"
          class="new-session-page__browser-nav"
          title=${A(`newSession.browserUp`)}
          aria-label=${A(`newSession.browserUp`)}
          @click=${()=>{t.listing?.parent?t.navigate(t.listing.parent):e.onBack()}}
        >
          ${P.arrowLeft}
        </button>
        <input
          class="new-session-page__browser-path"
          type="text"
          role="combobox"
          aria-expanded="true"
          aria-autocomplete="list"
          aria-controls=${`${n}-list`}
          aria-activedescendant=${a?`${n}-option-${t.activeIndex}`:L}
          aria-label=${A(`newSession.folder`)}
          placeholder=${e.label}
          .value=${t.draft}
          @input=${e=>{t.setDraft(e.target.value)}}
          @keydown=${e=>{switch(e.key){case`ArrowDown`:case`ArrowUp`:e.preventDefault(),t.moveHighlight(e.key===`ArrowDown`?1:-1),requestAnimationFrame(()=>document.getElementById(`${n}-option-${t.activeIndex}`)?.scrollIntoView({block:`nearest`}));break;case`Enter`:e.preventDefault(),t.activate();break;case`Tab`:!e.shiftKey&&t.completeHighlighted()&&e.preventDefault()}}}
        />
        ${t.loading?I`<span class="new-session-page__browser-loading" role="status"
                >${A(`common.loading`)}</span
              >`:L}
        <button
          type="button"
          class="new-session-page__browser-nav"
          title=${A(`common.close`)}
          aria-label=${A(`common.close`)}
          @click=${e.onClose}
        >
          ${P.x}
        </button>
      </div>
      ${t.error?I`<div class="new-session-page__error" role="alert">${t.error}</div>`:L}
      <div
        class="new-session-page__browser-list"
        role="listbox"
        id=${`${n}-list`}
        aria-label=${A(`newSession.folder`)}
      >
        ${i===`none`?L:I`<div class="new-session-page__browser-empty">
                ${A(i===`no-matches`?`newSession.browserNoMatches`:`newSession.browserEmpty`)}
              </div>`}
        ${r.map((e,r)=>I`
            <button
              type="button"
              role="option"
              id=${`${n}-option-${r}`}
              aria-selected=${r===t.activeIndex}
              class="new-session-page__browser-entry ${r===t.activeIndex?`new-session-page__browser-entry--active`:``} ${e.hidden?`new-session-page__browser-entry--hidden`:``}"
              title=${e.hidden?A(`newSession.hiddenFolder`):L}
              @click=${()=>void t.navigate(e.path)}
            >
              <span class="new-session-page__target-icon" aria-hidden="true">${P.folder}</span>
              <span>${e.name}</span>
            </button>
          `)}
      </div>
      <div class="new-session-page__browser-actions">
        ${s?I`
                <button
                  type="button"
                  class="new-session-page__browser-register"
                  ?disabled=${e.registeringProject}
                  @click=${()=>e.onRegisterProject(s)}
                >
                  ${A(`newSession.registerProject`)}
                </button>
              `:L}
        <button
          type="button"
          class="new-session-page__browser-use"
          ?disabled=${o===null||e.registeringProject}
          @click=${()=>{o!==null&&(e.onApplyFolder(o),e.onClose())}}
        >
          ${A(`newSession.browserUse`)}
        </button>
      </div>
    </div>
  `}function Vs(){return(Vs=e((()=>{R(),F(),M(),H(),U()})))()}function Hs(e,t,n){let r=new Map;for(let[n,i]of e.entries()){let e=t(i);r.set(e,[...r.get(e)??[],n])}let i=e.map(()=>void 0);for(let t of r.values()){if(t.length<2)continue;let r=n.at(-1);if(!r)continue;let a=n.find(n=>{let i=t.map(t=>n(e[t])??r(e[t]));return i.every(e=>e!==void 0)&&new Set(i).size===t.length})??r;for(let n of t)i[n]=a(e[n])??r(e[n])}return i}function Us(e){let t=e.trim();return!t||t.startsWith(`-`)||/\s/u.test(t)?null:/^(?:https:\/\/|ssh:\/\/git@|git@[^:]+:)/iu.test(t)?t:null}function Ws(e){return e.target instanceof HTMLInputElement?e.target.value:``}function Gs(e){let t=e.folder.trim(),n=e.projects.find(t=>t.id===e.projectId),r=e.projectQuery.trim().toLowerCase(),i=r?e.projects.filter(e=>[e.displayName,e.originUrl??``,e.repoRoot??``].join(`
`).toLowerCase().includes(r)):e.projects;return{label:e.freshWorkspace?A(`newSession.newWorkspace`):n?n.displayName:e.selectedRemoteProject?.identity?e.selectedRemoteProject.identity:t?Ka(t):Ka(e.workspace)||A(`newSession.folderPlaceholder`),localProjects:i,recents:r?[]:e.recents.filter(e=>e.kind!==`project`),showWorkspace:!r||[Ka(e.workspace),e.workspace].join(`
`).toLowerCase().includes(r)}}function Ks(e){let t=e.folder.trim(),n=Us(e.projectQuery),r=e.projectQuery.trim(),i=!e.browseAvailable&&!e.isAdmin,a=e.state.recents,o=Hs(a,e=>e.displayName,[e=>e.kind===`folder`?Xa(e.folder):void 0,e=>e.kind===`folder`?e.folder:void 0,e=>e.kind===`folder`?e.folder:e.url]),s=I`
    <button
      type="button"
      class="session-menu__item"
      data-value="browse"
      aria-pressed="false"
      aria-disabled=${i?`true`:L}
      ?disabled=${e.submitting||e.pendingPlacement||!e.browseAvailable&&!i}
      @click=${()=>{e.browseAvailable&&!e.submitting&&!e.pendingPlacement&&e.onBrowse()}}
    >
      <span class="session-menu__check" aria-hidden="true"></span>
      <span class="session-menu__text">${A(`newSession.browse`)}</span>
      <span class="new-session-page__menu-chevron" aria-hidden="true">${P.chevronRight}</span>
    </button>
  `;return I`
    <span class="new-session-page__select">
      <button
        id=${(e.idPrefix??`new-session`)+`-project-trigger`}
        type="button"
        class="new-session-page__trigger ${e.popoverHiding?`new-session-page__trigger--hiding`:``}"
        aria-label="${A(`newSession.what`)}: ${e.state.label}"
        data-project-id=${e.projectId||L}
        aria-haspopup="dialog"
        aria-expanded=${String(e.popoverOpen)}
        ?disabled=${e.submitting||e.pendingPlacement}
        @click=${e.onGuardTransition}
      >
        <span class="new-session-page__target-icon" aria-hidden="true"
          >${e.projectId?P.gitBranch:P.folder}</span
        >
        <span class="new-session-page__trigger-label">${e.state.label}</span>
        <span
          class="new-session-page__trigger-chevron new-session-page__trigger-chevron--desktop"
          aria-hidden="true"
          >${P.chevronDown}</span
        >
        <span
          class="new-session-page__trigger-chevron new-session-page__trigger-chevron--mobile"
          aria-hidden="true"
          >${P.chevronsUpDown}</span
        >
      </button>
    </span>
    <wa-popover
      ${zt(Mr)}
      class="new-session-page__select new-session-page__project-popover new-session-page__picker-popover"
      for=${(e.idPrefix??`new-session`)+`-project-trigger`}
      placement="bottom-start"
      without-arrow
      @wa-show=${e.onPopoverShow}
      @wa-hide=${e.onPopoverHide}
      @wa-after-hide=${e.onPopoverAfterHide}
    >
      ${e.browserOpen?Bs({browser:e.browser,id:(e.idPrefix??`new-session`)+`-place-browser`,label:e.gatewayLabel,registerProjectPath:e.registerProjectPath,registeringProject:e.registeringProject,onBack:e.onBrowserBack,onRegisterProject:e.onRegisterProject,onClose:e.onClose,onApplyFolder:e.onApplyFolder}):I`
              <div class="new-session-page__picker-root">
                <div class="new-session-page__menu-title">${A(`newSession.projects`)}</div>
                ${I`
                  ${e.onNewWorkspace&&!r?Y({value:`new-workspace`,label:A(`newSession.newWorkspace`),icon:P.folder,sub:A(`newSession.newWorkspaceDescription`),checked:e.freshWorkspace===!0,onSelect:e.onNewWorkspace},e.submitting||e.pendingPlacement):L}
                  ${e.workspace&&e.state.showWorkspace?Y({value:`workspace`,label:Ka(e.workspace),icon:P.folder,checked:!e.freshWorkspace&&!e.projectId&&t===e.workspace,onSelect:()=>e.onApplyFolder(e.workspace)},e.submitting):L}
                  <label class="new-session-page__project-search">
                    <span class="sr-only">${A(`newSession.projectSearchPlaceholder`)}</span>
                    <input
                      type="search"
                      placeholder=${A(`newSession.projectSearchPlaceholder`)}
                      .value=${e.projectQuery}
                      ?disabled=${e.submitting||e.pendingPlacement}
                      @input=${t=>e.onProjectQueryInput(Ws(t))}
                      @keydown=${t=>{t.key===`Enter`&&n&&e.projectAddAvailable&&(t.preventDefault(),e.onSelectRemoteProject({identity:n,cloneUrl:n}))}}
                    />
                  </label>
                  ${e.state.localProjects.map(t=>Y({value:`project:${t.id}`,label:t.displayName,icon:P.gitBranch,checked:e.projectId===t.id,title:t.repoRoot,onSelect:()=>e.onSelectProject(t.id)},e.submitting))}
                  ${n&&e.projectAddAvailable?Y({value:`project-clone-url`,label:n,icon:P.gitBranch,sub:A(`newSession.cloneProject`),checked:e.selectedRemoteProject?.cloneUrl===n,onSelect:()=>e.onSelectRemoteProject({identity:n,cloneUrl:n})},e.submitting):L}
                  ${!n&&r.length>=2&&e.projectSearchAvailable?I`
                          <div class="new-session-page__menu-title">
                            ${A(`newSession.githubProjects`)}
                          </div>
                          ${e.projectSearchCredentialMissing?I`<div class="new-session-page__menu-note">
                                  ${A(`newSession.githubTokenHint`)}
                                </div>`:L}
                          ${e.projectSearchLoading?I`<div class="new-session-page__project-status" role="status">
                                  ${A(`common.loading`)}
                                </div>`:L}
                          ${e.projectSearchError?I`<div class="new-session-page__project-error" role="alert">
                                  ${e.projectSearchError}
                                </div>`:L}
                          ${e.remoteProjects.map(t=>Y({value:`remote-project:${t.fullName}`,label:t.fullName,icon:P.gitBranch,sub:t.description??A(`newSession.cloneProject`),checked:e.selectedRemoteProject?.cloneUrl===t.cloneUrl,title:t.webUrl,onSelect:()=>e.onSelectRemoteProject({identity:t.fullName,cloneUrl:t.cloneUrl})},e.submitting||!e.projectAddAvailable))}
                        `:L}
                  ${e.projects.length===0&&e.canWrite&&!e.isAdmin?I`<div class="new-session-page__menu-note">
                          ${A(`newSession.projectsAdminHint`)}
                        </div>`:L}
                `}
                ${e.state.recents.length>0?I`
                        <div class="new-session-page__menu-title">
                          ${A(`newSession.recentFolders`)}
                        </div>
                        ${a.map((n,r)=>Y({value:n.kind===`repository`?`repository:${n.url}`:`recent:${n.folder}`,label:n.displayName,icon:n.kind===`folder`?P.folder:P.gitBranch,sub:o[r],checked:n.kind===`repository`?e.selectedRemoteProject?.cloneUrl===n.url:!e.freshWorkspace&&!e.projectId&&t===n.folder,title:n.kind===`repository`?n.url:n.folder,onSelect:()=>n.kind===`repository`?e.onSelectRemoteProject({identity:n.displayName,cloneUrl:n.url}):e.onApplyFolder(n.folder)},e.submitting))}
                      `:L}
                ${i?I`<openclaw-tooltip .content=${A(`newSession.browseRequiresAdmin`)}>
                        ${s}
                      </openclaw-tooltip>`:s}
              </div>
            `}
    </wa-popover>
  `}function qs(){return(qs=e((()=>{R(),Bt(),F(),Vr(),M(),H(),es(),Vs(),U()})))()}function Js(e,t){let n=new Set,r=[];for(let i of e){let e=D(i.execCwd)??D(i.worktree?.repoRoot),a=D(i.execNode);if(e&&!a&&e!==t.workspace&&t.allowGatewayFolder(e)&&!n.has(e)&&(n.add(e),r.push({folder:e}),r.length>=4))break}return r}function Ys(){return(Ys=e((()=>{})))()}var Xs;function Zs(){return(Zs=e((()=>{dr(),He(),on(),jn(),zs(),qs(),Ys(),Xs=class{constructor(e,t,n,r){this.host=e,this.gateway=t,this.read=n,this.callbacks=r,this.lastProjectResult=null,this.projectSelection=null,this.projectQueryValue=``,this.environmentQueryValue=``,this.debouncedProjectQuery=``,this.browserOpenValue=!1,this.browserProjectPathValue=null,this.browserRegistrationId=null,this.browserRegistrationCounter=0,this.openPopoverValue=null,this.focusRequestId=0,this.hidingPopovers=new Set,this.browser=new Rs(e=>{let t=this.read().context?.gateway.snapshot;return t?.phase!==`connected`||!t.client||!this.browserOpenValue?Promise.reject(Error(`Folder browser is unavailable`)):t.client.request(`fs.listDir`,e?{path:e}:{})},this.callbacks.requestUpdate,e=>{this.browserProjectPathValue=null,this.callbacks.onApprovedListing(e);let t=this.read(),n=t.context?.gateway.snapshot.client;t.isAdmin&&n&&n.request(`worktrees.branches`,{repoRoot:e.path,includeRepositoryStatus:!0}).then(t=>{this.browser.listing===e&&t.repositoryStatus===`git`&&(this.browserProjectPathValue=e.path,this.callbacks.requestUpdate())}).catch(()=>void 0)}),e.addController({hostUpdate:()=>this.bindProjectCatalog()}),this.projectSearchTask=new fr(e,{args:()=>[this.read().context&&this.gateway.connected?this.gateway.client:null,this.read().context?rn(this.read().context?.gateway.snapshot,`projects.searchRemote`,`operator.read`):!1,this.debouncedProjectQuery,this.gateway.connectionEpoch],task:([e,t,n],{signal:r})=>!e||!t||n.length<2||Us(n)?gr:e.request(`projects.searchRemote`,{query:n},{signal:r})})}get projects(){return this.projectCatalog?.snapshot.result?.projects??[]}get projectsReady(){return this.projectCatalog?.snapshot.ready??!1}get projectRecents(){return this.projectCatalog?.snapshot.result?.recents}get projectId(){return this.projectSelection?.kind===`local`?this.projectSelection.id:``}get remoteProject(){return this.projectSelection?.kind===`remote`?this.projectSelection.project:null}get projectQuery(){return this.projectQueryValue}get environmentQuery(){return this.environmentQueryValue}changeEnvironmentQuery(e){this.environmentQueryValue=e,this.callbacks.requestUpdate()}get projectSearchResult(){return this.projectSearchTask.status===pr.COMPLETE&&this.debouncedProjectQuery===this.projectQueryValue.trim()?this.projectSearchTask.value??null:null}get projectSearchLoading(){return this.debouncedProjectQuery.length>=2&&this.debouncedProjectQuery===this.projectQueryValue.trim()&&this.projectSearchTask.status===pr.PENDING}get projectSearchError(){if(this.projectSearchTask.status!==pr.ERROR||this.debouncedProjectQuery!==this.projectQueryValue.trim())return null;let e=this.projectSearchTask.error;return pe(e)}get browserOpen(){return this.browserOpenValue}get browserProjectPath(){return this.browser.loading||!this.browser.draftInLoadedDirectory()?null:this.browserProjectPathValue}get browserRegistering(){return this.browserRegistrationId!==null}popoverOpen(e){return this.openPopoverValue===e}popoverHiding(e){return this.hidingPopovers.has(e)}popoverCallbacks(e){return{popoverOpen:this.popoverOpen(e),popoverHiding:this.popoverHiding(e),onGuardTransition:t=>this.guardPopoverTransition(t,e),onPopoverShow:()=>this.onPopoverShow(e),onPopoverHide:()=>this.onPopoverHide(e),onPopoverAfterHide:()=>this.onPopoverAfterHide(e)}}bindProjectCatalog(){let e=this.gateway.connected?this.read().context?.gateway:void 0;if(e===this.projectCatalogGateway)return;this.projectCatalogCleanup?.(),this.projectCatalogGateway=e,this.projectCatalog=e?hn(e):void 0,this.lastProjectResult=null;let t=()=>{let e=this.projectCatalog?.snapshot.result??null;e&&e!==this.lastProjectResult&&(this.lastProjectResult=e,this.projectId&&!e.projects.some(e=>e.id===this.projectId)&&this.callbacks.onProjectMissing()),this.callbacks.requestUpdate()};this.projectCatalogCleanup=this.projectCatalog?.subscribe(t),t()}async refreshProjects(e=!1){this.bindProjectCatalog(),await this.projectCatalog?.refresh(e)}selectedProject(){return this.projects.find(e=>e.id===this.projectId)??(this.gateway.connected?void 0:this.selectedProjectRecord)}selectProject(e){this.projectSelection=e,this.selectedProjectRecord=this.projects.find(e=>e.id===this.projectId)}recordRemoteProjectId(e,t){let n=this.remoteProject;n?.cloneUrl===e&&(this.projectSelection={kind:`remote`,project:{...n,projectId:t}})}clearProjectSelection(){this.projectSelection=null,this.selectedProjectRecord=void 0}resolveProjectRecents(e){let t=t=>e.isAdmin||Ya(e.workspaceRoots,t);return this.projectRecents?.filter(e=>e.kind===`project`?this.projects.some(t=>t.id===e.projectId):e.kind===`repository`||!e.execNode&&t(e.folder))??Js(e.sessions,{workspace:e.workspace,allowGatewayFolder:t}).map(e=>({kind:`folder`,folder:e.folder,displayName:Ka(e.folder)}))}changeProjectQuery(e){this.projectQueryValue=e,this.clearProjectSearchTimer(),this.debouncedProjectQuery=``,this.projectSearchTask.run([null,!1,``,this.gateway.connectionEpoch]);let t=e.trim(),n=this.read().context;if(t.length<2||Us(t)||!this.gateway.connected||!this.gateway.client||!n||!rn(n.gateway.snapshot,`projects.searchRemote`,`operator.read`)){this.callbacks.requestUpdate();return}let r=this.gateway.client,i=this.gateway.connectionEpoch;this.projectSearchTimer=globalThis.setTimeout(()=>{this.projectSearchTimer=void 0,r===this.gateway.client&&i===this.gateway.connectionEpoch&&(this.debouncedProjectQuery=t,this.projectSearchTask.run([r,!0,t,i]),this.callbacks.requestUpdate())},300),this.callbacks.requestUpdate()}resetProjectSearch(){this.clearProjectSearchTimer(),this.projectQueryValue=``,this.debouncedProjectQuery=``,this.callbacks.requestUpdate()}resetProjects(e=!0){this.projectCatalog&&this.refreshProjects(!0),e&&(this.clearProjectSelection(),this.resetProjectSearch())}close(){this.resetBrowser(!0);for(let e of[`where`,`project`,`checkout`]){let t=this.callbacks.querySelector(`.new-session-page__${e}-popover`);t&&(t.open=!1)}}showRoot(){let e=this.browserOpenValue;this.resetBrowser(!1),e&&this.focusProjectView(`[data-value="browse"]`)}selectGatewayBrowser(e){this.browserOpenValue=!0,this.loadBrowser(e&&Wa(e)?e:void 0),this.focusProjectView(`.new-session-page__browser-path`)}loadBrowser(e){let t=this.read().context?.gateway.snapshot;t?.phase===`connected`&&t.client&&this.browserOpenValue&&(this.browserProjectPathValue=null,this.browser.navigate(e))}async registerBrowserProject(e){let t=this.read(),n=t.context?.gateway.snapshot,r=n?.client;if(n?.phase!==`connected`||!r||!t.isAdmin||this.browserProjectPath!==e||this.browserRegistering)return;let i=this.browser.listingGeneration,a=++this.browserRegistrationCounter;this.browserRegistrationId=a;let o=()=>this.browserRegistrationId===a&&this.browser.listingGeneration===i&&this.browserProjectPath===e&&r===this.gateway.client;this.browser.error=null,this.callbacks.requestUpdate();try{let t=await r.request(`projects.register`,{path:e});if(!o()||(await this.refreshProjects(!0),!o()))return;this.callbacks.onSelectProject(t.id),this.close()}catch(e){o()&&(this.browser.error=pe(e))}finally{this.browserRegistrationId===a&&(this.browserRegistrationId=null,this.callbacks.requestUpdate())}}onPopoverShow(e){this.openPopoverValue=e,e===`where`&&(this.environmentQueryValue=``),e===`project`?this.showRoot():this.callbacks.requestUpdate()}onPopoverHide(e){this.openPopoverValue===e&&(this.openPopoverValue=null),this.hidingPopovers.add(e),e===`project`?this.showRoot():this.callbacks.requestUpdate()}onPopoverAfterHide(e){this.hidingPopovers.delete(e),this.restorePopoverTrigger(`${this.callbacks.pickerIdPrefix??`new-session`}-${e}-trigger`,`.new-session-page__${e}-popover`),this.callbacks.requestUpdate()}guardPopoverTransition(e,t){this.hidingPopovers.has(t)&&(e.preventDefault(),e.stopImmediatePropagation())}clearPopoverHiding(){this.hidingPopovers.clear(),this.callbacks.requestUpdate()}disconnect(){this.focusRequestId+=1,this.environmentQueryValue=``,this.browser.reset(),this.clearProjectSearchTimer(),this.projectCatalogCleanup?.(),this.projectCatalogCleanup=void 0,this.projectCatalogGateway=void 0,this.projectCatalog=void 0,this.projectSearchTask.run([null,!1,``,-1])}resetBrowser(e){this.focusRequestId+=1,this.browser.reset(),this.browserOpenValue=!1,this.browserProjectPathValue=null,this.browserRegistrationId=null,e&&(this.openPopoverValue=null),this.callbacks.requestUpdate()}clearProjectSearchTimer(){globalThis.clearTimeout(this.projectSearchTimer),this.projectSearchTimer=void 0}focusProjectView(e){let t=++this.focusRequestId,n=this.callbacks.activeElement();this.host.updateComplete.then(()=>{if(t!==this.focusRequestId||this.openPopoverValue!==`project`||this.hidingPopovers.has(`project`))return;let r=this.callbacks.activeElement();if(r&&r!==n&&r!==this.callbacks.body())return;let i=this.callbacks.querySelector(`.new-session-page__project-popover`)?.querySelector(e);i?.isConnected&&i.focus({preventScroll:!0})})}restorePopoverTrigger(e,t){let n=this.callbacks.activeElement(),r=this.callbacks.querySelector(t),i=this.callbacks.body();(!n||n===i||r?.contains(n))&&this.callbacks.querySelector(`#${e}`)?.focus()}}})))()}function Qs(e){if(e.connected)return;let t=e.environment;if(t?.lastConnectedAtMs===void 0)return A(`newSession.neverConnected`);if(t.lastDisconnectedAtMs!==void 0){let n=gn(Math.max(0,e.nowMs-t.lastDisconnectedAtMs))??A(`common.justNow`);return A(`newSession.offlineFor`,{duration:n})}let n=t.lastSeenAtMs??t.lastConnectedAtMs;return A(`newSession.lastSeen`,{time:be(n)})}function $s(e,t={}){let n=e?.issues?.find(e=>e.code===`update-required`),r=e?.issues?.find(e=>e.code===`worker-host-unavailable`),i=Qs({environment:e,connected:t.connected??!0,nowMs:t.nowMs??Date.now()}),a=n?A(`newSession.nodeUpdateRequired`,{updateCommand:n.updateCommand,restartCommand:n.headlessReconnectCommand}):r?.message??i,o=a?[a]:[];e?.platform&&o.push(Cn(e.platform));for(let t of ec(e?.capabilities))if(o.includes(t)||o.push(t),o.length>=4)break;return o}function ec(e=[]){return[...new Set(e.flatMap(e=>{let t=e.split(`.`,1)[0]?.toLowerCase(),n=Object.entries(tc).find(([e])=>e===t)?.[1];return n?[A(n)]:[]}))]}var tc;function nc(){return(nc=e((()=>{M(),H(),Pn(),we(),bn(),U(),tc={camera:`newSession.capabilityCamera`,location:`newSession.capabilityLocation`,talk:`newSession.capabilityTalk`,screen:`newSession.capabilityScreenCapture`,canvas:`newSession.capabilityCanvas`,microphone:`newSession.capabilityVoice`,voice:`newSession.capabilityVoice`}})))()}function rc(e,t){let n=e.issues?.find(e=>e.code===`update-required`);if(n)return A(`newSession.nodeUpdateRequired`,{updateCommand:n.updateCommand,restartCommand:n.headlessReconnectCommand});let r=e.issues?.find(e=>e.code===`worker-host-unavailable`);if(r)return r.message;if(e.status!==`available`)return A(`newSession.deviceUnavailable`);if(e.sessionHost!==!0)return A(`newSession.sessionHostingDisabled`);if(t.requiredNodeCommands.length>0){let t=e.requiredNodeCommand;if(!t)return A(`newSession.placementNotReady`);if(t.state!==`invocable`&&t.message)return t.message;if(t.state===`pending-approval`)return A(`newSession.nodeCommandPendingApproval`,{command:t.command});if(t.state===`undeclared`)return A(`newSession.nodeCommandUndeclared`,{command:t.command});if(t.state===`unauthorized`)return A(`newSession.nodeCommandUnauthorized`,{command:t.command})}if(t.consumesWorkerSlot)return e.workerSlots?tn(e.workerSlots)===0?A(`newSession.deviceNoSlots`):void 0:A(`newSession.deviceCapacityUnavailable`)}function ic(e,t=sc,n){let r=(e??[]).flatMap(e=>{if(e.type!==`node`||!e.id.startsWith(`node:`))return[];let r=e.id.slice(5).trim();if(!r)return[];let i=n??rc(e,t),a=$s(e,{connected:e.status===`available`}),o=+((e.issues?.length??0)>0||e.status!==`available`),s=i&&!a.includes(i)?[...a.slice(0,o),i,...a.slice(o)].slice(0,4):a;return[{deviceId:r,label:e.label??r,platform:e.platform,hideDetails:!n&&e.status===`unavailable`&&!e.issues?.length,remediation:n?void 0:e.issues?.some(e=>e.code===`update-required`)?`update-device`:e.status===`available`&&e.sessionHost!==!0&&!e.issues?.length?`enable-session-hosting`:void 0,facts:n?[n]:s,workerSlots:e.workerSlots,capabilities:e.capabilities,invocableCommands:e.invocableCommands,selectable:i===void 0,...i?{disabledReason:i}:{}}]}).toSorted((e,t)=>e.label.localeCompare(t.label)||e.deviceId.localeCompare(t.deviceId)),i=Hs(r,e=>e.label,[e=>e.deviceId.slice(0,8)]),a=[];for(let[e,t]of r.entries()){let n=i[e];a.push(n?{...t,subtitle:n}:t)}return a}function ac(e,t,n){if(n)return n;let r=new Set((e??[]).filter(e=>e.type===`node`&&e.sessionHost===!0).map(e=>e.id));if(r.size===0){let t=(e??[]).find(e=>e.issues?.some(e=>e.code===`update-required`||e.code===`worker-host-unavailable`));return t?rc(t,sc):A(`newSession.noSessionHosts`)}return t.some(e=>e.selectable)?void 0:t.find(e=>r.has(`node:${e.deviceId}`))?.disabledReason}function oc(e,t,n){let r=e.find(e=>e.deviceId===n.deviceId);return{ready:n.autoDevice?e.some(e=>e.selectable):!n.deviceId||r?.selectable===!0,disabledReason:n.autoDevice?ac(t,e):n.deviceId?r?.disabledReason??A(`newSession.nodeUnavailable`):void 0}}var sc;function cc(){return(cc=e((()=>{nn(),M(),H(),nc(),U(),sc={requiredNodeCommands:[],consumesWorkerSlot:!0}})))()}var lc;function uc(){return(uc=e((()=>{Go(),lc=class{constructor(){this.overrides=new Map}clear(){this.overrides.clear()}applyPending(e,t,n){t||n?this.overrides.set(e,{machineClass:t,os:n}):this.overrides.delete(e)}resolve(e){return this.overrides.get(e)?.machineClass??``}resolveOs(e){return this.overrides.get(e)?.os??``}selection(e,t){let n=t.find(t=>t.id===e),r=this.resolveOs(e)||n&&Ro(n)||``;return{machineClass:this.resolve(e)||n&&Bo(n,r)?.id||``,os:r}}selectedOs(e){return this.resolveOs(e.id)||Ro(e)}machines(e){return zo(e,this.selectedOs(e))}selectOs(e,t,n,r=!1,i){let a=n.find(t=>t.id===e),o=a?.operatingSystems?.find(e=>e.id===t);if(r||!a||!o||o.disabledReason)return!1;let s=this.resolve(e);return this.applyPending(e,zo(a,o.id).some(e=>e.id===s)?s:void 0,o.id),i?.(),!0}select(e,t,n,r=!1,i){let a=n.find(t=>t.id===e),o=a&&this.machines(a).find(e=>e.id===t);return r||!o?!1:(this.applyPending(e,o.id,this.selectedOs(a)),i?.(),!0)}}})))()}function dc(e){if(e.remoteProject)return{kind:`pending-clone`,cloneUrl:e.remoteProject.cloneUrl};let t=e.selectedProject?.repoRoot??(e.folder.trim()||e.workspace);return!t||e.selectedProject&&!e.selectedProject.repoRoot?{kind:`idle`}:!e.selectedProject&&t===e.workspace&&!e.workspaceGit?{kind:`direct`,repoRoot:t}:{kind:`checking`,repoRoot:t}}var fc;function pc(){return(pc=e((()=>{j(),fc=class{constructor(e,t){this.read=e,this.callbacks=t,this.worktreeValue=!1,this.worktreeNameValue=``,this.repositoryValue={kind:`idle`},this.requestToken=0,this.selectionRevision=0,this.preferredWorktreeRestore=!1,this.worktreeSelectedByUser=!1,this.baseRefSelectedByUser=!1,this.nameSelectedByUser=!1}get worktree(){return this.worktreeValue}get preferenceWorktree(){return this.worktreeValue||this.preferredWorktreeRestore}get worktreeName(){return this.worktreeNameValue}get baseRef(){return this.baseRefOverride??``}get remoteRepository(){let{remotePlacement:e,remoteProject:t}=this.read();if(!e||!t)return;let n=this.baseRef.trim();return{url:t.cloneUrl,...n?{ref:n}:{}}}get repository(){return this.repositoryValue}get preferenceReady(){return!this.preferredWorktreeRestore}get hasUserSelection(){return this.worktreeSelectedByUser||this.baseRefSelectedByUser||this.nameSelectedByUser}adoptPreference(e){if(this.worktreeSelectedByUser||(this.worktreeValue=!1,this.preferredWorktreeRestore=e?.worktree===!0),!this.baseRefSelectedByUser){let t=e?.baseRef||void 0;this.baseRefOverride!==t&&(this.selectionRevision+=1),this.baseRefOverride=t}if(!this.nameSelectedByUser){let t=e?.worktreeName??``;this.worktreeNameValue!==t&&(this.selectionRevision+=1),this.worktreeNameValue=t}this.matchesCurrentRepo()?this.repositoryValue.kind!==`checking`&&this.adoptResolvedRepository(this.repositoryValue):this.invalidate()}reset(){this.invalidate(),this.worktreeValue=!1,this.clearDetails(),this.preferredWorktreeRestore=!1,this.worktreeSelectedByUser=!1}clearDetails(e=!1){this.selectionRevision+=1,this.baseRefOverride=void 0,this.worktreeNameValue=``,this.baseRefSelectedByUser=!1,this.nameSelectedByUser=!1,e&&this.callbacks.persistPreference({baseRef:``,worktreeName:``})}invalidate(){this.requestToken+=1,this.repositoryValue={kind:`idle`}}selectWorktree(e,t=!0){this.selectionRevision+=1,this.preferredWorktreeRestore=!1,this.worktreeSelectedByUser=!0,this.worktreeValue=e,t&&this.clearDetails(!0)}forceWorktree(e){this.selectionRevision+=1,this.worktreeValue=e}rejectPreferredWorktree(){this.preferredWorktreeRestore=!1,this.worktreeValue=!1,this.clearDetails(!0)}select(e){this.worktreeValue===e||this.read().remotePlacement||(this.selectWorktree(e,!1),this.callbacks.persistPreference({folder:this.read().folder.trim()||this.read().workspace,worktree:this.worktreeValue}),this.worktreeValue&&!this.available()&&this.load(),this.callbacks.requestUpdate())}setBaseRef(e,t){t||(this.selectionRevision+=1,this.baseRefOverride=e,this.baseRefSelectedByUser=!0,this.callbacks.persistPreference({baseRef:e}),this.callbacks.requestUpdate())}setWorktreeName(e,t){t||(this.selectionRevision+=1,this.worktreeNameValue=e,this.nameSelectedByUser=!0,this.callbacks.persistPreference({worktreeName:e}),this.callbacks.requestUpdate())}captureSubmittedName(e,t){let n=e.worktreeName?.trim();if(!e.worktree||!n)return;let r=this.selectionRevision,i=this.read(),a=g(t.agentId),o=i.agents.find(e=>g(e.id)===a),s={agentId:a,workspace:D(o?.workspace)??``},c=s.agentId===i.agentId,l=this.callbacks.capturePreferenceConsumption(s,{worktreeName:n,...t.recovered?{}:{selectedBaseRef:this.baseRefOverride?.trim()??``},folder:e.cwd??(c&&i.folder.trim()||s.workspace),baseRef:e.worktreeBaseRef??(c?this.baseRef:void 0),projectId:e.projectId??(c?i.selectedProject?.id:void 0)});return l&&(()=>l(()=>{s.agentId===this.read().agentId&&r===this.selectionRevision&&n===this.worktreeNameValue.trim()&&(this.selectionRevision+=1,this.worktreeNameValue=``,this.nameSelectedByUser=!0,this.callbacks.requestUpdate())}))}available(){let e=this.repositoryValue;return e.kind===`git`||e.kind===`pending-clone`}matchesCurrentRepo(){let e=this.read(),t=this.repositoryValue;if(t.kind===`pending-clone`)return e.remoteProject?.cloneUrl===t.cloneUrl;if(t.kind===`idle`||e.remoteProject)return!1;let n=e.selectedProject?.repoRoot??(e.folder.trim()||e.workspace);return t.repoRoot===n}load(){let e=++this.requestToken,t=this.read(),n=dc(t);if(n.kind!==`checking`)return this.adoptResolvedRepository(n);let r=t.gateway?.client;if(t.gateway?.phase!==`connected`||!r)return this.adoptResolvedRepository({kind:`idle`});let{repoRoot:i}=n;this.repositoryValue=n,r.request(`worktrees.branches`,{repoRoot:i,includeRepositoryStatus:!0}).then(t=>{e===this.requestToken&&this.adoptResolvedRepository(t?.repositoryStatus===`git`?{kind:`git`,repoRoot:i,branches:t.branches,...t.defaultBranch?{defaultBranch:t.defaultBranch}:{},...t.headBranch?{headBranch:t.headBranch}:{},...t.branchesUnavailable?{branchesUnavailable:!0}:{}}:{kind:t?.repositoryStatus===`not_git`?`direct`:`unavailable`,repoRoot:i})}).catch(()=>{e===this.requestToken&&this.adoptResolvedRepository({kind:`unavailable`,repoRoot:i})})}synchronize(){this.matchesCurrentRepo()||this.load()}adoptResolvedRepository(e){if(this.repositoryValue=e,e.kind===`direct`){if(!this.read().remotePlacement){let e=this.worktreeValue||this.preferredWorktreeRestore;this.worktreeValue=!1,e&&this.callbacks.persistPreference({worktree:!1})}}else this.preferredWorktreeRestore&&!this.worktreeSelectedByUser&&(this.worktreeValue=!0);this.preferredWorktreeRestore=!1,this.callbacks.requestUpdate()}}})))()}function mc(e){return e instanceof tt&&e.gatewayCode===`INVALID_REQUEST`&&/^(?:Error:\s+)?(?:ENOENT|ENOTDIR):/u.test(e.message)}var hc;function gc(){return(gc=e((()=>{St(),hc=class{constructor(e,t){this.read=e,this.callbacks=t,this.state=`none`,this.requestToken=0,this.approvedRoots=[]}knownWorkspaceRoots(e){return e?[e,...this.approvedRoots]:this.approvedRoots}recordApprovedListing(e){if(this.read().isAdmin)return;let t=new Set(this.approvedRoots);t.add(e.path),e.parent&&t.add(e.parent),t.size!==this.approvedRoots.length&&(this.approvedRoots=[...t],this.callbacks.onApprovedRootsChange())}reset(){this.cancel(),this.approvedRoots=[]}get blocked(){return this.state!==`none`}cancel(){this.requestToken+=1,this.state=`none`}restore(){this.state=`none`,this.callbacks.onMissing()}validate(e){let t=this.read().gateway,n=t?.client;if(t?.phase!==`connected`||!n){this.restore();return}let r=++this.requestToken;this.state=`checking`;let i=()=>{let t=this.read();return r===this.requestToken&&!t.selectedByUser&&t.folder===e};n.request(`fs.listDir`,{path:e}).then(e=>{i()&&(this.recordApprovedListing(e),this.state=`none`,this.callbacks.onVerified())}).catch(e=>{if(i()){if(!this.read().isAdmin||mc(e)){this.restore();return}this.state=`failed`,this.callbacks.onFailed()}})}}})))()}function _c(){return{catalog:[],hasSnapshot:!1,status:`idle`}}function vc(e){let{model:t,selection:n,metadata:r,agent:i,defaults:a}=e,o=r.modelSelectionPolicy,s=o?.restricted?o.defaultModel??void 0:i?.model?.primary,c=X(o?.restricted?o.defaultModel:s??a?.model,o?.restricted||s?void 0:a?.modelProvider,r.catalog),l=X(t,void 0,r.catalog,n.agentRuntime),u=l?.entry??c?.entry;return{defaultTarget:c,agentDefaultModel:s,modelCatalogState:{hasSnapshot:i!==void 0&&r.hasSnapshot,initialized:!r.retired&&(r.initialized??r.hasSnapshot),refreshFailed:r.refreshFailed,pendingProviders:r.pendingProviders,modelSelectionPolicy:o,retired:r.retired,status:!i&&r.status!==`error`?`loading`:r.status},contextWindowTarget:yc(u,n.contextWindow),fastModeTarget:{agentRuntime:u?.agentRuntime,model:l?.model??c?.model,modelProvider:l?.provider??c?.provider??void 0,fastMode:n.fastMode,effectiveFastMode:n.fastMode??u?.effectiveFastMode},thinkingDefaults:xc(c,o?.restricted?void 0:i,o?.restricted?void 0:a,r.catalog),thinkingSession:bc(l,void 0,n)}}function yc(e,t){let n=t||e?.contextWindowDefault;return e?.contextWindows&&n?{contextWindow:n,contextWindows:e.contextWindows,...e.contextWindowDefault?{contextWindowDefault:e.contextWindowDefault}:{}}:void 0}function bc(e,t,n){let r=n?.agentRuntime?e?.entry:void 0;return{model:e?.model??t?.model?.primary,modelProvider:e?.provider??void 0,agentRuntime:t?.agentRuntime??e?.entry?.agentRuntime,thinkingLevels:t?.thinkingLevels??r?.thinkingLevels,thinkingOptions:t?.thinkingOptions,thinkingDefault:t?.thinkingDefault??r?.thinkingDefault,thinkingLevel:n?.thinkingLevel||void 0}}function xc(e,t,n,r){let i=Nn(bc(e,t),n,r);return{modelProvider:e?.provider??null,model:e?.model??null,contextTokens:n?.contextTokens??null,agentRuntime:i?.agentRuntime,thinkingLevels:i?.thinkingLevels,thinkingDefault:i?.thinkingDefault}}function X(e,t,n,r){let i=fe(e,t,n);if(!i)return null;let a=i.toLowerCase(),o=n.find(e=>ae(e.id,e.provider).toLowerCase()===a);if(o)return{entry:yn(o,r),model:o.id,provider:Ce(o.provider)||null};let s=i.indexOf(`/`);return s>0?{model:i.slice(s+1),provider:Ce(i.slice(0,s))||null}:{model:i,provider:Ce(t??``)||null}}function Sc(e){let{metadata:t,agent:n}=e;if(!t.hasSnapshot||t.status===`offline`)return;let r=t.modelSelectionPolicy,i=e.model||(r?.restricted?r.defaultModel??void 0:n?.model?.primary);return e.agentRuntime?X(i,void 0,t.catalog,e.agentRuntime)?.entry?.unavailableReason:cn(i,void 0,t.catalog)}function Cc(e,t,n){let r=X(e.model,void 0,t,n);return r?.entry?.available===!0&&r.entry.manualSelectionAllowed!==!1&&r.provider===e.provider}function wc(e){let{metadata:t,model:n,agentRuntime:r}=e;if(t.retired||e.initialModelPending||!t.hasSnapshot&&(n||r))return A(t.status===`error`?`chat.modelControls.modelsUnavailable`:`chat.modelControls.loadingModels`);if(t.modelSelectionPolicy?.restricted&&!n&&!t.modelSelectionPolicy.defaultModel)return A(t.catalog.length?`chat.modelControls.selectionRequired`:`chat.modelControls.noPermittedModels`);if(r&&t.hasSnapshot&&!X(n,void 0,t.catalog,r)?.entry)return A(`chat.modelControls.modelsUnavailable`);let i=ur(Sc(e));if(e.accountSelected){if(t.status===`error`)return A(`chat.modelControls.modelsUnavailable`);if(e.metadataPending||!t.hasSnapshot)return A(`chat.modelControls.loadingModels`);if(!e.accountReady)return i??A(`chat.modelControls.modelsUnavailable`)}return i}function Tc(e){if(e.retired)return;let t=e.modelSelectionPolicy,n=e.model||(t?.restricted?t.defaultModel??``:``),r;if(n)r=X(n,void 0,e.catalog,e.agentRuntime)?.entry?.agentRuntime;else if(!t?.restricted){let t=e.agent?.model?.primary;r=X(t??e.defaults?.model,t?void 0:e.defaults?.modelProvider,e.catalog)?.entry?.agentRuntime??e.agent?.agentRuntime??e.defaults?.agentRuntime}let i=r?.id.trim();if(r&&i&&i!==`auto`&&i!=="default")return i===r.id?r:{...r,id:i}}function Ec(e){let t=e.model.trim(),n=t?X(t,void 0,e.catalog,e.agentRuntime):null;if(t&&(!n?.entry||n.entry.available===!1||n.entry.manualSelectionAllowed===!1))return{model:``,thinkingLevel:``,repaired:!0};let r=n?.entry?ae(n.entry.id,n.entry.provider):``,i=e.modelSelectionPolicy,a=i?.restricted?void 0:e.agent,o=i?.restricted?void 0:e.defaults,s=i?.restricted?i.defaultModel:a?.model?.primary,c=r?null:X(s??o?.model,s?void 0:o?.modelProvider,e.catalog),l=(n??c)?.provider,u=n?.entry??c?.entry,d=u?.supportsFastMode??(!l||cr(l))?e.fastMode:void 0,f={model:r,...r&&e.agentRuntime?{agentRuntime:e.agentRuntime}:{},fastMode:d},p=d!==e.fastMode;if(!e.thinkingLevel)return{...f,thinkingLevel:``,repaired:p};let m=Nn(bc(n??c,r?void 0:a,{agentRuntime:e.agentRuntime}),r?void 0:o,e.catalog)?.thinkingLevels,h=mn(e.thinkingLevel),g=m?.some(e=>mn(e.id)===h);return u?.reasoning===!1||m!==void 0&&!g?{...f,thinkingLevel:``,repaired:!0}:{...f,thinkingLevel:e.thinkingLevel,repaired:p}}function Dc(e){return e&&!e.devicePlacement?A(`newSession.deviceRuntimeUnsupported`):void 0}function Oc(e,t){return e?.cloudPlacementSupported===!1?A(`newSession.cloudRuntimeUnsupported`,{runtime:e.id}):e&&t&&e.cloudPlacementExecutionMode&&!Po(t,e.cloudPlacementExecutionMode)?A(`newSession.cloudProfileRuntimeUnsupported`,{runtime:e.id}):void 0}function kc(){return(kc=e((()=>{M(),Sn(),H(),ye(),un(),On(),Go(),U(),fn()})))()}var Ac;function jc(){return(jc=e((()=>{kc(),Ac=class{constructor(e){this.onSelectionChange=e,this.explicitSelection=!1,this.restoredSelection=!1,this.fastModeSelected=!1,this.selected=``,this.contextWindow=``,this.thinkingLevel=``}resetSelection(e=``){this.selected=e,this.agentRuntime=void 0,this.contextWindow=``,this.thinkingLevel=``,this.fastMode=void 0,this.explicitSelection=!1,this.restoredSelection=!1,this.fastModeSelected=!1}applyModelSelection(e){this.selected=e.model,this.agentRuntime=e.agentRuntime,this.thinkingLevel=e.thinkingLevel,this.fastMode=e.fastMode}draftSelection(e){return this.explicitSelection?{agentId:e,model:this.selected,agentRuntime:this.agentRuntime,thinkingLevel:this.thinkingLevel}:void 0}preferenceForDraft(e,t){let n=this.fastModeSelected||e===void 0?this.fastMode:e?.fastMode;return this.explicitSelection?{model:this.selected,agentRuntime:this.agentRuntime,thinkingLevel:this.thinkingLevel,fastMode:n}:t.initialModel?t.initialModelPending?{model:t.initialModel}:void 0:t.policy===`configured`||t.policy===null?{fastMode:n}:this.fastModeSelected?{...e,fastMode:n}:e}takeDraftSelection(e,t,n){let r=this.pendingDraftSelection;if(t&&r&&r.agentId===e&&(this.pendingDraftSelection=void 0,!this.explicitSelection||this.restoredSelection))return this.explicitSelection=!0,this.restoredSelection=!0,this.selected=r.model,this.agentRuntime=r.agentRuntime,this.thinkingLevel=r.thinkingLevel,this.fastModeSelected||(this.fastMode=n??this.fastMode),{...r,fastMode:this.fastMode}}markExplicitSelection(){this.explicitSelection=!0,this.restoredSelection=!1}retireModelSelection(e){return e&&!this.restoredSelection?!1:(this.restoredSelection=!1,this.explicitSelection=!1,e||(this.fastModeSelected=!1),this.pendingDraftSelection=void 0,this.selected=``,this.agentRuntime=void 0,this.thinkingLevel=``,this.contextWindow=``,!0)}restoreModelPreference(e,t,n){if(!e)return;let r=Ec({model:e.model??``,agentRuntime:e.agentRuntime,thinkingLevel:e.thinkingLevel??``,fastMode:e.fastMode,...t});this.applyModelSelection(r),r.repaired&&n&&this.persistSelection(e.agentRuntime?this.agentRuntime??``:void 0)}persistSelection(e=this.agentRuntime){this.onSelectionChange({model:this.selected,...e===void 0?{}:{agentRuntime:e},thinkingLevel:this.thinkingLevel,fastMode:this.fastMode})}}})))()}var Mc;function Nc(){return(Nc=e((()=>{b(),vt(),ye(),un(),On(),Xe(),$a(),nr(),j(),Xr(),Da(),Aa(),q(),jc(),kc(),vs(),Mc=class extends Ac{constructor(e,t=()=>void 0,n=()=>void 0){super(t),this.notify=e,this.onCatalogTargetSelect=n,this.selectionGeneration=0,this.initialModelPending=!1,this.agentId=``,this.metadataState=_c(),this.restoringPreference=!1,this.pendingSelectionGeneration=0,this.catalogTargets=new Do(e),this.metadataReader=new Qa(()=>{if(this.metadataClient&&this.metadataScope&&!this.ownsMetadata(this.metadataClient,this.metadataScope)){this.restoringPreference=!1,this.draftAccount=void 0,this.clearMetadataSubscription(),this.updateMetadataState({catalog:[],hasSnapshot:!1,status:`offline`});return}if(this.metadataReader.pending){let e=this.metadataReader.snapshot;e.retired?this.metadataState={catalog:[],hasSnapshot:!1,retired:!0,status:`loading`}:e.hasSnapshot&&!this.metadataState.hasSnapshot&&this.assignMetadataCatalog(e,!0),this.updateMetadataState({...this.metadataState,status:this.metadataState.hasSnapshot?this.metadataState.status===`error`?`error`:`ready`:`loading`})}else this.notify()},{timeoutMs:ie,onResult:e=>{this.metadataClient&&this.metadataScope&&this.ownsMetadata(this.metadataClient,this.metadataScope)&&this.publishMetadataCatalog(e)},onError:()=>{this.metadataClient&&this.metadataScope&&this.ownsMetadata(this.metadataClient,this.metadataScope)&&this.metadataFailed()}})}get catalog(){return this.metadataState.catalog}get effectiveModel(){return this.draftAccount?.model??this.selected}clearMetadataSubscription(){this.metadataReader.clear(),this.metadataScope=void 0,this.metadataGateway=void 0}ownsMetadata(e,t){let n=this.pendingContext?.gateway.snapshot;return this.metadataClient===e&&this.metadataGateway===this.pendingContext?.gateway&&this.metadataScope===t&&n?.phase===`connected`&&n.client===e&&n.hello===this.metadataHello&&n.selfUser?.id===this.metadataIdentityId}bindMetadataSubscription(e,t){if(this.metadataScope&&this.metadataClient===e&&this.metadataGateway===this.pendingContext?.gateway&&this.metadataScope.agentId===t.agentId&&this.metadataScope.authProfileId===t.authProfileId)return this.metadataScope;this.clearMetadataSubscription(),this.metadataClient=e,this.metadataScope=t;let n=this.pendingContext?.gateway;return this.metadataGateway=n,n&&this.metadataReader.bind(n,t),t}loadCatalogTargets(e,t,n){this.catalogTargets.load(e,t,n)}updateMetadataState(e){this.metadataState={...e,initialized:!e.retired&&e.status!==`offline`&&(e.hasSnapshot||Me(this.metadataClient))},this.notify()}assignMetadataCatalog(e,t=!1){this.metadataState={...this.metadataState,catalog:e.models,displayOnly:t,...Kn(e)}}publishMetadataCatalog(e){if(this.assignMetadataCatalog(e),this.metadataState.accountSelection=e.accountSelection,!this.draftAccount&&this.pendingSelectionGeneration===this.selectionGeneration&&(this.initialModelPending&&!e.modelSelectionPolicy?.restricted?this.resetSelection(this.initialModel):this.restorePreference()),this.initialModelPending=!1,!this.draftAccount&&e.modelSelectionPolicy?.restricted&&this.selected){let t=Ec({model:this.selected,agentRuntime:this.agentRuntime,thinkingLevel:this.thinkingLevel,fastMode:this.fastMode,modelSelectionPolicy:e.modelSelectionPolicy,catalog:e.models});this.applyModelSelection(t)}this.restoringPreference=!1,this.notify()}metadataFailed(){!this.metadataState.retired&&!this.metadataState.modelSelectionPolicy?.restricted&&!this.draftAccount&&this.pendingSelectionGeneration===this.selectionGeneration&&(this.initialModelPending?(this.resetSelection(this.initialModel),this.initialModelPending=!1):this.pendingPreference&&(this.selected=this.pendingPreference.model??``,this.agentRuntime=this.pendingPreference.agentRuntime,this.thinkingLevel=this.pendingPreference.thinkingLevel??``,this.fastMode=this.pendingPreference.fastMode)),this.restoringPreference=!1,this.updateMetadataState({...this.metadataState,status:`error`})}selectDraftAccount(e,t){let n=this.metadataClient;if(!n||!t)return Promise.resolve(!1);this.selectionGeneration+=1,this.restoringPreference=!1,this.draftAccount={authProfileId:e.authProfileId,provider:e.provider,model:t};let r={agentId:this.agentId,authProfileId:e.authProfileId};this.metadataState={catalog:[],accountSelection:this.metadataState.accountSelection,hasSnapshot:!1,status:`loading`};let i=this.bindMetadataSubscription(n,r);return this.metadataReader.read().then(e=>!!e&&this.ownsMetadata(n,i))}clearDraftAccount(){return this.draftAccount?(this.draftAccount=void 0,this.clearMetadataSubscription(),this.metadataState=_c(),!0):!1}retryPickerCatalogs(){let e=this.metadataClient,t=this.metadataScope;!this.metadataReader.pending&&e&&t&&this.metadataReader.read(),this.catalogTargets.retry(e,this.agentId)}invalidate(e=!1){if(!e&&this.metadataClient&&et(this.metadataClient,this.metadataScope),this.clearDraftAccount(),this.clearMetadataSubscription(),this.catalogTargets.clear(),this.restoringPreference=!1,e){this.pendingDraftSelection=void 0,this.agentId=``,this.metadataClient=void 0,this.resetSelection(),this.initialModel=void 0,this.initialModelPending=!1,this.updateMetadataState(_c());return}this.updateMetadataState({...this.metadataState,status:this.metadataState.hasSnapshot?this.metadataState.status:`idle`})}reset(){this.invalidate(!0)}load(e,t,n,r={}){let i=e?.gateway.snapshot,a=i?.client,o=t.trim()?g(t):``;if(this.pendingContext=e,(this.agentId!==o||this.metadataClient&&this.metadataClient!==a||this.metadataGateway&&this.metadataGateway!==e?.gateway||this.metadataIdentityId!==i?.selfUser?.id||this.metadataHello&&this.metadataHello!==i?.hello)&&(this.draftAccount=void 0,this.clearMetadataSubscription(),this.agentId!==o&&(this.resetSelection(),this.initialModel=void 0,this.initialModelPending=!1),this.agentId=o,this.metadataClient=void 0,this.metadataState=_c()),this.metadataIdentityId=i?.selfUser?.id,this.metadataHello=i?.hello,!e||i?.phase!==`connected`||!a||!o||!n){this.clearDraftAccount(),this.clearMetadataSubscription(),this.metadataClient=void 0,this.restoringPreference=!1,e&&i?.phase!==`connected`&&(this.metadataState={catalog:[],hasSnapshot:!1,status:`offline`}),this.notify();return}let s=r.initialModel;s&&s!==this.initialModel&&(this.resetSelection(),this.selectionGeneration+=1,this.initialModel=s,this.initialModelPending=!0);let c=this.selectionGeneration,l={agentId:o,...this.draftAccount?{authProfileId:this.draftAccount.authProfileId}:{}},u=this.metadataScope,d=this.bindMetadataSubscription(a,l)!==u;if(this.pendingPreference=this.preferenceForDraft(r.preference,{policy:e.config?.current.newSessionModelDefaults,initialModel:this.initialModel,initialModelPending:this.initialModelPending}),this.pendingAgent=r.agent,this.pendingSelectionGeneration=c,this.applyPendingDraftSelection(),this.restoringPreference=!this.draftAccount&&rs(this.pendingPreference),this.metadataReader.pending){this.notify();return}if(!d&&this.metadataState.status!==`idle`){this.metadataState.status===`ready`&&this.metadataState.hasSnapshot&&!this.draftAccount&&this.pendingSelectionGeneration===this.selectionGeneration&&this.restorePreference(),this.restoringPreference=!1;return}this.metadataReader.read()}isRestoringPreference(){return this.restoringPreference}requiresModelSetup(e){return Kr({...e,modelSelectionPolicy:this.metadataState.modelSelectionPolicy,catalogInitialized:this.metadataState.hasSnapshot&&!this.metadataState.retired})}modelUnavailableReason(e){return Sc({model:this.effectiveModel,agentRuntime:this.agentRuntime,metadata:this.metadataState,agent:e})}modelSelectionBlockedReason(e){return wc({model:this.effectiveModel,agentRuntime:this.agentRuntime,metadata:this.metadataState,agent:e,initialModelPending:this.initialModelPending,accountSelected:!!this.draftAccount,accountReady:this.accountSelectionReady(),metadataPending:this.metadataReader.pending})}modelForSubmission(){return this.draftAccount?`${this.draftAccount.model}@${this.draftAccount.authProfileId}`:this.selected}accountSelectionReady(){if(!this.draftAccount)return!0;let e=this.metadataState.accountSelection;return!this.metadataClient||!this.metadataScope||!this.ownsMetadata(this.metadataClient,this.metadataScope)||this.metadataReader.pending||this.metadataState.status!==`ready`||e?.kind!==`personal`||e.authProfileId!==this.draftAccount.authProfileId?!1:Cc(this.draftAccount,this.catalog,this.agentRuntime)}restorePreference(){let e=this.metadataState.modelSelectionPolicy;this.restoreModelPreference(this.pendingPreference,{agent:this.pendingAgent,defaults:this.pendingContext?.sessions.state.result?.defaults,modelSelectionPolicy:e,catalog:this.catalog},!this.initialModelPending&&!e?.restricted&&this.pendingContext?.config?.current.newSessionModelDefaults!==`configured`&&this.pendingContext?.config?.current.newSessionModelDefaults!==null)}restoreDraftSelection(e){this.pendingDraftSelection=e,e||this.retireDraftSelection(!0),this.applyPendingDraftSelection()}retireDraftSelection(e=!1){this.retireModelSelection(e)&&(this.pendingSelectionGeneration=++this.selectionGeneration,this.pendingPreference={fastMode:this.fastMode},!e&&this.clearDraftAccount()&&this.load(this.pendingContext,this.agentId,!0,{agent:this.pendingAgent}),this.notify())}applyPendingDraftSelection(){let e=this.takeDraftSelection(this.agentId,this.pendingContext?.config?.current.newSessionModelDefaults===`configured`,this.pendingPreference?.fastMode);e&&(this.selectionGeneration+=1,this.initialModelPending=!1,this.pendingPreference=e,this.pendingSelectionGeneration=this.selectionGeneration,this.metadataState.status===`ready`&&this.restorePreference(),this.notify())}resolveAgentRuntime(e={agent:this.pendingAgent,context:this.pendingContext}){return Tc({model:this.effectiveModel,agentRuntime:this.agentRuntime,agent:e.agent,defaults:e.context?.sessions.state.result?.defaults,catalog:this.metadataState.displayOnly?[]:this.catalog,modelSelectionPolicy:this.metadataState.modelSelectionPolicy,retired:this.metadataState.retired})}devicePlacementUnsupportedReason(){return Dc(this.resolveAgentRuntime())}autoPlacementSelectionMode(){return this.resolveAgentRuntime()?.cloudPlacementExecutionMode===`remote-exec`?`eligible-order`:`least-busy`}cloudRuntimeUnsupportedReason(e){return Oc(this.resolveAgentRuntime(),e)}render(e){let t=e.context?.gateway.snapshot,n=`new-session:${g(e.agentId)}`,r=e.context?.sessions.state.result??null,i=e.agent!==void 0,{defaultTarget:a,...o}=vc({model:this.effectiveModel,selection:this,metadata:this.metadataState,agent:e.agent,defaults:r?.defaults}),s=t?.client,c=this.metadataScope,l=this.metadataState.accountSelection,u=()=>!!(s&&c&&this.ownsMetadata(s,c)&&this.metadataState.accountSelection===l);return ya({...o,renderAccountSection:n=>fa({owner:this,client:s,selection:u()&&t?.selfUser?l:void 0,model:n,disabled:e.sending||!n||!Tt(t?.hello?.auth??null),ownsSelection:u,onSelect:e=>u()?this.selectDraftAccount(e,n):Promise.resolve(!1),onAutomatic:this.draftAccount?()=>{u()&&(this.selectionGeneration+=1,this.clearDraftAccount(),this.load(e.context,e.agentId,!0,{agent:e.agent}))}:void 0,onManage:()=>e.context?.navigate(`profile`),onRequestUpdate:this.notify}),activeRunId:null,connected:t?.phase===`connected`,gatewayAvailable:!!t?.client,loading:!1,modelCatalog:this.catalog,modelOverrides:{[n]:this.effectiveModel||null},modelPickerTargetGroups:this.catalogTargets.groups(),modelSwitching:!1,sending:e.sending,sessionKey:n,selectedSession:void 0,selectedAgentRuntime:this.agentRuntime,sessionsResult:i?r:null,stream:null,onModelSelect:(t,n,r)=>{this.selectionGeneration+=1,this.initialModelPending=!1,this.restoringPreference=!1;let i=Ec({model:t,agentRuntime:r??void 0,thinkingLevel:this.thinkingLevel,fastMode:this.fastMode,agent:e.agent,defaults:e.context?.sessions.state.result?.defaults,modelSelectionPolicy:this.metadataState.modelSelectionPolicy,catalog:this.catalog});if(i.model===this.effectiveModel&&i.agentRuntime===this.agentRuntime&&i.fastMode===this.fastMode&&mn(i.thinkingLevel)===mn(this.thinkingLevel))return;this.metadataState.displayOnly=!1;let o=this.agentRuntime!==i.agentRuntime;this.applyModelSelection(i),this.markExplicitSelection();let s=X(i.model,void 0,this.catalog,this.agentRuntime)??a;this.draftAccount&&this.draftAccount.provider!==s?.provider?(this.clearDraftAccount(),this.load(e.context,e.agentId,!0,{agent:e.agent})):this.draftAccount&&s&&(this.draftAccount={...this.draftAccount,model:ae(s.model,s.provider)}),this.contextWindow=``,this.persistSelection(o?this.agentRuntime??``:void 0),this.onDraftSelectionChange?.()},onModelPickerTargetSelect:(e,t)=>{e===`cliAgents`&&this.onCatalogTargetSelect(t)},onModelPickerTargetRetry:e=>{e===`cliAgents`&&this.catalogTargets.retry(this.metadataClient,this.agentId)},onThinkingSelect:e=>{this.selectionGeneration+=1,this.restoringPreference=!1,this.thinkingLevel=e,this.markExplicitSelection(),this.persistSelection(),this.onDraftSelectionChange?.()},onFastModeSelect:e=>{this.selectionGeneration+=1,this.restoringPreference=!1,this.fastModeSelected=!0,this.fastMode=Dn(e),this.persistSelection(),this.notify()},onContextWindowSelect:e=>{this.selectionGeneration+=1,this.restoringPreference=!1,this.contextWindow=e,this.notify()},onModelSetup:()=>e.context?.navigate(`model-setup`),onProviderSettings:t=>Ua(e.context,e.agentId,t),onModelPickerOpen:()=>this.retryPickerCatalogs(),onRequestUpdate:this.notify})}}})))()}var Pc;function Fc(){return(Fc=e((()=>{vt(),M(),H(),Se(),j(),q(),cc(),uc(),pc(),gc(),Nc(),vs(),U(),Pc=class{get terminalOnNode(){return this.terminalHostId.startsWith(`node:`)}selectTerminalHost(e){this.read().submitting||(this.terminalHostInitialized=!0,e!==this.terminalHostId&&(this.terminalHostId=e,this.folderValidation.cancel(),this.browser.clearProjectSelection(),this.repositoryState.reset(),this.folderValue=this.terminalOnNode?``:this.workspacePath(),this.folderSelectedByUser=!0,this.terminalOnNode||this.repositoryState.load(),this.callbacks.requestUpdate()))}synchronizeTerminalHosts(){let e=this.read().data?.terminalHosts;!this.terminalHostInitialized&&e?.length&&this.selectTerminalHost(e.find(e=>e.hostId===this.terminalHostId)?.hostId??e[0].hostId)}constructor(e,t,n,r){this.gateway=e,this.browser=t,this.read=n,this.callbacks=r,this.terminalHostId=`gateway:local`,this.terminalHostInitialized=!1,this.agentIdValue=``,this.folderValue=``,this.freshWorkspaceValue=!0,this.deviceIdValue=``,this.autoDeviceValue=!1,this.cloudProfileIdValue=``,this.cloudMachines=new lc,this.agentsHydratedValue=!1,this.agentSelectedByUser=!1,this.routeModelIntentActive=!0,this.folderSelectedByUser=!1,this.preferredWhereRestore=null,this.preferredProjectRestore=``,this.whereSelectedByUser=!1,this.projectSelectedByUser=!1,this.folderValidation=new hc(()=>({gateway:this.read().context?.gateway.snapshot,folder:this.folderValue,selectedByUser:this.folderSelectedByUser,isAdmin:this.isAdmin()}),{onApprovedRootsChange:r.requestUpdate,onVerified:()=>{this.callbacks.onClearError(A(`newSession.browserLoadFailed`)),this.repositoryState.load()},onMissing:()=>this.restoreWorkspaceFolder(),onFailed:()=>this.callbacks.onError(A(`newSession.browserLoadFailed`))}),this.repositoryState=new fc(()=>({agentId:this.agentIdValue,agents:this.agents(),remotePlacement:this.remotePlacement,selectedProject:this.browser.selectedProject(),remoteProject:this.browser.remoteProject,folder:this.folderValue,workspace:this.workspacePath(),workspaceGit:this.selectedAgent()?.workspaceGit===!0,gateway:this.read().context?.gateway.snapshot}),{requestUpdate:r.requestUpdate,persistPreference:e=>this.persistPreference(e),capturePreferenceConsumption:(e,t)=>this.gateway.capturePreferenceConsumption(e.agentId,e.workspace,t)}),this.modelControl=new Mc(r.requestUpdate,e=>this.persistPreference(e),e=>this.read().context?.navigate(`new-session`,{search:ge(this.agentIdValue,{catalogId:e})}))}get agentId(){return this.agentIdValue}get folder(){return this.folderValue}get worktree(){return(this.freshWorkspace||this.repositoryState.worktree)&&!this.remoteRepository}get freshWorkspace(){return this.remotePlacement&&this.freshWorkspaceValue}get remoteRepository(){return this.repositoryState.remoteRepository}get worktreeName(){return this.freshWorkspace?``:this.repositoryState.worktreeName}get baseRef(){return this.freshWorkspace?``:this.repositoryState.baseRef}get repository(){return this.repositoryState.repository}get deviceId(){return this.deviceIdValue}get autoDevice(){return this.autoDeviceValue}get remotePlacement(){return!!(this.deviceIdValue||this.autoDeviceValue||this.cloudProfileIdValue)}get cloudProfileId(){return this.cloudProfileIdValue}get cloudSelection(){return this.cloudMachines.selection(this.cloudProfileIdValue,this.gateway.cloudProfiles)}get agentsHydrated(){return this.agentsHydratedValue}preferenceSelection(){let e=this.preferredWhereRestore??ns(this);return{workspace:this.workspacePath(),folder:this.folderValue,projectId:this.preferredProjectRestore||this.browser.projectId,where:e,worktree:(e.kind!==`local`&&this.freshWorkspaceValue||this.repositoryState.preferenceWorktree)&&!this.remoteRepository,freshWorkspace:this.freshWorkspaceValue,baseRef:this.repositoryState.baseRef,worktreeName:this.repositoryState.worktreeName}}get placementPreferenceReady(){return(this.freshWorkspace||this.repositoryState.preferenceReady)&&this.preferredWhereRestore===null&&!this.preferredProjectRestore}canAdoptGroupDefaults(){return!this.folderSelectedByUser&&!this.whereSelectedByUser&&!this.projectSelectedByUser&&!this.repositoryState.hasUserSelection}adoptGroupDefaults(){this.read().data?.groupStatus===`resolved`&&this.canAdoptGroupDefaults()&&this.adoptAgentDefaults({preserveSelectedAgent:!0})}setAgentsHydrated(e){this.agentsHydratedValue=e}agents(){return de(this.read().context?.agents.state.agentsList?.agents??[])}selectedAgent(){let e=g(this.agentIdValue);return this.agents().find(t=>g(t.id)===e)}devicePlacementRuntime(){return this.modelControl.resolveAgentRuntime({agent:this.selectedAgent(),context:this.read().context})}devices(){return ic(this.gateway.environments,this.devicePlacementRuntime()?.devicePlacement,this.gateway.deviceCatalogDisabledReason)}findDevice(e){return this.devices().find(t=>t.deviceId===e)}devicePlacementReady(){return this.devicePlacement().ready}devicePlacementDisabledReason(){return this.devicePlacement().disabledReason}devicePlacement(){return oc(this.devices(),this.gateway.environments,this)}isAdmin(){return wt(this.read().context?.gateway.snapshot.hello?.auth??null)}canWrite(){return Tt(this.read().context?.gateway.snapshot.hello?.auth??null)}workspacePath(){return D(this.selectedAgent()?.workspace)??``}knownWorkspaceRoots(){return this.folderValidation.knownWorkspaceRoots(this.workspacePath())}recordGatewayApprovedListing(e){this.folderValidation.recordApprovedListing(e)}folderSubmissionBlocked(){return this.freshWorkspace?!1:this.browser.projectId||this.browser.remoteProject?!this.browser.remoteProject&&!this.browser.selectedProject():this.folderValidation.blocked}adoptAgentDefaults(e={}){let t=this.read(),n=this.agents(),r=t.context?.agents.state.agentsList?.defaultId,i=n.some(e=>e.id===r)?r??``:n[0]?.id??``;if(e.preserveSelectedAgent&&this.agentSelectedByUser&&this.selectedAgent()||(this.agentIdValue=xo(t.data,n,i),this.agentSelectedByUser=!1),K(t.data)&&this.terminalOnNode){this.callbacks.requestUpdate();return}let a=this.agentIdValue?this.gateway.readPreference(this.agentIdValue):null,o=e.preserveSelectedFolder&&this.folderSelectedByUser;if(!o&&!t.pendingPlacementSessionKey){let e=this.workspacePath(),n=is(a,e),r=!!t.data?.group,i=t.data?.groupCwd??``,o=t.data?.groupWorktree===!0;this.folderValue=r?i||e:n.folder,this.projectSelectedByUser||(this.freshWorkspaceValue=!r&&n.freshWorkspace),this.folderSelectedByUser=!1,this.repositoryState.adoptPreference(r?{worktree:o}:a);let s=r||K(t.data)?{kind:`local`}:a?.where??{kind:`local`};this.whereSelectedByUser||(this.preferredWhereRestore=s.kind===`local`?null:s),this.preferredProjectRestore=r||K(t.data)?``:a?.projectId??``,this.projectSelectedByUser=!1,n.workspaceMoved&&!r&&this.persistPreference({folder:e})}o&&!t.pendingPlacementSessionKey&&this.agentIdValue&&this.persistPreference({folder:this.folderValue,worktree:this.worktree}),this.remotePlacement&&this.repositoryState.forceWorktree(!0),this.modelControl.load(t.context,this.agentIdValue,!K(t.data),{agent:this.selectedAgent(),preference:a,initialModel:this.routeModelIntentActive?fo(t.data,this.agentIdValue):void 0}),this.preferredProjectRestore?this.folderValidation.cancel():!this.folderSelectedByUser&&this.folderValue!==this.workspacePath()&&!t.pendingPlacementSessionKey?this.folderValidation.validate(this.folderValue):(this.folderValidation.cancel(),this.repositoryState.synchronize()),this.callbacks.requestUpdate()}resetPlaceSelection(){this.freshWorkspaceValue=!0,this.folderSelectedByUser=!1,this.folderValidation.reset(),this.preferredWhereRestore=null,this.preferredProjectRestore=``,this.whereSelectedByUser=!1,this.projectSelectedByUser=!1,this.deviceIdValue=``,this.autoDeviceValue=!1,this.cloudProfileIdValue=``,this.repositoryState.reset()}resetDraft(){this.routeModelIntentActive=!0,this.terminalHostId=`gateway:local`,this.terminalHostInitialized=!1,this.agentSelectedByUser=!1,this.folderValue=``,this.browser.clearProjectSelection(),this.resetPlaceSelection(),this.browser.resetProjectSearch(),this.modelControl.reset(),this.cloudMachines.clear(),this.callbacks.requestUpdate()}invalidateGatewayDiscovery(e){if(this.repositoryState.invalidate(),this.agentsHydratedValue=!1,this.modelControl.invalidate(e),this.browser.close(),this.folderValidation.reset(),this.browser.resetProjectSearch(),this.browser.resetProjects(e),!e){this.callbacks.requestUpdate();return}this.agentIdValue=``,this.agentSelectedByUser=!1,this.folderValue=``,this.resetPlaceSelection(),this.cloudMachines.clear(),this.callbacks.requestUpdate()}applyPendingPlacement(e){this.agentIdValue=e.agentId,this.deviceIdValue=e.deviceId??``,this.autoDeviceValue=e.autoDevice===!0,this.cloudProfileIdValue=e.profileId,this.cloudMachines.applyPending(e.profileId,e.machineClass,e.os),this.repositoryState.forceWorktree(!0),this.folderValue=e.cwd??``,this.freshWorkspaceValue=e.worktreeSource===`empty`,this.freshWorkspaceValue&&this.browser.clearProjectSelection(),e.repository&&(this.browser.selectProject({kind:`remote`,project:{identity:e.repository.url,cloneUrl:e.repository.url}}),this.repositoryState.setBaseRef(e.repository.ref??``,!1),this.repositoryState.load()),this.callbacks.requestUpdate()}clearCloudProfile(){this.cloudProfileIdValue=``,this.browser.close(),this.callbacks.requestUpdate()}clearProjectSelection(){(this.browser.projectId||this.browser.remoteProject)&&this.repositoryState.clearDetails(!0),this.browser.clearProjectSelection(),this.repositoryState.load(),this.callbacks.requestUpdate()}selectAgentId(e){let t=this.read();t.submitting||t.pendingPlacementSessionKey||K(t.data)||g(e)!==g(this.agentIdValue)&&(this.agentIdValue=g(e),this.routeModelIntentActive=!1,this.modelControl.reset(),this.callbacks.onError(null),this.agentSelectedByUser=!0,this.browser.clearProjectSelection(),this.resetPlaceSelection(),this.browser.close(),this.adoptAgentDefaults({preserveSelectedAgent:!0}))}applyFolder(e){let t=this.read();if(!(t.submitting||t.pendingPlacementSessionKey)){if(this.browser.clearProjectSelection(),this.folderValidation.cancel(),this.callbacks.onError(null),this.folderValue=e.trim(),this.freshWorkspaceValue=!1,this.folderSelectedByUser=!0,this.projectSelectedByUser=!0,this.preferredProjectRestore=``,K(t.data)&&this.terminalOnNode){this.callbacks.requestUpdate();return}this.repositoryState.selectWorktree(this.remotePlacement),this.agentsHydratedValue&&this.persistPreference({folder:this.folderValue,projectId:``,worktree:this.worktree,freshWorkspace:!1}),this.repositoryState.load()}}selectNewWorkspace(){let e=this.read();e.submitting||e.pendingPlacementSessionKey||!this.remotePlacement||(this.folderValidation.cancel(),this.browser.clearProjectSelection(),this.browser.resetProjectSearch(),this.callbacks.onError(null),this.folderValue=this.workspacePath(),this.folderSelectedByUser=!0,this.projectSelectedByUser=!0,this.preferredProjectRestore=``,this.freshWorkspaceValue=!0,this.repositoryState.selectWorktree(!0),this.persistPreference({folder:this.folderValue,projectId:``,worktree:!0,freshWorkspace:!0}),this.browser.close(),this.callbacks.requestUpdate())}selectProjectId(e){let t=this.browser.projects.find(t=>t.id===e);t&&this.selectProject({kind:`local`,id:t.id})}selectRemoteProject(e){this.selectProject({kind:`remote`,project:e})}selectProject(e){let t=this.read();t.submitting||t.pendingPlacementSessionKey||(this.browser.selectProject(e),this.freshWorkspaceValue=!1,this.folderValidation.cancel(),this.browser.resetProjectSearch(),this.callbacks.onError(null),this.folderSelectedByUser=!1,this.projectSelectedByUser=!0,this.preferredProjectRestore=``,this.repositoryState.selectWorktree(this.remotePlacement),e.kind===`local`&&this.persistPreference({projectId:e.id,where:ns(this),worktree:this.worktree,worktreeName:``,freshWorkspace:!1}),this.repositoryState.load(),this.browser.close())}selectDevice(e,t=!1){let n=this.read();n.submitting||n.pendingPlacementSessionKey||e&&this.findDevice(e)?.selectable!==!0||t&&!this.devices().some(e=>e.selectable)||(e!==this.deviceIdValue||t!==this.autoDeviceValue||this.cloudProfileIdValue)&&(this.folderValidation.cancel(),this.deviceIdValue=e,this.autoDeviceValue=t,this.cloudProfileIdValue=``,this.whereSelectedByUser=!0,this.preferredWhereRestore=null,this.repositoryState.forceWorktree(!!(e||t)),this.persistPreference({where:ns({cloudProfileId:``,deviceId:e,autoDevice:t}),projectId:this.browser.projectId,folder:this.folderValue,worktree:!!(e||t)||this.worktree,freshWorkspace:this.freshWorkspaceValue}),this.browser.close(),this.repositoryState.synchronize(),this.callbacks.requestUpdate())}selectCloudProfile(e){let t=this.read(),n=this.gateway.cloudProfiles.find(t=>t.id===e);t.submitting||t.pendingPlacementSessionKey||!this.isAdmin()||!n||this.modelControl.cloudRuntimeUnsupportedReason(n)||(this.cloudProfileIdValue=e,this.deviceIdValue=``,this.autoDeviceValue=!1,this.whereSelectedByUser=!0,this.preferredWhereRestore=null,this.callbacks.onError(null),this.repositoryState.forceWorktree(!0),this.persistPreference({where:{kind:`cloud`,id:e},projectId:this.browser.projectId,worktree:!0,freshWorkspace:this.freshWorkspaceValue}),this.repositoryState.synchronize(),this.callbacks.requestUpdate())}selectWorktree(e){e&&this.freshWorkspaceValue&&!this.remotePlacement&&!this.read().submitting&&(this.freshWorkspaceValue=!1,this.persistPreference({freshWorkspace:!1})),this.repositoryState.select(e)}setBaseRef(e){this.repositoryState.setBaseRef(e,this.read().submitting)}setWorktreeName(e){this.repositoryState.setWorktreeName(e,this.read().submitting)}captureSubmittedWorktreeName(e,t,n=!1){return this.repositoryState.captureSubmittedName(e,{agentId:t,recovered:n})}restorePreferenceSelections(){let e=!1,t=this.whereSelectedByUser?null:this.preferredWhereRestore,n=this.projectSelectedByUser?``:this.preferredProjectRestore;if(n){let t=this.browser.projects.find(e=>e.id===n);t?(this.browser.selectProject({kind:`local`,id:t.id}),this.folderSelectedByUser=!1,this.preferredProjectRestore=``,e=!0):this.browser.projectsReady&&(this.preferredProjectRestore=``,e=!0)}if((t?.kind===`device`||t?.kind===`auto-device`)&&this.gateway.cloudProfilesReady)this.autoDeviceValue=t.kind===`auto-device`,this.deviceIdValue=t.kind===`device`?t.id:``,this.cloudProfileIdValue=``,this.repositoryState.forceWorktree(this.remotePlacement),this.preferredWhereRestore=null,e=!0;else if(t?.kind===`cloud`&&this.gateway.cloudProfilesReady){let n=this.gateway.cloudProfiles.find(e=>e.id===t.id);this.isAdmin()&&n&&!this.modelControl.cloudRuntimeUnsupportedReason(n)?(this.deviceIdValue=``,this.autoDeviceValue=!1,this.cloudProfileIdValue=t.id,this.repositoryState.forceWorktree(!0)):(this.cloudProfileIdValue=``,this.persistPreference({where:{kind:`local`}})),this.preferredWhereRestore=null,e=!0}e&&(this.repositoryState.synchronize(),this.callbacks.requestUpdate())}browseAvailable(){return this.gateway.connected&&(this.isAdmin()||!!this.workspacePath())}worktreeAvailable(){return this.repositoryState.available()}persistPreference(e){this.gateway.persistPreference(this.agentIdValue,this.workspacePath(),e)}restoreWorkspaceFolder(){this.callbacks.onClearError(A(`newSession.browserLoadFailed`)),this.folderValue=this.workspacePath(),this.repositoryState.rejectPreferredWorktree(),this.persistPreference({folder:this.folderValue,worktree:!1}),this.repositoryState.load()}}})))()}var Ic;function Lc(){return(Lc=e((()=>{qr(),Sa(),Ic=class{constructor(e,t){this.notify=e,this.onUserChange=t,this.attachments=[],this.reads=new ca(e)}get pendingReads(){return this.reads.pendingReads}get readSignal(){return this.reads.readSignal}replace(e){this.attachments=e,this.onUserChange(),this.notify()}restore(e){Yr(this.attachments,[e]),this.attachments=e,this.notify()}updatePending(e,t){this.reads.updatePending(e,t)}abortReads(){this.reads.abortReads()}take(){this.abortReads();let e=this.attachments;return this.attachments=[],this.notify(),e}reset(e){this.abortReads(),e.release&&Be(this.attachments),this.attachments=[],this.notify()}clearAfterSubmit(e){e&&Be(this.attachments),this.attachments=[],this.notify()}}})))()}function Rc(e){let{gateway:t}=e,n=t.snapshot.client,r=t.connectionRevision,i=t.connection.gatewayUrl,a=t.snapshot.hello?.auth?.recoveryScope;return()=>e.gateway===t&&t.snapshot.phase===`connected`&&t.connection.gatewayUrl===i&&t.connectionRevision===r&&t.snapshot.hello?.auth?.recoveryScope===a&&(!!a||t.snapshot.client===n)}function zc(){return(zc=e((()=>{})))()}async function Bc(e){let t;for(;!t;)try{let n=await e.client.request(`agent.wait`,{runId:e.runId,timeoutMs:3e4},{timeoutMs:null});if(e.context.gateway.snapshot.client!==e.client)return;let r=n.status===`timeout`&&n.endedAt===void 0&&!n.error&&!n.stopReason&&n.providerStarted!==!0;if(n.status===`pending`||n.pendingError===!0)await Wc();else if(r){let n=e.context.placementStartup.get(e.key)?.initialTurn;n?.sendState===`failed`&&n.sendRunId===e.runId?t={status:`error`,error:n.sendError}:await Wc()}else t=n}catch{let t=e.context.gateway.snapshot,n=t.phase===`connecting`||t.phase===`starting`||t.phase===`reconnecting`;if(t.client!==e.client||!n)return;await Wc()}if(!e.isCurrentOwner())return;let n=e.context.gateway.snapshot;if(ce(n,e.key,e.agentId))return;let r=e.context.sessions.state.result?.sessions.find(t=>je(t.key,e.key)),i=t.status===`ok`?A(`sessionsView.statusDone`):t.status===`timeout`?A(`sessionsView.statusTimeout`):t.stopReason===`rpc`?A(`sessionsView.statusKilled`):A(`sessionsView.statusFailed`),a=Qe({face:`chat`,sessionKey:e.key,fallbackAgentId:e.agentId,exactKey:!0});e.context.nativeNotifications?.backgroundSessionCompleted({runId:e.runId,path:a.options.pathname,...a.options.search?{search:a.options.search}:{}}),ke({fifo:!0,message:`${xe(e.key,r)}: ${i}`,actionLabel:A(`sessionsView.openSession`),onAction:()=>{e.isCurrentOwner()&&(Et({selection:e.context.agentSelection,gateway:e.context.gateway,sessionKey:e.key,agentId:e.agentId}),e.context.navigate(`chat`,Qe({context:e.context,face:`chat`,sessionKey:e.key,agentId:e.agentId}).options))}})}function Vc(e){let t=Rc(e.context);return(n,r)=>{let i=r?.trim();return e.enabled?(i&&Bc({agentId:e.agentId,client:e.client,context:e.context,key:n,runId:i,isCurrentOwner:t}),!0):!1}}function Hc(e,t,n,r){Fr({connected:e.gateway.snapshot.phase===`connected`,directComposerSend:r&&Ar(),message:t,hasAttachments:n,isCommand:Un(t)!==null})&&kr(e)}var Uc,Wc;function Gc(){return(Gc=e((()=>{Ot(),Rr(),M(),zn(),Le(),Fe(),j(),Ee(),Uc=1e3,Wc=()=>new Promise(e=>{globalThis.setTimeout(e,Uc)})})))()}function Kc(e){return e.allowedVisibilities?.includes(`draft`)===!0&&e.hasMultipleIdentities===!0}function qc(e){let t=e.trim();return!t||Yc.test(t)}function Jc(e){let t=D(e.cwd),n=D(e.workspace),r=D(e.catalogId),i=D(e.category),a=D(e.model),o=D(e.agentRuntime),s=D(e.contextWindow),c=D(e.thinkingLevel),l=e.deferInitialTurn?``:e.message,d=e.deferInitialTurn&&e.visibility!==`incognito`?u(e.message.trim(),1e3):void 0,f=e.worktreeSource===`empty`,p=f?void 0:e.repository,m=f||p?void 0:D(e.projectId),h=!f&&!p&&!m&&(l.trim()||!e.deferInitialTurn&&e.attachments?.length)?D(e.projectGitUrl):void 0,_=!f&&!p&&!m&&!h&&t&&t!==n?t:void 0;return{...D(e.key)?{key:D(e.key)}:{},agentId:g(e.agentId),message:l,...!e.deferInitialTurn&&e.mentions?.length?{mentions:e.mentions.map(e=>({...e}))}:{},...D(e.displayName)?{displayName:D(e.displayName)}:{},...d?{titleSource:d}:{},...e.visibility===`incognito`?{incognito:!0}:{},...e.visibility===`draft`?{visibility:`draft`}:{},...!e.deferInitialTurn&&e.attachments?.length?{attachments:e.attachments}:{},...r?{catalogId:r}:{},...i?{category:i}:{},...!r&&a?{model:a}:{},...!r&&a&&o?{agentRuntime:o}:{},...!r&&s?{contextWindow:s}:{},...!r&&c?{thinkingLevel:c}:{},...!r&&e.fastMode!==void 0?{fastMode:e.fastMode}:{},...e.toolOverrides?{toolOverrides:e.toolOverrides}:{},...e.permissionMode?{permissionMode:e.permissionMode}:{},...m?{projectId:m}:{},...h?{projectGitUrl:h}:{},...p?{repository:{...p}}:{},..._?{cwd:_}:{},...f?{worktree:!0,worktreeSource:`empty`}:{},...e.worktree&&!p&&!f?{worktree:!0,...D(e.baseRef)?{worktreeBaseRef:D(e.baseRef)}:{},...D(e.worktreeName)?{worktreeName:D(e.worktreeName)}:{}}:{}}}var Yc;function Xc(){return(Xc=e((()=>{j(),Yc=/^[a-z0-9][a-z0-9-]{0,63}$/})))()}var Zc;function Qc(){return(Qc=e((()=>{vt(),M(),Xn(),ja(),Xc(),Zc=class{constructor(e){this.notify=e,this.toolOverridesValue=null,this.onMutation=()=>{},this.skillCatalog=new oi(e)}setMutationCallback(e){this.onMutation=e}get toolOverrides(){return this.toolOverridesValue}setToolOverrides(e){let t=Rn(e)>0?e:null;t!==this.toolOverridesValue&&(this.onMutation(),this.toolOverridesValue=t,this.notify())}reset(){this.toolOverridesValue=null}restoreToolOverrides(e){e!==void 0&&this.setToolOverrides(e)}canStartAsDraft(e){return Kc({allowedVisibilities:e?.gateway.snapshot.hello?.policy?.allowedSessionVisibilities,hasMultipleIdentities:e?.gateway.snapshot.hello?.policy?.hasMultipleSessionSharingIdentities})}composerProps(e,t,n){return{toolOverrides:this.toolOverridesValue,capabilityMenu:e?this.props(e,t,n):void 0}}props(e,t,n){this.skillCatalog.synchronize(t.client,t.connectionEpoch);let r=e.runtimeConfig.state,i=r.configSnapshot?.runtimeConfig??null,a=t.connected&&!!t.client,o=Pt(e.gateway.snapshot),s=a?i?o.canAdmin?null:A(`chat.composer.menu.adminBlocked`):r.lastError??A(`common.loading`):A(`chat.composer.menu.offlineBlocked`);return{basePath:e.basePath,skills:this.skillCatalog.rows(n,this.toolOverridesValue),skillsLoading:this.skillCatalog.isLoading(n),skillsError:this.skillCatalog.hasError(n),mcpServers:vn(i)??[],toolsEffectiveResult:null,toolsEffectiveLoading:!1,toolsEffectiveError:!1,toolAccessMutationBlockedReason:s,webSearchBaseEnabled:aa(i),mutationBlockedReason:s,canAdmin:o.canAdmin&&a,adminBlockedReason:o.canAdmin?a?null:A(`chat.composer.menu.offlineBlocked`):A(`chat.composer.menu.adminBlocked`),onLoadSkills:()=>{let e=t.client,r=t.connectionEpoch;this.skillCatalog.load(e,r,n,()=>t.connected&&t.client===e&&t.connectionEpoch===r)},onPatchToolOverrides:e=>this.setToolOverrides(e),onNavigate:(t,n)=>e.navigate(t,n)}}}})))()}var $c;function el(){return(el=e((()=>{ii(),Ji(),xi(),Hi(),Oi(),ri(),$c=class{constructor(){this.critterVisit=Math.random(),this.textarea=null,this.placeholderFrame=null,this.placeholderStartedAt=null,this.placeholderText=``,this.placeholderTarget=``,this.placeholderEntered=!1,this.capturedSelection=null,this.skillCommandClient=null,this.skillCommandAgentId=``,this.skillCommandDraftOwnerKey=``,this.skillMenuState=Ui(),this.slashMenuState=pi(),this.mentionMenu=new Ea,this.emojiMenu=new Xi,this.composing=!1,this.capabilityMenuOpen=!1,this.capabilityMenuView=`root`,this.ref=e=>{let t=e instanceof HTMLTextAreaElement?e:null;this.textarea&&this.textarea!==t&&Ii(this.textarea),this.textarea&&!t&&this.resetPlaceholder(),this.textarea=t,t&&(oa(t),ba(t))},this.getTextarea=()=>this.textarea}syncDraft(e){this.textarea?.isConnected&&this.textarea.value!==e&&ba(this.textarea)}getPlaceholder(e,t,n){if(t.length>0||this.placeholderEntered)return this.placeholderEntered=!0,this.placeholderFrame!==null&&(globalThis.cancelAnimationFrame?.(this.placeholderFrame),this.placeholderFrame=null),e;this.placeholderTarget!==e&&(this.resetPlaceholder(),this.placeholderTarget=e);let r=globalThis.requestAnimationFrame?.bind(globalThis);if(!r||(globalThis.matchMedia?.(`(prefers-reduced-motion: reduce)`).matches??!1))return this.placeholderText=e,this.placeholderEntered=!0,e;if(this.placeholderFrame===null){let t=i=>{this.placeholderStartedAt??=i;let a=Math.max(0,i-this.placeholderStartedAt-180),o=Math.min(e.length,Math.floor(a/26));if(o!==this.placeholderText.length&&(this.placeholderText=e.slice(0,o),n()),o<e.length){this.placeholderFrame=r(t);return}this.placeholderFrame=null,this.placeholderEntered=!0};this.placeholderFrame=r(t)}return this.placeholderText}resetPlaceholder(){this.placeholderFrame!==null&&(globalThis.cancelAnimationFrame?.(this.placeholderFrame),this.placeholderFrame=null),this.placeholderStartedAt=null,this.placeholderText=``,this.placeholderTarget=``,this.placeholderEntered=!1}captureSelection(){let e=this.textarea;this.capturedSelection=e?{start:e.selectionStart,end:e.selectionEnd,value:e.value}:null}previewTranscript(e){let t=this.textarea;if(!t)return;let n=this.capturedSelection??{start:t.selectionStart,end:t.selectionEnd,value:t.value};return sa(n.value,e,n.start,n.end).value}insertTranscript(e,t){let n=this.textarea;if(!n)return null;let r=this.capturedSelection,i=r&&(!t||r.value===n.value)?r:{start:t?n.selectionStart:n.value.length,end:t?n.selectionEnd:n.value.length,value:n.value};this.capturedSelection=null;let a=sa(i.value,e,i.start,i.end);return a.value===i.value?null:(n.value=a.value,Qi(n),queueMicrotask(()=>{n.isConnected&&(n.focus({preventScroll:!0}),n.selectionStart=a.caret,n.selectionEnd=a.caret)}),a.value)}syncSkillCommandOwner(e,t,n){let r=t.trim();(this.skillCommandClient!==e||this.skillCommandAgentId!==r||this.skillCommandDraftOwnerKey!==n)&&(this.skillCommandClient=e,this.skillCommandAgentId=r,this.skillCommandDraftOwnerKey=n,this.emojiMenu.close(),hi(this.skillMenuState))}ownsSkillCommands(e,t,n){return this.skillCommandClient===e&&this.skillCommandAgentId===t.trim()&&this.skillCommandDraftOwnerKey===n}disconnect(){this.emojiMenu.close(),this.composing=!1,this.mentionMenu.dispose(),this.resetPlaceholder(),this.skillCommandClient=null,this.skillCommandAgentId=``,this.skillCommandDraftOwnerKey=``,hi(this.skillMenuState),za(this.slashMenuState),this.capabilityMenuOpen=!1,this.capabilityMenuView=`root`,this.textarea&&=(Ii(this.textarea),null)}}})))()}var tl,nl,rl,il;function al(){return(al=e((()=>{Vn(),Gn(),ia(),i(),tl=()=>({writeId:Math.random().toString(36).slice(2),retired:!1,committedRevision:0,writes:new Set}),nl=O(()=>import(`./composer-draft-store.runtime-v4vUYxIm.js`),__vite__mapDeps([3,4,5,6,7,8,9,10,11,12,13,2,14,15,16,17]),import.meta.url),rl=200,il=class e{static{this.active=new Set}constructor(e,t,n){this.read=e,this.apply=t,this.onStorageError=n,this.contentReconciled=!1,this.pendingModelSelectionMutation=!1,this.gatewayOwner=``,this.recoveryScope=``,this.routeKey=``,this.revision=0,this.mutationGeneration=0,this.mutation=tl(),this.inheritedWriteIds=[],this.disconnected=!1,this.pendingHandoffMutation=null,this.submittedMutation=null,this.pristineMutationBaseline=0,this.restoreGeneration=0,this.restoredIdentity=``,this.pending=null,this.timer=null,this.lineageByScope=new Map}setOwner(e,t,n=!1){let r=qn(e).gatewayOwner,i=JSON.stringify([r,t]),a=this.gatewayOwner?JSON.stringify([this.gatewayOwner,this.recoveryScope]):``;if(a===i)return;let o=this.routeKey;this.persistNow(),this.restoreGeneration+=1,this.restoredIdentity=``,this.contentReconciled=!1,this.routeKey=``,this.gatewayOwner=r,this.recoveryScope=t,a&&!n&&(this.pendingModelSelectionMutation=!1,this.apply(``,[],!0)),n||this.activateRoute(o)}setIncognito(e){if(e)return this.retireActive();let t=this.scope();return(t?this.lineage(t).retirement:void 0)?.then(()=>{})??Promise.resolve()}transitionIncognito(e,t,n){let r=this.setIncognito(t);if(e&&!t){this.noteUserMutation(),r.finally(n);return}n()}selectRoute(e){e&&this.routeKey!==e&&(this.persistNow(),this.routeKey&&(this.pendingModelSelectionMutation=!1),this.routeKey=e,this.contentReconciled=!1,this.revision=0)}activateRoute(e){this.selectRoute(e);let t=this.scope();if(!t)return;let n=W(t);if(n===this.restoredIdentity)return;if(this.restoredIdentity=n,this.contentReconciled=!1,this.read().incognito){this.retireActive();return}let r=++this.restoreGeneration,i=this.mutationGeneration,a=this.read(),o=$i(a.message,a.attachments,void 0,a.mentions),s=this.restoreScope(t,r,i,o);this.restorePromise=s,s.then(e=>{this.restorePromise===s&&(this.restorePromise=void 0,this.contentReconciled=e,this.flushModelSelectionMutation())},()=>{this.restorePromise===s&&(this.restorePromise=void 0,this.contentReconciled=!1,G(t,this.onStorageError))})}noteDraftReplaced(){this.restoreGeneration+=1,this.mutationGeneration+=1,this.mutation=tl(),this.pendingHandoffMutation=null,this.submittedMutation=null,this.inheritedWriteIds=[],this.pristineMutationBaseline=this.mutationGeneration}noteModelSelectionMutation(){let e=!this.contentReconciled&&this.mutationGeneration===this.pristineMutationBaseline&&(this.submittedMutation===this.mutation||!this.restorePromise);this.submittedMutation=null,this.pendingModelSelectionMutation=!0,e?(this.restoredIdentity=``,this.activateRoute(this.routeKey)):this.flushModelSelectionMutation()}flushModelSelectionMutation(){this.pendingModelSelectionMutation&&!this.restorePromise&&this.restoredIdentity&&(this.contentReconciled||this.mutationGeneration>this.pristineMutationBaseline)&&!this.disconnected&&this.submittedMutation!==this.mutation&&this.noteUserMutation()}noteUserMutation(){if(this.pendingModelSelectionMutation=!1,this.mutationGeneration+=1,this.mutation=tl(),this.pendingHandoffMutation=null,this.submittedMutation=null,this.revision=lr(this.revision),this.read().incognito)return;this.discardPending();let e=this.snapshot();e&&(this.pending=e,this.timer=globalThis.setTimeout(()=>this.persistNow(),rl))}retireActive(){this.mutationGeneration+=1,this.mutation.retired=!0,this.discardPending();let e=lr(this.revision);this.revision=e;let t=this.scope();if(!t)return Promise.resolve();let n=this.lineage(t);return n.localWriteIds.clear(),n.retirement=(async()=>{let{retireDurableComposerDraft:r}=await nl,i=Math.max(e,n.revision),a=await r(t,i);if(a.status===`storage-failed`)G(t,this.onStorageError);else if(a.status===`persisted`){let e=a.revision??i;return this.adoptCommittedRevision(t,e,a.writeId),{revision:e,writeId:a.writeId}}})(),n.retirement.then(()=>{})}captureSubmission(){this.pendingModelSelectionMutation=!1,this.reconcileHandoffCommit(),this.submittedMutation=this.mutation,this.mutationGeneration===this.pristineMutationBaseline&&(this.restorePromise&&(this.contentReconciled=!1),this.restoreGeneration+=1),this.persistNow();let e=this.scope(),t=e?this.lineage(e):null;return{scope:e,mutation:this.mutation,revision:this.revision,incognito:this.read().incognito,pendingEdit:this.mutationGeneration>this.pristineMutationBaseline&&this.mutation.committedRevision===0,writeIds:new Set([t?.writeId,this.mutation.writeId,...this.inheritedWriteIds,...t?.localWriteIds??[]])}}adoptHandoff(e){let t=this.scope();t&&e.scope&&W(t)===W(e.scope)&&(this.mutation=e.mutation,this.revision=Math.max(this.revision,e.revision),e.pendingEdit&&!e.mutation.committedRevision&&(this.pristineMutationBaseline=this.mutationGeneration-1,this.pendingHandoffMutation=e.mutation),this.inheritedWriteIds=[...e.writeIds])}async clearSubmittedDraft(t,n){t.mutation.retired=!0;let{scope:r}=t,i=this.scope();if(this.mutation===t.mutation&&(!r&&!i||r&&i&&W(r)===W(i))&&(this.modelSelection?.retire(),n?.()),await Promise.all(t.mutation.writes),!r)return;let{readDurableComposerDraft:a}=await nl;for(let n=0;n<3;n+=1){let n=await a(r);if(n.status===`storage-failed`){G(r,this.onStorageError);return}if(n.status!==`found`||!t.writeIds.has(n.draft.writeId))return;let i=n.draft.revision,o=n.draft.writeId,s=lr(i),c=`clear:${s}`,{result:l}=await Oa({scope:r,expectedRevision:i,...o?{expectedWriteId:o}:{},revision:s,text:``,storedAttachments:[],writeId:c});if(l.status===`persisted`){this.adoptCommittedRevision(r,l.revision??s,l.writeId??c);for(let t of e.active){let e=t.scope();e&&W(e)===W(r)&&(t.restoredIdentity=``,t.activateRoute(e.scopeKey))}return}if(l.status===`storage-failed`){G(r,this.onStorageError);return}}}persistNow(){this.clearTimer();let e=this.pending;if(!e)return;if(this.read().incognito){this.discardPending();return}this.pending=null;let t=(async()=>{try{let t=e.retirement?await e.retirement:void 0;if(e.mutation.retired||!this.lineage(e.scope).localWriteIds.has(e.writeId))return;let n=t&&t.revision>e.expectedRevision?{...e,expectedRevision:t.revision,expectedWriteId:t.writeId,revision:lr(Math.max(e.revision,t.revision))}:e,{result:r,payloadUnavailable:i}=await Oa(n);if(i&&G(e.scope,this.onStorageError),r.status===`persisted`||r.status===`payload-too-large`){let t=r.revision??n.revision;e.mutation.committedRevision=t,this.adoptCommittedRevision(e.scope,t,r.writeId??e.writeId),r.status===`payload-too-large`&&G(e.scope,this.onStorageError);return}if(r.status===`storage-failed`){G(e.scope,this.onStorageError);return}if(this.disconnected||e.mutation.retired||this.routeKey!==e.scope.scopeKey||this.revision!==e.revision)return;this.restoredIdentity=``,this.activateRoute(this.routeKey)}finally{this.forgetLocalWrite(e)}})();e.mutation.writes.add(t),t.finally(()=>e.mutation.writes.delete(t))}connect(){this.disconnected=!1,e.active.add(this)}disconnect(){this.disconnected=!0,e.active.delete(this),this.persistNow(),this.restoreGeneration+=1}scope(){return!this.gatewayOwner||!this.recoveryScope||!this.routeKey?null:{gatewayOwner:this.gatewayOwner,recoveryScope:this.recoveryScope,scopeKey:this.routeKey}}snapshot(){let e=this.scope();if(!e||this.revision<=0||this.mutation.retired)return null;let t=this.read(),n=this.lineage(e),r=[...n.localWriteIds],i=this.mutation.writeId;return n.localWriteIds.add(i),{scope:e,mutation:this.mutation,retirement:n.retirement,expectedRevision:n.revision,...n.writeId?{expectedWriteId:n.writeId}:{},expectedWriteIds:r,revision:this.revision,text:t.message,...t.mentions?.length?{mentions:t.mentions.map(e=>({...e}))}:{},modelSelection:this.modelSelection?.read(),storedAttachments:qi(t.attachments),writeId:i}}isRestoreCurrent(e,t,n,r){let i=this.read(),a=this.scope();return t===this.restoreGeneration&&n===this.mutationGeneration&&a!==null&&W(e)===W(a)&&r===$i(i.message,i.attachments,void 0,i.mentions)}async restoreScope(e,t,n,r){let{readDurableComposerDraft:i}=await nl,a=await i(e);if(a.status===`storage-failed`)return G(e,this.onStorageError),!1;let o=a.status===`found`?a.draft.revision:a.revision,s=a.status===`found`?a.draft.writeId:a.writeId,c=this.lineage(e);if(c.revision=o??0,c.writeId=s,!this.isRestoreCurrent(e,t,n,r)||(this.reconcileHandoffCommit(),this.submittedMutation===this.mutation&&this.mutation.committedRevision>0))return!1;if(o===void 0||o<this.revision||n>this.pristineMutationBaseline)return o!==void 0&&o>=this.revision?this.revision=lr(o):this.revision<=0&&n>this.pristineMutationBaseline&&(this.revision=lr(0)),this.pending=this.snapshot(),this.persistNow(),!0;let l=[];if(a.status===`found`)try{l=await ai(a.draft.attachments)}catch{return G(e,this.onStorageError),!1}return this.isRestoreCurrent(e,t,n,r)?(this.revision=o,a.status===`found`&&a.draft.mentions?this.apply(a.draft.text,l,void 0,a.draft.mentions):this.apply(a.status===`found`?a.draft.text:``,l),this.modelSelection?.restore(a.status===`found`?a.draft.modelSelection:void 0),this.mutation.committedRevision=o,!0):!1}reconcileHandoffCommit(){this.pendingHandoffMutation===this.mutation&&this.mutation.committedRevision>0&&this.submittedMutation!==this.mutation&&(this.revision=Math.max(this.revision,this.mutation.committedRevision),this.pristineMutationBaseline=this.mutationGeneration,this.pendingHandoffMutation=null)}clearTimer(){this.timer!==null&&(globalThis.clearTimeout(this.timer),this.timer=null)}discardPending(){this.clearTimer();let e=this.pending;this.pending=null,e&&this.forgetLocalWrite(e)}forgetLocalWrite(e){let t=W(e.scope),n=this.lineageByScope.get(t);n&&(n.localWriteIds.delete(e.writeId),!n.revision&&!n.writeId&&!n.localWriteIds.size&&!n.retirement&&this.lineageByScope.delete(t))}lineage(e){let t=W(e),n=this.lineageByScope.get(t);return n||(n={revision:0,localWriteIds:new Set},this.lineageByScope.set(t,n)),n}adoptCommittedRevision(e,t,n){let r=W(e),i=this.lineage(e);i.revision=t,n&&(i.writeId=n);let a=this.scope();a&&W(a)===r&&t>this.revision&&(this.revision=t)}}})))()}function ol(e,t){let{os:n,machineClass:r}=t.cloudSelection;return{target:e.sessionKey?e.target:t.cloudProfileId?{kind:`profile`,profileId:t.cloudProfileId,...n?{os:n}:{},...r?{machineClass:r}:{}}:t.deviceId?{kind:`device`,deviceId:t.deviceId}:t.autoDevice?{kind:`auto-device`}:null}}function sl(e){let t=e.createParams?.incognito?`incognito`:e.createParams?.visibility===`draft`?`draft`:`normal`;return{placement:{agentId:e.agentId,profileId:e.target.kind===`profile`?e.target.profileId:``,...e.target.kind===`profile`?{os:e.target.os,machineClass:e.target.machineClass}:e.target.kind===`device`?{deviceId:e.target.deviceId}:{autoDevice:!0},cwd:e.createParams?.cwd,...e.createParams?.worktreeSource?{worktreeSource:e.createParams.worktreeSource}:{},...e.createParams?.repository?{repository:{...e.createParams.repository}}:{}},draft:{message:e.message,...e.mentions?.length?{mentions:e.mentions}:{},attachments:_e(e.attachments),visibility:t,toolOverrides:e.createParams?.toolOverrides??null,permissionMode:e.createParams?.permissionMode}}}async function cl(e){let{pending:t,submittedRecovery:n,sessionKey:r}=e,{gatewayUrl:i,recoveryScope:a}=n,o=e=>t.owns(i,a,e),s=()=>o(n.sessionKey);if(n.phase===`creating`&&(!e.isLifecycleCurrent()||!s())){if(t.hasOtherLiveOwner(i,a,n.sessionKey))return;let o=await Bn({client:e.client,describe:e.context.sessions.describe},r,e.agentId);o?(s()&&(t.promoteToDispatching(r),t.retryAllowed=!0),e.setError(A(`newSession.placementStartFailed`,{error:o}))):s()&&e.clearRecovery();return}if(n.phase===`creating`&&e.isLifecycleCurrent()&&s()&&!t.promoteToDispatching(r)){e.onRecoveryUnavailable();return}let c=t.capture();if(!c||c.phase===`creating`){e.onRecoveryUnavailable();return}if(!e.isRequestCurrent())return;e.context.placementStartup.start({recovery:c,persistRecovery:t.persistent,mode:n.phase===`creating`?`dispatch`:`recover`,createdAt:e.createdAt}),await e.consumeWorktreeName?.();let l=()=>e.isLifecycleCurrent()&&o(c.sessionKey);if(l()&&(await e.clearDraft(),l())){if(t.reset(),e.completeInBackground(c.sessionKey,c.messageId)){e.onAccepted();return}await e.navigate()}}function ll(){return(ll=e((()=>{M(),H(),$n(),We(),U()})))()}var ul;function dl(){return(dl=e((()=>{Yt(),c(),ul=class{constructor(e){this.gateway=e,this.pending=null}get active(){return this.pending!==null}start(e,t=!1){let n=this.gateway.sessionCreateScope;if(!n)return e;if(!this.pending){let r=Date.now();this.pending={params:Object.freeze({...e,idempotencyKey:v()}),scope:n,startedAt:r,deadline:r+Zt,interrupted:!1,background:t}}return this.pending.params}clear(){this.pending=null}interrupt(){return!this.pending||!this.matchesGateway()?(this.clear(),!1):(this.pending.interrupted=!0,!0)}retireChangedOwner(){return!this.pending||this.matchesGateway()?!1:(this.clear(),!0)}resume(){return this.pending?.interrupted?Date.now()>=this.pending.deadline?(this.clear(),{kind:`expired`}):this.matchesGateway()?this.gateway.connected?(this.pending.interrupted=!1,{kind:`resume`,params:this.pending.params,startedAt:this.pending.startedAt,background:this.pending.background}):{kind:`wait`}:(this.clear(),{kind:`owner-changed`}):{kind:`wait`}}matchesGateway(){return this.pending?.scope===this.gateway.sessionCreateScope}}})))()}function fl(e,t){return Jc({...t,deferInitialTurn:e.remotePlacement,agentId:e.agentId,model:e.modelControl.modelForSubmission(),agentRuntime:e.modelControl.agentRuntime,contextWindow:e.modelControl.contextWindow,thinkingLevel:e.modelControl.thinkingLevel,fastMode:e.modelControl.fastMode,projectId:e.browser.remoteProject?.projectId??e.browser.projectId,projectGitUrl:e.browser.remoteProject?.cloneUrl,repository:e.remoteRepository,worktree:e.worktree,worktreeSource:e.freshWorkspace?`empty`:void 0,baseRef:e.baseRef,worktreeName:e.worktreeName,cwd:e.folder,workspace:e.workspacePath()})}function pl(){return(pl=e((()=>{Xc()})))()}function ml(e,t,n,r,i={}){return fl(e,{...i,message:i.message??``,toolOverrides:n.capabilities.toolOverrides,permissionMode:n.permission.value,visibility:i.visibility??n.visibility,catalogId:r.data?.catalogId,category:t.resolvedGroupCategory()})}function hl(e,t,n,r,i=!1){let a=t.pendingPlacement,o=!r&&!!a.sessionKey,s=xn(t.message,t.mentions),c=r?.params.message??(o?a.message:s.text),l=(r?r.params.mentions:o?a.mentions:s.mentions)?.map(({profileId:e,start:t,end:n})=>({profileId:e,start:t,end:n})),u=t.attachmentDraft.attachments;if(!r&&!o){let t=Ei(u,e.gateway.snapshot.hello?.policy);if(t!==void 0)return ke({message:t}),null}let d=r?r.params.attachments:o?void 0:ei(u),f=o?a.attachments:d,p=r?.params.agentId??(o?a.agentId:g(n.agentId)),m=o?a.gatewayUrl:e.gateway.connection.gatewayUrl,h=e.gateway.snapshot.client;if(!h||!e.gateway.snapshot.hello)return null;let _=Vc({enabled:i,agentId:p,client:h,context:e}),v=o?a.recoveryScope:h.recoveryScope,y=r?.params??(o?a.createParams:fl(n,{message:c,visibility:t.visibility}));return{consumeWorktreeName:y&&n.captureSubmittedWorktreeName(y,p,!!(r||o)),pendingPlacement:o,message:c,mentions:l,attachments:u,draftAttachments:d,apiAttachments:f,agentId:p,gatewayUrl:m,client:h,recoveryScope:v,completeInBackground:_,hasInitialTurn:!!(c||f?.length)}}function gl(e,t,n){let{hello:r,selfUser:i}=e.gateway.snapshot,a=wn(r,t.client.instanceId,i)??void 0;return{text:t.message,mentions:t.mentions,attachments:t.attachments,createdAt:n,sender:a}}function _l(){return(_l=e((()=>{Fn(),dn(),j(),Ee(),$r(),La(),Gc(),pl()})))()}function vl(e){let t=e.context.gateway.snapshot,n={id:v(),text:e.message,...e.mentions?.length?{mentions:e.mentions}:{},attachments:e.attachments,createdAt:Date.now(),kind:`queued`,refreshSessions:!0,sendAttempts:1,sendError:e.error,sendState:`failed`,sessionKey:e.sessionKey,sessionId:e.sessionId,agentId:g(e.agentId)},r={scope:{sessionKey:n.sessionKey,agentId:n.agentId},awaitingDefaults:!1},i=Ra({settings:kt(),assistantAgentId:t.assistantAgentId,agentsList:e.context.agents.state.agentsList,hello:t.hello},r,n);return(!i||e.retryAfter)&&Ba(e.sessionKey,{...n,sendRunId:v()},e.retryAfter),!i}function yl(){return(yl=e((()=>{Ct(),j(),c(),gi(),Va()})))()}function bl(e,t){let{context:n,client:r,result:i,turn:a}=e,{text:o,attachments:s}=a,c=i.initialRun.status===`rejected`&&vl({agentId:e.agentId,attachments:s,context:n,error:i.initialRun.error,message:o,mentions:a.mentions,sessionKey:i.key,sessionId:typeof i.entry?.sessionId==`string`?i.entry.sessionId:void 0,retryAfter:t});return i.initialRun.status===`started`&&n.chatSubmissions.retain(Ja(i.key,a,r,i.initialRun.runId)),c}async function xl(e){let{context:t,client:n,agentId:r,result:i,instant:a}=e,{key:o,initialRun:s}=i;if(a&&await a.waitForReady(),!e.isCurrent()||a&&!a.isCurrent()){s.status!==`rejected`&&await e.clearDraft(!0,!1);return}let c=s.status===`rejected`?en(s.errorDetails):void 0,l=c?ne():void 0;try{if(s.status===`rejected`&&e.onRejectedPrompt){let t=Gr(e.turn.attachments);bl({...e,turn:{...e.turn,attachments:t}},l?.promise)||Be(t),e.onRejectedPrompt(s.error)}else{let t=bl(e,l?.promise);await e.clearDraft(!t)}if(!e.isCurrent()||a&&!a.isCurrent())return;if(e.completeInBackground(o,s.status===`started`?s.runId:void 0)){e.onAccepted?.();return}if(a?.admitted(o,r),await e.navigation.navigate(t,{client:n,key:o,agentId:r},a?.commit.bind(a)),e.finishNavigation(),c){let e=t.gateway.snapshot,a=()=>t.gateway.snapshot.phase===`connected`&&t.gateway.snapshot.client===n&&t.gateway.snapshot.hello===e.hello&&je(t.gateway.snapshot.sessionKey,o);try{let{confirmNativeRuntimePermissionRecovery:n}=await O(async()=>{let{confirmNativeRuntimePermissionRecovery:e}=await import(`./chat-native-runtime-recovery-ttYYPde6.js`);return{confirmNativeRuntimePermissionRecovery:e}},__vite__mapDeps([18,4,5,6,7,8,9,10,11,12,13,2,14,15,16,17]),import.meta.url),s=await n({sessions:t.sessions,hello:e.hello},o,c,{agentId:r,expectedSessionId:typeof i.entry?.sessionId==`string`?i.entry.sessionId:void 0,signal:t.lifecycleAbortSignal,retriesMessage:!0,canDispatch:a});l?.resolve(!!(s&&a()))}catch(e){a()&&ke({message:A(`chat.nativeRuntimeRecovery.failed`,{error:pe(e)})})}}}finally{l?.resolve(!1)}}function Sl(){return(Sl=e((()=>{$t(),C(),M(),Sn(),He(),j(),Ee(),qr(),qa(),yl(),i(),fn()})))()}function Cl(e,t,n){let{router:r,lifecycleAbortSignal:i}=e,a=new AbortController,o=r.navigate(t,e,{history:`none`},n),s=r.getState().location,c=i?AbortSignal.any([a.signal,i]):a.signal,l=r.subscribe(e=>{e.location!==s&&a.abort()});return c.addEventListener(`abort`,l,{once:!0}),{ready:o.catch(()=>void 0),signal:c,isActive:()=>!c.aborted&&r.getState().location===s,dispose:()=>{l(),c.removeEventListener(`abort`,l)}}}function wl(e,t){let n=Ol.get(e);if(n&&n.search===t&&n.owns())return Ol.delete(e),kl.set(n.draft.data,{page:n.draft.page,canDisplay:n.canDisplay}),n.draft.data}function Tl(e,t){e&&kl.get(e)?.page===t&&kl.delete(e)}function El(e){let t=e&&typeof e==`object`?kl.get(e):void 0;return t?.canDisplay()?t.page:void 0}function Dl(e,t){return Ol.set(e,t),()=>{Ol.get(e)===t&&Ol.delete(e)}}var Ol,kl;function Al(){return(Al=e((()=>{Ol=new WeakMap,kl=new WeakMap})))()}function jl(e){let{context:t,params:n,agentId:r,retainDraft:i}=e;if(!e.enabled||!t.gateway.snapshot.hello?.auth?.recoveryScope||!i)return;let a=(e.resumed?n.key:void 0)??`agent:${r}:dashboard:${n.incognito?`incognito-`:``}${v()}`;return e.resumed||(n.key=a),()=>{let n=i();return n?new Nl(t,a,r,n,e.message):void 0}}var Ml,Nl;function Pl(){return(Pl=e((()=>{bt(),st(),Fe(),c(),Al(),Ml=new WeakMap,Nl=class{constructor(e,t,n,r,i){this.context=e,this.key=t,this.draft=r,this.stopGateway=()=>{},this.clearPendingCreate=()=>{},this.disposed=!1,this.lifetime=new AbortController,this.onLeave=()=>{this.dispose()},this.creation={sessionKey:t,admitted:!1},this.client=e.gateway.snapshot.client,this.hello=e.gateway.snapshot.hello,this.gatewayUrl=e.gateway.connection.gatewayUrl,this.recoveryScope=this.hello?.auth?.recoveryScope,this.presentationScope=Mt(e.gateway);let a=Ml.get(e);this.previousSessionKey=e.gateway.snapshot.sessionKey,this.previousAgentId=e.agentSelection.state.selectedId,a?.dispose(),this.returnLocation={pathname:globalThis.location.pathname,search:globalThis.location.search,hash:globalThis.location.hash},Ml.set(e,this);let o={pathname:Qe({context:e,face:`chat`,sessionKey:t,agentId:n,exactKey:!0}).options.pathname,search:``,hash:``};this.transition=Cl(e,`chat`,o),this.clearPendingCreate=e.chatSubmissions.beginCreate({creation:this.creation,message:i,canDisplay:()=>this.canDisplay()}),this.transition.signal.addEventListener(`abort`,this.onLeave,{once:!0}),this.stopGateway=e.gateway.subscribe(()=>{let t=e.gateway.snapshot;(t.phase!==`connected`||t.hello!==this.hello||t.client!==this.client||e.gateway.connection.gatewayUrl!==this.gatewayUrl||t.hello?.auth?.recoveryScope!==this.recoveryScope)&&(t.phase!==`connected`&&e.gateway.connection.gatewayUrl===this.gatewayUrl&&r.synchronizeGateway(),this.rollback())})}sameIdentity(){let{gateway:e}=this.context;return!!this.recoveryScope&&e.connection.gatewayUrl===this.gatewayUrl&&e.snapshot.phase===`connected`&&e.snapshot.hello?.auth?.recoveryScope===this.recoveryScope}canDisplay(){return Mt(this.context.gateway)===this.presentationScope&&this.context.gateway.connection.gatewayUrl===this.gatewayUrl&&(this.context.gateway.snapshot.phase!==`connected`||this.sameIdentity())}liveConnection(){return this.sameIdentity()&&this.context.gateway.snapshot.client===this.client&&this.context.gateway.snapshot.hello===this.hello}ownsSelection(){let e=this.admittedSelection?.key??this.previousSessionKey,t=this.admittedSelection?.agentId??this.previousAgentId;return this.context.gateway.snapshot.sessionKey===e&&this.context.agentSelection.state.selectedId===t}async waitForReady(){await this.transition.ready}isCurrent(){return!this.disposed&&!this.rollingBack&&Ml.get(this.context)===this&&this.transition.isActive()&&this.liveConnection()&&this.ownsSelection()}rollback(){return this.rollingBack??=this.restore(),this.rollingBack}async restore(){await this.transition.ready;try{await gt(this.context.gateway,this.lifetime.signal)}catch{return}if(this.disposed||Ml.get(this.context)!==this||!this.transition.isActive())return;let e=this.sameIdentity()&&this.ownsSelection();this.transition.dispose(),this.stopGateway();let t=this.context.agentSelection.state.selectedId,n={draft:this.draft,search:this.returnLocation.search??``,owns:()=>Ml.get(this.context)===this&&!this.disposed&&this.sameIdentity(),canDisplay:()=>this.sameIdentity()&&this.context.agentSelection.state.selectedId===t},r=()=>{};e&&(this.draft.synchronizeGateway(),r=Dl(this.context,n));try{let e=Cl(this.context,`new-session`,this.returnLocation);await e.ready,await new Promise(e=>{globalThis.setTimeout(e,0)}),e.dispose()}finally{r(),this.dispose()}}admitted(e,t){this.admittedSelection={key:e,agentId:t},!this.disposed&&e===this.key&&(this.creation.admitted=!0,this.clearPendingCreate())}commit(){return this.disposed||this.rollingBack||!this.transition.isActive()||!this.liveConnection()?!1:(this.transition.dispose(),this.stopGateway(),!0)}async finish(){await this.rollingBack,this.dispose()}dispose(){this.disposed||(this.disposed=!0,this.lifetime.abort(),this.clearPendingCreate(),this.transition.dispose(),this.stopGateway(),Ml.get(this.context)===this&&Ml.delete(this.context),this.draft.release())}}})))()}var Fl;function Il(){return(Il=e((()=>{Fl=class{constructor(e){this.requestUpdate=e}setMutationCallback(e){this.onMutation=e}set(e){this.value=e,this.onMutation?.(),this.requestUpdate()}restore(e){this.value=e}reset(){this.value=void 0}}})))()}function Ll(e){if(e.querySelector(`.agent-chat__composer-combobox`))return{cancel:()=>void 0,ready:Promise.resolve()};let{promise:t,resolve:n}=ne(),r=()=>n();return e.addEventListener(Ge,r,{once:!0}),{cancel:()=>e.removeEventListener(Ge,r),ready:t}}async function Rl(e){let{document:t,navigate:n,prefersReducedMotion:r,router:i,signal:a,to:o}=e,s=t.querySelector(`openclaw-router-outlet`),c=Ll(t),l=!1,u,{promise:d,resolve:f}=ne(),p=()=>{l||(l=!0,u?.cancel(),f())},m=()=>{};a?.addEventListener(`abort`,p,{once:!0});try{if(a?.aborted)return;let e=n(),t=i.getState().location.pathname,f=()=>{let e=i.getState();((e.pendingMatches[0]??e.matches[0])?.routeId!==o||e.location.pathname!==t)&&p()};if(m=i.subscribe(f),f(),await Promise.race([(async()=>{await e,await s?.updateComplete,await c.ready})(),d]),l||r)return;u=s?.animate?.(Bl,Vl),await Promise.race([u?.finished.catch(()=>void 0),d])}finally{m(),a?.removeEventListener(`abort`,p),c.cancel()}}async function zl(e){let{from:t,navigate:n,to:r}=e;return t!==`new-session`||r!==`chat`?n():Rl(e)}var Bl,Vl;function Hl(){return(Hl=e((()=>{C(),Ve(),Bl=[{transform:`translateY(5px) scale(0.997)`},{transform:`none`}],Vl={duration:180,easing:`cubic-bezier(0.16, 1, 0.3, 1)`}})))()}var Ul;function Wl(){return(Wl=e((()=>{Ot(),bt(),Hl(),kn(),Fe(),j(),qa(),Ul=class{constructor(){this.current=null,this.submitted=null}captureSubmission(e,t,n,r=()=>!0){let i=e.gateway,a=Mt(i),o=i.connection.gatewayUrl,s=i.snapshot.hello?.auth?.recoveryScope??(i.snapshot.client?.recoveryScopeReady?i.snapshot.client.recoveryScope:void 0),c=()=>{let e=i.snapshot,t=e.hello?.auth?.recoveryScope??(e.client?.recoveryScopeReady?e.client.recoveryScope:void 0);return s??=t,Mt(i)===a&&i.connection.gatewayUrl===o&&(!t||t===s)};return(i,a)=>{n&&r()&&c()&&(this.submitted={context:e,message:n,key:i,agentId:t,error:a,canDisplay:c})}}submission(e){let t=this.submitted;return t&&t.context===e&&t.canDisplay()?t:null}messageForTurn(e,t,n){return Ha(n,`available`)??(this.isCurrent(e,t)?this.submission(e)?.message??null:null)}async openSubmission(e,t,n){let r=e?.gateway.snapshot.client;if(!t||!e||!r||e.gateway.snapshot.phase!==`connected`||this.submission(e)!==t)return;let i=n.capture();n.publish(t.message,null);let a;try{await this.navigate(e,{client:r,key:t.key,agentId:t.agentId})}catch(e){i()&&t.canDisplay()&&(a=e instanceof Error?e.message:String(e))}finally{i()&&n.publish(null,a)}}clearSubmission(){this.submitted=null}isCurrent(e,t){let n=this.current,r=e?.gateway.snapshot;return!!(n&&r?.phase===`connected`&&r.client===n.client&&r.hello===n.hello&&r.sessionKey===n.key&&g(t)===n.agentId)}async navigate(e,t,n){let r={...t,hello:e.gateway.snapshot.hello};this.current=r,Et({selection:e.agentSelection,gateway:e.gateway,sessionKey:t.key,agentId:t.agentId});let i=Qe({context:e,face:`chat`,sessionKey:t.key,agentId:t.agentId,focusComposer:!0,navigationKey:t.key}).options;await zl({document,from:`new-session`,to:`chat`,router:e.router,signal:e.lifecycleAbortSignal,prefersReducedMotion:globalThis.matchMedia?.(`(prefers-reduced-motion: reduce)`).matches??!1,navigate:()=>{if(this.current!==r||!this.isCurrent(e,t.agentId))throw new DOMException(`Session navigation interrupted`,`AbortError`);if(n&&!n())throw new DOMException(`Session navigation superseded`,`AbortError`);return Mn(e.gateway,i.pathname,t.key),e.navigateAndWait(`chat`,i)}}),this.current===r&&(this.current=null)}}})))()}async function Gl(e,t){let n=t.name?.trim(),r=t.baseRef?.trim();return e.request(`worktrees.create`,{repoRoot:t.repoRoot.trim(),...n?{name:n}:{},...r?{baseRef:r}:{}})}function Kl(){return(Kl=e((()=>{})))()}function ql(e,t){let n=Ie(e,{method:`sessions.catalog.startTerminal`,requiredScope:`operator.admin`});return!n.allowed||!t?n:Ie(e,{method:`worktrees.create`,requiredScope:`operator.admin`})}async function Jl(e,t,n){let r=t.cwd;if(t.worktree){let i=await Gl(e,{repoRoot:r,name:t.worktreeName,baseRef:t.baseRef});if(!n())return null;r=i.path}return sn(e,{catalogId:t.catalogId,agentId:t.agentId,hostId:t.hostId,cwd:r,...t.initialMessage?{initialMessage:t.initialMessage}:{}},n)}async function Yl(e){let{context:t,data:n}=e.snapshot,{place:r,flow:i}=e,a=t?.gateway.snapshot.client,o=n?.catalogId.trim()??``,s=g(r.agentId);if(!t||!a||!o||!s||!i.canSubmit()){i.noteBlockedSubmitAttempt();return}let c=e.capture(a),l=i.message.trim(),u={catalogId:o,agentId:s,hostId:r.terminalHostId,cwd:r.folder.trim()||(r.terminalOnNode?``:r.workspacePath()),initialMessage:l,worktree:r.worktree,worktreeName:r.worktreeName,baseRef:r.baseRef},d=r.captureSubmittedWorktreeName(u,s);c.publish(Ha({text:l,createdAt:Date.now()},`available`),!0),r.browser.close(),e.closeTransientUi();try{let e=await Jl(a,u,c.isCurrent);if(!e||!c.isCurrent()||(await d?.(),!c.isCurrent()))return;await c.consume(),c.isCurrent()&&t.replace(`terminal`,{pathname:_t(e.sessionId,t.basePath),search:``,hash:``})}catch(e){c.isCurrent()&&i.setError(e instanceof Error?e.message:String(e))}finally{c.isRequestCurrent()&&c.publish(null,!1)}}function Xl(e){return e.hosts?e.hosts.length===0?I`<span class="new-session-page__catalog-unavailable" role="status">
      ${A(`newSession.nativeHostsUnavailable`)}
    </span>`:e.hosts.length===1&&e.hosts[0]?.hostId===e.hostId?L:I`<div class="new-session-page__select new-session-page__menu-field">
    <span>${A(`newSession.where`)}</span>
    <select
      class="new-session-page__trigger"
      aria-label=${A(`newSession.where`)}
      .value=${e.hostId}
      ?disabled=${e.submitting}
      @change=${t=>{t.currentTarget instanceof HTMLSelectElement&&e.onSelect(t.currentTarget.value)}}
    >
      ${e.hosts.some(t=>t.hostId===e.hostId)?L:I`<option value=${e.hostId} selected disabled>
              ${A(`newSession.chooseNativeHost`)}
            </option>`}
      ${e.hosts.map(t=>I`<option value=${t.hostId} ?selected=${t.hostId===e.hostId}>
          ${t.label}
        </option>`)}
    </select>
  </div>`:L}function Zl(){return(Zl=e((()=>{R(),yt(),M(),H(),oe(),In(),j(),qa(),U()})))()}function Ql(e){let{gateway:t,place:n,pendingPlacement:r,hasInitialTurn:i,createParams:a}=e,o=!!r.sessionKey,s=ol(r,n).target,c=!s&&!i?n.browser.remoteProject:null;if(!o&&c&&!c.projectId){let e=Ie(t,{method:`projects.add`,requiredScope:`operator.write`});if(!e.allowed)return e}if(!s||!o||r.phase===`creating`){let e=Ie(t,{method:`sessions.create`,params:a,sessionScope:!0});if(!e.allowed||!s)return e}return Ie(t,{method:`sessions.dispatch`,requiredScope:s.kind===`profile`?`operator.admin`:`operator.write`,params:tr({key:r.sessionKey,agentId:r.agentId||n.agentId,target:s})})}function $l(e){let{snapshot:t,gateway:n,place:r,pendingPlacement:i}=e,a=r.selectedAgent(),o=t.context?.agents.state;return r.modelControl.requiresModelSetup({catalog:K(t.data)||r.remotePlacement||!!i.sessionKey,connected:n.connected,agentsLoaded:!(!o?.agentsList||o.agentsListCached),selectedAgentFound:a!==void 0,agentModel:a?.model?.primary})}function eu(e){let t=e.gatewayState,n=e.placeState,r=e.submissionSnapshot(),i=K(r.data)?`terminal`:`session`,a=!!e.pendingPlacement.sessionKey;if(e.submitting)return{gate:`submitting`};if(e.mentions.length>0&&(i===`terminal`||e.visibility===`incognito`||e.message.trimStart().startsWith(`/`)))return{gate:`mentions-unsupported`,reason:A(`chat.mentions.unsupported`)};if(t.preferenceLoading||i===`session`&&n.modelControl.isRestoringPreference()||!n.placementPreferenceReady)return{gate:`preference-restore`,reason:A(`newSession.restoringPreferences`)};if(i===`session`&&e.requiresModelSetup())return{gate:`model-setup`,reason:A(`modelSetup.required.title`)};if(yo(r.data,r.context?.sessions))return{gate:`route-pending`,reason:A(`newSession.catalogUnavailable`)};if(e.pendingAttachmentReads>0)return{gate:`attachment-reads`,reason:A(`newSession.readingAttachment`)};if(!a&&e.submissionOutcomeUnknown)return{gate:`outcome-unknown`,reason:A(e.submissionOutcomeUnknown===`gateway-changed`?`newSession.createOutcomeUnknown`:`newSession.placementSetupInterrupted`)};let o=r.context?.gateway,s=o?.snapshot.phase===`connected`?o.snapshot.client??null:null;if(!o||!s)return{gate:`disconnected`,reason:A(`sessionsView.actionRequiresConnection`)};let c=i===`terminal`?ql(o.snapshot,n.worktree):e.submissionAccess();if(!c.allowed)return{gate:`access`,reason:c.reason};if(i===`terminal`){if(r.context?.config.current.cliAgentsEnabled!==!0||!r.context.config.current.terminalEnabled)return{gate:`terminal-capabilities`,reason:A(`newSession.terminalDisabled`)};if(!r.data?.terminalHosts?.some(e=>e.hostId===n.terminalHostId))return{gate:`device`,reason:A(`newSession.terminalHostUnavailable`)};if(e.hasDraftAttachments)return{gate:`terminal-capabilities`,reason:A(`newSession.terminalAttachmentsUnsupported`)};if(n.remotePlacement||e.pendingPlacement.sessionKey)return{gate:`device`,reason:A(`newSession.terminalPlacementUnsupported`)}}if(i===`terminal`&&e.hasCapabilityOverrides)return{gate:`terminal-capabilities`,reason:A(`newSession.terminalCapabilityOverridesUnsupported`)};if(n.folderSubmissionBlocked())return{gate:`folder`,reason:A(`newSession.checkingPlace`)};if(a)return e.pendingPlacement.retryAllowed&&s.recoveryScopeReady&&e.placementTargetForSubmission()&&e.pendingPlacement.agentId&&e.pendingPlacement.gatewayUrl===o.connection.gatewayUrl&&e.pendingPlacement.recoveryScope===s.recoveryScope?tu(e,i,a):{gate:`placement-recovery`,reason:A(`newSession.placementNotReady`)};if(r.context?.agents.state.agentsListCached)return{gate:`agents`,reason:A(r.context.agents.state.agentsError?`newSession.agentDefaultsUnavailable`:`newSession.loadingAgentDefaults`)};let l=i===`session`&&n.modelControl.modelSelectionBlockedReason(n.selectedAgent());if(l)return{gate:`model-unavailable`,reason:l};if(n.agents().length===0)return{gate:`agents`,reason:A(`newSession.agentsUnavailable`)};if(!So(r.data,n.selectedAgent()))return{gate:`agent-not-allowed`,reason:A(`newSession.catalogUnavailable`)};if(i===`session`&&!n.devicePlacementReady())return{gate:`device`,reason:n.devicePlacementDisabledReason()??A(`newSession.nodeUnavailable`)};let u=n.modelControl.devicePlacementUnsupportedReason();if((n.deviceId||n.autoDevice)&&u)return{gate:`device-runtime`,reason:u};let d=e.placementTargetForSubmission();if(d&&(!s.recoveryScope||!s.recoveryScopeReady||t.cloudProfilesPending))return{gate:`placement-recovery`,reason:A(`newSession.placementNotReady`)};let f=d?.kind===`profile`?d.profileId:``;return f&&(!t.cloudProfilesReady||!t.cloudProfiles.some(e=>e.id===f)||e.cloudRuntimeUnsupportedReason())?{gate:`cloud`,reason:e.cloudRuntimeUnsupportedReason()??A(`newSession.placementNotReady`)}:n.worktree&&!n.freshWorkspace&&!n.worktreeAvailable()?{gate:`worktree-unavailable`,reason:n.repository.kind===`checking`?A(`newSession.checkingGit`):n.remotePlacement?A(`newSession.remoteSourceUnavailable`):A(`newSession.worktreeUnavailable`)}:n.worktree&&!n.freshWorkspace&&!qc(n.worktreeName)?{gate:`worktree-name`,reason:A(`newSession.worktreeNameInvalid`)}:i===`terminal`&&!(n.folder.trim()||!n.terminalOnNode&&n.workspacePath())?{gate:`terminal-folder`,reason:A(`newSession.terminalNeedsFolder`)}:tu(e,i,a)}function tu(e,t,n){if(t!==`session`)return;let r=n?e.pendingPlacement.message:e.message.trim(),i=n?!!e.pendingPlacement.attachments?.length:e.hasDraftAttachments;return r||i?void 0:{gate:`empty-draft`}}var nu;function ru(){return(ru=e((()=>{M(),H(),oe(),$n(),q(),Xc(),ll(),Zl(),U(),nu=new Set([`attachment-reads`,`outcome-unknown`,`worktree-name`])})))()}var iu;function au(){return(au=e((()=>{M(),H(),dn(),oe(),Ne(),gi(),Lc(),Gc(),Qc(),q(),el(),al(),ll(),dl(),_l(),Sl(),Pl(),Il(),As(),Wl(),ru(),Zl(),U(),iu=class{get messageValue(){return this.messageText}set messageValue(e){e!==this.messageText&&(this.messageText=e,this.callbacks.onMessageChange?.(e))}constructor(e,t,n,r){this.gateway=e,this.place=t,this.read=n,this.callbacks=r,this.visibilityValue=`normal`,this.messageText=``,this.mentionsValue=[],this.activeSubmission=null,this.blockedSubmitGate=null,this.rejectedPromptError=null,this.submissionOutcomeUnknown=null,this.startedSession=new Ul,this.error=null,this.submitRequestToken=0,this.pendingPlacement=new ks(()=>this.read().context),this.composerTextarea=new $c,this.permission=new Fl(()=>this.callbacks.requestUpdate()),this.buildDraftSessionCreateParams=(e={})=>ml(this.place,this.gateway,this,this.read(),e),this.submissionAccess=(e=this.pendingPlacement.createParams??this.buildDraftSessionCreateParams())=>Ql({gateway:this.read().context?.gateway.snapshot,place:this.place,pendingPlacement:this.pendingPlacement,hasInitialTurn:!!(this.messageValue.trim()||this.attachmentDraft.attachments.length),createParams:e}),this.submitDisabledReason=()=>this.submitBlock()?.reason,this.canSubmit=()=>this.submitBlock()===void 0,this.requiresModelSetup=()=>$l({snapshot:this.read(),gateway:this.gateway,place:this.place,pendingPlacement:this.pendingPlacement}),this.placement=()=>ol(this.pendingPlacement,this.place),this.capabilities=new Zc(r.requestUpdate),this.capabilities.setMutationCallback(()=>this.startedSession.current=null),this.permission.setMutationCallback(()=>this.startedSession.current=null),this.sessionStartup=new ul(e),this.draftPersistence=new il(()=>({message:this.messageValue,mentions:this.mentionsValue,attachments:this.attachmentDraft.attachments,incognito:this.visibilityValue===`incognito`}),(e,t,n,r)=>{this.restoreDraftState({message:e,mentions:r,attachments:t,visibility:n?`normal`:this.visibilityValue})},()=>this.setError(Di)),this.attachmentDraft=new Ic(r.requestUpdate,()=>{this.rejectedPromptError=null,this.startedSession.current=null,this.draftPersistence.noteUserMutation()})}get visibility(){return this.visibilityValue}get message(){return this.messageValue}get mentions(){return this.mentionsValue}get submitting(){return this.activeSubmission!==null||this.sessionStartup.active}get pendingMessage(){return this.activeSubmission?.message??this.completedSubmission?.message??null}get completedSubmission(){return this.activeSubmission?null:this.startedSession.submission(this.read().context)}openSubmittedSession(){return this.startedSession.openSubmission(this.read().context,this.completedSubmission,{capture:()=>{let e=++this.submitRequestToken;return()=>e===this.submitRequestToken},publish:(e,t)=>{this.activeSubmission=e?{phase:`accepted`,message:e}:null,t!==void 0&&(this.error=t),this.callbacks.requestUpdate()}})}resumeInterruptedSubmission(){let e=this.sessionStartup.resume();e.kind===`resume`?this.submit(e):e.kind!==`wait`&&(this.activeSubmission=null,this.submissionOutcomeUnknown=`gateway-changed`,this.callbacks.requestUpdate())}setMessage(e,t){e!==this.messageValue&&(this.rejectedPromptError=null),this.startedSession.current=null,this.mentionsValue=t??Yn(this.messageValue,e,this.mentionsValue),this.messageValue=e,this.draftPersistence.noteUserMutation(),this.callbacks.requestUpdate()}restoreMessage(e,t=[]){this.rejectedPromptError=null,this.draftPersistence.noteDraftReplaced(),this.messageValue=e,this.mentionsValue=t,this.callbacks.requestUpdate()}restoreDraftState(e){this.draftPersistence.noteDraftReplaced(),this.messageValue=e.message,this.mentionsValue=e.mentions??[],this.visibilityValue=e.visibility,this.capabilities.restoreToolOverrides(e.toolOverrides),`permissionMode`in e&&this.permission.restore(e.permissionMode),this.attachmentDraft.restore(e.attachments)}setVisibility(e){this.startedSession.current=null;let t=this.visibilityValue===`incognito`,n=this.callbacks.requestUpdate;this.visibilityValue=e,this.draftPersistence.transitionIncognito(t,e===`incognito`,n)}setError(e){(e!==null||this.error===A(`newSession.cloudRecoveryUnavailable`))&&(this.error=e),this.callbacks.requestUpdate()}clearError(e){(e===void 0||this.error===e)&&(this.error=null,this.callbacks.requestUpdate())}markPendingPlacementUnavailable(e){this.pendingPlacement.retryAllowed=!1,this.submissionOutcomeUnknown=e,this.callbacks.requestUpdate()}noteBlockedSubmitAttempt(){this.blockedSubmitGate=this.submitBlock()?.gate??null,this.callbacks.requestUpdate()}blockedSubmitNotice(){let e=this.blockedSubmitGate?this.submitBlock():void 0;return e?.gate===this.blockedSubmitGate&&!nu.has(e.gate)?e.reason:void 0}incognitoDisabledReason(){let e=Ie(this.read().context?.gateway.snapshot,{method:`sessions.create`,params:this.buildDraftSessionCreateParams({visibility:`incognito`})});return e.allowed?void 0:e.reason}submitBlock(){return this.rejectedPromptError?{gate:`initial-turn-rejected`,reason:this.rejectedPromptError}:!K(this.read().data)&&this.attachmentDraft.pendingReads===0&&this.startedSession.isCurrent(this.read().context,this.place.agentId)?this.activeSubmission?{gate:`submitting`}:void 0:eu({gatewayState:this.gateway,placeState:this.place,pendingPlacement:this.pendingPlacement,submitting:this.activeSubmission!==null,message:this.messageValue,submissionOutcomeUnknown:this.submissionOutcomeUnknown,pendingAttachmentReads:this.attachmentDraft.pendingReads,hasDraftAttachments:this.attachmentDraft.attachments.length>0,hasCapabilityOverrides:this.capabilities.toolOverrides!==null,mentions:this.mentionsValue,visibility:this.visibilityValue,submissionSnapshot:()=>this.read(),requiresModelSetup:()=>this.requiresModelSetup(),submissionAccess:()=>this.submissionAccess(),placementTargetForSubmission:()=>this.placement().target,cloudRuntimeUnsupportedReason:()=>this.place.modelControl.cloudRuntimeUnsupportedReason(this.gateway.cloudProfiles.find(e=>e.id===this.place.cloudProfileId))})}invalidate(e=null){this.submitRequestToken+=1,this.startedSession.current=null;let t=this.activeSubmission?.phase===`creating`,n=e!==null&&t&&this.sessionStartup.interrupt();(e&&t&&!n||this.sessionStartup.retireChangedOwner())&&(this.submissionOutcomeUnknown=e),n||(this.activeSubmission=null),this.callbacks.requestUpdate()}resetDraft(){this.startedSession.clearSubmission(),this.rejectedPromptError=null,this.sessionStartup.clear();let e=!!this.pendingPlacement.sessionKey;this.blockedSubmitGate=null,this.invalidate(),this.submissionOutcomeUnknown=e?this.submissionOutcomeUnknown??`placement-interrupted`:null,this.visibilityValue=`normal`,this.capabilities.reset(),this.permission.reset(),this.attachmentDraft.reset({release:!0}),e?(this.pendingPlacement.restored||(this.pendingPlacement.retryAllowed=!1),this.applyRecoveryDraft(this.pendingPlacement.capture()),this.pendingPlacement.restored=!1):(this.clearPendingPlacementRecovery(),this.draftPersistence.noteDraftReplaced(),this.messageValue=``,this.mentionsValue=[]),this.clearError()}clearPendingPlacementRecovery(){this.pendingPlacement.clear(),this.submissionOutcomeUnknown=null,this.callbacks.requestUpdate()}releasePendingPlacementOwner(){this.pendingPlacement.reset(),this.submissionOutcomeUnknown=null,this.callbacks.requestUpdate()}restorePendingPlacementRecovery(e,t){this.applyRecoveryDraft(this.pendingPlacement.restore(e,t))}async submit(e,t=!1){if(!e&&K(this.read().data))return this.startInTerminal();let n=e?.background??(t&&this.visibilityValue!==`draft`),r=this.read().context;if(!r||!e&&!this.canSubmit()){this.noteBlockedSubmitAttempt();return}if(!Ye(r.config)&&(this.attachmentDraft.attachments.length||this.pendingPlacement.attachments?.length||e?.params.attachments?.length)){this.error=Re(),this.callbacks.requestUpdate();return}this.blockedSubmitGate=null;let i=hl(r,this,this.place,e,n);if(!i)return;let a=this.callbacks.takePreparedTitle?.(),o=++this.submitRequestToken,s=this.draftPersistence.captureSubmission(),c=e?.startedAt??Date.now(),l=gl(r,i,c),u=this.startedSession.messageForTurn(r,this.place.agentId,l),d=this.startedSession.captureSubmission(r,i.agentId,u,()=>o===this.submitRequestToken);this.activeSubmission={phase:`creating`,message:u},this.error=null,this.place.browser.close(),this.callbacks.closeTransientUi(),this.callbacks.requestUpdate();let f;try{let t=this.startedSession.current;if(t&&this.startedSession.isCurrent(r,this.place.agentId)){await this.startedSession.navigate(r,t);return}this.startedSession.current=null;let u=e?null:this.placement().target;Hc(r,i.message,!!i.apiAttachments?.length,!e&&!i.pendingPlacement);let p=!e&&!i.pendingPlacement&&!u&&!i.hasInitialTurn?this.place.browser.remoteProject:null;if(p&&!p.projectId&&!this.place.browser.projectId){let e=await i.client.request(`projects.add`,{gitUrl:p.cloneUrl},{timeoutMs:null});if(o!==this.submitRequestToken||this.gateway.client!==i.client)return;this.place.browser.recordRemoteProjectId(p.cloneUrl,e.id)}let m=e?.params??this.buildDraftSessionCreateParams({message:i.message,mentions:i.mentions,displayName:a,visibility:this.visibilityValue===`draft`&&!this.capabilities.canStartAsDraft(this.read().context)?`normal`:this.visibilityValue,attachments:i.draftAttachments}),h=jl({context:r,params:m,resumed:!!e,enabled:!n&&!u,agentId:i.agentId,retainDraft:this.callbacks.retainForHandoff,message:this.pendingMessage}),g=u?i.pendingPlacement?this.pendingPlacement.createParams:this.pendingPlacement.stageCreate({agentId:i.agentId,target:u,message:i.message,mentions:i.mentions,attachments:i.apiAttachments,gatewayUrl:i.gatewayUrl,recoveryScope:i.recoveryScope,createParams:m,persistent:this.visibilityValue!==`incognito`}):void 0,_=e?Ie(r.gateway.snapshot,{method:`sessions.create`,params:m,sessionScope:!0}):this.submissionAccess(g??m);if(!_.allowed){this.sessionStartup.clear(),this.error=_.reason;return}let v=u?this.pendingPlacement.capture():null;if(u&&!v){this.setPlacementRecoveryUnavailable(`creating`);return}i.apiAttachments?.length&&Ke(r.config);let y=i.pendingPlacement&&this.pendingPlacement.phase!==`creating`?Promise.resolve({key:this.pendingPlacement.sessionKey,initialRun:{status:`idle`}}):r.sessions.createResult(g??e?.params??this.sessionStartup.start(m,n),{reconciliation:`background`});f=h?.();let b=await y;if(b&&!u&&b.initialRun.status!==`rejected`&&await i.consumeWorktreeName?.(),o!==this.submitRequestToken&&!u){b&&b.initialRun.status!==`rejected`&&await this.clearSubmittedDraft(!0,s,!1);return}if(!b){if(o!==this.submitRequestToken)return;this.sessionStartup.clear(),this.error=r.sessions.state.error??A(`newSession.createFailed`),f&&await f.rollback();return}if(u&&v){await cl({context:r,client:i.client,agentId:i.agentId,pending:this.pendingPlacement,submittedRecovery:v,sessionKey:b.key,createdAt:c,isRequestCurrent:()=>o===this.submitRequestToken,isLifecycleCurrent:()=>this.read().isConnected&&i.client.recoveryScopeReady&&o===this.submitRequestToken&&this.gateway.client===i.client&&this.gateway.gatewayUrl===i.gatewayUrl&&this.gateway.recoveryScope===i.recoveryScope,clearRecovery:()=>this.clearPendingPlacementRecovery(),setError:e=>this.setError(e),onRecoveryUnavailable:()=>this.setPlacementRecoveryUnavailable(`created`),clearDraft:()=>(d(b.key),this.clearSubmittedDraft(!0,s)),consumeWorktreeName:i.consumeWorktreeName,completeInBackground:i.completeInBackground,onAccepted:()=>this.callbacks.onAccepted?.({...b,agentId:i.agentId}),navigate:()=>this.startedSession.navigate(r,{client:i.client,key:b.key,agentId:i.agentId})});return}await xl({onRejectedPrompt:n&&this.callbacks.retainRejectedPrompt?e=>{this.rejectedPromptError=e,this.error=e,this.sessionStartup.clear()}:void 0,context:r,client:i.client,agentId:i.agentId,result:b,turn:l,instant:f,navigation:this.startedSession,isCurrent:()=>o===this.submitRequestToken,clearDraft:(e,t)=>(t!==!1&&d(b.key,b.initialRun.status===`rejected`?b.initialRun.error:void 0),this.clearSubmittedDraft(e,s,t)),completeInBackground:i.completeInBackground,onAccepted:()=>this.callbacks.onAccepted?.({...b,agentId:i.agentId}),finishNavigation:()=>this.sessionStartup.clear()})}catch(e){o===this.submitRequestToken&&this.gateway.client===i.client&&(this.sessionStartup.clear(),this.error=e instanceof Error?e.message:String(e),f&&await f.rollback())}finally{f&&await f.finish(),o===this.submitRequestToken&&(this.activeSubmission=null,this.callbacks.requestUpdate())}}startInTerminal(){return Yl({snapshot:this.read(),place:this.place,flow:this,closeTransientUi:this.callbacks.closeTransientUi,capture:e=>{this.blockedSubmitGate=null,this.error=null;let t=++this.submitRequestToken,n=this.draftPersistence.captureSubmission(),r=()=>t===this.submitRequestToken;return{isRequestCurrent:r,isCurrent:()=>r()&&this.gateway.client===e,publish:(e,t)=>{this.activeSubmission=t?{phase:`creating`,message:e}:null,this.callbacks.requestUpdate()},consume:()=>(this.startedSession.current=null,this.clearSubmittedDraft(!0,n))}}})}clearSubmittedDraft(e,t,n=!0){return this.draftPersistence.clearSubmittedDraft(t,()=>{n?this.activeSubmission&&(this.activeSubmission.phase=`accepted`):this.activeSubmission=null,this.messageValue=``,this.mentionsValue=[],this.draftPersistence.noteDraftReplaced(),this.attachmentDraft.clearAfterSubmit(e),this.sessionStartup.clear()})}disconnect(){this.pendingPlacement.releaseClaim(),this.startedSession.current=null,this.draftPersistence.disconnect(),this.attachmentDraft.reset({release:!0}),this.composerTextarea.disconnect()}setPlacementRecoveryUnavailable(e){this.error=e===`creating`?A(`newSession.placementCreateFailed`):A(`newSession.placementStartFailed`,{error:`placement recovery storage is unavailable`})}applyRecoveryDraft(e){if(!e)return;let t=sl(e);this.place.applyPendingPlacement(t.placement),this.restoreDraftState(t.draft)}}})))()}function ou(e){return uu.has(e)}function su(e){let t=new Map;for(let n of e){let e=(n.deviceId??n.instanceId)?.trim().toLowerCase();e&&n.roles?.includes(`node`)&&t.set(e,n.reason?.trim().toLowerCase()===`disconnect`?`offline`:`connected`)}return JSON.stringify([...t].toSorted(([e],[t])=>e.localeCompare(t)))}function cu(e){let t=e.querySelector(`.new-session-page__select--agent wa-dropdown`);t&&(t.open=!1)}function lu(e){for(let t of[`wa-dropdown[open]`,`wa-popover.new-session-page__picker-popover`])for(let n of e.querySelectorAll(t))n.open=!1}var uu;function du(){return(du=e((()=>{uu=new Set([`config.changed`,`node.pair.requested`,`node.pair.resolved`,`node.runnerInventory.changed`,`device.pair.requested`,`device.pair.resolved`])})))()}var fu;function pu(){return(pu=e((()=>{Lt(),lt(),ut(),M(),Ee(),Pe(),_a(),q(),Ns(),Zs(),Fc(),au(),du(),fu=class{protectPrivateDraftFromReload(){let e=()=>this.submission.visibility===`incognito`&&!!(this.submission.message||this.submission.mentions.length||this.submission.attachmentDraft.attachments.length||this.submission.attachmentDraft.pendingReads),t=(e=!1)=>ke({message:A(e?`chat.privateDraftReload.changed`:`chat.privateDraftReload.blocked`),actionLabel:A(`chat.privateDraftReload.review`),onAction:()=>void n()}),n=async()=>{let n=this.read().context;if(!n||!this.read().isConnected||!e()||this.privateDraftReview)return;let r=new AbortController,i=n.gateway.snapshot.client,a=n.gateway.connection,o=this.submission.message,s=this.submission.mentions,c=[...this.submission.attachmentDraft.attachments],l=this.submission.attachmentDraft.pendingReads,u=()=>!r.signal.aborted&&this.read().isConnected&&this.read().context===n&&n.gateway.snapshot.client===i&&n.gateway.connection===a,d=()=>u()&&this.submission.visibility===`incognito`&&this.submission.message===o&&this.submission.mentions===s&&this.submission.attachmentDraft.pendingReads===l&&this.submission.attachmentDraft.attachments.length===c.length&&c.every((e,t)=>this.submission.attachmentDraft.attachments[t]===e);this.privateDraftReview={controller:r,isCurrent:d};let f=ot(n.gateway);try{let n=await ua({text:o,attachments:c,hasGoal:!1,pendingReads:l,isCurrent:d,signal:r.signal});if(!d()){u()&&e()&&t(!0);return}if(!n)return;this.submission.attachmentDraft.reset({release:!0}),this.submission.setMessage(``,[]),await ct({timeoutMs:0,...f})}catch{u()&&ke({message:A(`chat.privateDraftReload.unavailable`)})}finally{this.privateDraftReview?.controller===r&&(this.privateDraftReview=void 0),r.signal.reason===`draft-changed`&&this.read().isConnected&&this.read().context===n&&n.gateway.connection===a&&n.gateway.snapshot.client===i&&e()&&t(!0)}},r=rt(()=>!e(),()=>t());return()=>{r(),this.privateDraftReview?.controller.abort()}}constructor(e,t,n){this.read=t;let r=()=>{this.privateDraftReview&&!this.privateDraftReview.isCurrent()&&this.privateDraftReview.controller.abort(`draft-changed`),n.requestUpdate()};this.gateway=new Ms(e,()=>({...t(),isAdmin:this.place?.isAdmin()??!1,canStartAsDraft:this.submission?.capabilities.canStartAsDraft(t().context)??!1,visibility:this.submission?.visibility??`normal`,cloudProfileId:this.place?.cloudProfileId??``,pendingPlacement:this.submission?.pendingPlacement??{sessionKey:``,gatewayUrl:``,recoveryScope:``},agentsHydrated:this.place?.agentsHydrated??!1,runtimeId:this.place?.devicePlacementRuntime()?.id??``}),{preferenceScope:n.preferenceScope,readPalettePreference:n.readPalettePreference,requestUpdate:r,updateComplete:()=>e.updateComplete,onInvalidate:(e,t)=>{this.invalidate(e,t),n.onInvalidate()},onVisibilityRetired:()=>this.submission.setVisibility(`normal`),onCloudProfileCleared:()=>this.place.clearCloudProfile(),onCloudState:e=>this.submission.setError(e),onPendingPlacementReset:()=>this.submission.releasePendingPlacementOwner(),onRecoveryReady:n.onRecoveryReady,onAdoptAgentDefaults:()=>this.place.adoptAgentDefaults({preserveSelectedAgent:!0,preserveSelectedFolder:!0})}),this.browser=new Xs(e,this.gateway,()=>({context:t().context,isAdmin:this.place?.isAdmin()??!1}),{requestUpdate:r,onProjectMissing:()=>this.place.clearProjectSelection(),onSelectProject:e=>this.place.selectProjectId(e),onApprovedListing:e=>this.place.recordGatewayApprovedListing(e),querySelector:n.querySelector,activeElement:n.activeElement,body:n.body,pickerIdPrefix:n.pickerIdPrefix}),this.place=new Pc(this.gateway,this.browser,()=>({context:t().context,data:t().data,submitting:this.submission?.submitting??!1,pendingPlacementSessionKey:this.submission?.pendingPlacement.sessionKey??``}),{requestUpdate:r,onError:e=>e===null?this.submission.clearError():this.submission.setError(e),onClearError:e=>this.submission.clearError(e)}),this.submission=new iu(this.gateway,this.place,t,{...n,requestUpdate:r}),this.submission.draftPersistence.modelSelection={read:()=>t().context?.config?.current.newSessionModelDefaults===`configured`?this.place.modelControl.draftSelection(this.place.agentId):void 0,restore:e=>this.place.modelControl.restoreDraftSelection(e),retire:()=>{t().context?.config?.current.newSessionModelDefaults===`configured`&&this.place.modelControl.retireDraftSelection()}},this.place.modelControl.onDraftSelectionChange=()=>{t().context?.config?.current.newSessionModelDefaults===`configured`&&this.submission.draftPersistence.noteModelSelectionMutation()},this.subscriptions=new qe(e).effect(()=>this.read().context,()=>this.protectPrivateDraftFromReload()).watch(()=>this.read().context?.gateway,(e,t)=>e.subscribe(t),e=>this.gateway.synchronize(e)).effect(()=>this.read().context?.gateway,e=>{let t=su(pt(e.snapshot.hello?.snapshot)??[]);return e.subscribeEvents(n=>{if(this.read().context?.gateway!==e)return;let r=n.event===`presence`?pt(n.payload):null,i=r?su(r):t;(ou(n.event)||i!==t)&&(t=i,this.gateway.refreshCloudProfiles(),this.gateway.handleCatalogRetry())})})}agentsReady(){let e=this.read().context?.agents.state;return!!(this.gateway.connected&&this.gateway.client&&e?.connected&&e.client===this.gateway.client&&!e.agentsListCached&&this.place.agents().length>0)}synchronizeSelections(){let e=this.read().context?.config?.current.newSessionModelDefaults;if(!this.place.agentsHydrated&&this.agentsReady())this.place.setAgentsHydrated(!0),this.place.adoptAgentDefaults({preserveSelectedAgent:!0,preserveSelectedFolder:!0});else if(this.place.agentsHydrated&&e!==this.modelDefaultsPolicy){let{context:e,data:t}=this.read();this.place.modelControl.load(e,this.place.agentId,!K(t),{agent:this.place.selectedAgent(),preference:this.gateway.readPreference(this.place.agentId)})}e===`configured`&&this.modelDefaultsPolicy!==`configured`&&!this.submission.submitting&&this.place.modelControl.draftSelection(this.place.agentId)&&this.submission.draftPersistence.noteModelSelectionMutation(),this.modelDefaultsPolicy=e,this.place.restorePreferenceSelections(),this.place.synchronizeTerminalHosts()}invalidate(e,t){this.place.invalidateGatewayDiscovery(e),this.submission.attachmentDraft.abortReads(),this.submission.invalidate(t),e&&this.submission.pendingPlacement.sessionKey&&this.submission.markPendingPlacementUnavailable(t),e&&this.submission.clearError()}disconnect(){this.subscriptions.clear(),this.gateway.invalidateDiscovery(!0,this.submission.pendingPlacement.sessionKey?`placement-interrupted`:`gateway-changed`),this.gateway.disconnect(),this.browser.disconnect(),this.submission.disconnect()}}})))()}function mu(e){let t=e.context?.gateway,n=t?.snapshot.client,r=t?.snapshot.selfUser?.identity;if(n&&t?.snapshot.phase===`connected`&&r?.type===`profile`&&Tt(t.snapshot.hello?.auth??null)&&!e.isCatalogTarget&&!e.nativeTerminal&&e.visibility!==`incognito`)return{client:n,ownerKey:JSON.stringify([t.connectionRevision,n.recoveryScope,r.id,e.draftOwnerKey]),params:{agentId:e.agentId,...e.visibility===`draft`?{visibility:`draft`}:{}}}}function hu(){return(hu=e((()=>{vt()})))()}function gu(e){wu=e.type===`pointerdown`}function _u(e,t){if(e.target!==e.currentTarget)return;let n=document.activeElement;if(n instanceof HTMLInputElement&&wu&&n.selectionStart!==n.selectionEnd){wu=!1,e.preventDefault();return}t()}function vu(e){e?.querySelector(`input`)?.removeAttribute(`aria-activedescendant`);for(let t of e?.querySelectorAll(`[data-worktree-suggestion]`)??[])t.setAttribute(`aria-selected`,`false`)}function yu(e,t){if(!(e instanceof HTMLElement))return;let n=e.closest(`.new-session-page__branch-field`);n?.querySelector(`wa-popup`)?.toggleAttribute(`active`,t),(n?.querySelector(`input`))?.setAttribute(`aria-expanded`,String(t)),t||vu(n)}function bu(e,t){let n=[...e.closest(`.new-session-page__branch-field`)?.querySelectorAll(`[data-worktree-suggestion]`)??[]];if(n.length===0)return!1;let r=n.findIndex(e=>e.getAttribute(`aria-selected`)===`true`);if(t.key===`Enter`&&!t.isComposing&&r>=0)return n[r].click(),!0;if(t.key!==`ArrowDown`&&t.key!==`ArrowUp`)return!1;let i=t.key===`ArrowDown`?1:-1,a=r<0?i===1?0:n.length-1:(r+i+n.length)%n.length;for(let[e,t]of n.entries())t.setAttribute(`aria-selected`,String(e===a));return e.setAttribute(`aria-activedescendant`,n[a].id),yu(e,!0),!0}function xu(e){let t=e.worktreeName.trim();return e.worktree&&!e.repository&&t?{label:A(`newSession.checkoutWorktreeNamed`,{name:t})}:e.destination===`cloud`?{label:e.baseRef?A(`newSession.checkoutCloudFrom`,{branch:e.baseRef}):A(`newSession.checkoutCloud`)}:e.repository?{label:e.baseRef?A(`newSession.checkoutRepositoryFrom`,{branch:e.baseRef}):A(`newSession.checkoutRepository`)}:e.destination===`local`&&!e.worktreeAvailable&&!e.worktree?null:e.worktree?{label:e.baseRef?A(`newSession.checkoutWorktreeFrom`,{branch:e.baseRef}):A(`newSession.checkoutWorktree`)}:{label:e.headBranch||A(`newSession.checkoutCurrent`)}}function Su(e){let t=t=>{let n=t.currentTarget;if(!(n instanceof HTMLElement))return;if(bu(n,t)){t.preventDefault(),t.stopPropagation();return}if(t.key===`Escape`){t.preventDefault(),t.stopPropagation(),n.closest(`wa-popover`)?.removeAttribute(`open`);return}let r=n.closest(`wa-popover`),i=r?.querySelector(`input[data-worktree-name]`)?.value??e.worktreeName;if(!(t.key!==`Enter`||t.isComposing||!e.repository&&!qc(i))&&(wu=!1,t.preventDefault(),r)){let t=n=>{n.target===r&&(r.removeEventListener(`wa-after-hide`,t),e.onConfirm())};r.addEventListener(`wa-after-hide`,t),r.removeAttribute(`open`)}},n=(e.branches?.branches??[]).slice(0,8),r=e.worktreeName.trim(),i=I`<input
    id=${(e.idPrefix??`new-session`)+`-worktree-base-ref`}
    type="text"
    role=${n.length?`combobox`:L}
    aria-label=${A(`newSession.worktreeBaseRef`)}
    aria-autocomplete=${n.length?`list`:L}
    aria-controls=${n.length?(e.idPrefix??`new-session`)+`-worktree-branch-suggestions`:L}
    aria-expanded=${n.length?`false`:L}
    ?disabled=${e.submitting||e.pendingPlacement}
    placeholder=${e.branchesLoading?A(`common.loading`):e.branches?.defaultBranch??A(`newSession.worktreeBaseRef`)}
    .value=${e.baseRef}
    @focus=${e=>yu(e.currentTarget,!0)}
    @input=${t=>{t.currentTarget instanceof HTMLInputElement&&(vu(t.currentTarget.closest(`.new-session-page__branch-field`)),yu(t.currentTarget,!0),e.onBaseRefInput(t.currentTarget.value))}}
    @keydown=${t}
    @pointerdown=${gu}
    @pointerup=${gu}
    @pointercancel=${gu}
  />`;return I`
    <div class="new-session-page__menu-field">
      <span>${A(`newSession.worktreeBaseRef`)}</span>
      ${n.length?I`<div
              class="new-session-page__branch-field"
              @focusout=${e=>{let t=e.currentTarget;t instanceof HTMLElement&&(!(e.relatedTarget instanceof Node)||!t.contains(e.relatedTarget))&&yu(t,!1)}}
            >
              ${i}
              <wa-popup
                class="new-session-page__branch-popup"
                anchor=${(e.idPrefix??`new-session`)+`-worktree-base-ref`}
                placement="bottom-start"
                sync="width"
              >
                <div
                  id=${(e.idPrefix??`new-session`)+`-worktree-branch-suggestions`}
                  class="new-session-page__branch-suggestions"
                  role="listbox"
                  aria-label=${A(`newSession.worktreeBaseRef`)}
                >
                  ${n.map((t,n)=>I`<button
                      id=${`${e.idPrefix??`new-session`}-worktree-branch-suggestion-${n}`}
                      type="button"
                      role="option"
                      aria-selected="false"
                      class="session-menu__item"
                      data-worktree-suggestion=${t.name}
                      tabindex="-1"
                      @mousedown=${e=>e.preventDefault()}
                      @click=${n=>{e.onBaseRefInput(t.name),yu(n.currentTarget,!1)}}
                    >
                      <span class="session-menu__text">${t.name}</span>
                    </button>`)}
                </div>
              </wa-popup>
            </div>`:i}
    </div>
    <div class="new-session-page__menu-note">
      ${A(e.branches?.branchesUnavailable?`newSession.worktreeBranchesUnavailable`:`newSession.worktreeBranchesLimited`)}
    </div>
    ${e.repository?L:I`<label class="new-session-page__menu-field">
              <span>${A(`newSession.worktreeName`)}</span>
              <input
                type="text"
                data-worktree-name
                ?disabled=${e.submitting||e.pendingPlacement}
                placeholder=${A(`newSession.worktreeNamePlaceholder`)}
                .value=${e.worktreeName}
                @input=${t=>{t.currentTarget instanceof HTMLInputElement&&e.onWorktreeNameInput(t.currentTarget.value)}}
                @keydown=${t}
                @pointerdown=${gu}
                @pointerup=${gu}
                @pointercancel=${gu}
              />
            </label>
            <div class="new-session-page__menu-note">
              ${r?A(`newSession.worktreeBranchNote`,{branch:`openclaw/${r}`}):A(`newSession.worktreeBranchFromTitleNote`)}
            </div>`}
  `}function Cu(e){return I`
    <span class="new-session-page__select">
      <button
        id=${(e.idPrefix??`new-session`)+`-checkout-trigger`}
        type="button"
        class="new-session-page__trigger ${e.popoverHiding?`new-session-page__trigger--hiding`:``}"
        title="${A(`newSession.checkout`)}: ${e.state.label}"
        aria-label="${A(`newSession.checkout`)}: ${e.state.label}"
        data-worktree=${String(e.worktree)}
        aria-haspopup="dialog"
        aria-expanded=${String(e.popoverOpen)}
        ?disabled=${e.submitting||e.pendingPlacement}
        @click=${e.onGuardTransition}
      >
        <span class="new-session-page__target-icon" aria-hidden="true">${P.gitBranch}</span>
        <span class="new-session-page__trigger-label">${e.state.label}</span>
        <span
          class="new-session-page__trigger-chevron new-session-page__trigger-chevron--desktop"
          aria-hidden="true"
          >${P.chevronDown}</span
        >
        <span
          class="new-session-page__trigger-chevron new-session-page__trigger-chevron--mobile"
          aria-hidden="true"
          >${P.chevronsUpDown}</span
        >
      </button>
    </span>
    <wa-popover
      ${zt(Mr)}
      class="new-session-page__select new-session-page__checkout-popover new-session-page__picker-popover"
      for=${(e.idPrefix??`new-session`)+`-checkout-trigger`}
      placement="bottom-start"
      without-arrow
      @wa-show=${t=>{t.target===t.currentTarget&&e.onPopoverShow()}}
      @wa-hide=${t=>_u(t,e.onPopoverHide)}
      @wa-after-hide=${t=>{t.target===t.currentTarget&&e.onPopoverAfterHide()}}
    >
      <div class="new-session-page__picker-root">
        <div class="new-session-page__menu-title">${A(`newSession.checkout`)}</div>
        ${e.repository?L:I`${Y({value:`checkout`,label:A(`newSession.checkoutCurrent`),icon:P.folder,sub:e.branches?.headBranch,checked:!e.worktree,disabled:e.remotePlacement,title:e.remotePlacement?A(`newSession.checkoutRemoteLocked`):void 0,onSelect:()=>e.onSelectWorktree(!1),keepOpen:!0},e.submitting)}
              ${Y({value:`worktree`,label:A(`newSession.checkoutWorktree`),icon:P.gitBranch,sub:A(`newSession.checkoutWorktreeSub`),checked:e.worktree,disabled:!e.worktreeAvailable,title:e.worktreeAvailable?void 0:e.repositoryUnavailable?A(`newSession.gitCheckUnavailable`):A(`newSession.worktreeUnavailable`),onSelect:()=>e.onSelectWorktree(!0),keepOpen:!0},e.submitting)} `}
        ${e.worktree||e.repository?Su(e):L}
        ${e.remotePlacement?I`<div class="new-session-page__menu-note">
                ${A(e.repository?`newSession.placementClonesRepository`:`newSession.placementSyncsFolder`,{folder:e.folderLabel})}
              </div>`:L}
      </div>
    </wa-popover>
  `}var wu;function Tu(){return(Tu=e((()=>{R(),Bt(),F(),Vr(),M(),H(),es(),Xc(),U(),wu=!1})))()}var Eu;function Du(){return(Du=e((()=>{R(),mt(),F(),Eu={laptop:N(B`<path
      d="M18 5a2 2 0 0 1 2 2v8.526a2 2 0 0 0 .212.897l1.068 2.127a1 1 0 0 1-.9 1.45H3.62a1 1 0 0 1-.9-1.45l1.068-2.127A2 2 0 0 0 4 15.526V7a2 2 0 0 1 2-2z"
    />
    <path d="M20.054 15.987H3.946" />`),pcCase:N(B`<rect width="14" height="20" x="5" y="2" rx="2" />
    <path d="M15 14h.01M9 6h6M9 10h6" />`),macMini:N(B`<path
      d="M2.212 11.577a2 2 0 0 0-.212.896V18a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-5.527a2 2 0 0 0-.212-.896L18.55 5.11A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z"
    />
    <path d="M21.946 12.013H2.054M6 16h.01M10 16h.01" />`),macStudio:N(B`<path d="m3 8 3-4h12l3 4v10a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2Z" />
    <path d="M3 8h18M6 15h2M11 15h2M17 15h.01" />`),allInOne:P.monitor,tablet:N(B`<rect width="16" height="20" x="4" y="2" rx="2" ry="2" />
    <path d="M12 18h.01" />`),watch:N(B`<circle cx="12" cy="12" r="6" />
    <polyline points="12 10 12 12 13 13" />
    <path d="m16.13 7.66-.81-4.05a2 2 0 0 0-2-1.61h-2.68a2 2 0 0 0-2 1.61l-.78 4.05" />
    <path d="m7.88 16.36.8 4a2 2 0 0 0 2 1.61h2.72a2 2 0 0 0 2-1.61l.81-4.05" />`),smartphone:P.smartphone,browser:P.globe,terminal:P.terminal,server:P.server}})))()}function Ou(e){let t=e?.trim();if(t)return t.startsWith(`MacBook`)?`laptop`:t.startsWith(`Macmini`)?`mini`:t.startsWith(`MacPro`)?`pro`:t.startsWith(`iMac`)?`imac`:ju[t]}function ku(e){let t=e?.replace(/[_-]+/g,` `);if(t){if(/\bmac\s*book(?:\s*(?:pro|air))?\b/i.test(t))return`laptop`;if(/\bmac\s*mini\b/i.test(t))return`mini`;if(/\bmac\s*studio\b/i.test(t))return`studio`}}function Au(e){let t=e?.trim();if(t)switch(Ou(t)){case`laptop`:return t.startsWith(`MacBookAir`)||Mu.has(t)?`MacBook Air`:/^MacBook\d/.test(t)?`MacBook`:`MacBook Pro`;case`mini`:return`Mac mini`;case`studio`:return`Mac Studio`;case`pro`:return`Mac Pro`;case`imac`:return`iMac`;default:return}}var ju,Mu;function Nu(){return(Nu=e((()=>{ju={"Mac13,1":`studio`,"Mac13,2":`studio`,"Mac14,2":`laptop`,"Mac14,3":`mini`,"Mac14,5":`laptop`,"Mac14,6":`laptop`,"Mac14,7":`laptop`,"Mac14,8":`pro`,"Mac14,9":`laptop`,"Mac14,10":`laptop`,"Mac14,12":`mini`,"Mac14,13":`studio`,"Mac14,14":`studio`,"Mac14,15":`laptop`,"Mac15,3":`laptop`,"Mac15,4":`imac`,"Mac15,5":`imac`,"Mac15,6":`laptop`,"Mac15,7":`laptop`,"Mac15,8":`laptop`,"Mac15,9":`laptop`,"Mac15,10":`laptop`,"Mac15,11":`laptop`,"Mac15,12":`laptop`,"Mac15,13":`laptop`,"Mac15,14":`studio`,"Mac16,1":`laptop`,"Mac16,2":`imac`,"Mac16,3":`imac`,"Mac16,5":`laptop`,"Mac16,6":`laptop`,"Mac16,7":`laptop`,"Mac16,8":`laptop`,"Mac16,9":`studio`,"Mac16,10":`mini`,"Mac16,11":`mini`,"Mac16,12":`laptop`,"Mac16,13":`laptop`,"Mac17,2":`laptop`},Mu=new Set([`Mac14,2`,`Mac14,15`,`Mac15,12`,`Mac15,13`,`Mac16,12`,`Mac16,13`])})))()}function Pu(e){let t=ic(e.environments,e.devicePlacement,e.deviceDisabledReason),n=ac(e.environments,t,e.deviceDisabledReason),r=t.find(t=>t.deviceId===e.deviceId),i=e.cloudProfiles.find(t=>t.id===e.cloudProfileId);if(e.cloudProfileId){let r=i?Ro(i):``,a=e.os||r,o=i?.operatingSystems??[],s=i?zo(i,a):[],c=i?Bo(i,a):void 0,l=e.machineClass?s.find(t=>t.id===e.machineClass):c;return{kind:`cloud`,label:i?.id??e.cloudProfileId,operatingSystems:o,selectedOsId:a,cloudMachines:s,selectedMachineId:l?.id??``,devices:t,cloudProfiles:e.cloudProfiles,autoDeviceDisabledReason:n}}return{kind:e.deviceId?`device`:e.autoDevice?`auto-device`:`local`,label:e.deviceId?r?.label??e.deviceId:A(e.autoDevice?`newSession.autoDevice`:`newSession.local`),cloudMachines:[],selectedMachineId:``,operatingSystems:[],selectedOsId:``,devices:t,cloudProfiles:e.cloudProfiles,autoDeviceDisabledReason:n}}function Fu(e){let t=e?.platform?.trim();if(t&&!/^(?:darwin|macos|mac os(?: x)?)\b/i.test(t))return P.monitor;let n=ku(e?.label),r=n===`laptop`?Eu.laptop:n===`mini`?Eu.macMini:n===`studio`?Eu.macStudio:void 0;return r?I`<span class="new-session-page__device-icon" data-form=${n}>${r}</span>`:P.monitor}function Iu(e){return I`<div
    class="new-session-page__environment-skeletons"
    role="status"
    aria-label=${A(`common.loading`)}
    aria-busy="true"
    data-section=${e}
  >
    <span class="skeleton new-session-page__environment-skeleton-row" aria-hidden="true"></span>
    <span class="skeleton new-session-page__environment-skeleton-row" aria-hidden="true"></span>
  </div>`}function Lu(e){let t=yr(e.state.cloudProfiles.find(t=>t.id===e.cloudProfileId)),n=e.state.kind===`cloud`?t.icon:e.state.kind===`local`?P.home:e.state.kind===`auto-device`?Ru:Fu(e.state.devices.find(t=>t.deviceId===e.deviceId)),r=e.gatewayName.trim()||A(`newSession.local`),i=e.state.kind===`local`?r:e.state.label,a=e.state.kind===`cloud`?[e.state.operatingSystems.find(t=>t.id===e.state.selectedOsId)?.label,e.state.cloudMachines.find(t=>t.id===e.state.selectedMachineId)?.label].filter(Boolean).join(` · `):``,o=e.environmentQuery.trim().toLocaleLowerCase(),s=(...e)=>e.some(e=>e?.toLocaleLowerCase().includes(o)),c=s(A(`newSession.local`),A(`newSession.gatewayHost`),e.gatewayName),l=e.state.devices.filter(e=>s(A(`newSession.device`),A(`newSession.yourDevices`),e.label,e.deviceId,...e.facts)).toSorted((e,t)=>Number(t.selectable)-Number(e.selectable)),u=e.isAdmin?e.state.cloudProfiles.filter(e=>s(A(`newSession.cloud`),e.id,e.providerId,e.providerDisplayId,yr(e).label,e.trust===`disposable`?A(`newSession.environmentDisposable`):e.trust===`persistent`?A(`newSession.environmentPersistent`):void 0)):[],d=e.isAdmin&&!!e.cloudProfileId&&!e.state.cloudProfiles.some(t=>t.id===e.cloudProfileId)&&s(A(`newSession.cloud`),e.cloudProfileId),f=e.state.devices.length>1&&(l.length>0||s(A(`newSession.autoDeviceChoose`),A(`newSession.autoDevice`))),p=e.state.autoDeviceDisabledReason??A(e.autoPlacementMode===`eligible-order`?`newSession.autoDeviceHintEligible`:`newSession.autoDeviceHint`),m=e.submitting||e.pendingPlacement,h=e.catalogLoading&&l.length===0,g=e.isAdmin&&e.catalogLoading&&u.length===0,_;return I`
    <span class="new-session-page__select new-session-page__select--where">
      <button
        id=${(e.idPrefix??`new-session`)+`-where-trigger`}
        type="button"
        class="new-session-page__trigger ${e.popoverHiding?`new-session-page__trigger--hiding`:``}"
        aria-label="${A(`newSession.where`)}: ${i}${a?`, ${a}`:``}"
        aria-description=${e.state.kind===`cloud`&&t.label?A(`newSession.cloudWorkerProvider`,{provider:t.label}):L}
        data-cloud-profile=${e.cloudProfileId||L}
        data-machine-class=${e.machineClass||L}
        data-os=${e.os||L}
        data-device-id=${e.deviceId||L}
        data-auto-device=${e.autoDevice?`true`:L}
        aria-haspopup="dialog"
        aria-expanded=${String(e.popoverOpen)}
        ?disabled=${e.submitting||e.pendingPlacement}
        @click=${e.onGuardTransition}
      >
        <span class="new-session-page__target-icon" aria-hidden="true">${n}</span>
        <span class="new-session-page__trigger-label">${i}</span>
        ${a?I`<span class="new-session-page__trigger-summary">${a}</span>`:L}
        <span
          class="new-session-page__trigger-chevron new-session-page__trigger-chevron--desktop"
          aria-hidden="true"
          >${P.chevronDown}</span
        >
        <span
          class="new-session-page__trigger-chevron new-session-page__trigger-chevron--mobile"
          aria-hidden="true"
          >${P.chevronsUpDown}</span
        >
      </button>
    </span>
    <wa-popover
      ${zt(Mr)}
      class="new-session-page__select new-session-page__where-popover new-session-page__picker-popover"
      for=${(e.idPrefix??`new-session`)+`-where-trigger`}
      placement="bottom-start"
      without-arrow
      @wa-show=${t=>{t.target===t.currentTarget&&(t.currentTarget instanceof mr&&(t.currentTarget.popup.autoSize=`vertical`,t.currentTarget.popup.autoSizePadding=8),e.onPopoverShow())}}
      @wa-hide=${t=>{t.target===t.currentTarget&&e.onPopoverHide()}}
      @wa-after-hide=${t=>{t.target===t.currentTarget&&e.onPopoverAfterHide()}}
    >
      <div class="new-session-page__environment-layout">
        <div class="new-session-page__picker-root new-session-page__environment-picker">
          <label class="new-session-page__environment-search">
            <span aria-hidden="true">${P.search}</span>
            <input
              type="search"
              autofocus
              aria-label=${A(`newSession.environmentSearchPlaceholder`)}
              placeholder=${A(`newSession.environmentSearchPlaceholder`)}
              .value=${e.environmentQuery}
              ?disabled=${m}
              @input=${t=>{t.currentTarget instanceof HTMLInputElement&&e.onEnvironmentQueryInput(t.currentTarget.value)}}
            />
          </label>
          <div ${zt(e=>{if(_?.(),!(e instanceof HTMLElement))return;let t=()=>{let t=e.scrollHeight-e.clientHeight;e.toggleAttribute(`data-fade-top`,t>1&&e.scrollTop>1),e.toggleAttribute(`data-fade-bottom`,t>1&&e.scrollTop<t-1)},n=typeof ResizeObserver>`u`?void 0:new ResizeObserver(t);n?.observe(e);let r=new MutationObserver(t);r.observe(e,{childList:!0,subtree:!0,characterData:!0}),e.addEventListener(`scroll`,t,{passive:!0}),_=()=>{n?.disconnect(),r.disconnect(),e.removeEventListener(`scroll`,t)},t()})} class="new-session-page__environment-list">
            ${c||l.length||f?I`<div
                    class="new-session-page__environment-heading new-session-page__devices-heading"
                  >
                    <span>${A(`newSession.yourDevices`)}</span>
                    ${e.isAdmin?I`<button
                            type="button"
                            class="new-session-page__connect-device"
                            data-action="connect-machine"
                            aria-label=${A(`newSession.connectMachine`)}
                            ?disabled=${m}
                            @click=${e.onConnectMachine}
                          >
                            ${zu}
                          </button>`:L}
                  </div>`:L}
            ${f?I`<openclaw-tooltip
                    class="new-session-page__environment-details"
                    placement="right-start"
                  >
                    <button
                      type="button"
                      class="session-menu__item new-session-page__environment-option"
                      data-value="auto-device"
                      data-popover="close"
                      aria-pressed=${String(e.autoDevice===!0)}
                      aria-description=${p}
                      ?disabled=${m||!e.autoDevice&&!!e.state.autoDeviceDisabledReason}
                      @click=${e.onSelectAutoDevice}
                    >
                      <span class="session-menu__icon" aria-hidden="true">${Ru}</span>
                      <span class="session-menu__text">${A(`newSession.autoDeviceChoose`)}</span>
                      <span class="session-menu__check" aria-hidden="true"
                        >${e.autoDevice?P.check:L}</span
                      >
                    </button>
                    <div slot="content" class="new-session-page__environment-card">
                      <strong>${A(`newSession.autoDeviceChoose`)}</strong>
                      <div class="new-session-page__card-row">
                        <span class="new-session-page__card-icon" aria-hidden="true"
                          >${P.info}</span
                        >
                        <span>${p}</span>
                      </div>
                    </div>
                  </openclaw-tooltip>`:L}
            ${c?Y({value:`gateway`,label:r,icon:P.home,summary:A(`newSession.runsOnGateway`),compact:!0,checked:e.state.kind===`local`,onSelect:()=>e.onSelectDevice(``)},m):L}
            ${Ht(l,e=>e.deviceId,t=>Y({value:`device:${t.deviceId}`,label:t.label,sub:t.subtitle,icon:Fu(t),platform:t.platform?Cn(t.platform):void 0,capabilityLabels:ec(t.capabilities),hideDetails:t.hideDetails,remediation:t.remediation,capacityLabel:t.selectable&&t.workerSlots?A(`newSession.concurrentSessionsValue`,{used:String(t.workerSlots.total-t.workerSlots.available),total:String(t.workerSlots.total)}):void 0,compact:!0,checked:e.state.kind===`device`&&e.deviceId===t.deviceId,disabled:!t.selectable,title:t.disabledReason,onSelect:()=>e.onSelectDevice(t.deviceId)},m))}
            ${h?Iu(`devices`):L}
            ${u.length||d||g?I`<div
                    class="new-session-page__environment-heading new-session-page__devices-heading"
                  >
                    <span>${A(`newSession.cloud`)}</span>
                    ${e.isAdmin&&!g?I`<button
                            type="button"
                            class="new-session-page__connect-device"
                            data-action="manage-cloud-workers"
                            aria-label=${A(`newSession.manageCloudWorkers`)}
                            ?disabled=${m}
                            @click=${e.onManageCloudWorkers}
                          >
                            ${zu}
                          </button>`:L}
                  </div>`:L}
            ${Jo({profiles:u,selectedId:e.cloudProfileId,selectedOs:e.state.selectedOsId,selectedMachine:e.state.selectedMachineId,onSelectOs:e.onSelectCloudOs,onSelectMachine:e.onSelectCloudMachine,submitting:m,compact:!0,disabled:!!e.cloudDisabledReason,disabledReason:e.cloudDisabledReason,profileDisabledReason:e.cloudProfileDisabledReason,onSelect:e.onSelectCloudProfile})}
            ${g?Iu(`cloud`):L}
            ${d?Y({value:`cloud:${e.cloudProfileId}`,label:e.cloudProfileId,icon:P.cloud,description:A(`newSession.catalogUnavailable`),compact:!0,checked:!0,disabled:!0,title:A(`newSession.catalogUnavailable`),onSelect:()=>void 0},m):L}
            ${!c&&l.length===0&&u.length===0&&!d&&!h&&!g?I`<div class="new-session-page__environment-empty" role="status">
                    ${A(`newSession.environmentSearchEmpty`)}
                  </div>`:L}
          </div>
        </div>
      </div>
    </wa-popover>
  `}var Ru,zu;function Bu(){return(Bu=e((()=>{hr(),R(),Bt(),qt(),Du(),mt(),F(),vr(),Vr(),M(),H(),Nu(),bn(),es(),cc(),Go(),nc(),U(),Ru=N(B`<rect x="2" y="7" width="14" height="11" />
  <path d="M6 7V3h16v12h-6M6 22h6M9 18v4" />`),zu=N(B`<circle cx="12" cy="12" r="9" />
  <path d="M12 8v8M8 12h8" />`)})))()}function Vu(e){let t=g(e.agentId);return I`
    <span class="new-session-page__select new-session-page__select--agent">
      <openclaw-agent-select
        .variant=${e.variant??`compact`}
        .options=${e.agents.map(t=>({value:g(t.id),label:ve(t,e.agentIdentity?.get(t.id)),agent:t}))}
        .identityById=${Object.fromEntries(e.agents.flatMap(t=>{let n=e.agentIdentity?.get(t.id);return n?[[t.id,n]]:[]}))}
        .value=${t}
        .accessibleLabel=${A(`newSession.agent`)}
        .menuLabel=${A(`newSession.agents`)}
        .disabled=${e.disabled}
        .onSelect=${e.onSelect}
        @wa-show=${()=>e.onOpenChange(!0)}
        @wa-hide=${()=>e.onOpenChange(!1)}
      ></openclaw-agent-select>
    </span>
  `}function Hu({idPrefix:e,context:t,data:n,gateway:r,place:i,submitting:a,pendingPlacement:o,onConnectMachine:s,onNavigate:c,onFocusComposer:l,requestUpdate:u}){let d=i.browser,{machineClass:f,os:p}=i.cloudSelection,m=K(n),h=m||!i.isAdmin()?[]:r.cloudProfiles,g=i.repository.kind===`git`?i.repository:null,_=m?[]:d.projects,v=m?[]:d.resolveProjectRecents({sessions:t?.sessions.state.result?.sessions??[],workspace:i.workspacePath(),workspaceRoots:i.knownWorkspaceRoots(),isAdmin:i.isAdmin()}),y=Pu({environments:i.canWrite()?r.environments:[],cloudProfiles:h,cloudProfileId:i.cloudProfileId,machineClass:f,os:p,deviceId:i.deviceId,autoDevice:i.autoDevice,devicePlacement:i.devicePlacementRuntime()?.devicePlacement,deviceDisabledReason:i.modelControl.devicePlacementUnsupportedReason()??r.deviceCatalogDisabledReason}),b=Gs({folder:i.folder,workspace:i.workspacePath(),projectId:d.projectId,selectedRemoteProject:d.remoteProject,projects:_,recents:v,projectQuery:d.projectQuery,freshWorkspace:i.freshWorkspace}),x=xu({destination:i.cloudProfileId?`cloud`:i.remotePlacement?`remote`:`local`,worktree:i.worktree,worktreeAvailable:i.worktreeAvailable(),worktreeName:i.worktreeName,headBranch:g?.headBranch,baseRef:i.baseRef,repository:!!i.remoteRepository}),S=r.gatewayName?A(`newSession.gatewayNamed`,{name:r.gatewayName}):A(`newSession.gateway`);return I`${m?Xl({hosts:n?.terminalHosts,hostId:i.terminalHostId,submitting:a,onSelect:e=>i.selectTerminalHost(e)}):Lu({idPrefix:e,state:y,environmentQuery:d.environmentQuery,onEnvironmentQueryInput:e=>d.changeEnvironmentQuery(e),gatewayName:r.gatewayName,cloudProfileId:i.cloudProfileId,machineClass:f,os:p,deviceId:i.deviceId,autoDevice:i.autoDevice,autoPlacementMode:i.modelControl.autoPlacementSelectionMode(),cloudDisabledReason:i.modelControl.cloudRuntimeUnsupportedReason(),cloudProfileDisabledReason:e=>i.modelControl.cloudRuntimeUnsupportedReason(e),submitting:a,pendingPlacement:o,catalogLoading:i.canWrite()&&r.cloudProfilesPending,isAdmin:i.isAdmin(),...d.popoverCallbacks(`where`),onSelectDevice:e=>i.selectDevice(e),onSelectAutoDevice:()=>i.selectDevice(``,!0),onSelectCloudProfile:(e,t)=>{t&&i.cloudMachines.applyPending(e),i.selectCloudProfile(e)},onSelectCloudOs:e=>i.cloudMachines.selectOs(i.cloudProfileId,e,h,a||o,u),onSelectCloudMachine:e=>i.cloudMachines.select(i.cloudProfileId,e,h,a||o,u),onConnectMachine:s,onManageCloudWorkers:()=>{d.close(),c(`cloud-workers`)}})}${m&&i.terminalOnNode?I`<label class="new-session-page__select new-session-page__menu-field"
          ><span>${A(`newSession.terminalNodeFolder`)}</span
          ><input
            aria-label=${A(`newSession.terminalNodeFolder`)}
            .value=${i.folder}
            ?disabled=${a}
            @input=${e=>{e.currentTarget instanceof HTMLInputElement&&i.applyFolder(e.currentTarget.value)}}
        /></label>`:Ks({idPrefix:e,state:b,browseAvailable:i.browseAvailable(),isAdmin:i.isAdmin(),canWrite:i.canWrite(),folder:i.folder,workspace:i.workspacePath(),projects:_,projectQuery:d.projectQuery,projectSearchAvailable:!m&&rn(t?.gateway.snapshot,`projects.searchRemote`,`operator.read`),projectAddAvailable:!m&&rn(t?.gateway.snapshot,i.remotePlacement?`sessions.create`:`projects.add`,`operator.write`),remoteProjects:d.projectSearchResult?.projects??[],selectedRemoteProject:d.remoteProject,projectSearchCredentialMissing:d.projectSearchResult?.credential===`missing`,projectSearchLoading:d.projectSearchLoading,projectSearchError:d.projectSearchError,projectId:d.projectId,freshWorkspace:i.freshWorkspace,onNewWorkspace:i.remotePlacement?()=>i.selectNewWorkspace():void 0,gatewayLabel:S,submitting:a,pendingPlacement:o,...d.popoverCallbacks(`project`),browserOpen:d.browserOpen,browser:d.browser,registerProjectPath:d.browserProjectPath,registeringProject:d.browserRegistering,onSelectProject:e=>i.selectProjectId(e),onProjectQueryInput:e=>d.changeProjectQuery(e),onSelectRemoteProject:e=>i.selectRemoteProject(e),onApplyFolder:e=>i.applyFolder(e),onBrowse:()=>d.selectGatewayBrowser(i.folder.trim()||i.workspacePath()),onBrowserBack:()=>d.showRoot(),onRegisterProject:e=>void d.registerBrowserProject(e),onClose:()=>d.close()})}${x&&!i.freshWorkspace&&!(m&&i.terminalOnNode)?Cu({idPrefix:e,state:x,remotePlacement:i.remotePlacement,repository:!!i.remoteRepository,folderLabel:b.label,worktree:i.worktree,worktreeAvailable:i.worktreeAvailable(),repositoryUnavailable:i.repository.kind===`unavailable`,branches:g,branchesLoading:i.repository.kind===`checking`,baseRef:i.baseRef,worktreeName:i.worktreeName,submitting:a,pendingPlacement:o,...d.popoverCallbacks(`checkout`),onSelectWorktree:e=>i.selectWorktree(e),onBaseRefInput:e=>i.setBaseRef(e),onWorktreeNameInput:e=>i.setWorktreeName(e),onConfirm:l}):L}`}function Uu(){return(Uu=e((()=>{R(),M(),H(),Se(),on(),j(),q(),Tu(),Za(),qs(),Zl(),Bu(),U()})))()}function Wu(e){let t=`${e.getFullYear()}-${e.getMonth()+1}-${e.getDate()}`,n=2166136261;for(let e=0;e<t.length;e++)n^=t.charCodeAt(e),n=Math.imul(n,16777619);return n>>>0}function Gu(e){return Wu(e)%16==3}function Ku(){try{let e=k()?.getItem(id),t=e?JSON.parse(e):{},n=new Map;if(Array.isArray(t)){for(let e of t)typeof e==`string`&&e&&n.set(e,{firstSeenAt:null,name:null,shinySeenAt:null});return n}if(t&&typeof t==`object`)for(let[e,r]of Object.entries(t))e&&n.set(e,{firstSeenAt:typeof r?.firstSeenAt==`number`?r.firstSeenAt:null,name:typeof r?.name==`string`&&r.name?r.name:null,shinySeenAt:typeof r?.shinySeenAt==`number`?r.shinySeenAt:null});return n}catch{return new Map}}function qu(e){let t={};for(let[n,r]of[...e.entries()].toSorted(([e],[t])=>e.localeCompare(t)))t[n]={...r.firstSeenAt===null?{}:{firstSeenAt:r.firstSeenAt},...r.name===null?{}:{name:r.name},...r.shinySeenAt===null?{}:{shinySeenAt:r.shinySeenAt}};k()?.setItem(id,JSON.stringify(t))}function Ju(){return new Set(Ku().keys())}function Yu(){return Ku()}function Xu(e,t={}){try{let n=Ku(),r=n.get(e);if(r){let e=t.shiny===!0&&r.shinySeenAt===null;if(r.firstSeenAt!==null&&r.name!==null&&!e)return}n.set(e,{firstSeenAt:r?.firstSeenAt??Date.now(),name:r?.name??t.name??null,shinySeenAt:r?.shinySeenAt??(t.shiny===!0?Date.now():null)}),qu(n)}catch{}}function Zu(){try{let e=k()?.getItem(ad),t=e?JSON.parse(e):{},n=t&&typeof t==`object`?t:{};return{visits:typeof n.visits==`number`&&n.visits>=0?n.visits:0,shoos:typeof n.shoos==`number`&&n.shoos>=0?n.shoos:0}}catch{return{visits:0,shoos:0}}}function Qu(e){try{k()?.setItem(ad,JSON.stringify(e))}catch{}}function $u(){let e=Zu();Qu({...e,visits:e.visits+1})}function ed(){let e=Zu();Qu({...e,shoos:e.shoos+1})}function td(){let{visits:e,shoos:t}=Zu();return{tier:e<3?`shy`:e<15?`regular`:`friend`,wary:t>=3&&t>e*.3,visits:e,shoos:t}}function nd(e){return sd.find(([t])=>e>=t)?.[1]??null}function rd(e,t){if(e===null||t.getTime()-e<cd)return!1;let n=new Date(e);return n.getMonth()===t.getMonth()&&n.getDate()===t.getDate()}var id,ad,od,sd,cd;function ld(){return(ld=e((()=>{id=`openclaw.control.lobsterdex.v1`,ad=`openclaw.control.lobsterpet.familiarity.v1`,od={shy:{stayMul:.6,firstDelayMul:1.3,gapMul:1},regular:{stayMul:1,firstDelayMul:1,gapMul:1},friend:{stayMul:1.6,firstDelayMul:.7,gapMul:.8},waryGapMul:1.7},sd=[[250,`Elder`],[100,`Captain`],[50,`Sir`]],cd=2592e7})))()}function ud(e){return(se(e)^pd)>>>0}function dd(e){let t=null;for(let n of e??[]){if(!n.status||n.status===`running`)continue;let e=n.endedAt??n.lastActivityAt??n.updatedAt??0;(!t||e>t.at)&&(t={at:e,outcome:n.status===`failed`||n.status===`timeout`?`error`:n.status===`killed`?`aborted`:`ok`})}return t?.outcome??`ok`}function fd(e,t){return e?t?.some(w)?`busy`:`idle`:`offline`}var pd;function md(){return(md=e((()=>{pd=Math.trunc(Math.random()*4294967295)})))()}function hd(e){let t=e.position;return t?I`
    <wa-dropdown
      class="session-menu lobster-pet-dismiss-menu"
      .open=${!0}
      placement="top-start"
      .distance=${0}
      aria-label=${A(`quickSettings.appearance.lobsterVisits`)}
      @wa-select=${t=>{t.preventDefault(),t.detail.item.value===`dismiss`?e.onDismiss(!1):t.detail.item.value===`dismiss-permanently`&&e.onDismiss(!0)}}
      @wa-after-hide=${e.onClose}
    >
      <button
        slot="trigger"
        type="button"
        tabindex="-1"
        aria-hidden="true"
        aria-label=${A(`quickSettings.appearance.lobsterVisits`)}
        style="position: fixed; left: ${t.x}px; top: ${t.y}px; width: 1px; height: 1px; opacity: 0; pointer-events: none;"
      ></button>
      <wa-dropdown-item class="session-menu__item" value="dismiss"
        >${A(`common.dismiss`)}</wa-dropdown-item
      >
      <wa-dropdown-item class="session-menu__item" value="dismiss-permanently"
        >${A(`common.dismissAndDontShowAgain`)}</wa-dropdown-item
      >
    </wa-dropdown>
  `:L}function gd(){return(gd=e((()=>{R(),M(),Tr()})))()}function _d(e,t,n){let r=e;if(!t)return r;try{let e=window.AudioContext;if(!e)return r;r??=new e,r.state===`suspended`&&r.resume();let t=r.currentTime,i=r.createOscillator(),a=r.createGain();i.type=`sine`,n===`poke`?(i.frequency.setValueAtTime(330,t),i.frequency.exponentialRampToValueAtTime(165,t+.09)):(i.frequency.setValueAtTime(392,t),i.frequency.exponentialRampToValueAtTime(523,t+.18)),a.gain.setValueAtTime(1e-4,t),a.gain.exponentialRampToValueAtTime(.05,t+.02),a.gain.exponentialRampToValueAtTime(1e-4,t+(n===`poke`?.12:.24)),i.connect(a).connect(r.destination),i.start(t),i.stop(t+.26)}catch{}return r}function vd(){let e=_d(null,!0,`poke`);e&&window.setTimeout(()=>void e.close().catch(()=>{}),300)}function yd(){return(yd=e((()=>{})))()}function bd(e){return Sd[e]??e}function xd(e){return h(Cd[(e>>>3)%Cd.length],`lobster pet name catalog entry`)}var Sd,Cd,wd;function Td(){return(Td=e((()=>{T(),Sd={blue:`Blueberry`,gold:`Goldie`,lumen:`Glimmer`,magma:`Ember`,oilslick:`Slick`,aurora:`Borealis`,nebula:`Cosmo`,banana:`Peel`,mood:`Ringo`,bee:`Buzz`,rubberduck:`Debuggy`,watermelon:`Pips`,clawtron:`Clawtron`,selene:`Selene`,geode:`Amethyst`,ghost:`Boo`,glass:`Prism`,split:`Picasso`,sourdough:`Boule`,zombie:`Shambles`,plush:`Buttons`,balloon:`Squeaky`,cottoncandy:`Taffy`,cryptid:`Nessie`,flatpack:`Skaldjur`,tinfoil:`Mulder`,actual:`Homarus`,disco:`Boogie`,chimera:`Frankie`,blueprint:`Prototype`,phosphor:`TTY`,ascii:`Figlet`,portal:`Warp`,notexture:`Magenta`,loading:`Spinner`,eclipse:`Umbra`,heisenbug:`Segfault`,invisible:`Nobody`,pixel:`Sprite`,retro:`OG`,goldenretro:`24K`},Cd=[`Pinchy`,`Barnaby`,`Thermidor`,`Clawdette`,`Sheldon`,`Scuttles`,`Bisque`,`Crusty`,`Snips`,`Bubbles`,`Clawdia`,`Ferdinand`,`Maple`,`Pearl`,`Biscuit`,`Captain`,`Ziggy`,`Noodle`,`Waffles`,`Pippin`,`Squirt`,`Chip`,`Clementine`,`Moss`],wd={crimson:{flavor:`The classic red, first in every tide pool.`,hint:`Where every story starts.`},blue:{flavor:`1 in 2 million, and knows it.`,hint:`One in two million.`},gold:{flavor:`1 in 30 million karats.`,hint:`Worth its weight.`},lumen:{flavor:`Brings its own night lights.`,hint:`Glows where it's darkest.`},magma:{flavor:`Fresh from the vent, still cooling.`,hint:`Runs hot.`},oilslick:{flavor:`Black shell, rainbow finish.`,hint:`Spilled, not stirred.`},aurora:{flavor:`Northern lights, southern claws.`,hint:`Best seen on clear nights.`},nebula:{flavor:`Not from any ocean on this planet.`,hint:`Came from very far away.`},banana:{flavor:`Banana. For scale.`,hint:`For scale.`},mood:{flavor:`Wears whatever color you're feeling.`,hint:`Matches your vibe.`},bee:{flavor:`Technically not a bee.`,hint:`Do not tell the bees.`},rubberduck:{flavor:`Listens to your bugs. Judges silently.`,hint:`Quack.`},watermelon:{flavor:`Contains 6% lobster.`,hint:`Ripe when thumped.`},clawtron:{flavor:`60% rivets, 40% love.`,hint:`Beep boop snip.`},selene:{flavor:`Carries the current moon on its belly.`,hint:`Waxes and wanes.`},geode:{flavor:`Rock outside, amethyst inside.`,hint:`Crack the surface.`},ghost:{flavor:`1 in 100 million, barely there.`,hint:`You'd walk right past it.`},glass:{flavor:`Fully transparent. Nothing to hide.`,hint:`Easy to miss, hard to forget.`},split:{flavor:`Two lobsters, one shell.`,hint:`Can't pick a side.`},sourdough:{flavor:`Started from a starter. 24-hour proof.`,hint:`Still proofing.`},zombie:{flavor:`Slightly used. Still friendly.`,hint:`It's been better.`},plush:{flavor:`Machine washable. Air dry only.`,hint:`Soft to the touch.`},balloon:{flavor:`Do not pop.`,hint:`Handle with care.`},cottoncandy:{flavor:`Pastel, like the famous Maine catch.`,hint:`Sweeter than it looks.`},cryptid:{flavor:`Every photo comes out blurry.`,hint:`Sightings unconfirmed.`},flatpack:{flavor:`Some assembly required.`,hint:`Missing one screw.`},tinfoil:{flavor:`The tide is a psyop.`,hint:`They know.`},actual:{flavor:`An actual lobster. Unsettling, honestly.`,hint:`Anatomically correct.`},disco:{flavor:`Born under a mirror ball.`,hint:`The night is still young.`},chimera:{flavor:`Borrowed parts. No refunds.`,hint:`Something's off.`},blueprint:{flavor:`Final hardware pending approval.`,hint:`Still on the drawing board.`},phosphor:{flavor:`80 columns, 24 rows, one lobster.`,hint:`Hums at sixty hertz.`},ascii:{flavor:`Renders anywhere. Even over SSH.`,hint:`chmod +x`},portal:{flavor:`Arrives before it leaves.`,hint:`Mind the gap.`},notexture:{flavor:`Texture not found.`,hint:`404.`},loading:{flavor:`Still loading. Any second now.`,hint:`…`},eclipse:{flavor:`Do not look directly at it.`,hint:`Once in a blue moon.`},heisenbug:{flavor:`Only renders right when nobody's watching.`,hint:`Cannot be reproduced.`},invisible:{flavor:`It's right there. Look closer.`,hint:`Trust me, it exists.`},pixel:{flavor:`Rendered in 1987. Still runs.`,hint:`Insert coin.`},retro:{flavor:`The original: big claw, no apologies.`,hint:`The one that started it all.`},goldenretro:{flavor:`One in a generation.`,hint:`Worth the wait.`}}})))()}function Ed(e){return((e.getTime()-Od)/864e5%Dd+Dd)%Dd/Dd}var Dd,Od;function kd(){return(kd=e((()=>{Dd=29.53059,Od=Date.parse(`2000-01-06T18:14:00.000Z`)})))()}var Ad,jd;function Md(){return(Md=e((()=>{Ad=[[{id:`crimson`,shell:`#ff4f40`,claw:`#ff775f`},26],[{id:`blue`,shell:`#4a7dfc`,claw:`#7fa4ff`},7],[{id:`gold`,shell:`#f4b840`,claw:`#f9d47a`},5],[{id:`lumen`,shell:`#1d2f4e`,claw:`#2e4a77`},2],[{id:`magma`,shell:`#241214`,claw:`#3a1d18`},2],[{id:`oilslick`,shell:`#15171d`,claw:`#23262e`},2],[{id:`aurora`,shell:`#dce6f0`,claw:`#e9f0f7`},2],[{id:`nebula`,shell:`#34255c`,claw:`#4a3a7d`},2],[{id:`banana`,shell:`#f7e27d`,claw:`#f3d55b`},2],[{id:`mood`,shell:`var(--accent, #7f77dd)`,claw:`var(--accent-hover, #9a93e8)`},1.5],[{id:`bee`,shell:`#f4c531`,claw:`#2b2b23`},1.5],[{id:`rubberduck`,shell:`#ffd93b`,claw:`#ffb03b`},1.5],[{id:`watermelon`,shell:`#3f9d63`,claw:`#4fb072`},1.5],[{id:`clawtron`,shell:`#8d99a6`,claw:`#a2aeba`},1],[{id:`selene`,shell:`#c9ced8`,claw:`#d8dde5`},1],[{id:`geode`,shell:`#6b6474`,claw:`#7d7588`},1],[{id:`ghost`,shell:`#dce8f2`,claw:`#ecf3fa`},1],[{id:`glass`,shell:`#cfe4f4`,claw:`#e0eef8`},1],[{id:`split`,shell:`#ff4f40`,claw:`#ff775f`},1],[{id:`sourdough`,shell:`#d9a662`,claw:`#e6bc82`},1],[{id:`zombie`,shell:`#9db08a`,claw:`#86a17a`},1],[{id:`plush`,shell:`#e8967a`,claw:`#f2b09a`},1],[{id:`balloon`,shell:`#ff5c8a`,claw:`#ff7ea1`},1],[{id:`cryptid`,shell:`#6e6257`,claw:`#7d7263`},.9],[{id:`flatpack`,shell:`#d9c9a8`,claw:`#d9c9a8`},.9],[{id:`tinfoil`,shell:`#9aa4ad`,claw:`#a8b2bb`},.9],[{id:`actual`,shell:`#a63c28`,claw:`#8f3220`},.9],[{id:`cottoncandy`,shell:`#f6a8c9`,claw:`#a5c6f0`},.8],[{id:`disco`,shell:`#b8c4d8`,claw:`#cbd5e6`},.8],[{id:`chimera`,shell:`#b0685a`,claw:`#b0685a`},.75],[{id:`pixel`,shell:`#d84c3e`,claw:`#ef8f6a`},.7],[{id:`blueprint`,shell:`#123a66`,claw:`#123a66`},.7],[{id:`phosphor`,shell:`#0d2415`,claw:`#0f2b19`},.7],[{id:`ascii`,shell:`var(--lob-ascii-ink, #d8dee6)`,claw:`var(--lob-ascii-ink, #d8dee6)`},.7],[{id:`portal`,shell:`#4a9df8`,claw:`#ff9a2e`},.7],[{id:`notexture`,shell:`#ff00dc`,claw:`#111111`},.65],[{id:`loading`,shell:`#3a4150`,claw:`#454d5e`},.65],[{id:`eclipse`,shell:`#14161d`,claw:`#1d2026`},.65],[{id:`heisenbug`,shell:`#262a33`,claw:`#343945`},.6],[{id:`invisible`,shell:`rgba(127,140,160,0.07)`,claw:`rgba(127,140,160,0.07)`},.55],[{id:`retro`,shell:`#e8262c`,claw:`#f04a3e`},.5],[{id:`goldenretro`,shell:`#e8b422`,claw:`#f6cf5a`},.1]],jd=Ad.map(([e])=>e)})))()}function Nd(e,t){return B`
    <g class="lob-flatpack">
      <path
        d="M48 10 C28 10 17 25 17 41 C17 58 29 69 48 69 C67 69 79 58 79 41 C79 25 68 10 48 10 Z"
        fill="var(--lob-shell)"
        stroke="#8a7c5f"
        stroke-width="2"
        stroke-dasharray="4 3"
      />
      <g class="lob-eye-open" style=${e}>
        <circle cx="39" cy="34" r="4.5" fill="#0a1014" />
        <circle cx="57" cy="34" r="4.5" fill="#0a1014" />
        <circle cx="40.2" cy="32.8" r="1.7" fill="var(--lob-glint, #00e5cc)" />
        <circle cx="58.2" cy="32.8" r="1.7" fill="var(--lob-glint, #00e5cc)" />
      </g>
      <g
        class="lob-eye-closed"
        stroke="#0a1014"
        stroke-width="2.5"
        stroke-linecap="round"
        fill="none"
        style=${t}
      >
        <path d="M34 35 Q39 31 44 35" />
        <path d="M52 35 Q57 31 62 35" />
      </g>

      <g fill="none" stroke="#8a7c5f" stroke-width="1.5" stroke-dasharray="4 3">
        <path d="M27 48 Q50 58 75 61" />
        <path d="M68 47 Q79 58 92 70" />
      </g>
      <g class="lob-claw lob-claw--l">
        <path
          d="M76 53 C66 50 62 58 67 65 C72 72 82 68 85 60 C87 55 82 53 76 53 Z"
          fill="var(--lob-claw)"
          stroke="#8a7c5f"
          stroke-width="1.5"
          stroke-dasharray="4 3"
        />
      </g>
      <g class="lob-claw lob-claw--r">
        <path
          d="M98 65 C109 62 115 70 111 79 C107 88 96 84 91 76 C88 70 92 66 98 65 Z"
          fill="var(--lob-claw)"
          stroke="#8a7c5f"
          stroke-width="1.5"
          stroke-dasharray="4 3"
        />
      </g>

      <g fill="var(--lob-shell)" stroke="#8a7c5f" stroke-width="1.5" stroke-dasharray="4 3">
        <rect x="15" y="88" width="15" height="6" rx="2" />
        <rect x="34" y="88" width="15" height="6" rx="2" />
        <rect x="53" y="88" width="15" height="6" rx="2" />
        <rect x="72" y="88" width="15" height="6" rx="2" />
      </g>

      <g fill="none" stroke="#5f5648" stroke-width="3" stroke-linecap="round">
        <path d="M84 24 L101 8" />
        <path d="M93 31 L113 14" />
      </g>
      <g fill="#8a7c5f">
        <circle cx="105" cy="29" r="3" />
        <circle cx="113" cy="35" r="3" />
      </g>
      <path
        class="lob-flatpack__allen-key"
        d="M101 84 L101 99 L115 99"
        fill="none"
        stroke="#5f5648"
        stroke-width="3"
        stroke-linecap="round"
        stroke-linejoin="round"
      />
    </g>
  `}function Pd(e,t){return B`
    <!-- Skeleton placeholders stay neutral instead of inheriting palette colors. -->
    <g class="lob-skeleton">
      <rect class="lob-skeleton__block" style="--i:0" x="24" y="18" width="72" height="64" rx="10" fill="#2f3542" />
      <rect class="lob-skeleton__block" style="--i:1" x="2" y="43" width="24" height="20" rx="8" fill="#39404f" />
      <rect class="lob-skeleton__block" style="--i:2" x="94" y="43" width="24" height="20" rx="8" fill="#39404f" />
      <path class="lob-skeleton__block" style="--i:3" d="M45 21 L34 7" stroke="#39404f" stroke-width="6" stroke-linecap="round" />
      <path class="lob-skeleton__block" style="--i:4" d="M75 21 L86 7" stroke="#39404f" stroke-width="6" stroke-linecap="round" />
      <rect class="lob-skeleton__block" style="--i:5" x="31" y="79" width="10" height="22" rx="4" fill="#2f3542" />
      <rect class="lob-skeleton__block" style="--i:6" x="46" y="79" width="10" height="24" rx="4" fill="#39404f" />
      <rect class="lob-skeleton__block" style="--i:7" x="64" y="79" width="10" height="24" rx="4" fill="#39404f" />
      <rect class="lob-skeleton__block" style="--i:8" x="79" y="79" width="10" height="22" rx="4" fill="#2f3542" />
      <g class="lob-eye-open" style=${e}>
        <circle cx="47" cy="43" r="5" fill="#4a5364" />
        <circle cx="73" cy="43" r="5" fill="#4a5364" />
      </g>
      <g class="lob-eye-closed" style=${t} fill="#4a5364">
        <rect x="41" y="42" width="12" height="3" rx="1.5" />
        <rect x="67" y="42" width="12" height="3" rx="1.5" />
      </g>
    </g>
  `}function Fd(e,t){return B`
    <g class="lob-actual">
      <g fill="none" stroke="#6f281d" stroke-linecap="round">
        <path d="M47 27 Q27 5 2 3" stroke-width="2" />
        <path d="M73 27 Q93 5 118 3" stroke-width="2" />
        <path d="M46 29 Q34 16 22 13" stroke-width="1.3" />
        <path d="M74 29 Q86 16 98 13" stroke-width="1.3" />
      </g>

      <g fill="none" stroke="#7f3022" stroke-width="2.2" stroke-linecap="round">
        <path d="M39 48 Q22 52 10 65" />
        <path d="M38 56 Q20 62 8 77" />
        <path d="M40 65 Q24 72 15 88" />
        <path d="M43 74 Q31 82 27 97" />
        <path d="M81 48 Q98 52 110 65" />
        <path d="M82 56 Q100 62 112 77" />
        <path d="M80 65 Q96 72 105 88" />
        <path d="M77 74 Q89 82 93 97" />
      </g>

      <g class="lob-actual__tail" fill="#8f3220" stroke="#6f281d" stroke-width="1.4">
        <path d="M48 88 Q38 91 31 103 Q44 103 55 96 Z" />
        <path d="M72 88 Q82 91 89 103 Q76 103 65 96 Z" />
        <path d="M54 89 Q60 96 66 89 L69 104 Q60 101 51 104 Z" />
      </g>

      <g class="lob-claw lob-claw--l">
        <path
          d="M34 43 Q25 31 12 33 Q0 35 2 48 Q4 61 17 63 Q28 64 35 54 L30 49 Q22 54 15 50 Q10 47 13 42 Q17 37 24 42 Z"
          fill="var(--lob-claw)"
          stroke="#6f281d"
          stroke-width="1.5"
        />
      </g>
      <g class="lob-claw lob-claw--r">
        <path
          d="M86 44 Q94 32 104 34 Q113 35 116 42 L107 45 L118 49 Q115 58 105 60 Q96 61 87 53 Z"
          fill="var(--lob-claw)"
          stroke="#6f281d"
          stroke-width="1.5"
        />
      </g>

      <path
        class="lob-actual__carapace"
        d="M60 20 Q38 20 34 38 Q32 50 41 58 Q49 64 60 64 Q71 64 79 58 Q88 50 86 38 Q82 20 60 20 Z"
        fill="var(--lob-shell)"
        stroke="#6f281d"
        stroke-width="1.8"
      />
      <g class="lob-actual__abdomen" stroke="#6f281d" stroke-width="1.4">
        <path d="M39 54 Q60 62 81 54 L79 65 Q60 72 41 65 Z" fill="#b34b35" />
        <path d="M41 65 Q60 72 79 65 L76 76 Q60 82 44 76 Z" fill="#a63c28" />
        <path d="M44 76 Q60 82 76 76 L72 87 Q60 92 48 87 Z" fill="#b34b35" />
        <path d="M48 87 Q60 92 72 87 L67 96 Q60 99 53 96 Z" fill="#a63c28" />
      </g>
      <path d="M48 42 Q60 48 72 42 Q69 56 60 58 Q51 56 48 42 Z" fill="#bd6044" opacity="0.72" />

      <g fill="none" stroke="#6f281d" stroke-width="2.2" stroke-linecap="round">
        <path d="M47 28 L45 23" />
        <path d="M73 28 L75 23" />
      </g>
      <g class="lob-eye-open" style=${e}>
        <circle cx="45" cy="22" r="3.5" fill="#17100e" />
        <circle cx="75" cy="22" r="3.5" fill="#17100e" />
        <circle cx="46" cy="21" r="1" fill="#f2c6a8" />
        <circle cx="76" cy="21" r="1" fill="#f2c6a8" />
      </g>
      <g class="lob-eye-closed" style=${t} fill="none" stroke="#17100e" stroke-width="2" stroke-linecap="round">
        <path d="M41.5 22 H48.5" />
        <path d="M71.5 22 H78.5" />
      </g>
    </g>
  `}function Id(e,t){return B`
    <g class="lob-balloon">
      <g fill="none" stroke="var(--lob-shell)" stroke-width="4" stroke-linecap="round">
        <path d="M48 13 Q45 5 42 3" />
        <path d="M72 13 Q75 5 78 3" />
      </g>

      <g class="lob-claw lob-claw--l" fill="var(--lob-claw)">
        <ellipse cx="29" cy="29" rx="9" ry="7" transform="rotate(-20 29 29)" />
        <ellipse cx="20" cy="35" rx="8" ry="6" transform="rotate(18 20 35)" />
      </g>
      <g class="lob-claw lob-claw--r" fill="var(--lob-claw)">
        <ellipse cx="91" cy="29" rx="9" ry="7" transform="rotate(20 91 29)" />
        <ellipse cx="100" cy="35" rx="8" ry="6" transform="rotate(-18 100 35)" />
      </g>

      <ellipse cx="60" cy="29" rx="24" ry="19" fill="var(--lob-shell)" />
      <circle cx="60" cy="48" r="4" fill="#d94b72" />
      <ellipse cx="60" cy="61" rx="18" ry="14" fill="var(--lob-shell)" />
      <circle cx="60" cy="75" r="3.5" fill="#d94b72" />
      <ellipse cx="60" cy="86" rx="13" ry="10" fill="var(--lob-shell)" />

      <g fill="#ffffff" opacity="0.55">
        <ellipse cx="50" cy="22" rx="4" ry="10" transform="rotate(35 50 22)" />
        <ellipse cx="52" cy="56" rx="3" ry="7" transform="rotate(32 52 56)" />
        <ellipse cx="54" cy="82" rx="2.4" ry="5" transform="rotate(28 54 82)" />
      </g>

      <g class="lob-eye-open" style=${e}>
        <circle cx="50" cy="30" r="4.5" fill="#0a1014" />
        <circle cx="70" cy="30" r="4.5" fill="#0a1014" />
        <circle cx="51.3" cy="28.7" r="1.8" fill="var(--lob-glint, #00e5cc)" />
        <circle cx="71.3" cy="28.7" r="1.8" fill="var(--lob-glint, #00e5cc)" />
      </g>
      <g
        class="lob-eye-closed"
        style=${t}
        fill="none"
        stroke="#0a1014"
        stroke-width="2.5"
        stroke-linecap="round"
      >
        <path d="M45 31 Q50 27 55 31" />
        <path d="M65 31 Q70 27 75 31" />
      </g>

      <path d="M55 96 L60 91 L65 96 L60 101 Z" fill="#d94b72" />
      <path
        d="M60 100 Q67 102 62 105 Q57 108 65 111"
        fill="none"
        stroke="#c9d2da"
        stroke-width="1.2"
        stroke-linecap="round"
      />
    </g>
  `}function Ld(e,t){return B`
    <!-- Like pet names and lore, terminal glyph art is an English-only easter-egg channel. -->
    <g
      class="lob-ascii"
      fill="var(--lob-shell)"
      font-family="ui-monospace, SFMono-Regular, Menlo, monospace"
      font-size="11"
      text-anchor="middle"
      xml:space="preserve"
    >
      <text x="60" y="17">\\ /         \\ /</text>
      <text x="60" y="31">{  \\_______/  }</text>
      <g class="lob-eye-open" style=${e}>
        <text x="60" y="45">(o)     (o)</text>
      </g>
      <g class="lob-eye-closed" style=${t}>
        <text x="60" y="45">(-)     (-)</text>
      </g>
      <text x="60" y="59">(    '---'    )</text>
      <text x="60" y="73"> \\   _____   /</text>
      <text x="60" y="87">  (_________)</text>
      <text x="60" y="101">    | | | |</text>
    </g>
  `}function Rd(e,t){return B`
    <g class="lob-portal">
      <ellipse
        class="lob-portal-ring lob-portal-ring--blue"
        cx="30"
        cy="50"
        rx="14"
        ry="30"
        fill="#0d1b33"
        fill-opacity="0.85"
        stroke="currentColor"
        stroke-width="3"
        transform="rotate(-12 30 50)"
      />

      <!-- Fixed lobster red preserves the split-body gag while shell/claw vars carry portal identity. -->
      <path d="M31 30 Q45 20 56 30 Q62 39 60 53 Q58 64 47 70 L31 67 Z" fill="#b0432f" />
      <g class="lob-claw lob-claw--l">
        <path
          d="M52 54 Q58 48 63 51 Q67 56 63 62 Q58 67 52 63 Z"
          fill="#b0432f"
        />
      </g>
      <g fill="none" stroke="#b0432f" stroke-width="2" stroke-linecap="round">
        <path d="M42 31 Q43 16 50 7" />
        <path d="M52 28 Q58 14 66 9" />
      </g>
      <g class="lob-eye-open" style=${e}>
        <circle cx="45" cy="39" r="4" fill="#0a1014" />
        <circle cx="57" cy="37" r="4" fill="#0a1014" />
        <circle cx="46" cy="38" r="1.5" fill="var(--lob-glint, #00e5cc)" />
        <circle cx="58" cy="36" r="1.5" fill="var(--lob-glint, #00e5cc)" />
      </g>
      <g
        class="lob-eye-closed"
        style=${t}
        fill="none"
        stroke="#0a1014"
        stroke-width="2.2"
        stroke-linecap="round"
      >
        <path d="M41 40 Q45 37 49 40" />
        <path d="M53 38 Q57 35 61 38" />
      </g>

      <g class="lob-portal-rear" fill="#b0432f">
        <path d="M91 44 Q82 40 75 44 L82 51 L74 56 L82 61 L75 68 Q83 70 92 64 Z" />
        <path d="M88 52 Q82 49 78 45" fill="none" stroke="#7f3022" stroke-width="2" />
        <path d="M88 61 Q82 64 78 69" fill="none" stroke="#7f3022" stroke-width="2" />
      </g>
      <ellipse
        class="lob-portal-ring lob-portal-ring--orange"
        cx="92"
        cy="58"
        rx="14"
        ry="30"
        fill="#0d1b33"
        fill-opacity="0.85"
        stroke="currentColor"
        stroke-width="3"
        transform="rotate(10 92 58)"
      />
    </g>
  `}function zd(e){return B`
    <g class="lob-tinfoil" fill="none" stroke="#c9d2da" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
      <path d="M27 31 L38 27 L45 34 L55 25 L64 33 L75 26 L91 34" />
      <path d="M20 51 L31 45 L43 54 L55 45 L68 54 L82 44 L100 53" />
      <path d="M23 70 L36 64 L47 73 L60 63 L74 72 L90 65 L98 72" />
      <path d="M35 86 L46 80 L58 87 L70 79 L84 85" />
    </g>
    ${e?B`
          <g class="lob-tinfoil-hat">
            <path d="M43 14 L57 0 L78 15 L60 11 Z" fill="#c0c9d1" />
            <path d="M57 0 L60 11 L78 15" fill="none" stroke="#7f8992" stroke-width="1.5" />
            <path d="M43 14 L60 11 L53 5" fill="none" stroke="#9aa4ad" stroke-width="1.5" />
          </g>
        `:``}
  `}var Bd,Vd,Hd,Ud,Wd;function Gd(){return(Gd=e((()=>{R(),Bd=B`
  <g class="lob-watermelon">
    <g fill="none" stroke="#2c7a4a" stroke-width="4" stroke-linecap="round">
      <path d="M31 25 Q39 13 48 11" />
      <path d="M48 22 Q54 10 60 9" />
      <path d="M66 22 Q72 10 80 15" />
      <path d="M82 28 Q89 20 94 30" />
    </g>
    <ellipse cx="60" cy="69" rx="35" ry="23" fill="#e5484d" />
    <g fill="#28211c">
      <ellipse cx="42" cy="62" rx="2" ry="3.4" transform="rotate(-20 42 62)" />
      <ellipse cx="58" cy="58" rx="2" ry="3.4" transform="rotate(8 58 58)" />
      <ellipse cx="76" cy="64" rx="2" ry="3.4" transform="rotate(24 76 64)" />
      <ellipse cx="49" cy="77" rx="2" ry="3.4" transform="rotate(18 49 77)" />
      <ellipse cx="68" cy="79" rx="2" ry="3.4" transform="rotate(-16 68 79)" />
      <ellipse cx="84" cy="75" rx="1.8" ry="3.1" transform="rotate(30 84 75)" />
    </g>
  </g>
`,Vd=B`
  <path
    class="lob-eclipse-corona"
    d="M29 31 Q40 10 61 9 Q82 9 94 31"
    fill="none"
    stroke="#ffe9b8"
    stroke-width="2.5"
    stroke-linecap="round"
  />
`,Hd=[{y:12,x:44,count:4},{y:20,x:36,count:6},{y:28,x:28,count:8},{y:36,x:20,count:10},{y:44,x:16,count:11},{y:52,x:16,count:11},{y:60,x:16,count:11},{y:68,x:20,count:10},{y:76,x:24,count:9},{y:84,x:32,count:7},{y:92,x:44,count:4}],Ud=B`
  <g class="lob-notexture" shape-rendering="crispEdges">
    ${Hd.flatMap((e,t)=>Array.from({length:e.count},(n,r)=>B`<rect
          x=${e.x+r*8}
          y=${e.y}
          width="8"
          height="8"
          fill=${(t+r)%2==0?`#ff00dc`:`#111111`}
        />`))}
  </g>
`,Wd=B`
  <g class="lob-chimera-stitches" fill="none" stroke="#4a3f3a" stroke-width="1.8" stroke-linecap="round">
    <path d="M18 47 L27 50 M19 51 L22 46 M23 53 L26 48" />
    <path d="M93 50 L102 47 M94 48 L97 53 M98 46 L101 51" />
  </g>
`})))()}function Kd(e){let t=(Math.round(e)%8+8)%8;if(t===0)return B`<g class="lob-selene-moon"><circle cx="60" cy="64" r="12" fill="#26304a" /><circle cx="60" cy="64" r="11" fill="none" stroke="#f4f7fc" stroke-width="1" /></g>`;if(t===4)return B`<g class="lob-selene-moon"><circle cx="60" cy="64" r="12" fill="#26304a" /><circle cx="60" cy="64" r="11" fill="#f4f7fc" /></g>`;let n=t<4?[-5,-9,-14][t-1]:[14,9,5][t-5];return B`
    <g class="lob-selene-moon">
      <circle cx="60" cy="64" r="12" fill="#26304a" />
      <circle cx="60" cy="64" r="11" fill="#f4f7fc" />
      <circle cx=${60+(n??0)} cy="64" r="11" fill="#26304a" />
    </g>
  `}function qd(e,t){return B`
    <g class="lob-pixel-frame" shape-rendering="crispEdges">
      <g class="lob-pixel-antennae" fill="#d84c3e">
        <rect x="30" y="0" width="6" height="6" /><rect x="36" y="6" width="6" height="6" /><rect x="42" y="12" width="6" height="6" />
        <rect x="84" y="0" width="6" height="6" /><rect x="78" y="6" width="6" height="6" /><rect x="72" y="12" width="6" height="6" />
      </g>
      <g class="lob-pixel-claws">
        <path d="M18 42 H6 V48 H0 V60 H6 V66 H18 V60 H24 V48 H18 Z M6 48 H12 V60 H6 Z" fill="#d84c3e" />
        <rect x="6" y="60" width="12" height="6" fill="#a83428" />
        <path d="M102 42 H114 V48 H120 V60 H114 V66 H102 V60 H96 V48 H102 Z M108 48 H114 V60 H108 Z" fill="#d84c3e" />
        <rect x="102" y="60" width="12" height="6" fill="#a83428" />
      </g>
      <!-- Main cells keep the palette variable so offline and mood-style tinting still read. -->
      <g class="lob-pixel-body" fill="var(--lob-shell, #d84c3e)">
        <rect x="42" y="12" width="36" height="6" /><rect x="36" y="18" width="48" height="6" />
        <rect x="30" y="24" width="60" height="6" /><rect x="24" y="30" width="72" height="48" />
        <rect x="30" y="78" width="60" height="12" /><rect x="36" y="90" width="48" height="6" />
        <rect x="36" y="96" width="12" height="9" /><rect x="72" y="96" width="12" height="9" />
      </g>
      <g fill="#ef8f6a"><rect x="36" y="24" width="24" height="6" /><rect x="30" y="30" width="18" height="12" /><rect x="24" y="42" width="12" height="12" /></g>
      <g fill="#a83428"><rect x="30" y="78" width="60" height="12" /><rect x="36" y="90" width="48" height="6" /><rect x="36" y="96" width="12" height="9" /><rect x="72" y="96" width="12" height="9" /></g>
      <g class="lob-eye-open" style=${e}>
        <rect x="42" y="30" width="6" height="6" fill="#0a1014" /><rect x="72" y="30" width="6" height="6" fill="#0a1014" />
        <rect x="42" y="30" width="2.5" height="2.5" fill="#fff" /><rect x="72" y="30" width="2.5" height="2.5" fill="#fff" />
      </g>
      <g class="lob-eye-closed" style=${t} fill="#0a1014"><rect x="42" y="33" width="6" height="3" /><rect x="72" y="33" width="6" height="3" /></g>
    </g>
  `}function Jd(e){return B`
    <svg class="lobster-bottle__svg" viewBox="0 0 48 44" aria-hidden="true">
      <g transform="rotate(-16 24 30)">
        <rect x="5" y="18" width="30" height="16" rx="7" fill="#7fc8b8" opacity="0.72" />
        <rect x="33" y="22" width="9" height="8" rx="2.5" fill="#7fc8b8" opacity="0.72" />
        ${e?B`
              <rect x="36" y="20" width="11" height="7" rx="1.5" fill="#f2e5c9" transform="rotate(-24 41 23)" />
              <rect x="43" y="30" width="4.5" height="8" rx="1.6" fill="#8a5a2b" transform="rotate(38 45 34)" />
            `:B`<rect x="41" y="21.5" width="5" height="9" rx="1.8" fill="#8a5a2b" />`}
        <rect x="11" y="22" width="12" height="8" rx="1.5" fill="#f2e5c9" />
        <path d="M13 24.5 L21 24.5 M13 27 L19 27" stroke="#b6a071" stroke-width="1" />
        <ellipse cx="13" cy="20.5" rx="5" ry="2" fill="#ffffff" opacity="0.35" />
      </g>
    </svg>
  `}var Yd,Xd,Zd,Qd,$d,ef,tf,nf,rf,af,of,sf,cf,lf,uf,df,ff,pf,mf,hf,gf,_f,vf,yf,bf,xf,Sf,Cf,wf,Tf,Ef,Df,Of,kf,Af,jf,Mf,Nf,Pf;function Ff(){return(Ff=e((()=>{R(),Pr(),Gd(),Yd={crown:Dr.crown,sprout:B`
    <g>
      <path d="M60 12 Q58 4 63 1" stroke="#3f9d63" stroke-width="3" stroke-linecap="round" fill="none" />
      <ellipse cx="67" cy="3" rx="5" ry="3" fill="#57c785" transform="rotate(-24 67 3)" />
    </g>
  `,patch:B`
    <g>
      <path d="M28 27 Q60 14 92 22" stroke="#101820" stroke-width="4" stroke-linecap="round" fill="none" />
      <circle cx="75" cy="32" r="9" fill="#101820" />
    </g>
  `,santa:Dr.santa,pumpkin:Dr.pumpkin,party:Dr.party,barnacle:B`
    <g class="lob-barnacles">
      <path d="M32 22 L36.5 13 L41 22 Z" fill="#cfd8de" />
      <path d="M42 18 L45.5 11 L49 18 Z" fill="#b8c4cc" />
      <path d="M27 26 L30 20.5 L33 26 Z" fill="#b8c4cc" />
      <circle cx="36.5" cy="18.5" r="1.1" fill="#8a949d" />
      <circle cx="45.5" cy="15" r="0.9" fill="#8a949d" />
    </g>
  `,monocle:B`
    <g class="lob-monocle" fill="none" stroke="#f4b840">
      <circle cx="75" cy="32" r="8.5" stroke-width="2.5" />
      <path d="M81 39 Q85 48 80 56" stroke-width="1.5" />
    </g>
  `},Xd=B`
  <g class="lob-freckles" fill="#ffffff" opacity="0.3">
    <circle cx="42" cy="45" r="1.6" />
    <circle cx="50" cy="41" r="1.2" />
    <circle cx="70" cy="45" r="1.6" />
    <circle cx="78" cy="41" r="1.2" />
    <circle cx="55" cy="62" r="1.4" />
    <circle cx="67" cy="66" r="1.2" />
  </g>
`,Zd=B`
  <g class="lob-lumen" fill="#7ef5dd">
    <circle cx="36" cy="54" r="2.4" />
    <circle cx="50" cy="66" r="2" />
    <circle cx="66" cy="70" r="2.2" />
    <circle cx="80" cy="60" r="2" />
    <circle cx="88" cy="46" r="1.7" />
    <circle cx="60" cy="86" r="1.7" />
  </g>
`,Qd=B`
  <g class="lob-magma" fill="none" stroke="#ff6a3d" stroke-width="2" stroke-linecap="round">
    <path d="M40 44 L48 54 L42 66 L50 78" />
    <path d="M74 40 L68 52 L78 64" />
    <path d="M56 82 L62 90" />
  </g>
`,$d=B`
  <g class="lob-oilsheen">
    <ellipse cx="46" cy="60" rx="22" ry="11" fill="#7f77dd" opacity="0.3" transform="rotate(-14 46 60)" />
    <ellipse cx="76" cy="74" rx="17" ry="8" fill="#1d9e75" opacity="0.28" transform="rotate(10 76 74)" />
  </g>
`,ef=B`
  <g class="lob-aurora" fill="none" stroke-linecap="round">
    <path class="lob-aurora__band1" d="M24 62 Q48 48 70 58 T102 54" stroke="#4ecfa6" stroke-width="6" opacity="0.5" />
    <path class="lob-aurora__band2" d="M28 76 Q54 62 78 72 T100 68" stroke="#a184ec" stroke-width="5" opacity="0.45" />
  </g>
`,tf=B`
  <g class="lob-nebula-stars">
    <circle cx="38" cy="52" r="1" fill="#fff" />
    <circle cx="52" cy="70" r="1.2" fill="#fff" />
    <circle cx="84" cy="48" r="1.4" fill="#fff" />
    <circle cx="66" cy="86" r="1" fill="#fff" />
    <circle cx="72" cy="60" r="1.6" fill="#8be9fd" />
    <circle cx="46" cy="40" r="1.4" fill="#ff9de2" />
    <path class="lob-twinkle" d="M60 52 L61.5 55.5 L65 57 L61.5 58.5 L60 62 L58.5 58.5 L55 57 L58.5 55.5 Z" fill="#fff" />
  </g>
`,nf=B`
  <g class="lob-glass-glints" fill="none" stroke="#ffffff" stroke-width="2.5" stroke-linecap="round" opacity="0.7">
    <path d="M34 22 L28 32" />
    <path d="M40 16 L37 22" />
  </g>
`,rf=B`
  <g class="lob-geode-facets">
    <polygon points="70,34 80,30 78,44" fill="#9b6ff0" />
    <polygon points="82,46 94,42 88,58" fill="#b48ef0" />
    <polygon points="72,58 84,62 74,74" fill="#7a4fd0" />
    <polygon points="86,68 96,64 90,80" fill="#9b6ff0" />
    <circle class="lob-twinkle" cx="90" cy="50" r="1.8" fill="#fff" />
  </g>
`,af=B`
  <g class="lob-scanlines" stroke="#3fff7d" stroke-width="1" opacity="0.16">
    <path d="M40 20 H80 M30 27 H90 M26 34 H94 M21 41 H99 M18 48 H102 M17 55 H103 M17 62 H103 M18 69 H102 M22 76 H98 M31 83 H89 M45 90 H75" />
  </g>
`,of=B`
  <g class="lob-glitch-ghosts">
    <path d="M60 8 C32 8 16 32 16 52 C16 72 30 90 44 95 L44 104 L54 104 L54 96 C58 97.5 62 97.5 66 96 L66 104 L76 104 L76 95 C90 90 104 72 104 52 C104 32 88 8 60 8 Z" transform="translate(-3 0)" fill="#ff3355" opacity="0.4" />
    <path d="M60 8 C32 8 16 32 16 52 C16 72 30 90 44 95 L44 104 L54 104 L54 96 C58 97.5 62 97.5 66 96 L66 104 L76 104 L76 95 C90 90 104 72 104 52 C104 32 88 8 60 8 Z" transform="translate(3 1)" fill="#22d3ee" opacity="0.4" />
  </g>
`,sf=B`
  <g class="lob-blueprint" fill="none" stroke="#cfe3ff">
    <path class="lob-bp-outline" d="M60 8 C32 8 16 32 16 52 C16 72 30 90 44 95 L44 104 L54 104 L54 96 C58 97.5 62 97.5 66 96 L66 104 L76 104 L76 95 C90 90 104 72 104 52 C104 32 88 8 60 8 Z" stroke-width="1.5" stroke-dasharray="5 3" />
    <path d="M54 58 H66 M60 52 V64" stroke-width="1" opacity="0.7" />
    <path d="M16 100 H104" stroke-width="1" stroke-dasharray="2 3" opacity="0.7" />
  </g>
`,cf=B`
  <g class="lob-mecha">
    <g fill="none" stroke="#5f6a75" stroke-width="1.5">
      <path d="M28 56 Q60 66 92 56" />
      <path d="M34 74 Q60 82 86 74" />
    </g>
    <g fill="#5f6a75">
      <circle cx="36" cy="61" r="1.4" />
      <circle cx="60" cy="64" r="1.4" />
      <circle cx="84" cy="61" r="1.4" />
    </g>
    <circle class="lob-led" cx="89" cy="7" r="3" fill="#ff4444" />
  </g>
`,lf=new Set(`split.retro.lumen.magma.oilslick.aurora.nebula.glass.geode.phosphor.heisenbug.blueprint.clawtron.selene.pixel.banana.bee.rubberduck.watermelon.sourdough.zombie.plush.balloon.disco.cryptid.flatpack.tinfoil.actual.chimera.notexture.loading.eclipse.ascii.portal.invisible.goldenretro`.split(`.`)),uf=B`
  <g fill="#8a6430">
    <rect x="56" y="8" width="8" height="6" rx="2.5" />
    <ellipse cx="60" cy="91" rx="6" ry="3.5" />
    <circle cx="37" cy="48" r="2.5" />
    <circle cx="79" cy="55" r="2" />
    <circle cx="47" cy="70" r="1.8" />
    <circle cx="72" cy="79" r="2.3" />
  </g>
`,df=B`
  <g class="lob-bee-wings" fill="#ffffff" opacity="0.45">
    <ellipse cx="38" cy="14" rx="8" ry="4.5" transform="rotate(-24 38 14)" />
    <ellipse cx="82" cy="14" rx="8" ry="4.5" transform="rotate(24 82 14)" />
  </g>
  <g fill="#2b2b23" opacity="0.9">
    <path d="M19 42 Q60 51 101 42 L103 50 Q60 60 17 50 Z" />
    <path d="M17 58 Q60 67 103 58 L101 67 Q60 76 19 67 Z" />
    <path d="M24 76 Q60 84 96 76 L90 85 Q60 92 30 85 Z" />
  </g>
`,ff=B`
  <g>
    <ellipse cx="60" cy="71" rx="21" ry="14" fill="#ffffff" opacity="0.5" />
    <rect x="47" y="41" width="26" height="8" rx="4" fill="#ff9a2e" />
    <rect x="50" y="47" width="20" height="5" rx="2.5" fill="#e98322" />
  </g>
`,pf=B`
  <g fill="none" stroke="#a8763e" stroke-width="2.5" stroke-linecap="round">
    <path d="M38 23 Q45 29 52 30" />
    <path d="M52 17 Q59 24 66 25" />
    <path d="M67 18 Q74 24 81 25" />
  </g>
  <g fill="#ffffff" opacity="0.5">
    <circle cx="34" cy="39" r="1.2" /><circle cx="86" cy="38" r="1" />
    <circle cx="45" cy="57" r="1.4" /><circle cx="74" cy="62" r="1.1" />
    <circle cx="56" cy="78" r="1" /><circle cx="83" cy="75" r="1.3" />
  </g>
`,mf=B`
  <g fill="none" stroke="#5a6b52" stroke-width="2" stroke-linecap="round">
    <path d="M32 24 Q47 19 61 23" />
    <path d="M38 19 L40 26 M46 18 L47 25 M54 19 L53 26" />
    <path d="M57 72 Q72 78 87 72" />
    <path d="M65 72 L63 79 M73 73 L72 80 M81 71 L83 78" />
  </g>
  <ellipse cx="35" cy="61" rx="9" ry="6" fill="#86987a" opacity="0.8" transform="rotate(-18 35 61)" />
`,hf=B`
  <g fill="none" stroke="#c97a5e" stroke-width="1.5" stroke-dasharray="3 3">
    <path d="M30 32 Q60 4 90 32" />
    <path d="M60 50 Q58 72 60 96" />
  </g>
  <g class="lob-plush-button">
    <circle cx="78" cy="44" r="3.5" fill="#7a4a3a" />
    <circle cx="76.8" cy="44" r="0.7" fill="#e8967a" />
    <circle cx="79.2" cy="44" r="0.7" fill="#e8967a" />
  </g>
`,gf=B`
  <g class="lob-disco" fill="#ffffff">
    <rect x="42" y="18" width="4" height="4" opacity="0.3" /><rect x="52" y="16" width="4" height="4" opacity="0.5" />
    <rect x="63" y="17" width="4" height="4" opacity="0.25" /><rect x="74" y="20" width="4" height="4" opacity="0.4" />
    <rect x="31" y="40" width="4" height="4" opacity="0.4" /><rect x="53" y="39" width="4" height="4" opacity="0.25" />
    <rect x="65" y="42" width="4" height="4" opacity="0.5" /><rect x="86" y="40" width="4" height="4" opacity="0.3" />
    <rect x="39" y="59" width="4" height="4" opacity="0.25" /><rect x="51" y="62" width="4" height="4" opacity="0.45" />
    <rect x="68" y="60" width="4" height="4" opacity="0.3" /><rect x="80" y="58" width="4" height="4" opacity="0.5" />
    <rect x="49" y="79" width="4" height="4" opacity="0.35" /><rect x="70" y="80" width="4" height="4" opacity="0.25" />
  </g>
`,_f={lumen:Zd,magma:Qd,oilslick:$d,aurora:ef,nebula:tf,glass:nf,geode:rf,phosphor:af,blueprint:sf,clawtron:cf,banana:uf,bee:df,rubberduck:ff,sourdough:pf,zombie:mf,plush:hf,disco:gf,watermelon:Bd,eclipse:Vd,notexture:Ud,chimera:Wd},vf=B`
  <path
    class="lob-split-half"
    d="M60 8 C88 8 104 32 104 52 C104 72 90 90 76 95 L76 104 L66 104 L66 96 C64 96.8 62 97.1 60 97.1 L60 8 Z"
    fill="var(--lob-shell2, #46536b)"
  />
`,yf=B`
  <path
    d="M95 55 C112 53 119 39 116 25 C113 11 99 5 91 12 C88 15 87 19 88 23 C83 27 83 36 88 43 C91 49 93 52 95 55 Z"
    fill="var(--lob-claw)"
  />
  <path
    d="M92 14 C97 22 99 31 95 41"
    class="lob-retro-claw-line"
    stroke="#b8151b"
    stroke-width="3"
    stroke-linecap="round"
    fill="none"
  />
`,bf=B`
  <g class="lob-antennae" stroke="var(--lob-shell)" stroke-width="4" stroke-linecap="round" fill="none">
    <path d="M50 16 Q45 4 37 1" />
    <path d="M70 16 Q75 4 83 1" />
  </g>
`,xf=B`
  <g stroke="#0a1014" stroke-linecap="round" fill="none">
    <path d="M37 24 L51 28" stroke-width="3.5" />
    <path d="M69 28 L83 24" stroke-width="3.5" />
    <path d="M49 45 Q59 51 69 45 L72 42" stroke-width="3" />
  </g>
`,Sf=B`
  <g class="lob-tail">
    <ellipse cx="16" cy="84" rx="11" ry="7" transform="rotate(-32 16 84)" />
    <ellipse cx="104" cy="84" rx="11" ry="7" transform="rotate(32 104 84)" />
  </g>
`,Cf=B`
  <g class="lob-bindle">
    <path d="M70 62 L99 30" stroke="#8a5a2b" stroke-width="3.5" stroke-linecap="round" />
    <circle cx="101" cy="27" r="9.5" fill="#e8b04b" />
    <circle cx="98" cy="24" r="1.6" fill="#b6791f" />
    <circle cx="104" cy="29" r="1.6" fill="#b6791f" />
    <circle cx="100" cy="32" r="1.3" fill="#b6791f" />
  </g>
`,wf=new Set([`crown`,`sprout`,`santa`,`pumpkin`,`party`]),Tf=B`
  <g class="lob-cap">
    <path d="M46 10 Q60 -3 74 10 L74 13 Q60 7 46 13 Z" fill="#f5f7fa" />
    <path d="M45 12 Q60 6 75 12 L75 16 Q60 10.5 45 16 Z" fill="#dfe7ee" />
    <circle cx="60" cy="2.5" r="1.8" fill="#3b6ea5" />
  </g>
`,Ef=B`
  <g stroke="#0a1014" stroke-linecap="round" fill="none">
    <path d="M37 24 L51 28" stroke-width="3.5" />
    <path d="M69 28 L83 24" stroke-width="3.5" />
    <path d="M50 48 Q60 42 70 48" stroke-width="3" />
  </g>
`,Df={perky:B`
    <g class="lob-antennae" stroke="var(--lob-shell)" stroke-width="4" stroke-linecap="round" fill="none">
      <path d="M46 14 Q38 4 31 7" />
      <path d="M74 14 Q82 4 89 7" />
    </g>
  `,droopy:B`
    <g class="lob-antennae" stroke="var(--lob-shell)" stroke-width="4" stroke-linecap="round" fill="none">
      <path d="M46 14 Q36 8 34 18" />
      <path d="M74 14 Q84 8 86 18" />
    </g>
  `},Of=B`
  <svg
    class="lobster-pet__svg"
    viewBox="0 0 120 105"
    preserveAspectRatio="none"
    aria-hidden="true"
  >
    <g stroke="#a63a2e" stroke-width="4" stroke-linecap="round" fill="none">
      <path d="M22 78 L8 88" />
      <path d="M28 88 L16 99" />
      <path d="M98 78 L112 88" />
      <path d="M92 88 L104 99" />
    </g>
    <g stroke="#c44536" stroke-width="3.5" stroke-linecap="round" fill="none">
      <path d="M44 38 L40 24" />
      <path d="M76 38 L80 24" />
    </g>
    <circle cx="40" cy="22" r="4.5" fill="#0a1014" />
    <circle cx="80" cy="22" r="4.5" fill="#0a1014" />
    <circle cx="41.5" cy="20.5" r="1.8" fill="#ffd166" />
    <circle cx="81.5" cy="20.5" r="1.8" fill="#ffd166" />
    <ellipse cx="60" cy="70" rx="46" ry="30" fill="#c44536" />
    <ellipse cx="48" cy="60" rx="16" ry="9" fill="#ffffff" opacity="0.1" />
    <path
      d="M16 58 C2 52 -2 62 4 72 C10 82 20 76 24 66 C26 60 22 58 16 58 Z"
      fill="#d95f4b"
    />
    <path
      d="M104 58 C118 52 122 62 116 72 C110 82 100 76 96 66 C94 60 98 58 104 58 Z"
      fill="#d95f4b"
    />
    <path d="M48 82 Q60 90 72 82" stroke="#7e2a20" stroke-width="3" stroke-linecap="round" fill="none" />
  </svg>
`,kf=B`
  <svg
    class="lobster-pet__svg"
    viewBox="0 0 120 105"
    preserveAspectRatio="none"
    aria-hidden="true"
  >
    <path
      d="M14 96 Q32 84 58 88 L96 88 Q110 90 112 97 Q112 103 102 103 L24 103 Q14 103 14 96 Z"
      fill="#c9a06a"
    />
    <g stroke="#c9a06a" stroke-width="3.5" stroke-linecap="round" fill="none">
      <path d="M94 88 Q96 76 91 68" />
      <path d="M103 88 Q107 76 103 66" />
    </g>
    <circle cx="90" cy="65" r="3.6" fill="#0a1014" />
    <circle cx="103" cy="63" r="3.6" fill="#0a1014" />
    <circle cx="91" cy="64" r="1.3" fill="#ffd166" />
    <circle cx="104" cy="62" r="1.3" fill="#ffd166" />
    <circle cx="50" cy="62" r="27" fill="#8a5a2b" />
    <path
      d="M50 41 a21 21 0 1 1 -15 36 a14 14 0 1 0 11 -25 a8 8 0 1 0 4 14"
      stroke="#5f3d1c"
      stroke-width="4"
      stroke-linecap="round"
      fill="none"
    />
  </svg>
`,Af=B`
  <svg
    class="lobster-pet__svg"
    viewBox="0 0 120 105"
    preserveAspectRatio="none"
    aria-hidden="true"
  >
    <path d="M30 82 Q20 74 27 65 Q30 76 40 79 Z" fill="#f0b52e" />
    <ellipse cx="58" cy="85" rx="34" ry="17" fill="#ffd23e" />
    <circle cx="82" cy="50" r="18" fill="#ffd23e" />
    <path d="M98 49 Q112 52 99 59 Q95 56 95 51 Z" fill="#ff8c2e" />
    <circle cx="86" cy="44" r="3.6" fill="#0a1014" />
    <circle cx="87" cy="43" r="1.3" fill="#ffffff" />
    <path d="M44 82 Q58 72 72 82 Q58 93 44 82 Z" fill="#f0b52e" opacity="0.75" />
  </svg>
`,jf=B`
  <svg
    class="lobster-pet__svg"
    viewBox="0 0 120 105"
    preserveAspectRatio="none"
    aria-hidden="true"
  >
    <g class="lob-jelly-tentacles" stroke="#9f7dfa" stroke-width="2.5" stroke-linecap="round" fill="none" opacity="0.8">
      <path d="M40 58 Q35 74 42 90" />
      <path d="M54 61 Q52 78 57 96" />
      <path d="M68 61 Q71 78 64 94" />
      <path d="M80 58 Q85 72 78 88" />
    </g>
    <path
      d="M30 52 C30 22 90 22 90 52 L90 58 Q82 52 75 58 Q67 52 60 58 Q52 52 45 58 Q38 52 30 58 Z"
      fill="#b79bff"
      opacity="0.78"
    />
    <ellipse cx="47" cy="37" rx="12" ry="6" fill="#ffffff" opacity="0.25" />
    <circle cx="52" cy="45" r="2.6" fill="#0a1014" />
    <circle cx="66" cy="45" r="2.6" fill="#0a1014" />
  </svg>
`,Mf={crab:Of,snail:kf,duck:Af,jellyfish:jf},Nf=B`
  <svg class="lobster-pet__balloon" viewBox="0 0 40 62" aria-hidden="true">
    <path d="M20 34 Q23 46 18 60" stroke="#8a949d" stroke-width="1.5" fill="none" />
    <ellipse cx="20" cy="16" rx="13" ry="15" fill="#ff5c8a" />
    <path d="M17 30 L20 34.5 L23 30 Z" fill="#e0446f" />
    <ellipse cx="15" cy="10" rx="4" ry="6" fill="#ffffff" opacity="0.3" />
  </svg>
`,Pf={stranger:`a stranger`,crab:`definitely a lobster`,snail:`in no particular hurry`,duck:`a duck. obviously`,jellyfish:`just drifting`}})))()}function If(e){let t=Yf.map(e=>h(jd.find(t=>t.id===e),`chimera donor palette ${e}`)),n=()=>{let n=Math.floor(e()*t.length);return h(t.splice(n,1)[0],`distinct chimera donor`)};return{body:n().shell,clawLeft:n().shell,clawRight:n().shell,antennae:n().shell}}function Lf(e){return{palette:e,scale:2,accessory:`none`,antennae:`perky`,side:`left`,spotPct:0,facing:1,personality:`friendly`,blinkDelayS:se(e.id)%36/10,clawSize:`regular`,tailFan:!1,shiny:!1,crusherSide:null,freckles:!1,glint:null,chimeraParts:e.id===`chimera`?Xf:null}}function Rf(e){return e.getMonth()===Qf.month&&e.getDate()===Qf.day}function zf(e){let t=e.getMonth(),n=e.getDate();return t===11?[[`santa`,18]]:t===9&&n>=20?[[`pumpkin`,18]]:t===8&&n===25?[[`monocle`,24]]:[]}function Bf(e,t){let n=bd(e.palette.id);return n===e.palette.id?xd(t):n}function Z(e){let t=e>>>0;return()=>{t=t+1831565813|0;let e=Math.imul(t^t>>>15,1|t);return e=e+Math.imul(e^e>>>7,61|e)^e,((e^e>>>14)>>>0)/4294967296}}function Vf(e,t){let n=t.reduce((e,[,t])=>e+t,0),r=e()*n;for(let[e,n]of t)if(r-=n,r<=0)return e;return h(t.at(-1),`weighted lobster choice fallback`)[0]}function Hf(e,t,n){return t+e()*(n-t)}function Uf(e,t=new Date){let n=Z(e),r=Vf(n,Ad),i=Vf(n,ep),a=Vf(n,[...Zf,...zf(t)]),o=n()<.6?`perky`:`droopy`,s=n()<.5?`left`:`right`,c=ap[s],l=Math.round(Hf(n,c[0],c[1])),u=n()<.5?1:-1,d=Vf(n,$f),f=Math.round(Hf(n,0,4)*10)/10;n();let p=Vf(n,tp),m=n()<.3,h=n()<1/512,g=n(),_=n()<.5?`left`:`right`,v=g<.15?_:null,y=n()<.12,b=n(),x=rp[Math.floor(n()*rp.length)]??null,S=b<.3?x:null,C=If(n),w={palette:r,scale:i,accessory:a,antennae:o,side:s,spotPct:l,facing:u,personality:d,blinkDelayS:f,clawSize:p,tailFan:m,shiny:h,crusherSide:v,freckles:y,glint:S,chimeraParts:r.id===`chimera`?C:null},T=r.id===`clawtron`?{...w,antennae:`perky`}:w;if(r.id===`zombie`&&(T={...w,antennae:`droopy`}),Rf(t)){let e=Ad.find(([e])=>e.id===`retro`)?.[0];return{...T,palette:e??r,accessory:`party`,chimeraParts:null}}return T}function Wf(e,t={}){let n=e.palette.id===`flatpack`,r=Jf[e.palette.id],i=Kf.has(e.palette.id),a=t.shell||t.sleeping&&!t.reading,o=a?`display:none`:``,s=a?`opacity:1`:t.standalone||t.reading?`display:none`:``,c=Math.round(Ed(new Date)*8)%8;return B`
    <svg
      class="lobster-pet__svg"
      viewBox="0 0 120 105"
      preserveAspectRatio="xMidYMax meet"
      aria-hidden="true"
    >
      <g class=${qf[e.palette.id]??``}>
        ${r?r(o,s):B`
              ${i?bf:Df[e.antennae]}
              ${e.tailFan?Sf:L}
              <g class="lob-claw lob-claw--l">
                <path d="M20 42 C5 37 0 47 5 57 C10 67 20 62 25 52 C28 45 25 42 20 42 Z" fill="var(--lob-claw)" />
              </g>
              ${i?L:B`<g class="lob-claw lob-claw--r"><path d="M100 42 C115 37 120 47 115 57 C110 67 100 62 95 52 C92 45 95 42 100 42 Z" fill="var(--lob-claw)" /></g>`}
              ${e.palette.id===`heisenbug`?of:L}
              <path class="lob-standard-dome" d="M60 8 C32 8 16 32 16 52 C16 72 30 90 44 95 L44 104 L54 104 L54 96 C58 97.5 62 97.5 66 96 L66 104 L76 104 L76 95 C90 90 104 72 104 52 C104 32 88 8 60 8 Z" fill="var(--lob-shell)" />
              ${e.palette.id===`split`||e.palette.id===`geode`?vf:L}
              ${e.palette.id===`selene`?Kd(c):L}
              ${_f[e.palette.id]??L}
              ${e.palette.id===`tinfoil`?zd(!wf.has(e.accessory)):L}
              ${e.freckles&&!lf.has(e.palette.id)?Xd:L}
              ${e.palette.id===`invisible`?L:B`<ellipse cx="48" cy="28" rx="20" ry="11" fill="#ffffff" opacity="0.1" />`}
              <g class="lob-eye-open" style=${o}>
                <circle cx="45" cy="32" r="5.5" fill="#0a1014" />
                <circle cx="75" cy="32" r="5.5" fill="#0a1014" />
                <circle cx="46.5" cy="30.5" r="2.2" fill="var(--lob-glint, #00e5cc)" />
                <circle cx="76.5" cy="30.5" r="2.2" fill="var(--lob-glint, #00e5cc)" />
              </g>
              ${t.sleeping&&!t.reading?B`<g class="lob-eye-peek"><circle cx="45" cy="32" r="4" fill="#0a1014" /><circle cx="46" cy="30.8" r="1.6" fill="var(--lob-glint, #00e5cc)" /></g>`:L}
              <g class="lob-eye-closed" stroke="#0a1014" stroke-width="3" stroke-linecap="round" fill="none" style=${s}>
                <path d="M39 33 Q45 28 51 33" /><path d="M69 33 Q75 28 81 33" />
              </g>
            `}
      ${i?B`
            ${xf}
            <g class="lob-claw lob-claw--r">${yf}</g>
          `:L}
      ${t.grumpy&&!i&&(!r||e.palette.id===`pixel`)?Ef:L}
      ${e.accessory===`none`||t.shell||n?L:Yd[e.accessory]}
      ${t.bindle&&!i&&!n?Cf:L}
      ${t.sailorCap&&!t.shell&&!n&&!wf.has(e.accessory)&&e.palette.id!==`tinfoil`?Tf:L}
      ${t.reading?ip:L}
      </g>
    </svg>
  `}function Gf(e){let t=e.crusherSide,n=(se(e.palette.id)>>>8)%34/10,r=e.chimeraParts,i=r?jd.find(e=>e.shell===r.body)?.claw:void 0,a=n=>t===null?np[e.clawSize]:t===n?np.mighty:np.dainty;return[`--lob-shell:${e.chimeraParts?.body??e.palette.shell}`,`--lob-claw:${i??e.palette.claw}`,`--lob-blink-delay:${e.blinkDelayS}s`,`--lob-breathe-delay:-${n}s`,`--lob-claw-l:${a(`left`)}`,`--lob-claw-r:${a(`right`)}`,...e.chimeraParts?[`--lob-chimera-l:${e.chimeraParts.clawLeft}`,`--lob-chimera-r:${e.chimeraParts.clawRight}`,`--lob-antennae-color:${e.chimeraParts.antennae}`]:[],...e.glint?[`--lob-glint-seed:${e.glint}`]:[]].join(`;`)}var Kf,qf,Jf,Yf,Xf,Zf,Qf,$f,ep,tp,np,rp,ip,ap;function op(){return(op=e((()=>{T(),R(),Td(),kd(),Md(),Gd(),Ff(),Kf=new Set([`retro`,`goldenretro`]),qf={heisenbug:`lob-heisenbug-frame`,cryptid:`lob-cryptid-frame`,balloon:`lob-balloon-frame`},Jf={flatpack:Nd,loading:Pd,actual:Fd,balloon:Id,ascii:Ld,portal:Rd,pixel:qd},Yf=[`crimson`,`blue`,`gold`,`banana`,`watermelon`],Xf={body:`#ff4f40`,clawLeft:`#4a7dfc`,clawRight:`#f4b840`,antennae:`#3f9d63`},Zf=[[`none`,62],[`sprout`,14],[`patch`,14],[`crown`,10]],Qf={month:10,day:24},$f=[[`sleepy`,25],[`zoomy`,25],[`friendly`,25],[`showoff`,25]],ep=[[1.7,25],[2,55],[2.5,20]],tp=[[`regular`,55],[`dainty`,25],[`mighty`,20]],np={dainty:.85,regular:1,mighty:1.18},rp=[`#ffd166`,`#ff8ac2`,`#b79bff`],ip=B`
  <g class="lob-reading-book" transform="translate(0 2)">
    <path
      d="M25 62 Q43 56 59 66 L59 92 Q43 82 25 86 Z M61 66 Q77 56 95 62 L95 86 Q77 82 61 92 Z"
      fill="var(--lob-claw)"
      stroke="color-mix(in srgb, var(--lob-claw) 72%, #0a1014)"
      stroke-width="2.5"
      stroke-linejoin="round"
    />
    <path d="M29 62 Q44 58 59 68 L59 88 Q44 79 29 82 Z" fill="#fffaf0" />
    <path d="M61 68 Q76 58 91 62 L91 82 Q76 79 61 88 Z" fill="#fffaf0" />
    <path d="M60 67 L60 89" stroke="#d7cfc0" stroke-width="1.5" />
    <g stroke="#b8b0a3" stroke-width="1.25" stroke-linecap="round" opacity="0.58">
      <path d="M34 67 L51 71" /><path d="M34 72 L50 75" /><path d="M67 71 L85 67" />
      <path d="M68 76 L85 72" /><path d="M70 80 L83 77" />
    </g>
    <path
      class="lob-reading-book__page-glow"
      d="M31 62 Q45 59 57 68 L57 72 Q44 65 31 67 Z"
      fill="#ffffff"
      opacity="0"
    />
  </g>
`,ap={left:[12,38],right:[60,84]}})))()}function sp(e,t,n=new Date){return e===`busy`||e===`offline`?Cp[e]:bp(n)?Sp.sleepy:t?Sp[t]:null}function cp(e){return e===`error`?`droop`:e===`aborted`?`startle`:`cheer`}function lp(e){return e<.06?`balloon`:e<.13?`bubble`:`walk`}function up(e){return Z((e^12317)>>>0)()<.12}function dp(e){return Z((e^30485)>>>0)()<.04}function fp(e,t){return(Object.hasOwn(Tp,e)?Tp[e]:void 0)??t?.[e]?.crossMs??12e3}function pp(e,{critters:t=[],strangers:n=!0}={}){let r=Z((e^3243)>>>0),i=r()*1e3,a=[[`crab`,15],[`snail`,12],[`duck`,12],[`jellyfish`,11],...n?[[`stranger`,45]]:[],...t.map(e=>[e,20])],o=0,s=a.find(([,e])=>(o+=e,i<o))?.[0];return s?{kind:s,atMs:Math.round(2500+r()*6500),direction:r()<.5?1:-1,floor:r()<.55,hops:r()<.35&&s!==`snail`}:null}function mp(e){return Z((e^57811)>>>0)()<.015}function hp(e,t){if(t.length===0)return null;let n=Z((e^61982)>>>0);return n()>=.08?null:t[Math.floor(n()*t.length)]??null}function gp(e,t){let n=Ju(),r={elder:!1,oldFriend:!1,friendName:null,dexComplete:jd.every(e=>n.has(e.id)),look:t};if(mp(e))return{...r,elder:!0,look:{...t,scale:3,accessory:`barnacle`,personality:`sleepy`,clawSize:`mighty`,crusherSide:null}};if(t.palette.id===`retro`||t.palette.id===`goldenretro`)return r;let i=hp(e,[...n].filter(e=>jd.some(t=>t.id===e)).toSorted()),a=i?jd.find(e=>e.id===i):void 0;return a?{...r,oldFriend:!0,friendName:Yu().get(a.id)?.name??null,look:{...t,palette:a,chimeraParts:a.id===`chimera`?Lf(a).chimeraParts:null}}:r}function _p(e,t){return e.elder?`Methuselah`:e.friendName??Bf(e.look,t)}function vp(e){let t=Z((e^45175)>>>0);return t()>=.03?null:{atMs:Math.round(3500+t()*6500),spotPct:Math.round(15+t()*70),fortuneIndex:Math.floor(t()*kp.length)}}function yp(e){try{let t=k();if(!t)return!1;let n=t.getItem(Ap);return n!==e&&(t.setItem(Ap,e),n!==null)}catch{return!1}}function bp(e=new Date){let t=e.getHours();return t>=22||t<6}function Q(){return typeof window<`u`&&typeof window.matchMedia==`function`&&window.matchMedia(`(prefers-reduced-motion: reduce)`).matches}var xp,Sp,Cp,wp,Tp,Ep,Dp,Op,kp,Ap;function jp(){return(jp=e((()=>{ld(),op(),Md(),Lr(),xp={wave:1400,snip:1e3,hop:750,spin:950,peek:1700,nap:4400,bubble:2600,scuttle:1250,startle:750,cheer:1300,molt:2600,pet:1500,droop:1600,sweep:1800},Sp={sleepy:{delayMs:[6e3,12e3],acts:[[`nap`,40],[`bubble`,20],[`wave`,12],[`scuttle`,12],[`peek`,10],[`hop`,6]]},zoomy:{delayMs:[2800,6e3],acts:[[`scuttle`,42],[`hop`,22],[`spin`,12],[`peek`,12],[`wave`,12]]},friendly:{delayMs:[3600,7500],acts:[[`wave`,32],[`snip`,22],[`scuttle`,18],[`hop`,14],[`bubble`,14]]},showoff:{delayMs:[3600,7500],acts:[[`spin`,24],[`snip`,22],[`peek`,20],[`hop`,18],[`wave`,16]]}},Cp={busy:{delayMs:[2200,4500],acts:[[`scuttle`,40],[`hop`,20],[`snip`,20],[`wave`,12],[`spin`,8]]},offline:{delayMs:[2800,5600],acts:[[`scuttle`,55],[`peek`,30],[`hop`,15]]}},wp={walk:450,balloon:1250,bubble:700},Tp={stranger:11e3,crab:11e3,snail:9e4,duck:14e3,jellyfish:16e3,...Br},Ep=[1800,7500],Dp=[9e4,3e5],Op=[18e5,36e5],kp=[`the tide returns every branch to shore`,`molt before you feel ready`,`a shell is just armor you outgrew`,`somewhere, a test is green because of you`,`swim sideways when forward fails`,`the reef remembers kind commits`,`even the deep keeps a night light`,`barnacles are only patient passengers`,`no current lasts forever`,`bury your treasure in version control`,`the crab was a lobster all along`,`small claws, firm grip`,`rest is also progress`,`what washes away was never pinned`],Ap=`openclaw.control.lobsterpet.gatewayVersion.v1`})))()}var Mp;function Np(){return(Np=e((()=>{jp(),Mp=class{constructor(e,t){this.host=e,this.hooks=t,this.grumpyTimer=null,this.holdTimer=null,this.audioCtx=null,this.pokeTimes=[],this.lastGazeAt=0,this.handleHoldStart=e=>{e.button!==0||Q()||(this.holdTimer!==null&&window.clearTimeout(this.holdTimer),this.holdTimer=window.setTimeout(()=>{this.holdTimer=null,this.hooks.onGrumpyChange(!1),this.playChirp(`pet`),this.hooks.onAct(`pet`)},600))},this.handleHoldEnd=e=>{e.button===0&&this.holdTimer!==null&&(window.clearTimeout(this.holdTimer),this.holdTimer=null,this.pokeNow())},this.handleHoldCancel=()=>{this.holdTimer!==null&&(window.clearTimeout(this.holdTimer),this.holdTimer=null)},this.handleGaze=e=>{if(!this.hooks.canGaze()||Q())return;let t=Date.now();if(t-this.lastGazeAt<120)return;this.lastGazeAt=t;let n=this.host.querySelector(`.lobster-pet:not(.lobster-pet--shell)`);if(!n)return;let r=n.getBoundingClientRect(),i=r.left+r.width/2;this.hooks.onFacing(e.clientX<i?-1:1)},e.addController(this)}hostConnected(){document.addEventListener(`pointermove`,this.handleGaze,{passive:!0})}hostDisconnected(){document.removeEventListener(`pointermove`,this.handleGaze),this.handleHoldCancel(),this.clearGrumpyTimer(),this.audioCtx&&=(this.audioCtx.close().catch(()=>{}),null)}suspend(){this.handleHoldCancel(),this.clearGrumpyTimer(),this.hooks.onGrumpyChange(!1)}playChirp(e){this.audioCtx=_d(this.audioCtx,this.hooks.soundsEnabled(),e)}pokeNow(){this.playChirp(`poke`);let e=Date.now();if(this.pokeTimes=[...this.pokeTimes.filter(t=>e-t<6e3),e],this.pokeTimes.length>=10&&this.hooks.canHuff()){this.huffOff();return}this.pokeTimes.length>=3&&this.enterGrumpy(),this.hooks.onAct(`startle`)}clearGrumpyTimer(){this.grumpyTimer!==null&&(window.clearTimeout(this.grumpyTimer),this.grumpyTimer=null)}enterGrumpy(){this.hooks.onGrumpyChange(!0),this.clearGrumpyTimer(),this.grumpyTimer=window.setTimeout(()=>{this.grumpyTimer=null,this.hooks.onGrumpyChange(!1)},6e4)}huffOff(){this.pokeTimes=[],this.hooks.onGrumpyChange(!1),this.hooks.onHuff()}}})))()}function Pp(e){return e.hop?1100:Math.max(850,Math.min(2600,Math.abs(e.to.x-e.from.x)*8))}function Fp(e,t,n,r){let i=e,a=null;for(let e of n.toSorted((e,t)=>e.left-t.left)){let n=Math.min(t,e.left-r);n>i&&(!a||n-i>a[1]-a[0])&&(a=[i,n]),i=Math.max(i,e.right+r)}return t>i&&(!a||t-i>a[1]-a[0])&&(a=[i,t]),a}function Ip(e){let{composer:t,footer:n,editor:r}=e,i={top:null,floor:null,passage:null};if(t.width<=0||t.height<=0)return i;let a=Rp+(e.twins?28:0),o=Fp(t.left+a,t.right-a,e.topObstacles.filter(e=>e.height>0&&e.bottom>t.top-zp&&e.top<t.top),a),s=o?{start:o[0]-t.left,end:o[1]-t.left,y:0}:null;if(!n||n.height<=0)return{...i,top:s};let c=Math.min(t.bottom-8,n.bottom-5);if(c-48<(r?.bottom??t.top))return{...i,top:s};let l=Fp(Math.max(t.left,n.left)+a,Math.min(t.right,n.right)-a,e.controls.filter(e=>e.width>0&&e.height>0&&e.top<c&&e.bottom>c-48),a),u=l&&l[1]-l[0]>=24?{start:l[0]-t.left,end:l[1]-t.left,y:c-t.top}:null,d=Math.max(s?.start??1/0,u?.start??1/0,e.placeholderRight-t.left+a),f=Math.min(s?.end??-1/0,u?.end??-1/0);return{top:s,floor:u,passage:f-d>=28?[d,f]:null}}function Lp(e,t){return{x:e?e.start+(e.end-e.start)*t/100:0,y:e?.y??0}}var Rp,zp,Bp;function Vp(){return(Vp=e((()=>{Rp=38,zp=88,Bp=class{constructor(e,t){this.host=e,this.twins=t,this.scene={top:null,floor:null,passage:null},this.resize=null,this.mutation=null,this.active=!1,this.frame=null,this.observed=[],this.scheduleMeasure=()=>{this.active&&this.frame===null&&(this.frame=requestAnimationFrame(()=>this.measure()))},e.addController(this)}planWalk(e,t,n){let r=this.scene[e];if(!r)return null;let i=Math.round(n*100);return Math.abs(i-t)<4&&(i=t>50?0:100),{anchor:e,spotPct:i,facing:i<t?-1:1,travel:{from:Lp(r,t),to:Lp(r,i),hop:!1}}}planHop(e,t){let{passage:n,floor:r}=this.scene,i=this.scene[e];if(!n||!r||!i)return null;let a=Lp(i,t),o=(n[0]+n[1])/2;if(a.x<n[0]||a.x>n[1])return{anchor:e,spotPct:(o-i.start)/(i.end-i.start)*100,facing:o<a.x?-1:1,travel:{from:a,to:{x:o,y:i.y},hop:!1}};let s=e===`top`?`floor`:`top`,c=this.scene[s];if(!c)return null;let l=a.x<o?n[1]:n[0];return{anchor:s,spotPct:(l-c.start)/(c.end-c.start)*100,facing:l<a.x?-1:1,travel:{from:a,to:{x:l,y:c.y},hop:!0}}}hostConnected(){this.active=!0,typeof ResizeObserver<`u`?this.resize=new ResizeObserver(()=>this.measure()):window.addEventListener(`resize`,this.scheduleMeasure);let e=this.host.parentElement,t=e?.closest(`.new-session-page__draft`)??e;t&&(this.mutation=new MutationObserver(e=>{e.some(e=>e.target!==this.host&&!this.host.contains(e.target))&&this.scheduleMeasure()}),this.mutation.observe(t,{childList:!0,subtree:!0,attributes:!0,attributeFilter:[`class`,`style`,`hidden`,`aria-label`]})),this.scheduleMeasure()}hostDisconnected(){this.active=!1,this.frame!==null&&(cancelAnimationFrame(this.frame),this.frame=null),this.resize?.disconnect(),this.resize=null,this.mutation?.disconnect(),this.mutation=null,this.observed=[],window.removeEventListener(`resize`,this.scheduleMeasure)}measure(){if(this.frame!==null&&(cancelAnimationFrame(this.frame),this.frame=null),!this.active||!this.host.isConnected)return;let e=this.host.parentElement;if(!e?.matches(`.agent-chat__input`))return;let t=e.querySelector(`.agent-chat__composer-footer`),n=e.querySelector(`textarea`),r=Array.from(t?.querySelectorAll(`.agent-chat__composer-lead, .chat-composer-model-control, .agent-chat__composer-actions, button, wa-button, [role=button]`)??[]),i=e.closest(`.new-session-page__draft`),a=Array.from(i?.querySelectorAll(`.new-session-page__triggers > *, .new-session-page__incognito-notice--visible`)??[]),o=[e,...r,...a,...t?[t]:[],...n?[n]:[]];if(o.length!==this.observed.length||o.some((e,t)=>e!==this.observed[t])){this.resize?.disconnect();for(let e of o)this.resize?.observe(e);this.observed=o}let s=n?.getBoundingClientRect()??null,c=s?.left??0;if(n&&s){let e=getComputedStyle(n),t=n.getAttribute(`aria-label`)??n.placeholder,r=Number.parseFloat(e.fontSize)||16,i=t.length*r*.65;if(typeof CanvasRenderingContext2D<`u`){let n=document.createElement(`canvas`).getContext(`2d`);n&&(n.font=e.font,i=n.measureText(t).width)}c+=Math.min(s.width,i+(Number.parseFloat(e.paddingLeft)||0))}let l=Ip({composer:e.getBoundingClientRect(),footer:t?.getBoundingClientRect()??null,controls:r.map(e=>e.getBoundingClientRect()),topObstacles:a.map(e=>e.getBoundingClientRect()),editor:s,placeholderRight:c,twins:this.twins()});this.host.toggleAttribute(`data-scene-ready`,l.top!==null),JSON.stringify(l)!==JSON.stringify(this.scene)&&(this.scene=l,this.host.requestUpdate())}}})))()}function Hp(e,t){for(let n=1;n<=24;n++){let r=Uf(e+n*7919>>>0);if(r.palette.id!==t)return r}return Uf(e+1>>>0)}function Up(e,t,n,r){return[Gf(e),`--lob-scale:${t}`,`--lob-x:${n}%`,`--lob-face:${r}`].join(`;`)}function Wp(e){if(!e.scene.top)return L;let t=e.scene[e.anchor]??e.scene.top,n=n=>{let r=e.anniversary&&e.look.accessory!==`party`?{...e.look,accessory:`party`}:e.look,i=[`lobster-pet`,`lobster-pet--${e.mode}`,`lobster-pet--palette-${e.look.palette.id}`,n?`lobster-pet--twin`:``,r.accessory===`party`?`lobster-pet--party`:``,e.look.shiny?`lobster-pet--shiny`:``,e.elder?`lobster-pet--elder`:``,e.presence===`leaving`?`lobster-pet--away`:``,e.entering?`lobster-pet--entering`:``,e.entering&&e.entrance!==`walk`?`lobster-pet--enter-${e.entrance}`:``,e.grumpy?`lobster-pet--grumpy`:``,e.vigil?`lobster-pet--vigil`:``,e.act?`lobster-pet--act-${e.act}`:``].filter(Boolean).join(` `),a=Lp(t,e.spotPct);n&&(a.x=Math.max(t.start,Math.min(t.end,a.x-e.facing*28)));let o=n?e.look.scale*.55:e.look.scale,s=`${Up(e.look,o,e.spotPct,e.facing)};--lob-x:${a.x}px;--lob-y:${a.y}px${n?`;--lob-act-delay:0.18s`:``}`,c=e.travel,l=c?`--lob-from-x:${c.from.x-c.to.x}px;--lob-from-y:${c.from.y-c.to.y}px;--lob-travel-ms:${Pp(c)}ms${n?`;animation-delay:0.18s`:``}`:``,u=nd(e.familiarityVisits),d=e.nameOverride??Bf(e.look,e.seed),f=u?`${u} ${d}`:d,p=e.look.shiny?`✦ ${f}`:f,m=e.movingDay&&!n,h=n?`${p} Jr.`:m?`${p} · just moved in`:e.flavor?`${p} · ${e.flavor}`:p;return I`
      <div
        class="lobster-pet__motion ${c?c.hop?`lobster-pet__motion--hop`:`lobster-pet__motion--walk`:``}"
        style=${l}
      >
        <div
          class=${i}
          style=${s}
          aria-hidden="true"
          title=${h}
          @pointerdown=${e.onPointerDown}
          @pointerup=${e.onPointerUp}
          @pointercancel=${e.onPointerCancel}
          @pointerleave=${e.onPointerCancel}
          @contextmenu=${e.onContextMenu}
        >
          <div class="lobster-pet__body">
            ${Wf(r,{grumpy:e.grumpy,bindle:m,sailorCap:e.sailorDay})}
            ${e.entering&&e.entrance===`balloon`?Nf:L}
            ${e.entering&&e.entrance===`bubble`?I`<span class="lobster-pet__entry-bubble"></span>`:L}
            ${e.look.shiny?I`
                    <span class="lobster-pet__sparkle" style="--i:0;left:12%;bottom:64%">✦</span>
                    <span class="lobster-pet__sparkle" style="--i:1;left:76%;bottom:82%">✦</span>
                  `:L}
            <span class="lobster-pet__z" style="--i:0">z</span>
            <span class="lobster-pet__z" style="--i:1">z</span>
            <span class="lobster-pet__z" style="--i:2">Z</span>
            <span class="lobster-pet__bubble" style="--i:0"></span>
            <span class="lobster-pet__bubble" style="--i:1"></span>
            <span class="lobster-pet__bubble" style="--i:2"></span>
            <span class="lobster-pet__heart">♥</span>
            <svg class="lobster-pet__broom" viewBox="0 0 24 40" aria-hidden="true">
              <path d="M12 2 L12 24" stroke="#8a5a2b" stroke-width="3" stroke-linecap="round" />
              <path d="M6 24 L18 24 L21 38 L3 38 Z" fill="#e8b04b" />
              <path
                d="M7.5 28 L6.5 36 M12 28 L12 36 M16.5 28 L17.5 36"
                stroke="#b6791f"
                stroke-width="1.5"
              />
            </svg>
          </div>
        </div>
      </div>
    `},r=e.residentEnabled&&e.presence!==`out`,i=e.residentEnabled&&e.shellVisible&&e.visitsEnabled&&!e.dismissed,a=e.passer&&!ee(e.passer.kind)?e.critterArtwork?.[e.passer.kind]:void 0,o=e.passer?.kind===`stranger`&&!a,s=e.passer!==null&&e.visitsEnabled&&(e.residentEnabled||!o)&&!e.dismissed&&(e.passer.anchor===`top`||e.floorEnabled&&e.scene.floor!==null),c=e.bottle!==null&&e.visitsEnabled&&!e.dismissed;if(!r&&!i&&!s&&!c)return L;let l=Up(e.look,e.shellScale,e.shellSpotPct,e.facing),u=Lp(e.scene[e.shellAnchor],e.shellSpotPct),d=o?Hp(e.seed,e.look.palette.id):e.look,f=e.passer?[`lobster-pet`,`lobster-pet--passer`,o?`lobster-pet--palette-${d.palette.id}`:`lobster-pet--${e.passer.kind}`,o&&d.shiny?`lobster-pet--shiny`:``,e.passer.direction===1?`lobster-pet--passer-ltr`:`lobster-pet--passer-rtl`,e.passer.hops&&e.scene.passage?`lobster-pet--passer-hop`:``].filter(Boolean).join(` `):``,p=e.passer?e.scene[e.passer.anchor]:null,m=e.passer?.hops&&e.scene.passage?e.scene.passage:[p?.start??0,p?.end??0],h=e.passer?.direction===1?m[0]:m[1],g=e.passer?.direction===1?m[1]:m[0],_=e.passer?`${Gp(e.passer.kind,e.passer.direction,d,!!a)};--lob-cross:${e.passer.crossMs}ms;--lob-cross-from:${h}px;--lob-cross-to:${g}px;--lob-y:${p?.y??0}px`:``,v=e.passer&&Object.hasOwn(Kp,e.passer.kind)?Kp[e.passer.kind]:void 0,y=e.passer&&Object.hasOwn(qp,e.passer.kind)?qp[e.passer.kind]:void 0,b=Lp(e.scene.top,e.bottle?.spotPct??50);return I`
    ${i?I`
            <div
              class="lobster-pet lobster-pet--shell"
              style=${`${l};--lob-x:${u.x}px;--lob-y:${u.y}px`}
              aria-hidden="true"
            >
              <div class="lobster-pet__body">${Wf(e.look,{shell:!0})}</div>
            </div>
          `:L}
    ${c&&e.bottle?I`
            <div
              class="lobster-bottle ${e.bottle.opened?`lobster-bottle--open`:``}"
              style="--lob-x:${b.x}px"
              title=${e.bottle.opened?e.bottle.fortune:`a message in a bottle`}
              aria-hidden="true"
              @pointerdown=${e.onBottleOpen}
            >
              ${Jd(e.bottle.opened)}
            </div>
          `:L}
    ${r?n(!1):L}
    ${r&&e.twinPlanned?n(!0):L}
    ${s&&e.passer?I`
            <div
              class=${f}
              style=${_}
              aria-hidden="true"
              title=${(a?a.title:y)??e.passer.kind}
            >
              <div class="lobster-pet__body">
                ${a?Or(a.url,`lobster-pet__svg`):o?Wf(d,{standalone:!0}):v??L}
              </div>
            </div>
          `:L}
  `}function Gp(e,t,n,r){if(r)return`--lob-scale:1.8;--lob-w:1;--lob-h:1;--lob-face:${t}`;if(e===`stranger`)return Up(n,Math.min(n.scale,2),0,t);if(ee(e))return Hr(e,t);let i={crab:`--lob-scale:2;--lob-w:1;--lob-h:0.82;--lob-face:1`,snail:`--lob-scale:1.7;--lob-w:1;--lob-h:0.9;--lob-face:${t}`,duck:`--lob-scale:1.9;--lob-w:1;--lob-h:1;--lob-face:${t}`,jellyfish:`--lob-scale:1.7;--lob-w:0.9;--lob-h:1.1;--lob-face:1`};return(Object.hasOwn(i,e)?i[e]:void 0)??`--lob-scale:1.8;--lob-w:1;--lob-h:1;--lob-face:${t}`}var Kp,qp;function Jp(){return(Jp=e((()=>{R(),o(),ld(),op(),Vp(),Ff(),Ur(),Lr(),Kp={...Mf,...jr},qp={...Pf,...Er}})))()}var Yp;function Xp(){return(Xp=e((()=>{T(),jp(),Yp=class{constructor(e,t){this.host=e,this.hooks=t,this.passer=null,this.connected=!1,this.bottlePlan=null,this.bottleVisible=!1,this.bottleOpened=!1,this.passerTimer=null,this.passerEndTimer=null,this.passerWatchTimer=null,this.seed=null,this.passerConsumed=!1,this.crossingMs=0,this.bottleTimer=null,this.bottleEndTimer=null,this.openBottle=()=>{!this.bottleOpened&&this.bottleVisible&&(this.bottleOpened=!0,this.armBottleEbb(12e4),this.host.requestUpdate())},e.addController(this)}hostConnected(){this.connected=!0}hostUpdate(){this.hooks.visitsEnabled()||(this.clearTimers(),this.passer=null,this.bottleVisible=!1)}hostDisconnected(){this.connected=!1,this.clearTimers(),this.passer=null,this.bottleVisible=!1,this.host.requestUpdate()}reset(e){e!==this.seed&&(this.seed=e,this.passerConsumed=!1),this.clearTimers(),this.passer=null,this.bottleVisible=!1,this.bottleOpened=!1,this.connected&&this.hooks.visitsEnabled()&&(this.schedulePasser(e),this.scheduleBottle(e))}replanPasser(e){let t=this.passer,n=this.hooks.passerOptions(),r=t&&[`stranger`,`crab`,`snail`,`duck`,`jellyfish`].includes(t.kind);if(t&&(t.kind!==`stranger`||n.strangers!==!1||n.critters?.includes(t.kind))&&(r||n.critters?.includes(t.kind)))return;let i=this.passer!==null;this.clearPasserTimers(),this.passer=null,i&&this.hooks.onPasserDone(),this.connected&&this.hooks.visitsEnabled()&&this.schedulePasser(e)}passerCrossMs(){return this.passer?this.crossingMs:0}bottle(){return!this.bottleVisible||!this.bottlePlan?null:{spotPct:this.bottlePlan.spotPct,opened:this.bottleOpened,fortune:h(kp[this.bottlePlan.fortuneIndex],`lobster bottle fortune`)}}clearTimers(){this.clearPasserTimers();for(let e of[this.bottleTimer,this.bottleEndTimer])e!==null&&window.clearTimeout(e);this.bottleTimer=null,this.bottleEndTimer=null}clearPasserTimers(){for(let e of[this.passerTimer,this.passerEndTimer,this.passerWatchTimer])e!==null&&window.clearTimeout(e);this.passerTimer=null,this.passerEndTimer=null,this.passerWatchTimer=null}schedulePasser(e){if(this.passerConsumed)return;let t=pp(e,this.hooks.passerOptions());t&&!Q()&&(this.passerTimer=window.setTimeout(()=>{if(this.passerTimer=null,this.passerConsumed=!0,!this.connected||!this.hooks.visitsEnabled()||document.hidden||Q())return;this.hooks.onPasserStart(t),this.passer=t,this.crossingMs=fp(t.kind,this.hooks.passerOptions().critterArtwork),this.host.requestUpdate();let e=this.passerCrossMs();this.hooks.onPasserFacing(t.direction===1?-1:1),this.passerWatchTimer=window.setTimeout(()=>{this.passerWatchTimer=null,this.hooks.onPasserFacing(t.direction),this.hooks.onPasserMidCross()},e/2),this.passerEndTimer=window.setTimeout(()=>{this.passerEndTimer=null,this.passer=null,this.host.requestUpdate(),this.hooks.onPasserDone()},e)},t.atMs))}scheduleBottle(e){this.bottlePlan=vp(e),this.bottlePlan&&(this.bottleTimer=window.setTimeout(()=>{this.bottleTimer=null,this.connected&&this.hooks.visitsEnabled()&&(this.bottleVisible=!0,this.host.requestUpdate(),this.armBottleEbb(3e5))},this.bottlePlan.atMs))}armBottleEbb(e){this.bottleEndTimer!==null&&window.clearTimeout(this.bottleEndTimer),this.bottleEndTimer=window.setTimeout(()=>{this.bottleEndTimer=null,this.bottleVisible=!1,this.host.requestUpdate()},e)}}})))()}var $;function Zp(){return(Zp=e((()=>{R(),Gt(),Ct(),ld(),md(),gd(),Np(),op(),jp(),Jp(),Vp(),Xp(),$=class extends f{constructor(...e){super(...e),this.seed=0,this.mode=`idle`,this.visitsEnabled=!0,this.residentEnabled=!0,this.floorEnabled=!1,this.runOutcome=`ok`,this.soundsEnabled=!1,this.gatewayVersion=null,this.onVisitsDisabled=()=>void 0,this.act=null,this.spotPct=80,this.facing=1,this.entering=!1,this.entrance=`walk`,this.presence=`out`,this.anchor=`top`,this.geometry=new Bp(this,()=>this.residentEnabled&&this.twinPlanned),this.travel=null,this.travelScene=this.geometry.scene,this.motionRng=Z(0),this.passerAnchor=`top`,this.passerHops=!1,this.shellAnchor=`top`,this.scheduledVisiting=!1,this.dismissed=!1,this.dismissMenuPosition=null,this.grumpy=!1,this.vigil=!1,this.outcomePresenceOwner=null,this.movingDay=!1,this.movingDayChecked=!1,this.anniversary=!1,this.sailorDay=!1,this.identity=null,this.entranceRng=Z(0),this.traffic=new Yp(this,{visitsEnabled:()=>this.visitsEnabled&&!this.dismissed,passerOptions:()=>({critters:this.critters,strangers:this.residentEnabled,critterArtwork:this.critterArtwork}),onPasserStart:e=>{this.passerAnchor=e.floor&&this.floorEnabled&&this.geometry.scene.floor?`floor`:`top`,this.passerHops=this.passerAnchor===`floor`&&e.hops&&this.geometry.scene.passage!==null},onPasserFacing:e=>this.watchTraffic(e),onPasserMidCross:()=>this.reactToPasser(),onPasserDone:()=>this.scheduleNextAct()}),this.interactions=new Mp(this,{soundsEnabled:()=>this.soundsEnabled,canHuff:()=>this.mode!==`offline`,canGaze:()=>this.presence===`in`&&this.act===null&&!this.vigil,onGrumpyChange:e=>{this.grumpy=e},onAct:e=>this.performAct(e),onFacing:e=>{this.facing=e},onHuff:()=>{this.clearVisitTimers(),this.scheduledVisiting=!1,this.armArrival(Hf(this.visitRng,Op[0],Op[1]))}}),this.shellVisible=!1,this.shellSpotPct=50,this.shellScale=2,this.molted=!1,this.moltPlanned=!1,this.twinPlanned=!1,this.shellTimer=null,this.familiarity={tier:`regular`,wary:!1,visits:0,shoos:0},this.greetedThisLoad=!1,this.look=null,this.rng=Z(0),this.visitRng=Z(0),this.idleTimer=null,this.actEndTimer=null,this.enterTimer=null,this.visitTimer=null,this.leaveTimer=null,this.vigilTimer=null,this.restartPending=!1,this.handleVisibilityChange=()=>{document.hidden?(this.outcomePresenceOwner=null,this.clearActTimers(),this.act=null):this.scheduleNextAct()},this.openDismissMenu=e=>{this.residentEnabled&&this.visitsEnabled&&(e.preventDefault(),e.stopPropagation(),this.interactions.handleHoldCancel(),this.dismissMenuPosition={x:e.clientX,y:e.clientY})}}createRenderRoot(){return this}connectedCallback(){super.connectedCallback(),this.hasUpdated&&(this.look=null,this.requestUpdate()),document.addEventListener(`visibilitychange`,this.handleVisibilityChange)}disconnectedCallback(){document.removeEventListener(`visibilitychange`,this.handleVisibilityChange),this.clearActTimers(),this.clearVisitTimers(),this.restartPending=!1,this.scheduledVisiting=!1,this.presence=`out`,this.act=null,this.shellTimer!==null&&(window.clearTimeout(this.shellTimer),this.shellTimer=null),this.vigilTimer!==null&&(window.clearTimeout(this.vigilTimer),this.vigilTimer=null),super.disconnectedCallback()}wantsVisible(){return this.visitsEnabled&&this.residentEnabled&&!this.dismissed&&(this.mode===`offline`||this.vigil||this.outcomePresenceOwner!==null||this.scheduledVisiting)}willUpdate(e){if(!this.isConnected)return;let t=this.look===null||e.has(`seed`);if(t)this.look=Uf(this.seed),this.rng=Z(this.seed^2654435769),this.motionRng=Z(this.seed^987138),this.visitRng=Z(this.seed^99282957),this.entranceRng=Z((this.seed^57978)>>>0),this.identity=gp(this.seed,this.look),this.look=this.identity.look,this.spotPct=this.look.spotPct,this.facing=this.look.facing,this.clearActTimers(),this.act=null,this.dismissed=!1,this.dismissMenuPosition=null,this.presence=`out`,this.molted=!1,this.shellVisible=!1,this.shellTimer!==null&&(window.clearTimeout(this.shellTimer),this.shellTimer=null),this.moltPlanned=up(this.seed)&&!this.identity.elder,this.twinPlanned=dp(this.seed),this.geometry.scheduleMeasure(),this.familiarity=td(),this.sailorDay=Gu(new Date),this.greetedThisLoad=!1,this.scheduleVisits(),this.traffic.reset(this.seed),this.vigil=!1,this.outcomePresenceOwner=null,this.trackVigil();else if(e.has(`mode`)){let t=e.get(`mode`)===`busy`&&this.mode===`idle`,n=t&&this.vigil?`vigil`:null;if(this.trackVigil(),this.presence===`in`&&!Q()){let e=cp(this.runOutcome);this.performAct(t?e:`startle`,n)}}(e.has(`visitsEnabled`)||e.has(`residentEnabled`))&&(this.visitsEnabled&&e.get(`visitsEnabled`)===!1&&(this.dismissed=!1,this.traffic.reset(this.seed)),!this.visitsEnabled||!this.residentEnabled?this.suspendResident():(e.get(`visitsEnabled`)===!1||e.get(`residentEnabled`)===!1)&&(this.scheduleVisits(),this.trackVigil()));let n=e.get(`critters`)??[],r=this.critters??[],i=e.has(`critters`)&&(n.length!==r.length||n.some((e,t)=>e!==r[t]));!t&&(e.has(`residentEnabled`)||i)&&(this.traffic.replanPasser(this.seed),this.geometry.scheduleMeasure()),this.residentEnabled&&!this.movingDayChecked&&this.gatewayVersion&&(this.movingDayChecked=!0,this.movingDay=yp(this.gatewayVersion)),this.toggleAttribute(`data-dex-complete`,(this.identity?.dexComplete??!1)&&this.visitsEnabled&&this.residentEnabled&&!this.dismissed),((!this.floorEnabled||!this.geometry.scene.floor)&&this.anchor===`floor`||this.travel&&this.travelScene!==this.geometry.scene)&&(this.clearActTimers(),this.act=null,this.anchor=`top`,this.restartPending=this.presence===`in`),this.setAttribute(`data-spot`,this.anchor),this.toggleAttribute(`data-floor-enabled`,this.floorEnabled),this.reconcilePresence()}reconcilePresence(){let e=this.wantsVisible();if(e&&this.presence!==`in`){this.leaveTimer!==null&&(window.clearTimeout(this.leaveTimer),this.leaveTimer=null),this.presence===`out`&&(this.rollPerch(),this.entrance=lp(this.entranceRng()),this.look&&(this.anniversary=rd(Yu().get(this.look.palette.id)?.firstSeenAt??null,new Date),Xu(this.look.palette.id,{name:this.identity?_p(this.identity,this.seed):Bf(this.look,this.seed),shiny:this.look.shiny}),$u())),this.presence=`in`,this.entering=!Q(),this.restartPending=!0;return}!e&&this.presence===`in`&&(this.dismissMenuPosition=null,this.outcomePresenceOwner=null,this.clearActTimers(),this.act=null,this.entering=!1,this.presence=`leaving`,this.leaveTimer=window.setTimeout(()=>{this.leaveTimer=null,this.presence=`out`},350))}updated(){this.isConnected&&this.restartPending&&(this.restartPending=!1,this.enterTimer=window.setTimeout(()=>{this.enterTimer=null,this.entering=!1,!this.greetedThisLoad&&(this.familiarity.tier===`friend`||this.identity?.oldFriend===!0)&&this.presence===`in`&&!Q()&&(this.greetedThisLoad=!0,this.performAct(`wave`))},wp[this.entrance]),this.scheduleNextAct())}trackVigil(){this.vigilTimer!==null&&(window.clearTimeout(this.vigilTimer),this.vigilTimer=null),this.mode===`busy`&&this.visitsEnabled&&this.residentEnabled&&!this.dismissed?this.vigilTimer=window.setTimeout(()=>{this.vigilTimer=null,this.vigil=!0,this.clearActTimers(),this.act=null},6e5):this.vigil=!1}dismiss(e){this.dismissMenuPosition=null,this.dismissed=!0,ed(),e&&(this.visitsEnabled=!1,ht({lobsterPetVisits:!1}),this.onVisitsDisabled())}clearActTimers(){this.travel=null;for(let e of[this.idleTimer,this.actEndTimer,this.enterTimer])e!==null&&window.clearTimeout(e);this.idleTimer=null,this.actEndTimer=null,this.enterTimer=null}clearVisitTimers(){for(let e of[this.visitTimer,this.leaveTimer])e!==null&&window.clearTimeout(e);this.visitTimer=null,this.leaveTimer=null}suspendResident(){this.clearActTimers(),this.clearVisitTimers(),this.interactions.suspend();for(let e of[this.shellTimer,this.vigilTimer])e!==null&&window.clearTimeout(e);this.shellTimer=null,this.vigilTimer=null,this.shellVisible=!1,this.vigil=!1,this.outcomePresenceOwner=null,this.dismissMenuPosition=null,this.scheduledVisiting=!1,this.presence=`out`,this.act=null,this.entering=!1,this.restartPending=!1}scheduleVisits(){if(this.clearVisitTimers(),this.scheduledVisiting=!1,!this.visitsEnabled||!this.residentEnabled||this.visitRng()<.5)return;let e=od[this.familiarity.tier];this.armArrival(Hf(this.visitRng,Ep[0],Ep[1])*e.firstDelayMul)}armArrival(e){this.isConnected&&this.visitsEnabled&&this.residentEnabled&&(this.visitTimer=window.setTimeout(()=>{this.visitTimer=null,this.scheduledVisiting=!0,this.armDeparture(Hf(this.visitRng,Dp[0],Dp[1])*od[this.familiarity.tier].stayMul)},e))}armDeparture(e){this.visitTimer=window.setTimeout(()=>{this.visitTimer=null,this.scheduledVisiting=!1;let e=od[this.familiarity.tier],t=this.familiarity.wary?od.waryGapMul:1;this.armArrival(Hf(this.visitRng,Op[0],Op[1])*e.gapMul*t)},e)}watchTraffic(e){this.presence===`in`&&this.act!==`scuttle`&&!this.vigil&&(this.facing=e)}reactToPasser(){let e=this.familiarity.tier===`friend`?`wave`:this.familiarity.tier===`shy`?`peek`:null;e===null||this.presence!==`in`||this.act!==null||this.vigil||this.mode!==`idle`||Q()||this.performAct(e)}rollPerch(){this.anchor=`top`,this.spotPct=Math.round(Hf(this.visitRng,12,88)),this.facing=this.visitRng()<.5?1:-1}scheduleNextAct(){if(!this.isConnected||!this.visitsEnabled||!this.residentEnabled||!this.look||this.presence!==`in`||this.vigil||this.traffic.passer!==null||this.idleTimer!==null||this.actEndTimer!==null||Q())return;let e=sp(this.mode,this.look.personality);if(!e)return;let t=Hf(this.rng,e.delayMs[0],e.delayMs[1]);this.idleTimer=window.setTimeout(()=>{this.idleTimer=null;let e=sp(this.mode,this.look?.personality??null);if(e&&!document.hidden&&this.presence===`in`&&this.traffic.passer===null){if(this.moltPlanned&&!this.molted&&this.mode===`idle`){this.performAct(`molt`);return}this.performAct(Vf(this.rng,e.acts))}},t)}performAct(e,t=null){if(!this.visitsEnabled||!this.residentEnabled||this.presence!==`in`)return;this.clearActTimers(),this.outcomePresenceOwner=t,this.entering=!1,e===`hop`?this.startFloorHop():e===`scuttle`&&this.applyMove(this.geometry.planWalk(this.anchor,this.spotPct,this.rng()));let n=this.travel?Pp(this.travel):xp[e];this.act=this.travel&&!this.travel.hop?`scuttle`:e,this.actEndTimer=window.setTimeout(()=>{if(this.actEndTimer=null,this.act=null,this.travel=null,e===`molt`&&this.completeMolt(),e===`droop`){this.performAct(`sweep`,t);return}this.outcomePresenceOwner=null,this.wantsVisible()&&this.scheduleNextAct()},n+(this.twinPlanned?180:0))}completeMolt(){this.molted=!0,this.look&&=(this.shellScale=this.look.scale,{...this.look,scale:this.look.scale<2?2:2.5}),this.shellSpotPct=this.spotPct,this.shellAnchor=this.anchor,this.shellVisible=!0,this.spotPct=Math.min(100,Math.max(0,this.spotPct+this.facing*9)),this.shellTimer!==null&&window.clearTimeout(this.shellTimer),this.shellTimer=window.setTimeout(()=>{this.shellTimer=null,this.shellVisible=!1},6e4)}applyMove(e){e&&(this.anchor=e.anchor,this.spotPct=e.spotPct,this.facing=e.facing,this.travel=e.travel,this.travelScene=this.geometry.scene)}startFloorHop(){!this.floorEnabled||this.identity?.elder||this.anchor===`top`&&this.motionRng()>=.45||this.applyMove(this.geometry.planHop(this.anchor,this.spotPct))}render(){let e=this.look;if(!e)return L;let t=this.identity,n=t?.elder?`old as the tides`:t?.oldFriend?`an old friend`:null;return[Wp({look:e,mode:this.mode,presence:this.presence,shellVisible:this.shellVisible&&(this.shellAnchor===`top`||this.floorEnabled&&this.geometry.scene.floor!==null),shellAnchor:this.shellAnchor,scene:this.geometry.scene,travel:this.travel,floorEnabled:this.floorEnabled,visitsEnabled:this.visitsEnabled,residentEnabled:this.residentEnabled,critterArtwork:this.critterArtwork,dismissed:this.dismissed,passer:this.traffic.passer?{kind:this.traffic.passer.kind,direction:this.traffic.passer.direction,crossMs:this.traffic.passerCrossMs(),anchor:this.passerAnchor,hops:this.passerHops}:null,twinPlanned:this.twinPlanned,anniversary:this.anniversary,entering:this.entering,entrance:this.entrance,grumpy:this.grumpy,vigil:this.vigil,elder:t?.elder??!1,act:this.act,spotPct:this.spotPct,facing:this.facing,anchor:this.anchor,shellScale:this.shellScale,shellSpotPct:this.shellSpotPct,familiarityVisits:this.familiarity.visits,seed:this.seed,movingDay:this.movingDay,sailorDay:this.sailorDay,nameOverride:t?_p(t,this.seed):null,flavor:n,bottle:this.traffic.bottle(),onPointerDown:this.interactions.handleHoldStart,onPointerUp:this.interactions.handleHoldEnd,onPointerCancel:this.interactions.handleHoldCancel,onContextMenu:this.openDismissMenu,onBottleOpen:this.traffic.openBottle}),hd({position:this.dismissMenuPosition,onDismiss:e=>this.dismiss(e),onClose:()=>{this.dismissMenuPosition=null}})]}},E([V({attribute:!1})],$.prototype,`seed`,void 0),E([V({attribute:!1})],$.prototype,`mode`,void 0),E([V({attribute:!1})],$.prototype,`visitsEnabled`,void 0),E([V({attribute:!1})],$.prototype,`residentEnabled`,void 0),E([V({attribute:!1})],$.prototype,`critters`,void 0),E([V({attribute:!1})],$.prototype,`critterArtwork`,void 0),E([V({attribute:!1})],$.prototype,`floorEnabled`,void 0),E([V({attribute:!1})],$.prototype,`runOutcome`,void 0),E([V({attribute:!1})],$.prototype,`soundsEnabled`,void 0),E([V({attribute:!1})],$.prototype,`gatewayVersion`,void 0),E([V({attribute:!1})],$.prototype,`onVisitsDisabled`,void 0),E([z()],$.prototype,`act`,void 0),E([z()],$.prototype,`spotPct`,void 0),E([z()],$.prototype,`facing`,void 0),E([z()],$.prototype,`entering`,void 0),E([z()],$.prototype,`entrance`,void 0),E([z()],$.prototype,`presence`,void 0),E([z()],$.prototype,`anchor`,void 0),E([z()],$.prototype,`scheduledVisiting`,void 0),E([z()],$.prototype,`dismissed`,void 0),E([z()],$.prototype,`dismissMenuPosition`,void 0),E([z()],$.prototype,`grumpy`,void 0),E([z()],$.prototype,`vigil`,void 0),E([z()],$.prototype,`outcomePresenceOwner`,void 0),E([z()],$.prototype,`movingDay`,void 0),E([z()],$.prototype,`anniversary`,void 0),E([z()],$.prototype,`shellVisible`,void 0),customElements.get(`openclaw-lobster-pet`)||customElements.define(`openclaw-lobster-pet`,$)})))()}function Qp(e,t){return I`
    <div class="callout danger new-session-page__error new-session-page__alert" role="alert">
      <span class="new-session-page__alert-icon" aria-hidden="true">${P.alertTriangle}</span>
      <span class="callout__content new-session-page__alert-message"
        >${pe(e)}</span
      >
      ${t?I`<button
              class="btn btn--sm"
              type="button"
              ?disabled=${t.disabled}
              @click=${t.onClick}
            >
              ${t.label}
            </button>`:L}
    </div>
  `}function $p(e){let{pendingMessage:t}=e,n=t?_n(t):null,r=ui(!0,n?.sender?e.userId:null),i=e.submitting&&!t;return I`
    <div class="sr-only" role="status" aria-live="polite">
      ${t?e.completion?.label??e.statusLabel??A(`newSession.starting`):L}
    </div>
    <div
      class="new-session-page__scroll ${t?`chat-thread ${r===`footer`?`chat-thread--direct`:``}`:``}"
      ?inert=${i}
      aria-busy=${String(e.submitting)}
      @mousedown=${Dt}
    >
      ${e.error?Qp(e.error,e.errorAction):L}
      ${t&&n?em(t,n,r,e.onOpenImage,e.statusLabel,e.completion):e.renderDraft()}
      ${t&&e.showDraft?e.renderDraft():L}
    </div>
  `}function em(e,t,n,r,i=A(`newSession.starting`),a){let o=`new-session-submission`,s=t.sender?rr(t.sender):null,{images:c,attachments:l}=Mi(e,t.content),u=Ca(l),d=ir(e,t),f=Cr(d),p={onOpenImage:r};return I`<div class="new-session-page__starting chat-thread-inner">
    <div
      class="chat-group user ${t.sender?`chat-group--with-footer`:``} ${s===null?``:`chat-group--sender-tint`}"
      style=${s===null?L:`--chat-sender-hue: ${s}`}
      data-chat-row-key=${o}
    >
      ${t.sender&&n===`gutter`?di(Ir(t.sender),ln(t.sender)??``):L}
      <div class="chat-group-messages">
        <div
          class="chat-bubble ${c.length||u?`chat-bubble--with-images`:``} ${u?`chat-bubble--with-files`:``}"
          data-message-id=${o}
          data-message-text=${d||L}
        >
          ${la(c,p)}
          ${da(l,p,void 0,void 0,!1)}
          ${f?ga(f,o,{role:`user`,isStreaming:!1},{codeBlockChrome:`none`}):d?Pa(d,o,{role:`user`,isStreaming:!1},{codeBlockChrome:`none`}):L}
        </div>
      </div>
      ${t.sender&&n===`footer`?I`<div class="chat-group-footer">
              <div class="chat-group-footer__meta">
                ${Bi(t.sender)}
              </div>
            </div>`:L}
    </div>
    <div class="chat-group assistant chat-group--working">
      <div class="chat-group-messages">
        ${a?I`<div class="callout" role="status">
                <span class="callout__content">${a.label}</span>
                ${a.onOpen?I`<button
                        class="btn btn--sm"
                        type="button"
                        ?disabled=${a.disabled}
                        @click=${a.onOpen}
                      >
                        ${A(`sessionsView.openSession`)}
                      </button>`:L}
              </div>`:Ta({kind:`reading-indicator`,key:o,startedAt:e.timestamp},{startupLabel:i})}
      </div>
    </div>
  </div>`}function tm(){return(tm=e((()=>{R(),jt(),F(),wr(),Sr(),M(),H(),Zn(),pn(),An(),He(),Tn(),Fa(),va(),ra(),Ai(),na(),Ci(),U()})))()}var nm;function rm(){return(rm=e((()=>{R(),Ct(),M(),H(),mi(),ri(),Zi(),U(),nm=class{constructor(e){this.options=e,this.dictation=null,this.owner=null,this.devicePicker=new Ki(e.requestUpdate)}dispose(){this.owner=null,this.dictation?.dispose(),this.dictation=null,this.devicePicker.dispose()}get active(){return this.dictation?.active===!0}previewDraft(){let e=this.dictation;return e?.active?this.options.textarea.previewTranscript(e.transcript):void 0}renderStatus(){return wa(this.dictation??void 0)}render(e,t){this.owner?.key!==e&&(this.owner={key:e},this.dictation?.dispose(),this.dictation=null);let n=this.owner,r=()=>this.owner===n,i=this.options.getClient(),a=this.options.isConnected()&&i!==null;this.devicePicker.syncCatalog(i,a);let o=this.options.canCommit(),s={client:i,connected:a,enabled:o,dictationAvailable:this.devicePicker.dictationStatus===`ready`,realtimeTalkActive:!1,onCommit:(e,t)=>{if(!r()||!this.options.canCommit())return;let n=this.options.textarea.insertTranscript(e,t);n!==null&&this.options.onMessage(n),this.options.requestUpdate()},onError:e=>{r()&&this.options.onError(e)},onStateChange:()=>{r()&&this.options.requestUpdate()},onDictationUnavailable:this.devicePicker.handleOpen};this.dictation??=new Fi(s),this.dictation.update(s);let c=this.dictation;return I`
      ${bi({connected:a,sending:!1,isBusy:!o,dictation:c,idleLabel:A(`newSession.dictate`),microphonePicker:Yi({devices:this.devicePicker.devices,loading:this.devicePicker.loading,open:this.devicePicker.open,selectedDeviceId:t?.trim()??``,voiceActive:!1,issue:this.devicePicker.issue,showRealtimeCapability:!1,realtimeStatus:this.devicePicker.realtimeStatus,dictationStatus:this.devicePicker.dictationStatus,onOpen:this.devicePicker.handleOpen,onClose:this.devicePicker.handleClose,onSelect:e=>{ht({realtimeTalkInputDeviceId:e.trim()||void 0}),this.devicePicker.handleClose()}}),onDirectDictationStart:()=>this.options.textarea.captureSelection()})}
      ${Si(c,()=>{r()&&this.options.canCommit()&&this.options.onSubmit()})}
    `}}})))()}var im=t({activateDraft:()=>sm,restoreDraft:()=>om,restoreDraftOwner:()=>cm,retainDraft:()=>am});function am(e,t,n,r){t.draftPersistence.persistNow();let i=e?.gateway.snapshot.client;if(!e||!i||t.submitting||t.pendingPlacement.sessionKey)return;let a=n??uo(window.location.search);e.chatAttachmentHandoff.prepare({reviewPrivateDraft:ua,owner:i,paneId:lm,scopeKey:a,message:r===a?t.message:``,mentions:r===a?t.mentions:void 0,newSessionDraft:t.draftPersistence.captureSubmission(),attachments:t.attachmentDraft.take(),fallbacks:{}})}function om(e,t,n,r,i){let a=e?.gateway.snapshot.client;e&&a?.recoveryScopeReady&&t.draftPersistence.setOwner(e.gateway.connection.gatewayUrl,a.recoveryScope,!0),t.draftPersistence.selectRoute(n);let o=e&&a?e.chatAttachmentHandoff.consume({owner:a,paneId:lm,scopeKey:n}):null;return o?(t.restoreDraftState({message:r||o.message||``,mentions:r?i:o.mentions,attachments:o.attachments,visibility:o.newSessionDraft?.incognito?`incognito`:t.visibility}),!r&&o.newSessionDraft&&t.draftPersistence.adoptHandoff(o.newSessionDraft)):r&&t.restoreMessage(r,i),sm(t,n),n}function sm(e,t){e.pendingPlacement.sessionKey||e.draftPersistence.activateRoute(t)}function cm(e,t,n){e.restorePendingPlacementRecovery(t,n),e.draftPersistence.setOwner(t,n,!!e.pendingPlacement.sessionKey)}var lm;function um(){return(um=e((()=>{_a(),q(),lm=`new-session-draft`})))()}function dm(e,t){return e?.client===t?.client&&e?.agentId===t?.agentId&&e?.ownerKey===t?.ownerKey&&e?.message===t?.message&&e?.model===t?.model}var fm;function pm(){return(pm=e((()=>{on(),q(),fm=class{constructor(e,t){this.read=t,this.current=null,this.title=null,this.active=!1,this.pending=!1,this.readyAt=0,this.connected=!1,this.composing=!1,this.submitted=null,e.addController(this)}hostConnected(){this.connected=!0}hostUpdated(){this.sync(this.input())}hostDisconnected(){this.connected=!1,this.sync(null),this.submitted=null}setComposing(e){this.composing=e,this.hostUpdated()}takePreparedTitle(){let e=this.input(),t=dm(this.current,e)?this.title??void 0:void 0;return this.submitted=e??this.submitted,this.sync(null),t}sync(e){let t=e?.message.trim()??``,n=e&&t.length>=12&&!t.startsWith(`/`)?{...e,message:t}:null;dm(this.current,n)||(clearTimeout(this.timer),this.current=n,this.title=null,this.pending=n!==null,this.readyAt=Date.now()+1e3,this.schedule())}schedule(){this.pending&&!this.active&&(this.timer=setTimeout(()=>void this.prepare(),Math.max(0,this.readyAt-Date.now())))}async prepare(){let e=this.current;if(e&&this.pending){this.pending=!1,this.active=!0;try{let t=await e.client.request(`sessions.title.prepare`,{agentId:e.agentId,message:u(e.message,1e3),...e.model?{model:e.model}:{}},{timeoutMs:2e4});this.current===e&&(this.title=t.title)}catch{}finally{this.active=!1,this.schedule()}}}input(){let{context:e,data:t,place:n,submission:r,dictating:i}=this.read(),a=e?.gateway.snapshot;if(!this.connected||K(t)||this.composing||i||r.submitting||r.visibility===`incognito`||r.pendingPlacement.sessionKey||!n.agentId||!n.modelControl.accountSelectionReady()||!rn(a,`sessions.title.prepare`,`operator.write`)||!a?.client)return null;let o={client:a.client,ownerKey:lo(t),agentId:n.agentId,message:r.message.trim(),model:n.modelControl.modelForSubmission()};return dm(o,this.submitted)?null:o}}})))()}function mm(e){let t=e.visibility===`draft`,n=e.submitting||e.messageLocked,r=A(`newSession.draft`);return I`
    <button
      type="button"
      class="new-session-page__visibility new-session-page__visibility--draft ${t?`new-session-page__visibility--active`:``}"
      role="switch"
      aria-label=${r}
      aria-checked=${String(t)}
      ?disabled=${n}
      title=${A(`newSession.draftDescription`)}
      @click=${()=>e.onVisibilityChange?.(t?`normal`:`draft`)}
    >
      <span class="new-session-page__visibility-icon" aria-hidden="true">${P.pencil}</span>
      <span class="new-session-page__visibility-label">${r}</span>
    </button>
  `}function hm(e,t){let n=e.visibility===`draft`,r=e.submitting||e.messageLocked===!0,i=e.textareaController;return Ti({attachments:t,capabilityMenu:e.capabilityMenu,disabled:r,open:i.capabilityMenuOpen,view:i.capabilityMenuView,toolOverrides:e.toolOverrides,rootToggles:e.draftAvailable?[{value:`new-session-draft`,label:A(`newSession.draft`),icon:P.pencil,checked:n,disabled:r,title:A(`newSession.draftDescription`),onChange:t=>e.onVisibilityChange?.(t?`draft`:`normal`)}]:void 0,onOpenChange:t=>{i.capabilityMenuOpen=t,t||(i.capabilityMenuView=`root`),e.requestUpdate()},onViewChange:t=>{i.capabilityMenuView=t,e.requestUpdate()}})}function gm(e){let t=Rn(e.toolOverrides);if(t===0)return L;let n=e.submitting||e.messageLocked===!0;return I`
    <button
      type="button"
      class="new-session-page__selection-status"
      ?disabled=${n}
      @click=${()=>{e.textareaController.capabilityMenuView=`root`,e.textareaController.capabilityMenuOpen=!0,e.requestUpdate()}}
    >
      ${A(t===1?`chat.composer.overrides.countOne`:`chat.composer.overrides.count`,{count:String(t)})}
    </button>
  `}function _m(){return(_m=e((()=>{R(),F(),M(),H(),vi(),U()})))()}function vm(e){e.textareaController.emojiMenu.close(),e.textareaController.mentionMenu.close(),hi(e.textareaController.skillMenuState),za(e.textareaController.slashMenuState),e.onSubmit()}function ym(e){let t=e.submitting?A(`newSession.starting`):A(e.nativeTerminal?`newSession.startInTerminal`:`newSession.start`),n=!e.canSubmit&&e.submitDisabledReason!==void 0,r=e.submitting||e.pendingAttachmentReads>0;return I` <openclaw-tooltip content=${e.submitDisabledReason??t}>
    <button
      type="button"
      class="chat-send-btn new-session-page__start-submit ${n?`new-session-page__start-submit--blocked`:``} ${r?`new-session-page__start-submit--busy`:``}"
      ?disabled=${!e.canSubmit&&!n}
      aria-disabled=${String(!e.canSubmit)}
      aria-busy=${String(r)}
      aria-label=${t}
      @click=${()=>vm(e)}
    >
      ${r?P.loader:e.nativeTerminal?P.squareTerminal:P.arrowUp}
    </button>
  </openclaw-tooltip>`}function bm(e,t,n,r,i){if(t.dictationActive||t.submitting||t.messageLocked||t.textareaController.composing||e.isComposing||e.keyCode===229||t.textareaController.emojiMenu.handleKeydown(e,`new-session`,t.requestUpdate)||t.textareaController.mentionMenu.handleKeydown(e,i,t.requestUpdate)||_i(e,t.textareaController.skillMenuState,n,t.requestUpdate)||yi(e,t.textareaController.slashMenuState,r,t.requestUpdate)||e.key!==`Enter`)return;let a=e.metaKey||e.ctrlKey,o=t.requiresModifier?a&&e.shiftKey:a&&!e.shiftKey;if(!e.altKey&&o&&t.onBackgroundSubmit){if(e.repeat){e.preventDefault();return}(t.canSubmit||t.submitDisabledReason!==void 0)&&(e.preventDefault(),hi(t.textareaController.skillMenuState),za(t.textareaController.slashMenuState),t.textareaController.mentionMenu.close(),t.onBackgroundSubmit());return}if(!(e.shiftKey||t.requiresModifier&&!a)){if(e.repeat){e.preventDefault();return}(t.canSubmit||t.submitDisabledReason!==void 0)&&(e.preventDefault(),vm(t))}}function xm(e){let t=e.textareaController.skillMenuState,n=e.textareaController.slashMenuState,r=e.textareaController.mentionMenu,i=e.textareaController.emojiMenu,a=e.submitting||e.messageLocked===!0||e.dictationActive===!0;r.syncDirectory(e.submitting||e.messageLocked||e.dictationActive?void 0:e.mentionDirectory);let o={paneId:`new-session`,getDraft:()=>e.textareaController.getTextarea()?.value??e.message,commitDraft:e.onInput,getTextarea:e.textareaController.getTextarea,refreshCommands:e.refreshCommands},s={...o,resolveArgOptions:e=>e.argOptions??[],runCommand:()=>vm(e),canRun:e=>!e,commandFilter:e=>e.executeLocal!==!0},c={paneId:o.paneId,getDraft:o.getDraft,getTextarea:o.getTextarea,getMentions:()=>e.getMentions?.()??e.mentions??[],commitDraft:e.onInput},l=o=>{i.update(o,e.requestUpdate,!a&&!e.nativeTerminal&&!e.textareaController.composing&&!t.skillMenuOpen&&!n.slashMenuOpen&&!r.open)},u=(a,c)=>{if(e.nativeTerminal||e.textareaController.composing||c?.isComposing){i.close();return}li(a.value,n,s,e.requestUpdate),wi(a.value,a.selectionStart,t,o,e.requestUpdate),c?.inputType===`insertFromPaste`||c?.inputType===`insertFromDrop`?r.close():r.update(a,e.requestUpdate,c?c.inputType===`insertText`&&c.data?.includes(`@`)===!0?`trigger`:`input`:`selection`),l(a)},d=t=>{let n=t.currentTarget;n instanceof HTMLTextAreaElement&&(t.type===`keyup`?(r.update(n,e.requestUpdate),l(n)):u(n))};(a||e.nativeTerminal||e.textareaController.composing)&&i.close();let f={attachmentReads:e.attachmentReads,attachmentLimits:e.attachmentLimits,uploadConfig:e.uploadConfig,attachments:e.attachments,get disabled(){return e.submitting||e.messageLocked===!0||e.dictationActive===!0},getAttachments:e.getAttachments,draft:e.message,getDraft:()=>e.message,onAttachmentsChange:e.onAttachmentsChange,onDraftChange:e.onInput,onPendingReadsChange:e.onPendingReadsChange,onOpenImage:e.onOpenImage,onOpenSidebar:e.onOpenSidebar,readSignal:e.readSignal},p=pa({...f,canCompose:!a&&!e.nativeTerminal}),m=e.dictationPreview??e.message;e.textareaController.syncDraft(m);let h=A(e.nativeTerminal?`newSession.nativeTerminalPrompt`:`newSession.messagePlaceholder`),g=e.dictationActive?``:e.textareaController.getPlaceholder(h,e.message,e.requestUpdate),{skillMenuVisible:_,slashMenuVisible:v,menuVisible:y,menuListboxId:b,activeMenuOptionId:x,activeMenuOptionLabel:S}=Wi(o.paneId,!e.nativeTerminal&&!a,t,n,r,i),C=Ma(o.paneId,`active-menu-announcement`),w=e.requiresModifier?`Control+Enter Meta+Enter`:`Enter`,T=e.requiresModifier?`Control+Shift+Enter Meta+Shift+Enter`:`Control+Enter Meta+Enter`,ee=e.onBackgroundSubmit?`${w} ${T}`:w;return I`
    <div
      class="agent-chat__composer-shell new-session-page__composer"
      @drop=${t=>{e.nativeTerminal&&t.dataTransfer?.files.length?(t.preventDefault(),e.onUnsupportedAttachment?.()):p.onDrop(t)}}
      @dragenter=${p.onDragenter}
      @dragleave=${p.onDragleave}
      @dragover=${p.onDragover}
    >
      <div
        class="agent-chat__input agent-chat__input--mobile-toolbar${e.dictationActive?` agent-chat__input--dictating`:``}"
        @openclaw-composer-dismiss-invocations=${()=>{r.close(),i.dismiss(e.textareaController.getTextarea()),e.requestUpdate()}}
      >
        ${e.renderCritters(!a&&m.length===0&&e.attachments.length===0&&e.pendingAttachmentReads===0&&!y&&!e.textareaController.capabilityMenuOpen)}
        ${r.render(c,e.requestUpdate)}
        ${i.render(`new-session`,e.textareaController.getTextarea(),e.requestUpdate)}
        ${e.nativeTerminal?L:Ia(f)}
        ${fi(e.message,e.mentions,()=>e.onInput(e.message,[]),r.selectedAvatarUrls)}
        ${ka(f)}
        ${ta(e.pendingAttachmentReads)}
        <div class="agent-chat__composer-lede">${e.dictationStatus??L}</div>
        <div class="agent-chat__composer-input-row">
          <div class="agent-chat__composer-combobox">
            ${v?Ri(n,s,e.message,e.requestUpdate):L}
            ${_?Gi(t,o,e.requestUpdate):L}
            <textarea
              ${zt(e.textareaController.ref)}
              class="new-session-page__message"
              rows="1"
              ?autofocus=${globalThis.matchMedia?.(`(max-width: 560px)`)?.matches??!1}
              ?disabled=${e.submitting||e.messageLocked}
              ?readonly=${e.dictationActive}
              placeholder=${g}
              aria-label=${h}
              aria-keyshortcuts=${ee}
              .value=${Ut([m],()=>Kt(m))}
              aria-autocomplete="list"
              aria-controls=${Vt(y?b:void 0)}
              aria-haspopup=${Vt(y?`listbox`:void 0)}
              aria-activedescendant=${Vt(x??void 0)}
              aria-describedby=${C}
              @input=${t=>{if(e.dictationActive)return;let n=t.target;Qi(n);let r=c.getMentions();e.onInput(n.value,r.length?Yn(e.message,n.value,r,e.textareaController.mentionInput):void 0),e.textareaController.mentionInput=void 0,u(n,t)}}
              @beforeinput=${t=>{let n=t.target;e.textareaController.mentionInput={value:n.value,start:n.selectionStart,end:n.selectionEnd,inputType:t.inputType},i.complete(t,e.requestUpdate,!a&&!e.nativeTerminal&&!e.textareaController.composing)}}
              @select=${d}
              @focus=${d}
              @pointerup=${d}
              @keyup=${e=>{i.handleKeyup(e),(e.key.startsWith(`Arrow`)||e.key===`Home`||e.key===`End`)&&d(e)}}
              @blur=${()=>{let t=i.open;e.textareaController.composing=!1,i.close(),t&&e.requestUpdate()}}
              @compositionend=${t=>{e.textareaController.composing=!1,t.target instanceof HTMLTextAreaElement&&u(t.target)}}
              @keydown=${t=>bm(t,e,o,s,c)}
              @compositionstart=${()=>{e.textareaController.composing=!0,i.close(),r.close(),e.requestUpdate()}}
              @paste=${t=>{e.nativeTerminal&&t.clipboardData?.files.length?(t.preventDefault(),e.onUnsupportedAttachment?.()):!a&&!e.nativeTerminal&&ea(t,f)}}
            ></textarea>
            <span class="agent-chat__composer-placeholder" aria-hidden="true"
              >${g}</span
            >
            <span
              id=${C}
              class="sr-only"
              role="status"
              aria-live="polite"
              aria-atomic="true"
              >${S}</span
            >
          </div>
        </div>
        <div class="agent-chat__composer-footer">
          <div class="agent-chat__composer-lead">
            ${e.nativeTerminal?L:hm(e,f)}
            ${e.permissionControl??L}
            ${!e.nativeTerminal&&e.draftAvailable?mm(e):L}
            ${e.nativeTerminal?L:gm(e)}
          </div>
          <div class="agent-chat__composer-trail">
            <div class="agent-chat__composer-controls">
              ${e.modelControl&&e.modelControl!==L?I`<div class="chat-composer-model-control">${e.modelControl}</div>`:L}
            </div>
            <div class="agent-chat__composer-actions">
              ${e.voiceControl??L}${e.dictationActive?L:ym(e)}
            </div>
          </div>
        </div>
      </div>
      ${e.blockedSubmitNotice?I`<div
              class="new-session-page__blocked-submit agent-chat__composer-status"
              data-tone="info"
              role="status"
            >
              <div class="agent-chat__composer-status-band">
                <span class="agent-chat__composer-status-icon" aria-hidden="true"
                  >${P.info}</span
                >
                <span class="agent-chat__composer-status-text">${e.blockedSubmitNotice}</span>
              </div>
            </div>`:L}
    </div>
  `}function Sm(){return(Sm=e((()=>{R(),Jt(),Rt(),Wt(),Bt(),F(),M(),H(),dn(),Ft(),Li(),xa(),ii(),Vi(),Pi(),Hi(),Oi(),_m(),U()})))()}function Cm(e,t,n){let r=e.worktree&&!qc(e.worktreeName),i=t.capabilities;return I`
    ${r?Qp(A(`newSession.worktreeNameInvalid`)):L}
    ${n&&i.toolOverrides?Qp(A(`newSession.terminalCapabilityOverridesUnsupported`),{label:A(`common.reset`),onClick:()=>i.setToolOverrides(null)}):L}
    ${t.submissionOutcomeUnknown?Qp(A(t.submissionOutcomeUnknown===`gateway-changed`?`newSession.createOutcomeUnknown`:`newSession.placementSetupInterrupted`),t.pendingPlacement.sessionKey?{label:A(`common.reset`),onClick:()=>t.clearPendingPlacementRecovery()}:void 0):L}
  `}function wm(e){let t=e.attachmentDraft.readSignal,n=e.nativeTerminal?null:e.context?.gateway.snapshot.client??null,r=e.context?.gateway,i=mu(e);return e.textareaController.syncSkillCommandOwner(n,e.agentId,e.draftOwnerKey),xm({...e,renderCritters:t=>I`<openclaw-lobster-pet
      .seed=${ud(`${e.textareaController.critterVisit}:${e.draftOwnerKey}`)}
      .mode=${fd(!r?.snapshot.offlineStable,e.context?.sessions.state.result?.sessions)}
      .runOutcome=${dd(e.context?.sessions.state.result?.sessions)}
      .visitsEnabled=${e.context?.theme.settings.lobsterPetVisits!==!1}
      .residentEnabled=${e.context?.theme.branding.mascot!==`none`}
      .critters=${e.context?.theme.branding.critters}
      .critterArtwork=${e.context?.theme.branding.artwork?.critters}
      .soundsEnabled=${e.context?.theme.settings.lobsterPetSounds===!0}
      .gatewayVersion=${e.context?.config.current.serverVersion??r?.snapshot.hello?.server?.version??null}
      .onVisitsDisabled=${()=>e.context?.theme.refresh()}
      .floorEnabled=${t}
    ></openclaw-lobster-pet>`,uploadConfig:e.context?.config,attachmentLimits:ci(e.context?.gateway.snapshot.hello?.policy),attachments:e.attachmentDraft.attachments,getAttachments:()=>e.attachmentDraft.attachments,get message(){return e.message},mentionDirectory:i,modelControl:e.isCatalogTarget?L:e.modelControl.render({agent:e.agent,agentId:e.agentId,context:e.context,sending:e.submitting}),pendingAttachmentReads:e.attachmentDraft.pendingReads,attachmentReads:e.attachmentDraft.reads,readSignal:t,refreshCommands:n?()=>ti({client:n,agentId:e.agentId,shouldApply:()=>e.textareaController.ownsSkillCommands(n,e.agentId,e.draftOwnerKey)}):void 0,get dictationActive(){return e.dictationActive},get submitting(){return e.submitting},get messageLocked(){return e.messageLocked},onAttachmentsChange:t=>{!e.submitting&&!e.messageLocked&&e.attachmentDraft.replace(t)},onPendingReadsChange:n=>e.attachmentDraft.updatePending(t,n)})}function Tm(){return(Tm=e((()=>{R(),md(),M(),H(),Zr(),La(),Sm(),Xc(),tm(),hu(),U()})))()}function Em(e,t){let n=e.visibility===`incognito`,r=e.visibility===`draft`,i=e.incognitoDisabledReason(),a=e.submitting||!!e.pendingPlacement.sessionKey||!!i,o=i??A(`newSession.incognitoDescription`);return I`
    <div class="new-session-page__incognito-rail">
      ${t?I`
              <openclaw-tooltip
                class="new-session-page__draft-tooltip"
                .content=${A(`newSession.draftDescription`)}
              >
                <button
                  type="button"
                  class="shell-chrome-controls__button new-session-page__draft-toggle ${r?`new-session-page__draft-toggle--active`:``}"
                  role="switch"
                  aria-label=${`${A(`newSession.draft`)}: ${A(`newSession.draftDescription`)}`}
                  aria-checked=${String(r)}
                  ?disabled=${e.submitting||!!e.pendingPlacement.sessionKey}
                  title=${A(`newSession.draftDescription`)}
                  @click=${()=>e.setVisibility(r?`normal`:`draft`)}
                >
                  ${P.pencil}
                  ${r?I`<span class="new-session-page__draft-toggle-label"
                          >${A(`newSession.draft`)}</span
                        >`:L}
                </button>
              </openclaw-tooltip>
            `:L}
      <openclaw-tooltip .content=${o}>
        <button
          type="button"
          class="shell-chrome-controls__button new-session-page__incognito-toggle ${n?`new-session-page__incognito-toggle--active`:``}"
          role="switch"
          aria-label=${A(`newSession.incognito`)}
          aria-checked=${String(n)}
          ?disabled=${a}
          title=${o}
          @click=${()=>{a||e.setVisibility(n?`normal`:`incognito`)}}
        >
          ${Om}
        </button>
      </openclaw-tooltip>
    </div>
  `}function Dm(e){let t=A(`newSession.incognitoDescription`);return I`
    <div
      class="new-session-page__incognito-notice ${e?`new-session-page__incognito-notice--visible`:``}"
      role="status"
      aria-hidden=${String(!e)}
    >
      <span class="new-session-page__incognito-notice-icon" aria-hidden="true">
        ${Om}
      </span>
      <span>${t}</span>
    </div>
  `}var Om;function km(){return(km=e((()=>{R(),mt(),F(),Ft(),M(),H(),U(),Om=N(B` <path
    d="M4 13V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.706.706l3.588 3.588A2.4 2.4 0 0 1 20 8v5"
  />
  <path d="M14 2v5a1 1 0 0 0 1 1h5" />
  <path d="M10 22v-5" />
  <path d="M14 19v-2" />
  <path d="M18 20v-3" />
  <path d="M2 13h20" />
  <path d="M6 20v-3" />`)})))()}function Am(e){let{context:t,gateway:n,place:r,submission:i,dictation:a,titlePreparation:o,draftOwnerKey:s,isCatalogTarget:c,renderTargetBar:l,requestUpdate:u,onMessage:d,onOpenImage:f}=e,p=i.capabilities,m=t?.theme.settings,h=a.render(s,m?.realtimeTalkInputDeviceId),g=a.active;return I`
    <div
      class="new-session-page__draft"
      aria-busy=${String(i.submitting)}
      @compositionstart=${()=>{o.setComposing(!0)}}
      @compositionend=${()=>{o.setComposing(!1)}}
      @focusout=${()=>{o.setComposing(!1)}}
    >
      ${l()} ${Cm(r,i,c)}
      ${wm({agent:r.selectedAgent(),agentId:r.agentId,attachmentDraft:i.attachmentDraft,canSubmit:!i.submitting&&!g&&i.canSubmit(),submitDisabledReason:i.submitDisabledReason(),blockedSubmitNotice:i.blockedSubmitNotice(),get dictationActive(){return a.active},dictationPreview:a.previewDraft(),dictationStatus:a.renderStatus(),context:t,isCatalogTarget:c,draftOwnerKey:s,get message(){return i.message},mentions:i.mentions,getMentions:()=>i.mentions,visibility:i.visibility,draftAvailable:p.canStartAsDraft(t),...p.composerProps(t,n,r.agentId),modelControl:r.modelControl,permissionControl:c?void 0:ji({canSelectFull:r.isAdmin(),defaultMode:r.selectedAgent()?.defaultPermissionMode,disabled:i.submitting||!!i.pendingPlacement.sessionKey,disabledReason:i.submitting?A(`newSession.starting`):void 0,mode:i.permission.value,onSelect:e=>i.permission.set(e??void 0)}),requiresModifier:m?.chatSendShortcut===`modifier-enter`,requestUpdate:u,get submitting(){return i.submitting},textareaController:i.composerTextarea,voiceControl:h,get messageLocked(){return!!i.pendingPlacement.sessionKey},nativeTerminal:c,onUnsupportedAttachment:()=>i.setError(A(`newSession.terminalAttachmentsUnsupported`)),onInput:d,onOpenImage:f,onOpenSidebar:e.onOpenSidebar,onVisibilityChange:e=>{!i.submitting&&!i.pendingPlacement.sessionKey&&i.setVisibility(e)},onSubmit:()=>void i.submit(),onBackgroundSubmit:i.visibility===`draft`||c?void 0:()=>void i.submit(void 0,!0)})}
      ${c?L:Dm(i.visibility===`incognito`)}
    </div>
  `}function jm(){return(jm=e((()=>{R(),M(),H(),ki(),Tm(),km(),U()})))()}var Mm,Nm,Pm,Fm,Im,Lm;function Rm(){return(Rm=e((()=>{a(),R(),Gt(),Ot(),It(),nt(),xt(),M(),H(),Se(),me(),Vr(),Fe(),j(),ze(),Pe(),Wr(),ni(),zi(),ma(),ha(),q(),rm(),ro(),tm(),pu(),um(),pm(),jm(),km(),Al(),du(),Uu(),i(),U(),{activateDraft:Mm,restoreDraft:Nm,restoreDraftOwner:Pm,retainDraft:Fm}=im,Im={tagName:`openclaw-chat-detail-panel`,get label(){return A(`chat.attachments.pastedText`)},loadModule:async()=>{await O(()=>import(`./sidebar-DMrsq_Hl.js`),__vite__mapDeps([19,4,5,6,7,8,9,10,11,12,13,2,15,16,17,14]),import.meta.url),await O(()=>import(`./chat-detail-panel-dVq3CZO7.js`),__vite__mapDeps([20,4,5,6,7,8,9,10,12,13,11,2,14,17,15,16]),import.meta.url)}},Lm=class extends Je{constructor(){super(),this.retainedForHandoff=null,this.openedFor=null,this.critterImport=he(()=>O(()=>import(`./lobster-pet.runtime-CcS_o7AM.js`),[],import.meta.url)),this.openedGroupDefaults=``,this.openedAgentId=``,this.messageOwnerKey=``,this.attachmentPanel=null,this.attachmentPanelLoader=new ft(this),this.closeAttachmentPanel=()=>{this.attachmentPanel=null},this.openAttachmentPanel=e=>{e.kind===`attachment`&&(this.attachmentPanel={content:e,ownerKey:this.routeOwnerKey(),agentId:this.place.agentId})},this.imageLightbox=null,this.agentPickerOpen=!1,this.groupRouteRevalidation=new Eo(()=>this.data,()=>this.context?.revalidate(`new-session`)),this.titlePreparation=new fm(this,()=>({context:this.context,data:this.data,place:this.place,submission:this.submission,dictating:this.dictation.active})),this.flushDraft=()=>this.submission.draftPersistence.persistNow(),this.setImageLightbox=e=>{this.imageLightbox=e},this.draft=new fu(this,()=>({context:this.context,data:this.data,isConnected:this.isConnected}),{requestUpdate:()=>this.requestUpdate(),querySelector:e=>this.querySelector(e),activeElement:()=>this.ownerDocument.activeElement,body:()=>this.ownerDocument.body,onInvalidate:()=>{this.closeAttachmentPanel(),this.connectMachine?.close()},onRecoveryReady:(e,t)=>Pm(this.submission,e,t),closeTransientUi:()=>{this.closeAttachmentPanel(),lu(this)},takePreparedTitle:()=>this.titlePreparation.takePreparedTitle(),retainForHandoff:()=>{if(!this.data||!this.isConnected)return;let e={};return this.retainedForHandoff=e,{page:this,data:this.data,synchronizeGateway:()=>{this.context&&this.gateway.synchronize(this.context.gateway)},release:()=>{this.retainedForHandoff===e&&(this.retainedForHandoff=null,this.isConnected||this.disposeDraft())}}}}),this.gateway=this.draft.gateway,this.browser=this.draft.browser,this.place=this.draft.place,this.submission=this.draft.submission,this.connectMachine=new no(()=>({client:this.gateway.client,connected:this.gateway.connected}),()=>this.requestUpdate()),this.dictation=new nm({textarea:this.submission.composerTextarea,getClient:()=>this.gateway.client,isConnected:()=>this.gateway.connected,canCommit:()=>!this.submission.submitting&&!this.submission.pendingPlacement.sessionKey,onMessage:e=>this.setMessageFromUser(e),onError:e=>this.submission.setError(e),onSubmit:()=>void this.submission.submit(),requestUpdate:()=>this.requestUpdate()}),this.subscriptions=new qe(this).effect(()=>this.ownerDocument,si).watch(()=>this.context?.theme,(e,t)=>e.subscribe(t)).watch(()=>this.context?.agents,(e,t)=>e.subscribe(t)).watch(()=>this.context?.agentIdentity,(e,t)=>e.subscribe(t)).watch(()=>this.context?.sessions,(e,t)=>e.subscribe(t),e=>this.groupRouteRevalidation.synchronize(e)).watch(()=>this.context?.placementStartup,(e,t)=>e.subscribe(t)).watch(()=>this.context?.runtimeConfig,(e,t)=>e.subscribe(t)).watch(()=>this.context?.config,(e,t)=>e.subscribe(()=>t()))}handleEvent(e){e instanceof KeyboardEvent&&Qr(this,e)}focusComposer(){let e=this.context,t=this.routeOwnerKey(),n=document.activeElement;this.updateComplete.then(()=>{this.isConnected&&!this.retainedForHandoff&&this.context===e&&this.routeOwnerKey()===t&&(document.activeElement===n||document.activeElement===document.body)&&!document.openClawModalLayers?.size&&this.submission.composerTextarea.getTextarea()?.focus({preventScroll:!0})})}connectedCallback(){super.connectedCallback(),this.submission.draftPersistence.connect(),this.critterImport.schedule(),document.addEventListener(`keydown`,this,!0),window.addEventListener(`beforeunload`,this.flushDraft)}disconnectedCallback(){this.closeAttachmentPanel(),this.attachmentPanelLoader.requestWhileActive(Im,!1),this.critterImport.dispose(),document.removeEventListener(`keydown`,this,!0),window.removeEventListener(`beforeunload`,this.flushDraft),this.subscriptions.clear(),this.dictation.dispose(),this.connectMachine.close(),this.retainedForHandoff||this.disposeDraft(),super.disconnectedCallback()}disposeDraft(){Tl(this.data,this),Fm(this.context,this.submission,this.openedFor,this.messageOwnerKey),this.draft.disconnect()}willUpdate(){let e=this.attachmentPanel;e&&(e.ownerKey!==this.routeOwnerKey()||e.agentId!==this.place.agentId||this.submission.submitting||this.submission.pendingPlacement.sessionKey||!this.submission.attachmentDraft.attachments.some(t=>t.id===e.content.sourceIdentity))&&(this.attachmentPanel=null),this.attachmentPanelLoader.requestWhileActive(Im,this.attachmentPanel!==null)}updated(){this.connectMachine.open&&!this.place.isAdmin()&&this.connectMachine.close(),this.gateway.retryPendingCatalogTarget(),this.context?.agentIdentity.ensure(this.agentPickerOpen?this.place.agents().map(e=>e.id):[this.place.agentId]);let e=this.draft.agentsReady();this.place.modelControl.loadCatalogTargets(this.context,e&&this.place.agentId?this.place.selectedAgent()?.id??``:``,this.context?.config.current.cliAgentsEnabled===!0&&!K(this.data));let t=this.routeOwnerKey(),n=this.data?.agentId??``,r=ho(this.data);if(this.openedFor!==t){this.openedFor!==null&&this.submission.visibility===`incognito`&&Fm(this.context,this.submission,this.openedFor,this.messageOwnerKey);let i=this.messageOwnerKey===t?this.submission.message:``,a=this.messageOwnerKey===t?this.submission.mentions:void 0;this.openedFor=t,this.openedGroupDefaults=r,this.openedAgentId=n,this.place.setAgentsHydrated(e),this.resetDraft(),this.messageOwnerKey=Nm(this.context,this.submission,t,i,a),this.focusComposer();return}this.openedGroupDefaults!==r&&(this.openedGroupDefaults=r,this.place.adoptGroupDefaults()),this.openedAgentId!==n&&(this.openedAgentId=n,this.place.setAgentsHydrated(!1)),this.draft.synchronizeSelections(),Mm(this.submission,t),this.submission.resumeInterruptedSubmission()}resetDraft(){this.place.resetDraft(),this.submission.resetDraft(),this.messageOwnerKey=lo(this.data),this.browser.clearPopoverHiding(),cu(this),this.browser.close(),this.connectMachine.close(),this.place.adoptAgentDefaults()}routeOwnerKey(){return this.data?lo(this.data):uo(window.location.search)}setMessageFromUser(e,t){!this.submission.submitting&&!this.submission.pendingPlacement.sessionKey&&(this.submission.setMessage(e,t),this.messageOwnerKey=uo(window.location.search))}renderTargetBar(){let e=this.place.agents(),t=this.context?.sessions;return To({data:this.data,groupPending:vo(this.data,t),agentSelect:e.length>1?Vu({agents:e,agentId:this.place.agentId,agentIdentity:this.context?.agentIdentity,disabled:this.submission.submitting||!!this.submission.pendingPlacement.sessionKey,onSelect:e=>this.place.selectAgentId(e),onOpenChange:e=>{this.agentPickerOpen=e}}):L,placeSelect:Hu({context:this.context,data:this.data,gateway:this.gateway,place:this.place,submitting:this.submission.submitting,pendingPlacement:!!this.submission.pendingPlacement.sessionKey,onConnectMachine:()=>this.openConnectMachine(),onNavigate:(e,t)=>this.context?.navigate(e,t),onFocusComposer:()=>this.submission.composerTextarea.getTextarea()?.focus({preventScroll:!0}),requestUpdate:()=>this.requestUpdate()}),retrying:this.gateway.catalogRetrying||!!(this.data?.group&&t?.groupsStatus()===`loading`),onRetry:this.gateway.handleCatalogRetry})}openConnectMachine(){this.place.isAdmin()&&(this.browser.close(),this.connectMachine.start())}renderDraftBlock(){return Am({context:this.context,gateway:this.gateway,place:this.place,submission:this.submission,dictation:this.dictation,titlePreparation:this.titlePreparation,draftOwnerKey:this.routeOwnerKey(),isCatalogTarget:K(this.data),renderTargetBar:()=>this.renderTargetBar(),requestUpdate:()=>this.requestUpdate(),onMessage:(e,t)=>this.setMessageFromUser(e,t),onOpenImage:this.setImageLightbox,onOpenSidebar:this.openAttachmentPanel})}renderWelcome(){let e=this.place.selectedAgent(),t=this.context?.agentIdentity.get(this.place.agentId),n=this.context?.gateway.snapshot;return Na({currentAgentId:this.place.agentId,assistantName:e?ve(e,t):``,assistantAvatar:De(e??{},t),assistantAvatarUrl:Te(e??{},t),hint:A(K(this.data)?`newSession.nativeTerminalHint`:`newSession.hint`),composer:this.renderDraftBlock(),hideSecondaryContent:this.submission.visibility===`incognito`,fadeSecondaryContent:this.submission.message.trim().length>0,modelSetupRequired:this.submission.requiresModelSetup(),onModelSetup:()=>this.context?.navigate(`model-setup`),sessions:this.context?.sessions.state.result,sessionKey:s({agentId:this.place.agentId||`main`,mainKey:this.context?.agents.state.agentsList?.mainKey}),sessionHost:{assistantAgentId:n?.assistantAgentId??null,agentsList:this.context?.agents.state.agentsList??null,hello:n?.hello??null},onDraftChange:e=>this.setMessageFromUser(e),onSend:()=>void this.submission.submit(),onOpenSession:e=>{let{context:t,submission:n}=this;!t||n.submitting||n.pendingPlacement.sessionKey||(Et({selection:t.agentSelection,gateway:t.gateway,sessionKey:e,agentId:this.place.agentId}),t.navigate(`chat`,Qe({context:t,face:`chat`,sessionKey:e}).options))}})}render(){let e=this.submission.pendingMessage,t=this.submission.completedSubmission,n=t?this.context?.placementStartup.get(t.key):null,r=this.context?.gateway.snapshot.selfUser?.identity,i=this.submission.visibility===`incognito`,a=this.attachmentPanelLoader.visibleState;return I`
      <div
        class="new-session-page ${e?`chat`:``} ${i?`new-session-page--incognito`:``}"
      >
        ${K(this.data)?L:Em(this.submission,this.submission.capabilities.canStartAsDraft(this.context))}
        ${$p({error:this.submission.error,pendingMessage:e,userId:r?.type===`profile`?r.id:null,submitting:this.submission.submitting,statusLabel:this.context?.gateway.snapshot.phase===`connected`?void 0:A(`connection.reconnecting`),completion:t?{label:t.error??n?.error??Jr(null,n)??A(`newSession.created`),onOpen:()=>void this.submission.openSubmittedSession(),disabled:this.context?.gateway.snapshot.phase!==`connected`}:void 0,showDraft:!!t,renderDraft:()=>t?this.renderDraftBlock():this.renderWelcome(),onOpenImage:this.setImageLightbox})}
        ${to({open:this.connectMachine.open&&this.place.isAdmin(),loading:this.connectMachine.loading,error:this.connectMachine.error,setup:this.connectMachine.setup,onRefresh:()=>void this.connectMachine.refresh(),onClose:()=>{this.connectMachine.close(),this.requestUpdate()},onManageDevices:()=>{this.connectMachine.close(),this.context?.navigate(`devices`)}})}
        ${Ni(this.imageLightbox,()=>this.setImageLightbox(null))}
      </div>
      ${this.attachmentPanel?I`<aside class="new-session-attachment-panel">
              ${a?.status===`error`?At({error:a.error,stale:a.stale,onRetry:()=>this.attachmentPanelLoader.retry(),onClose:this.closeAttachmentPanel}):a?I`<div role="status">${A(`common.loading`)}</div>`:L}
              <openclaw-chat-detail-panel
                .content=${{...this.attachmentPanel.content}}
                @chat-detail-panel-close=${this.closeAttachmentPanel}
              ></openclaw-chat-detail-panel>
            </aside>`:L}
    `}},E([V({attribute:!1})],Lm.prototype,`data`,void 0),E([re({context:Nt,subscribe:!0})],Lm.prototype,`context`,void 0),E([z()],Lm.prototype,`attachmentPanel`,void 0),E([z()],Lm.prototype,`imageLightbox`,void 0),E([z()],Lm.prototype,`agentPickerOpen`,void 0)})))()}var zm;function Bm(){return(Bm=e((()=>{R(),Al(),Rm(),customElements.get(`openclaw-new-session-page`)||customElements.define(`openclaw-new-session-page`,Lm),zm=e=>El(e)??I`<openclaw-new-session-page .data=${e}></openclaw-new-session-page>`})))()}async function Vm(e,t,n){let r=n&&n!==`preload`&&wl(e,t);if(r)return r;let i=oo(t),a=i.agentId.trim(),o=``,s=!1,c,l,u;if(i.group){let t=e.sessions.groupsGeneration(),n=await e.sessions.groupsLoad();l=e.sessions.groupsGeneration(),u=e.sessions.groupsStatus();let r=t===l&&u===`ready`?n:null,a=r?.find(e=>e.name===i.group);c=r===null?`unavailable`:a?`resolved`:`missing`,o=a?.cwd??``,s=a?.worktree===!0}let d={...i,requestedAgentId:a,groupStatus:c,groupCwd:o,groupWorktree:s,groupCatalogGeneration:l,groupDefaultsStatus:u,model:i.catalogId?``:i.requestedModel??``,catalogLabel:``,startTerminal:!1};if(!i.catalogId)return d;let f=(e=``)=>({...d,agentId:e}),p=e.gateway.snapshot,m=e.agents.state;if(p.phase!==`connected`||!p.client||!m.connected||m.client!==p.client)return f();let h=!m.agentsList||m.agentsListCached?await e.agents.ensureList():m.agentsList,_=e.gateway.snapshot,v=e.agents.state;if(_.phase!==`connected`||!_.client||_.client!==p.client||!v.connected||v.client!==_.client||v.agentsListCached||v.agentsList!==h)return f();let y=h,b=de(y?.agents??[]),x=_.hello?_.assistantAgentId:null;if(!y&&a&&(!x||g(a)!==g(x)))return f();let S=y?b.some(e=>e.id===y.defaultId)?y.defaultId:b[0]?.id:x,C=S?y?xo(i,b,S):xo(void 0,[],S):``,w=f(C);if(!C)return w;let T=await Co(_.client,i.catalogId,C);return T?{...w,...T}:w}function Hm(){return(Hm=e((()=>{Se(),j(),q(),Al(),so()})))()}export{Rs as $,Ou as A,Kl as B,ld as C,Pu as D,Bu as E,fu as F,lc as G,vl as H,pu as I,ic as J,uc as K,lu as L,Du as M,hu as N,Nu as O,mu as P,Bs as Q,du as R,Yu as S,Vu as T,Rc as U,yl as V,zc as W,Gs as X,qs as Y,Vs as Z,bd as _,tm as a,Y as at,md as b,Lf as c,Go as ct,Gf as d,no as dt,zs as et,Wf as f,ro as ft,Td as g,Za as gt,wd as h,$a as ht,zm as i,Jo as it,Eu as j,Au as k,Uf as l,so as lt,Md as m,Qa as mt,Vm as n,Qo as nt,$p as o,Ko as ot,jd as p,to as pt,cc as q,Bm as r,$o as rt,Zp as s,Po as st,Hm as t,es as tt,op as u,ao as ut,yd as v,Uu as w,ud as x,vd as y,Gl as z};