UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

224 lines • 58.3 kB
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./session-progress-C-s0xOM2.js","./gateway-runtime-C77LeWZN.js","./session-snapshot-database-BBKeXATO.js","./control-ui-boot-shared-CkXlyZBY.js","./control-ui-boot-shared-gZIpWrfw.js","./control-ui-boot-shared-SQHdJTzb.js","./control-ui-boot-shared-VLPz5vN2.js","./config-runtime-BecGLziM.js","./control-ui-boot-shared-Q8KG_noF.js","./plugin-contracts-runtime-ByiEPbv_.js","./markdown-runtime-ORQpioyT.js","./control-ui-boot-chat-Ye5j4vAg.js","./control-ui-boot-shared-UG5ko-VG.js","./control-ui-boot-shared-dOnP4mAA.js","./control-ui-boot-shared-styles-BXPMRytW.js","./sidebar-update-runtime-DQZboSgD.js","./control-ui-boot-chat-k_u3nGjS.js","./chat-transcript-styles-BN-TorbW.js","./control-ui-boot-chat-styles-BcslGtWC.js","./control-ui-core-DI-Q_yCI.css","./control-ui-boot-shared-styles-DUf4zEvn.css","./control-ui-boot-shared-DIWJGbGi.css","./sidebar-update-runtime-Bpn2ByHA.css","./chat-transcript-styles-B0IJwY9P.css","./control-ui-boot-chat-styles-SRk09zDG.css","./control-ui-boot-chat-C2DT0d4M.css","./report-8rkbtzoL.js","./board-layout-BmeSfx17.js","./report-Cegj5HJR.css","./website-CO8I6LOD.js","./website-DHaa5x94.css","./browser-Cbyq_Ha0.js","./browser-panel-s0odPIu7.js","./scrollbar-styles-z704pTjt.js","./panel-icon-button-BbsY5x_R.js","./panel-tab-strip-CniNZmas.js","./gateway-websocket-url-BW0hi5Wr.js","./dock-destination-controls-BmjaupAr.js","./panel-empty-state-Cvj4wChf.js","./browser-QJsz_Ze0.css","./mcp-app-view-registration-B3yat5MI.js","./mcp-app-routing-DFzELUUu.js"])))=>i.map(i=>d[i]);
import{n as e,r as t}from"./rolldown-runtime-8BhlS34s.js";import{Gs as n,Ic as r,Js as i,Lc as a,Nu as o,Pu as s,_u as c,dn as l,ju as u,mi as ee,n as te,r as ne,un as re,vu as ie,xu as d,yu as f,zu as p}from"./control-ui-core-CBJ5efDh.js";import{Ai as ae,Bi as oe,Fi as se,G as ce,Hi as le,J as ue,Vi as de,di as fe,fi as pe,ki as me,zi as he}from"./control-ui-core-DtLivg_r.js";import{G as m,J as h,W as g,Z as ge,at as _,c as _e,f as ve,g as ye,h as be,l as xe,n as Se,rt as v,t as Ce}from"./lit-runtime-IOnANfcZ.js";import{Mt as we,Ur as Te,Wr as Ee,Zr as y,jt as b,ma as x,pa as S,wa as C}from"./ui-CmSP4d14.js";import{Mi as w,dt as De}from"./control-ui-boot-shared-XreXSF7h.js";import{B as Oe,R as ke,z as Ae}from"./control-ui-boot-chat-XPUNenUd.js";import{B as je,C as Me,S as Ne,_ as Pe,b as Fe,g as T,h as E,m as D,p as Ie,v as O,x as Le,y as Re,z as ze}from"./control-ui-boot-chat-CGYcTLro.js";import{H as k,U as A,a as Be,c as j,d as Ve,f as He,i as Ue,l as We,m as Ge,o as Ke,p as qe,r as Je,s as M,vt as Ye,yt as Xe}from"./control-ui-boot-chat-CmENwCKi.js";import{n as Ze,t as Qe}from"./control-ui-disabled-B8wp3jVt.js";import{n as $e,t as et}from"./near-viewport-observer-WgGck829.js";import{a as N,i as tt,r as nt}from"./widget-sandbox-host-COBvR0Ux.js";import{n as rt,t as it}from"./mcp-app-confirm-BOrRV_eo.js";import{n as at,r as ot}from"./sandbox-host-Dm6XHU23.js";function P(e){return e?.split(`:`,1)[0]?.trim()||`unknown`}function F(e,t){if(!e)return null;let n=I.find(t=>t.kind===e);if(!n)return null;let r=P(e);return t.some(t=>t.kind===e&&t.pluginId===r)?n:null}function st(e,t){return e.contentKind===`html`||e.contentKind===`plugin`&&!e.frameUrl&&F(e.pluginKind,t)?.previewSafe===!0}var I;function L(){return(L=e((()=>{s(),x(),I=[{kind:`session:progress`,tagName:`openclaw-session-progress-widget`,get label(){return p(`sessionProgressCard.widgetLabel`)},loadModule:()=>S(()=>import(`./session-progress-C-s0xOM2.js`),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25]),import.meta.url),previewSafe:!1},{kind:`session:report`,tagName:`openclaw-report-widget`,get label(){return p(`board.widget.kindReport`)},loadModule:()=>S(()=>import(`./report-8rkbtzoL.js`),__vite__mapDeps([26,1,2,7,3,4,5,6,8,9,10,11,12,13,14,15,16,17,18,27,19,20,21,22,23,24,25,28]),import.meta.url),previewSafe:!0},{kind:`session:website`,tagName:`openclaw-website-widget`,get label(){return p(`board.widget.kindWebsite`)},loadModule:()=>S(()=>import(`./website-CO8I6LOD.js`),__vite__mapDeps([29,1,2,7,3,4,5,6,8,9,10,11,12,13,14,15,16,17,18,27,19,20,21,22,23,24,25,30]),import.meta.url),previewSafe:!1},{kind:`browser:dashboard`,tagName:`openclaw-browser-dashboard-widget`,get label(){return p(`board.widget.kindBrowserDashboard`)},loadModule:()=>S(()=>import(`./browser-Cbyq_Ha0.js`),__vite__mapDeps([31,1,2,4,3,5,6,9,8,7,10,11,12,13,14,15,16,17,18,32,33,34,35,36,37,38,19,20,21,22,23,24,25,39]),import.meta.url),previewSafe:!1}]})))()}function R(e){return e.toSorted((e,t)=>e.position-t.position||e.tabId.localeCompare(t.tabId))}function ct(e,t,n){let r=e.tabId===t,i=e.tabId===n;return h`
    <wa-tab
      class=${`board-tabs__tab ${r?`board-tabs__tab--active`:``} ${i?`board-tabs__tab--drop`:``}`}
      panel=${e.tabId}
      ?active=${r}
      data-board-tab-id=${e.tabId}
    >
      ${e.title}
    </wa-tab>
  `}function lt(e){let{tabs:t,activeTabId:n,hoverTabId:r,onTabShow:i,onOverflowSelect:a}=e;if(t.length<=1)return m;let o=t.slice(0,6),s=t.find(e=>e.tabId===n);s&&!o.some(e=>e.tabId===s.tabId)&&(o[o.length-1]=s);let c=new Set(o.map(e=>e.tabId)),l=t.filter(e=>!c.has(e.tabId));return h`
    <nav class="board-tabs" aria-label=${p(`board.tabsLabel`)}>
      <wa-tab-group
        class="board-tabs__track"
        .active=${n}
        activation="manual"
        without-scroll-controls
        @wa-tab-show=${i}
      >
        ${o.map(e=>ct(e,n,r))}
      </wa-tab-group>
      ${l.length>0?h`
              <wa-dropdown
                class="board-tabs__overflow"
                placement="bottom-end"
                @wa-select=${a}
              >
                <button
                  class="board-tabs__overflow-trigger"
                  slot="trigger"
                  type="button"
                  aria-label=${p(`board.moreTabs`)}
                  title=${p(`board.moreTabs`)}
                >
                  •••
                </button>
                ${l.map(e=>h`
                    <wa-dropdown-item
                      class="board-tabs__overflow-item"
                      value=${e.tabId}
                      data-board-tab-id=${e.tabId}
                    >
                      ${e.title}
                    </wa-dropdown-item>
                  `)}
              </wa-dropdown>
            `:m}
    </nav>
  `}function z(){return(z=e((()=>{g(),s()})))()}function ut(e){let{appView:t,widget:n}=e,r=t?.status===`ready`&&t.expiresAtMs>Date.now()?t:void 0,i=h`<div class="board-widget__app-loading" data-test-id="board-mcp-app-loading">
    ${p(`board.widget.appLoading`)}
  </div>`,a=r&&(!e.active||e.nearVisible)?h`<mcp-app-view
          class="board-widget__mcp-app-view"
          .sessionKey=${e.sessionKey}
          .viewId=${r.viewId}
          .fillContainer=${!0}
          .surface=${`board`}
          .title=${n.title||n.name}
          @openclaw-mcp-app-view-expired=${e.expired}
        ></mcp-app-view>`:!e.nearVisible||!t?i:t.status===`stale`?h`<div class="board-widget__stale" data-test-id="board-mcp-app-stale">
              <strong>${p(`board.widget.appStaleTitle`)}</strong>
              <span>${p(`board.widget.appStaleDetail`)}</span>
              <div class="board-widget__grant-actions">
                <button
                  class="btn btn--small btn--primary"
                  type="button"
                  ?disabled=${e.loading}
                  @click=${e.retry}
                >
                  ${p(`board.widget.retry`)}
                </button>
                <button
                  class="btn btn--small"
                  type="button"
                  ?disabled=${e.busy}
                  @click=${e.remove}
                >
                  ${p(`board.widget.remove`)}
                </button>
              </div>
            </div>`:i;return h`<div class="board-widget__mcp-app">${e.accessNotice}${a}</div>`}function B(){return(B=e((()=>{g(),s()})))()}function V(e,t){return`${e}\0${t.name}\0${t.revision}\0${t.instanceId??``}\0${t.grantState}`}function H(e){e!==void 0&&window.clearTimeout(e)}var U,W;function G(){return(G=e((()=>{d(),$e(),U=5e3,W=class{constructor(e){this.host=e,this.loading=!1,this.appViewGeneration=0,this.key=``,this.generation=0,this.visibility=new et(600,()=>this.visibilityChanged())}get nearVisible(){return this.visibility.nearVisible}update(e,t){if(this.callbacks=t,!e||e.contentKind!==`mcp-app`||!t){this.reset();return}let n=V(this.host.sessionKey(),e),r=t.appViewGeneration();(n!==this.key||r!==this.appViewGeneration)&&(this.reset(),this.key=n,this.appViewGeneration=r)}activityChanged(){this.host.active()||(this.visibility.disconnect(),this.clearTimers())}observe(e,t){if(!e||!t){this.visibility.disconnect();return}this.visibility.observe(e)}sync(){let e=this.host.widget(),t=this.callbacks;if(!this.host.active()||!e||e.contentKind!==`mcp-app`||!t){this.renewalTimer=H(this.renewalTimer);return}if(!this.nearVisible){this.loading||(this.renewalTimer=H(this.renewalTimer));return}!this.state&&!this.loading?this.load(e,t,`cached`):this.state?.status===`ready`&&!this.loading&&this.renewalTimer===void 0&&this.expiryTimer===void 0&&this.scheduleRenewal(e,t,this.state,!1)}disconnect(){this.visibility.disconnect(),this.reset(),this.callbacks=void 0}retry(){let e=this.host.widget();this.host.active()&&e&&this.callbacks&&this.load(e,this.callbacks,`refresh`)}expire(){let e=this.host.widget(),t=this.callbacks;if(!e||!t)return;let n=this.loading;this.state={status:`stale`,error:`MCP App view expired`},this.loading=!1,this.host.requestUpdate(),this.host.active()&&!n&&this.load(e,t,`expired`)}reset(){this.clearTimers(),this.generation+=1,this.key=``,this.appViewGeneration=0,this.state=void 0,this.loading=!1}clearTimers(){this.renewalTimer=H(this.renewalTimer),this.expiryTimer=H(this.expiryTimer)}visibilityChanged(){queueMicrotask(()=>{this.host.connected()&&this.host.requestUpdate()}),!this.nearVisible&&!this.loading&&(this.renewalTimer=H(this.renewalTimer))}async load(e,t,n){if(!this.host.active()||this.loading||!this.nearVisible)return;let r=V(this.host.sessionKey(),e);if(r!==this.key)return;let i=++this.generation,a=()=>{let e=this.host.widget();return this.host.connected()&&i===this.generation&&this.key===r&&e?.contentKind===`mcp-app`&&V(this.host.sessionKey(),e)===r};this.clearTimers(),this.loading=!0;let o=n===`refresh`&&this.state?.status===`ready`?this.state:null;n===`expired`&&(this.state=void 0),this.host.requestUpdate(),o&&(this.expiryTimer=window.setTimeout(()=>{this.expiryTimer=void 0,a()&&(this.state={status:`stale`,error:`MCP App lease expired while renewing`},this.loading=!1,this.host.requestUpdate())},Math.max(0,o.expiresAtMs-Date.now())));let s;try{s=await(n===`cached`?t.widgetAppView(e.name,e.revision):t.refreshWidgetAppView(e.name,e.revision))}catch(e){if(!a())return;s={status:`stale`,error:f(e)}}if(a()){if(s.status===`stale`&&o&&o.expiresAtMs>Date.now()){this.loading=!1,this.host.requestUpdate();return}this.clearTimers(),this.state=s,this.loading=!1,this.scheduleRenewal(e,t,s,n!==`cached`),this.host.requestUpdate()}}scheduleExpiry(e,t){if(t.status!==`ready`)return;this.expiryTimer=H(this.expiryTimer);let n=this.key;this.expiryTimer=window.setTimeout(()=>{this.expiryTimer=void 0;let r=this.host.widget(),i=this.state;this.host.connected()&&this.key===n&&r?.name===e.name&&r.revision===e.revision&&i?.status===`ready`&&i.viewId===t.viewId&&i.expiresAtMs===t.expiresAtMs&&(this.state={status:`stale`,error:`MCP App lease expired`},this.host.requestUpdate())},Math.max(0,t.expiresAtMs-Date.now()))}scheduleRenewal(e,t,n,r){if(this.renewalTimer=H(this.renewalTimer),n.status!==`ready`||!this.host.active())return;let i=this.key,a=n.expiresAtMs-Date.now()-U;if(!this.nearVisible){r&&a<=0&&this.scheduleExpiry(e,n);return}if(a<=0){r?this.scheduleExpiry(e,n):this.load(e,t,`refresh`);return}this.renewalTimer=window.setTimeout(()=>{this.renewalTimer=void 0;let n=this.host.widget();this.host.connected()&&this.host.active()&&this.nearVisible&&this.key===i&&n?.name===e.name&&n.revision===e.revision&&this.load(n,t,`refresh`)},a)}}})))()}function dt(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.type===`openclaw:widget-bridge-request`&&typeof t.id==`string`&&t.id.length>0&&t.id.length<=128&&typeof t.method==`string`&&typeof t.ticket==`string`}function K(e,t){let n=e[t];if(typeof n!=`string`||n.length===0)throw Error(`widget host request ${t} is required`);return n}var q,ft,pt,mt,ht;function gt(){return(gt=e((()=>{Xe(),re(),q=8192,ft=5e3,pt=6e4,mt=12,ht=class{constructor(e){this.recentStatePayloads=new Map,this.pendingStates=new Map,this.stateAttemptTimes=[],this.frame=e.frame,this.ticket=e.ticket,this.client=e.client,this.rateKey=e.rateKey,this.confirmPrompt=e.confirmPrompt}updateIdentity(e,t){this.frame=e,this.ticket=t}async emitState(e){let t=JSON.stringify(e);if(t===void 0)throw Error(`widget state payload must be JSON`);if(new TextEncoder().encode(t).byteLength>q)throw Error(`widget state payload exceeds ${q} UTF-8 bytes`);let n=Date.now();for(let[e,t]of this.recentStatePayloads)n-t>=ft&&this.recentStatePayloads.delete(e);if(this.recentStatePayloads.has(t))return{ok:!0,appended:!1,coalesced:!0};let r=this.pendingStates.get(t);if(r)return await r;if(this.stateAttemptTimes=this.stateAttemptTimes.filter(e=>n-e<pt),this.stateAttemptTimes.length>=mt)throw Error(`widget state emission rate limit exceeded`);this.stateAttemptTimes.push(n);let i=this.client.request(`board.event`,{ticket:this.ticket,payload:e});this.pendingStates.set(t,i);try{let e=await i;return this.recentStatePayloads.set(t,Date.now()),e}finally{this.pendingStates.get(t)===i&&this.pendingStates.delete(t)}}async handle(e,t={}){if(e.ticket!==this.ticket)throw Error(`widget view ticket does not match the active frame`);let n=e.params;if(!C(n))throw Error(`widget host request params are invalid`);switch(e.method){case`host.open`:{let e=K(n,`url`);if(!/^https?:\/\//i.test(e))throw Error(`widget link url is invalid`);if(!l(e))throw Error(`widget link could not be opened`);return{ok:!0}}case`prompt.send`:{if(t.promptUserActivated!==!0)throw Error(`widget prompt requires active user interaction`);let e=K(n,`text`),r=await this.client.request(`board.prompt.authorize`,{ticket:this.ticket});if(t.isCurrent?.()===!1)throw Error(`widget prompt request is no longer current`);if(!await Ye(this.frame,e,this.rateKey,r.confirmationRequired===!1?void 0:this.confirmPrompt,t.isCurrent))throw Error(`widget prompt was not accepted`);return{ok:!0}}case`state.emit`:return await this.emitState(n.payload);case`data.read`:case`action.run`:{let t=e.method===`data.read`,r=t?`bindingId`:`action`,i=K(n,r),a=n.params;if(a!==void 0&&!C(a))throw Error(t?`widget data binding params are invalid`:`widget action params are invalid`);return await this.client.request(t?`board.data.read`:`board.action`,{ticket:this.ticket,[r]:i,...t&&a===void 0?{}:{params:a??{}}})}case`cron.trigger`:return await this.client.request(`board.action`,{ticket:this.ticket,action:`cron.trigger`,jobId:K(n,`jobId`)});default:throw Error(`widget host method is not supported: ${e.method}`)}}}})))()}function _t(e){return e instanceof J&&e.kind===`unavailable`||e instanceof DOMException&&e.name===`TimeoutError`||e instanceof TypeError}var J,vt;function yt(){return(yt=e((()=>{d(),N(),gt(),J=class extends Error{constructor(e,t){super(t),this.kind=e}},vt=class{constructor(e){this.options=e,this.active=!0,this.bridgeController=null,this.bridgePort=null,this.adoptedTicket=``,this.retiredTicket=``,this.offeredTicket=``,this.requestGeneration=0,this.pendingRequests=new Set,this.documentHost=new tt(this.documentOptions()),this.documentHost.setActive(e.connected!==!1)}get frame(){return this.options.frame}setActive(e){if(e!==this.active){if(this.active=e,this.documentHost.setActive(e&&this.options.connected!==!1),!e){this.cancelPendingRequests(`Widget inactive`),this.requestGeneration+=1;return}this.postHostInit()}}update(e){let t=this.options.client,n=this.options.connected!==!1&&e.connected===!1,r=this.documentKey(),i=this.options.sandboxUrl;this.options=e;let a=r!==this.documentKey(),o=i!==e.sandboxUrl;(a||o)&&(this.reset(),this.bridgeController=null,this.bridgeClient=void 0),(t!==e.client||n)&&(this.retiredTicket=this.adoptedTicket||e.widget.viewTicket||``,this.cancelPendingRequests(`Gateway connection changed`),this.requestGeneration+=1,this.bridgeController=null,this.bridgeClient=void 0,this.documentHost.loaded||this.documentHost.reset());let s=this.active&&e.connected!==!1;s||this.documentHost.setActive(!1),this.documentHost.update(this.documentOptions()),s&&this.documentHost.setActive(!0),e.widget.viewTicket&&!a&&(this.adoptedTicket&&this.bridgeController?.updateIdentity(e.frame,this.adoptedTicket),this.postHostInit())}reset(){this.documentHost.reset(),this.requestGeneration+=1,this.pendingRequests.clear(),this.bridgePort?.close(),this.bridgePort=null,this.adoptedTicket=``,this.retiredTicket=``,this.offeredTicket=``}dispose(){this.active=!1,this.reset(),this.documentHost.dispose(),this.bridgeController=null,this.bridgeClient=void 0}handleFrameError(){this.documentHost.handleFrameError()}handleMessage(e){if(e.source===this.options.frame.contentWindow&&e.origin===this.options.sandboxOrigin&&(this.documentHost.handleMessage(e),e.data?.method!==`ui/notifications/sandbox-proxy-ready`&&this.documentHost.ready)){if(e.data?.type===`openclaw:widget-prompt-offer`){e.ports[0]?.close();return}if(e.data?.type===`openclaw:widget-bridge-port-offer`){let t=e.ports[0];if(this.options.bridgeEnabled===!1||!t||this.bridgePort){t?.close();return}this.bridgePort=t,t.addEventListener(`message`,e=>{this.handleBridgeMessage(e.data)}),t.start(),this.postHostInit();return}e.data?.type===`openclaw:widget-bridge-ready`&&this.postHostInit()}}handleBridgeMessage(e){if(this.options.bridgeEnabled!==!1){if(e&&typeof e==`object`&&Reflect.get(e,`type`)===`openclaw:widget-host-init-ack`&&typeof Reflect.get(e,`ticket`)==`string`){let t=Reflect.get(e,`ticket`);if(t!==this.offeredTicket)return;this.offeredTicket=``,this.adoptedTicket=t,this.bridgeController?.updateIdentity(this.options.frame,t),this.postHostInit();return}if(!this.active){dt(e)&&this.postResponse(e.id,!1,void 0,`Widget inactive`);return}this.handleBridgeRequest(e)}}handleBridgeRequest(e){if(!this.documentHost.ready||!dt(e))return;let t=this.options.client,n=this.adoptedTicket;if(!t||!n||n===this.retiredTicket||this.options.connected===!1){this.postResponse(e.id,!1,void 0,`Gateway unavailable`);return}!this.bridgeController||this.bridgeClient!==t?(this.bridgeClient=t,this.bridgeController=new ht({frame:this.options.frame,ticket:n,client:t,rateKey:this.documentKey(),confirmPrompt:this.options.confirmPrompt})):this.bridgeController.updateIdentity(this.options.frame,n);let r=this.requestGeneration,i=this.options.frame;this.pendingRequests.add(e.id),this.bridgeController.handle(e,{promptUserActivated:e.method===`prompt.send`,isCurrent:()=>r===this.requestGeneration&&i===this.options.frame}).then(t=>{this.completeRequest(e.id,r,!0,t)}).catch(t=>{this.completeRequest(e.id,r,!1,void 0,f(t))})}completeRequest(e,t,n,r,i){t===this.requestGeneration&&this.pendingRequests.has(e)&&(this.pendingRequests.delete(e),this.postResponse(e,n,r,i))}cancelPendingRequests(e){for(let t of this.pendingRequests)this.postResponse(t,!1,void 0,e);this.pendingRequests.clear()}documentKey(){let e=this.options.resolveFrameUrl(this.options.widget.name,this.options.widget.revision).split(/[?#]/u,1)[0],t=this.options.widget.viewGeneration??this.options.widget.viewTicket??``,n=this.options.bridgeEnabled===!1?`passive`:`interactive`;return`${e}\0${this.options.widget.revision}\0${t}\0${n}`}postHostInit(){let e=this.options.widget.viewTicket;if(this.options.bridgeEnabled===!1||this.options.connected===!1||!this.documentHost.ready||!this.active||!this.bridgePort||!e||!this.documentHost.loaded||e===this.adoptedTicket||this.offeredTicket!==``)return;this.offeredTicket=e;let t=this.options.controlUiBaseUrl?.trim();this.bridgePort.postMessage({type:`openclaw:widget-host-init`,ticket:e,...t?{controlUiBaseUrl:t}:{}},[])}documentOptions(){let e=this.options;return{frame:e.frame,sandboxOrigin:e.sandboxOrigin,sandboxUrl:e.sandboxUrl,documentKey:this.documentKey(),loadDocument:t=>this.fetchDocument(e,t),retryDocument:_t,onLoaded:()=>{this.options.onLoaded(),this.postHostInit()},onPending:()=>this.options.onPending?.(),onRendered:e.onRendered?()=>this.options.onRendered?.():void 0,onError:e=>{e instanceof J&&e.kind===`unauthorized`?this.options.onUnauthorized(this.options.widget):_t(e)?this.options.onLoadFailed(this.options.widget):this.options.onError(e)},onReadyTimeout:()=>{this.reset(),this.options.onReadyTimeout()}}}async fetchDocument(e,t){let{widget:n,resolveFrameUrl:r,sourceOrigin:i}=e,a;try{a=new URL(r(n.name,n.revision),i)}catch(e){throw new J(`invalid-url`,f(e))}if(a.origin!==i)throw new J(`invalid-url`,`widget content URL is outside the active Gateway`);e.onFrameUrl(a.href);let o=await fetch(a.href,{cache:`no-store`,signal:t});if(o.status===401)throw new J(`unauthorized`,`widget content request failed (401)`);if(!o.ok)throw new J(o.status===408||o.status>=500?`unavailable`:`rejected`,`widget content request failed (${o.status})`);return await o.text()}postResponse(e,t,n,r){this.bridgePort?.postMessage({type:`openclaw:widget-bridge-response`,id:e,ok:t,...t?{result:n}:{error:r??`widget host request failed`}})}}})))()}function bt(){return typeof document<`u`&&document.visibilityState===`hidden`}function xt(e,t){return!e.sandboxOrigin&&t&&!ee(new URL(t).hostname)?p(`board.widget.sandboxOriginRequired`):p(`board.widget.frameAuthorizationFailed`)}var St,Ct,wt,Tt,Et,Y,Dt,Ot,kt,X,At,jt;function Mt(){return(Mt=e((()=>{g(),s(),yt(),ze(),d(),n(),we(),N(),ke(),ue(),rt(),k(),St=`openclaw:widget-size`,Ct=`openclaw:widget-board-host`,wt=`openclaw:widget-scroll`,Tt=`openclaw:widget-command-palette`,Et=`openclaw:widget-shortcut-host`,Y=3,Dt=15e3,Ot=1e3,kt=1e3,X=3e4,At=class{constructor(e,t){this.currentTicket=e,this.canRefresh=t,this.timer=null,this.attempts=0,this.scheduledTicket=``}clearTimer(){this.timer!==null&&(window.clearTimeout(this.timer),this.timer=null)}reset(){this.clearTimer(),this.attempts=0,this.scheduledTicket=``}schedule(e,t){let n=e?.viewTicket,r=e?je(e):void 0;if(!this.canRefresh()||!e||!t||!n||r===void 0){this.reset();return}if(this.scheduledTicket===n)return;this.clearTimer(),this.attempts=0,this.scheduledTicket=n;let i=Math.max(Ot,r-Dt);this.timer=window.setTimeout(()=>{this.timer=null,this.refresh(e.name,n,t)},i)}refresh(e,t,n){if(!this.canRefresh()){this.reset();return}if(this.currentTicket()!==t||this.scheduledTicket!==t)return;this.attempts+=1;let r=()=>{this.currentTicket()===t&&this.scheduledTicket===t&&(this.clearTimer(),this.timer=window.setTimeout(()=>{this.timer=null,this.refresh(e,t,n)},Math.min(kt*this.attempts,X)))};n(e).then(r,r)}},jt=class{constructor(e){this.host=e,this.error=``,this.waiting=!1,this.renderStalled=!1,this.frameFailureKey=``,this.frameRefreshAttempts=0,this.frameProbeGeneration=0,this.boardHostNonce=``,this.keyboardHostNonce=``,this.lastFrameUrl=``,this.sandboxOrigin=``,this.sandboxHost=null,this.contentVisible=!1,this.revealFrame=0,this.confirmation=new it(()=>this.host.requestUpdate()),this.ticketRefresh=new At(()=>this.host.widget()?.viewTicket,()=>this.host.active()&&!bt()&&this.gatewayAvailable()),this.handleVisibilityChange=()=>{if(bt()){this.ticketRefresh.reset();return}this.ticketRefresh.schedule(this.host.widget(),this.host.refreshFrame())},this.handleWindowMessage=e=>{if(!this.host.connected())return;let t=this.host.root().querySelector(`.board-widget__frame`);if(!t||e.source!==t.contentWindow)return;let n=this.host.widget();if(!this.host.active()){e.origin===this.sandboxOrigin&&this.sandboxHost?.handleMessage(e);return}let r=e.data;n&&r?.type===St&&typeof r.height==`number`&&Number.isFinite(r.height)&&r.height>0&&this.host.reportContentHeight(n.name,r.height),n&&r?.type===wt&&r.nonce===this.boardHostNonce&&typeof r.deltaY==`number`&&Number.isFinite(r.deltaY)&&r.deltaY!==0&&this.host.scrollBy(r.deltaY),n&&r?.type===Tt&&this.keyboardHostNonce&&r.nonce===this.keyboardHostNonce&&e.origin===this.sandboxOrigin&&t.isConnected&&document.activeElement===t&&!document.openClawModalLayers?.size&&window.dispatchEvent(new CustomEvent(ce)),n?.viewTicket&&e.origin===this.sandboxOrigin&&this.syncSandboxHost(t,n)?.handleMessage(e)}}get presentationReady(){return this.contentVisible||this.waiting||this.renderStalled||!!this.error}gatewayAvailable(){let e=this.host.context()?.gateway.snapshot;return!e||i(e)}connect(){window.addEventListener(`message`,this.handleWindowMessage),this.host.active()&&document.addEventListener(`visibilitychange`,this.handleVisibilityChange),Ae()}disconnect(){this.resetPresentation(),this.stopWork(),window.removeEventListener(`message`,this.handleWindowMessage),this.sandboxHost?.dispose(),this.sandboxHost=null}suspend(){this.stopWork(),this.sandboxHost?.setActive(!1)}stopWork(){this.confirmation.cancel(),document.removeEventListener(`visibilitychange`,this.handleVisibilityChange),this.ticketRefresh.reset()}activityChanged(){if(this.host.active()){this.connect(),this.sandboxHost?.setActive(this.gatewayAvailable());let e=this.host.root().querySelector(`.board-widget__frame`);e&&this.postBoardHostState(e)}else this.suspend()}widgetChanged(e,t){if(e.name!==t?.name||e.revision!==t?.revision){this.resetFailures(!1);return}if(!this.error)return;let n=this.host.resolveFrameUrl()?.(t.name,t.revision)??``;n&&n!==this.lastFrameUrl&&this.setError(``,!1)}update(){if(this.confirmation.update(),!this.host.active()){this.suspend();return}this.connect(),this.ticketRefresh.schedule(this.host.widget(),this.host.refreshFrame()),this.updateSandboxHost()}render(e){let t=this.host.resolveFrameUrl();if(!t)throw Error(p(`board.widget.frameResolverMissing`));let n=t(e.name,e.revision);this.lastFrameUrl=n;let r=this.resolveSandboxFrameUrl(e);if(r)return h`
        <div class="board-widget__frame-pane">
          ${this.confirmation.render()}
          ${this.contentVisible||this.host.loadingCovered?.()?m:this.renderStalled?h`<div class="board-widget__notice" role="status">
                    ${p(`board.widget.resourceUnavailable`)}
                    <button class="btn btn--small" @click=${()=>this.retryContent()}>
                      ${p(`common.retry`)}
                    </button>
                  </div>`:this.waiting?h`<div class="board-widget__notice" role="status">
                      ${p(`board.widget.waitingForConnection`)}
                    </div>`:A(`discussion`,p(`common.loading`),!1,!0)}
          <iframe
            class="board-widget__frame"
            style=${this.contentVisible?``:`opacity: 0`}
            ?inert=${!this.contentVisible}
            sandbox="allow-scripts allow-same-origin allow-forms"
            referrerpolicy="origin"
            loading="eager"
            title=${e.title||e.name}
            src=${r}
            @openclaw:restore-focus=${e=>{let t=e.currentTarget;t instanceof HTMLIFrameElement&&this.host.active()&&document.activeElement===t&&this.keyboardHostNonce&&t.contentWindow?.postMessage({type:`openclaw:widget-shortcut-focus`,nonce:this.keyboardHostNonce},this.sandboxOrigin)}}
            @error=${()=>{this.sandboxHost?this.sandboxHost.handleFrameError():this.refreshFailedFrame(e)}}
            @load=${e=>this.notifyBoardHost(e)}
          ></iframe>
        </div>
      `;if(e.sandboxUrl||e.sandboxPort||e.viewTicket)throw Error(p(`board.widget.sandboxUnavailable`));return h`
      <iframe
        class="board-widget__frame"
        sandbox="allow-scripts"
        referrerpolicy="no-referrer"
        loading="lazy"
        title=${e.title||e.name}
        src=${n}
        @error=${()=>this.refreshFailedFrame(e)}
        @load=${t=>{this.notifyBoardHost(t),this.verifyAuthorization(t,e)}}
      ></iframe>
    `}setError(e,t=!0){this.error!==e&&(this.error=e,t&&this.host.requestUpdate())}resetFailures(e=!0){this.confirmation.cancel(),this.waiting=!1,this.renderStalled=!1,this.resetPresentation(),this.frameProbeGeneration+=1,this.frameFailureKey=``,this.frameRefreshAttempts=0,this.setError(``,e),this.sandboxHost?.reset()}resetPresentation(){window.cancelAnimationFrame(this.revealFrame),this.revealFrame=0,this.contentVisible=!1}revealContent(){this.contentVisible||this.revealFrame||(this.revealFrame=window.requestAnimationFrame(()=>{this.revealFrame=window.requestAnimationFrame(()=>{this.revealFrame=0,this.contentVisible=!0,this.host.requestUpdate()})}))}refreshFailedFrame(e){if(!this.host.active())return;this.frameProbeGeneration+=1;let t=`${e.name}:${e.revision}`;if(this.frameFailureKey!==t&&(this.resetFailures(!1),this.frameFailureKey=t),this.frameRefreshAttempts>=Y){this.setError(xt(e,this.sandboxOrigin));return}let n=this.host.refreshFrame();if(!n){this.setError(p(`board.widget.frameResolverMissing`));return}this.frameRefreshAttempts+=1,n(e.name).catch(e=>{this.setError(f(e))}),this.frameRefreshAttempts>=Y&&this.setError(xt(e,this.sandboxOrigin))}verifyAuthorization(e,t){let n=e.currentTarget,r=n instanceof HTMLIFrameElement?n.getAttribute(`src`)??``:``;if(!r.startsWith(`/__openclaw__/board/`))return;let i=this.frameProbeGeneration+1;this.frameProbeGeneration=i;let a=()=>n instanceof HTMLIFrameElement&&n.isConnected&&n.getAttribute(`src`)===r&&this.frameProbeGeneration===i&&this.host.active()&&this.host.widget()?.name===t.name&&this.host.widget()?.revision===t.revision;fetch(r,{cache:`no-store`}).then(e=>{a()&&(e.status===401?this.refreshFailedFrame(t):e.ok&&this.resetFailures())}).catch(()=>{a()&&this.refreshFailedFrame(t)})}notifyBoardHost(e){let t=e.currentTarget;t instanceof HTMLIFrameElement&&this.postBoardHostState(t)}postBoardHostState(e){this.boardHostNonce=b(),this.keyboardHostNonce=this.sandboxOrigin?b():``,Oe(e,this.sandboxOrigin||`*`),e.contentWindow?.postMessage({type:Ct,nonce:this.boardHostNonce},this.sandboxOrigin||`*`),this.keyboardHostNonce&&e.contentWindow?.postMessage({type:Et,nonce:this.keyboardHostNonce},this.sandboxOrigin)}resolveSandboxFrameUrl(e){let t=this.host.context()?.gateway.connection.gatewayUrl;if(!e.sandboxUrl||!e.sandboxPort||!e.viewTicket||t===void 0)return;let n=ot(e.sandboxUrl,e.sandboxPort,e.sandboxOrigin,t,window.location.origin);return this.sandboxOrigin=new URL(n).origin,n}sandboxHostOptions(e,t){let n=this.host.resolveFrameUrl();if(!n)return;let r=this.host.context(),i=r?.gateway.snapshot.client,a=r?.gateway.connectionRevision,o=r?.gateway.snapshot.hello;return{frame:e,widget:t,bridgeEnabled:this.host.bridgeEnabled?.()??!0,connected:!r||r.gateway.snapshot.phase===`connected`,sandboxOrigin:this.sandboxOrigin,sandboxUrl:e.src,sourceOrigin:at(r?.gateway.connection.gatewayUrl??``,window.location.origin),controlUiBaseUrl:`${window.location.origin}${r?.basePath??``}`,client:r?.gateway.snapshot.client??void 0,resolveFrameUrl:n,confirmPrompt:n=>this.confirmation.request({frame:e,title:t.title||t.name,text:n,kind:`message`,isCurrent:()=>{let n=this.host.widget(),r=this.host.context()?.gateway;return this.host.active()&&this.host.connected()&&this.gatewayAvailable()&&e===this.host.root().querySelector(`.board-widget__frame`)&&n?.name===t.name&&n.revision===t.revision&&n.viewGeneration===t.viewGeneration&&r?.snapshot.client===i&&r?.connectionRevision===a&&r?.snapshot.hello===o}}),onFrameUrl:e=>{this.lastFrameUrl=e},onLoadFailed:()=>this.waitForConnection(),onUnauthorized:e=>this.refreshFailedFrame(e),onReadyTimeout:()=>this.waitForConnection(),onPending:()=>this.waitForConnection(),onLoaded:()=>{this.waiting=!1,this.resetPresentation(),this.frameFailureKey=``,this.frameRefreshAttempts=0,this.setError(``,!1),this.host.requestUpdate()},onRendered:()=>{this.postBoardHostState(e),this.waiting=!1,this.renderStalled=!1,this.setError(``),this.revealContent()},onError:e=>{if(e instanceof nt){this.renderStalled=!0,this.host.requestUpdate();return}this.setError(f(e))}}}retryContent(){this.renderStalled=!1,this.waiting=!1,this.sandboxHost?.reset(),this.host.requestUpdate()}waitForConnection(){this.waiting=!0,this.host.requestUpdate()}updateSandboxHost(){let e=this.host.root().querySelector(`.board-widget__frame`),t=this.host.widget();if(!e?.isConnected||!t||!t.sandboxUrl||!t.sandboxPort||!t.viewTicket){this.sandboxHost?.dispose(),this.sandboxHost=null;return}this.syncSandboxHost(e,t)}syncSandboxHost(e,t){let n=this.sandboxHostOptions(e,t);if(!n)return;let r=this.host.active()&&this.gatewayAvailable();return r||this.sandboxHost?.setActive(!1),!this.sandboxHost||this.sandboxHost.frame!==e?(this.sandboxHost?.dispose(),this.sandboxHost=new vt(n)):this.sandboxHost.update(n),this.sandboxHost.setActive(r),this.sandboxHost}}})))()}var Nt,Z;function Pt(){return(Pt=e((()=>{Ee(),g(),ge(),ve(),ae(),de(),s(),O(),L(),d(),c(),o(),a(),Qe(),te(),fe(),B(),G(),He(),Be(),Mt(),se(),w(),x(),Nt=()=>S(()=>import(`./mcp-app-view-registration-B3yat5MI.js`),__vite__mapDeps([40,1,2,12,4,3,5,6,9,8,7,10,13,14,15,41,11,16,17,18,19,20,21,22,23,24,25]),import.meta.url),Z=class extends u{constructor(...e){super(...e),this.fitAutoContent=!1,this.pageChrome=!1,this.tabs=[],this.session={sessionKey:``},this.sessionKey=``,this.active=!0,this.bridgeEnabled=!0,this.dragging=!1,this.focusTabIndex=-1,this.positionInSet=1,this.setSize=1,this.busy=!1,this.canMutate=!0,this.canGrant=!0,this.loadingCovered=!1,this.actionError=``,this.actionPending=!1,this.bodyErrored=!1,this.coreWidgetLoader=new he(this),this.pluginSubscriptions=new r(this).watchStore(()=>this.context?.plugins),this.appView=new W({active:()=>this.active,connected:()=>this.isConnected,requestUpdate:()=>this.requestUpdate(),sessionKey:()=>this.sessionKey,widget:()=>this.widget}),this.frame=new jt({active:()=>this.active,loadingCovered:()=>this.loadingCovered,bridgeEnabled:()=>this.bridgeEnabled,connected:()=>this.isConnected,context:()=>this.context,refreshFrame:()=>this.callbacks?.frameLoadFailed,reportContentHeight:(e,t)=>this.callbacks?.reportContentHeight(e,t),scrollBy:e=>{this.closest(`openclaw-board-view`)?.scrollBy({top:e,behavior:`auto`})},requestUpdate:()=>this.requestUpdate(),resolveFrameUrl:()=>this.widgetFrameUrl,root:()=>this,widget:()=>this.widget})}connectedCallback(){super.connectedCallback(),this.frame.connect(),this.requestUpdate()}willUpdate(e){let t=e.get(`widget`);t&&t!==this.widget&&(this.actionError=``,this.frame.widgetChanged(t,this.widget)),this.appView.update(this.widget,this.callbacks),e.has(`active`)&&(this.appView.activityChanged(),this.frame.activityChanged(),this.active&&this.appView.observe(this.querySelector(`.board-widget`),this.widget?.contentKind===`mcp-app`)),this.syncCoreWidget()}updated(){if(!this.isConnected){this.appView.observe(null,!1);return}this.appView.observe(this.querySelector(`.board-widget`),this.active&&this.widget?.contentKind===`mcp-app`),queueMicrotask(()=>{this.isConnected&&this.appView.sync()}),this.frame.update(),this.loadingCovered&&this.presentationReady&&this.dispatchEvent(new Event(`openclaw-board-widget-presentation`,{bubbles:!0}))}get presentationReady(){let e=this.widget;return!e?.viewTicket||e.grantState===`pending`||e.grantState===`rejected`||this.bodyErrored||this.frame.presentationReady}disconnectedCallback(){this.pluginSubscriptions.clear();for(let e of I)this.coreWidgetLoader.requestWhileActive(e,!1);this.frame.disconnect(),this.appView.disconnect(),super.disconnectedCallback()}async runAction(e,t){if(!(this.actionPending||this.busy)){this.actionPending=!0,this.actionError=``,Ue(this);try{await e()}catch(e){this.actionError=f(e),t&&ie({message:t})}finally{this.actionPending=!1}}}runGrantDecision(e,t,n){let r=p(n===`granted`?`board.widget.allowFailed`:`board.widget.rejectFailed`);this.runAction(()=>t.grant(e.name,n),r)}selectMenuItem(e){let t=this.widget,n=this.callbacks;if(t&&n&&this.active&&this.canMutate){if(e===`remove`){this.runAction(()=>n.remove(t));return}if(e?.startsWith(`move:`)){this.runAction(()=>n.moveToTab(t,e.slice(5)));return}if(e?.startsWith(`resize:`)){let r=e.slice(7),i=Je[r];i&&this.runAction(()=>n.resizeTo(t,i.w,i.h));return}if(e===`height:auto`){let e=t.heightMode===`fixed`?`auto`:`fixed`;this.runAction(()=>n.setHeightMode(t,e))}}}renderBody(e,t){e.contentKind===`mcp-app`&&oe(`mcp-app-view`,Nt).catch(()=>void 0);let n=e.grantState===`pending`?Ge({widget:e,disabled:this.busy||this.actionPending||!this.canGrant,onGrant:n=>this.runGrantDecision(e,t,n),...this.actionError?{error:M(this.actionError,!0)}:{}}):e.grantState===`rejected`?Ve({disabled:this.busy||this.actionPending||!this.canMutate,onRemove:()=>void this.runAction(()=>t.remove(e))}):m;if(e.contentKind===`mcp-app`)return ut({accessNotice:n,appView:this.appView.state,busy:this.busy||this.actionPending||!this.canMutate,active:this.active,loading:this.appView.loading,nearVisible:this.appView.nearVisible,sessionKey:this.sessionKey,widget:e,expired:()=>this.appView.expire(),remove:()=>void this.runAction(()=>t.remove(e)),retry:()=>this.appView.retry()});if(n!==m)return n;if(e.contentKind===`plugin`&&e.frameUrl)return this.frame.render(e);if(e.contentKind===`plugin`){let n=P(e.pluginKind),r=this.context?.gateway.snapshot.hello?.controlUiWidgetKinds??[],i=F(e.pluginKind,r);if(i){let t=this.coreWidgetLoader.visibleState;if(t?.element===i&&t.status===`error`)return pe({error:t.error,stale:t.stale,subtitle:i.label,onRetry:()=>this.coreWidgetLoader.retry()});if(!le(i))return h`<p class="board-widget__plugin-loading">
            ${p(`board.widget.pluginLoading`)}
          </p>`;let n=be(i.tagName);return ye`<${n} .widget=${e} .session=${this.session} .active=${this.active}></${n}>`}let a=this.context?.plugins,o=`${n}/${e.pluginKind?.slice(n.length+1)}`,s=r.some(t=>t.kind===e.pluginKind&&t.pluginId===n);if(s&&a?.registrations(`widgets`).find(e=>e.key===o))return ne(`widgets`,o,{...this.session,widget:{name:e.name,props:e.props},canMutate:this.canMutate,canGrant:this.canGrant},this.active);if(this.context&&this.context.gateway.snapshot.phase!==`connected`||a?.isLoading(n))return h`<p class="board-widget__plugin-loading">${p(`board.widget.pluginLoading`)}</p>`;let c=Ze(this.context,n);if(!c&&s&&a){let e=a.errors.find(e=>e.pluginId===n||e.pluginId===`host`);if(e)return j(e.message,()=>void a.refresh())}return Ke({pluginId:n,content:c,disabled:this.busy||this.actionPending||!this.canMutate,onRemove:()=>void this.runAction(()=>t.remove(e))})}return this.frame.render(e)}syncCoreWidget(){let e=this.widget,t=this.context?.gateway.snapshot.hello?.controlUiWidgetKinds??[],n=e?.contentKind===`plugin`&&!e.frameUrl?F(e.pluginKind,t):null;for(let e of I)this.coreWidgetLoader.requestWhileActive(e,this.isConnected&&this.active&&n===e)}handleKeyDown(e,t,n){if(e.target!==e.currentTarget||!this.canMutate||this.pageChrome)return;let r=e.key===`ArrowLeft`?`left`:e.key===`ArrowRight`?`right`:e.key===`ArrowUp`?`up`:e.key===`ArrowDown`?`down`:null;r&&(e.preventDefault(),e.altKey?this.runAction(()=>n.nudge(t,r)):n.focus(t,r))}render(){let e=this.widget,t=this.rect,n=this.callbacks;if(!e||!t||!n)return m;let r,i;try{r=this.frame.error?j(this.frame.error):this.renderBody(e,n),i=!!this.frame.error}catch(e){r=j(e),i=!0}this.bodyErrored=i;let a=e.title||e.name,o=!this.canMutate,s=i||this.actionError!==``||e.grantState===`pending`||e.grantState===`rejected`||e.contentKind===`mcp-app`||e.contentKind===`plugin`&&!e.frameUrl,c=e.contentKind===`html`||e.frameUrl?e.presentation??`card`:void 0,l=this.dragging||this.pageChrome?void 0:Pe(e,this.contentHeightPx,D(),this.fitAutoContent?240:void 0),u=l===void 0?``:` height: calc(${l}px - var(--board-widget-height-trim, 0px)); align-self: start;`;return h`
      <section
        class=${`board-widget ${this.pageChrome?`board-widget--page-chrome`:``} ${this.dragging?`board-widget--dragging`:``} ${c?`board-widget--${c}`:``}`}
        style=${`${Me(t)} --board-widget-rows: ${t.h}; --board-widget-order: ${this.positionInSet};${u}`}
        role="listitem"
        tabindex=${this.focusTabIndex}
        aria-posinset=${this.positionInSet}
        aria-setsize=${this.setSize}
        aria-label=${o||this.pageChrome?a:p(`board.widget.cellLabel`,{title:a})}
        data-widget-name=${e.name}
        data-test-id="board-widget"
        @focus=${()=>n.focusChanged(e.name)}
        @keydown=${t=>this.handleKeyDown(t,e,n)}
      >
        ${this.pageChrome?m:h`<header class="board-widget__bar">
                ${o?m:h`<span
                        class="board-widget__drag-handle"
                        aria-hidden="true"
                        title=${p(`board.widget.moveHandle`,{title:a})}
                        @pointerdown=${t=>n.movePointerDown(e,t)}
                      >
                        <span aria-hidden="true">⠿</span>
                      </span>`}
                <span class="board-widget__title" title=${a}>${a}</span>
                <span class="board-widget__kind"
                  >${e.contentKind===`mcp-app`?p(`board.widget.kindMcp`):e.contentKind===`plugin`?e.kindLabel||F(e.pluginKind,this.context?.gateway.snapshot.hello?.controlUiWidgetKinds??[])?.label||p(`board.widget.kindPlugin`):p(`board.widget.kindHtml`)}</span
                >
                ${qe(e)}
                ${o?m:We({widget:e,tabs:this.tabs,disabled:this.busy||this.actionPending,onSelect:e=>this.selectMenuItem(e.detail.item.value)})}
              </header>`}
        <div
          class=${`board-widget__body ${s?`board-widget__body--scrollable`:``} ${c===`card`?`board-widget__body--card`:``}`}
        >
          ${r}
          ${this.actionError&&e.grantState!==`pending`?h`<div class="board-widget__error-overlay">
                  ${M(this.actionError)}
                </div>`:m}
        </div>
        ${o||this.pageChrome?m:h`<span
                class="board-widget__resize-handle"
                aria-hidden="true"
                title=${p(`board.widget.resizeHandle`,{title:a})}
                @pointerdown=${t=>n.resizePointerDown(e,t)}
              ></span>`}
        ${e.grantState===`granted`&&!this.pageChrome?h`<span class="board-widget__grant-dot" aria-hidden="true"></span>`:m}
      </section>
    `}},y([Te({context:me,subscribe:!0})],Z.prototype,`context`,void 0),y([_({attribute:!1})],Z.prototype,`widget`,void 0),y([_({attribute:!1})],Z.prototype,`rect`,void 0),y([_({attribute:!1})],Z.prototype,`contentHeightPx`,void 0),y([_({type:Boolean})],Z.prototype,`fitAutoContent`,void 0),y([_({type:Boolean})],Z.prototype,`pageChrome`,void 0),y([_({attribute:!1})],Z.prototype,`tabs`,void 0),y([_({attribute:!1})],Z.prototype,`session`,void 0),y([_({attribute:!1})],Z.prototype,`sessionKey`,void 0),y([_({attribute:!1})],Z.prototype,`widgetFrameUrl`,void 0),y([_({attribute:!1})],Z.prototype,`callbacks`,void 0),y([_({type:Boolean})],Z.prototype,`active`,void 0),y([_({type:Boolean})],Z.prototype,`bridgeEnabled`,void 0),y([_({type:Boolean})],Z.prototype,`dragging`,void 0),y([_({type:Number})],Z.prototype,`focusTabIndex`,void 0),y([_({type:Number})],Z.prototype,`positionInSet`,void 0),y([_({type:Number})],Z.prototype,`setSize`,void 0),y([_({type:Boolean})],Z.prototype,`busy`,void 0),y([_({type:Boolean})],Z.prototype,`canMutate`,void 0),y([_({type:Boolean})],Z.prototype,`canGrant`,void 0),y([_({type:Boolean})],Z.prototype,`loadingCovered`,void 0),y([v()],Z.prototype,`actionError`,void 0),y([v()],Z.prototype,`actionPending`,void 0),customElements.get(`openclaw-board-widget-cell`)||customElements.define(`openclaw-board-widget-cell`,Z)})))()}var Ft=t({});function Q(e,t){return e.widgets.filter(e=>e.tabId===t).toSorted((e,t)=>e.position-t.position||e.name.localeCompare(t.name))}var $;function It(){return(It=e((()=>{g(),ge(),_e(),Ce(),s(),O(),o(),k(),De(),w(),z(),Pt(),$=class extends u{constructor(...e){super(...e),this.session={sessionKey:``},this.activeTabId=``,this.active=!0,this.bridgeEnabled=!0,this.canMutate=!0,this.canGrant=!0,this.fitAutoContent=!1,this.pageWidgetName=``,this.previewItems=null,this.gestureName=``,this.hoverTabId=``,this.announcement=``,this.announcementRevision=0,this.actionError=``,this.focusName=``,this.mutationPending=!1,this.initialLoading=!0,this.gesture=null,this.mutationRequestId=0,this.stableCellOrder=new Map,this.stableCellOrderSequence=0,this.visitedTabs=new Set,this.contentHeights=new Map,this.finePointerQuery=typeof window.matchMedia==`function`?window.matchMedia(Ie):null,this.handlePointerModeChange=()=>this.requestUpdate(),this.reconcileInitialPresentation=()=>{this.initialLoading&&this.snapshot&&[...this.querySelectorAll(`openclaw-board-widget-cell`)].filter(e=>!e.hidden).every(e=>e.hasUpdated&&!e.isUpdatePending&&e.presentationReady)&&(this.initialLoading=!1)},this.cellCallbacks={appViewGeneration:()=>this.callbacks?.appViewGeneration??0,grant:async(e,t)=>{if(!this.callbacks)return;let n=this.snapshot?.sessionKey;await this.callbacks.grant(e,t),n===this.snapshot?.sessionKey&&this.announce(p(t===`granted`?`board.announcement.granted`:`board.announcement.rejected`))},movePointerDown:(e,t)=>this.beginGesture(`move`,e,t),resizePointerDown:(e,t)=>this.beginGesture(`resize`,e,t),moveToTab:(e,t)=>this.moveWidget(e,this.nextPosition(t),t),resizeTo:async(e,t,n)=>this.applyOps([{kind:`widget_resize`,name:e.name,sizeW:t,sizeH:n,heightMode:`fixed`}],p(`board.announcement.resized`,{title:e.title||e.name})),setHeightMode:async(e,t)=>{let n=t===`fixed`?T(e,this.contentHeights.get(e.name),e.name===this.pageWidgetName?0:D()):e.sizeH;await this.applyOps([{kind:`widget_resize`,name:e.name,sizeW:e.sizeW,sizeH:n,heightMode:t}],p(`board.announcement.resized`,{title:e.title||e.name}))},reportContentHeight:(e,t)=>{let n=this.snapshot?.widgets.find(t=>t.name===e);n&&n.contentKind===`html`&&this.contentHeights.get(e)!==t&&(this.contentHeights.set(e,t),this.requestUpdate())},remove:async e=>this.applyOps([{kind:`widget_remove`,name:e.name}],p(`board.announcement.removed`,{title:e.title||e.name})),nudge:async(e,t)=>this.nudgeWidget(e,t),focus:(e,t)=>this.focusWidget(e,t),focusChanged:e=>{this.focusName=e},frameLoadFailed:async e=>this.callbacks?.frameLoadFailed?.(e),widgetAppView:async(e,t)=>await this.callbacks?.widgetAppView?.(e,t)??{status:`stale`,error:`MCP App view unavailable`},refreshWidgetAppView:async(e,t)=>await this.callbacks?.refreshWidgetAppView?.(e,t)??{status:`stale`,error:`MCP App view unavailable`}},this.handlePointerMove=e=>{let t=this.gesture;if(!t||e.pointerId!==t.pointerId)return;if(t.mode===`move`){let n=document.elementFromPoint(e.clientX,e.clientY)?.closest(`[data-board-tab-id]`),r=n?.closest(`openclaw-board-view`)===this?n.dataset.boardTabId??``:``,i=r!==``&&(this.snapshot?.tabs.some(e=>e.tabId===r)??!1),a=this.snapshot?this.activeTab(R(this.snapshot.tabs))?.tabId:this.activeTabId;if(this.hoverTabId=i&&r!==a?r:``,n){this.previewItems=t.items,t.dropValid=this.hoverTabId!==``;return}let o=this.querySelector(`.board-grid`),s=document.elementFromPoint(e.clientX,e.clientY);if(!o||s?.closest(`.board-grid`)!==o){this.hoverTabId=``,this.previewItems=t.items,t.dropValid=!1;return}t.dropValid=!0;let c=o.getBoundingClientRect(),l=Math.max(1,(c.width-132)/12),u=this.previewItems??t.items,ee=s?.closest(`openclaw-board-widget-cell`)?.widget?.name;this.previewItems=Le(u,t.name,{name:ee,x:Math.floor((e.clientX-c.left)/(l+12)),y:Math.floor((e.clientY-c.top)/68)});return}let n=this.querySelector(`.board-grid`)?.getBoundingClientRect(),r=n?Math.max(1,(n.width-132)/12):56,i=Math.round((e.clientX-t.originClientX)/(r+12)),a=Math.round((e.clientY-t.originClientY)/68);this.previewItems=Ne(t.items,t.name,t.originW+i,t.originH+a)},this.handlePointerUp=e=>{let t=this.gesture;if(!t||e.pointerId!==t.pointerId)return;this.handlePointerMove(e);let n=this.previewItems,r=this.hoverTabId;this.cancelGesture();let i=this.snapshot?.widgets.find(e=>e.name===t.name);if(!i)return;if(t.mode===`move`){if(!t.dropValid)return;let e=r?this.nextPosition(r):n?.find(e=>e.name===t.name)?.order??i.position;if(!r&&e===i.position)return;this.moveWidget(i,e,r||void 0).catch(()=>void 0);return}let a=n?.find(e=>e.name===t.name);a&&(a.w!==t.originW||a.h!==t.originH)&&this.cellCallbacks.resizeTo(i,a.w,a.h).catch(()=>void 0)},this.handlePointerCancel=e=>{this.gesture&&e.pointerId===this.gesture.pointerId&&this.cancelGesture()},this.handleTabShow=e=>{let t=this.snapshot?R(this.snapshot.tabs):[],n=this.activeTab(t)?.tabId??this.activeTabId;e.detail.name!==n&&t.some(t=>t.tabId===e.detail.name)&&this.callbacks?.selectTab(e.detail.name)},this.handleOverflowSelect=e=>{let t=e.detail.item.value;t&&this.snapshot?.tabs.some(e=>e.tabId===t)&&this.callbacks?.selectTab(t)}}connectedCallback(){super.connectedCallback(),this.finePointerQuery?.addEventListener(`change`,this.handlePointerModeChange)}willUpdate(e){let t=e.get(`session`);if((e.has(`session`)&&(t?.agentId!==this.session.agentId||t?.sessionKey!==this.session.sessionKey)||e.has(`snapshot`)&&e.get(`snapshot`)?.sessionKey!==this.snapshot?.sessionKey)&&(this.initialLoading=!0,this.scrollTop=0,this.visitedTabs.clear(),this.stableCellOrder.clear(),this.stableCellOrderSequence=0,this.contentHeights.clear()),e.has(`snapshot`)){this.actionError=``;let t=e.get(`snapshot`);if(t?.sessionKey!==this.snapshot?.sessionKey)this.mutationRequestId+=1,this.mutationPending=!1,this.focusName=``;else if(t&&this.snapshot){let e=new Map(t.widgets.map(e=>[e.name,e]));for(let t of this.contentHeights.keys()){let n=e.get(t),r=this.snapshot.widgets.find(e=>e.name===t);(!r||r.contentKind!==`html`||n?.revision!==r.revision)&&this.contentHeights.delete(t)}}let n=new Set(this.snapshot?.tabs.map(e=>e.tabId));for(let e of this.visitedTabs)n.has(e)||this.visitedTabs.delete(e);let r=new Set(this.snapshot?.widgets.map(e=>e.name));for(let e of this.stableCellOrder.keys())r.has(e)||this.stableCellOrder.delete(e)}e.has(`activeTabId`)&&(this.focusName=``),this.gesture&&(e.has(`snapshot`)||e.has(`activeTabId`)||e.has(`pageWidgetName`)||e.has(`active`)&&!this.active)&&this.cancelGesture()}disconnectedCallback(){this.finePointerQuery?.removeEventListener(`change`,this.handlePointerModeChange),this.cancelGesture(),super.disconnectedCallback()}updated(){this.reconcileInitialPresentation()}activeTab(e){return e.find(e=>e.tabId===this.activeTabId)??e[0]}announce(e){this.announcement=e,this.announcementRevision+=1}async applyOps(e,t){if(!this.callbacks)return;if(this.mutationPending)throw Error(p(`board.actionInProgress`));let n=this.snapshot?.sessionKey,r=this.mutationRequestId+1;this.mutationRequestId=r,this.mutationPending=!0,this.actionError=``;try{await this.callbacks.applyOps(e),r===this.mutationRequestId&&n===this.snapshot?.sessionKey&&this.announce(t)}catch(e){throw r===this.mutationRequestId&&n===this.snapshot?.sessionKey&&(this.actionError=p(`board.actionFailed`),this.announce(this.actionError)),e}finally{r===this.mutationRequestId&&(this.mutationPending=!1)}}nextPosition(e){let t=this.snapshot?.widgets.filter(t=>t.tabId===e).map(e=>e.position)??[0];return Math.max(-1,...t)+1}moveWidget(e,t,n){return this.applyOps([{kind:`widget_move`,name:e.name,position:t,...n===void 0?{}:{tabId:n}}],p(`board.announcement.moved`,{title:e.title||e.name}))}selectPageWidgetMenuItem(e,t,n){let r=this.snapshot?.widgets.find(t=>t.name===e);this.active&&this.canMutate&&this.pageWidgetName===e&&r?.revision===t&&r.tabId===this.activeTabId&&[...this.querySelectorAll(`openclaw-board-widget-cell`)].find(e=>e.pageChrome&&e.widget===r)?.selectMenuItem(n)}beginGesture(e,t,n){if(!this.active||!this.canMutate||n.button!==0||this.gesture||this.mutationPending)return;let r=this.snapshot,i=r?R(r.tabs):[],a=this.activeTab(i);if(!r||!a)return;n.preventDefault(),n.stopPropagation();try{n.currentTarget?.setPointerCapture?.(n.pointerId)}catch{}let o=E(Q(r,a.tabId),this.contentHeights);this.gesture={dropValid:!1,mode:e,name:t.name,originClientX:n.clientX,originClientY:n.clientY,originW:t.sizeW,originH:T(t,this.contentHeights.get(t.name),D()),pointerId:n.pointerId,items:o},this.previewItems=o,this.gestureName=t.name,window.addEventListener(`pointermove`,this.handlePointerMove),window.addEventListener(`pointerup`,this.handlePointerUp),window.addEventListener(`pointercancel`,this.handlePointerCancel)}cancelGesture(){window.removeEventListener(`pointermove`,this.handlePointerMove),window.removeEventListener(`pointerup`,this.handlePointerUp),window.removeEventListener(`pointercancel`,this.handlePointerCancel),this.gesture=null,this.previewItems=null,this.gestureName=``,this.hoverTabId=``}async nudgeWidget(e,t){let n=this.snapshot;if(!n)return;let r=E(Q(n,e.tabId),this.contentHeights),i=Fe(r,e.name,t).find(t=>t.name===e.name);i&&i.order!==e.position&&await this.moveWidget(e,i.order)}focusWidget(e,t){let n=this.snapshot;if(!n)return;let r=Q(n,e.tabId),i=r.findIndex(t=>t.name===e.name);if(i<0)return;let a=r[Math.max(0,Math.min(i+(t===`left`||t===`up`?-1:1),r.length-1))];a&&a.name!==e.name&&(this.focusName=a.name,this.updateComplete.then(()=>{[...this.querySelectorAll(`openclaw-board-widget-cell`)].find(e=>e.widget?.name===a.name)?.querySelector(`.board-widget`)?.focus()}))}renderGrid(e,t,n,r){let i=t.flatMap(t=>{let n=e.filter(e=>e.tabId===t.tabId),i=(t.tabId===r?this.previewItems:null)??E(n,this.contentHeights,this.fitAutoContent,this.pageWidgetName);return Re(i,this.fitAutoContent?240:void 0)}),a=new Set(e.filter(e=>e.tabId===r).map(e=>e.name)),o=i.filter(e=>a.has(e.name));for(let e of i)this.stableCellOrder.has(e.name)||(this.stableCellOrder.set(e.name,this.stableCellOrderSequence),this.stableCellOrderSequence+=1);let s=i.toSorted((e,t)=>(this.stableCellOrder.get(e.name)??0)-(this.stableCellOrder.get(t.name)??0)||e.name.localeCompare(t.name)),c=new Map(o.map((e,t)=>[e.name,t])),l=o.some(e=>e.name===this.focusName)?this.focusName:o[0]?.name??``,u=new Map(e.map(e=>[e.name,e]));return h`
      <div
        class="board-grid"
        role="list"
        aria-label=${p(`board.gridLabel`)}
        ?hidden=${o.length===0}
      >
        ${Se(s,e=>JSON.stringify([this.session.agentId,this.session.sessionKey,n,e.name]),e=>{let r=u.get(e.name);return r?h`
              <openclaw-board-widget-cell
                ?hidden=${!a.has(r.name)}
                ?inert=${!a.has(r.name)}
                .widget=${r}
                .rect=${e}
                .contentHeightPx=${this.contentHeights.get(r.name)}
                .fitAutoContent=${this.fitAutoContent}
                .pageChrome=${r.name===this.pageWidgetName}
                .tabs=${t}
                .session=${this.session}
                .sessionKey=${n}
                .widgetFrameUrl=${this.widgetFrameUrl}
                .callbacks=${this.cellCallbacks}
                .active=${this.active&&a.has(r.name)}
                .bridgeEnabled=${this.bridgeEnabled}
                .dragging=${r.name===this.gestureName}
                .focusTabIndex=${r.name===l?0:-1}
                .positionInSet=${(c.get(r.name)??0)+1}
                .setSize=${o.length}
                .busy=${this.mutationPending}
                .canMutate=${this.canMutate}
                .canGrant=${this.canGrant}
                .loadingCovered=${this.initialLoading}
              ></openclaw-board-widget-cell>
            `:m})}
        ${this.gesture?.mode===`move`?h`<div class="board-grid__append-zone" aria-hidden="true"></div>`:m}
      </div>
      ${o.length===0?h`
              <div class="board-empty" data-test-id="board-empty">
                <span class="board-empty__mark" aria-hidden="true">+</span>
                <strong>${p(`board.emptyTitle`)}</strong>
                <span>${p(`board.emptyHint`)}</span>
              </div>
            `:m}
    `}render(){let e=this.snapshot,t=R(e?.tabs??[]),n=this.activeTab(t),r=n?.tabId??this.activeTabId,i=e&&n?Q(e,n.tabId):[];n&&this.visitedTabs.add(r);let a=(e?.widgets??[]).filter(e=>this.visitedTabs.has(e.tabId)||this.stableCellOrder.has(e.name)),o=i.length===1&&i[0]?.sizeW===12,s=o&&(i[0]?.name===this.pageWidgetName||i[0]?.pluginKind===`session:website`||i[0]?.pluginKind===`browser:dashboard`),c=!e||this.initialLoading;return h`
      ${c?A(`board`,p(`common.loading`),!1,!0):m}
      <section
        class=${`board-view ${o?`board-view--single-full-width`:``} ${s?`board-view--page`:``} ${c?`board-view--loading`:``}`}
        aria-label=${p(`board.label`)}
        aria-busy=${c}
        ?inert=${c}
        @openclaw-board-widget-presentation=${this.reconcileInitialPresentation}
      >
        ${lt({tabs:t,activeTabId:r,hoverTabId:this.hoverTabId,onTabShow:this.handleTabShow,onOverflowSelect:this.handleOverflowSelect})}
        ${e?this.renderGrid(a,t,e.sessionKey,r):m}
        ${this.actionError?h`<div class="board-view__error" role="alert">${this.actionError}</div>`:m}
        <div class="board-announcer" aria-live="polite" aria-atomic="true">
          ${this.announcement?xe(this.announcementRevision,h`<span data-announcement-revision=${this.announcementRevision}
                    >${this.announcement}</span
                  >`):m}
        </div>
      </section>
    `}},y([_({attribute:!1})],$.prototype,`session`,void 0),y([_({attribute:!1})],$.prototype,`snapshot`,void 0),y([_({attribute:!1})],$.prototype,`activeTabId`,void 0),y([_({attribute:!1})],$.prototype,`widgetFrameUrl`,void 0),y([_({attribute:!1})],$.prototype,`callbacks`,void 0),y([_({type:Boolean})],$.prototype,`active`,void 0),y([_({type:Boolean})],$.prototype,`bridgeEnabled`,void 0),y([_({type:Boolean})],$.prototype,`canMutate`,void 0),y([_({type:Boolean})],$.prototype,`canGrant`,void 0),y([_({type:Boolean})],$.prototype,`fitAutoContent`,void 0),y([_({attribute:!1})],$.prototype,`pageWidgetName`,void 0),y([v()],$.prototype,`previewItems`,void 0),y([v()],$.prototype,`gestureName`,void 0),y([v()],$.prototype,`hoverTabId`,void 0),y([v()],$.prototype,`announcement`,void 0),y([v()],$.prototype,`announcementRevision`,void 0),y([v()],$.prototype,`actionError`,void 0),y([v()],$.prototype,`focusName`,void 0),y([v()],$.prototype,`mutationPending`,void 0),y([_({type:Boolean,reflect:!0,attribute:`data-initial-loading`})],$.prototype,`initialLoading`,void 0),customElements.get(`openclaw-board-view`)||customElements.define(`openclaw-board-view`,$)})))()}export{st as i,It as n,L as r,Ft as t};