@keyueclaw/skills-ui 0.1.6 → 0.1.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -474,7 +474,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
474
474
  `)}}catch(e){return{content:`Failed to get model info: ${String(e)}`}}try{let r=await e.request(`sessions.patch`,{key:t,model:n.trim()}),i=_u(r.resolved?.model??n.trim(),r.resolved?.modelProvider);return{content:`Model set to \`${n.trim()}\`.`,action:`refresh`,sessionPatch:{modelOverride:gu(i)}}}catch(e){return{content:`Failed to set model: ${String(e)}`}}}async function Su(e,t,n){let r=n.trim();if(!r)try{let{session:n,models:r}=await Iu(e,t);return{content:Nu(`Current thinking level: ${Lu(n,r)}.`,lu(n?.modelProvider,n?.model))}}catch(e){return{content:`Failed to get thinking level: ${String(e)}`}}let i=ou(r);if(!i)try{let n=await Pu(e,t);return{content:`Unrecognized thinking level "${r}". Valid levels: ${lu(n?.modelProvider,n?.model)}.`}}catch(e){return{content:`Failed to validate thinking level: ${String(e)}`}}try{return await e.request(`sessions.patch`,{key:t,thinkingLevel:i}),{content:`Thinking level set to **${i}**.`,action:`refresh`}}catch(e){return{content:`Failed to set thinking level: ${String(e)}`}}}async function Cu(e,t,n){let r=n.trim();if(!r)try{return{content:Nu(`Current verbose level: ${fu((await Pu(e,t))?.verboseLevel)??`off`}.`,`on, full, off`)}}catch(e){return{content:`Failed to get verbose level: ${String(e)}`}}let i=fu(r);if(!i)return{content:`Unrecognized verbose level "${r}". Valid levels: off, on, full.`};try{return await e.request(`sessions.patch`,{key:t,verboseLevel:i}),{content:`Verbose mode set to **${i}**.`,action:`refresh`}}catch(e){return{content:`Failed to set verbose mode: ${String(e)}`}}}async function wu(e,t,n){let r=n.trim().toLowerCase();if(!r||r===`status`)try{return{content:Nu(`Current fast mode: ${Ru(await Pu(e,t))}.`,`status, on, off`)}}catch(e){return{content:`Failed to get fast mode: ${String(e)}`}}if(r!==`on`&&r!==`off`)return{content:`Unrecognized fast mode "${n.trim()}". Valid levels: status, on, off.`};try{return await e.request(`sessions.patch`,{key:t,fastMode:r===`on`}),{content:`Fast mode ${r===`on`?`enabled`:`disabled`}.`,action:`refresh`}}catch(e){return{content:`Failed to set fast mode: ${String(e)}`}}}async function Tu(e,t){try{let n=Fu(await e.request(`sessions.list`,{}),t);if(!n)return{content:`No active session.`};let r=n.inputTokens??0,i=n.outputTokens??0,a=n.totalTokens??r+i,o=n.contextTokens??0,s=o>0?Math.round(r/o*100):null,c=[`**Session Usage**`,`Input: **${zu(r)}** tokens`,`Output: **${zu(i)}** tokens`,`Total: **${zu(a)}** tokens`];return s!==null&&c.push(`Context: **${s}%** of ${zu(o)}`),n.model&&c.push(`Model: \`${n.model}\``),{content:c.join(`
475
475
  `)}}catch(e){return{content:`Failed to get usage: ${String(e)}`}}}async function Eu(e){try{let t=await e.request(`agents.list`,{}),n=t?.agents??[];if(n.length===0)return{content:`No agents configured.`};let r=[`**Agents** (${n.length})\n`];for(let e of n){let n=e.id===t?.defaultId,i=e.identity?.name||e.name||e.id,a=n?` *(default)*`:``;r.push(`- \`${e.id}\` — ${i}${a}`)}return{content:r.join(`
476
476
  `)}}catch(e){return{content:`Failed to list agents: ${String(e)}`}}}async function Du(e,t,n){let r=n.trim();if(!r)return{content:"Usage: `/kill <id|all>`"};try{let n=Ou((await e.request(`sessions.list`,{}))?.sessions??[],t,r);if(n.length===0)return{content:r.toLowerCase()===`all`?`No active sub-agent sessions found.`:`No matching sub-agent sessions found for \`${r}\`.`};let i=await Promise.allSettled(n.map(t=>e.request(`chat.abort`,{sessionKey:t}))),a=i.filter(e=>e.status===`rejected`),o=i.filter(e=>e.status===`fulfilled`&&e.value?.aborted!==!1).length;if(o===0){if(a.length===0)return{content:r.toLowerCase()===`all`?`No active sub-agent runs to abort.`:`No active runs matched \`${r}\`.`};throw a[0]?.reason??Error(`abort failed`)}return r.toLowerCase()===`all`?{content:o===n.length?`Aborted ${o} sub-agent session${o===1?``:`s`}.`:`Aborted ${o} of ${n.length} sub-agent sessions.`}:{content:o===n.length?`Aborted ${o} matching sub-agent session${o===1?``:`s`} for \`${r}\`.`:`Aborted ${o} of ${n.length} matching sub-agent sessions for \`${r}\`.`}}catch(e){return{content:`Failed to abort: ${String(e)}`}}}function Ou(e,t,n){let r=n.trim().toLowerCase();if(!r)return[];let o=new Set,s=t.trim().toLowerCase(),c=i(s)?.agentId??(s===`main`?`main`:void 0),l=Au(e);for(let t of e){let e=t?.key?.trim();if(!e||!a(e))continue;let n=e.toLowerCase(),u=i(n),d=ku(n,s,l,c,u?.agentId);(r===`all`&&d||d&&n===r||d&&((u?.agentId??``)===r||n.endsWith(`:subagent:${r}`)||n===`subagent:${r}`))&&o.add(e)}return[...o]}function ku(e,t,n,r,i){if(!r||i!==r)return!1;let o=Mu(t,r),s=new Set,c=ju(n.get(e)?.spawnedBy);for(;c&&!s.has(c);){if(o.has(c))return!0;s.add(c),c=ju(n.get(c)?.spawnedBy)}return a(t)?e.startsWith(`${t}:subagent:`):!1}function Au(e){let t=new Map;for(let n of e){let e=ju(n?.key);e&&t.set(e,n)}return t}function ju(e){return e?.trim().toLowerCase()||void 0}function Mu(e,t){let n=new Set([e]);if(t===`main`){let t=`agent:${pu}:main`;e===`main`?n.add(t):e===t&&n.add(mu)}return n}function Nu(e,t){return`${e}\nOptions: ${t}.`}async function Pu(e,t){return Fu(await e.request(`sessions.list`,{}),t)}function Fu(e,t){let n=ju(t),r=i(n??``)?.agentId??(n===`main`?`main`:void 0),a=n?Mu(n,r):new Set;return e?.sessions?.find(e=>{let t=ju(e.key);return t?a.has(t):!1})}async function Iu(e,t){let[n,r]=await Promise.all([e.request(`sessions.list`,{}),e.request(`models.list`,{})]);return{session:Fu(n,t),models:r?.models??[]}}function Lu(e,t){return ou(e?.thinkingLevel)||(!e?.modelProvider||!e.model?`off`:uu({provider:e.modelProvider,model:e.model,catalog:t}))}function Ru(e){return e?.fastMode===!0?`on`:`off`}function zu(e){return e>=1e6?`${(e/1e6).toFixed(1).replace(/\.0$/,``)}M`:e>=1e3?`${(e/1e3).toFixed(1).replace(/\.0$/,``)}k`:String(e)}var Bu={AUTH_REQUIRED:`AUTH_REQUIRED`,AUTH_UNAUTHORIZED:`AUTH_UNAUTHORIZED`,AUTH_TOKEN_MISSING:`AUTH_TOKEN_MISSING`,AUTH_TOKEN_MISMATCH:`AUTH_TOKEN_MISMATCH`,AUTH_TOKEN_NOT_CONFIGURED:`AUTH_TOKEN_NOT_CONFIGURED`,AUTH_PASSWORD_MISSING:`AUTH_PASSWORD_MISSING`,AUTH_PASSWORD_MISMATCH:`AUTH_PASSWORD_MISMATCH`,AUTH_PASSWORD_NOT_CONFIGURED:`AUTH_PASSWORD_NOT_CONFIGURED`,AUTH_BOOTSTRAP_TOKEN_INVALID:`AUTH_BOOTSTRAP_TOKEN_INVALID`,AUTH_DEVICE_TOKEN_MISMATCH:`AUTH_DEVICE_TOKEN_MISMATCH`,AUTH_RATE_LIMITED:`AUTH_RATE_LIMITED`,AUTH_TAILSCALE_IDENTITY_MISSING:`AUTH_TAILSCALE_IDENTITY_MISSING`,AUTH_TAILSCALE_PROXY_MISSING:`AUTH_TAILSCALE_PROXY_MISSING`,AUTH_TAILSCALE_WHOIS_FAILED:`AUTH_TAILSCALE_WHOIS_FAILED`,AUTH_TAILSCALE_IDENTITY_MISMATCH:`AUTH_TAILSCALE_IDENTITY_MISMATCH`,CONTROL_UI_ORIGIN_NOT_ALLOWED:`CONTROL_UI_ORIGIN_NOT_ALLOWED`,CONTROL_UI_DEVICE_IDENTITY_REQUIRED:`CONTROL_UI_DEVICE_IDENTITY_REQUIRED`,DEVICE_IDENTITY_REQUIRED:`DEVICE_IDENTITY_REQUIRED`,DEVICE_AUTH_INVALID:`DEVICE_AUTH_INVALID`,DEVICE_AUTH_DEVICE_ID_MISMATCH:`DEVICE_AUTH_DEVICE_ID_MISMATCH`,DEVICE_AUTH_SIGNATURE_EXPIRED:`DEVICE_AUTH_SIGNATURE_EXPIRED`,DEVICE_AUTH_NONCE_REQUIRED:`DEVICE_AUTH_NONCE_REQUIRED`,DEVICE_AUTH_NONCE_MISMATCH:`DEVICE_AUTH_NONCE_MISMATCH`,DEVICE_AUTH_SIGNATURE_INVALID:`DEVICE_AUTH_SIGNATURE_INVALID`,DEVICE_AUTH_PUBLIC_KEY_INVALID:`DEVICE_AUTH_PUBLIC_KEY_INVALID`,PAIRING_REQUIRED:`PAIRING_REQUIRED`},Vu=new Set([`retry_with_device_token`,`update_auth_configuration`,`update_auth_credentials`,`wait_then_retry`,`review_auth_configuration`]);function Hu(e){if(!e||typeof e!=`object`||Array.isArray(e))return null;let t=e.code;return typeof t==`string`&&t.trim().length>0?t:null}function Uu(e){if(!e||typeof e!=`object`||Array.isArray(e))return{};let t=e,n=typeof t.canRetryWithDeviceToken==`boolean`?t.canRetryWithDeviceToken:void 0,r=typeof t.recommendedNextStep==`string`?t.recommendedNextStep.trim():``;return{canRetryWithDeviceToken:n,recommendedNextStep:Vu.has(r)?r:void 0}}function Wu(e){let t=e.scopes.join(`,`),n=e.token??``;return[`v2`,e.deviceId,e.clientId,e.clientMode,e.role,t,String(e.signedAtMs),n,e.nonce].join(`|`)}var Gu={WEBCHAT_UI:`webchat-ui`,CONTROL_UI:`openclaw-control-ui`,WEBCHAT:`webchat`,CLI:`cli`,GATEWAY_CLIENT:`gateway-client`,MACOS_APP:`openclaw-macos`,IOS_APP:`openclaw-ios`,ANDROID_APP:`openclaw-android`,NODE_HOST:`node-host`,TEST:`test`,FINGERPRINT:`fingerprint`,PROBE:`openclaw-probe`},Ku=Gu,qu={WEBCHAT:`webchat`,CLI:`cli`,UI:`ui`,BACKEND:`backend`,NODE:`node`,PROBE:`probe`,TEST:`test`};new Set(Object.values(Gu)),new Set(Object.values(qu));var Ju=!1;function Yu(e){e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t=``;for(let n=0;n<e.length;n++)t+=e[n].toString(16).padStart(2,`0`);return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}function Xu(){let e=new Uint8Array(16),t=Date.now();for(let t=0;t<e.length;t++)e[t]=Math.floor(Math.random()*256);return e[0]^=t&255,e[1]^=t>>>8&255,e[2]^=t>>>16&255,e[3]^=t>>>24&255,e}function Zu(){Ju||(Ju=!0,console.warn(`[uuid] crypto API missing; falling back to weak randomness`))}function Qu(e=globalThis.crypto){if(e&&typeof e.randomUUID==`function`)return e.randomUUID();if(e&&typeof e.getRandomValues==`function`){let t=new Uint8Array(16);return e.getRandomValues(t),Yu(t)}return Zu(),Yu(Xu())}var $u=class extends Error{constructor(e){super(e.message),this.name=`GatewayRequestError`,this.gatewayCode=e.code,this.details=e.details}};function ed(e){return Hu(e?.details)}function td(e){if(!e)return!1;let t=ed(e);return t===Bu.AUTH_TOKEN_MISSING||t===Bu.AUTH_BOOTSTRAP_TOKEN_INVALID||t===Bu.AUTH_PASSWORD_MISSING||t===Bu.AUTH_PASSWORD_MISMATCH||t===Bu.AUTH_RATE_LIMITED||t===Bu.PAIRING_REQUIRED||t===Bu.CONTROL_UI_DEVICE_IDENTITY_REQUIRED||t===Bu.DEVICE_IDENTITY_REQUIRED}function nd(e){try{let t=new URL(e,window.location.href),n=t.hostname.trim().toLowerCase(),r=n===`localhost`||n===`::1`||n===`[::1]`||n===`127.0.0.1`,i=n.startsWith(`127.`);if(r||i)return!0;let a=new URL(window.location.href);return t.host===a.host}catch{return!1}}var rd=4008,id=class{constructor(e){this.opts=e,this.ws=null,this.pending=new Map,this.closed=!1,this.lastSeq=null,this.connectNonce=null,this.connectSent=!1,this.connectTimer=null,this.backoffMs=800,this.pendingDeviceTokenRetry=!1,this.deviceTokenRetryBudgetUsed=!1}start(){this.closed=!1,this.connect()}stop(){this.closed=!0,this.ws?.close(),this.ws=null,this.pendingConnectError=void 0,this.pendingDeviceTokenRetry=!1,this.deviceTokenRetryBudgetUsed=!1,this.flushPending(Error(`gateway client stopped`))}get connected(){return this.ws?.readyState===WebSocket.OPEN}connect(){this.closed||(this.ws=new WebSocket(this.opts.url),this.ws.addEventListener(`open`,()=>this.queueConnect()),this.ws.addEventListener(`message`,e=>this.handleMessage(String(e.data??``))),this.ws.addEventListener(`close`,e=>{let t=String(e.reason??``),n=this.pendingConnectError;this.pendingConnectError=void 0,this.ws=null,this.flushPending(Error(`gateway closed (${e.code}): ${t}`)),this.opts.onClose?.({code:e.code,reason:t,error:n}),!(ed(n)===Bu.AUTH_TOKEN_MISMATCH&&this.deviceTokenRetryBudgetUsed&&!this.pendingDeviceTokenRetry)&&(td(n)||this.scheduleReconnect())}),this.ws.addEventListener(`error`,()=>{}))}scheduleReconnect(){if(this.closed)return;let e=this.backoffMs;this.backoffMs=Math.min(this.backoffMs*1.7,15e3),window.setTimeout(()=>this.connect(),e)}flushPending(e){for(let[,t]of this.pending)t.reject(e);this.pending.clear()}async sendConnect(){if(this.connectSent)return;this.connectSent=!0,this.connectTimer!==null&&(window.clearTimeout(this.connectTimer),this.connectTimer=null);let e=typeof crypto<`u`&&!!crypto.subtle,t=[`operator.admin`,`operator.approvals`,`operator.pairing`],n=`operator`,r=this.opts.token?.trim()||void 0,i=this.opts.password?.trim()||void 0,a=null,o={authToken:r,authPassword:i,canFallbackToShared:!1};e&&(a=await Vn(),o=this.selectConnectAuth({role:n,deviceId:a.deviceId}),this.pendingDeviceTokenRetry&&o.authDeviceToken&&(this.pendingDeviceTokenRetry=!1));let s=o.authToken,c=o.authDeviceToken??o.resolvedDeviceToken,l=s||o.authPassword?{token:s,deviceToken:c,password:o.authPassword}:void 0,u;if(e&&a){let e=Date.now(),r=this.connectNonce??``,i=Wu({deviceId:a.deviceId,clientId:this.opts.clientName??Ku.CONTROL_UI,clientMode:this.opts.mode??qu.WEBCHAT,role:n,scopes:t,signedAtMs:e,token:s??null,nonce:r}),o=await Hn(a.privateKey,i);u={id:a.deviceId,publicKey:a.publicKey,signature:o,signedAt:e,nonce:r}}let d={minProtocol:3,maxProtocol:3,client:{id:this.opts.clientName??Ku.CONTROL_UI,version:this.opts.clientVersion??`control-ui`,platform:this.opts.platform??navigator.platform??`web`,mode:this.opts.mode??qu.WEBCHAT,instanceId:this.opts.instanceId},role:n,scopes:t,device:u,caps:[`tool-events`],auth:l,userAgent:navigator.userAgent,locale:navigator.language,userPhone:this.opts.phone};this.request(`connect`,d).then(e=>{this.pendingDeviceTokenRetry=!1,this.deviceTokenRetryBudgetUsed=!1,e?.auth?.deviceToken&&a&&wt({deviceId:a.deviceId,role:e.auth.role??n,token:e.auth.deviceToken,scopes:e.auth.scopes??[]}),this.backoffMs=800,this.opts.onHello?.(e)}).catch(e=>{let t=e instanceof $u?ed(e):null,i=e instanceof $u?Uu(e.details):{},s=i.recommendedNextStep===`retry_with_device_token`,c=i.canRetryWithDeviceToken===!0||s||t===Bu.AUTH_TOKEN_MISMATCH;!this.deviceTokenRetryBudgetUsed&&!o.authDeviceToken&&r&&a&&o.storedToken&&c&&nd(this.opts.url)&&(this.pendingDeviceTokenRetry=!0,this.deviceTokenRetryBudgetUsed=!0),e instanceof $u?this.pendingConnectError={code:e.gatewayCode,message:e.message,details:e.details}:this.pendingConnectError=void 0,o.canFallbackToShared&&a&&t===Bu.AUTH_DEVICE_TOKEN_MISMATCH&&Tt({deviceId:a.deviceId,role:n}),this.ws?.close(rd,`connect failed`)})}handleMessage(e){let t;try{t=JSON.parse(e)}catch{return}let n=t;if(n.type===`event`){let e=t;if(e.event===`connect.challenge`){let t=e.payload,n=t&&typeof t.nonce==`string`?t.nonce:null;n&&(this.connectNonce=n,this.sendConnect());return}let n=typeof e.seq==`number`?e.seq:null;n!==null&&(this.lastSeq!==null&&n>this.lastSeq+1&&this.opts.onGap?.({expected:this.lastSeq+1,received:n}),this.lastSeq=n);try{this.opts.onEvent?.(e)}catch(e){console.error(`[gateway] event handler error:`,e)}return}if(n.type===`res`){let e=t,n=this.pending.get(e.id);if(!n)return;this.pending.delete(e.id),e.ok?n.resolve(e.payload):n.reject(new $u({code:e.error?.code??`UNAVAILABLE`,message:e.error?.message??`request failed`,details:e.error?.details}));return}}selectConnectAuth(e){let t=this.opts.token?.trim()||void 0,n=this.opts.password?.trim()||void 0,r=Ct({deviceId:e.deviceId,role:e.role})?.token,i=this.pendingDeviceTokenRetry&&!!t&&!!r&&nd(this.opts.url),a=t||n?void 0:r??void 0;return{authToken:t??a,authDeviceToken:i?r??void 0:void 0,authPassword:n,resolvedDeviceToken:a,storedToken:r??void 0,canFallbackToShared:!!(r&&t)}}request(e,t){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)return Promise.reject(Error(`gateway not connected`));let n=Qu(),r={type:`req`,id:n,method:e,params:t},i=new Promise((e,t)=>{this.pending.set(n,{resolve:t=>e(t),reject:t})});return this.ws.send(JSON.stringify(r)),i}queueConnect(){this.connectNonce=null,this.connectSent=!1,this.connectTimer!==null&&window.clearTimeout(this.connectTimer),this.connectTimer=window.setTimeout(()=>{this.sendConnect()},750)}};function ad(e){return typeof e==`string`?e:e instanceof Error&&typeof e.message==`string`?e.message:`unknown error`}function od(e){let t=ad(e.message);switch(ed(e)){case Bu.AUTH_TOKEN_MISMATCH:return`gateway token mismatch`;case Bu.AUTH_UNAUTHORIZED:return`gateway auth failed`;case Bu.AUTH_RATE_LIMITED:return`too many failed authentication attempts`;case Bu.PAIRING_REQUIRED:return`gateway pairing required`;case Bu.CONTROL_UI_DEVICE_IDENTITY_REQUIRED:return`device identity required (use HTTPS/localhost or allow insecure auth explicitly)`;case Bu.CONTROL_UI_ORIGIN_NOT_ALLOWED:return`origin not allowed (open the Control UI from the gateway host or allow it in gateway.controlUi.allowedOrigins)`;case Bu.AUTH_TOKEN_MISSING:return`gateway token missing`;default:break}let n=t.trim().toLowerCase();return n===`fetch failed`||n===`failed to fetch`||n===`connect failed`?`gateway connect failed`:t}function sd(e){return e&&typeof e==`object`?od(e):ad(e)}var cd=/^\s*NO_REPLY\s*$/;function ld(e){return cd.test(e)}function ud(e){if(!e||typeof e!=`object`)return!1;let t=e;if((typeof t.role==`string`?t.role.toLowerCase():``)!==`assistant`)return!1;if(typeof t.text==`string`)return ld(t.text);let n=Ga(e);return typeof n==`string`&&ld(n)}function dd(e){let t=e;t.toolStreamById instanceof Map&&Array.isArray(t.toolStreamOrder)&&Array.isArray(t.chatToolMessages)&&Array.isArray(t.chatStreamSegments)&&Jl(t)}async function fd(e){if(!(!e.client||!e.connected)){e.chatLoading=!0,e.lastError=null;try{let t=await e.client.request(`chat.history`,{sessionKey:e.sessionKey,limit:200});e.chatMessages=(Array.isArray(t.messages)?t.messages:[]).filter(e=>!ud(e)),e.chatThinkingLevel=t.thinkingLevel??null,dd(e),e.chatStream=null,e.chatStreamStartedAt=null}catch(t){e.lastError=String(t)}finally{e.chatLoading=!1}}}function pd(e){let t=/^data:([^;]+);base64,(.+)$/.exec(e);return t?{mimeType:t[1],content:t[2]}:null}function md(e,t){if(!e||typeof e!=`object`)return null;let n=e,r=n.role;if(typeof r==`string`){if((t.roleCaseSensitive?r:r.toLowerCase())!==`assistant`)return null}else if(t.roleRequirement===`required`)return null;return t.requireContentArray?Array.isArray(n.content)?n:null:!(`content`in n)&&!(t.allowTextField&&`text`in n)?null:n}function hd(e){return md(e,{roleRequirement:`required`,roleCaseSensitive:!0,requireContentArray:!0})}function gd(e){return md(e,{roleRequirement:`optional`,allowTextField:!0})}async function _d(e,t,n){if(!e.client||!e.connected)return null;let r=t.trim(),i=n&&n.length>0;if(!r&&!i)return null;let a=Date.now(),o=[];if(r&&o.push({type:`text`,text:r}),i)for(let e of n)o.push({type:`image`,source:{type:`base64`,media_type:e.mimeType,data:e.dataUrl}});e.chatMessages=[...e.chatMessages,{role:`user`,content:o,timestamp:a}],e.chatSending=!0,e.lastError=null;let s=Qu();e.chatRunId=s,e.chatStream=``,e.chatStreamStartedAt=a;let c=i?n.map(e=>{let t=pd(e.dataUrl);return t?{type:`image`,mimeType:t.mimeType,content:t.content}:null}).filter(e=>e!==null):void 0;try{return await e.client.request(`chat.send`,{sessionKey:e.sessionKey,message:r,deliver:!1,idempotencyKey:s,attachments:c}),s}catch(t){let n=sd(t);return e.chatRunId=null,e.chatStream=null,e.chatStreamStartedAt=null,e.lastError=n,e.chatMessages=[...e.chatMessages,{role:`assistant`,content:[{type:`text`,text:`Error: `+n}],timestamp:Date.now()}],null}finally{e.chatSending=!1}}async function vd(e){if(!e.client||!e.connected)return!1;let t=e.chatRunId;try{return await e.client.request(`chat.abort`,t?{sessionKey:e.sessionKey,runId:t}:{sessionKey:e.sessionKey}),!0}catch(t){return e.lastError=sd(t),!1}}function yd(e,t){if(!t||t.sessionKey!==e.sessionKey)return null;if(t.runId&&e.chatRunId&&t.runId!==e.chatRunId){if(t.state===`final`){let n=gd(t.message);return n&&!ud(n)?(e.chatMessages=[...e.chatMessages,n],null):`final`}return null}if(t.state===`delta`){let n=Ga(t.message);if(typeof n==`string`&&!ld(n)){let t=e.chatStream??``;(!t||n.length>=t.length)&&(e.chatStream=n)}}else if(t.state===`final`){let n=gd(t.message);n&&!ud(n)?e.chatMessages=[...e.chatMessages,n]:e.chatStream?.trim()&&!ld(e.chatStream)&&(e.chatMessages=[...e.chatMessages,{role:`assistant`,content:[{type:`text`,text:e.chatStream}],timestamp:Date.now()}]),e.chatStream=null,e.chatRunId=null,e.chatStreamStartedAt=null}else if(t.state===`aborted`){let n=hd(t.message);if(n&&!ud(n))e.chatMessages=[...e.chatMessages,n];else{let t=e.chatStream??``;t.trim()&&!ld(t)&&(e.chatMessages=[...e.chatMessages,{role:`assistant`,content:[{type:`text`,text:t}],timestamp:Date.now()}])}e.chatStream=null,e.chatRunId=null,e.chatStreamStartedAt=null}else t.state===`error`&&(e.chatStream=null,e.chatRunId=null,e.chatStreamStartedAt=null,e.lastError=t.errorMessage??`chat error`);return t.state}async function bd(e){try{return(await e.request(`models.list`,{}))?.models??[]}catch{return[]}}function xd(e){return e.chatSending||!!e.chatRunId}async function Sd(e){e.connected&&(e.chatMessage=``,await vd(e))}async function Cd(e,t,n){Jl(e),u(e);let r=await _d(e,t,n?.attachments),i=!!r;return!i&&n?.previousDraft!=null&&(e.chatMessage=n.previousDraft),!i&&n?.previousAttachments&&(e.chatAttachments=n.previousAttachments),i&&_l(e,e.sessionKey),i&&n?.restoreDraft&&n.previousDraft?.trim()&&(e.chatMessage=n.previousDraft),i&&n?.restoreAttachments&&n.previousAttachments?.length&&(e.chatAttachments=n.previousAttachments),c(e,!0),i&&!e.chatRunId&&wd(e),i&&n?.refreshSessions&&r&&e.refreshSessionsAfterChat.add(r),i}async function wd(e){if(!e.connected||xd(e))return;let[t,...n]=e.chatQueue;if(!t)return;e.chatQueue=n;let r=!1;try{t.localCommandName?(await Td(e,t.localCommandName,t.localCommandArgs??``),r=!0):r=await Cd(e,t.text,{attachments:t.attachments,refreshSessions:t.refreshSessions})}catch(t){e.lastError=String(t)}r?e.chatQueue.length>0&&wd(e):e.chatQueue=[t,...e.chatQueue]}async function Td(e,t,n,r){switch(t){case`stop`:await Sd(e);return;case`new`:await Cd(e,`/new`,{refreshSessions:!0,previousDraft:r?.previousDraft,restoreDraft:r?.restoreDraft});return;case`reset`:await Cd(e,`/reset`,{refreshSessions:!0,previousDraft:r?.previousDraft,restoreDraft:r?.restoreDraft});return;case`clear`:await Ed(e);return;case`focus`:e.onSlashAction?.(`toggle-focus`);return;case`export`:e.onSlashAction?.(`export`);return}if(!e.client)return;let i=e.sessionKey,a=await vu(e.client,i,t,n);a.content&&Dd(e,a.content),a.sessionPatch&&`modelOverride`in a.sessionPatch&&(e.chatModelOverrides={...e.chatModelOverrides,[i]:a.sessionPatch.modelOverride??null}),a.action===`refresh`&&await Od(e),c(e)}async function Ed(e){if(!(!e.client||!e.connected)){try{await e.client.request(`sessions.reset`,{key:e.sessionKey}),e.chatMessages=[],e.chatStream=null,e.chatRunId=null,await fd(e)}catch(t){e.lastError=String(t)}c(e)}}function Dd(e,t){e.chatMessages=[...e.chatMessages,{role:`system`,content:t,timestamp:Date.now()}]}async function Od(e,t){await Promise.all([fd(e),Jn(e,{activeMinutes:0,limit:0,includeGlobal:!0,includeUnknown:!0}),Nd(e),kd(e)]),t?.scheduleScroll!==!1&&c(e)}async function kd(e){if(!e.client||!e.connected){e.chatModelsLoading=!1,e.chatModelCatalog=[];return}e.chatModelsLoading=!0;try{e.chatModelCatalog=await bd(e.client)}finally{e.chatModelsLoading=!1}}var Ad=wd;function jd(e){let t=i(e.sessionKey);return t?.agentId?t.agentId:(e.hello?.snapshot)?.sessionDefaults?.defaultAgentId?.trim()||`main`}function Md(e,t){let n=Pr(e),r=encodeURIComponent(t);return n?`${n}/avatar/${r}?meta=1`:`avatar/${r}?meta=1`}async function Nd(e){if(!e.connected){e.chatAvatarUrl=null;return}let t=jd(e);if(!t){e.chatAvatarUrl=null;return}e.chatAvatarUrl=null;let n=Md(e.basePath,t);try{let t=await fetch(n,{method:`GET`});if(!t.ok){e.chatAvatarUrl=null;return}let r=await t.json();e.chatAvatarUrl=(typeof r.avatarUrl==`string`?r.avatarUrl.trim():``)||null}catch{e.chatAvatarUrl=null}}function Pd(e){if(!e||e.state!==`final`)return!1;if(!e.message||typeof e.message!=`object`)return!0;let t=e.message,n=typeof t.role==`string`?t.role.toLowerCase():``;return!!(n&&n!==`assistant`)}function Fd(e,t){if(typeof e!=`string`)return;let n=e.trim();if(n)return n.length<=t?n:n.slice(0,t)}var Id=50,Ld=200;function Rd(e){let t=Fd(e?.name,Id)??`Assistant`,n=Fd(e?.avatar??void 0,Ld)??null;return{agentId:typeof e?.agentId==`string`&&e.agentId.trim()?e.agentId.trim():null,name:t,avatar:n}}async function zd(e,t){if(!e.client||!e.connected)return;let n=t?.sessionKey?.trim()||e.sessionKey.trim(),r=n?{sessionKey:n}:{};try{let t=await e.client.request(`agent.identity.get`,r);if(!t)return;let n=Rd(t);e.assistantName=n.name,e.assistantAvatar=n.avatar,e.assistantAgentId=n.agentId??null}catch{}}function Bd(e){return typeof e==`object`&&!!e}function Vd(e){if(!Bd(e))return null;let t=typeof e.id==`string`?e.id.trim():``,n=e.request;if(!t||!Bd(n))return null;let r=typeof n.command==`string`?n.command.trim():``;if(!r)return null;let i=typeof e.createdAtMs==`number`?e.createdAtMs:0,a=typeof e.expiresAtMs==`number`?e.expiresAtMs:0;return!i||!a?null:{id:t,request:{command:r,cwd:typeof n.cwd==`string`?n.cwd:null,host:typeof n.host==`string`?n.host:null,security:typeof n.security==`string`?n.security:null,ask:typeof n.ask==`string`?n.ask:null,agentId:typeof n.agentId==`string`?n.agentId:null,resolvedPath:typeof n.resolvedPath==`string`?n.resolvedPath:null,sessionKey:typeof n.sessionKey==`string`?n.sessionKey:null},createdAtMs:i,expiresAtMs:a}}function Hd(e){if(!Bd(e))return null;let t=typeof e.id==`string`?e.id.trim():``;return t?{id:t,decision:typeof e.decision==`string`?e.decision:null,resolvedBy:typeof e.resolvedBy==`string`?e.resolvedBy:null,ts:typeof e.ts==`number`?e.ts:null}:null}function Ud(e){let t=Date.now();return e.filter(e=>e.expiresAtMs>t)}function Wd(e,t){let n=Ud(e).filter(e=>e.id!==t.id);return n.push(t),n}function Gd(e,t){return Ud(e).filter(e=>e.id!==t)}var Kd={ok:!1,ts:0,durationMs:0,heartbeatSeconds:0,defaultAgentId:``,agents:[],sessions:{path:``,count:0,recent:[]}};async function qd(e){try{return await e.request(`health`,{})??Kd}catch{return Kd}}async function Jd(e){if(!(!e.client||!e.connected)&&!e.healthLoading){e.healthLoading=!0,e.healthError=null;try{e.healthResult=await qd(e.client)}catch(t){e.healthError=String(t)}finally{e.healthLoading=!1}}}function Yd(e,t){return`${e}::${t}`}async function Xd(e,t,n){if(!e.client||!e.connected||!n?.force&&e.skillFilesLoading)return;e.skillFilesLoading=!0,e.skillFilesError=null;let r=null;try{let n=await e.client.request(`skills.files.list`,{skillKey:t});n&&(e.skillFilesLists={...e.skillFilesLists,[t]:n},!e.skillFilesActiveName&&n.files.length>0&&(e.skillFilesActiveName=n.files[0].name,r=n.files[0].name))}catch(t){e.skillFilesError=t instanceof Error?t.message:String(t)}finally{e.skillFilesLoading=!1}r&&await Zd(e,t,r)}async function Zd(e,t,n,r){if(!e.client||!e.connected||!r?.force&&e.skillFilesLoading)return;let i=Yd(t,n);if(!(!r?.force&&Object.hasOwn(e.skillFilesContents,i))){e.skillFilesLoading=!0,e.skillFilesError=null;try{let r=await e.client.request(`skills.files.get`,{skillKey:t,name:n});if(r){let t=e.skillFilesContents[i],n=e.skillFilesDrafts[i];e.skillFilesContents={...e.skillFilesContents,[i]:r.content},(!Object.hasOwn(e.skillFilesDrafts,i)||n===t)&&(e.skillFilesDrafts={...e.skillFilesDrafts,[i]:r.content})}}catch(t){e.skillFilesError=t instanceof Error?t.message:String(t)}finally{e.skillFilesLoading=!1}}}async function Qd(e,t,n,r){if(!e.client||!e.connected||e.skillFilesSaving)return null;e.skillFilesSaving=!0,e.skillFilesError=null;try{let i=(await e.client.request(`skills.files.set`,{skillKey:t,name:n,content:r}))?.skillKey??t,a=Yd(i,n);return e.skillFilesContents={...e.skillFilesContents,[a]:r},e.skillFilesDrafts={...e.skillFilesDrafts,[a]:r},i}catch(t){return e.skillFilesError=t instanceof Error?t.message:String(t),null}finally{e.skillFilesSaving=!1}}function $d(e,t,n,r){let i=Yd(t,n);e.skillFilesDrafts={...e.skillFilesDrafts,[i]:r}}function ef(e,t){e.skillFilesActiveKey=t,e.skillFilesActiveName=null}function tf(e){e.skillFilesActiveKey=null,e.skillFilesActiveName=null}function nf(e,t){e.skillFilesActiveName=t}var rf=`skill-creator`;async function af(e){if(!(await e.request(`agents.list`,{})).agents.some(e=>e.id===rf))try{await e.request(`agents.create`,{name:rf,skills:[rf],templatePrefix:`SKILL_`})}catch{}}async function of(e,t,n){if(!e.client||!e.connected||!t.trim()||!n)return;let r=Date.now(),i=Qu();e.skillAiChatMessages=[...e.skillAiChatMessages,{role:`user`,content:[{type:`text`,text:t}],timestamp:r}],e.skillAiChatSending=!0,e.skillAiChatRunId=i,e.skillAiChatStream=``,e.skillAiChatStreamStartedAt=r,e.skillAiBuilderBuilding=!0;try{await e.client.request(`chat.send`,{sessionKey:`agent:skill-creator:${n}`,message:t.trim(),deliver:!1,idempotencyKey:i})}catch{e.skillAiChatSending=!1,e.skillAiChatRunId=null,e.skillAiChatStream=null,e.skillAiChatStreamStartedAt=null,e.skillAiBuilderBuilding=!1}}function sf(e,t){let n=`${t}::`,r={},i={};for(let[t,i]of Object.entries(e.skillFilesContents))t.startsWith(n)||(r[t]=i);for(let[t,r]of Object.entries(e.skillFilesDrafts))t.startsWith(n)||(i[t]=r);e.skillFilesContents=r,e.skillFilesDrafts=i}function cf(e){e.skillAiBuilderMode=!1,e.skillAiBuilderSkillKey=null,e.skillAiBuilderBuilding=!1,e.skillAiBuilderExitConfirm=!1,e.skillAiBuilderActiveTab=`chat`,e.skillAiBuilderOpenTabs=[],e.skillAiChatMessages=[],e.skillAiChatStream=null,e.skillAiChatSending=!1,e.skillAiChatRunId=null,e.skillAiChatMessage=``,e.skillAiToolCalls=[],e.skillFilesActiveKey=null,e.skillFilesActiveName=null}function lf(e){return{connected:e.connected,loading:e.skillsLoading,report:e.skillsReport,error:e.skillsError,filter:e.skillsFilter,edits:e.skillEdits,messages:e.skillMessages,busyKey:e.skillsBusyKey,onFilterChange:t=>e.skillsFilter=t,onRefresh:()=>void Zn(e,{clearMessages:!0}),onToggle:(t,n)=>void $n(e,t,n),onEdit:(t,n)=>Qn(e,t,n),onSaveKey:t=>void er(e,t),onInstall:(t,n,r)=>void tr(e,t,n,r),skillFilesLists:e.skillFilesLists,skillFilesContents:e.skillFilesContents,skillFilesDrafts:e.skillFilesDrafts,skillFilesActiveKey:e.skillFilesActiveKey,skillFilesActiveName:e.skillFilesActiveName,skillFilesLoading:e.skillFilesLoading,skillFilesSaving:e.skillFilesSaving,skillFilesError:e.skillFilesError,skillFilesFullscreen:e.skillFilesFullscreen,skillFilesBackConfirm:e.skillFilesBackConfirm,onOpenEditor:t=>{sf(e,t),ef(e,t),e.skillFilesActiveDir=e.skillsReport?.skills.find(e=>e.skillKey===t)?.baseDir??null,Xd(e,t)},onCloseEditor:()=>{let t=e.skillFilesActiveKey;t&&sf(e,t),tf(e),e.skillFilesActiveDir=null,e.skillFilesFullscreen=!1,e.skillFilesBackConfirm=!1,e.skillCreateMode&&(e.skillCreateMode=!1,e.skillCreateName=``,e.skillCreateDesc=``,e.skillCreateError=null),Zn(e)},onSelectFile:async(t,n)=>{nf(e,n),n&&await Zd(e,t,n,{force:!0})},onRefreshFilesList:async t=>{await Xd(e,t,{force:!0})},onEditFileDraft:(t,n,r)=>$d(e,t,n,r),onSaveFile:async(t,n,r)=>{let i=await Qd(e,t,n,r);if(await Zn(e),i&&i!==t){let n=e.skillFilesActiveName;e.skillFilesActiveKey=i,e.skillAiBuilderSkillKey===t&&(e.skillAiBuilderSkillKey=i),e.skillFilesActiveDir=e.skillsReport?.skills.find(e=>e.skillKey===i)?.baseDir??null,await Xd(e,i,{force:!0}),n&&(e.skillFilesActiveName=n,await Zd(e,i,n,{force:!0}))}},onToggleFullscreen:()=>{e.skillFilesFullscreen=!e.skillFilesFullscreen},onShowBackConfirm:()=>{e.skillFilesBackConfirm=!0},onHideBackConfirm:()=>{e.skillFilesBackConfirm=!1},skillCreateMode:e.skillCreateMode,skillCreateName:e.skillCreateName,skillCreateDesc:e.skillCreateDesc,skillCreateBusy:e.skillCreateBusy,skillCreateError:e.skillCreateError,onStartCreate:()=>{e.skillCreateMode=!0,e.skillCreateName=``,e.skillCreateDesc=``,e.skillCreateError=null},onCancelCreate:()=>{e.skillCreateMode=!1,e.skillCreateName=``,e.skillCreateDesc=``,e.skillCreateError=null,e.skillFilesActiveKey=null,e.skillFilesActiveName=null},onCreateNameChange:t=>e.skillCreateName=t,onCreateDescChange:t=>e.skillCreateDesc=t,onSubmitCreate:async()=>{let t=await rr(e,e.skillCreateName,e.skillCreateDesc);t&&(e.skillCreateMode=!1,e.skillCreateName=``,e.skillCreateDesc=``,await Zn(e),sf(e,t),ef(e,t),e.skillFilesActiveDir=e.skillsReport?.skills.find(e=>e.skillKey===t)?.baseDir??null,Xd(e,t))},skillUploadBusy:e.skillUploadBusy,skillUploadError:e.skillUploadError,skillUploadOverwriteKey:e.skillUploadOverwriteKey,onUploadFile:async t=>{e.skillUploadError=null;let n=await ar(e,t,!1);n?.conflictKey?(e.skillUploadOverwriteKey=n.conflictKey,e.skillUploadPendingFile=t):n?.skillKey&&Zn(e)},onConfirmOverwrite:async()=>{let t=e.skillUploadPendingFile;t&&(e.skillUploadOverwriteKey=null,e.skillUploadPendingFile=null,(await ar(e,t,!0))?.skillKey&&Zn(e))},onCancelOverwrite:()=>{e.skillUploadOverwriteKey=null,e.skillUploadPendingFile=null},skillDeleteConfirmKey:e.skillDeleteConfirmKey,onRequestDelete:t=>{e.skillDeleteConfirmKey=t},onConfirmDelete:async t=>{e.skillDeleteConfirmKey=null,await or(e,t)&&await Zn(e)},onCancelDelete:()=>{e.skillDeleteConfirmKey=null},skillExportBusyKey:e.skillExportBusyKey,onExport:async t=>{if(e.client){e.skillExportBusyKey=t;try{await sr(e.client,t)}catch(t){e.skillsError=String(t)}finally{e.skillExportBusyKey=null}}},skillsTab:e.skillsTab,onTabChange:t=>{e.skillsTab=t,t===`team`&&cr(e)},skillMenuOpenKey:e.skillMenuOpenKey,onMenuOpen:t=>{e.skillMenuOpenKey=t},onMenuClose:()=>{e.skillMenuOpenKey=null},teamSkillsLoading:e.teamSkillsLoading,teamSkillsReport:e.teamSkillsReport,teamSkillsError:e.teamSkillsError,teamSkillsSyncBusyKey:e.teamSkillsSyncBusyKey,teamSkillsSyncedKeys:e.teamSkillsSyncedKeys,onSyncTeamSkill:async t=>{try{await lr(e,t)}catch(e){console.error(`syncTeamSkill failed`,e)}},onRefreshTeamSkills:()=>void cr(e),skillAiDialogOpen:e.skillAiDialogOpen,skillAiFormName:e.skillAiFormName,skillAiFormDesc:e.skillAiFormDesc,skillAiFormTrigger:e.skillAiFormTrigger,skillAiFormInstruction:e.skillAiFormInstruction,skillAiFormExample:e.skillAiFormExample,skillAiFormError:e.skillAiFormError,onOpenAiDialog:()=>{e.skillAiDialogOpen=!0,e.skillAiFormName=``,e.skillAiFormDesc=``,e.skillAiFormTrigger=``,e.skillAiFormInstruction=``,e.skillAiFormExample=``,e.skillAiFormError=null},onCloseAiDialog:()=>{e.skillAiDialogOpen=!1,e.skillAiFormError=null},onAiFormChange:(t,n)=>{t===`name`?(e.skillAiFormName=n,e.skillAiFormError=null):t===`desc`?e.skillAiFormDesc=n:t===`trigger`?e.skillAiFormTrigger=n:t===`instruction`?e.skillAiFormInstruction=n:t===`example`&&(e.skillAiFormExample=n)},onStartAiGenerate:async()=>{let t=e.skillAiFormName.trim(),n=e.skillAiFormDesc.trim();if(!t||!n||!e.skillAiFormTrigger.trim()||!e.skillAiFormInstruction.trim())return;if((e.skillsReport?.skills??[]).find(e=>e.skillKey===t||e.name?.toLowerCase()===t.toLowerCase())){e.skillAiFormError=`技能"${t}"已存在,请换一个名称。`;return}e.skillAiFormError=null;let r=t;if(e.skillAiDialogOpen=!1,e.skillAiBuilderMode=!0,e.skillAiBuilderSkillKey=r,e.skillAiBuilderBuilding=!1,e.skillAiBuilderActiveTab=`chat`,e.skillAiBuilderOpenTabs=[],e.skillAiChatMessages=[],e.skillAiChatStream=null,e.skillAiChatSending=!1,e.skillAiChatRunId=null,e.skillAiChatMessage=``,e.client){try{await af(e.client)}catch{}e.client.request(`chat.send`,{sessionKey:`agent:skill-creator:${r}`,message:`/clear`,deliver:!1,idempotencyKey:Qu()}).catch(()=>{})}await of(e,[`## 技能信息`,``,`- **技能名称**:${t}`,`- **技能描述**:${n}`,`- **何时触发**:${e.skillAiFormTrigger}`,`- **指令描述**:${e.skillAiFormInstruction}`,...e.skillAiFormExample.trim()?[`- **对话示例**:${e.skillAiFormExample}`]:[],``,`请按以上信息帮我生成一个完整的技能。`].join(`
477
- `),r)},skillAiBuilderMode:e.skillAiBuilderMode,skillAiBuilderSkillKey:e.skillAiBuilderSkillKey,skillAiBuilderBuilding:e.skillAiBuilderBuilding,skillAiBuilderActiveTab:e.skillAiBuilderActiveTab,skillAiBuilderOpenTabs:e.skillAiBuilderOpenTabs,skillAiChatMessages:e.skillAiChatMessages,skillAiChatStream:e.skillAiChatStream,skillAiChatSending:e.skillAiChatSending,skillAiChatMessage:e.skillAiChatMessage,skillAiToolCalls:e.skillAiToolCalls,skillAiBuilderExitConfirm:e.skillAiBuilderExitConfirm,onSkillAiTabChange:t=>{if(t.startsWith(`__close__:`)){let n=t.slice(10);e.skillAiBuilderOpenTabs=e.skillAiBuilderOpenTabs.filter(e=>e!==n),e.skillAiBuilderActiveTab===n&&(e.skillAiBuilderActiveTab=`chat`)}else e.skillAiBuilderActiveTab=t,t!==`chat`&&Zd(e,e.skillAiBuilderSkillKey??``,t)},onSkillAiChatMessageChange:t=>{e.skillAiChatMessage=t},onSkillAiChatSend:async()=>{let t=e.skillAiChatMessage.trim();!t||e.skillAiChatSending||e.skillAiBuilderBuilding||(e.skillAiChatMessage=``,await of(e,t,e.skillAiBuilderSkillKey??``))},onCloseAiBuilder:()=>{if(e.skillAiBuilderBuilding){e.skillAiBuilderExitConfirm=!0;return}let t=e.skillAiBuilderSkillKey;cf(e),t&&Zn(e)},onConfirmExitBuilder:async()=>{if(e.client&&e.skillAiBuilderSkillKey)try{await e.client.request(`chat.abort`,{sessionKey:`agent:skill-creator:${e.skillAiBuilderSkillKey}`,...e.skillAiChatRunId?{runId:e.skillAiChatRunId}:{}})}catch{}let t=e.skillAiBuilderSkillKey;cf(e),t&&Zn(e)},onCancelExitBuilder:()=>{e.skillAiBuilderExitConfirm=!1},onSkillAiFileTabOpen:t=>{let n=e.skillAiBuilderSkillKey??``;e.skillAiBuilderOpenTabs.includes(t)||(e.skillAiBuilderOpenTabs=[...e.skillAiBuilderOpenTabs,t]),e.skillFilesActiveKey=n,e.skillFilesActiveName=t,Zd(e,n,t),e.skillAiBuilderActiveTab=t}}}function uf(e){return/^(?:typeerror:\s*)?(?:fetch failed|failed to fetch)$/i.test(e.trim())}function df(e){let t=e.serverVersion?.trim();if(!t)return;let n=e.pageUrl??(typeof window>`u`?void 0:window.location.href);if(n)try{let r=new URL(n),i=new URL(e.gatewayUrl,r);return!new Set([`ws:`,`wss:`,`http:`,`https:`]).has(i.protocol)||i.host!==r.host?void 0:t}catch{return}}function ff(e,t){let n=(e??``).trim(),r=t.mainSessionKey?.trim();if(!r)return n;if(!n)return r;let i=t.mainKey?.trim()||`main`,a=t.defaultAgentId?.trim();return n===`main`||n===i||a&&(n===`agent:${a}:main`||n===`agent:${a}:${i}`)?r:n}function pf(e,t){if(!t?.mainSessionKey)return;let n=e.userPhone&&/^\d{7,15}$/.test(e.userPhone)?`agent:phone-${e.userPhone}:webchat`:null;if(n){e.sessionKey!==n&&(e.sessionKey=n);return}let r=ff(e.sessionKey,t),i=ff(e.settings.sessionKey,t),a=ff(e.settings.lastActiveSessionKey,t),o=r||i||e.sessionKey,s={...e.settings,sessionKey:i||o,lastActiveSessionKey:a||o},c=s.sessionKey!==e.settings.sessionKey||s.lastActiveSessionKey!==e.settings.lastActiveSessionKey;o!==e.sessionKey&&(e.sessionKey=o),c&&gl(e,s)}function mf(e){let t=e;t.pendingShutdownMessage=null,e.lastError=null,e.lastErrorCode=null,e.hello=null,e.connected=!1,e.execApprovalQueue=[],e.execApprovalError=null;let n=e.client,r=df({gatewayUrl:e.settings.gatewayUrl,serverVersion:e.serverVersion}),i=new id({url:e.settings.gatewayUrl,token:e.settings.token.trim()?e.settings.token:void 0,password:e.password.trim()?e.password:void 0,clientName:`openclaw-control-ui`,clientVersion:r,mode:`webchat`,instanceId:e.clientInstanceId,phone:e.userPhone??void 0,onHello:n=>{e.client===i&&(t.pendingShutdownMessage=null,e.connected=!0,e.lastError=null,e.lastErrorCode=null,e.hello=n,bf(e,n),e.chatRunId=null,e.chatStream=null,e.chatStreamStartedAt=null,Jl(e),e.userPhone&&i.request(`user.provision`,{}).catch(()=>{}),zd(e),xe(e),Jd(e),se(e,{quiet:!0}),Un(e,{quiet:!0}),yl(e),af(i))},onClose:({code:n,reason:r,error:a})=>{if(e.client===i)if(e.connected=!1,e.lastErrorCode=ed(a)??(typeof a?.code==`string`?a.code:null),n!==1012){if(a?.message){e.lastError=e.lastErrorCode&&uf(a.message)?sd({message:a.message,details:a.details,code:a.code}):a.message;return}e.lastError=t.pendingShutdownMessage??`disconnected (${n}): ${r||`no reason`}`}else e.lastError=t.pendingShutdownMessage??null,e.lastErrorCode=null},onEvent:t=>{e.client===i&&hf(e,t)},onGap:({expected:t,received:n})=>{e.client===i&&(e.lastError=`event gap detected (expected seq ${t}, got ${n}); refresh recommended`,e.lastErrorCode=null)}});e.client=i,n?.stop(),i.start()}function hf(e,t){try{yf(e,t)}catch(e){console.error(`[gateway] handleGatewayEvent error:`,t.event,e)}}function gf(e,t,n){if(n!==`final`&&n!==`error`&&n!==`aborted`)return!1;let r=e,i=r.toolStreamOrder.length>0;Jl(r),Ad(e);let a=t?.runId;return a&&e.refreshSessionsAfterChat.has(a)&&(e.refreshSessionsAfterChat.delete(a),n===`final`&&Jn(e,{activeMinutes:120})),i&&n===`final`?(fd(e),!0):!1}function _f(e,t){if(!(!e.skillAiChatRunId&&t.state!==`delta`))if(t.state===`delta`){let n=Ga(t.message);typeof n==`string`&&(e.skillAiChatStream=n)}else if(t.state===`final`){if(t.runId&&t.runId!==e.skillAiChatRunId)return;let n=t.message;if(n&&typeof n==`object`){let t=n;typeof t.role==`string`&&t.role.toLowerCase()===`assistant`&&(e.skillAiChatMessages=[...e.skillAiChatMessages,t])}else e.skillAiChatStream?.trim()&&(e.skillAiChatMessages=[...e.skillAiChatMessages,{role:`assistant`,content:[{type:`text`,text:e.skillAiChatStream}],timestamp:Date.now()}]);e.skillAiChatStream=null,e.skillAiChatRunId=null,e.skillAiChatStreamStartedAt=null,e.skillAiChatSending=!1,e.skillAiBuilderBuilding=!1,e.skillAiToolCalls=[];let r=e.skillAiBuilderSkillKey,i=new Set(e.skillsReport?.skills.filter(e=>e.source===`openclaw-managed`&&!e.bundled).map(e=>e.skillKey)??[]);(async()=>{await Zn(e);let t=e.skillAiBuilderSkillKey??r;if(r&&!e.skillsReport?.skills.some(e=>e.skillKey===r)){let n=(e.skillsReport?.skills??[]).filter(e=>e.source===`openclaw-managed`&&!e.bundled&&!i.has(e.skillKey)).map(e=>e.skillKey);n.length===1&&(e.skillAiBuilderSkillKey=n[0],e.skillFilesActiveKey===r&&(e.skillFilesActiveKey=n[0]),t=n[0])}t&&await Xd(e,t,{force:!0})})()}else (t.state===`aborted`||t.state===`error`)&&(e.skillAiChatStream=null,e.skillAiChatRunId=null,e.skillAiChatStreamStartedAt=null,e.skillAiChatSending=!1,e.skillAiBuilderBuilding=!1,e.skillAiToolCalls=[])}function vf(e,t){t?.sessionKey&&_l(e,t.sessionKey);let n=e;if(n.skillAiBuilderMode&&n.skillAiBuilderSkillKey&&t){let e=t.sessionKey===`agent:skill-creator:${n.skillAiBuilderSkillKey}`,r=!!n.skillAiChatRunId&&t.runId===n.skillAiChatRunId;if(e||r){_f(n,t);return}}let r=yd(e,t),i=gf(e,t,r);r===`final`&&!i&&Pd(t)&&fd(e)}function yf(e,t){if(e.eventLogBuffer=[{ts:Date.now(),event:t.event,payload:t.payload},...e.eventLogBuffer].slice(0,250),(e.tab===`debug`||e.tab===`overview`)&&(e.eventLog=e.eventLogBuffer),t.event===`agent`){if(e.onboarding)return;let n=t.payload;if(n?.stream===`tool`){let t=e,r=n.sessionKey,i=!!r&&t.skillAiBuilderSkillKey!=null&&r===`agent:skill-creator:${t.skillAiBuilderSkillKey}`,a=!!t.skillAiChatRunId&&n.runId===t.skillAiChatRunId;if(t.skillAiBuilderMode&&(i||a)){let e=n.data??{},r=typeof e.toolCallId==`string`?e.toolCallId:``,i=typeof e.name==`string`?e.name:`tool`,a=typeof e.phase==`string`?e.phase:``;if(r){let e=t.skillAiToolCalls??[];e.find(e=>e.toolCallId===r)?a===`result`&&(t.skillAiToolCalls=e.map(e=>e.toolCallId===r?{...e,phase:`done`}:e)):t.skillAiToolCalls=[...e,{toolCallId:r,name:i,phase:`pending`}]}return}}eu(e,n);return}if(t.event===`chat`){vf(e,t.payload);return}if(t.event===`presence`){let n=t.payload;n?.presence&&Array.isArray(n.presence)&&(e.presenceEntries=n.presence,e.presenceError=null,e.presenceStatus=null);return}if(t.event===`shutdown`){let n=t.payload,r=n&&typeof n.reason==`string`&&n.reason.trim()?n.reason.trim():`gateway stopping`,i=typeof n?.restartExpectedMs==`number`?`Restarting: ${r}`:`Disconnected: ${r}`;e.pendingShutdownMessage=i,e.lastError=i,e.lastErrorCode=null;return}if(t.event===`cron`&&e.tab===`cron`&&Nl(e),(t.event===`device.pair.requested`||t.event===`device.pair.resolved`)&&Un(e,{quiet:!0}),t.event===`exec.approval.requested`){let n=Vd(t.payload);if(n){e.execApprovalQueue=Wd(e.execApprovalQueue,n),e.execApprovalError=null;let t=Math.max(0,n.expiresAtMs-Date.now()+500);window.setTimeout(()=>{e.execApprovalQueue=Gd(e.execApprovalQueue,n.id)},t)}return}if(t.event===`exec.approval.resolved`){let n=Hd(t.payload);n&&(e.execApprovalQueue=Gd(e.execApprovalQueue,n.id));return}t.event===`update.available`&&(e.updateAvailable=t.payload?.updateAvailable??null)}function bf(e,t){let n=t.snapshot;n?.presence&&Array.isArray(n.presence)&&(e.presenceEntries=n.presence),n?.health&&(e.debugHealth=n.health,e.healthResult=n.health),n?.sessionDefaults&&pf(e,n.sessionDefaults),e.updateAvailable=n?.updateAvailable??null}var xf=`/__openclaw/control-ui-config.json`;async function Sf(e){if(typeof window>`u`||typeof fetch!=`function`)return;let t=Pr(e.basePath??``),n=t?`${t}${xf}`:xf;try{let t=await fetch(n,{method:`GET`,headers:{Accept:`application/json`},credentials:`same-origin`});if(!t.ok)return;let r=await t.json(),i=Rd({agentId:r.assistantAgentId??null,name:r.assistantName,avatar:r.assistantAvatar??null});e.assistantName=i.name,e.assistantAvatar=i.avatar,e.assistantAgentId=i.agentId??null,e.serverVersion=r.serverVersion??null}catch{}}var Cf=[],wf=[];(()=>{let e=`lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,3b,f,,w,1j,,,,4,8,4,,3,7,a,2,t,,1m,,,,2,4,8,,9,,a,2,q,,2,2,1l,,4,2,4,2,2,3,3,,u,2,3,,b,2,1l,,4,5,,2,4,,k,2,m,6,,,1m,,,2,,4,8,,7,3,a,2,u,,1n,,,,c,,9,,14,,3,,1l,3,5,3,,4,7,2,b,2,t,,1m,,2,,2,,3,,5,2,7,2,b,2,s,2,1l,2,,,2,4,8,,9,,a,2,t,,20,,4,,2,3,,,8,,29,,2,7,c,8,2q,,2,9,b,6,22,2,r,,,,,,1j,e,,5,,2,5,b,,10,9,,2u,4,,6,,2,2,2,p,2,4,3,g,4,d,,2,2,6,,f,,jj,3,qa,3,t,3,t,2,u,2,1s,2,,7,8,,2,b,9,,19,3,3b,2,y,,3a,3,4,2,9,,6,3,63,2,2,,1m,,,7,,,,,2,8,6,a,2,,1c,h,1r,4,1c,7,,,5,,14,9,c,2,w,4,2,2,,3,1k,,,2,3,,,3,1m,8,2,2,48,3,,d,,7,4,,6,,3,2,5i,1m,,5,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,p,2,5,,47,2,q,i,d,,12,8,p,b,1a,3,1c,,2,4,2,2,13,,1v,6,2,2,2,2,c,,8,,1b,,1f,,,3,2,2,5,2,,,16,2,8,,6m,,2,,4,,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,ar,2,49,b,4w,,1i,f,1k,3,1d,4,2,2,1x,3,10,5,,8,1q,,c,2,1g,9,a,4,2,,2n,3,2,,,2,6,,4g,,3,8,l,2,1l,2,,,,,m,,e,7,3,5,5f,8,2,3,,,n,,29,,2,6,,,2,,,2,,2,6j,,2,4,6,2,,2,r,2,2d,8,2,,,2,2y,,,,2,6,,,2t,3,2,4,,5,77,9,,2,6t,,a,2,,,4,,40,4,2,2,4,,w,a,14,6,2,4,8,,9,6,2,3,1a,d,,2,ba,7,,6,,,2a,m,2,7,,2,,2,3e,6,3,,,2,,7,,,20,2,3,,,,9n,2,f0b,5,1n,7,t4,,1r,4,29,,f5k,2,43q,,,3,4,5,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,79,7,c5,4,15s,7,31,7,240,5,gx7k,2o,3k,6o`.split(`,`).map(e=>e?parseInt(e,36):1);for(let t=0,n=0;t<e.length;t++)(t%2?wf:Cf).push(n+=e[t])})();function Tf(e){if(e<768)return!1;for(let t=0,n=Cf.length;;){let r=t+n>>1;if(e<Cf[r])n=r;else if(e>=wf[r])t=r+1;else return!0;if(t==n)return!1}}function Ef(e){return e>=127462&&e<=127487}var Df=8205;function Of(e,t,n=!0,r=!0){return(n?kf:Af)(e,t,r)}function kf(e,t,n){if(t==e.length)return t;t&&Mf(e.charCodeAt(t))&&Nf(e.charCodeAt(t-1))&&t--;let r=jf(e,t);for(t+=Pf(r);t<e.length;){let i=jf(e,t);if(r==Df||i==Df||n&&Tf(i))t+=Pf(i),r=i;else if(Ef(i)){let n=0,r=t-2;for(;r>=0&&Ef(jf(e,r));)n++,r-=2;if(n%2==0)break;t+=2}else break}return t}function Af(e,t,n){for(;t>0;){let r=kf(e,t-2,n);if(r<t)return r;t--}return 0}function jf(e,t){let n=e.charCodeAt(t);if(!Nf(n)||t+1==e.length)return n;let r=e.charCodeAt(t+1);return Mf(r)?(n-55296<<10)+(r-56320)+65536:n}function Mf(e){return e>=56320&&e<57344}function Nf(e){return e>=55296&&e<56320}function Pf(e){return e<65536?1:2}var k=class e{lineAt(e){if(e<0||e>this.length)throw RangeError(`Invalid position ${e} in document of length ${this.length}`);return this.lineInner(e,!1,1,0)}line(e){if(e<1||e>this.lines)throw RangeError(`Invalid line number ${e} in ${this.lines}-line document`);return this.lineInner(e,!0,1,0)}replace(e,t,n){[e,t]=Wf(this,e,t);let r=[];return this.decompose(0,e,r,2),n.length&&n.decompose(0,n.length,r,3),this.decompose(t,this.length,r,1),If.from(r,this.length-(t-e)+n.length)}append(e){return this.replace(this.length,this.length,e)}slice(e,t=this.length){[e,t]=Wf(this,e,t);let n=[];return this.decompose(e,t,n,0),If.from(n,t-e)}eq(e){if(e==this)return!0;if(e.length!=this.length||e.lines!=this.lines)return!1;let t=this.scanIdentical(e,1),n=this.length-this.scanIdentical(e,-1),r=new Bf(this),i=new Bf(e);for(let e=t,a=t;;){if(r.next(e),i.next(e),e=0,r.lineBreak!=i.lineBreak||r.done!=i.done||r.value!=i.value)return!1;if(a+=r.value.length,r.done||a>=n)return!0}}iter(e=1){return new Bf(this,e)}iterRange(e,t=this.length){return new Vf(this,e,t)}iterLines(e,t){let n;if(e==null)n=this.iter();else{t??=this.lines+1;let r=this.line(e).from;n=this.iterRange(r,Math.max(r,t==this.lines+1?this.length:t<=1?0:this.line(t-1).to))}return new Hf(n)}toString(){return this.sliceString(0)}toJSON(){let e=[];return this.flatten(e),e}constructor(){}static of(t){if(t.length==0)throw RangeError(`A document must have at least one line`);return t.length==1&&!t[0]?e.empty:t.length<=32?new Ff(t):If.from(Ff.split(t,[]))}},Ff=class e extends k{constructor(e,t=Lf(e)){super(),this.text=e,this.length=t}get lines(){return this.text.length}get children(){return null}lineInner(e,t,n,r){for(let i=0;;i++){let a=this.text[i],o=r+a.length;if((t?n:o)>=e)return new Uf(r,o,n,a);r=o+1,n++}}decompose(t,n,r,i){let a=t<=0&&n>=this.length?this:new e(zf(this.text,t,n),Math.min(n,this.length)-Math.max(0,t));if(i&1){let t=r.pop(),n=Rf(a.text,t.text.slice(),0,a.length);if(n.length<=32)r.push(new e(n,t.length+a.length));else{let t=n.length>>1;r.push(new e(n.slice(0,t)),new e(n.slice(t)))}}else r.push(a)}replace(t,n,r){if(!(r instanceof e))return super.replace(t,n,r);[t,n]=Wf(this,t,n);let i=Rf(this.text,Rf(r.text,zf(this.text,0,t)),n),a=this.length+r.length-(n-t);return i.length<=32?new e(i,a):If.from(e.split(i,[]),a)}sliceString(e,t=this.length,n=`
477
+ `),r)},skillAiBuilderMode:e.skillAiBuilderMode,skillAiBuilderSkillKey:e.skillAiBuilderSkillKey,skillAiBuilderBuilding:e.skillAiBuilderBuilding,skillAiBuilderActiveTab:e.skillAiBuilderActiveTab,skillAiBuilderOpenTabs:e.skillAiBuilderOpenTabs,skillAiChatMessages:e.skillAiChatMessages,skillAiChatStream:e.skillAiChatStream,skillAiChatSending:e.skillAiChatSending,skillAiChatMessage:e.skillAiChatMessage,skillAiToolCalls:e.skillAiToolCalls,skillAiBuilderExitConfirm:e.skillAiBuilderExitConfirm,onSkillAiTabChange:t=>{if(t.startsWith(`__close__:`)){let n=t.slice(10);e.skillAiBuilderOpenTabs=e.skillAiBuilderOpenTabs.filter(e=>e!==n),e.skillAiBuilderActiveTab===n&&(e.skillAiBuilderActiveTab=`chat`)}else e.skillAiBuilderActiveTab=t,t!==`chat`&&Zd(e,e.skillAiBuilderSkillKey??``,t)},onSkillAiChatMessageChange:t=>{e.skillAiChatMessage=t},onSkillAiChatSend:async()=>{let t=e.skillAiChatMessage.trim();!t||e.skillAiChatSending||e.skillAiBuilderBuilding||(e.skillAiChatMessage=``,await of(e,t,e.skillAiBuilderSkillKey??``))},onCloseAiBuilder:()=>{if(e.skillAiBuilderBuilding){e.skillAiBuilderExitConfirm=!0;return}let t=e.skillAiBuilderSkillKey;cf(e),t&&Zn(e)},onConfirmExitBuilder:async()=>{if(e.client&&e.skillAiBuilderSkillKey)try{await e.client.request(`chat.abort`,{sessionKey:`agent:skill-creator:${e.skillAiBuilderSkillKey}`,...e.skillAiChatRunId?{runId:e.skillAiChatRunId}:{}})}catch{}let t=e.skillAiBuilderSkillKey;cf(e),t&&Zn(e)},onCancelExitBuilder:()=>{e.skillAiBuilderExitConfirm=!1},onSkillAiFileTabOpen:t=>{let n=e.skillAiBuilderSkillKey??``;e.skillAiBuilderOpenTabs.includes(t)||(e.skillAiBuilderOpenTabs=[...e.skillAiBuilderOpenTabs,t]),e.skillFilesActiveKey=n,e.skillFilesActiveName=t,Zd(e,n,t),e.skillAiBuilderActiveTab=t}}}function uf(e){return/^(?:typeerror:\s*)?(?:fetch failed|failed to fetch)$/i.test(e.trim())}function df(e){let t=e.serverVersion?.trim();if(!t)return;let n=e.pageUrl??(typeof window>`u`?void 0:window.location.href);if(n)try{let r=new URL(n),i=new URL(e.gatewayUrl,r);return!new Set([`ws:`,`wss:`,`http:`,`https:`]).has(i.protocol)||i.host!==r.host?void 0:t}catch{return}}function ff(e,t){let n=(e??``).trim(),r=t.mainSessionKey?.trim();if(!r)return n;if(!n)return r;let i=t.mainKey?.trim()||`main`,a=t.defaultAgentId?.trim();return n===`main`||n===i||a&&(n===`agent:${a}:main`||n===`agent:${a}:${i}`)?r:n}function pf(e,t){if(!t?.mainSessionKey)return;let n=e.userPhone&&/^\d{7,15}$/.test(e.userPhone)?`agent:phone-${e.userPhone}:webchat`:null;if(n){e.sessionKey!==n&&(e.sessionKey=n);return}let r=ff(e.sessionKey,t),i=ff(e.settings.sessionKey,t),a=ff(e.settings.lastActiveSessionKey,t),o=r||i||e.sessionKey,s={...e.settings,sessionKey:i||o,lastActiveSessionKey:a||o},c=s.sessionKey!==e.settings.sessionKey||s.lastActiveSessionKey!==e.settings.lastActiveSessionKey;o!==e.sessionKey&&(e.sessionKey=o),c&&gl(e,s)}function mf(e){let t=e;t.pendingShutdownMessage=null,e.lastError=null,e.lastErrorCode=null,e.hello=null,e.connected=!1,e.execApprovalQueue=[],e.execApprovalError=null;let n=e.client,r=df({gatewayUrl:e.settings.gatewayUrl,serverVersion:e.serverVersion}),i=new id({url:e.settings.gatewayUrl,token:e.settings.token.trim()?e.settings.token:void 0,password:e.password.trim()?e.password:void 0,clientName:`openclaw-control-ui`,clientVersion:r,mode:`webchat`,instanceId:e.clientInstanceId,phone:e.userPhone??void 0,onHello:n=>{e.client===i&&(t.pendingShutdownMessage=null,e.connected=!0,e.lastError=null,e.lastErrorCode=null,e.hello=n,bf(e,n),e.chatRunId=null,e.chatStream=null,e.chatStreamStartedAt=null,Jl(e),zd(e),xe(e),Jd(e),se(e,{quiet:!0}),Un(e,{quiet:!0}),yl(e),(async()=>{e.userPhone&&await i.request(`user.provision`,{}).catch(()=>{}),await af(i)})())},onClose:({code:n,reason:r,error:a})=>{if(e.client===i)if(e.connected=!1,e.lastErrorCode=ed(a)??(typeof a?.code==`string`?a.code:null),n!==1012){if(a?.message){e.lastError=e.lastErrorCode&&uf(a.message)?sd({message:a.message,details:a.details,code:a.code}):a.message;return}e.lastError=t.pendingShutdownMessage??`disconnected (${n}): ${r||`no reason`}`}else e.lastError=t.pendingShutdownMessage??null,e.lastErrorCode=null},onEvent:t=>{e.client===i&&hf(e,t)},onGap:({expected:t,received:n})=>{e.client===i&&(e.lastError=`event gap detected (expected seq ${t}, got ${n}); refresh recommended`,e.lastErrorCode=null)}});e.client=i,n?.stop(),i.start()}function hf(e,t){try{yf(e,t)}catch(e){console.error(`[gateway] handleGatewayEvent error:`,t.event,e)}}function gf(e,t,n){if(n!==`final`&&n!==`error`&&n!==`aborted`)return!1;let r=e,i=r.toolStreamOrder.length>0;Jl(r),Ad(e);let a=t?.runId;return a&&e.refreshSessionsAfterChat.has(a)&&(e.refreshSessionsAfterChat.delete(a),n===`final`&&Jn(e,{activeMinutes:120})),i&&n===`final`?(fd(e),!0):!1}function _f(e,t){if(!(!e.skillAiChatRunId&&t.state!==`delta`))if(t.state===`delta`){let n=Ga(t.message);typeof n==`string`&&(e.skillAiChatStream=n)}else if(t.state===`final`){if(t.runId&&t.runId!==e.skillAiChatRunId)return;let n=t.message;if(n&&typeof n==`object`){let t=n;typeof t.role==`string`&&t.role.toLowerCase()===`assistant`&&(e.skillAiChatMessages=[...e.skillAiChatMessages,t])}else e.skillAiChatStream?.trim()&&(e.skillAiChatMessages=[...e.skillAiChatMessages,{role:`assistant`,content:[{type:`text`,text:e.skillAiChatStream}],timestamp:Date.now()}]);e.skillAiChatStream=null,e.skillAiChatRunId=null,e.skillAiChatStreamStartedAt=null,e.skillAiChatSending=!1,e.skillAiBuilderBuilding=!1,e.skillAiToolCalls=[];let r=e.skillAiBuilderSkillKey,i=new Set(e.skillsReport?.skills.filter(e=>e.source===`openclaw-managed`&&!e.bundled).map(e=>e.skillKey)??[]);(async()=>{await Zn(e);let t=e.skillAiBuilderSkillKey??r;if(r&&!e.skillsReport?.skills.some(e=>e.skillKey===r)){let n=(e.skillsReport?.skills??[]).filter(e=>e.source===`openclaw-managed`&&!e.bundled&&!i.has(e.skillKey)).map(e=>e.skillKey);n.length===1&&(e.skillAiBuilderSkillKey=n[0],e.skillFilesActiveKey===r&&(e.skillFilesActiveKey=n[0]),t=n[0])}t&&await Xd(e,t,{force:!0})})()}else (t.state===`aborted`||t.state===`error`)&&(e.skillAiChatStream=null,e.skillAiChatRunId=null,e.skillAiChatStreamStartedAt=null,e.skillAiChatSending=!1,e.skillAiBuilderBuilding=!1,e.skillAiToolCalls=[])}function vf(e,t){t?.sessionKey&&_l(e,t.sessionKey);let n=e;if(n.skillAiBuilderMode&&n.skillAiBuilderSkillKey&&t){let e=t.sessionKey===`agent:skill-creator:${n.skillAiBuilderSkillKey}`,r=!!n.skillAiChatRunId&&t.runId===n.skillAiChatRunId;if(e||r){_f(n,t);return}}let r=yd(e,t),i=gf(e,t,r);r===`final`&&!i&&Pd(t)&&fd(e)}function yf(e,t){if(e.eventLogBuffer=[{ts:Date.now(),event:t.event,payload:t.payload},...e.eventLogBuffer].slice(0,250),(e.tab===`debug`||e.tab===`overview`)&&(e.eventLog=e.eventLogBuffer),t.event===`agent`){if(e.onboarding)return;let n=t.payload;if(n?.stream===`tool`){let t=e,r=n.sessionKey,i=!!r&&t.skillAiBuilderSkillKey!=null&&r===`agent:skill-creator:${t.skillAiBuilderSkillKey}`,a=!!t.skillAiChatRunId&&n.runId===t.skillAiChatRunId;if(t.skillAiBuilderMode&&(i||a)){let e=n.data??{},r=typeof e.toolCallId==`string`?e.toolCallId:``,i=typeof e.name==`string`?e.name:`tool`,a=typeof e.phase==`string`?e.phase:``;if(r){let e=t.skillAiToolCalls??[];e.find(e=>e.toolCallId===r)?a===`result`&&(t.skillAiToolCalls=e.map(e=>e.toolCallId===r?{...e,phase:`done`}:e)):t.skillAiToolCalls=[...e,{toolCallId:r,name:i,phase:`pending`}]}return}}eu(e,n);return}if(t.event===`chat`){vf(e,t.payload);return}if(t.event===`presence`){let n=t.payload;n?.presence&&Array.isArray(n.presence)&&(e.presenceEntries=n.presence,e.presenceError=null,e.presenceStatus=null);return}if(t.event===`shutdown`){let n=t.payload,r=n&&typeof n.reason==`string`&&n.reason.trim()?n.reason.trim():`gateway stopping`,i=typeof n?.restartExpectedMs==`number`?`Restarting: ${r}`:`Disconnected: ${r}`;e.pendingShutdownMessage=i,e.lastError=i,e.lastErrorCode=null;return}if(t.event===`cron`&&e.tab===`cron`&&Nl(e),(t.event===`device.pair.requested`||t.event===`device.pair.resolved`)&&Un(e,{quiet:!0}),t.event===`exec.approval.requested`){let n=Vd(t.payload);if(n){e.execApprovalQueue=Wd(e.execApprovalQueue,n),e.execApprovalError=null;let t=Math.max(0,n.expiresAtMs-Date.now()+500);window.setTimeout(()=>{e.execApprovalQueue=Gd(e.execApprovalQueue,n.id)},t)}return}if(t.event===`exec.approval.resolved`){let n=Hd(t.payload);n&&(e.execApprovalQueue=Gd(e.execApprovalQueue,n.id));return}t.event===`update.available`&&(e.updateAvailable=t.payload?.updateAvailable??null)}function bf(e,t){let n=t.snapshot;n?.presence&&Array.isArray(n.presence)&&(e.presenceEntries=n.presence),n?.health&&(e.debugHealth=n.health,e.healthResult=n.health),n?.sessionDefaults&&pf(e,n.sessionDefaults),e.updateAvailable=n?.updateAvailable??null}var xf=`/__openclaw/control-ui-config.json`;async function Sf(e){if(typeof window>`u`||typeof fetch!=`function`)return;let t=Pr(e.basePath??``),n=t?`${t}${xf}`:xf;try{let t=await fetch(n,{method:`GET`,headers:{Accept:`application/json`},credentials:`same-origin`});if(!t.ok)return;let r=await t.json(),i=Rd({agentId:r.assistantAgentId??null,name:r.assistantName,avatar:r.assistantAvatar??null});e.assistantName=i.name,e.assistantAvatar=i.avatar,e.assistantAgentId=i.agentId??null,e.serverVersion=r.serverVersion??null}catch{}}var Cf=[],wf=[];(()=>{let e=`lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,3b,f,,w,1j,,,,4,8,4,,3,7,a,2,t,,1m,,,,2,4,8,,9,,a,2,q,,2,2,1l,,4,2,4,2,2,3,3,,u,2,3,,b,2,1l,,4,5,,2,4,,k,2,m,6,,,1m,,,2,,4,8,,7,3,a,2,u,,1n,,,,c,,9,,14,,3,,1l,3,5,3,,4,7,2,b,2,t,,1m,,2,,2,,3,,5,2,7,2,b,2,s,2,1l,2,,,2,4,8,,9,,a,2,t,,20,,4,,2,3,,,8,,29,,2,7,c,8,2q,,2,9,b,6,22,2,r,,,,,,1j,e,,5,,2,5,b,,10,9,,2u,4,,6,,2,2,2,p,2,4,3,g,4,d,,2,2,6,,f,,jj,3,qa,3,t,3,t,2,u,2,1s,2,,7,8,,2,b,9,,19,3,3b,2,y,,3a,3,4,2,9,,6,3,63,2,2,,1m,,,7,,,,,2,8,6,a,2,,1c,h,1r,4,1c,7,,,5,,14,9,c,2,w,4,2,2,,3,1k,,,2,3,,,3,1m,8,2,2,48,3,,d,,7,4,,6,,3,2,5i,1m,,5,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,p,2,5,,47,2,q,i,d,,12,8,p,b,1a,3,1c,,2,4,2,2,13,,1v,6,2,2,2,2,c,,8,,1b,,1f,,,3,2,2,5,2,,,16,2,8,,6m,,2,,4,,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,ar,2,49,b,4w,,1i,f,1k,3,1d,4,2,2,1x,3,10,5,,8,1q,,c,2,1g,9,a,4,2,,2n,3,2,,,2,6,,4g,,3,8,l,2,1l,2,,,,,m,,e,7,3,5,5f,8,2,3,,,n,,29,,2,6,,,2,,,2,,2,6j,,2,4,6,2,,2,r,2,2d,8,2,,,2,2y,,,,2,6,,,2t,3,2,4,,5,77,9,,2,6t,,a,2,,,4,,40,4,2,2,4,,w,a,14,6,2,4,8,,9,6,2,3,1a,d,,2,ba,7,,6,,,2a,m,2,7,,2,,2,3e,6,3,,,2,,7,,,20,2,3,,,,9n,2,f0b,5,1n,7,t4,,1r,4,29,,f5k,2,43q,,,3,4,5,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,79,7,c5,4,15s,7,31,7,240,5,gx7k,2o,3k,6o`.split(`,`).map(e=>e?parseInt(e,36):1);for(let t=0,n=0;t<e.length;t++)(t%2?wf:Cf).push(n+=e[t])})();function Tf(e){if(e<768)return!1;for(let t=0,n=Cf.length;;){let r=t+n>>1;if(e<Cf[r])n=r;else if(e>=wf[r])t=r+1;else return!0;if(t==n)return!1}}function Ef(e){return e>=127462&&e<=127487}var Df=8205;function Of(e,t,n=!0,r=!0){return(n?kf:Af)(e,t,r)}function kf(e,t,n){if(t==e.length)return t;t&&Mf(e.charCodeAt(t))&&Nf(e.charCodeAt(t-1))&&t--;let r=jf(e,t);for(t+=Pf(r);t<e.length;){let i=jf(e,t);if(r==Df||i==Df||n&&Tf(i))t+=Pf(i),r=i;else if(Ef(i)){let n=0,r=t-2;for(;r>=0&&Ef(jf(e,r));)n++,r-=2;if(n%2==0)break;t+=2}else break}return t}function Af(e,t,n){for(;t>0;){let r=kf(e,t-2,n);if(r<t)return r;t--}return 0}function jf(e,t){let n=e.charCodeAt(t);if(!Nf(n)||t+1==e.length)return n;let r=e.charCodeAt(t+1);return Mf(r)?(n-55296<<10)+(r-56320)+65536:n}function Mf(e){return e>=56320&&e<57344}function Nf(e){return e>=55296&&e<56320}function Pf(e){return e<65536?1:2}var k=class e{lineAt(e){if(e<0||e>this.length)throw RangeError(`Invalid position ${e} in document of length ${this.length}`);return this.lineInner(e,!1,1,0)}line(e){if(e<1||e>this.lines)throw RangeError(`Invalid line number ${e} in ${this.lines}-line document`);return this.lineInner(e,!0,1,0)}replace(e,t,n){[e,t]=Wf(this,e,t);let r=[];return this.decompose(0,e,r,2),n.length&&n.decompose(0,n.length,r,3),this.decompose(t,this.length,r,1),If.from(r,this.length-(t-e)+n.length)}append(e){return this.replace(this.length,this.length,e)}slice(e,t=this.length){[e,t]=Wf(this,e,t);let n=[];return this.decompose(e,t,n,0),If.from(n,t-e)}eq(e){if(e==this)return!0;if(e.length!=this.length||e.lines!=this.lines)return!1;let t=this.scanIdentical(e,1),n=this.length-this.scanIdentical(e,-1),r=new Bf(this),i=new Bf(e);for(let e=t,a=t;;){if(r.next(e),i.next(e),e=0,r.lineBreak!=i.lineBreak||r.done!=i.done||r.value!=i.value)return!1;if(a+=r.value.length,r.done||a>=n)return!0}}iter(e=1){return new Bf(this,e)}iterRange(e,t=this.length){return new Vf(this,e,t)}iterLines(e,t){let n;if(e==null)n=this.iter();else{t??=this.lines+1;let r=this.line(e).from;n=this.iterRange(r,Math.max(r,t==this.lines+1?this.length:t<=1?0:this.line(t-1).to))}return new Hf(n)}toString(){return this.sliceString(0)}toJSON(){let e=[];return this.flatten(e),e}constructor(){}static of(t){if(t.length==0)throw RangeError(`A document must have at least one line`);return t.length==1&&!t[0]?e.empty:t.length<=32?new Ff(t):If.from(Ff.split(t,[]))}},Ff=class e extends k{constructor(e,t=Lf(e)){super(),this.text=e,this.length=t}get lines(){return this.text.length}get children(){return null}lineInner(e,t,n,r){for(let i=0;;i++){let a=this.text[i],o=r+a.length;if((t?n:o)>=e)return new Uf(r,o,n,a);r=o+1,n++}}decompose(t,n,r,i){let a=t<=0&&n>=this.length?this:new e(zf(this.text,t,n),Math.min(n,this.length)-Math.max(0,t));if(i&1){let t=r.pop(),n=Rf(a.text,t.text.slice(),0,a.length);if(n.length<=32)r.push(new e(n,t.length+a.length));else{let t=n.length>>1;r.push(new e(n.slice(0,t)),new e(n.slice(t)))}}else r.push(a)}replace(t,n,r){if(!(r instanceof e))return super.replace(t,n,r);[t,n]=Wf(this,t,n);let i=Rf(this.text,Rf(r.text,zf(this.text,0,t)),n),a=this.length+r.length-(n-t);return i.length<=32?new e(i,a):If.from(e.split(i,[]),a)}sliceString(e,t=this.length,n=`
478
478
  `){[e,t]=Wf(this,e,t);let r=``;for(let i=0,a=0;i<=t&&a<this.text.length;a++){let o=this.text[a],s=i+o.length;i>e&&a&&(r+=n),e<s&&t>i&&(r+=o.slice(Math.max(0,e-i),t-i)),i=s+1}return r}flatten(e){for(let t of this.text)e.push(t)}scanIdentical(){return 0}static split(t,n){let r=[],i=-1;for(let a of t)r.push(a),i+=a.length+1,r.length==32&&(n.push(new e(r,i)),r=[],i=-1);return i>-1&&n.push(new e(r,i)),n}},If=class e extends k{constructor(e,t){super(),this.children=e,this.length=t,this.lines=0;for(let t of e)this.lines+=t.lines}lineInner(e,t,n,r){for(let i=0;;i++){let a=this.children[i],o=r+a.length,s=n+a.lines-1;if((t?s:o)>=e)return a.lineInner(e,t,n,r);r=o+1,n=s+1}}decompose(e,t,n,r){for(let i=0,a=0;a<=t&&i<this.children.length;i++){let o=this.children[i],s=a+o.length;if(e<=s&&t>=a){let i=r&((a<=e?1:0)|(s>=t?2:0));a>=e&&s<=t&&!i?n.push(o):o.decompose(e-a,t-a,n,i)}a=s+1}}replace(t,n,r){if([t,n]=Wf(this,t,n),r.lines<this.lines)for(let i=0,a=0;i<this.children.length;i++){let o=this.children[i],s=a+o.length;if(t>=a&&n<=s){let c=o.replace(t-a,n-a,r),l=this.lines-o.lines+c.lines;if(c.lines<l>>4&&c.lines>l>>6){let a=this.children.slice();return a[i]=c,new e(a,this.length-(n-t)+r.length)}return super.replace(a,s,c)}a=s+1}return super.replace(t,n,r)}sliceString(e,t=this.length,n=`
479
479
  `){[e,t]=Wf(this,e,t);let r=``;for(let i=0,a=0;i<this.children.length&&a<=t;i++){let o=this.children[i],s=a+o.length;a>e&&i&&(r+=n),e<s&&t>a&&(r+=o.sliceString(e-a,t-a,n)),a=s+1}return r}flatten(e){for(let t of this.children)t.flatten(e)}scanIdentical(t,n){if(!(t instanceof e))return 0;let r=0,[i,a,o,s]=n>0?[0,0,this.children.length,t.children.length]:[this.children.length-1,t.children.length-1,-1,-1];for(;;i+=n,a+=n){if(i==o||a==s)return r;let e=this.children[i],c=t.children[a];if(e!=c)return r+e.scanIdentical(c,n);r+=e.length+1}}static from(t,n=t.reduce((e,t)=>e+t.length+1,-1)){let r=0;for(let e of t)r+=e.lines;if(r<32){let e=[];for(let n of t)n.flatten(e);return new Ff(e,n)}let i=Math.max(32,r>>5),a=i<<1,o=i>>1,s=[],c=0,l=-1,u=[];function d(t){let n;if(t.lines>a&&t instanceof e)for(let e of t.children)d(e);else t.lines>o&&(c>o||!c)?(f(),s.push(t)):t instanceof Ff&&c&&(n=u[u.length-1])instanceof Ff&&t.lines+n.lines<=32?(c+=t.lines,l+=t.length+1,u[u.length-1]=new Ff(n.text.concat(t.text),n.length+1+t.length)):(c+t.lines>i&&f(),c+=t.lines,l+=t.length+1,u.push(t))}function f(){c!=0&&(s.push(u.length==1?u[0]:e.from(u,l)),l=-1,c=u.length=0)}for(let e of t)d(e);return f(),s.length==1?s[0]:new e(s,n)}};k.empty=new Ff([``],0);function Lf(e){let t=-1;for(let n of e)t+=n.length+1;return t}function Rf(e,t,n=0,r=1e9){for(let i=0,a=0,o=!0;a<e.length&&i<=r;a++){let s=e[a],c=i+s.length;c>=n&&(c>r&&(s=s.slice(0,r-i)),i<n&&(s=s.slice(n-i)),o?(t[t.length-1]+=s,o=!1):t.push(s)),i=c+1}return t}function zf(e,t,n){return Rf(e,[``],t,n)}var Bf=class{constructor(e,t=1){this.dir=t,this.done=!1,this.lineBreak=!1,this.value=``,this.nodes=[e],this.offsets=[t>0?1:(e instanceof Ff?e.text.length:e.children.length)<<1]}nextInner(e,t){for(this.done=this.lineBreak=!1;;){let n=this.nodes.length-1,r=this.nodes[n],i=this.offsets[n],a=i>>1,o=r instanceof Ff?r.text.length:r.children.length;if(a==(t>0?o:0)){if(n==0)return this.done=!0,this.value=``,this;t>0&&this.offsets[n-1]++,this.nodes.pop(),this.offsets.pop()}else if((i&1)==(t>0?0:1)){if(this.offsets[n]+=t,e==0)return this.lineBreak=!0,this.value=`
480
480
  `,this;e--}else if(r instanceof Ff){let i=r.text[a+(t<0?-1:0)];if(this.offsets[n]+=t,i.length>Math.max(0,e))return this.value=e==0?i:t>0?i.slice(e):i.slice(0,i.length-e),this;e-=i.length}else{let i=r.children[a+(t<0?-1:0)];e>i.length?(e-=i.length,this.offsets[n]+=t):(t<0&&this.offsets[n]--,this.nodes.push(i),this.offsets.push(t>0?1:(i instanceof Ff?i.text.length:i.children.length)<<1))}}}next(e=0){return e<0&&(this.nextInner(-e,-this.dir),e=this.value.length),this.nextInner(e,this.dir)}},Vf=class{constructor(e,t,n){this.value=``,this.done=!1,this.cursor=new Bf(e,t>n?-1:1),this.pos=t>n?e.length:0,this.from=Math.min(t,n),this.to=Math.max(t,n)}nextInner(e,t){if(t<0?this.pos<=this.from:this.pos>=this.to)return this.value=``,this.done=!0,this;e+=Math.max(0,t<0?this.pos-this.to:this.from-this.pos);let n=t<0?this.pos-this.from:this.to-this.pos;e>n&&(e=n),n-=e;let{value:r}=this.cursor.next(e);return this.pos+=(r.length+e)*t,this.value=r.length<=n?r:t<0?r.slice(r.length-n):r.slice(0,n),this.done=!this.value,this}next(e=0){return e<0?e=Math.max(e,this.from-this.pos):e>0&&(e=Math.min(e,this.to-this.pos)),this.nextInner(e,this.cursor.dir)}get lineBreak(){return this.cursor.lineBreak&&this.value!=``}},Hf=class{constructor(e){this.inner=e,this.afterBreak=!0,this.value=``,this.done=!1}next(e=0){let{done:t,lineBreak:n,value:r}=this.inner.next(e);return t&&this.afterBreak?(this.value=``,this.afterBreak=!1):t?(this.done=!0,this.value=``):n?this.afterBreak?this.value=``:(this.afterBreak=!0,this.next()):(this.value=r,this.afterBreak=!1),this}get lineBreak(){return!1}};typeof Symbol<`u`&&(k.prototype[Symbol.iterator]=function(){return this.iter()},Bf.prototype[Symbol.iterator]=Vf.prototype[Symbol.iterator]=Hf.prototype[Symbol.iterator]=function(){return this});var Uf=class{constructor(e,t,n,r){this.from=e,this.to=t,this.number=n,this.text=r}get length(){return this.to-this.from}};function Wf(e,t,n){return t=Math.max(0,Math.min(e.length,t)),[t,Math.max(t,Math.min(e.length,n))]}function Gf(e,t,n=!0,r=!0){return Of(e,t,n,r)}function Kf(e){return e>=56320&&e<57344}function qf(e){return e>=55296&&e<56320}function Jf(e,t){let n=e.charCodeAt(t);if(!qf(n)||t+1==e.length)return n;let r=e.charCodeAt(t+1);return Kf(r)?(n-55296<<10)+(r-56320)+65536:n}function Yf(e){return e<=65535?String.fromCharCode(e):(e-=65536,String.fromCharCode((e>>10)+55296,(e&1023)+56320))}function Xf(e){return e<65536?1:2}var Zf=/\r\n?|\n/,Qf=(function(e){return e[e.Simple=0]=`Simple`,e[e.TrackDel=1]=`TrackDel`,e[e.TrackBefore=2]=`TrackBefore`,e[e.TrackAfter=3]=`TrackAfter`,e})(Qf||={}),$f=class e{constructor(e){this.sections=e}get length(){let e=0;for(let t=0;t<this.sections.length;t+=2)e+=this.sections[t];return e}get newLength(){let e=0;for(let t=0;t<this.sections.length;t+=2){let n=this.sections[t+1];e+=n<0?this.sections[t]:n}return e}get empty(){return this.sections.length==0||this.sections.length==2&&this.sections[1]<0}iterGaps(e){for(let t=0,n=0,r=0;t<this.sections.length;){let i=this.sections[t++],a=this.sections[t++];a<0?(e(n,r,i),r+=i):r+=a,n+=i}}iterChangedRanges(e,t=!1){rp(this,e,t)}get invertedDesc(){let t=[];for(let e=0;e<this.sections.length;){let n=this.sections[e++],r=this.sections[e++];r<0?t.push(n,r):t.push(r,n)}return new e(t)}composeDesc(e){return this.empty?e:e.empty?this:ap(this,e)}mapDesc(e,t=!1){return e.empty?this:ip(this,e,t)}mapPos(e,t=-1,n=Qf.Simple){let r=0,i=0;for(let a=0;a<this.sections.length;){let o=this.sections[a++],s=this.sections[a++],c=r+o;if(s<0){if(c>e)return i+(e-r);i+=o}else{if(n!=Qf.Simple&&c>=e&&(n==Qf.TrackDel&&r<e&&c>e||n==Qf.TrackBefore&&r<e||n==Qf.TrackAfter&&c>e))return null;if(c>e||c==e&&t<0&&!o)return e==r||t<0?i:i+s;i+=s}r=c}if(e>r)throw RangeError(`Position ${e} is out of range for changeset of length ${r}`);return i}touchesRange(e,t=e){for(let n=0,r=0;n<this.sections.length&&r<=t;){let i=this.sections[n++],a=this.sections[n++],o=r+i;if(a>=0&&r<=t&&o>=e)return r<e&&o>t?`cover`:!0;r=o}return!1}toString(){let e=``;for(let t=0;t<this.sections.length;){let n=this.sections[t++],r=this.sections[t++];e+=(e?` `:``)+n+(r>=0?`:`+r:``)}return e}toJSON(){return this.sections}static fromJSON(t){if(!Array.isArray(t)||t.length%2||t.some(e=>typeof e!=`number`))throw RangeError(`Invalid JSON representation of ChangeDesc`);return new e(t)}static create(t){return new e(t)}},ep=class e extends $f{constructor(e,t){super(e),this.inserted=t}apply(e){if(this.length!=e.length)throw RangeError(`Applying change set to a document with the wrong length`);return rp(this,(t,n,r,i,a)=>e=e.replace(r,r+(n-t),a),!1),e}mapDesc(e,t=!1){return ip(this,e,t,!0)}invert(t){let n=this.sections.slice(),r=[];for(let e=0,i=0;e<n.length;e+=2){let a=n[e],o=n[e+1];if(o>=0){n[e]=o,n[e+1]=a;let s=e>>1;for(;r.length<s;)r.push(k.empty);r.push(a?t.slice(i,i+a):k.empty)}i+=a}return new e(n,r)}compose(e){return this.empty?e:e.empty?this:ap(this,e,!0)}map(e,t=!1){return e.empty?this:ip(this,e,t,!0)}iterChanges(e,t=!1){rp(this,e,t)}get desc(){return $f.create(this.sections)}filter(t){let n=[],r=[],i=[],a=new op(this);done:for(let e=0,o=0;;){let s=e==t.length?1e9:t[e++];for(;o<s||o==s&&a.len==0;){if(a.done)break done;let e=Math.min(a.len,s-o);tp(i,e,-1);let t=a.ins==-1?-1:a.off==0?a.ins:0;tp(n,e,t),t>0&&np(r,n,a.text),a.forward(e),o+=e}let c=t[e++];for(;o<c;){if(a.done)break done;let e=Math.min(a.len,c-o);tp(n,e,-1),tp(i,e,a.ins==-1?-1:a.off==0?a.ins:0),a.forward(e),o+=e}}return{changes:new e(n,r),filtered:$f.create(i)}}toJSON(){let e=[];for(let t=0;t<this.sections.length;t+=2){let n=this.sections[t],r=this.sections[t+1];r<0?e.push(n):r==0?e.push([n]):e.push([n].concat(this.inserted[t>>1].toJSON()))}return e}static of(t,n,r){let i=[],a=[],o=0,s=null;function c(t=!1){if(!t&&!i.length)return;o<n&&tp(i,n-o,-1);let r=new e(i,a);s=s?s.compose(r.map(s)):r,i=[],a=[],o=0}function l(t){if(Array.isArray(t))for(let e of t)l(e);else if(t instanceof e){if(t.length!=n)throw RangeError(`Mismatched change set length (got ${t.length}, expected ${n})`);c(),s=s?s.compose(t.map(s)):t}else{let{from:e,to:s=e,insert:l}=t;if(e>s||e<0||s>n)throw RangeError(`Invalid change range ${e} to ${s} (in doc of length ${n})`);let u=l?typeof l==`string`?k.of(l.split(r||Zf)):l:k.empty,d=u.length;if(e==s&&d==0)return;e<o&&c(),e>o&&tp(i,e-o,-1),tp(i,s-e,d),np(a,i,u),o=s}}return l(t),c(!s),s}static empty(t){return new e(t?[t,-1]:[],[])}static fromJSON(t){if(!Array.isArray(t))throw RangeError(`Invalid JSON representation of ChangeSet`);let n=[],r=[];for(let e=0;e<t.length;e++){let i=t[e];if(typeof i==`number`)n.push(i,-1);else if(!Array.isArray(i)||typeof i[0]!=`number`||i.some((e,t)=>t&&typeof e!=`string`))throw RangeError(`Invalid JSON representation of ChangeSet`);else if(i.length==1)n.push(i[0],0);else{for(;r.length<e;)r.push(k.empty);r[e]=k.of(i.slice(1)),n.push(i[0],r[e].length)}}return new e(n,r)}static createSet(t,n){return new e(t,n)}};function tp(e,t,n,r=!1){if(t==0&&n<=0)return;let i=e.length-2;i>=0&&n<=0&&n==e[i+1]?e[i]+=t:i>=0&&t==0&&e[i]==0?e[i+1]+=n:r?(e[i]+=t,e[i+1]+=n):e.push(t,n)}function np(e,t,n){if(n.length==0)return;let r=t.length-2>>1;if(r<e.length)e[e.length-1]=e[e.length-1].append(n);else{for(;e.length<r;)e.push(k.empty);e.push(n)}}function rp(e,t,n){let r=e.inserted;for(let i=0,a=0,o=0;o<e.sections.length;){let s=e.sections[o++],c=e.sections[o++];if(c<0)i+=s,a+=s;else{let l=i,u=a,d=k.empty;for(;l+=s,u+=c,c&&r&&(d=d.append(r[o-2>>1])),!(n||o==e.sections.length||e.sections[o+1]<0);)s=e.sections[o++],c=e.sections[o++];t(i,l,a,u,d),i=l,a=u}}}function ip(e,t,n,r=!1){let i=[],a=r?[]:null,o=new op(e),s=new op(t);for(let e=-1;;)if(o.done&&s.len||s.done&&o.len)throw Error(`Mismatched change set lengths`);else if(o.ins==-1&&s.ins==-1){let e=Math.min(o.len,s.len);tp(i,e,-1),o.forward(e),s.forward(e)}else if(s.ins>=0&&(o.ins<0||e==o.i||o.off==0&&(s.len<o.len||s.len==o.len&&!n))){let t=s.len;for(tp(i,s.ins,-1);t;){let n=Math.min(o.len,t);o.ins>=0&&e<o.i&&o.len<=n&&(tp(i,0,o.ins),a&&np(a,i,o.text),e=o.i),o.forward(n),t-=n}s.next()}else if(o.ins>=0){let t=0,n=o.len;for(;n;)if(s.ins==-1){let e=Math.min(n,s.len);t+=e,n-=e,s.forward(e)}else if(s.ins==0&&s.len<n)n-=s.len,s.next();else break;tp(i,t,e<o.i?o.ins:0),a&&e<o.i&&np(a,i,o.text),e=o.i,o.forward(o.len-n)}else if(o.done&&s.done)return a?ep.createSet(i,a):$f.create(i);else throw Error(`Mismatched change set lengths`)}function ap(e,t,n=!1){let r=[],i=n?[]:null,a=new op(e),o=new op(t);for(let e=!1;;)if(a.done&&o.done)return i?ep.createSet(r,i):$f.create(r);else if(a.ins==0)tp(r,a.len,0,e),a.next();else if(o.len==0&&!o.done)tp(r,0,o.ins,e),i&&np(i,r,o.text),o.next();else if(a.done||o.done)throw Error(`Mismatched change set lengths`);else{let t=Math.min(a.len2,o.len),n=r.length;if(a.ins==-1){let n=o.ins==-1?-1:o.off?0:o.ins;tp(r,t,n,e),i&&n&&np(i,r,o.text)}else o.ins==-1?(tp(r,a.off?0:a.len,t,e),i&&np(i,r,a.textBit(t))):(tp(r,a.off?0:a.len,o.off?0:o.ins,e),i&&!o.off&&np(i,r,o.text));e=(a.ins>t||o.ins>=0&&o.len>t)&&(e||r.length>n),a.forward2(t),o.forward(t)}}var op=class{constructor(e){this.set=e,this.i=0,this.next()}next(){let{sections:e}=this.set;this.i<e.length?(this.len=e[this.i++],this.ins=e[this.i++]):(this.len=0,this.ins=-2),this.off=0}get done(){return this.ins==-2}get len2(){return this.ins<0?this.len:this.ins}get text(){let{inserted:e}=this.set,t=this.i-2>>1;return t>=e.length?k.empty:e[t]}textBit(e){let{inserted:t}=this.set,n=this.i-2>>1;return n>=t.length&&!e?k.empty:t[n].slice(this.off,e==null?void 0:this.off+e)}forward(e){e==this.len?this.next():(this.len-=e,this.off+=e)}forward2(e){this.ins==-1?this.forward(e):e==this.ins?this.next():(this.ins-=e,this.off+=e)}},sp=class e{constructor(e,t,n){this.from=e,this.to=t,this.flags=n}get anchor(){return this.flags&32?this.to:this.from}get head(){return this.flags&32?this.from:this.to}get empty(){return this.from==this.to}get assoc(){return this.flags&8?-1:this.flags&16?1:0}get bidiLevel(){let e=this.flags&7;return e==7?null:e}get goalColumn(){let e=this.flags>>6;return e==16777215?void 0:e}map(t,n=-1){let r,i;return this.empty?r=i=t.mapPos(this.from,n):(r=t.mapPos(this.from,1),i=t.mapPos(this.to,-1)),r==this.from&&i==this.to?this:new e(r,i,this.flags)}extend(e,t=e,n=0){if(e<=this.anchor&&t>=this.anchor)return A.range(e,t,void 0,void 0,n);let r=Math.abs(e-this.anchor)>Math.abs(t-this.anchor)?e:t;return A.range(this.anchor,r,void 0,void 0,n)}eq(e,t=!1){return this.anchor==e.anchor&&this.head==e.head&&this.goalColumn==e.goalColumn&&(!t||!this.empty||this.assoc==e.assoc)}toJSON(){return{anchor:this.anchor,head:this.head}}static fromJSON(e){if(!e||typeof e.anchor!=`number`||typeof e.head!=`number`)throw RangeError(`Invalid JSON representation for SelectionRange`);return A.range(e.anchor,e.head)}static create(t,n,r){return new e(t,n,r)}},A=class e{constructor(e,t){this.ranges=e,this.mainIndex=t}map(t,n=-1){return t.empty?this:e.create(this.ranges.map(e=>e.map(t,n)),this.mainIndex)}eq(e,t=!1){if(this.ranges.length!=e.ranges.length||this.mainIndex!=e.mainIndex)return!1;for(let n=0;n<this.ranges.length;n++)if(!this.ranges[n].eq(e.ranges[n],t))return!1;return!0}get main(){return this.ranges[this.mainIndex]}asSingle(){return this.ranges.length==1?this:new e([this.main],0)}addRange(t,n=!0){return e.create([t].concat(this.ranges),n?0:this.mainIndex+1)}replaceRange(t,n=this.mainIndex){let r=this.ranges.slice();return r[n]=t,e.create(r,this.mainIndex)}toJSON(){return{ranges:this.ranges.map(e=>e.toJSON()),main:this.mainIndex}}static fromJSON(t){if(!t||!Array.isArray(t.ranges)||typeof t.main!=`number`||t.main>=t.ranges.length)throw RangeError(`Invalid JSON representation for EditorSelection`);return new e(t.ranges.map(e=>sp.fromJSON(e)),t.main)}static single(t,n=t){return new e([e.range(t,n)],0)}static create(t,n=0){if(t.length==0)throw RangeError(`A selection needs at least one range`);for(let r=0,i=0;i<t.length;i++){let a=t[i];if(a.empty?a.from<=r:a.from<r)return e.normalized(t.slice(),n);r=a.to}return new e(t,n)}static cursor(e,t=0,n,r){return sp.create(e,e,(t==0?0:t<0?8:16)|(n==null?7:Math.min(6,n))|(r??16777215)<<6)}static range(e,t,n,r,i){let a=(n??16777215)<<6|(r==null?7:Math.min(6,r));return!i&&e!=t&&(i=t<e?1:-1),t<e?sp.create(t,e,48|a):sp.create(e,t,(i?i<0?8:16:0)|a)}static normalized(t,n=0){let r=t[n];t.sort((e,t)=>e.from-t.from),n=t.indexOf(r);for(let r=1;r<t.length;r++){let i=t[r],a=t[r-1];if(i.empty?i.from<=a.to:i.from<a.to){let o=a.from,s=Math.max(i.to,a.to);r<=n&&n--,t.splice(--r,2,i.anchor>i.head?e.range(s,o):e.range(o,s))}}return new e(t,n)}};function cp(e,t){for(let n of e.ranges)if(n.to>t)throw RangeError(`Selection points outside of document`)}var lp=0,j=class e{constructor(e,t,n,r,i){this.combine=e,this.compareInput=t,this.compare=n,this.isStatic=r,this.id=lp++,this.default=e([]),this.extensions=typeof i==`function`?i(this):i}get reader(){return this}static define(t={}){return new e(t.combine||(e=>e),t.compareInput||((e,t)=>e===t),t.compare||(t.combine?(e,t)=>e===t:up),!!t.static,t.enables)}of(e){return new dp([],this,0,e)}compute(e,t){if(this.isStatic)throw Error(`Can't compute a static facet`);return new dp(e,this,1,t)}computeN(e,t){if(this.isStatic)throw Error(`Can't compute a static facet`);return new dp(e,this,2,t)}from(e,t){return t||=e=>e,this.compute([e],n=>t(n.field(e)))}};function up(e,t){return e==t||e.length==t.length&&e.every((e,n)=>e===t[n])}var dp=class{constructor(e,t,n,r){this.dependencies=e,this.facet=t,this.type=n,this.value=r,this.id=lp++}dynamicSlot(e){let t=this.value,n=this.facet.compareInput,r=this.id,i=e[r]>>1,a=this.type==2,o=!1,s=!1,c=[];for(let t of this.dependencies)t==`doc`?o=!0:t==`selection`?s=!0:(e[t.id]??1)&1||c.push(e[t.id]);return{create(e){return e.values[i]=t(e),1},update(e,r){if(o&&r.docChanged||s&&(r.docChanged||r.selection)||pp(e,c)){let r=t(e);if(a?!fp(r,e.values[i],n):!n(r,e.values[i]))return e.values[i]=r,1}return 0},reconfigure:(e,o)=>{let s,c=o.config.address[r];if(c!=null){let r=Ep(o,c);if(this.dependencies.every(t=>t instanceof j?o.facet(t)===e.facet(t):t instanceof gp?o.field(t,!1)==e.field(t,!1):!0)||(a?fp(s=t(e),r,n):n(s=t(e),r)))return e.values[i]=r,0}else s=t(e);return e.values[i]=s,1}}}};function fp(e,t,n){if(e.length!=t.length)return!1;for(let r=0;r<e.length;r++)if(!n(e[r],t[r]))return!1;return!0}function pp(e,t){let n=!1;for(let r of t)Tp(e,r)&1&&(n=!0);return n}function mp(e,t,n){let r=n.map(t=>e[t.id]),i=n.map(e=>e.type),a=r.filter(e=>!(e&1)),o=e[t.id]>>1;function s(e){let n=[];for(let t=0;t<r.length;t++){let a=Ep(e,r[t]);if(i[t]==2)for(let e of a)n.push(e);else n.push(a)}return t.combine(n)}return{create(e){for(let t of r)Tp(e,t);return e.values[o]=s(e),1},update(e,n){if(!pp(e,a))return 0;let r=s(e);return t.compare(r,e.values[o])?0:(e.values[o]=r,1)},reconfigure(e,i){let a=pp(e,r),c=i.config.facets[t.id],l=i.facet(t);if(c&&!a&&up(n,c))return e.values[o]=l,0;let u=s(e);return t.compare(u,l)?(e.values[o]=l,0):(e.values[o]=u,1)}}}var hp=j.define({static:!0}),gp=class e{constructor(e,t,n,r,i){this.id=e,this.createF=t,this.updateF=n,this.compareF=r,this.spec=i,this.provides=void 0}static define(t){let n=new e(lp++,t.create,t.update,t.compare||((e,t)=>e===t),t);return t.provide&&(n.provides=t.provide(n)),n}create(e){return(e.facet(hp).find(e=>e.field==this)?.create||this.createF)(e)}slot(e){let t=e[this.id]>>1;return{create:e=>(e.values[t]=this.create(e),1),update:(e,n)=>{let r=e.values[t],i=this.updateF(r,n);return this.compareF(r,i)?0:(e.values[t]=i,1)},reconfigure:(e,n)=>{let r=e.facet(hp),i=n.facet(hp),a;return(a=r.find(e=>e.field==this))&&a!=i.find(e=>e.field==this)?(e.values[t]=a.create(e),1):n.config.address[this.id]==null?(e.values[t]=this.create(e),1):(e.values[t]=n.field(this),0)}}}init(e){return[this,hp.of({field:this,create:e})]}get extension(){return this}},_p={lowest:4,low:3,default:2,high:1,highest:0};function vp(e){return t=>new bp(t,e)}var yp={highest:vp(_p.highest),high:vp(_p.high),default:vp(_p.default),low:vp(_p.low),lowest:vp(_p.lowest)},bp=class{constructor(e,t){this.inner=e,this.prec=t}},xp=class e{of(e){return new Sp(this,e)}reconfigure(t){return e.reconfigure.of({compartment:this,extension:t})}get(e){return e.config.compartments.get(this)}},Sp=class{constructor(e,t){this.compartment=e,this.inner=t}},Cp=class e{constructor(e,t,n,r,i,a){for(this.base=e,this.compartments=t,this.dynamicSlots=n,this.address=r,this.staticValues=i,this.facets=a,this.statusTemplate=[];this.statusTemplate.length<n.length;)this.statusTemplate.push(0)}staticFacet(e){let t=this.address[e.id];return t==null?e.default:this.staticValues[t>>1]}static resolve(t,n,r){let i=[],a=Object.create(null),o=new Map;for(let e of wp(t,n,o))e instanceof gp?i.push(e):(a[e.facet.id]||(a[e.facet.id]=[])).push(e);let s=Object.create(null),c=[],l=[];for(let e of i)s[e.id]=l.length<<1,l.push(t=>e.slot(t));let u=r?.config.facets;for(let e in a){let t=a[e],n=t[0].facet,i=u&&u[e]||[];if(t.every(e=>e.type==0))if(s[n.id]=c.length<<1|1,up(i,t))c.push(r.facet(n));else{let e=n.combine(t.map(e=>e.value));c.push(r&&n.compare(e,r.facet(n))?r.facet(n):e)}else{for(let e of t)e.type==0?(s[e.id]=c.length<<1|1,c.push(e.value)):(s[e.id]=l.length<<1,l.push(t=>e.dynamicSlot(t)));s[n.id]=l.length<<1,l.push(e=>mp(e,n,t))}}return new e(t,o,l.map(e=>e(s)),s,c,a)}};function wp(e,t,n){let r=[[],[],[],[],[]],i=new Map;function a(e,o){let s=i.get(e);if(s!=null){if(s<=o)return;let t=r[s].indexOf(e);t>-1&&r[s].splice(t,1),e instanceof Sp&&n.delete(e.compartment)}if(i.set(e,o),Array.isArray(e))for(let t of e)a(t,o);else if(e instanceof Sp){if(n.has(e.compartment))throw RangeError(`Duplicate use of compartment in extensions`);let r=t.get(e.compartment)||e.inner;n.set(e.compartment,r),a(r,o)}else if(e instanceof bp)a(e.inner,e.prec);else if(e instanceof gp)r[o].push(e),e.provides&&a(e.provides,o);else if(e instanceof dp)r[o].push(e),e.facet.extensions&&a(e.facet.extensions,_p.default);else{let t=e.extension;if(!t)throw Error(`Unrecognized extension value in extension set (${e}). This sometimes happens because multiple instances of @codemirror/state are loaded, breaking instanceof checks.`);a(t,o)}}return a(e,_p.default),r.reduce((e,t)=>e.concat(t))}function Tp(e,t){if(t&1)return 2;let n=t>>1,r=e.status[n];if(r==4)throw Error(`Cyclic dependency between fields and/or facets`);if(r&2)return r;e.status[n]=4;let i=e.computeSlot(e,e.config.dynamicSlots[n]);return e.status[n]=2|i}function Ep(e,t){return t&1?e.config.staticValues[t>>1]:e.values[t>>1]}var Dp=j.define(),Op=j.define({combine:e=>e.some(e=>e),static:!0}),kp=j.define({combine:e=>e.length?e[0]:void 0,static:!0}),Ap=j.define(),jp=j.define(),Mp=j.define(),Np=j.define({combine:e=>e.length?e[0]:!1}),Pp=class{constructor(e,t){this.type=e,this.value=t}static define(){return new Fp}},Fp=class{of(e){return new Pp(this,e)}},Ip=class{constructor(e){this.map=e}of(e){return new M(this,e)}},M=class e{constructor(e,t){this.type=e,this.value=t}map(t){let n=this.type.map(this.value,t);return n===void 0?void 0:n==this.value?this:new e(this.type,n)}is(e){return this.type==e}static define(e={}){return new Ip(e.map||(e=>e))}static mapEffects(e,t){if(!e.length)return e;let n=[];for(let r of e){let e=r.map(t);e&&n.push(e)}return n}};M.reconfigure=M.define(),M.appendConfig=M.define();var Lp=class e{constructor(t,n,r,i,a,o){this.startState=t,this.changes=n,this.selection=r,this.effects=i,this.annotations=a,this.scrollIntoView=o,this._doc=null,this._state=null,r&&cp(r,n.newLength),a.some(t=>t.type==e.time)||(this.annotations=a.concat(e.time.of(Date.now())))}static create(t,n,r,i,a,o){return new e(t,n,r,i,a,o)}get newDoc(){return this._doc||=this.changes.apply(this.startState.doc)}get newSelection(){return this.selection||this.startState.selection.map(this.changes)}get state(){return this._state||this.startState.applyTransaction(this),this._state}annotation(e){for(let t of this.annotations)if(t.type==e)return t.value}get docChanged(){return!this.changes.empty}get reconfigured(){return this.startState.config!=this.state.config}isUserEvent(t){let n=this.annotation(e.userEvent);return!!(n&&(n==t||n.length>t.length&&n.slice(0,t.length)==t&&n[t.length]==`.`))}};Lp.time=Pp.define(),Lp.userEvent=Pp.define(),Lp.addToHistory=Pp.define(),Lp.remote=Pp.define();function Rp(e,t){let n=[];for(let r=0,i=0;;){let a,o;if(r<e.length&&(i==t.length||t[i]>=e[r]))a=e[r++],o=e[r++];else if(i<t.length)a=t[i++],o=t[i++];else return n;!n.length||n[n.length-1]<a?n.push(a,o):n[n.length-1]<o&&(n[n.length-1]=o)}}function zp(e,t,n){let r,i,a;return n?(r=t.changes,i=ep.empty(t.changes.length),a=e.changes.compose(t.changes)):(r=t.changes.map(e.changes),i=e.changes.mapDesc(t.changes,!0),a=e.changes.compose(r)),{changes:a,selection:t.selection?t.selection.map(i):e.selection?.map(r),effects:M.mapEffects(e.effects,r).concat(M.mapEffects(t.effects,i)),annotations:e.annotations.length?e.annotations.concat(t.annotations):t.annotations,scrollIntoView:e.scrollIntoView||t.scrollIntoView}}function Bp(e,t,n){let r=t.selection,i=Gp(t.annotations);return t.userEvent&&(i=i.concat(Lp.userEvent.of(t.userEvent))),{changes:t.changes instanceof ep?t.changes:ep.of(t.changes||[],n,e.facet(kp)),selection:r&&(r instanceof A?r:A.single(r.anchor,r.head)),effects:Gp(t.effects),annotations:i,scrollIntoView:!!t.scrollIntoView}}function Vp(e,t,n){let r=Bp(e,t.length?t[0]:{},e.doc.length);t.length&&t[0].filter===!1&&(n=!1);for(let i=1;i<t.length;i++){t[i].filter===!1&&(n=!1);let a=!!t[i].sequential;r=zp(r,Bp(e,t[i],a?r.changes.newLength:e.doc.length),a)}let i=Lp.create(e,r.changes,r.selection,r.effects,r.annotations,r.scrollIntoView);return Up(n?Hp(i):i)}function Hp(e){let t=e.startState,n=!0;for(let r of t.facet(Ap)){let t=r(e);if(t===!1){n=!1;break}Array.isArray(t)&&(n=n===!0?t:Rp(n,t))}if(n!==!0){let r,i;if(n===!1)i=e.changes.invertedDesc,r=ep.empty(t.doc.length);else{let t=e.changes.filter(n);r=t.changes,i=t.filtered.mapDesc(t.changes).invertedDesc}e=Lp.create(t,r,e.selection&&e.selection.map(i),M.mapEffects(e.effects,i),e.annotations,e.scrollIntoView)}let r=t.facet(jp);for(let n=r.length-1;n>=0;n--){let i=r[n](e);e=i instanceof Lp?i:Array.isArray(i)&&i.length==1&&i[0]instanceof Lp?i[0]:Vp(t,Gp(i),!1)}return e}function Up(e){let t=e.startState,n=t.facet(Mp),r=e;for(let i=n.length-1;i>=0;i--){let a=n[i](e);a&&Object.keys(a).length&&(r=zp(r,Bp(t,a,e.changes.newLength),!0))}return r==e?e:Lp.create(t,e.changes,e.selection,r.effects,r.annotations,r.scrollIntoView)}var Wp=[];function Gp(e){return e==null?Wp:Array.isArray(e)?e:[e]}var N=(function(e){return e[e.Word=0]=`Word`,e[e.Space=1]=`Space`,e[e.Other=2]=`Other`,e})(N||={}),Kp=/[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/,qp;try{qp=RegExp(`[\\p{Alphabetic}\\p{Number}_]`,`u`)}catch{}function Jp(e){if(qp)return qp.test(e);for(let t=0;t<e.length;t++){let n=e[t];if(/\w/.test(n)||n>`€`&&(n.toUpperCase()!=n.toLowerCase()||Kp.test(n)))return!0}return!1}function Yp(e){return t=>{if(!/\S/.test(t))return N.Space;if(Jp(t))return N.Word;for(let n=0;n<e.length;n++)if(t.indexOf(e[n])>-1)return N.Word;return N.Other}}var P=class e{constructor(e,t,n,r,i,a){this.config=e,this.doc=t,this.selection=n,this.values=r,this.status=e.statusTemplate.slice(),this.computeSlot=i,a&&(a._state=this);for(let e=0;e<this.config.dynamicSlots.length;e++)Tp(this,e<<1);this.computeSlot=null}field(e,t=!0){let n=this.config.address[e.id];if(n==null){if(t)throw RangeError(`Field is not present in this state`);return}return Tp(this,n),Ep(this,n)}update(...e){return Vp(this,e,!0)}applyTransaction(t){let n=this.config,{base:r,compartments:i}=n;for(let e of t.effects)e.is(xp.reconfigure)?(n&&=(i=new Map,n.compartments.forEach((e,t)=>i.set(t,e)),null),i.set(e.value.compartment,e.value.extension)):e.is(M.reconfigure)?(n=null,r=e.value):e.is(M.appendConfig)&&(n=null,r=Gp(r).concat(e.value));let a;n?a=t.startState.values.slice():(n=Cp.resolve(r,i,this),a=new e(n,this.doc,this.selection,n.dynamicSlots.map(()=>null),(e,t)=>t.reconfigure(e,this),null).values);let o=t.startState.facet(Op)?t.newSelection:t.newSelection.asSingle();new e(n,t.newDoc,o,a,(e,n)=>n.update(e,t),t)}replaceSelection(e){return typeof e==`string`&&(e=this.toText(e)),this.changeByRange(t=>({changes:{from:t.from,to:t.to,insert:e},range:A.cursor(t.from+e.length)}))}changeByRange(e){let t=this.selection,n=e(t.ranges[0]),r=this.changes(n.changes),i=[n.range],a=Gp(n.effects);for(let n=1;n<t.ranges.length;n++){let o=e(t.ranges[n]),s=this.changes(o.changes),c=s.map(r);for(let e=0;e<n;e++)i[e]=i[e].map(c);let l=r.mapDesc(s,!0);i.push(o.range.map(l)),r=r.compose(c),a=M.mapEffects(a,c).concat(M.mapEffects(Gp(o.effects),l))}return{changes:r,selection:A.create(i,t.mainIndex),effects:a}}changes(t=[]){return t instanceof ep?t:ep.of(t,this.doc.length,this.facet(e.lineSeparator))}toText(t){return k.of(t.split(this.facet(e.lineSeparator)||Zf))}sliceDoc(e=0,t=this.doc.length){return this.doc.sliceString(e,t,this.lineBreak)}facet(e){let t=this.config.address[e.id];return t==null?e.default:(Tp(this,t),Ep(this,t))}toJSON(e){let t={doc:this.sliceDoc(),selection:this.selection.toJSON()};if(e)for(let n in e){let r=e[n];r instanceof gp&&this.config.address[r.id]!=null&&(t[n]=r.spec.toJSON(this.field(e[n]),this))}return t}static fromJSON(t,n={},r){if(!t||typeof t.doc!=`string`)throw RangeError(`Invalid JSON representation for EditorState`);let i=[];if(r){for(let e in r)if(Object.prototype.hasOwnProperty.call(t,e)){let n=r[e],a=t[e];i.push(n.init(e=>n.spec.fromJSON(a,e)))}}return e.create({doc:t.doc,selection:A.fromJSON(t.selection),extensions:n.extensions?i.concat([n.extensions]):i})}static create(t={}){let n=Cp.resolve(t.extensions||[],new Map),r=t.doc instanceof k?t.doc:k.of((t.doc||``).split(n.staticFacet(e.lineSeparator)||Zf)),i=t.selection?t.selection instanceof A?t.selection:A.single(t.selection.anchor,t.selection.head):A.single(0);return cp(i,r.length),n.staticFacet(Op)||(i=i.asSingle()),new e(n,r,i,n.dynamicSlots.map(()=>null),(e,t)=>t.create(e),null)}get tabSize(){return this.facet(e.tabSize)}get lineBreak(){return this.facet(e.lineSeparator)||`