UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

887 lines • 169 kB
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./markdown-mermaid-SJLrLUOj.js","./gateway-runtime-Cr51Pi7N.js","./session-snapshot-database-BurLa_ut.js","./control-ui-boot-shared-Sj2zqjOr.js","./plugin-contracts-runtime-CNCaYops.js","./control-ui-boot-shared-D4XEBdOG.js","./config-runtime-BecGLziM.js","./markdown-runtime-ORQpioyT.js","./sidebar-update-runtime-DonYLwN5.js","./theme-color-DAo4KRoc.js","./control-ui-core-yIvVj14Y.css","./control-ui-boot-shared-styles-DKyMAG_6.css","./control-ui-boot-shared-CXHNz0Bh.css","./sidebar-update-runtime-ah7rgQE7.css"])))=>i.map(i=>d[i]);
import{n as e}from"./rolldown-runtime-8BhlS34s.js";import{Ac as t,Al as n,Cu as r,El as i,Eu as a,Fl as o,Fs as s,Il as c,Iu as l,Lc as u,Ll as d,Lu as f,Ms as p,Qs as m,Sl as h,Su as g,Tu as _,Uc as v,Vc as y,W as b,Ys as x,bl as ee,du as S,jl as C,ju as w,kc as te,kl as ne,ku as re,o as ie,pu as ae,s as oe,sc as T,wu as se,xl as ce,z as le,zu as ue}from"./control-ui-core-BncvAZjR.js";import{A as de,I as fe,N as pe,j as me}from"./control-ui-boot-shared-Dfs-gZII.js";import{Ar as he,C as ge,Cr as _e,Jt as ve,Mr as ye,Or as be,Sr as xe,Ti as Se,Ua as Ce,Wa as we,Xn as Te,Zn as Ee,bi as De,cr as Oe,kr as ke,mn as Ae,mo as je,na as E,nn as Me,qt as Ne,ra as Pe,rn as Fe,sr as Ie,tn as Le,w as Re,wi as ze,wr as Be,xi as Ve,xr as He,yn as Ue}from"./control-ui-core-9qYjK5B2.js";import{$ as D,B as We,I as Ge,R as Ke,X as O,Y as k,Z as qe,a as Je,ct as A,d as Ye,g as Xe,i as Ze,mt as Qe,nt as $e,r as et,t as tt,u as nt,ut as j,z as rt}from"./lit-runtime-B8uOr6OX.js";import{Ct as it,M as at,On as ot,St as st,j as ct,kn as lt,nr as ut,rr as dt,wr as ft}from"./control-ui-boot-shared-umGE-sEP.js";import{G as pt,K as mt,M as ht,R as gt,U as _t,W as vt,z as yt}from"./control-ui-boot-chat-VeeaXyJz.js";import{Aa as bt,Bt as xt,Ca as St,Da as Ct,Do as wt,Eo as Tt,Fa as Et,Gr as Dt,Hr as Ot,Ia as kt,Ja as At,Ki as jt,La as Mt,Qr as Nt,Sa as M,Si as Pt,Ta as Ft,Ui as It,Ur as Lt,Vr as Rt,Xa as zt,Zr as Bt,_a as Vt,ao as Ht,ba as Ut,bn as Wt,br as Gt,da as Kt,di as qt,dt as Jt,gi as Yt,ja as Xt,ji as Zt,ka as Qt,la as $t,oo as en,qr as tn,ut as nn,va as rn,vr as an,wa as on,xa as sn,xr as cn,yn as ln,yr as un,zr as dn,zt as fn}from"./control-ui-boot-shared-DJkUdZmL.js";import{$ as pn,Ao as mn,B as hn,Ei as gn,Fi as _n,Oo as vn,Ot as N,Pi as yn,Qa as bn,Qi as xn,Qt as Sn,Xr as Cn,Yi as wn,Yr as Tn,Za as En,Zr as Dn,_a as On,bi as kn,ca as An,ei as jn,en as Mn,fa as P,hi as Nn,ii as F,ja as Pn,jt as Fn,ma as I,oa as In,qi as L,ro as Ln,sa as Rn,ti as zn,tt as Bn,wo as Vn,yi as Hn}from"./ui-DuRgK6kL.js";import{C as Un,D as Wn,E as Gn,S as Kn,b as qn}from"./control-ui-boot-shared-em9-jnbz.js";import{$i as Jn,$t as Yn,Ci as Xn,Ct as Zn,Di as Qn,Ei as $n,Et as er,Jr as tr,Jt as nr,Kt as rr,Mr as ir,Nr as ar,Ot as or,Pr as sr,Pt as cr,Qt as lr,Si as ur,St as dr,Tn as fr,Xi as pr,Yr as mr,Yt as hr,Zi as gr,Zt as _r,bt as vr,ea as yr,fn as br,ir as xr,jr as Sr,kt as Cr,mn as wr,mt as Tr,pt as Er,ta as Dr,vt as Or,wn as kr,wt as Ar}from"./control-ui-boot-shared-xfDhIVun.js";import{$s as jr,Gu as Mr,Hc as Nr,Qs as Pr,Qu as Fr,Sc as Ir,Uc as Lr,Xu as Rr,Zu as zr,ao as Br,bc as Vr,co as Hr,xc as Ur}from"./control-ui-boot-shared-D3oo_6Fq.js";import"./control-ui-boot-shared-styles-BaQ2sAfZ.js";import{B as Wr,C as Gr,E as Kr,S as qr,T as Jr,_ as Yr,h as Xr,w as Zr,x as Qr}from"./control-ui-boot-chat-Ck7W_FPO.js";import"./control-ui-boot-chat-DxoNF0Ad.js";var $r,ei;function ti(){return(ti=e((()=>{f(),$r={custodian:{pluginPlaceholder:`Ask OpenClaw about {plugin}`,pluginIntroTitle:`Ask about {plugin}`,pluginStarterPurpose:`What does it do?`,pluginStarterTools:`What tools does it have?`,pluginStarterSetup:`How do I set it up?`,pluginPromptPurpose:`What does {plugin} do?`,pluginPromptTools:`What tools does {plugin} provide?`,pluginPromptSetup:`How do I set up {plugin}?`,pluginHelpQuestion:`Explain {setting}`,pluginHelpFailed:`Could not prepare the setting question. Try Ask OpenClaw again.`,pluginHelpUnset:`Not set`,pluginHelpValue:`Current value: {value}`},pluginsPage:{installProgress:{title:`Installation progress`,stopped:`Installation stopped`,rejected:{title:`Plugin not installed`,recovery:`This attempt did not install the plugin. Resolve the reported issue, then select Retry install.`},saved:{title:`Installation saved`,recovery:`The installation was saved. Resolve the reported issue before reloading the plugin; do not install it again.`},unknown:{title:`Installation status unknown`,recovery:`The Gateway did not confirm the installation outcome. Reconnect and check installed plugins before trying again.`},retry:{title:`Installation failed`,recovery:`Resolve the reported issue, then select Retry install to try again.`},details:`Failure details`,viewStatus:`View status`,failure:`Installation failed`,resolve:{started:`Resolving package`,completed:`Package resolved`,failed:`Package resolution failed`},download:{started:`Downloading plugin`,completed:`Plugin downloaded`,failed:`Plugin download failed`},extract:{started:`Extracting archive`,completed:`Archive extracted`,failed:`Archive extraction failed`},files:{started:`Preparing plugin files`,completed:`Plugin files prepared`,failed:`Plugin file preparation failed`},dependencies:{started:`Installing plugin dependencies`,completed:`Plugin dependencies installed`,failed:`Dependency installation failed`},runtime:{started:`Applying plugin to Gateway`,completed:`Plugin applied to Gateway`,failed:`Plugin could not be applied to Gateway`}},editor:{title:`{name} settings`,search:`Search settings`,navigation:`Settings sections`,other:`Other`,noMatches:`No matching settings.`,empty:`This plugin has no configurable settings.`,permissions:`Permissions`,actions:`Actions for {name}`,reset:`Reset value`,ask:`Ask OpenClaw`},credentials:{stored:`••••••••`,replace:`Enter a new key to replace the stored credential.`,reveal:`Show API key`,hide:`Hide API key`,signup:`Get an API key`,useReference:`Use a secret reference`,editReference:`Edit reference`,viewSource:`View source`,fromSource:`From {source}`,environment:`From environment · {name}`,referenceTitle:`Secret reference`,referenceHelp:`Choose where this credential is stored. Saving changes the reference only; it does not rotate or test the secret.`,environmentHelp:`This credential comes from {name} in the Gateway environment. Change that environment variable at its source. Its value is never shown here.`,source:`Source`,provider:`Provider`,identifier:`Identifier`,sources:{env:`Environment`,file:`File`,exec:`Command provider`,store:`Secret store`},help:{env:`Use the environment variable name, for example SEARCH_API_KEY.`,file:`Use a JSON pointer such as /search/apiKey, or value for a single-value file provider.`,exec:`Use the identifier accepted by the configured command provider, such as team/search-key.`,store:`Use the stored secret name, for example SEARCH_API_KEY.`},unresolved:`This reference is currently unresolved. The configured source must provide the secret before the plugin can use it.`,invalid:`The setting could not accept this value. Check the source, provider, and identifier.`,invalidStored:`This credential has an invalid stored value. Replace it or edit its reference.`,stale:`Configuration changed. Reload this reference before editing it.`,saveFailed:`The credential could not be saved. Your draft is still available; try saving again.`},detailCapabilities:`Capabilities`,uiCapabilities:{page:{name:`Pages`,description:`Adds pages to OpenClaw.`},navigation:{name:`Navigation`,description:`Adds links to OpenClaw navigation.`},panel:{name:`Panels`,description:`Adds interface panels.`},action:{name:`Actions`,description:`Adds buttons or menu actions.`},accessory:{name:`Session accessories`,description:`Adds information or controls alongside sessions.`},widget:{name:`Dashboard widgets`,description:`Adds widgets to the dashboard.`},replacement:{name:`Interface replacements`,description:`Replaces supported parts of the interface.`},"link-reader":{name:`Link previews`,description:`Shows previews and details for supported links.`}},capabilityFamilies:{speechProviders:{name:`Text to speech`,description:`Turn text into spoken audio.`},realtimeTranscriptionProviders:{name:`Live transcription`,description:`Transcribe audio as it arrives.`},realtimeVoiceProviders:{name:`Realtime voice`,description:`Support live voice conversations.`},mediaUnderstandingProviders:{name:`Media understanding`,description:`Analyze supported media inputs.`},imageGenerationProviders:{name:`Image generation`,description:`Create images from prompts and supported references.`},videoGenerationProviders:{name:`Video generation`,description:`Create video with supported generation models.`},musicGenerationProviders:{name:`Music generation`,description:`Create music with supported generation models.`},embeddingProviders:{name:`Embeddings`,description:`Represent content for semantic search and retrieval.`},webSearchProviders:{name:`Web search`,description:`Find information on the web.`},webFetchProviders:{name:`Web fetching`,description:`Read content from web pages.`},webContentExtractors:{name:`Web content extraction`,description:`Extract readable content from web pages.`},documentExtractors:{name:`Document extraction`,description:`Extract content from supported documents.`},transcriptSourceProviders:{name:`Transcripts`,description:`Capture or import transcripts from supported sources.`},migrationProviders:{name:`Migration`,description:`Bring supported data into OpenClaw.`}},breadcrumb:`Breadcrumb`,settingsDescription:`Configure installed plugins, access, and lifecycle.`,settingsTabs:`Plugin settings sections`,settingsInstalled:`Installed`,settingsInstalledDescription:`Search and configure plugins available to this gateway.`,advanced:`Advanced`,advancedDescription:`Global plugin loading, allow and deny lists, and capability slot ownership.`,searchInstalled:`Search installed plugins`,noSettingsMatches:`No installed plugins match this search.`,noInstalled:`No plugins are installed.`,connectToManage:`Connect to the gateway to inspect plugins.`,auth:{accounts:`Accounts`,credentials:`Credentials`,edit:`Edit`,connected:`Connected`,configured:`Configured`,editAccount:`Edit {name} connection`,editCredential:`Edit {name}`,connectAccount:`Connect {name}`,configure:`Configure`,configureCredential:`Configure {name}`,connect:`Connect`,requestFailed:`Sign-in did not finish. Try connecting again.`,sessionExpired:`This sign-in session expired. Try connecting again.`},toggleNamed:`Enable or disable {name}`,schemaUnavailable:`Plugin settings schema is unavailable.`,pluginNotFound:`This installed plugin could not be found.`,configuration:`Configuration`,configurationDescription:`Settings declared by this plugin.`,accessCapabilities:`Access & capabilities`,accessCapabilitiesDescription:`What this plugin can access with the current policy.`,promptContextAccess:`Add context to prompts`,promptContextAccessDescription:`Allows hooks to add plugin context before a model runs.`,conversationAccess:`Read conversation context`,conversationAccessDescription:`Allows hooks to inspect conversation content.`,modelOverrideAccess:`Override model selection`,modelOverrideAccessDescription:`Allows plugin actions or subagents to choose another model.`,accessAllowed:`Allowed`,accessBlocked:`Blocked`,lifecycle:`Lifecycle`,lifecycleDescription:`Installed source, version, trust, and removal controls.`,version:`Version`,installedSource:`Installed source`,integrity:`Integrity`,trustStatus:`Trust status`,setupRequiredDescription:`Complete the required configuration before enabling this plugin.`,additionalConfigurationRequired:`This plugin requires additional configuration`,uninstall:`Uninstall`,uninstallNamed:`Uninstall {name}`,uninstallDescription:`Remove this plugin package and its configured entries.`,managedCannotUninstall:`This plugin is managed by its installation source and cannot be uninstalled here.`,searchLabel:`Search plugins`,hubTablistLabel:`Plugins sections`,workshopTab:`Workshop`,backToSkills:`Back to Skills`,installedPluginsTitle:`Installed plugins`,featuredTitle:`Featured`,loadingFeatured:`Loading featured plugins…`,noFeaturedResults:`No featured plugins are available right now.`,exploreTitle:`Explore plugins`,loadingDiscovery:`Loading ClawHub plugins…`,loadMore:`Load more`,loadingMore:`Loading more…`,discoveryOffline:`Connect to browse plugins from ClawHub.`,noDiscoveryResults:`No plugins found`,noDiscoveryResultsHint:`Try a different search or choose another filter.`,searchClawHub:`Search ClawHub plugins`,searchPlugins:`Search plugins`,viewsLabel:`Catalog views`,intentAll:`All`,intentTrending:`Trending`,intentOfficial:`Official`,intentBundled:`Bundled`,loadingCategories:`Loading plugin categories…`,categoriesLabel:`Plugin categories`,categoriesTitle:`Categories`,allCategories:`All categories`,catalogPaginationLabel:`Plugin catalog pages`,previousPage:`Back`,nextPage:`Next`,pageNumber:`Page {page}`,downloadCount:`{count} downloads`,catalogPluginColumn:`Plugin`,catalogDownloadsColumn:`Downloads`,localPopularityUnavailable:`This plugin has not been published to ClawHub and does not have download metrics.`,detailBack:`Back to Explore plugins`,detailLoading:`Loading plugin details…`,detailSections:`Plugin details`,detailViewOnClawHub:`View on ClawHub`,detailUpdated:`Updated`,detailPublished:`Published`,detailRepository:`Repository`,detailDocumentation:`Documentation`,detailCategories:`Categories`,detailInstalledVersion:`Installed version`,detailSettings:`Settings`,detailEnable:`Enable`,detailDisable:`Disable`,detailTools:`Tools`,detailToolInputs:`Inputs`,detailType:`Type`,detailSecurity:`Security audit`,detailSecurityAudit:`View security audit`,detailNoReadme:`This plugin does not include a README.`,detailNoSkills:`This plugin does not declare any skills.`,detailNoConfiguration:`This plugin does not declare any configuration fields.`,detailNoCompatibility:`No compatibility requirements were published.`,detailNoVersions:`No release history is available.`,detailRequired:`Required`,detailOptional:`Optional`,detailSensitive:`Sensitive`,detailMinimumGateway:`Minimum Gateway version`,detailPluginApi:`Plugin API`,detailBuiltWith:`Built with OpenClaw`,detailSdkVersion:`Plugin SDK`,detailSourceCommit:`Source commit`,detailSourcePath:`Source path`,detailMcpServer:`MCP Server`,detailMcpServers:`MCP Servers`,mcpDetails:{endpoint:`Endpoint`,endpointRedacted:`Withheld because the endpoint may contain private connection details.`,transport:`Transport`,authentication:`Authentication`,scope:`Requested permissions`,unavailable:`Connection details are not included in this plugin’s catalog metadata.`,auth:{oauth:`OAuth`,"api-key":`API key`,none:`None`}},detailTabs:{readme:`README`,skills:`Skills`,configuration:`Configuration`,mcpServers:`MCP Servers`,commands:`Commands`,hooks:`Hooks`,lspServers:`LSP servers`,compatibility:`Compatibility`,versions:`Versions`,access:`Access`,lifecycle:`Lifecycle`,advanced:`Advanced`},installCount:`{count} installs`,installed:`Installed`,installedDisabled:`Installed · Disabled`,pluginSettings:`Plugin settings`,setupRequired:`Setup required`,setupRequiredNotice:`Additional configuration required before this plugin can be enabled.`,searchInstalledPlaceholder:`Search installed plugins`,showAllPlugins:`Show all {count}`,viewAllInstalledPlugins:`View all`,hideInstalledPlugins:`Hide`,tryAgain:`Try again`,loading:`Loading plugins…`,noInstalledTitle:`No optional plugins installed`,noInstalledMatchTitle:`No installed plugins match`,categoryChannels:`Channels`,categoryModels:`Models`,categoryMemory:`Memory`,categoryContext:`Context`,categoryWeb:`Web`,categoryVoice:`Voice`,categoryMedia:`Media`,categoryProviders:`Model providers`,categoryTools:`Tools`,categoryRuntime:`Runtime`,categoryGateway:`Gateway`,categorySecurity:`Security`,categoryOther:`Other`,categoryUncategorized:`Uncategorized`,remove:`Remove`,removeConfirmTitle:`Remove {name}?`,removeConfirmMessage:`This removes the plugin package and all of its entries. Active work using this plugin finishes before removal.`,cancel:`Cancel`,reload:`Reload`,installSaved:`Installation of {name} was saved. {error}`,installSavedNotApplied:`Installation of {name} was saved, but the Gateway has not applied it. {error} Fix the reported problem, then run openclaw plugins reload {name}.`,runtimeFailurePhase:`Runtime phase: {phase}.`,enableAction:`Enable`,working:`Working…`,detailOrigin:`Source`,detailPackage:`Package`,detailPluginId:`Plugin ID`,offlineBody:`Connect to browse installed and recommended plugins.`,optionalCapability:`Optional OpenClaw capability.`,enabled:`Enabled`,disabled:`Disabled`,available:`Available`,needsAttention:`Needs attention`,included:`Included`,global:`Global`,workspace:`Workspace`,config:`Config`,official:`Official`,community:`Community`,verifiedSource:`Verified source`,codePlugin:`Code plugin`,bundlePlugin:`Bundle plugin`,unavailable:`Unavailable`,install:`Install`,retryInstall:`Retry install`,retryInstallNamed:`Retry install of {name}`,viewInstallStatusNamed:`View status of {name} installation`,installing:`Installing`,installNamed:`Install {name}`,connectToChange:`Connect to the gateway to change plugins.`,adminRequired:`Plugin changes require operator.admin access.`,changesDisabled:`This gateway does not allow plugin changes.`,configRefreshFailed:`Could not refresh Control UI configuration: {error}`,continueInstall:`Continue installation`,installAvailabilityChanged:`Plugin availability changed. Refresh the catalog to see its current state.`,installDestinationChanged:`The Gateway or operator changed. Install the plugin again to request a fresh review.`}},ei=Object.assign(()=>{Object.assign(l.custodian,$r.custodian),l.pluginsPage=$r.pluginsPage},{catalog:$r})})))()}function ni(e){if(e.id===N.TUI)return`terminal`;if(e.mode===`webchat`||e.id===N.CONTROL_UI||e.id===N.BROWSER_COPILOT||e.id===N.WEBCHAT_UI||e.id===N.WEBCHAT)return`web`;if(e.id===N.CLI||e.mode===`cli`)return`cli`;if(e.mode===`ui`||e.id===N.MACOS_APP||e.id===N.LINUX_APP||e.id===N.IOS_APP||e.id===N.WATCHOS_APP||e.id===N.ANDROID_APP)return`app`}function ri(){return(ri=e((()=>{Fn()})))()}function ii(e){let t=e.map(e=>{let t=ni(e)??`rpc`,n=w(`chat.messages.sourceKinds.${t}`);return e.displayName&&e.displayName!==n?`${n} (${e.displayName})`:n});return w(`chat.messages.viaSource`,{source:[...new Set(t)].join(`, `)})}function ai(){return(ai=e((()=>{a(),Ht(),ri(),en()})))()}function oi(e){return e.replace(/^\/(?:Users|home)\/[^/]+(\/|$)/,`~$1`).replace(/^[A-Za-z]:\\Users\\[^\\]+(\\|$)/i,`~$1`)}function si(e){let t=at({name:e.name,args:e.args}),n=pt(t.name),r=Vn(n),i=vi[r],a=Wt(n),o=i?.label??i?.title??_t(n),{detail:s}=mt({toolKey:r,args:t.args,spec:i,fallbackDetailKeys:_i.detailKeys,detailMode:`first`,toolDetailMode:e.detailMode,detailCoerce:{includeFalsy:!0}});return s&&=oi(s),{name:n,icon:a,label:o,detail:s}}function ci(e){return e.detail?`with ${e.detail}`:void 0}function li(e){return e===hi||e.startsWith(`${hi}/`)||e===mi||e.startsWith(`${mi}/`)}function ui(e,t=!1){try{let n=new URL(e,`http://localhost`);return n.origin===`http://localhost`?li(n.pathname)?`${n.pathname}${n.search}${n.hash}`:void 0:!t||!dt(n)?void 0:n.toString()}catch{return}}function di(e){let t=e?.trim();return!!(t&&ui(t,!1))}function fi(e,t,n=!1){let r=e?.trim();if(!r)return;let i=ui(r,n);if(i){if(!t?.trim())return i;try{let e=new URL(t),n=e.pathname.replace(/\/+$/,``);if(!n.startsWith(gi))return i;let r=new URL(i,e.origin);return li(r.pathname)?(r.protocol=e.protocol,r.username=e.username,r.password=e.password,r.host=e.host,r.pathname=`${n}${r.pathname}`,r.toString()):i}catch{return i}}}function pi(e,t){if(t===`strict`||t===`scripts`&&e===`strict`)return``;if(t===`scripts`)return`allow-scripts`;switch(e){case`strict`:return``;case`trusted`:return`allow-scripts allow-same-origin`;default:return`allow-scripts`}}var mi,hi,gi,_i,vi;function yi(){return(yi=e((()=>{ut(),Gn(),ct(),vt(),ln(),mi=`/__openclaw__/a2ui`,hi=`/__openclaw__/canvas`,gi=`/__openclaw__/cap`,_i=Wn.fallback,vi=Wn.tools})))()}var bi,xi;function Si(){return(Si=e((()=>{f(),bi={browser:{unavailable:`Browser control is unavailable for this connection. Reconnect with browser access.`,navigationBlocked:`The current browser navigation rules block this address. Select another tab or enter an allowed address.`,navigationCheckFailed:`OpenClaw couldn’t verify this tab’s address. Refresh to try again.`,tabUnavailable:`This tab is no longer available. Select another tab.`,noChatTarget:`Open a chat session first so the annotation has somewhere to go.`,annotationLimitReached:`Remove a browser annotation before retrying (maximum 4 cards and 8,000 characters of generated context).`,inspectUnavailable:`Element inspection is disabled (browser.evaluateEnabled=false).`,annotationSent:`Annotation added to the chat composer.`,dashboardSessionShared:`You and your agent share this isolated session browser`,dashboardShared:`You and your agent share this browser page`,dashboardStopped:`This dashboard's browser is stopped.`,dashboardStopping:`Browser stop is pending. Retry to finish closing its tab.`,dashboardStop:`Stop browser`,dashboardRetryStop:`Retry stop`,dashboardResume:`Resume browser`,dashboardReconnect:`Reconnect`,dashboardUnavailable:`Connect to a Gateway with browser access to use this dashboard.`,dashboardMissingIdentity:`Save this dashboard widget again before opening its browser.`,dashboardInvalidReply:`The browser response does not match this dashboard. Reconnect and try again.`,downloading:`Downloading…`,downloadFile:`Download file`,inputLabel:`Browser input: click a field in the page, then type or paste`,manualTextCorrection:`Autocorrect is unavailable in browser control. Edit the text directly.`,errors:{pasteFailed:`Could not paste. Reconnect to a managed browser and try again.`,requestFailed:`Browser request failed: {error}`,downloadFailed:`Could not download this file: {error}. Try again, or open it in your browser to save it.`,downloadEmpty:`No file returned.`,screenshotPathMissing:`Browser screenshot did not return a media path.`,screenshotFetchTimedOut:`Screenshot fetch timed out.`,screenshotFetchFailed:`Screenshot fetch failed ({status}).`,screenshotReadFailed:`Screenshot read failed.`,screenshotDecodeFailed:`Screenshot decode failed.`,canvasUnavailable:`Canvas 2D context unavailable.`},annotatePrompt:{browserTarget:`Browser target: {target}`,introTitled:`I annotated the page at {url} (page-reported title: "{title}") — the attached screenshot shows my markup.`,introUntitled:`I annotated the page at {url} — the attached screenshot shows my markup.`,region:`Marked region {index}: centered around {x}% across / {y}% down, spanning about {width}% × {height}% of the view.`,moreRegions:`…plus {count} more marked region(s), all visible in the screenshot.`,elementDetail:`Marked element (page-reported): {descriptor} — {width}×{height}px at ({x}, {y}).`,outro:`Please look at the marked area and tell me what you make of it.`}}},xi=Object.assign(()=>{let{errors:e,annotatePrompt:t,...n}=bi.browser;Object.assign(l.browser,n),Object.assign(l.browser.errors,e),Object.assign(l.browser.annotatePrompt,t)},{catalog:bi})})))()}var Ci;function wi(){return(wi=e((()=>{Ci=String.raw`function openclawInspectBrowserElement(x, y) {
  const el = document.elementFromPoint(x, y);
  if (!el) return null;
  const rect = el.getBoundingClientRect();
  const label = el.getAttribute("aria-label") || el.getAttribute("alt") || el.getAttribute("title") || "";
  const text = (el.textContent || "").replace(/\s+/g, " ").trim();
  const nameSource = label || text;
  const nameLimit = 120;
  // This serialized page function cannot call imported helpers; back up only when the cap splits a surrogate pair.
  const nameEnd = (nameSource.codePointAt(nameLimit - 1) || 0) > 0xffff ? nameLimit - 1 : nameLimit;
  return {
    tag: el.tagName.toLowerCase(),
    id: el.id || "",
    classes: Array.from(el.classList).slice(0, 6),
    role: el.getAttribute("role") || "",
    name: nameSource.slice(0, nameEnd),
    rect: { x: rect.x, y: rect.y, width: rect.width, height: rect.height },
    focusable: typeof el.tabIndex === "number" && el.tabIndex >= 0,
  };
}`})))()}async function Ti(e,t,n=`open`){let r=P(await e.request(t.sessionScoped?`browser.dashboard.request`:`browser.request`,{...t.sessionScoped?{sessionKey:t.sessionKey,...t.agentId?{agentId:t.agentId}:{},dashboard:{name:t.name,instanceId:t.instanceId}}:{target:`host`},method:n===`stop`?`DELETE`:n===`inspect`?`GET`:`POST`,path:`/dashboard`,...n===`inspect`?{query:t.sessionScoped?{}:t}:{body:{...t.sessionScoped?{}:t,...n===`resume`?{resume:!0}:{}}},timeoutMs:12e4},{timeoutMs:15e4})),i=Dr(r?.browserTab);if(typeof r?.sessionKey!=`string`||!r.sessionKey||r.name!==t.name||r.instanceId!==t.instanceId||typeof r.revision!=`number`||!Number.isSafeInteger(r.revision)||typeof r.paused!=`boolean`||typeof r.stopping!=`boolean`||r.stopping&&!r.paused||typeof r.url!=`string`||!r.paused&&!i&&n!==`inspect`)throw Error(w(`browser.dashboardInvalidReply`));return{sessionKey:r.sessionKey,name:t.name,instanceId:t.instanceId,revision:r.revision,paused:r.paused,stopping:r.stopping,url:r.url,...i?{browserTab:i}:{}}}function Ei(e){let t={...P(e)};for(let e of[`target`,`targetId`,`node`,`profile`])delete t[e];return t}function Di(e){return e.slice(-64)}function Oi(e,t,n=()=>!0,r,i){return{async request(a,o,s){if(!n())throw new DOMException(`Browser request scope ended`,`AbortError`);let c=P(o);if(r?.sessionScoped){let t={method:c?.method,path:c?.path,...c?.timeoutMs===void 0?{}:{timeoutMs:c.timeoutMs},...c?.query?{query:Ei(c.query)}:{},...c?.body?{body:Ei(c.body)}:{},sessionKey:r.sessionKey,...r.agentId?{agentId:r.agentId}:{},dashboard:{name:r.name,instanceId:r.instanceId}};return s?await e.request(`browser.dashboard.request`,t,s):await e.request(`browser.dashboard.request`,t)}let l=!r&&a===ea?i?.():void 0,u=t||r||l?{...c,...t?{target:t.target,...t.target===`node`?{node:t.node}:{},query:{...P(c?.query),profile:t.profile}}:{},...r?{dashboard:r}:{},...l?{tabScope:{sessionKey:l.sessionKey,...c?.method===`GET`&&c.path===`/tabs`?{referencedTabs:Di(l.referencedTabs)}:{}}}:{}}:o;return s?await e.request(a,u,s):await e.request(a,u)}}}function R(e,t,n){return n?e.request(ea,t,n):e.request(ea,t)}function ki(e,t){return R(e,{method:`POST`,path:`/act`,body:t})}function z(e){return mn(e)??``}function Ai(e){let t=P(e),n=z(t?.targetId);return n?{kind:`remote`,id:z(t?.tabId)||n,targetId:n,title:z(t?.title),url:z(t?.url),...t?.urlUnavailableReason===`navigation_blocked`||t?.urlUnavailableReason===`navigation_check_failed`?{urlUnavailableReason:t.urlUnavailableReason}:{}}:null}async function ji(e){let t=P(await R(e,{method:`GET`,path:`/tabs`})),n=Array.isArray(t?.tabs)?t.tabs.flatMap(e=>Ai(e)??[]):[];return{running:t?.running===!0,tabs:n}}async function Mi(e){await R(e,{method:`POST`,path:`/start`,body:{}})}async function Ni(e,t){return Ai(await R(e,{method:`POST`,path:`/tabs/open`,body:{url:t}}))}async function Pi(e,t){await R(e,{method:`POST`,path:`/tabs/focus`,body:{targetId:t}})}async function Fi(e,t){await R(e,{method:`DELETE`,path:`/tabs/${encodeURIComponent(t)}`})}async function Ii(e,t,n,r){let i=P(await e.request(ea,{method:`POST`,path:`/download`,body:{targetId:t,currentDocument:!0,expectedUrl:n,timeoutMs:12e4},timeoutMs:15e4},{signal:r,timeoutMs:15e4})),a=P(i?.download),o=z(a?.path),s=z(a?.suggestedFilename);if(!o||!s)throw Error(w(`browser.errors.downloadEmpty`));return{path:o,filename:s}}async function Li(e,t){let n=P(await R(e,{method:`POST`,path:`/navigate`,body:t}));return{targetId:z(n?.targetId)||t.targetId||``,url:z(n?.url)||t.url}}async function Ri(e,t,n){let r=P(await R(e,{method:`POST`,path:`/screencast`,body:t},n)),i=z(r?.token),a=z(r?.wsPath);if(!i||!a)throw Error(`browser screencast response is malformed`);return{token:i,wsPath:a,targetId:z(r?.targetId),url:z(r?.url)}}function zi(e){let t=P(e),n=P(t?.details);return n?.code===`SCREENCAST_UNSUPPORTED`||P(n?.body)?.code===`SCREENCAST_UNSUPPORTED`||P(t?.body)?.code===`SCREENCAST_UNSUPPORTED`}async function Bi(e,t){let n=P(await R(e,{method:`POST`,path:`/screenshot`,body:{targetId:t,type:`png`}})),r=z(n?.path);if(!r)throw Error(w(`browser.errors.screenshotPathMissing`));return{path:r,targetId:z(n?.targetId)||t,url:z(n?.url)}}async function Vi(e,t){await ki(e,{kind:`clickCoords`,targetId:t.targetId,x:Math.max(0,Math.round(t.x)),y:Math.max(0,Math.round(t.y)),...t.doubleClick?{doubleClick:!0}:{}})}async function Hi(e,t){await ki(e,{kind:`press`,targetId:t.targetId,key:t.key})}async function Ui(e,t){try{await ki(e,{kind:`insertText`,...t})}catch{throw Error(w(`browser.errors.pasteFailed`))}}async function Wi(e,t){await ki(e,{kind:`resize`,targetId:t.targetId,width:Math.round(t.width),height:Math.round(t.height)})}async function Gi(e,t){return P(await ki(e,{kind:`evaluate`,targetId:t.targetId,fn:t.fn}))?.result??null}function Ki(e){return e instanceof Te&&P(e.details)?.reason===`navigation_blocked`}function qi(e){if(!(e instanceof Error))return!1;let t=e instanceof Te?P(e.details):null,n=t?.code;return n===void 0&&t?.unrecognizedCode!==!0?e.message.includes(`evaluateEnabled=false`):n===`ACT_EVALUATE_DISABLED`}async function Ji(e,t){let n=Math.round(t.deltaX),r=Math.round(t.deltaY);await Gi(e,{targetId:t.targetId,fn:`() => { window.scrollBy(${n}, ${r}); return true; }`})}async function Yi(e,t){await Gi(e,{targetId:t.targetId,fn:`() => { history.go(${t.delta}); return true; }`})}async function Xi(e,t){let n=P(await Gi(e,{targetId:t,fn:`() => ({ cssWidth: window.innerWidth, cssHeight: window.innerHeight, title: document.title, url: location.href })`})),r=kn(n?.cssWidth),i=kn(n?.cssHeight);return!r||!i||r<=0||i<=0?null:{cssWidth:r,cssHeight:i,title:z(n?.title),url:z(n?.url)}}async function Zi(e,t){let n=Math.max(0,Math.round(t.x)),r=Math.max(0,Math.round(t.y));return Qi(await Gi(e,{targetId:t.targetId,fn:`() => { ${Ci}\nreturn openclawInspectBrowserElement(${n}, ${r}); }`}))}function Qi(e){let t=P(e);if(!t)return null;let n=P(t.rect);return{tag:z(t.tag),id:z(t.id),classes:Array.isArray(t.classes)?t.classes.filter(e=>typeof e==`string`):[],role:z(t.role),name:z(t.name),rect:{x:kn(n?.x)??0,y:kn(n?.y)??0,width:kn(n?.width)??0,height:kn(n?.height)??0},focusable:t.focusable===!0}}async function $i(e){let t=new Headers({Accept:`image/*`});e.authToken&&t.set(`Authorization`,`Bearer ${e.authToken}`);let n=new AbortController,r=setTimeout(()=>n.abort(new DOMException(w(`browser.errors.screenshotFetchTimedOut`),`TimeoutError`)),ta),i;try{let r=await fetch(Er(e.path,e.resourceBasePath),{method:`GET`,headers:t,credentials:`same-origin`,signal:n.signal});if(!r.ok)throw r.body?.cancel().catch(()=>void 0),Error(w(`browser.errors.screenshotFetchFailed`,{status:String(r.status)}));i=await r.blob()}finally{clearTimeout(r)}return Zt(i,{readError:()=>w(`browser.errors.screenshotReadFailed`),invalidResultError:()=>w(`browser.errors.screenshotReadFailed`)})}var ea,ta;function na(){return(na=e((()=>{gn(),Ee(),Tr(),a(),Si(),wi(),yr(),xi(),ea=`browser.request`,ta=3e4})))()}function ra(e){return e.callId??e.messageId??e.previewRevision}function ia(e,t){let n=oa.get(e);if(n?.toolMessages===t)return n.latest;let r=new Map;for(let n of[e,t])for(let e of n)if(On(e))for(let t of qt(e)){let e=ra(t);if(t.browserTab&&e&&Pt(t,!1)===`succeeded`){let n=Jn(t.browserTab);r.delete(n),r.set(n,{tab:t.browserTab,revision:e})}}return oa.set(e,{toolMessages:t,latest:r}),r}function aa(e){let t=Jn(e.tab),n=sa.get(e.client);n||(n={tabs:new Map,images:new Map},sa.set(e.client,n));let{tabs:r,images:i}=n,a=r.get(t);if(a||(a={revisions:new Set},r.set(t,a)),a.revisions.has(e.revision))return a.pending??Promise.resolve(i.get(t));a.revisions.add(e.revision);let o=(a.pending??Promise.resolve()).then(async()=>{try{let n=await Bi(Oi(e.client,e.tab),e.tab.targetId),r=await $i({resourceBasePath:e.resourceBasePath,authToken:e.authToken,path:n.path});if(i.delete(t),i.set(t,r),i.size>ca){let e=i.keys().next().value;e!==void 0&&i.delete(e)}return r}catch{i.delete(t);return}finally{a.pending===o&&(a.pending=void 0)}});return a.pending=o,o}var oa,sa,ca;function la(){return(la=e((()=>{na(),yr(),Yt(),oa=new WeakMap,sa=new WeakMap,ca=32})))()}function ua(e){return!e.outputTruncated&&(e.toolOutput?.captureTruncated===!0||!e.toolOutput&&/\n\.\.\.\(OpenClaw truncated Codex native tool output: original \d+ chars, showing \d+; rerun with narrower args\.\)\s*$/u.test(e.outputText??``))}function da(e){return w(e.toolOutput?.source===`provider-response`?`chat.toolCards.providerResponse`:e.toolOutput?.source===`execution`?`chat.toolCards.executionOutput`:`chat.toolCards.toolOutput`)}function fa(e){let t=yn(e),n=On(t)&&typeof t.wall_time_seconds==`number`&&typeof t.exit_code==`number`&&typeof t.output==`string`&&Object.keys(t).every(e=>[`chunk_id`,`wall_time_seconds`,`exit_code`,`original_token_count`,`output`].includes(e))?{text:t.output,exitCode:t.exit_code}:void 0,r=n?.text??e,i=Yn(r)?.root?qn(r,Kn(r,void 0,{insertSpaces:!0,tabSize:2})):r;return n&&n.exitCode!==0?`${w(`chat.toolCards.exitCode`,{code:String(n.exitCode)})}\n${i}`:i}function pa(e){let t=e.outputText;if(t===void 0||e.preview||e.toolOutput?.source!==`provider-response`||e.name!==`exec`||!On(e.args)||typeof e.args.input!=`string`)return t;let n=yn(t);return!Array.isArray(n)||n.length===0||!n.every(e=>On(e)&&e.type===`input_text`&&typeof e.text==`string`)?t:n.filter((e,t)=>t!==0||n.length===1||!/^Script completed\nWall time [\d.]+ seconds\nOutput:\n$/u.test(e.text)).map(e=>fa(e.text)).join(`
`)}var ma;function ha(){return(ha=e((()=>{Nn(),Un(),lr(),a(),ma=8e3})))()}function ga(e,t){let n=new URL(e||t,t);if(n.protocol===`ws:`?n.protocol=`http:`:n.protocol===`wss:`&&(n.protocol=`https:`),n.protocol!==`http:`&&n.protocol!==`https:`)throw Error(`Gateway URL is invalid`);return n.origin}function _a(e,t,n,r,i,a=`Sandbox host URL is invalid`){if(!Number.isInteger(t)||t<1||t>65535)throw Error(a);let o;try{o=ga(r,i)}catch{throw Error(a)}let s=n?new URL(n):new URL(o);if(n){if(s.origin!==n.replace(/\/$/u,``)||s.username!==``||s.password!==``)throw Error(a)}else s.port=String(t);s.pathname=`/`,s.search=``,s.hash=``;let c=new URL(e,s);if(s.protocol!==`http:`&&s.protocol!==`https:`||s.origin===new URL(i).origin||s.origin===o||c.origin!==s.origin||c.pathname!==`/mcp-app-sandbox`)throw Error(a);return c.href}function va(){return(va=e((()=>{})))()}function ya(e,t){let n=t-Aa,r=(B.get(e)??[]).filter(e=>e>n);if(!B.has(e)&&B.size>=Ma){let e=B.keys().next().value;e!==void 0&&B.delete(e)}return r.length>=ja?(B.set(e,r),!1):(r.push(t),B.set(e,r),!0)}function ba(e){if(!e.isConnected||!(typeof e.checkVisibility==`function`?e.checkVisibility():e.getClientRects().length>0))return!1;let t=e.ownerDocument.activeElement;for(;t?.shadowRoot?.activeElement;)t=t.shadowRoot.activeElement;return t===e}async function xa(e,t,n,r,i){let a=typeof t==`string`?t.trim():``;return!a||a.length>ka||a.startsWith(`/`)||a.startsWith(`!`)||!ba(e)||!ya(n,Date.now())||r&&!await r(a)||i?.()===!1||!ba(e)?!1:(e.dispatchEvent(new CustomEvent(Da,{bubbles:!0,composed:!0,detail:{text:a}})),!0)}function Sa(e,t=!1,n=!1,r=!1,i={}){return{openLinks:{},serverTools:{},sandbox:{csp:e??{}},...r?{serverResources:{}}:{},...t?{message:{text:{},...i.richMessage?{image:{},resource:{},resourceLink:{}}:{}}}:{},...n?{updateModelContext:{text:{},...i.richModelContext?{image:{},resource:{},resourceLink:{},structuredContent:{}}:{}}}:{},experimental:{...i.richModelContext?{"openai/modelContext":{}}:{},...i.richMessage?{"openai/message":{}}:{},...i.fileResources?{"openai/resource":{}}:{},...i.openFiles?{"openai/files":{}}:{}}}}function Ca(e,t,n,r,i){return _a(e,t,n,r,i,w(`mcpApp.errors.invalidSandboxUrl`))}function wa(e){switch(e.type){case`text`:return typeof e.text==`string`&&e.text.trim().length>0;case`image`:return typeof e.data==`string`&&!!e.mimeType;case`resource_link`:return typeof e.uri==`string`&&!!e.uri&&typeof e.name==`string`&&!!e.name;case`resource`:return!!e.resource&&typeof e.resource.uri==`string`&&(`text`in e.resource&&typeof e.resource.text==`string`||`blob`in e.resource&&typeof e.resource.blob==`string`);default:return!1}}async function Ta(e,t,n,r,i){let a=n._meta?.[`openai/message`],o=I(a);return a!==void 0&&!o||n.role!==`user`||!n.content.length||n.content.some(e=>!wa(e))||o?.target!==void 0&&o.target!==`active`&&o.target!==`new`||o?.send!==void 0&&o.send!==!0||JSON.stringify(n.content).length>8388608||!ba(e)||!ya(t.sessionKey+`\0`+t.viewId,Date.now())||/^[!/]/u.test(Wr(n.content).trimStart())||!await r(n.content.map(e=>{let t=e._meta?.[`openai/title`];return typeof t==`string`&&t.trim()?t:e.type===`text`?e.text:e.type===`resource_link`?e.title??e.name:e.type===`resource`?e.resource.uri:e.type}).join(`

`))||i?.()===!1||!ba(e)?!1:new Promise(r=>{e.dispatchEvent(new CustomEvent(`openclaw-mcp-app-message`,{bubbles:!0,composed:!0,cancelable:!0,detail:{...t,content:n.content,target:o?.target===`new`?`new`:`active`,respond:r}}))&&r(!1)})}function Ea(e,t){let n=e?.availableDisplayModes??(e?.preferredDisplayMode?[e.preferredDisplayMode]:t),r=[`inline`,`fullscreen`].filter(e=>(!n||n.includes(e))&&(!t||t.includes(e)));if(!r.length)throw Error(`MCP App supports no available host display mode`);return{available:r,initial:e?.preferredDisplayMode&&r.includes(e.preferredDisplayMode)?e.preferredDisplayMode:r[0]}}var Da,Oa,ka,Aa,ja,Ma,B,Na,Pa,Fa;function Ia(){return(Ia=e((()=>{a(),Gt(),cn(),Da=`openclaw-widget-prompt`,Oa=`openclaw-mcp-app-view-expired`,ka=4e3,Aa=6e4,ja=10,Ma=100,B=new Map,Na=`openclaw-mcp-app-message`,Pa=`openclaw-mcp-app-context`,Fa=`openclaw-mcp-app-file-open`})))()}var La;function Ra(){return(Ra=e((()=>{ae(),La=class{constructor(){this.entries=new Map}clear(){this.entries.clear()}prune(e){let t=new Set(e.filter(e=>e.contentKind===`mcp-app`).map(e=>this.key(e)));for(let e of this.entries.keys())t.has(e)||this.entries.delete(e)}async resolve(e,t,n){let r=this.key(e);return n&&this.entries.delete(r),await An(this.entries,r,()=>t().then(e=>({status:`ready`,...e})).catch(e=>({status:`stale`,error:S(e)})))}key(e){return`${e.name}\0${e.revision}\0${e.instanceId??``}\0${e.grantState}`}}})))()}function za(e){return{sessionKey:e,revision:0,tabs:[],widgets:[]}}function Ba(e){let t=e?.trim()??``;return t?ft(t,80):void 0}function Va(){return(Va=e((()=>{})))()}var Ha,Ua;function Wa(){return(Wa=e((()=>{Ha=class{constructor(e){this.value=e,this.listeners=new Set}subscribe(e){return Tn(this.listeners,e)}set(e){this.value=e;for(let e of this.listeners)e()}},Ua=class{constructor(){this.listeners=new Set}subscribe(e){return Tn(this.listeners,e)}emit(e){for(let t of this.listeners)t(e)}}})))()}function Ga(e){let t=14695981039346656037n;for(let n of new TextEncoder().encode(e))t^=BigInt(n),t=BigInt.asUintN(64,t*1099511628211n);return t.toString(16).padStart(16,`0`)}function Ka(e){let t=`canvas-${e.toLowerCase().replace(/[^a-z0-9._-]/gu,`-`)}`;return t===`canvas-${e}`&&t.length<=64?t:`${t.slice(0,47).replace(/[._-]+$/gu,``)||`canvas-widget`}-${Ga(e)}`}function qa(e){return`mcp-app-${Ga(e)}`}function Ja(){return(Ja=e((()=>{})))()}function Ya(e,t=Date.now()){e.viewTicket&&e.viewTicketTtlMs&&Qa.set(e,t)}function Xa(e,t,n=Date.now()){Ya(e,Qa.get(t)??n)}function Za(e,t=Date.now()){let n=e.viewTicketTtlMs;if(!e.viewTicket||!n)return;let r=Qa.get(e);return r===void 0?n:Math.max(0,n-(t-r))}var Qa;function $a(){return($a=e((()=>{Qa=new WeakMap})))()}function eo(e,t){return{...e,...t.frameUrl===void 0?{}:{frameUrl:t.frameUrl},...t.viewTicket===void 0?{}:{viewTicket:t.viewTicket},...t.viewTicketTtlMs===void 0?{}:{viewTicketTtlMs:t.viewTicketTtlMs},...t.viewGeneration===void 0?{}:{viewGeneration:t.viewGeneration},...t.sandboxUrl===void 0?{}:{sandboxUrl:t.sandboxUrl},...t.sandboxPort===void 0?{}:{sandboxPort:t.sandboxPort},...t.sandboxOrigin===void 0?{}:{sandboxOrigin:t.sandboxOrigin}}}var to;function no(){return(no=e((()=>{Mn(),wn(),ae(),h(),Ra(),Va(),Wa(),$a(),to=class{constructor(e,t,n=!0,r=!0,i=!1,a=!0,o=!0){this.session=e,this.canPinWidgets=r,this.canPinMcpApps=i,this.canMutate=a,this.canGrant=o,this.loadErrorSignal=new Ha(null),this.eventStream=new Ua,this.retiredClients=new WeakSet,this.clientGeneration=0,this.refreshRequested=!1,this.userRefreshRequested=!1,this.changedWidgets=new Set,this.stateGeneration=0,this.connected=!1,this.appViews=new La,this.disposed=!1,this.snapshotLoaded=!1,this.snapshotSignal=new Ha(za(this.sessionKey)),this.snapshot$=this.snapshotSignal,this.loadError$=this.loadErrorSignal,this.events=this.eventStream,this.client=t,this.connected=n,this.subscribe(t),n&&this.activate()}get sessionKey(){return this.session.sessionKey}attachClient(e,t=!0){if(this.disposed||e!==this.client&&this.retiredClients.has(e))return;let n=t!==this.connected,r=t&&!this.connected;if(this.connected=t,t||this.wakeRetryDelay?.(),e===this.client){n&&(this.clientGeneration+=1,this.stateGeneration+=1,this.appViews.clear(),this.publishAppViewGeneration()),r&&this.activate();return}this.retiredClients.add(this.client),this.unsubscribe?.(),this.client=e,this.clientGeneration+=1,this.stateGeneration+=1,this.changedWidgets.clear(),this.appViews.clear(),this.snapshotLoaded=!1,this.setLoadError(null),this.snapshotSignal.set(za(this.sessionKey)),this.subscribe(e),t&&this.activate()}activate(){return this.requestRefresh()}get hasLoadedSnapshot(){return this.snapshotLoaded}get appViewGeneration(){return this.clientGeneration}dispose(){this.disposed||(this.disposed=!0,this.connected=!1,this.unsubscribe?.(),this.unsubscribe=void 0,this.clientGeneration+=1,this.stateGeneration+=1,this.refreshRequested=!1,this.userRefreshRequested=!1,this.changedWidgets.clear(),this.appViews.clear(),this.wakeRetryDelay?.())}async applyOps(e){await this.mutate(`board.update`,{...this.session,ops:e})}async grant(e,t){let n=this.snapshotSignal.value.widgets.find(t=>t.name===e);if(!n)throw this.requestRefresh(),Error(`Dashboard widget not found: ${e}`);await this.mutate(`board.widget.grant`,{...this.session,name:e,decision:t,revision:n.revision,...n.instanceId?{instanceId:n.instanceId}:{}})}pinWidget(e){return this.pinBoardWidget(e,e.name??Ka(e.docId),{kind:`canvas-doc`,docId:e.docId})}pinMcpApp(e){return this.pinBoardWidget(e,e.name??qa(e.viewId),{kind:`mcp-app`,viewId:e.viewId})}async pinBoardWidget(e,t,n){let r=Ba(e.title);await this.mutate(`board.widget.put`,{...this.session,name:t,...r?{title:r}:{},content:n,...e.tabId||e.size||e.after?{placement:{...e.tabId?{tabId:e.tabId}:{},...e.size?{size:e.size}:{},...e.after?{after:e.after}:{}}}:{}},t)}widgetFrameUrl(e,t){return this.snapshotSignal.value.widgets.find(n=>n.name===e&&n.revision===t)?.frameUrl??``}refreshWidgetFrame(e){return this.requestRefresh(e,!0)}async widgetAppView(e,t){return await this.resolveWidgetAppView(e,t,!1)}async refreshWidgetAppView(e,t){return await this.resolveWidgetAppView(e,t,!0)}async resolveWidgetAppView(e,t,n){if(this.disposed||!this.connected)return{status:`stale`,error:`Dashboard MCP App view unavailable`};let r=this.snapshotSignal.value.widgets.find(n=>n.name===e&&n.revision===t&&n.contentKind===`mcp-app`);if(!r)return{status:`stale`,error:`Dashboard MCP App widget unavailable`};let i=this.client,a=this.clientGeneration,o=await this.appViews.resolve(r,async()=>await i.request(`board.widget.appView`,{...this.session,name:e,revision:t,...r.instanceId?{instanceId:r.instanceId}:{}}),n);return this.disposed||!this.connected||i!==this.client||a!==this.clientGeneration?{status:`stale`,error:`Dashboard MCP App view unavailable`}:o}subscribe(e){this.unsubscribe=e.addEventListener(t=>{if(!(this.disposed||e!==this.client)){if(t.event===`board.changed`){let e=t.payload;e&&this.matchesSession(e.sessionKey)&&(this.stateGeneration+=1,this.requestRefresh(e.widget));return}if(t.event===`board.command`){let e=t.payload;e?.command&&this.matchesSession(e.sessionKey,e.agentId)&&this.eventStream.emit({sessionKey:this.snapshotSignal.value.sessionKey,command:e.command})}}})}matchesSession(e,t){if(typeof e!=`string`)return!1;let r=c({},this.sessionKey,this.session.agentId);if(t){let n=c({},e,t);return r.sessionKey===n.sessionKey&&r.agentId===n.agentId}if(!this.snapshotLoaded){let t=C(e);return!(!t||t.agentId!==r.agentId||n(e)!==r.sessionKey&&n(t.rest)!==r.sessionKey)}return n(e)===n(this.snapshotSignal.value.sessionKey)}requestRefresh(e,t=!1){return this.disposed?Promise.resolve():(this.refreshRequested=!0,this.userRefreshRequested||=t,e&&this.changedWidgets.add(e),this.wakeRetryDelay?.(),this.refreshLoop??=this.runRefreshLoop().finally(()=>{this.refreshLoop=void 0,this.refreshRequested&&(this.connected||this.userRefreshRequested)&&this.requestRefresh()}),this.refreshLoop)}async runRefreshLoop(){let e={delayMs:1e3};for(;this.refreshRequested;){if(this.disposed){this.refreshRequested=!1;return}if(!this.connected&&!this.userRefreshRequested)return;this.userRefreshRequested=!1;let t=new Set(this.changedWidgets);this.changedWidgets.clear();let n=this.client,r=this.stateGeneration;try{let i=await n.request(`board.get`,this.session);if(this.disposed)return;if(n!==this.client){this.refreshRequested=!0;continue}if(this.userRefreshRequested=!1,r!==this.stateGeneration){this.refreshRequested=!0;for(let e of t)this.changedWidgets.add(e);continue}for(let e of this.changedWidgets)t.add(e);this.changedWidgets.clear(),this.refreshRequested=!1,this.setSnapshot(i,t),e.delayMs=1e3}catch(i){if(this.disposed)return;if(this.refreshRequested=!0,n!==this.client)continue;this.setLoadError(S(i));for(let e of t)this.changedWidgets.add(e);if(i instanceof Sn&&i.gatewayCode===`UNAVAILABLE`&&!i.retryable){this.refreshRequested=this.stateGeneration!==r||this.userRefreshRequested;continue}if(!this.connected){if(this.userRefreshRequested)continue;return}let a=e.delayMs;e.delayMs=Math.min(a*2,3e4),await this.waitForRetry(a);continue}}}async waitForRetry(e){let t=new AbortController,n=()=>t.abort();this.wakeRetryDelay=n,await xn(e,t.signal).catch(()=>void 0),this.wakeRetryDelay===n&&(this.wakeRetryDelay=void 0)}async mutate(e,t,n){if(this.disposed)throw Error(`Session dashboard provider is no longer active`);let r=this.client,i=this.clientGeneration,a=++this.stateGeneration,o=()=>!this.disposed&&r===this.client&&i===this.clientGeneration&&a===this.stateGeneration;try{let i=await r.request(e,t);o()&&(this.stateGeneration+=1,this.setSnapshot(i,n?new Set([n]):new Set,!0))}catch(e){throw o()&&this.requestRefresh(),e}}setSnapshot(e,t=new Set,n=!1){let r=Date.now(),i=new Map(this.snapshotSignal.value.widgets.map(e=>[e.name,e])),a=e.widgets.map(e=>{let a=i.get(e.name);if(a&&!t.has(e.name)&&a.revision===e.revision&&a.instanceId===e.instanceId){if(n&&e.viewGeneration===void 0){let t=eo(e,a);return Xa(t,a,r),t}if(a.viewGeneration===e.viewGeneration&&!e.sandboxUrl&&a.frameUrl){let t={...e,frameUrl:a.frameUrl};return Ya(t,r),t}}return Ya(e,r),e});this.appViews.prune(a),this.snapshotLoaded=!0,this.snapshotSignal.set({...e,widgets:a}),this.setLoadError(null)}setLoadError(e){this.loadErrorSignal.value!==e&&this.loadErrorSignal.set(e)}publishAppViewGeneration(){let e=this.snapshotSignal.value;e.widgets.some(e=>e.contentKind===`mcp-app`)&&this.snapshotSignal.set({...e,widgets:e.widgets.map(e=>e.contentKind===`mcp-app`?Object.assign({},e):e)})}}})))()}function ro(e){return e.tabs.length>0||e.widgets.length>0}function io(e){let t=c({},ne(e.sessionKey),e.agentId);return JSON.stringify([e.agentId??t.agentId,t.sessionKey])}function ao(e,t=!0){let n=io(e),r=ne(e.sessionKey),i=t?V.get(n)?.provider:void 0;if(i)return i;let a=lo.get(n);return a||(a=new so(r),lo.set(n,a)),a}function oo(e,t,n=!0,r=!0,i=!1,a=!0,o=!0){let s=io(e),c=V.get(s);if(c)c.provider.attachClient(t,n);else{let r={...e,sessionKey:ne(e.sessionKey)};c={provider:new to(r,t,n),consumers:0},V.set(s,c)}let l=new co(c.provider,{canPinWidgets:r,canPinMcpApps:i,canMutate:a,canGrant:o});c.consumers+=1;let u=!1;return{provider:l,update:(e,t,n)=>{u||V.get(s)?.provider!==c.provider||(l.updateCapabilities(n),c.provider.attachClient(e,t))},release:()=>{if(u)return;u=!0,l.deactivate();let e=V.get(s);e&&e.provider===c.provider&&(--e.consumers,!(e.consumers>0)&&(V.delete(s),e.provider.dispose()))}}}var so,co,lo,V;function uo(){return(uo=e((()=>{h(),no(),Va(),Wa(),so=class{constructor(e=``){this.sessionKey=e,this.appViewGeneration=0,this.canMutate=!1,this.canGrant=!1,this.canPinWidgets=!1,this.canPinMcpApps=!1,this.hasLoadedSnapshot=!0,this.loadError$=new Ha(null),this.events=new Ua,this.snapshot$=new Ha(za(e))}async applyOps(e){}async grant(e,t){}async pinWidget(e){throw Error(`Session dashboard unavailable`)}async pinMcpApp(e){throw Error(`Session dashboard unavailable`)}widgetFrameUrl(e,t){return``}async refreshWidgetFrame(e){}async widgetAppView(e,t){return{status:`stale`,error:`Session dashboard unavailable`}}async refreshWidgetAppView(e,t){return{status:`stale`,error:`Session dashboard unavailable`}}},co=class{constructor(e,t){this.transport=e,this.capabilities=t,this.active=!0,this.loadError$=e.loadError$,this.snapshot$=e.snapshot$,this.events=e.events}get sessionKey(){return this.transport.sessionKey}get appViewGeneration(){return this.transport.appViewGeneration}get canPinWidgets(){return this.active&&this.capabilities.canPinWidgets}get canPinMcpApps(){return this.active&&this.capabilities.canPinMcpApps}get canMutate(){return this.active&&this.capabilities.canMutate}get canGrant(){return this.active&&this.capabilities.canGrant}get hasLoadedSnapshot(){return this.transport.hasLoadedSnapshot}updateCapabilities(e){this.active&&(this.capabilities=e)}deactivate(){this.active=!1}async applyOps(e){if(!this.canMutate)throw Error(`Session dashboard mutation unavailable`);await this.transport.applyOps(e)}async grant(e,t){if(!this.canGrant)throw Error(`Session dashboard approval unavailable`);await this.transport.grant(e,t)}async pinWidget(e){if(!this.canMutate||!this.canPinWidgets)throw Error(`Session dashboard widget pinning unavailable`);await this.transport.pinWidget(e)}async pinMcpApp(e){if(!this.canMutate||!this.canPinMcpApps)throw Error(`Session dashboard MCP App pinning unavailable`);await this.transport.pinMcpApp(e)}widgetFrameUrl(e,t){return this.transport.widgetFrameUrl(e,t)}refreshWidgetFrame(e){return this.transport.refreshWidgetFrame(e)}widgetAppView(e,t){return this.transport.widgetAppView(e,t)}refreshWidgetAppView(e,t){return this.transport.refreshWidgetAppView(e,t)}},lo=new Map,V=new Map})))()}function fo(e){if(e===null)return 0;let t;if(/^\d+$/u.test(e))t=Number(e);else{let n=/^(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s)?$/iu.exec(e);if(!n||!e)return;t=Number(n[1]??0)*3600+Number(n[2]??0)*60+Number(n[3]??0)}return Number.isSafeInteger(t)&&t>=0?t:void 0}function po(e){if(!e)return;let t;try{t=new URL(e)}catch{return}if(t.protocol!==`https:`||t.username||t.password||t.port)return;let n=t.searchParams,r=new URLSearchParams(t.hash.slice(1));if([`v`,`start`,`t`].some(e=>n.getAll(e).length>1)||r.getAll(`t`).length>1)return;let i;if(mo.has(t.hostname)&&t.pathname===`/watch`)i=n.get(`v`)??void 0;else{if(n.has(`v`))return;t.hostname===`youtu.be`?i=/^\/([A-Za-z0-9_-]{11})\/?$/u.exec(t.pathname)?.[1]:mo.has(t.hostname)?i=/^\/(?:shorts|live|embed)\/([A-Za-z0-9_-]{11})\/?$/u.exec(t.pathname)?.[1]:ho.has(t.hostname)&&(i=/^\/embed\/([A-Za-z0-9_-]{11})\/?$/u.exec(t.pathname)?.[1])}if(!i||!go.test(i))return;let a=fo(n.get(`start`)??n.get(`t`)??r.get(`t`));if(a===void 0)return;let o=new URL(`https://www.youtube.com/watch`);o.searchParams.set(`v`,i);let s=new URL(`https://www.youtube-nocookie.com/embed/${i}`);return s.searchParams.set(`playsinline`,`1`),a>0&&(o.searchParams.set(`t`,String(a)),s.searchParams.set(`start`,String(a))),{videoId:i,startSeconds:a,watchUrl:o.href,embedUrl:s.href,thumbnailUrl:`https://i.ytimg.com/vi/${i}/hqdefault.jpg`}}var mo,ho,go;function _o(){return(_o=e((()=>{mo=new Set([`youtube.com`,`www.youtube.com`,`m.youtube.com`]),ho=new Set([`youtube-nocookie.com`,`www.youtube-nocookie.com`]),go=/^[A-Za-z0-9_-]{11}$/u})))()}function vo(e){let t=new Map,n=e.sessionData;if(!n)return t;let r=[[n.sessionsAgentId,n.sessionsResult?.sessions],...Object.entries(n.sessionResultsByAgent).map(([e,t])=>[e,t.sessions]),...Object.entries(n.childSessionRowsByParent).filter(([e])=>n.loadedChildSessionKeys.has(e)).map(([e,t])=>[C(e)?.agentId??n.sessionsAgentId,t])];for(let[n,i]of r)if(n)for(let r of i??[]){let i=C(r.key)?.agentId??r.agentId??n,a=H(r.key,i,e);t.has(a)||t.set(a,{row:r,agentId:i})}return t}function H(e,t,n){let r=C(e)?.agentId??Ln(t);return`${r}\u0000${ee({agentsList:{defaultId:r,mainKey:n.mainKey,scope:n.globalScope?`global`:`agent`}},C(e)||e.toLowerCase()===`global`?e:`agent:${r}:${e}`)}`}function yo(e){let t=e.filter(e=>e!==void 0);return t.length?Math.min(...t):void 0}function bo(e,t=`compact`){let n=new Date(e);return D`<time
    datetime=${n.toISOString()}
    title=${n.toLocaleString(re.getLocale())}
    aria-label=${t===`minute-compact`?O:n.toLocaleString(re.getLocale())}
    ><openclaw-elapsed-time
      .startMs=${e}
      .minimumUnit=${t===`minute-compact`?`minute`:`second`}
      .singleUnit=${t===`single-unit`}
    ></openclaw-elapsed-time
  ></time>`}function xo(e){return[...new Set((e.entries??[]).map(e=>{let t=e.deviceFamily?.trim(),n=fn(e.platform??``,t),r=t===`Mac`?`macOS`:t===`iPad`?`iPadOS`:t,i=ni({id:e.clientId,mode:e.mode}),a=i?w(`presence.card.${i}`):void 0;return[...new Set([t,n.label===r?void 0:n.label,n.architecture,a].map(e=>e?.trim()).filter(Boolean))].join(` · `)}).filter(Boolean))].toSorted()}function So(e,t,n){if(!n&&e.length===0)return O;let r=w(n?`presence.card.recentSessions`:`presence.card.viewingNow`);return D`<section class="person-activity-card__section">
    <h3>${r}</h3>
    ${e.length?D`<div class="person-activity-card__sessions">
            ${Je(e.slice(0,3),({row:e,agentId:n})=>H(e.key,n,t),({row:e,agentId:r})=>{let i=m(e.key,e),a=n?Nt(i,`person-activity-card__session-name`,{delay:250,speed:80}):D`<span
                      class="person-activity-card__session-name person-activity-card__session-name--multiline"
                      >${i}</span
                    >`,o=v({face:y(e),sessionKey:e.key,fallbackAgentId:r,basePath:t.routing.basePath,row:e,mainKey:t.mainKey});return D`<a
                  class="person-activity-card__session session-row-host"
                  href=${o.href}
                  @click=${n=>{s(n)&&(n.preventDefault(),t.openSession(e,r))}}
                  ><span class="person-activity-card__session-icon" aria-hidden="true"
                    >${E.messageSquare}</span
                  >
                  <span class="person-activity-card__session-copy"
                    >${n?Ye(i,a):a}
                    ${e.updatedAt==null?O:D`<span class="person-activity-card__session-age"
                            >${bo(e.updatedAt,`single-unit`)}</span
                          >`}</span
                  >
                </a>`})}
          </div>`:D`<p class="person-activity-card__muted">${w(`presence.card.noRecentSessions`)}</p>`}
  </section>`}function Co(e,t){let{user:n}=e,r=Ot(n,w(`presence.card.person`)),i=ar(n.identity?.id,e.routing,r.name),a=n.entries!==void 0,o=n.entries?.length===0,s=n.entries??[],c=yo(s.map(e=>e.onlineSince)),l=Dt(n),u=Lt(n),d=xo(n),f=[...new Set(s.flatMap(e=>e.timeZone?.trim()?[e.timeZone.trim()]:[]))].toSorted(),p=new Set(n.watchedSessions.map(t=>H(t,e.watchAgentId,e))),m=vo(e),h=(t,n)=>(n.row.updatedAt??0)-(t.row.updatedAt??0)||H(t.row.key,t.agentId,e).localeCompare(H(n.row.key,n.agentId,e)),g=[...p].flatMap(e=>m.get(e)??[]).toSorted(h),{sessionData:_}=e,v=(t.recentSessionKeys?.flatMap(e=>m.get(e)??[])??[...m.values()]).filter(({row:t,agentId:r})=>!p.has(H(t.key,r,e))&&[t.owner?.actor,t.createdActor].some(e=>Rt(n,e?.identity)));return t.recentSessionKeys||v.sort(h),(t.recentSessionKeys||_?.sessionsResult||Object.keys(_?.sessionResultsByAgent??{}).length)&&(t.recentSessionKeys=v.slice(0,3).map(({row:t,agentId:n})=>H(t.key,n,e))),D`<div class="person-activity-card">
    <header class="person-activity-card__header">
      <openclaw-viewer-avatar
        .user=${n}
        .markAsViewer=${!1}
        variant="footer"
        aria-hidden="true"
      ></openclaw-viewer-avatar>
      <div>
        <h2>${r.name}</h2>
        ${a?D` <span
                class="person-activity-card__status ${o?`person-activity-card__status--offline`:`person-activity-card__status--${u}`}"
                ><span aria-hidden="true"></span>${o?w(`presence.offline`):c===void 0?w(`presence.rosterTitle`):[w(`presence.card.onlineFor`),` `,bo(c,`minute-compact`)]}${!o&&u!==`unknown`?D` · ${w(u===`active`?`presence.active`:`presence.idle`)}`:O}</span
              >`:O}
      </div>
    </header>
    ${r.isSharedOwner?D`<p class="person-activity-card__hint person-activity-card__muted">${w(`presence.sharedOwner.hint`)}</p>`:O}
    ${!a||o?O:D`<dl class="person-activity-card__facts">
            ${d.length||f.length?D`<div>
                    <dt>${w(`presence.card.where`)}</dt>
                    <dd>
                      ${d.map(e=>D`<span>${e}</span>`)}${f.map(e=>D`<small>${w(`presence.card.reportedTimeZone`,{zone:e})}</small>`)}
                    </dd>
                  </div>`:O}
            <div>
              <dt>${w(`presence.card.lastActivity`)}</dt>
              <dd>
                ${l===void 0?w(`presence.card.notObserved`):D`<span>${bo(l)} ${w(`presence.card.ago`)}</span>`}
              </dd>
            </div>
          </dl>`}
    ${So(g,e,!1)}${So(t.recentSessionKeys?v:[],e,!0)}
    ${i?D`<footer>
            <a href=${i.href} @click=${i.open}
              >${w(`presence.card.viewActivity`)}<span aria-hidden="true"
                >${E.chevronRight}</span
              ></a
            >
          </footer>`:O}
  </div>`}var wo,To;function Eo(){return(Eo=e((()=>{k(),We(),nt(),Ze(),a(),ri(),Bt(),xt(),dn(),x(),u(),h(),Pe(),ir(),xr(),Sr(),wo=class extends rt{render(e){return Co(e,this)}},To=Ke(wo)})))()}function Do(e){e.setAttribute(`aria-haspopup`,`dialog`),e.setAttribute(`aria-expanded`,`false`)}function Oo(e){e?.removeAttribute(`aria-controls`),e?.removeAttribute(`aria-expanded`),e?.removeAttribute(`aria-haspopup`)}function ko(e,t){let n=document.createElement(`div`);return n.id=e,n.className=t,n.dataset.open=`true`,n.setAttribute(`role`,`dialog`),n}function Ao(e){let t=document.body;for(let n=e.anchor;n;n=p(n))if(n.localName===`openclaw-modal-dialog`){t=n;break}t.append(e.card),mr(e.card),e.trigger.setAttribute(`aria-controls`,e.card.id),e.trigger.setAttribute(`aria-expanded`,`true`);let n=()=>jo(e.anchor,e.card,e.placement),r=null,i=()=>{r===null&&(r=requestAnimationFrame(()=>{r=null,n()}))},a=t=>{let n=t.composedPath()[0];if(n===window||n===document){i();return}for(let t=e.anchor;t;t=p(t))if(t===n){i();return}};return window.addEventListener(`resize`,i),window.addEventListener(`scroll`,a,!0),e.observeVisualViewport!==!1&&(window.visualViewport?.addEventListener(`resize`,i),window.visualViewport?.addEventListener(`scroll`,i)),n(),()=>{r!==null&&cancelAnimationFrame(r),window.removeEventListener(`resize`,i),window.removeEventListener(`scroll`,a,!0),window.visualViewport?.removeEventListener(`resize`,i),window.visualViewport?.removeEventListener(`scroll`,i)}}function jo(e,t,n){let r=e.getBoundingClientRect(),i=t.offsetWidth,a=t.offsetHeight,o=Math.max(W,innerWidth-i-W),s=Math.max(W,innerHeight-a-W),c=r.bottom+U+a+W<=innerHeight;if(n===`horizontal`){let e=r.right+U+i+W<=innerWidth,n=r.left-U-i>=W,l=r.top-U-a>=W;if(e||n||!c&&!l){let n=e?r.right+U:r.left-i-U;t.dataset.side=e?`right`:`left`,t.style.left=`${Math.min(Math.max(W,n),o)}px`,t.style.top=`${Math.min(Math.max(W,r.top),s)}px`;return}}let l=c?`bottom`:`top`,u=c?r.bottom+U:r.top-a-U;t.dataset.side=l,t.style.left=`${Math.min(Math.max(W,r.left),o)}px`,t.style.top=`${Math.min(Math.max(W,u),s)}px`}var U,W,Mo;function No(){return(No=e((()=>{tr(),U=10,W=12,Mo=class{constructor(e,t=120,n=e){this.close=e,this.closeDelayMs=t,this.dismiss=n,this.card=null,this.pointerInside=!1,this.pointerOverCard=!1,this.focusInside=!1,this.cardFocusInside=!1,this.explicitHold=!1,this.restoringFocus=!1,this.closeTimer=null,this.exitCleanup=null,this.anchor=null,this.openTimer=null,this.placement=`vertical`,this.stopPositioning=null,this.trigger=null,this.triggerAncestors=[],this.presentationObserver=new MutationObserver(()=>{this.checkPresentation()&&this.observePresentation()}),this.unmountContents=null,this.handleCardPointerEnter=e=>{e.currentTarget===this.card&&(this.pointerOverCard=!0,this.clearClose())},this.handleCardFocusIn=e=>{e.currentTarget===this.card&&(this.cardFocusInside=!0,this.clearClose())},this.handleCardFocusOut=e=>{let t=this.card;t&&e.currentTarget===this.card&&(e.relatedTarget instanceof Node&&t.contains(e.relatedTarget)||(this.cardFocusInside=!1,this.scheduleClose()))},this.handleTriggerKeyDown=e=>{if(e.key===`Escape`){this.dismiss();return}if(e.key!==`Tab`||e.shiftKey||e.composedPath()[0]!==this.trigger)return;let t=this.focusables()[0];t&&(e.preventDefault(),t.focus())},this.handleCardKeyDown=e=>{if(e.key!==`Escape`&&e.key!==`Tab`)return;let t=this.focusables(),n=e.shiftKey?t[0]:t.at(-1);if(e.key===`Tab`&&document.activeElement!==n)return;e.preventDefault();let r=this.trigger;this.dismiss(),this.returnFocus(r)}}renderContents(e,t){let n=e.contains(document.activeElement)?document.activeElement:null;if(t(),n&&!e.contains(document.activeElement)){let e=n instanceof HTMLAnchorElement?this.focusables().find(e=>e instanceof HTMLAnchorElement&&e.href===n.href):void 0;e?e.focus({preventScroll:!0}):(this.returnFocus(this.trigger),this.focusInside=document.activeElement===this.trigger)}}returnFocus(e){this.restoringFocus=!0,e?.focus({preventScroll:!0}),this.restoringFocus=!1}get held(){return this.explicitHold||this.pointerInside||this.pointerOverCard||this.focusInside||this.cardFocusInside}schedulePointerExit(e=220){this.pointerInside=!1,this.scheduleClose(e)}focusables(){return[...this.card?.querySelectorAll(`a[href]:not([tabindex="-1"])`)??[]]}scheduleOpen(e,t,n=this.trigger){this.trigger=n,this.observePresentation(),this.openTimer=window.setTimeout(()=>{this.openTimer=null,this.checkPresentation()&&t()},e)}clearClose(){this.closeTimer!==null&&(window.clearTimeout(this.closeTimer),this.closeTimer=null)}scheduleClose(e=this.closeDelayMs){if(this.clearClose(),!this.held){if(!this.card){this.close();return}this.closeTimer=window.setTimeout(()=>{this.closeTimer=null,this.held||this.close()},e)}}markTrigger(e){this.trigger!==e&&Oo(this.trigger),this.trigger=e,Do(e),this.observePresentation()}presentationAncestors(){let e=[],t=this.trigger;for(;t;)e.push(t),t=t instanceof Element&&t.assignedSlot?t.assignedSlot:t instanceof ShadowRoot?t.host:t.parentNode;return e}checkPresentation(){return this.trigger&&(!this.trigger.isConnected||this.presentationAncestors().some(e=>e instanceof Element&&(e.hasAttribute(`inert`)||e.hasAttribute(`hidden`)||e.getAttribute(`aria-hidden`)===`true`)))?(this.dismiss(),!1):!0}observePresentation(){let e=this.presentationAncestors();if(!(e.length===this.triggerAncestors.length&&e.every((e,t)=>e===this.triggerAncestors[t]))){this.presentationObserver.disconnect(),this.triggerAncestors=e;for(let t of e)this.presentationObserver.observe(t,{childList:!0,attributes:!0,attributeFilter:[`inert`,`hidden`,`aria-hidden`,`slot`,`name`]})}}mount(e,t,n,r=!0,i){if(!this.checkPresentation()){i?.(),t.remove();return}this.clearCard(),this.anchor=e,this.card=t,t.addEventListener(`pointerenter`,this.handleCardPointerEnter),t.addEventListener(`focusin`,this.handleCardFocusIn),t.addEventListener(`focusout`,this.handleCardFocusOut),this.placement=n,this.unmountContents=i??null,this.stopPositioning=Ao({anchor:e,trigger:this.trigger??e,card:t,placement:n,observeVisualViewport:r})}clearCard(e=0){this.stopPositioning?.(),this.stopPositioning=null,this.exitCleanup?.(),this.exitCleanup=null;let t=this.card,n=this.unmountContents;if(this.card=null,this.unmountContents=null,!t)return;if(e<=0||!t.isConnected||globalThis.matchMedia?.(`(prefers-reduced-motion: reduce)`).matches){n?.(),t.remove();return}t.dataset.open=`false`,t.style.pointerEvents=`none`;let r=null,i=()=>{r!==null&&(window.clearTimeout(r),r=null),t.removeEventListener(`transitionend`,a),n?.(),t.remove(),this.exitCleanup===i&&(this.exitCleanup=null)},a=e=>{e.target===t&&e.propertyName===`opacity`&&i()};t.addEventListener(`transitionend`,a),r=window.setTimeout(i,e+50),this.exitCleanup=i}position(){this.anchor&&this.card&&jo(this.anchor,this.card,this.placement)}reset(e=0){this.presentationObserver.disconnect(),this.triggerAncestors=[],this.openTimer!==null&&(window.clearTimeout(this.openTimer),this.openTimer=null),this.clearClose(),this.pointerInside=!1,this.pointerOverCard=!1,this.focusInside=!1,this.cardFocusInside=!1,this.explicitHold=!1,Oo(this.trigger),this.clearCard(e),this.anchor=null,this.trigger=null}}})))()}var Po,Fo;function Io(){return(Io=e((()=>{jn(),k(),$e(),Bn(),De(),Se(),a(),dn(),Vr(),u(),h(),Lr(),_(),jr(),Xn(),Eo(),kr(),ir(),No(),Po=0,Fo=class e extends g{constructor(...t){super(...t),this.profileId=``,this.label=``,this.context=new zn(this,{context:ze,subscribe:!0}),this.connection=new Nr(this,{getGateway:()=>this.context.value?.gateway,invalidateRequests:()=>this.close()}),this.portal=new Mo(()=>this.close()),this.activityExpiry=Pr(this,()=>tn(this.activity?.data?.presencePayload).users.filter(e=>Rt(e,this.person?.identity)),()=>this.renderCard()),this.close=()=>{e.active.get(this.ownerDocument)===this&&e.active.delete(this.ownerDocument),this.activity?.dispose(),this.activity=void 0,this.activityExpiry.sync(),this.stopRoute?.(),this.stopRoute=void 0,document.removeEventListener(`pointerdown`,this.outside,!0),document.removeEventListener(`focusin`,this.outside,!0),document.removeEventListener(`keydown`,this.escape,!0),this.portal.reset(),this.person=void 0,this.trigger?.setAttribute(`aria-expanded`,`false`),this.trigger?.setAttribute(`aria-haspopup`,`dialog`)},this.outside=e=>{e.composedPath().some(e=>e===this||e===this.portal.card)||this.close()},this.escape=e=>{if(e.key!==`Escape`)return;e.preventDefault(),e.stopPropagation();let t=this.portal.card?.contains(document.activeElement),n=this.trigger;this.close(),t&&this.portal.returnFocus(n)}}static{this.active=new WeakMap}createRenderRoot(){return this.replaceChildren(),super.createRenderRoot()}disconnectedCallback(){this.close(),super.disconnectedCallback()}willUpdate(e){e.has(`profileId`)&&this.close()}updated(){for(let e of this.trigger?.childNodes??[])e.nodeType===Node.TEXT_NODE&&e.textContent&&!e.textContent.trim()&&(e.textContent=``);this.portal.card&&this.renderCard()}get trigger(){return this.querySelector(`button`)}open(){let t=this.trigger;if(!t||!this.profileId||this.portal.card)return;e.active.get(this.ownerDocument)?.close(),e.active.set(this.ownerDocument,this);let n=ko(`openclaw-person-reference-`+ ++Po,`session-progress-hovercard person-activity-hovercard`);this.portal.markTrigger(t),n.addEventListener(`keydown`,this.portal.handleCardKeyDown),n.addEventListener(`pointerleave`,()=>{this.portal.pointerOverCard=!1,this.portal.scheduleClose()}),this.portal.mount(t,n,`vertical`,!0,()=>qe(O,n)),document.addEventListener(`pointerdown`,this.outside,!0),document.addEventListener(`focusin`,this.outside,!0),document.addEventListener(`keydown`,this.escape,!0);let r=this.context.value;this.stopRoute=r?.router.subscribe(()=>this.close()),r&&(this.activity=fr(r,()=>this.renderCard())),this.person=this.connection.capture()?void 0:null,this.renderCard(),this.loadPerson(n)}async loadPerson(e){let t=this.connection.capture(),n=this.context.value,r=this.profileId;if(!t||!n)return;let i=null;try{let{profiles:e}=await t.client.request(`users.list`,{}),n=new Map(e.map(e=>[e.id,e])),a=new Set,o=n.get(r);for(;o?.mergedInto&&!a.has(o.id);)a.add(o.id),o=n.get(o.mergedInto);o&&!o.mergedInto&&(i={id:o.id,identity:{type:`profile`,id:o.id},name:o.displayName?.trim()||o.githubIdentity?.login||w(`presence.card.person`),avatarUrl:o.hasAvatar?pn(o.id,o.updatedAt):void 0,watchedSessions:[]})}catch{}this.portal.card===e&&this.profileId===r&&this.context.value===n&&this.connection.isCurrent(t)&&(this.person=i,this.renderCard())}renderCard(){this.activityExpiry.sync();let e=this.portal.card,t=this.context.value;if(!e)return;e.setAttribute(`aria-label`,w(`presence.card.ariaLabel`,{name:this.person?.name??this.label}));let n=this.activity?.data,r=tn(n?.presencePayload).users.find(e=>Rt(e,this.person?.identity)),a=this.person&&{...this.person,name:r?.name??this.person.name,avatarUrl:r?.avatarUrl??this.person.avatarUrl,watchedSessions:r?.watchedSessions??[],entries:r?.entries??(n?.presencePayload?[]:void 0)},s={agentsList:t?.agents.state.agentsList,hello:t?.gateway.snapshot.hello},c=this.connection.capture(),l=t?.router.getState().location;this.portal.renderContents(e,()=>qe(a&&t?To({user:a,sessionData:n,watchAgentId:d(s),mainKey:o(s),globalScope:i(s),routing:sr(t,this.close),openSession:(e,n)=>{let r=y(e),i=v({face:r,sessionKey:e.key,row:e,fallbackAgentId:n,basePath:t.basePath,mainKey:o(s)});this.close(),Ir(this,{agentId:n,face:r,sessionKey:e.key,commit:()=>!c||this.context.value!==t||t.router.getState().location!==l||!this.connection.isCurrent(c)?!1:(Ur(t.gateway,i.options.pathname,e.key),t.navigate(r,i.options),Ve({selection:t.agentSelection,gateway:t.gateway,sessionKey:e.key,agentId:n}),!0)})}}):D`<div class="person-reference__status" role="status">
              ${this.person===void 0?w(`common.loading`):w(`chat.mentions.unavailable`)}
            </div>`,e)),this.portal.position()}render(){let e=Qn({id:this.profileId,identity:{type:`profile`,id:this.profileId},name:this.label.replace(/^@/u,``)}),t=D`<span
      class=${ur(`markdown-person-reference__avatar`,e)}
      aria-hidden="true"
      data-initials=${e.fallback.initials}
      >${$n({view:e,fallbackSelector:`.markdown-person-reference__avatar`,ariaHidden:!0})}</span
    >`,n=this.label.startsWith(`@`)?D`<span class="markdown-person-reference__prefix" aria-hidden="true">@</span
          >${this.label.slice(1)}`:this.label;return D`<button
      type="button"
      class="markdown-person-reference"
      aria-haspopup="dialog"
      aria-expanded="false"
      aria-label=${w(`presence.card.ariaLabel`,{name:this.label})}
      @pointerenter=${e=>{e.pointerType!==`touch`&&(this.portal.pointerInside=!0,this.portal.clearClose(),this.portal.scheduleOpen(250,()=>{this.portal.held&&this.open()}))}}
      @pointerleave=${()=>this.portal.schedulePointerExit()}
      @pointercancel=${this.close}
      @contextmenu=${this.close}
      @focus=${()=>{this.portal.restoringFocus||(this.portal.focusInside=!0,this.portal.clearClose(),this.open())}}
      @blur=${()=>{this.portal.focusInside=!1,this.portal.scheduleClose()}}
      @keydown=${this.portal.handleTriggerKeyDown}
      @click=${()=>{if(this.portal.explicitHold){this.close();return}this.portal.explicitHold=!0,this.open()}}
    >
      ${t}${n}
    </button>`}},F([j({attribute:`profile-id`})],Fo.prototype,`profileId`,void 0),F([j()],Fo.prototype,`label`,void 0),customElements.get(`openclaw-person-reference`)||customElements.define(`openclaw-person-reference`,Fo)})))()}var Lo,Ro,zo,Bo;function Vo(){return(Vo=e((()=>{k(),We(),a(),oe(),rr(),er(),Rn(),Lo=0,Ro=`.code-block-wrapper, .markdown-mermaid`,zo=class extends ie{constructor(...e){super(...e),this.scanPending=!1,this.active=!0,this.pendingBlocks=new Set,this.observedNodes=new Set,this.resizeObserver=typeof ResizeObserver>`u`?null:new ResizeObserver(e=>{if(!this.active||!this.isConnected)return;let t=new Set(e.map(({target:e})=>e.closest(`.code-block-wrapper`)));for(let e of t)e&&nr(e)}),this.mutationObserver=new MutationObserver(e=>{this.collectMutations(e),this.pendingBlocks.size&&this.scheduleScan()})}presentationChanged(e){e?.isPresented()===!1&&(this.active=!1,this.release())}collectMutations(e){for(let t of e){let e=(t.target instanceof Element?t.target:t.target.parentElement)?.closest(Ro);e&&this.pendingBlocks.add(e);for(let e of t.addedNodes)e instanceof HTMLElement&&this.collectBlocks(e);for(let e of t.removedNodes){if(!(e instanceof HTMLElement)||this.root?.contains(e))continue;let t=[e,...e.querySelectorAll(`.code-block-viewport, code`)];for(let e of t)this.observedNodes.delete(e)&&this.resizeObserver?.unobserve(e)}}}render(e=!0){return O}update(e,[t=!0]){this.updatePresentation(t);let n=e.element instanceof HTMLElement?e.element:void 0;return n!==this.root&&(this.release(),this.root=n),this.active=typeof t==`boolean`?t:t.isPresented(),this.active?this.scheduleScan():this.release(),O}disconnected(){super.disconnected(),this.release()}release(){this.mutationObserver.disconnect(),this.observedRoot=void 0,this.pendingBlocks.clear(),this.resizeObserver?.disconnect(),this.observedNodes.clear(),this.root&&or(this.root)}reconnected(){super.reconnected(),this.scheduleScan()}scheduleScan(){!this.scanPending&&this.active&&this.isConnected&&(this.scanPending=!0,queueMicrotask(()=>{this.scanPending=!1,this.active&&this.isConnected&&this.root?.isConnected&&this.scan(this.root)}))}scan(e){Ar(e),this.observedRoot!==e&&(this.collectBlocks(e),this.mutationObserver.observe(e,{childList:!0,subtree:!0,characterData:!this.resizeObserver}),this.observedRoot=e),this.collectMutations(this.mutationObserver.takeRecords());let t=[...this.pendingBlocks];this.pendingBlocks.clear();for(let n of t){if(!e.contains(n))continue;if(n.matches(`.markdown-mermaid`)){if(n.querySelector(`pre code`)){let t=()=>this.active&&this.isConnected&&this.root===e&&e.isConnected&&e.contains(n);In(async()=>{let{mountMermaidBlocks:e}=await import(`./markdown-mermaid-SJLrLUOj.js`);return{mountMermaidBlocks:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13]),import.meta.url).then(({mountMermaidBlocks:e})=>{t()&&e(n)},()=>{t()&&n.matches(`.markdown-mermaid`)&&(n.classList.remove(`markdown-mermaid`),n.prepend(w(`chat.mermaid.rendererError`)))})}continue}let t=n.querySelector(`.code-block-viewport`),r=t?.querySelector(`code`);if(!t||!r)continue;let i=n.querySelector(`.code-block-expand`);i&&(t.id||=`code-block-${++Lo}`,i.getAttribute(`aria-controls`)!==t.id&&i.setAttribute(`aria-controls`,t.id));for(let e of[t,r])this.observedNodes.has(e)||(this.observedNodes.add(e),this.resizeObserver?.observe(e));this.resizeObserver||nr(n)}}collectBlocks(e){e.matches(Ro)&&this.pendingBlocks.add(e);for(let t of e.querySelectorAll(Ro))this.pendingBlocks.add(t)}},Bo=Ke(zo)})))()}function Ho(e,t=``){try{let n=new URL(e,globalThis.location.origin),r=`${Pn(t)}${gt}`;return n.origin===globalThis.location.origin&&n.pathname.startsWith(r)&&/^[^/]+\/[^/]+$/u.test(n.pathname.slice(r.length))}catch{return!1}}async function Uo(e,{variant:t,...n},r,i){let{client:a,connectionEpoch:o,resourceBasePath:s}=e;if(!e.connected||!a)return null;let c=!/^artifact_managed_(?:image|media)_/u.test(n.artifactId)&&globalThis.location?.protocol===`https:`&&ve(a.gatewayUrl),l=()=>!r?.aborted&&e.connected&&e.client===a&&e.connectionEpoch===o,u=async e=>{if(!l())return null;let t=await a.request(`artifacts.download`,{...n,...e?{transport:`http`}:{}},{timeoutMs:3e4});return l()?t:null},d=await u(c);if(!d)return null;let f=d.url?.trim();if(!c||!f?.startsWith(`/api/artifacts/download/`))return d;let p={...d,url:`${Pn(s??``)}${f}${t===`thumbnail`?`?variant=thumbnail`:``}`},m=d.artifact.mimeType?.split(`;`,1)[0]?.trim().toLowerCase()??``;if(!i?.readBinary&&!/^(?:image\/|text\/|application\/json$)/u.test(m))return p;try{if(!Ho(p.url,s))throw Error(`Invalid artifact download URL`);let e=AbortSignal.timeout(3e4),n=await Le(p.url,{credentials:`same-origin`,redirect:`error`,signal:r?AbortSignal.any([r,e]):e});if(!n.ok)throw Error(`Artifact download failed (${n.status})`);if(n.headers.get(`content-disposition`)?.split(`;`,1)[0]?.trim().toLowerCase()!==`attachment`)throw Error(`Artifact download returned an unexpected content disposition`);let i=await n.blob(),a=i.type.split(`;`,1)[0]?.trim().toLowerCase();if(a!==(m||`application/octet-stream`)&&(t!==`thumbnail`||d.artifact.type!==`image`||a!==`image/png`))throw Error(`Artifact download returned an unexpected content type`);return l()?{...p,blob:i}:null}catch{return await u(!1)}}async function Wo(e,t,n){let r=await Uo(e,t,n);if(r?.blob&&(r.artifact.type!==`image`||!Go.test(r.blob.type.split(`;`,1)[0]?.trim().toLowerCase()??``)))return null;if(r?.encoding===`base64`&&r.artifact.type===`image`&&Go.test(r.artifact.mimeType??``)&&r.data)return{url:`data:${r.artifact.mimeType};base64,${r.data}`};let i=r?.url?.trim();if(!i)return null;let a=r?.expiresAt?.trim();return{url:i,...a?{expiresAt:a}:{},...r?.blob?{blob:r.blob}:{}}}var Go;function Ko(){return(Ko=e((()=>{yt(),je(),Me(),Ne(),Go=/^image\/(?:png|jpeg|gif|webp|avif)$/u})))()}function qo(e){if(!e.startsWith(rs))return;let t=JSON.parse(e.slice(9));if(!Array.isArray(t)||t.length!==2||typeof t[0]!=`string`||!t[0]||typeof t[1]!=`string`||!t[1])throw Error(`Invalid outbox recovery transfer`);return{account:t[0],sourceId:t[1]}}function G(e,t){return JSON.stringify(e)===JSON.stringify(t)}function Jo(e,t){let n=t.slice(t.indexOf(`:`)+1),r=e.sessions[n];return t.startsWith(`legacy-session:`)?r&&{sourceVersion:4,sourceScopeKey:n,session:r}:e.recovery[n]}function Yo(e,t){let n=t.slice(t.indexOf(`:`)+1);t.startsWith(`legacy-session:`)?delete e.sessions[n]:delete e.recovery[n]}function Xo(e,t,n){let r=[n],i=t.unscopedKey+`:account:`;for(let n=0;n<e.length;n++){let a=e.key(n);a?.startsWith(i)&&r.push(M(e,{...t,key:a,recoveryScope:decodeURIComponent(a.slice(i.length))}))}return r.flatMap(e=>Object.entries(e.recovery).flatMap(([e,t])=>{let n=qo(e);return n?[{...n,entry:t}]:[]}))}function Zo(e){let t=ue();if(!t)throw Error(`Browser storage is unavailable`);let n=on(e),r=M(t,n),i=n.recoveryScope?M(t,Ft(e.settings?.gatewayUrl)):null,a={},o=(e,t,r=!1)=>{let i=qo(e)?.account;if(i&&i!==n.recoveryScope)return;let o=r&&!i?`legacy-recovery:`+e:e;if(a[o]&&!G(a[o],t))throw Error(`Conflicting outbox recovery transfer`);a[o]=t};for(let[e,t]of Object.entries(r.recovery))o(e,t);if(i){let n=Xo(t,Ft(e.settings?.gatewayUrl),i),r=(e,t)=>n.some(n=>n.sourceId===e&&G(n.entry,t));for(let[e,t]of Object.entries(i.sessions)){let n=`legacy-session:`+e,i={sourceVersion:4,sourceScopeKey:e,session:t};r(n,i)||(a[n]=i)}for(let[e,t]of Object.entries(i.recovery))r(`legacy-recovery:`+e,t)||o(e,t,!0)}return{entries:Object.entries(a).filter(([,t])=>(Vt(t.session)||!!t.session.queue?.length)&&(t.session.queue??[]).every(t=>Mt(e,t))).map(([e,t])=>Object.assign({},t,{id:e,owner:{gatewayOwner:n.gatewayOwner,recoveryScope:n.recoveryScope}})),blocked:r.recoveryBlocked===!0||i?.recoveryBlocked===!0}}function Qo(e,t){let n=ue(),r=kt(e);if(!n||!r||!ce(e)||e.selectedChatSessionIncognito||bn(t.sessionKey)||e.connected&&e.client&&!e.client.recoveryScopeReady)return null;let i=on(e),a=M(n,i);St(a,e);let o=T(c(e,t.sessionKey,t.agentId)),s=a.sessions[o]??null;return{scope:t,gatewayOwner:i.gatewayOwner,recoveryScope:r,session:JSON.stringify(s),input:JSON.stringify([e.sessionKey,e.currentSessionId,e.connectionEpoch,e.chatMessage,e.chatMentions,e.chatGoalDraftMode,e.chatReplyTarget,e.chatAttachments,e.chatQueue]),revision:Xt(n,i.key,o,s?.draftRevision).latestAttempt}}function $o(e,t,n,r=0){let i=ns(e,t,n,r);return i===`completed`?`restored`:i}function es(e,t,n=()=>!0){let r=ns(e,t,null,0,n);return r===`completed`?`discarded`:r}function ts(e,t){if(!t.length||!e.sessionKey||!ce(e))return`unchanged`;let n=e.chatMessages,r=e.currentSessionId,i=T(c(e,e.sessionKey)),a=()=>e.chatMessages===n&&e.currentSessionId===r&&!!e.sessionKey&&T(c(e,e.sessionKey))===i,o=e=>{if(e.sessionId&&e.sessionId!==r)return!1;let t=Tt(n,e.sendRunId,!0);return!(!t||t.id===null&&t.sequence===null)},s=!1;for(let n of t){let t=sn(n.sourceScopeKey);if(!t||T(t)!==i||!n.session.queue?.some(o)||(n.id.startsWith(`legacy-session:`)||n.id.startsWith(`legacy-recovery:`))&&(Vt(n.session)||!n.session.queue.every(o)))continue;let r=ns(e,n,null,0,a,o);if(r!==`completed`)return r;s=!0}return s?`retired`:`unchanged`}function ns(e,t,n,r=0,i=()=>!0,a){let o=ue();if(!o)return`storage-failed`;if(is.has(o))return`conflict`;is.add(o);try{let s=e.client,l=on(e),u=e.connectionEpoch,d=()=>i()&&ue()===o&&e.client===s&&e.connectionEpoch===u&&!e.selectedChatSessionIncognito&&!bn(e.sessionKey)&&!!l.recoveryScope&&t.owner.gatewayOwner===l.gatewayOwner&&t.owner.recoveryScope===l.recoveryScope&&JSON.stringify(on(e))===JSON.stringify(l)&&(!n||JSON.stringify(Qo(e,n.scope))===JSON.stringify(n));if(!d())return`conflict`;let f=(e,t,n,r={})=>Ct(o,e,t,{requiredSessionKey:r.requiredSessionKey,beforeCommit:()=>{if(r.validate&&!r.validate()||JSON.stringify(M(o,e))!==n||!d())throw new as}}),p=M(o,l);if(n){let t=c(e,n.scope.sessionKey,n.scope.agentId),r=T(t),i=p.sessions[r];if(r!==T(n.scope)||i?.draft||i?.goalMode||i?.replyTarget||i?.queue?.length)return`conflict`}let{id:m,owner:h,...g}=t,_=Ft(e.settings?.gatewayUrl),v=qo(m),y=v?.account,b=v?.sourceId??m,x=m,ee=!!(y||m.startsWith(`legacy-`)),S=()=>{if(!ee)return!0;let e=M(o,_);return!e.recovery[x]&&!G(Jo(e,b),g)};if(y||m.startsWith(`legacy-`)){if(y&&y!==l.recoveryScope)return`conflict`;let n=M(o,_);if(x=y?m:rs+JSON.stringify([l.recoveryScope,m]),!y){let r=Jo(n,m);if(r){if(!G(r,g)||Xo(o,_,n).some(e=>e.sourceId===m&&G(e.entry,g))||n.recovery[x]||p.recovery[x]||!(t.session.queue??[]).every(t=>Mt(e,t))||!d())return`conflict`;let i=JSON.stringify(n);if(n.recovery[x]=g,Yo(n,m),f(_,n,i),n=M(o,_),!G(n.recovery[x],g))return`storage-failed`}}let r=n.recovery[x],i=p.recovery[x];if(!r&&!i||r&&!G(r,g)||i&&!G(i,g)||!(t.session.queue??[]).every(t=>Mt(e,t))||!d())return`conflict`;if(y&&G(Jo(n,b),g)){let e=JSON.stringify(n);if(n.recovery[x]=g,Yo(n,b),f(_,n,e),n=M(o,_),r=n.recovery[x],!G(r,g)||G(Jo(n,b),g))return`storage-failed`}if(r){if(p=M(o,l),p.recovery[x]&&!G(p.recovery[x],g))return`conflict`;if(!p.recovery[x]){if(!d())return`conflict`;let e=JSON.stringify(p);if(p.recovery[x]=g,f(l,p,e),p=M(o,l),!G(p.recovery[x],g))return`storage-failed`}if(n=M(o,_),!G(n.recovery[x],g)||G(Jo(n,b),g)||!d())return`conflict`;let e=JSON.stringify(n);if(delete n.recovery[x],f(_,n,e),!S())return`conflict`}p=M(o,l)}if(!G(p.recovery[x],g)||!(t.session.queue??[]).every(t=>Mt(e,t))||!d())return`conflict`;let C=JSON.stringify(p),w;if(n){let i=c(e,n.scope.sessionKey,n.scope.agentId);if(w=T(i),w!==T(n.scope))return`conflict`;let a=p.sessions[w];if(a?.draft||a?.goalMode||a?.replyTarget||a?.queue?.length)return`conflict`;let o=t.session;p.sessions[w]={...o,awaitingDefaults:void 0,draftRevision:bt(Math.max(r,n.revision,o.draftRevision??0)),queue:o.queue?.map(e=>Object.assign({},e,i,{storageScope:JSON.stringify([n.gatewayOwner,n.recoveryScope]),sendState:e.sendState===`held`?`held`:(e.sendAttempts??0)>0||e.sendState===`unconfirmed`?`unconfirmed`:`failed`,sendError:e.sendError??`Recovered message. Review this destination and retry only if it did not arrive.`}))}}let te=p.recovery[x],ne=a?te.session.queue?.filter(e=>!a(e)):[],re=a&&(Vt(te.session)||ne?.length)?{...te,session:zt({...te.session,queue:ne})}:void 0;if(re?p.recovery[x]=re:delete p.recovery[x],!d())return`conflict`;f(l,p,C,{requiredSessionKey:w,validate:S});let ie=M(o,l);return!G(ie.recovery[x],re)||w!==void 0&&JSON.stringify(ie.sessions[w])!==JSON.stringify(zt(p.sessions[w]))?`storage-failed`:(Ut(),`completed`)}catch(e){return e instanceof as?`conflict`:`storage-failed`}finally{is.delete(o)}}var rs,is,as;function os(){return(os=e((()=>{En(),h(),wt(),Et(),At(),Qt(),rn(),rs=`transfer:`,is=new WeakSet,as=class extends Error{}})))()}function ss(e){let t=new CustomEvent(ys,{detail:e,cancelable:!0});return window.dispatchEvent(t),t.defaultPrevented?`accepted`:t.rejection?`rejected`:`unhandled`}function K(e){return Math.min(1,Math.max(0,e))}function cs(e){if(e.points.length===0)return null;let t=1,n=1,r=0,i=0;for(let a of e.points)t=Math.min(t,K(a.x)),n=Math.min(n,K(a.y)),r=Math.max(r,K(a.x)),i=Math.max(i,K(a.y));return{x:t,y:n,width:r-t,height:i-n}}function ls(e){return String(Math.round(K(e)*100))}function us(e,t){return L(e.replace(/\s+/g,` `).trim(),t)}function ds(e){let t=us(e,xs);try{let e=new URL(t);return!e.username&&!e.password?t:(e.username=``,e.password=``,L(e.href,xs))}catch{let e=t.replace(/^([a-z][a-z\d+.-]*:\/\/)[^/?#\s]*@/i,`$1`);return L(e,xs)}}function fs(e){try{let t=new URL(e).hostname;if(t)return us(t,Ss)}catch{}return L(e,Ss)}function ps(e,t=40){return e.replace(/[^\w-]/g,``).slice(0,t)}function ms(e){let t=e.classes.slice(0,3).map(e=>ps(e)).filter(e=>e.length>0).map(e=>`.${e}`).join(``),n=ps(e.tag)||`element`,r=ps(e.id),i=`${n}${r?`#${r}`:``}${t}`,a=us(e.name,bs);return`${i}${a?` "${a}"`:``}${e.role?` (role=${us(e.role,40)})`:``}`}function hs(e){let t=ds(e.url),n=us(e.title,bs),r=fs(t),i=e.strokes.flatMap(e=>cs(e)??[]),a=e.element?{descriptor:ms(e.element),width:String(Math.round(e.element.rect.width)),height:String(Math.round(e.element.rect.height)),x:String(Math.round(e.element.rect.x)),y:String(Math.round(e.element.rect.y))}:null,o=[n?w(`browser.annotatePrompt.introTitled`,{url:t,title:n}):w(`browser.annotatePrompt.introUntitled`,{url:t})];return e.browserTab&&o.push(w(`browser.annotatePrompt.browserTarget`,{target:JSON.stringify(e.browserTab)})),i.slice(0,Cs).forEach((e,t)=>{o.push(w(`browser.annotatePrompt.region`,{index:String(t+1),x:ls(e.x+e.width/2),y:ls(e.y+e.height/2),width:ls(e.width),height:ls(e.height)}))}),i.length>Cs&&o.push(w(`browser.annotatePrompt.moreRegions`,{count:String(i.length-Cs)})),a&&o.push(w(`browser.annotatePrompt.elementDetail`,a)),o.push(w(`browser.annotatePrompt.outro`)),{modelContext:o.join(`
`),card:{title:n||L(r,bs),displayUrl:r,markedRegionCount:i.length,inspectedElement:a!==null}}}function gs(e){return Math.max(4,Math.round(e*.005))}function _s(e,t){e.lineCap=`round`,e.lineJoin=`round`,e.strokeStyle=ws,e.lineWidth=gs(t.width);for(let n of t.strokes)if(n.points.length!==0){if(e.beginPath(),n.points.forEach((n,r)=>{let i=K(n.x)*t.width,a=K(n.y)*t.height;r===0?e.moveTo(i,a):e.lineTo(i,a)}),n.points.length===1){let r=n.points[0];r&&e.lineTo(K(r.x)*t.width+.1,K(r.y)*t.height)}e.stroke()}if(t.highlight){let{x:n,y:r,width:i,height:a}=t.highlight;e.strokeRect(K(n)*t.width,K(r)*t.height,Math.max(2,i*t.width),Math.max(2,a*t.height))}}function vs(e){let t=document.createElement(`canvas`);t.width=e.width,t.height=e.height;let n=t.getContext(`2d`);if(!n)throw Error(w(`browser.errors.canvasUnavailable`));return n.drawImage(e.image,0,0,e.width,e.height),_s(n,e),t.toDataURL(`image/png`)}var ys,bs,xs,Ss,Cs,ws;function Ts(){return(Ts=e((()=>{a(),Si(),xi(),ys=`openclaw:browser-annotation`,bs=80,xs=500,Ss=160,Cs=8,ws=`#e0442d`})))()}var Es,q;function Ds(){return(Ds=e((()=>{Dn(),k(),$e(),Se(),Oe(),a(),Gt(),ae(),un(),_(),Pe(),cn(),Es=`openclaw-mcp-app-resource-mention`,q=class extends r{constructor(...e){super(...e),this.sessionKey=``,this.agentId=``,this.expanded=!1,this.serverName=``,this.query=``,this.resources=[],this.busy=!1,this.searched=!1,this.error=null,this.generation=0,this.scope=-1,this.catalog=new an(this,()=>this.context,()=>({sessionKey:this.sessionKey,agentId:this.agentId}))}willUpdate(e){let t=this.context?Ie(this.context.gateway).key:-1;(e.has(`sessionKey`)||e.has(`agentId`)||t!==this.scope)&&(this.scope=t,this.generation++,this.resources=[],this.error=null,this.searched=!1,this.busy=!1)}async search(){let e=this.context?.gateway.snapshot.client;if(!e||!this.serverName)return;let t=++this.generation,n=this.scope,{sessionKey:r,agentId:i,serverName:a}=this,o=()=>this.isConnected&&this.generation===t&&this.context?.gateway.snapshot.client===e&&this.scope===n;this.busy=!0,this.error=null,this.resources=[];try{let t=await e.request(`mcp.app.mention`,{sessionKey:r,agentId:i,serverName:a,query:this.query});o()&&(this.resources=t.resources,this.searched=!0)}catch(e){o()&&(this.error=I(I(e)?.details)?.code===`MCP_APP_UNSUPPORTED_MENTION_RESULT`?w(`mcpApp.errors.unsupportedResources`):S(e))}finally{o()&&(this.busy=!1)}}attach(e){this.context?.gateway.snapshot.phase===`connected`&&this.resources.includes(e)&&(this.dispatchEvent(new CustomEvent(`openclaw-mcp-app-resource-mention`,{bubbles:!0,composed:!0,cancelable:!0,detail:{sessionKey:this.sessionKey,agentId:this.agentId,serverName:this.serverName,resource:e}}))?this.error=w(`mcpApp.errors.mountUnavailable`):this.expanded=!1)}disconnectedCallback(){this.generation++,super.disconnectedCallback()}render(){let e=this.catalog.servers.filter(e=>e.mentionTool);return e.length?(e.some(e=>e.serverName===this.serverName)||(this.serverName=e[0].serverName),D`<section class="mcp-app-resources">
      <button
        type="button"
        class="btn btn--sm"
        aria-expanded=${String(this.expanded)}
        @click=${()=>{this.expanded=!this.expanded}}
      >
        ${E.link} ${w(`mcpApp.resources`)}
      </button>
      ${this.expanded?D`<p class="muted">${w(`mcpApp.resourceDescription`)}</p>
              <form
                class="mcp-app-resources__search"
                @submit=${e=>{e.preventDefault(),this.search()}}
              >
                <select
                  aria-label=${w(`mcpApp.title`)}
                  .value=${this.serverName}
                  ?disabled=${this.busy}
                  @change=${e=>{e.currentTarget instanceof HTMLSelectElement&&(this.serverName=e.currentTarget.value,this.generation++,this.resources=[],this.searched=!1)}}
                >
                  ${e.map(e=>D`<option value=${e.serverName}>${e.label}</option>`)}
                </select>
                <input
                  type="search"
                  aria-label=${w(`mcpApp.resourceSearch`)}
                  placeholder=${w(`mcpApp.resourceQuery`)}
                  .value=${this.query}
                  @input=${e=>{e.currentTarget instanceof HTMLInputElement&&(this.query=e.currentTarget.value,this.generation++,this.busy=!1,this.resources=[],this.searched=!1)}}
                />
                <button class="btn" type="submit" ?disabled=${this.busy}>
                  ${w(`mcpApp.resourceSearch`)}
                </button>
              </form>
              <div class="mcp-app-resources__results">
                ${this.resources.map(e=>D`<button type="button" class="btn mcp-app-resources__result" ?disabled=${this.busy} @click=${()=>this.attach(e)}><span>${e.title||e.name}</span><small>${e.description||e.uri}</small></button>`)}
              </div>
              ${this.searched&&!this.resources.length?D`<p role="status">${w(`mcpApp.noResources`)}</p>`:O} `:O}
      ${this.error?D`<p role="alert">${this.error}</p>`:O}
    </section>`):O}},F([Cn({context:ze,subscribe:!0})],q.prototype,`context`,void 0),F([j({attribute:!1})],q.prototype,`sessionKey`,void 0),F([j({attribute:!1})],q.prototype,`agentId`,void 0),F([A()],q.prototype,`expanded`,void 0),F([A()],q.prototype,`serverName`,void 0),F([A()],q.prototype,`query`,void 0),F([A()],q.prototype,`resources`,void 0),F([A()],q.prototype,`busy`,void 0),F([A()],q.prototype,`searched`,void 0),F([A()],q.prototype,`error`,void 0),customElements.get(`openclaw-mcp-app-resources`)||customElements.define(`openclaw-mcp-app-resources`,q)})))()}var Os,ks;function As(){return(As=e((()=>{f(),Os={chat:{detailPanel:{close:`Close sidebar`,copyPath:`Copy path`,discard:`Discard`,editFile:`Edit file`,searchInFile:`Search in file`,showInFiles:`Show in Files`,unavailable:`Unable to open`,outsideSessionBoundary:`This file is outside {session}'s workspace, and you can't open it.`,assetsUnavailable:`Some assets couldn't be loaded ({count})`,previousMatch:`Previous match`,nextMatch:`Next match`,overwrite:`Overwrite`,viewRawText:`View Raw Text`,viewSource:`Source`,renderedMarkdown:`Rendered Markdown`,renderedMarkdownHint:`Sanitized rich-text preview for quick reading.`,noPreviewableMarkdown:`No previewable markdown content.`,noContent:`No content available`,fullContentOversized:`Full content is unavailable because the stored transcript entry is too large to return safely.`,fullContentNotVisible:`Full content is unavailable because this transcript entry does not have a visible WebChat projection.`,fullContentUnavailable:`Full content is no longer available for this transcript entry.`,copyContents:`Copy file contents`,fileChanged:`File changed on disk since it was loaded.`,renderPreview:`Render preview`,imagePreview:`Image preview`,file:`File`,markdownPreview:`Markdown preview`,toolDetails:`Tool details`,reloadFailed:`Failed to reload the latest file.`,reloadBlocked:`Save or discard your file edits before reloading.`,draftRecovery:{review:`Review file drafts`,description:`Copy or download unsaved edits before discarding them. This only changes drafts in this tab, not files on disk. After resolving all drafts, try Refresh again.`,copy:`Copy {name}`,download:`Download {name}`,discard:`Discard {name}`,keep:`Keep drafts`,changed:`These edits changed. Close this dialog and review the drafts again.`,copyFailed:`Could not copy the edits. Select the text or download the draft instead.`},overwriteLoadFailed:`Failed to load the latest file before overwriting.`,fullContentLoadFailed:`Failed to load full content: {error}`}},filePreview:{bundle:{binary:`This binary file is included in the bundle but cannot be displayed as text.`,"too-large":`This file exceeds the preview limit. Its contents have not been truncated or loaded.`,unavailable:`This file could not be read safely or is unavailable. Close and reopen the skill to try again.`,incomplete:`Some bundle content is unavailable. Select a file to see its status.`},listLabel:`Files`,searchPlaceholder:`Search files…`,readOnly:`read-only`,emptyTitle:`No files match`,emptySubtitle:`Try another file name or content search.`,copyFile:`Copy file`,fileCount:`{count} files`,filteredFileCount:`{count}/{total} files`,noMatches:`No files match.`,navigate:`navigate`,kind:{text:`Text`,shell:`Shell`,file:`File`}}},ks=Object.assign(()=>{Object.assign(l.chat.detailPanel,Os.chat.detailPanel),Object.assign(l.filePreview,Os.filePreview)},{catalog:Os})})))()}function js(e,t,n=!1,r=!1){return D`
    <openclaw-panel-loading-skeleton
      .variant=${e}
      .label=${t}
      ?compact=${n}
      ?overlay=${r}
      role="status"
      aria-busy="true"
      aria-label=${t}
    ></openclaw-panel-loading-skeleton>
  `}var Ms;function Ns(){return(Ns=e((()=>{k(),$e(),_(),Ms=class extends se{constructor(...e){super(...e),this.variant=`files`,this.compact=!1,this.overlay=!1,this.label=``}static{this.styles=Qe`
    :host {
      display: block;
      box-sizing: border-box;
      width: 100%;
      min-height: 100%;
      padding: 14px;
      color: var(--muted);
    }

    :host([compact]) {
      min-height: 0;
      padding: 8px;
    }

    :host([data-panel-skeleton="desktop"]) {
      display: flex;
      flex: 1;
      min-height: 0;
      align-items: center;
      justify-content: center;
    }

    .desktop-loading {
      display: flex;
      flex-direction: column;
      align-items: center;
      gap: 12px;
      text-align: center;
      font-size: 13px;
    }

    .desktop-spinner {
      width: 24px;
      height: 24px;
      border: 2px solid var(--border);
      border-top-color: var(--muted);
      border-radius: 50%;
      animation: spin 1s linear infinite;
    }

    :host([overlay]) {
      position: absolute;
      inset: 0;
      z-index: 2;
      min-height: 0;
      background: color-mix(in srgb, var(--bg, #0e1015) 92%, transparent);
      pointer-events: none;
    }

    :host([compact]) .viewport,
    :host([compact]) .terminal,
    :host([compact]) .discussion-frame {
      min-height: 72px;
    }

    * {
      box-sizing: border-box;
    }

    /* Terminal/desktop/browser hosts use shadow roots, so base.css's .skeleton
       and global reduced-motion gate cannot reach here. Keep this primitive
       declaration-identical to base.css; the unit test guards against drift. */
    .skeleton {
      position: relative;
      overflow: hidden;
      background: var(--skeleton-base, var(--bg-muted));
      border-radius: var(--radius-md);
    }

    .skeleton::after {
      position: absolute;
      inset: 0;
      background: linear-gradient(
        90deg,
        transparent 25%,
        var(--skeleton-highlight, var(--bg-hover)) 50%,
        transparent 75%
      );
      content: "";
      transform: translateX(-100%);
      animation: shimmer var(--skeleton-duration, 1.5s) ease-in-out infinite;
      will-change: transform;
    }

    .line {
      height: 10px;
    }

    .short {
      width: 36%;
    }

    .medium {
      width: 62%;
    }

    .long {
      width: 88%;
    }

    .row,
    .toolbar,
    .bubble,
    .summary {
      display: flex;
      gap: 10px;
      align-items: center;
    }

    .rows,
    .conversation,
    .code {
      display: grid;
      gap: 12px;
    }

    .toolbar {
      padding-bottom: 12px;
      border-bottom: 1px solid var(--border);
      margin-bottom: 14px;
    }

    .icon {
      width: 18px;
      height: 18px;
      flex: 0 0 auto;
      border-radius: 5px;
    }

    .copy {
      display: grid;
      flex: 1;
      gap: 6px;
    }

    .meta {
      height: 7px;
      width: 28%;
    }

    .viewport {
      min-height: 220px;
      border-radius: 8px;
    }

    .address {
      height: 28px;
      flex: 1;
      border-radius: 7px;
    }

    .button {
      width: 28px;
      height: 28px;
      flex: 0 0 auto;
    }

    .summary {
      margin-bottom: 16px;
    }

    .pill {
      width: 64px;
      height: 24px;
      border-radius: 999px;
    }

    .file-heading {
      height: 30px;
      margin-bottom: 14px;
    }

    .code .line {
      height: 9px;
      border-radius: 3px;
    }

    .terminal {
      display: grid;
      gap: 11px;
      padding: 12px;
      min-height: 220px;
      align-content: start;
      border-radius: 8px;
      background: color-mix(in srgb, var(--bg) 76%, transparent);
    }

    .bubble {
      width: 82%;
      min-height: 58px;
      padding: 12px;
      align-items: flex-start;
      border-radius: 12px;
      background: color-mix(in srgb, var(--bg-muted) 76%, transparent);
    }

    .bubble.user {
      width: 58%;
      margin-left: auto;
    }

    .discussion-frame {
      min-height: 280px;
      padding: 18px;
      border: 1px solid var(--border);
      border-radius: 8px;
    }

    /* Mirrors board.css: a 38px tab strip over a 12-column grid with 56px rows,
       so the placeholder occupies the same footprint as the widgets it precedes. */
    .board-tabs {
      display: flex;
      gap: 14px;
      align-items: center;
      min-height: 38px;
      margin-bottom: 12px;
      padding: 0 13px;
      border-bottom: 1px solid var(--border);
    }

    .tab {
      width: 64px;
      height: 10px;
      border-radius: 5px;
    }

    .board-grid {
      container-type: inline-size;
      display: grid;
      gap: 12px;
      grid-auto-rows: 56px;
      grid-template-columns: repeat(12, minmax(0, 1fr));
    }

    .widget {
      display: grid;
      grid-template-rows: 38px minmax(0, 1fr);
      min-height: 0;
      min-width: 0;
      overflow: hidden;
      border: 1px solid var(--border);
      border-radius: 12px;
    }

    @container (max-width: 560px) {
      .widget {
        grid-column: 1 / -1 !important;
      }
    }

    .widget-bar {
      display: flex;
      gap: 7px;
      align-items: center;
      padding: 0 12px;
      border-bottom: 1px solid var(--border);
    }

    .widget-body {
      display: grid;
      gap: 10px;
      align-content: start;
      padding: 12px;
    }

    @keyframes shimmer {
      from {
        transform: translateX(-100%);
      }
      to {
        transform: translateX(100%);
      }
    }

    @keyframes spin {
      to {
        transform: rotate(360deg);
      }
    }

    @media (prefers-reduced-motion: reduce) {
      .desktop-spinner,
      .skeleton::after {
        animation: none;
      }
    }
  `}line(e=`long`){return D`<div class="skeleton line ${e}"></div>`}rows(e){return Array.from({length:e},(e,t)=>D`
        <div class="row">
          <div class="skeleton icon"></div>
          <div class="copy">
            ${this.line(t%2==0?`long`:`medium`)}
            <div class="skeleton meta"></div>
          </div>
        </div>
      `)}widget(e,t,n){return D`
      <div class="widget" style=${`grid-column: span ${e}; grid-row: span ${t}`}>
        <div class="widget-bar">
          <div class="skeleton icon"></div>
          ${this.line(`short`)}
        </div>
        <div class="widget-body">${n.map(e=>this.line(e))}</div>
      </div>
    `}render(){switch(this.variant){case`board`:return D`
          <div class="board-tabs">
            <div class="skeleton tab"></div>
            <div class="skeleton tab"></div>
          </div>
          <div class="board-grid">
            ${this.widget(6,4,[`long`,`medium`,`short`])}
            ${this.widget(6,4,[`medium`,`long`])} ${this.widget(4,3,[`medium`,`short`])}
            ${this.widget(8,3,[`long`,`medium`,`long`])}
          </div>
        `;case`browser`:return D`
          <div class="toolbar">
            <div class="skeleton button"></div>
            <div class="skeleton button"></div>
            <div class="skeleton address"></div>
          </div>
          <div class="skeleton viewport"></div>
        `;case`chat`:return D`
          <div class="conversation">
            <div class="bubble"><div class="copy">${this.line()}${this.line(`medium`)}</div></div>
            <div class="bubble user"><div class="copy">${this.line(`medium`)}</div></div>
            <div class="bubble"><div class="copy">${this.line()}${this.line(`short`)}</div></div>
          </div>
        `;case`desktop`:return D`
          <div class="desktop-loading">
            <span class="desktop-spinner" aria-hidden="true"></span>
            <span>${this.label}</span>
          </div>
        `;case`discussion`:return D`
          <div class="discussion-frame">
            <div class="conversation">
              ${this.line(`medium`)} ${this.line()} ${this.line(`long`)} ${this.line(`short`)}
            </div>
          </div>
        `;case`file-list`:return D`<div class="rows">${this.rows(5)}</div>`;case`document`:return D`
          <div class="skeleton file-heading medium"></div>
          <div class="code">
            ${this.line()} ${this.line()} ${this.line(`medium`)} ${this.line()}
            ${this.line(`short`)}
          </div>
        `;case`review`:return D`
          <div class="summary">
            <div class="skeleton pill"></div>
            <div class="skeleton pill"></div>
          </div>
          <div class="skeleton file-heading"></div>
          <div class="code">
            ${this.line()} ${this.line(`long`)} ${this.line(`medium`)} ${this.line()}
            ${this.line(`short`)}
          </div>
        `;case`terminal`:return D`
          <div class="toolbar">
            <div class="skeleton pill"></div>
            <div class="skeleton pill"></div>
          </div>
          <div class="terminal">
            ${this.line(`medium`)} ${this.line()} ${this.line(`short`)} ${this.line(`long`)}
          </div>
        `;default:return D`
          <div class="toolbar">
            <div class="skeleton address"></div>
            <div class="skeleton button"></div>
          </div>
          <div class="rows">${this.rows(5)}</div>
        `}}},F([j({reflect:!0,attribute:`data-panel-skeleton`})],Ms.prototype,`variant`,void 0),F([j({type:Boolean,reflect:!0})],Ms.prototype,`compact`,void 0),F([j({type:Boolean,reflect:!0})],Ms.prototype,`overlay`,void 0),F([j()],Ms.prototype,`label`,void 0),customElements.get(`openclaw-panel-loading-skeleton`)||customElements.define(`openclaw-panel-loading-skeleton`,Ms)})))()}async function Ps(e,t){if(t===null)return[];if(t!==void 0)try{return[await e.request(`environments.status`,{environmentId:t})]}catch(e){if(e instanceof Te&&e.code===`INVALID_REQUEST`&&e.message===`unknown environmentId`)return[];throw e}return(await e.request(`environments.list`,{})).environments}async function Fs(e,t){let n=await t.target;if(!t.isCurrent())return;let r=await Ps(e,n);if(!t.isCurrent())return;let i=r.find(e=>e.id===n);if(i?.status===`starting`)return{environments:[i],selectedSource:void 0,pendingSource:i.id};if(i?.status===`error`||!t.recoverToPicker&&i&&i.status!==`available`)throw Error(i.worker?.error??`Desktop environment is unavailable`);if(!(t.recoverToPicker&&n!==void 0&&!r.some(e=>e.id===n&&e.desktop)&&(r=await Ps(e,void 0),!t.isCurrent())))return{selectedSource:r.find(e=>e.id===n&&e.status===`available`&&e.desktop===!0)?.id,environments:r.filter(e=>e.desktop===!0)}}function Is(e){return e.id===`gateway`?{kind:`host`}:e.id.startsWith(`node:`)&&e.id.length>5?{kind:`node`,nodeId:e.id.slice(5)}:{kind:`environment`,environmentId:e.id}}function Ls(){return(Ls=e((()=>{Ee()})))()}var Rs,zs;function Bs(){return(Bs=e((()=>{f(),Rs={sessionsView:{placementFactService:`Service`,placementFactProfile:`Profile`,placementFactMachine:`Machine`,placementFactState:`State`,placementFactDisk:`Disk`,placementDiskFree:`{free} free`,runsOnDevice:`Runs on device`,runsOnWorker:`Runs on worker`,stopWorker:`Stop worker…`,stopWorkerConfirm:`Stop the worker for "{session}"?`,stopWorkerConfirmAction:`Stop worker`,deviceOffline:`Device offline`,waitingForDevice:`Waiting for device to reconnect; retry after it returns.`,continueOnGatewayMenu:`Continue on Gateway…`,continueOnGatewayAction:`Continue on Gateway`,continueOnGatewayConfirm:`Continue "{session}" on the Gateway? Unsynced device files and in-flight work may be lost. OpenClaw will continue from the last Gateway-synced state and will not replay the interrupted turn.`,discardWorkspaceDeleteConfirm:`The device for "{session}" is offline and has changes that have not synced. Reconnect it to keep those changes. To delete this session now, discard unsynced device files and in-flight work, then retry deletion once. The last Gateway-synced workspace is used; interrupted work is not replayed.`,discardWorkspaceDeleteAction:`Discard changes and delete`,discardWorkspaceArchiveConfirm:`The device for "{session}" is offline and has changes that have not synced. Reconnect it to keep those changes. To archive this session now, discard unsynced device files and in-flight work, then retry archiving once. The last Gateway-synced workspace is used; interrupted work is not replayed.`,discardWorkspaceArchiveAction:`Discard changes and archive`,workspaceRecoveryBatchHint:`Recover each offline session separately before retrying this selection.`,stopDeviceWorker:`Stop device worker…`,offlineDeviceStopUnavailable:`Reconnect the device to stop and sync its workspace, or Continue on Gateway.`,stopDeviceWorkerConfirm:`Stop the device worker for "{session}"?`,stopDeviceWorkerConfirmAction:`Stop device worker`,restartSession:`Restart session…`,restartingSession:`Restarting session…`,restartSessionTitle:`Restart session`,restartSessionDescription:`Choose where "{session}" should restart.`,restartSessionWarning:`The session restarts from its last saved workspace on the selected destination. Changes that the previous worker did not upload may be lost.`,restartSessionAction:`Restart session`,chooseWorker:`Choose worker…`,dispatchingSession:`Starting worker…`,repositoryWorkerRequiredLabel:`Worker required`,repositoryWorkerRequiredTitle:`Repository worker required`,repositoryWorkerRequiredPrompt:`Choose a device or cloud worker before sending another message in this repository session.`,dispatchSessionTitle:`Choose a worker`,dispatchSessionDescription:`Choose where "{session}" should continue.`,dispatchSessionNotice:`This repository exists only on workers, so the Gateway cannot run this session locally.`,dispatchSessionAction:`Continue on worker`,stoppingSession:`Stopping session…`,finishingSessionMove:`Finishing session move…`,syncingCloudFiles:`Cloud · syncing files`,syncingCloudFilesComposer:`Send now; your message starts automatically after workspace sync.`,syncingCloudFilesDetail:`Safely applying cloud edits`,failedSessionTitle:`Runner failed`,failedSessionRestartPrompt:`Restart this session to continue.`,failedSessionStopPrompt:`Stop the failed worker before restarting this session.`,failedSessionUnavailable:`This session's runner failed and cannot accept messages.`}},zs=Object.assign(()=>{Object.assign(l.sessionsView,Rs.sessionsView)},{catalog:Rs})})))()}function Vs(e,t,n){return Math.min(n,Math.max(t,Number.isFinite(e)?Math.round(e):t))}function Hs(e,t){return{name:e.name,w:e.w,h:e.h,order:t}}function Us(e,t=oc){return e.map(e=>({name:e.name,w:Vs(e.w,1,12),h:Vs(e.h,1,t),order:Number.isFinite(e.order)?e.order:0})).toSorted((e,t)=>e.order-t.order||e.name.localeCompare(t.name)).map(Hs)}function Ws(e,t,n,r,i){for(let a=n;a<n+i;a+=1)for(let n=t;n<t+r;n+=1)if(e[a]?.[n])return!1;return!0}function Gs(e,t){for(let n=t.y;n<t.y+t.h;n+=1){let r=e[n]??Array.from({length:12},()=>!1);e[n]=r;for(let e=t.x;e<t.x+t.w;e+=1)r[e]=!0}}function Ks(e,t){for(let n=0;;n+=1)for(let r=0;r<=12-t.w;r+=1)if(Ws(e,r,n,t.w,t.h))return{name:t.name,x:r,y:n,w:t.w,h:t.h}}function qs(e,t=oc){return Js(Us(e,t))}function Js(e){let t=[],n=[];for(let r of e){let e=Ks(t,r);Gs(t,e),n.push(e)}return n}function Ys(e,t){return t.x>=e.x&&t.x<e.x+e.w&&t.y>=e.y&&t.y<e.y+e.h}function Xs(e,t,n){let r=Us(e),i=r.findIndex(e=>e.name===t);if(i<0)return r;let a=Js(r),o=a.find(e=>e.name===n.name)??n,s={x:Vs(o.x,0,11),y:Math.max(0,Number.isFinite(o.y)?Math.floor(o.y):0)},c=a.find(e=>e.name===t);if(c&&Ys(c,s))return r;let l=r.splice(i,1),u=a.find(e=>e.name!==t&&Ys(e,s))??a.filter(e=>e.name!==t&&(e.y>s.y||e.y===s.y&&e.x>=s.x)).toSorted((e,t)=>e.y-t.y||e.x-t.x)[0],d=u?r.findIndex(e=>e.name===u.name):r.length;return r.splice(Math.max(0,d),0,...l),r.map(Hs)}function Zs(e,t,n,r){return Us(e).map(e=>e.name===t?{name:e.name,w:Vs(n,1,12),h:Vs(r,1,oc),order:e.order}:e)}function Qs(e,t,n){let r=Us(e),i=r.findIndex(e=>e.name===t);if(i<0)return r;let a=n===`left`||n===`up`?-1:1,o=Math.min(r.length-1,Math.max(0,i+a));return o!==i&&r.splice(o,0,...r.splice(i,1)),r.map(Hs)}function $s(e){return`grid-column: ${e.x+1} / span ${e.w}; grid-row: ${e.y+1} / span ${e.h};`}function ec(){return typeof window.matchMedia==`function`&&!window.matchMedia(`(hover: hover) and (pointer: fine)`).matches?lc:0}function tc(e,t,n){if(!(e.contentKind!==`html`||e.heightMode===`fixed`||t===void 0||!Number.isFinite(t)||t<=0))return t+2+n+((e.presentation??`card`)===`card`?24:0)}function nc(e){return e*56+(e-1)*12}function rc(e,t,n=0,r=cc){let i=tc(e,t,n);if(i===void 0)return e.sizeH;let a=Math.ceil((i+12)/68);return Math.min(r,Math.max(sc,a))}function ic(e,t,n=0,r=cc){let i=tc(e,t,n);if(i!==void 0)return Math.min(i,nc(rc(e,t,n,r)))}function ac(e,t,n=!1,r=``){let i=ec();return e.map(e=>({name:e.name,w:e.sizeW,h:rc(e,t.get(e.name),e.name===r?0:i,n?240:void 0),order:e.position}))}var oc,sc,cc,lc,uc;function dc(){return(dc=e((()=>{oc=20,sc=2,cc=20,lc=38,uc=`(hover: hover) and (pointer: fine)`})))()}function fc(e){let t=L(e.replace(/\s+/g,` `).trim(),mc);return t?`Regarding "${t}": `:null}function pc(e){return e.trim().replace(/^\/(?:btw|side)(?::\s*|\s+|$)/i,``).trim()}var mc;function hc(){return(hc=e((()=>{mc=300})))()}var gc;function _c(){return(_c=e((()=>{Xr(),gc=class{constructor(e,t){this.host=e,this.options=t,this.connected=!1,this.store=null,this.stopUpdates=null,this.client=null,this.hello=null,this.retry=()=>{this.target?.sessionKey&&this.store?.load(this.target).catch(()=>void 0)},this.refresh=e=>{this.connected&&(this.synchronize(),this.target&&this.store?.refresh(this.target,e))},this.dismiss=e=>this.target?this.store?.dismiss(this.target,e)??Promise.resolve(!1):Promise.resolve(!1),this.handleStoreUpdate=()=>{let e=this.presentation,t=this.readPresentation();this.presentation=t,t&&(!e||t.card!==e.card||t.error!==e.error||t.refreshState!==e.refreshState||t.client!==e.client||t.hello!==e.hello||t.phase!==e.phase)&&this.host.requestUpdate()},e.addController(this)}get card(){return this.target?this.store?.get(this.target)??null:null}get lifetime(){return this.target?this.store?.getLifetime(this.target):void 0}get loading(){return!this.target||this.store?.get(this.target)===void 0}get error(){return this.target?this.store?.getError(this.target):void 0}get refreshState(){return this.target?this.store?.getRefreshState(this.target):void 0}hostConnected(){this.connected=!0,this.synchronize()}hostUpdate(){this.connected&&this.synchronize()}hostDisconnected(){this.connected=!1,this.release()}readPresentation(){let e=this.options.gateway()?.snapshot;return this.target?{card:this.store?.get(this.target),error:this.error,refreshState:this.refreshState,client:e?.client,hello:e?.hello,phase:e?.phase}:void 0}synchronize(){let e=this.options.gateway()??null,t=this.options.target()??void 0,n=e?.snapshot.client??null,r=e?.snapshot.hello??null,i=e?Yr(e):null;i!==this.store&&(this.release(),this.store=i,this.stopUpdates=i?.subscribe(this.handleStoreUpdate)??null),(t?.sessionKey!==this.target?.sessionKey||t?.agentId!==this.target?.agentId||t&&(n!==this.client||r!==this.hello))&&(this.target=t,this.client=n,this.hello=r,this.store?.watch(this,t?[t]:[],{admitAutomaticRead:()=>{let i=this.options.target();return this.connected&&this.options.gateway()===e&&e?.snapshot.client===n&&e?.snapshot.hello===r&&i?.sessionKey===t?.sessionKey&&i?.agentId===t?.agentId}}),this.presentation=this.readPresentation())}release(){this.store?.unwatch(this),this.stopUpdates?.(),this.stopUpdates=null,this.store=null,this.target=void 0,this.client=null,this.hello=null,this.presentation=void 0}}})))()}function vc(e){let t=e.busy||e.disabled===!0;return D`
    <form class="mcp-server-form" @submit=${t=>{t.preventDefault();let n=t.currentTarget,r=new FormData(n),i=r.get(`mcp-name`),a=r.get(`mcp-transport`),o=r.get(`mcp-target`);e.onSubmit({name:typeof i==`string`?i.trim():``,transport:a===`sse`||a===`stdio`?a:`streamable-http`,target:typeof o==`string`?o.trim():``})}}>
      <label>
        <span>${w(`mcpServers.nameLabel`)}</span>
        <input
          name="mcp-name"
          class="settings-input"
          type="text"
          required
          placeholder="context7"
          autocomplete="off"
          ?autofocus=${e.autofocus??!1}
          title=${e.blockedReason??``}
          ?disabled=${t}
        />
      </label>
      <label>
        <span>${w(`mcpServers.transportLabel`)}</span>
        <select
          name="mcp-transport"
          class="settings-select"
          title=${e.blockedReason??``}
          ?disabled=${t}
        >
          <option value="streamable-http">${w(`mcpServers.transportStreamableHttp`)}</option>
          <option value="sse">${w(`mcpServers.transportSse`)}</option>
          <option value="stdio">${w(`mcpServers.transportStdio`)}</option>
        </select>
      </label>
      <label class="mcp-server-form__target">
        <span>${w(`mcpServers.targetLabel`)}</span>
        <input
          name="mcp-target"
          class="settings-input"
          type="text"
          required
          placeholder="https://mcp.example.com/mcp  ·  npx some-mcp-server"
          autocomplete="off"
          title=${e.blockedReason??``}
          ?disabled=${t}
        />
      </label>
      <div class="mcp-server-form__actions">
        <button
          type="submit"
          class="btn btn--sm"
          title=${e.blockedReason??``}
          ?disabled=${t}
        >
          ${e.busy?w(`mcpServers.adding`):w(`mcpServers.add`)}
        </button>
        <button type="button" class="btn btn--sm" ?disabled=${e.busy} @click=${e.onCancel}>
          ${w(`common.cancel`)}
        </button>
      </div>
    </form>
  `}function yc(){return(yc=e((()=>{k(),a(),nn(),Jt()})))()}function bc(e){return typeof e==`string`?it(e):void 0}function xc(e,t={}){let n=I(e),r=I(n?.messages),i=I(r?.queue),a=bc(I(i?.byChannel)?.webchat)??bc(i?.mode),o=bc(t.effectiveMode),s=bc(t.sessionMode);if(s)return s;if(t.configNeedsApply)return o;if((t.sessionMetadataLoaded!==!1||o)&&(n||o))return a??o??`steer`}function Sc(e,t){return Ue(e)??t}function Cc(){return(Cc=e((()=>{st(),ht(),Ae()})))()}async function wc(e,t){switch(t.kind){case`device-pairing`:{let t=e.gateway.snapshot;return t.phase!==`connected`||!xe(t).canAdmin?!1:e.overlays.openDevicePairSetup()}default:return t.kind,!1}}function Tc(){return(Tc=e((()=>{He()})))()}function Ec(e){e.target&&kc.set(e.target,e.timeStamp)}function Dc(e){e.target&&kc.delete(e.target)}function Oc(e){if(e.isComposing||e.keyCode===229)return!0;if(e.key!==`Enter`)return Dc(e),!1;let t=e.target?kc.get(e.target):void 0;return t!==void 0&&Math.abs(e.timeStamp-t)<100}var kc;function Ac(){return(Ac=e((()=>{kc=new WeakMap})))()}var jc,Mc;function Nc(){return(Nc=e((()=>{f(),jc={chat:{pullRequests:{checksQueued:`Queued`,checksSkippedCount:`{count} skipped`,checksLoading:`Loading jobs and steps…`,checksEmpty:`No check details are available for this commit.`,checksUnavailable:`Couldn’t load all CI details. Try again or open the checks on GitHub.`,checksStale:`Some CI details are unavailable or out of date. Try again or open the job on GitHub.`,checksRateLimited:`GitHub’s rate limit was reached. CI details may be out of date.`,checksRetryAfter:`Try again in {duration}.`,checksNoSteps:`This check does not provide GitHub Actions steps.`,checksStepsUnavailable:`Step details are not available yet.`,openJob:`Open job on GitHub`,openCheck:`Open check details`,automationLabel:`Pull request automations`,automationAutoFix:`Auto-fix CI & address comments`,automationAutoMerge:`Auto-merge when ready`,automationAutoArchive:`Auto-archive on merge or close`,automationSchedulerDisabled:`The scheduler is disabled. Enabled jobs will not run.`,automationSessionRequired:`Automations need a verified session identity. Reopen this session and try again.`,automationReadRequired:`Connect with read access to view automations.`,automationAdminRequired:`Administrator access is required to change automations.`,automationRefreshRequired:`Refresh automations before changing them.`,automationLoadFailed:`Couldn’t load automations. Try again.`,automationSaveFailed:`Couldn’t confirm the change. Refresh to check the current state before trying again.`,automationRunning:`Running`,automationStopping:`Stopping`,automationEnabled:`Enabled`,automationOff:`Off`,automationNextCheck:`Next check: {time}`,automationScheduleDisabled:`Automatically disabled after {count} scheduling errors.`,automationFailureDisabled:`Automatically disabled after {count} failed runs.`,automationLastError:`Last error: {error}`,automationOpenJob:`Open automation`,automationNoChecks:`No CI checks reported.`,automationLoading:`Loading automations…`,automationSaving:`Saving automations…`,automationUnavailable:`Automations are currently unavailable.`,automationRetry:`Try again`}}},Mc=Object.assign(()=>Object.assign(l.chat.pullRequests,jc.chat.pullRequests),{catalog:jc})})))()}function Pc(e){let t=lt(e??``);return t?D`<span
        class="session-color-dot"
        style=${`--session-color: var(--session-color-${t})`}
        role="img"
        aria-label=${w(`sessionsView.sessionColor`,{color:w(`sessionsView.colors.${t}`)})}
      ></span>`:O}function Fc(){return(Fc=e((()=>{k(),ot(),a()})))()}function Ic(e){if(e.status!==503)return;let t=e.headers?.get(`retry-after`)?.trim();if(!t||!/^\d+$/.test(t))return;let n=Number(t)*1e3;return Number.isSafeInteger(n)&&n>0&&n<=Hc?n:void 0}function Lc(e,t){J.get(e)===t&&(J.delete(e),t.retryTimer!==void 0&&(clearTimeout(t.retryTimer),t.retryTimer=void 0),t.controller.abort(),t.blobUrl&&URL.revokeObjectURL(t.blobUrl))}function Rc(e,t,n,r,i){return JSON.stringify([n,r,t,i,e])}function zc(e,t){let n=J.get(e);n&&(n.consumers.delete(t),!(n.consumers.size>0||n.releaseTimer!==void 0)&&(n.releaseTimer=setTimeout(()=>{n.releaseTimer=void 0,!(J.get(e)!==n||n.consumers.size>0)&&Lc(e,n)},0)))}async function Bc(e,t,n,r,i,a){a.unavailable=!1;let o=setTimeout(()=>a.controller.abort(),Vc),s=null,c=!1,l;try{for(let e of n.length>0?n:[``]){let n=await Le(t,{...e?{headers:{Authorization:`Bearer ${e}`}}:{},signal:a.controller.signal});if(n.ok){s=URL.createObjectURL(await n.blob());break}if(c=n.status===404,a.unavailable=i&&n.status===503,l=a.unavailable?Ic(n):void 0,n.status!==401&&n.status!==403)break}}catch{}finally{clearTimeout(o)}if(J.get(e)!==a){s&&URL.revokeObjectURL(s);return}if(!s){if(c&&r)return;if(a.unavailable&&a.consumers.size>0){l!==void 0&&a.retryAttempts<Uc&&(a.retryAttempts+=1,a.retryTimer=setTimeout(()=>{a.retryTimer=void 0,J.get(e)===a&&a.consumers.size!==0&&(a.controller=new AbortController,Bc(e,t,n,r,i,a))},l));return}Lc(e,a);return}a.unavailable=!1,a.blobUrl=s;for(let e of a.consumers.values())e()}var Vc,Hc,Uc,J,Wc;function Gc(){return(Gc=e((()=>{Me(),Vc=3e4,Hc=3e4,Uc=3,J=new Map,Wc=class{constructor(e,t={}){this.host=e,this.options=t,this.owner=Symbol(`authenticated-avatar-route-owner`),this.keys=new Set,this.connected=!1,this.onUpdate=()=>{this.connected&&this.host.requestUpdate()},e.addController(this)}hostConnected(){this.connected=!0,this.stopAuthRecovery??=Fe(()=>{for(let e of this.keys){let t=J.get(e);t?.unavailable&&t.retryTimer===void 0&&Lc(e,t)}this.onUpdate()}),this.host.requestUpdate()}hostDisconnected(){this.connected=!1,this.stopAuthRecovery?.(),this.stopAuthRecovery=void 0,this.reset()}reset(){for(let e of this.keys)zc(e,this.owner);this.keys.clear()}withActiveRoutes(e){let t=this.keys;this.keys=new Set;try{return e()}finally{for(let e of t)this.keys.has(e)||zc(e,this.owner)}}resolve(e,t,n=``){if(!e.startsWith(`/`))return e;if(!this.connected)return null;let r=this.options.cacheNotFound===!0,i=this.options.retryUnavailable===!0,a=Rc(e,t,r,i,n),o=J.get(a);return o||(o={blobUrl:null,consumers:new Map,controller:new AbortController,releaseTimer:void 0,retryTimer:void 0,retryAttempts:0,unavailable:!1},J.set(a,o),Bc(a,e,t,r,i,o)),o.releaseTimer!==void 0&&(clearTimeout(o.releaseTimer),o.releaseTimer=void 0),o.consumers.set(this.owner,this.onUpdate),this.keys.add(a),o.blobUrl}}})))()}var Y;function Kc(){return(Kc=e((()=>{k(),$e(),Gc(),_(),Pe(),Y=class extends g{constructor(...e){super(...e),this.routeUrl=null,this.authTokens=[],this.authReady=!1,this.undecodableRouteUrl=null,this.loader=new Wc(this,{cacheNotFound:!0,retryUnavailable:!0})}render(){return this.loader.withActiveRoutes(()=>this.renderContent())}renderContent(){let e=this.routeUrl,t=e&&this.authReady&&this.undecodableRouteUrl!==e?this.loader.resolve(e,this.authTokens,this.connectionId):null;return t?D`<img
      class="workspace-icon"
      src=${t}
      alt=""
      aria-hidden="true"
      decoding="async"
      @error=${()=>{this.undecodableRouteUrl=e}}
    />`:D`<span class="workspace-icon-fallback" aria-hidden="true">${E.folder}</span>`}},F([j({attribute:!1})],Y.prototype,`routeUrl`,void 0),F([j({attribute:!1})],Y.prototype,`authTokens`,void 0),F([j({attribute:!1})],Y.prototype,`authReady`,void 0),F([j({attribute:!1})],Y.prototype,`connectionId`,void 0),F([A()],Y.prototype,`undecodableRouteUrl`,void 0),customElements.get(`openclaw-workspace-icon`)||customElements.define(`openclaw-workspace-icon`,Y)})))()}function X(e){return typeof e==`string`&&e.length>0}function qc(e){return On(e)&&X(e.catalogId)&&X(e.hostId)&&X(e.threadId)?{catalogId:e.catalogId,hostId:e.hostId,threadId:e.threadId,...X(e.sourceHomeId)?{sourceHomeId:e.sourceHomeId}:{}}:null}function Jc(e){if(!On(e))return null;if(e.kind===`attach`)return X(e.sessionId)&&typeof e.agentOwned==`boolean`?{kind:`attach`,sessionId:e.sessionId,agentOwned:e.agentOwned}:null;let t=e.agentId;if(t!==null&&!X(t))return null;if(e.kind===`restore`||e.kind===`open`)return{kind:e.kind,agentId:t};if(e.kind===`catalog`){let n=qc(e.catalog);return n?{kind:`catalog`,agentId:t,catalog:n}:null}return null}function Yc(e){try{let t=globalThis.sessionStorage?.getItem(e),n=t?JSON.parse(t):null;return Array.isArray(n)?n:[]}catch{return[]}}function Xc(e=``){return Yc(el+e).filter(X)}function Zc(e,t=``){try{globalThis.sessionStorage?.setItem(el+t,JSON.stringify(e))}catch{}}function Qc(){return Yc(tl).flatMap(e=>Jc(e)??[])}function $c(e){try{if(e.length===0){globalThis.sessionStorage?.removeItem(tl);return}globalThis.sessionStorage?.setItem(tl,JSON.stringify(e))}catch{}}var el,tl;function nl(){return(nl=e((()=>{el=`openclaw.terminal.sessions.v1`,tl=`openclaw.terminal.actions.v1`})))()}function rl(e,t){let n=e instanceof CustomEvent&&typeof e.detail==`object`&&e.detail!==null?e.detail:null;if(!n||n.open===!1)return null;let r=n.agentId?.trim()||t;return n.newSession===!0?{kind:`open`,agentId:r}:n.terminalSessionId?{kind:`attach`,sessionId:n.terminalSessionId,agentOwned:n.agentOwned??!0}:n.open===!0?{kind:`restore`,agentId:r}:null}var il,al;function ol(){return(ol=e((()=>{nl(),il=class{constructor(e=!0){this.persistent=e,this.refreshPending=!1,this.refreshTimedOut=!1,this.refreshTimer=null,this.drainScheduled=!1,this.hosts=[],this.fenceHost=null,this.fenceGeneration=0,this.timeoutHost=null,this.actions=[],this.rehydrate()}rehydrate(){if(!this.persistent)return;let e=Qc(),t=e.some(e=>e.kind!==`restore`)?e.filter(e=>e.kind!==`restore`):e;this.actions.splice(0,this.actions.length,...t),t.length!==e.length&&this.persist()}persist(){this.persistent&&$c(this.actions)}get host(){return this.hosts.at(-1)??null}bindHost(e){this.hosts.length===0&&this.rehydrate(),this.hosts=[...this.hosts.filter(t=>t!==e),e],this.drain()}releaseHost(e){this.hosts=this.hosts.filter(t=>t!==e),this.fenceHost===e&&this.resetLifecycle(e),this.hosts.length===0&&(this.clearRefreshTimer(),this.refreshTimedOut=!1,this.timeoutHost=null,this.rehydrate())}get hasActions(){return this.actions.length>0}get fenced(){return this.refreshPending}get waitingForRefresh(){return this.refreshPending&&!this.refreshTimedOut&&this.actions.length>0}beginRefreshFence(e,t){this.refreshPending=!0,this.fenceHost=e,this.fenceGeneration=t,this.clearRefreshFailure(),this.clearRefreshTimer(),this.armRefreshTimer()}releaseRefreshFence(e){this.fenceHost===e&&(this.resetLifecycle(e),this.drain())}resetLifecycle(e){(this.fenceHost===null||this.fenceHost===e)&&(this.clearRefreshTimer(),this.refreshPending=!1,this.fenceHost=null,this.clearRefreshFailure())}async queue(e,t={}){let n=!1;if(e.kind!==`restore`)for(let e=this.actions.length-1;e>=0;--e)this.actions[e]?.kind===`restore`&&(this.actions.splice(e,1),n=!0);let r=this.actions.some(e=>e.kind!==`restore`),i=JSON.stringify(e);if(!(e.kind===`restore`&&r)&&!this.actions.some(e=>JSON.stringify(e)===i)&&(this.actions.push(e),n=!0),n&&this.persist(),t.deferUntilHostChange)return;this.armRefreshTimer();let a=this.host;this.refreshPending?a?.requestUpdate():a&&!a.hasTabs()&&a.setBooting(!0),await this.drain()}async drain(){let e=this.host;if(!this.drainScheduled&&this.actions.length!==0&&e&&this.canRun(e)){this.drainScheduled=!0;try{await e.bootQueue.enqueue(async t=>{let n=this.actions[0];if(!n||!t()||!this.canRun(e))return;let r=await this.execute(e,n,()=>this.retireAction(n));r&&t()&&(this.retireAction(n),r===`cancelled-restore`&&this.host===e&&e.cancelledRestoreCompleted())})}finally{this.drainScheduled=!1;let e=this.host;this.actions.length>0&&e&&this.canRun(e)?this.drain():this.actions.length===0&&e&&!e.hasTabs()&&e.setBooting(!1)}}}retireAction(e){let t=this.actions.indexOf(e);t!==-1&&(this.actions.splice(t,1),this.persist())}cancel(e){this.host===e&&(this.actions.splice(0),this.persist(),e.setBooting(!1),this.clearRefreshFailure())}canRun(e){return!this.refreshPending&&e.canRun()}async execute(e,t,n){if(t.kind===`attach`)return e.attach(t.sessionId,t.agentOwned,n);if(t.kind===`open`)return e.open(void 0,t.agentId,n);let r=await e.reattach(t.kind===`restore`?n:void 0);return this.canRun(e)?t.kind===`catalog`?e.open(t.catalog,t.agentId,n):r?`cancelled-restore`:e.ensureInitial(t.agentId,n):!1}clearRefreshTimer(){this.refreshTimer!==null&&(globalThis.clearTimeout(this.refreshTimer),this.refreshTimer=null)}clearRefreshFailure(){this.refreshTimedOut&&=(this.timeoutHost?.clearTimeout(),this.timeoutHost=null,!1)}armRefreshTimer(){let e=this.fenceHost;if(!this.refreshPending||!e||this.refreshTimer!==null||this.actions.length===0)return;let t=this.fenceGeneration;this.refreshTimer=globalThis.setTimeout(()=>{this.refreshTimer=null,this.fenceHost===e&&t===e.currentGeneration()&&this.refreshPending&&this.actions.length!==0&&(this.refreshTimedOut=!0,this.timeoutHost=e,e.showTimeout(),e.setBooting(!1))},e.timeoutMs())}},al=new il})))()}var Z;function sl(){return(sl=e((()=>{Dn(),k(),$e(),Se(),Oe(),a(),Gt(),ae(),Qr(),_(),t(),Pe(),cn(),Z=class extends r{constructor(...e){super(...e),this.sessionKey=``,this.agentId=``,this.error=null,this.pending=new Set,this.subscriptions=new te(this).watch(()=>this.context?.gateway,(e,t)=>{let n=new Map,r=e.subscribe(t),i=e.subscribeEvents(t=>{if(t.event!==`mcp.app.hostContextChanged`)return;let r=t.payload;if(!r||typeof r!=`object`||!(`viewId`in r)||typeof r.viewId!=`string`)return;let i=e.snapshot.client,a=Jr(i,this.sessionKey,this.agentId).find(e=>e.viewId===r.viewId);if(!i||!a)return;if(`modelContext`in r&&r.modelContext===null){if(!(`updateId`in r)||r.updateId!==a.state?.updateId)return;n.set(a.viewId,(n.get(a.viewId)??0)+1),Zr(i,{...a,state:null});return}let o=(n.get(a.viewId)??0)+1;n.set(a.viewId,o);let s=t=>{this.isConnected&&e.snapshot.client===i&&n.get(a.viewId)===o&&Zr(i,{...a,state:t})};i.request(`mcp.app.modelContext`,{sessionKey:a.sessionKey,agentId:a.agentId,viewId:a.viewId}).then(e=>s(e.state)).catch(()=>s(null))});return()=>{r(),i(),n.clear()}}).watch(()=>this.context?.gateway.snapshot.client,(e,t)=>Kr(e,t))}async removeItem(e,t){let n=this.context,r=n?.gateway.snapshot.client,i=e.state;if(!n||!r||!i||n.gateway.snapshot.phase!==`connected`)return;let a=Ie(n.gateway).key,o=this.sessionKey;this.pending=new Set([...this.pending,e.viewId]),this.error=null;try{let s=await r.request(`mcp.app.removeModelContext`,{sessionKey:e.sessionKey,agentId:e.agentId,viewId:e.viewId,updateId:i.updateId,...t===void 0?{}:{index:t}});this.isConnected&&n.gateway.snapshot.client===r&&Ie(n.gateway).key===a&&o===this.sessionKey&&Jr(r,o,this.agentId).find(t=>t.viewId===e.viewId)?.state?.updateId===i.updateId&&Zr(r,{...e,state:s.state})}catch(e){this.isConnected&&n.gateway.snapshot.client===r&&o===this.sessionKey&&(this.error=S(e))}finally{this.pending=new Set([...this.pending].filter(t=>t!==e.viewId))}}disconnectedCallback(){this.subscriptions.clear(),super.disconnectedCallback()}render(){let e=Jr(this.context?.gateway.snapshot.client??null,this.sessionKey,this.agentId);return e.length?D`<section class="mcp-app-context" aria-label=${w(`mcpApp.contextTitle`)}>
      <div class="mcp-app-context__header" title=${w(`mcpApp.contextDescription`)}>
        ${E.puzzle} ${w(`mcpApp.contextTitle`)}
      </div>
      ${e.map(e=>D`<div class="mcp-app-context__items">
            ${(e.state?.content??[]).map((t,n)=>{let r=t.type===`image`?`mcpApp.imageContent`:t.type===`text`?`mcpApp.textContent`:`mcpApp.resourceContent`,i=qr(t,`${e.title} · ${w(r)}`),a=Gr(t);return D`<div class="mcp-app-context__item">
                ${a?D`<img src=${a} alt=${i} referrerpolicy="no-referrer" loading="lazy" />`:E.fileText}<span
                  class="mcp-app-context__label"
                  title=${i}
                  >${i}</span
                ><button
                  type="button"
                  ?disabled=${this.pending.has(e.viewId)}
                  aria-label=${w(`mcpApp.removeContext`,{title:i})}
                  @click=${()=>void this.removeItem(e,n)}
                >
                  ${E.x}
                </button>
              </div>`})}${e.state?.structuredContent?D`<div class="mcp-app-context__item"><span>${e.title}</span><button type="button" ?disabled=${this.pending.has(e.viewId)} aria-label=${w(`mcpApp.removeContext`,{title:e.title})} @click=${()=>void this.removeItem(e)}>${E.x}</button></div>`:O}
          </div>`)}
      ${this.error?D`<p role="alert">${this.error}</p>`:O}
    </section>`:O}},F([Cn({context:ze,subscribe:!0})],Z.prototype,`context`,void 0),F([j({attribute:!1})],Z.prototype,`sessionKey`,void 0),F([j({attribute:!1})],Z.prototype,`agentId`,void 0),F([A()],Z.prototype,`error`,void 0),F([A()],Z.prototype,`pending`,void 0),customElements.get(`openclaw-mcp-app-context-strip`)||customElements.define(`openclaw-mcp-app-context-strip`,Z)})))()}function cl(e,t){let n=e??ll;switch(t.type){case`mount`:return{...ll,open:t.manualOpen===void 0?t.open:!!t.manualOpen,manualOpen:t.manualOpen,readingHistory:t.readingHistory};case`history`:return{...n,readingHistory:t.readingHistory,gestures:t.readingHistory?n.gestures:0,distancePx:t.readingHistory?n.distancePx:0};case`gesture`:return{...n,gestures:n.gestures+1,distancePx:n.distancePx+t.distancePx};case`settle`:{if(!n.readingHistory)return{...n,gestures:0,distancePx:0};let e=n.manualReopens>0;return!n.open||n.manualOpen===!1||n.manualReopens>=Q.pinnedAfterReopens||n.gestures<(e?Q.reopenedGestures:Q.gestures)||n.distancePx<(e?Q.reopenedDistancePx:Q.distancePx)?n:{...n,open:!1,manualOpen:void 0,gestures:0,distancePx:0}}case`takeover`:return{...n,gestures:0,distancePx:0};case`extent`:case`click`:{let e=t.type===`click`?t.open:t.extent>0,r=t.type===`click`?t.open:t.extent!==0&&t.extent;return{...n,open:e,manualOpen:r,manualReopens:n.manualReopens+Number(!n.open&&e),gestures:0,distancePx:0}}case`clamp`:return typeof n.manualOpen==`number`&&n.manualOpen>t.limit?{...n,manualOpen:t.limit,open:t.limit>0}:n}return t}var Q,ll;function ul(){return(ul=e((()=>{Q={gestures:2,distancePx:320,reopenedGestures:3,reopenedDistancePx:640,pinnedAfterReopens:2,gesturePauseMs:200,touchGesturePx:24,scrollSettleMs:300},ll={open:!1,manualOpen:void 0,manualReopens:0,readingHistory:!1,gestures:0,distancePx:0}})))()}var dl,fl,pl,ml;function hl(){return(hl=e((()=>{k(),Xe(),We(),ge(),Br(),ul(),dl=new WeakMap,fl=class{constructor(e,t){this.element=e,this.transcript=null,this.disposed=!1,this.scrollSettled=!1,this.suppressClick=!1,this.touching=!1,this.scrolling=!1,this.scheduleCollapse=()=>{clearTimeout(this.settleTimer),this.scrollSettled=!1,this.settleTimer=setTimeout(()=>{this.settleTimer=void 0,this.scrollSettled=!0,this.settleDisclosure()},Q.scrollSettleMs)},this.handleTranscriptScroll=e=>{if(e.type!==`input`&&e.type!==`offset`)return;if(this.touching=e.touching,e.type===`offset`){this.scrolling=e.scrolling,e.programmatic&&this.gesture?.distancePx===0&&(this.gesture=void 0),!e.programmatic&&e.delta!==0&&(this.gesture&&(this.gesture.distancePx+=Math.max(0,-e.delta)),this.scheduleCollapse()),!this.scrolling&&this.scrollSettled&&this.settleDisclosure();return}let{event:t}=e;if(t instanceof WheelEvent){if(t.ctrlKey)return;let e=performance.now();(this.gesture?.kind!==`wheel`||this.lastWheelAt===void 0||e-this.lastWheelAt>Q.gesturePauseMs)&&(this.flushGesture(),this.scrollSettled=!1,this.gesture={kind:`wheel`,valid:!0,distancePx:0}),this.lastWheelAt=e,this.scheduleCollapse()}else typeof TouchEvent<`u`&&t instanceof TouchEvent?(t.type===`touchstart`&&t.touches.length===1&&(this.flushGesture(),this.scrollSettled=!1,this.gesture={kind:`touch`,valid:!0,distancePx:0}),this.gesture?.kind===`touch`&&(t.touches.length>1||t.type===`touchcancel`||t.type===`touchend`&&t.touches.length>0)&&(this.gesture.valid=!1),!this.touching&&this.scrollSettled&&this.settleDisclosure()):this.flushGesture()},this.clampExtent=()=>{typeof this.state.manualOpen==`number`&&this.state.manualOpen>this.limit()&&(this.dispatch({type:`clamp`,limit:this.limit()}),this.cancelDrag()),this.apply()},this.click=e=>{if(e.defaultPrevented||this.isControl(e)||!(e.target instanceof Element)||e.target.closest(`summary`)?.parentElement!==this.element)return;if(e.preventDefault(),this.suppressClick&&e.detail!==0){this.suppressClick=!1;return}this.cancelDrag();let t=this.chosen(),n=typeof t==`boolean`&&this.element.open||typeof t==`number`&&t>0&&(t>=this.limit()||!!(this.body&&this.body.clientHeight>0&&this.body.scrollHeight<=this.body.clientHeight+1));this.resetScrollInput(),this.dispatch({type:`click`,open:!n}),this.apply()},this.wheel=e=>{if(e.defaultPrevented||this.isControl(e)||this.drag||e.ctrlKey||e.metaKey||e.shiftKey||!Number.isFinite(e.deltaY)||!Number.isFinite(e.deltaX)||!e.deltaY||Math.abs(e.deltaX)>=Math.abs(e.deltaY))return;let t=e.deltaMode===WheelEvent.DOM_DELTA_LINE?Number.parseFloat(getComputedStyle(this.summary).lineHeight)||18:e.deltaMode===WheelEvent.DOM_DELTA_PAGE?this.limit():1,n=this.extent(),r=Math.max(0,Math.min(this.limit(),n-e.deltaY*t));e.preventDefault(),this.move(r)},this.pointerDown=e=>{!e.isPrimary||e.button!==0||this.isControl(e)||e.defaultPrevented||(this.suppressClick=!1,this.drag={id:e.pointerId,x:e.clientX,y:e.clientY,extent:this.extent(),active:!1},this.summary?.setPointerCapture(e.pointerId))},this.pointerMove=e=>{let t=this.drag;if(!t||t.id!==e.pointerId)return;let n=e.clientX-t.x,r=e.clientY-t.y;if(!t.active){if(Math.max(Math.abs(n),Math.abs(r))<3)return;if(Math.abs(n)>=Math.abs(r)){this.cancelDrag();return}this.takeover(),t.active=!0,this.suppressClick=!0}e.preventDefault();let i=t.extent-r;this.move(i),(i<0||i>this.limit())&&(t.extent=this.extent(),t.y=e.clientY)},this.otherPointer=e=>{this.drag&&e.pointerId!==this.drag.id&&this.cancelDrag()},this.pointerEnd=e=>{e.pointerId===this.drag?.id&&this.cancelDrag()},this.cancelDrag=()=>{let e=this.drag;this.drag=void 0,e&&this.summary?.hasPointerCapture(e.id)&&this.summary.releasePointerCapture(e.id)},this.sessionKey=t[0],this.gatewayScope=t[2]?.gatewayScope,this.cardLifetime=t[2]?.cardLifetime,this.state=this.mount(t),this.element.addEventListener(`click`,this.click)}mount([,e,t]){return this.resetScrollInput(),this.cancelDrag(),this.rememberedChoice=this.cardLifetime?dl.get(this.cardLifetime):void 0,cl(void 0,{type:`mount`,open:e&&!Re(),manualOpen:this.rememberedChoice?.choice,readingHistory:t?.readingHistory===!0})}update(e){let[t,,n]=e;this.lifecycle=n,(t!==this.sessionKey||n?.gatewayScope!==this.gatewayScope||n?.cardLifetime!==this.cardLifetime)&&(this.sessionKey=t,this.gatewayScope=n?.gatewayScope,this.cardLifetime=n?.cardLifetime,this.state=this.mount(e));let r=n?.readingHistory===!0;r!==this.state.readingHistory&&(r||this.resetScrollInput(),this.dispatch({type:`history`,readingHistory:r})),n?.presented===!1&&(this.takeover(),this.disconnectHeader()),this.connectHeader(),this.apply(),queueMicrotask(()=>{this.disposed||(this.connectHeader(),this.connectTranscript(),this.apply())})}dispatch(e){let t=this.state;if(this.state=cl(t,e),!this.cardLifetime)return;let n=e.type===`click`||e.type===`extent`||e.type===`clamp`,r=e.type===`settle`&&t.open&&!this.state.open;(n||r&&dl.get(this.cardLifetime)===this.rememberedChoice)&&(this.rememberedChoice={choice:this.state.manualOpen??this.state.open},dl.set(this.cardLifetime,this.rememberedChoice))}resetScrollInput(){clearTimeout(this.settleTimer),this.settleTimer=void 0,this.scrollSettled=!1,this.lastWheelAt=void 0,this.gesture=void 0,this.touching=!1,this.scrolling=!1}flushGesture(){let e=this.gesture;this.gesture=void 0,e?.valid&&e.distancePx>0&&(e.kind===`wheel`||e.distancePx>Q.touchGesturePx)&&this.dispatch({type:`gesture`,distancePx:e.distancePx})}settleDisclosure(){this.touching||this.scrolling||((!this.gesture?.valid||this.gesture.distancePx>0)&&this.flushGesture(),this.state.distancePx>0&&(this.dispatch({type:`settle`}),this.apply()))}connectTranscript(){if(this.disposed)return;let e=this.lifecycle?.presented===!1?null:this.element.closest(`.chat-main`)?.querySelector(`.chat-thread`)??null;e!==this.transcript&&(this.resetScrollInput(),this.unsubscribeTranscript?.(),this.transcript=e,this.unsubscribeTranscript=e?Hr(e,this.handleTranscriptScroll):void 0)}connectHeader(){if(this.disposed||this.lifecycle?.presented===!1||(this.summary??=this.element.querySelector(`summary`)??void 0,this.body??=this.element.querySelector(`.session-progress-card__body`)??void 0,!this.summary||this.listeners))return;this.listeners=new AbortController;let e=this.listeners.signal;this.summary.addEventListener(`wheel`,this.wheel,{passive:!1,signal:e}),this.summary.addEventListener(`pointerdown`,this.pointerDown,{signal:e}),this.summary.addEventListener(`pointermove`,this.pointerMove,{signal:e}),this.summary.addEventListener(`pointerup`,this.pointerEnd,{signal:e}),this.summary.addEventListener(`pointercancel`,this.pointerEnd,{signal:e}),this.summary.addEventListener(`lostpointercapture`,this.pointerEnd,{signal:e}),this.summary.ownerDocument.addEventListener(`pointerdown`,this.otherPointer,{capture:!0,signal:e}),this.summary.ownerDocument.defaultView?.addEventListener(`blur`,this.cancelDrag,{signal:e}),this.summary.ownerDocument.defaultView?.addEventListener(`resize`,this.clampExtent,{signal:e}),typeof ResizeObserver<`u`&&this.body&&(this.resizeObserver=new ResizeObserver(this.clampExtent),this.resizeObserver.observe(this.body))}disconnectHeader(){this.cancelDrag(),this.listeners?.abort(),this.listeners=void 0,this.resizeObserver?.disconnect(),this.resizeObserver=void 0}chosen(){return this.state.manualOpen??this.state.open}limit(){return this.body&&Number.parseFloat(getComputedStyle(this.body).maxHeight)||300}extent(){let e=this.chosen();return typeof e==`number`?Math.min(e,this.limit()):e?this.body?.getBoundingClientRect().height??0:0}apply(){this.body??=this.element.querySelector(`.session-progress-card__body`)??void 0;let e=this.chosen(),t=typeof e==`number`,n=t?Math.min(e,this.limit()):0;this.element.open=t?n>0:e,this.body&&(this.body.style.height=t?n+`px`:``,this.body.style.minHeight=t?n+`px`:``),this.element.dataset.reveal=t?`partial`:e?`open`:`closed`}isControl(e){return e.target instanceof Element&&!!e.target.closest(`button, a, input, select, textarea`)}move(e){this.takeover(),this.dispatch({type:`extent`,extent:Math.max(0,Math.min(this.limit(),e))}),this.lifecycle?.onManipulate?.(),this.apply()}takeover(){this.resetScrollInput(),this.dispatch({type:`takeover`})}dispose(){this.disposed=!0,this.unsubscribeTranscript?.(),this.unsubscribeTranscript=void 0,this.element.removeEventListener(`click`,this.click),this.disconnectHeader(),this.resetScrollInput()}},pl=class extends Ge{render(...e){return O}update(e,t){return e.element instanceof HTMLDetailsElement&&(this.element=e.element,this.input=t,this.isConnected&&this.reconnected()),O}disconnected(){this.controller?.dispose(),this.controller=void 0}reconnected(){this.element&&this.input&&(this.controller??=new fl(this.element,this.input),this.controller.update(this.input))}},ml=Ke(pl)})))()}function gl(e,t){if(!t)return O;let n=t.state===`pending`,r=t.state===`failed`||t.state===`timeout`,i=w(n?`sessionProgressCard.refresh.pending`:r?`sessionProgressCard.refresh.retry`:`sessionProgressCard.refresh.label`);return D`<button
    class="session-progress-card__refresh"
    type="button"
    data-state=${t.state??`idle`}
    aria-label=${i}
    title=${r&&t.state?w(kl[t.state]):i}
    aria-busy=${String(n)}
    ?disabled=${n}
    @click=${r=>{r.preventDefault(),r.stopPropagation(),n||t.onRefresh(e)}}
  >
    ${n?E.loader:t.state===`updated`?E.check:E.refresh}
  </button>`}function _l(e){if(e.length>jl)return vr(e,{progressBars:!0});let t=`${re.getLocale()}\0${e}`,n=Ml.get(t);if(n!==void 0)return Ml.delete(t),Ml.set(t,n),n;let r=vr(e,{progressBars:!0});return Ml.set(t,r),hn(Ml,Al),r}function vl(e){let t=e.steps;return t?.length?{completed:t.filter(e=>e.status===`completed`).length,total:t.length}:null}function yl(e){return e.find(e=>e.status===`in_progress`)??e.find(e=>e.status===`pending`)}function bl(e,t){let n=Hn(t),r=Hn(e.updatedAt);return n!==void 0&&r!==void 0&&r<n}function xl(e,t,n,r=!0){let i=e?bl(e,n):!1;if(t&&$[t]&&!i)return null;let a=e?vl(e):null;if(!a||!e?.steps)return null;let o=yl(e.steps);if(!o)return null;let s=o.status===`in_progress`&&(i||!r)?`paused`:o.status;return{...a,status:s,step:o.step}}function Sl(e){return yl(e)??e.findLast(e=>e.status===`completed`)}function Cl(e,t){let n=t&&$[t];if(e===`in_progress`&&n)return n===`completed`?E.check:E.circleX;switch(e){case`completed`:return E.check;case`in_progress`:return D`<span class="session-run-spinner"></span>`;case`paused`:case`pending`:return E.clock}return e}function wl(e){let t=document.createElement(`template`);t.innerHTML=e;let n=t.content.querySelector(`progress`);if(!n)return e;let r=n.getAttribute(`value`)?.trim(),i=n.getAttribute(`max`)?.trim(),a=n.getAttribute(`aria-label`)?.trim()||(r&&i?`${w(`sessionProgressCard.title`)} · ${r}/${i}`:w(`sessionProgressCard.title`));n.setAttribute(`aria-label`,a);let o=n.parentElement,s=document.createElement(`div`);s.className=`session-progress-card__progress`;let c=document.createElement(`span`);return c.className=`session-progress-card__progress-label`,c.textContent=a,s.append(c,n),o?.tagName===`P`&&o.children.length===0&&!o.textContent?.trim()&&o.remove(),t.content.prepend(s),t.innerHTML}function Tl(e,t={}){if(!e)return O;let n=_l(e);return D`<div class="session-progress-card__markdown sidebar-markdown">
    ${et(t.promoteProgress?wl(n):n)}
  </div>`}function El(e,t,n){let r=e.steps;return r?.length?D`<ol class="session-progress-card__steps">
    ${r.map(e=>{let r=e.status===`in_progress`&&n?$[n]:void 0,i=e.status===`in_progress`&&!t&&!r?`paused`:e.status,a=w(r?`sessionProgressCard.status.${r}`:i===`paused`?`sessionProgressCard.status.paused`:Nl[i]);return D`<li
        class="session-progress-card__step session-progress-card__step--${i}"
        aria-label=${w(`sessionProgressCard.stepLabel`,{status:a,step:e.step})}
      >
        <span
          class="session-progress-card__step-marker"
          data-status=${i}
          data-outcome=${r?n:O}
          aria-hidden="true"
          >${Cl(i,n)}</span
        >
        <span class="session-progress-card__step-text">${e.step}</span>
      </li>`})}
  </ol>`:O}function Dl(e,t,n){if(!n)return O;let r=w(t===`dismiss`?`sessionProgressCard.dismiss`:`sessionProgressCard.clearSaved`);return D`<button
    class="rail-header__action session-progress-card__${t}"
    type="button"
    aria-label=${r}
    title=${r}
    @click=${t=>{t.preventDefault(),t.stopPropagation(),n(e)}}
  >
    ${t===`dismiss`?E.x:E.trash}
  </button>`}function Ol(e,t,n,r,i,a,o=!0,s=!1,c,l,u){if(!e)return O;let d=vl(e),f=d?w(`sessionProgressCard.countLabel`,{completed:String(d.completed),total:String(d.total)}):w(`sessionProgressCard.noteLabel`),p=Hn(i),m=Hn(a),h=Hn(e.updatedAt),g=p!==void 0&&m!==void 0&&m>=p&&h!==void 0&&h>=p&&h<=m,_=o&&!bl(e,i)&&(h===void 0||r!==`queued`&&(p!==void 0||r===void 0)),v=r&&$[r]&&g?m:void 0,y=r&&$[r]&&!v?void 0:r,b=v??h??Date.now(),x=v?`sessionProgressCard.activity.${$[r]}`:`sessionProgressCard.activity.updated`,ee=Fl(b,x),S=Dl(e,`dismiss`,n),C=Dl(e,`clear-saved`,u);if(t===`composer`){let t=e.steps??[],n=Sl(t),r=Math.max(1,n?t.indexOf(n)+1:0),i=t.length>0&&t.every(e=>e.status===`completed`),a=n?.step??w(`sessionProgressCard.noteLabel`),o=y?$[y]:void 0,u=o?w(`sessionProgressCard.outcome.${o}`):null,p=`${a}. ${u??f}`,m=d?w(`sessionProgressCard.shortCount`,{completed:String(r),total:String(d.total)}):O,h=n?.status===`in_progress`&&!_&&!o?`paused`:n?.status,g=o?o===`completed`?E.check:E.circleX:i?E.check:n?.status===`in_progress`?Cl(h??`pending`):E.clock;return D`<details
      class="session-progress-card session-progress-card--composer"
      data-progress-card-placement="composer"
      data-complete=${String(i)}
      ${ml(c?.sessionIdentity??e.sessionKey,!s,c)}
    >
      <summary class="session-progress-card__summary" aria-label=${p}>
        <span
          class="session-progress-card__summary-indicator session-progress-card__current-marker${i||y===`done`?` session-progress-card__summary-indicator--complete`:``}"
          data-status=${h??`pending`}
          data-outcome=${y??O}
          aria-hidden="true"
        >
          ${g}
        </span>
        <span class="session-progress-card__summary-collapsed">
          <span class="session-progress-card__current">${a}</span>
        </span>
        ${d?D`<span
                class="session-progress-card__summary-count session-progress-card__summary-count--collapsed"
                data-outcome=${y??O}
                >${u??`${r}/${d.total}`}</span
              >`:O}
        <span class="session-progress-card__summary-expanded">
          <span class="session-progress-card__summary-title"
            >${w(`sessionProgressCard.composerTitle`)}</span
          >
          <span class="session-progress-card__heading-actions"
            ><span>${ee}${d?D` · ${m}`:O}</span></span
          >
        </span>
        <span class="session-progress-card__summary-controls">
          ${gl(e,l)} ${C} ${S}
          <span
            class="session-progress-card__summary-chevron session-progress-card__chevron"
            aria-hidden="true"
            >${E.chevronDown}</span
          >
        </span>
        ${l?.state?D`<span
                class="session-progress-card__refresh-status"
                data-state=${l.state}
                role="status"
                >${w(kl[l.state])}</span
              >`:O}
      </summary>
      <div
        class="session-progress-card__body"
        role="region"
        aria-label=${f}
        ${wr()}
      >
        ${Tl(e.markdown)}
        ${El(e,_,y)}
      </div>
    </details>`}return D`<section
    class="session-progress-card session-progress-card--${t}"
    data-progress-card-placement=${t}
    aria-label=${f}
  >
    <div class="session-progress-card__heading">
      <span>${w(`sessionProgressCard.title`)}</span>
      <span class="session-progress-card__heading-actions">
        <span
          >${ee}${d?D` · ${d.completed}/${d.total}`:O}</span
        >${S}
      </span>
    </div>
    <div class="session-progress-card__body">
      ${Tl(e.markdown)}
      ${El(e,_,y)}
    </div>
  </section>`}var kl,Al,jl,Ml,Nl,$,Pl,Fl;function Il(){return(Il=e((()=>{gn(),k(),Xe(),We(),tt(),a(),b(),Pe(),Or(),br(),hl(),kl={pending:`sessionProgressCard.refresh.pending`,failed:`sessionProgressCard.refresh.failed`,timeout:`sessionProgressCard.refresh.timeout`,updated:`sessionProgressCard.refresh.updated`},Al=16,jl=14e4,Ml=new Map,Nl={completed:`sessionProgressCard.status.completed`,in_progress:`sessionProgressCard.status.inProgress`,pending:`sessionProgressCard.status.pending`},$={done:`completed`,failed:`failed`,killed:`stopped`,timeout:`failed`},Pl=class extends Ge{constructor(...e){super(...e),this.timestamp=0,this.labelKey=`sessionProgressCard.activity.updated`}render(e,t){return this.timestamp=e,this.labelKey=t,this.isConnected&&this.startTimer(),this.renderTime()}disconnected(){this.stopTimer()}reconnected(){this.setValue(this.renderTime()),this.startTimer()}startTimer(){this.timer||=setInterval(()=>this.setValue(this.renderTime()),3e4)}stopTimer(){this.timer&&=(clearInterval(this.timer),void 0)}renderTime(){let e=w(this.labelKey,{time:le(this.timestamp)});return D`<time
      datetime=${new Date(this.timestamp).toISOString()}
      aria-label=${e}
      title=${e}
      >${e}</time
    >`}},Fl=Ke(Pl)})))()}function Ll(e){let{widget:t}=e,n=t.declared?.netOrigins??[],r=t.declared?.tools??[];return D`
    <div class="board-widget__grant board-widget__grant--pending" data-test-id="board-pending">
      <div class="board-widget__grant-mark" aria-hidden="true">!</div>
      <strong>${w(`board.widget.needsApproval`)}</strong>
      ${n.length>0||r.length>0?D`<div class="board-widget__grant-groups">
              ${[[`board.widget.networkAccess`,n],[`board.widget.hostTools`,r]].map(([e,t])=>t.length>0?D`<section>
                      <strong>${w(e)}</strong>
                      <ul class="board-widget__grant-summary">
                        ${t.map(e=>D`<li>${e}</li>`)}
                      </ul>
                    </section>`:O)}
            </div>`:t.declaredSummary?.length?D`<ul class="board-widget__grant-summary">
                ${t.declaredSummary.map(e=>D`<li>${e}</li>`)}
              </ul>`:D`<span>${w(`board.widget.needsApprovalDetail`)}</span>`}
      <div class="board-widget__grant-actions">
        <button
          class="btn btn--small btn--primary"
          type="button"
          data-test-id="board-grant-allow"
          ?disabled=${e.disabled}
          @click=${()=>e.onGrant(`granted`)}
        >
          ${w(`board.widget.allow`)}
        </button>
        <button
          class="btn btn--small"
          type="button"
          data-test-id="board-grant-reject"
          ?disabled=${e.disabled}
          @click=${()=>e.onGrant(`rejected`)}
        >
          ${w(`board.widget.reject`)}
        </button>
      </div>
      ${e.error??O}
    </div>
  `}function Rl(e,t=`tooltip`){if(e.grantState!==`granted`||!e.declared)return O;let n=[...(e.declared.netOrigins??[]).map(e=>w(`board.widget.networkCapability`,{capability:e})),...(e.declared.tools??[]).map(e=>w(`board.widget.toolCapability`,{capability:e}))];return n.length===0?O:t===`details`?D`<div
      class="board-widget__menu-capabilities"
      role="note"
      aria-label=${w(`board.widget.activeCapabilities`)}
    >
      <strong>${w(`board.widget.activeCapabilities`)}</strong>
      <ul>
        ${n.map(e=>D`<li>${e}</li>`)}
      </ul>
    </div>`:D`
    <openclaw-tooltip
      .content=${`${w(`board.widget.activeCapabilities`)}\n${n.join(`
`)}`}
    >
      <span class="board-widget__capabilities" data-test-id="board-capabilities-granted">
        ${w(`board.widget.granted`)}
      </span>
    </openclaw-tooltip>
  `}function zl(){return(zl=e((()=>{k(),a()})))()}function Bl(e){let t=e.querySelector(`.board-widget__menu`);t&&(t.open=!1)}function Vl(e){let{onSelect:t}=e;return D`
    <wa-dropdown class="board-widget__menu" placement="bottom-end" @wa-select=${t}>
      <button
        class="board-widget__menu-trigger"
        slot="trigger"
        type="button"
        aria-label=${w(`board.widget.menuLabel`)}
        title=${w(`board.widget.menuLabel`)}
      >
        ⋮
      </button>
      ${Hl(e)}
    </wa-dropdown>
  `}function Hl(e){let{widget:t,tabs:n,disabled:r,prefix:i=``}=e,a=n.filter(e=>e.tabId!==t.tabId);return D`
    <div class="board-widget__menu-heading">${w(`board.widget.moveToTab`)}</div>
    ${a.length>0?a.map(e=>D`
              <wa-dropdown-item value=${`${i}move:${e.tabId}`} ?disabled=${r}>
                ${e.title}
              </wa-dropdown-item>
            `):D`<span class="board-widget__menu-empty">${w(`board.widget.noOtherTabs`)}</span>`}
    <div class="board-widget__menu-heading">${w(`board.widget.resize`)}</div>
    ${Object.entries(ql).map(([e,t])=>D`
        <wa-dropdown-item
          class="board-widget__preset"
          value=${`${i}resize:${e}`}
          ?disabled=${r}
        >
          ${e.toUpperCase()}
          <span slot="details">${t.w}×${t.h}</span>
        </wa-dropdown-item>
      `)}
    ${t.contentKind===`html`?D`<wa-dropdown-item
            class="board-widget__preset"
            type="checkbox"
            value=${`${i}height:auto`}
            ?checked=${t.heightMode!==`fixed`}
            ?disabled=${r}
          >
            ${w(`board.widget.autoHeight`)}
          </wa-dropdown-item>`:O}
    <div class="board-widget__menu-separator" role="separator"></div>
    <wa-dropdown-item
      class="board-widget__menu-danger"
      value=${`${i}remove`}
      ?disabled=${r}
    >
      <span slot="icon" class="board-widget__menu-icon" aria-hidden="true">${E.trash}</span>
      ${w(`board.widget.remove`)}
    </wa-dropdown-item>
  `}function Ul(e){return D`
    <div class="board-widget__grant board-widget__grant--rejected" data-test-id="board-rejected">
      <strong>${w(`board.widget.rejected`)}</strong>
      <span>${w(`board.widget.rejectedDetail`)}</span>
      <button
        class="btn btn--small"
        type="button"
        ?disabled=${e.disabled}
        @click=${e.onRemove}
      >
        ${w(`board.widget.remove`)}
      </button>
    </div>
  `}function Wl(e){return D`
    <div class="board-widget__disabled-plugin" data-test-id="board-disabled-plugin">
      ${e.content??D`<strong>${w(`board.widget.disabledPlugin`,{pluginId:e.pluginId})}</strong>`}
      <button
        class="btn btn--small"
        type="button"
        ?disabled=${e.disabled}
        @click=${e.onRemove}
      >
        ${w(`board.widget.remove`)}
      </button>
    </div>
  `}function Gl(e,t){let n=S(e);return D`
    <div class="board-widget__error" role="alert" data-test-id="board-widget-error">
      <strong>${w(`board.widget.errorTitle`)}</strong>
      <span>${w(`board.widget.errorDetail`)}</span>
      <details>
        <summary>${w(`board.widget.errorShow`)}</summary>
        <code>${n}</code>
      </details>
      ${t?D`<button class="btn btn--small" type="button" @click=${t}>
              ${w(`board.widget.retry`)}
            </button>`:O}
    </div>
  `}function Kl(e,t=!1){return D`
    <div
      class=${`board-widget__error ${t?`board-widget__error--inline`:``}`}
      role="alert"
      data-test-id="board-widget-action-error"
    >
      <strong>${w(`board.widget.actionErrorTitle`)}</strong>
      <span>${w(`board.widget.actionErrorDetail`)}</span>
      <details>
        <summary>${w(`board.widget.errorShow`)}</summary>
        <code>${e}</code>
      </details>
    </div>
  `}var ql;function Jl(){return(Jl=e((()=>{k(),a(),ae(),Pe(),ql={sm:{w:3,h:3},md:{w:6,h:4},lg:{w:8,h:6},xl:{w:12,h:8}}})))()}function Yl(e,t){let n=ye(e,t);return n?.reader.linkReader.previewMethod?n:null}function Xl(e,t=Be.providerFor(e),n=Yl){let r=t?.client&&t.readers?n(e.href,t.readers):null;return r&&ke(e)?r:null}async function Zl(e,t){let n=Xl(e),r=Be.providerFor(e);if(!n||!r?.client?.connected||t.aborted)return;let{client:i,agentId:a,readers:o}=r;await Be.define();let s=Be.providerFor(e);await s?.updateComplete,!(t.aborted||!e.isConnected||e.href!==n.href||document.hidden||s!==r||s.client!==i||s.agentId!==a||s.readers!==o)&&await s.prefetch(n,t)}function Ql(){return(Ql=e((()=>{_e(),be()})))()}var $l,eu,tu,nu,ru;function iu(){return(iu=e((()=>{k(),We(),oe(),_e(),Ql(),be(),$l=8,eu=150,tu=500,nu=class extends ie{constructor(...e){super(...e),this.provider=null,this.handleCapabilities=()=>{this.release(),this.attempted.clear(),this.scheduleScan()},this.active=!1,this.observer=null,this.mutations=null,this.scope=new AbortController,this.observed=new Map,this.attempted=new Set,this.claims=new Map,this.resolveClaim=(e,t)=>{t!==this.claimReaders&&(this.claims.clear(),this.claimReaders=t);let n=this.claims.get(e);return n===void 0&&(n=Yl(e,t),this.claims.set(e,n)),n},this.handleVisibilityChange=()=>{this.active&&!document.hidden?this.mutations||this.scheduleScan():this.release()}}presentationChanged(e){e?.isPresented()===!1&&(this.active=!1,this.release())}render(e,t,n=!0){return O}update(e,[t,n,r=!0]){this.updatePresentation(n),(t!==this.sessionKey||!r)&&(this.release(),this.attempted.clear(),this.sessionKey=t),this.root=e.element instanceof HTMLElement?e.element:void 0;let i=this.root?.closest(`openclaw-link-reader-hovercard-provider`)??null;return i!==this.provider&&(this.provider?.removeEventListener(`link-reader-capabilities-changed`,this.handleCapabilities),this.provider=i,this.provider?.addEventListener(`link-reader-capabilities-changed`,this.handleCapabilities),this.release(),this.attempted.clear()),this.active=r&&(typeof n==`boolean`?n:n.isPresented()),document.addEventListener(`visibilitychange`,this.handleVisibilityChange),this.handleVisibilityChange(),O}disconnected(){super.disconnected(),this.provider?.removeEventListener(`link-reader-capabilities-changed`,this.handleCapabilities),document.removeEventListener(`visibilitychange`,this.handleVisibilityChange),this.release()}reconnected(){super.reconnected(),this.provider?.addEventListener(`link-reader-capabilities-changed`,this.handleCapabilities),document.addEventListener(`visibilitychange`,this.handleVisibilityChange),this.handleVisibilityChange()}release(){this.cancelScan?.(),this.cancelScan=void 0,this.observer?.disconnect(),this.observer=null,this.mutations?.disconnect(),this.mutations=null,this.observed.clear(),this.claims.clear(),this.claimReaders=void 0,clearTimeout(this.timer),this.timer=void 0,this.scope.abort(),this.scope=new AbortController,this.pendingKey&&this.attempted.delete(this.pendingKey),this.pendingKey=void 0}canPrefetch(){return this.active&&this.isConnected&&!!this.root?.isConnected&&!document.hidden}scheduleScan(){if(this.cancelScan||this.attempted.size>=$l)return;let e=()=>{this.cancelScan=void 0,this.canPrefetch()&&this.attempted.size<$l&&this.scan()};if(typeof requestIdleCallback==`function`){let t=requestIdleCallback(e,{timeout:tu});this.cancelScan=()=>cancelIdleCallback(t)}else{let t=setTimeout(e,tu);this.cancelScan=()=>clearTimeout(t)}}scan(){let e=this.root;if(e&&typeof IntersectionObserver<`u`){if(!this.observer){let t=new IntersectionObserver(e=>{if(this.observer===t&&this.canPrefetch()){for(let t of e){if(!(t.target instanceof HTMLAnchorElement))continue;let e=this.observed.get(t.target);e&&(e.visible=t.isIntersecting)}this.schedulePrefetch()}});this.observer=t,this.mutations=new MutationObserver(()=>this.scheduleScan()),this.mutations.observe(e,{childList:!0,subtree:!0,attributes:!0,attributeFilter:[`href`]})}for(let[t,{key:n}]of this.observed){let r=Xl(t,Be.providerFor(t),this.resolveClaim);(!e.contains(t)||!r||he(r)!==n)&&(this.observer.unobserve(t),this.observed.delete(t))}for(let t of e.querySelectorAll(`a[href]`)){if(this.observed.has(t))continue;let e=Xl(t,Be.providerFor(t),this.resolveClaim);if(!e)continue;let n=he(e);this.attempted.has(n)||(this.observed.set(t,{key:n,visible:!1}),this.observer.observe(t))}}}schedulePrefetch(){this.timer!==void 0||this.pendingKey!==void 0||!this.canPrefetch()||this.attempted.size>=$l||(this.timer=setTimeout(()=>{this.timer=void 0,this.prefetchNext()},eu))}async prefetchNext(){if(this.canPrefetch())for(let[e,{key:t,visible:n}]of this.observed){if(!n||!this.root?.contains(e)||this.attempted.has(t))continue;this.attempted.add(t);let r=this.scope;this.pendingKey=t;try{await Zl(e,r.signal)}catch{}finally{r===this.scope&&(this.pendingKey=void 0,this.attempted.size>=$l?this.release():this.schedulePrefetch())}return}}},ru=Ke(nu)})))()}function au(e){return e===`web_search`||e===`web_fetch`?e:void 0}function ou(e){if(typeof e!=`string`||e.length>2048||!dt(e))return null;let t=new URL(e);return t.username||t.password?null:t}function su(e){let t=new URL(e);return t.hash=``,t.href}function cu(e){return e.map(e=>e.type===`text`||e.type===`code_inline`?e.content:e.type===`softbreak`||e.type===`hardbreak`?` `:``).join(``).replace(/\s+/gu,` `).trim()}function lu(e){return xu.parse(_r(e),{})}function uu(e,t){if(typeof e!=`string`||e.length>yu)return;let n=t===`web_search`?`Web Search`:`Web Fetch`,r=/(?:^|\n)<<<EXTERNAL_UNTRUSTED_CONTENT id="([a-f0-9]{16})">>>\r?\nSource: ([^\r\n]+)\r?\n---\r?\n([\s\S]*?)\r?\n<<<END_EXTERNAL_UNTRUSTED_CONTENT id="\1">>>/u.exec(e);return r?.[2]===n&&L(r[3]?.trim()??``,vu)||void 0}function du(e,t){let n=uu(e,t);if(!n)return;let r=lu(n).filter(e=>e.type===`inline`).map(e=>cu(e.children??[])).join(` `).trim();return r?L(r,180):void 0}function fu(e,t){let n=uu(e,t);if(!n)return;let r=lu(n),i=r.flatMap((e,n)=>e.type===`inline`&&r[n-1]?.type===`paragraph_open`&&(t===`web_search`||r[n-1]?.level===0)?[cu(e.children??[])]:[]).find(e=>e.length>=(t===`web_fetch`?60:1));if(i)return i.length>bu?`${L(i,279).trimEnd()}…`:i}function pu(e){return e.details===void 0?!e.outputText||e.outputText.length>1e5?null:_n(e.outputText)??null:P(e.details)}function mu(e,t,n){let r=pu(e),i=P(r?.externalContent);if(!r||i?.source!==t||i.untrusted!==!0||i.wrapped!==!0)return[];let a=(e,r,i,a=[su(e)])=>a.some(e=>n.has(e))?[{candidate:{url:e,name:t,title:r.title,excerpt:i?r[i]:void 0},keys:a}]:[];if(t===`web_search`){let e=r.kind===`results`?r.results:r.kind===`answer`?r.citations:void 0;return Array.isArray(e)?e.slice(0,20).flatMap(e=>{let t=P(e),n=ou(t?.url);return t&&n?a(n,t,r.kind===`results`?`snippet`:void 0):[]}):[]}if(typeof r.status!=`number`||r.status<200||r.status>=300)return[];let o=ou(r.url),s=ou(r.finalUrl);return o&&s?a(s,r,`text`,[...new Set([su(o),su(s)])]):[]}function hu(e){let t=e.source,n=e.page&&fu(e.page.excerpt,`web_fetch`),r=n||e.search&&fu(e.search.excerpt,`web_search`);return{url:t.url.href,title:du(t.title,t.name)??t.url.hostname,domain:t.url.hostname,...r?{excerpt:r,excerptKind:n?`page`:`search`}:{}}}function gu(e){let t=P(e.answer);if(!t||Rr(t)!==e.runId)return[];let n=$t(e.answer);if(!n||n.length>vu)return[];let r=Su.get(t),i=r?.text===n?r.links:lu(n).flatMap(e=>(e.children??[]).flatMap(e=>{let t=e.type===`link_open`?ou(e.attrGet(`href`)):null;return t?[su(t)]:[]}));if(r?.text!==n&&Su.set(t,{text:n,links:i,inputs:[],previews:[]}),i.length===0)return[];let a=e.basePath??we(globalThis.location.pathname)[0],o=[e.runId,a,e.sessionPublicOrigin,globalThis.location.origin],s=[],c=!1;frameInputs:for(let n of e.groups)if(o.push(n.runId),n.runId===e.runId)for(let{message:e}of n.messages){if(o.push(e),e===t){c=!0;break frameInputs}let n=P(e);if(n){s.push(n),o.push(n.role,n.toolName,n.tool_name,n.content,Rr(n));for(let e of qt(n))o.push(e,e.callId,e.runId,e.name,e.completed,e.live,e.isError,e.outputText,e.details)}}if(!c)return[];if(r?.text===n&&o.length===r.inputs.length&&o.every((e,t)=>Object.is(e,r.inputs[t])))return r.previews;let l=new Set(i),u=new Map,d=new Map,f=new Map;for(let t of s){let n=typeof t.role==`string`?jt(t.role):``;if(n!==`assistant`&&n!==`tool`||Rr(t)!==e.runId)continue;let r=Array.isArray(t.content)?t.content:[];if(r.some(t=>{let n=P(t),r=vn(n?.runId);return n&&(me(n.type)||pe(n.type))&&r&&r!==e.runId}))continue;let i=vn(t.toolName)??vn(t.tool_name);for(let n of r){let r=P(n),i=r&&me(r.type)?fe(r)??vn(t.toolCallId):void 0,a=vn(r?.name);i&&a&&f.set(zr(e.runId,i),a)}for(let n of qt(t)){if(n.runId!==e.runId||Pt(n,!1)!==`succeeded`)continue;let t=au((n.callId?f.get(zr(e.runId,n.callId)):void 0)??i);if(!(!t||n.name!==t||i&&i!==t))for(let{candidate:e,keys:r}of mu(n,t,l)){let n=su(e.url),i=u.get(n)??{source:e};if(t===`web_fetch`){i.source=e,i.page=e,i.search??=r.map(e=>u.get(e)?.search).find(e=>e!==void 0),l.add(n);for(let e of r)e!==n&&d.set(e,n);d.delete(n)}else i.search?.excerpt||(i.search=e,i.page||(i.source=e));u.set(n,i)}}}let p=new Map,m=t=>gr(t)!==null||cr(t,{basePath:a,publicOrigin:e.sessionPublicOrigin})!==null;for(let e of i){if(m(e))continue;let t=e;for(let e=d.get(t);e;e=d.get(t))t=e;let n=u.get(t);if(n&&!p.has(t)&&!m(t)&&p.set(t,hu(n)),p.size>=_u)break}let h=[...p.values()];return Su.set(t,{text:n,links:i,inputs:o,previews:h}),h}var _u,vu,yu,bu,xu,Su;function Cu(){return(Cu=e((()=>{ut(),Nn(),de(),Ce(),pr(),Zn(),Cr(),hr(),Mr(),Fr(),Kt(),It(),Yt(),_u=8,vu=3e4,yu=1e5,bu=280,xu=dr(),Su=new WeakMap})))()}export{ec as $,Si as $n,Ka as $t,Wc as A,Vi as An,$o as At,wc as B,Ki as Bn,ko as Bt,ol as C,ra as Cn,ss as Ct,Xc as D,Oi as Dn,es as Dt,nl as E,aa as En,Qo as Et,Mc as F,Yi as Fn,Wo as Ft,yc as G,Hi as Gn,po as Gt,Cc as H,ji as Hn,Eo as Ht,Dc as I,na as In,Vo as It,_c as J,Ti as Jn,io as Jt,vc as K,Qi as Kn,oo as Kt,Ac as L,Ui as Ln,Bo as Lt,Fc as M,Ii as Mn,Uo as Mt,Pc as N,$i as Nn,Ko as Nt,Zc as O,Di as On,os as Ot,Nc as P,Pi as Pn,Ho as Pt,uc as Q,Mi as Qn,Za as Qt,Oc as R,Zi as Rn,Io as Rt,il as S,da as Sn,vs as St,rl as T,ia as Tn,_s as Tt,Sc as U,Li as Un,To as Ut,Tc as V,zi as Vn,No as Vt,xc as W,Ni as Wn,_o as Wt,pc as X,Wi as Xn,uo as Xt,fc as Y,Ri as Yn,ao as Yt,hc as Z,Ji as Zn,$a as Zt,Il as _,_a as _n,ks as _t,ql as a,Oa as an,pi as ar,Qs as at,Ol as b,ha as bn,ys as bt,Wl as c,Sa as cn,ii as cr,$s as ct,Vl as d,Ia as dn,ti as dr,Is as dt,Ja as en,xi as er,ac as et,Hl as f,ba as fn,ei as fr,Ls as ft,Ll as g,ga as gn,As as gt,Rl as h,va as hn,js as ht,ru as i,Na as in,fi as ir,qs as it,Gc as j,Fi as jn,ts as jt,Kc as k,Bi as kn,Zo as kt,Kl as l,Ta as ln,ni as lr,Bs as lt,zl as m,Ca as mn,Ns as mt,Cu as n,Pa as nn,yi as nr,ic as nt,Bl as o,Da as on,si as or,Xs as ot,Ul as p,Ea as pn,Fs as pt,gc as q,Xi as qn,ro as qt,iu as r,Fa as rn,di as rr,dc as rt,Jl as s,ya as sn,ai as sr,Zs as st,gu as t,qa as tn,ci as tr,rc as tt,Gl as u,xa as un,ri as ur,zs as ut,xl as v,ma as vn,Es as vt,al as w,la as wn,Ts as wt,sl as x,ua as xn,hs as xt,Tl as y,pa as yn,Ds as yt,Ec as z,qi as zn,Mo as zt};