UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

252 lines • 54.1 kB
import{n as e}from"./rolldown-runtime-8BhlS34s.js";import{Br as t,Ii as n,eo as r,qr as i,ro as a,zr as o}from"./control-ui-foundation-ZY_Flbbd.js";import{Cl as s,Ct as c,Ic as l,Il as u,N as d,Ns as f,Pc as p,R as m,Rl as h,Ul as g,Vc as ee,Wl as te,Zl as _,bl as v,cc as ne,ct as re,eu as ie,hc as ae,hu as y,ks as oe,lu as se,nl as ce,nu as le,ot as ue,ou as de,sc as fe,uu as b,vt as pe,xc as me}from"./control-ui-core-3P365fbR.js";import{$i as he,$r as ge,B as _e,Br as ve,Da as ye,Gi as x,H as be,Ji as S,K as C,Ki as w,Kr as xe,Na as Se,Qi as Ce,V as we,Wi as Te,Wr as Ee,Xi as T,Zi as E,_r as De,co as Oe,dr as ke,fo as Ae,fr as je,hi as Me,ho as Ne,ja as Pe,ma as Fe,mi as Ie,mo as Le,q as Re,ur as D,va as ze,vi as Be,wi as Ve,yi as He,z as Ue}from"./control-ui-core-CFW9Qtjn.js";import{$ as O,F as We,M as Ge,Q as Ke,X as k,Y as A,ct as j,nt as qe,tt as Je,ut as M}from"./lit-runtime-P5vbNq6b.js";import"./control-ui-boot-shared-Rs4iS2kF.js";import{d as Ye,l as Xe}from"./gateway-runtime-5YzSCmfV.js";import{Al as Ze,El as N,dl as P,jl as Qe,kl as $e,no as et,ro as tt,ul as F}from"./control-ui-boot-shared-DoKu-5Ju.js";import{Qa as nt,ea as rt,eo as it,it as at,rt as I,ta as ot}from"./control-ui-boot-shared-CG9HtEG-.js";import{St as st,z as ct}from"./control-ui-boot-shared-BykNRHBP.js";import{$n as lt,Bn as ut,F as dt,Jt as ft,P as pt,an as mt,nn as ht,on as gt,qt as _t,sn as vt,tr as L,zn as yt}from"./control-ui-boot-shared-CcmBeh0v.js";import{cr as bt,d as xt,f as St,h as Ct,or as wt,sr as Tt}from"./control-ui-boot-shared-CApmg5ot.js";import{D as Et,E as Dt,F as Ot,I as kt,L as R,N as At,P as jt,R as Mt,T as Nt,U as Pt,X as Ft,Y as It,dt as Lt,ft as Rt,ht as zt,mt as Bt,pt as Vt,w as Ht}from"./control-ui-boot-new-BTHisEC4.js";import"./css-chat-custodian-new-session-B_euK-Vu.js";import"./css-new-session-BGJnpiJ5.js";import{n as Ut,t as Wt}from"./transcript-search-Bw6jSdBN.js";import{n as Gt,t as Kt}from"./en-apps-8oPCuuXd.js";import{a as qt,o as Jt}from"./settings-targets-BVKntTff.js";var z;function B(){return(B=e((()=>{z=class{constructor(e,t,n){this.read=e,this.restore=t,this.notify=n,this.remember=!1,this.saving=!1,this.failed=!1,this.selection=null,this.edited=!1,this.scope=``,this.generation=0,this.pending=null}get available(){let{draft:e}=this.read();return e?.gateway.connected===!0&&e.gateway.preferenceState?.mode===`remote`}begin(){if(this.saving||this.failed){this.restore(this.selection);return}this.edited=!1,this.observed=void 0,this.selection=null,this.remember=!1,this.failed=!1,this.synchronize()}synchronize(){let{draft:e,context:t}=this.read();if(!e||!t)return;let n=t.gateway,r=JSON.stringify([n.connection.gatewayUrl,n.snapshot.selfUser?.id??``,n.snapshot.hello?.auth?.recoveryScope??``]);n.snapshot.phase===`connected`&&(this.scope!==r||this.source!==n)&&(this.scope=r,this.source=n,this.generation+=1,this.edited=!1,this.observed=void 0,this.saving=!1,this.failed=!1,this.remember=!1,this.selection=null,this.pending=null);let i=e.gateway.preferenceState;if(i!==this.binding){let e=this.saving;this.binding=i,this.observed=void 0,this.generation+=1,this.saving=!1,e&&(this.failed=!0,this.remember=!1,this.notify())}let a=i?.mode===`remote`?i.palettePreference:null;this.observed!==a&&i?.mode!==`loading`&&e.agentsReady()&&(this.observed=a,!(this.edited||e.submission.submitting||e.submission.pendingPlacement.sessionKey||e.submission.submissionOutcomeUnknown)&&(this.selection=a,this.remember=this.selection!==null,this.restore(this.selection),this.notify()))}changed(){this.edited=!0,this.selection=this.capture(),this.failed&&this.pending&&(this.pending=this.selection),this.remember&&this.save(this.selection),this.notify()}setRemember(e){this.available&&(this.edited=!0,this.remember=e,this.selection=e?this.capture():null,e||this.restore(null),this.save(this.selection),this.notify())}retry(){this.failed&&this.available&&this.save(this.pending)}capture(){let e=this.read().draft?.place;if(!e?.agentId)return null;let t=e.preferenceSelection();return delete t.worktreeName,{agentId:e.agentId,selection:t}}async save(e){let{draft:t}=this.read();if(!t)return;let n=++this.generation,r=t.gateway.preferenceState;this.pending=e,this.saving=!0,this.failed=!1;let i=await t.gateway.savePalettePreference(e);n===this.generation&&r===t.gateway.preferenceState&&(this.saving=!1,this.failed=!i,!i&&e&&!r?.palettePreference&&(this.remember=!1),i&&(this.remember=e!==null),this.notify())}}})))()}var V,H;function U(){return(U=e((()=>{A(),Ge(),Ce(),E(),Te(),I(),b(),F(),Ze(),ie(),It(),Ht(),Dt(),Qe(),P(),V=he(Je`<path d="M4 7h8m4 0h4M4 17h2m4 0h10"/><circle cx="14" cy="7" r="2"/><circle cx="8" cy="17" r="2"/>`),H=class{constructor(e,t){this.host=e,this.id=t,this.open=!1,this.places=!1,this.query=``}close(){this.open=!1,this.places=!1,this.query=``,this.host.requestUpdate()}async showPlaces(e,t=!1){this.places=e,this.query=``,this.host.requestUpdate(),await this.host.updateComplete;let n=e?t?`back`:`search`:`workspace`;this.host.querySelector(`.palette-session-settings__`+n)?.focus({preventScroll:!0})}keydown(e){if(e.defaultPrevented||e.isComposing||e.keyCode===229||e.composedPath().some(e=>e instanceof Element&&e.matches(`wa-dropdown[open]`)))return;if(e.key===`Escape`){e.preventDefault(),e.stopPropagation(),this.places?this.showPlaces(!1):(this.close(),this.host.querySelector(`#`+this.id+`-settings-trigger`)?.focus({preventScroll:!0}));return}if(![`ArrowDown`,`ArrowUp`].includes(e.key)||!(e.currentTarget instanceof HTMLElement)||e.composedPath().some(e=>e instanceof Element&&e.tagName===`WA-DROPDOWN`))return;let t=[...e.currentTarget.querySelectorAll(`button:not(:disabled), input:not(:disabled)`)],n=t.findIndex(e=>e===this.host.ownerDocument.activeElement);t.length&&(e.preventDefault(),e.stopPropagation(),t[(n+(e.key===`ArrowDown`?1:-1)+t.length)%t.length]?.focus())}render(e){let{draft:t,context:n,preferences:r,onChange:i}=e,{place:a,gateway:o,submission:s}=t,c=s.submitting||!!s.pendingPlacement.sessionKey||!!s.submissionOutcomeUnknown,l=Et({environments:a.canWrite()?o.environments:[],cloudProfiles:a.isAdmin()?o.cloudProfiles:[],cloudProfileId:a.cloudProfileId,...a.cloudSelection,deviceId:a.deviceId,autoDevice:a.autoDevice,devicePlacement:a.devicePlacementRuntime()?.devicePlacement,deviceDisabledReason:a.modelControl.devicePlacementUnsupportedReason()??o.deviceCatalogDisabledReason}),u=l.kind===`local`?o.gatewayName||y(`newSession.local`):l.label,d=[l.operatingSystems.find(e=>e.id===l.selectedOsId)?.label,l.cloudMachines.find(e=>e.id===l.selectedMachineId)?.label].filter(Boolean).join(` · `),f=Ft({folder:a.folder,workspace:a.workspacePath(),projectId:t.browser.projectId,selectedRemoteProject:t.browser.remoteProject,projects:t.browser.projects,recents:[],projectQuery:``,freshWorkspace:a.freshWorkspace}),p=[{id:`local`,label:o.gatewayName||y(`newSession.local`),remote:!1,selected:!a.remotePlacement,select:()=>a.selectDevice(``)},...l.devices.map(e=>({id:`device:`+e.deviceId,label:e.label,remote:!0,selected:a.deviceId===e.deviceId,disabledReason:e.disabledReason,select:()=>a.selectDevice(e.deviceId)})),...l.devices.length?[{id:`auto-device`,label:y(`newSession.autoDevice`),remote:!0,selected:a.autoDevice,disabledReason:l.autoDeviceDisabledReason,select:()=>a.selectDevice(``,!0)}]:[],...l.cloudProfiles.map(e=>({id:`cloud:`+e.id,label:y(`newSession.cloudWorker`,{profile:e.id}),remote:!0,selected:a.cloudProfileId===e.id,disabledReason:a.modelControl.cloudRuntimeUnsupportedReason(e),select:()=>a.selectCloudProfile(e.id)}))],m=(e,t)=>{c||e.disabledReason||(e.select(),t?a.selectProjectId(t):e.remote?a.selectNewWorkspace():a.applyFolder(a.workspacePath()),i(),this.showPlaces(!1))},h=this.query.trim().toLocaleLowerCase(),g=p.map(e=>({machine:e,choices:[{id:``,label:e.remote?y(`newSession.newWorkspace`):Ct(a.workspacePath())||y(`newSession.folderPlaceholder`)},...t.browser.projects.map(e=>({id:e.id,label:e.displayName}))].filter(t=>!h||(e.label+` `+t.label).toLocaleLowerCase().includes(h))})).filter(e=>e.choices.length);return O`
      <button
        id=${this.id+`-settings-trigger`}
        class="palette-session-settings__trigger"
        type="button"
        aria-label=${y(`commandPalette.newSessionSettings`)}
        title=${y(`commandPalette.newSessionSettings`)}
        aria-haspopup="dialog"
        aria-expanded=${String(this.open)}
      >
        ${V}
      </button>
      <wa-popover
        ${We(at)}
        class="palette-session-settings"
        for=${this.id+`-settings-trigger`}
        placement="bottom-end"
        without-arrow
        .open=${this.open}
        @wa-show=${e=>{e.target===e.currentTarget&&(this.open=!0,this.host.requestUpdate())}}
        @wa-hide=${e=>{e.target===e.currentTarget&&this.close()}}
      >
        <div
          class="palette-session-settings__content"
          @keydown=${e=>this.keydown(e)}
        >
          ${this.places?O`
                  <div class="palette-session-settings__heading">
                    <button
                      type="button"
                      class="palette-session-settings__back"
                      aria-label=${y(`common.back`)}
                      @click=${()=>this.showPlaces(!1)}
                    >
                      ${T.arrowLeft}</button
                    ><span>${y(`newSession.projects`)}</span>
                  </div>
                  <input
                    class="palette-session-settings__search"
                    type="search"
                    aria-label=${y(`common.search`)}
                    placeholder=${y(`common.search`)}
                    .value=${this.query}
                    @input=${e=>{e.currentTarget instanceof HTMLInputElement&&(this.query=e.currentTarget.value,this.host.requestUpdate())}}
                  />
                  <div class="palette-session-settings__choices">
                    ${g.map(({machine:e,choices:n})=>O` <section aria-label=${e.label}>
                        <div class="palette-session-settings__machine">${e.label}</div>
                        ${n.map(n=>O`<button type="button" class="palette-session-settings__row" data-machine=${e.id} data-project=${n.id} aria-pressed=${String(e.selected&&(n.id?t.browser.projectId===n.id:!t.browser.projectId&&(e.remote?a.freshWorkspace:a.folder===a.workspacePath())))} title=${e.disabledReason??k} ?disabled=${c||!!e.disabledReason} @click=${()=>m(e,n.id)}><span class="palette-session-settings__icon">${n.id?T.gitBranch:T.folder}</span><span class="palette-session-settings__label">${n.label}</span><span class="palette-session-settings__check">${e.selected&&(n.id?t.browser.projectId===n.id:!t.browser.projectId&&(e.remote?a.freshWorkspace:a.folder===a.workspacePath()))?T.check:k}</span></button>`)}
                        ${e.disabledReason?O`<div class="palette-session-settings__unavailable">${e.disabledReason}</div>`:k}
                      </section>`)}
                    ${g.length?k:O`<div class="palette-session-settings__unavailable">${y(`newSession.environmentSearchEmpty`)}</div>`}
                    ${o.cloudProfilesPending?O`<div role="status" class="palette-session-settings__unavailable">${y(`common.loading`)}</div>`:k}
                  </div>
                  ${a.isAdmin()?O`<button class="palette-session-settings__row" type="button" ?disabled=${c} @click=${e.onConnectMachine}><span class="palette-session-settings__icon">${T.plus}</span><span>${y(`newSession.connectMachine`)}</span></button>`:k}
                `:O`
                  <div class="palette-session-settings__title">
                    ${y(`commandPalette.newSessionSettings`)}
                  </div>
                  <div class="palette-session-settings__agent">
                    ${Nt({agents:a.agents(),variant:`default`,agentId:a.agentId,agentIdentity:n?.agentIdentity,disabled:c,onSelect:e=>{a.selectAgentId(e),i()},onOpenChange:e.onAgentPickerOpen})}
                  </div>
                  <button
                    class="palette-session-settings__row palette-session-settings__workspace"
                    type="button"
                    ?disabled=${c}
                    @click=${e=>this.showPlaces(!0,e.detail>0)}
                  >
                    <span class="palette-session-settings__icon">${T.folder}</span
                    ><span class="palette-session-settings__copy"
                      ><span class="palette-session-settings__label">${f.label}</span
                      ><span class="palette-session-settings__secondary"
                        >${u}${d?` · `+d:``}</span
                      ></span
                    ><span class="palette-session-settings__chevron">${T.chevronRight}</span>
                  </button>
                  <button
                    class="palette-session-settings__row palette-session-settings__worktree"
                    type="button"
                    role="switch"
                    aria-checked=${String(a.worktree)}
                    aria-label=${y(`newSession.checkoutWorktree`)}
                    title=${a.remotePlacement?y(`newSession.checkoutRemoteLocked`):a.worktreeAvailable()?k:y(`newSession.worktreeUnavailable`)}
                    ?disabled=${c||a.remotePlacement||!a.worktreeAvailable()}
                    @click=${()=>{a.selectWorktree(!a.worktree),i()}}
                  >
                    <span class="palette-session-settings__icon">${T.gitBranch}</span
                    ><span>${y(`newSession.checkoutWorktree`)}</span
                    ><span class="palette-session-settings__switch" aria-hidden="true"></span>
                  </button>
                `}
          ${!this.places||r.failed?O`<div class="palette-session-settings__footer">
                  ${this.places?k:O`<label
                          class="palette-session-settings__remember"
                          title=${r.available?k:y(`commandPalette.rememberUnavailable`)}
                          ><input
                            type="checkbox"
                            .checked=${r.remember}
                            ?disabled=${c||!r.available}
                            @change=${e=>{e.currentTarget instanceof HTMLInputElement&&r.setRemember(e.currentTarget.checked)}}
                          /><span
                            >${S(y(`commandPalette.rememberSettings`,{shortcut:`{shortcut}`}),w(_.commandPalette,{inline:!0}))}</span
                          ></label
                        >`}
                  ${r.failed?O`<div class="palette-session-settings__error" role="alert">${y(`commandPalette.settingsSaveFailed`)} <button type="button" class="btn btn--sm" @click=${()=>r.retry()}>${y(`common.retry`)}</button></div>`:k}
                </div>`:k}
        </div>
      </wa-popover>
    `}}})))()}var W;function G(){return(G=e((()=>{A(),Ie(),ke(),b(),F(),oe(),ae(),g(),ne(),yt(),I(),gt(),Rt(),kt(),At(),Mt(),B(),U(),P(),W=class e{static{this.nextId=0}constructor(t,n,r){this.host=t,this.read=n,this.callbacks=r,this.agentPickerOpen=!1,this.idPrefix=`palette-session-${++e.nextId}`,this.pasteImages=e=>{this.synchronizePresentationScope();let t=this.attachmentProps();this.read().open&&!this.messageLocked&&t&&mt(e,t,{imagesOnly:!0})},this.preferences=new z(()=>({draft:this.draft,context:this.read().context}),e=>this.restoreSettings(e),()=>t.requestUpdate()),this.settings=new H(t,this.idPrefix),this.connectMachine=new Lt(()=>({client:this.draft?.gateway.client??null,connected:this.draft?.gateway.connected??!1}),()=>t.requestUpdate()),this.subscriptions=new fe(t).watch(()=>this.draft&&this.read().context?.agents,(e,t)=>e.subscribe(t)).watch(()=>this.draft&&this.read().context?.agentIdentity,(e,t)=>e.subscribe(t)).watch(()=>this.draft&&this.read().context?.sessions,(e,t)=>e.subscribe(t)).watch(()=>this.draft&&this.read().context?.config,(e,t)=>e.subscribe(()=>t())),t.addController(this)}get message(){return this.draft?.submission.message??``}get mentions(){return this.draft?.submission.mentions??[]}get mentionDirectory(){return this.draft&&this.read().open&&!this.messageLocked?jt({context:this.read().context,agentId:this.draft.place.agentId,draftOwnerKey:this.idPrefix,visibility:this.draft.submission.visibility}):void 0}get submitting(){return this.draft?.submission.submitting??!1}get messageLocked(){return this.submitting||!!(this.coldSubmitReadSignal||this.draft?.submission.pendingPlacement.sessionKey)}get hasPrompt(){return!!(this.message.trim()||this.draft?.submission.attachmentDraft.attachments.length)}get canSubmit(){return!this.coldSubmitReadSignal&&this.hasPrompt&&!!this.draft?.submission.canSubmit()}get error(){let e=this.draft?.submission;return e?.error??e?.blockedSubmitNotice()??(e?.submissionOutcomeUnknown?e.submitDisabledReason():null)??(this.preferences.failed?y(`commandPalette.settingsSaveFailed`):null)}get disabledReason(){return this.draft?.submission.submitDisabledReason()}setMessage(e,t){this.draft&&!this.messageLocked&&((e!==this.message||t!==void 0&&t!==this.mentions)&&(this.rejectedOpen=void 0,this.draft.submission.clearError()),this.draft.submission.setMessage(e,t))}attachmentProps(){let e=this.draft?.submission.attachmentDraft;if(!e)return;let t=e.readSignal;return{uploadConfig:this.read().context?.config,attachments:e.attachments,attachmentReads:e.reads,attachmentLimits:ut(this.read().context?.gateway.snapshot.hello?.policy),disabled:this.messageLocked,getAttachments:()=>e.attachments,readSignal:t,onPendingReadsChange:n=>e.updatePending(t,n),onAttachmentsChange:n=>{t.aborted||!this.read().open||this.submitting||this.draft?.submission.pendingPlacement.sessionKey||(this.rejectedOpen=void 0,this.draft?.submission.clearError(),e.replace(n))}}}adoptImageFiles(e,t=!1){let n=this.attachmentProps();if(!this.read().open||this.messageLocked||!n)return;let r=ht(e,n);t&&r===e.length&&(this.coldSubmitReadSignal=n.readSignal,this.host.requestUpdate())}renderAttachments(){let e=this.attachmentProps(),t=e?vt(e):k;return t===k?k:O`<div class="cmd-palette__attachments">${t}</div>`}open(){if(this.synchronizePresentationScope(),this.draft&&(this.submitting||this.draft.submission.pendingPlacement.sessionKey||this.draft.submission.submissionOutcomeUnknown||this.draft.submission.error))return;let e=this.read().context?.agentSelection.state.selectedId??``;this.data={agentId:e,requestedAgentId:e,catalogId:``,model:``,catalogLabel:``,startTerminal:!1},this.draft||=new Ot(this.host,()=>({context:this.read().context,data:this.data,isConnected:this.host.isConnected}),{requestUpdate:()=>this.host.requestUpdate(),onMessageChange:e=>this.callbacks.onMessageChange?.(e),querySelector:e=>this.host.querySelector(e),activeElement:()=>this.host.ownerDocument.activeElement,body:()=>this.host.ownerDocument.body,pickerIdPrefix:this.idPrefix,preferenceScope:`palette`,readPalettePreference:()=>this.preferences.selection,closeTransientUi:()=>R(this.host),onInvalidate:()=>this.connectMachine.close(),onRecoveryReady:(e,t)=>this.bindOwner(e,t),onAccepted:e=>this.accepted(e),retainRejectedPrompt:!0}),this.rejectedOpen=void 0,this.coldSubmitReadSignal=void 0,this.draft.place.resetDraft(),this.draft.submission.resetDraft(),this.draft.place.setAgentsHydrated(this.draft.agentsReady()),this.preferences.begin(),this.draft.place.adoptAgentDefaults(),this.host.requestUpdate()}close(){this.coldSubmitReadSignal=void 0;let e=this.draft?.submission;e&&!this.submitting&&!e.pendingPlacement.sessionKey&&!e.submissionOutcomeUnknown&&!e.error?e.attachmentDraft.reset({release:!0}):e?.attachmentDraft.abortReads(),this.settings.close(),this.draft?.browser.close(),this.connectMachine.close(),R(this.host)}async submit(){this.synchronizePresentationScope(),this.read().open&&!this.coldSubmitReadSignal&&this.hasPrompt&&this.draft&&await this.draft.submission.submit(void 0,!0)}hostUpdate(){this.synchronizePresentationScope()}synchronizePresentationScope(){let e=this.read().context?.gateway,t=e?D(e):void 0,n=this.presentationScope!==void 0&&this.presentationScope!==t;this.presentationScope=t,n&&(this.close(),this.rejectedOpen=void 0,this.owner=void 0,this.draft?.gateway.invalidateDiscovery(!0,`gateway-changed`),this.draft?.submission.releasePendingPlacementOwner(),this.draft?.submission.resetDraft(),this.draft?.submission.restoreMessage(``),this.callbacks.onMessageChange?.(``))}hostUpdated(){let e=this.draft;if(!e)return;this.connectMachine.open&&!e.place.isAdmin()&&this.connectMachine.close(),this.preferences.synchronize(),e.synchronizeSelections(),e.submission.resumeInterruptedSubmission();let t=e.submission.attachmentDraft;if(this.coldSubmitReadSignal&&(this.coldSubmitReadSignal.aborted||t.pendingReads===0)){let e=!this.coldSubmitReadSignal.aborted&&!t.reads.project(t.attachments).some(e=>e.state===`error`);this.coldSubmitReadSignal=void 0,this.host.requestUpdate(),e&&this.submit()}this.read().open&&this.read().context?.agentIdentity.ensure(this.agentPickerOpen?e.place.agents().map(e=>e.id):[e.place.agentId])}hostDisconnected(){this.disconnect()}disconnect(){this.close(),this.subscriptions.clear(),this.draft?.disconnect()}renderControls(){let e=this.draft;return e?this.settings.render({draft:e,context:this.read().context,preferences:this.preferences,onAgentPickerOpen:e=>{this.agentPickerOpen=e,this.host.requestUpdate()},onChange:()=>this.preferences.changed(),onConnectMachine:()=>{e.place.isAdmin()&&(this.settings.close(),e.browser.close(),this.connectMachine.start())}}):k}restoreSettings(e){if(!this.draft||!this.data||this.messageLocked)return;let t=this.read().context?.agentSelection.state.selectedId??``,n=e?.agentId??t;this.data={...this.data,agentId:n,requestedAgentId:n},this.draft.place.resetDraft(),this.draft.place.setAgentsHydrated(this.draft.agentsReady()),this.draft.place.adoptAgentDefaults(),this.draft.place.restorePreferenceSelections()}renderRecovery(){return this.rejectedOpen?O`<button class="btn btn--sm" type="button" @click=${this.rejectedOpen}>
          ${y(`sessionsView.openSession`)}
        </button>`:k}renderAuxiliary(){return Vt({open:this.connectMachine.open&&this.read().open&&(this.draft?.place.isAdmin()??!1),loading:this.connectMachine.loading,error:this.connectMachine.error,setup:this.connectMachine.setup,onRefresh:()=>void this.connectMachine.refresh(),onClose:()=>{this.connectMachine.close(),this.host.requestUpdate()},onManageDevices:()=>{this.callbacks.onClose(),this.read().context?.navigate(`devices`)}})}bindOwner(e,t){let n=this.read().context?.gateway;n&&(this.owner&&(this.owner.gateway!==n||this.owner.url!==e||this.owner.scope!==t)&&(this.rejectedOpen=void 0,this.draft?.submission.restoreMessage(``)),this.owner={gateway:n,url:e,scope:t})}accepted(e){let t=this.read().context;if(!t)return;let{gateway:n}=t,r=Pt(t),i=t.sessions.state.result?.sessions.find(t=>t.key===e.key),a=e.initialRun.status===`rejected`?e.initialRun.error:y(e.initialRun.status===`started`?`sessionsView.statusRunning`:`sessionsView.statusIdle`),o=()=>{this.read().context===t&&r()&&(Me({selection:t.agentSelection,gateway:n,sessionKey:e.key,agentId:e.agentId}),t.navigate(`chat`,me({context:t,face:`chat`,sessionKey:e.key,agentId:e.agentId}).options),e.initialRun.status===`rejected`&&this.callbacks.onClose())};te({fifo:!0,message:`${f(e.key,i)}: ${a}`,actionLabel:y(`sessionsView.openSession`),onAction:o}),e.initialRun.status===`rejected`?(this.rejectedOpen=o,this.host.requestUpdate()):this.callbacks.onClose()}}})))()}function Yt(e){let t=tn.get(e);return t?y(t):e}function K(e,t,n,r={}){return{...r,id:`nav-${r.id??e}`,label:t,icon:n,category:`navigation`,action:`nav:${e}`}}function Xt(e,t){return[K(`new-session`,y(`newSession.title`),`plus`),K(`sessions`,y(`palette.items.sessions`),`fileText`),K(`meetings`,y(`tabs.meetings`),`book`,{description:y(`subtitles.meetings`)}),K(`cron`,y(`palette.items.scheduled`),`scrollText`),K(`skills`,y(`palette.items.skills`),`zap`),K(`plugins`,y(`palette.items.plugins`),`plug`),K(`apps`,y(`palette.items.apps`),`layoutGrid`),K(`appearance`,y(`palette.items.settings`),`settings`,{id:`settings`}),K(`agents`,y(`palette.items.agents`),`folder`),{id:`slash:verbose`,label:`/verbose`,icon:`terminal`,category:`search`,action:`/verbose full`,description:y(`palette.descriptions.verboseMode`)},...e?[{id:`panel-desktop`,label:y(`palette.items.desktop`),icon:`monitor`,category:`navigation`,action:`panel:desktop`}]:[],...t?[{id:`panel-custodian`,label:y(`nav.askOpenClaw`),icon:`lobster`,category:`navigation`,action:`panel:custodian`}]:[]]}function Zt(e){let t=Xt(e.desktopAvailable,e.custodianAvailable).filter(t=>e.includeSlashCommands||t.category!==`search`);if(!e.query)return t;let n=r(e.query),i=t=>{let i=r(t.label);return i===n?3:i.startsWith(n)?2:i.includes(n)||r(t.description).includes(n)||r(t.searchText).includes(n)||e.primaryModelSearch&&r(t.primaryModel).includes(n)?1:0},a=t.filter(e=>i(e)>0),o=e.catalogItems.map(e=>({item:e,rank:i(e)})).filter(({rank:e})=>e>0).toSorted((e,t)=>t.rank-e.rank||e.item.label.localeCompare(t.item.label)).slice(0,nn).map(({item:e})=>e);return[...e.sessionItems,...a,...o]}function Qt(e,t=null){let n=Se(e,t).flatMap(e=>e.routes).concat(Fe).map(e=>({id:`settings-${e}`,label:ye(e),icon:`settings`,category:`settings`,action:`nav:${e}`,description:Pe(e),searchText:e})),r=rn.map(e=>({id:`app-${e}`,label:y(`appsPage.cards.${e}.title`),icon:`layoutGrid`,category:`apps`,action:`nav:apps`,description:y(`appsPage.cards.${e}.desc`),searchText:e})),i=qt.meetingCapture;return[...n,...e?[{id:`settings-meeting-capture`,label:y(i.labelKey),icon:`settings`,category:`settings`,action:`nav:${i.routeId}`,search:i.search,hash:i.hash,searchText:i.aliases}]:[],...r]}async function $t(e){let t=async(t,n)=>e.methodAvailable(t)?e.client.request(t,n).catch(()=>null):null,[n,r,i,a]=await Promise.all([e.agents().catch(()=>null),e.methodAvailable(`cron.list`)?re(e.client).catch(()=>null):null,t(`skills.status`,{agentId:e.agentId}),t(`plugins.list`,{})]);return[...(n?.agents??[]).map(e=>({id:`agent-${e.id}`,label:e.identity?.name??e.name??e.id,icon:`bot`,category:`agents`,action:`nav:agents`,agentId:e.id,description:e.id,searchText:[e.id,e.workspace,e.identity?.theme].filter(Boolean).join(` `),primaryModel:e.model?.primary})),...(r?.jobs??[]).map(e=>({id:`automation-${e.id}`,label:e.displayName??e.name,icon:`calendarClock`,category:`automations`,action:`nav:cron`,searchText:[e.id,e.declarationKey,e.name,e.agentId].filter(Boolean).join(` `)})),...(i?.skills??[]).map(e=>({id:`skill-${e.skillKey}`,label:e.name,icon:`zap`,category:`skills`,action:`nav:skills`,description:e.description,searchText:[e.skillKey,e.source].filter(Boolean).join(` `)})),...(a?.plugins??[]).map(e=>({id:`plugin-${e.id}`,label:e.name,icon:`plug`,category:`plugins`,action:e.installed?`nav:plugin-settings`:`nav:plugins`,pluginId:e.id,catalogId:e.installed?void 0:e.catalogId,hasPluginIcon:e.hasIcon,description:e.description,searchText:[e.id,e.packageName,e.category,e.kind?.join(` `)].filter(Boolean).join(` `)}))]}function en(e){return e.models.map(e=>({id:`model-${JSON.stringify([e.provider,e.id])}`,label:e.name||e.id,icon:`brain`,category:`models`,action:`nav:model-providers`,description:e.provider,searchText:[e.id,e.provider,e.alias,e.tags?.join(` `)].filter(Boolean).join(` `)}))}var tn,nn,rn;function q(){return(q=e((()=>{ze(),b(),Kt(),F(),ue(),Jt(),P(),Gt(),tn=new Map([[`search`,`palette.categories.search`],[`navigation`,`palette.categories.navigation`],[`skills`,`palette.categories.skills`],[`agents`,`palette.items.agents`],[`apps`,`palette.items.apps`],[`automations`,`palette.items.scheduled`],[`models`,`routeTitles.modelProviders`],[`plugins`,`palette.items.plugins`],[`settings`,`palette.items.settings`],[`chats`,`sessionsView.title`],[`messages`,`palette.categories.messages`]]),nn=10,rn=[`ios`,`android`,`appleWatch`,`wearOs`,`macos`,`windows`,`linux`,`chrome`,`plugins`]})))()}function an(e,t,n){let i=[n,e.key,e.label,e.subject,e.category,e.kind,e.model,e.modelProvider,e.owner?.actor.label,e.owner?.actor.id,e.createdActor?.label,e.createdActor?.id].map(e=>r(e)).filter(Boolean);return i.some(e=>e===t)?3:i.some(e=>e.startsWith(t))?2:+!!i.some(e=>e.includes(t))}function on(e){let t=e.replace(/\s+/gu,` `).trim();return t.length>cn?`${n(t,159)}…`:t}function sn(e){let{visibleRows:t,visibleKeys:n,transcriptResult:i}=e,a=r(e.search),o=ct(i?.results??[],e=>e.sessionKey),s=new Map(t.map(e=>[e.key,e]));for(let e of i?.sessions??[])s.has(e.key)||s.set(e.key,e);return[...s.values()].map(e=>{let t=f(e.key,e),r=an(e,a,t);return{row:e,label:t,rawMetadataRank:r,metadataRank:Math.max(+!!n.has(e.key),r),transcriptHit:o.get(e.key)}}).filter(({metadataRank:e,transcriptHit:t})=>e>0||t).toSorted((e,t)=>{let n=t.metadataRank-e.metadataRank;return n===0?(t.transcriptHit?.score??-1/0)-(e.transcriptHit?.score??-1/0)||(t.row.updatedAt??0)-(e.row.updatedAt??0):n}).slice(0,10).map(({row:e,label:t,rawMetadataRank:n,transcriptHit:r})=>({id:`session-${e.key}`,label:t,icon:`messageSquare`,category:r&&n===0?`messages`:`chats`,action:`${J}${e.key}`,session:e,description:r&&n===0?on(r.snippet):void 0}))}var J,cn;function Y(){return(Y=e((()=>{oe(),J=`session:`,cn=160})))()}function ln(e,t){let n=t.trim(),r=n?new RegExp(st(n),`iu`).exec(e):null,i=r?.index??-1;return r?O`
        ${e.slice(0,i)}<mark>${e.slice(i,i+r[0].length)}</mark>${e.slice(i+r[0].length)}
      `:e}function un(e,t,n,r,i={},a){let o=e.session,s=o?.owner?.actor,c=n?l(n,r):void 0,u=e.pluginId;return O`
    ${n?O`<span class="cmd-palette__avatar" aria-hidden="true">
            ${it({id:n.id,avatar:h(n,r),textAvatar:ee(n,r)})}
            ${s?.id?O`<span class="cmd-palette__owner">${ot({...s,id:s.id})}</span>`:k}
          </span>`:u?St(u,e.label,{iconUrl:i[u],onIconError:()=>a?.(u),className:`cmd-palette__plugin-icon`}):O`<span class="nav-item__icon" aria-hidden="true">${T[e.icon]}</span>`}
    <span class="cmd-palette__item-copy">
      <span class="cmd-palette__item-heading">
        <span class="cmd-palette__item-title">${ln(e.label,t)}</span>
        ${o?.updatedAt?O`<span class="cmd-palette__item-time">${d(o.updatedAt,{fallback:``})}</span>`:k}
      </span>
      ${o?O`<span class="cmd-palette__item-meta">${c}${s?.id?O`<span aria-hidden="true"> · </span>${y(`sessionsView.ownedBy`,{name:s.label||s.id})}`:k}</span>`:k}
      ${e.description?O`<span class="cmd-palette__item-desc">${ln(e.description,t)}</span>`:k}
    </span>
  `}function dn(){return(dn=e((()=>{A(),b(),p(),u(),m(),xt(),E(),nt(),rt()})))()}function fn(e){let t=new Map;for(let n of e){let e=t.get(n.category)??[];e.push(n),t.set(n.category,e)}return[...t.entries()]}function pn(e,t){if(!(t.draft.submitting||t.searchDebouncing)){if(e.action.startsWith(`nav:`)){let n=e.action.slice(4);e.agentId?t.onNavigate?.(n,{pathname:Ae(e.agentId,null,t.basePath)}):e.catalogId?t.onNavigate?.(n,{pathname:Le(e.catalogId,t.basePath)}):e.pluginId&&n===`plugin-settings`?t.onNavigate?.(n,{pathname:Ne(e.pluginId,t.basePath)}):e.search||e.hash?t.onNavigate?.(n,{search:e.search,hash:e.hash}):t.onNavigate?.(n)}else e.action.startsWith(`session:`)?t.onSelectSession?.(e.action.slice(J.length)):e.action===`panel:desktop`?window.dispatchEvent(new CustomEvent(xe,{detail:{open:!0}})):e.action===`panel:custodian`?window.dispatchEvent(new CustomEvent(Ee,{detail:{open:!0}})):t.onSlashCommand?.(e.action);t.onToggle()}}function mn(){requestAnimationFrame(()=>{document.querySelector(`.cmd-palette__item--active`)?.scrollIntoView({block:`nearest`})})}function hn(e,t){let n=t();if(e.defaultPrevented)return;if(n.composing||e.isComposing||e.keyCode===229){e.stopPropagation();return}if(!(e.target instanceof HTMLTextAreaElement)||e.target.id!==bn)return;if(e.key===`Enter`&&e.repeat){e.preventDefault();return}if(!n.draft.messageLocked&&!e.shiftKey&&!e.altKey&&!e.metaKey&&!e.ctrlKey&&n.mentionMenu.handleKeydown(e,n.mentionHost,n.requestUpdate)){e.stopPropagation();return}if(le(_.modifiedEnter,e)){e.preventDefault(),e.stopPropagation(),n.draft.submit();return}if(e.shiftKey||e.altKey||e.metaKey||e.ctrlKey)return;if(e.key===`Escape`){e.preventDefault(),e.stopPropagation(),n.onToggle();return}if(n.draft.submitting)return;e.key===`Enter`&&n.searchDebouncing&&(n.onFlushSearch(),n=t());let{items:r,activeIndex:i}=vn(n),a=n.searchDebouncing?[]:r;if(e.key===`Enter`){e.preventDefault();let t=a[i];t&&pn(t,n);return}if(a.length===0||n.query.includes(`
`)||e.key!==`ArrowDown`&&e.key!==`ArrowUp`)return;e.preventDefault();let o=e.key===`ArrowDown`?1:-1;n.onActiveIdChange(a[(i+o+a.length)%a.length].id),mn()}function gn(e){return`cmd-palette-option-${e}`}function _n(e,t){return t===`all`||e.category===(t===`sessions`?`chats`:`messages`)}function vn(e){let t=e.promptMode||e.mentionMenu.open||e.draft.mentions.length>0,n=t?[]:Zt({...e,query:e.searchQuery,includeSlashCommands:!!e.onSlashCommand}),r=fn(n.filter(t=>_n(t,e.filter))),i=r.flatMap(([,e])=>e);return{hideSearch:t,matches:n,grouped:r,items:i,activeIndex:Math.max(0,i.findIndex(t=>t.id===e.activeId))}}function yn(e){let t=e();if(!t.open)return k;let n=t.mentionMenu.open,r=L(t.mentionHost.paneId,`mention-menu-listbox`),i=L(t.mentionHost.paneId,`mention-announcement`),{hideSearch:a,matches:o,grouped:c,items:l,activeIndex:u}=vn(t),d=[t.sessionSearchFailed?y(`palette.searchFailed`):t.sessionSearchIndexing?y(`palette.searchIndexing`):t.sessionSearchPartial?y(`palette.searchPartial`):null,t.archivedTranscriptsExcluded>0?y(`sessionsView.transcriptSearchArchivedExcluded`,{count:String(t.archivedTranscriptsExcluded)}):null].filter(e=>!!e),f=!t.searchDebouncing&&l[u]?gn(u):void 0,p=y(`palette.placeholder`),m=y(t.draft.submitting?`palette.startingSession`:`palette.startSession`),h=t.composing||!t.draft.canSubmit,g=t.draft.disabledReason??(t.draft.hasPrompt?void 0:y(`palette.promptRequired`)),ee=w(_.modifiedEnter),te=!!t.searchQuery.trim()&&!t.sessionSearchPending&&!t.catalogSearchPending&&!t.modelSearchError&&!t.sessionSearchFailed&&!t.sessionSearchPartial&&!t.sessionSearchIndexing&&t.archivedTranscriptsExcluded===0;return O`
    <openclaw-modal-dialog
      class="cmd-palette-overlay palette"
      label=${p}
      style=${be}
      @modal-cancel=${e=>{if(t.composing||t.mentionMenu.open){e.preventDefault(),t.composing||(t.mentionMenu.close(),t.requestUpdate());return}if(t.draft.submitting){e.preventDefault();return}t.onToggle()}}
    >
      <div
        class="cmd-palette ${a?`cmd-palette--prompt`:``}"
        @click=${e=>e.stopPropagation()}
        @keydown=${t=>hn(t,e)}
      >
        ${we({value:t.query,placeholder:p,onInputRef:t.onInputRef,onValueChange:t.onQueryChange,onBeforeInput:t.onBeforeInput,onSelectionChange:t.onSelectionChange,onCompositionStart:t.onCompositionStart,onCompositionEnd:t.onCompositionEnd,onPaste:t.draft.pasteImages,disabled:t.draft.submitting,readOnly:t.draft.messageLocked,controls:n?r:a?void 0:X,activeDescendant:n?(t.draft.mentions.length<10?t.mentionMenu.activeId(t.mentionHost.paneId):null)??void 0:f,describedBy:n?i:a?void 0:`cmd-palette-keys`,actions:O`
            <openclaw-tooltip content=${g??y(`palette.startSessionBackground`)}>
              <button
                type="button"
                class="cmd-palette__create"
                aria-label=${y(`palette.startSessionBackground`)}
                aria-busy=${String(t.draft.submitting)}
                ?disabled=${h}
                @click=${()=>{t.composing||t.draft.submit()}}
              >
                ${m}${ee}
              </button>
            </openclaw-tooltip>
            ${t.draft.renderControls()}
          `})}
        ${t.draft.mentions.length?O`<div class="cmd-palette__mentions" ?inert=${t.draft.messageLocked}>
                ${dt(t.query,t.draft.mentions,()=>{t.draft.setMessage(t.query,[]),t.requestUpdate(),t.mentionHost.getTextarea()?.focus({preventScroll:!0})},t.mentionMenu.selectedAvatarUrls)}
              </div>`:k}
        ${t.draft.renderAttachments()}
        ${t.mentionMenu.render(t.mentionHost,t.requestUpdate)}
        <span
          id=${i}
          class="sr-only"
          role="status"
          aria-live="polite"
          aria-atomic="true"
          >${t.mentionMenu.activeLabel()}</span
        >
        <div
          class="cmd-palette__search"
          ?inert=${a}
          aria-hidden=${a?`true`:k}
        >
          <div class="cmd-palette__search-content">
            ${a?Ke:O`
                    ${t.searchQuery.trim()&&t.onSelectSession?O`<div
                            class="cmd-palette__filters"
                            role="group"
                            aria-label=${y(`palette.filterLabel`)}
                          >
                            ${[`all`,`sessions`,`messages`].map(e=>O`<button type="button" class="cmd-palette__filter" aria-pressed=${t.filter===e?`true`:`false`} @click=${()=>t.onFilterChange(e)}>${y(`palette.filters.${e}`)}<span>${o.filter(t=>_n(t,e)).length}</span></button>`)}
                          </div>`:k}
                    ${t.sessionSearchPending||t.catalogSearchPending?O`<div class="cmd-palette__empty" role="status">
                            ${y(t.sessionSearchPending?`palette.searchingSessions`:`palette.searchingCommands`)}
                          </div>`:k}
                    <div
                      id=${X}
                      class="cmd-palette__results"
                      ?hidden=${l.length===0}
                      role="listbox"
                      aria-label=${p}
                      aria-busy=${t.searchDebouncing||t.sessionSearchPending||t.catalogSearchPending?`true`:`false`}
                    >
                      ${c.map(([e,n])=>O`
                          <div class="cmd-palette__group-label">
                            ${Yt(e)}<span
                              class="cmd-palette__group-count"
                              >${n.length}</span
                            >
                          </div>
                          ${n.map(e=>{let n=l.indexOf(e),r=n===u,i=e.session?s(e.session,t.defaultAgentId):e.agentId,a=i?t.agents.find(e=>e.id===i)??{id:i}:void 0;return O`
                              <div
                                id=${gn(n)}
                                class="cmd-palette__item ${e.session?`cmd-palette__item--session`:``} ${r?`cmd-palette__item--active`:``}"
                                role="option"
                                aria-selected=${r?`true`:`false`}
                                aria-disabled=${t.draft.submitting||t.searchDebouncing?`true`:k}
                                @click=${n=>{n.stopPropagation(),pn(e,t)}}
                                @mouseenter=${()=>t.onActiveIdChange(e.id)}
                              >
                                ${un(e,t.searchQuery,a,t.agentIdentity?.get(i),t.pluginIconUrls,t.onPluginIconError)}
                              </div>
                            `})}
                        `)}
                    </div>
                    ${t.modelSearchError?O`<div class="cmd-palette__source-error" role="status">${t.modelSearchError}</div>`:k}
                    ${d.map(e=>O`<div class="cmd-palette__source-error" role="status">${e}</div>`)}
                    ${l.length===0&&te?O`<div class="cmd-palette__no-results" role="status">
                            <span class="cmd-palette__no-results-icon" aria-hidden="true"
                              >${T.messageSquarePlus}</span
                            >
                            <h2>${y(`palette.noResults`)}</h2>
                            <p>
                              ${S(y(`palette.noResultsStart`,{shortcut:`{shortcut}`}),w(_.modifiedEnter,{inline:!0}))}
                            </p>
                          </div>`:k}
                    <div id="cmd-palette-keys" class="cmd-palette__footer">
                      ${l.length>0&&!t.query.includes(`
`)?O`<span class="cmd-palette__hint"
                                >${x([`↑`,`↓`])}${` `}<span
                                  >${y(`palette.footer.navigate`)}</span
                                ></span
                              >
                              <span class="cmd-palette__hint"
                                >${x(`↵`)}${` `}<span
                                  >${y(`palette.footer.select`)}</span
                                ></span
                              >`:k}
                      <span class="cmd-palette__hint"
                        >${w(_.newline)}${` `}<span
                          >${y(`palette.footer.newline`)}</span
                        ></span
                      >
                    </div>
                  `}
          </div>
        </div>
        ${t.draft.error?O`<div class="cmd-palette__creation-error" role="alert">${t.draft.error}</div>`:k}
        ${t.draft.renderRecovery()===k?k:O`<div class="cmd-palette__footer">${t.draft.renderRecovery()}</div>`}
      </div>
    </openclaw-modal-dialog>
    ${t.draft.renderAuxiliary()}
  `}var bn,X;function xn(){return(xn=e((()=>{A(),Oe(),b(),F(),N(),ie(),ce(),lt(),pt(),q(),C(),_e(),dn(),Y(),E(),Te(),ve(),Ve(),ge(),P(),bn=Ue,X=`cmd-palette-listbox`})))()}var Sn,Cn,wn,Tn,Z,Q,$;function En(){return(En=e((()=>{t(),qe(),He(),ke(),De(),b(),N(),Xe(),pe(),zt(),ce(),Wt(),tt(),se(),ne(),ft(),G(),Tt(),q(),C(),Y(),xn(),Sn=200,Cn=2,wn=60,Tn=50,Z={includeGlobal:!1,includeUnknown:!1,configuredAgentsOnly:!0,excludeSubagents:!0,excludeCron:!0,excludeSystem:!0},Q=3e4,$=class extends de{get query(){return this.draft.message}constructor(){super(),this.desktopAvailable=!1,this.custodianAvailable=!1,this.open=!1,this.pluginIconUrls={},this.pluginIcons=new wt({getFetchContext:()=>bt(this.context),isConnected:()=>this.isConnected&&this.open&&this.gateway.connected,onUrlsChange:e=>{this.pluginIconUrls=e}}),this.mentionMenu=new _t,this.composing=!1,this.mentionHost={paneId:`command-palette`,getDraft:()=>this.query,getMentions:()=>this.draft.mentions,getTextarea:()=>this.inputElement??null,commitDraft:(e,t)=>this.draft.setMessage(e,t)},this.requestMentionUpdate=()=>{this.mentionMenu.open||this.draft.mentions.length>0?(this.clearSessionSearch(),this.clearCatalogSearch()):this.scheduleSessionSearch(this.query),this.requestUpdate()},this.filter=`all`,this.draft=new W(this,()=>({context:this.context,open:this.open}),{onClose:()=>this.closePalette(),onMessageChange:e=>{let t=e.trim(),n=Array.from(t).length;this.promptMode=t.includes(`
`)||(this.promptMode?n>Tn:n>=wn),t||(this.filter=`all`),this.scheduleSessionSearch(e)}}),this.searchQuery=``,this.promptMode=!1,this.activeId=null,this.sessionItems=[],this.catalogItems=[],this.sessionSearchPending=!1,this.sessionSearchFailed=!1,this.sessionSearchPartial=!1,this.archivedTranscriptsExcluded=0,this.sessionSearchIndexing=!1,this.subscriptions=new fe(this),this.sessionSearchTimer=null,this.sessionSearchId=0,this.modelReader=new Bt(()=>this.requestUpdate()),this.gateway=new et(this,{getGateway:()=>this.context?.gateway,invalidateRequests:()=>{this.clearSessionSearch(),this.clearCatalogSearch(),this.scheduleSessionSearch(this.query)},onSnapshot:()=>this.synchronizePresentationScope(),ensureInitialData:()=>this.scheduleSessionSearch(this.query)}),this.togglePalette=()=>{if(this.open){this.draft.submitting||this.closePalette();return}this.openPalette()},this.handleInputRef=e=>{this.inputElement?.removeEventListener(`focus`,this.adoptInitialInput),this.inputElement=e instanceof HTMLTextAreaElement?e:void 0,this.inputElement?.addEventListener(`focus`,this.adoptInitialInput)},this.adoptInitialInput=()=>{let e=this.inputElement;if(!this.open||!e?.isConnected||document.activeElement!==e)return;if(this.takeInitialInput){let t=this.takeInitialInput;this.takeInitialInput=void 0;let n=t();if(!n){this.closePalette();return}this.initialInput=n,this.draft.setMessage(n.value),e.value=n.value}let t=this.initialInput;t&&(this.initialInput=void 0,t.returnFocus!==void 0&&e.closest(`openclaw-modal-dialog`)?.setReturnFocusTarget(t.returnFocus),e.setSelectionRange(t.selectionStart,t.selectionEnd,t.selectionDirection),!t.submitRequested&&t.mentionTrigger!==void 0&&t.selectionStart===t.selectionEnd&&t.value.slice(0,t.selectionStart).lastIndexOf(`@`)===t.mentionTrigger&&(this.mentionMenu.syncDirectory(this.draft.mentionDirectory),this.mentionMenu.update(e,this.requestMentionUpdate,`trigger`)),t.imageFiles?.length?this.draft.adoptImageFiles(t.imageFiles,t.submitRequested):t.submitRequested&&this.draft.submit())},this.handleGlobalKeydown=e=>{e.defaultPrevented||this.composing||e.isComposing||e.keyCode===229||Re(e)&&(e.preventDefault(),this.togglePalette())},this.subscriptions.effect(()=>this.context?.gateway,e=>e.subscribeEvents(t=>{let n=c(t);this.context?.gateway===e&&(t.event===`cron`||t.event===`chat.metadata.changed`||n)&&(n===`clear`&&(this.catalogLoad=void 0,this.catalogItems=[]),this.open?this.ensureCatalogItems(!0):this.clearCatalogSearch())})),this.subscriptions.watch(()=>this.context?.agentSelection,(e,t)=>e.subscribe(t),()=>{this.clearSessionSearch(),this.clearCatalogSearch(),this.scheduleSessionSearch(this.query)})}connectedCallback(){super.connectedCallback(),document.addEventListener(`keydown`,this.handleGlobalKeydown)}disconnectedCallback(){document.removeEventListener(`keydown`,this.handleGlobalKeydown),this.initialInput=void 0,this.takeInitialInput=void 0,this.inputElement?.removeEventListener(`focus`,this.adoptInitialInput),this.inputElement=void 0,this.open=!1,this.mentionMenu.dispose(),this.composing=!1,this.mentionInput=void 0,this.activeId=null,this.clearSessionSearch(),this.clearCatalogSearch(),super.disconnectedCallback()}openPalette(e){let t=document.activeElement instanceof HTMLElement?document.activeElement:null;this.open=!0,this.mentionMenu.close(),this.draft.open(),this.composing=!1,this.mentionInput=void 0,this.takeInitialInput=typeof e==`function`?e:void 0,this.initialInput=typeof e==`function`?void 0:e??{value:this.query,selectionStart:this.query.length,selectionEnd:this.query.length,selectionDirection:`none`,returnFocus:t},this.initialInput&&this.draft.setMessage(this.initialInput.value),this.activeId=null,this.filter=`all`,this.scheduleSessionSearch(this.query)}synchronizePresentationScope(){let e=this.context?.gateway,t=e?D(e):void 0;this.presentationScope&&this.presentationScope!==t&&(this.closePalette(),this.activeId=null,this.clearCatalogSearch()),this.presentationScope=t}get isOpen(){return this.open}closePalette(){this.mentionMenu.close(),this.composing=!1,this.mentionInput=void 0,this.initialInput=void 0,this.takeInitialInput=void 0,this.open=!1,this.draft.close(),this.clearSessionSearch()}updated(){this.adoptInitialInput();let e=new Set(this.catalogItems.flatMap(e=>e.hasPluginIcon&&e.pluginId?[e.pluginId]:[]));this.pluginIcons.reconcileKeys(e);for(let t of this.querySelectorAll(`.cmd-palette__plugin-icon[data-plugin-icon-id]`)){let n=t.dataset.pluginIconId;n&&e.has(n)&&this.pluginIcons.load(n)}}invalidateSessionSearch(){this.sessionSearchTimer!==null&&(globalThis.clearTimeout(this.sessionSearchTimer),this.sessionSearchTimer=null),this.sessionSearchId+=1}clearSessionSearch(){this.invalidateSessionSearch(),this.sessionItems=[],this.sessionSearchPending=!1,this.sessionSearchFailed=!1,this.sessionSearchPartial=!1,this.archivedTranscriptsExcluded=0,this.sessionSearchIndexing=!1}clearCatalogSearch(){this.modelReader.clear(),this.catalogLoad=void 0,this.catalogItems=[],this.pluginIcons.reset()}ensureCatalogItems(e=!1){let t=this.context,n=t?.gateway,r=n?.snapshot.client;if(!this.open||this.promptMode||this.mentionMenu.open||this.draft.mentions.length>0||!t||!this.gateway.connected||!n||!r)return Promise.resolve();let i=t.agentSelection.state.selectedId??v(n.snapshot),a=this.catalogLoad,o=!e&&a?.client===r&&a.agentId===i&&(a.loadedAt===void 0||Date.now()-a.loadedAt<Q),s=this.modelReader.bind(n,{agentId:i});if((!o&&!e||s||this.modelReader.failed)&&this.modelReader.read(),o)return a.promise;let c=n.snapshot,l=D(n),u=$t({client:r,agentId:i,agents:()=>t.agents?.ensureList?.()??Promise.resolve(null),methodAvailable:e=>!!Ye(c,e)}).then(e=>{this.catalogLoad?.promise===u&&D(n)===l&&this.context?.gateway===n&&this.context?.agentSelection===t.agentSelection&&n.snapshot.client===r&&(this.catalogItems=e,this.catalogLoad={...this.catalogLoad,loadedAt:Date.now()})});return this.catalogLoad={client:r,agentId:i,promise:u},u}scheduleSessionSearch(e,t=!1){if(this.invalidateSessionSearch(),this.promptMode||this.mentionMenu.open||this.draft.mentions.length>0){this.clearSessionSearch(),this.clearCatalogSearch();return}let n=a(e);if(!this.open||!n){this.clearSessionSearch(),this.searchQuery=e,this.activeId=null;return}if(this.composing)return;let r=()=>{this.clearSessionSearch(),this.searchQuery!==e&&(this.activeId=null),this.searchQuery=e,!(n.length<Cn)&&(this.sessionSearchPending=!!(this.onSelectSession&&this.context?.sessions&&this.gateway.connected),this.ensureCatalogItems(),this.onSelectSession?this.searchSessions(n):this.sessionSearchPending=!1)};t?r():this.sessionSearchTimer=globalThis.setTimeout(r,Sn)}async searchSessions(e){let t=this.context,n=t?.sessions,r=t?.gateway,i=r?.snapshot.client;if(!n||r?.snapshot.phase!==`connected`||!i){this.sessionSearchPending=!1;return}let a=++this.sessionSearchId,o=D(r),s=()=>a===this.sessionSearchId&&D(r)===o&&this.open&&this.context?.sessions===n&&this.context?.gateway===r&&this.context?.agentSelection===t?.agentSelection&&r.snapshot.client===i&&r.snapshot.phase===`connected`,c=Ut({client:i,query:e,listOptions:Z,isCurrent:s}).then(e=>({error:!1,result:e})).catch(()=>({error:!0,result:null}));try{let t=await n.list({...Z,search:e,limit:10});if(!s()||!t)return;let r=t.sessions,i=new Set(r.map(e=>e.key)),a=await c;if(!s())return;let o=a.result;this.sessionSearchPartial=a.error,this.archivedTranscriptsExcluded=o?.archivedTranscriptsExcluded??0,this.sessionSearchIndexing=o?.indexing===!0,this.sessionItems=sn({visibleRows:r,visibleKeys:i,transcriptResult:o,search:e})}catch{s()&&(this.sessionSearchFailed=!0)}finally{s()&&(this.sessionSearchPending=!1)}}updateMentionMenu(e){if(this.mentionMenu.syncDirectory(this.draft.mentionDirectory),!this.mentionMenu.open&&!e)return;let t=this.inputElement;if(!t||this.composing||e?.isComposing||e?.inputType===`insertFromPaste`||e?.inputType===`insertFromDrop`){this.mentionMenu.close(),this.requestMentionUpdate();return}this.mentionMenu.update(t,this.requestMentionUpdate,e?e.inputType===`insertText`&&e.data?.includes(`@`)===!0?`trigger`:`input`:`selection`)}render(){this.mentionMenu.syncDirectory(this.draft.mentionDirectory);let e=this.modelReader.snapshot;return yn(()=>({basePath:this.context?.basePath??``,open:this.open,query:this.query,searchQuery:this.searchQuery,searchDebouncing:this.composing||this.query!==this.searchQuery,onFlushSearch:()=>this.scheduleSessionSearch(this.query,!0),promptMode:this.promptMode,mentionMenu:this.mentionMenu,mentionHost:this.mentionHost,requestUpdate:this.requestMentionUpdate,composing:this.composing,onBeforeInput:e=>{let t=this.inputElement;this.mentionInput=t?{value:t.value,start:t.selectionStart,end:t.selectionEnd,inputType:e.inputType}:void 0},onSelectionChange:()=>this.updateMentionMenu(),onCompositionStart:()=>{this.composing=!0,this.invalidateSessionSearch(),this.mentionMenu.close(),this.requestUpdate()},onCompositionEnd:()=>{this.composing=!1,this.updateMentionMenu(),this.scheduleSessionSearch(this.query)},activeId:this.activeId,filter:this.filter,onFilterChange:e=>{this.filter=e,this.activeId=null},agents:this.context?.agents.state.agentsList?.agents??[],agentIdentity:this.context?.agentIdentity,defaultAgentId:this.context?.agentSelection.state.selectedId??v(this.context?.gateway.snapshot??{}),sessionItems:this.sessionItems,modelSearchError:this.modelReader.failed?y(`palette.modelSearchFailed`):null,primaryModelSearch:e.hasSnapshot&&!e.modelSelectionPolicy?.restricted,catalogItems:[...Qt(je(this.context?.gateway.snapshot.hello?.auth??null),this.context?.nativeDeviceSettings),...this.catalogItems,...en(e)],sessionSearchPending:this.sessionSearchPending,catalogSearchPending:!!(a(this.searchQuery)&&!this.promptMode&&(this.catalogLoad&&this.catalogLoad.loadedAt===void 0||this.modelReader.pending)),sessionSearchFailed:this.sessionSearchFailed,sessionSearchPartial:this.sessionSearchPartial,sessionSearchIndexing:this.sessionSearchIndexing,archivedTranscriptsExcluded:this.archivedTranscriptsExcluded,desktopAvailable:this.desktopAvailable,custodianAvailable:this.custodianAvailable,onToggle:this.togglePalette,onQueryChange:(e,t)=>{this.draft.setMessage(e,$e(this.query,e,this.draft.mentions,this.mentionInput)),this.mentionInput=void 0,this.updateMentionMenu(t)},onActiveIdChange:e=>{this.activeId=e},onNavigate:this.onNavigate,onSelectSession:this.onSelectSession,onSlashCommand:this.onSlashCommand,pluginIconUrls:this.pluginIconUrls,onPluginIconError:e=>this.pluginIcons.handleError(e),onInputRef:this.handleInputRef,draft:this.draft}))}},i([M({attribute:!1})],$.prototype,`onNavigate`,void 0),i([M({attribute:!1})],$.prototype,`onSelectSession`,void 0),i([M({attribute:!1})],$.prototype,`onSlashCommand`,void 0),i([M({attribute:!1})],$.prototype,`desktopAvailable`,void 0),i([M({attribute:!1})],$.prototype,`custodianAvailable`,void 0),i([o({context:Be,subscribe:!0})],$.prototype,`context`,void 0),i([j()],$.prototype,`open`,void 0),i([j()],$.prototype,`pluginIconUrls`,void 0),i([j()],$.prototype,`composing`,void 0),i([j()],$.prototype,`filter`,void 0),i([j()],$.prototype,`searchQuery`,void 0),i([j()],$.prototype,`promptMode`,void 0),i([j()],$.prototype,`activeId`,void 0),i([j()],$.prototype,`sessionItems`,void 0),i([j()],$.prototype,`catalogItems`,void 0),i([j()],$.prototype,`sessionSearchPending`,void 0),i([j()],$.prototype,`sessionSearchFailed`,void 0),i([j()],$.prototype,`sessionSearchPartial`,void 0),i([j()],$.prototype,`archivedTranscriptsExcluded`,void 0),i([j()],$.prototype,`sessionSearchIndexing`,void 0),i([j()],$.prototype,`sessionSearchTimer`,void 0),i([j()],$.prototype,`catalogLoad`,void 0),customElements.get(`openclaw-command-palette`)||customElements.define(`openclaw-command-palette`,$)})))()}En();export{$ as CommandPalette};