UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

476 lines 58 kB
import{n as e}from"./rolldown-runtime-DkW27tQK.js";import{Kt as t,R as n,wr as r,z as i}from"./control-ui-foundation-Cydpkyqa.js";import{As as a,Bn as o,Cc as s,Do as c,Eo as l,Ga as ee,Oo as u,Sc as te,Wa as ne,bc as re,cr as ie,dr as ae,ur as oe,zn as se,zs as ce}from"./control-ui-core-Rwzhj6nO.js";import{$ as le,C as ue,K as d,X as f,at as p,b as de,q as m,st as fe}from"./lit-runtime-CV_MH99K.js";import{An as pe,Zt as h,_ as me,_n as he,g as ge,jn as _e,nn as ve}from"./control-ui-core-YphAl4aM.js";import{Gt as g,Q as ye,Rt as _,Wt as v,Yt as y,Z as be,en as b}from"./control-ui-core-vvcQQV2m.js";import{B as x,Er as xe,Ir as Se,Lr as Ce,Mr as S,Nr as we,Pr as Te,V as Ee,jr as De,wr as Oe,z as ke}from"./control-ui-boot-shared-BYq7Cchl.js";import{a as C,r as Ae}from"./gateway-runtime-Bqqcp9-I.js";import{Ca as je,Ea as Me,Sa as w,Ta as T,wa as E,xa as D}from"./control-ui-boot-shared-DfZ39Yj9.js";import{L as Ne,z as Pe}from"./control-ui-boot-chat-_QSl8fbH.js";import{ui as Fe}from"./control-ui-boot-shared-CXVvK2AW.js";import{r as Ie,t as Le}from"./wizard-step-controls-BcNiLuAR.js";import{p as Re,u as ze}from"./control-ui-boot-chat-D85X0PFX.js";import{n as Be,t as Ve}from"./settings-workspace-Bseic8Tf.js";var O,He;function Ue(){return(Ue=e((()=>{Ce(),O=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if(we(e),De(t,void 0,`key`),this.iHash=e.create(),typeof this.iHash.update!=`function`)throw Error(`expected Hash instance`);this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,r=new Uint8Array(n);r.set(t.length>n?e.create().update(t).digest():t);for(let e=0;e<r.length;e++)r[e]^=54;this.iHash.update(r),this.oHash=e.create();for(let e=0;e<r.length;e++)r[e]^=106;this.oHash.update(r),Se(r)}update(e){return S(this),this.iHash.update(e),this}digestInto(e){S(this),Te(e,this),this.finished=!0;let t=e.subarray(0,this.outputLen);this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:n,finished:r,destroyed:i,blockLen:a,outputLen:o,canXOF:s}=this;return e=e,e.finished=r,e.destroyed=i,e.blockLen=a,e.outputLen=o,e.canXOF=s,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},He=(()=>{let e=((e,t,n)=>new O(e,t).update(n).digest());return e.create=(e,t)=>new O(e,t),e})()})))()}function We(e){return e===`provider-auth`?15e5:Ze}function k(e,t){return`${e}\u0000${t}`}function Ge(e){let{result:t}=e;if(t.ok&&t.modelRef){let n=[t.gatewayRestartRequired?e.restartWarning:null,e.refreshWarning].filter(Boolean).join(`
`);return{phase:`success`,modelRef:t.modelRef,...typeof t.latencyMs==`number`?{latencyMs:t.latencyMs}:{},...n?{warning:n}:{}}}return{phase:`failure`,targetId:e.targetId,status:t.status&&t.status!==`ok`?t.status:`unknown`,error:c(t.error,e.fallbackError)}}function Ke(e){return e.ok?{phase:`ok`,modelRef:e.modelRef,...typeof e.latencyMs==`number`?{latencyMs:e.latencyMs}:{}}:{phase:`failed`,status:e.status,error:c(e.error)}}function qe(e,t,n){return!t.done&&t.step?{phase:`step`,authChoice:e,step:t.step,busy:!1,validationError:t.error?.trim()?c(t.error):null}:t.done&&t.status===`done`?{phase:`done`,authChoice:e,...t.preparedModelRef?{preparedModelRef:t.preparedModelRef}:{}}:t.status===`cancelled`?{phase:`cancelled`,message:c(t.error,n)}:{phase:`error`,message:c(t.error,n)}}function Je(e){return e.type===`multiselect`?Array.isArray(e.initialValue)?[...e.initialValue]:[]:e.initialValue}var Ye,Xe,Ze,A;function j(){return(j=e((()=>{u(),Ye=4e4,Xe=3e4,Ze=48e4,A=3e4})))()}function Qe(e){let t=t=>{t.key===I&&t.newValue===null&&t.oldValue&&e(t.oldValue)};return z.add(e),window.addEventListener(`storage`,t),()=>{z.delete(e),window.removeEventListener(`storage`,t)}}function $e(e,t,n){try{let r=JSON.parse(n.getItem(L)??`null`);if(r?.version!==1||typeof r.privateKey!=`string`||!r.privateKey)return null;let i=e.gateway.connection,a=i.token||i.password||i.bootstrapToken,o=a?``:e.gateway.snapshot.hello?.auth?.deviceToken;if(!a&&!o)return null;let s=[t.gatewayUrl,t.agentId,t.modelRef??``,t.kind,String(t.deadlineMs),i.token,i.password,i.bootstrapToken,i.bootstrapProfile??``,o??``],c=new TextEncoder,l=s.map(e=>`${c.encode(e).length}:${e}`).join(`|`);return Array.from(He(xe,c.encode(r.privateKey),c.encode(l))).map(e=>e.toString(16).padStart(2,`0`)).join(``)}catch{return null}}function M(e,t){try{let n=e.getItem(I);if((t===void 0||t&&n===JSON.stringify(t))&&(e.removeItem(I),n))for(let e of z)e(n)}catch{}}function N(e,n){let r=s();if(!r||e.gateway.snapshot.phase!==`connected`)return null;try{let i=r.getItem(I);if(!i||n&&i!==JSON.stringify(n))return null;let a=JSON.parse(i);if(a?.version!==1||typeof a.gatewayUrl!=`string`||typeof a.agentId!=`string`||a.modelRef!==null&&typeof a.modelRef!=`string`||typeof a.kind!=`string`||typeof a.deadlineMs!=`number`||!Number.isFinite(a.deadlineMs)||a.deadlineMs<=Date.now()||typeof a.owner!=`string`||a.gatewayUrl!==t(e.gateway.connection.gatewayUrl)||a.agentId!==(e.agentSelection.state.selectedId??``))return M(r),null;let{owner:o,...s}=a;return $e(e,s,r)===o?a:(M(r),null)}catch{return M(r),null}}function P(e){return Date.now()+We(e)+R}function et(e,n){let r=s();if(!r||e.gateway.snapshot.phase!==`connected`)return null;try{let i={version:1,gatewayUrl:t(e.gateway.connection.gatewayUrl),agentId:e.agentSelection.state.selectedId??``,modelRef:n.modelRef??null,kind:n.kind,deadlineMs:n.deadlineMs??P(n.kind)},a=$e(e,i,r);if(!a)return null;let o={...i,owner:a};return r.setItem(I,JSON.stringify(o)),o}catch{return null}}function F(e){let t=s();t&&M(t,e)}function tt(e,t,n,r,i,a){let{context:o}=e,s=o.gateway.snapshot;!i()&&s.phase===`connected`&&s.client===t.client&&s.hello===t.hello&&o.gateway.connectionRevision===n&&(o.agentSelection.state.selectedId?.trim()||null)===r&&e.isStillDefaultLanding()&&N(o)!==null&&e.redirect(),a()}var I,L,R,z;function B(){return(B=e((()=>{Ue(),Oe(),j(),I=`openclaw.modelSetup.pendingActivation.v1`,L=`openclaw-device-identity-v1`,R=5e3,z=new Set})))()}function V(e){return l(e,b(`modelSetup.errors.requestFailed`))}async function H(e,t){try{return{client:e,value:await t()}}catch(t){return{client:e,error:t}}}function U(){return(U=e((()=>{y(),u()})))()}var W;function G(){return(G=e((()=>{y(),B(),U(),j(),W=class{constructor(e){this.host=e,this.generation=0,this.started=!1,this.readyConnection=null,this.pending=null}subscribe(e){return Qe(t=>{let n=this.pending;n?.receipt&&JSON.stringify(n.receipt)===t&&(this.pending=null,n.outcome===`verified`&&this.host.setActivationState({phase:`idle`}),this.host.setVerifyState({phase:`idle`}),e())})}setReadyConnection(e){this.readyConnection=e}routeChanged(){this.reset(),this.readyConnection=null,this.pending=null,this.host.routeData()?.firstRun===!1&&F()}connectionChanged(e){this.reset(),this.readyConnection=null,this.pending&&(e.client!==this.pending.owner.connection.client||e.agentId!==this.pending.owner.connection.agentId||this.host.context().gateway.connectionRevision!==this.pending.owner.connectionRevision)&&(this.pending=null)}retryDetection(){if(this.host.actionsDisabled())return!1;if(this.pending&&Date.now()<this.pending.deadlineMs)return this.host.setRefreshWarning(b(`modelSetup.recovery.wait`)),!1;if(this.host.routeData()?.firstRun){let e=this.host.pageState(),t=this.pending&&e.phase===`ready`&&e.result.configuredModel;this.pending=null,F(),this.host.setRefreshWarning(null),this.reset(),this.started=!!t}return!0}dispose(){this.reset(),this.readyConnection=null,this.pending=null}visiblePageState(e){let t=this.host.pageState();return this.host.routeData()?.firstRun&&t.phase===`ready`&&t.result.setupComplete&&t.result.configuredModel&&!e?{...t,result:{...t.result,setupComplete:!1}}:t}start(){let e=this.host.routeData(),t=this.host.context(),n=t.gateway.snapshot,r=this.host.pageState(),i=this.readyConnection;if(!e?.firstRun||this.started||r.phase!==`ready`||!i||i.client!==n.client||i.hello!==n.hello||i.agentId!==t.agentSelection.state.selectedId||this.host.actionsDisabled()||!this.host.canUseSetup(n.client))return;let a=N(t);this.pending?.receipt&&a?.owner!==this.pending.receipt.owner&&(this.pending=null);let o=a??this.pending;o&&(this.pending={owner:this.owner(e.firstRun),modelRef:o.modelRef,kind:o.kind,deadlineMs:o.deadlineMs,receipt:a,outcome:`pending`});let s=r.result.setupComplete&&r.result.configuredModel;if(this.pending&&(!s||!this.pending.modelRef)){this.started=!0,this.showUnresolved();return}if(s&&!this.host.canVerify(n.client)){this.started=!0,this.host.setVerifyState({phase:`failed`,status:`unknown`,error:`${b(`modelSetup.access.gatewayTooOld`)}. ${b(`updates.confirm.action`)}. ${b(`desktop.reconnect`)}.`});return}this.started=!0,this.run(this.owner(e.firstRun),r.result)}beginActivation(e){let t=this.host.routeData();if(!t?.firstRun)return null;let n=this.owner(t.firstRun),r=et(this.host.context(),e);return this.pending={owner:n,kind:e.kind,modelRef:e.modelRef??null,receipt:r,outcome:`pending`,deadlineMs:r?.deadlineMs??P(e.kind)},this.started=!0,this.pending}recordActivation(e,t){if(e){if(!t.ok){this.ownsActivation(e)&&(e.outcome=`rejected`),F(e.receipt),this.pending===e&&(this.pending=null);return}!t.modelRef||this.pending!==e||!this.ownsActivation(e)||(e.modelRef=t.modelRef,e.outcome=`verified`,e.receipt=et(this.host.context(),e))}}finishActivation(e,t,n){!this.pending||!this.ownsActivation()||!e.ok||!e.modelRef||(e.gatewayRestartRequired?(this.host.setActivationState({phase:`testing`,targetId:t}),this.host.setRefreshWarning(n??b(`updates.dialog.restarting`))):n||this.completeNavigation())}get unresolved(){return this.pending!==null}async useCurrentModel(){let e=this.host.pageState(),t=this.pending;if(!t||e.phase!==`ready`||!e.result.configuredModel||this.host.actionsDisabled())return;let n=e.result.configuredModel,r=this.owner(t.owner.firstRun),i=await this.verify();!this.owns(r)||this.pending!==t||!i||`error`in i||(i.value.ok&&i.value.modelRef===n?this.completeNavigation():i.value.ok&&this.showUnresolved())}owner(e){let t=this.host.context();return{generation:this.generation,firstRun:e,connectionRevision:t.gateway.connectionRevision,connection:{client:t.gateway.snapshot.client,hello:t.gateway.snapshot.hello,agentId:t.agentSelection.state.selectedId}}}clearPending(){this.pending=null,F()}ownsActivation(e=this.pending){return e?this.owns(e.owner)?e.outcome===`rejected`?this.pending===null:this.pending===e&&(!e.receipt||N(this.host.context(),e.receipt)!==null)&&Date.now()<e.deadlineMs:!1:!this.host.routeData()?.firstRun}async verify(){let e=this.host.routeData();if(!e)return;let t=this.owner(e.firstRun),n=this.pending,r=await this.host.verify();if(!(!this.owns(t)||!r)){if(this.pending!==n||n&&!this.ownsActivation(n)){this.host.setVerifyState({phase:`idle`});return}return this.host.setVerifyState(`error`in r?{phase:`failed`,status:`unknown`,error:V(r.error)}:Ke(r.value)),r}}continueSetup(){this.pending?this.pending.outcome===`verified`&&this.ownsActivation()&&this.completeNavigation():this.host.context().navigate(`chat`)}completeNavigation(){this.clearPending(),this.host.setRefreshWarning(null),this.host.context().navigate(`custodian`,{search:`?onboarding=1`})}showUnresolved(){this.host.setRefreshWarning(null),this.host.setVerifyState({phase:`failed`,status:`unknown`,error:`${b(`modelSetup.errors.activationFailed`)} ${this.pending?.modelRef??``}`.trim()})}reset(){this.generation+=1,this.started=!1}owns(e){let t=this.host.context(),n=t.gateway.snapshot;return e.generation===this.generation&&e.connectionRevision===t.gateway.connectionRevision&&e.firstRun===this.host.routeData()?.firstRun&&n.phase===`connected`&&n.client===e.connection.client&&n.hello===e.connection.hello&&t.agentSelection.state.selectedId===e.connection.agentId}async run(e,t){if(t.setupComplete&&t.configuredModel){if(this.pending&&t.configuredModel!==this.pending.modelRef){this.showUnresolved();return}let n=await this.verify();if(!this.owns(e)||!n||`error`in n)return;if(n.value.ok){this.finishVerified(n.value.modelRef);return}if(this.pending||n.value.status===`unavailable`)return}for(let n of t.candidates){let r=k(n.kind,n.modelRef);if(!(n.credentials===!1||t.configuredModel&&(n.kind===`existing-model`||n.modelRef===t.configuredModel))){if(!this.owns(e))return;await this.host.activate(n,r);return}}}finishVerified(e){this.pending?this.pending.modelRef===e?this.completeNavigation():this.showUnresolved():this.host.context().navigate(`chat`)}}})))()}function K(e){return e.brandId&&D(e.brandId)?e.brandId:null}function q(e,t,n=``){let r=K(t);if(r)return T(r,{className:`model-setup__icon ${n}`.trim()});let i=t.icon?e.iconUrls[t.icon]:void 0;return!t.icon||!i?Me(t.label,{className:`model-setup__icon ${n}`.trim()}):f`<img
    class=${`model-setup__icon ${n}`.trim()}
    src=${i}
    alt=${t.label}
    width="24"
    height="24"
    @error=${()=>e.onIconError(t.icon)}
  />`}var nt;function J(){return(J=e((()=>{d(),w(),Re(),nt=class{constructor(e,t,n){this.getContext=e,this.getPageState=t,this.onChange=n,this.urls={},this.misses=new Set,this.requests=new Map}reconcile(){let e=this.currentIconUrls(),t={...this.urls},n=!1;for(let[r,i]of Object.entries(t))e.has(r)||(URL.revokeObjectURL(i),delete t[r],n=!0);n&&this.publish(t);for(let[t,n]of this.requests)e.has(t)||(clearTimeout(n.timeout),n.controller.abort(),this.requests.delete(t));for(let t of this.misses)e.has(t)||this.misses.delete(t);for(let t of e)!this.urls[t]&&!this.misses.has(t)&&!this.requests.has(t)&&this.fetch(t)}invalidate(e){let t=this.requests.get(e);t&&(clearTimeout(t.timeout),t.controller.abort(),this.requests.delete(e));let n=this.urls[e];n&&URL.revokeObjectURL(n);let r={...this.urls};delete r[e],this.publish(r),this.misses.add(e)}reset(){for(let e of this.requests.values())clearTimeout(e.timeout),e.controller.abort();for(let e of Object.values(this.urls))URL.revokeObjectURL(e);this.requests.clear(),this.misses.clear(),this.publish({})}currentIconUrls(){let e=this.getPageState();if(e.phase!==`ready`)return new Set;let t=e.result;return new Set([...t.candidates,...t.unavailableCandidates??[],...t.manualProviders,...t.authOptions??[],...t.prepareOptions??[],...t.recommendedInstalls??[]].flatMap(e=>e.icon&&!K(e)?[e.icon]:[]))}fetch(e){let t=new AbortController,n=setTimeout(()=>t.abort(new DOMException(`catalog icon fetch timed out`,`TimeoutError`)),1e4),r={controller:t,timeout:n};this.requests.set(e,r);let i=this.getContext();ze({iconUrl:e,resourceBasePath:i.resourceBasePath,gatewayUrl:i.gateway.connection.gatewayUrl,auth:{hello:i.gateway.snapshot.hello,settings:{token:i.gateway.connection.token},password:i.gateway.connection.password},signal:t.signal}).then(t=>{if(this.requests.get(e)!==r||this.getContext().gateway.snapshot.phase!==`connected`||!this.currentIconUrls().has(e)){t&&URL.revokeObjectURL(t);return}t?this.publish({...this.urls,[e]:t}):this.misses.add(e)}).catch(()=>{this.requests.get(e)===r&&this.misses.add(e)}).finally(()=>{clearTimeout(n),this.requests.get(e)===r&&this.requests.delete(e)})}publish(e){this.urls=e,this.onChange(e)}}})))()}function Y(e){return`provider-auto:${encodeURIComponent(e)}`}function rt(e){let t=[{id:`ollama`,brandId:`ollama`,label:b(`modelSetup.prepare.ollamaLabel`),hint:b(`modelSetup.prepare.ollamaHint`)},{id:`llama-cpp`,brandId:`llama-cpp`,label:b(`modelSetup.prepare.llamaCppLabel`)}];return(e.prepareOptions??t).filter(t=>!e.candidates.some(e=>e.credentials!==!1&&(e.kind===Y(t.id)||e.modelRef.startsWith(`${t.brandId??t.id}/`))))}function it(e,t){return e.candidates.find(e=>e.kind===Y(t)&&e.credentials!==!1)}function X(){return(X=e((()=>{y()})))()}function at(e,t,n){return e.request(`openclaw.setup.detect`,t?{agentId:t}:{},{timeoutMs:Ye,...n?{signal:n}:{}})}function ot(e,t,n){return e.request(`openclaw.setup.verify`,t?{agentId:t}:{},{timeoutMs:Xe,...n?{signal:n}:{}})}function st(){return(st=e((()=>{j()})))()}function ct(e){let t={auth:b(`modelSetup.failure.auth`),rate_limit:b(`modelSetup.failure.rateLimit`),billing:b(`modelSetup.failure.billing`),timeout:b(`modelSetup.failure.timeout`),format:b(`modelSetup.failure.format`),unavailable:b(`modelSetup.failure.unavailable`),unknown:b(`modelSetup.failure.unknown`)};return t[e]??t.unknown}function lt(e){let t={auth:b(`modelSetup.failureGuidance.auth`),rate_limit:b(`modelSetup.failureGuidance.rateLimit`),billing:b(`modelSetup.failureGuidance.billing`),timeout:b(`modelSetup.failureGuidance.timeout`),format:b(`modelSetup.failureGuidance.format`),unavailable:m,unknown:b(`modelSetup.failureGuidance.unknown`)};return t[e]??t.unknown}function ut(e,t){return f`
    <div class="model-setup__failure" role="alert">
      <span class="model-setup__failure-icon" aria-hidden="true">${v.alertTriangle}</span>
      <span><strong>${ct(e)}.</strong> ${t} ${lt(e)}</span>
    </div>
  `}function dt(e){let t=e.indexOf(`/`);return t<0?e:e.slice(t+1)}function ft(e,t){return e.candidates.find(e=>e.modelRef===t)}function pt(e,t){let n=dt(t),r=e?.detail.trim();return!r||e?.kind===`existing-model`?n:r.toLowerCase().includes(n.toLowerCase())?r:`${n} · ${r}`}function mt(e){switch(e.phase){case`checking`:return b(`modelSetup.verify.checkingButton`);case`failed`:return b(`modelSetup.verify.retry`);case`ok`:return b(`modelSetup.verify.checkAgain`);default:return b(`modelSetup.verify.button`)}}function ht(e){let t=e.result.configuredModel,n=e.verify.phase===`ok`?e.verify.modelRef:t,r=E(n),i=n===t?ft(e.result,t):void 0,a=r?je(r):n,o=pt(i,n);return f`
    <section class="settings-section model-setup__current" data-verify-phase=${e.verify.phase}>
      <div class="settings-section__header">
        <h2>${b(`modelSetup.verify.title`)}</h2>
      </div>
      <div class="model-setup__row">
        <div class="model-setup__provider-copy">
          ${r?T(r,{className:`model-setup__icon`}):m}
          <div class="model-setup__current-copy">
            <strong>${a}</strong>
            <div class="muted">${o}</div>
            ${e.verify.phase===`checking`?f`<div class="model-setup__testing" role="status">
                    ${b(`modelSetup.verify.checking`,{modelRef:t})}
                  </div>`:e.verify.phase===`ok`?f`<div class="model-setup__verified" role="status">
                      ${e.verify.latencyMs===void 0?b(`modelSetup.verify.ready`):b(`modelSetup.verify.readyIn`,{latencyMs:String(e.verify.latencyMs)})}
                    </div>`:e.verify.phase===`failed`?ut(e.verify.status,e.verify.error):m}
          </div>
        </div>
        <div class="model-setup__row-actions">
          ${e.canVerify?f`<button
                  type="button"
                  class="btn"
                  ?disabled=${e.actionsDisabled}
                  @click=${e.onVerify}
                >
                  ${mt(e.verify)}
                </button>`:m}
          ${e.onContinue?f`<button type="button" class="btn primary" @click=${e.onContinue}>
                  ${v.messageSquare} ${b(`modelSetup.success.continueSetup`)}
                </button>`:m}
        </div>
      </div>
    </section>
  `}function gt(){return(gt=e((()=>{d(),g(),w(),y()})))()}function _t(e){let t=e.currentTarget,n=Array.from(t.querySelectorAll(`wa-dropdown-item[data-manual-provider]:not([disabled])`)),r=n.find(e=>e.hasAttribute(`data-selected`))??n[0];if(r){for(let e of n)e.active=e===r;r.focus({preventScroll:!0}),r.scrollIntoView?.({block:`nearest`})}}function vt(e){let t=e.currentTarget;if(t.open){if(e.key===`Tab`){e.preventDefault(),e.stopPropagation();let n=e.shiftKey?t.querySelector(`[slot="trigger"]`):t.closest(`.model-setup__manual`)?.querySelector(`input[type="password"]`);t.addEventListener(`wa-after-hide`,()=>n?.focus({preventScroll:!0}),{once:!0}),t.open=!1;return}e.key===`Escape`&&(e.preventDefault(),t.addEventListener(`wa-after-hide`,()=>t.querySelector(`[slot="trigger"]`)?.focus({preventScroll:!0}),{once:!0}))}}function yt(e,t,n){let r=e.detail.item,i=e.currentTarget,a=r.value??r.getAttribute(`value`);if(a){if(a!==t){i.addEventListener(`wa-after-hide`,()=>i.querySelector(`[slot="trigger"]`)?.focus({preventScroll:!0}),{once:!0}),n(a);return}e.preventDefault(),r.checked=!0,i.querySelector(`[slot="trigger"]`)?.focus({preventScroll:!0}),i.open=!1}}function Z(e){return e.groupLabel?.trim()||e.label}function bt(e){let t=e.label.trim();return t===Z(e)?void 0:t}function xt(e,t,n){let r=n?bt(n):void 0,i=n?[Z(n),r].filter(Boolean).join(`, `):b(`modelSetup.manual.selectProvider`);return f`
    <wa-dropdown
      class="model-setup-provider-select"
      placement="bottom-start"
      aria-label=${b(`modelSetup.manual.provider`)}
      @wa-select=${t=>yt(t,e.manualProviderId,e.onManualProviderChange)}
      @wa-after-show=${_t}
      @keydown=${vt}
    >
      <button
        slot="trigger"
        type="button"
        class="model-setup-provider-select__trigger"
        aria-label=${`${b(`modelSetup.manual.provider`)}: ${i}`}
        ?disabled=${e.actionsDisabled||t.manualProviders.length===0}
      >
        ${n?q(e,n,`model-setup__icon--picker`):f`<span class="model-setup-provider-select__placeholder-icon" aria-hidden="true">
                ${v.key}
              </span>`}
        <span class="model-setup-provider-select__copy">
          <strong>
            ${n?Z(n):b(`modelSetup.manual.selectProvider`)}
          </strong>
          ${n?r?f`<span>${r}</span>`:m:f`<span>${b(`modelSetup.manual.selectProviderHint`)}</span>`}
        </span>
        <span class="model-setup-provider-select__chevron" aria-hidden="true">
          ${v.chevronDown}
        </span>
      </button>
      ${t.manualProviders.map(t=>{let n=t.id===e.manualProviderId,r=bt(t),i=[Z(t),r,t.hint].filter(Boolean).join(`, `);return f`
          <wa-dropdown-item
            class="model-setup-provider-select__option"
            data-manual-provider=${t.id}
            ?data-selected=${n}
            aria-label=${i}
            .value=${t.id}
            type="checkbox"
            .checked=${n}
            ?disabled=${e.actionsDisabled}
            ${ue(e=>ye(e,n))}
          >
            <span slot="icon">
              ${q(e,t,`model-setup__icon--picker`)}
            </span>
            <span class="model-setup-provider-select__copy">
              <strong>${Z(t)}</strong>
              ${r?f`<span>${r}</span>`:m}
              ${t.hint?f`<small>${t.hint}</small>`:m}
            </span>
          </wa-dropdown-item>
        `})}
    </wa-dropdown>
  `}function St(){return(St=e((()=>{d(),de(),g(),be(),y(),J()})))()}function Ct(e,t,n,r){let i=E(e.modelRef),a=i&&D(i)?i:null,o=e.warning??b(`modelSetup.success.body`,{modelRef:e.modelRef}),s=r?b(`modelSetup.success.continueSetup`):e.warning?b(`tabs.chat`):b(`modelSetup.success.openChat`);return f`
    <openclaw-modal-dialog
      label=${b(`modelSetup.success.title`)}
      description=${o}
      @modal-cancel=${n}
    >
      <section class="model-setup-success" role="status">
        <div
          class=${`model-setup-success__icon${a?` model-setup-success__icon--provider`:``}`}
          aria-hidden="true"
        >
          ${a?f`
                  ${T(a,{className:`model-setup-success__provider-icon`})}
                  <span class="model-setup-success__status-badge">${v.check}</span>
                `:v.shieldCheck}
        </div>
        <div class="model-setup-success__copy">
          <h2>${b(`modelSetup.success.title`)}</h2>
          ${e.warning?m:f`<p>${o}</p>`}
        </div>
        ${e.warning?f`<div class="model-setup-success__warning">${e.warning}</div>`:m}
        <div class="model-setup-success__summary">
          <span>${b(`modelSetup.success.activeModel`)}</span>
          <strong>${e.modelRef}</strong>
          ${e.latencyMs===void 0?m:f`<span>
                  ${b(`modelSetup.success.latency`,{latencyMs:String(e.latencyMs)})}
                </span>`}
        </div>
        <footer class="model-setup-success__actions">
          <button type="button" class="btn" @click=${n}>
            ${b(`modelSetup.success.stayHere`)}
          </button>
          <button type="button" class="btn primary" autofocus @click=${t}>
            ${v.messageSquare} ${s}
          </button>
        </footer>
      </section>
    </openclaw-modal-dialog>
  `}function wt(){return(wt=e((()=>{d(),g(),_(),w(),y()})))()}function Tt(e){if(e.state.phase===`idle`)return m;let t=e.state.phase===`starting`||e.state.phase===`step`||e.state.phase===`done`;return f`
    <openclaw-modal-dialog
      label=${b(e.mode===`prepare`?`modelSetup.wizard.prepareDialogLabel`:e.mode===`activate`?`modelSetup.heading`:`modelSetup.wizard.dialogLabel`)}
      @modal-cancel=${t?e.onCancel:e.onClose}
    >
      <div class="model-setup-wizard">
        <div class="model-setup-wizard__header">
          <h2>
            ${e.state.phase===`step`&&e.state.step.title?e.state.step.title:b(e.mode===`prepare`?`modelSetup.wizard.prepareTitle`:e.mode===`activate`?`modelSetup.heading`:`modelSetup.wizard.title`)}
          </h2>
        </div>
        <div class="model-setup-wizard__body">
          ${e.refreshWarning?f`<div class="callout warning" role="alert">${e.refreshWarning}</div>`:m}
          ${e.state.phase===`starting`?f`<div role="status">
                  ${b(e.mode===`prepare`?`modelSetup.wizard.prepareStarting`:e.mode===`activate`?`modelSetup.wizard.checking`:`modelSetup.wizard.starting`)}
                </div>`:e.state.phase===`done`?f`<div role="status">${b(`modelSetup.wizard.checking`)}</div>`:e.state.phase===`error`||e.state.phase===`cancelled`?f`<div class="callout danger" role="alert">${e.state.message}</div>`:f`
                      ${e.state.validationError?f`<div class="callout danger" role="alert">
                              ${e.state.validationError}
                            </div>`:m}
                      ${Ie({step:e.state.step,value:e.value,busy:e.state.busy,inputId:Et,confirmAffirmativeLabel:e.mode===`prepare`&&e.state.step.type===`confirm`?b(`modelSetup.wizard.continue`):void 0,leadingAction:f`<button
                          type="button"
                          class="btn"
                          @click=${e.onCancel}
                        >
                          ${b(`common.cancel`)}
                        </button>`,onValueChange:e.onValueChange,onAnswer:e.onAnswer})}
                      ${e.state.busy?f`<div role="status">${b(`modelSetup.wizard.working`)}</div>`:m}
                    `}
        </div>
        ${e.state.phase===`step`?m:f`
                <div class="model-setup-wizard__footer">
                  <button
                    type="button"
                    class="btn"
                    @click=${t?e.onCancel:e.onClose}
                  >
                    ${b(t?`common.cancel`:`common.close`)}
                  </button>
                </div>
              `}
      </div>
    </openclaw-modal-dialog>
  `}var Et;function Dt(){return(Dt=e((()=>{d(),Le(),y(),_(),Et=`model-setup-wizard-text-input`})))()}function Ot(e){return e.recommended?b(`modelSetup.candidates.recommended`):e.credentials===!0?b(`modelSetup.candidates.credentialsReady`):e.credentials===!1?b(`modelSetup.candidates.signInNeeded`):b(`modelSetup.candidates.detected`)}function kt(e,t){let n=t.configuredModel?t.candidates.filter(e=>e.kind!==`existing-model`&&e.modelRef!==t.configuredModel):t.candidates;return n.length===0?m:f`
    <section class="settings-section">
      <div class="settings-section__header">
        <h2>${b(`modelSetup.candidates.title`)}</h2>
      </div>
      <div class="model-setup__rows">
        ${n.map(t=>{let n=e.activation.phase===`testing`&&e.activation.targetId===k(t.kind,t.modelRef),r=e.activation.phase===`failure`&&e.activation.targetId===k(t.kind,t.modelRef)?e.activation:null;return f`
            <div class="model-setup__row" data-candidate-kind=${t.kind}>
              <div class="model-setup__row-main">
                <div class="model-setup__row-title">
                  ${q(e,t)}
                  <strong>${t.label}</strong>
                  <span class="model-setup__chip">${Ot(t)}</span>
                </div>
                <div class="muted">
                  ${t.modelRef} · ${c(t.detail)}
                </div>
              </div>
              <div class="model-setup__row-actions">
                <button
                  type="button"
                  class=${`btn ${r?``:`primary`}`}
                  ?disabled=${e.actionsDisabled}
                  @click=${()=>e.onActivateCandidate(t)}
                >
                  <span>
                    ${b(n?`modelSetup.candidates.testingButton`:r?`modelSetup.candidates.retry`:`modelSetup.candidates.testAndUse`)}
                  </span>
                </button>
              </div>
            </div>
          `})}
      </div>
    </section>
  `}function At(e,t){let n=t.recommendedInstalls??[];return t.candidates.length>0||(t.authOptions?.length??0)>0||n.length===0?m:f`
    <section class="settings-section model-setup__empty">
      <div class="settings-section__header">
        <h2>${b(`modelSetup.empty.title`)}</h2>
      </div>
      <p class="muted">${b(`modelSetup.empty.intro`)}</p>
      <div class="model-setup__recommendations">
        ${n.map(t=>f`
            <div class="model-setup__recommendation" data-recommended-install=${t.id}>
              ${q(e,t,`model-setup__icon--recommendation`)}
              <div class="model-setup__row-main">
                <strong>${t.label}</strong>
                <div class="muted">${t.hint}</div>
                <a href=${t.website} target="_blank" rel="noopener">${t.website}</a>
              </div>
            </div>
          `)}
      </div>
    </section>
  `}function jt(e,t){return t.unavailableCandidates?.length?f`
    <section class="settings-section">
      <div class="settings-section__header">
        <h2>${b(`modelSetup.unavailable.title`)}</h2>
      </div>
      <div class="model-setup__rows">
        ${t.unavailableCandidates.map(n=>{let r=(t.authOptions??[]).find(e=>e.id===n.authOptionId),i=t.manualProviders.find(e=>e.id===n.manualProviderId);return f`
            <div
              class="model-setup__row model-setup__row--info"
              data-unavailable-candidate=${n.id}
            >
              <div class="model-setup__provider-copy">
                ${q(e,n)}
                <div>
                  <div>
                    <strong>${n.label}</strong> — ${c(n.detail)}
                  </div>
                  <div class="muted">${c(n.reason)}</div>
                </div>
              </div>
              <div class="model-setup__row-actions">
                ${r?f`<button
                        type="button"
                        class="btn primary"
                        ?disabled=${e.actionsDisabled}
                        @click=${()=>e.onStartAuth(r)}
                      >
                        ${b(`modelSetup.unavailable.signIn`,{provider:r.groupLabel??r.label})}
                      </button>`:m}
                ${i?f`<button
                        type="button"
                        class="btn"
                        ?disabled=${e.actionsDisabled}
                        @click=${()=>e.onUseManualProvider(i.id)}
                      >
                        ${b(`modelSetup.unavailable.useApiKey`)}
                      </button>`:m}
                <button
                  type="button"
                  class="btn"
                  ?disabled=${e.actionsDisabled}
                  @click=${e.onDetect}
                >
                  ${b(`modelSetup.checkAgain`)}
                </button>
              </div>
            </div>
          `})}
      </div>
    </section>
  `:m}function Mt(e,t){return f`
    <div class="model-setup__row" data-auth-choice=${t.id}>
      <div class="model-setup__provider-copy">
        ${q(e,t)}
        <div>
          <strong>${t.label}</strong>
          ${t.groupLabel?f`<div class="muted">${t.groupLabel}</div>`:m}
          ${t.hint?f`<div class="muted">${t.hint}</div>`:m}
        </div>
      </div>
      <button
        type="button"
        class="btn"
        ?disabled=${e.actionsDisabled}
        @click=${()=>e.onStartAuth(t)}
      >
        ${t.kind===`device-code`?b(`modelSetup.signIn.pair`):b(`modelSetup.signIn.signIn`)}
      </button>
    </div>
  `}function Nt(e,t){let n=(t.authOptions??[]).toSorted((e,t)=>Number(t.featured)-Number(e.featured));if(n.length===0)return m;let r=n.filter(e=>e.featured),i=n.filter(e=>!e.featured);return f`
    <section class="settings-section">
      <div class="settings-section__header">
        <h2>${b(`modelSetup.signIn.title`)}</h2>
      </div>
      <div class="model-setup__rows">${r.map(t=>Mt(e,t))}</div>
      ${i.length?f`<details
              class="model-setup__more"
              .open=${e.moreSignInOpen}
              @toggle=${t=>e.onMoreSignInToggle(t.currentTarget.open)}
            >
              <summary>${b(`modelSetup.signIn.more`)}</summary>
              <div class="model-setup__rows">
                ${i.map(t=>Mt(e,t))}
              </div>
            </details>`:m}
    </section>
  `}function Pt(e,t){if(!e.canPrepare)return m;let n=rt(t);return n.length===0?m:f`
    <section class="settings-section">
      <div class="settings-section__header">
        <h2>${b(`modelSetup.prepare.title`)}</h2>
      </div>
      <p class="muted">${b(`modelSetup.prepare.intro`)}</p>
      <div class="model-setup__rows">
        ${n.map(t=>f`
            <div class="model-setup__row" data-prepare-choice=${t.id}>
              <div class="model-setup__provider-copy">
                ${q(e,t)}
                <div>
                  <strong>${t.label}</strong>
                  ${t.hint?f`<div class="muted">${t.hint}</div>`:m}
                </div>
              </div>
              <button
                type="button"
                class="btn"
                ?disabled=${e.actionsDisabled}
                @click=${()=>e.onStartPrepare(t)}
              >
                ${t.actionLabel??b(`modelSetup.prepare.ollamaButton`)}
              </button>
            </div>
          `)}
      </div>
    </section>
  `}function Ft(e,t){let n=t.manualProviders.find(t=>t.id===e.manualProviderId),r=`manual:${e.manualProviderId}`,i=e.activation.phase===`testing`&&e.activation.targetId===r;return f`
    <section class="settings-section">
      <div class="settings-section__header">
        <h2>${b(`modelSetup.manual.title`)}</h2>
      </div>
      <div class="model-setup__manual">
        <div class="field">
          <span>${b(`modelSetup.manual.provider`)}</span>
          ${xt(e,t,n)}
        </div>
        <label class="field">
          <span>
            ${n?b(`modelSetup.manual.accessValueFor`,{provider:Z(n)}):b(`modelSetup.manual.accessValue`)}
          </span>
          <input
            class="input"
            type="password"
            autocomplete="off"
            .value=${e.manualApiKey}
            ?disabled=${e.actionsDisabled}
            placeholder=${b(`modelSetup.manual.accessValuePlaceholder`)}
            @input=${t=>e.onManualApiKeyChange(t.currentTarget.value)}
          />
        </label>
        <div class="model-setup__manual-help">
          ${v.shieldCheck}
          <span>${b(`modelSetup.manual.verifyHint`)}</span>
        </div>
        ${e.manualError?f`<div class="callout danger" role="alert">${e.manualError}</div>`:m}
        <button
          type="button"
          class="btn primary"
          ?disabled=${e.actionsDisabled||!e.manualProviderId}
          @click=${e.onManualConnect}
        >
          ${b(i?`modelSetup.candidates.testingButton`:`modelSetup.manual.connectAndVerify`)}
        </button>
      </div>
    </section>
  `}function It(e){e.querySelector(`.model-setup > .model-setup__testing, .model-setup > .model-setup__failure`)?.scrollIntoView?.({block:`nearest`,behavior:`auto`})}function Lt(e){return e.phase===`testing`?f`<div class="model-setup__testing" role="status">${b(`modelSetup.testing`)}</div>`:e.phase===`failure`?ut(e.status,e.error):m}function Rt(e,t){let n=e.firstRun&&t.setupComplete&&e.activation.phase!==`success`?e.onOpenChat:void 0,r=t.configuredModel?ht({result:t,verify:e.verify,canVerify:e.canVerify,actionsDisabled:e.actionsDisabled,onVerify:e.onVerify,onContinue:n}):m;return e.canAdmin?e.gatewayTooOld?f`${r}
      <div class="callout warning" role="note">${b(`modelSetup.access.gatewayTooOld`)}</div>`:f`
    ${r} ${At(e,t)} ${kt(e,t)}
    ${jt(e,t)} ${Pt(e,t)}
    ${Nt(e,t)} ${Ft(e,t)}
  `:f`${r}
      <div class="callout warning" role="note">${b(`modelSetup.access.adminRequired`)}</div>`}function Q(e){return f`
    <section class=${`settings-section ${e.className??``}`.trim()}>
      <div class="settings-section__header"><h2>${e.title}</h2></div>
      ${e.intro?f`<p class="muted">${e.intro}</p>`:m}
      <div class="model-setup__rows">
        ${Array.from({length:e.rows??1},(t,n)=>f`
            <div class="model-setup__row model-setup__loading-row">
              <span class="model-setup__loading-icon skeleton"></span>
              <span class="model-setup__loading-copy">
                ${n===0&&e.status?f`<span class="model-setup__loading-status">${e.status}</span>`:f`<span class="skeleton skeleton-line skeleton-line--medium"></span>`}
                <span class="skeleton skeleton-line skeleton-line--long"></span>
              </span>
              <span class="model-setup__loading-action skeleton"></span>
            </div>
          `)}
      </div>
    </section>
  `}function zt(e){return f`
    <div
      class="model-setup__loading"
      role="status"
      aria-busy="true"
      aria-label=${b(`modelSetup.loading`)}
    >
      <div class="model-setup__loading-sections" aria-hidden="true">
        ${e?Q({title:b(`modelSetup.verify.title`),className:`model-setup__loading-section--selected`,status:b(`modelSetup.loading`)}):m}
        ${Q({title:b(`modelSetup.candidates.title`),className:`model-setup__loading-section--candidates`,status:e?void 0:b(`modelSetup.loading`)})}
        ${Q({title:b(`modelSetup.prepare.title`),intro:b(`modelSetup.prepare.intro`),rows:2})}
        ${Q({title:b(`modelSetup.signIn.title`),className:`model-setup__loading-section--sign-in`})}
        ${Q({title:b(`modelSetup.manual.title`)})}
      </div>
    </div>
  `}function Bt(e){let t;e.page.phase===`ready`?t=Rt({...e,actionsDisabled:e.actionsDisabled||e.activationUnresolved===!0},e.page.result):e.canAdmin?e.gatewayTooOld?t=f`<div class="callout warning" role="note">
      ${b(`modelSetup.access.gatewayTooOld`)}
    </div>`:e.page.phase===`loading`?t=zt(e.modelConfigured===!0):e.page.phase===`detect-error`&&(t=f`
      <div class="callout danger" role="alert">${e.page.message}</div>
      <button type="button" class="btn" @click=${e.onDetect}>${b(`modelSetup.retry`)}</button>
    `):t=f`<div class="callout warning" role="note">
      ${b(`modelSetup.access.adminRequired`)}
    </div>`;let n=f`
    <div class="model-setup">
      <div class="model-setup__intro">
        <div>
          <h1>${b(`modelSetup.heading`)}</h1>
          <p>${b(`modelSetup.intro`)}</p>
        </div>
        ${e.page.phase===`ready`&&!e.page.result.configuredModel&&e.activation.phase!==`success`&&e.canAdmin&&!e.gatewayTooOld?f`<button
                type="button"
                class="btn"
                ?disabled=${e.actionsDisabled}
                @click=${e.onDetect}
              >
                ${b(`modelSetup.checkAgain`)}
              </button>`:m}
      </div>
      ${e.canAdmin&&!e.gatewayTooOld?Lt(e.activation):m}
      ${e.refreshWarning?f`<div class="callout warning" role="alert">${e.refreshWarning}</div>`:m}
      ${e.activationUnresolved&&!e.actionsDisabled&&e.activation.phase!==`success`?f`<div class="model-setup__recovery">
              <p>${b(`modelSetup.recovery.unknown`)}</p>
              ${e.page.phase===`ready`&&e.page.result.configuredModel&&e.canVerify?f`<button
                      type="button"
                      class="btn primary"
                      @click=${e.onUseCurrentModel}
                    >
                      ${b(`modelSetup.recovery.useCurrent`)}
                    </button>`:m}
              <button type="button" class="btn" @click=${e.onDetect}>
                ${b(`modelSetup.checkAgain`)}
              </button>
            </div>`:m}
      ${t}
    </div>
    ${Tt({mode:e.wizardMode,state:e.wizard,refreshWarning:e.refreshWarning,value:e.wizardValue,onValueChange:e.onWizardValueChange,onAnswer:e.onWizardAnswer,onCancel:e.onWizardCancel,onClose:e.onWizardClose})}
    ${e.activation.phase===`success`?Ct(e.activation,e.onOpenChat,e.onSuccessClose,e.firstRun):m}
  `;return f`
    <section class="content-header">
      <div>
        <div class="page-title">${_e(`model-setup`)}</div>
        <div class="page-subtitle">
          ${pe(`model-setup`)} ${Pe(Vt)}
        </div>
      </div>
    </section>
    ${Be(n)}
  `}var Vt;function Ht(){return(Ht=e((()=>{d(),he(),g(),Ne(),Ve(),y(),u(),gt(),J(),X(),St(),j(),wt(),Dt(),Vt=`https://docs.openclaw.ai/concepts/model-providers`})))()}var Ut;function Wt(){return(Wt=e((()=>{u(),ie(),ee(),j(),Ut=class{constructor(e){this.options=e,this.currentState={phase:`idle`},this.session=null}get state(){return this.currentState}async start(e,t=`openclaw.setup.auth.start`){return this.startSession(e,t,{authChoice:e})}activate(e,t){return this.startSession(e.authChoice??e.kind,`openclaw.setup.activate.start`,e,t)}async startSession(e,t,n,r){let i=this.options.getClient();if(!i||this.currentState.phase!==`idle`)return null;let a={client:i,sessionId:ne(),abortController:new AbortController,startMethod:t,activationTargetId:r,onTerminalResult:this.options.onStart?.(t,`kind`in n?n:void 0)};this.session=a,this.setState({phase:`starting`,authChoice:e});try{let r=this.options.getAgentId(),o=i.request(t,{sessionId:a.sessionId,...n,...r?{agentId:r}:{}},{timeoutMs:null}).catch(e=>{if(!oe(e))throw e;return{sessionId:a.sessionId,done:!0,status:`error`,error:l(e,this.options.requestFailedMessage())}}),s=await this.awaitWizardStart(a,o);return a!==this.session&&!s.done?(await this.cancelSession(a),null):s.done?this.applyResult(a,e,s):await this.requestNext(a,e)}catch(e){return this.handleError(e,a),null}}async answer(e,t=!0){let n=this.currentState,r=this.session;if(n.phase!==`step`||n.busy||!r)return null;this.setState({...n,busy:!0,validationError:null});let i=t?{stepId:n.step.id,value:e}:{stepId:n.step.id};try{return await this.requestNext(r,n.authChoice,i)}catch(e){return this.handleError(e,r),null}}async cancel(e={}){let t=this.session;e.settleActiveRequest||t?.abortController.abort(),this.session=null,this.setState({phase:`idle`}),t&&await this.cancelSession(t)}close(){this.session?.abortController.abort(),this.session=null,this.setState({phase:`idle`})}fail(e){this.session=null,this.setState({phase:`error`,message:e})}async awaitWizardStart(e,t){let n=!1,r,i=t.then(async t=>(n&&(t.done?this.reportTerminalResult(e,t):await this.cancelSession(e)),t));try{return await Promise.race([i,new Promise((t,i)=>{r=setTimeout(()=>{n=!0,i(Error(`gateway request timed out after ${A}ms: ${e.startMethod}`))},A)})])}finally{clearTimeout(r)}}async requestNext(e,t,n){let{client:r,sessionId:i,abortController:a}=e,o=a.signal,s=n;for(;;){let n=await r.request(`wizard.next`,{sessionId:i,...s?{answer:s}:{}},{timeoutMs:null,signal:o}),a=this.applyResult(e,t,n);if(e!==this.session||a)return a;let c=this.currentState;if(c.phase!==`step`||c.step.executor!==`gateway`)return null;s=void 0}}applyResult(e,t,n){let r=this.reportTerminalResult(e,n);if(e!==this.session)return null;if(r?.()===!1)return this.close(),null;let i=qe(t,n,n.status===`cancelled`?this.options.cancelledMessage():this.options.requestFailedMessage());return n.done&&(this.session=null),this.setState(i),i.phase===`done`?{startMethod:e.startMethod,...e.activationTargetId?{activationTargetId:e.activationTargetId}:{},...r?{isCurrent:r}:{},...i.preparedModelRef?{preparedModelRef:i.preparedModelRef}:{},...n.modelActivation?{modelActivation:n.modelActivation}:{}}:null}handleError(e,t){if(t!==this.session)return;this.session=null,t.abortController.abort();let n=ae(e);n||this.cancelSession(t);let r=n?this.options.sessionExpiredMessage():l(e,this.options.requestFailedMessage());this.setState({phase:`error`,message:r})}async cancelSession(e){try{let t=await e.client.request(`wizard.cancel`,{sessionId:e.sessionId},{timeoutMs:A});(t.status===`cancelled`||t.status===`error`)&&this.reportTerminalResult(e,{done:!0,...t})}catch{}}reportTerminalResult(e,t){let n=t.status===`cancelled`||t.status===`error`;if(t.done&&(e===this.session||n))return e.onTerminalResult?.(t)}setState(e){this.currentState=e,this.options.onChange(e)}}})))()}var $;function Gt(){return(Gt=e((()=>{i(),ke(),le(),me(),ve(),y(),Ae(),a(),te(),o(),G(),J(),U(),X(),st(),j(),Ht(),Wt(),B(),$=class extends re{constructor(...e){super(...e),this.pageState={phase:`loading`},this.activationState={phase:`idle`},this.verifyState={phase:`idle`},this.wizardState={phase:`idle`},this.wizardMode=`auth`,this.manualProviderId=``,this.manualApiKey=``,this.manualError=null,this.moreSignInOpen=!1,this.iconUrls={},this.setupRefreshWarning=null,this.observedConnection=null,this.pendingPrepareOption=null,this.wizardMutationGeneration=0,this.wizardMutationActive=!1,this.wizardReturnFocus=null,this.firstRun=new W({context:()=>this.context,routeData:()=>this.routeData,pageState:()=>this.pageState,actionsDisabled:()=>this.actionsDisabled(),canUseSetup:e=>this.canUseSetup(e),canVerify:e=>this.canVerify(e),verify:()=>this.verifyConnection().then(()=>this.verifyTask.value),activate:(e,t)=>this.activate({kind:e.kind,modelRef:e.modelRef},t),setVerifyState:e=>this.verifyState=e,setActivationState:e=>this.activationState=e,setRefreshWarning:e=>this.setupRefreshWarning=e}),this.iconLoader=new nt(()=>this.context,()=>this.pageState,e=>this.iconUrls=e),this.subscriptions=new se(this).watch(()=>this.context?.gateway,(e,t)=>e.subscribe(t),e=>this.synchronizeGateway(e.snapshot)).watch(()=>this.context?.agentSelection,(e,t)=>e.subscribe(t),()=>this.synchronizeGateway(this.context.gateway.snapshot)).watch(()=>this.firstRun,(e,t)=>e.subscribe(t)),this.wizard=new Ut({getClient:()=>this.context?.gateway.snapshot.client??null,getAgentId:()=>this.context?.agentSelection.state.selectedId??null,onChange:e=>{e.phase!==`starting`&&e.phase!==`done`&&(this.activationState={phase:`idle`});let t=this.wizardState.phase===`step`?this.wizardState.step.id:null;this.wizardState=e.phase===`step`&&this.wizardMutationActive?{...e,busy:!0}:e,e.phase===`step`&&e.step.id!==t&&(this.wizardValue=Je(e.step))},onStart:(e,t)=>{if(e===`openclaw.setup.prepare.start`)return;let n=this.firstRun.beginActivation(t??{kind:`provider-auth`});return e=>{if(e.status===`done`&&e.modelActivation)return this.firstRun.recordActivation(n,{ok:!0,...e.modelActivation}),()=>this.firstRun.ownsActivation(n);if(e.status===`cancelled`||e.status===`error`)return this.firstRun.recordActivation(n,{ok:!1}),this.requestUpdate(),()=>this.firstRun.ownsActivation(n)}},requestFailedMessage:()=>b(`modelSetup.errors.requestFailed`),cancelledMessage:()=>b(`modelSetup.wizard.cancelled`),sessionExpiredMessage:()=>b(`modelSetup.wizard.sessionExpired`)}),this.detectTask=new x(this,{autoRun:!1,args:()=>{let e=this.context?.gateway.snapshot.client??null;return[this.canUseSetup(e)?e:null,this.context?.agentSelection.state.selectedId??null,null]},task:async([e,t,n],{signal:r})=>{if(!e||!n)return Ee;let i=this.context.gateway.snapshot.hello;return{...await H(e,()=>at(e,t??void 0,r)),agentId:t,hello:i,token:n}},onComplete:e=>{if(this.context.gateway.snapshot.client===e.client&&this.context.gateway.snapshot.hello===e.hello&&this.context.agentSelection.state.selectedId===e.agentId){if(`error`in e){this.firstRun.setReadyConnection(null),this.pageState={phase:`detect-error`,message:V(e.error)};return}this.firstRun.setReadyConnection({client:e.client,hello:e.hello,agentId:e.agentId}),this.pageState={phase:`ready`,result:e.value},this.syncManualProvider(this.pageState)}}}),this.verifyTask=new x(this,{autoRun:!1,args:()=>[null,null],task:async([e,t],{signal:n})=>e?H(e,()=>ot(e,t??void 0,n)):Ee})}disconnectedCallback(){this.firstRun.dispose(),this.resetActivity(),this.observedConnection=null,this.subscriptions.clear(),super.disconnectedCallback()}willUpdate(){this.synchronizeGateway(this.context.gateway.snapshot)}updated(e){this.isConnected&&(e.has(`activationState`)&&this.activationState.phase!==`idle`&&It(this.renderRoot),this.wizardState.phase!==`idle`&&this.querySelector(`openclaw-modal-dialog`)?.setReturnFocusTarget(this.wizardReturnFocus),this.iconLoader.reconcile(),this.firstRun.start())}synchronizeGateway(e){let t=this.routeData;if(!this.isConnected||!t)return;let n={client:e.client,hello:e.hello,agentId:this.context.agentSelection.state.selectedId,connected:e.phase===`connected`,firstRun:t.firstRun},r=this.observedConnection;r&&n.client===r.client&&n.hello===r.hello&&n.agentId===r.agentId&&n.connected===r.connected&&n.firstRun===r.firstRun||(this.observedConnection=n,n.firstRun===r?.firstRun?this.firstRun.connectionChanged(n):this.firstRun.routeChanged(),this.resetActivity(),this.pageState={phase:`loading`},this.canUseSetup(n.client)&&this.detect())}resetActivity(){this.wizardMutationGeneration+=1,this.wizardMutationActive=!1,this.detectTask.run([null,null,null]),this.activationState={phase:`idle`},this.verifyState={phase:`idle`},this.verifyTask.run([null,null]),this.iconLoader.reset(),this.pendingPrepareOption=null,this.wizard.cancel()}canUseSetup(e){let t=this.context.gateway.snapshot;return!!(e&&t.phase===`connected`&&h(t.hello?.auth??null)&&C(t,`openclaw.setup.detect`)===!0)}syncManualProvider(e){e.phase===`ready`&&(e.result.manualProviders.some(e=>e.id===this.manualProviderId)||(this.manualProviderId=e.result.manualProviders[0]?.id??``))}async detect(){let e=this.context.gateway.snapshot.client;if(!this.canUseSetup(e))return null;this.resetVerify(),this.pageState={phase:`loading`};let t={};await this.detectTask.run([e,this.context.agentSelection.state.selectedId,t]);let n=this.detectTask.value;return n?.token===t&&`value`in n?n.value:null}canVerify(e){let t=this.context.gateway.snapshot;return this.canUseSetup(e)&&C(t,`openclaw.setup.verify`)===!0}resetVerify(){this.verifyState={phase:`idle`},this.verifyTask.run([null,null])}async verifyConnection(){let e=this.context.gateway.snapshot.client;!this.canVerify(e)||this.actionsDisabled()||(this.verifyState={phase:`checking`},await this.verifyTask.run([e,this.context.agentSelection.state.selectedId]))}async activate(e,t){let n=this.context.gateway.snapshot.client;!this.canUseSetup(n)||this.actionsDisabled()||this.firstRun.unresolved||(this.manualError=null,this.activationState={phase:`testing`,targetId:t},this.pendingPrepareOption=null,this.wizardMode=`activate`,await this.runWizardMutation(()=>this.wizard.activate(e,t)))}finishActivation(e,t,n){this.activationState=Ge({result:e,targetId:t,fallbackError:b(`modelSetup.errors.activationFailed`),restartWarning:b(`labsPage.restartRequired`),refreshWarning:n}),this.activationState.phase===`success`&&(this.manualApiKey=``),this.firstRun.finishActivation(e,t,n)}activateCandidate(e){this.activate({kind:e.kind,modelRef:e.modelRef},k(e.kind,e.modelRef))}connectManual(){let e=this.manualApiKey.trim();if(!this.manualProviderId||!e){this.manualError=b(`modelSetup.manual.required`);return}this.activate({kind:`api-key`,authChoice:this.manualProviderId,apiKey:e},`manual:${this.manualProviderId}`)}selectManualProvider(e){e!==this.manualProviderId&&(this.manualApiKey=``),this.manualProviderId=e,this.manualError=null}async useManualProvider(e){this.selectManualProvider(e),await this.updateComplete;let t=this.renderRoot.querySelector(`.model-setup__manual input[type="password"]`);t?.scrollIntoView?.({block:`center`,behavior:Fe()}),t?.focus()}async handleWizardDone({startMethod:e,preparedModelRef:t,activationTargetId:n,modelActivation:r,isCurrent:i}){let a=e===`openclaw.setup.prepare.start`?this.pendingPrepareOption:null;if(this.pendingPrepareOption=null,a&&t){let e=Y(a.id);this.wizard.close(),this.activate({kind:e,modelRef:t},k(e,t));return}if(e!==`openclaw.setup.prepare.start`){if(i?.()===!1){this.wizard.close();return}if(!r){this.wizard.fail(b(e===`openclaw.setup.activate.start`?`modelSetup.errors.activationFailed`:`modelSetup.wizard.notComplete`));return}this.wizard.close(),this.finishActivation({ok:!0,...r},n??`provider-auth`,this.setupRefreshWarning);return}let o=await this.detect();if(!o){this.wizard.fail(b(`modelSetup.errors.requestFailed`));return}if(a){this.pageState={phase:`ready`,result:{...o,configuredModel:void 0,setupComplete:!1}};let e=it(o,a.id);if(!e){this.wizard.fail(b(`modelSetup.prepare.providerNotReady`,{provider:a.label}));return}this.wizard.close(),this.activateCandidate(e);return}this.wizard.close()}closeWizard(){this.wizardMutationGeneration+=1,this.wizardMutationActive=!1,this.pendingPrepareOption=null,this.activationState={phase:`idle`},this.wizard.close()}async runWizardMutation(e){let t=this.context.gateway.snapshot.client;if(this.wizardMutationActive||!this.canUseSetup(t)||this.wizard.state.phase===`idle`&&this.firstRun.unresolved)return;if(this.wizard.state.phase===`idle`){let e=this.ownerDocument.activeElement;this.wizardReturnFocus=e instanceof HTMLElement&&this.contains(e)?e:null}let n=++this.wizardMutationGeneration;this.wizardMutationActive=!0,this.requestUpdate();try{let r=await this.context.runtimeConfig.runExternalMutation(async n=>{if(n!==t)throw Error(`Connection changed before model setup continued.`);return await e()},{canDispatch:()=>n===this.wizardMutationGeneration&&this.context.gateway.snapshot.client===t&&this.canUseSetup(t),dispatchError:b(`modelSetup.errors.requestFailed`)});if(n!==this.wizardMutationGeneration){r.ok&&!r.refresh.ok&&this.isConnected&&(this.setupRefreshWarning=r.refresh.error),this.isConnected&&this.canUseSetup(this.context.gateway.snapshot.client)&&this.detect();return}if(!r.ok){this.wizard.fail(r.error);return}this.setupRefreshWarning=r.refresh.ok?null:r.refresh.error;let i=r.value;i?(this.wizardMutationActive=!1,await this.handleWizardDone(i)):this.wizardState.phase===`step`&&this.wizardState.busy&&(this.wizardState={...this.wizardState,busy:!1})}catch(e){n===this.wizardMutationGeneration&&this.wizard.fail(V(e))}finally{n===this.wizardMutationGeneration&&(this.wizardMutationActive=!1,this.requestUpdate())}}cancelWizard(){this.wizardMutationGeneration+=1,this.wizardMutationActive=!1,this.pendingPrepareOption=null,this.activationState={phase:`idle`},this.wizard.cancel({settleActiveRequest:!0})}actionsDisabled(){return this.activationState.phase===`testing`||this.verifyState.phase===`checking`||this.wizardMutationActive||this.wizardState.phase!==`idle`&&this.wizardState.phase!==`error`&&this.wizardState.phase!==`cancelled`}render(){let e=this.context.gateway.snapshot,t=h(e.hello?.auth??null),n=e.phase===`connected`&&C(e,`openclaw.setup.detect`)!==!0,r=t&&!n&&C(e,`openclaw.setup.verify`)===!0;return Bt({page:this.firstRun.visiblePageState(this.verifyState.phase===`ok`),activation:this.activationState,verify:this.verifyState,wizard:this.wizardState,wizardMode:this.wizardMode,wizardValue:this.wizardValue,canAdmin:t,canVerify:r,canPrepare:t&&!n&&C(e,`openclaw.setup.prepare.start`)===!0,modelConfigured:ce(e)?.modelConfigured===!0,gatewayTooOld:n,refreshWarning:this.setupRefreshWarning,activationUnresolved:this.firstRun.unresolved,onUseCurrentModel:()=>void this.firstRun.useCurrentModel(),actionsDisabled:this.actionsDisabled(),manualProviderId:this.manualProviderId,manualApiKey:this.manualApiKey,manualError:this.manualError,moreSignInOpen:this.moreSignInOpen,firstRun:this.routeData?.firstRun===!0,iconUrls:this.iconUrls,onDetect:()=>{this.firstRun.retryDetection()&&this.detect()},onVerify:()=>void this.firstRun.verify(),onActivateCandidate:e=>this.activateCandidate(e),onStartAuth:e=>{this.pendingPrepareOption=null,this.wizardMode=`auth`,this.runWizardMutation(()=>this.wizard.start(e.id))},onStartPrepare:e=>{this.pendingPrepareOption=e,this.wizardMode=`prepare`,this.runWizardMutation(()=>this.wizard.start(e.id,`openclaw.setup.prepare.start`))},onManualProviderChange:e=>this.selectManualProvider(e),onUseManualProvider:e=>void this.useManualProvider(e),onManualApiKeyChange:e=>{this.manualApiKey=e,this.manualError=null},onManualConnect:()=>this.connectManual(),onMoreSignInToggle:e=>this.moreSignInOpen=e,onIconError:e=>this.iconLoader.invalidate(e),onOpenChat:()=>this.firstRun.continueSetup(),onSuccessClose:()=>{this.activationState={phase:`idle`},this.detect()},onWizardValueChange:e=>this.wizardValue=e,onWizardAnswer:(e,t)=>void this.runWizardMutation(()=>this.wizard.answer(e,t)),onWizardCancel:()=>this.cancelWizard(),onWizardClose:()=>this.closeWizard()})}},r([n({context:ge,subscribe:!0})],$.prototype,`context`,void 0),r([fe({attribute:!1})],$.prototype,`routeData`,void 0),r([p()],$.prototype,`pageState`,void 0),r([p()],$.prototype,`activationState`,void 0),r([p()],$.prototype,`verifyState`,void 0),r([p()],$.prototype,`wizardState`,void 0),r([p()],$.prototype,`wizardMode`,void 0),r([p()],$.prototype,`wizardValue`,void 0),r([p()],$.prototype,`manualProviderId`,void 0),r([p()],$.prototype,`manualApiKey`,void 0),r([p()],$.prototype,`manualError`,void 0),r([p()],$.prototype,`moreSignInOpen`,void 0),r([p()],$.prototype,`iconUrls`,void 0),r([p()],$.prototype,`setupRefreshWarning`,void 0),customElements.get(`openclaw-model-setup-page`)||customElements.define(`openclaw-model-setup-page`,$)})))()}Gt();export{tt as resumeFirstRunActivation};
//# sourceMappingURL=model-setup-page-Ccclb_L6.js.map