import{n as e}from"./rolldown-runtime-DkW27tQK.js";import{bt as t,er as n}from"./control-ui-foundation-CeFMP1Ly.js";import{bc as r,fl as i,fs as a,hl as o,ii as s,kc as c,ml as ee,ms as l,ps as u,ri as te,ti as ne,vr as re,yr as ie}from"./control-ui-core-pH6nakZ-.js";import{G as d,J as f,W as p,Z as ae,_ as oe,at as se,b as ce,rt as m}from"./lit-runtime-BEtFSUCp.js";import{Cn as le,Jt as ue,Sn as de,Ut as fe,ln as pe,m as me,p as he}from"./control-ui-core-DGVkFhVB.js";import{Ht as h,Lt as g,N as ge,Nt as _e,P as ve,Rt as _,qt as v}from"./control-ui-core-Br5DB0Zj.js";import{An as ye,F as be,Fn as xe,I as y,In as Se,L as b,Ln as Ce,Mn as we,Pn as Te,Sn as Ee,jn as De,kn as Oe,wn as ke}from"./control-ui-boot-wpHCbPL9.js";import{a as x,r as S}from"./gateway-runtime-DUNO4Mi1.js";import{Gl as C,Jl as w,Kl as T,Xl as Ae,Yl as E,an as je,cn as Me,on as Ne,ql as Pe}from"./control-ui-boot-Cdpgu1Gm.js";import{K as Fe,U as Ie}from"./control-ui-boot-D1DWJlBr.js";import{r as Le,t as Re}from"./wizard-step-controls-D3s65of1.js";import{n as ze,t as Be}from"./settings-workspace-Bo4nqRhI.js";var D,O;function k(){return(k=e((()=>{xe(),D=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if(De(e),Oe(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{let e=((e,t,n)=>new D(e,t).update(n).digest());return e.create=(e,t)=>new D(e,t),e})()})))()}function A(e){return e===`provider-auth`?15e5:e===`codex-cli`?Ge:P}function j(e,t){return`${e}\u0000${t}`}function Ve(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:u(t.error,e.fallbackError)}}function He(e){return e.ok?{phase:`ok`,modelRef:e.modelRef,...typeof e.latencyMs==`number`?{latencyMs:e.latencyMs}:{}}:{phase:`failed`,status:e.status,error:u(e.error)}}function Ue(e,t,n){return!t.done&&t.step?{phase:`step`,authChoice:e,step:t.step,busy:!1,validationError:t.error?.trim()?u(t.error):null}:t.done&&t.status===`done`?{phase:`done`,authChoice:e,...t.preparedModelRef?{preparedModelRef:t.preparedModelRef}:{}}:t.status===`cancelled`?{phase:`cancelled`,message:u(t.error,n)}:{phase:`error`,message:u(t.error,n)}}function We(e){return e.type===`multiselect`?Array.isArray(e.initialValue)?[...e.initialValue]:[]:e.initialValue}var M,N,P,Ge,F;function I(){return(I=e((()=>{l(),M=4e4,N=3e4,P=15e4,Ge=48e4,F=3e4})))()}function Ke(e){let t=t=>{t.key===B&&t.newValue===null&&t.oldValue&&e(t.oldValue)};return V.add(e),window.addEventListener(`storage`,t),()=>{V.delete(e),window.removeEventListener(`storage`,t)}}function qe(e,t,n){try{let r=JSON.parse(n.getItem(Ze)??`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,ee=s.map(e=>`${c.encode(e).length}:${e}`).join(`|`);return Array.from(O(ke,c.encode(r.privateKey),c.encode(ee))).map(e=>e.toString(16).padStart(2,`0`)).join(``)}catch{return null}}function L(e,t){try{let n=e.getItem(B);if((t===void 0||t&&n===JSON.stringify(t))&&(e.removeItem(B),n))for(let e of V)e(n)}catch{}}function R(e,n){let r=o();if(!r||e.gateway.snapshot.phase!==`connected`)return null;try{let i=r.getItem(B);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 L(r),null;let{owner:o,...s}=a;return qe(e,s,r)===o?a:(L(r),null)}catch{return L(r),null}}function Je(e){return Date.now()+A(e)+Qe}function Ye(e,n){let r=o();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??Je(n.kind)},a=qe(e,i,r);if(!a)return null;let o={...i,owner:a};return r.setItem(B,JSON.stringify(o)),o}catch{return null}}function z(e){let t=o();t&&L(t,e)}function Xe(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()&&R(o)!==null&&e.redirect(),a()}var B,Ze,Qe,V;function H(){return(H=e((()=>{k(),Ee(),I(),B=`openclaw.modelSetup.pendingActivation.v1`,Ze=`openclaw-device-identity-v1`,Qe=5e3,V=new Set})))()}function U(e){return a(e,v(`modelSetup.errors.requestFailed`))}async function W(e,t){try{return{client:e,value:await t()}}catch(t){return{client:e,error:t}}}function G(){return(G=e((()=>{h(),l()})))()}var $e;function et(){return(et=e((()=>{h(),S(),H(),G(),I(),$e=class{constructor(e){this.host=e,this.generation=0,this.started=!1,this.attempts=new Set,this.readyConnection=null,this.pending=null}subscribe(e){return Ke(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&&z()}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()e.onIconError(t.icon)} />`}var nt;function q(){return(q=e((()=>{p(),T(),Fe(),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&&!tt(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();Ie({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 J(e){return`provider-auto:${encodeURIComponent(e)}`}function rt(e){let t=[{id:`ollama`,brandId:`ollama`,label:v(`modelSetup.prepare.ollamaLabel`),hint:v(`modelSetup.prepare.ollamaHint`)},{id:`llama-cpp`,brandId:`llama-cpp`,label:v(`modelSetup.prepare.llamaCppLabel`)}];return(e.prepareOptions??t).filter(t=>!e.candidates.some(e=>e.credentials!==!1&&(e.kind===J(t.id)||e.modelRef.startsWith(`${t.brandId??t.id}/`))))}function it(e,t){return e.candidates.find(e=>e.kind===J(t)&&e.credentials!==!1)}function Y(){return(Y=e((()=>{h()})))()}function at(e,t,n){return e.request(`openclaw.setup.detect`,t?{agentId:t}:{},{timeoutMs:M,...n?{signal:n}:{}})}function ot(e,t,n){return e.request(`openclaw.setup.verify`,t?{agentId:t}:{},{timeoutMs:N,...n?{signal:n}:{}})}function st(){return(st=e((()=>{I()})))()}function ct(e){let t={auth:v(`modelSetup.failure.auth`),rate_limit:v(`modelSetup.failure.rateLimit`),billing:v(`modelSetup.failure.billing`),timeout:v(`modelSetup.failure.timeout`),format:v(`modelSetup.failure.format`),unavailable:v(`modelSetup.failure.unavailable`),unknown:v(`modelSetup.failure.unknown`)};return t[e]??t.unknown}function lt(e){let t={auth:v(`modelSetup.failureGuidance.auth`),rate_limit:v(`modelSetup.failureGuidance.rateLimit`),billing:v(`modelSetup.failureGuidance.billing`),timeout:v(`modelSetup.failureGuidance.timeout`),format:v(`modelSetup.failureGuidance.format`),unavailable:v(`modelSetup.failureGuidance.unavailable`),unknown:v(`modelSetup.failureGuidance.unknown`)};return t[e]??t.unknown}function ut(e,t){return f` `}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 v(`modelSetup.verify.checkingButton`);case`failed`:return v(`modelSetup.verify.retry`);case`ok`:return v(`modelSetup.verify.checkAgain`);default:return v(`modelSetup.verify.button`)}}function ht(e){let t=e.result.configuredModel,n=e.verify.phase===`ok`?e.verify.modelRef:t,r=w(n),i=n===t?ft(e.result,t):void 0,a=r?Pe(r):n,o=pt(i,n);return f`

${v(`modelSetup.verify.title`)}

${r?E(r,{className:`model-setup__icon`}):d}
${a}
${o}
${e.verify.phase===`checking`?f`
${v(`modelSetup.verify.checking`,{modelRef:t})}
`:e.verify.phase===`ok`?f`
${e.verify.latencyMs===void 0?v(`modelSetup.verify.ready`):v(`modelSetup.verify.readyIn`,{latencyMs:String(e.verify.latencyMs)})}
`:e.verify.phase===`failed`?e.verify.status===`unavailable`?f``:ut(e.verify.status,e.verify.error):d}
${e.canVerify?f``:d} ${e.onContinue?f``:d}
`}function gt(){return(gt=e((()=>{p(),_(),T(),h()})))()}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 bt(e,t,n,r){let i=w(e.modelRef),a=i&&C(i)?i:null,o=e.warning??v(`modelSetup.success.body`,{modelRef:e.modelRef}),s=r?v(`modelSetup.success.continueSetup`):e.warning?v(`tabs.chat`):v(`modelSetup.success.openChat`);return f`

${v(`modelSetup.success.title`)}

${e.warning?d:f`

${o}

`}
${e.warning?f`
${e.warning}
`:d}
${v(`modelSetup.success.activeModel`)} ${e.modelRef} ${e.latencyMs===void 0?d:f` ${v(`modelSetup.success.latency`,{latencyMs:String(e.latencyMs)})} `}
`}function xt(){return(xt=e((()=>{p(),_(),_e(),T(),h()})))()}function St(e){if(e.state.phase===`idle`)return d;let t=e.state.phase===`starting`||e.state.phase===`step`||e.state.phase===`done`;return f`

${e.state.phase===`step`&&e.state.step.title?e.state.step.title:v(e.mode===`prepare`?`modelSetup.wizard.prepareTitle`:`modelSetup.wizard.title`)}

${e.refreshWarning?f``:d} ${e.state.phase===`starting`?f`
${v(e.mode===`prepare`?`modelSetup.wizard.prepareStarting`:`modelSetup.wizard.starting`)}
`:e.state.phase===`done`?f`
${v(`modelSetup.wizard.checking`)}
`:e.state.phase===`error`||e.state.phase===`cancelled`?f``:f` ${e.state.validationError?f``:d} ${Le({step:e.state.step,value:e.value,busy:e.state.busy,inputId:Ct,confirmAffirmativeLabel:e.mode===`prepare`&&e.state.step.type===`confirm`?v(`modelSetup.wizard.continue`):void 0,leadingAction:f``,onValueChange:e.onValueChange,onAnswer:e.onAnswer})} ${e.state.busy?f`
${v(`modelSetup.wizard.working`)}
`:d} `}
${e.state.phase===`step`?d:f` `}
`}var Ct;function wt(){return(wt=e((()=>{p(),Re(),h(),_e(),Ct=`model-setup-wizard-text-input`})))()}function Tt(e){return e.recommended?v(`modelSetup.candidates.recommended`):e.credentials===!0?v(`modelSetup.candidates.credentialsReady`):e.credentials===!1?v(`modelSetup.candidates.signInNeeded`):v(`modelSetup.candidates.detected`)}function Et(e,t){let n=t.configuredModel?t.candidates.filter(e=>e.kind!==`existing-model`&&e.modelRef!==t.configuredModel):t.candidates;return n.length===0?d:f`

${v(`modelSetup.candidates.title`)}

${n.map(t=>{let n=e.activation.phase===`testing`&&e.activation.targetId===j(t.kind,t.modelRef),r=e.activation.phase===`failure`&&e.activation.targetId===j(t.kind,t.modelRef)?e.activation:null;return f`
${K(e,t)} ${t.label} ${Tt(t)}
${t.modelRef} · ${u(t.detail)}
`})}
`}function Dt(e,t){let n=t.recommendedInstalls??[];return t.candidates.length>0||(t.authOptions?.length??0)>0||n.length===0?d:f`

${v(`modelSetup.empty.title`)}

${v(`modelSetup.empty.intro`)}

${n.map(t=>f`
${K(e,t,`model-setup__icon--recommendation`)}
${t.label}
${t.hint}
${t.website}
`)}
`}function Ot(e,t){return t.unavailableCandidates?.length?f`

${v(`modelSetup.unavailable.title`)}

${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`
${K(e,n)}
${n.label} — ${u(n.detail)}
${u(n.reason)}
${r?f``:d} ${i?f``:d}
`})}
`:d}function X(e,t){return f`
${K(e,t)}
${t.label} ${t.groupLabel?f`
${t.groupLabel}
`:d} ${t.hint?f`
${t.hint}
`:d}
`}function kt(e,t){let n=(t.authOptions??[]).toSorted((e,t)=>Number(t.featured)-Number(e.featured));if(n.length===0)return d;let r=n.filter(e=>e.featured),i=n.filter(e=>!e.featured);return f`

${v(`modelSetup.signIn.title`)}

${r.map(t=>X(e,t))}
${i.length?f`
e.onMoreSignInToggle(t.currentTarget.open)} > ${v(`modelSetup.signIn.more`)}
${i.map(t=>X(e,t))}
`:d}
`}function At(e,t){if(!e.canPrepare)return d;let n=rt(t);return n.length===0?d:f`

${v(`modelSetup.prepare.title`)}

${v(`modelSetup.prepare.intro`)}

${n.map(t=>f`
${K(e,t)}
${t.label} ${t.hint?f`
${t.hint}
`:d}
`)}
`}function Z(e){return e.groupLabel?.trim()||e.label}function jt(e){let t=e.label.trim();return t===Z(e)?void 0:t}function Mt(e,t,n){let r=n?jt(n):void 0,i=n?[Z(n),r].filter(Boolean).join(`, `):v(`modelSetup.manual.selectProvider`);return f` yt(t,e.manualProviderId,e.onManualProviderChange)} @wa-after-show=${_t} @keydown=${vt} > ${t.manualProviders.map(t=>{let n=t.id===e.manualProviderId,r=jt(t),i=[Z(t),r,t.hint].filter(Boolean).join(`, `);return f` ve(e,n))} > ${K(e,t,`model-setup__icon--picker`)} ${Z(t)} ${r?f`${r}`:d} ${t.hint?f`${t.hint}`:d} `})} `}function Nt(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`

${v(`modelSetup.manual.title`)}

${v(`modelSetup.manual.provider`)} ${Mt(e,t,n)}
${g.shieldCheck} ${v(`modelSetup.manual.verifyHint`)}
${e.manualError?f``:d}
`}function Pt(e){e.querySelector(`.model-setup > .model-setup__testing, .model-setup > .model-setup__failure`)?.scrollIntoView?.({block:`nearest`,behavior:`auto`})}function Ft(e){return e.phase===`testing`?f`
${v(`modelSetup.testing`)}
`:e.phase===`failure`?ut(e.status,e.error):d}function It(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}):d;return e.canAdmin?e.gatewayTooOld?f`${r}
${v(`modelSetup.access.gatewayTooOld`)}
`:f` ${r} ${Dt(e,t)} ${Et(e,t)} ${Ot(e,t)} ${At(e,t)} ${kt(e,t)} ${Nt(e,t)} `:f`${r}
${v(`modelSetup.access.adminRequired`)}
`}function Q(e){return f`

${e.title}

${e.intro?f`

${e.intro}

`:d}
${Array.from({length:e.rows??1},(t,n)=>f`
${n===0&&e.status?f`${e.status}`:f``}
`)}
`}function Lt(e){return f`
`}function Rt(e){let t;e.page.phase===`ready`?t=It({...e,actionsDisabled:e.actionsDisabled||e.activationUnresolved===!0},e.page.result):e.canAdmin?e.gatewayTooOld?t=f`
${v(`modelSetup.access.gatewayTooOld`)}
`:e.page.phase===`loading`?t=Lt(e.modelConfigured===!0):e.page.phase===`detect-error`&&(t=f` `):t=f`
${v(`modelSetup.access.adminRequired`)}
`;let n=f`

${v(`modelSetup.heading`)}

${v(`modelSetup.intro`)}

${e.page.phase===`ready`&&!e.page.result.configuredModel&&e.activation.phase!==`success`&&e.canAdmin&&!e.gatewayTooOld?f``:d}
${e.canAdmin&&!e.gatewayTooOld?Ft(e.activation):d} ${e.refreshWarning?f``:d} ${e.activationUnresolved&&!e.actionsDisabled&&e.activation.phase!==`success`?f`

${v(`modelSetup.recovery.unknown`)}

${e.page.phase===`ready`&&e.page.result.configuredModel&&e.canVerify?f``:d}
`:d} ${t}
${St({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`?bt(e.activation,e.onOpenChat,e.onSuccessClose,e.firstRun):d} `;return f`
${le(`model-setup`)}
${de(`model-setup`)} ${Me(zt)}
${ze(n)} `}var zt;function Bt(){return(Bt=e((()=>{p(),oe(),pe(),_(),Ne(),Be(),ge(),h(),l(),gt(),q(),Y(),I(),xt(),wt(),zt=`https://docs.openclaw.ai/concepts/model-providers`})))()}var Vt;function Ht(){return(Ht=e((()=>{l(),ne(),I(),Vt=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`){let n=this.options.getClient();if(!n||this.currentState.phase!==`idle`)return null;let r={client:n,sessionId:crypto.randomUUID(),abortController:new AbortController,startMethod:t,onTerminalResult:this.options.onStart?.(t)};this.session=r,this.setState({phase:`starting`,authChoice:e});try{let i=this.options.getAgentId(),o=n.request(t,{sessionId:r.sessionId,authChoice:e,...i?{agentId:i}:{}},{timeoutMs:null}).catch(e=>{if(!te(e))throw e;return{sessionId:r.sessionId,done:!0,status:`error`,error:a(e,this.options.requestFailedMessage())}}),s=await this.awaitWizardStart(r,o);return r!==this.session&&!s.done?(await this.cancelSession(r),null):s.done?this.applyResult(r,e,s):await this.requestNext(r,e)}catch(e){return this.handleError(e,r),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 ${F}ms: ${e.startMethod}`))},F)})])}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;let i=Ue(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,...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=s(e);n||this.cancelSession(t);let r=n?this.options.sessionExpiredMessage():a(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:F});(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 Ut(){return(Ut=e((()=>{Ce(),be(),ae(),me(),ue(),h(),ne(),S(),r(),ee(),ie(),et(),q(),G(),Y(),st(),I(),Bt(),Ht(),H(),$=class extends i{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.firstRun=new $e({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).then(()=>this.activationTask.value),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 re(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 Vt({getClient:()=>this.context?.gateway.snapshot.client??null,getAgentId:()=>this.context?.agentSelection.state.selectedId??null,onChange:e=>{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=We(e.step))},onStart:e=>{if(e!==`openclaw.setup.auth.start`)return;let t=this.firstRun.beginActivation({kind:`provider-auth`});return e=>{if(e.status===`done`&&e.modelActivation)return this.firstRun.recordActivation(t,{ok:!0,...e.modelActivation}),()=>this.firstRun.ownsActivation(t);(e.status===`cancelled`||e.status===`error`)&&(this.firstRun.recordActivation(t,{ok:!1}),this.requestUpdate())}},requestFailedMessage:()=>v(`modelSetup.errors.requestFailed`),cancelledMessage:()=>v(`modelSetup.wizard.cancelled`),sessionExpiredMessage:()=>v(`modelSetup.wizard.sessionExpired`)}),this.detectTask=new y(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 b;let i=this.context.gateway.snapshot.hello;return{...await W(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:U(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.activationTask=new y(this,{autoRun:!1,args:()=>[null,null],task:async([e,t],{signal:n})=>{if(!e||!t)return b;let r=()=>!0;return{...await W(e,async()=>{let i=await this.context.runtimeConfig.runExternalMutation(async i=>{if(i!==e)throw Error(`Connection changed before model activation started.`);n.throwIfAborted();let a=this.firstRun.beginActivation(t);r=()=>this.firstRun.ownsActivation(a);let o=await i.request(`openclaw.setup.activate`,t,{timeoutMs:A(t.kind),signal:n}).catch(e=>{throw te(e)&&this.firstRun.recordActivation(a,{ok:!1}),e});return this.firstRun.recordActivation(a,o),o});if(!i.ok)throw Error(i.error);return{result:i.value,refreshError:i.refresh.ok?null:i.refresh.error}}),isCurrent:r}},onComplete:e=>{let t=this.activationState;if(t.phase===`testing`&&this.context.gateway.snapshot.client===e.client){if(!e.isCurrent()){this.activationState={phase:`idle`};return}if(`error`in e){this.activationState={phase:`failure`,targetId:t.targetId,status:`unknown`,error:U(e.error)};return}this.finishActivation(e.value.result,t.targetId,e.value.refreshError)}}}),this.verifyTask=new y(this,{autoRun:!1,args:()=>[null,null],task:async([e,t],{signal:n})=>e?W(e,()=>ot(e,t??void 0,n)):b})}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`&&Pt(this.renderRoot),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.activationTask.run([null,null]),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`&&fe(t.hello?.auth??null)&&x(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)&&x(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;if(!this.canUseSetup(n)||this.actionsDisabled()||this.firstRun.unresolved)return;this.manualError=null,this.activationState={phase:`testing`,targetId:t};let r=this.context.agentSelection.state.selectedId;await this.activationTask.run([n,{...e,...r?{agentId:r}:{}}])}finishActivation(e,t,n){this.activationState=Ve({result:e,targetId:t,fallbackError:v(`modelSetup.errors.activationFailed`),restartWarning:v(`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},j(e.kind,e.modelRef))}connectManual(){let e=this.manualApiKey.trim();if(!this.manualProviderId||!e){this.manualError=v(`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:je()}),t?.focus()}async handleWizardDone({startMethod:e,preparedModelRef:t,modelActivation:n,isCurrent:r}){let i=e===`openclaw.setup.prepare.start`?this.pendingPrepareOption:null;if(this.pendingPrepareOption=null,i&&t){let e=J(i.id);this.wizard.close(),this.activate({kind:e,modelRef:t},j(e,t));return}if(e===`openclaw.setup.auth.start`){if(r?.()===!1){this.wizard.close();return}if(!n){this.wizard.fail(v(`modelSetup.wizard.notComplete`));return}this.wizard.close(),this.finishActivation({ok:!0,...n},`provider-auth`,this.setupRefreshWarning);return}let a=await this.detect();if(!a){this.wizard.fail(v(`modelSetup.errors.requestFailed`));return}if(i){this.pageState={phase:`ready`,result:{...a,configuredModel:void 0,setupComplete:!1}};let e=it(a,i.id);if(!e){this.wizard.fail(v(`modelSetup.prepare.providerNotReady`,{provider:i.label}));return}this.wizard.close(),this.activateCandidate(e);return}this.wizard.close()}closeWizard(){this.wizardMutationGeneration+=1,this.wizardMutationActive=!1,this.pendingPrepareOption=null,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;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:v(`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(U(e))}finally{n===this.wizardMutationGeneration&&(this.wizardMutationActive=!1,this.requestUpdate())}}cancelWizard(){this.wizardMutationGeneration+=1,this.wizardMutationActive=!1,this.pendingPrepareOption=null,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=fe(e.hello?.auth??null),n=e.phase===`connected`&&x(e,`openclaw.setup.detect`)!==!0,r=t&&!n&&x(e,`openclaw.setup.verify`)===!0;return Rt({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&&x(e,`openclaw.setup.prepare.start`)===!0,modelConfigured:c(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()})}},n([Se({context:he,subscribe:!0})],$.prototype,`context`,void 0),n([se({attribute:!1})],$.prototype,`routeData`,void 0),n([m()],$.prototype,`pageState`,void 0),n([m()],$.prototype,`activationState`,void 0),n([m()],$.prototype,`verifyState`,void 0),n([m()],$.prototype,`wizardState`,void 0),n([m()],$.prototype,`wizardMode`,void 0),n([m()],$.prototype,`wizardValue`,void 0),n([m()],$.prototype,`manualProviderId`,void 0),n([m()],$.prototype,`manualApiKey`,void 0),n([m()],$.prototype,`manualError`,void 0),n([m()],$.prototype,`moreSignInOpen`,void 0),n([m()],$.prototype,`iconUrls`,void 0),n([m()],$.prototype,`setupRefreshWarning`,void 0),customElements.get(`openclaw-model-setup-page`)||customElements.define(`openclaw-model-setup-page`,$)})))()}Ut();export{Xe as resumeFirstRunActivation}; //# sourceMappingURL=model-setup-page-GgzvZ28q.js.map