openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
242 lines (241 loc) • 39.4 kB
JavaScript
import{n as e}from"./rolldown-runtime-DkW27tQK.js";import{$i as t,Ii as n,Kn as r,R as i,Vn as a,la as o,wr as s,z as c}from"./control-ui-foundation-Cydpkyqa.js";import{As as l,Bi as u,Cc as d,Do as f,Eo as p,Ga as ee,Oo as te,Sc as ne,Ts as re,Vi as ie,Vs as ae,Wa as oe,Wi as se,bc as ce}from"./control-ui-core-Rwzhj6nO.js";import{$ as m,K as h,X as g,at as le,q as _,st as v}from"./lit-runtime-CV_MH99K.js";import{Fn as ue,Jn as de,M as fe,Mt as pe,Nn as me,Yn as he,_ as ge,ar as _e,cn as ve,g as ye,i as be,j as xe,jt as Se,n as Ce,r as we,sn as Te}from"./control-ui-core-YphAl4aM.js";import{Ft as Ee,Gt as De,Wt as Oe,Yt as y,en as b}from"./control-ui-core-vvcQQV2m.js";import{Ft as ke,Pt as Ae}from"./control-ui-boot-shared-BYq7Cchl.js";import{a as x,i as je,n as S,r as C}from"./gateway-runtime-Bqqcp9-I.js";import{An as Me,Dn as Ne,Dr as Pe,Er as w,Hn as Fe,Or as T,Pn as Ie,Rn as Le,Tr as Re,Wn as ze,hn as Be,kr as Ve,mn as He,wr as Ue}from"./control-ui-boot-shared-DfZ39Yj9.js";import{_n as We,vn as Ge}from"./control-ui-boot-chat-_QSl8fbH.js";import"./control-ui-boot-shared-CXVvK2AW.js";import{n as Ke,t as E}from"./custodian-alert-store-C8M3qKFB.js";import{_ as qe,d as Je,p as Ye,v as Xe}from"./control-ui-boot-chat-Bia0O-uD.js";import{r as Ze,t as Qe}from"./wizard-step-controls-BcNiLuAR.js";import"./control-ui-boot-chat-BhPddYSI.js";function $e(e){if(!r(e))return;let t=e.code;return t===D.INFERENCE_UNAVAILABLE?{code:t}:void 0}function et(e){if(!r(e))return;let t=e.code;return t===D.SESSION_INVALIDATED?{code:t}:void 0}var D;function O(){return(O=e((()=>{D={INFERENCE_UNAVAILABLE:`system_agent_inference_unavailable`,SESSION_INVALIDATED:`system_agent_session_invalidated`}})))()}async function tt(e){let{context:t}=e,n=t.gateway.snapshot.sessionKey?.trim();if(e.agentId){let r=await t.agents.refreshList();if(!e.isCurrent())return`stale`;n=re({agentId:e.agentId,mainKey:r?.mainKey}),pe({selection:t.agentSelection,gateway:t.gateway,sessionKey:n,agentId:e.agentId})}return e.hatchDraft&&n?(t.navigate(`chat`,{pathname:nt(t,n),search:`?draft=${encodeURIComponent(b(`custodian.hatchDraft`))}`}),`navigated`):`exit-setup`}function nt(e,t){return se({face:`chat`,sessionKey:t,fallbackAgentId:ie(e),basePath:e.basePath,mainKey:ae({agentsList:e.agents.state.agentsList,hello:e.gateway.snapshot.hello})}).href}function k(){return(k=e((()=>{Se(),y(),u(),l()})))()}function rt(e){return e!==null&&e.length<=512&&e.trim().length>0}function A(){return`control-ui-onboarding-${oe()}`}function j(e){try{d()?.setItem(M,e)}catch{}}function it(){let e=null;try{e=d()?.getItem(M)??null}catch{}if(rt(e))return{sessionId:e,restored:!0};let t=A();return j(t),{sessionId:t,restored:!1}}var M,N;function P(){return(P=e((()=>{ee(),M=`openclaw.custodian.session.v1`,N=class{constructor(){this.lastDeviceToken=``}key(e){if(!e)return``;let{gatewayUrl:t,token:n,password:r,bootstrapToken:i}=e.connection,a=e.snapshot.hello?.auth;return a&&(this.lastDeviceToken=a.deviceToken??``),JSON.stringify([t,n,r,i,this.lastDeviceToken])}}})))()}function at(e){if(!e||e.gateway.snapshot.phase!==`connected`)return`unresolved`;let t=e.agents.state.agentsList;if(!t)return`unresolved`;let r=n(e.gateway.snapshot.assistantAgentId??t.defaultId??``),i=t.agents.find(e=>n(e.id)===r);return i?i.model?.primary?.trim()?`ready`:`required`:`unresolved`}function F(){return(F=e((()=>{l()})))()}function I(e,t){return e.options?.find(e=>Object.is(e.value,t))}function ot(e,t){if(e.type===`note`||e.type===`action`||e.type===`progress`)return{answer:{stepId:e.id},display:b(`common.continue`)};if(e.type===`text`)return typeof t==`string`?{answer:{stepId:e.id,value:t},display:t}:null;if(e.type===`confirm`)return typeof t==`boolean`?{answer:{stepId:e.id,value:t},display:b(t?`common.yes`:`common.no`)}:null;if(e.type===`select`){let n=I(e,t);return n?{answer:{stepId:e.id,value:t},display:n.label}:null}if(!Array.isArray(t))return null;if(t.length===0)return{answer:{stepId:e.id,value:[]},display:b(`common.none`)};let n=t.map(t=>I(e,t)?.label);return n.every(e=>e!==void 0)?{answer:{stepId:e.id,value:t},display:n.join(`, `)}:null}function st(e){return e.type===`multiselect`?Array.isArray(e.initialValue)?[...e.initialValue]:[]:e.initialValue}function ct(e){return je(e?.gateway.snapshot??{},Ae.SYSTEM_AGENT_WIZARD_CANCEL)??!1}function L(){return(L=e((()=>{ke(),y(),C()})))()}function lt(e,t){return t===`received`?`sent`:e instanceof Te||t===`unsent`?`rejected`:`unknown`}function ut(e,t){return t===`sent`?!1:t===`unknown`||e}function dt(e,t,n){return n!==`rejected`&&e!==null&&e.severity===t.severity&&e.message===t.message}function ft(e,t,n){if(n.event!==`health`)return[e,t];let r=xt(n);return t?[r,t]:[r,null]}function pt(e){if(e.kind===`config-reload`)return b(`custodian.nudge.configReload`);let t=e.channelLabel??b(`custodian.nudge.channelFallback`);return e.kind===`channel-auth`?b(`custodian.nudge.channelAuth`,{channel:t}):e.kind===`channel-disconnected`?b(`custodian.nudge.channelDisconnected`,{channel:t}):b(`custodian.nudge.channelDegraded`,{channel:t})}function mt(e){return g`<div class="custodian__nudge" role="status">
<button
class="custodian__nudge-action"
type="button"
?disabled=${e.disabled}
=${e.onSend}
>
${pt(e.nudge)}
</button>
<button
class="custodian__nudge-dismiss"
type="button"
aria-label=${b(`custodian.nudge.dismiss`)}
=${e.onDismiss}
>
×
</button>
</div>`}function ht(e){return g`<div class="custodian__nudge custodian__nudge--channel-onboarding" role="status">
<div class="custodian__nudge-copy">
<strong>${b(`custodian.nudge.channelSetupTitle`)}</strong>
<span>${b(`custodian.nudge.channelSetupBody`)}</span>
</div>
<button
class="btn btn--sm primary custodian__nudge-cta"
type="button"
=${e.onOpenChannels}
>
${b(`custodian.nudge.channelSetupAction`)}
</button>
<button
class="custodian__nudge-dismiss"
type="button"
aria-label=${b(`custodian.nudge.channelSetupDismiss`)}
=${e.onDismiss}
>
×
</button>
</div>`}function gt(e){return g`<div class="custodian__nudge custodian__nudge--channel-onboarding" role="alert">
<div class="custodian__nudge-copy">
<strong>${b(`custodian.nudge.channelStatusErrorTitle`)}</strong>
<span>${b(`custodian.nudge.channelStatusErrorBody`)}</span>
</div>
<button
class="btn btn--sm primary custodian__nudge-cta"
type="button"
?disabled=${e.retrying}
=${e.onRetry}
>
${e.retrying?b(`common.loading`):b(`common.retry`)}
</button>
<button
class="custodian__nudge-dismiss"
type="button"
aria-label=${b(`custodian.nudge.channelSetupDismiss`)}
=${e.onDismiss}
>
×
</button>
</div>`}function _t(e){return z.some(t=>e[t]===`configured_unavailable`)}function vt(e){return a(e.probe)?.ok===!1}function yt(e,t,n){if(n.configured===!1||n.enabled===!1)return null;let r=e.toLowerCase();if(_t(n))return{severity:3,kind:`channel-auth`,channelLabel:t,message:`what happened with ${r} authentication?`};let i=typeof n.healthState==`string`?n.healthState.trim().toLowerCase():void 0;if(i===`terminal-disconnect`||vt(n))return{severity:3,kind:`channel-degraded`,channelLabel:t,message:`what happened with ${r}?`};if(i===`not-running`&&n.running===!1){let e=typeof n.reconnectAttempts==`number`?n.reconnectAttempts:0,t=typeof n.lastStartAt==`number`?n.lastStartAt:void 0,r=typeof n.lastStopAt==`number`?n.lastStopAt:void 0;if(n.restartPending===!1&&r!==void 0&&(t===void 0||r>=t)&&e<10)return null}return n.connected!==!0&&i!==`healthy`&&typeof n.lastError==`string`&&n.lastError.trim()?{severity:3,kind:`channel-degraded`,channelLabel:t,message:`what happened with ${r}?`}:n.connected===!1&&n.running===!0?{severity:2,kind:`channel-disconnected`,channelLabel:t,message:`what happened with ${r}?`}:i&&R.has(i)?{severity:1,kind:`channel-degraded`,channelLabel:t,message:`what happened with ${r}?`}:null}function bt(e){let t=a(e);if(!t)return null;if(a(t.configReload)?.hotReloadStatus===`disabled`)return{severity:3,kind:`config-reload`,message:`what happened with configuration reload?`};let n=a(t.channels);if(!n)return null;let r=a(t.channelLabels),i=null;for(let[e,t]of Object.entries(n)){let n=a(t);if(!n)continue;let o=typeof r?.[e]==`string`?r[e]:e,s=a(n.accounts),c=s?Object.values(s).map(a).filter(e=>e!==null):[],l=c.length>0?c:[n];for(let t of l){let n=yt(e,o,t);n&&(!i||n.severity>i.severity)&&(i=n)}}return i}function xt(e){return e.event===`health`?bt(e.payload):null}var R,z;function B(){return(B=e((()=>{h(),ve(),y(),R=new Set([`disconnected`,`stale-socket`,`stuck`,`terminal-disconnect`]),z=[`tokenStatus`,`botTokenStatus`,`appTokenStatus`,`signingSecretStatus`,`userTokenStatus`]})))()}function St(e,t){return e?`onboarding`:t?`new-agent`:`caretaker`}function V(e,t){let n=e===`caretaker`?{}:{welcomeVariant:e};if(t===void 0)return n;let r=window.location.pathname,i=_e(r,de(r));return{...n,message:t,...i?{context:{page:i}}:{}}}function H(e){return e.message!==void 0||e.wizardAnswer!==void 0||e.wizardCancel!==void 0}function Ct(e){let t=e&&typeof e==`object`?e.details:void 0;return{inferenceUnavailable:$e(t)!==void 0,sessionInvalidated:et(t)!==void 0}}function U(){return(U=e((()=>{O(),he()})))()}var W;function G(){return(G=e((()=>{h(),m(),y(),W=class extends o{constructor(...e){super(...e),this.selectedValue=``,this.requestKey=``,this.focusPreselection=!1}createRenderRoot(){return this}willUpdate(){let e=this.props,t=e?JSON.stringify([e.header??``,e.question,e.options.map(e=>[e.value,e.label,e.recommended===!0])]):``;t!==this.requestKey&&(this.requestKey=t,this.selectedValue=e?.options.slice(0,4).find(e=>e.recommended)?.value??``,this.focusPreselection=!!this.selectedValue)}updated(e){!this.focusPreselection||this.props?.disabled||(this.focusPreselection=!1,[...this.querySelectorAll(`.option-card__choice`)].find(e=>e.dataset.optionValue===this.selectedValue)?.focus({preventScroll:!0}))}select(e){this.props?.disabled||(this.selectedValue=e,this.props?.onSelect?.(e),this.dispatchEvent(new CustomEvent(`option-select`,{bubbles:!0,composed:!0,detail:{value:e}})))}skip(){this.props?.disabled||(this.props?.onSkip?.(),this.dispatchEvent(new CustomEvent(`option-skip`,{bubbles:!0,composed:!0})))}render(){let e=this.props;if(!e)return _;let t=e.options.slice(0,4),n=t.findIndex(e=>e.recommended===!0);return g`
<section class="option-card" role="group" aria-label=${e.question}>
${e.header?g`<div class="option-card__chip">${e.header}</div>`:_}
<div class="option-card__question">${e.question}</div>
<div class="option-card__choices" role="radiogroup">
${t.map((t,r)=>{let i=r===n,a=t.value===this.selectedValue;return g`
<button
class=${`option-card__choice ${i?`option-card__choice--recommended`:``} ${a?`option-card__choice--selected`:``}`}
type="button"
role="radio"
aria-checked=${a?`true`:`false`}
data-option-value=${t.value}
?disabled=${e.disabled}
=${()=>this.select(t.value)}
>
<span class="option-card__choice-copy">
<strong>${t.label}</strong>
${t.description?g`<span class="option-card__description">${t.description}</span>`:_}
</span>
${i?g`<span class="option-card__recommended">
${b(`optionCard.recommended`)}
</span>`:_}
</button>
`})}
</div>
<button
class="option-card__skip"
type="button"
?disabled=${e.disabled}
=${()=>this.skip()}
>
${b(`optionCard.skip`)}
</button>
</section>
`}},s([v({attribute:!1})],W.prototype,`props`,void 0),s([le()],W.prototype,`selectedValue`,void 0),customElements.get(`openclaw-option-card`)||customElements.define(`openclaw-option-card`,W)})))()}function wt(e){return g`<div class="custodian__option-card">
<openclaw-option-card
.props=${{header:e.question.header,question:e.question.question,options:e.question.options.map(e=>({value:e.label,label:e.label,description:e.description,recommended:e.recommended})),disabled:e.disabled,onSelect:e.onSelect,onSkip:e.onSkip}}
></openclaw-option-card>
</div>`}function K(){return(K=e((()=>{h(),G()})))()}function Tt(e){if(!e||typeof e!=`object`)return null;let n=t(e.id),r=t(e.header),i=t(e.question);if(!n||!r||!i||!Array.isArray(e.options)||e.options.length<2||e.options.length>4)return null;let a=[];for(let n of e.options){let e=t(n?.label);if(!e)return null;let r=t(n.description??null),i=t(n.reply??null);a.push({label:e,...r?{description:r}:{},...n.recommended===!0?{recommended:!0}:{},...i?{reply:i}:{}})}return new Set(a.map(e=>e.label.toLocaleLowerCase())).size!==a.length||a.filter(e=>e.recommended).length>1?null:{id:n,header:r,question:i,options:a,isOther:e.isOther===!0,...e.skipAction===`exit`?{skipAction:`exit`}:{}}}function Et(){return(Et=e((()=>{})))()}function Dt(e,t,n,r=null,i=null){return{id:e,role:t,text:n,at:Date.now(),question:r,step:i}}function Ot(e,t){let n=t.step??null,r=n?null:Tt(t.question),i=Lt.test(t.reply);return i&&!r&&!n?null:Dt(e,`assistant`,i?``:t.reply,r,n)}function kt(e,t,n,r,i){return r||i||e.some(e=>e.question!==null&&e.question.id!==`system-agent-quick-actions`&&!t.has(`${e.id}:${e.question.id}`)&&!n.has(`${e.id}:${e.question.id}`))}function At(e,t){let n=new Set(t);for(let t of e)t.question&&n.add(`${t.id}:${t.question.id}`);return n}function q(e){return p(e,b(`custodian.requestFailed`))}function jt(e){let t=`msg-${e.id}`,n={role:e.role,content:e.text};return{kind:`group`,key:t,role:e.role,messages:[{message:n,key:t}],visibleContent:Le(n,ze(n)),timestamp:e.at,isStreaming:!1}}async function Mt(e){try{return{ok:!0,turns:(await e.request(`openclaw.chat.history`,{},{timeoutMs:It})).turns}}catch(e){return{ok:!1,error:q(e)}}}function Nt(e,t){let n=t;return{messages:e.map(e=>({id:n++,role:e.role,text:e.role===`user`&&e.text===J?b(`custodian.sensitiveReply`):e.text,at:e.at,question:null,step:null})),nextMessageId:n}}function Pt(e,t){return e.id===t?Xe({kind:`divider`,key:`custodian-earlier`,label:b(`custodian.earlier`),timestamp:e.at}):_}function Ft(e){let t=e.message.question,n=e.message.step;return g`
${e.message.text?Ye(jt(e.message),{showReasoning:!1,showToolCalls:!1,assistantName:b(`custodian.title`),assistantAvatar:e.assistantAvatar}):_}
${Pt(e.message,e.boundaryAfterId)}
${e.showQuestion&&t?wt({question:t,disabled:e.questionDisabled,onSelect:e.onSelect,onSkip:e.onSkip}):_}
${e.showWizardStep&&n?g`<section
class="custodian__wizard-step"
aria-label=${f(n.title??n.message,`Setup`)}
>
${n.title?g`<strong class="custodian__wizard-title"
>${f(n.title)}</strong
>`:_}
${Ze({step:n,value:e.wizardValue,busy:e.wizardDisabled,inputId:`custodian-wizard-input-${e.message.id}`,sensitiveRevealed:e.wizardSecretVisible,onValueChange:e.onWizardValueChange,onAnswer:e.onWizardAnswer,leadingAction:e.showWizardCancel?g`<button
class="btn btn--ghost custodian__wizard-cancel"
type="button"
?disabled=${e.wizardDisabled}
=${e.onWizardCancel}
>
${b(`custodian.cancel`)}
</button>`:void 0,onToggleSensitiveVisibility:e.onToggleWizardSecretVisibility})}
</section>`:_}
`}var It,Lt,Rt,J;function Y(){return(Y=e((()=>{h(),T(),Qe(),y(),Fe(),Ie(),te(),qe(),Je(),K(),Et(),It=15e3,Lt=/^\s*NO_REPLY\s*$/,Rt=class{constructor(e){this.onStatusChange=e,this.status=w(),this.generation=0,this.inFlight=null}get refreshing(){return this.inFlight!==null}invalidate(){this.generation+=1,this.inFlight=null}reset(){this.invalidate(),this.status=w()}async read(e,t,n){let r=this.inFlight;if(r&&r.client===e&&r.epoch===t)return await r.promise,null;let i=++this.generation;this.status=Ue(this.status,{clearError:!1});let a=Mt(e);this.inFlight={client:e,epoch:t,promise:a},this.onStatusChange();try{let e=await a;return!n()||i!==this.generation?null:(this.status=e.ok?Re():Pe(this.status,e.error),e)}finally{this.inFlight?.promise===a&&(this.inFlight=null,this.onStatusChange())}}async loadMessages(e,t,n,r){let i=await this.read(e,t,r);return i?.ok&&r()?Nt(i.turns,n):null}},J=`<redacted secret>`})))()}var zt,Bt,X;function Z(){return(Z=e((()=>{y(),C(),k(),P(),F(),L(),B(),U(),Y(),zt=19e4,Bt=class{constructor(){this.messages=[],this.sending=!1,this.sensitive=!1,this.wizardInputPending=!1,this.wizardSecretVisible=!1,this.questionReplyUncertain=!1,this.error=null,this.transcript=new Rt(()=>this.emit()),this.dismissedQuestions=new Set,this.answeredQuestions=new Set,this.activeClient=null,this.chatAvailable=!1,this.eventNudge=null,this.eventNudgePending=null,this.channelOnboardingNudgeClosed=!1,this.earlierBoundaryAfterId=null,this.abandonedTurnOutcomeUnknown=!1,this.inferenceState=`unverified`,this.inputDrafts={ordinary:{value:``},sensitive:{value:``}},this.context=null,this.variant=`caretaker`,this.sessionVariant=null,this.restoredIdentity=it(),this.sessionId=this.restoredIdentity.sessionId,this.rejoinBarrierPending=this.restoredIdentity.restored,this.requestEpoch=0,this.requestAbort=null,this.nextMessageId=1,this.retryParams=null,this.sessionClient=null,this.sessionOwnershipKey=null,this.sessionOwner=new N,this.sessionStarted=!1,this.configuredInferenceState=`unresolved`,this.eventNudgeClosed=!1,this.gatewayCleanup=null,this.agentCleanup=null,this.eventCleanup=null,this.listeners=new Set}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}connect(e,t){let n=this.context!==e,r=this.variant!==t;!n&&!r||(n&&(this.gatewayCleanup?.(),this.agentCleanup?.(),this.eventCleanup?.(),this.context=e,this.gatewayCleanup=e.gateway.subscribe(()=>{this.synchronizeClient(),this.emit()}),this.agentCleanup=e.agents.subscribe(()=>{this.synchronizeClient(),this.emit()}),this.eventCleanup=e.gateway.subscribeEvents(e=>{this.variant!==`caretaker`||this.eventNudgeClosed||([this.eventNudge,this.eventNudgePending]=ft(this.eventNudge,this.eventNudgePending,e),this.emit())})),this.variant=t,this.synchronizeClient(),this.emit())}get input(){return this.inputDrafts[this.sensitive?`sensitive`:`ordinary`].value}set input(e){this.inputDrafts[this.sensitive?`sensitive`:`ordinary`]={value:e}}setInput(e){this.input=e,this.emit()}resetPromptInput(e){this.inputDrafts.sensitive={value:``},[this.wizardValue,this.wizardSecretVisible]=[void 0,!1],this.sensitive=e}setWizardValue(e){this.wizardValue=e,this.emit()}toggleWizardSecretVisibility(){this.wizardSecretVisible=!this.wizardSecretVisible,this.emit()}hasRealUserTurn(){return this.messages.some(e=>e.role===`user`)}get activeVariant(){return this.variant}hasUnresolvedQuestion(){return kt(this.messages,this.dismissedQuestions,this.answeredQuestions,this.wizardInputPending,this.questionReplyUncertain)}async refreshTranscriptIfIdle(){let e=this.activeClient;!e||!this.canRefreshTranscript()||await this.refreshTranscriptHistory(e,this.requestEpoch)&&this.abandonedTurnOutcomeUnknown&&(this.abandonedTurnOutcomeUnknown=!1,this.emit())}canRefreshTranscript(){let e=this.sending||this.hasUnresolvedQuestion()||this.transcript.refreshing;return this.activeClient!==null&&this.sessionStarted&&this.chatAvailable&&!e}canRetry(){return this.retryParams!==null&&!H(this.retryParams)}get setupRequired(){return this.configuredInferenceState===`required`}get canSend(){return this.activeClient!==null&&this.chatAvailable&&!this.sending&&this.configuredInferenceState===`ready`&&this.inferenceState===`ready`}get wizardCancelAvailable(){return ct(this.context)}retry(){let e=this.activeClient,t=this.retryParams;e&&t&&!H(t)&&this.chatAvailable&&!this.sending&&this.initializeSession(e,t,!1)}async send(e,t,n=this.hasUnresolvedQuestion(),r){let i=e??this.input,a=this.sensitive?i:i.trim(),o=this.activeClient;if(!a.trim()||!o||!this.canSend)return this.emit(),`rejected`;let s=this.sensitive?b(`custodian.sensitiveReply`):t??a,c={sessionId:this.sessionId,...V(this.variant,a)};return await this.sendUserTurn(o,c,s,n,()=>r&&(!r.isCurrent()||!r.admit())?!1:(e===void 0&&(this.input=``),!0))}async sendUserTurn(e,t,n,r,i){let a=[this.answeredQuestions,this.questionReplyUncertain],o,s=await this.requestReply(e,t,()=>{let e=this.inputDrafts.ordinary;if(i&&!i())return!1;let t=this.inputDrafts.ordinary;this.resetPromptInput(this.sensitive),o=this.requestEpoch,r&&(this.questionReplyUncertain=!0),this.abandonedTurnOutcomeUnknown=!1,this.answeredQuestions=At(this.messages,this.answeredQuestions);let s=Dt(this.nextMessageId++,`user`,n);return this.messages=[...this.messages,s],()=>{this.messages=this.messages.filter(e=>e!==s),this.answeredQuestions=a[0],e!==t&&this.inputDrafts.ordinary===t&&(this.inputDrafts.ordinary=e)}});return r&&this.requestEpoch===o&&(this.questionReplyUncertain=ut(a[1],s),s===`rejected`&&(this.answeredQuestions=a[0]),this.emit()),s}async sendEventNudge(){let e=this.eventNudge;if(!e||this.sensitive||this.hasUnresolvedQuestion())return;this.eventNudgePending=e,this.emit();let t=await this.send(e.message);if(this.eventNudgePending===e){this.eventNudgePending=null;let n=dt(this.eventNudge,e,t);[this.eventNudgeClosed,this.eventNudge]=[n,n?null:this.eventNudge],this.emit()}}dismissEventNudge(){[this.eventNudge,this.eventNudgeClosed]=[null,!0],this.emit()}dismissChannelOnboardingNudge(){this.channelOnboardingNudgeClosed=!0,this.emit(),this.context?.replace(`custodian`)}openChannelsFromOnboarding(){this.channelOnboardingNudgeClosed=!0,this.revokeNavigationAuthority(),this.emit(),this.context?.navigate(`channels`)}async dismissQuestion(e){let t=e.question;if(t){if(t.skipAction===`exit`){this.exitSetup();return}await this.send(t.isOther?b(`optionCard.skip`):`cancel`,b(`optionCard.skip`),!0)!==`rejected`&&this.messages.includes(e)&&(this.dismissedQuestions=new Set(this.dismissedQuestions).add(`${e.id}:${t.id}`),this.emit())}}answerQuestion(e,t){let n=e.question;if(!n)return;let r=n.options.find(e=>e.label===t);this.send(r?.reply??t,t,!0)}answerWizardStep(e,t){if(!e.step||!this.wizardInputPending)return;let n=ot(e.step,t),r=this.activeClient;if(!n||!r||!this.canSend){this.emit();return}let i=e.step.sensitive?b(`custodian.sensitiveReply`):n.display;this.sendUserTurn(r,{sessionId:this.sessionId,wizardAnswer:n.answer},i,!0)}cancelWizardStep(e){let t=e.step,n=this.activeClient;if(!t||!this.wizardInputPending||!n||!this.canSend||!this.wizardCancelAvailable){this.emit();return}this.sendUserTurn(n,{sessionId:this.sessionId,wizardCancel:{stepId:t.id}},b(`custodian.cancel`),!0)}exitSetup(e=`chat`){this.revokeNavigationAuthority(),this.context?.navigate(e)}revokeNavigationAuthority(){this.requestAbort?.abort(),this.requestAbort=null,this.advanceRequestEpoch(),this.sending=!1,this.questionReplyUncertain=!1,this.retryParams=null,this.error=null}advanceRequestEpoch(){return this.transcript.invalidate(),++this.requestEpoch}emit(){for(let e of this.listeners)e()}startSession(e,t){this.sessionVariant=this.variant,this.sessionClient=e,this.sessionOwnershipKey=this.sessionOwner.key(this.context?.gateway??null),this.sessionStarted=!0,this.initializeSession(e,{sessionId:this.sessionId,...V(this.variant)},t)}replaceSessionId(e){e===void 0&&(this.rejoinBarrierPending=!1);let t=e??A();this.sessionId=t,j(t)}abandonPendingUserTurn(e){!e||!H(e)||(this.retryParams=null,this.abandonedTurnOutcomeUnknown=!0)}restartVolatileSession(e){this.replaceSessionId(),this.answeredQuestions=At(this.messages,this.answeredQuestions),this.resetPromptInput(!1),this.wizardInputPending=this.questionReplyUncertain=!1,this.earlierBoundaryAfterId=this.messages.at(-1)?.id??null,this.startSession(e,!1)}synchronizeClient(){let e=this.context;if(!e)return;let t=e.gateway.snapshot,n=t.phase===`connected`?t.client:null,r=n!==null&&S(t,`openclaw.chat`,`operator.admin`),i=x(t,`openclaw.chat`)===!1,a=at(this.context),o=a!==this.configuredInferenceState;this.configuredInferenceState=a;let s=this.sessionStarted&&this.sessionVariant!==this.variant,c=this.sessionOwner.key(e.gateway),l=this.sessionStarted&&n!==null&&this.activeClient===null,u=this.sessionStarted&&n!==null&&this.sessionClient!==null&&n!==this.sessionClient,d=this.sessionOwnershipKey!==null&&c!==this.sessionOwnershipKey;if(n===this.activeClient&&!s&&!u&&!d&&this.chatAvailable===(r&&a!==`unresolved`)&&!o)return;let f=this.sending&&this.retryParams!==null,p=f?this.retryParams:null;if(this.activeClient=n,this.advanceRequestEpoch(),this.sending=!1,this.chatAvailable=!1,s||d)d&&this.replaceSessionId(),[this.eventNudge,this.eventNudgePending]=[null,null],this.eventNudgeClosed=!1,this.abandonedTurnOutcomeUnknown=!1,this.sessionStarted=!1,this.clearConversation();else if(n&&(u||l)){if(!r){this.sessionStarted=!1,this.abandonPendingUserTurn(p),this.error=i?b(`custodian.unsupportedGateway`):null;return}this.chatAvailable=!0,this.abandonPendingUserTurn(p),this.requestAbort?.abort(),this.requestAbort=null,this.sessionClient=n,this.sessionOwnershipKey=c,this.questionReplyUncertain||this.abandonedTurnOutcomeUnknown?(this.questionReplyUncertain=!1,this.wizardInputPending=!1,this.abandonedTurnOutcomeUnknown=!1,this.rejoinBarrierPending=!0,this.initializeSession(n,{sessionId:this.sessionId,...V(this.variant)})):this.refreshTranscriptIfIdle();return}else f&&(p?.message===void 0&&(this.error=b(`custodian.connectionChanged`)),this.abandonPendingUserTurn(p));if(n){if(!r){this.error=i?b(`custodian.unsupportedGateway`):null;return}if(a!==`unresolved`){if(this.chatAvailable=!0,a===`required`){this.sessionStarted=!1,this.clearConversation();return}if(this.sessionStarted){this.retryParams||(this.error=f?this.error:null);return}this.clearConversation(),this.startSession(n,!0)}}}async initializeSession(e,t,n=!0){let r=this.advanceRequestEpoch();this.sending=!0,this.inferenceState=`unverified`,this.error=null,this.retryParams=t,this.emit(),n&&await this.refreshTranscriptHistory(e,r),r===this.requestEpoch&&e===this.activeClient&&await this.requestReply(e,t)}async refreshTranscriptHistory(e,t){let n=this.context;if(!n||x(n.gateway.snapshot,`openclaw.chat.history`)!==!0)return!1;let r=await this.transcript.loadMessages(e,t,this.nextMessageId,()=>t===this.requestEpoch&&e===this.activeClient);return r?([this.messages,this.nextMessageId]=[r.messages,r.nextMessageId],this.earlierBoundaryAfterId=this.messages.at(-1)?.id??null,this.emit(),!0):!1}clearConversation(){this.messages=[],this.dismissedQuestions=new Set,this.answeredQuestions=new Set,this.retryParams=null,this.error=null,this.transcript.reset(),this.inferenceState=`unverified`,this.inputDrafts.ordinary={value:``},this.resetPromptInput(!1),this.wizardInputPending=this.questionReplyUncertain=!1,this.earlierBoundaryAfterId=null}async requestReply(e,t,n){let r=this.context;if(!r)return`rejected`;let i=()=>e===this.activeClient&&r.gateway.snapshot.client===e&&S(r.gateway.snapshot,`openclaw.chat`,`operator.admin`);if(!i())return`rejected`;this.requestAbort?.abort();let a=new AbortController;this.requestAbort=a;let o=this.advanceRequestEpoch(),s=`unsent`,c;this.sending=!0,this.error=null,this.retryParams=t,this.emit();try{if(o!==this.requestEpoch||!i()||(c=n?.())===!1)return this.retryParams===t&&(this.retryParams=null),`rejected`;let l=e.request(`openclaw.chat`,t,{timeoutMs:zt,onSent:()=>{s=`sent`},signal:a.signal});this.emit();let u=await l;if(s=`received`,o!==this.requestEpoch||e!==this.activeClient||(this.replaceSessionId(u.sessionId),this.resetPromptInput(u.sensitive===!0),this.wizardInputPending=u.wizardInputPending===!0,this.retryParams=null,this.inferenceState=`ready`,this.rejoinBarrierPending&&!H(t)&&(this.rejoinBarrierPending=!1,await this.refreshTranscriptHistory(e,o),o!==this.requestEpoch||e!==this.activeClient)))return`sent`;this.wizardValue=u.step?st(u.step):void 0;let d=Ot(this.nextMessageId,u);return d&&(this.nextMessageId+=1,this.messages=[...this.messages,d]),u.handoff?.kind===`model-accounts`?this.exitSetup(`profile`):u.action===`open-agent`?await tt({context:r,...u.agentId?{agentId:u.agentId}:{},hatchDraft:u.agentDraft===`hatch`,isCurrent:()=>o===this.requestEpoch&&e===this.activeClient})===`exit-setup`&&this.exitSetup():u.action===`exit`&&this.exitSetup(),`sent`}catch(n){if(o===this.requestEpoch&&e===this.activeClient){s===`unsent`&&c&&c(),this.error=q(n);let{inferenceUnavailable:r,sessionInvalidated:i}=Ct(n);r&&(this.inferenceState=`unverified`,this.retryParams={sessionId:this.sessionId,...V(this.variant)}),i&&H(t)?(this.restartVolatileSession(e),this.error=b(`custodian.sessionRestarted`,{error:q(n)})):i&&(this.replaceSessionId(),this.retryParams={...t,sessionId:this.sessionId},this.error=b(`custodian.sessionRestarted`,{error:q(n)}))}return H(t)&&this.retryParams===t&&(this.retryParams=null),lt(n,s)}finally{this.requestAbort===a&&(this.requestAbort=null),o===this.requestEpoch&&(this.sending=!1),this.emit()}}},X=new Bt})))()}function Vt(){return(Vt=e((()=>{})))()}function Ht(e,t,n){e.kind===`navigate`?t.navigate(e.routeId):n&&Ce({startGatewayUpdate:()=>void t.overlays.runUpdate(),watchUpdateProgress:we(t),onAcknowledge:()=>t.overlays.acknowledgeUpdateRun(),onCheckStatus:()=>t.overlays.refreshUpdateStatus(),onReviewUpdate:()=>t.navigate(`updates`),updateAvailable:t.overlays.snapshot.updateAvailable,updateSchedule:t.overlays.snapshot.updateSchedule,viaNativeApp:xe()})}function Ut(e){let{action:t}=e.alert,n=S(e.context.gateway.snapshot,`update.run`,`operator.admin`),r=t?.target.kind===`update`&&!n;return g`<article class="custodian__nudge custodian__alert-card" role="status">
<div class="custodian__alert-heading">
<strong>${e.alert.title}</strong>
<button
class="custodian__nudge-dismiss"
type="button"
aria-label=${b(`common.dismiss`)}
=${e.onDismiss}
>
×
</button>
</div>
<ul class="custodian__alert-facts">
${e.alert.facts.map(e=>g`<li>${e}</li>`)}
</ul>
${t?g`<button
class="btn btn--sm primary custodian__alert-action"
type="button"
title=${r?b(`updates.adminRequired`):_}
?disabled=${r}
=${()=>Ht(t.target,e.context,n)}
>
${t.label}
</button>`:_}
</article>`}function Wt(){return(Wt=e((()=>{h(),fe(),be(),y(),C()})))()}var Q;function $(){return($=e((()=>{c(),h(),m(),ge(),ue(),De(),We(),Me(),Be(),T(),Ee(),y(),ne(),Wt(),Ke(),Z(),B(),U(),Y(),Q=class extends ce{constructor(...e){super(...e),this.store=X,this.onboarding=!1,this.newAgentIntent=!1,this.showChannelOnboardingNudge=!1,this.channelOnboardingError=null,this.channelOnboardingRetrying=!1,this.onRetryChannelOnboarding=()=>void 0,this.compact=!1,this.historyContent=_,this.subscribedStore=null,this.storeCleanup=null,this.alertCleanup=null,this.lastMessageId=null}connectedCallback(){super.connectedCallback(),this.subscribeToStore(),this.alertCleanup=E.subscribe(()=>this.requestUpdate())}disconnectedCallback(){this.storeCleanup?.(),this.storeCleanup=null,this.alertCleanup?.(),this.alertCleanup=null,this.subscribedStore=null,super.disconnectedCallback()}async getUpdateComplete(){let e=await super.getUpdateComplete();return await Promise.all(Array.from(this.querySelectorAll(`openclaw-option-card`)).map(e=>e.updateComplete)),e}willUpdate(e){e.has(`store`)&&this.subscribeToStore(),this.store.connect(this.context,St(this.onboarding,this.newAgentIntent))}updated(){let e=this.store;e.canSend&&!e.sensitive&&!e.hasUnresolvedQuestion()&&E.askIfReady((t,n,r)=>void e.send(t,r,!1,n));let t=this.querySelector(`.custodian__messages`),n=this.store.messages.at(-1)?.id??null;if(n!==this.lastMessageId){this.lastMessageId=n;let e=t?.lastElementChild;e instanceof HTMLElement&&e.scrollIntoView?.({block:`nearest`})}}subscribeToStore(){!this.isConnected||this.subscribedStore===this.store||(this.storeCleanup?.(),this.subscribedStore=this.store,this.storeCleanup=this.store.subscribe(()=>this.requestUpdate()))}handleComposerKeydown(e){e.key!==`Enter`||e.shiftKey||e.isComposing||(e.preventDefault(),this.store.send())}render(){let e=this.store,t=me(`favicon.svg`,this.context.resourceBasePath),n=E.alert?Ut({alert:E.alert,context:this.context,onDismiss:()=>E.dismiss()}):_;if(e.setupRequired)return g`
<section
class="custodian-surface custodian-surface--setup-required ${this.compact?`custodian-surface--panel`:``}"
>
${n}
<div class="custodian__setup-state" role="alert">
<openclaw-mascot mood="idle" .size=${this.compact?72:96}></openclaw-mascot>
<h2>${b(`modelSetup.required.title`)}</h2>
<p>${b(`modelSetup.required.body`)}</p>
<div class="custodian__setup-actions">
<button
class="btn primary"
type="button"
=${()=>e.exitSetup(`model-setup`)}
>
${b(`modelSetup.required.action`)}
</button>
</div>
</div>
</section>
`;let r=e.messages.length===0&&e.error!==null&&!e.sending,i=e.wizardInputPending?e.messages.findLast(e=>e.step!==null):void 0;return g`
<section
class="custodian-surface ${this.compact?`custodian-surface--panel`:``} ${r?`custodian-surface--empty-error`:``}"
>
<div
class="custodian__messages"
${Ge()}
aria-live="polite"
=${e=>{Ne(e),He(e)}}
>
${n}
${this.channelOnboardingError?gt({retrying:this.channelOnboardingRetrying,onRetry:this.onRetryChannelOnboarding,onDismiss:()=>e.dismissChannelOnboardingNudge()}):this.showChannelOnboardingNudge?ht({onOpenChannels:()=>e.openChannelsFromOnboarding(),onDismiss:()=>e.dismissChannelOnboardingNudge()}):_}
${!this.onboarding&&e.eventNudge&&!e.eventNudgePending?mt({nudge:e.eventNudge,disabled:!e.canSend||e.sensitive||e.hasUnresolvedQuestion(),onSend:()=>void e.sendEventNudge(),onDismiss:()=>e.dismissEventNudge()}):_}
${e.messages.map(n=>{let r=n.question?`${n.id}:${n.question.id}`:``,a=n.question!==null&&!e.dismissedQuestions.has(r);return Ft({message:n,boundaryAfterId:e.earlierBoundaryAfterId,assistantAvatar:t,showQuestion:a,questionDisabled:!e.canSend||e.answeredQuestions.has(r),onSelect:t=>e.answerQuestion(n,t),onSkip:()=>void e.dismissQuestion(n),showWizardStep:n===i,wizardValue:e.wizardValue,wizardDisabled:!e.canSend,wizardSecretVisible:e.wizardSecretVisible,onWizardValueChange:t=>e.setWizardValue(t),onWizardAnswer:t=>e.answerWizardStep(n,t),showWizardCancel:e.wizardCancelAvailable,onWizardCancel:()=>e.cancelWizardStep(n),onToggleWizardSecretVisibility:()=>e.toggleWizardSecretVisibility()})})}
${e.sending?g`<div class="chat-group assistant custodian__thinking-row" role="status">
<div class="chat-avatar assistant custodian__mascot-avatar" aria-hidden="true">
<openclaw-mascot mood="thinking" .size=${26}></openclaw-mascot>
</div>
<div class="chat-group-messages custodian__thinking">
<span></span><span></span><span></span>
<span class="sr-only">${b(`custodian.thinking`)}</span>
</div>
</div>`:_}
${e.abandonedTurnOutcomeUnknown?g`<div class="custodian__error" role="alert">
<span>${b(`custodian.connectionChanged`)}</span>
</div>`:_}
${Ve({status:e.transcript.status,onRetry:()=>void e.refreshTranscriptIfIdle(),retryDisabled:!e.canRefreshTranscript(),className:`custodian__transcript-status`})}
${e.error&&!(e.abandonedTurnOutcomeUnknown&&e.error===b(`custodian.connectionChanged`))?g`<div class="custodian__error" role="alert">
<span>${e.error}</span>
${e.activeClient&&e.chatAvailable&&e.canRetry()?g`<button
class="btn btn--sm"
type="button"
=${()=>e.retry()}
>
${b(`common.retry`)}
</button>`:_}
</div>`:_}
</div>
${this.historyContent}
${i?_:g`<div class="agent-chat__composer-shell">
<div class="agent-chat__input">
<div class="agent-chat__composer-input-row">
<div class="agent-chat__composer-combobox">
${e.sensitive?g`<input
type="password"
.value=${e.input}
autocomplete="off"
placeholder=${b(`custodian.sensitivePlaceholder`)}
aria-label=${b(`custodian.sensitivePlaceholder`)}
?disabled=${!e.canSend}
=${t=>e.setInput(t.target.value)}
=${e=>this.handleComposerKeydown(e)}
/>`:g`<textarea
rows="1"
.value=${e.input}
autocomplete="on"
placeholder=${b(`custodian.placeholder`)}
aria-label=${b(`custodian.placeholder`)}
?disabled=${!e.canSend}
=${t=>e.setInput(t.target.value)}
=${e=>this.handleComposerKeydown(e)}
></textarea>`}
</div>
<div class="agent-chat__composer-actions">
<button
class="chat-send-btn"
type="button"
aria-label=${b(`custodian.send`)}
?disabled=${!e.input.trim()||!e.canSend}
=${()=>void e.send()}
>
${Oe.arrowUp}
<span class="agent-chat__control-label">${b(`custodian.send`)}</span>
</button>
</div>
</div>
</div>
</div>`}
</section>
`}},s([i({context:ye,subscribe:!0})],Q.prototype,`context`,void 0),s([v({attribute:!1})],Q.prototype,`store`,void 0),s([v({attribute:!1})],Q.prototype,`onboarding`,void 0),s([v({attribute:!1})],Q.prototype,`newAgentIntent`,void 0),s([v({attribute:!1})],Q.prototype,`showChannelOnboardingNudge`,void 0),s([v({attribute:!1})],Q.prototype,`channelOnboardingError`,void 0),s([v({attribute:!1})],Q.prototype,`channelOnboardingRetrying`,void 0),s([v({attribute:!1})],Q.prototype,`onRetryChannelOnboarding`,void 0),s([v({attribute:!1})],Q.prototype,`compact`,void 0),s([v({attribute:!1})],Q.prototype,`historyContent`,void 0),customElements.get(`openclaw-custodian-surface`)||customElements.define(`openclaw-custodian-surface`,Q)})))()}export{Z as i,Vt as n,X as r,$ as t};
//# sourceMappingURL=custodian-surface-B8--KKtk.js.map