@keyueclaw/web-sdk 0.1.21 → 0.1.22

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.
@@ -1840,7 +1840,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
1840
1840
  `)}}async function jB(e,t){try{return await e.request(`sessions.compact`,{key:t}),{content:`Context compacted successfully.`,action:`refresh`}}catch(e){return{content:`Compaction failed: ${String(e)}`}}}async function MB(e,t,n){if(!n)try{let[n,r]=await Promise.all([e.request(`sessions.list`,{}),e.request(`models.list`,{})]),i=KB(n,t)?.model||n?.defaults?.model||`default`,a=r?.models?.map(e=>e.id)??[],o=[`**Current model:** \`${i}\``];return a.length>0&&o.push(`**Available:** ${a.slice(0,10).map(e=>`\`${e}\``).join(`, `)}${a.length>10?` +${a.length-10} more`:``}`),{content:o.join(`
1841
1841
  `)}}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=OB(r.resolved?.model??n.trim(),r.resolved?.modelProvider);return{content:`Model set to \`${n.trim()}\`.`,action:`refresh`,sessionPatch:{modelOverride:DB(i)}}}catch(e){return{content:`Failed to set model: ${String(e)}`}}}async function NB(e,t,n){let r=n.trim();if(!r)try{let{session:n,models:r}=await qB(e,t);return{content:WB(`Current thinking level: ${JB(n,r)}.`,bB(n?.modelProvider,n?.model))}}catch(e){return{content:`Failed to get thinking level: ${String(e)}`}}let i=_B(r);if(!i)try{let n=await GB(e,t);return{content:`Unrecognized thinking level "${r}". Valid levels: ${bB(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 PB(e,t,n){let r=n.trim();if(!r)try{return{content:WB(`Current verbose level: ${CB((await GB(e,t))?.verboseLevel)??`off`}.`,`on, full, off`)}}catch(e){return{content:`Failed to get verbose level: ${String(e)}`}}let i=CB(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 FB(e,t,n){let r=n.trim().toLowerCase();if(!r||r===`status`)try{return{content:WB(`Current fast mode: ${YB(await GB(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 IB(e,t){try{let n=KB(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: **${XB(r)}** tokens`,`Output: **${XB(i)}** tokens`,`Total: **${XB(a)}** tokens`];return s!==null&&c.push(`Context: **${s}%** of ${XB(o)}`),n.model&&c.push(`Model: \`${n.model}\``),{content:c.join(`
1842
1842
  `)}}catch(e){return{content:`Failed to get usage: ${String(e)}`}}}async function LB(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(`
1843
- `)}}catch(e){return{content:`Failed to list agents: ${String(e)}`}}}async function RB(e,t,n){let r=n.trim();if(!r)return{content:"Usage: `/kill <id|all>`"};try{let n=zB((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 zB(e,t,n){let r=n.trim().toLowerCase();if(!r)return[];let i=new Set,a=t.trim().toLowerCase(),o=rF(a)?.agentId??(a===`main`?`main`:void 0),s=VB(e);for(let t of e){let e=t?.key?.trim();if(!e||!iF(e))continue;let n=e.toLowerCase(),c=rF(n),l=BB(n,a,s,o,c?.agentId);(r===`all`&&l||l&&n===r||l&&((c?.agentId??``)===r||n.endsWith(`:subagent:${r}`)||n===`subagent:${r}`))&&i.add(e)}return[...i]}function BB(e,t,n,r,i){if(!r||i!==r)return!1;let a=UB(t,r),o=new Set,s=HB(n.get(e)?.spawnedBy);for(;s&&!o.has(s);){if(a.has(s))return!0;o.add(s),s=HB(n.get(s)?.spawnedBy)}return iF(t)?e.startsWith(`${t}:subagent:`):!1}function VB(e){let t=new Map;for(let n of e){let e=HB(n?.key);e&&t.set(e,n)}return t}function HB(e){return e?.trim().toLowerCase()||void 0}function UB(e,t){let n=new Set([e]);if(t===`main`){let t=`agent:${wB}:main`;e===`main`?n.add(t):e===t&&n.add(TB)}return n}function WB(e,t){return`${e}\nOptions: ${t}.`}async function GB(e,t){return KB(await e.request(`sessions.list`,{}),t)}function KB(e,t){let n=HB(t),r=rF(n??``)?.agentId??(n===`main`?`main`:void 0),i=n?UB(n,r):new Set;return e?.sessions?.find(e=>{let t=HB(e.key);return t?i.has(t):!1})}async function qB(e,t){let[n,r]=await Promise.all([e.request(`sessions.list`,{}),e.request(`models.list`,{})]);return{session:KB(n,t),models:r?.models??[]}}function JB(e,t){return _B(e?.thinkingLevel)||(!e?.modelProvider||!e.model?`off`:xB({provider:e.modelProvider,model:e.model,catalog:t}))}function YB(e){return e?.fastMode===!0?`on`:`off`}function XB(e){return e>=1e6?`${(e/1e6).toFixed(1).replace(/\.0$/,``)}M`:e>=1e3?`${(e/1e3).toFixed(1).replace(/\.0$/,``)}k`:String(e)}var ZB={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`},QB=new Set([`retry_with_device_token`,`update_auth_configuration`,`update_auth_credentials`,`wait_then_retry`,`review_auth_configuration`]);function $B(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 eV(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:QB.has(r)?r:void 0}}function tV(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 nV={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`},rV=nV,iV={WEBCHAT:`webchat`,CLI:`cli`,UI:`ui`,BACKEND:`backend`,NODE:`node`,PROBE:`probe`,TEST:`test`};new Set(Object.values(nV)),new Set(Object.values(iV));var aV=class extends Error{constructor(e){super(e.message),this.name=`GatewayRequestError`,this.gatewayCode=e.code,this.details=e.details}};function oV(e){return $B(e?.details)}function sV(e){if(!e)return!1;let t=oV(e);return t===ZB.AUTH_TOKEN_MISSING||t===ZB.AUTH_BOOTSTRAP_TOKEN_INVALID||t===ZB.AUTH_PASSWORD_MISSING||t===ZB.AUTH_PASSWORD_MISMATCH||t===ZB.AUTH_RATE_LIMITED||t===ZB.PAIRING_REQUIRED||t===ZB.CONTROL_UI_DEVICE_IDENTITY_REQUIRED||t===ZB.DEVICE_IDENTITY_REQUIRED}function cV(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 lV=4008,uV=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}),!(oV(n)===ZB.AUTH_TOKEN_MISMATCH&&this.deviceTokenRetryBudgetUsed&&!this.pendingDeviceTokenRetry)&&(sV(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 XL(),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=tV({deviceId:a.deviceId,clientId:this.opts.clientName??rV.CONTROL_UI,clientMode:this.opts.mode??iV.WEBCHAT,role:n,scopes:t,signedAtMs:e,token:s??null,nonce:r}),o=await ZL(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??rV.CONTROL_UI,version:this.opts.clientVersion??`control-ui`,platform:this.opts.platform??navigator.platform??`web`,mode:this.opts.mode??iV.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&&PI({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 aV?oV(e):null,i=e instanceof aV?eV(e.details):{},s=i.recommendedNextStep===`retry_with_device_token`,c=i.canRetryWithDeviceToken===!0||s||t===ZB.AUTH_TOKEN_MISMATCH;!this.deviceTokenRetryBudgetUsed&&!o.authDeviceToken&&r&&a&&o.storedToken&&c&&cV(this.opts.url)&&(this.pendingDeviceTokenRetry=!0,this.deviceTokenRetryBudgetUsed=!0),e instanceof aV?this.pendingConnectError={code:e.gatewayCode,message:e.message,details:e.details}:this.pendingConnectError=void 0,o.canFallbackToShared&&a&&t===ZB.AUTH_DEVICE_TOKEN_MISMATCH&&FI({deviceId:a.deviceId,role:n}),this.ws?.close(lV,`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 aV({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=NI({deviceId:e.deviceId,role:e.role})?.token,i=this.pendingDeviceTokenRetry&&!!t&&!!r&&cV(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=Ie(),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 dV(e){return typeof e==`string`?e:e instanceof Error&&typeof e.message==`string`?e.message:`unknown error`}function fV(e){let t=dV(e.message);switch(oV(e)){case ZB.AUTH_TOKEN_MISMATCH:return`gateway token mismatch`;case ZB.AUTH_UNAUTHORIZED:return`gateway auth failed`;case ZB.AUTH_RATE_LIMITED:return`too many failed authentication attempts`;case ZB.PAIRING_REQUIRED:return`gateway pairing required`;case ZB.CONTROL_UI_DEVICE_IDENTITY_REQUIRED:return`device identity required (use HTTPS/localhost or allow insecure auth explicitly)`;case ZB.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 ZB.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 pV(e){return e&&typeof e==`object`?fV(e):dV(e)}var mV=/^\s*NO_REPLY\s*$/;function hV(e){return mV.test(e)}function gV(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 hV(t.text);let n=dz(e);return typeof n==`string`&&hV(n)}function _V(e){for(let t=e.length-1;t>=0;--t){let n=e[t];if(!n||typeof n!=`object`)continue;let r=n;if((typeof r.role==`string`?r.role.toLowerCase():``)!==`assistant`)continue;let i=r.__runLatency&&typeof r.__runLatency==`object`?r.__runLatency:null;return typeof i?.ttftMs==`number`||typeof i?.totalMs==`number`}return!1}function vV(e,t){if(!t)return e;for(let n=e.length-1;n>=0;--n){let r=e[n];if(!r||typeof r!=`object`)continue;let i=r;if((typeof i.role==`string`?i.role.toLowerCase():``)!==`assistant`)continue;let a=[...e];return a[n]={...i,__runLatency:{ttftMs:t.ttftMs,totalMs:t.totalMs}},a}return e}function yV(e){let t=e;t.toolStreamById instanceof Map&&Array.isArray(t.toolStreamOrder)&&Array.isArray(t.chatToolMessages)&&Array.isArray(t.chatStreamSegments)&&aB(t)}async function bV(e,t){if(!(!e.client||!e.connected)){e.chatLoading=!0,e.lastError=null;try{let n=await e.client.request(`chat.history`,{sessionKey:e.sessionKey,limit:200}),r=(Array.isArray(n.messages)?n.messages:[]).filter(e=>!gV(e));e.chatMessages=t?.preserveLastLatency&&!_V(r)?vV(r,e.lastLatency):r,e.chatThinkingLevel=n.thinkingLevel??null,yV(e),e.chatStream=null,e.chatStreamStartedAt=null,t?.preserveLastLatency&&!_V(r)||(e.lastLatency=null)}catch(t){e.lastError=String(t)}finally{e.chatLoading=!1}}}function xV(e){let t=/^data:([^;]+);base64,(.+)$/.exec(e);return t?{mimeType:t[1],content:t[2]}:null}function SV(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 CV(e){return SV(e,{roleRequirement:`required`,roleCaseSensitive:!0,requireContentArray:!0})}function wV(e){return SV(e,{roleRequirement:`optional`,allowTextField:!0})}async function TV(e,t,n,r){if(!e.client||!e.connected)return null;let i=t.trim(),a=n&&n.length>0;if(!i&&!a)return null;let o=Date.now(),s=[];if(i&&s.push({type:`text`,text:i}),a)for(let e of n)s.push({type:`image`,source:{type:`base64`,media_type:e.mimeType,data:e.dataUrl}});r?.optimisticUserMessage!==!1&&(e.chatMessages=[...e.chatMessages,{role:`user`,content:s,timestamp:o}]),e.chatSending=!0,e.lastError=null,e.lastLatency=null;let c=Ie();e.chatRunId=c,e.chatStream=``,e.chatStreamStartedAt=o;let l=a?n.map(e=>{let t=xV(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:i,deliver:!1,idempotencyKey:c,attachments:l,clientSentAt:o}),c}catch(t){let n=pV(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 EV(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=pV(t),!1}}function DV(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=wV(t.message);return n&&!gV(n)?(e.chatMessages=[...e.chatMessages,n],null):`final`}return null}if(t.state===`delta`){t.retract&&(e.chatStream=null);let n=dz(t.message);if(typeof n==`string`&&!hV(n)){let t=e.chatStream??``;(!t||n.length>=t.length)&&(e.chatStream=n)}t.firstTokenAt!=null&&e.chatStreamStartedAt!=null&&!e.lastLatency&&(e.lastLatency={ttftMs:t.firstTokenAt-e.chatStreamStartedAt,totalMs:null})}else if(t.state===`final`){let n=wV(t.message),r=e.chatStreamStartedAt==null?null:{ttftMs:t.firstTokenAt==null?null:t.firstTokenAt-e.chatStreamStartedAt,totalMs:t.endedAt==null?null:t.endedAt-e.chatStreamStartedAt};if(n&&!gV(n))r&&(n.__runLatency=r),e.chatMessages=[...e.chatMessages,n];else if(e.chatStream?.trim()&&!hV(e.chatStream)){let t={role:`assistant`,content:[{type:`text`,text:e.chatStream}],timestamp:Date.now()};r&&(t.__runLatency=r),e.chatMessages=[...e.chatMessages,t]}e.lastLatency=r,e.chatStream=null,e.chatRunId=null,e.chatStreamStartedAt=null}else if(t.state===`aborted`){let n=CV(t.message);if(n&&!gV(n))e.chatMessages=[...e.chatMessages,n];else{let t=e.chatStream??``;t.trim()&&!hV(t)&&(e.chatMessages=[...e.chatMessages,{role:`assistant`,content:[{type:`text`,text:t}],timestamp:Date.now()}])}e.chatStreamStartedAt!=null&&(e.lastLatency={ttftMs:e.lastLatency?.ttftMs??null,totalMs:Date.now()-e.chatStreamStartedAt}),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 OV(e){try{return(await e.request(`models.list`,{}))?.models??[]}catch{return[]}}var kV=`/new`,AV=new Set;function jV(e){return e.chatSending||!!e.chatRunId}function MV(e){return!e.connected||e.tab!=null&&e.tab!==`chat`||e.chatLoading||e.chatSending||e.chatRunId||(e.chatQueue?.length??0)>0||e.chatMessages.length>0?!1:!e.chatStream?.trim()}async function NV(e,t){e.chatLoading=!0;try{await bV(e,t)}finally{e.chatLoading=!1}let n=e.sessionKey;if(n){if(e.chatMessages.length>0){AV.delete(n);return}if(MV(e)&&!AV.has(n)){if(AV.add(n),!await TV(e,kV,void 0,{optimisticUserMessage:!1})){AV.delete(n);return}jz(e,n)}}}async function PV(e){e.connected&&(e.chatMessage=``,await EV(e))}async function FV(e,t,n){aB(e),lF(e);let r=await TV(e,t,n?.attachments),i=!!r;return!i&&n?.previousDraft!=null&&(e.chatMessage=n.previousDraft),!i&&n?.previousAttachments&&(e.chatAttachments=n.previousAttachments),i&&jz(e,e.sessionKey),i&&n?.restoreDraft&&n.previousDraft?.trim()&&(e.chatMessage=n.previousDraft),i&&n?.restoreAttachments&&n.previousAttachments?.length&&(e.chatAttachments=n.previousAttachments),sF(e,!0),i&&!e.chatRunId&&IV(e),i&&n?.refreshSessions&&r&&e.refreshSessionsAfterChat.add(r),i}async function IV(e){if(!e.connected||jV(e))return;let[t,...n]=e.chatQueue;if(!t)return;e.chatQueue=n;let r=!1;try{t.localCommandName?(await LV(e,t.localCommandName,t.localCommandArgs??``),r=!0):r=await FV(e,t.text,{attachments:t.attachments,refreshSessions:t.refreshSessions})}catch(t){e.lastError=String(t)}r?e.chatQueue.length>0&&IV(e):e.chatQueue=[t,...e.chatQueue]}async function LV(e,t,n,r){switch(t){case`stop`:await PV(e);return;case`new`:await FV(e,`/new`,{refreshSessions:!0,previousDraft:r?.previousDraft,restoreDraft:r?.restoreDraft});return;case`reset`:await FV(e,`/reset`,{refreshSessions:!0,previousDraft:r?.previousDraft,restoreDraft:r?.restoreDraft});return;case`clear`:await RV(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 kB(e.client,i,t,n);a.content&&zV(e,a.content),a.sessionPatch&&`modelOverride`in a.sessionPatch&&(e.chatModelOverrides={...e.chatModelOverrides,[i]:a.sessionPatch.modelOverride??null}),a.action===`refresh`&&await BV(e),sF(e)}async function RV(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 NV(e)}catch(t){e.lastError=String(t)}sF(e)}}function zV(e,t){e.chatMessages=[...e.chatMessages,{role:`system`,content:t,timestamp:Date.now()}]}async function BV(e,t){await Promise.all([NV(e),rR(e,{activeMinutes:0,limit:0,includeGlobal:!0,includeUnknown:!0}),GV(e),VV(e)]),t?.scheduleScroll!==!1&&sF(e)}async function VV(e){if(!e.client||!e.connected){e.chatModelsLoading=!1,e.chatModelCatalog=[];return}e.chatModelsLoading=!0;try{e.chatModelCatalog=await OV(e.client)}finally{e.chatModelsLoading=!1}}var HV=IV;function UV(e){let t=rF(e.sessionKey);return t?.agentId?t.agentId:(e.hello?.snapshot)?.sessionDefaults?.defaultAgentId?.trim()||`main`}function WV(e,t){let n=TR(e),r=encodeURIComponent(t);return n?`${n}/avatar/${r}?meta=1`:`avatar/${r}?meta=1`}async function GV(e){if(!e.connected){e.chatAvatarUrl=null;return}let t=UV(e);if(!t){e.chatAvatarUrl=null;return}e.chatAvatarUrl=null;let n=WV(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 KV(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 qV(e,t){if(typeof e!=`string`)return;let n=e.trim();if(n)return n.length<=t?n:n.slice(0,t)}var JV=50,YV=200;function XV(e){let t=qV(e?.name,JV)??`Assistant`,n=qV(e?.avatar??void 0,YV)??null;return{agentId:typeof e?.agentId==`string`&&e.agentId.trim()?e.agentId.trim():null,name:t,avatar:n}}async function ZV(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=XV(t);e.assistantName=n.name,e.assistantAvatar=n.avatar,e.assistantAgentId=n.agentId??null}catch{}}function QV(e){return typeof e==`object`&&!!e}function $V(e){if(!QV(e))return null;let t=typeof e.id==`string`?e.id.trim():``,n=e.request;if(!t||!QV(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 eH(e){if(!QV(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 tH(e){let t=Date.now();return e.filter(e=>e.expiresAtMs>t)}function nH(e,t){let n=tH(e).filter(e=>e.id!==t.id);return n.push(t),n}function rH(e,t){return tH(e).filter(e=>e.id!==t)}var iH={ok:!1,ts:0,durationMs:0,heartbeatSeconds:0,defaultAgentId:``,agents:[],sessions:{path:``,count:0,recent:[]}};async function aH(e){try{return await e.request(`health`,{})??iH}catch{return iH}}async function oH(e){if(!(!e.client||!e.connected)&&!e.healthLoading){e.healthLoading=!0,e.healthError=null;try{e.healthResult=await aH(e.client)}catch(t){e.healthError=String(t)}finally{e.healthLoading=!1}}}function sH(e){return/^(?:typeerror:\s*)?(?:fetch failed|failed to fetch)$/i.test(e.trim())}function cH(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 lH(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 uH(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=lH(e.sessionKey,t),i=lH(e.settings.sessionKey,t),a=lH(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&&Az(e,s)}function dH(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=cH({gatewayUrl:e.settings.gatewayUrl,serverVersion:e.serverVersion}),i=new uV({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,yH(e,n),e.chatRunId=null,e.chatStream=null,e.chatStreamStartedAt=null,aB(e),ZV(e),KF(e),oH(e),DF(e,{quiet:!0}),QL(e,{quiet:!0}),Nz(e),(async()=>{e.userPhone&&await i.request(`user.provision`,{}).catch(()=>{}),await Be(i)})())},onClose:({code:n,reason:r,error:a})=>{if(e.client===i)if(e.connected=!1,e.lastErrorCode=oV(a)??(typeof a?.code==`string`?a.code:null),n!==1012){if(a?.message){e.lastError=e.lastErrorCode&&sH(a.message)?pV({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&&fH(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 fH(e,t){try{vH(e,t)}catch(e){console.error(`[gateway] handleGatewayEvent error:`,t.event,e)}}function pH(e,t,n){if(n!==`final`&&n!==`error`&&n!==`aborted`)return!1;let r=e,i=r.toolStreamOrder.length>0;aB(r),HV(e);let a=t?.runId;return a&&e.refreshSessionsAfterChat.has(a)&&(e.refreshSessionsAfterChat.delete(a),n===`final`&&rR(e,{activeMinutes:120})),i&&n===`final`?(NV(e,{preserveLastLatency:!0}),!0):!1}function mH(e,t){if(!(!e.skillAiChatRunId&&t.state!==`delta`))if(t.state===`delta`){let n=dz(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;let r=e.skillAiBuilderSkillKey,i=new Set(e.skillsReport?.skills.filter(e=>e.source===`openclaw-managed`&&!e.bundled).map(e=>e.skillKey)??[]);(async()=>{await d(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 gH(e,t)})()}else (t.state===`aborted`||t.state===`error`)&&(e.skillAiChatStream=null,e.skillAiChatRunId=null,e.skillAiChatStreamStartedAt=null,e.skillAiChatSending=!1,e.skillAiBuilderBuilding=!1)}var hH=new Set([`write`,`edit`,`apply_patch`]);async function gH(e,t){we(e,t),await Te(e,t,{force:!0});let n=new Set(e.skillFilesLists[t]?.files.map(e=>e.name).filter(Boolean)??[]),r=new Set;for(let t of e.skillAiBuilderOpenTabs)n.has(t)&&r.add(t);let i=e.skillFilesActiveName?.trim();i&&n.has(i)&&r.add(i);for(let n of r)await Ee(e,t,n,{force:!0})}function _H(e,t){t?.sessionKey&&jz(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){mH(n,t);return}}let r=DV(e,t),i=pH(e,t,r);r===`final`&&!i&&KV(t)&&NV(e)}function vH(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`}]}a===`result`&&hH.has(i.trim().toLowerCase())&&t.skillAiBuilderSkillKey&&gH(t,t.skillAiBuilderSkillKey);return}}dB(e,n);return}if(t.event===`chat`){_H(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`&&Wz(e),(t.event===`device.pair.requested`||t.event===`device.pair.resolved`)&&QL(e,{quiet:!0}),t.event===`exec.approval.requested`){let n=$V(t.payload);if(n){e.execApprovalQueue=nH(e.execApprovalQueue,n),e.execApprovalError=null;let t=Math.max(0,n.expiresAtMs-Date.now()+500);window.setTimeout(()=>{e.execApprovalQueue=rH(e.execApprovalQueue,n.id)},t)}return}if(t.event===`exec.approval.resolved`){let n=eH(t.payload);n&&(e.execApprovalQueue=rH(e.execApprovalQueue,n.id));return}t.event===`update.available`&&(e.updateAvailable=t.payload?.updateAvailable??null)}function yH(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&&uH(e,n.sessionDefaults),e.updateAvailable=n?.updateAvailable??null}var bH=`/__openclaw/control-ui-config.json`;async function xH(e){if(typeof window>`u`||typeof fetch!=`function`)return;let t=TR(e.basePath??``),n=t?`${t}${bH}`:bH;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=XV({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{}}function SH(e){return e.replace(/^http:\/\//i,`ws://`).replace(/^https:\/\//i,`wss://`)}function CH(e,t){e.themeResolved=t;let n=t.endsWith(`light`)?`light`:`dark`;e.dataset.theme=t,e.dataset.themeMode=n,e.style.colorScheme=n}function wH(e){if(e.themeMode!==`system`){e.systemThemeCleanup?.(),e.systemThemeCleanup=null;return}if(e.systemThemeCleanup||typeof globalThis.matchMedia!=`function`)return;let t=globalThis.matchMedia(`(prefers-color-scheme: light)`),n=()=>{e.themeMode===`system`&&CH(e,FR(e.theme,`system`))};if(typeof t.addEventListener==`function`){t.addEventListener(`change`,n),e.systemThemeCleanup=()=>t.removeEventListener(`change`,n);return}try{t.addListener(n),e.systemThemeCleanup=()=>t.removeListener(n)}catch{}}function TH(e){e.theme=e.settings.theme??`dash`,e.themeMode=e.settings.themeMode??`system`,CH(e,FR(e.theme,e.themeMode)),wH(e)}function EH(e){if(!e.endpoint)return;let t=SH(e.endpoint);e.settings={...e.settings,gatewayUrl:t},e.token&&(YR(t,e.token),e.settings={...e.settings,token:e.token})}var DH=class extends DA{constructor(...e){super(...e),this.endpoint=``,this.token=``,this.theme=`dash`,this.clientInstanceId=Ie(),this.connectGeneration=0,this.settings=ZR(),this.connected=!1,this.hello=null,this.lastError=null,this.lastErrorCode=null,this.themeMode=`system`,this.themeResolved=`dash-dark`,this.themeOrder=[...kR],this.pendingGatewayUrl=null,this.systemThemeCleanup=null,this.pendingGatewayToken=null,this.basePath=``,this.client=null,this.password=``,this.serverVersion=null,this.assistantName=``,this.assistantAvatar=null,this.assistantAgentId=null,this.noUrlSync=!0,this.chatRunId=null,this.chatQueue=[],this.refreshSessionsAfterChat=new Set,this.eventLogBuffer=[],this.eventLog=[],this.presenceEntries=[],this.presenceError=null,this.presenceStatus=null,this.agentsLoading=!1,this.agentsList=null,this.agentsError=null,this.healthLoading=!1,this.healthResult=null,this.healthError=null,this.debugHealth=null,this.execApprovalQueue=[],this.execApprovalError=null,this.updateAvailable=null,this.gatewayBootstrapDone=!1}createRenderRoot(){return this}beforeGatewayConnectSetup(){}afterGatewayConnected(){}shouldReconnectOnPropChange(){return this.gatewayBootstrapDone}startEmbeddedGatewayConnection(){EH(this),this.settings={...this.settings,theme:this.theme},this.gatewayBootstrapDone=!1,++this.connectGeneration;let e=this.connectGeneration;TH(this),xH(this).finally(()=>{this.connectGeneration===e&&(this.gatewayBootstrapDone=!0,dH(this))})}stopEmbeddedGatewayConnection(){this.connectGeneration+=1,this.client?.stop(),this.client=null,this.connected=!1,Pz(this)}handleEmbeddedGatewayUpdates(e){this.shouldReconnectOnPropChange()&&(e.has(`endpoint`)||e.has(`token`))&&(EH(this),this.endpoint&&dH(this)),e.has(`theme`)&&(this.settings={...this.settings,theme:this.theme},TH(this)),e.has(`connected`)&&this.connected&&this.afterGatewayConnected()}connectedCallback(){super.connectedCallback(),this.beforeGatewayConnectSetup(),this.startEmbeddedGatewayConnection()}disconnectedCallback(){super.disconnectedCallback(),this.stopEmbeddedGatewayConnection()}updated(e){super.updated(e),this.handleEmbeddedGatewayUpdates(e)}};J([MA({type:String})],DH.prototype,`endpoint`,void 0),J([MA({type:String})],DH.prototype,`token`,void 0),J([MA({type:String})],DH.prototype,`theme`,void 0),J([q()],DH.prototype,`settings`,void 0),J([q()],DH.prototype,`connected`,void 0),J([q()],DH.prototype,`hello`,void 0),J([q()],DH.prototype,`lastError`,void 0),J([q()],DH.prototype,`lastErrorCode`,void 0),J([q()],DH.prototype,`themeMode`,void 0),J([q()],DH.prototype,`themeResolved`,void 0),J([q()],DH.prototype,`themeOrder`,void 0),J([q()],DH.prototype,`pendingGatewayUrl`,void 0),J([q()],DH.prototype,`systemThemeCleanup`,void 0);var $=class extends DH{constructor(...e){super(...e),this._sessionKey=`agent:skill-creator`,this.tab=`skills`,this.toolStreamById=new Map,this.toolStreamOrder=[],this.toolStreamSyncTimer=null,this.chatToolMessages=[],this.chatStreamSegments=[],this.applySessionKey=``,this.skillsLoading=!1,this.skillsReport=null,this.skillsError=null,this.skillsFilter=``,this.skillEdits={},this.skillsBusyKey=null,this.skillMessages={},this.skillsTab=`personal`,this.skillMenuOpenKey=null,this.teamSkillsLoading=!1,this.teamSkillsReport=null,this.teamSkillsError=null,this.teamSkillsSyncBusyKey=null,this.teamSkillsSyncedKeys=[],this.teamOrganizationId=null,this.skillFilesLists={},this.skillFilesContents={},this.skillFilesDrafts={},this.skillFilesActiveKey=null,this.skillFilesActiveName=null,this.skillFilesActiveDir=null,this.skillFilesLoading=!1,this.skillFilesSaving=!1,this.skillFilesError=null,this.skillFilesFullscreen=!1,this.skillFilesBackConfirm=!1,this.skillCreateMode=!1,this.skillCreateName=``,this.skillCreateDesc=``,this.skillCreateBusy=!1,this.skillCreateError=null,this.skillAiDialogOpen=!1,this.skillAiFormName=``,this.skillAiFormDesc=``,this.skillAiFormTrigger=``,this.skillAiFormInstruction=``,this.skillAiFormExample=``,this.skillAiInstructionReferences=[],this.skillAiDialogFullscreenField=null,this.skillAiFormError=null,this.skillAiBuilderMode=!1,this.skillAiBuilderSkillKey=null,this.skillAiBuilderBuilding=!1,this.skillAiBuilderActiveTab=`chat`,this.skillAiBuilderOpenTabs=[],this.skillAiChatMessages=[],this.skillAiChatStream=null,this.skillAiChatSending=!1,this.skillAiChatRunId=null,this.skillAiChatMessage=``,this.skillAiChatReferences=[],this.skillAiReferenceMode=`hidden`,this.skillAiReferenceTargetField=`chat`,this.skillAiReferenceActiveApiId=null,this.skillAiReferenceSelectedIndex=0,this.skillAiReferenceMatchFrom=null,this.skillAiReferenceMatchTo=null,this.skillAiReferenceQuery=``,this.skillAiChatStreamStartedAt=null,this.skillAiToolCalls=[],this.skillAiBuilderExitConfirm=!1,this.skillUploadBusy=!1,this.skillUploadError=null,this.skillUploadOverwriteKey=null,this.skillUploadPendingFile=null,this.skillDeleteConfirmKey=null,this.skillExportBusyKey=null,this.apiDefinitionsItems=[],this.apiDefinitionsPath=null,this.apiDefinitionsLoading=!1,this.apiDefinitionsError=null,this.apiDefinitionsHash=null,this.apiDefinitionsToast=null,this.apiDefinitionsToastKind=`error`,this.apiDefinitionsQuery=``}get sessionKey(){return this._sessionKey}set sessionKey(e){}afterGatewayConnected(){d(this),te(this),a(this)}render(){return G`
1843
+ `)}}catch(e){return{content:`Failed to list agents: ${String(e)}`}}}async function RB(e,t,n){let r=n.trim();if(!r)return{content:"Usage: `/kill <id|all>`"};try{let n=zB((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 zB(e,t,n){let r=n.trim().toLowerCase();if(!r)return[];let i=new Set,a=t.trim().toLowerCase(),o=rF(a)?.agentId??(a===`main`?`main`:void 0),s=VB(e);for(let t of e){let e=t?.key?.trim();if(!e||!iF(e))continue;let n=e.toLowerCase(),c=rF(n),l=BB(n,a,s,o,c?.agentId);(r===`all`&&l||l&&n===r||l&&((c?.agentId??``)===r||n.endsWith(`:subagent:${r}`)||n===`subagent:${r}`))&&i.add(e)}return[...i]}function BB(e,t,n,r,i){if(!r||i!==r)return!1;let a=UB(t,r),o=new Set,s=HB(n.get(e)?.spawnedBy);for(;s&&!o.has(s);){if(a.has(s))return!0;o.add(s),s=HB(n.get(s)?.spawnedBy)}return iF(t)?e.startsWith(`${t}:subagent:`):!1}function VB(e){let t=new Map;for(let n of e){let e=HB(n?.key);e&&t.set(e,n)}return t}function HB(e){return e?.trim().toLowerCase()||void 0}function UB(e,t){let n=new Set([e]);if(t===`main`){let t=`agent:${wB}:main`;e===`main`?n.add(t):e===t&&n.add(TB)}return n}function WB(e,t){return`${e}\nOptions: ${t}.`}async function GB(e,t){return KB(await e.request(`sessions.list`,{}),t)}function KB(e,t){let n=HB(t),r=rF(n??``)?.agentId??(n===`main`?`main`:void 0),i=n?UB(n,r):new Set;return e?.sessions?.find(e=>{let t=HB(e.key);return t?i.has(t):!1})}async function qB(e,t){let[n,r]=await Promise.all([e.request(`sessions.list`,{}),e.request(`models.list`,{})]);return{session:KB(n,t),models:r?.models??[]}}function JB(e,t){return _B(e?.thinkingLevel)||(!e?.modelProvider||!e.model?`off`:xB({provider:e.modelProvider,model:e.model,catalog:t}))}function YB(e){return e?.fastMode===!0?`on`:`off`}function XB(e){return e>=1e6?`${(e/1e6).toFixed(1).replace(/\.0$/,``)}M`:e>=1e3?`${(e/1e3).toFixed(1).replace(/\.0$/,``)}k`:String(e)}var ZB={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`},QB=new Set([`retry_with_device_token`,`update_auth_configuration`,`update_auth_credentials`,`wait_then_retry`,`review_auth_configuration`]);function $B(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 eV(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:QB.has(r)?r:void 0}}function tV(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 nV={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`},rV=nV,iV={WEBCHAT:`webchat`,CLI:`cli`,UI:`ui`,BACKEND:`backend`,NODE:`node`,PROBE:`probe`,TEST:`test`};new Set(Object.values(nV)),new Set(Object.values(iV));var aV=class extends Error{constructor(e){super(e.message),this.name=`GatewayRequestError`,this.gatewayCode=e.code,this.details=e.details}};function oV(e){return $B(e?.details)}function sV(e){if(!e)return!1;let t=oV(e);return t===ZB.AUTH_TOKEN_MISSING||t===ZB.AUTH_BOOTSTRAP_TOKEN_INVALID||t===ZB.AUTH_PASSWORD_MISSING||t===ZB.AUTH_PASSWORD_MISMATCH||t===ZB.AUTH_RATE_LIMITED||t===ZB.PAIRING_REQUIRED||t===ZB.CONTROL_UI_DEVICE_IDENTITY_REQUIRED||t===ZB.DEVICE_IDENTITY_REQUIRED}function cV(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 lV=4008,uV=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}),!(oV(n)===ZB.AUTH_TOKEN_MISMATCH&&this.deviceTokenRetryBudgetUsed&&!this.pendingDeviceTokenRetry)&&(sV(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 XL(),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=tV({deviceId:a.deviceId,clientId:this.opts.clientName??rV.CONTROL_UI,clientMode:this.opts.mode??iV.WEBCHAT,role:n,scopes:t,signedAtMs:e,token:s??null,nonce:r}),o=await ZL(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??rV.CONTROL_UI,version:this.opts.clientVersion??`control-ui`,platform:this.opts.platform??navigator.platform??`web`,mode:this.opts.mode??iV.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&&PI({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 aV?oV(e):null,i=e instanceof aV?eV(e.details):{},s=i.recommendedNextStep===`retry_with_device_token`,c=i.canRetryWithDeviceToken===!0||s||t===ZB.AUTH_TOKEN_MISMATCH;!this.deviceTokenRetryBudgetUsed&&!o.authDeviceToken&&r&&a&&o.storedToken&&c&&cV(this.opts.url)&&(this.pendingDeviceTokenRetry=!0,this.deviceTokenRetryBudgetUsed=!0),e instanceof aV?this.pendingConnectError={code:e.gatewayCode,message:e.message,details:e.details}:this.pendingConnectError=void 0,o.canFallbackToShared&&a&&t===ZB.AUTH_DEVICE_TOKEN_MISMATCH&&FI({deviceId:a.deviceId,role:n}),this.ws?.close(lV,`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 aV({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=NI({deviceId:e.deviceId,role:e.role})?.token,i=this.pendingDeviceTokenRetry&&!!t&&!!r&&cV(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=Ie(),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 dV(e){return typeof e==`string`?e:e instanceof Error&&typeof e.message==`string`?e.message:`unknown error`}function fV(e){let t=dV(e.message);switch(oV(e)){case ZB.AUTH_TOKEN_MISMATCH:return`gateway token mismatch`;case ZB.AUTH_UNAUTHORIZED:return`gateway auth failed`;case ZB.AUTH_RATE_LIMITED:return`too many failed authentication attempts`;case ZB.PAIRING_REQUIRED:return`gateway pairing required`;case ZB.CONTROL_UI_DEVICE_IDENTITY_REQUIRED:return`device identity required (use HTTPS/localhost or allow insecure auth explicitly)`;case ZB.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 ZB.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 pV(e){return e&&typeof e==`object`?fV(e):dV(e)}var mV=/^\s*NO_REPLY\s*$/;function hV(e){return mV.test(e)}function gV(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 hV(t.text);let n=dz(e);return typeof n==`string`&&hV(n)}function _V(e){for(let t=e.length-1;t>=0;--t){let n=e[t];if(!n||typeof n!=`object`)continue;let r=n;if((typeof r.role==`string`?r.role.toLowerCase():``)!==`assistant`)continue;let i=r.__runLatency&&typeof r.__runLatency==`object`?r.__runLatency:null;return typeof i?.ttftMs==`number`||typeof i?.totalMs==`number`}return!1}function vV(e,t){if(!t)return e;for(let n=e.length-1;n>=0;--n){let r=e[n];if(!r||typeof r!=`object`)continue;let i=r;if((typeof i.role==`string`?i.role.toLowerCase():``)!==`assistant`)continue;let a=[...e];return a[n]={...i,__runLatency:{ttftMs:t.ttftMs,totalMs:t.totalMs}},a}return e}function yV(e){let t=e;t.toolStreamById instanceof Map&&Array.isArray(t.toolStreamOrder)&&Array.isArray(t.chatToolMessages)&&Array.isArray(t.chatStreamSegments)&&aB(t)}async function bV(e,t){if(!(!e.client||!e.connected)){e.chatLoading=!0,e.lastError=null;try{let n=await e.client.request(`chat.history`,{sessionKey:e.sessionKey,limit:200}),r=(Array.isArray(n.messages)?n.messages:[]).filter(e=>!gV(e));e.chatMessages=t?.preserveLastLatency&&!_V(r)?vV(r,e.lastLatency):r,e.chatThinkingLevel=n.thinkingLevel??null,yV(e),e.chatStream=null,e.chatStreamStartedAt=null,t?.preserveLastLatency&&!_V(r)||(e.lastLatency=null)}catch(t){e.lastError=String(t)}finally{e.chatLoading=!1}}}function xV(e){let t=/^data:([^;]+);base64,(.+)$/.exec(e);return t?{mimeType:t[1],content:t[2]}:null}function SV(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 CV(e){return SV(e,{roleRequirement:`required`,roleCaseSensitive:!0,requireContentArray:!0})}function wV(e){return SV(e,{roleRequirement:`optional`,allowTextField:!0})}async function TV(e,t,n,r){if(!e.client||!e.connected)return null;let i=t.trim(),a=n&&n.length>0;if(!i&&!a)return null;let o=Date.now(),s=[];if(i&&s.push({type:`text`,text:i}),a)for(let e of n)s.push({type:`image`,source:{type:`base64`,media_type:e.mimeType,data:e.dataUrl}});r?.optimisticUserMessage!==!1&&(e.chatMessages=[...e.chatMessages,{role:`user`,content:s,timestamp:o}]),e.chatSending=!0,e.lastError=null,e.lastLatency=null;let c=Ie();e.chatRunId=c,e.chatStream=``,e.chatStreamStartedAt=o;let l=a?n.map(e=>{let t=xV(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:i,deliver:!1,idempotencyKey:c,attachments:l,clientSentAt:o}),c}catch(t){let n=pV(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 EV(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=pV(t),!1}}function DV(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=wV(t.message);return n&&!gV(n)?(e.chatMessages=[...e.chatMessages,n],null):`final`}return null}if(t.state===`delta`){t.retract&&(e.chatStream=null);let n=dz(t.message);if(typeof n==`string`&&!hV(n)){let t=e.chatStream??``;(!t||n.length>=t.length)&&(e.chatStream=n)}t.firstTokenAt!=null&&e.chatStreamStartedAt!=null&&!e.lastLatency&&(e.lastLatency={ttftMs:t.firstTokenAt-e.chatStreamStartedAt,totalMs:null})}else if(t.state===`final`){let n=wV(t.message),r=e.chatStreamStartedAt==null?null:{ttftMs:t.firstTokenAt==null?null:t.firstTokenAt-e.chatStreamStartedAt,totalMs:t.endedAt==null?null:t.endedAt-e.chatStreamStartedAt};if(n&&!gV(n))r&&(n.__runLatency=r),e.chatMessages=[...e.chatMessages,n];else if(e.chatStream?.trim()&&!hV(e.chatStream)){let t={role:`assistant`,content:[{type:`text`,text:e.chatStream}],timestamp:Date.now()};r&&(t.__runLatency=r),e.chatMessages=[...e.chatMessages,t]}e.lastLatency=r,e.chatStream=null,e.chatRunId=null,e.chatStreamStartedAt=null}else if(t.state===`aborted`){let n=CV(t.message);if(n&&!gV(n))e.chatMessages=[...e.chatMessages,n];else{let t=e.chatStream??``;t.trim()&&!hV(t)&&(e.chatMessages=[...e.chatMessages,{role:`assistant`,content:[{type:`text`,text:t}],timestamp:Date.now()}])}e.chatStreamStartedAt!=null&&(e.lastLatency={ttftMs:e.lastLatency?.ttftMs??null,totalMs:Date.now()-e.chatStreamStartedAt}),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 OV(e){try{return(await e.request(`models.list`,{}))?.models??[]}catch{return[]}}var kV=`/new`,AV=new Set;function jV(e){return e.chatSending||!!e.chatRunId}function MV(e){return!e.connected||e.tab!=null&&e.tab!==`chat`||e.chatLoading||e.chatSending||e.chatRunId||(e.chatQueue?.length??0)>0||e.chatMessages.length>0?!1:!e.chatStream?.trim()}async function NV(e,t){e.chatLoading=!0;try{await bV(e,t)}finally{e.chatLoading=!1}let n=e.sessionKey;if(n){if(e.chatMessages.length>0){AV.delete(n);return}if(MV(e)&&!AV.has(n)){if(AV.add(n),!await TV(e,kV,void 0,{optimisticUserMessage:!1})){AV.delete(n);return}jz(e,n)}}}async function PV(e){e.connected&&(e.chatMessage=``,await EV(e))}async function FV(e,t,n){aB(e),lF(e);let r=await TV(e,t,n?.attachments),i=!!r;return!i&&n?.previousDraft!=null&&(e.chatMessage=n.previousDraft),!i&&n?.previousAttachments&&(e.chatAttachments=n.previousAttachments),i&&jz(e,e.sessionKey),i&&n?.restoreDraft&&n.previousDraft?.trim()&&(e.chatMessage=n.previousDraft),i&&n?.restoreAttachments&&n.previousAttachments?.length&&(e.chatAttachments=n.previousAttachments),sF(e,!0),i&&!e.chatRunId&&IV(e),i&&n?.refreshSessions&&r&&e.refreshSessionsAfterChat.add(r),i}async function IV(e){if(!e.connected||jV(e))return;let[t,...n]=e.chatQueue;if(!t)return;e.chatQueue=n;let r=!1;try{t.localCommandName?(await LV(e,t.localCommandName,t.localCommandArgs??``),r=!0):r=await FV(e,t.text,{attachments:t.attachments,refreshSessions:t.refreshSessions})}catch(t){e.lastError=String(t)}r?e.chatQueue.length>0&&IV(e):e.chatQueue=[t,...e.chatQueue]}async function LV(e,t,n,r){switch(t){case`stop`:await PV(e);return;case`new`:await FV(e,`/new`,{refreshSessions:!0,previousDraft:r?.previousDraft,restoreDraft:r?.restoreDraft});return;case`reset`:await FV(e,`/reset`,{refreshSessions:!0,previousDraft:r?.previousDraft,restoreDraft:r?.restoreDraft});return;case`clear`:await RV(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 kB(e.client,i,t,n);a.content&&zV(e,a.content),a.sessionPatch&&`modelOverride`in a.sessionPatch&&(e.chatModelOverrides={...e.chatModelOverrides,[i]:a.sessionPatch.modelOverride??null}),a.action===`refresh`&&await BV(e),sF(e)}async function RV(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 NV(e)}catch(t){e.lastError=String(t)}sF(e)}}function zV(e,t){e.chatMessages=[...e.chatMessages,{role:`system`,content:t,timestamp:Date.now()}]}async function BV(e,t){await Promise.all([NV(e),rR(e,{activeMinutes:0,limit:0,includeGlobal:!0,includeUnknown:!0}),GV(e),VV(e)]),t?.scheduleScroll!==!1&&sF(e)}async function VV(e){if(!e.client||!e.connected){e.chatModelsLoading=!1,e.chatModelCatalog=[];return}e.chatModelsLoading=!0;try{e.chatModelCatalog=await OV(e.client)}finally{e.chatModelsLoading=!1}}var HV=IV;function UV(e){let t=rF(e.sessionKey);return t?.agentId?t.agentId:(e.hello?.snapshot)?.sessionDefaults?.defaultAgentId?.trim()||`main`}function WV(e,t){let n=TR(e),r=encodeURIComponent(t);return n?`${n}/avatar/${r}?meta=1`:`avatar/${r}?meta=1`}async function GV(e){if(!e.connected){e.chatAvatarUrl=null;return}let t=UV(e);if(!t){e.chatAvatarUrl=null;return}e.chatAvatarUrl=null;let n=WV(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 KV(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 qV(e,t){if(typeof e!=`string`)return;let n=e.trim();if(n)return n.length<=t?n:n.slice(0,t)}var JV=50,YV=200;function XV(e){let t=qV(e?.name,JV)??`Assistant`,n=qV(e?.avatar??void 0,YV)??null;return{agentId:typeof e?.agentId==`string`&&e.agentId.trim()?e.agentId.trim():null,name:t,avatar:n}}async function ZV(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=XV(t);e.assistantName=n.name,e.assistantAvatar=n.avatar,e.assistantAgentId=n.agentId??null}catch{}}function QV(e){return typeof e==`object`&&!!e}function $V(e){if(!QV(e))return null;let t=typeof e.id==`string`?e.id.trim():``,n=e.request;if(!t||!QV(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 eH(e){if(!QV(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 tH(e){let t=Date.now();return e.filter(e=>e.expiresAtMs>t)}function nH(e,t){let n=tH(e).filter(e=>e.id!==t.id);return n.push(t),n}function rH(e,t){return tH(e).filter(e=>e.id!==t)}var iH={ok:!1,ts:0,durationMs:0,heartbeatSeconds:0,defaultAgentId:``,agents:[],sessions:{path:``,count:0,recent:[]}};async function aH(e){try{return await e.request(`health`,{})??iH}catch{return iH}}async function oH(e){if(!(!e.client||!e.connected)&&!e.healthLoading){e.healthLoading=!0,e.healthError=null;try{e.healthResult=await aH(e.client)}catch(t){e.healthError=String(t)}finally{e.healthLoading=!1}}}function sH(e){return/^(?:typeerror:\s*)?(?:fetch failed|failed to fetch)$/i.test(e.trim())}function cH(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 lH(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 uH(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=lH(e.sessionKey,t),i=lH(e.settings.sessionKey,t),a=lH(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&&Az(e,s)}function dH(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=cH({gatewayUrl:e.settings.gatewayUrl,serverVersion:e.serverVersion}),i=new uV({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,yH(e,n),e.chatRunId=null,e.chatStream=null,e.chatStreamStartedAt=null,aB(e),ZV(e),KF(e),oH(e),DF(e,{quiet:!0}),QL(e,{quiet:!0}),Nz(e),(async()=>{e.userPhone&&await i.request(`user.provision`,{}).catch(()=>{}),await Be(i)})())},onClose:({code:n,reason:r,error:a})=>{if(e.client===i)if(e.connected=!1,e.lastErrorCode=oV(a)??(typeof a?.code==`string`?a.code:null),n!==1012){if(a?.message){e.lastError=e.lastErrorCode&&sH(a.message)?pV({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&&fH(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 fH(e,t){try{vH(e,t)}catch(e){console.error(`[gateway] handleGatewayEvent error:`,t.event,e)}}function pH(e,t,n){if(n!==`final`&&n!==`error`&&n!==`aborted`)return!1;let r=e,i=r.toolStreamOrder.length>0;aB(r),HV(e);let a=t?.runId;return a&&e.refreshSessionsAfterChat.has(a)&&(e.refreshSessionsAfterChat.delete(a),n===`final`&&rR(e,{activeMinutes:120})),i&&n===`final`?(NV(e,{preserveLastLatency:!0}),!0):!1}function mH(e,t){if(!(!e.skillAiChatRunId&&t.state!==`delta`))if(t.state===`delta`){let n=dz(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;let r=e.skillAiBuilderSkillKey,i=new Set(e.skillsReport?.skills.filter(e=>e.source===`openclaw-managed`&&!e.bundled).map(e=>e.skillKey)??[]);(async()=>{await d(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 gH(e,t)})()}else (t.state===`aborted`||t.state===`error`)&&(e.skillAiChatStream=null,e.skillAiChatRunId=null,e.skillAiChatStreamStartedAt=null,e.skillAiChatSending=!1,e.skillAiBuilderBuilding=!1)}var hH=new Set([`write`,`edit`,`apply_patch`]);async function gH(e,t){we(e,t),await Te(e,t,{force:!0});let n=new Set(e.skillFilesLists[t]?.files.map(e=>e.name).filter(Boolean)??[]),r=new Set;for(let t of e.skillAiBuilderOpenTabs)n.has(t)&&r.add(t);let i=e.skillFilesActiveName?.trim();i&&n.has(i)&&r.add(i);for(let n of r)await Ee(e,t,n,{force:!0})}function _H(e,t){t?.sessionKey&&jz(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){mH(n,t);return}}let r=DV(e,t),i=pH(e,t,r);r===`final`&&!i&&KV(t)&&NV(e)}function vH(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`}]}a===`result`&&hH.has(i.trim().toLowerCase())&&t.skillAiBuilderSkillKey&&gH(t,t.skillAiBuilderSkillKey);return}}dB(e,n);return}if(t.event===`chat`){_H(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`&&Wz(e),(t.event===`device.pair.requested`||t.event===`device.pair.resolved`)&&QL(e,{quiet:!0}),t.event===`exec.approval.requested`){let n=$V(t.payload);if(n){e.execApprovalQueue=nH(e.execApprovalQueue,n),e.execApprovalError=null;let t=Math.max(0,n.expiresAtMs-Date.now()+500);window.setTimeout(()=>{e.execApprovalQueue=rH(e.execApprovalQueue,n.id)},t)}return}if(t.event===`exec.approval.resolved`){let n=eH(t.payload);n&&(e.execApprovalQueue=rH(e.execApprovalQueue,n.id));return}t.event===`update.available`&&(e.updateAvailable=t.payload?.updateAvailable??null)}function yH(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&&uH(e,n.sessionDefaults),e.updateAvailable=n?.updateAvailable??null}var bH=`/__openclaw/control-ui-config.json`;async function xH(e){if(typeof window>`u`||typeof fetch!=`function`)return;let t=TR(e.basePath??``),n=t?`${t}${bH}`:bH;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=XV({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{}}function SH(e){return e.replace(/^http:\/\//i,`ws://`).replace(/^https:\/\//i,`wss://`)}function CH(e,t){e.themeResolved=t;let n=t.endsWith(`light`)?`light`:`dark`;e.dataset.theme=t,e.dataset.themeMode=n,e.style.colorScheme=n}function wH(e){if(e.themeMode!==`system`){e.systemThemeCleanup?.(),e.systemThemeCleanup=null;return}if(e.systemThemeCleanup||typeof globalThis.matchMedia!=`function`)return;let t=globalThis.matchMedia(`(prefers-color-scheme: light)`),n=()=>{e.themeMode===`system`&&CH(e,FR(e.theme,`system`))};if(typeof t.addEventListener==`function`){t.addEventListener(`change`,n),e.systemThemeCleanup=()=>t.removeEventListener(`change`,n);return}try{t.addListener(n),e.systemThemeCleanup=()=>t.removeListener(n)}catch{}}function TH(e){e.theme=e.settings.theme??`dash`,e.themeMode=e.settings.themeMode??`system`,CH(e,FR(e.theme,e.themeMode)),wH(e)}function EH(e){if(!e.endpoint)return;let t=SH(e.endpoint);e.settings={...e.settings,gatewayUrl:t},e.token&&(YR(t,e.token),e.settings={...e.settings,token:e.token})}var DH=class extends DA{constructor(...e){super(...e),this.endpoint=``,this.token=``,this.theme=`dash`,this.clientInstanceId=Ie(),this.connectGeneration=0,this.settings=ZR(),this.connected=!1,this.hello=null,this.lastError=null,this.lastErrorCode=null,this.themeMode=`system`,this.themeResolved=`dash-dark`,this.themeOrder=[...kR],this.pendingGatewayUrl=null,this.systemThemeCleanup=null,this.pendingGatewayToken=null,this.basePath=``,this.client=null,this.password=``,this.serverVersion=null,this.assistantName=``,this.assistantAvatar=null,this.assistantAgentId=null,this.noUrlSync=!0,this.chatRunId=null,this.chatQueue=[],this.refreshSessionsAfterChat=new Set,this.eventLogBuffer=[],this.eventLog=[],this.presenceEntries=[],this.presenceError=null,this.presenceStatus=null,this.agentsLoading=!1,this.agentsList=null,this.agentsError=null,this.healthLoading=!1,this.healthResult=null,this.healthError=null,this.debugHealth=null,this.execApprovalQueue=[],this.execApprovalError=null,this.updateAvailable=null,this.gatewayBootstrapDone=!1}createRenderRoot(){return this}beforeGatewayConnectSetup(){}afterGatewayConnected(){}shouldReconnectOnPropChange(){return this.gatewayBootstrapDone}startEmbeddedGatewayConnection(){EH(this),this.settings={...this.settings,theme:this.theme},this.gatewayBootstrapDone=!1,++this.connectGeneration;let e=this.connectGeneration;TH(this),xH(this).finally(()=>{this.connectGeneration===e&&(this.gatewayBootstrapDone=!0,dH(this))})}stopEmbeddedGatewayConnection(){this.connectGeneration+=1,this.client?.stop(),this.client=null,this.connected=!1,Pz(this)}handleEmbeddedGatewayUpdates(e){this.shouldReconnectOnPropChange()&&(e.has(`endpoint`)||e.has(`token`))&&(EH(this),this.endpoint&&dH(this)),e.has(`theme`)&&(this.settings={...this.settings,theme:this.theme},TH(this)),e.has(`connected`)&&this.connected&&this.afterGatewayConnected()}connectedCallback(){super.connectedCallback(),this.beforeGatewayConnectSetup(),this.startEmbeddedGatewayConnection()}disconnectedCallback(){super.disconnectedCallback(),this.stopEmbeddedGatewayConnection()}updated(e){super.updated(e),this.handleEmbeddedGatewayUpdates(e)}};J([MA({type:String})],DH.prototype,`endpoint`,void 0),J([MA({type:String})],DH.prototype,`token`,void 0),J([MA({type:String})],DH.prototype,`theme`,void 0),J([q()],DH.prototype,`settings`,void 0),J([q()],DH.prototype,`connected`,void 0),J([q()],DH.prototype,`hello`,void 0),J([q()],DH.prototype,`lastError`,void 0),J([q()],DH.prototype,`lastErrorCode`,void 0),J([q()],DH.prototype,`themeMode`,void 0),J([q()],DH.prototype,`themeResolved`,void 0),J([q()],DH.prototype,`themeOrder`,void 0),J([q()],DH.prototype,`pendingGatewayUrl`,void 0),J([q()],DH.prototype,`systemThemeCleanup`,void 0);var $=class extends DH{constructor(...e){super(...e),this._sessionKey=`agent:skill-creator`,this.tab=`skills`,this.toolStreamById=new Map,this.toolStreamOrder=[],this.toolStreamSyncTimer=null,this.chatToolMessages=[],this.chatStreamSegments=[],this.applySessionKey=``,this.skillsLoading=!1,this.skillsReport=null,this.skillsError=null,this.skillsFilter=``,this.skillsViewMode=`card`,this.skillEdits={},this.skillsBusyKey=null,this.skillMessages={},this.skillsTab=`personal`,this.skillMenuOpenKey=null,this.teamSkillsLoading=!1,this.teamSkillsReport=null,this.teamSkillsError=null,this.teamSkillsSyncBusyKey=null,this.teamSkillsSyncedKeys=[],this.teamOrganizationId=null,this.skillFilesLists={},this.skillFilesContents={},this.skillFilesDrafts={},this.skillFilesActiveKey=null,this.skillFilesActiveName=null,this.skillFilesActiveDir=null,this.skillFilesLoading=!1,this.skillFilesSaving=!1,this.skillFilesError=null,this.skillFilesFullscreen=!1,this.skillFilesBackConfirm=!1,this.skillCreateMode=!1,this.skillCreateName=``,this.skillCreateDesc=``,this.skillCreateBusy=!1,this.skillCreateError=null,this.skillAiDialogOpen=!1,this.skillAiFormName=``,this.skillAiFormDesc=``,this.skillAiFormTrigger=``,this.skillAiFormInstruction=``,this.skillAiFormExample=``,this.skillAiInstructionReferences=[],this.skillAiDialogFullscreenField=null,this.skillAiFormError=null,this.skillAiBuilderMode=!1,this.skillAiBuilderSkillKey=null,this.skillAiBuilderBuilding=!1,this.skillAiBuilderActiveTab=`chat`,this.skillAiBuilderOpenTabs=[],this.skillAiChatMessages=[],this.skillAiChatStream=null,this.skillAiChatSending=!1,this.skillAiChatRunId=null,this.skillAiChatMessage=``,this.skillAiChatReferences=[],this.skillAiReferenceMode=`hidden`,this.skillAiReferenceTargetField=`chat`,this.skillAiReferenceActiveApiId=null,this.skillAiReferenceSelectedIndex=0,this.skillAiReferenceMatchFrom=null,this.skillAiReferenceMatchTo=null,this.skillAiReferenceQuery=``,this.skillAiChatStreamStartedAt=null,this.skillAiToolCalls=[],this.skillAiBuilderExitConfirm=!1,this.skillUploadBusy=!1,this.skillUploadError=null,this.skillUploadOverwriteKey=null,this.skillUploadPendingFile=null,this.skillDeleteConfirmKey=null,this.skillExportBusyKey=null,this.apiDefinitionsItems=[],this.apiDefinitionsPath=null,this.apiDefinitionsLoading=!1,this.apiDefinitionsError=null,this.apiDefinitionsHash=null,this.apiDefinitionsToast=null,this.apiDefinitionsToastKind=`error`,this.apiDefinitionsQuery=``}get sessionKey(){return this._sessionKey}set sessionKey(e){}afterGatewayConnected(){d(this),te(this),a(this)}render(){return G`
1844
1844
  <div class="keyueclaw-skills-scope">${IP(at(this))}</div>
1845
1845
  ${this._renderToast()}
1846
1846
  `}_renderToast(){if(!this.apiDefinitionsToast)return K;let e=this.apiDefinitionsToastKind===`success`,t=e?`#16a34a`:`var(--keyueclaw-accent)`;return G`
@@ -1852,5 +1852,5 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
1852
1852
  @click=${()=>{this.apiDefinitionsToast=null}}>✕</button>
1853
1853
  </div>
1854
1854
  </div>
1855
- `}};J([q()],$.prototype,`skillsLoading`,void 0),J([q()],$.prototype,`skillsReport`,void 0),J([q()],$.prototype,`skillsError`,void 0),J([q()],$.prototype,`skillsFilter`,void 0),J([q()],$.prototype,`skillEdits`,void 0),J([q()],$.prototype,`skillsBusyKey`,void 0),J([q()],$.prototype,`skillMessages`,void 0),J([q()],$.prototype,`skillsTab`,void 0),J([q()],$.prototype,`skillMenuOpenKey`,void 0),J([q()],$.prototype,`teamSkillsLoading`,void 0),J([q()],$.prototype,`teamSkillsReport`,void 0),J([q()],$.prototype,`teamSkillsError`,void 0),J([q()],$.prototype,`teamSkillsSyncBusyKey`,void 0),J([q()],$.prototype,`teamSkillsSyncedKeys`,void 0),J([q()],$.prototype,`teamOrganizationId`,void 0),J([q()],$.prototype,`skillFilesLists`,void 0),J([q()],$.prototype,`skillFilesContents`,void 0),J([q()],$.prototype,`skillFilesDrafts`,void 0),J([q()],$.prototype,`skillFilesActiveKey`,void 0),J([q()],$.prototype,`skillFilesActiveName`,void 0),J([q()],$.prototype,`skillFilesActiveDir`,void 0),J([q()],$.prototype,`skillFilesLoading`,void 0),J([q()],$.prototype,`skillFilesSaving`,void 0),J([q()],$.prototype,`skillFilesError`,void 0),J([q()],$.prototype,`skillFilesFullscreen`,void 0),J([q()],$.prototype,`skillFilesBackConfirm`,void 0),J([q()],$.prototype,`skillCreateMode`,void 0),J([q()],$.prototype,`skillCreateName`,void 0),J([q()],$.prototype,`skillCreateDesc`,void 0),J([q()],$.prototype,`skillCreateBusy`,void 0),J([q()],$.prototype,`skillCreateError`,void 0),J([q()],$.prototype,`skillAiDialogOpen`,void 0),J([q()],$.prototype,`skillAiFormName`,void 0),J([q()],$.prototype,`skillAiFormDesc`,void 0),J([q()],$.prototype,`skillAiFormTrigger`,void 0),J([q()],$.prototype,`skillAiFormInstruction`,void 0),J([q()],$.prototype,`skillAiFormExample`,void 0),J([q()],$.prototype,`skillAiInstructionReferences`,void 0),J([q()],$.prototype,`skillAiDialogFullscreenField`,void 0),J([q()],$.prototype,`skillAiFormError`,void 0),J([q()],$.prototype,`skillAiBuilderMode`,void 0),J([q()],$.prototype,`skillAiBuilderSkillKey`,void 0),J([q()],$.prototype,`skillAiBuilderBuilding`,void 0),J([q()],$.prototype,`skillAiBuilderActiveTab`,void 0),J([q()],$.prototype,`skillAiBuilderOpenTabs`,void 0),J([q()],$.prototype,`skillAiChatMessages`,void 0),J([q()],$.prototype,`skillAiChatStream`,void 0),J([q()],$.prototype,`skillAiChatSending`,void 0),J([q()],$.prototype,`skillAiChatMessage`,void 0),J([q()],$.prototype,`skillAiChatReferences`,void 0),J([q()],$.prototype,`skillAiReferenceMode`,void 0),J([q()],$.prototype,`skillAiReferenceTargetField`,void 0),J([q()],$.prototype,`skillAiReferenceActiveApiId`,void 0),J([q()],$.prototype,`skillAiReferenceSelectedIndex`,void 0),J([q()],$.prototype,`skillAiReferenceMatchFrom`,void 0),J([q()],$.prototype,`skillAiReferenceMatchTo`,void 0),J([q()],$.prototype,`skillAiReferenceQuery`,void 0),J([q()],$.prototype,`skillAiToolCalls`,void 0),J([q()],$.prototype,`skillAiBuilderExitConfirm`,void 0),J([q()],$.prototype,`skillUploadBusy`,void 0),J([q()],$.prototype,`skillUploadError`,void 0),J([q()],$.prototype,`skillUploadOverwriteKey`,void 0),J([q()],$.prototype,`skillUploadPendingFile`,void 0),J([q()],$.prototype,`skillDeleteConfirmKey`,void 0),J([q()],$.prototype,`skillExportBusyKey`,void 0),J([q()],$.prototype,`apiDefinitionsItems`,void 0),J([q()],$.prototype,`apiDefinitionsPath`,void 0),J([q()],$.prototype,`apiDefinitionsLoading`,void 0),J([q()],$.prototype,`apiDefinitionsError`,void 0),J([q()],$.prototype,`apiDefinitionsHash`,void 0),J([q()],$.prototype,`apiDefinitionsToast`,void 0),J([q()],$.prototype,`apiDefinitionsToastKind`,void 0),$=J([kA(`keyueclaw-skills`)],$),Object.defineProperty(e,`KeyueClawSkillsElement`,{enumerable:!0,get:function(){return $}})});
1855
+ `}};J([q()],$.prototype,`skillsLoading`,void 0),J([q()],$.prototype,`skillsReport`,void 0),J([q()],$.prototype,`skillsError`,void 0),J([q()],$.prototype,`skillsFilter`,void 0),J([q()],$.prototype,`skillsViewMode`,void 0),J([q()],$.prototype,`skillEdits`,void 0),J([q()],$.prototype,`skillsBusyKey`,void 0),J([q()],$.prototype,`skillMessages`,void 0),J([q()],$.prototype,`skillsTab`,void 0),J([q()],$.prototype,`skillMenuOpenKey`,void 0),J([q()],$.prototype,`teamSkillsLoading`,void 0),J([q()],$.prototype,`teamSkillsReport`,void 0),J([q()],$.prototype,`teamSkillsError`,void 0),J([q()],$.prototype,`teamSkillsSyncBusyKey`,void 0),J([q()],$.prototype,`teamSkillsSyncedKeys`,void 0),J([q()],$.prototype,`teamOrganizationId`,void 0),J([q()],$.prototype,`skillFilesLists`,void 0),J([q()],$.prototype,`skillFilesContents`,void 0),J([q()],$.prototype,`skillFilesDrafts`,void 0),J([q()],$.prototype,`skillFilesActiveKey`,void 0),J([q()],$.prototype,`skillFilesActiveName`,void 0),J([q()],$.prototype,`skillFilesActiveDir`,void 0),J([q()],$.prototype,`skillFilesLoading`,void 0),J([q()],$.prototype,`skillFilesSaving`,void 0),J([q()],$.prototype,`skillFilesError`,void 0),J([q()],$.prototype,`skillFilesFullscreen`,void 0),J([q()],$.prototype,`skillFilesBackConfirm`,void 0),J([q()],$.prototype,`skillCreateMode`,void 0),J([q()],$.prototype,`skillCreateName`,void 0),J([q()],$.prototype,`skillCreateDesc`,void 0),J([q()],$.prototype,`skillCreateBusy`,void 0),J([q()],$.prototype,`skillCreateError`,void 0),J([q()],$.prototype,`skillAiDialogOpen`,void 0),J([q()],$.prototype,`skillAiFormName`,void 0),J([q()],$.prototype,`skillAiFormDesc`,void 0),J([q()],$.prototype,`skillAiFormTrigger`,void 0),J([q()],$.prototype,`skillAiFormInstruction`,void 0),J([q()],$.prototype,`skillAiFormExample`,void 0),J([q()],$.prototype,`skillAiInstructionReferences`,void 0),J([q()],$.prototype,`skillAiDialogFullscreenField`,void 0),J([q()],$.prototype,`skillAiFormError`,void 0),J([q()],$.prototype,`skillAiBuilderMode`,void 0),J([q()],$.prototype,`skillAiBuilderSkillKey`,void 0),J([q()],$.prototype,`skillAiBuilderBuilding`,void 0),J([q()],$.prototype,`skillAiBuilderActiveTab`,void 0),J([q()],$.prototype,`skillAiBuilderOpenTabs`,void 0),J([q()],$.prototype,`skillAiChatMessages`,void 0),J([q()],$.prototype,`skillAiChatStream`,void 0),J([q()],$.prototype,`skillAiChatSending`,void 0),J([q()],$.prototype,`skillAiChatMessage`,void 0),J([q()],$.prototype,`skillAiChatReferences`,void 0),J([q()],$.prototype,`skillAiReferenceMode`,void 0),J([q()],$.prototype,`skillAiReferenceTargetField`,void 0),J([q()],$.prototype,`skillAiReferenceActiveApiId`,void 0),J([q()],$.prototype,`skillAiReferenceSelectedIndex`,void 0),J([q()],$.prototype,`skillAiReferenceMatchFrom`,void 0),J([q()],$.prototype,`skillAiReferenceMatchTo`,void 0),J([q()],$.prototype,`skillAiReferenceQuery`,void 0),J([q()],$.prototype,`skillAiToolCalls`,void 0),J([q()],$.prototype,`skillAiBuilderExitConfirm`,void 0),J([q()],$.prototype,`skillUploadBusy`,void 0),J([q()],$.prototype,`skillUploadError`,void 0),J([q()],$.prototype,`skillUploadOverwriteKey`,void 0),J([q()],$.prototype,`skillUploadPendingFile`,void 0),J([q()],$.prototype,`skillDeleteConfirmKey`,void 0),J([q()],$.prototype,`skillExportBusyKey`,void 0),J([q()],$.prototype,`apiDefinitionsItems`,void 0),J([q()],$.prototype,`apiDefinitionsPath`,void 0),J([q()],$.prototype,`apiDefinitionsLoading`,void 0),J([q()],$.prototype,`apiDefinitionsError`,void 0),J([q()],$.prototype,`apiDefinitionsHash`,void 0),J([q()],$.prototype,`apiDefinitionsToast`,void 0),J([q()],$.prototype,`apiDefinitionsToastKind`,void 0),$=J([kA(`keyueclaw-skills`)],$),Object.defineProperty(e,`KeyueClawSkillsElement`,{enumerable:!0,get:function(){return $}})});
1856
1856
  //# sourceMappingURL=skills.umd.cjs.map