UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

2 lines • 273 kB
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./control-ui-connection-D5QrEAFW.css","./control-ui-boot-shared-styles-BorAdMVO.css","./control-ui-boot-chat-DewxEbIm.js","./deferred-ui-support-D-VedBtc.js","./markdown-runtime-DmM7zNej.js","./control-ui-boot-chat-styles-CEPkk0Pv.js","./chat-message-media-runtime-BIOBdIgm.js","./virtual-core-runtime-BYd4CRBu.js","./control-ui-boot-chat-styles-BoDuSoES.css","./cloud-target-view-DyYFo_EG.js","./place-browser-DBuGCgSP.js","./lobster-pet-identity-Cg5EqPlD.js","./lobster-dex-Mq9Rr_vU.js","./lobster-pet-audio-waE6qgq0.js","./lobster-pet-identity-D4tlOWIt.css","./panel-empty-state-D5H9zOzY.js","./en-chat-session-optional-iBUVV79A.js","./chat-attachment-text-reader-DYgn--mC.js","./canvas-limits-DuPWavzb.js","./canvas-embed-policy-fbO0_Zm9.js","./canvas-frame-presentation-CwBCYJii.js","./file-disclosure-D6bCIJV1.js","./chat-video-player-BIDKBSio.js","./chat-attachment-admission-ref-C_srMB_p.js","./chat-html-preview-view-CEXfRv3H.js","./chat-file-scroll-BYjNc13x.js","./chat-diff-render.solid-B4cx69we.js","./file-disclosure-DEPLU5-d.css","./chat-detail-panel-j9tTgWSw.css"])))=>i.map(i=>d[i]);
import{n as e,r as t}from"./rolldown-runtime-CNOWq4Kh.js";import{$o as n,$s as r,At as i,Gi as a,Ho as o,It as s,Kl as c,Nt as l,O as u,Oa as d,Pt as f,Qn as p,Qs as m,Qt as h,Rt as g,Sn as _,Tt as v,Xt as y,Yn as b,Zo as x,at as ee,bn as te,dc as ne,et as re,fi as ie,in as ae,j as oe,jt as se,ka as ce,kc as le,lc as ue,ln as S,lo as C,lu as w,mc as de,nc as T,oc as fe,ot as pe,pc as me,sc as he,tt as ge,uu as E,vi as D,wa as O,wc as _e,xa as k,xc as ve,zi as ye,zs as be}from"./control-ui-connection-Bfj9beF_.js";import{$S as xe,$i as Se,$k as Ce,$p as we,Aa as Te,Ai as Ee,An as De,Ao as Oe,As as ke,BA as A,BD as Ae,Bi as je,Bo as Me,Bs as Ne,Bt as Pe,Bx as Fe,CD as Ie,CO as Le,Ca as Re,Cb as ze,Ci as Be,Ck as Ve,Cp as He,DS as Ue,Da as We,Di as Ge,Dn as Ke,Dt as qe,Ea as Je,Eb as Ye,Ei as Xe,Ek as Ze,En as Qe,Ep as $e,FA as et,FM as tt,Fg as nt,Fi as rt,Fo as it,Fs as at,Ft as ot,GO as st,Ga as ct,Gb as lt,Gx as ut,HO as dt,Ha as ft,Hb as pt,Hn as mt,Ho as ht,Ia as gt,Ii as _t,It as vt,JC as yt,JS as bt,Ja as xt,Jg as St,Jk as Ct,Jn as wt,Jt as Tt,Kn as Et,Kt as Dt,LD as Ot,La as kt,Ld as At,Li as jt,Lr as Mt,Ls as Nt,Mi as Pt,Mn as Ft,Mo as It,Mt as Lt,Mv as Rt,Ni as zt,No as Bt,Nr as Vt,Ns as Ht,Nv as Ut,Og as Wt,Oi as Gt,On as Kt,PD as qt,Pi as Jt,Po as Yt,QA as Xt,Qb as Zt,Qt,Ra as $t,Rd as en,Ri as tn,Rs as nn,Rx as rn,Si as an,Sn as on,Tx as sn,Ub as cn,Un as ln,Va as un,Vi as dn,Vk as fn,Vr as pn,Vs as mn,Vx as hn,Wa as gn,Wb as _n,Ws as vn,Wx as yn,XO as bn,XS as xn,Xa as Sn,Xn as Cn,Xp as wn,Xt as Tn,YC as En,Ya as Dn,Yk as On,Yn as kn,Yr as An,Yt as jn,ZA as Mn,Zk as Nn,Zt as Pn,_C as Fn,_D as In,_O as Ln,_i as Rn,_j as zn,_k as Bn,_n as Vn,_t as Hn,_x as Un,aM as Wn,a_ as Gn,aj as Kn,ao as qn,ar as Jn,bD as Yn,bO as Xn,bT as Zn,ba as Qn,bi as $n,bn as er,bp as tr,br as nr,bv as rr,bx as ir,ca as ar,ci as or,dO as sr,da as cr,dj as j,dk as lr,dn as ur,dr,ds as fr,dw as pr,eA as mr,eC as hr,e_ as gr,ea as _r,ej as vr,ex as yr,fD as br,fO as xr,fT as Sr,fi as Cr,gD as wr,gE as Tr,gO as Er,ga as Dr,gf as Or,gk as kr,go as Ar,gt as jr,gx as Mr,hD as Nr,hE as Pr,hf as Fr,hi as Ir,hj as Lr,hs as Rr,ht as zr,hx as Br,iM as Vr,i_ as Hr,ii as Ur,ij as Wr,io as Gr,ix as Kr,jA as qr,jD as Jr,ja as Yr,ji as Xr,jn as Zr,jo as Qr,jr as $r,jt as ei,kD as ti,kS as ni,kb as ri,ki as ii,kk as ai,kn as oi,kp as si,ks as ci,lO as li,lw as M,mD as ui,mE as di,mT as fi,mj as N,mn as pi,ms as mi,mt as hi,mx as gi,nD as P,nj as _i,nk as vi,nr as yi,oa as bi,ok as xi,on as Si,or as Ci,os as wi,pD as Ti,pO as Ei,pj as Di,pn as Oi,po as ki,px as Ai,qa as ji,qg as Mi,qn as Ni,qt as Pi,sO as Fi,sa as Ii,sk as Li,sn as Ri,tA as zi,tD as Bi,ti as Vi,to as Hi,tr as Ui,uO as Wi,ua as Gi,ui as Ki,uj as qi,uk as Ji,un as Yi,ur as Xi,us as Zi,vC as Qi,vD as $i,vO as ea,va as ta,vj as na,vn as ra,vt as ia,wD as aa,wO as oa,wk as sa,wn as ca,wr as la,wt as ua,wx as da,xT as fa,xa as pa,xi as ma,xn as ha,xr as ga,xx as _a,yO as va,ya,yn as ba,zA as F,zM as xa,zi as Sa,zk as Ca,zr as wa,zs as Ta,zt as Ea}from"./control-ui-boot-shared-DFTSUQQ0.js";import{$ as Da,A as Oa,B as ka,C as Aa,Ct as ja,F as I,I as Ma,J as Na,K as Pa,M as Fa,O as L,P as Ia,Rt as La,S as Ra,St as za,U as R,V as Ba,W as Va,_t as Ha,d as z,f as B,g as V,gt as H,j as U,l as W,m as G,o as Ua,p as Wa,r as Ga,s as Ka,u as K,w as qa,x as q,y as Ja,yt as Ya}from"./solid-runtime-C416s-HC.js";import"./control-ui-boot-shared-styles-CTDFATjh.js";import{A as Xa,E as Za,L as Qa,M as $a,N as eo,O as to,P as no,S as ro,a as io,c as ao,d as oo,h as so,i as co,k as lo,l as uo,m as fo,n as po,p as mo,r as ho,t as go,u as _o,v as vo,w as yo,x as bo,y as xo}from"./route-controls-runtime-Bx6nx3QW.js";import"./control-ui-boot-new-styles-C0RRkvtM.js";import{d as So,g as Co,i as wo,l as To,m as Eo,o as Do,r as Oo,t as ko}from"./composer-invocation-menus-C8QNiPIl.js";async function Ao(e){let t=await e.request(`agents.list`,{includeSessionPlacement:!0});if(!t.sessionPlacement)throw Error(`Session placement policy is unavailable`);return t.sessionPlacement}function jo(e){return{key:e.key,agentId:e.agentId,...e.target.kind===`profile`?{profileId:e.target.profileId,...e.target.os?{os:e.target.os}:{},...e.target.machineClass?{machineClass:e.target.machineClass}:{}}:e.target.kind===`device`?{deviceId:e.target.deviceId}:{autoDevice:!0}}}function Mo(e){return e instanceof re?e.retryable||e.gatewayCode===`UNAVAILABLE`:!0}async function No(e,t){try{let n=await e.describe({key:t},{refresh:!0,client:e.client});if(n?.session===null)return{status:`missing`};let r=n?.session?.sessionId;return{status:`read`,placement:n?.session?.placement,...r?.trim()?{sessionId:r}:{}}}catch(e){return Jr(e,null)?{status:`awaiting-gateway`}:Mo(e)?{status:`unavailable`}:{status:`rejected`,error:y(e)}}}async function Po(e,t){try{await e.request(`sessions.reclaim`,{key:t.key,agentId:t.agentId});return}catch(e){return y(e)}}async function J(e,t,n,r){if(!n())return{status:`interrupted`};let i=await Po(e,t);return i?{status:`cleanup-rejected`,error:i,...r===void 0?{}:{messageId:r}}:{status:`cancelled`}}async function Fo(e,t,n,r=!1){let{client:i}=e;if(!i)return`gateway unavailable during draft cleanup`;let a=await No({...e,client:i},t);if(a.status===`missing`)return;if(a.status===`rejected`)return a.error;if(a.status===`unavailable`||a.status===`awaiting-gateway`)return r?`session placement could not be verified`:`placement draft session could not be verified`;if(r&&a.placement){let e=await Po(i,{key:t,agentId:n});if(e)return e}if(!a.sessionId)return`placement draft session identity is unavailable`;let o={key:t,agentId:n,expectedSessionId:a.sessionId};try{await i.request(`sessions.patch`,{...o,archived:!0})}catch(e){return y(e)}try{if((await i.request(`sessions.delete`,{...o,deleteTranscript:!0,archivedOnly:!0})).deleted!==!0)throw Error(`placement draft session was not deleted`);return}catch(e){let t=y(e);try{await i.request(`sessions.patch`,{...o,archived:!1})}catch(e){return`${t}; restoring the placement draft failed: ${y(e)}`}return t}}async function Io(e,t,n,r=()=>!0){let{client:i}=e,a=t.message,o=t.mentions,s=t.cleanupOnCancellation??(()=>!0),c=async(r,i)=>{let a={key:t.key,agentId:t.agentId},o=t.sessionId,{client:c}=e,l=i,u=0,d=0,f=!1;for(let t=0;t<Ro;t+=1){let t=l??await No(e,a.key);if(f=t.status===`read`&&t.placement!==void 0&&Vo.has(t.placement.state),l=void 0,t.status===`missing`)return{status:`missing`};if(t.status===`rejected`)return{status:`cleanup-rejected`,error:t.error};if(t.status===`unavailable`||t.status===`awaiting-gateway`){if(u=t.status===`awaiting-gateway`?0:u+1,!n())return J(c,a,s);if(u>=zo){let e=await Po(c,a),t=`session placement could not be verified`;return{status:`cleanup-rejected`,error:e?`${t}; cleanup failed: ${e}`:t}}await _e(Lo)}else{if(u=0,t.status===`read`){if(o&&t.sessionId&&o!==t.sessionId)return{status:`cleanup-rejected`,error:`The conversation changed. Review this message before retrying.`};let e=t.placement;if(e)d=0;else if(d+=1,d>=Bo)return{status:`cleanup-rejected`,error:`session placement could not be verified`};if(!n())return J(c,a,s);if(e?.state===`active`)return{status:`active`,placement:e,sessionId:t.sessionId};if(r===`retry`&&(!e||e.state===`local`||e.state===`reclaimed`||e.state===`failed`))return{status:`dispatch`,sessionId:t.sessionId};if(e&&!Vo.has(e.state)){if(e.state===`failed`){let e=await Po(c,a);if(e)return{status:`cleanup-rejected`,error:e}}return{status:`rejected`,placement:e}}}await _e(Lo)}}return n()?{status:`cleanup-rejected`,error:O(f?`newSession.placementStillStarting`:`newSession.placementCompletionUnconfirmed`)}:J(c,a,s)},l={status:`dispatch`},u=``,d,f=t.target.kind===`profile`&&t.target.required?t.target:void 0;if(t.mode!==`resend`&&f)try{let r=Ao(i);d=No(e,t.key);let a=await r;if(!n())return J(i,t,s);if(a.requiredProfile?.id!==f.profileId)return{status:`dispatch-rejected`,error:O(`newSession.requiredWorkerChanged`)};if(!a.requiredProfile.providerId)return{status:`dispatch-rejected`,error:O(`newSession.requiredWorkerUnavailable`)}}catch(e){return n()?{status:`dispatch-rejected`,error:y(e)}:J(i,t,s)}if(t.mode!==`resend`&&(t.mode!==`dispatch`||f)&&(l=await c(t.mode,d&&await d),l.status===`dispatch`&&!n()))return J(i,t,s);if(t.mode!==`resend`&&!f&&l.status===`dispatch`)try{let e=await i.request(`sessions.dispatch`,jo(t));l=await c(`recover`,e.placement?{status:`read`,placement:e.placement,sessionId:e.sessionId}:void 0)}catch(e){if(u=y(e),!s()&&!n())return{status:`interrupted`};if(!Mo(e))return{status:`dispatch-rejected`,error:u};l=await c(`recover`)}if(!s()&&!n())return{status:`interrupted`};if(l.status===`cancelled`||l.status===`interrupted`||l.status===`cleanup-rejected`)return l;if(l.status===`missing`)return{status:`session-missing`,error:`placement draft session no longer exists`};if(l.status===`rejected`){let e=typeof l.placement?.state==`string`?l.placement.state:``;return{status:`dispatch-rejected`,error:(l.placement?.state===`failed`?l.placement.recoveryError:void 0)||u||(e?`session placement became ${e}`:``)}}if(!n())return J(i,t,s);let p=t.messageId??m(),h=t.sessionId??l.sessionId;if(!h)return{status:`send-not-started`,messageId:p,error:`Session identity is unavailable. Retry.`};let g=async(e,n)=>{let r=t.mode===`resend`?void 0:await Po(i,t);return{status:n,messageId:p,error:r?`${e}; cleanup failed: ${r}`:e}};if(!r(h))return g(`placement recovery storage is unavailable`,`send-not-started`);try{let e=await i.request(`chat.send`,{sessionKey:t.key,sessionId:h,expectedLeafEntryId:null,agentId:t.agentId,message:a,...o?.length?{mentions:o}:{},attachments:t.attachments,idempotencyKey:p},{timeoutMs:me,signal:t.signal,retainSentResultOnAbort:!0});if(!n())return await J(i,t,s,p);let r=Un(e,p);return Mr(r)?g(Ai(r,`chat`),`send-definitive-rejected`):{status:`started`,messageId:p}}catch(e){return Br(e)?{status:`send-definitive-rejected`,messageId:p,error:y(e)}:n()?e instanceof ee||e instanceof Error&&!(e instanceof re)&&e.message===`gateway not connected`?g(y(e),`send-not-started`):Mo(e)?{status:`send-rejected`,retryAfterMs:_a(e)??500,error:y(e),messageId:p}:g(y(e),`send-definitive-rejected`):J(i,t,s,p)}}var Lo,Ro,zo,Bo,Vo;function Ho(){return(Ho=e((()=>{ve(),de(),pe(),ge(),k(),yn(),h(),ti(),r(),ir(),gi(),ut(),Lo=250,Ro=1200,zo=4,Bo=20,Vo=new Set([`requested`,`provisioning`,`syncing`,`starting`,`draining`,`reconciling`])})))()}function Uo(e,t,n){e.onNavigate&&e.sessionDataContext&&(e.sessionDataContext.agentSelection.set(n),e.onNavigate(`terminal`,{pathname:x(`terminal`,e.basePath),search:xi(t),hash:``}))}async function Wo(e,t,n){let{prepareCatalogTerminal:r}=await w(async()=>{let{prepareCatalogTerminal:e}=await import(`./catalog-terminal-start-Bf4vtlzu.js`).then(e=>(e.n(),e.t));return{prepareCatalogTerminal:e}},__vite__mapDeps([0]),import.meta.url);return r(e,t,n)}function Go(){return(Go=e((()=>{o(),Li(),E()})))()}var Y,Ko,X;function Z(){return(Z=e((()=>{yn(),ce(),Y=ut.catalog.newSession,Ko={newSession:{openClawWorker:`OpenClaw worker`,deviceFolder:`Existing folder`,deviceFolderOn:`Existing folder on {device}`,deviceFolderModelUnsupported:`Not available with this model`,deviceFolderDescription:`Work in place on the selected device. Files are not copied to the Gateway.`,deviceFolderPath:`Absolute path on device`,deviceFolderPathPlaceholder:`/path/to/existing/folder`,deviceFolderUnavailable:`This device cannot use an existing folder right now. Check its connection and session-hosting support, or choose another workspace.`,deviceFolderRuntimeUnsupported:`This model can't work in an existing device folder. Choose an OpenClaw model or another workspace; your folder path is kept.`,deviceFolderPathRequired:`Enter an absolute path to an existing folder on the selected device.`,deviceFolderAttachmentsUnsupported:`Existing device folders cannot receive attachments. Remove them, or choose another workspace.`,requiredWorkerHint:`Say what you’d like to work on.`,requiredWorker:`Worker`,requiredWorkerUnavailable:Y.requiredWorkerUnavailable,requiredWorkerChanged:Y.requiredWorkerChanged,title:d.newSession.title,hint:d.newSession.hint,environments:`Environments`,gateway:`Gateway · local`,cloudWorkerMachine:`{profile} · {machine}`,cloudWorkerOsMachine:`{profile} · {os} · {machine}`,cloudWorkerOs:`{profile} · {os}`,cloudRuntimeUnsupported:`The {runtime} runtime does not support cloud workers.`,cloudProfileRuntimeUnsupported:`The {runtime} runtime cannot use this cloud worker. Choose a compatible cloud worker or run locally.`,deviceRuntimeUnsupported:`This runtime does not support paired devices`,placementStartFailed:Y.placementStartFailed,placementCreateFailed:`Couldn't prepare session recovery. Your draft has been kept.`,placementStillStarting:Y.placementStillStarting,placementCompletionUnconfirmed:Y.placementCompletionUnconfirmed,placementReloadBlocked:d.newSession.placementReloadBlocked,placementCancelled:Y.placementCancelled,discardUnsavedAndReload:d.newSession.discardUnsavedAndReload,yourDevices:`Your devices`,autoDeviceSub:`Least-busy device`,autoDeviceSubEligible:`First eligible device`,cloud:Y.cloud,hosted:`Hosted workspaces`,hostedWorkspace:`Hosted workspace`,hostedHint:`Runs in the provider’s workspace. Send files as chat attachments; local folders and repositories are not copied.`,hostedUnavailable:`No available model for this hosted workspace. Check the runtime setup and API-key account in model settings.`,hostModelRequired:`Choose a model with an available local runtime before selecting a device or cloud worker.`,hostedSetup:`Agents API setup`,hostedSetupHint:`Requires the enabled Agents API plugin, a compatible API-key model, and a hosted environment. ChatGPT subscriptions are not supported.`,machine:`Machine`,operatingSystem:`Operating system`,runsOn:Y.runsOn,browse:`Browse folders`,worktree:`Worktree`,checkingGit:`Checking Git availability…`,folderRequiresScope:`Checking Git for this folder requires {scope} access. Ask the person who manages OpenClaw for access.`,gitCheckAccessDenied:`You don't have permission to check Git for this folder. Ask the person who manages OpenClaw for access.`,gitCheckUnavailable:`Couldn't verify Git for this folder. Choose it again to retry.`,starting:Y.starting,followUps:`Follow-up messages`,followUpCommandsUnavailable:Y.followUpCommandsUnavailable,followUpReloadBlocked:Y.followUpReloadBlocked,followUpsPaused:Y.followUpsPaused,followUpsAdmissionFailed:Y.followUpsAdmissionFailed,createFailed:Y.createFailed,checkoutCurrentNote:`Works in the selected folder on its current branch.`,preferenceSaveUnconfirmed:Y.preferenceSaveUnconfirmed,worktreeNameClearUnconfirmed:Y.worktreeNameClearUnconfirmed,agent:`Agent`,agents:`Agents`,where:`Where`,gatewayNamed:`Gateway · {name}`,cloudWorker:`Cloud · {profile}`,cloudWorkerProvider:`Cloud worker provider: {provider}`,cloudRecoveryUnavailable:`Cloud workers are unavailable because this connection does not support task recovery. Reconnect or update the Gateway.`,placementSyncsFolder:`Syncs {folder} to the selected runner`,placementClonesRepository:`Clones {folder} on the selected runner. No Gateway checkout is created.`,folder:`Folder`,autoDevice:`Auto`,neverConnected:`Never connected`,offlineFor:`Offline for {duration}`,lastSeen:`Last seen {time}`,nodeUpdateRequired:`Update required: run {updateCommand}, then reconnect. For a headless node, run {restartCommand}.`,nodeCommandPendingApproval:`Ask an administrator to approve the pending {command} request, or pick another device.`,nodeCommandUndeclared:`Make {command} available on this device, then reconnect, or pick another device.`,nodeCommandUnauthorized:`Authorize {command} in the Gateway node command policy, or pick another device.`,capabilityCamera:`Camera`,capabilityLocation:`Location`,capabilityTalk:`Talk`,capabilityScreenCapture:`Screen capture`,capabilityCanvas:`Canvas`,capabilityVoice:`Voice`,environmentDisposable:`Disposable`,environmentPersistent:`Persistent`,registerProject:`Register as project`,machineShape:`{cpu} vCPU · {memory} GB`,machineCpu:`{cpu} vCPU`,machineMemory:`{memory} GB`,machineDefault:`Default`,browseRequiresAdmin:`To browse outside agent workspaces, open Inbox, select Limited access, request admin, then approve in Devices.`,connectMachine:`Connect a device`,browserUp:`Parent folder`,browserUse:`Use this folder`,browserEmpty:`No subfolders`,browserNoMatches:`No matching folders`,browserLoadFailed:`Couldn't list that folder.`,hiddenFolder:`Hidden folder`,worktreeUnavailable:`Selected folder is not a Git checkout`,worktreeBaseRef:`From`,worktreeBranchesLimited:`Suggestions are limited. Enter any branch or commit.`,worktreeBranchesUnavailable:`Branch suggestions are unavailable. Enter a branch or commit.`,worktreeName:`Name`,worktreeNamePlaceholder:`Named from the session title`,worktreeBranchNote:`Creates branch {branch} in a separate checkout.`,worktreeBranchFromTitleNote:`Creates a branch from the session title in a separate checkout.`,worktreeNameInvalid:`Use lowercase letters, digits, and dashes.`,draft:`Draft`,draftDescription:`Keep this session to yourself until you publish it`,draftUnavailable:`Draft creation is disabled. Your message and attachments have been kept. Turn off Draft to create a Shared session, or ask an administrator to enable Draft creation.`,messagePlaceholder:`What should this session work on?`,dictate:`Dictate`,readingAttachment:`Reading attachment`,start:`Start session`,created:`Session created`,startInTerminal:`Start in terminal`,nativeTerminalHint:`Start the native CLI on the selected machine using its own account and configuration. This does not create an OpenClaw Chat.`,chooseNativeHost:`Choose a native CLI host`,nativeHostsUnavailable:`No native CLI is available. Install it on the Gateway or connect a machine with CLI access, then reconnect to the Gateway.`,nativeTerminalPrompt:`Optional initial prompt for the native CLI`,terminalNodeFolder:`Existing absolute folder on this node`,terminalAttachmentsUnsupported:`Remove attachments before starting a native CLI. Add files from the terminal after it opens.`,createOutcomeUnknown:`The Gateway changed while this session was starting. Check recent sessions before starting this task again.`,cliAgentsGroup:`CLI agents`,cliAgentsUnavailable:`CLI agents unavailable`,placementSetupInterrupted:`This session's runner setup was interrupted. Check recent sessions before starting this task again.`,catalogUnavailable:`This session target is unavailable.`,placementNotReady:`The selected runner isn't ready yet. Try again in a moment.`,nodeUnavailable:`The selected device is unavailable. Pick another place.`,terminalCapabilityOverridesUnsupported:`Clear session capability overrides before starting in a terminal.`,checkout:`Checkout`,checkoutCurrent:`Current checkout`,checkoutWorktree:`New worktree`,checkoutWorktreeNamed:`Worktree · {name}`,checkoutWorktreeSub:`Isolated copy of the repo`,checkoutWorktreeFrom:`New worktree from {branch}`,checkoutCloud:`Starting branch`,checkoutCloudFrom:`From {branch}`,checkoutRepository:`Remote checkout`,checkoutRepositoryFrom:`Remote checkout from {branch}`,checkoutRequiresWorktree:`Use an isolated worktree for this project and agent`,checkoutCheckUnavailable:`Checkout unavailable. Select the project again to retry`,checkoutRemoteLocked:`Devices and cloud run in a worktree`,local:`Local`,folderPlaceholder:`Agent workspace`,projects:`Projects`,projectsAdminHint:`Admins can register projects from Browse folders`,projectSearchPlaceholder:`Search projects or paste a Git URL`,githubProjects:`GitHub`,githubTokenHint:`No Control UI GitHub credential or shared Gateway environment token is configured; public GitHub results only.`,cloneProject:`Clone`,recentFolders:`Recent`,what:`What`,newWorkspace:`New workspace`,newWorkspaceDescription:`Start in an empty folder for this session.`,remoteSourceUnavailable:`This folder cannot provide a Git checkout. Select New workspace to start empty, or choose a repository.`,environmentSearchPlaceholder:`Search environments`,environmentSearchEmpty:`No matching environments`,gatewayHost:`Gateway host`,device:`Device`,environmentDetails:`Show details for {name}`,concurrentSessionsValue:`{used} of {total} session slots in use`,autoDeviceChoose:`Any available device`,manageCloudWorkers:`Manage cloud workers`,persistentEnvironmentHint:`Reusable host`,disposableEnvironmentHint:`Disposable host`,sessionHostingAction:`Session hosting is disabled. Run these commands on the paired device:`,updateAction:`This device needs an update. Run the following command:`,reconnectAction:`Then reconnect the device. For a headless device, run:`,runsOnGateway:`Runs on your gateway`,autoDeviceHint:`Chooses the least-busy connected device`,autoDeviceHintEligible:`Chooses the first eligible connected device`,autoDeviceInfo:`About automatic device selection`,autoDeviceScope:`Connected devices only`,restoringPreferences:`Restoring your last session setup…`,checkingPlace:`Checking the selected place…`,agentsUnavailable:`No agents are available on this Gateway yet.`,loadingAgentDefaults:`Refreshing agent defaults…`,agentDefaultsUnavailable:`Could not refresh agent defaults. Reload to try again.`,terminalHostUnavailable:`Native CLI host unavailable. Check that the CLI is installed and the node is connected with its fresh-start command approved, then retry the catalog.`,terminalDisabled:`Enable CLI agents and terminals in Gateway settings to start a native CLI.`,terminalPlacementUnsupported:`Native CLI sessions use a specific host, not OpenClaw worker placement. Reset this draft and choose a native host.`,terminalNeedsFolder:`Pick a folder before starting in a terminal.`,noSessionHosts:`No devices have session hosting enabled. Connect a machine with session hosting enabled, or enable it on a paired device.`,deviceUnavailable:`Device unavailable. Reconnect it and try again.`,environmentUnavailable:`Unavailable`,sessionHostingDisabled:`Session hosting is disabled. On the paired device, run openclaw config set nodeHost.workerRuns.enabled true, then openclaw node install --force.`,deviceCapacityUnavailable:`Worker capacity is unavailable. Restart the device session host and try again.`,deviceNoSlots:`No worker slots are available. Wait for a slot or pick another device.`,connectMachineTitle:`Connect a machine`,connectMachineDescription:`Run this command on the machine you want to connect.`,connectMachineGenerating:`Creating a secure connection link…`,connectMachineFailed:`Couldn't create a connection link.`,connectMachineMissingUrl:`The Gateway did not return a join URL. Update it and try again.`,connectMachineUnavailable:`Reconnect to the Gateway and try again.`,connectMachineTeamHint:`Installs a background node service that pairs this machine with your team and can run agent sessions.`,connectMachineCommandOnly:`Command access only (no agent sessions)`,connectMachineInstalled:`Already have OpenClaw installed? Run:`,connectMachineSingleUse:`This link is single-use and expires soon.`,connectMachineSingleUseExpires:`This link is single-use and expires at {time}.`,connectMachineFreshCode:`Mint fresh code`,connectMachineRefreshing:`Minting…`,connectMachineManageDevices:`Manage devices`}},X=Object.assign(()=>{Object.assign(d.newSession,Ko.newSession)},{catalog:Ko})})))()}var qo;function Jo(){return(Jo=e((()=>{k(),Z(),h(),E(),X(),qo=class{constructor(e,t){this.gateway=e,this.changed=t,this.openValue=!1,this.loadingValue=!1,this.errorValue=null,this.setupValue=null,this.requestId=0,this.request=null,this.requestListeners=new Set,this.subscribeRequests=e=>{let t=p(this.requestListeners,e);return this.request&&e(this.request),t}}get open(){return this.openValue}start(){this.openValue=!0,this.errorValue=null,this.setupValue=null,this.changed(),this.refresh()}close(){this.retireRequest?.(),this.retireRequest=void 0,this.request=null,this.requestId+=1,this.openValue=!1,this.loadingValue=!1,this.errorValue=null,this.setupValue=null}view(e,t){return{open:this.open&&e,loading:this.loadingValue,error:this.errorValue,setup:this.setupValue,subscribeRequests:this.subscribeRequests,onClose:()=>{this.close(),this.changed()},onRefresh:()=>void this.refresh(),onManageDevices:t}}refresh(){if(!this.openValue||this.loadingValue)return Promise.resolve();let{client:e,connected:t}=this.gateway();if(!t||!e)return this.errorValue=O(`newSession.connectMachineUnavailable`),this.changed(),Promise.resolve();let n=++this.requestId;this.loadingValue=!0,this.errorValue=null;let r=Promise.withResolvers();this.retireRequest=r.resolve;let i=this.load(n,e),a={completion:i,retired:r.promise,isCurrent:()=>this.loadingValue&&this.stillCurrent(n,e),reportError:t=>{this.stillCurrent(n,e)&&(this.errorValue=y(t),this.changed())}};this.request=a,this.changed();for(let e of this.requestListeners)e(a);return i}async load(e,t){try{let{requestDevicePairJoinSetup:n}=await w(async()=>{let{requestDevicePairJoinSetup:e}=await import(`./device-pair-setup-runtime-DXEqakSV.js`).then(e=>(e.a(),e.i));return{requestDevicePairJoinSetup:e}},__vite__mapDeps([0]),import.meta.url);if(!this.stillCurrent(e,t))return;let r=await n(t);if(!this.stillCurrent(e,t))return;if(!r.joinUrl?.trim()){this.setupValue=null,this.errorValue=O(`newSession.connectMachineMissingUrl`);return}this.setupValue=r}catch(n){this.stillCurrent(e,t)&&(this.errorValue=y(n))}finally{e===this.requestId&&(this.request=null,this.loadingValue=!1,this.changed())}}stillCurrent(e,t){let n=this.gateway();return e===this.requestId&&t===n.client&&n.connected&&this.openValue}}})))()}function Yo(e,t,n,r){return JSON.stringify([e,t,n,...r?[r]:[]])}function Xo(e){return Yo(e?.requestedAgentId??``,e?.catalogId??``,e?.group??``,e?.requestedModel)}function Zo(e){let t=xo(e);return Yo(t.agentId,t.catalogId,t.group??``,t.requestedModel)}function Qo(e,t){return!e?.requestedAgentId||T(e.requestedAgentId)===T(t)?e?.requestedModel:void 0}function $o(e){return!!(e?.catalogId&&e.startTerminal&&e.catalogLabel)}function es(e){return M(e)&&!$o(e)||!!(e?.group&&e.groupStatus!==`resolved`)}function ts(e){return JSON.stringify([e?.groupStatus??``,e?.groupCwd??``,e?.groupWorktree===!0])}function ns(e,t){return!(!e?.group||t&&e.groupStatus===`resolved`)}function rs(e,t){return es(e)||ns(e,t)}function is(e,t){return e?.groupStatus===`resolved`&&!ns(e,t)?e.group:void 0}function as(e,t,n){let r=e?.agentId?.trim(),i=r?T(r):void 0;return i&&t.some(e=>T(e.id)===i)?i:n&&T(n)}function os(e,t){return!M(e)||$o(e)&&!!t}async function ss(e,t,n){try{let r=(await e.request(`sessions.catalog.list`,{...n?{agentId:n}:{},catalogId:t,limitPerHost:1})).catalogs.find(e=>e.id===t),i=r?.capabilities.startTerminal;return r&&i===!0?{catalogLabel:r.label,startTerminal:!0,terminalHosts:r.hosts.filter(e=>e.canStartTerminal===!0).map(({hostId:e,label:t})=>({hostId:e,label:t}))}:void 0}catch{return}}var cs;function Q(){return(Q=e((()=>{k(),Z(),s(),D(),vo(),X(),cs=class{constructor(e){this.notify=e}clear(){let e=this.read;this.read=void 0,e&&this.notify()}startRequest(e){let t={owner:e,canRetry:!1,completion:{promise:e.client.request(`sessions.catalog.list`,{agentId:e.agentId,metadataOnly:!0}).then(e=>{let n=e.catalogs.filter(e=>e.capabilities.startTerminal===!0).map(({id:e,label:t})=>({value:e,label:t}));return this.read===t&&(t.options=n,this.notify()),n},e=>{throw this.read===t&&(t.canRetry=!0,this.notify()),e})}};t.completion.promise.catch(()=>{}),this.read=t,this.notify()}load(e,t,n){let r=e?.gateway.snapshot,i=r?.client,a=t.trim()?T(t):``;if(!n||r?.phase!==`connected`||!i||!a||g(r,`sessions.catalog.list`)!==!0){this.clear();return}let o={agentId:a,client:i},s=this.read;s&&s.owner.client===o.client&&s.owner.agentId===o.agentId||(this.clear(),this.startRequest(o))}retry(e,t){let n=this.read;n?.canRetry&&n.owner.client===e&&n.owner.agentId===t&&this.startRequest(n.owner)}groups(){let e=this.read;if(e&&e.options?.length!==0)return[{errorLabel:O(`newSession.cliAgentsUnavailable`),id:`cliAgents`,label:O(`newSession.cliAgentsGroup`),options:e.options??[],completion:e.completion}]}}})))()}var ls;function us(){return(us=e((()=>{ls=[1e3,3e3,1e4,3e4,6e4]})))()}var ds=t({requestPlaceCatalog:()=>fs});async function fs(e,t){let n=await e.request(`environments.list`,t?{runtimeId:t}:{});return{profiles:(n.profiles??[]).filter(e=>n.dispatchableProfileIds?.includes(e.id)??!0).toSorted((e,t)=>e.id.localeCompare(t.id)),suggestedProfile:n.suggestedProfile,environments:n.environments.filter(e=>[`local`,`node`,`worker`].includes(e.type)).toSorted((e,t)=>e.id.localeCompare(t.id))}}function ps(e){let t=e.cpu===void 0?void 0:String(e.cpu),n=e.memoryGb===void 0?void 0:String(e.memoryGb);return t&&n?O(`newSession.machineShape`,{cpu:t,memory:n}):t?O(`newSession.machineCpu`,{cpu:t}):n?O(`newSession.machineMemory`,{memory:n}):void 0}function ms(){return(ms=e((()=>{k(),Z(),un(),X(),ft()})))()}function hs(e){let t=gs.get(e.client);t||(t=new WeakMap,gs.set(e.client,t));let n=t.get(e.hello);n||(n=new Map,t.set(e.hello,n));let r=JSON.stringify([e.gatewayUrl,e.profileId]),i=n.get(r);if(!i){let t=n,a=new _s(e,()=>{t.get(r)===a&&t.delete(r)});i=a,n.set(r,i)}return i}var gs,_s;function vs(){return(vs=e((()=>{Sr(),zt(),E(),gs=new WeakMap,_s=class{constructor(e,t){this.owner=e,this.release=t,this.mode=`loading`,this.palettePreference=null,this.listeners=new Map,this.writing=Promise.resolve(),this.pendingWrites=0,this.loading=this.load()}subscribe(e,t){return this.listeners.set(e,t),()=>{this.listeners.delete(e),this.releaseIfIdle()}}releaseIfIdle(){!this.listeners.size&&!this.pendingWrites&&this.release()}hasCurrentBinding(){return[...this.listeners.values()].some(e=>e())}setPalettePreference(e,t){if(!t())return Promise.resolve(!1);let n=async()=>{if(await this.loading,!this.hasCurrentBinding()||this.mode!==`remote`)return!1;try{return(await fi(this.owner.client,{entries:{"new-session.palette.v1":e}})).status===`ok`&&(this.palettePreference=e,this.publish(`changed`),!0)}catch{return!1}};this.pendingWrites+=1;let r=this.writing.then(n,n);return this.writing=r.then(()=>{},()=>{}),r.finally(()=>{--this.pendingWrites,this.releaseIfIdle()})}publish(e){for(let[t,n]of this.listeners)n()&&t(e)}async load(){try{let{loadUserPreferences:e}=await w(async()=>{let{loadUserPreferences:e}=await import(`./user-prefs-request-BE7DKPZP.js`).then(e=>(e.t(),e.r));return{loadUserPreferences:e}},__vite__mapDeps([0,1]),import.meta.url);if(!this.hasCurrentBinding())return;let t=await e(this.owner.client,this.owner.profileId);if(!this.hasCurrentBinding())return;if(t.status!==`ok`){this.mode=`local`;return}this.palettePreference=Xr(t.entries[Ee]),this.mode=`remote`}catch{this.mode=`local`}finally{this.publish(`loaded`)}}}})))()}function ys(e){return e.gatewayIdentityChanged||!e.placementDraftOwned?`gateway-changed`:`placement-interrupted`}var bs,xs;function Ss(){return(Ss=e((()=>{lo(),r(),bs=new WeakMap,xs=class{constructor(e){this.readOwner=e,this.sessionKey=``,this.messageId=``,this.message=``,this.target=null,this.agentId=``,this.gatewayUrl=``,this.recoveryScope=``,this.phase=`dispatching`,this.retryAllowed=!1,this.restored=!1,this.persistent=!0}releaseClaim(){this.claim?.owners.get(this.claim.key)===this&&this.claim.owners.delete(this.claim.key),this.claim=void 0}claimOwners(){let e=this.readOwner?.();if(!e)return;let t=bs.get(e);return t||(t=new Map,bs.set(e,t)),t}claimKey(e,t,n){return JSON.stringify([e,t,n])}clear(){this.persistent&&to(this.gatewayUrl,this.recoveryScope,this.sessionKey,this.messageId),this.reset()}hasOtherLiveOwner(e,t,n){let r=this.claimOwners()?.get(this.claimKey(e,t,n));return r!==void 0&&r!==this}owns(e,t,n){return!this.hasOtherLiveOwner(e,t,n)&&this.gatewayUrl===e&&this.recoveryScope===t&&this.sessionKey===n}reset(){this.releaseClaim(),this.sessionKey=``,this.messageId=``,this.message=``,this.mentions=void 0,this.attachments=void 0,this.target=null,this.agentId=``,this.gatewayUrl=``,this.recoveryScope=``,this.phase=`dispatching`,this.createParams=void 0,this.retryAllowed=!1,this.restored=!1,this.persistent=!0}restore(e,t){let n=this.claimOwners(),r=Xa(e,t).find(r=>{let i=n?.get(this.claimKey(e,t,r.sessionKey));return r.phase===`creating`&&(!i||i===this)});return!r||r.phase!==`creating`?null:(this.apply(r,!0,!0),r)}capture(){return this.snapshot(this.sessionKey,this.phase)}stageCreate(e){let t=`agent:${e.agentId}:dashboard:${m()}`,n=$a({...e.createParams,key:t},t,e.agentId);if(!n)return null;let r=e.persistent!==!1;r||delete n.key;let i={sessionKey:t,messageId:m(),message:e.message,...e.mentions?.length?{mentions:e.mentions}:{},attachments:e.attachments,target:e.target,agentId:e.agentId,gatewayUrl:e.gatewayUrl,recoveryScope:e.recoveryScope,phase:`creating`,createParams:n};return r&&!Qa(i)?null:(this.apply(i,!1,r),n)}promoteToDispatching(e){let t=this.sessionKey,n=this.snapshot(e,`dispatching`);return!n||this.persistent&&!no(t,n)?!1:(this.releaseClaim(),this.sessionKey=e,this.phase=`dispatching`,this.createParams=void 0,!0)}snapshot(e,t){return!this.sessionKey||!this.messageId||!this.target||!this.agentId||t===`creating`&&!this.createParams?null:{sessionKey:e,messageId:this.messageId,message:this.message,...this.mentions?.length?{mentions:this.mentions}:{},attachments:this.attachments,target:this.target,agentId:this.agentId,gatewayUrl:this.gatewayUrl,recoveryScope:this.recoveryScope,phase:t,...t===`creating`&&this.createParams?{createParams:this.createParams}:{}}}apply(e,t,n){this.releaseClaim();let r=this.claimOwners();if(r&&e.phase===`creating`){let t=this.claimKey(e.gatewayUrl,e.recoveryScope,e.sessionKey);r.set(t,this),this.claim={owners:r,key:t}}this.sessionKey=e.sessionKey,this.messageId=e.messageId,this.message=e.message,this.mentions=e.mentions,this.attachments=e.attachments,this.target=e.target,this.agentId=e.agentId,this.gatewayUrl=e.gatewayUrl,this.recoveryScope=e.recoveryScope,this.phase=e.phase,this.createParams=e.createParams,this.retryAllowed=!0,this.restored=t,this.persistent=n}}})))()}var Cs,ws;function Ts(){return(Ts=e((()=>{u(),se(),k(),Z(),s(),kt(),Q(),us(),ms(),ii(),vs(),Ss(),X(),Cs=[0,1e3,3e3],ws=class{static requiredPlacement(e,t){return!!e.requiredProfile&&!M(t)}constructor(e,t){this.read=e,this.callbacks=t,this.cloudProfilesValue=[],this.gatewayAuthorityValue=``,this.environmentsValue=null,this.cloudProfilesReadyValue=!1,this.catalogRetryingValue=!1,this.catalogRevalidationPending=!1,this.gatewaySource=null,this.gatewayClientValue=null,this.gatewayUrlValue=``,this.gatewayBootIdValue=``,this.gatewayRecoveryScopeValue=``,this.gatewayRecoveryScopeReady=!1,this.gatewayConnectedValue=!1,this.gatewayConnectionEpochValue=0,this.catalogRetryScope=``,this.catalogRetryAttempt=0,this.cloudProfileRetryAttempt=0,this.cloudProfileRefresh=null,this.gatewayNameValue=``,this.gatewayNameArgs=[],this.cloudProfileArgs=[],this.cloudProfileStatus=`initial`,this.cloudProfileComplete=Promise.resolve(),this.handleCatalogRetry=()=>{let{context:e,data:t}=this.read();if(!this.gatewayConnectedValue||t?.group&&e?.sessions.groupsStatus()===`loading`||!t?.startTerminal&&!rs(t,e?.sessions))return;if(this.catalogRetryingValue){this.catalogRevalidationPending=!0;return}t?.group&&e?.sessions.groupsInvalidate();let n=e?.revalidate(`new-session`);n&&(globalThis.clearTimeout(this.catalogRetryTimer),this.catalogRetryTimer=void 0,this.catalogRetryingValue=!0,this.catalogRevalidation=n,this.callbacks.changed(),n.catch(()=>void 0).then(()=>this.callbacks.updateComplete()).finally(()=>{this.catalogRetryingValue=!1,this.catalogRevalidationPending?(this.catalogRevalidationPending=!1,this.handleCatalogRetry()):this.retryPendingCatalogTarget(),this.callbacks.changed()}))},this.preferences=new Gt(()=>({source:this.gatewaySource,client:this.gatewayClientValue,gatewayUrl:this.gatewayUrlValue,recoveryScope:this.gatewayRecoveryScopeValue,bootId:this.gatewayBootIdValue,connected:this.gatewayConnectedValue,connectionEpoch:this.gatewayConnectionEpochValue,data:this.read().data,pendingPlacementSessionKey:this.read().pendingPlacement.sessionKey,agentsHydrated:this.read().agentsHydrated}),t)}synchronizeMetadata(){this.synchronizeGatewayName(),this.synchronizeCloudProfiles()}synchronizeGatewayName(){let e=this.read().isConnected&&this.gatewayConnectedValue?this.gatewaySource:null,t=gt(this.read().context?.gateway.snapshot)&&document.visibilityState!==`hidden`,n=[e,t,this.gatewayConnectionEpochValue];if(n.every((e,t)=>Object.is(e,this.gatewayNameArgs[t]))||(this.gatewayNameArgs=n,this.gatewayNameRequest?.abort(),this.gatewayNameRequest=void 0,this.gatewayNameValue=``,!e||!t))return;let r=new AbortController;this.gatewayNameRequest=r,$t(e,r.signal).then(({value:e})=>{r.signal.aborted||(this.gatewayNameValue=c(e.machineName)??c(e.hostname)?.split(`.`,1)[0]??``)}).catch(()=>void 0).finally(()=>{this.gatewayNameRequest===r&&(this.gatewayNameRequest=void 0,this.callbacks.changed())})}cloudProfileInput(){return[this.read().isConnected&&this.gatewayConnectedValue?this.gatewayClientValue:null,this.gatewayConnectionEpochValue,i(this.read().context?.gateway.snapshot.hello?.auth??null),this.read().isAdmin,this.gatewayRecoveryScopeValue,this.read().runtimeId,this.placementPolicy()]}synchronizeCloudProfiles(){let e=this.cloudProfileInput();e.every((e,t)=>Object.is(e,this.cloudProfileArgs[t]))||this.readCloudProfiles(e)}readCloudProfiles(e=this.cloudProfileInput()){this.cloudProfileArgs=e;let[t,n,r,i,a,o,s]=e,c={};if(this.cloudProfileRequest=c,this.cloudProfileStatus=t&&s?`pending`:`initial`,!t||!s)return this.callbacks.changed(),Promise.resolve();let l=s.requiredProfile,u=l||!r?Promise.resolve({profiles:l?.providerId?[{...l,providerId:l.providerId}]:[],environments:[],suggestedProfile:void 0}):fs(t,o).then(e=>({...e,profiles:e.profiles,suggestedProfile:i?e.suggestedProfile:void 0}));return this.cloudProfileComplete=u.then(e=>{this.cloudProfileRequest===c&&(this.cloudProfileStatus=`complete`,this.resetCloudProfileRetry(),this.environmentsValue=e.environments,this.applyCloudProfiles(e.profiles),this.suggestedProfileValue=e.profiles.length===0?e.suggestedProfile:void 0,this.cloudProfilesReadyValue=!0)}).catch(()=>{this.cloudProfileRequest===c&&(this.cloudProfileStatus=`error`,this.scheduleCloudProfileRetry())}).finally(()=>{this.cloudProfileRequest===c&&this.callbacks.changed()}),this.callbacks.changed(),this.cloudProfileComplete}retireCloudProfiles(){this.cloudProfileRequest=void 0,this.cloudProfileArgs=[],this.cloudProfileStatus=`initial`}get gatewayName(){return this.gatewayNameValue}get cloudProfiles(){return this.cloudProfilesValue}get suggestedProfile(){return this.suggestedProfileValue}async adoptSuggestedProfile(){let e=this.gatewayClientValue,t=this.gatewayConnectionEpochValue,n=this.sessionCreateScope;if(!e||!this.gatewayConnectedValue||!this.read().isAdmin||!this.suggestedProfileValue)return;let{profile:r}=await e.request(`environments.adoptSuggestedProfile`,{});if(e===this.gatewayClientValue&&t===this.gatewayConnectionEpochValue&&n===this.sessionCreateScope&&this.gatewayConnectedValue&&this.read().isAdmin)return this.readCloudProfiles(),this.applyCloudProfiles([r]),this.suggestedProfileValue=void 0,this.callbacks.changed(),r.id}placementPolicy(){return this.callbacks.readAgents()?.state.agentsList?.sessionPlacement}get requiredProfile(){return this.placementPolicy()?.requiredProfile?.id}get placementPolicyReady(){let e=this.placementPolicy();return e!==void 0&&(!e.requiredProfile||this.cloudProfilesReadyValue)}get environments(){return this.environmentsValue}get cloudProfilesReady(){return this.cloudProfilesReadyValue}get cloudProfilesRead(){return this.cloudProfileStatus===`initial`?void 0:this.cloudProfileComplete}get cloudProfilesPending(){return this.cloudProfileStatus===`pending`}get deviceCatalogDisabledReason(){return this.cloudProfilesReadyValue&&this.cloudProfileStatus===`complete`?void 0:O(`newSession.placementNotReady`)}get catalogRetrying(){return this.catalogRetryingValue}get catalogRetryRead(){return this.catalogRevalidation}get client(){return this.gatewayClientValue}get gatewayUrl(){return this.gatewayUrlValue}get recoveryScope(){return this.gatewayRecoveryScopeValue}get sessionCreateScope(){let e=[this.gatewayUrlValue,this.gatewayRecoveryScopeValue,this.gatewayBootIdValue];return e.every(Boolean)?JSON.stringify(e):``}get connected(){return this.gatewayConnectedValue}get connectionEpoch(){return this.gatewayConnectionEpochValue}get preferenceLoading(){return this.preferences.loading||this.identityPreferences?.mode===`loading`}refreshCloudProfiles(){if(this.cloudProfileStatus===`pending`){let e=this.cloudProfileRefresh??this.cloudProfileComplete.catch(()=>void 0).then(()=>{if(this.cloudProfileRefresh===e)return this.cloudProfileRefresh=null,this.refreshCloudProfiles()});return this.cloudProfileRefresh=e,e}return globalThis.clearTimeout(this.cloudProfileRetryTimer),this.cloudProfileRetryTimer=void 0,this.readCloudProfiles()}async retryRequiredPlacement(){await this.callbacks.readAgents()?.refreshList(),await this.refreshCloudProfiles()}synchronize(e){let t=e.snapshot,n=t.phase===`connected`,r=this.gatewaySource===null,i=n?t.hello?.server?.bootId?.trim()??``:this.gatewayBootIdValue,a=!r&&n&&!!this.gatewayBootIdValue&&i!==this.gatewayBootIdValue,o=!r&&this.gatewayUrlValue!==e.connection.gatewayUrl,s=!r&&this.gatewaySource!==e,c=n?JSON.stringify([t.selfUser?.id,t.hello?.auth?.role,t.hello?.auth?.scopes?.toSorted()]):this.gatewayAuthorityValue,l=!r&&this.gatewayAuthorityValue!==c,u=!r&&(s||this.gatewayClientValue!==t.client||l),d=!r&&this.gatewayConnectedValue!==n,f=n&&(u||!this.gatewayConnectedValue),p=n&&t.client?.recoveryScopeReady===!0&&!this.gatewayRecoveryScopeReady,m=n?t.hello?.auth?.recoveryScope??``:oe({client:t.client})??``,h=!r&&this.gatewayRecoveryScopeValue!==m;if(this.gatewayAuthorityValue=c,this.gatewaySource=e,this.gatewayClientValue=t.client,this.gatewayUrlValue=e.connection.gatewayUrl,this.gatewayBootIdValue=i,this.gatewayRecoveryScopeValue=m,this.gatewayRecoveryScopeReady=t.client?.recoveryScopeReady===!0,this.gatewayConnectedValue=n,o||a||u||d||h){let e=s||o||h||l,t=o||h;this.invalidateDiscovery(e,ys({gatewayIdentityChanged:t,placementDraftOwned:!!this.read().pendingPlacement.sessionKey}))}if(r||o||h||p||f){let e=this.read().pendingPlacement;e.gatewayUrl&&(e.gatewayUrl!==this.gatewayUrlValue||e.recoveryScope!==this.gatewayRecoveryScopeValue)&&this.callbacks.onPendingPlacementReset(),m&&(!n||t.client?.recoveryScopeReady)&&this.callbacks.onRecoveryReady(this.gatewayUrlValue,this.gatewayRecoveryScopeValue)}f&&(this.gatewayConnectionEpochValue+=1,!r&&this.read().data?.startTerminal?this.handleCatalogRetry():this.retryPendingCatalogTarget()),this.preferences.synchronize(),this.synchronizeIdentityPreferences(t.selfUser?.id),this.callbacks.changed()}invalidateDiscovery(e,t){this.cloudProfileRefresh=null,this.retireCloudProfiles(),this.cloudProfilesValue=[],this.suggestedProfileValue=void 0,this.cloudProfilesReadyValue=!1,e&&(this.environmentsValue=null),this.resetCloudProfileRetry(),this.callbacks.onInvalidate(e,t),this.callbacks.changed()}retryPendingCatalogTarget(){let{context:e,data:t}=this.read();if(this.catalogRetryingValue)return;if(t?.group&&e?.sessions.groupsStatus()===`loading`){globalThis.clearTimeout(this.catalogRetryTimer),this.catalogRetryTimer=void 0;return}if(!this.gatewayConnectedValue||!rs(t,e?.sessions)){globalThis.clearTimeout(this.catalogRetryTimer),this.catalogRetryTimer=void 0,this.catalogRetryScope=``,this.catalogRetryAttempt=0;return}let n=`${this.gatewayConnectionEpochValue}:${Xo(t)}`;if(this.catalogRetryScope!==n&&(globalThis.clearTimeout(this.catalogRetryTimer),this.catalogRetryTimer=void 0,this.catalogRetryScope=n,this.catalogRetryAttempt=0),this.catalogRetryTimer||this.catalogRetryAttempt>=Cs.length)return;let r=Cs[this.catalogRetryAttempt];this.catalogRetryAttempt+=1,this.catalogRetryTimer=globalThis.setTimeout(()=>{this.catalogRetryTimer=void 0;let e=this.read();if(this.catalogRetryScope!==n||!this.gatewayConnectedValue||e.data?.group&&e.context?.sessions.groupsStatus()===`loading`||!rs(e.data,e.context?.sessions))return;e.data?.group&&e.context?.sessions.groupsInvalidate();let t=e.context?.revalidate(`new-session`);t&&t.catch(()=>void 0).then(()=>this.callbacks.updateComplete()).then(()=>this.retryPendingCatalogTarget())},r)}get preferenceState(){return this.identityPreferences}savePalettePreference(e){let t=this.identityPreferences,n=this.read().context?.gateway.snapshot,r=n?.client,i=n?.hello,a=n?.selfUser?.id,o=this.gatewayUrlValue;return t?.setPalettePreference(e,()=>this.identityPreferences===t&&this.gatewayConnectedValue&&this.read().context?.gateway.snapshot.client===r&&this.read().context?.gateway.snapshot.hello===i&&this.read().context?.gateway.snapshot.selfUser?.id===a&&this.read().context?.gateway.connection.gatewayUrl===o)??Promise.resolve(!1)}readPreference(e){return this.preferences.readPreference(e)}capturePreferenceConsumption(e,t,n){if(this.callbacks.preferenceScope!==`palette`)return this.preferences.capturePreferenceConsumption(e,t,n)}persistPreference(e,t,n){if(this.callbacks.preferenceScope!==`palette`)return this.preferences.persistPreference(e,t,n)}disconnect(){this.preferences.disconnect(),this.stopPreferences?.(),this.stopPreferences=void 0,this.identityPreferences=void 0,this.cloudProfilesValue=[],this.suggestedProfileValue=void 0,this.cloudProfilesReadyValue=!1,this.environmentsValue=null,this.cloudProfileRefresh=null,this.gatewaySource=null,this.gatewayAuthorityValue=``,this.gatewayClientValue=null,this.gatewayConnectedValue=!1,this.gatewayConnectionEpochValue=0,this.catalogRetryScope=``,this.catalogRetryAttempt=0,globalThis.clearTimeout(this.catalogRetryTimer),this.catalogRetryTimer=void 0,this.gatewayNameRequest?.abort(),this.gatewayNameRequest=void 0,this.gatewayNameArgs=[],this.gatewayNameValue=``,this.retireCloudProfiles(),this.resetCloudProfileRetry()}applyCloudProfiles(e){let t=e.length>0&&!this.gatewayRecoveryScopeValue;this.cloudProfilesValue=t?[]:e;let n=this.read(),r=!!n.pendingPlacement.sessionKey,a=i(n.context?.gateway.snapshot.hello?.auth??null);(!this.gatewayConnectedValue||!a)&&!r&&this.callbacks.onCloudProfileCleared(),!r&&n.cloudProfileId&&!e.some(e=>e.id===n.cloudProfileId)?this.callbacks.onCloudState(O(`newSession.catalogUnavailable`)):t?this.callbacks.onCloudState(O(`newSession.cloudRecoveryUnavailable`)):this.callbacks.onCloudState(null)}resetCloudProfileRetry(){globalThis.clearTimeout(this.cloudProfileRetryTimer),this.cloudProfileRetryTimer=void 0,this.cloudProfileRetryAttempt=0}scheduleCloudProfileRetry(){if(this.cloudProfileRetryTimer||!this.gatewayConnectedValue||!this.gatewayClientValue||this.cloudProfileRetryAttempt>=ls.length)return;let e=ls[this.cloudProfileRetryAttempt];this.cloudProfileRetryAttempt+=1,this.cloudProfileRetryTimer=globalThis.setTimeout(()=>{this.cloudProfileRetryTimer=void 0,this.gatewayConnectedValue&&this.readCloudProfiles()},e)}synchronizeIdentityPreferences(e){let t=this.gatewayConnectedValue?this.gatewayClientValue:null,n=this.read().context,r=n?.gateway.snapshot.hello,i=n&&g(n.gateway.snapshot,`users.prefs.get`)===!0&&g(n.gateway.snapshot,`users.prefs.set`)===!0,a=this.callbacks.preferenceScope===`palette`&&t&&r&&e&&i?hs({client:t,hello:r,profileId:e,gatewayUrl:this.gatewayUrlValue}):void 0;if(a===this.identityPreferences||(this.stopPreferences?.(),this.stopPreferences=void 0,this.identityPreferences=a,!a))return;let o=()=>{this.identityPreferences===a&&this.callbacks.changed()};this.stopPreferences=a.subscribe(o,()=>this.identityPreferences===a&&this.gatewayConnectedValue&&this.read().context?.gateway.snapshot.client===t&&this.read().context?.gateway.snapshot.hello===r&&this.read().context?.gateway.connection.gatewayUrl===this.gatewayUrlValue),a.mode!==`loading`&&o()}}})))()}function Es(e){let t=e.replace(/[\\/]+$/u,``),n=Math.max(t.lastIndexOf(`/`),t.lastIndexOf(`\\`));if(n<0)return;let r=n===0?t.slice(0,1):t.slice(0,n);return Ae(r)||void 0}function Ds(e){return e.startsWith(`/`)||e.startsWith(`\\`)||/^[A-Za-z]:[\\/]/.test(e)}function Os(e){if(!Ds(e))return null;let t=e.trim().replaceAll(`\\`,`/`),n=/^[A-Za-z]:\//u.test(t)||t.startsWith(`//`),r=[],i=/^[A-Za-z]:\//u.test(t)?1:t.startsWith(`//`)?2:0;for(let e of t.split(`/`))e&&e!==`.`&&(e===`..`?r.length>i&&r.pop():r.push(e));let a=`${t.startsWith(`//`)?`//`:t.startsWith(`/`)?`/`:``}${r.join(`/`)}`.replace(/\/+$/u,``)||`/`;return n?a.toLowerCase():a}function ks(e,t){let n=Os(e);return n!==null&&n===Os(t)}function As(e,t){let n=Os(t);return n!==null&&e.some(e=>{let t=Os(e);return t!==null&&(n===t||n.startsWith(t===`/`?t:`${t}/`))})}function js(){return(js=e((()=>{})))()}function Ms(e){return e instanceof re&&e.gatewayCode===`INVALID_REQUEST`&&/^(?:Error:\s+)?(?:ENOENT|ENOTDIR):/u.test(e.message)}var Ns;function Ps(){return(Ps=e((()=>{ge(),Ns=class{constructor(e,t){this.read=e,this.callbacks=t,this.state=`none`,this.requestToken=0,this.approvedRoots=[]}knownWorkspaceRoots(e){return e?[e,...this.approvedRoots]:this.approvedRoots}recordApprovedListing(e){if(this.read().isAdmin)return;let t=new Set(this.approvedRoots);t.add(e.path),e.parent&&t.add(e.parent),t.size!==this.approvedRoots.length&&(this.approvedRoots=[...t],this.callbacks.onApprovedRootsChange())}reset(){this.cancel(),this.approvedRoots=[]}get blocked(){return this.state!==`none`}cancel(){this.requestToken+=1,this.state=`none`}restore(){this.state=`none`,this.callbacks.onMissing()}validate(e){let t=this.read().gateway,n=t?.client;if(t?.phase!==`connected`||!n){this.restore();return}let r=++this.requestToken;this.state=`checking`;let i=()=>{let t=this.read();return r===this.requestToken&&!t.selectedByUser&&t.folder===e};n.request(`fs.listDir`,{path:e}).then(e=>{i()&&(this.recordApprovedListing(e),this.state=`none`,this.callbacks.onVerified())}).catch(e=>{i()&&(!this.read().isAdmin||Ms(e)?this.restore():(this.state=`failed`,this.callbacks.onFailed()))})}}})))()}function Fs(e){if(!Ds(e))return null;let t=/^[A-Za-z]:[\\/]/u.test(e)?3:1,n=e.search(/[\\/]+$/u),r=n>=0?n:Math.max(e.lastIndexOf(`/`),e.lastIndexOf(`\\`));return{directory:e.slice(0,Math.max(t,r)),prefix:n>=0?``:e.slice(r+1)}}function Is(e,t){if(!t)return[...e];let n=t.toLowerCase(),r=[],i=[],a=[],o=[];for(let s of e){if(s.hidden&&!t.startsWith(`.`))continue;let e=s.name.toLowerCase();s.name===t?r.push(s):e===n?i.push(s):e.startsWith(n)?a.push(s):e.includes(n)&&o.push(s)}return[...r,...i,...a,...o]}function Ls(e){let{listing:t,draft:n,loading:r}=e,i=Fs(n);if(t&&ks(n,t.path)||!i){let e=t?.entries??[];return{entries:e,empty:t&&e.length===0&&!r?`no-subfolders`:`none`}}if(t&&ks(i.directory,t.path)){let e=Is(t.entries,i.prefix);return{entries:e,empty:e.length===0&&!r?i.prefix?`no-matches`:`no-subfolders`:`none`}}return{entries:[],empty:r?`none`:`no-matches`}}function Rs(){return(Rs=e((()=>{js()})))()}var zs;function Bs(){return(Bs=e((()=>{tt(),k(),Z(),Ps(),js(),Rs(),X(),zs=class{constructor(e,t,n){this.listDirectory=e,this.changed=t,this.onListing=n,this.listing=null,this.draft=``,this.loading=!1,this.readCompletion=null,this.error=null,this.activeIndex=-1,this.token=0}navigate(e,t=`navigation`){this.cancelPending(),this.draft=e??``,this.activeIndex=-1,this.error=null,this.loading=!0;let n=this.load(e,t,this.token);return this.readCompletion=n,this.changed(),n.then(()=>{})}setDraft(e){this.cancelPending(),this.draft=e,this.activeIndex=-1,this.error=null;let t=Fs(e.trim());if(this.loading=!(!t||this.draftInLoadedDirectory()),t&&this.loading){let e=this.token;this.readCompletion=new Promise(n=>{this.timer=globalThis.setTimeout(()=>{this.timer=void 0,this.load(t.directory,`typing`,e).then(n)},300)})}this.changed()}draftInLoadedDirectory(){if(!this.listing)return!1;let e=this.draft.trim(),t=Fs(e);return!t||ks(e,this.listing.path)||ks(t.directory,this.listing.path)}moveHighlight(e){let t=this.view().entries.length;t!==0&&(this.activeIndex=this.activeIndex<0?e===1?0:t-1:(this.activeIndex+e+t)%t,this.changed())}highlightedEntry(){return this.view().entries[this.activeIndex]}completeHighlighted(){let e=this.highlightedEntry()??this.view().entries[0];return!e||this.draft.trim()===e.path?!1:(this.setDraft(e.path),!0)}async activate(){let e=this.usablePath();e!==null&&await this.navigate(this.highlightedEntry()?.path??(e||void 0))}usablePath(){let e=this.draft.trim();return!e||Ds(e)?e:null}reset(){this.cancelPending(),this.listing=null,this.draft=``,this.loading=!1,this.error=null,this.activeIndex=-1}view(){let e=this.draft.trim();return Ls({listing:this.listing,draft:e,loading:this.loading})}cancelPending(){this.token+=1,globalThis.clearTimeout(this.timer),this.timer=void 0,this.readCompletion=null}async load(e,t,n){let r=this.draft;try{let i=await this.listDirectory(e);if(n!==this.token)return null;this.listing=i,t!==`typing`&&this.draft===r&&(this.draft=i.path),this.activeIndex=-1,this.onListing?.(i)}catch(r){if(n!==this.token)return null;if(t===`initial`&&e&&Ms(r))return this.draft=``,await this.load(void 0,`navigation`,n);if(t!==`typing`)return xa(r)?.missingScope?O(`newSession.browseRequiresAdmin`):O(`newSession.browserLoadFailed`)}finally{n===this.token&&(this.loading=!1,this.changed())}return null}}})))()}function Vs(e){let t=e.trim();return!t||t.startsWith(`-`)||/\s/u.test(t)?null:/^(?:https:\/\/|ssh:\/\/git@|git@[^:]+:)/iu.test(t)?t:null}function Hs(e){let t=e.folder.trim(),n=e.projects.find(t=>t.id===e.projectId),r=e.projectQuery.trim().toLowerCase().normalize(`NFC`);return{label:e.freshWorkspace?O(`newSession.newWorkspace`):n?n.displayName:e.selectedRemoteProject?.identity?e.selectedRemoteProject.identity:t?Ae(t):Ae(e.workspace)||O(`newSession.folderPlaceholder`),recents:r?[]:e.recents.filter(e=>e.kind!==`project`),showWorkspace:!r||Ae(e.workspace).toLowerCase().normalize(`NFC`).includes(r)}}function Us(){return(Us=e((()=>{k(),Z(),X()})))()}var Ws;function Gs(){return(Gs=e((()=>{h(),s(),Fr(),js(),Bs(),Us(),Ws=class{constructor(e,t,n){this.gateway=e,this.read=t,this.callbacks=n,this.projectFocus={},this.lastProjectResult=null,this.projectSelection=null,this.projectQueryValue=``,this.environmentQueryValue=``,this.debouncedProjectQuery=``,this.browserOpenValue=!1,this.browserNodeIdValue=``,this.browserProjectPathValue=null,this.browserRegistration=null,this.openPopoverValue=null,this.focusRequestId=0,this.projectSearchArgs=[],this.projectSearchReadValue=null,this.projectSearchRequest=so(()=>this.callbacks.changed(),{task:([e,t],{signal:n})=>e.request(`projects.searchRemote`,{query:t},{signal:n}),onComplete:e=>{this.finishProjectSearch?.({result:e}),this.finishProjectSearch=void 0},onError:e=>{this.finishProjectSearch?.({error:e}),this.finishProjectSearch=void 0}}),this.browser=new zs(e=>{let t=this.read().context?.gateway.snapshot;return t?.phase!==`connected`||!t.client||!this.browserOpenValue?Promise.reject(Error(`Folder browser is unavailable`)):t.client.request(`fs.listDir`,{...this.browserNodeIdValue?{nodeId:this.browserNodeIdValue}:{},...e?{path:e}:{}})},this.callbacks.changed,e=>{if(this.browserProjectPathValue=null,this.browserNodeIdValue)return;this.callbacks.onApprovedListing(e);let t=this.read(),n=t.context?.gateway.snapshot.client;t.isAdmin&&n&&n.request(`worktrees.branches`,{repoRoot:e.path,includeRepositoryStatus:!0}).then(t=>{this.browser.listing===e&&t.repositoryStatus===`git`&&(this.browserProjectPathValue=e.path,this.callbacks.changed())}).catch(()=>void 0)})}synchronize(){let e=this.browserRegistration;e&&(!this.gateway.connected||e.client!==this.gateway.client||e.epoch!==this.gateway.connectionEpoch)&&this.retireRegistration(),this.bindProjectCatalog();let t=this.projectSearchInput();t.every((e,t)=>Object.is(e,this.projectSearchArgs[t]))||this.searchProjects(t)}projectSearchInput(){return[this.read().context&&this.gateway.connected?this.gateway.client:null,f(this.read().context?.gateway.snapshot,`projects.searchRemote`,`operator.read`),this.debouncedProjectQuery,this.gateway.connectionEpoch]}searchProjects(e=this.projectSearchInput()){this.projectSearchArgs=e,this.projectSearchRequest.cancel(),this.finishProjectSearch?.(null),this.finishProjectSearch=void 0,this.projectSearchReadValue=null;let[t,n,r]=e;if(!t||!n||r.length<2||Vs(r))return;let i=Promise.withResolvers();this.projectSearchReadValue={query:r,completed:i.promise},this.finishProjectSearch=i.resolve,this.projectSearchRequest.run([t,r])}get projects(){return this.projectCatalog?.snapshot.result?.projects??[]}get projectsReady(){return this.projectCatalog?.snapshot.ready??!1}get projectCatalogError(){return this.projectCatalog?.snapshot.error??null}get projectsLoading(){return this.projectCatalog?.loading??!1}get projectRead(){return this.projectCatalog?.pendingRead??null}get projectRecents(){return this.projectCatalog?.snapshot.result?.recents}get githubHost(){return this.projectCatalog?.snapshot.result?.githubHost}get defaultRemoteProject(){let e=this.projectCatalog?.snapshot.result?.defaultRepository;return e?{identity:e.identity,cloneUrl:e.url,...e.ref?{defaultBranch:e.ref}:{}}:null}get defaultRemoteProjectProfileId(){return this.projectCatalog?.snapshot.result?.defaultRepository?.profileId??``}get projectId(){return this.projectSelection?.kind===`local`?this.projectSelection.id:``}get remoteProject(){return this.projectSelection?.kind===`remote`?this.projectSelection.project:null}get projectQuery(){return this.projectQueryValue}get environmentQuery(){return this.environmentQueryValue}changeEnvironmentQuery(e){this.environmentQueryValue=e,this.callbacks.changed()}get projectSearchRead(){return this.projectSearchReadValue?.query===this.projectQueryValue.trim()?this.projectSearchReadValue:null}get browserOpen(){return this.browserOpenValue}get browserNodeId(){return this.browserNodeIdValue}get browserProjectPath(){return this.browser.loading||!this.browser.draftInLoadedDirectory()?null:this.browserProjectPathValue}get browserRegistering(){return this.browserRegistration!==null}popoverOpen(e){return this.openPopoverValue===e}popoverCallbacks(e){return{popoverOpen:this.popoverOpen(e),onPopoverShow:()=>this.transitionPopover(e,!0),onPopoverHide:()=>this.transitionPopover(e,!1),onPopoverAfterHide:this.callbacks.changed}}bindProjectCatalog(){let e=this.gateway.connected?this.read().context?.gateway:void 0;if(e===this.projectCatalogGateway)return;this.projectCatalogCleanup?.(),this.projectCatalogGateway=e,this.projectCatalog=e?Or(e):void 0,this.lastProjectResult=null;let t=()=>{let e=this.projectCatalog?.snapshot.result??null;e&&e!==this.lastProjectResult&&(this.lastProjectResult=e,this.projectId&&!e.projects.some(e=>e.id===this.projectId)&&this.callbacks.onProjectMissing()),this.callbacks.changed()};this.projectCatalogCleanup=this.projectCatalog?.subscribe(t),t()}async refreshProjects(e=!1){this.bindProjectCatalog(),await this.projectCatalog?.refresh(e)}selectedProject(){return this.projects.find(e=>e.id===this.projectId)??(this.gateway.connected?void 0:this.selectedProjectRecord)}selectProject(e){this.projectSelection=e,this.selectedProjectRecord=this.projects.find(e=>e.id===this.projectId)}recordRemoteProjectId(e,t){let n=this.remoteProject;n?.cloneUrl===e&&(this.projectSelection={kind:`remote`,project:{...n,projectId:t}})}clearProjectSelection(){this.projectSelection=null,this.selectedProjectRecord=void 0}resolveProjectRecents(e){let t=t=>e.isAdmin||As(e.workspaceRoots,t),n=this.projectRecents?.filter(e=>e.kind===`project`?this.projects.some(t=>t.id===e.projectId):e.kind===`repository`||!e.execNode&&t(e.folder));if(n!==void 0)return n;let r=new Set;for(let n of e.sessions){let i=c(n.execCwd)??c(n.worktree?.repoRoot),a=c(n.execNode);if(i&&!a&&i!==e.workspace&&t(i)&&(r.add(i),r.size>=4))break}return Array.from(r,e=>({kind:`folder`,folder:e,displayName:Ae(e)}))}changeProjectQuery(e){this.projectQueryValue=e,this.clearProjectSearchTimer(),this.debouncedProjectQuery=``,this.searchProjects([null,!1,``,this.gateway.connectionEpoch]);let t=e.trim(),n=this.read().context;if(t.length<2||Vs(t)||!this.gateway.connected||!this.gateway.client||!n||!f(n.gateway.snapshot,`projects.searchRemote`,`operator.read`)){this.callbacks.changed();return}let r=this.gateway.client,i=this.gateway.connectionEpoch;this.projectSearchTimer=globalThis.setTimeout(()=>{this.projectSearchTimer=void 0,r===this.gateway.client&&i===this.gateway.connectionEpoch&&(this.debouncedProjectQuery=t,this.searchProjects([r,!0,t,i]),this.callbacks.changed())},300),this.callbacks.changed()}resetProjectSearch(){this.clearProjectSearchTimer(),this.projectQueryValue=``,this.debouncedProjectQuery=``,this.callbacks.changed()}resetProjects(e=!0){this.projectCatalog&&this.refreshProjects(!0),e&&(this.clearProjectSelection(),this.resetProjectSearch())}close(){this.resetBrowser(!0)}showRoot(){let e=this.browserOpenValue;this.resetBrowser(!1),e&&this.focusProjectView(`browse`)}selectGatewayBrowser(e){this.openBrowser(``,e)}selectDeviceBrowser(e,t){this.openBrowser(e,t)}openBrowser(e,t){this.browserOpenValue=!0,this.browserNodeIdValue=e,this.browserProjectPathValue=null,this.browser.navigate(t&&Ds(t)?t:void 0,`initial`),this.focusProjectView(`path`)}async registerBrowserProject(e,t){let n=this.read(),r=n.context?.gateway.snapshot,i=r?.client;if(r?.phase!==`connected`||!i||!n.isAdmin||this.browserProjectPath!==e||this.browserRegistering)return;let a=this.browser.listing,o=Promise.withResolvers(),s=this.gateway.connectionEpoch,c={retire:o.resolve,client:i,epoch:s};this.browserRegistration=c;let l=()=>this.gateway.connected&&this.browser.listing===a&&this.browserProjectPath===e&&i===this.gateway.client&&s===this.gateway.connectionEpoch,u=()=>this.browserRegistration===c&&l();this.browser.error=null,this.browser.readCompletion=null,this.callbacks.changed(),t?.({retired:o.promise,isCurrent:l});try{let t=await i.request(`projects.register`,{path:e});if(!u()||(await this.refreshProjects(!0),!u()))return;this.callbacks.onSelectProject(t.id),this.close()}catch(e){u()&&(this.browser.error=y(e))}finally{this.browserRegistration===c&&(this.browserRegistration=null,this.callbacks.changed())}}transitionPopover(e,t){t?(this.openPopoverValue=e,e===`where`&&(this.environmentQueryValue=``)):this.openPopoverValue===e&&(this.openPopoverValue=null),e===`project`?this.showRoot():this.callbacks.changed()}disconnect(){this.focusRequestId+=1,this.environmentQueryValue=``,this.browser.reset(),this.retireRegistration(),this.clearProjectSearchTimer(),this.projectCatalogCleanup?.(),this.projectCatalogCleanup=void 0,this.projectCatalogGateway=void 0,this.projectCatalog=void 0,this.searchProjects([null,!1,``,-1])}resetBrowser(e){this.focusRequestId+=1,this.browser.reset(),this.browserOpenValue=!1,this.browserNodeIdValue=``,this.browserProjectPathValue=null,this.retireRegistration(),e&&(this.openPopoverValue=null),this.callbacks.changed()}retireRegistration(){this.browserRegistration?.retire(),this.browserRegistration=null}clearProjectSearchTimer(){globalThis.clearTimeout(this.projectSearchTimer),this.projectSearchTimer=void 0}focusProjectView(e){let t=++this.focusRequestId,n=this.callbacks.activeElement();this.callbacks.updateComplete().then(()=>{if(t!==this.focusRequestId||this.openPopoverValue!==`project`)return;let r=this.callbacks.activeElement(),i=this.projectFocus[e];i?.isConnected&&(!r||r===n||r===r.ownerDocument.body)&&i.focus({preventScroll:!0})})}}})))()}function Ks(e){return e.available+(e.reclaimableIdle??0)}function qs(){return(qs=e((()=>{})))()}function Js(e){let t=e?.issues?.find(e=>e.code===`update-required`);return t?O(`newSession.nodeUpdateRequired`,{updateCommand:t.updateCommand,restartCommand:t.headlessReconnectCommand}):e?.issues?.find(e=>e.code===`worker-host-unavailable`)?.message}function Ys(e){if(e.connected)return;let t=e.environment;if(t?.lastConnectedAtMs===void 0)return O(`newSession.neverConnected`);if(t.lastDisconnectedAtMs!==void 0){let e=wn(Math.max(0,Date.now()-t.lastDisconnectedAtMs))??O(`common.justNow`);return O(`newSession.offlineFor`,{duration:e})}let n=t.lastSeenAtMs??t.lastConnectedAtMs;return O(`newSession.lastSeen`,{time:ze(n)})}function Xs(e,t={}){let n=Ys({environment:e,connected:t.connected??!0}),r=Js(e)??n,i=r?[r]:[];e?.platform&&i.push(Lt(e.platform));for(let t of Zs(e?.capabilities))if(i.includes(t)||i.push(t),i.length>=4)break;return i}function Zs(e=[]){return[...new Set(e.flatMap(e=>{let t=e.split(`.`,1)[0]?.toLowerCase(),n=Object.entries(Qs).find(([e])=>e===t)?.[1];return n?[O(n)]:[]}))]}var Qs;function $s(){return($s=e((()=>{k(),Z(),we(),ri(),ei(),X(),Qs={camera:`newSession.capabilityCamera`,location:`newSession.capabilityLocation`,talk:`newSession.capabilityTalk`,screen:`newSession.capabilityScreenCapture`,canvas:`newSession.capabilityCanvas`,microphone:`newSession.capabilityVoice`,voice:`newSession.capabilityVoice`}})))()}function ec(e,t,n){let r=new Map;for(let[n,i]of e.entries()){let e=t(i);r.set(e,[...r.get(e)??[],n])}let i=e.map(()=>void 0);for(let t of r.values()){if(t.length<2)continue;let r=n.at(-1);if(!r)continue;let a=n.find(n=>{let i=t.map(t=>n(e[t])??r(e[t]));return i.every(e=>e!==void 0)&&new Set(i).size===t.length})??r;for(let n of t)i[n]=a(e[n])??r(e[n])}return i}function tc(){return(tc=e((()=>{})))()}function nc(e,t){let n=Js(e);if(n!==void 0)return n;if(e.status!==`available`)return O(`newSession.deviceUnavailable`);if(e.sessionHost!==!0)return O(`newSession.sessionHostingDisabled`);if(t.requiredNodeCommands.length>0){let t=e.requiredNodeCommand;if(!t)return O(`newSession.placementNotReady`);if(t.state!==`invocable`&&t.message)return t.message;if(t.state===`pending-approval`)return O(`newSession.nodeCommandPendingApproval`,{command:t.command});if(t.state===`undeclared`)return O(`newSession.nodeCommandUndeclared`,{command:t.command});if(t.state===`unauthorized`)return O(`newSession.nodeCommandUnauthorized`,{command:t.command})}if(t.consumesWorkerSlot)return e.workerSlots?Ks(e.workerSlots)===0?O(`newSession.deviceNoSlots`):void 0:O(`newSession.deviceCapacityUnavailable`)}function rc(e,t=cc,n){let r=(e??[]).flatMap(e=>{if(e.type!==`node`||!e.id.startsWith(`node:`))return[];let r=e.id.slice(5).trim();if(!r)return[];let i=n??nc(e,t),a=Xs(e,{connected:e.status===`available`}),o=+((e.issues?.length??0)>0||e.status!==`available`),s=i&&!a.includes(i)?[...a.slice(0,o),i,...a.slice(o)].slice(0,4):a;return[{deviceId:r,label:e.label??r,platform:e.platform,hideDetails:!n&&e.status===`unavailable`&&!e.issues?.length,remediation:n?void 0:e.issues?.some(e=>e.code===`update-required`)?`update-device`:e.status===`available`&&e.sessionHost!==!0&&!e.issues?.length?`enable-session-hosting`:void 0,facts:n?[n]:s,workerSlots:e.workerSlots,workerHost:e.workerHost,capabilities:e.capabilities,invocableCommands:e.invocableCommands,selectable:i===void 0,...i?{disabledReason:i}:{}}]}).toSorted((e,t)=>e.label.localeCompare(t.label)||e.deviceId.localeCompare(t.deviceId)),i=ec(r,e=>e.label,[e=>e.deviceId.slice(0,8)]);return r.forEach((e,t)=>{let n=i[t];n&&(r[t]={...e,subtitle:n})}),r}function ic(e,t,n){if(n)return n;let r=new Set((e??[]).filter(e=>e.type===`node`&&e.sessionHost===!0).map(e=>e.id));if(r.size===0){let t=(e??[]).find(e=>e.issues?.some(e=>e.code===`update-required`||e.code===`worker-host-unavailable`));return t?nc(t,cc):O(`newSession.noSessionHosts`)}return t.some(e=>e.selectable)?void 0:t.find(e=>r.has(`node:${e.deviceId}`))?.disabledReason}function ac(e,t,n){let r=e.find(e=>e.deviceId===n.deviceId);return{ready:n.autoDevice?e.some(e=>e.selectable):!n.deviceId||r?.selectable===!0,disabledReason:n.autoDevice?ic(t,e):n.deviceId?r?.disabledReason??O(`newSession.nodeUnavailable`):void 0}}function oc(e,t){return!!(e&&t.some(t=>t.deviceId===e&&t.selectable&&t.workerHost?.deviceFolders===!0))}function sc(e,t){return t.find(t=>t.deviceId===e&&t.workerHost?.deviceFolders===!0&&t.invocableCommands?.includes(`fs.listDir`))}var cc;function lc(){return(lc=e((()=>{qs(),k(),Z(),$s(),X(),cc={requiredNodeCommands:[],consumesWorkerSlot:!0}})))()}function uc(e,t){return e.executionModes?.includes(t)===!0}function dc(e){return e.operatingSystems?.find(e=>e.default)?.id??e.operatingSystems?.[0]?.id??e.machines?.find(e=>e.os)?.os??``}function fc(e,t){return(e.machines??[]).filter(e=>!e.os||e.os===t)}function pc(e,t=dc(e)){let n=fc(e,t);return n.find(e=>e.default)??n.find(e=>n.every(t=>e.cpu!==void 0&&e.memoryGb!==void 0&&t.cpu!==void 0&&t.memoryGb!==void 0&&e.cpu<=t.cpu&&e.memoryGb<=t.memoryGb))??n[0]}function mc(){return(mc=e((()=>{})))()}var hc;function gc(){return(gc=e((()=>{hc=class{constructor(){this.overrides=new Map}clear(){this.overrides.clear()}applyPending(e,t,n){t||n?this.overrides.set(e,{machineClass:t,os:n}):this.overrides.delete(e)}resolve(e){return this.overrides.get(e)?.machineClass??``}resolveOs(e){return this.overrides.get(e)?.os??``}selection(e,t){let n=t.find(t=>t.id===e),r=this.resolveOs(e)||n&&dc(n)||``;return{machineClass:this.resolve(e)||n&&pc(n,r)?.id||``,os:r}}selectedOs(e){return this.resolveOs(e.id)||dc(e)}machines(e){return fc(e,this.selectedOs(e))}selectOs(e,t,n,r=!1,i){let a=n.find(t=>t.id===e),o=a?.operatingSystems?.find(e=>e.id===t);if(r||!a||!o||o.disabledReason)return!1;let s=this.resolve(e);return this.applyPending(e,fc(a,o.id).some(e=>e.id===s)?s:void 0,o.id),i?.(),!0}select(e,t,n,r=!1,i){let a=n.find(t=>t.id===e),o=a&&this.machines(a).find(e=>e.id===t);return r||!o?!1:(this.applyPending(e,o.id,this.selectedOs(a)),i?.(),!0)}}})))()}function _c(e){let t=e?.gateway?.github?.host?.trim().toLowerCase()||`github.com`;if(!/^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$/u.test(t)||t.includes(`..`))throw Error(`gateway.github.host must be a hostname`);return t}function vc(){return(vc=e((()=>{})))()}function yc(e){let t=e.split(`/`).filter(Boolean),n=t[0],r=t[1]?.replace(/\.git$/iu,``);return t.length!==2||!n||!r||!xc.test(n)||!xc.test(r)||n===`.`||n===`..`||r===`.`||r===`..`?null:{owner:n,repo:r}}function bc(e,t=_c()){let n=e.trim();if(!n||n.startsWith(`-`)||n.includes(`\0`)||/[\r\n\t ]/u.test(n))return null;let r=`git@${t}:`,i=n.toLowerCase().startsWith(r)?n.slice(r.length):void 0,a;if(i!==void 0)a=yc(i);else{let e=URL.parse(n);if(!e)return null;let r=e.protocol===`https:`,i=e.protocol===`ssh:`&&e.username===`git`&&(!e.port||e.port===`22`);if(!r&&!i||e.hostname.toLowerCase()!==t||e.password||r&&e.username||e.search||e.hash)return null;a=yc(e.pathname)}return a?{url:`https://${t}/${a.owner.toLowerCase()}/${a.repo.toLowerCase()}.git`,name:a.repo}:null}var xc;function Sc(){return(Sc=e((()=>{vc(),xc=/^[A-Za-z0-9_.-]+$/u})))()}function Cc(){return{deviceId:``,autoDevice:!1,cloudProfileId:``,freshWorkspace:!0,folderSelectedByUser:!1,preferredWhereRestore:null,preferredProjectRestore:``,preferredRemoteProjectRestore:null,configuredDefaultRepositoryPending:!1,configuredDefaultRepositoryOptOut:!1,whereSelectedByUser:!1,projectSelectedByUser:!1,requiredModelDefaults:!1}}function wc(e,t,n,r,i){let a=e.preferredWhereRestore??rt(e);return{workspace:r,folder:i,projectId:e.preferredProjectRestore||t.projectId,remoteProject:e.preferredRemoteProjectRestore??t.remoteProject,defaultRepositoryOptOut:e.configuredDefaultRepositoryOptOut,where:a,worktree:(a.kind!==`local`||n.preferenceWorktree)&&!n.remoteRepository,freshWorkspace:e.freshWorkspace,baseRef:n.baseRef,worktreeName:n.worktreeName}}function Tc(e,t){return!e.folderSelectedByUser&&!e.whereSelectedByUser&&!e.projectSelectedByUser&&!t.hasUserSelection}function Ec(e,t){e.projectSelectedByUser=!0,e.preferredProjectRestore=``,e.preferredRemoteProjectRestore=null,e.configuredDefaultRepositoryPending=!1,e.configuredDefaultRepositoryOptOut=t}function Dc(e,t,n,r){let i=n||r;if(!e.whereSelectedByUser){let n=i?void 0:t?.where;e.preferredWhereRestore=n?.kind===`local`?null:n??null}e.preferredProjectRestore=i?``:t?.projectId??``,e.preferredRemoteProjectRestore=i?null:t?.remoteProject??null,e.configuredDefaultRepositoryOptOut=t?.defaultRepositoryOptOut===!0,e.configuredDefaultRepositoryPending=!i&&!e.configuredDefaultRepositoryOptOut&&!t?.projectId&&!t?.remoteProject,e.preferredRemoteProjectRestore&&(e.preferredProjectRestore=``),e.projectSelectedByUser=!1}function Oc(e,t,n,r=!1){return r||t&&!(e.configuredDefaultRepositoryPending&&n)&&e.preferredWhereRestore===null&&!e.preferredProjectRestore&&!e.preferredRemoteProjectRestore}function kc(e){let{state:t,browser:n,gateway:r,modelControl:i,repositoryState:a,isAdmin:o,persistPreference:s,changed:c}=e;if(t.requiredModelDefaults!==e.requiredPlacement&&(t.requiredModelDefaults=e.requiredPlacement,e.loadConfiguredDefaults(e.requiredPlacement)),e.requiredPlacement){(n.browserOpen||[`where`,`project`,`checkout`].some(e=>n.popoverOpen(e)))&&n.close();return}let l=!1,u=t.whereSelectedByUser?null:t.preferredWhereRestore,d=t.projectSelectedByUser?``:t.preferredProjectRestore,f=t.preferredRemoteProjectRestore,p=n.remoteProject;if((f||p)&&n.projectsReady&&n.githubHost){let e=e=>bc(e.cloneUrl,n.githubHost)!==null,r=f&&!e(f),i=p&&!e(p);(r||i)&&(r&&(t.preferredRemoteProjectRestore=null),i&&(n.clearProjectSelection(),t.projectSelectedByUser=!1),(i||r&&!p&&!n.projectId)&&a.clearDetails(!0),t.configuredDefaultRepositoryPending=!t.configuredDefaultRepositoryOptOut&&!d,s({remoteProject:t.preferredRemoteProjectRestore??n.remoteProject??null}),l=!0)}let m=n.defaultRemoteProject,h=n.defaultRemoteProjectProfileId,g=h?r.cloudProfiles.find(e=>e.id===h):void 0,_=!!(m&&t.preferredRemoteProjectRestore?.cloneUrl===m.cloneUrl),v=t.configuredDefaultRepositoryPending||_,y=v&&n.projectsReady&&(!h||r.cloudProfilesReady),b=!!(y&&(!h||o()&&g&&!i.cloudRuntimeUnsupportedReason(g))),x=t.projectSelectedByUser||!n.projectsReady?null:_?b?t.preferredRemoteProjectRestore:null:t.preferredRemoteProjectRestore??(b?m:null);if(y&&(t.configuredDefaultRepositoryPending=!1,_&&!b&&(t.preferredRemoteProjectRestore=null,l=!0),c()),x){let r=v&&x.cloneUrl===m?.cloneUrl;h&&r&&b&&!t.whereSelectedByUser&&!u&&e.where.kind===`local`&&(t.deviceId=``,t.autoDevice=!1,t.cloudProfileId=h),n.selectProject({kind:`remote`,project:x}),t.freshWorkspace=!1,t.folderSelectedByUser=!1,(r&&!_||!a.baseRef&&x.defaultBranch)&&a.setDetail(`baseRef`,x.defaultBranch??``,!1),t.preferredRemoteProjectRestore=null,l=!0}if(d&&!x){let e=n.projects.find(e=>e.id===d);e&&(n.selectProject({kind:`local`,id:e.id}),t.folderSelectedByUser=!1),(e||n.projectsReady)&&(t.preferredProjectRestore=``,l=!0)}if(u&&u.kind!==`local`&&r.cloudProfilesReady){if(u.kind===`cloud`){let e=r.cloudProfiles.find(e=>e.id===u.id);o()&&e&&!i.cloudRuntimeUnsupportedReason(e)?(t.deviceId=``,t.autoDevice=!1,t.cloudProfileId=u.id):(t.cloudProfileId=``,s({where:{kind:`local`}}))}else t.autoDevice=u.kind===`auto-device`,t.deviceId=u.kind===`device`?u.id:``,t.cloudProfileId=``;t.preferredWhereRestore=null,l=!0}l&&(a.synchronize(),c())}function Ac(){return(Ac=e((()=>{Sc(),zt()})))()}function jc(e){if(e.remoteProject)return{kind:`pending-clone`,cloneUrl:e.remoteProject.cloneUrl};if(e.selectedProject&&!e.selectedProject.repoRoot)return e.selectedProject.source===`workspace`?{kind:`idle`}:{kind:`pending-project`,projectId:e.selectedProject.id};let t=e.selectedProject?.repoRoot??(e.folder.trim()||e.workspace);return t?!e.selectedProject&&t===e.workspace&&!e.workspaceGit?{kind:`direct`,repoRoot:t}:{kind:`checking`,repoRoot:t}:{kind:`idle`}}var Mc;function Nc(){return(Nc=e((()=>{ne(),tt(),D(),Mc=class{get checkoutRead(){return this.checkoutReadValue}get repositoryRead(){return this.repositoryReadValue}constructor(e,t){this.read=e,this.callbacks=t,this.worktreeValue=!1,this.details={worktreeName:``},this.repositoryValue={kind:`idle`},this.requestToken=0,this.selectionRevision=0,this.preferredWorktreeRestore=!1,this.worktreeSelectedByUser=!1,this.selectedDetails=new Set}matchesProjectCheckout(){let{selectedProject:e,agentId:t,remotePlacement:n}=this.read();return n||!e?!this.checkoutScope:this.checkoutScope?.project===e&&this.checkoutScope.agentId===t}get currentCheckoutUnavailable(){let e=this.read();if(!e.selectedProject||e.remotePlacement)return;let t=this.checkoutOptions;return!this.matchesProjectCheckout()||!t||t===`loading`?`checking`:t===`error`?`unavailable`:t.current?void 0:t.worktree?`worktree`:`unavailable`}get checkoutSubmissionBlocked(){if(!this.read().selectedProject||this.read().remotePlacement)return!1;let e=this.checkoutOptions;return!this.matchesProjectCheckout()||!e||typeof e==`string`||!(this.worktreeValue?e.worktree:e.current)}synchronizeProjectCheckout(){this.matchesProjectCheckout()||this.load()}get worktree(){return this.worktreeValue}get preferenceWorktree(){return this.worktreeValue||this.preferredWorktreeRestore}get worktreeName(){return this.details.worktreeName}get baseRef(){return this.details.baseRef??``}get remoteRepository(){let{remotePlacement:e,remoteProject:t}=this.read();if(!e||!t)return;let n=this.baseRef.trim();return{url:t.cloneUrl,...n?{ref:n}:{}}}get repository(){return this.repositoryValue}get preferenceReady(){return!this.preferredWorktreeRestore}get hasUserSelection(){return this.worktreeSelectedByUser||this.selectedDetails.size>0}adoptPreference(e){if(this.worktreeSelectedByUser||(this.worktreeValue=!1,this.preferredWorktreeRestore=e?.worktree===!0&&(!e.where||e.where.kind===`local`)),!this.selectedDetails.has(`baseRef`)){let t=e?.baseRef||void 0;this.details.baseRef!==t&&(this.selectionRevision+=1),this.details.baseRef=t}if(!this.selectedDetails.has(`worktreeName`)){let t=e?.worktreeName??``;this.details.worktreeName!==t&&(this.selectionRevision+=1),this.details.worktreeName=t}this.matchesCurrentRepo()?this.repositoryValue.kind!==`checking`&&this.adoptResolvedRepository(this.repositoryValue):this.invalidate()}reset(){this.invalidate(),this.worktreeValue=!1,this.clearDetails(),this.preferredWorktreeRestore=!1,this.worktreeSelectedByUser=!1}clearDetails(e=!1){this.selectionRevision+=1,this.details.baseRef=void 0,this.details.worktreeName=``,this.selectedDetails.clear(),e&&this.callbacks.persistPreference({baseRef:``,worktreeName:``})}invalidate(){this.requestToken+=1,this.repositoryValue={kind:`idle`},this.checkoutScope=void 0,this.checkoutOptions=void 0,this.checkoutReadValue=void 0,this.repositoryReadValue=void 0}selectWorktree(e,t=!0){this.selectionRevision+=1,this.preferredWorktreeRestore=!1,this.worktreeSelectedByUser=!0,this.worktreeValue=e,t&&this.clearDetails(!0)}rejectPreferredWorktree(){this.preferredWorktreeRestore=!1,this.worktreeValue=!1,this.clearDetails(!0)}select(e){return this.worktreeValue===e||this.read().remotePlacement||(e?!this.available():this.currentCheckoutUnavailable)?!1:(this.selectWorktree(e,!1),this.callbacks.persistPreference({folder:this.read().folder.trim()||this.read().workspace,worktree:this.worktreeValue}),this.callbacks.changed(),!0)}setDetail(e,t,n){n||(this.selectionRevision+=1,this.details[e]=t,this.selectedDetails.add(e),this.callbacks.persistPreference({[e]:t}),this.callbacks.changed())}captureSubmittedName(e,t){let n=e.worktreeName?.trim();if(!e.worktree||!n)return;let r=this.selectionRevision,i=this.read(),a=T(t.agentId),o=i.agents.find(e=>T(e.id)===a),s={agentId:a,workspace:c(o?.workspace)??``},l=s.agentId===i.agentId,u=this.callbacks.capturePreferenceConsumption(s,{worktreeName:n,...t.recovered?{}:{selectedBaseRef:this.details.baseRef?.trim()??``},folder:e.cwd??(l&&i.folder.trim()||s.workspace),baseRef:e.worktreeBaseRef??(l?this.baseRef:void 0),projectId:e.projectId??(l?i.selectedProject?.id:void 0)});return u&&(()=>u(()=>{s.agentId===this.read().agentId&&r===this.selectionRevision&&n===this.details.worktreeName.trim()&&(this.selectionRevision+=1,this.details.worktreeName=``,this.selectedDetails.add(`worktreeName`),this.callbacks.changed())}))}available(){let e=this.read();if(e.selectedProject&&!e.remotePlacement){let e=this.checkoutOptions;return this.matchesProjectCheckout()&&e!==void 0&&typeof e!=`string`&&e.worktree}let t=this.repositoryValue;return t.kind===`git`||t.kind===`pending-clone`||t.kind===`pending-project`}matchesCurrentRepo(){let e=this.read(),t=this.repositoryValue;if(!this.matchesProjectCheckout())return!1;if(t.kind===`pending-project`)return!e.remoteProject&&!e.selectedProject?.repoRoot&&e.selectedProject?.id===t.projectId;if(t.kind===`pending-clone`)return e.remoteProject?.cloneUrl===t.cloneUrl;if(t.kind===`idle`||e.remoteProject)return!1;let n=e.selectedProject?.repoRoot??(e.folder.trim()||e.workspace);return t.repoRoot===n}load(){let e=++this.requestToken,t=this.read();if(this.checkoutScope=t.selectedProject&&!t.remotePlacement?{project:t.selectedProject,agentId:t.agentId}:void 0,this.checkoutOptions=this.checkoutScope?`loading`:void 0,this.checkoutReadValue=void 0,this.repositoryReadValue=void 0,this.checkoutScope&&t.gateway?.phase===`connected`&&t.gateway.client){let n=t.gateway.client.request(`projects.checkoutOptions`,{projectId:this.checkoutScope.project.id,agentId:this.checkoutScope.agentId});this.checkoutReadValue={completed:n},n.then(t=>{e===this.requestToken&&this.matchesProjectCheckout()&&(this.checkoutOptions=t,this.reconcileCheckoutChoice(),this.callbacks.changed())}).catch(()=>{e===this.requestToken&&(this.checkoutOptions=`error`,this.callbacks.changed())})}let n=jc(t);if(n.kind!==`checking`)return this.adoptResolvedRepository(n);let r=t.gateway?.client;if(t.gateway?.phase!==`connected`||!r)return this.adoptResolvedRepository({kind:`idle`});let{repoRoot:i}=n;this.repositoryValue=n;let a=r.request(`worktrees.branches`,{repoRoot:i,includeRepositoryStatus:!0});this.repositoryReadValue={completed:a},a.then(t=>{e===this.requestToken&&this.adoptResolvedRepository(t?.repositoryStatus===`git`?{kind:`git`,repoRoot:i,branches:t.branches,...t.defaultBranch?{defaultBranch:t.defaultBranch}:{},...t.headBranch?{headBranch:t.headBranch}:{},...t.branchesUnavailable?{branchesUnavailable:!0}:{}}:{kind:t?.repositoryStatus===`not_git`?`direct`:`unavailable`,repoRoot:i})}).catch(t=>{if(e!==this.requestToken)return;let n=xa(t);this.adoptResolvedRepository(n||t instanceof ue&&t.gatewayCode===`FORBIDDEN`?{kind:`forbidden`,repoRoot:i,...n?{missingScope:n.missingScope}:{}}:{kind:`unavailable`,repoRoot:i})})}synchronize(){this.matchesCurrentRepo()||this.load()}reconcileCheckoutChoice(){let e=this.checkoutOptions;this.matchesProjectCheckout()&&e&&typeof e!=`string`&&!this.read().remotePlacement&&!(this.worktreeValue?e.worktree:e.current)&&(e.current||e.worktree)&&(this.worktreeValue=e.worktree,this.preferredWorktreeRestore=!1,this.callbacks.persistPreference({worktree:this.worktreeValue}))}adoptResolvedRepository(e){if(this.repositoryValue=e,e.kind===`direct`&&(!this.read().selectedProject||this.read().remotePlacement)){let e=this.worktreeValue||this.preferredWorktreeRestore;this.worktreeValue=!1,e&&!this.read().remotePlacement&&this.callbacks.persistPreference({worktree:!1})}else this.preferredWorktreeRestore&&!this.worktreeSelectedByUser&&(this.worktreeValue=!0);this.preferredWorktreeRestore=!1,this.reconcileCheckoutChoice(),this.callbacks.changed()}}})))()}function Pc(){return{catalog:[],hasSnapshot:!1,status:`idle`}}function Fc(e){let{agent:t,defaults:n,catalog:r,modelSelectionPolicy:i}=e;return $(i?.restricted?i.defaultModel:t?.model?.primary??n?.model,i?.restricted||t?.model?.primary?void 0:n?.modelProvider,r)}function Ic(e){return($(e.model,void 0,e.catalog,e.agentRuntime)?.entry??Fc(e)?.entry)?.cyberAccessProgramDefault}function Lc(e){let{model:t,selection:n,metadata:r,agent:i,defaults:a}=e,o=r.modelSelectionPolicy,s=o?.restricted?o.defaultModel??void 0:i?.model?.primary,c=Fc({agent:i,defaults:a,catalog:r.catalog,modelSelectionPolicy:o}),l=$(t,void 0,r.catalog,n.agentRuntime),u=l?.entry??c?.entry,d=n.contextWindow||u?.contextWindowDefault,f=Mt(Rc(c,o?.restricted?void 0:i),o?.restricted?void 0:a,r.catalog),p={hasSnapshot:i!==void 0&&r.hasSnapshot,initialized:!r.retired&&(r.initialized??r.hasSnapshot),refreshFailed:r.refreshFailed,pendingProviders:r.pendingProviders,modelSelectionPolicy:o,retired:r.retired,status:!i&&r.status!==`error`?`loading`:r.status};return{defaultTarget:c,accessProgramDefault:u?.cyberAccessProgramDefault,agentDefaultModel:s,modelCatalogState:p,contextWindowTarget:u?.contextWindows&&d?{contextWindow:d,contextWindows:u.contextWindows,...u.contextWindowDefault?{contextWindowDefault:u.contextWindowDefault}:{}}:void 0,fastModeTarget:{agentRuntime:u?.agentRuntime,model:l?.model??c?.model,modelProvider:l?.provider??c?.provider??void 0,fastMode:n.fastMode,effectiveFastMode:n.fastMode??u?.effectiveFastMode},thinkingDefaults:{modelProvider:c?.provider??null,model:c?.model??null,contextTokens:o?.restricted?null:a?.contextTokens??null,agentRuntime:f?.agentRuntime,thinkingLevels:f?.thinkingLevels,thinkingDefault:f?.thinkingDefault},thinkingSession:Rc(l,void 0,n)}}function Rc(e,t,n){let r=n?.agentRuntime?e?.entry:void 0;return{model:e?.model??t?.model?.primary,modelProvider:e?.provider??void 0,agentRuntime:t?.agentRuntime??e?.entry?.agentRuntime,thinkingLevels:t?.thinkingLevels??r?.thinkingLevels,thinkingOptions:t?.thinkingOptions,thinkingDefault:t?.thinkingDefault??r?.thinkingDefault,thinkingLevel:n?.thinkingLevel||void 0}}function $(e,t,n,r){let i=zi(e,t,n);if(!i)return null;let a=i.toLowerCase(),o=n.find(e=>Nn(e.id,e.provider).toLowerCase()===a);if(o)return{entry:Gr(o,r),model:o.id,provider:mr(o.provider)||null};let s=i.indexOf(`/`);return{model:s>0?i.slice(s+1):i,provider:mr(s>0?i.slice(0,s):t??``)||null}}function zc(e){let{metadata:t,agent:n}=e;if(!t.hasSnapshot||t.status===`offline`)return;let r=t.modelSelectionPolicy,i=e.model||(r?.restricted?r.defaultModel??void 0:n?.model?.primary);return e.agentRuntime?$(i,void 0,t.catalog,e.agentRuntime)?.entry?.unavailableReason:Hi(i,void 0,t.catalog)}function Bc(e,t,n){let r=$(e.model,void 0,t,n);return r?.entry?.available===!0&&r.entry.manualSelectionAllowed!==!1&&r.provider===e.provider}function Vc(e){let{metadata:t,model:n,agentRuntime:r}=e;if(t.retired||e.initialModelPending||!t.hasSnapshot&&(n||r))return O(t.status===`error`?`chat.modelControls.modelsUnavailable`:`chat.modelControls.loadingModels`);if(t.modelSelectionPolicy?.restricted&&!n&&!t.modelSelectionPolicy.defaultModel)return O(t.catalog.length?`chat.modelControls.selectionRequired`:`chat.modelControls.noPermittedModels`);let i=n||r?$(n,void 0,t.catalog,r)?.entry:void 0;if(r&&t.hasSnapshot&&!i||n&&i?.manualSelectionAllowed===!1)return O(`chat.modelControls.modelsUnavailable`);if(r&&i?.available===!1)return ji(zc(e))??O(`chat.modelControls.modelsUnavailable`);let a=ji(zc(e),!n&&!r&&!e.accountSelected?e.inference:void 0);if(e.accountSelected){if(t.status===`error`)return O(`chat.modelControls.modelsUnavailable`);if(e.metadataPending||!t.hasSnapshot)return O(`chat.modelControls.loadingModels`);if(!e.accountReady)return a??O(`chat.modelControls.modelsUnavailable`)}return a}function Hc(e){if(e.retired)return;let t=e.modelSelectionPolicy,n=e.model||(t?.restricted?t.defaultModel??``:``),r;n?r=$(n,void 0,e.catalog,e.agentRuntime)?.entry?.agentRuntime:t?.restricted||(r=Fc(e)?.entry?.agentRuntime??e.agent?.agentRuntime??e.defaults?.agentRuntime);let i=r?.id.trim();if(r&&i&&i!==`auto`&&i!=="default")return i===r.id?r:{...r,id:i}}function Uc(e){let t=e.model.trim(),n=t?$(t,void 0,e.catalog,e.agentRuntime):null;if(t&&(!n?.entry||n.entry.available===!1||n.entry.manualSelectionAllowed===!1))return e.agentRuntime&&e.agentRuntime!==`openclaw`?{model:t,agentRuntime:e.agentRuntime,thinkingLevel:e.thinkingLevel,fastMode:e.fastMode,repaired:!1}:{model:``,thinkingLevel:``,repaired:!0};let r=n?.entry?Nn(n.entry.id,n.entry.provider):``,i=e.modelSelectionPolicy,a=i?.restricted?void 0:e.agent,o=i?.restricted?void 0:e.defaults,s=r?null:Fc(e),c=(n??s)?.provider,l=n?.entry??s?.entry,u=l?.supportsFastMode??(!c||Dn(c))?e.fastMode:void 0,d={model:r,...r&&e.agentRuntime?{agentRuntime:e.agentRuntime}:{},fastMode:u},f=u!==e.fastMode;if(!e.thinkingLevel)return{...d,thinkingLevel:``,repaired:f};let p=Mt(Rc(n??s,r?void 0:a,{agentRuntime:e.agentRuntime}),r?void 0:o,e.catalog)?.thinkingLevels,m=Vt(e.thinkingLevel),h=p?.some(e=>Vt(e.id)===m);return l?.reasoning===!1||p!==void 0&&!h?{...d,thinkingLevel:``,repaired:!0}:{...d,thinkingLevel:e.thinkingLevel,repaired:f}}function Wc(e){return e&&!e.devicePlacement?O(`newSession.deviceRuntimeUnsupported`):void 0}function Gc(e,t){return e?.cloudPlacementSupported===!1?O(`newSession.cloudRuntimeUnsupported`,{runtime:e.id}):e&&t&&e.cloudPlacementExecutionMode&&!uc(t,e.cloudPlacementExecutionMode)?O(`newSession.cloudProfileRuntimeUnsupported`,{runtime:e.id}):void 0}function Kc(){return(Kc=e((()=>{k(),ci(),Z(),Ce(),xt(),$r(),X(),ke()})))()}function qc(e,t,n){let r=new Map;for(let i of e){let e=Nn(i.id,i.provider);for(let a of[i.agentRuntime,...(i.runtimeChoices??[]).map(e=>e.agentRuntime)]){if(a?.workspaceEnvironment?.kind!==`provider-hosted`)continue;let o=Gr(i,a.id),s=n&&o?.available===!0&&o.manualSelectionAllowed!==!1;(!r.get(a.id)?.model||s&&e===t)&&r.set(a.id,{id:a.id,label:a.workspaceEnvironment.label,...s?{model:e}:{disabledReason:O(`newSession.hostedUnavailable`)}})}}return[...r.values()]}function Jc(e,t){let n=$(t,void 0,e),r=n&&e.find(e=>e.id===n.model&&e.provider===n.provider);if(!r)return;let i=[r,...r.runtimeChoices??[]].find(e=>e.agentRuntime&&!e.agentRuntime.workspaceEnvironment&&e.available===!0&&e.manualSelectionAllowed!==!1);return i?.agentRuntime?{model:Nn(r.id,r.provider),runtime:i.agentRuntime}:void 0}function Yc(e){return e.hostEnvironmentRuntime()?.runtime??e.resolveAgentRuntime()}function Xc(e){return e.hostEnvironmentDisabledReason()??Wc(Yc(e))}function Zc(e,t){return e.hostEnvironmentDisabledReason()??Gc(Yc(e),t)}function Qc(){return(Qc=e((()=>{k(),Z(),Ce(),Kc(),X()})))()}var $c;function el(){return(el=e((()=>{Qc(),$c=class{constructor(e,t,n,r){this.gateway=e,this.place=t,this.read=n,this.callbacks=r,this.adoption=null}get pending(){return this.adoption!==null}cancel(){this.adoption?.resolve(),this.adoption=null}canSelect(e){let t=this.read(),n=this.gateway.cloudProfiles.find(t=>t.id===e);return!t.submitting&&!t.pendingPlacementSessionKey&&!this.place.requiredPlacement&&n!==void 0&&!Zc(this.place.modelControl,n)}async adopt(e){let t=this.read();if(this.pending||t.submitting||t.pendingPlacementSessionKey||this.place.requiredPlacement||!this.place.isAdmin()||!this.gateway.suggestedProfile||Zc(this.place.modelControl))return;let n=Promise.withResolvers();this.adoption=n,this.callbacks.onError(null),this.callbacks.changed();let r=this.settle(n);return e?.({completion:r,retired:n.promise,isCurrent:()=>this.adoption===n,reportError:e=>{this.adoption===n&&(this.callbacks.onError(e instanceof Error?e.message:String(e)),this.callbacks.changed())}}),r}async settle(e){try{let t=await this.gateway.adoptSuggestedProfile();this.adoption===e&&t&&this.place.selectCloudProfile(t)}catch(t){this.adoption===e&&this.callbacks.onError(t instanceof Error?t.message:String(t))}finally{this.adoption===e&&(this.cancel(),this.callbacks.changed())}}}})))()}function tl(e,t){let n=e.read();!e.place.deviceFolderAvailable||n.submitting||n.pendingPlacementSessionKey||(t(),e.selection.freshWorkspace=!1,e.selection.folderSelectedByUser=!0,Ec(e.selection,!0),e.browser.resetProjectSearch(),e.folderValidation.cancel(),e.browser.clearProjectSelection(),e.repositoryState.reset(),e.browser.close(),e.callbacks.changed())}function nl(e,t,n=!1){let r=e.read();e.place.requiredPlacement||r.submitting||r.pendingPlacementSessionKey||e.place.hostedEnvironment&&(t||n)&&Xc(e.modelControl)||e.modelControl.selectHostEnvironment()&&(t&&e.place.devices().find(e=>e.deviceId===t)?.selectable!==!0||n&&!e.place.devices().some(e=>e.selectable)||(e.place.suggestedCloudProfile.cancel(),e.selection.whereSelectedByUser=!0,e.selection.preferredWhereRestore=null,t===e.selection.deviceId&&n===e.selection.autoDevice&&!e.selection.cloudProfileId?(e.browser.close(),e.callbacks.changed()):(e.folderValidation.cancel(),e.clearDeviceFolder(),e.selection.deviceId=t,e.selection.autoDevice=n,e.selection.cloudProfileId=``,e.persistPreference({where:rt({cloudProfileId:``,deviceId:t,autoDevice:n}),projectId:e.browser.projectId,folder:e.place.folder,worktree:!!(t||n)||e.place.worktree,freshWorkspace:e.selection.freshWorkspace}),e.browser.close(),e.repositoryState.synchronize(),e.callbacks.changed())))}function rl(e,t){e.place.suggestedCloudProfile.canSelect(t)&&e.modelControl.selectHostEnvironment()&&(e.place.suggestedCloudProfile.cancel(),e.clearDeviceFolder(),e.selection.cloudProfileId=t,e.selection.deviceId=``,e.selection.autoDevice=!1,e.selection.whereSelectedByUser=!0,e.selection.preferredWhereRestore=null,e.callbacks.onError(null),e.persistPreference({where:{kind:`cloud`,id:t},projectId:e.browser.projectId,worktree:!0,freshWorkspace:e.selection.freshWorkspace}),e.repositoryState.synchronize(),e.callbacks.changed())}function il(e,t){!e.read().submitting&&e.repositoryState.select(t)&&t&&e.selection.freshWorkspace&&(e.selection.freshWorkspace=!1,e.persistPreference({freshWorkspace:!1}))}function al(){return(al=e((()=>{Ac(),Qc(),zt()})))()}var ol;function sl(){return(sl=e((()=>{ol=class{constructor(){this.hostIdValue=`gateway:local`,this.initialized=!1}get hostId(){return this.hostIdValue}get onNode(){return this.hostIdValue.startsWith(`node:`)}select(e,t,n){t||(this.initialized=!0,e!==this.hostIdValue&&(this.hostIdValue=e,n()))}synchronize(e,t){!this.initialized&&e?.length&&t(e.find(e=>e.hostId===this.hostIdValue)?.hostId??e[0].hostId)}reset(){this.hostIdValue=`gateway:local`,this.initialized=!1}}})))()}var cl;function ll(){return(ll=e((()=>{xt(),$r(),Kc(),cl=class{selectHostedEnvironment(e){let t=this.hostedEnvironments().find(t=>t.id===e);return t?.model?(this.selectModel(t.model,e),!0):!1}selectHostEnvironment(){if(!this.resolveAgentRuntime()?.workspaceEnvironment)return!0;let e=this.hostEnvironmentRuntime();return e?(this.selectModel(e.model,qn(e.runtime)),!0):!1}devicePlacementUnsupportedReason(){return Wc(this.resolveAgentRuntime())}autoPlacementSelectionMode(e=this.resolveAgentRuntime()){return e?.cloudPlacementExecutionMode===`remote-exec`?`eligible-order`:`least-busy`}cloudRuntimeUnsupportedReason(e){return Gc(this.resolveAgentRuntime(),e)}constructor(e,t){this.onSelectionChange=e,this.changed=t,this.selectionOrigin=`none`,this.fastModeSelected=!1,this.selectionGeneration=0,this.restoringPreference=!1,this.selected=``,this.contextWindow=``,this.thinkingLevel=``,this.listeners=b(),this.notify=()=>{this.listeners.publish(),this.changed()},this.subscribe=this.listeners.subscribe,this.selectThinkingLevel=e=>{this.selectionGeneration+=1,this.restoringPreference=!1,this.thinkingLevel=e,this.markExplicitSelection(),this.persistSelection(),this.onDraftSelectionChange?.(),this.notify()},this.selectFastMode=e=>{this.selectionGeneration+=1,this.restoringPreference=!1,this.fastModeSelected=!0,this.fastMode=Sn(e),this.persistSelection(),this.notify()},this.selectAccessProgram=(e,t,n)=>{this.selectionGeneration+=1,this.restoringPreference=!1,this.cyberAccessProgram=e,e===`standard`?n&&(this.daybreakAccessProgram=n):this.daybreakAccessProgram=e,this.markExplicitSelection(),this.onSelectionChange({cyberAccessProgram:e,...this.daybreakAccessProgram===void 0?{}:{daybreakAccessProgram:this.daybreakAccessProgram}}),this.onDraftSelectionChange?.(),this.notify()}}initializeAccessProgram(){let e=this.accessProgramForSubmission();this.cyberAccessProgram===void 0&&e!==void 0&&(this.cyberAccessProgram=e,this.onSelectionChange({cyberAccessProgram:e}))}resetSelection(e=``){this.selected=e,this.agentRuntime=void 0,this.contextWindow=``,this.thinkingLevel=``,this.fastMode=void 0,this.cyberAccessProgram=void 0,this.daybreakAccessProgram=void 0,this.selectionOrigin=`none`,this.fastModeSelected=!1}applyModelSelection(e){let t=this.selected!==e.model||this.agentRuntime!==e.agentRuntime||this.thinkingLevel!==e.thinkingLevel||this.fastMode!==e.fastMode;return this.selected=e.model,this.agentRuntime=e.agentRuntime,this.thinkingLevel=e.thinkingLevel,this.fastMode=e.fastMode,t}draftSelection(e){return this.selectionOrigin===`none`?void 0:{agentId:e,model:this.selected,agentRuntime:this.agentRuntime,thinkingLevel:this.thinkingLevel,cyberAccessProgram:this.cyberAccessProgram,daybreakAccessProgram:this.daybreakAccessProgram}}preferenceForDraft(e,t){let n=this.fastModeSelected||e===void 0?this.fastMode:e?.fastMode;if(this.selectionOrigin!==`none`)return{model:this.selected,agentRuntime:this.agentRuntime,thinkingLevel:this.thinkingLevel,cyberAccessProgram:this.cyberAccessProgram??e?.cyberAccessProgram,daybreakAccessProgram:this.daybreakAccessProgram??e?.daybreakAccessProgram,fastMode:n};let r={cyberAccessProgram:e?.cyberAccessProgram,daybreakAccessProgram:e?.daybreakAccessProgram};return t.initialModel?{...r,model:t.initialModelPending?t.initialModel:this.selected,agentRuntime:this.agentRuntime,thinkingLevel:this.thinkingLevel,fastMode:n}:t.policy===`configured`||t.policy===null?{fastMode:n,...r}:this.fastModeSelected?{...e,fastMode:n}:e}takeDraftSelection(e,t,n){let r=this.pendingDraftSelection;if(t&&r&&r.agentId===e&&(this.pendingDraftSelection=void 0,this.selectionOrigin!==`explicit`))return this.selectionOrigin=`restored`,this.selected=r.model,this.agentRuntime=r.agentRuntime,this.thinkingLevel=r.thinkingLevel,this.cyberAccessProgram=r.cyberAccessProgram,this.daybreakAccessProgram=r.daybreakAccessProgram,this.fastModeSelected||(this.fastMode=n??this.fastMode),{...r,fastMode:this.fastMode}}markExplicitSelection(){this.selectionOrigin=`explicit`}retireModelSelection(e){return e&&this.selectionOrigin!==`restored`?!1:(this.selectionOrigin=`none`,e||(this.fastModeSelected=!1),this.pendingDraftSelection=void 0,this.selected=``,this.agentRuntime=void 0,this.thinkingLevel=``,this.cyberAccessProgram=void 0,this.daybreakAccessProgram=void 0,this.contextWindow=``,!0)}restoreModelPreference(e,t,n){if(!e)return!1;let r=Uc({model:e.model??``,agentRuntime:e.agentRuntime,thinkingLevel:e.thinkingLevel??``,fastMode:e.fastMode,...t}),i=this.cyberAccessProgram!==e.cyberAccessProgram;this.cyberAccessProgram=e.cyberAccessProgram,this.daybreakAccessProgram=e.daybreakAccessProgram;let a=this.applyModelSelection(r)||i;return r.repaired&&n&&this.persistSelection(e.agentRuntime?this.agentRuntime??``:void 0),a}selectModelIntent(e,t,n,r){let i=Uc({model:e,agentRuntime:t,thinkingLevel:this.thinkingLevel,fastMode:this.fastMode,...n});if(i.model===r&&i.agentRuntime===this.agentRuntime&&i.fastMode===this.fastMode&&Vt(i.thinkingLevel)===Vt(this.thinkingLevel))return!1;let a=this.agentRuntime!==i.agentRuntime;this.applyModelSelection(i),this.markExplicitSelection();let o=$(i.model,void 0,n.catalog,this.agentRuntime)??Fc(n);return this.contextWindow=``,{target:o,runtimeChanged:a}}persistSelection(e=this.agentRuntime){this.onSelectionChange({model:this.selected,...e===void 0?{}:{agentRuntime:e},thinkingLevel:this.thinkingLevel,fastMode:this.fastMode,...this.cyberAccessProgram===void 0?{}:{cyberAccessProgram:this.cyberAccessProgram},...this.daybreakAccessProgram===void 0?{}:{daybreakAccessProgram:this.daybreakAccessProgram}})}}})))()}function ul(){let e;return t=>{let n=[t.model,t.agentRuntime,t.catalog,t.retired,t.agent?.model?.primary,t.agent?.agentRuntime,t.defaults?.model,t.defaults?.modelProvider,t.defaults?.agentRuntime,t.modelSelectionPolicy?.restricted,t.modelSelectionPolicy?.defaultModel];if(e?.inputs.every((e,t)=>e===n[t]))return e.value;let r=Hc(t);return e={inputs:n,value:r},r}}function dl(){return(dl=e((()=>{Kc()})))()}var fl;function pl(){return(pl=e((()=>{he(),se(),k(),Ce(),Pr(),ro(),An(),D(),gn(),Ui(),Q(),Qc(),ll(),Kc(),zt(),dl(),fl=class extends cl{constructor(e,t=()=>void 0,n=()=>void 0){super(t,e),this.onCatalogTargetSelect=n,this.initialModelPending=!1,this.agentId=``,this.metadataState=Pc(),this.pendingSelectionGeneration=0,this.resolveRuntime=ul(),this.configuredDefaults=!1,this.catalogTargets=new cs(this.notify),this.metadataReader=new bo(()=>{if(this.metadataClient&&this.metadataScope&&!this.ownsMetadata(this.metadataClient,this.metadataScope))this.restoringPreference=!1,this.draftAccount=void 0,this.clearMetadataSubscription(),this.updateMetadataState({catalog:[],hasSnapshot:!1,status:`offline`});else if(this.metadataReader.pending){let e=this.metadataReader.snapshot;e.retired?this.metadataState={catalog:[],hasSnapshot:!1,retired:!0,status:`loading`}:e.hasSnapshot&&!this.metadataState.hasSnapshot&&this.assignMetadataCatalog(e,!0),this.updateMetadataState({...this.metadataState,status:this.metadataState.hasSnapshot&&this.metadataState.status===`ready`?`ready`:`loading`})}else this.notify()},{timeoutMs:fe,onRead:e=>{this.metadataRead=e},onResult:e=>{if(this.ownsMetadata()){if(this.assignMetadataCatalog(e),this.metadataState.accountSelection=e.accountSelection,!this.draftAccount&&this.pendingSelectionGeneration===this.selectionGeneration&&(this.initialModelPending&&!e.modelSelectionPolicy?.restricted?this.resetSelection(this.initialModel):this.restorePreference()),this.initialModelPending=!1,!this.draftAccount&&e.modelSelectionPolicy?.restricted&&this.selected){let t=Uc({model:this.selected,agentRuntime:this.agentRuntime,thinkingLevel:this.thinkingLevel,fastMode:this.fastMode,modelSelectionPolicy:e.modelSelectionPolicy,catalog:e.models});this.applyModelSelection(t)}this.restoringPreference=!1,this.notify()}},onError:()=>{this.ownsMetadata()&&(!this.metadataState.retired&&!this.metadataState.modelSelectionPolicy?.restricted&&!this.draftAccount&&this.pendingSelectionGeneration===this.selectionGeneration&&(this.initialModelPending?(this.resetSelection(this.initialModel),this.initialModelPending=!1):this.pendingPreference&&(this.selected=this.pendingPreference.model??``,this.agentRuntime=this.pendingPreference.agentRuntime,this.thinkingLevel=this.pendingPreference.thinkingLevel??``,this.fastMode=this.pendingPreference.fastMode,this.cyberAccessProgram=this.pendingPreference.cyberAccessProgram)),this.restoringPreference=!1,this.updateMetadataState({...this.metadataState,status:`error`}))}})}get catalog(){return this.metadataState.catalog}get effectiveModel(){return this.draftAccount?.model??this.selected}clearMetadataSubscription(){this.metadataReader.clear(),this.metadataRead=void 0,this.metadataScope=void 0,this.metadataGateway=void 0}ownsMetadata(e=this.metadataClient,t=this.metadataScope){let n=this.pendingContext?.gateway.snapshot;return!!(e&&t&&this.metadataClient===e&&this.metadataGateway===this.pendingContext?.gateway&&this.metadataScope===t&&n?.phase===`connected`&&n.client===e&&n.hello===this.metadataHello&&n.selfUser?.id===this.metadataIdentityId)}bindMetadataSubscription(e,t){if(this.metadataScope&&this.metadataClient===e&&this.metadataGateway===this.pendingContext?.gateway&&this.metadataScope.agentId===t.agentId&&this.metadataScope.authProfileId===t.authProfileId)return this.metadataScope;this.clearMetadataSubscription(),this.metadataClient=e,this.metadataScope=t;let n=this.pendingContext?.gateway;return this.metadataGateway=n,n&&this.metadataReader.bind(n,t),t}loadCatalogTargets(e,t,n){this.catalogTargets.load(e,t,n)}updateMetadataState(e){this.metadataState={...e,initialized:!e.retired&&e.status!==`offline`&&(e.hasSnapshot||di(this.metadataClient))},this.notify()}assignMetadataCatalog(e,t=!1){this.metadataState={...this.metadataState,catalog:e.models,displayOnly:t,...Vi(e)}}selectDraftAccount(e,t){let n=this.metadataClient;if(!n||!t)return Promise.resolve(!1);this.selectionGeneration+=1,this.restoringPreference=!1,this.draftAccount={authProfileId:e.authProfileId,provider:e.provider,model:t};let r={agentId:this.agentId,authProfileId:e.authProfileId};this.metadataState={catalog:[],accountSelection:this.metadataState.accountSelection,hasSnapshot:!1,status:`loading`};let i=this.bindMetadataSubscription(n,r);return this.metadataReader.read().then(e=>!!e&&this.ownsMetadata(n,i))}clearDraftAccount(){return this.draftAccount?(this.draftAccount=void 0,this.clearMetadataSubscription(),this.metadataState=Pc(),!0):!1}invalidate(e=!1){!e&&this.metadataClient&&Tr(this.metadataClient,this.metadataScope),this.clearDraftAccount(),this.clearMetadataSubscription(),this.catalogTargets.clear(),this.restoringPreference=!1,e?(this.pendingDraftSelection=void 0,this.agentId=``,this.metadataClient=void 0,this.resetSelection(),this.initialModel=void 0,this.initialModelPending=!1,this.updateMetadataState(Pc())):this.updateMetadataState({...this.metadataState,status:this.metadataState.hasSnapshot?this.metadataState.status:`idle`})}reset(){this.resolveRuntime=ul(),this.invalidate(!0)}load(e,t,n,r={}){let i=e?.gateway.snapshot,a=i?.client,o=t.trim()?T(t):``;if(this.pendingContext=e,(this.agentId!==o||this.metadataClient&&this.metadataClient!==a||this.metadataGateway&&this.metadataGateway!==e?.gateway||this.metadataIdentityId!==i?.selfUser?.id||this.metadataHello&&this.metadataHello!==i?.hello)&&(this.draftAccount=void 0,this.clearMetadataSubscription(),this.agentId!==o&&(this.resetSelection(),this.initialModel=void 0,this.initialModelPending=!1),this.agentId=o,this.metadataClient=void 0,this.metadataState=Pc()),this.metadataIdentityId=i?.selfUser?.id,this.metadataHello=i?.hello,!e||i?.phase!==`connected`||!a||!o||!n){this.clearDraftAccount(),this.clearMetadataSubscription(),this.metadataClient=void 0,this.restoringPreference=!1,e&&i?.phase!==`connected`&&(this.metadataState={catalog:[],hasSnapshot:!1,status:`offline`}),this.notify();return}this.configuredDefaults=r.configuredDefaults===!0;let s=r.initialModel;s&&s!==this.initialModel&&(this.resetSelection(),this.selectionGeneration+=1,this.initialModel=s,this.initialModelPending=!0);let c=this.selectionGeneration,l={agentId:o,...this.draftAccount?{authProfileId:this.draftAccount.authProfileId}:{}},u=this.metadataScope,d=this.bindMetadataSubscription(a,l)!==u;this.pendingPreference=this.preferenceForDraft(r.preference,{policy:this.modelDefaultsPolicy,initialModel:this.initialModel,initialModelPending:this.initialModelPending}),this.pendingAgent=r.agent,this.pendingSelectionGeneration=c,this.applyPendingDraftSelection(),this.restoringPreference=!this.draftAccount&&Pt(this.pendingPreference),this.metadataReader.pending?this.notify():!d&&this.metadataState.status!==`idle`?(this.metadataState.status===`ready`&&this.metadataState.hasSnapshot&&!this.draftAccount&&this.pendingSelectionGeneration===this.selectionGeneration&&this.restorePreference(),this.restoringPreference=!1):this.metadataReader.read()}isRestoringPreference(){return this.restoringPreference}requiresModelSetup(e){return ct({...e,modelCatalogState:{...this.metadataState,initialized:this.metadataState.hasSnapshot&&!this.metadataState.retired}})}modelSelectionBlockedReason(e,t){let n=this.resolveAgentRuntime({agent:e,context:this.pendingContext});return Vc({model:this.effectiveModel,agentRuntime:this.agentRuntime,metadata:this.metadataState,agent:e,initialModelPending:this.initialModelPending,accountSelected:!!this.draftAccount,accountReady:this.accountSelectionReady(),metadataPending:this.metadataReader.pending,inference:n?.id===`openclaw`&&n.cloudPlacementExecutionMode===`worker-turn`?t:void 0})}accessProgramForSubmission(){return this.cyberAccessProgram??(this.ownsMetadata()&&this.metadataState.status===`ready`?Ic({model:this.effectiveModel,agentRuntime:this.agentRuntime,agent:this.pendingAgent,defaults:this.pendingContext?.sessions.state.result?.defaults,...this.metadataState}):void 0)}modelForSubmission(){return this.draftAccount?`${this.draftAccount.model}@${this.draftAccount.authProfileId}`:this.selected}accountSelectionReady(){if(!this.draftAccount)return!0;let e=this.metadataState.accountSelection;return!this.ownsMetadata()||this.metadataReader.pending||this.metadataState.status!==`ready`||e?.kind!==`personal`||e.authProfileId!==this.draftAccount.authProfileId?!1:Bc(this.draftAccount,this.catalog,this.agentRuntime)}restorePreference(){let e=this.metadataState.modelSelectionPolicy;this.restoreModelPreference(this.pendingPreference,{agent:this.pendingAgent,defaults:this.pendingContext?.sessions.state.result?.defaults,modelSelectionPolicy:e,catalog:this.catalog},!this.initialModelPending&&!e?.restricted&&this.modelDefaultsPolicy!==`configured`&&this.modelDefaultsPolicy!==null)&&this.notify()}restoreDraftSelection(e){this.pendingDraftSelection=e,e||this.retireDraftSelection(!0),this.applyPendingDraftSelection()}retireDraftSelection(e=!1){this.retireModelSelection(e)&&(this.pendingSelectionGeneration=++this.selectionGeneration,this.pendingPreference={fastMode:this.fastMode},!e&&this.clearDraftAccount()&&this.load(this.pendingContext,this.agentId,!0,{agent:this.pendingAgent}),this.notify())}get modelDefaultsPolicy(){return this.configuredDefaults?`configured`:this.pendingContext?.config?.current.newSessionModelDefaults}applyPendingDraftSelection(){let e=this.takeDraftSelection(this.agentId,this.modelDefaultsPolicy===`configured`,this.pendingPreference?.fastMode);e&&(this.selectionGeneration+=1,this.initialModelPending=!1,this.pendingPreference=e,this.pendingSelectionGeneration=this.selectionGeneration,this.metadataState.status===`ready`&&this.restorePreference(),this.notify())}resolveAgentRuntime(e={agent:this.pendingAgent,context:this.pendingContext}){return this.resolveRuntime({model:this.effectiveModel,agentRuntime:this.agentRuntime,agent:e.agent,defaults:e.context?.sessions.state.result?.defaults,catalog:this.metadataState.displayOnly?[]:this.catalog,modelSelectionPolicy:this.metadataState.modelSelectionPolicy,retired:this.metadataState.retired})}selectModel(e,t){this.selectionGeneration+=1,this.initialModelPending=!1,this.restoringPreference=!1;let n=this.selectModelIntent(e,t,{agent:this.pendingAgent,defaults:this.pendingContext?.sessions.state.result?.defaults,catalog:this.catalog,modelSelectionPolicy:this.metadataState.modelSelectionPolicy},this.effectiveModel);if(n===!1)return;let{target:r,runtimeChanged:i}=n;this.metadataState.displayOnly=!1,this.draftAccount&&this.draftAccount.provider!==r?.provider?(this.clearDraftAccount(),this.load(this.pendingContext,this.agentId,!0,{agent:this.pendingAgent})):this.draftAccount&&r&&(this.draftAccount={...this.draftAccount,model:Nn(r.model,r.provider)}),this.persistSelection(i?this.agentRuntime??``:void 0),this.onDraftSelectionChange?.(),this.notify()}hostedEnvironmentsLoading(){return!this.metadataState.hasSnapshot&&this.metadataState.status!==`error`}hostedEnvironments(){return qc(this.catalog,this.effectiveModel||this.pendingAgent?.model?.primary||``,this.metadataState.status===`ready`&&!this.metadataState.retired&&!this.metadataState.displayOnly)}hostEnvironmentDisabledReason(){return this.resolveAgentRuntime()?.workspaceEnvironment&&!this.hostEnvironmentRuntime()?O(`newSession.hostModelRequired`):void 0}hostEnvironmentRuntime(){return this.metadataState.retired||this.metadataState.displayOnly||!this.resolveAgentRuntime()?.workspaceEnvironment?void 0:Jc(this.catalog,this.effectiveModel||this.pendingAgent?.model?.primary)}get metadataReadScope(){return this.metadataScope}renderProps(e){let t=e.context?.gateway.snapshot,n=`new-session:${T(e.agentId)}`,r=e.context?.sessions.state.result??null,a=e.agent!==void 0,{defaultTarget:o,...s}=Lc({model:this.effectiveModel,selection:this,metadata:this.metadataState,agent:e.agent,defaults:r?.defaults}),c=t?.client,l=this.metadataScope,u=this.metadataState.accountSelection,d=()=>!!(c&&l&&this.ownsMetadata(c,l)&&this.metadataState.accountSelection===u);return{...s,renderAccountSection:n=>yi({owner:this,client:c,selection:d()&&t?.selfUser?u:void 0,model:n,disabled:e.sending||!n||!i(t?.hello?.auth??null),ownsSelection:d,onSelect:e=>d()?this.selectDraftAccount(e,n):Promise.resolve(!1),onAutomatic:this.draftAccount?()=>{d()&&(this.selectionGeneration+=1,this.clearDraftAccount(),this.load(e.context,e.agentId,!0,{agent:e.agent}))}:void 0,onManage:()=>e.context?.navigate(`profile`)}),activeRunId:null,connected:t?.phase===`connected`,gatewayAvailable:!!t?.client,loading:!1,modelCatalog:this.catalog,modelOverrides:{[n]:this.effectiveModel||null},modelPickerTargetGroups:this.catalogTargets.groups(),modelSwitching:!1,sending:e.sending,sessionKey:n,selectedSession:void 0,requestedAccessProgram:this.cyberAccessProgram??(this.ownsMetadata()&&this.metadataState.status===`ready`?s.accessProgramDefault:void 0),daybreakAccessProgram:this.daybreakAccessProgram,selectedAgentRuntime:this.agentRuntime,sessionsResult:a?r:null,stream:null,onModelSelect:(e,t,n)=>{this.selectModel(e,n??void 0)},onModelPickerTargetSelect:(e,t)=>{e===`cliAgents`&&this.onCatalogTargetSelect(t)},onModelPickerTargetRetry:e=>{e===`cliAgents`&&this.catalogTargets.retry(this.metadataClient,this.agentId)},onThinkingSelect:this.selectThinkingLevel,onAccessProgramSelect:this.selectAccessProgram,onFastModeSelect:this.selectFastMode,onContextWindowSelect:e=>{this.selectionGeneration+=1,this.restoringPreference=!1,this.contextWindow=e,this.notify()},onModelSetup:()=>e.context?.navigate(`model-setup`),onProviderSettings:t=>wi(e.context,e.agentId,t),onModelPickerOpen:()=>{let e=this.metadataClient,t=this.metadataScope;!this.metadataReader.pending&&e&&t&&this.metadataReader.read(),this.catalogTargets.retry(e,this.agentId)}}}}})))()}var ml;function hl(){return(hl=e((()=>{se(),k(),Z(),Ve(),D(),Q(),lc(),gc(),Ts(),Ac(),Nc(),el(),al(),sl(),Ps(),pl(),js(),zt(),X(),ml=class{get terminalHostId(){return this.terminalHost.hostId}get terminalOnNode(){return this.terminalHost.onNode}selectTerminalHost(e){this.terminalHost.select(e,this.read().submitting,()=>{this.folderValidation.cancel(),this.browser.clearProjectSelection(),this.repositoryState.reset(),this.folderValue=this.terminalOnNode?``:this.workspacePath(),this.selection.folderSelectedByUser=!0,this.terminalOnNode||this.repositoryState.load(),this.callbacks.changed()})}synchronizeTerminalHosts(){this.terminalHost.synchronize(this.read().data?.terminalHosts,e=>this.selectTerminalHost(e))}get deviceFolder(){return this.deviceFolderValue!==null&&this.deviceId?{deviceId:this.deviceId,path:this.deviceFolderValue}:void 0}get deviceFolderAvailable(){return this.deviceFolderOffered&&!this.deviceFolderRuntimeUnsupportedReason}get deviceFolderRuntimeUnsupportedReason(){return this.devicePlacementRuntime()?.cloudPlacementExecutionMode===`worker-turn`?void 0:O(`newSession.deviceFolderRuntimeUnsupported`)}get deviceFolderOffered(){return oc(this.deviceId,this.devices())}selectDeviceFolder(){tl(this.targetActions(),()=>{this.deviceFolderValue=``})}setDeviceFolderPath(e){this.deviceFolderValue===null||this.read().submitting||this.read().pendingPlacementSessionKey||(this.deviceFolderValue=e,this.callbacks.changed())}constructor(e,t,n,r){this.gateway=e,this.browser=t,this.read=n,this.callbacks=r,this.terminalHost=new ol,this.agentIdValue=``,this.folderValue=``,this.deviceFolderValue=null,this.cloudMachines=new hc,this.agentsHydrated=!1,this.agentSelectedByUser=!1,this.routeModelIntentActive=!0,this.selection=Cc(),this.suggestedCloudProfile=new $c(e,this,n,r),this.folderValidation=new Ns(()=>({gateway:this.read().context?.gateway.snapshot,folder:this.folderValue,selectedByUser:this.selection.folderSelectedByUser,isAdmin:this.isAdmin()}),{onApprovedRootsChange:r.changed,onVerified:()=>{this.callbacks.onClearError(O(`newSession.browserLoadFailed`)),this.repositoryState.load()},onMissing:()=>{this.callbacks.onClearError(O(`newSession.browserLoadFailed`)),this.folderValue=this.workspacePath(),this.repositoryState.rejectPreferredWorktree(),this.persistPreference({folder:this.folderValue,worktree:!1}),this.repositoryState.load()},onFailed:()=>this.callbacks.onError(O(`newSession.browserLoadFailed`))}),this.repositoryState=new Mc(()=>({agentId:this.agentIdValue,agents:this.agents(),remotePlacement:this.remotePlacement,selectedProject:this.browser.selectedProject(),remoteProject:this.browser.remoteProject,folder:this.folderValue,workspace:this.workspacePath(),workspaceGit:this.selectedAgent()?.workspaceGit===!0,gateway:this.read().context?.gateway.snapshot}),{changed:r.changed,persistPreference:e=>this.persistPreference(e),capturePreferenceConsumption:(e,t)=>this.gateway.capturePreferenceConsumption(e.agentId,e.workspace,t)}),this.modelControl=new fl(r.changed,e=>this.persistPreference(e),e=>this.read().context?.navigate(`new-session`,{search:pr(this.agentIdValue,{catalogId:e})}))}get agentId(){return this.agentIdValue}get folder(){return this.folderValue}get hostedEnvironment(){return this.requiredPlacement||M(this.read().data)?void 0:this.modelControl.resolveAgentRuntime()?.workspaceEnvironment}selectHostedEnvironment(e){let t=this.read();t.submitting||t.pendingPlacementSessionKey||!this.canWrite()||this.requiredPlacement||M(t.data)||this.modelControl.selectHostedEnvironment(e)&&(this.deviceFolderValue=null,this.suggestedCloudProfile.cancel(),this.browser.close(),this.callbacks.onError(null),this.callbacks.changed())}get worktree(){return!this.deviceFolder&&!this.hostedEnvironment&&(this.remotePlacement||this.repositoryState.worktree)&&!this.remoteRepository}get currentCheckoutUnavailableReason(){let e=this.repositoryState.currentCheckoutUnavailable;return e===`checking`?O(`newSession.checkingPlace`):e===`worktree`?O(`newSession.checkoutRequiresWorktree`):e===`unavailable`?O(`newSession.checkoutCheckUnavailable`):void 0}get checkoutVisible(){return!this.deviceFolder&&!this.hostedEnvironment&&!this.freshWorkspace&&(this.repository.kind!==`direct`||!!this.browser.projectId)&&(this.worktreeAvailable()||this.worktree||!!this.browser.projectId)}get freshWorkspace(){return!this.deviceFolder&&(this.requiredPlacement||this.remotePlacement&&this.selection.freshWorkspace)}get remoteRepository(){return this.requiredPlacement||this.deviceFolder?void 0:this.repositoryState.remoteRepository}get worktreeName(){return this.freshWorkspace?``:this.repositoryState.worktreeName}get baseRef(){return this.freshWorkspace?``:this.repositoryState.baseRef}get repository(){return this.repositoryState.repository}get deviceId(){return this.requiredPlacement||this.hostedEnvironment?``:this.selection.deviceId}get autoDevice(){return!this.requiredPlacement&&!this.hostedEnvironment&&this.selection.autoDevice}get remotePlacement(){return!!(this.requiredPlacement||!this.hostedEnvironment&&(this.selection.deviceId||this.selection.autoDevice||this.selection.cloudProfileId))}get requiredPlacement(){return ws.requiredPlacement(this.gateway,this.read().data)}get cloudProfileId(){return this.requiredPlacement?this.gateway.requiredProfile:this.hostedEnvironment?``:this.selection.cloudProfileId}get cloudSelection(){return this.requiredPlacement?{os:``,machineClass:``}:this.cloudMachines.selection(this.selection.cloudProfileId,this.gateway.cloudProfiles)}preferenceSelection(){return wc(this.selection,this.browser,this.repositoryState,this.workspacePath(),this.folderValue)}get placementPreferenceReady(){return!!this.deviceFolder||!!this.hostedEnvironment||Oc(this.selection,this.freshWorkspace||this.repositoryState.preferenceReady,this.browser.projectsLoading||this.browser.projectsReady,this.requiredPlacement)}adoptGroupDefaults(){this.read().data?.groupStatus===`resolved`&&Tc(this.selection,this.repositoryState)&&this.adoptAgentDefaults({preserveSelectedAgent:!0})}agents(){return sa(this.read().context?.agents.state.agentsList?.agents??[])}selectedAgent(){let e=T(this.agentIdValue);return this.agents().find(t=>T(t.id)===e)}devicePlacementRuntime(){return this.modelControl.resolveAgentRuntime({agent:this.selectedAgent(),context:this.read().context})}devices(){return rc(this.gateway.environments,this.devicePlacementRuntime()?.devicePlacement,this.gateway.deviceCatalogDisabledReason)}devicePlacement(){return ac(this.devices(),this.gateway.environments,this)}isAdmin(){return v(this.read().context?.gateway.snapshot.hello?.auth??null)}canWrite(){return i(this.read().context?.gateway.snapshot.hello?.auth??null)}workspacePath(){return c(this.selectedAgent()?.workspace)??``}knownWorkspaceRoots(){return this.folderValidation.knownWorkspaceRoots(this.workspacePath())}recordGatewayApprovedListing(e){this.folderValidation.recordApprovedListing(e)}folderSubmissionBlocked(){return this.deviceFolder?!this.deviceFolderAvailable||!Ds(this.deviceFolder.path.trim()):this.hostedEnvironment||this.freshWorkspace?!1:this.browser.projectId||this.browser.remoteProject?!this.browser.remoteProject&&(!this.browser.selectedProject()||this.repositoryState.checkoutSubmissionBlocked):this.folderValidation.blocked}adoptAgentDefaults(e={}){let t=this.read(),n=this.agents(),r=t.context?.agents.state.agentsList?.defaultId,i=n.some(e=>e.id===r)?r??``:n[0]?.id??``;if(e.preserveSelectedAgent&&this.agentSelectedByUser&&this.selectedAgent()||(this.agentIdValue=as(t.data,n,i),this.agentSelectedByUser=!1),M(t.data)&&this.terminalOnNode){this.callbacks.changed();return}let a=this.agentIdValue?this.gateway.readPreference(this.agentIdValue):null,o=e.preserveSelectedFolder&&this.selection.folderSelectedByUser;if(!o&&!t.pendingPlacementSessionKey){let e=this.workspacePath(),n=Jt(a,e),r=!!t.data?.group,i=t.data?.groupCwd??``,o=t.data?.groupWorktree===!0;this.folderValue=r?i||e:n.folder,this.selection.projectSelectedByUser||(this.selection.freshWorkspace=!r&&n.freshWorkspace),this.selection.folderSelectedByUser=!1,this.repositoryState.adoptPreference(r?{worktree:o}:a),Dc(this.selection,a,r,M(t.data)),n.workspaceMoved&&!r&&this.persistPreference({folder:e})}o&&!t.pendingPlacementSessionKey&&this.agentIdValue&&this.persistPreference({folder:this.folderValue,worktree:this.worktree}),this.modelControl.load(t.context,this.agentIdValue,!M(t.data),{agent:this.selectedAgent(),preference:a,configuredDefaults:this.requiredPlacement,initialModel:this.routeModelIntentActive?Qo(t.data,this.agentIdValue):void 0}),this.selection.preferredProjectRestore?this.folderValidation.cancel():!this.selection.folderSelectedByUser&&this.folderValue!==this.workspacePath()&&!t.pendingPlacementSessionKey?this.folderValidation.validate(this.folderValue):(this.folderValidation.cancel(),this.repositoryState.synchronize()),this.callbacks.changed()}resetPlaceSelection(){this.deviceFolderValue=null,this.suggestedCloudProfile.cancel(),this.folderValidation.reset(),Object.assign(this.selection,Cc()),this.repositoryState.reset()}resetDraft(){this.routeModelIntentActive=!0,this.terminalHost.reset(),this.agentSelectedByUser=!1,this.folderValue=``,this.browser.clearProjectSelection(),this.resetPlaceSelection(),this.browser.resetProjectSearch(),this.modelControl.reset(),this.cloudMachines.clear(),this.callbacks.changed()}invalidateGatewayDiscovery(e){this.suggestedCloudProfile.cancel(),this.repositoryState.invalidate(),this.agentsHydrated=!1,this.modelControl.invalidate(e),this.browser.close(),this.folderValidation.reset(),this.browser.resetProjectSearch(),this.browser.resetProjects(e),e&&(this.agentIdValue=``,this.agentSelectedByUser=!1,this.folderValue=``,this.resetPlaceSelection(),this.cloudMachines.clear()),this.callbacks.changed()}applyPendingPlacement(e){this.agentIdValue=e.agentId,this.selection.deviceId=e.deviceId??``,this.selection.autoDevice=e.autoDevice===!0,this.selection.cloudProfileId=e.profileId,this.cloudMachines.applyPending(e.profileId,e.machineClass,e.os),this.folderValue=e.cwd??``,this.deviceFolderValue=e.deviceFolder?.path??null,this.selection.freshWorkspace=e.worktreeSource===`empty`,this.selection.freshWorkspace&&this.browser.clearProjectSelection(),e.repository&&(this.browser.selectProject({kind:`remote`,project:{identity:e.repository.url,cloneUrl:e.repository.url}}),this.repositoryState.setDetail(`baseRef`,e.repository.ref??``,!1),this.repositoryState.load()),this.callbacks.changed()}clearCloudProfile(){this.selection.cloudProfileId=``,this.browser.close(),this.callbacks.changed()}clearProjectSelection(){(this.browser.projectId||this.browser.remoteProject)&&this.repositoryState.clearDetails(!0),this.browser.clearProjectSelection(),Ec(this.selection,!0),this.persistPreference({projectId:``,remoteProject:null,defaultRepositoryOptOut:!0}),this.repositoryState.load(),this.callbacks.changed()}selectAgentId(e){let t=this.read();t.submitting||t.pendingPlacementSessionKey||M(t.data)||T(e)!==T(this.agentIdValue)&&(this.agentIdValue=T(e),this.routeModelIntentActive=!1,this.modelControl.reset(),this.callbacks.onError(null),this.agentSelectedByUser=!0,this.browser.clearProjectSelection(),this.resetPlaceSelection(),this.browser.close(),this.adoptAgentDefaults({preserveSelectedAgent:!0}))}applyFolder(e){let t=this.read();t.submitting||t.pendingPlacementSessionKey||(this.deviceFolderValue=null,this.browser.clearProjectSelection(),this.folderValidation.cancel(),this.callbacks.onError(null),this.folderValue=e.trim(),this.selection.freshWorkspace=!1,this.selection.folderSelectedByUser=!0,Ec(this.selection,!0),M(t.data)&&this.terminalOnNode?this.callbacks.changed():(this.repositoryState.selectWorktree(!1),this.agentsHydrated&&this.persistPreference({folder:this.folderValue,projectId:``,remoteProject:null,defaultRepositoryOptOut:!0,worktree:this.worktree,freshWorkspace:!1}),this.repositoryState.load()))}selectNewWorkspace(){let e=this.read();e.submitting||e.pendingPlacementSessionKey||!this.remotePlacement||(this.folderValidation.cancel(),this.browser.clearProjectSelection(),this.browser.resetProjectSearch(),this.callbacks.onError(null),this.deviceFolderValue=null,this.folderValue=this.workspacePath(),this.selection.folderSelectedByUser=!0,Ec(this.selection,!0),this.selection.freshWorkspace=!0,this.repositoryState.selectWorktree(!1),this.persistPreference({folder:this.folderValue,projectId:``,remoteProject:null,defaultRepositoryOptOut:!0,worktree:!0,freshWorkspace:!0}),this.browser.close(),this.callbacks.changed())}selectProjectId(e){let t=this.browser.projects.find(t=>t.id===e);t&&this.selectProject({kind:`local`,id:t.id})}selectRemoteProject(e){this.selectProject({kind:`remote`,project:e})}selectProject(e){let t=this.read();t.submitting||t.pendingPlacementSessionKey||(this.deviceFolderValue=null,this.browser.selectProject(e),this.selection.freshWorkspace=!1,this.folderValidation.cancel(),this.browser.resetProjectSearch(),this.callbacks.onError(null),this.selection.folderSelectedByUser=!1,Ec(this.selection,!1),this.repositoryState.clearDetails(!0),this.persistPreference({projectId:e.kind===`local`?e.id:``,remoteProject:e.kind===`remote`?e.project:null,defaultRepositoryOptOut:!1,...e.kind===`local`?{where:rt(this)}:{},worktree:this.worktree,...e.kind===`local`?{worktreeName:``}:{},freshWorkspace:!1}),e.kind===`remote`&&e.project.defaultBranch&&this.repositoryState.setDetail(`baseRef`,e.project.defaultBranch,!1),this.repositoryState.load(),this.browser.close())}targetActions(){return{place:this,read:this.read,selection:this.selection,callbacks:this.callbacks,folderValidation:this.folderValidation,repositoryState:this.repositoryState,browser:this.browser,modelControl:this.modelControl,persistPreference:e=>this.persistPreference(e),clearDeviceFolder:()=>{this.deviceFolderValue=null}}}selectDevice(e,t=!1){nl(this.targetActions(),e,t)}selectCloudProfile(e){rl(this.targetActions(),e)}selectWorktree(e){il(this.targetActions(),e)}setBaseRef(e){this.repositoryState.setDetail(`baseRef`,e,this.read().submitting)}setWorktreeName(e){this.repositoryState.setDetail(`worktreeName`,e,this.read().submitting)}captureSubmittedWorktreeName(e,t,n=!1){return this.repositoryState.captureSubmittedName(e,{agentId:t,recovered:n})}restorePreferenceSelections(){this.hostedEnvironment||(kc({state:this.selection,browser:this.browser,gateway:this.gateway,where:rt(this),modelControl:this.modelControl,repositoryState:this.repositoryState,isAdmin:()=>this.isAdmin(),persistPreference:e=>this.persistPreference(e),changed:this.callbacks.changed,requiredPlacement:this.requiredPlacement,loadConfiguredDefaults:e=>{this.modelControl.load(this.read().context,this.agentId,!M(this.read().data),{agent:this.selectedAgent(),preference:this.gateway.readPreference(this.agentId),configuredDefaults:e})}}),this.repositoryState.synchronizeProjectCheckout())}browseAvailable(){return this.gateway.connected&&(this.isAdmin()||!!this.workspacePath())}worktreeAvailable(){return!this.hostedEnvironment&&this.repositoryState.available()}persistPreference(e){this.gateway.persistPreference(this.agentIdValue,this.workspacePath(),e)}}})))()}var gl;function _l(){return(_l=e((()=>{Zt(),cr(),gl=class{constructor(e,t){this.notify=e,this.onUserChange=t,this.attachments=[],this.reads=new Gi(e)}replace(e){this.attachments=e,this.onUserChange(),this.notify()}restore(e){yr(this.attachments,[e]),this.attachments=e,this.notify()}take(){this.reads.abortReads();let e=this.attachments;return this.attachments=[],this.notify(),e}reset(){this.reads.abortReads(),this.clearAfterSubmit(!0)}clearAfterSubmit(e){e&&Kr(this.attachments),this.attachments=[],this.notify()}}})))()}function vl(e){let{gateway:t}=e,n=t.snapshot.client,r=t.connectionRevision,i=t.connection.gatewayUrl,a=t.snapshot.hello?.auth?.recoveryScope;return()=>e.gateway===t&&t.snapshot.phase===`connected`&&t.connection.gatewayUrl===i&&t.connectionRevision===r&&t.snapshot.hello?.auth?.recoveryScope===a&&(!!a||t.snapshot.client===n)}function yl(e,t,n){lr({selection:e.agentSelection,gateway:e.gateway,sessionKey:t,agentId:n}),e.navigate(`chat`,vi({context:e,face:`chat`,sessionKey:t,agentId:n}).options)}function bl(){return(bl=e((()=>{Ji(),bn()})))()}function xl(e){let t=vl(e.context);return(n,r)=>{let i=r?.trim();if(!e.enabled)return!1;if(!i)return!0;let{agentId:o,client:s,context:c}=e;return(async()=>{let e;for(;!e;)try{let t=await s.request(`agent.wait`,{runId:i,timeoutMs:3e4},{timeoutMs:null});if(c.gateway.snapshot.client!==s)return;let r=t.status===`timeout`&&t.endedAt===void 0&&!t.error&&!t.stopReason&&t.providerStarted!==!0;if(t.status===`pending`||t.pendingError===!0)await _e(Cl);else if(r){let t=c.placementStartup.get(n)?.initialTurn;t?.sendState===`failed`&&t.sendRunId===i?e={status:`error`,error:t.sendError}:await _e(Cl)}else e=t}catch{let e=c.gateway.snapshot,t=e.phase===`connecting`||e.phase===`starting`||e.phase===`reconnecting`;if(e.client!==s||!t)return;await _e(Cl)}if(!t())return;let r=c.gateway.snapshot;if(a(r,n,o))return;let l=c.sessions.state.result?.sessions.find(e=>ie(e.key,n)),u=e.status===`ok`?O(`sessionsView.statusDone`):e.status===`timeout`?O(`sessionsView.statusTimeout`):e.stopReason===`rpc`?O(`sessionsView.statusKilled`):O(`sessionsView.statusFailed`),d=vi({face:`chat`,sessionKey:n,fallbackAgentId:o,exactKey:!0});c.nativeNotifications?.backgroundSessionCompleted({runId:i,path:d.options.pathname,...d.options.search?{search:d.options.search}:{}});let f=c.agents.state.agentsList?.agents.find(e=>e.id===o)??{id:o},p=c.agentIdentity.get(o);Yn({fifo:!0,avatar:{id:o,name:Ze(f,p),avatar:_(f,p),textAvatar:ai(f,p)},message:`${Ot(n,l)}: ${u}`,actionLabel:O(`sessionsView.openSession`),actionHref:vi({context:c,face:`chat`,sessionKey:n,agentId:o}).href,onAction:e=>{if(!t()){e?.preventDefault();return}let r=()=>yl(c,n,o);e?e.type===`click`&&et(e,r):r()}})})(),!0}}function Sl(e,t,n,r){Sa({connected:e.gateway.snapshot.phase===`connected`,directComposerSend:r&&jt(),message:t,hasAttachments:n,isCommand:Ar(t)!==null})&&_t(e)}var Cl;function wl(){return(wl=e((()=>{ve(),tn(),k(),Ve(),te(),ki(),qt(),bn(),D(),$i(),bl(),Cl=1e3})))()}var Tl;function El(){return(El=e((()=>{se(),k(),Hr(),fn(),ua(),ia(),Gn(),Tl=class{constructor(e,t){this.notify=e,this.onMutation=t,this.toolOverridesValue=null,this.skillCatalog=new jr(e)}get toolOverrides(){return this.toolOverridesValue}setToolOverrides(e){let t=Qt(e)>0?e:null;t!==this.toolOverridesValue&&(this.onMutation(),this.toolOverridesValue=t,this.notify())}reset(){this.toolOverridesValue=null}canStartAsDraft(e){let t=e?.gateway.snapshot.hello?.policy;return t?.allowedSessionVisibilities?.includes(`draft`)===!0&&t?.hasMultipleSessionSharingIdentities===!0}composerProps(e,t,n){return e?(this.skillCatalog.synchronize(t.client,t.connectionEpoch),{toolOverrides:this.toolOverridesValue,capabilityMenu:{read:()=>{let r=e.runtimeConfig.state,i=Ca(r),a=t.connected&&!!t.client,o=l(e.gateway.snapshot),s=a?i?o.canAdmin?null:O(`chat.composer.menu.adminBlocked`):r.lastError??O(`common.loading`):O(`chat.composer.menu.offlineBlocked`);return{basePath:e.basePath,skills:this.skillCatalog.rows(n,this.toolOverridesValue),skillsRead:this.skillCatalog.read(n),mcpServers:qe(i)??[],toolsEffectiveResult:null,toolsEffectiveLoading:!1,toolsEffectiveError:!1,toolAccessMutationBlockedReason:s,webSearchBaseEnabled:Hn(i),mutationBlockedReason:s,canAdmin:o.canAdmin&&a,adminBlockedReason:o.canAdmin?a?null:O(`chat.composer.menu.offlineBlocked`):O(`chat.composer.menu.adminBlocked`),onLoadSkills:()=>{let e=t.client,r=t.connectionEpoch;this.skillCatalog.load(e,r,n,()=>t.connected&&t.client===e&&t.connectionEpoch===r)},onPatchToolOverrides:e=>this.setToolOverrides(e),onNavigate:(t,n)=>e.navigate(t,n)}}}}):{toolOverrides:this.toolOverridesValue,capabilityMenu:void 0}}}})))()}function Dl(e){let t=null;return{captureSelection(){let n=e();t=n?{start:n.selectionStart,end:n.selectionEnd,value:n.value}:null},previewTranscript(n,r){let i=e();return i?n(r,t,{start:i.selectionStart,end:i.selectionEnd,value:i.value})?.value:void 0},insertTranscript(n,r,i,a){let o=e(),s=o&&n(r,t,{start:i?o.selectionStart:o.value.length,end:i?o.selectionEnd:o.value.length,value:o.value},i,a);return!o||!s||(t=s.captured,!s.changed)?null:(o.value=s.value,Ht(o),queueMicrotask(()=>{o.isConnected&&(o.focus({preventScroll:!0}),o.selectionStart=s.caret,o.selectionEnd=s.caret)}),s.value)}}}var Ol;function kl(){return(kl=e((()=>{ae(),Ta(),ln(),Ft(),Ol=class extends EventTarget{constructor(e){super(),this.options=e,this.devicePicker=new Zr,this.session=null,this.owner=null,this.changed=()=>this.dispatchEvent(new Event(`change`)),this.place=(...e)=>this.session?.placeTranscript(...e),this.devicePicker.subscribe(this.changed)}subscribe(e){return C(this,`change`,e)}dispose(){this.owner=null,this.session?.dispose(),this.session=null,this.devicePicker.dispose()}get active(){return this.session?.active===!0}previewDraft(){return this.session?.active?this.options.textarea.previewTranscript(this.place,this.session.transcript):void 0}get dictation(){return this.session??void 0}prepare(e,t){this.owner?.key!==e&&(this.owner={key:e},this.session?.dispose(),this.session=null);let n=this.owner,r=()=>this.owner===n,i=this.options.getClient(),a=this.options.isConnected()&&i!==null;this.devicePicker.syncCatalog(i,a);let o=this.options.canCommit(),s={client:i,connected:a,enabled:o,dictationAvailable:this.devicePicker.dictationStatus===`ready`,realtimeTalkActive:!1,onCommit:(e,t,n)=>{if(!r()||!this.options.canCommit())return;let i=this.options.textarea.insertTranscript(this.place,e,t,n);i!==null&&this.options.onMessage(i)},onError:e=>{r()&&this.options.onError(e)},onDictationUnavailable:this.devicePicker.handleOpen};this.session||(this.session=new mt(s),this.session.subscribe(this.changed)),this.session.update(s);let c=this.session;return{voice:{connected:a,disabled:!o,readDictation:()=>c,microphonePicker:{devices:this.devicePicker.devices,loading:this.devicePicker.loading,open:this.devicePicker.open,selectedDeviceId:t?.trim()??``,voiceActive:!1,issue:this.devicePicker.issue,showRealtimeCapability:!1,realtimeStatus:this.devicePicker.realtimeStatus,dictationStatus:this.devicePicker.dictationStatus,onOpen:this.devicePicker.handleOpen,onClose:this.devicePicker.handleClose,onSelect:e=>{S({realtimeTalkInputDeviceId:e.trim()||void 0}),this.devicePicker.handleClose()}},onDirectDictationStart:()=>this.options.textarea.captureSelection()},onSubmit:()=>{r()&&this.options.canCommit()&&this.options.onSubmit()}}}}})))()}function Al(){let e=null,t=null,n=``,r=``,i={...Dl(()=>e),critterVisit:Math.random(),skillMenu:Ki(),slashMenu:Ur(),mentionMenu:Ir(),emojiMenu:$n(),composing:!1,mentionInput:void 0,capabilityMenuOpen:!1,capabilityMenuView:`root`,ref(t){let n=t instanceof HTMLTextAreaElement?t:null;e&&e!==n&&at(e),e=n,n&&(Ne(n),vn(n))},syncDraft(t){e?.isConnected&&e.value!==t&&vn(e)},getTextarea:()=>e,syncSkillCommandOwner(e,a,o){let s=a.trim();i.ownsSkillCommands(e,s,o)||(t=e,n=s,r=o,i.emojiMenu.close(),i.skillMenu.reset(),i.slashMenu.reset())},ownsSkillCommands(e,i,a){return t===e&&n===i.trim()&&r===a},disconnect(){i.skillMenu.dispose(),i.slashMenu.dispose(),i.emojiMenu.dispose(),i.composing=!1,i.mentionMenu.dispose(),t=null,n=``,r=``,i.capabilityMenuOpen=!1,i.capabilityMenuView=`root`,i.ref()}};return i}function jl(){return(jl=e((()=>{Ta(),ma(),Rn(),Cr(),or(),kl()})))()}var Ml;function Nl(){return(Nl=e((()=>{Le(),Ti(),k(),yn(),rn(),gr(),$i(),Nr(),r(),Zt(),_l(),ut(),Ml=class{constructor(e,t,n,r){this.context=e,this.agentId=t,this.incognito=n,this.notifyDraft=r,this.id=m(),this.composerDraft={read:()=>({draft:this.message,mentions:this.mentions,attachments:this.attachmentDraft.attachments,pendingAttachmentReads:this.attachmentDraft.reads.pendingReads}),subscribe:e=>this.subscribe(e)},this.message=``,this.mentions=[],this.inputs=[],this.error=null,this.listeners=b(),this.invalidations=new Set,this.transferred=!1,this.disposed=!1,this.notify=()=>{this.notifyDraft(),this.listeners.publish()},this.subscribe=this.listeners.subscribe,this.gatewayUrl=e.gateway.connection.gatewayUrl,this.recoveryScope=e.gateway.snapshot.hello?.auth?.recoveryScope,this.presentationScope=br(e.gateway),this.attachmentDraft=new gl(this.notify,()=>{this.error=null});let i=C(window,`beforeunload`,e=>{this.hasInput&&(e.preventDefault(),e.returnValue=``)}),a=oa(()=>!this.hasInput,()=>Yn({message:O(`newSession.followUpReloadBlocked`)}));this.unregisterReload=()=>{a(),i()}}get hasInput(){return!!(this.message||this.inputs.length||this.transfer?.inputs.length||this.attachmentDraft.attachments.length||this.attachmentDraft.reads.pendingReads)}ownsScope(){let{gateway:e}=this.context;return!!this.recoveryScope&&br(e)===this.presentationScope&&e.connection.gatewayUrl===this.gatewayUrl&&(e.snapshot.phase!==`connected`||e.snapshot.hello?.auth?.recoveryScope===this.recoveryScope)}canDisplay(){return!this.disposed&&!this.transferred&&this.ownsScope()}canRecover(){return!this.disposed&&this.ownsScope()&&this.accepted!==void 0}get acceptedSessionKey(){return this.accepted?.key}canAdopt(){return this.canDisplay()&&this.accepted!==void 0}setMessage(e,t){this.canDisplay()&&(this.mentions=t??hn(this.message,e,this.mentions),this.message=e,this.error=null,this.notify())}enqueue(){if(!this.canDisplay()||this.attachmentDraft.reads.pendingReads)return!1;let e=Fe(this.message,this.mentions);if(!e.text&&!this.attachmentDraft.attachments.length)return!1;if(/^[!/]/u.test(e.text))this.error=O(`newSession.followUpCommandsUnavailable`);else if(this.inputs.length>=50)this.error=O(`chat.queue.full`);else if(this.attachmentDraft.attachments.length&&!In(this.context.config))this.error=wr();else{let t={id:m(),text:e.text,...e.mentions?.length?{mentions:e.mentions}:{},attachments:this.attachmentDraft.take(),createdAt:Date.now()};return this.inputs=[...this.inputs,t],this.message=``,this.mentions=[],this.error=null,this.notify(),!0}return this.notify(),!1}remove(e){if(!this.canDisplay())return;let t=this.inputs.find(t=>t.id===e);this.inputs=this.inputs.filter(e=>e!==t),Kr(t?.attachments??[]),this.notify()}accept(e){this.accepted=e}take(e=()=>{}){if(this.transfer)return this.canRecover()?this.transfer:void 0;if(!this.canAdopt())return;this.flushInput?.();let t=!1,n={sessionKey:this.accepted.key,draft:this.message,mentions:this.mentions,attachments:this.attachmentDraft.attachments,reads:this.attachmentDraft.reads,inputs:this.inputs,incognito:this.incognito,isCurrent:()=>!this.disposed&&this.ownsScope(),claimDraft:()=>!t&&(t=!0,!0),onInvalidate:e=>this.disposed?(e(),()=>{}):p(this.invalidations,e),complete:()=>{this.invalidations.clear(),this.unregisterReload(),this.transfer=void 0,e()},initialRejected:this.accepted.initialRun.status===`rejected`,...typeof this.accepted.entry?.sessionId==`string`?{sessionId:this.accepted.entry.sessionId}:{}};return this.transfer=n,this.transferred=!0,this.inputs=[],this.message=``,this.mentions=[],this.attachmentDraft.attachments=[],this.flushInput=void 0,this.releasePresentation?.(),this.releasePresentation=void 0,n}releaseDraft(){this.accepted||this.dispose()}dispose(){if(!this.disposed){this.disposed=!0;for(let e of this.invalidations)e();if(this.invalidations.clear(),this.transfer=void 0,this.unregisterReload(),this.transferred)this.listeners.clear();else{this.flushInput=void 0,this.releasePresentation?.(),this.releasePresentation=void 0,this.attachmentDraft.reset();for(let e of this.inputs)Kr(e.attachments);this.inputs=[],this.message=``,this.mentions=[],this.listeners.clear()}}}}})))()}function Pl(e,t){let n={...t,deferInitialTurn:e.remotePlacement,agentId:e.agentId,model:e.modelControl.modelForSubmission(),agentRuntime:e.modelControl.agentRuntime,contextWindow:e.modelControl.contextWindow,thinkingLevel:e.modelControl.thinkingLevel,fastMode:e.modelControl.fastMode,cyberAccessProgram:e.modelControl.accessProgramForSubmission(),projectId:e.hostedEnvironment?void 0:e.browser.remoteProject?.projectId??e.browser.projectId,projectGitUrl:e.hostedEnvironment?void 0:e.browser.remoteProject?.cloneUrl,repository:e.remoteRepository,deviceFolder:e.deviceFolder,worktree:e.worktree,worktreeSource:e.freshWorkspace?`empty`:void 0,baseRef:e.baseRef,worktreeName:e.worktreeName,cwd:e.hostedEnvironment?void 0:e.folder,workspace:e.workspacePath()},r=c(n.displayName),i=c(n.baseRef),a=c(n.worktreeName),o=c(n.cwd),s=c(n.workspace),l=c(n.catalogId),u=c(n.category),d=c(n.model),f=c(n.agentRuntime),p=c(n.contextWindow),m=c(n.thinkingLevel),h=n.deferInitialTurn?``:n.message,g=n.deferInitialTurn&&n.visibility!==`incognito`?le(n.message.trim(),1e3):void 0,_=n.deviceFolder,v=!_&&n.worktreeSource===`empty`,y=_||v?void 0:n.repository,b=_||v||y?void 0:c(n.projectId),x=!_&&!v&&!y&&!b&&(h.trim()||!n.deferInitialTurn&&n.attachments?.length)?c(n.projectGitUrl):void 0,ee=!_&&!v&&!y&&!b&&!x&&o&&o!==s?o:void 0;return{agentId:T(n.agentId),message:h,...!n.deferInitialTurn&&n.mentions?.length?{mentions:n.mentions.map(e=>({...e}))}:{},...r?{displayName:r}:{},...g?{titleSource:g}:{},...n.visibility===`incognito`?{incognito:!0}:{},...n.visibility===`draft`?{visibility:`draft`}:{},...!n.deferInitialTurn&&n.attachments?.length?{attachments:n.attachments}:{},...l?{catalogId:l}:{},...u?{category:u}:{},...!l&&d?{model:d}:{},...!l&&d&&f?{agentRuntime:f}:{},...!l&&p?{contextWindow:p}:{},...!l&&m?{thinkingLevel:m}:{},...!l&&n.fastMode!==void 0?{fastMode:n.fastMode}:{},...!l&&n.cyberAccessProgram!==void 0?{cyberAccessProgram:n.cyberAccessProgram}:{},...n.toolOverrides?{toolOverrides:n.toolOverrides}:{},...n.permissionMode?{permissionMode:n.permissionMode}:{},...b?{projectId:b}:{},...x?{projectGitUrl:x}:{},...y?{repository:{...y}}:{},..._?{deviceFolder:{..._,path:_.path.trim()}}:{},...ee?{cwd:ee}:{},...v?{worktree:!0,worktreeSource:`empty`}:{},...n.worktree&&!_&&!y&&!v?{worktree:!0,...i?{worktreeBaseRef:i}:{},...a?{worktreeName:a}:{}}:{}}}function Fl(){return(Fl=e((()=>{D()})))()}var Il,Ll,Rl,zl,Bl;function Vl(){return(Vl=e((()=>{Mi(),Wt(),Bt(),E(),Il=()=>({writeId:Math.random().toString(36).slice(2),retired:!1,committedRevision:0,writes:new Set}),Rl=()=>Ll??=w(()=>import(`./control-ui-boot-shared-DFTSUQQ0.js`).then(e=>(e.V(),e.B)),__vite__mapDeps([0,1]),import.meta.url),zl=200,Bl=class e{static{this.active=new Set}constructor(e,t,n){this.read=e,this.apply=t,this.onStorageError=n,this.contentReconciled=!1,this.pendingSelectionMutations=new Set,this.gatewayOwner=``,this.recoveryScope=``,this.routeKey=``,this.revision=0,this.mutationGeneration=0,this.mutation=Il(),this.inheritedWriteIds=[],this.disconnected=!1,this.pendingHandoffMutation=null,this.submittedMutation=null,this.pristineMutationBaseline=0,this.restoreGeneration=0,this.restoredIdentity=``,this.pending=null,this.timer=null,this.lineageByScope=new Map}setOwner(e,t,n=!1){let r=nt(e).gatewayOwner,i=JSON.stringify([r,t]),a=this.gatewayOwner?JSON.stringify([this.gatewayOwner,this.recoveryScope]):``;if(a===i)return;let o=this.routeKey;this.persistNow(),this.restoreGeneration+=1,this.restoredIdentity=``,this.contentReconciled=!1,this.routeKey=``,this.gatewayOwner=r,this.recoveryScope=t,a&&!n&&(this.pendingSelectionMutations.clear(),this.apply({message:``,attachments:[],permissionMode:void 0},!0)),n||this.activateRoute(o)}setIncognito(e){if(e)return this.retireActive();let t=this.scope();return(t?this.lineage(t).retirement:void 0)?.then(()=>{})??Promise.resolve()}transitionIncognito(e,t,n){let r=this.setIncognito(t);e&&!t?(this.noteUserMutation(),r.finally(n)):n()}selectRoute(e){e&&this.routeKey!==e&&(this.persistNow(),this.routeKey&&this.pendingSelectionMutations.clear(),this.routeKey=e,this.contentReconciled=!1,this.revision=0)}activateRoute(e){this.selectRoute(e);let t=this.scope();if(!t)return;let n=Qr(t);if(n===this.restoredIdentity)return;if(this.restoredIdentity=n,this.contentReconciled=!1,this.read().incognito){this.retireActive();return}let r=++this.restoreGeneration,i=this.mutationGeneration,a=this.read(),o=Re(a.message,a.attachments,void 0,a.mentions),s=this.restoreScope(t,i,()=>{let e=this.read();return r===this.restoreGeneration&&i===this.mutationGeneration&&this.matchesScope(t)&&o===Re(e.message,e.attachments,void 0,e.mentions)});this.restorePromise=s,s.then(e=>{this.restorePromise===s&&(this.restorePromise=void 0,this.contentReconciled=e,this.flushSelectionMutations())},()=>{this.restorePromise===s&&(this.restorePromise=void 0,this.contentReconciled=!1,Yt(t,this.onStorageError))})}noteDraftReplaced(){this.restoreGeneration+=1,this.mutationGeneration+=1,this.mutation=Il(),this.pendingHandoffMutation=null,this.submittedMutation=null,this.inheritedWriteIds=[],this.pristineMutationBaseline=this.mutationGeneration}noteSelectionMutation(e){let t=!this.contentReconciled&&this.mutationGeneration===this.pristineMutationBaseline&&(this.submittedMutation===this.mutation||!this.restorePromise);this.submittedMutation=null,this.pendingSelectionMutations.add(e),t?(this.restoredIdentity=``,this.activateRoute(this.routeKey)):this.flushSelectionMutations()}flushSelectionMutations(){this.pendingSelectionMutations.size>0&&!this.restorePromise&&this.restoredIdentity&&(this.contentReconciled||this.mutationGeneration>this.pristineMutationBaseline)&&!this.disconnected&&this.submittedMutation!==this.mutation&&this.noteUserMutation()}noteUserMutation(){if(this.pendingSelectionMutations.clear(),this.mutationGeneration+=1,this.mutation=Il(),this.pendingHandoffMutation=null,this.submittedMutation=null,this.revision=St(this.revision),this.read().incognito)return;this.discardPending();let e=this.snapshot();e&&(this.pending=e,this.timer=globalThis.setTimeout(()=>this.persistNow(),zl))}retireActive(){this.mutationGeneration+=1,this.mutation.retired=!0,this.discardPending();let e=St(this.revision);this.revision=e;let t=this.scope();if(!t)return Promise.resolve();let n=this.lineage(t);return n.localWriteIds.clear(),n.retirement=(async()=>{let{retireDurableComposerDraft:r}=await Rl(),i=Math.max(e,n.revision),a=await r(t,i);if(a.status===`storage-failed`)Yt(t,this.onStorageError);else if(a.status===`persisted`){let e=a.revision??i;return this.adoptCommittedRevision(t,e,a.writeId),{revision:e,writeId:a.writeId}}})(),n.retirement.then(()=>{})}captureSubmission(){this.pendingSelectionMutations.clear(),this.reconcileHandoffCommit(),this.submittedMutation=this.mutation,this.mutationGeneration===this.pristineMutationBaseline&&(this.restorePromise&&(this.contentReconciled=!1),this.restoreGeneration+=1),this.persistNow();let e=this.scope(),t=e?this.lineage(e):null;return{scope:e,mutation:this.mutation,revision:this.revision,incognito:this.read().incognito,pendingEdit:this.mutationGeneration>this.pristineMutationBaseline&&this.mutation.committedRevision===0,writeIds:new Set([t?.writeId,this.mutation.writeId,...this.inheritedWriteIds,...t?.localWriteIds??[]])}}adoptHandoff(e){e.scope&&this.matchesScope(e.scope)&&(this.mutation=e.mutation,this.revision=Math.max(this.revision,e.revision),e.pendingEdit&&!e.mutation.committedRevision&&(this.pristineMutationBaseline=this.mutationGeneration-1,this.pendingHandoffMutation=e.mutation),this.inheritedWriteIds=[...e.writeIds])}async clearSubmittedDraft(t,n){t.mutation.retired=!0;let{scope:r}=t;if(this.mutation===t.mutation&&this.matchesScope(r)&&(this.modelSelection?.retire(),n?.()),await Promise.all(t.mutation.writes),!r)return;let{readDurableComposerDraft:i}=await Rl();for(let n=0;n<3;n+=1){let n=await i(r);if(n.status===`storage-failed`){Yt(r,this.onStorageError);return}if(n.status!==`found`||!t.writeIds.has(n.draft.writeId))return;let a=n.draft.revision,o=n.draft.writeId,s=St(a),c=`clear:${s}`,{result:l}=await it({scope:r,expectedRevision:a,...o?{expectedWriteId:o}:{},revision:s,text:``,storedAttachments:[],writeId:c});if(l.status===`persisted`){this.adoptCommittedRevision(r,l.revision??s,l.writeId??c);for(let t of e.active){let e=t.scope();e&&Qr(e)===Qr(r)&&(t.restoredIdentity=``,t.activateRoute(e.scopeKey))}return}if(l.status===`storage-failed`){Yt(r,this.onStorageError);return}}}persistNow(){this.clearTimer();let e=this.pending;if(!e)return;if(this.read().incognito){this.discardPending();return}this.pending=null;let t=(async()=>{try{let t=e.retirement?await e.retirement:void 0;if(e.mutation.retired||!this.lineage(e.scope).localWriteIds.has(e.writeId))return;let n=t&&t.revision>e.expectedRevision?{...e,expectedRevision:t.revision,expectedWriteId:t.writeId,revision:St(Math.max(e.revision,t.revision))}:e,{result:r,payloadUnavailable:i}=await it(n);if(i&&Yt(e.scope,this.onStorageError),r.status===`persisted`||r.status===`payload-too-large`){let t=r.revision??n.revision;e.mutation.committedRevision=t,this.adoptCommittedRevision(e.scope,t,r.writeId??e.writeId),r.status===`payload-too-large`&&Yt(e.scope,this.onStorageError);return}if(r.status===`storage-failed`){Yt(e.scope,this.onStorageError);return}if(this.disconnected||e.mutation.retired||this.routeKey!==e.scope.scopeKey||this.revision!==e.revision)return;this.restoredIdentity=``,this.activateRoute(this.routeKey)}finally{this.forgetLocalWrite(e)}})();e.mutation.writes.add(t),t.finally(()=>e.mutation.writes.delete(t))}connect(){this.disconnected=!1,e.active.add(this)}disconnect(){this.disconnected=!0,e.active.delete(this),this.persistNow(),this.restoreGeneration+=1}scope(){return!this.gatewayOwner||!this.recoveryScope||!this.routeKey?null:{gatewayOwner:this.gatewayOwner,recoveryScope:this.recoveryScope,scopeKey:this.routeKey}}matchesScope(e){let t=this.scope();return e===null?t===null:t!==null&&Qr(e)===Qr(t)}snapshot(){let e=this.scope();if(!e||this.revision<=0||this.mutation.retired)return null;let t=this.read(),n=this.lineage(e),r=[...n.localWriteIds],i=this.mutation.writeId;return n.localWriteIds.add(i),{scope:e,mutation:this.mutation,retirement:n.retirement,expectedRevision:n.revision,...n.writeId?{expectedWriteId:n.writeId}:{},expectedWriteIds:r,revision:this.revision,text:t.message,...t.mentions?.length?{mentions:t.mentions.map(e=>({...e}))}:{},modelSelection:this.modelSelection?.read(),permissionMode:t.permissionMode,storedAttachments:Oe(t.attachments),writeId:i}}async restoreScope(e,t,n){let{readDurableComposerDraft:r}=await Rl(),i=await r(e);if(i.status===`storage-failed`)return Yt(e,this.onStorageError),!1;let a=i.status===`found`?i.draft.revision:i.revision,o=i.status===`found`?i.draft.writeId:i.writeId,s=this.lineage(e);if(s.revision=a??0,s.writeId=o,!n()||(this.reconcileHandoffCommit(),this.submittedMutation===this.mutation&&this.mutation.committedRevision>0))return!1;if(a===void 0||a<this.revision||t>this.pristineMutationBaseline)return a!==void 0&&a>=this.revision?this.revision=St(a):this.revision<=0&&t>this.pristineMutationBaseline&&(this.revision=St(0)),this.pending=this.snapshot(),this.persistNow(),!0;let c=[];if(i.status===`found`)try{c=await It(i.draft.attachments)}catch{return Yt(e,this.onStorageError),!1}if(!n())return!1;this.revision=a;let l=i.status===`found`?i.draft:void 0,u=this.pendingSelectionMutations.has(`permission`)?this.read().permissionMode:l?.permissionMode;return this.apply({message:l?.text??``,attachments:c,mentions:l?.mentions,permissionMode:u}),this.modelSelection?.restore(i.status===`found`?i.draft.modelSelection:void 0),this.mutation.committedRevision=a,!0}reconcileHandoffCommit(){this.pendingHandoffMutation===this.mutation&&this.mutation.committedRevision>0&&this.submittedMutation!==this.mutation&&(this.revision=Math.max(this.revision,this.mutation.committedRevision),this.pristineMutationBaseline=this.mutationGeneration,this.pendingHandoffMutation=null)}clearTimer(){this.timer!==null&&(globalThis.clearTimeout(this.timer),this.timer=null)}discardPending(){this.clearTimer();let e=this.pending;this.pending=null,e&&this.forgetLocalWrite(e)}forgetLocalWrite(e){let t=Qr(e.scope),n=this.lineageByScope.get(t);n&&(n.localWriteIds.delete(e.writeId),!n.revision&&!n.writeId&&!n.localWriteIds.size&&!n.retirement&&this.lineageByScope.delete(t))}lineage(e){let t=Qr(e),n=this.lineageByScope.get(t);return n||(n={revision:0,localWriteIds:new Set},this.lineageByScope.set(t,n)),n}adoptCommittedRevision(e,t,n){let r=this.lineage(e);r.revision=t,n&&(r.writeId=n),this.matchesScope(e)&&t>this.revision&&(this.revision=t)}}})))()}function Hl(e,t){let{os:n,machineClass:r}=t.cloudSelection;return e.sessionKey?e.target:t.cloudProfileId?{kind:`profile`,profileId:t.cloudProfileId,...t.requiredPlacement?{required:!0}:{},...n?{os:n}:{},...r?{machineClass:r}:{}}:t.deviceId?{kind:`device`,deviceId:t.deviceId}:t.autoDevice?{kind:`auto-device`}:null}function Ul(e){let t=e.createParams?.incognito?`incognito`:e.createParams?.visibility===`draft`?`draft`:`normal`;return{placement:{agentId:e.agentId,profileId:e.target.kind===`profile`?e.target.profileId:``,...e.target.kind===`profile`?{os:e.target.os,machineClass:e.target.machineClass}:e.target.kind===`device`?{deviceId:e.target.deviceId}:{autoDevice:!0},cwd:e.createParams?.cwd,...e.createParams?.deviceFolder?{deviceFolder:e.createParams.deviceFolder}:{},...e.createParams?.worktreeSource?{worktreeSource:e.createParams.worktreeSource}:{},...e.createParams?.repository?{repository:e.createParams.repository}:{}},draft:{message:e.message,...e.mentions?.length?{mentions:e.mentions}:{},attachments:fa(e.attachments),visibility:t,toolOverrides:e.createParams?.toolOverrides??null,permissionMode:e.createParams?.permissionMode}}}async function Wl(e){let{pending:t,submittedRecovery:n,sessionKey:r}=e,{gatewayUrl:i,recoveryScope:a}=n,o=e=>t.owns(i,a,e),s=()=>o(n.sessionKey);if(n.phase===`creating`&&(!e.isLifecycleCurrent()||!s())){if(t.hasOtherLiveOwner(i,a,n.sessionKey))return;let o=await Fo({client:e.client,describe:e.context.sessions.describe},r,e.agentId);o?(s()&&(t.promoteToDispatching(r),t.retryAllowed=!0),e.setError(O(`newSession.placementStartFailed`,{error:o}))):s()&&e.clearRecovery();return}if(n.phase===`creating`&&e.isLifecycleCurrent()&&s()&&!t.promoteToDispatching(r)){e.onRecoveryUnavailable();return}let c=t.capture();if(!c||c.phase===`creating`){e.onRecoveryUnavailable();return}if(!e.isRequestCurrent())return;let l=e.startupError?eo(c,e.startupError,t.persistent).recovery:c;e.context.placementStartup.start({recovery:l,persistRecovery:t.persistent,mode:n.phase===`creating`?`dispatch`:`recover`,createdAt:e.createdAt}),await e.consumeWorktreeName?.();let u=()=>e.isLifecycleCurrent()&&o(l.sessionKey);u()&&(await e.clearDraft(),u()&&(t.reset(),e.completeInBackground(l.sessionKey,l.messageId)?e.onAccepted():await e.navigate()))}function Gl(){return(Gl=e((()=>{k(),Z(),lo(),Ho(),Zn(),X()})))()}var Kl;function ql(){return(ql=e((()=>{la(),r(),Kl=class{constructor(e){this.gateway=e,this.pending=null}get active(){return this.pending!==null}start(e,t=!1){let n=this.gateway.sessionCreateScope;if(!n)return e;if(!this.pending){let r=Date.now();this.pending={params:Object.freeze({...e,idempotencyKey:m()}),scope:n,startedAt:r,interrupted:!1,background:t}}return this.pending.params}clear(){this.pending=null}interrupt(){return!this.pending||!this.matchesGateway()?(this.clear(),!1):(this.pending.interrupted=!0,!0)}retireChangedOwner(){return!this.pending||this.matchesGateway()?!1:(this.clear(),!0)}resume(){return this.pending?.interrupted?Date.now()>=this.pending.startedAt+24e4?(this.clear(),{kind:`expired`}):this.matchesGateway()?this.gateway.connected?(this.pending.interrupted=!1,{kind:`resume`,params:this.pending.params,startedAt:this.pending.startedAt,background:this.pending.background}):{kind:`wait`}:(this.clear(),{kind:`owner-changed`}):{kind:`wait`}}matchesGateway(){return this.pending?.scope===this.gateway.sessionCreateScope}}})))()}function Jl(e,t,n,r,i=!1){let a=t.pendingPlacement,o=!r&&!!a.sessionKey,s=Fe(t.message,t.mentions),c=r?.params.message??(o?a.message:s.text),l=(r?r.params.mentions:o?a.mentions:s.mentions)?.map(({profileId:e,start:t,end:n})=>({profileId:e,start:t,end:n})),u=t.attachmentDraft.attachments;if(!r&&!o){let t=Dr(u,e.gateway.snapshot.hello?.policy);if(t!==void 0)return Yn({message:t}),null}let d=r?r.params.attachments:o?void 0:Xe(u),f=o?a.attachments:d,p=r?.params.agentId??(o?a.agentId:T(n.agentId)),m=o?a.gatewayUrl:e.gateway.connection.gatewayUrl,h=e.gateway.snapshot.client;if(!h||!e.gateway.snapshot.hello)return null;!r&&!o&&n.modelControl.initializeAccessProgram();let g=xl({enabled:i,agentId:p,client:h,context:e}),_=o?a.recoveryScope:h.recoveryScope,v=r?.params??(o?a.createParams:Pl(n,{message:c,visibility:t.visibility})),{hello:y,selfUser:b}=e.gateway.snapshot;return{turn:{text:c,mentions:l,attachments:u,createdAt:r?.startedAt??Date.now(),sender:Be(y,h.instanceId,b)??void 0},consumeWorktreeName:v&&n.captureSubmittedWorktreeName(v,p,!!(r||o)),pendingPlacement:o,message:c,mentions:l,attachments:u,draftAttachments:d,apiAttachments:f,agentId:p,gatewayUrl:m,client:h,recoveryScope:_,completeInBackground:g,hasInitialTurn:!!(c||f?.length)}}function Yl(){return(Yl=e((()=>{an(),rn(),D(),$i(),Ge(),ta(),wl(),Fl()})))()}function Xl(e,t){let{context:n,result:r,turn:i}=e,{text:a,attachments:o}=i;return r.initialRun.status===`rejected`&&fo({agentId:e.agentId,attachments:o,context:n,error:r.initialRun.error,message:a,mentions:i.mentions,sessionKey:r.key,sessionId:typeof r.entry?.sessionId==`string`?r.entry.sessionId:void 0,retryAfter:t})}async function Zl(e){let{context:t,client:n,agentId:r,result:i,instant:a}=e,{key:o,initialRun:s}=i,c=s.status===`started`?pt(o,e.turn,n,s.runId):null;!a&&e.isCurrent()&&t.chatSubmissions.retain(c);let l=s.status===`rejected`?void 0:e.clearDraft(!0,e.isCurrent()&&(!a||a.isCurrent())?void 0:!1);if((a||l)&&await Promise.all([a?.waitForReady(),l]),!e.isCurrent()||a&&!a.isCurrent())return;let u=s.status===`rejected`&&sn(s.errorDetails)?s.errorDetails:void 0,d=u?Ct():void 0;try{if(s.status===`rejected`&&e.onRejectedPrompt){let t=lt(e.turn.attachments);Xl({...e,turn:{...e.turn,attachments:t}},d?.promise)||Kr(t),e.onRejectedPrompt(s.error)}else if(l)a&&t.chatSubmissions.retain(c);else{let t=Xl(e,d?.promise);await e.clearDraft(!t)}if(!e.isCurrent()||a&&!a.isCurrent())return;if(e.completeInBackground(o,s.status===`started`?s.runId:void 0)){e.onAccepted?.();return}if(e.composer&&(e.composer.accept(i),We(t,o,e.composer)),a?.admitted(o,r),await e.navigation.navigate(t,{client:n,key:o,agentId:r,entry:i.entry},a?.commit.bind(a)),e.finishNavigation(),u){let e=t.gateway.snapshot,a=()=>t.gateway.snapshot.phase===`connected`&&t.gateway.snapshot.client===n&&t.gateway.snapshot.hello===e.hello&&ie(t.gateway.snapshot.sessionKey,o);try{let{confirmNativeRuntimePermissionRecovery:n}=await w(async()=>{let{confirmNativeRuntimePermissionRecovery:e}=await import(`./chat-native-runtime-recovery-D_zQrB0i.js`);return{confirmNativeRuntimePermissionRecovery:e}},__vite__mapDeps([2,3,4,5,6,7,0,1,8]),import.meta.url),s=await n({sessions:t.sessions,hello:e.hello},o,u,{agentId:r,expectedSessionId:typeof i.entry?.sessionId==`string`?i.entry.sessionId:void 0,signal:t.lifecycleAbortSignal,retriesMessage:!0,canDispatch:a});d?.resolve(!!(s&&a()))}catch(e){a()&&Yn({message:O(`chat.nativeRuntimeRecovery.failed`,{error:y(e)})})}}}finally{d?.resolve(!1)}}function Ql(){return(Ql=e((()=>{On(),k(),ci(),h(),da(),D(),$i(),Zt(),_n(),Je(),mo(),E(),ke()})))()}function $l(e,t,n){let{router:r,lifecycleAbortSignal:i}=e,a=new AbortController,o=r.navigate(t,e,{history:`none`},n),s=r.getState().location,c=i?AbortSignal.any([a.signal,i]):a.signal,l=r.subscribe(e=>{e.location!==s&&a.abort()}),u=C(c,`abort`,l,{once:!0});return{ready:o.catch(()=>void 0),signal:c,isActive:()=>!c.aborted&&r.getState().location===s,dispose(){l(),u()}}}function eu(){return(eu=e((()=>{})))()}function tu(e,t){let n=au.get(e);if(n&&n.search===t&&n.owns())return au.delete(e),ou.set(n.draft.data,{page:n.draft.page,canDisplay:n.canDisplay}),n.draft.data}function nu(e,t){e&&ou.get(e)?.page===t&&ou.delete(e)}function ru(e){let t=e&&typeof e==`object`?ou.get(e):void 0;return t?.canDisplay()?t.page:void 0}function iu(e,t){return au.set(e,t),()=>{au.get(e)===t&&au.delete(e)}}var au,ou;function su(){return(su=e((()=>{au=new WeakMap,ou=new WeakMap})))()}function cu(e){let{context:t,params:n,agentId:r,retainDraft:i}=e;if(!e.enabled||!t.gateway.snapshot.hello?.auth?.recoveryScope||!i)return;let a=(e.resumed?n.key:void 0)??`agent:${r}:dashboard:${n.incognito?`incognito-`:``}${m()}`;return e.resumed||(n.key=a),()=>{let o=i();return o?new uu(t,a,r,o,e.message,e.composer,n.displayName,n.category):void 0}}var lu,uu;function du(){return(du=e((()=>{Ti(),hi(),bn(),r(),eu(),su(),lu=new WeakMap,uu=class{constructor(e,t,n,r,i,a,o,s){this.context=e,this.key=t,this.draft=r,this.stopGateway=()=>{},this.clearPendingCreate=()=>{},this.disposed=!1,this.lifetime=new AbortController,this.creation={sessionKey:t,admitted:!1},this.client=e.gateway.snapshot.client,this.hello=e.gateway.snapshot.hello,this.gatewayUrl=e.gateway.connection.gatewayUrl,this.recoveryScope=this.hello?.auth?.recoveryScope,this.presentationScope=br(e.gateway);let c=lu.get(e);this.previousSessionKey=e.gateway.snapshot.sessionKey,this.previousAgentId=e.agentSelection.state.selectedId,c?.dispose(),this.returnLocation={pathname:globalThis.location.pathname,search:globalThis.location.search,hash:globalThis.location.hash},lu.set(e,this);let l={pathname:vi({context:e,face:`chat`,sessionKey:t,agentId:n,exactKey:!0}).options.pathname,search:``,hash:``};this.clearPendingCreate=e.chatSubmissions.beginCreate({creation:this.creation,message:i,composer:a,displayName:o,category:s,canDisplay:()=>this.canDisplay()}),this.transition=$l(e,`chat`,l),C(this.transition.signal,`abort`,()=>this.dispose(),{once:!0,signal:this.lifetime.signal}),this.stopGateway=e.gateway.subscribe(()=>{let t=e.gateway.snapshot;(t.phase!==`connected`||t.hello!==this.hello||t.client!==this.client||e.gateway.connection.gatewayUrl!==this.gatewayUrl||t.hello?.auth?.recoveryScope!==this.recoveryScope)&&(t.phase!==`connected`&&e.gateway.connection.gatewayUrl===this.gatewayUrl&&r.synchronizeGateway(),this.rollback())})}sameIdentity(){let{gateway:e}=this.context;return!!this.recoveryScope&&e.connection.gatewayUrl===this.gatewayUrl&&e.snapshot.phase===`connected`&&e.snapshot.hello?.auth?.recoveryScope===this.recoveryScope}canDisplay(){return br(this.context.gateway)===this.presentationScope&&this.context.gateway.connection.gatewayUrl===this.gatewayUrl&&(this.context.gateway.snapshot.phase!==`connected`||this.sameIdentity())}liveConnection(){return this.sameIdentity()&&this.context.gateway.snapshot.client===this.client&&this.context.gateway.snapshot.hello===this.hello}ownsSelection(){let e=this.admittedSelection?.key??this.previousSessionKey,t=this.admittedSelection?.agentId??this.previousAgentId;return this.context.gateway.snapshot.sessionKey===e&&this.context.agentSelection.state.selectedId===t}async waitForReady(){await this.transition.ready}isCurrent(){return!this.disposed&&!this.rollingBack&&lu.get(this.context)===this&&this.transition.isActive()&&this.liveConnection()&&this.ownsSelection()}rollback(){return this.rollingBack??=this.restore(),this.rollingBack}async restore(){await this.transition.ready;try{await zr(this.context.gateway,this.lifetime.signal)}catch{return}if(this.disposed||lu.get(this.context)!==this||!this.transition.isActive())return;let e=this.sameIdentity()&&this.ownsSelection();this.transition.dispose(),this.stopGateway();let t=this.context.agentSelection.state.selectedId,n={draft:this.draft,search:this.returnLocation.search??``,owns:()=>lu.get(this.context)===this&&!this.disposed&&this.sameIdentity(),canDisplay:()=>this.canDisplay()&&this.context.agentSelection.state.selectedId===t},r=()=>{};e&&(this.draft.synchronizeGateway(),r=iu(this.context,n));try{let e=$l(this.context,`new-session`,this.returnLocation);await e.ready,await new Promise(e=>{globalThis.setTimeout(e,0)}),e.dispose()}finally{r(),this.dispose()}}admitted(e,t){this.admittedSelection={key:e,agentId:t},!this.disposed&&e===this.key&&(this.creation.admitted=!0,this.clearPendingCreate())}commit(){return this.disposed||this.rollingBack||!this.transition.isActive()||!this.liveConnection()?!1:(this.transition.dispose(),this.stopGateway(),!0)}async finish(){await this.rollingBack,this.dispose()}dispose(){this.disposed||(this.disposed=!0,this.lifetime.abort(),this.clearPendingCreate(),this.transition.dispose(),this.stopGateway(),lu.get(this.context)===this&&lu.delete(this.context),this.draft.release())}}})))()}function fu(e,t){if(t?.renderedElements?.(`openclaw-chat-pane`).some(e=>e.active&&e.composerReady))return{cancel:()=>void 0,ready:Promise.resolve()};let{promise:n,resolve:r}=Ct();return{cancel:C(e,dt,()=>r(),{once:!0}),ready:n}}async function pu(e){let{document:t,from:n,navigate:r,prefersReducedMotion:i,router:a,signal:o,to:s}=e;if(n!==`new-session`||s!==`chat`)return r();let c=e.getOutlet(),l=fu(t,c),u=!1,d,{promise:f,resolve:p}=Ct(),m=()=>{u||(u=!0,d?.cancel(),p())},h=()=>{},g=o&&C(o,`abort`,m,{once:!0});try{if(o?.aborted)return;let e=r(),t=a.getState().location.pathname,n=()=>{let e=a.getState();((e.pendingMatches[0]??e.matches[0])?.routeId!==s||e.location.pathname!==t)&&m()};if(h=a.subscribe(n),n(),await Promise.race([(async()=>{await e,await c?.settlePresentation(),await l.ready})(),f]),u||i)return;d=c?.animate?.(mu,hu),await Promise.race([d?.finished.catch(()=>void 0),f])}finally{h(),g?.(),l.cancel()}}var mu,hu;function gu(){return(gu=e((()=>{On(),st(),mu=[{transform:`translateY(5px) scale(0.997)`},{transform:`none`}],hu={duration:180,easing:`cubic-bezier(0.16, 1, 0.3, 1)`}})))()}function _u(e){let t=br(e),n=e.connection.gatewayUrl,r=e.snapshot.hello?.auth?.recoveryScope??(e.snapshot.client?.recoveryScopeReady?e.snapshot.client.recoveryScope:void 0);return()=>{let i=e.snapshot,a=i.hello?.auth?.recoveryScope??(i.client?.recoveryScopeReady?i.client.recoveryScope:void 0);return r??=a,br(e)===t&&e.connection.gatewayUrl===n&&(!a||a===r)}}var vu;function yu(){return(yu=e((()=>{Ji(),Ti(),gu(),qt(),kr(),bn(),D(),_n(),vu=class{constructor(){this.current=null,this.submitted=null}captureSubmission(e,t,n,r=()=>!0){let i=_u(e.gateway);return(a,o)=>{n&&r()&&i()&&(this.submitted={context:e,message:n,key:a,agentId:t,error:o,canDisplay:i})}}submission(e){let t=this.submitted;return t&&t.context===e&&t.canDisplay()?t:null}messageForTurn(e,t,n){return cn(n,`available`)??(this.isCurrent(e,t)?this.submission(e)?.message??null:null)}async openSubmission(e,t,n){let r=e?.gateway.snapshot.client;if(!t||!e||!r||e.gateway.snapshot.phase!==`connected`||this.submission(e)!==t)return;let i=n.capture();n.publish(t.message,null);let a;try{await this.navigate(e,{client:r,key:t.key,agentId:t.agentId})}catch(e){i()&&t.canDisplay()&&(a=e instanceof Error?e.message:String(e))}finally{i()&&n.publish(null,a)}}clearSubmission(){this.submitted=null}isCurrent(e,t){let n=this.current,r=e?.gateway.snapshot;return!!(n&&r?.phase===`connected`&&r.client===n.client&&r.hello===n.hello&&r.sessionKey===n.key&&T(t)===n.agentId)}async navigate(e,t,n){let r={...t,hello:e.gateway.snapshot.hello};this.current=r,lr({selection:e.agentSelection,gateway:e.gateway,sessionKey:t.key,agentId:t.agentId});let i=vi({context:e,face:`chat`,sessionKey:t.key,agentId:t.agentId,focusComposer:!0,navigationKey:t.key}).options;await pu({document,getOutlet:()=>e.routeOutlet,from:e.router.getState().matches[0]?.routeId,to:`chat`,router:e.router,signal:e.lifecycleAbortSignal,prefersReducedMotion:globalThis.matchMedia?.(`(prefers-reduced-motion: reduce)`).matches??!1,navigate:()=>{if(this.current!==r||!this.isCurrent(e,t.agentId))throw new DOMException(`Session navigation interrupted`,`AbortError`);if(n&&!n())throw new DOMException(`Session navigation superseded`,`AbortError`);return e.chatSubmissions.acceptCreate({creation:{sessionKey:t.key,admitted:!0},displayName:Ot(t.key,{displayName:c(t.entry?.displayName),label:c(t.entry?.label)}),category:c(t.entry?.category),canDisplay:_u(e.gateway)}),Bn(e.gateway,i.pathname,t.key),e.navigateAndWait(`chat`,i)}}),this.current===r&&(this.current=null)}}})))()}function bu(e){let t=e.trim();return!t||xu.test(t)}var xu;function Su(){return(Su=e((()=>{xu=/^[a-z0-9][a-z0-9-]{0,63}$/})))()}function Cu(e,t){let n=P(e,{method:`sessions.catalog.startTerminal`,requiredScope:`operator.admin`});return!n.allowed||!t?n:P(e,{method:`worktrees.create`,requiredScope:`operator.admin`})}async function wu(e){let{context:t,data:r}=e.snapshot,{place:i,flow:a}=e,o=t?.gateway.snapshot.client,s=r?.catalogId.trim()??``,c=T(i.agentId);if(!t||!o||!s||!c||!a.canSubmit()){a.noteBlockedSubmitAttempt();return}let l=e.capture(o),u=a.message.trim(),d={hostId:i.terminalHostId,cwd:i.folder.trim()||(i.terminalOnNode?``:i.workspacePath()),worktree:i.worktree,worktreeName:i.worktreeName,baseRef:i.baseRef},f=i.captureSubmittedWorktreeName(d,c);l.publish(cn({text:u,createdAt:Date.now()},`available`),!0),i.browser.close(),e.closeTransientUi();try{let e=d.cwd;if(d.worktree){let t=await oo(o,{repoRoot:e,name:d.worktreeName,baseRef:d.baseRef});if(!l.isCurrent())return;e=t.path}let r=await Wo(o,{catalogId:s,agentId:c,hostId:d.hostId,cwd:e,...u?{initialMessage:u}:{}},l.isCurrent);if(!r||!l.isCurrent()||(await f?.(),!l.isCurrent()))return;await l.consume(),l.isCurrent()&&t.replace(`terminal`,{pathname:n(r.sessionId,t.basePath),search:``,hash:``})}catch(e){l.isCurrent()&&a.setError(e instanceof Error?e.message:String(e))}finally{l.isRequestCurrent()&&l.publish(null,!1)}}function Tu(){return(Tu=e((()=>{o(),Z(),Bi(),Go(),D(),_n(),X()})))()}function Eu(e){switch(e.kind){case`forbidden`:return e.missingScope?O(`newSession.folderRequiresScope`,{scope:e.missingScope}):O(`newSession.gitCheckAccessDenied`);case`unavailable`:return O(`newSession.gitCheckUnavailable`);default:return}}function Du(e){let{gateway:t,place:n,pendingPlacement:r,hasInitialTurn:i,createParams:a}=e,o=!!r.sessionKey,s=Hl(r,n),c=!n.hostedEnvironment&&!s&&!i?n.browser.remoteProject:null;if(!o&&c&&!c.projectId){let e=P(t,{method:`projects.add`,requiredScope:`operator.write`});if(!e.allowed)return e}if(!s||!o||r.phase===`creating`){let e=P(t,{method:`sessions.create`,params:a,sessionScope:!0});if(!e.allowed||!s||s.kind===`profile`&&s.required)return e}return s.kind===`profile`&&s.required?P(t,{method:`chat.send`,sessionScope:!0}):P(t,{method:`sessions.dispatch`,requiredScope:`operator.write`,params:jo({key:r.sessionKey,agentId:r.agentId||n.agentId,target:s})})}function Ou(e){let{snapshot:t,gateway:n,place:r,pendingPlacement:i}=e;if(!n.placementPolicyReady)return!1;let a=r.selectedAgent(),o=t.context?.agents.state;return r.modelControl.requiresModelSetup({catalog:M(t.data)||r.remotePlacement||!!i.sessionKey,connected:n.connected,agentsLoaded:!!o?.agentsList,selectedAgentFound:a!==void 0,agentModel:a?.model?.primary})}function ku(e,t,n,r){let i=M(r.data)?`terminal`:`session`,a=!!n.pendingPlacement.sessionKey;if(n.mentions.length>0&&(i===`terminal`||n.visibility===`incognito`||n.message.trimStart().startsWith(`/`)))return{gate:`mentions-unsupported`,reason:O(`chat.mentions.unsupported`)};if(e.preferenceLoading||i===`session`&&t.modelControl.isRestoringPreference()||!t.placementPreferenceReady)return{gate:`preference-restore`,reason:O(`newSession.restoringPreferences`)};let o=r.context?.agents.state,s=()=>({gate:`agents`,reason:O(o?.agentsError?`newSession.agentDefaultsUnavailable`:`newSession.loadingAgentDefaults`)});if(i===`session`&&!e.placementPolicyReady)return o?.agentsList?{gate:`cloud`,reason:O(`newSession.placementNotReady`)}:s();if(i===`session`&&e.requiredProfile&&!e.cloudProfiles.some(t=>t.id===e.requiredProfile))return{gate:`cloud`,reason:O(`newSession.requiredWorkerUnavailable`)};if(i===`session`&&n.requiresModelSetup())return{gate:`model-setup`,reason:O(`modelSetup.required.title`)};if(rs(r.data,r.context?.sessions))return{gate:`route-pending`,reason:O(`newSession.catalogUnavailable`)};if(n.attachmentDraft.reads.pendingReads>0)return{gate:`attachment-reads`,reason:O(`newSession.readingAttachment`)};if(!a&&n.submissionOutcomeUnknown)return{gate:`outcome-unknown`,reason:O(n.submissionOutcomeUnknown===`gateway-changed`?`newSession.createOutcomeUnknown`:`newSession.placementSetupInterrupted`)};let c=r.context?.gateway,l=c?.snapshot.phase===`connected`?c.snapshot.client??null:null;if(!c||!l)return{gate:`disconnected`,reason:O(`sessionsView.actionRequiresConnection`)};if(i===`session`&&!a&&n.visibility===`draft`&&c.snapshot.hello?.policy?.allowedSessionVisibilities?.includes(`draft`)===!1)return{gate:`draft-unavailable`,reason:O(`newSession.draftUnavailable`)};let u=i===`terminal`?Cu(c.snapshot,t.worktree):n.submissionAccess();if(!u.allowed)return{gate:`access`,reason:u.reason};if(i===`terminal`){if(r.context?.config.current.cliAgentsEnabled!==!0||!r.context.config.current.terminalEnabled)return{gate:`terminal-capabilities`,reason:O(`newSession.terminalDisabled`)};if(!r.data?.terminalHosts?.some(e=>e.hostId===t.terminalHostId))return{gate:`device`,reason:O(`newSession.terminalHostUnavailable`)};if(n.attachmentDraft.attachments.length>0)return{gate:`terminal-capabilities`,reason:O(`newSession.terminalAttachmentsUnsupported`)};if(t.remotePlacement||n.pendingPlacement.sessionKey)return{gate:`device`,reason:O(`newSession.terminalPlacementUnsupported`)};if(n.capabilities.toolOverrides!==null)return{gate:`terminal-capabilities`,reason:O(`newSession.terminalCapabilityOverridesUnsupported`)}}if(t.suggestedCloudProfile.pending)return{gate:`cloud`,reason:O(`newSession.placementNotReady`)};if(a)return n.pendingPlacement.retryAllowed&&l.recoveryScopeReady&&Hl(n.pendingPlacement,t)&&n.pendingPlacement.agentId&&n.pendingPlacement.gatewayUrl===c.connection.gatewayUrl&&n.pendingPlacement.recoveryScope===l.recoveryScope?Au(n,i,a):{gate:`placement-recovery`,reason:O(`newSession.placementNotReady`)};if(t.folderSubmissionBlocked())return{gate:`folder`,reason:t.deviceFolder&&t.deviceFolderRuntimeUnsupportedReason||t.currentCheckoutUnavailableReason||O(t.deviceFolder?t.deviceFolderAvailable?`newSession.deviceFolderPathRequired`:`newSession.deviceFolderUnavailable`:`newSession.checkingPlace`)};if(t.deviceFolder&&n.attachmentDraft.attachments.length>0)return{gate:`folder`,reason:O(`newSession.deviceFolderAttachmentsUnsupported`)};if(!o?.agentsList)return s();let d=Hl(n.pendingPlacement,t),f=d?.kind===`profile`?d.profileId:``,p=e.cloudProfiles.find(e=>e.id===f),m=i===`session`&&t.modelControl.modelSelectionBlockedReason(t.selectedAgent(),p?.inference);if(m)return{gate:`model-unavailable`,reason:m};if(t.agents().length===0)return{gate:`agents`,reason:O(`newSession.agentsUnavailable`)};if(!os(r.data,t.selectedAgent()))return{gate:`agent-not-allowed`,reason:O(`newSession.catalogUnavailable`)};let h=i===`session`?t.devicePlacement():void 0;if(h&&!h.ready)return{gate:`device`,reason:h.disabledReason??O(`newSession.nodeUnavailable`)};let g=t.modelControl.devicePlacementUnsupportedReason();if((t.deviceId||t.autoDevice)&&g)return{gate:`device-runtime`,reason:g};if(d&&(!l.recoveryScope||!l.recoveryScopeReady||e.cloudProfilesPending))return{gate:`placement-recovery`,reason:O(`newSession.placementNotReady`)};let _=()=>t.modelControl.cloudRuntimeUnsupportedReason(p);return f&&(!e.cloudProfilesReady||!p||_())?{gate:`cloud`,reason:_()??O(`newSession.placementNotReady`)}:t.worktree&&!t.freshWorkspace&&!t.worktreeAvailable()?{gate:`worktree-unavailable`,reason:t.repository.kind===`checking`?O(`newSession.checkingGit`):t.remotePlacement&&t.repository.kind!==`forbidden`?O(`newSession.remoteSourceUnavailable`):Eu(t.repository)??O(`newSession.gitCheckUnavailable`)}:t.worktree&&!t.freshWorkspace&&!bu(t.worktreeName)?{gate:`worktree-name`,reason:O(`newSession.worktreeNameInvalid`)}:i===`terminal`&&!(t.folder.trim()||!t.terminalOnNode&&t.workspacePath())?{gate:`terminal-folder`,reason:O(`newSession.terminalNeedsFolder`)}:Au(n,i,a)}function Au(e,t,n){if(t!==`session`)return;let r=n?e.pendingPlacement.message:e.message.trim(),i=n?!!e.pendingPlacement.attachments?.length:e.attachmentDraft.attachments.length>0;return r||i?void 0:{gate:`empty-draft`}}var ju;function Mu(){return(Mu=e((()=>{k(),Z(),Bi(),Ho(),Q(),Su(),Gl(),Tu(),X(),ju=new Set([`attachment-reads`,`outcome-unknown`,`worktree-name`])})))()}var Nu;function Pu(){return(Pu=e((()=>{k(),Z(),dn(),rn(),Bi(),Nr(),pa(),_l(),wl(),El(),Q(),jl(),Je(),Nl(),Fl(),Vl(),Gl(),ql(),Yl(),Ql(),du(),Ss(),yu(),Mu(),Tu(),X(),Nu=class{updateMessage(e){e!==this.messageText&&(this.messageText=e,this.callbacks.onMessageChange?.(e))}get creationComposer(){return this.creationComposerValue?.canDisplay()?this.creationComposerValue:void 0}constructor(e,t,n,r){this.gateway=e,this.place=t,this.read=n,this.callbacks=r,this.visibilityValue=`normal`,this.messageText=``,this.mentionsValue=[],this.activeSubmission=null,this.blockedSubmitAttempt=!1,this.rejectedPromptError=null,this.submissionOutcomeUnknown=null,this.startedSession=new vu,this.error=null,this.submitRequest=new AbortController,this.pendingPlacement=new xs(()=>this.read().context),this.composerDraft=je(()=>({draft:this.messageText,mentions:this.mentionsValue,attachments:this.attachmentDraft.attachments,pendingAttachmentReads:this.attachmentDraft.reads.pendingReads,attachmentReadRevision:this.attachmentDraft.reads.revision})),this.draftChanged=()=>{this.composerDraft.publish(),this.callbacks.changed()},this.composerTextarea=Al(),this.buildDraftSessionCreateParams=(e={})=>Pl(this.place,{...e,message:e.message??``,toolOverrides:this.capabilities.toolOverrides,permissionMode:this.permissionMode,visibility:e.visibility??this.visibility,catalogId:this.read().data?.catalogId,category:is(this.read().data,this.read().context?.sessions)}),this.submissionAccess=(e=this.pendingPlacement.createParams??this.buildDraftSessionCreateParams())=>Du({gateway:this.read().context?.gateway.snapshot,place:this.place,pendingPlacement:this.pendingPlacement,hasInitialTurn:!!(this.messageText.trim()||this.attachmentDraft.attachments.length),createParams:e}),this.submitDisabledReason=()=>this.submitBlock()?.reason,this.canSubmit=()=>this.submitBlock()===void 0,this.requiresModelSetup=()=>Ou({snapshot:this.read(),gateway:this.gateway,place:this.place,pendingPlacement:this.pendingPlacement}),this.capabilities=new Tl(r.changed,()=>this.startedSession.current=null),this.sessionStartup=new Kl(e),this.draftPersistence=new Bl(()=>({message:this.messageText,mentions:this.mentionsValue,attachments:this.attachmentDraft.attachments,incognito:this.visibilityValue===`incognito`,permissionMode:this.permissionMode}),(e,t)=>this.restoreDraftState({...e,visibility:t?`normal`:this.visibilityValue}),()=>this.setError(Qn)),this.attachmentDraft=new gl(this.draftChanged,()=>{this.rejectedPromptError=null,this.startedSession.current=null,this.draftPersistence.noteUserMutation()})}get visibility(){return this.visibilityValue}get message(){return this.messageText}get mentions(){return this.mentionsValue}get submitting(){return this.activeSubmission!==null||this.sessionStartup.active}get pendingMessage(){return this.activeSubmission?.message??this.completedSubmission?.message??null}get completedSubmission(){return this.activeSubmission?null:this.startedSession.submission(this.read().context)}openSubmittedSession(){return this.startedSession.openSubmission(this.read().context,this.completedSubmission,{capture:()=>{let e=this.captureSubmitRequest();return()=>!e.aborted},publish:(e,t)=>{this.activeSubmission=e?{phase:`accepted`,message:e}:null,t!==void 0&&(this.error=t),this.callbacks.changed()}})}synchronizeSubmission(){this.blockedSubmitAttempt=this.blockedSubmitAttempt&&!!this.submitBlock()?.reason;let e=this.sessionStartup.resume();e.kind===`resume`?this.submit(e):e.kind!==`wait`&&(this.activeSubmission=null,this.submissionOutcomeUnknown=`gateway-changed`,this.callbacks.changed())}setMessage(e,t){e!==this.messageText&&(this.rejectedPromptError=null),this.startedSession.current=null,this.mentionsValue=t??hn(this.messageText,e,this.mentionsValue),this.updateMessage(e),this.draftPersistence.noteUserMutation(),this.draftChanged()}restoreMessage(e,t=[]){this.rejectedPromptError=null,this.draftPersistence.noteDraftReplaced(),this.updateMessage(e),this.mentionsValue=t,this.draftChanged()}restoreDraftState(e){this.draftPersistence.noteDraftReplaced(),this.updateMessage(e.message),this.mentionsValue=e.mentions??[],this.visibilityValue=e.visibility,e.toolOverrides!==void 0&&this.capabilities.setToolOverrides(e.toolOverrides),`permissionMode`in e&&(this.permissionMode=e.permissionMode),this.attachmentDraft.restore(e.attachments)}setPermissionMode(e){this.permissionMode=e,this.startedSession.current=null,this.draftPersistence.noteSelectionMutation(`permission`),this.callbacks.changed()}setVisibility(e){this.startedSession.current=null;let t=this.visibilityValue===`incognito`,n=this.callbacks.changed;this.visibilityValue=e,this.draftPersistence.transitionIncognito(t,e===`incognito`,n)}setError(e){(e!==null||this.error===O(`newSession.cloudRecoveryUnavailable`))&&(this.error=e),this.callbacks.changed()}clearError(e){(e===void 0||this.error===e)&&(this.error=null,this.callbacks.changed())}markPendingPlacementUnavailable(e){this.pendingPlacement.retryAllowed=!1,this.submissionOutcomeUnknown=e,this.callbacks.changed()}noteBlockedSubmitAttempt(){this.blockedSubmitAttempt=!!this.submitBlock()?.reason,this.callbacks.changed()}blockedSubmitNotice(){let e=this.submitBlock();return e?.gate===`draft-unavailable`||this.blockedSubmitAttempt&&e&&!ju.has(e.gate)?e.reason:void 0}incognitoDisabledReason(){let e=P(this.read().context?.gateway.snapshot,{method:`sessions.create`,params:this.buildDraftSessionCreateParams({visibility:`incognito`})});return e.allowed?void 0:e.reason}submitBlock(){return this.rejectedPromptError?{gate:`initial-turn-rejected`,reason:this.rejectedPromptError}:!M(this.read().data)&&this.attachmentDraft.reads.pendingReads===0&&this.startedSession.isCurrent(this.read().context,this.place.agentId)?this.activeSubmission?{gate:`submitting`}:void 0:this.activeSubmission?{gate:`submitting`}:ku(this.gateway,this.place,this,this.read())}captureSubmitRequest(){return this.submitRequest.abort(),this.submitRequest=new AbortController,this.submitRequest.signal}invalidate(e=null){this.submitRequest.abort(),this.startedSession.current=null;let t=this.activeSubmission?.phase===`creating`,n=e!==null&&t&&this.sessionStartup.interrupt();(e&&t&&!n||this.sessionStartup.retireChangedOwner())&&(this.submissionOutcomeUnknown=e),n||(this.activeSubmission=null),this.callbacks.changed()}resetDraft(){this.creationComposerValue?.releaseDraft(),this.creationComposerValue=void 0,this.startedSession.clearSubmission(),this.rejectedPromptError=null,this.sessionStartup.clear(),this.blockedSubmitAttempt=!1;let e=!!this.pendingPlacement.sessionKey;this.invalidate(),this.submissionOutcomeUnknown=e?this.submissionOutcomeUnknown??`placement-interrupted`:null,this.visibilityValue=`normal`,this.capabilities.reset(),this.permissionMode=void 0,this.attachmentDraft.reset(),e?(this.pendingPlacement.restored||(this.pendingPlacement.retryAllowed=!1),this.applyRecoveryDraft(this.pendingPlacement.capture()),this.pendingPlacement.restored=!1):(this.clearPendingPlacementRecovery(),this.draftPersistence.noteDraftReplaced(),this.updateMessage(``),this.mentionsValue=[]),this.clearError(),this.composerDraft.publish()}clearPendingPlacementRecovery(){this.pendingPlacement.clear(),this.submissionOutcomeUnknown=null,this.callbacks.changed()}releasePendingPlacementOwner(){this.pendingPlacement.reset(),this.submissionOutcomeUnknown=null,this.callbacks.changed()}restorePendingPlacementRecovery(e,t){this.applyRecoveryDraft(this.pendingPlacement.restore(e,t))}async submit(e,t=!1){if(!e&&M(this.read().data))return this.startInTerminal();let n=this.pendingPlacement,r=e?.background??(t&&this.visibilityValue!==`draft`),i=this.read().context;if(!i||!e&&!this.canSubmit()){this.noteBlockedSubmitAttempt();return}if(this.blockedSubmitAttempt=!1,!In(i.config)&&(this.attachmentDraft.attachments.length||n.attachments?.length||e?.params.attachments?.length)){this.error=wr(),this.callbacks.changed();return}let a=Jl(i,this,this.place,e,r);if(!a)return;let o=this.callbacks.takePreparedTitle?.(),s=this.captureSubmitRequest(),c=this.draftPersistence.captureSubmission(),l=this.startedSession.messageForTurn(i,a.agentId,a.turn),u=this.startedSession.captureSubmission(i,a.agentId,l,()=>!s.aborted);this.activeSubmission={phase:`creating`,message:l},this.error=null,this.place.browser.close(),this.callbacks.closeTransientUi(),this.callbacks.changed();let d,f;try{let t=this.startedSession.current;if(t&&this.startedSession.isCurrent(i,this.place.agentId)){await this.startedSession.navigate(i,t);return}this.startedSession.current=null,!r&&this.callbacks.retainForHandoff&&(!this.creationComposer||this.creationComposer.acceptedSessionKey)&&(this.creationComposerValue?.releaseDraft(),this.creationComposerValue=new Ml(i,a.agentId,this.visibilityValue===`incognito`,this.callbacks.changed)),this.creationComposer&&this.visibilityValue===`incognito`&&(this.creationComposer.incognito=!0);let l=e?null:Hl(n,this.place);Sl(i,a.message,!!a.apiAttachments?.length,!e&&!a.pendingPlacement);let p=!this.place.hostedEnvironment&&!e&&!a.pendingPlacement&&!l&&!a.hasInitialTurn?this.place.browser.remoteProject:null;if(p&&!p.projectId&&!this.place.browser.projectId){let e=await a.client.request(`projects.add`,{gitUrl:p.cloneUrl},{timeoutMs:null});if(s.aborted||this.gateway.client!==a.client)return;this.place.browser.recordRemoteProjectId(p.cloneUrl,e.id)}let m=e?.params??this.buildDraftSessionCreateParams({message:a.message,mentions:a.mentions,displayName:o,visibility:this.visibilityValue,attachments:a.draftAttachments}),h=cu({context:i,params:m,resumed:!!e,enabled:!r&&!l,agentId:a.agentId,retainDraft:this.callbacks.retainForHandoff,message:this.pendingMessage,composer:this.creationComposer}),g=l?a.pendingPlacement?n.createParams:n.stageCreate({agentId:a.agentId,target:l,message:a.message,mentions:a.mentions,attachments:a.apiAttachments,gatewayUrl:a.gatewayUrl,recoveryScope:a.recoveryScope,createParams:m,persistent:this.visibilityValue!==`incognito`}):void 0,_=e?P(i.gateway.snapshot,{method:`sessions.create`,params:m,sessionScope:!0}):this.submissionAccess(g??m);if(!_.allowed){this.sessionStartup.clear(),this.error=_.reason;return}let v=l?n.capture():null;if(l&&!v){this.error=O(`newSession.placementCreateFailed`);return}a.apiAttachments?.length&&ui(i.config);let y=a.pendingPlacement&&n.phase!==`creating`?Promise.resolve({key:n.sessionKey,initialRun:{status:`idle`}}):i.sessions.createResult(g??e?.params??this.sessionStartup.start(m,r),{reconciliation:`background`,signal:s});d=h?.();let b=await y;if(b&&!l&&b.initialRun.status!==`rejected`&&(f=a.consumeWorktreeName?.()),s.aborted&&!l){b&&b.initialRun.status!==`rejected`&&await this.clearSubmittedDraft(!0,c,!1);return}if(!b){if(s.aborted)return;this.sessionStartup.clear(),this.error=i.sessions.state.error??O(`newSession.createFailed`),d&&await d.rollback();return}if(l&&v){await Wl({context:i,client:a.client,agentId:a.agentId,pending:n,submittedRecovery:v,sessionKey:b.key,createdAt:a.turn.createdAt,startupError:b.initialRun.status===`rejected`?b.initialRun.error:void 0,isRequestCurrent:()=>!s.aborted,isLifecycleCurrent:()=>this.read().isConnected&&a.client.recoveryScopeReady&&!s.aborted&&this.gateway.client===a.client&&this.gateway.gatewayUrl===a.gatewayUrl&&this.gateway.recoveryScope===a.recoveryScope,clearRecovery:()=>this.clearPendingPlacementRecovery(),setError:e=>this.setError(e),onRecoveryUnavailable:()=>{this.error=O(`newSession.placementStartFailed`,{error:`placement recovery storage is unavailable`})},clearDraft:()=>{let e=this.creationComposer;return e&&(e.accept(b),We(i,b.key,e)),u(b.key),this.clearSubmittedDraft(!0,c)},consumeWorktreeName:a.consumeWorktreeName,completeInBackground:a.completeInBackground,onAccepted:()=>this.callbacks.onAccepted?.({...b,agentId:a.agentId}),navigate:()=>this.startedSession.navigate(i,{...b,client:a.client,agentId:a.agentId})});return}await Zl({onRejectedPrompt:r&&this.callbacks.retainRejectedPrompt?e=>{this.rejectedPromptError=e,this.error=e,this.sessionStartup.clear()}:void 0,context:i,client:a.client,agentId:a.agentId,result:b,turn:a.turn,instant:d,composer:this.creationComposer,navigation:this.startedSession,isCurrent:()=>!s.aborted,clearDraft:(e,t)=>(t!==!1&&u(b.key,b.initialRun.status===`rejected`?b.initialRun.error:void 0),this.clearSubmittedDraft(e,c,t)),completeInBackground:a.completeInBackground,onAccepted:()=>this.callbacks.onAccepted?.({...b,agentId:a.agentId}),finishNavigation:()=>this.sessionStartup.clear()})}catch(e){!s.aborted&&this.gateway.client===a.client&&(this.sessionStartup.clear(),this.error=e instanceof Error?e.message:String(e),d&&await d.rollback())}finally{(f||d)&&await Promise.all([f,d?.finish()]),s.aborted||(this.activeSubmission=null,this.callbacks.changed())}}startInTerminal(){return wu({snapshot:this.read(),place:this.place,flow:this,closeTransientUi:this.callbacks.closeTransientUi,capture:e=>{this.blockedSubmitAttempt=!1,this.error=null;let t=this.captureSubmitRequest(),n=this.draftPersistence.captureSubmission(),r=()=>!t.aborted;return{isRequestCurrent:r,isCurrent:()=>r()&&this.gateway.client===e,publish:(e,t)=>{this.activeSubmission=t?{phase:`creating`,message:e}:null,this.callbacks.changed()},consume:()=>(this.startedSession.current=null,this.clearSubmittedDraft(!0,n))}}})}clearSubmittedDraft(e,t,n=!0){return this.draftPersistence.clearSubmittedDraft(t,()=>{n?this.activeSubmission&&(this.activeSubmission.phase=`accepted`):this.activeSubmission=null,this.updateMessage(``),this.mentionsValue=[],this.permissionMode=void 0,this.draftPersistence.noteDraftReplaced(),this.attachmentDraft.clearAfterSubmit(e),this.sessionStartup.clear()})}disconnect(){this.submitRequest.abort(),this.creationComposerValue?.releaseDraft(),this.pendingPlacement.releaseClaim(),this.startedSession.current=null,this.draftPersistence.disconnect(),this.attachmentDraft.reset(),this.composerTextarea.disconnect()}applyRecoveryDraft(e){if(e){let t=Ul(e);this.place.applyPendingPlacement(t.placement),this.restoreDraftState(t.draft)}}}})))()}function Fu(e){return Lu.has(e)}function Iu(e){let t=new Map;for(let n of e){let e=(n.deviceId??n.instanceId)?.trim().toLowerCase();e&&n.roles?.includes(`node`)&&t.set(e,n.reason?.trim().toLowerCase()===`disconnect`?`offline`:`connected`)}return JSON.stringify([...t].toSorted(([e],[t])=>e.localeCompare(t)))}var Lu;function Ru(){return(Ru=e((()=>{Lu=new Set([`config.changed`,`node.pair.requested`,`node.pair.resolved`,`node.runnerInventory.changed`,`device.pair.requested`,`device.pair.resolved`])})))()}var zu;function Bu(){return(Bu=e((()=>{Le(),hr(),Ln(),k(),$i(),Me(),Q(),Ts(),Gs(),hl(),Pu(),Ru(),zu=class{protectPrivateDraftFromReload(){let e=()=>this.submission.visibility===`incognito`&&!!(this.submission.message||this.submission.mentions.length||this.submission.attachmentDraft.attachments.length||this.submission.attachmentDraft.reads.pendingReads),t=(e=!1)=>Yn({message:O(e?`chat.privateDraftReload.changed`:`chat.privateDraftReload.blocked`),actionLabel:O(`chat.privateDraftReload.review`),onAction:()=>void n()}),n=async()=>{let n=this.read().context;if(!n||!this.read().isConnected||!e()||this.privateDraftReview)return;let r=new AbortController,i=n.gateway.snapshot.client,a=n.gateway.connection,o=this.submission.message,s=this.submission.mentions,c=[...this.submission.attachmentDraft.attachments],l=this.submission.attachmentDraft.reads.pendingReads,u=()=>!r.signal.aborted&&this.read().isConnected&&this.read().context===n&&n.gateway.snapshot.client===i&&n.gateway.connection===a,d=()=>u()&&this.submission.visibility===`incognito`&&this.submission.message===o&&this.submission.mentions===s&&this.submission.attachmentDraft.reads.pendingReads===l&&this.submission.attachmentDraft.attachments.length===c.length&&c.every((e,t)=>this.submission.attachmentDraft.attachments[t]===e);this.privateDraftReview={controller:r,isCurrent:d};let f=xe(n.gateway);try{let n=await ht({text:o,attachments:c,hasGoal:!1,pendingReads:l,isCurrent:d,signal:r.signal});if(!d()){u()&&e()&&t(!0);return}if(!n)return;this.submission.attachmentDraft.reset(),this.submission.setMessage(``,[]),await Xn({timeoutMs:0,...f})}catch{u()&&Yn({message:O(`chat.privateDraftReload.unavailable`)})}finally{this.privateDraftReview?.controller===r&&(this.privateDraftReview=void 0),r.signal.reason===`draft-changed`&&this.read().isConnected&&this.read().context===n&&n.gateway.connection===a&&n.gateway.snapshot.client===i&&e()&&t(!0)}},r=oa(()=>!e(),()=>t());return()=>{r(),this.privateDraftReview?.controller.abort()}}constructor(e,t){this.read=e;let n=this.changed=()=>{this.privateDraftReview&&!this.privateDraftReview.isCurrent()&&this.privateDraftReview.controller.abort(`draft-changed`),t.changed()};this.gateway=new ws(()=>({...e(),isAdmin:this.place?.isAdmin()??!1,cloudProfileId:this.place?.cloudProfileId??``,pendingPlacement:this.submission?.pendingPlacement??{sessionKey:``,gatewayUrl:``,recoveryScope:``},agentsHydrated:this.place?.agentsHydrated??!1,runtimeId:this.place?.devicePlacementRuntime()?.id??``}),{preferenceScope:t.preferenceScope,readPalettePreference:t.readPalettePreference,readAgents:()=>e().context?.agents,changed:n,updateComplete:t.updateComplete,onInvalidate:(e,n)=>{this.invalidate(e,n),t.onInvalidate()},onCloudProfileCleared:()=>this.place.clearCloudProfile(),onCloudState:e=>this.submission.setError(e),onPendingPlacementReset:()=>this.submission.releasePendingPlacementOwner(),onRecoveryReady:t.onRecoveryReady,onAdoptAgentDefaults:()=>this.place.adoptAgentDefaults({preserveSelectedAgent:!0,preserveSelectedFolder:!0})}),this.browser=new Ws(this.gateway,()=>({context:e().context,isAdmin:this.place?.isAdmin()??!1}),{changed:n,updateComplete:t.updateComplete,onProjectMissing:()=>this.place.clearProjectSelection(),onSelectProject:e=>this.place.selectProjectId(e),onApprovedListing:e=>this.place.recordGatewayApprovedListing(e),activeElement:t.activeElement}),this.place=new ml(this.gateway,this.browser,()=>({context:e().context,data:e().data,submitting:this.submission?.submitting??!1,pendingPlacementSessionKey:this.submission?.pendingPlacement.sessionKey??``}),{changed:n,onError:e=>e===null?this.submission.clearError():this.submission.setError(e),onClearError:e=>this.submission.clearError(e)}),this.submission=new Nu(this.gateway,this.place,e,{...t,changed:n}),this.submission.draftPersistence.modelSelection={read:()=>this.place.modelControl.modelDefaultsPolicy===`configured`?this.place.modelControl.draftSelection(this.place.agentId):void 0,restore:e=>this.place.modelControl.restoreDraftSelection(e),retire:()=>{this.place.modelControl.modelDefaultsPolicy===`configured`&&this.place.modelControl.retireDraftSelection()}},this.place.modelControl.onDraftSelectionChange=()=>{this.place.modelControl.modelDefaultsPolicy===`configured`&&this.submission.draftPersistence.noteSelectionMutation(`model`)}}connect(){if(!this.stopLifetime){let e=this.protectPrivateDraftFromReload(),t=C(document,`visibilitychange`,()=>{this.synchronize(),this.changed()});this.stopLifetime=()=>{t(),e()}}this.synchronize()}synchronize(){if(!this.stopLifetime)return;let e=this.read().context?.gateway;if(e!==this.boundGateway&&(this.stopGateway?.(),this.stopGateway=void 0,this.boundGateway=e,e)){let t=e.subscribe(()=>{this.read().context?.gateway===e&&this.gateway.synchronize(e)}),n=Iu(rr(e.snapshot.hello?.snapshot)??[]),r=e.subscribeEvents(t=>{if(this.read().context?.gateway!==e)return;let r=t.event===`presence`?rr(t.payload):null,i=r?Iu(r):n;(Fu(t.event)||i!==n)&&(n=i,this.gateway.refreshCloudProfiles(),this.gateway.handleCatalogRetry())});this.stopGateway=()=>{t(),r()},this.gateway.synchronize(e)}this.gateway.synchronizeMetadata(),this.browser.synchronize()}agentsReady(){let e=this.read().context?.agents.state;return!!(this.gateway.connected&&this.gateway.client&&e?.connected&&!e.agentsLoading&&!e.agentsError&&e.client===this.gateway.client&&this.place.agents().length>0)}synchronizeSelections(){let e=this.place.requiredPlacement?`configured`:this.read().context?.config?.current.newSessionModelDefaults;if(!this.place.agentsHydrated&&this.agentsReady())this.place.agentsHydrated=!0,this.place.adoptAgentDefaults({preserveSelectedAgent:!0,preserveSelectedFolder:!0});else if(this.place.agentsHydrated&&e!==this.modelDefaultsPolicy){let{context:e,data:t}=this.read();this.place.modelControl.load(e,this.place.agentId,!M(t),{agent:this.place.selectedAgent(),preference:this.gateway.readPreference(this.place.agentId),configuredDefaults:this.place.requiredPlacement})}this.place.modelControl.modelDefaultsPolicy===`configured`&&this.modelDefaultsPolicy!==`configured`&&!this.submission.submitting&&this.place.modelControl.draftSelection(this.place.agentId)&&this.submission.draftPersistence.noteSelectionMutation(`model`),this.modelDefaultsPolicy=this.place.modelControl.modelDefaultsPolicy,this.place.restorePreferenceSelections(),this.place.synchronizeTerminalHosts()}invalidate(e,t){this.place.invalidateGatewayDiscovery(e),this.submission.attachmentDraft.reads.abortReads(),this.submission.invalidate(t),e&&this.submission.pendingPlacement.sessionKey&&this.submission.markPendingPlacementUnavailable(t),e&&this.submission.clearError()}disconnect(){this.stopLifetime?.(),this.stopLifetime=void 0,this.stopGateway?.(),this.stopGateway=void 0,this.boundGateway=void 0,this.gateway.invalidateDiscovery(!0,this.submission.pendingPlacement.sessionKey?`placement-interrupted`:`gateway-changed`),this.gateway.disconnect(),this.browser.disconnect(),this.submission.disconnect()}}})))()}function Vu(e){let t=e.context?.gateway,n=t?.snapshot.client,r=t?.snapshot.selfUser?.identity;if(n&&t?.snapshot.phase===`connected`&&r?.type===`profile`&&P(t.snapshot,{method:`sessions.create`,sessionScope:!0}).allowed&&!e.isCatalogTarget&&!e.nativeTerminal&&e.visibility!==`incognito`)return{client:n,ownerKey:JSON.stringify([t.connectionRevision,n.recoveryScope,r.id,e.draftOwnerKey]),params:{agentId:e.agentId,...e.visibility===`draft`?{visibility:`draft`}:{}}}}function Hu(){return(Hu=e((()=>{Bi()})))()}function Uu(e){let[t,n]=Ma(!1),r=Ya(function*(e){e.isCurrent()&&n(!0),yield Promise.race([e.completion,e.retired])});H(()=>e.subscribeRequests(e=>{H(()=>{r(e).catch(e.reportError)})}));let i=()=>t()||e.loading,a=()=>e.setup?.expiresAtMs?Ye(e.setup.expiresAtMs,{hour:`numeric`,minute:`2-digit`},``):``;return U(L,{get when(){return e.open},get children(){var t=Wu(),n=t.firstChild.firstChild,r=n.firstChild,o=r.firstChild,s=o.nextSibling,c=r.nextSibling,l=n.nextSibling,u=l.firstChild,d=u.nextSibling,f=d.nextSibling,p=l.nextSibling,m=p.firstChild;return t.addEventListener(`modal-cancel`,()=>e.onClose()),t._$owner=La(),z(o,()=>N(`newSession.connectMachineTitle`)),z(s,()=>N(`newSession.connectMachineDescription`)),c._$$click=()=>e.onClose(),z(c,U(F,{name:`x`})),z(l,(()=>{var t=B(()=>!(!i()||e.setup?.command));return()=>t()?(()=>{var e=Gu();return z(e,()=>N(`newSession.connectMachineGenerating`)),e})():void 0})(),u),z(l,(()=>{var t=B(()=>!!e.error);return()=>t()?(()=>{var t=Ku(),n=t.firstChild,r=n.nextSibling;return z(t,()=>N(`newSession.connectMachineFailed`),n),z(t,()=>e.error,r),t})():void 0})(),d),z(l,U(L,{get when(){return e.setup},children:e=>[U(uo,{get command(){return e().command}}),(()=>{var e=qu();return z(e,()=>N(`newSession.connectMachineTeamHint`)),e})(),(()=>{var t=Ju(),n=t.firstChild,r=n.nextSibling;return z(t,()=>N(`newSession.connectMachineInstalled`),n),z(r,()=>e().installedCommand),t})(),(()=>{var t=qu();return z(t,()=>e().versionNote),W(()=>!e().versionNote,e=>{V(t,`hidden`,e)}),t})(),(()=>{var t=Yu(),n=t.firstChild;return z(n,()=>N(`newSession.connectMachineCommandOnly`)),z(t,U(uo,{get command(){return e().serviceCommand}}),null),t})(),(()=>{var e=qu();return z(e,(()=>{var e=B(()=>!!a());return()=>e()?N(`newSession.connectMachineSingleUseExpires`,{time:a()}):N(`newSession.connectMachineSingleUse`)})()),e})()]}),f),p._$owner=La(),z(p,(()=>{var t=B(()=>!!(e.setup?.command||e.error));return()=>t()?(()=>{var t=Xu(),n=t.firstChild,r=n.nextSibling;return t._$$click=()=>e.onRefresh(),z(t,U(F,{name:`refresh`}),n),z(t,(()=>{var e=B(()=>!!i());return()=>e()?N(`newSession.connectMachineRefreshing`):N(`newSession.connectMachineFreshCode`)})(),r),W(()=>i(),e=>{V(t,`disabled`,e)}),t})():void 0})(),m),m._$$click=()=>e.onManageDevices(),z(m,()=>N(`newSession.connectMachineManageDevices`)),W(()=>({e:N(`newSession.connectMachineTitle`),t:N(`newSession.connectMachineDescription`),a:N(`common.dismiss`)}),({e,t:n,a:r},i)=>{e!==i?.e&&V(t,`label`,e),n!==i?.t&&V(t,`description`,n),r!==i?.a&&V(c,`aria-label`,r)}),t}})}var Wu,Gu,Ku,qu,Ju,Yu,Xu;function Zu(){return(Zu=e((()=>{K(),R(),_o(),A(),Za(),ri(),j(),Wu=q(`<openclaw-modal-dialog class=connect-machine-dialog><section class="exec-approval-card connect-machine-dialog__card"><header class=exec-approval-header><div><h2 class=exec-approval-title></h2><p class=exec-approval-sub></p></div><button class="btn btn--icon btn--ghost"type=button></button></header><div class=connect-machine-dialog__body><!><!><!></div><openclaw-modal-actions class="exec-approval-actions connect-machine-dialog__actions"><button class="btn btn--ghost"type=button>`,1),Gu=q(`<p class=connect-machine-dialog__status role=status>`),Ku=q(`<p class=exec-approval-error role=alert> <!>`),qu=q(`<p class=connect-machine-dialog__hint>`),Ju=q(`<p class=connect-machine-dialog__hint> <code translate=no style=overflow-wrap:anywhere>`),Yu=q(`<details><summary>`),Xu=q(`<button class=btn type=button><!><!>`),Ka([`click`])})))()}function Qu(e,t,n=t.cloudProfiles){return{hostedEnvironment:e.hostedEnvironment?{...e.hostedEnvironment,id:e.modelControl.resolveAgentRuntime().id}:void 0,environments:e.canWrite()?t.environments:[],cloudProfiles:n,cloudProfileId:e.cloudProfileId,...e.cloudSelection,deviceId:e.deviceId,autoDevice:e.autoDevice,devicePlacement:Yc(e.modelControl)?.devicePlacement,deviceDisabledReason:Xc(e.modelControl)??t.deviceCatalogDisabledReason}}function $u(e){let t=rc(e.environments,e.devicePlacement,e.deviceDisabledReason),n=ic(e.environments,t,e.deviceDisabledReason),r=t.find(t=>t.deviceId===e.deviceId),i=e.cloudProfiles.find(t=>t.id===e.cloudProfileId),a={devices:t,cloudProfiles:e.cloudProfiles,cloudMachines:[],selectedMachineId:``,operatingSystems:[],selectedOsId:``,autoDeviceDisabledReason:n};if(e.hostedEnvironment)return{...a,kind:`hosted`,label:e.hostedEnvironment.label,hostedRuntimeId:e.hostedEnvironment.id};if(e.cloudProfileId){let t=i?dc(i):``,n=e.os||t,r=i?.operatingSystems??[],o=i?fc(i,n):[],s=i?pc(i,n):void 0,c=e.machineClass?o.find(t=>t.id===e.machineClass):s;return{...a,kind:`cloud`,label:i?.id??e.cloudProfileId,operatingSystems:r,selectedOsId:n,cloudMachines:o,selectedMachineId:c?.id??``}}return{...a,kind:e.deviceId?`device`:e.autoDevice?`auto-device`:`local`,label:e.deviceId?r?.label??e.deviceId:O(e.autoDevice?`newSession.autoDevice`:`newSession.local`)}}function ed(){return(ed=e((()=>{k(),Z(),lc(),Qc(),X()})))()}function td(e,t,n,r,i){let a=I(()=>{n();let r=e();return{owner:r,retired:t(r)}},{equals:(e,t)=>e.owner===t.owner&&e.retired===t.retired}),o=I(()=>{let e=a(),[t,n]=Ma(!1);return{...e,saving:t,setSaving:n}}),s=n=>e()===n.owner&&t(n.owner)===n.retired,c=Ya(function*(e,t){s(e)&&(e.setSaving(!0),Da(r)),yield Promise.race([t,e.retired]),s(e)&&(yield Ha(r))});return{saving:()=>o().saving(),submit:e=>{let t=o(),n=e();return Promise.resolve().then(()=>c(t,n)).catch(e=>{s(t)&&i(t.owner,e)}),n}}}function nd(e,t,n,r){let{saving:i,submit:a}=td(e,e=>e.submissionLifetime,t,n,(e,t)=>r(t));return H(()=>{let t=e();return t.presentSubmit=a,()=>{t.presentSubmit===a&&(t.presentSubmit=void 0)}}),i}function rd(){return(rd=e((()=>{R()})))()}function id(e){let t,n,r;return H(()=>()=>r?.()),[(()=>{var r=od(),i=r.firstChild,a=i.firstChild,o=a.nextSibling,s=o.nextSibling,c=s.nextSibling;return Ja(i,[{get"aria-label"(){return e.label}},()=>e.triggerAttributes,{get id(){return`new-session-${e.kind}-trigger`},type:`button`,class:`new-session-page__trigger`,"aria-haspopup":`dialog`,get"aria-controls"(){return`new-session-${e.kind}-popover`},get"aria-expanded"(){return e.params.place.browser.popoverOpen(e.kind)?`true`:`false`},get disabled(){return e.params.submitting||e.params.pendingPlacement||e.kind===`where`&&e.params.place.suggestedCloudProfile.pending},onClick:()=>n.overlay.request(!n.overlay.open)}],!0),G(()=>e=>{t=e},i),z(a,()=>e.icon),z(o,()=>e.value),z(i,(()=>{var t=B(()=>!!e.summary);return()=>t()?[` `,(()=>{var t=sd();return z(t,()=>e.summary),t})()]:void 0})(),s),z(s,U(F,{name:`chevronDown`})),z(c,U(F,{name:`chevronsUpDown`})),W(()=>e.kind===`where`,e=>{r.classList.toggle(`new-session-page__select--where`,e)}),r})(),U(Zi,{get lazy(){return e.lazy},get onBeforeShow(){return e.onBeforeShow},get id(){return`new-session-${e.kind}-popover`},get label(){return e.label},anchor:t,get class(){return[`new-session-page__select`,`new-session-page__${e.kind}-popover`,`new-session-page__picker-popover`]},get open(){return e.params.place.browser.popoverOpen(e.kind)},placement:`bottom-start`,onOpenChange:t=>{e.params.place.browser.popoverCallbacks(e.kind)[t?`onPopoverShow`:`onPopoverHide`]()},ref:i=>{n=i;let a=i.overlay.surface,o=[C(a,`overlay-after-hide`,n=>{if(n.target===a){let n=a.ownerDocument.activeElement;(!n||n===a.ownerDocument.body||a.contains(n))&&t.focus(),e.params.place.browser.popoverCallbacks(e.kind).onPopoverAfterHide(),e.onAfterHide?.()}}),C(a,`click`,e=>{!e.defaultPrevented&&e.target instanceof Element&&e.target.closest(`[data-popover="close"]`)&&i.overlay.request(!1,`return`)})];r=()=>o.forEach(e=>e()),e.ref?.(i)},get children(){return U(Ra,{fallback:(t,n)=>U(ad,{get error(){return t()},retry:n,isOpen:()=>e.params.place.browser.popoverOpen(e.kind)}),get children(){return U(qa,{get fallback(){var e=cd();return z(e,()=>N(`common.loading`)),e},get children(){return e.children}})}})}})]}function ad(e){let t=!0;H(()=>()=>{t=!1});let n=async()=>{let n=ea(e.error)&&await Xn({canReload:()=>t&&e.isOpen()});t&&e.isOpen()&&!n&&e.retry()};return U(Fi,{get error(){return e.error},get stale(){return ea(e.error)},onRetry:()=>void n(),inline:!0})}var od,sd,cd;function ld(){return(ld=e((()=>{K(),R(),Ln(),A(),li(),fr(),j(),od=q(`<span class=new-session-page__select><button><span class=new-session-page__target-icon aria-hidden=true></span><span class=new-session-page__trigger-label></span><span class="new-session-page__trigger-chevron new-session-page__trigger-chevron--desktop"aria-hidden=true></span><span class="new-session-page__trigger-chevron new-session-page__trigger-chevron--mobile"aria-hidden=true>`),sd=q(`<span class=new-session-page__trigger-summary>`),cd=q(`<div role=status>`)})))()}function ud(e){let t=I(()=>{let t=e.params.place,n=t.cloudProfileId?`cloud`:t.remotePlacement?`remote`:`local`,r=t.worktreeName.trim();if(t.worktree&&!t.remoteRepository&&r)return N(`newSession.checkoutWorktreeNamed`,{name:r});if(n!==`cloud`&&!t.remoteRepository&&!t.worktree)return(t.repository.kind===`git`?t.repository.headBranch:void 0)||N(`newSession.checkoutCurrent`);let i=n===`cloud`?[`newSession.checkoutCloud`,`newSession.checkoutCloudFrom`]:t.remoteRepository?[`newSession.checkoutRepository`,`newSession.checkoutRepositoryFrom`]:[`newSession.checkoutWorktree`,`newSession.checkoutWorktreeFrom`];return t.baseRef?N(i[1],{branch:t.baseRef}):N(i[0])}),n,r=!1;return U(id,{lazy:!0,kind:`checkout`,get label(){return`${N(`newSession.checkout`)}: ${t()}`},get value(){return t()},get icon(){return U(F,{name:`gitBranch`})},get triggerAttributes(){return{title:`${N(`newSession.checkout`)}: ${t()}`,"data-worktree":String(e.params.place.worktree)}},get params(){return e.params},ref:e=>{n=e},onAfterHide:()=>{r&&(r=!1,e.params.onFocusComposer())},get children(){return U(dd,{get params(){return e.params},get folderLabel(){return e.folderLabel},onClose:()=>n.hide(),onConfirm:()=>{n.hide()&&(r=!0)}})}})}var dd;function fd(){return(fd=e((()=>{K(),R(),A(),Z(),bt(),j(),ld(),E(),X(),dd=Va(()=>w(()=>import(`./checkout-picker-content-ByYYaTKf.js`),__vite__mapDeps([9,0,1]),import.meta.url),{export:`CheckoutPickerContent`},`src/pages/new-session/checkout-picker-content.tsx`),xn(dd.preload)})))()}function pd(e){let t=()=>{let t=e.params.place.deviceFolder;return t?Ae(t.path.trim())||N(`newSession.deviceFolder`):e.state.label};return U(id,{lazy:!0,kind:`project`,get label(){return`${N(`newSession.what`)}: ${t()}`},get value(){return t()},get icon(){return U(F,{get name(){return e.params.place.browser.projectId?`gitBranch`:`folder`}})},get triggerAttributes(){return{"data-project-id":e.params.place.browser.projectId||void 0}},get params(){return e.params},get children(){return U(md,{get params(){return e.params},get state(){return e.state},get nativeTerminal(){return e.nativeTerminal},get focus(){return e.focus}})}})}var md;function hd(){return(hd=e((()=>{K(),R(),A(),bt(),j(),ld(),E(),md=Va(()=>w(()=>import(`./project-picker-content-U-AyGLb4.js`),__vite__mapDeps([10,9,0,1]),import.meta.url),{export:`ProjectPickerContent`},`src/pages/new-session/project-picker-content.tsx`),xn(md.preload)})))()}function gd(e){let t=Qi(()=>e.params.hostId),n=()=>!e.params.hosts||e.params.hosts.length===1&&e.params.hosts[0]?.hostId===e.params.hostId;return B(()=>B(()=>!!n())()?void 0:B(()=>!e.params.hosts?.length)()?(()=>{var t=_d();return G(()=>t=>e.ref?.(t),t),z(t,()=>N(`newSession.nativeHostsUnavailable`)),t})():(()=>{var n=vd(),r=n.firstChild,i=r.nextSibling,a=i.firstChild,o=a.nextSibling;return G(()=>t=>e.ref?.(t),n),z(r,()=>N(`newSession.where`)),i.addEventListener(`change`,t=>e.params.onSelect(t.currentTarget.value)),G(()=>t,i),z(i,(()=>{var t=B(()=>!e.params.hosts?.some(t=>t.hostId===e.params.hostId));return()=>t()?(()=>{var t=yd();return z(t,()=>N(`newSession.chooseNativeHost`)),W(()=>e.params.hostId,e=>{t.value=e}),t})():void 0})(),a),z(i,U(Aa,{get each(){return e.params.hosts},keyed:e=>e.hostId,children:t=>(()=>{var n=bd();return z(n,()=>t().label),W(()=>({e:t().hostId,t:t().hostId===e.params.hostId}),({e,t},r)=>{n.value=e,n.selected=t}),n})()}),o),W(()=>({e:N(`newSession.where`),t:e.params.submitting}),({e,t},n)=>{e!==n?.e&&V(i,`aria-label`,e),t!==n?.t&&V(i,`disabled`,t)}),n})())}var _d,vd,yd,bd;function xd(){return(xd=e((()=>{K(),R(),j(),Fn(),_d=q(`<span class=new-session-page__catalog-unavailable role=status>`),vd=q(`<div class="new-session-page__select new-session-page__menu-field"><span></span><select class=new-session-page__trigger><!><!>`),yd=q(`<option selected disabled>`),bd=q(`<option>`)})))()}function Sd(){return U(Wi,{get children(){return[Td(),Ed()]}})}function Cd(e){return U(Wi,{get children(){return B(()=>e.form===`laptop`)()?[Dd(),Od()]:B(()=>e.form===`mini`)()?[kd(),Ad()]:[jd(),Md()]}})}function wd(e){let t=()=>{let t=e.device?.platform?.trim();if(t&&!/^(?:darwin|macos|mac os(?: x)?)\b/i.test(t))return;let n=ao(e.device?.label);return n===`laptop`||n===`mini`||n===`studio`?n:void 0};return U(L,{get when(){return t()},get fallback(){return U(F,{name:`monitor`})},children:e=>(()=>{var t=Nd();return z(t,U(Cd,{get form(){return e()}})),W(()=>e(),e=>{V(t,`data-form`,e)}),t})()})}var Td,Ed,Dd,Od,kd,Ad,jd,Md,Nd;function Pd(){return(Pd=e((()=>{K(),R(),A(),sr(),io(),Td=q(`<svg><rect x=2 y=7 width=14 height=11></svg>`,2),Ed=q(`<svg><path d="M6 7V3h16v12h-6M6 22h6M9 18v4"></svg>`,2),Dd=q(`<svg><path d="M18 5a2 2 0 0 1 2 2v8.526a2 2 0 0 0 .212.897l1.068 2.127a1 1 0 0 1-.9 1.45H3.62a1 1 0 0 1-.9-1.45l1.068-2.127A2 2 0 0 0 4 15.526V7a2 2 0 0 1 2-2z"></svg>`,2),Od=q(`<svg><path d="M20.054 15.987H3.946"></svg>`,2),kd=q(`<svg><path d="M2.212 11.577a2 2 0 0 0-.212.896V18a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-5.527a2 2 0 0 0-.212-.896L18.55 5.11A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z"></svg>`,2),Ad=q(`<svg><path d="M21.946 12.013H2.054M6 16h.01M10 16h.01"></svg>`,2),jd=q(`<svg><path d="m3 8 3-4h12l3 4v10a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2Z"></svg>`,2),Md=q(`<svg><path d="M3 8h18M6 15h2M11 15h2M17 15h.01"></svg>`,2),Nd=q(`<span class=new-session-page__device-icon>`)})))()}function Fd(e){let t,n,r=e=>{t?.overlay.open&&e.ownerDocument.activeElement===n&&e.focus({preventScroll:!0}),n=void 0},i=I(()=>e.state.kind),a=I(()=>i()===`hosted`?U(F,{name:`cloud`}):i()===`cloud`?U(tr,{get profile(){return e.state.cloudProfiles.find(t=>t.id===e.params.place.cloudProfileId)}}):i()===`local`?U(F,{name:`home`}):i()===`auto-device`?U(Sd,{}):U(wd,{get device(){return e.state.devices.find(t=>t.deviceId===e.params.place.deviceId)}})),o=I(()=>{let t=e.params.place.cloudSelection,n=si(e.state.cloudProfiles.find(t=>t.id===e.params.place.cloudProfileId)),r=e.params.gateway.gatewayName.trim()||N(`newSession.local`);return{cloudSelection:t,cloudPresentation:n,label:e.state.kind===`local`?r:e.state.label,configurationSummary:e.state.kind===`cloud`?[e.state.operatingSystems.find(t=>t.id===e.state.selectedOsId)?.label,e.state.cloudMachines.find(t=>t.id===e.state.selectedMachineId)?.label].filter(Boolean).join(` · `):``}});return U(id,{lazy:!0,onBeforeShow:()=>{n=t?.overlay.surface.ownerDocument.activeElement},ref:n=>{t=n,e.ref?.(n)},kind:`where`,get label(){return`${N(`newSession.where`)}: ${o().label}`},get value(){return o().label},get icon(){return a()},get summary(){return o().configurationSummary},get triggerAttributes(){return{"aria-label":`${N(`newSession.where`)}: ${o().label}${o().configurationSummary?`, ${o().configurationSummary}`:``}`,"aria-description":e.state.kind===`cloud`&&o().cloudPresentation.label?N(`newSession.cloudWorkerProvider`,{provider:o().cloudPresentation.label}):void 0,"data-cloud-profile":e.params.place.cloudProfileId||void 0,"data-hosted-runtime":e.state.hostedRuntimeId||void 0,"data-machine-class":o().cloudSelection.machineClass||void 0,"data-os":o().cloudSelection.os||void 0,"data-device-id":e.params.place.deviceId||void 0,"data-auto-device":e.params.place.autoDevice?`true`:void 0}},get params(){return e.params},get children(){return U(Id,{get params(){return e.params},get state(){return e.state},onReady:r})}})}var Id;function Ld(){return(Ld=e((()=>{K(),R(),$e(),A(),He(),bt(),j(),ld(),Pd(),E(),Id=Va(()=>w(()=>import(`./where-picker-content-DmtrY-pd.js`),__vite__mapDeps([9,0,1]),import.meta.url),{export:`WherePickerContent`},`src/pages/new-session/where-picker-content.tsx`),xn(Id.preload)})))()}function Rd(e){var t=Vd(),n=t.firstChild,r=e.ref;return typeof r==`function`||Array.isArray(r)?G(()=>r,t):e.ref=t,n.addEventListener(`overlay-hide`,()=>e.params.onOpenChange(!1)),n.addEventListener(`overlay-show`,()=>e.params.onOpenChange(!0)),G(()=>t=>{t.focusTargetsRef=e.focusTargetsRef},n),n._$owner=La(),W(()=>({e:e.params.variant??`compact`,t:e.params.agents.map(t=>({value:T(t.id),label:Ze(t,e.params.agentIdentity?.get(t.id)),agent:t})),a:Object.fromEntries(e.params.agents.flatMap(t=>{let n=e.params.agentIdentity?.get(t.id);return n?[[t.id,n]]:[]})),o:T(e.params.agentId),i:N(`newSession.agent`),n:N(`newSession.agents`),s:e.params.disabled,h:e.params.onSelect}),({e,t,a:r,o:i,i:a,n:o,s,h:c},l)=>{e!==l?.e&&(n.variant=e),t!==l?.t&&(n.options=t),r!==l?.a&&(n.identityById=r),i!==l?.o&&(n.value=i),a!==l?.i&&(n.accessibleLabel=a),o!==l?.n&&(n.menuLabel=o),s!==l?.s&&(n.disabled=s),c!==l?.h&&(n.onSelect=c)}),t}function zd(e){let t=()=>e.gateway.cloudProfiles.find(t=>t.id===e.gateway.requiredProfile),n=I(()=>({promise:e.gateway.cloudProfilesRead}),{equals:(e,t)=>e.promise===t.promise}),r=I(()=>n().promise?.then(()=>null));var i=Hd(),a=i.firstChild,o=a.nextSibling;return G(()=>t=>e.ref?.(t),i),z(i,(()=>{var n=B(()=>!e.gateway.placementPolicyReady);return()=>n()?N(`newSession.placementNotReady`):B(()=>!t())()?N(`newSession.requiredWorkerUnavailable`):N(t()?.inference===`worker`?`newSession.openClawWorker`:`newSession.requiredWorker`)})(),a),z(i,U(qa,{get on(){return n()},get children(){return[B(()=>r()),B(()=>B(()=>!(e.gateway.placementPolicyReady&&t()))()?(()=>{var t=Ud();t._$$click=()=>void e.gateway.retryRequiredPlacement();var n=e.retryRef;return typeof n==`function`||Array.isArray(n)?G(()=>n,t):e.retryRef=t,z(t,()=>N(`common.retry`)),t})():void 0)]}}),o),i}function Bd(e){let t,n,r,i,a;H(()=>{e.ref?.(()=>[t,n,r?.overlay.trigger?.parentElement??void 0,r?.overlay.surface,i,a].filter(e=>e?.isConnected===!0))});let o=Qi(()=>e.params.place.folder),s=Qi(()=>e.params.place.deviceFolder?.path??``),c=I(()=>{let{context:t,data:n,gateway:r,place:i}=e.params,a=i.browser,o=M(n),s=o?[]:r.cloudProfiles,c=o?[]:a.projects,l=o?[]:a.resolveProjectRecents({sessions:t?.sessions.state.result?.sessions??[],workspace:i.workspacePath(),workspaceRoots:i.knownWorkspaceRoots(),isAdmin:i.isAdmin()});return{nativeTerminal:o,browser:a,whereState:$u(Qu(i,r,s)),projectState:Hs({folder:i.deviceFolder?.path??i.folder,workspace:i.workspacePath(),projectId:a.projectId,selectedRemoteProject:a.remoteProject,projects:c,recents:l,projectQuery:a.projectQuery,freshWorkspace:i.freshWorkspace})}});return[B(()=>B(()=>!!e.params.place.requiredPlacement)()?U(zd,{get gateway(){return e.params.gateway},ref:e=>{t=e}}):[B(()=>B(()=>!!c().nativeTerminal)()?U(gd,{ref:e=>{n=e},get params(){return{hosts:e.params.data?.terminalHosts,hostId:e.params.place.terminalHostId,submitting:e.params.submitting,onSelect:t=>e.params.place.selectTerminalHost(t)}}}):U(Fd,{get params(){return e.params},get state(){return c().whereState},ref:e=>{r=e}})),(()=>{var t=Wd(),n=t.firstChild,r=n.nextSibling;return G(()=>e=>{i=e},t),z(t,(()=>{var t=B(()=>!!e.params.place.hostedEnvironment);return()=>t()?(()=>{var e=Gd();return z(e,()=>N(`newSession.hostedWorkspace`)),W(()=>N(`newSession.hostedHint`),t=>{V(e,`title`,t)}),e})():B(()=>!!(c().nativeTerminal&&e.params.place.terminalOnNode))()?(()=>{var t=Kd(),n=t.firstChild,r=n.nextSibling;return z(n,()=>N(`newSession.terminalNodeFolder`)),r._$$input=t=>e.params.place.applyFolder(t.currentTarget.value),G(()=>o,r),W(()=>({e:N(`newSession.terminalNodeFolder`),t:e.params.submitting}),({e,t},n)=>{e!==n?.e&&V(r,`aria-label`,e),t!==n?.t&&V(r,`disabled`,t)}),t})():U(pd,{get params(){return e.params},get state(){return c().projectState},get nativeTerminal(){return c().nativeTerminal},get focus(){return c().browser.projectFocus}})})(),n),z(t,(()=>{var t=B(()=>!(!e.params.place.checkoutVisible||c().nativeTerminal&&e.params.place.terminalOnNode));return()=>t()?U(ud,{get params(){return e.params},get folderLabel(){return c().projectState.label}}):void 0})(),r),W(()=>!(!e.params.place.checkoutVisible||c().nativeTerminal&&e.params.place.terminalOnNode),e=>{t.classList.toggle(`new-session-page__workspace--checkout`,e)}),t})(),B(()=>B(()=>!!e.params.place.deviceFolder)()?(()=>{var t=qd(),n=t.firstChild,r=n.nextSibling,i=r.nextSibling;return G(()=>e=>{a=e},t),z(n,()=>N(`newSession.deviceFolderPath`)),r._$$input=t=>e.params.place.setDeviceFolderPath(t.currentTarget.value),G(()=>s,r),z(i,()=>e.params.place.deviceFolderRuntimeUnsupportedReason??N(`newSession.deviceFolderDescription`)),W(()=>({e:N(`newSession.deviceFolderPath`),t:N(`newSession.deviceFolderPathPlaceholder`),a:e.params.submitting||e.params.pendingPlacement}),({e,t,a:n},i)=>{e!==i?.e&&V(r,`aria-label`,e),t!==i?.t&&V(r,`placeholder`,t),n!==i?.a&&V(r,`disabled`,n)}),t})():void 0)]),` `]}var Vd,Hd,Ud,Wd,Gd,Kd,qd;function Jd(){return(Jd=e((()=>{K(),R(),Z(),Ve(),j(),Fn(),D(),Q(),fd(),yo(),Us(),hd(),xd(),ed(),Ld(),Vd=q(`<span class="new-session-page__select new-session-page__select--agent"><openclaw-agent-select>`,1),Hd=q(`<span class=new-session-page__select role=status data-required-placement><!><!>`),Ud=q(`<button type=button class="btn btn--sm">`),Wd=q(`<div class=new-session-page__workspace><!><!>`),Gd=q(`<span class="new-session-page__select new-session-page__hosted-workspace">`),Kd=q(`<label class="new-session-page__select new-session-page__menu-field"><span></span><input>`),qd=q(`<label class="new-session-page__select new-session-page__menu-field new-session-page__device-folder"><span></span><input><span class=muted>`),X(),Ka([`click`,`input`])})))()}function Yd(e){let t=I(()=>(e.renderRevision,e.control.prepare(e.ownerKey,e.inputDeviceId))),n=U(ur,Na(()=>t().voice.microphonePicker));return[U(Yi,Na(()=>t().voice,{get idleLabel(){return e.idleLabel},microphonePicker:n})),U(Si,{readDictation:()=>t().voice.readDictation(),get onSend(){return t().onSubmit}})]}function Xd(){return(Xd=e((()=>{K(),R(),Ri()})))()}function Zd(e){return e.pendingMessage?e.completion?.label??e.statusLabel??N(`newSession.starting`):void 0}function Qd(e){var t=ef(),n=t.firstChild,r=n.nextSibling;return z(n,U(F,{name:`alertTriangle`})),z(r,()=>y(e.message)),z(t,U(L,{get when(){return e.action},children:e=>(()=>{var t=tf();return t._$$click=()=>e().onClick(),z(t,()=>e().label),W(()=>e().disabled,e=>{V(t,`disabled`,e)}),t})()}),null),t}function $d(e){let t=kn(`scroll`),n=I(()=>Rr(!0,e.pendingMessage&&ni(e.pendingMessage.__openclaw)?e.userId:null));return[(()=>{var t=nf();return z(t,()=>Zd(e)),t})(),(()=>{var r=rf(),i=r.firstChild,a=i.nextSibling,o=a.nextSibling;return Ga(r,`mousedown`,Vr,!0),G(()=>t,r),z(r,U(L,{get when(){return e.error},children:t=>U(Qd,{get message(){return t()},get action(){return e.errorAction}})}),i),z(r,U(L,{get when(){return e.pendingMessage},get fallback(){return e.renderDraft()},children:t=>U(Ra,{fallback:(e,t)=>U(Fi,{get error(){return e()},onRetry:t,inline:!0}),get children(){return U(qa,{get fallback(){return U(xr,{})},get children(){return U(af,{get message(){return t()},get avatarPlacement(){return n()},get onOpenImage(){return e.onOpenImage},get statusLabel(){return e.statusLabel},get completion(){return e.completion}})}})}})}),a),z(r,U(L,{get when(){return B(()=>!!e.pendingMessage)()?e.showDraft:e.pendingMessage},get children(){return e.renderDraft()}}),o),W(()=>({e:Wa([e.inChat?``:`new-session-page__scroll`,{"chat-thread":!!(e.pendingMessage||e.inChat),"chat-thread--annotations":!!(e.pendingMessage||e.inChat),"chat-thread--direct":!!(e.pendingMessage||e.inChat)&&n()===`footer`}]),t:e.submitting&&!e.pendingMessage,a:e.submitting?`true`:`false`}),({e,t,a:n},i)=>{Ua(r,e,i?.e),t!==i?.t&&V(r,`inert`,t),n!==i?.a&&V(r,`aria-busy`,n)}),r})()]}var ef,tf,nf,rf,af,of;function sf(){return(sf=e((()=>{K(),R(),Wn(),Cn(),A(),li(),Ei(),Z(),Ue(),h(),j(),mi(),E(),ef=q(`<div class="callout danger new-session-page__error new-session-page__alert"role=alert><span class=new-session-page__alert-icon aria-hidden=true></span><span class="callout__content new-session-page__alert-message">`),tf=q(`<button class="btn btn--sm"type=button>`),nf=q(`<div class=sr-only role=status aria-live=polite>`),rf=q(`<div><!><!><!>`),Di(X),af=Va(()=>w(()=>import(`./draft-submission-view-BGSeDrqq.js`),__vite__mapDeps([2,3,4,5,6,7,0,1,8]),import.meta.url),{export:`NewSessionSubmission`},`src/pages/new-session/draft-submission-view.tsx`),of=()=>void af.preload().catch(()=>void 0),Ka([`click`,`mousedown`])})))()}function cf(e){var t=uf();return t._$$click=()=>e.onRetry(),z(t,(()=>{var t=B(()=>!!e.retrying);return()=>t()?N(`common.loading`):N(`lazyView.retry`)})()),W(()=>e.retrying,e=>{V(t,`disabled`,e)}),t}function lf(e){let t=I(()=>({promise:e.retryRead}),{equals:(e,t)=>e.promise===t.promise}),n=I(()=>t().promise?.then(()=>null)),r,i;var a=df(),o=a.firstChild,s=o.nextSibling,c=s.nextSibling;return G(()=>()=>e.ref?.(()=>[r,i].filter(e=>e?.isConnected===!0)),a),z(a,(()=>{var t=B(()=>!!M(e.data));return()=>t()?(()=>{var t=ff(),n=t.firstChild,i=n.nextSibling;return G(()=>e=>{r=e},t),z(n,U(F,{name:`terminal`})),z(i,()=>e.data?.catalogLabel||e.data?.catalogId||``),W(()=>e.data?.startTerminal&&e.data.catalogLabel?N(`newSession.nativeTerminalHint`):N(`newSession.catalogUnavailable`),e=>{V(t,`title`,e)}),t})():e.agentSelect})(),o),z(a,()=>e.placeSelect,s),z(a,(()=>{var t=B(()=>!!(es(e.data)||e.groupPending===!0));return()=>t()?(()=>{var t=pf(),r=t.firstChild,a=r.nextSibling;return G(()=>e=>{i=e},t),z(t,()=>N(`newSession.catalogUnavailable`),r),z(t,U(Ra,{fallback:(t,r)=>{let i=()=>{e.onRetry(),r()};return U(qa,{get fallback(){return U(cf,{retrying:!0,onRetry:i})},get children(){return U(cf,{get retrying(){return za(n)||e.retrying},onRetry:i})}})},get children(){return U(qa,{get fallback(){return U(cf,{retrying:!0,get onRetry(){return e.onRetry}})},get children(){return[B(()=>ja(n)),U(cf,{get retrying(){return za(n)||e.retrying},get onRetry(){return e.onRetry}})]}})}}),a),t})():void 0})(),c),a}var uf,df,ff,pf;function mf(){return(mf=e((()=>{K(),R(),A(),j(),Q(),uf=q(`<button class="btn btn--sm"type=button>`),df=q(`<div class=new-session-page__triggers><!><!><!>`),ff=q(`<span class="new-session-page__trigger new-session-page__runtime"><span class=new-session-page__target-icon aria-hidden=true></span><span class=new-session-page__trigger-label>`),pf=q(`<span class=new-session-page__catalog-unavailable><!><!>`),Ka([`click`])})))()}var hf;function gf(){return(gf=e((()=>{R(),hf=Fa()})))()}function _f(e){let t=()=>e.options.visibility===`draft`;var n=xf(),r=n.firstChild,i=r.nextSibling;return n._$$click=()=>e.options.onVisibilityChange?.(t()?`normal`:`draft`),z(r,U(F,{name:`pencil`})),z(i,()=>N(`newSession.draft`)),W(()=>({e:!!t(),t:N(`newSession.draft`),a:t()?`true`:`false`,o:e.options.submitting||e.options.messageLocked,i:N(`newSession.draftDescription`)}),({e,t,a:r,o:i,i:a},o)=>{e!==o?.e&&n.classList.toggle(`new-session-page__visibility--active`,e),t!==o?.t&&V(n,`aria-label`,t),r!==o?.a&&V(n,`aria-checked`,r),i!==o?.o&&V(n,`disabled`,i),a!==o?.i&&V(n,`title`,a)}),n}function vf(e){let t=Pa(hf),n=I(()=>{let n=e.options,r=n.submitting||n.messageLocked===!0;return{attachments:e.attachments,inputHandle:e.inputHandle,capabilityMenu:n.capabilityMenu,disabled:r,open:t.capabilityMenuOpen,view:t.capabilityMenuView,toolOverrides:n.toolOverrides,rootToggles:n.draftAvailable||n.visibility===`draft`?[{value:`new-session-draft`,label:N(`newSession.draft`),icon:`pencil`,checked:n.visibility===`draft`,disabled:r,title:N(`newSession.draftDescription`),onChange:e=>n.onVisibilityChange?.(e?`draft`:`normal`)}]:void 0,onOpenChange:e=>{t.capabilityMenuOpen=e,e||(t.capabilityMenuView=`root`),n.onChange()},onViewChange:e=>{t.capabilityMenuView=e,n.onChange()}}});return U(Tn,{get menu(){return n()}})}function yf(e){let t=Pa(hf),n=I(()=>Qt(e.options.toolOverrides));return U(L,{get when(){return n()>0},get children(){var r=Sf();return r._$$click=()=>{t.capabilityMenuView=`root`,t.capabilityMenuOpen=!0,e.options.onChange()},z(r,()=>N(n()===1?`chat.composer.overrides.countOne`:`chat.composer.overrides.count`,{count:String(n())})),W(()=>e.options.submitting||e.options.messageLocked===!0,e=>{V(r,`disabled`,e)}),r}})}function bf(e){let t=()=>e.options.submitting?N(`newSession.starting`):N(e.options.nativeTerminal?`newSession.startInTerminal`:`newSession.start`),n=()=>e.options.submitting||e.options.attachmentDraft.reads.pendingReads>0;var r=Cf(),i=r.firstChild;return r._$$pointerdown=t=>{t.button===0&&!e.options.canSubmit&&e.options.onBlockedSubmit?.()},r._$owner=La(),i._$$click=()=>e.onSubmit(),z(i,U(F,{get name(){return B(()=>!!n())()?`loader`:e.options.nativeTerminal?`squareTerminal`:`arrowUp`}})),W(()=>({e:e.options.submitDisabledReason??t(),t:!!n(),a:!e.options.canSubmit,o:e.options.canSubmit?`false`:`true`,i:n()?`true`:`false`,n:t()}),({e,t,a:n,o:a,i:o,n:s},c)=>{e!==c?.e&&V(r,`content`,e),t!==c?.t&&i.classList.toggle(`new-session-page__start-submit--busy`,t),n!==c?.a&&V(i,`disabled`,n),a!==c?.o&&V(i,`aria-disabled`,a),o!==c?.i&&V(i,`aria-busy`,o),s!==c?.n&&V(i,`aria-label`,s)}),r}var xf,Sf,Cf;function wf(){return(wf=e((()=>{K(),R(),A(),Z(),j(),Pn(),gf(),xf=q(`<button type=button class="new-session-page__visibility new-session-page__visibility--draft"role=switch><span class=new-session-page__visibility-icon aria-hidden=true></span><span class=new-session-page__visibility-label>`),Sf=q(`<button type=button class=new-session-page__selection-status>`),Cf=q(`<openclaw-tooltip><button type=button class="chat-send-btn new-session-page__start-submit">`,1),X(),Ka([`click`,`pointerdown`])})))()}function Tf(e,t){let n=I(()=>N(e().nativeTerminal?`newSession.nativeTerminalPrompt`:`newSession.messagePlaceholder`)),r=I(()=>e().message.length>0),i=!globalThis.requestAnimationFrame||(globalThis.matchMedia?.(`(prefers-reduced-motion: reduce)`).matches??!1),[a,o]=Ba({target:``,text:``}),s=!1;return Ia(()=>[n(),r()],([e,n])=>{if(s||=n,s||i)return;let r,a,c=0,l=n=>{if(!t.getTextarea()?.isConnected)return;r??=n;let i=Math.min(e.length,Math.floor(Math.max(0,n-r-180)/26));s=i===e.length,c!==i&&(c=i,o(t=>{t.target=e,t.text=e.slice(0,c)})),s||(a=requestAnimationFrame(l))};return a=requestAnimationFrame(l),()=>cancelAnimationFrame(a)}),()=>e().dictationActive?``:s||r()||i?n():a.target===n()?a.text:``}function Ef(){return(Ef=e((()=>{R(),j()})))()}function Df(e){let t=I(()=>e.identity),n=I(()=>(e.read(),!0));return U(Ra,{fallback:()=>e.children(),get children(){return U(qa,{get on(){return t()},get fallback(){return e.children()},get children(){return B(()=>!!n())()?e.children():void 0}})}})}function Of(e){let t=I(()=>e.control),n=I(()=>e.options.agent),r=I(()=>e.options.agentId),i=I(()=>e.options.context),a=I(()=>e.options.sending),o=I(()=>na({control:t(),context:i()},{read:()=>void 0,equality:`revision`,subscribe:({control:e,context:t},n)=>{let r=(t?[e,t.gateway,t.agents,t.config]:[e]).map(e=>e.subscribe(n));return()=>r.forEach(e=>e())}})),s=I(()=>na(i(),{read:e=>Object.entries(e?.sessions.state.result?.defaults??{}),equality:(e,t)=>e.length===t.length&&e.every(([e,n],r)=>e===t[r]?.[0]&&n===t[r]?.[1]),subscribe:(e,t)=>e?.sessions.subscribe(t)??(()=>{})})),c=I(()=>(o().revision(),{promise:t().metadataRead,scope:t().metadataReadScope}),{equals:(e,t)=>e.promise===t.promise&&e.scope===t.scope}),l=I(()=>c().promise),u=I(()=>(o().revision(),s().revision(),t().renderProps({agent:n(),agentId:r(),context:i(),sending:a()})));return U(Jn,Na(u,{renderModelCatalogStatus:e=>U(Df,{read:l,get identity(){return c()},children:e})}))}function kf(){return(kf=e((()=>{K(),R(),Lr(),Ci()})))()}function Af(e,t){t.emojiMenu.close(),t.mentionMenu.close(),t.skillMenu.reset(),t.slashMenu.reset(),e.onSubmit()}function jf(e,t){let{attachmentDraft:n,context:r}=e,i=n.reads.readSignal,a=r?.gateway,o=e.nativeTerminal?null:a?.snapshot.client??null,s=Vu(e),{skillMenu:c,slashMenu:l,mentionMenu:u,emojiMenu:d}=t,f=c.state,p=l.state,m=e.submitting||e.messageLocked===!0||e.dictationActive===!0,h={paneId:`new-session`,getDraft:()=>t.getTextarea()?.value??e.message,commitDraft:e.onInput,getTextarea:t.getTextarea,refreshCommands:o?()=>pn({client:o,agentId:e.agentId,shouldApply:()=>t.ownsSkillCommands(o,e.agentId,e.draftOwnerKey)}):void 0},g={...h,resolveArgOptions:e=>e.argOptions??[],runCommand:()=>Af(e,t),canRun:e=>!e,commandFilter:e=>e.executeLocal!==!0},_={paneId:h.paneId,getDraft:h.getDraft,getTextarea:h.getTextarea,getMentions:()=>e.getMentions?.()??e.mentions??[],commitDraft:e.onInput},v=n=>{if(aa(n)||e.dictationActive||e.submitting||e.messageLocked||t.composing||oi(n)||t.emojiMenu.handleKeydown(n,`new-session`)||t.mentionMenu.handleKeydown(n,_)||c.handleKeydown(n,h)||l.handleKeydown(n,g)||n.key!==`Enter`)return;let r=n.metaKey||n.ctrlKey,i=r&&n.shiftKey,a=!!(!n.altKey&&i&&e.onBackgroundSubmit);(a||!n.shiftKey&&(!e.requiresModifier||r))&&(n.repeat?n.preventDefault():(e.canSubmit||e.submitDisabledReason!==void 0)&&(n.preventDefault(),a?(t.skillMenu.reset(),t.slashMenu.reset(),t.mentionMenu.close(),e.onBackgroundSubmit?.()):Af(e,t)))},y=(n,r=f.skillMenuOpen||p.slashMenuOpen)=>{d.update(n,!m&&!e.nativeTerminal&&!t.composing&&!r&&!u.open)},b=(n,r)=>{if(e.nativeTerminal||t.composing||r?.isComposing){d.close();return}let i=l.update(n.value,g),a=c.update(n.value,n.selectionStart,h);r?.inputType===`insertFromPaste`||r?.inputType===`insertFromDrop`?u.close():u.update(n,r?r.inputType===`insertText`&&r.data?.includes(`@`)===!0?`trigger`:`input`:`selection`),y(n,i||a)},x=e=>{let t=e.currentTarget;t instanceof HTMLTextAreaElement&&(e.type===`keyup`?(u.update(t),y(t)):b(t))},ee={attachmentReads:n.reads,attachmentLimits:ya(a?.snapshot.hello?.policy),uploadConfig:r?.config,attachments:n.attachments,get disabled(){return e.submitting||e.messageLocked===!0||e.dictationActive===!0},getAttachments:()=>n.attachments,draft:e.message,getDraft:()=>e.message,onAttachmentsChange:t=>{!e.submitting&&!e.messageLocked&&n.replace(t)},onDraftChange:e.onInput,onPendingReadsChange:e=>n.reads.updatePending(i,e),onOpenImage:e.onOpenImage,onOpenSidebar:e.onOpenSidebar,readSignal:i},te=bi({...ee,canCompose:!m&&!e.nativeTerminal}),ne=e.dictationPreview??e.message;t.syncDraft(ne);let re=N(e.nativeTerminal?`newSession.nativeTerminalPrompt`:`newSession.messagePlaceholder`),{skillMenuVisible:ie,slashMenuVisible:ae,menuVisible:oe,menuListboxId:se,activeMenuOptionId:ce,activeMenuOptionLabel:le}=Qe(h.paneId,!e.nativeTerminal&&!m,f,p,u,d),ue=mn(h.paneId,`active-menu-announcement`),S=e.requiresModifier?`Control+Enter Meta+Enter`:`Enter Control+Enter Meta+Enter`,C=e.onBackgroundSubmit?`${S} Control+Shift+Enter Meta+Shift+Enter`:S;return{attachmentProps:ee,attachmentDropHandlers:te,commandClient:o,mentionDirectory:m?void 0:s,composerLocked:m,visibleMessage:ne,messagePlaceholder:re,keyShortcuts:C,skillMenuVisible:ie,slashMenuVisible:ae,menuVisible:oe,menuListboxId:se,activeMenuOptionId:ce,activeMenuOptionLabel:le,menuAnnouncementId:ue,skillMenuHost:h,slashMenuHost:g,mentionMenuHost:_,handleComposerKeydown:v,handleSelect:x,updateMenus:b}}function Mf(e){let t=Pa(hf),n=At(async()=>{Lf(!0),await Rf.preload()}),r=n.Boundary;H(()=>(n.schedule(),n.dispose));let i=Wr(),a=on(),o=kn(`composer`),s=I(()=>{let t=e.options.draftSource;return t?zn(t,e=>e.read()):void 0}),c=I(()=>{let t=s()?.read();return t?{...e.options,message:t.draft,mentions:t.mentions}:e.options}),l=I(()=>jf(c(),t)),u=Tf(c,t);Ia(()=>[l().commandClient,c().agentId,c().draftOwnerKey,l().mentionDirectory,l().composerLocked||c().nativeTerminal||t.composing],([e,n,r,i,a])=>{t.syncSkillCommandOwner(e,n,r),t.mentionMenu.syncDirectory(i),a&&t.emojiMenu.close()});let d=I(()=>l().visibleMessage),f=Qi(d),p,m,h,g,_,v,y=()=>{if(!m||!p||!h)return null;let t=e.surroundings?.();return{root:t?.root??m,composer:m,editor:p,footer:h,controls:[g,_,v].filter(e=>e?.isConnected===!0),obstacles:t?.obstacles??[]}};H(()=>(t.ref(p),()=>t.ref()));var b=Pf(),x=b.firstChild,ee=x.firstChild,te=ee.nextSibling,ne=te.nextSibling,re=ne.nextSibling,ie=re.nextSibling,ae=ie.nextSibling,oe=ae.nextSibling,se=oe.nextSibling,ce=se.nextSibling,le=ce.firstChild,ue=le.firstChild,S=ue.nextSibling,C=S.nextSibling,w=C.nextSibling,de=ce.nextSibling,T=de.firstChild,fe=T.firstChild,pe=fe.nextSibling,me=pe.nextSibling,he=me.nextSibling,ge=T.nextSibling.firstChild,E=ge.nextSibling,D=E.firstChild,O=D.nextSibling;return b.addEventListener(`dragover`,e=>l().attachmentDropHandlers.onDragover(e)),b.addEventListener(`dragleave`,e=>l().attachmentDropHandlers.onDragleave(e)),b.addEventListener(`dragenter`,e=>l().attachmentDropHandlers.onDragenter(e)),b.addEventListener(`drop`,e=>{c().nativeTerminal&&e.dataTransfer?.files.length?(e.preventDefault(),c().onUnsupportedAttachment?.()):l().attachmentDropHandlers.onDrop(e)}),G(()=>i,b),x.addEventListener(`openclaw-composer-dismiss-invocations`,()=>{t.mentionMenu.close(),t.emojiMenu.dismiss(t.getTextarea()),c().onChange()}),G(()=>e=>{m=e,o(e)},x),z(x,U(r,{get children(){return U(L,{get when(){return If()},get children(){return U(Rf,{composerElements:y,get seed(){return po(`${t.critterVisit}:${c().draftOwnerKey}`)},get mode(){return ho(!c().context?.gateway.snapshot.offlineStable,c().context?.sessions.state.result?.sessions)},get runOutcome(){return co(c().context?.sessions.state.result?.sessions)},get visitsEnabled(){return c().context?.theme.settings.lobsterPetVisits!==!1},get residentEnabled(){return c().context?.theme.branding.mascot!==`none`},get critters(){return c().context?.theme.branding.critters},get critterArtwork(){return c().context?.theme.branding.artwork?.critters},get soundsEnabled(){return c().context?.theme.settings.lobsterPetSounds===!0},get gatewayVersion(){return c().context?.config.current.serverVersion??c().context?.gateway.snapshot.hello?.server?.version??null},onVisitsDisabled:()=>c().context?.theme.refresh(),get floorEnabled(){return B(()=>!(l().composerLocked||l().visibleMessage.length!==0||c().attachmentDraft.attachments.length!==0||c().attachmentDraft.reads.pendingReads!==0||l().menuVisible))()?!t.capabilityMenuOpen:!l().composerLocked&&l().visibleMessage.length===0&&c().attachmentDraft.attachments.length===0&&c().attachmentDraft.reads.pendingReads===0&&!l().menuVisible}})}})}}),ee),z(x,U(Eo,{get args(){return[t.mentionMenu,l().mentionMenuHost]}}),te),z(x,U(To,{get args(){return[t.emojiMenu,`new-session`,t.getTextarea()]}}),ne),z(x,U(L,{get when(){return!c().nativeTerminal},get children(){return U(er,Na(()=>l().attachmentProps,{inputHandle:a}))}}),re),z(x,U(Tt,{get text(){return c().message},get mentions(){return c().mentions},onRemove:()=>c().onInput(c().message,[]),get avatarUrls(){return t.mentionMenu.selectedAvatarUrls}}),ie),z(x,U(Vn,Na(()=>l().attachmentProps,{get readRevision(){return l()}})),ae),z(x,U(ra,{get pendingReads(){return c().attachmentDraft.reads.pendingReads}}),oe),z(x,U(L,{get when(){return c().dictationError},children:e=>(()=>{var t=Ff();return z(t,e),t})()}),se),z(se,()=>c().dictationStatus),z(le,U(L,{get when(){return l().slashMenuVisible},get children(){return U(ko,{get menu(){return t.slashMenu},get host(){return l().slashMenuHost},get draft(){return l().visibleMessage}})}}),ue),z(le,U(L,{get when(){return l().skillMenuVisible},get children(){return U(wo,{get menu(){return t.skillMenu},get host(){return l().skillMenuHost}})}}),S),S.addEventListener(`paste`,e=>{c().nativeTerminal&&e.clipboardData?.files.length?(e.preventDefault(),c().onUnsupportedAttachment?.()):!l().composerLocked&&!c().nativeTerminal&&Ii(e,l().attachmentProps)}),S.addEventListener(`compositionstart`,e=>{Nt(e),t.composing=!0,t.emojiMenu.close(),t.mentionMenu.close(),c().onChange()}),S._$$keydown=e=>{Nt(e),l().handleComposerKeydown(e)},S.addEventListener(`compositionend`,e=>{De(e),t.composing=!1,l().updateMenus(e.currentTarget)}),S.addEventListener(`blur`,e=>{Nt(e),Ke(e),t.composing=!1,t.emojiMenu.close()}),S._$$keyup=e=>{Ke(e),t.emojiMenu.handleKeyup(e),(e.key.startsWith(`Arrow`)||e.key===`Home`||e.key===`End`)&&l().handleSelect(e)},S._$$pointerup=e=>l().handleSelect(e),S.addEventListener(`focus`,e=>l().handleSelect(e)),S.addEventListener(`select`,e=>l().handleSelect(e)),Ga(S,`pointerdown`,Nt,!0),Ga(S,`wheel`,Nt),Ga(S,`scroll`,nn),S._$$beforeinput=e=>{Nt(e);let n=e.currentTarget;t.mentionInput={value:n.value,start:n.selectionStart,end:n.selectionEnd,inputType:e.inputType},t.emojiMenu.complete(e,!l().composerLocked&&!c().nativeTerminal&&!t.composing)},S._$$input=e=>{if(Nt(e),c().dictationActive)return;let n=e.currentTarget;Ht(n,{nativeInput:!0});let r=l().mentionMenuHost.getMentions();c().onInput(n.value,r.length?hn(c().message,n.value,r,t.mentionInput):void 0),t.mentionInput=void 0,l().updateMenus(n,e)},G(()=>e=>{p=e,f(e)},S),z(C,u),z(w,()=>l().activeMenuOptionLabel),G(()=>e=>h=e,de),G(()=>e=>{g=e},T),z(T,U(L,{get when(){return!c().nativeTerminal},get children(){return U(vf,{get options(){return c()},get attachments(){return l().attachmentProps},inputHandle:a})}}),fe),z(T,()=>c().permissionControl,pe),z(T,U(L,{get when(){return B(()=>!c().nativeTerminal)()&&(c().draftAvailable||c().visibility===`draft`)},get children(){return U(_f,{get options(){return c()}})}}),me),z(T,U(L,{get when(){return!c().nativeTerminal},get children(){return U(yf,{get options(){return c()}})}}),he),z(ge,U(L,{get when(){return!c().isCatalogTarget},get children(){var e=Nf();return G(()=>e=>{_=e},e),z(e,U(Of,{get control(){return c().modelControl},get options(){return{agent:c().agent,agentId:c().agentId,context:c().context,sending:c().submitting}}})),e}})),G(()=>e=>{v=e},E),z(E,()=>c().voiceControl,D),z(E,U(L,{get when(){return!c().dictationActive},get children(){return U(bf,{get options(){return c()},onSubmit:()=>Af(c(),t)})}}),O),W(()=>({e:!!c().dictationActive,t:globalThis.matchMedia?.(`(max-width: 560px)`)?.matches??!1,a:c().submitting||c().messageLocked,o:c().dictationActive,i:u(),n:l().messagePlaceholder,s:Ie()?void 0:l().keyShortcuts,h:l().menuVisible?l().menuListboxId:void 0,r:l().menuVisible?`listbox`:void 0,d:l().activeMenuOptionId??void 0,l:l().menuAnnouncementId,u:l().menuAnnouncementId}),({e,t,a:n,o:r,i,n:a,s:o,h:s,r:c,d:l,l:u,u:d},f)=>{e!==f?.e&&x.classList.toggle(`agent-chat__input--dictating`,e),t!==f?.t&&V(S,`autofocus`,t),n!==f?.a&&V(S,`disabled`,n),r!==f?.o&&V(S,`readonly`,r),i!==f?.i&&V(S,`placeholder`,i),a!==f?.n&&V(S,`aria-label`,a),o!==f?.s&&V(S,`aria-keyshortcuts`,o),s!==f?.h&&V(S,`aria-controls`,s),c!==f?.r&&V(S,`aria-haspopup`,c),l!==f?.d&&V(S,`aria-activedescendant`,l),u!==f?.l&&V(S,`aria-describedby`,u),d!==f?.u&&V(w,`id`,d)}),b}var Nf,Pf,Ff,If,Lf,Rf;function zf(){return(zf=e((()=>{K(),R(),Kn(),go(),Cn(),en(),Z(),rn(),wa(),Kt(),j(),Fn(),Lr(),ta(),ha(),ar(),ba(),Ta(),qr(),So(),Co(),ca(),jn(),Do(),Oo(),wf(),Ef(),gf(),Hu(),kf(),E(),Nf=q(`<div class=chat-composer-model-control>`),Pf=q(`<div class="agent-chat__composer-shell new-session-page__composer"><div class="agent-chat__input agent-chat__input--mobile-toolbar"><!><!><!><!><!><!><!><div class=agent-chat__composer-lede></div><div class=agent-chat__composer-input-row><div class=agent-chat__composer-combobox><!><textarea class=new-session-page__message rows=1 enterkeyhint=enter aria-autocomplete=list></textarea><span class=agent-chat__composer-placeholder aria-hidden=true></span><span class=sr-only role=status aria-live=polite aria-atomic=true></span></div></div><div class=agent-chat__composer-footer><div class=agent-chat__composer-lead><!><!><!><!></div><div class=agent-chat__composer-trail><div class=agent-chat__composer-controls></div><div class=agent-chat__composer-actions><!><!>`),Ff=q(`<div class="callout danger new-session-page__error new-session-page__alert"role=alert>`),X(),[If,Lf]=ka(!1),Rf=Va(()=>w(()=>import(`./lobster-pet-DloBKmed.js`),__vite__mapDeps([11,12,13,0,1,14]),import.meta.url),{export:`LobsterPet`},`src/components/lobster-pet.tsx`),Ka([`input`,`beforeinput`,`pointerdown`,`pointerup`,`keyup`,`keydown`])})))()}function Bf(e,t){return e?.client===t?.client&&e?.agentId===t?.agentId&&e?.ownerKey===t?.ownerKey&&e?.message===t?.message&&e?.model===t?.model}function Vf(e){let t=null,n=null,r,i=!1,a=!1,o=0,s=!1,c=!1,l=null;return{dispose(){s=!0,u(null),l=null},synchronize:()=>u(m()),setComposing(e){c=e,u(m())},takePreparedTitle(){let e=m(),r=Bf(t,e)?n??void 0:void 0;return l=e??l,u(null),r}};function u(e){let i=e&&e.message.length>=12&&!e.message.startsWith(`/`)?e:null;Bf(t,i)||(clearTimeout(r),t=i,n=null,a=i!==null,o=Date.now()+1e3,d())}function d(){a&&!i&&(r=setTimeout(()=>void p(),Math.max(0,o-Date.now())))}async function p(){let e=t;if(e&&a){a=!1,i=!0;try{let r=await e.client.request(`sessions.title.prepare`,{agentId:e.agentId,message:le(e.message,1e3),...e.model?{model:e.model}:{}},{timeoutMs:2e4});t===e&&(n=r.title)}catch{}finally{i=!1,d()}}}function m(){let{context:t,data:n,place:r,submission:i,dictating:a}=e(),o=t?.gateway.snapshot;if(s||M(n)||c||a||i.submitting||i.visibility===`incognito`||i.pendingPlacement.sessionKey||!r.agentId||!r.modelControl.accountSelectionReady()||!f(o,`sessions.title.prepare`,`operator.write`)||!o?.client)return null;let u={client:o.client,ownerKey:Xo(n),agentId:r.agentId,message:i.message.trim(),model:r.modelControl.modelForSubmission()};return Bf(u,l)?null:u}}function Hf(){return(Hf=e((()=>{s(),Q()})))()}function Uf(e){let t=I(()=>e.sessions),n=I(()=>{let e=t();return e?zn(e,e=>e.state.result):void 0}),r=()=>e.options,i=I(()=>({sessionKey:r().sessionKey,defaultAgentId:ye(r().sessionHost??{})}),{equals:(e,t)=>e.sessionKey===t.sessionKey&&e.defaultAgentId===t.defaultAgentId}),a=I(()=>r().hideSecondaryContent||r().modelSetupRequired),o=I(()=>!a()&&!r().fadeSecondaryContent),s=yt(()=>{if(a())return[];qi();let e=i();return ga(n()?.read(),e.sessionKey,e.defaultAgentId)},o);return U(Ea,Na(r,{get assistantNameControl(){return e.assistantNameControl},get composer(){return e.composer},get preparedRecents(){return s()}}))}function Wf(){return(Wf=e((()=>{K(),R(),j(),En(),Lr(),D(),nr(),Pe()})))()}function Gf(e){let t=()=>e.mode===`draft`,n=()=>e.submission.visibility===e.mode,r=()=>e.submission.incognitoDisabledReason(),i=()=>e.submission.submitting||!!e.submission.pendingPlacement.sessionKey||!t()&&!!r(),a=()=>N(t()?`newSession.draft`:`sessionsView.incognitoLabel`),o=()=>t()?N(`newSession.draftDescription`):r()??N(`sessionsView.incognitoDescription`),s=()=>`new-session-page__${e.mode}-toggle`;var c=Jf(),l=c.firstChild,u=l.firstChild,d=u.nextSibling;return c._$owner=La(),l._$$click=()=>{(t()||!i())&&e.submission.setVisibility(n()?`normal`:e.mode)},z(l,U(F,{get name(){return t()?`pencil`:`incognito`}}),u),z(l,(()=>{var t=B(()=>!!n());return()=>t()?(()=>{var t=Yf();return z(t,a),W(()=>[`new-session-page__${e.mode}-toggle-label`],(e,n)=>{Ua(t,e,n)}),t})():void 0})(),d),W(()=>({e:Wa(t()?`new-session-page__draft-tooltip`:void 0),t:o(),a:Wa([`shell-chrome-controls__button`,s(),{[`${s()}--active`]:n()}]),o:t()?`${a()}: ${o()}`:a(),i:n()?`true`:`false`,n:i(),s:o()}),({e,t,a:n,o:r,i,n:a,s:o},s)=>{Ua(c,e,s?.e),t!==s?.t&&(c.content=t),Ua(l,n,s?.a),r!==s?.o&&V(l,`aria-label`,r),i!==s?.i&&V(l,`aria-checked`,i),a!==s?.n&&V(l,`disabled`,a),o!==s?.s&&V(l,`title`,o)}),c}function Kf(e){var t=Xf(),n=t.firstChild,r=n.nextSibling;return z(t,(()=>{var t=B(()=>!!(e.draftAvailable||e.submission.visibility===`draft`));return()=>t()?U(Gf,{get submission(){return e.submission},mode:`draft`}):void 0})(),n),z(t,U(Gf,{get submission(){return e.submission},mode:`incognito`}),r),t}function qf(e){var t=Zf(),n=t.firstChild,r=n.nextSibling,i=r.firstChild,a=i.nextSibling;return G(()=>t=>e.ref?.(t),t),z(n,U(F,{name:`incognito`})),z(r,()=>N(`sessionsView.incognitoDescription`),i),z(r,()=>N(`sessionsView.incognitoLimits`),a),W(()=>({e:!!e.active,t:e.active?`false`:`true`}),({e,t:n},r)=>{e!==r?.e&&t.classList.toggle(`new-session-page__incognito-notice--visible`,e),n!==r?.t&&V(t,`aria-hidden`,n)}),t}var Jf,Yf,Xf,Zf;function Qf(){return(Qf=e((()=>{K(),A(),qr(),Z(),j(),Jf=q(`<openclaw-tooltip><button type=button role=switch><!><!>`,1),Yf=q(`<span>`),Xf=q(`<div class=new-session-page__incognito-rail><!><!>`),Zf=q(`<div class=new-session-page__incognito-notice role=status><span class=new-session-page__incognito-notice-icon aria-hidden=true></span><span> <!>`),X(),Ka([`click`])})))()}function $f(e,t,n,r){t.draftPersistence.persistNow();let i=e?.gateway.snapshot.client;if(!e||!i||t.submitting||t.pendingPlacement.sessionKey)return;let a=n??Zo(window.location.search);e.chatAttachmentHandoff.prepare({reviewPrivateDraft:ht,owner:i,paneId:rp,scopeKey:a,message:r===a?t.message:``,mentions:r===a?t.mentions:void 0,newSessionDraft:t.draftPersistence.captureSubmission(),attachments:t.attachmentDraft.take(),fallbacks:{}})}function ep(e,t,n,r,i){let a=e?.gateway.snapshot.client;e&&a?.recoveryScopeReady&&t.draftPersistence.setOwner(e.gateway.connection.gatewayUrl,a.recoveryScope,!0),t.draftPersistence.selectRoute(n);let o=e&&a?e.chatAttachmentHandoff.consume({owner:a,paneId:rp,scopeKey:n}):null;return o?(t.restoreDraftState({message:r||o.message||``,mentions:r?i:o.mentions,attachments:o.attachments,visibility:o.newSessionDraft?.incognito?`incognito`:t.visibility}),!r&&o.newSessionDraft&&t.draftPersistence.adoptHandoff(o.newSessionDraft)):r&&t.restoreMessage(r,i),tp(t,n),n}function tp(e,t){e.pendingPlacement.sessionKey||e.draftPersistence.activateRoute(t)}function np(e,t,n){e.restorePendingPlacementRecovery(t,n),e.draftPersistence.setOwner(t,n,!!e.pendingPlacement.sessionKey)}var rp;function ip(){return(ip=e((()=>{Me(),Q(),rp=`new-session-draft`})))()}var ap;function op(){return(op=e((()=>{Ji(),Ut(),k(),Ve(),te(),bn(),D(),kl(),Q(),Jo(),ip(),Bu(),su(),ap=class{get submissionLifetime(){return this.submissionLifetimeValue.promise}submit(e=!1){let t=()=>this.submission.submit(void 0,e);return this.presentSubmit?this.presentSubmit(t):t()}get data(){return this.host.data}constructor(e){this.host=e,this.submissionLifetimeValue=Promise.withResolvers(),this.retireSubmissionPresentation=()=>{this.submissionLifetimeValue.resolve(),this.submissionLifetimeValue=Promise.withResolvers(),this.listeners.publish()},this.listeners=b(),this.contextSubscriptions=[],this.isConnected=!1,this.pendingChange=!1,this.changed=()=>{!this.pendingChange&&this.isConnected&&(this.pendingChange=!0,queueMicrotask(()=>{try{this.isConnected&&(this.synchronize(),this.titlePreparation?.synchronize())}finally{this.pendingChange=!1}})),this.listeners.publish()},this.subscribe=this.listeners.subscribe,this.retainedForHandoff=null,this.openedFor=null,this.openedGroupDefaults=``,this.openedAgentId=``,this.messageOwnerKey=``,this.attachmentPanel=null,this.closeAttachmentPanel=()=>{this.attachmentPanel&&(this.attachmentPanel=null,this.changed())},this.openAttachmentPanel=e=>{e.kind===`attachment`&&(this.attachmentPanel={content:e,ownerKey:this.routeOwnerKey(),agentId:this.place.agentId},this.changed())},this.imageLightbox=null,this.agentPickerOpen=!1,this.dictationError=null,this.flushDraft=()=>this.submission.draftPersistence.persistNow(),this.setImageLightbox=e=>{this.imageLightbox=e,this.changed()},this.draft=new zu(()=>({context:this.context,data:this.data,isConnected:this.isConnected}),{changed:this.changed,activeElement:()=>this.host.ownerDocument.activeElement,onInvalidate:()=>{this.retireSubmissionPresentation(),this.closeAttachmentPanel(),this.connectMachine?.close()},onRecoveryReady:(e,t)=>np(this.submission,e,t),closeTransientUi:()=>{this.closeAttachmentPanel(),this.draft.browser.close(),Rt(this.host)},takePreparedTitle:()=>this.titlePreparation?.takePreparedTitle(),updateComplete:()=>this.host.updateComplete,retainForHandoff:()=>{if(!this.data||!this.isConnected)return;let e={};return this.retainedForHandoff=e,{page:this.host,data:this.data,synchronizeGateway:()=>{this.context&&this.gateway.synchronize(this.context.gateway)},release:()=>{this.retainedForHandoff===e&&(this.retainedForHandoff=null,this.isConnected||this.disposeDraft())}}}}),this.gateway=this.draft.gateway,this.browser=this.draft.browser,this.place=this.draft.place,this.submission=this.draft.submission,this.connectMachine=new qo(()=>({client:this.gateway.client,connected:this.gateway.connected}),this.changed),this.dictation=new Ol({textarea:this.submission.composerTextarea,getClient:()=>this.gateway.client,isConnected:()=>this.gateway.connected,canCommit:()=>!this.submission.submitting&&!this.submission.pendingPlacement.sessionKey,onMessage:e=>this.setMessageFromUser(e),onError:e=>{this.dictationError=e,this.changed()},onSubmit:()=>void this.submit()});let t=!1;this.dictation.subscribe(()=>{let e=this.dictation.dictation?.connecting===!0;e&&!t&&(this.dictationError=null),t=e,this.changed()})}focusComposer(){let e=this.context,t=this.routeOwnerKey(),n=document.activeElement;this.host.updateComplete.then(()=>{this.isConnected&&!this.retainedForHandoff&&this.context===e&&this.routeOwnerKey()===t&&(document.activeElement===n||document.activeElement===document.body)&&!document.openClawModalLayers?.size&&this.submission.composerTextarea.getTextarea()?.focus({preventScroll:!0})})}connect(){if(!this.isConnected){this.isConnected=!0;try{let e=this.context;if(e){this.contextSubscriptions=[e.theme,e.agents,e.agentIdentity,e.placementStartup,e.runtimeConfig,e.config].map(e=>e.subscribe(this.changed));let t=e.router.getState().location;this.contextSubscriptions.push(e.router.subscribe(e=>{e.location!==t&&(t=e.location,this.retireSubmissionPresentation(),this.browser.close())}))}this.draft.connect(),this.submission.draftPersistence.connect(),this.changed()}catch(e){throw this.disconnect(),e}}}disconnect(){if(this.retireSubmissionPresentation(),this.isConnected){this.isConnected=!1,this.browser.close();for(let e of this.contextSubscriptions.splice(0))e();this.closeAttachmentPanel(),this.dictation.dispose(),this.connectMachine.close(),this.retainedForHandoff||this.disposeDraft()}}disposeDraft(){try{nu(this.data,this.host),$f(this.context,this.submission,this.openedFor,this.messageOwnerKey)}finally{this.draft.disconnect()}}synchronize(){this.draft.synchronize();let e=this.attachmentPanel;e&&(e.ownerKey!==this.routeOwnerKey()||e.agentId!==this.place.agentId||this.submission.submitting||this.submission.pendingPlacement.sessionKey||!this.submission.attachmentDraft.attachments.some(t=>t.id===e.content.sourceIdentity))&&this.closeAttachmentPanel(),this.connectMachine.open&&!this.place.isAdmin()&&this.connectMachine.close(),this.gateway.retryPendingCatalogTarget(),this.context?.agentIdentity.ensure(this.agentPickerOpen?this.place.agents().map(e=>e.id):[this.place.agentId]);let t=this.draft.agentsReady();this.place.modelControl.loadCatalogTargets(this.context,t&&this.place.agentId?this.place.selectedAgent()?.id??``:``,this.context?.config.current.cliAgentsEnabled===!0&&!M(this.data));let n=this.routeOwnerKey(),r=this.data?.agentId??``,i=ts(this.data);if(this.openedFor!==n){this.openedFor!==null&&this.submission.visibility===`incognito`&&$f(this.context,this.submission,this.openedFor,this.messageOwnerKey);let e=this.messageOwnerKey===n?this.submission.message:``,a=this.messageOwnerKey===n?this.submission.mentions:void 0;this.openedFor=n,this.openedGroupDefaults=i,this.openedAgentId=r,this.place.agentsHydrated=t,this.resetDraft(),this.messageOwnerKey=ep(this.context,this.submission,n,e,a),this.focusComposer()}else this.openedGroupDefaults!==i&&(this.openedGroupDefaults=i,this.place.adoptGroupDefaults()),this.openedAgentId!==r&&(this.openedAgentId=r,this.place.agentsHydrated=!1),this.draft.synchronizeSelections(),tp(this.submission,n),this.submission.synchronizeSubmission()}resetDraft(){this.retireSubmissionPresentation(),this.place.resetDraft(),this.submission.resetDraft(),this.messageOwnerKey=Xo(this.data),this.agentPicker&&Rt(this.agentPicker),this.browser.close(),this.connectMachine.close(),this.place.adoptAgentDefaults()}routeOwnerKey(){return this.data?Xo(this.data):Zo(window.location.search)}setMessageFromUser(e,t){!this.submission.submitting&&!this.submission.pendingPlacement.sessionKey&&(this.submission.setMessage(e,t),this.messageOwnerKey=Zo(window.location.search))}openConnectMachine(){this.place.isAdmin()&&(this.browser.close(),this.connectMachine.start())}composerOptions(){let{context:e,gateway:t,place:n,submission:r,dictation:i}=this,a=this.routeOwnerKey(),o=M(this.data),s=r.capabilities,c=e?.theme.settings,l=i.active;return{agent:n.selectedAgent(),agentId:n.agentId,attachmentDraft:r.attachmentDraft,draftSource:r.composerDraft,canSubmit:!r.submitting&&!l&&r.canSubmit(),submitDisabledReason:r.submitDisabledReason(),onBlockedSubmit:()=>r.noteBlockedSubmitAttempt(),get dictationActive(){return i.active},dictationPreview:i.previewDraft(),dictationError:this.dictationError,context:e,isCatalogTarget:o,draftOwnerKey:a,get message(){return r.message},mentions:r.mentions,getMentions:()=>r.mentions,visibility:r.visibility,draftAvailable:s.canStartAsDraft(e),...s.composerProps(e,t,n.agentId),modelControl:n.modelControl,requiresModifier:c?.chatSendShortcut===`modifier-enter`,onChange:this.changed,get submitting(){return r.submitting},get messageLocked(){return!!r.pendingPlacement.sessionKey},nativeTerminal:o,onUnsupportedAttachment:()=>r.setError(O(`newSession.terminalAttachmentsUnsupported`)),onInput:(e,t)=>this.setMessageFromUser(e,t),onOpenImage:this.setImageLightbox,onOpenSidebar:this.openAttachmentPanel,onVisibilityChange:e=>{!r.submitting&&!r.pendingPlacement.sessionKey&&r.setVisibility(e)},onSubmit:()=>void this.submit(),onBackgroundSubmit:r.visibility===`draft`||o?void 0:()=>void this.submit(!0)}}welcomeOptions(){let e=this.place.selectedAgent(),t=this.context?.agentIdentity.get(this.place.agentId),n=this.context?.gateway.snapshot;return{currentAgentId:this.place.agentId,assistantName:e?Ze(e,t):``,assistantAvatar:ai(e??{},t),assistantAvatarUrl:_(e??{},t),hint:O(M(this.data)?`newSession.nativeTerminalHint`:this.place.requiredPlacement?`newSession.requiredWorkerHint`:`newSession.hint`),hideSecondaryContent:this.submission.visibility===`incognito`,fadeSecondaryContent:this.submission.message.trim().length>0,modelSetupRequired:this.submission.requiresModelSetup(),onModelSetup:()=>this.context?.navigate(`model-setup`),sessions:this.context?.sessions.state.result,sessionKey:be({agentId:this.place.agentId||`main`,mainKey:this.context?.agents.state.agentsList?.mainKey}),sessionHost:{assistantAgentId:n?.assistantAgentId??null,agentsList:this.context?.agents.state.agentsList??null,hello:n?.hello??null},operatorAuth:n?.hello?.auth??null,onDraftChange:e=>this.setMessageFromUser(e),onSend:()=>void this.submit(),onOpenSession:e=>{let{context:t,submission:n}=this;!t||n.submitting||n.pendingPlacement.sessionKey||(lr({selection:t.agentSelection,gateway:t.gateway,sessionKey:e,agentId:this.place.agentId}),t.navigate(`chat`,vi({context:t,face:`chat`,sessionKey:e}).options))}}}}})))()}function sp(e){return U(L,{get when(){return ru(e.data)},get fallback(){var t=fp();return t._$owner=La(),W(()=>e.data,e=>{t.data=e}),t},keyed:!0,children:e=>e})}function cp(e){let t=()=>e.page().place,n=()=>e.page().submission;return U(L,{get when(){return t().agents().length>1},get children(){return U(Rd,{ref:t=>{e.page().agentPicker=t,e.ref?.(t)},get params(){return{agents:t().agents(),agentId:t().agentId,agentIdentity:e.page().context?.agentIdentity,disabled:n().submitting||!!n().pendingPlacement.sessionKey,onSelect:e=>t().selectAgentId(e),onOpenChange:t=>{e.page().agentPickerOpen=t,e.page().changed()}}}})}})}function lp(e){let t=()=>e.page().submission,n=()=>e.page().place,r,i,a,o=()=>[],s=()=>[],c=()=>r?{root:r,obstacles:[i,...o(),...s(),...t().visibility===`incognito`?[a]:[]].filter(e=>e?.isConnected===!0)}:void 0,l=I(()=>({context:e.page().context,data:e.page().data,gateway:e.page().gateway,place:n(),submitting:t().submitting,pendingPlacement:!!t().pendingPlacement.sessionKey,onConnectMachine:()=>e.page().openConnectMachine(),onNavigate:(t,n)=>e.page().context?.navigate(t,n),onFocusComposer:()=>t().composerTextarea.getTextarea()?.focus({preventScroll:!0}),onChange:()=>e.page().changed()})),u=U(L,{get when(){return!M(e.page().data)},get children(){return U(Dt,{get canSelectFull(){return n().isAdmin()},get defaultMode(){return n().selectedAgent()?.defaultPermissionMode},get disabled(){return t().submitting||!!t().pendingPlacement.sessionKey},get disabledReason(){return B(()=>!!t().submitting)()?N(`newSession.starting`):void 0},get mode(){return t().permissionMode},onSelect:e=>t().setPermissionMode(e??void 0)})}}),d=U(Oi,{readDictation:()=>e.page().dictation.dictation}),f=U(Yd,{get control(){return e.page().dictation},get ownerKey(){return e.page().routeOwnerKey()},get inputDeviceId(){return e.page().context?.theme.settings.realtimeTalkInputDeviceId},get idleLabel(){return N(`newSession.dictate`)},get renderRevision(){return e.revision()}});var p=mp(),m=p.firstChild,h=m.nextSibling,g=h.nextSibling,_=g.nextSibling,v=_.nextSibling,y=v.nextSibling,b=y.nextSibling;return p._$$focusout=()=>e.page().titlePreparation?.setComposing(!1),p.addEventListener(`compositionend`,()=>e.page().titlePreparation?.setComposing(!1)),p.addEventListener(`compositionstart`,()=>e.page().titlePreparation?.setComposing(!0)),G(()=>e=>{r=e},p),z(p,U(lf,{ref:e=>{o=e},get data(){return e.page().data},get groupPending(){return ns(e.page().data,e.page().context?.sessions)},get retrying(){return e.page().gateway.catalogRetrying||!!(e.page().data?.group&&e.page().context?.sessions.groupsStatus()===`loading`)},get retryRead(){return e.page().gateway.catalogRetryRead},onRetry:()=>e.page().gateway.handleCatalogRetry(),get agentSelect(){return U(L,{get when(){return!!e.page().submission.completedSubmission},get children(){return U(cp,{get page(){return e.page},ref:e=>{i=e}})}})},get placeSelect(){return U(Bd,{get params(){return l()},ref:e=>{s=e}})}}),m),z(p,U(L,{get when(){return B(()=>!!n().worktree)()?!bu(n().worktreeName):n().worktree},get children(){return U(Qd,{get message(){return N(`newSession.worktreeNameInvalid`)}})}}),h),z(p,U(L,{get when(){return B(()=>!!M(e.page().data))()?t().capabilities.toolOverrides:M(e.page().data)},get children(){return U(Qd,{get message(){return N(`newSession.terminalCapabilityOverridesUnsupported`)},get action(){return{label:N(`common.reset`),onClick:()=>t().capabilities.setToolOverrides(null)}}})}}),g),z(p,U(L,{get when(){return t().submissionOutcomeUnknown},get children(){return U(Qd,{get message(){return N(t().submissionOutcomeUnknown===`gateway-changed`?`newSession.createOutcomeUnknown`:`newSession.placementSetupInterrupted`)},get action(){return B(()=>!!t().pendingPlacement.sessionKey)()?{label:N(`common.reset`),onClick:()=>t().clearPendingPlacementRecovery()}:void 0}})}}),_),z(p,U(Mf,{surroundings:c,get options(){return Object.assign(e.options(),{permissionControl:u,dictationStatus:d,voiceControl:f})}}),v),z(p,U(L,{get when(){return t().blockedSubmitNotice()},get children(){var e=pp(),n=e.firstChild.firstChild,r=n.nextSibling;return z(n,U(F,{name:`info`})),z(r,()=>t().blockedSubmitNotice()),e}}),y),z(p,U(L,{get when(){return!M(e.page().data)},get children(){return U(qf,{get active(){return t().visibility===`incognito`},ref:e=>{a=e}})}}),b),W(()=>e.submitting?`true`:`false`,e=>{V(p,`aria-busy`,e)}),p}function up(e,t){let n=_i(),r=()=>dp(t),i=e=>(H(()=>{let e=!0;return n&&!Sp.has(t)&&va(xe(n.gateway,()=>e&&t.isConnected)),()=>{e=!1}}),U(Fi,{get error(){return e.error},get onRetry(){return e.reset}}));return U(wt,{get children(){return U(Ra,{fallback:(e,t)=>U(i,{get error(){return e()},reset:t}),get children(){return U(r,{})}})}})}function dp(e){let t=xp.get(e)??new ap(e);xp.set(e,t),t.context=_i();let n=zn(t,e=>e),r=n.read,i=()=>r().isConnected,a=t.context,o=a?zn(a.sessions,e=>({defaults:Object.entries(e.state.result?.defaults??{}),groupStatus:e.groupsStatus(),petMode:ho(!a.gateway.snapshot.offlineStable,e.state.result?.sessions),runOutcome:co(e.state.result?.sessions)}),(e,t)=>e.groupStatus===t.groupStatus&&e.petMode===t.petMode&&e.runOutcome===t.runOutcome&&e.defaults.length===t.defaults.length&&e.defaults.every(([e,n],r)=>e===t.defaults[r]?.[0]&&n===t.defaults[r]?.[1])):void 0;H(()=>o?.subscribe(t.changed)),H(()=>(t.connect(),()=>t.disconnect()));let s=I(()=>({value:n.revision()})),c=I(()=>r().submission.error),l=nd(()=>t,n.revision,c,e=>t.submission.setError(e instanceof Error?e.message:String(e)));H(()=>{let e=Vf(()=>({context:t.context,data:t.data,place:t.place,submission:t.submission,dictating:t.dictation.active}));return t.titlePreparation=e,e.synchronize(),()=>{e.dispose(),t.titlePreparation===e&&(t.titlePreparation=void 0)}});let u=I(()=>r().composerOptions()),d=()=>U(hf,{get value(){return t.submission.composerTextarea},get children(){return U(lp,{page:r,revision:s,options:u,get submitting(){return l()||r().submission.submitting}})}});H(()=>{let n=e.ownerDocument,r=e=>{e.target instanceof Element&&e.target.closest(`.chat-composer-model-control`)||(i.forEach(e=>e()),bp())},i=[`pointerdown`,`keydown`].map(t=>C(e,t,r,!0)),a=[dr(n),C(n,`keydown`,n=>Se(e,n,t.submission.composerTextarea.getTextarea()),!0),C(n.defaultView,`beforeunload`,t.flushDraft),...i];return()=>a.forEach(e=>e())});let f={get visibility(){return r().submission.visibility},get submitting(){return r().submission.submitting},get pendingPlacement(){return r().submission.pendingPlacement},incognitoDisabledReason:()=>r().submission.incognitoDisabledReason(),setVisibility:e=>t.submission.setVisibility(e)},p=()=>r().submission.completedSubmission,m=I(()=>{let e=r().submission,t=e.creationComposer;return e.pendingMessage||t?.hasInput?t:void 0}),h=()=>{let e=r().context?.gateway.snapshot.selfUser?.identity;return e?.type===`profile`?e.id:null},g=()=>{let e=p();if(!e)return;let n=r().context?.placementStartup.get(e.key);return{label:e.error??n?.error??Te(null,n)??N(`newSession.created`),onOpen:()=>void t.submission.openSubmittedSession(),disabled:r().context?.gateway.snapshot.phase!==`connected`}},_=()=>r().attachmentPanel,v=()=>r().imageLightbox,y=()=>{let e=_();return e?{...e.content}:null};return U(L,{get when(){return i()},children:n=>(H(()=>{Sp.add(e)}),[(()=>{var e=hp(),n=e.firstChild,i=n.nextSibling,a=i.nextSibling,o=a.nextSibling,s=o.nextSibling,u=s.nextSibling;return z(e,U(Et,{get context(){return r().context},surface:`new-session`}),n),z(e,U(L,{get when(){return!M(r().data)},get children(){return U(Kf,{submission:f,get draftAvailable(){return r().submission.capabilities.canStartAsDraft(r().context)}})}}),i),z(e,U($d,{get error(){return c()},get pendingMessage(){return r().submission.pendingMessage},get userId(){return h()},get submitting(){return l()||r().submission.submitting},get statusLabel(){return B(()=>r().context?.gateway.snapshot.phase===`connected`)()?void 0:N(`connection.reconnecting`)},get completion(){return g()},get showDraft(){return!!p()},renderDraft:()=>U(L,{get when(){return!!p()},get fallback(){return U(Uf,{get sessions(){return r().context?.sessions},get options(){return r().welcomeOptions()},get assistantNameControl(){return B(()=>!M(r().data)&&r().place.agents().length>1)()?U(cp,{page:r}):void 0},get composer(){return U(d,{})}})},get children(){return U(d,{})}}),get onOpenImage(){return t.setImageLightbox}}),a),z(e,U(L,{get when(){return m()},children:e=>U(Ra,{fallback:(e,t)=>U(Fi,{get error(){return e()},onRetry:t,inline:!0}),get children(){return U(qa,{get fallback(){return U(xr,{})},get children(){return U(vp,{get composer(){return e()},get onOpenImage(){return t.setImageLightbox}})}})}})}),o),z(e,U(Uu,Na(()=>r().connectMachine.view(r().place.isAdmin(),()=>{t.connectMachine.close(),t.context?.navigate(`devices`)}))),s),z(e,U(L,{get when(){return v()},children:e=>U(ot,{get mediaKind(){return e().kind??`image`},get gallery(){return e().gallery},get connectVideo(){return e().connectVideo},get loadDisplayImage(){return e().loadDisplayImage},get readOriginalBlob(){return e().readOriginalBlob},get src(){return e().src},get originalSrc(){return e().originalSrc??``},get imageTitle(){return e().title},get imageWidth(){return e().width},get imageHeight(){return e().height},"onImage-lightbox-close":()=>t.setImageLightbox(null)})}),u),W(()=>({e:!!r().submission.pendingMessage,t:r().submission.visibility===`incognito`}),({e:t,t:n},r)=>{t!==r?.e&&e.classList.toggle(`chat`,t),n!==r?.t&&e.classList.toggle(`new-session-page--incognito`,n)}),e})(),U(L,{get when(){return _()},children:e=>{let n=Oa(()=>U(yp,{get content(){return y()},get"onChat-detail-panel-close"(){return t.closeAttachmentPanel}})),r=()=>(()=>{var e=gp();return z(e,()=>N(`common.loading`)),e})();var i=_p();return z(i,U(Ra,{fallback:(e,i)=>{let a=!0,[o,s]=ka(!1),c=ea(e()),l=()=>a&&t.isConnected&&t.attachmentPanel!==null;H(()=>()=>{a=!1,c&&Er()});let u=async()=>{l()&&(s(!0),!(c&&await Xn({canReload:l}))&&l()&&(s(!1),i()))};return U(L,{get when(){return B(()=>!o())()&&!za(n)},get fallback(){return r()},get children(){return U(Fi,{get error(){return e()},stale:c,onRetry:()=>void u(),get onClose(){return t.closeAttachmentPanel}})}})},get children(){return U(qa,{get fallback(){return r()},get children(){return n()}})}})),i}})])})}var fp,pp,mp,hp,gp,_p,vp,yp,bp,xp,Sp;function Cp(){return(Cp=e((()=>{K(),R(),hr(),Ln(),vt(),go(),Cn(),Ni(),A(),li(),Ei(),Z(),vr(),j(),Lr(),Xt(),_r(),Yr(),Pi(),Xi(),pi(),Xd(),mf(),Q(),gf(),zf(),Zu(),Su(),sf(),Hf(),Wf(),Qf(),su(),op(),rd(),Jd(),E(),fp=q(`<openclaw-new-session-page>`,1),pp=q(`<div class="new-session-page__blocked-submit agent-chat__composer-status"data-tone=info role=status><div class=agent-chat__composer-status-band><span class=agent-chat__composer-status-icon aria-hidden=true></span><span class=agent-chat__composer-status-text>`),mp=q(`<div class=new-session-page__draft><!><!><!><!><!><!><!>`),hp=q(`<div class=new-session-page><!><!><!><!><!><!>`),gp=q(`<div role=status>`),_p=q(`<aside class=new-session-attachment-panel>`),X(),vp=Va(()=>w(()=>import(`./creation-composer-render-4PBpQGlb.js`).then(e=>(e.r(),e.n)),__vite__mapDeps([2,3,4,5,6,7,0,1,8]),import.meta.url),{export:`CreationComposer`},`src/pages/new-session/creation-composer-render.tsx`),yp=Va(async()=>(await w(()=>import(`./control-ui-boot-chat-styles-CEPkk0Pv.js`).then(e=>(e._(),e.v)),__vite__mapDeps([2,3,4,6,7,0,1,8]),import.meta.url),w(()=>import(`./chat-detail-panel-DYEUt8k3.js`),__vite__mapDeps([2,3,4,5,6,7,15,16,17,18,19,20,21,22,23,24,25,26,0,1,8,27,28]),import.meta.url)),{export:`ChatDetailPanel`}),bp=()=>{of(),vp.preload().catch(()=>void 0)},xp=new WeakMap,Sp=new WeakSet,Mn(`openclaw-new-session-page`,up,{properties:{data:{default:void 0,attribute:!1}},propertyChanged:e=>{let t=xp.get(e);t?.retireSubmissionPresentation(),t?.browser.close(),t?.changed()},disconnected:e=>{let t=xp.get(e);t?.retireSubmissionPresentation(),t?.browser.close()},methods:{focusComposer:e=>xp.get(e)?.focusComposer()}}),Ka([`focusout`])})))()}var wp=t({load:()=>Tp});async function Tp(e,t,n){let r=n&&n!==`preload`&&tu(e,t);if(r)return r;let i=xo(t),a=``,o=!1,s;if(i.group){let t=await e.sessions.groupsLoad(),n=t?.find(e=>e.name===i.group);s=t===null?`unavailable`:n?`resolved`:`missing`,a=n?.cwd??``,o=n?.worktree===!0}let c={...i,requestedAgentId:i.agentId,groupStatus:s,groupCwd:a,groupWorktree:o,catalogLabel:``,startTerminal:!1};if(!i.catalogId)return c;let l=(e=``)=>({...c,agentId:e}),u=e.gateway.snapshot,d=e.agents.state;if(u.phase!==`connected`||!u.client||!d.connected||d.client!==u.client)return l();let f=d.agentsList??await e.agents.ensureList(),p=e.gateway.snapshot,m=e.agents.state;if(p.phase!==`connected`||!p.client||p.client!==u.client||!m.connected||m.client!==p.client||!f||m.agentsList!==f)return l();let h=sa(f.agents),g=h.some(e=>e.id===f.defaultId)?f.defaultId:h[0]?.id,_=g?as(i,h,g):``,v=l(_);if(!_)return v;let y=await ss(p.client,i.catalogId,_);return y?{...v,...y}:v}function Ep(){return(Ep=e((()=>{Ve(),Q(),su(),vo()})))()}export{rc as $,bu as A,yl as B,Hu as C,Ho as Ct,Mu as D,Bu as E,Ol as F,gc as G,Yc as H,Dl as I,dc as J,fc as K,kl as L,yu as M,Zl as N,Eu as O,Ql as P,lc as Q,vl as R,Zu as S,Fo as St,zu as T,Qc as U,Zc as V,hc as W,mc as X,uc as Y,sc as Z,rd as _,Jo as _t,$d as a,Vs as at,$u as b,Go as bt,Xd as c,Bs as ct,Jd as d,Es as dt,ec as et,Sd as f,ds as ft,nd as g,qo as gt,td as h,fs as ht,Cp as i,Us as it,vu as j,Su as k,Rd as l,js as lt,Pd as m,ps as mt,wp as n,Zs as nt,sf as o,Hs as ot,wd as p,ms as pt,pc as q,sp as r,$s as rt,Yd as s,zs as st,Ep as t,tc as tt,zd as u,Ds as ut,Qu as v,Z as vt,Vu as w,Io as wt,Uu as x,Uo as xt,ed as y,X as yt,bl as z};