UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

52 lines (49 loc) • 14.4 kB
import{n as e}from"./rolldown-runtime-8BhlS34s.js";import{$i as t,Pu as n,Qi as r,Yi as i,dn as a,fn as o,pn as s,un as c,xu as l,yu as u,zu as d}from"./control-ui-core-CBJ5efDh.js";import{qr as f}from"./control-ui-core-DtLivg_r.js";import{G as p,J as m,W as h}from"./lit-runtime-IOnANfcZ.js";import{Gi as g,Mt as _,Ui as v,jt as y}from"./ui-CmSP4d14.js";import{cn as b,on as x}from"./control-ui-boot-shared-XreXSF7h.js";import{n as S,t as C}from"./en-settings-dSQ-fDvm.js";import{f as w,o as T,s as E,t as D}from"./state-Bjk4TzHh.js";import{r as O,t as k}from"./wizard-step-controls-BftYzvp2.js";var A;function j(){return(j=e((()=>{v(),l(),i(),c(),_(),T(),A=class{constructor(e){this.options=e,this.currentState={phase:`idle`},this.session=null,this.retirementGeneration=0}prepareSignIn(e,t){this.authLabel=t,this.pendingSignIn?.window?.close();let n=e===`oauth`||e===`device-code`;this.pendingSignIn={kind:n?e:`secret`,window:n?o():null}}get state(){return this.currentState}get hasAdmittedSession(){return this.session?.admitted===!0}suspend(e){let t=this.session;t&&(t.suspended=!0,t.abortController.abort(),t.reservedWindow?.close(),t.reservedWindow=null,this.setState({phase:`starting`,authChoice:t.authChoice,...e?{notice:e}:{}}))}restore(e,t){let n=this.options.getClient();n&&!this.session&&(this.session={...e,client:n,notes:[],admitted:!0,retirementGeneration:this.retirementGeneration,abortController:new AbortController,startMethod:`openclaw.setup.auth.start`,onTerminalResult:t},this.setState({phase:`starting`,authChoice:e.authChoice}))}async resume(){let e=this.session,t=this.options.getClient();if(!e?.admitted||!t)return null;e.retired=!0,e.abortController.abort();let n={...e,client:t,abortController:new AbortController,cancellationPromise:void 0,inputClosurePromise:void 0,suspended:!1,retired:!1};this.session=n,this.setState({phase:`starting`,authChoice:n.authChoice});try{return n.terminalResult?this.applyResult(n,n.terminalResult):await this.requestNext(n)}catch(e){return this.handleError(e,n),null}}async start(e,t=`openclaw.setup.auth.start`,n={},r){return this.startSession(e,t,{authChoice:e,...n,...r?{modelTarget:r}:{}})}activate(e,t){return this.startSession(e.authChoice??e.kind,`openclaw.setup.activate.start`,e,t)}startMcpLogin(e){return this.startSession(e,`mcp.authLogin`,{serverName:e})}async startSession(e,t,n,i){let a=this.options.getClient();if(!a||this.currentState.phase!==`idle`)return null;let o=y(),s={client:a,sessionId:o,retirementGeneration:this.retirementGeneration,authChoice:e,authKind:this.pendingSignIn?.kind,notes:[],reservedWindow:this.pendingSignIn?.window,abortController:new AbortController,startMethod:t,activationTargetId:i,onTerminalResult:this.options.onStart?.(t,`kind`in n?n:t===`openclaw.setup.auth.start`&&`authChoice`in n?{...n,kind:`provider-auth`,wizard:{sessionId:o,authChoice:e,authKind:this.pendingSignIn?.kind}}:void 0)};this.pendingSignIn=void 0,this.session=s,this.setState({phase:`starting`,authChoice:e});try{let e=t===`mcp.authLogin`?null:this.options.getAgentId(),i=a.request(t,{sessionId:s.sessionId,...n,...e?{agentId:e}:{}},{timeoutMs:null}).catch(e=>{if(!r(e))throw e;return{done:!0,status:`not-admitted`,error:u(e,this.options.requestFailedMessage())}}),o=await this.awaitWizardStart(s,i);return o.done?this.applyResult(s,o):(s.admitted=!0,s===this.session?await this.requestNext(s):(await this.cancelSession(s),null))}catch(e){return this.handleError(e,s),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,i)}catch(e){let t=r.externalInputRequest;if(t){r.externalInputRequest=void 0;let e=await t;if(e||r!==this.session)return e}return this.handleError(e,r),null}}async cancel(e={}){let t=this.session;this.clearSession(!e.settleActiveRequest),t&&await this.cancelSession(t)}async requestCancellation(){let e=this.session;if(!e)return this.close(),`cancelled`;e.cancellationRequested=!0;let n=()=>e===this.session&&!this.isRetired(e)&&!e.suspended,r;try{r=await this.sendCancellation(e)}catch(r){if(!n())return;if(t(r)){this.handleError(r,e);return}throw r}if(n()){if(r?.status===`cancelled`||r?.status===`error`){if(e.startMethod===`models.authLogin`||e.startMethod===`mcp.authLogin`){try{await e.client.request(`wizard.status`,{sessionId:e.sessionId},{timeoutMs:null,signal:e.abortController.signal})}catch(e){if(!n())return;if(!t(e))throw e}if(!n())return}return this.close(),`cancelled`}if(r?.status===`running`)return e.cancellationRequested=!1,`running`}}close(e={}){e.retireOwner&&(this.retirementGeneration+=1),this.clearSession()}clearSession(e=!0){this.pendingSignIn?.window?.close(),this.pendingSignIn=void 0,this.session?.reservedWindow?.close(),clearTimeout(this.session?.externalInputTimer),e&&this.session?.abortController.abort(),this.session=null,this.authLabel=void 0,this.setState({phase:`idle`})}fail(e){let t=this.authLabel;this.close(),this.authLabel=t,this.setState({phase:`error`,message:e})}async awaitWizardStart(e,t){let n=!1,r=t.then(async t=>(n&&(t.done?this.reportTerminalResult(e,t):await this.cancelSession(e)),t));return await g(r,D,()=>{throw n=!0,Error(this.options.gatewayNotRespondingMessage())})}async requestNext(e,t,n){if(e.suspended||this.isRetired(e))return null;let{client:r,sessionId:i,abortController:a,authChoice:o}=e,s=a.signal,c=t,l=n;for(;;){let t=await r.request(`wizard.next`,{sessionId:i,...c?{answer:c}:{}},{timeoutMs:null,signal:s});if(l&&!l()&&!t.done)return null;if(l=void 0,e===this.session&&!e.suspended&&!this.isRetired(e)&&!t.done&&t.step?.type===`note`&&(e.authKind===`oauth`||e.authKind===`device-code`)){t.step.message&&e.notes.push(t.step.message),(t.step.externalUrl||t.step.deviceCode)&&this.setState({phase:`step`,authChoice:o,step:t.step,busy:!0,validationError:null}),this.openSignInUrl(e,t.step.externalUrl),c={stepId:t.step.id};continue}let n=this.applyResult(e,t);if(e!==this.session||n)return n;let a=this.currentState;if(a.phase!==`step`||a.step.executor!==`gateway`)return null;c=void 0}}applyResult(e,t){if(e===this.session&&e.suspended&&t.done)return e.terminalResult=t,null;let n=this.reportTerminalResult(e,t);if(e!==this.session||e.suspended)return null;if(n?.()===!1||t.done&&t.status===`cancelled`&&e.cancellationRequested)return this.close(),null;let r=w(e.authChoice,t,t.status===`cancelled`?this.options.cancelledMessage():this.options.requestFailedMessage());return r.phase===`step`&&e.authKind===`oauth`&&r.step.type===`text`&&r.step.externalUrl&&(r={...r,externalAuthInput:!0}),e.notes.length&&(r.phase===`error`?r={...r,message:[r.message,...e.notes].join(` `)}:r.phase===`step`&&r.step.executor!==`gateway`&&!r.step.externalUrl&&(r={...r,step:{...r.step,message:[r.step.message,...e.notes].filter(Boolean).join(` `)}})),t.done&&(clearTimeout(e.externalInputTimer),e.reservedWindow?.close(),this.session=null),this.setState(r),r.phase===`step`&&(this.openSignInUrl(e,r.step.externalUrl),r.externalAuthInput?this.watchExternalInput(e,r):r.step.executor!==`gateway`&&(e.reservedWindow?.close(),e.reservedWindow=null)),!t.done||t.status!==`done`?null:{startMethod:e.startMethod,...e.activationTargetId?{activationTargetId:e.activationTargetId}:{},...n?{isCurrent:n}:{},...t.preparedModelRef?{preparedModelRef:t.preparedModelRef}:{},...t.modelActivation?{modelActivation:t.modelActivation}:{}}}openSignInUrl(e,t){if(!t||e.openedUrl===t)return;let n=s(t,window.location.href);n&&(e.reservedWindow&&!e.reservedWindow.closed?(e.reservedWindow.location.replace(n),e.reservedWindow=null):a(n),e.openedUrl=t)}watchExternalInput(e,t){let n=async()=>{let n=()=>e===this.session&&this.currentState===t&&!e.suspended;if(n())try{let t=this.requestNext(e,void 0,n);e.externalInputRequest=t;let r=await t;if(e.externalInputRequest!==t)return;if(e.externalInputRequest=void 0,r){let e=this.currentState,t=r.isCurrent;await this.options.onBackgroundCompletion?.({...r,isCurrent:()=>this.currentState===e&&t?.()!==!1})}}catch(t){n()&&this.handleError(t,e)}};e.externalInputTimer=setTimeout(()=>{n()},1e3)}handleError(e,n){if(n!==this.session||n.suspended)return;clearTimeout(n.externalInputTimer),n.reservedWindow?.close(),this.session=null,n.abortController.abort();let r=t(e);r?this.options.onSessionMissing?.():this.cancelSession(n);let i=r?this.options.sessionExpiredMessage():u(e,this.options.requestFailedMessage());this.setState({phase:`error`,message:[i,...n.notes].join(` `)})}async cancelSession(e){try{await this.sendCancellation(e,e.startMethod===`models.authLogin`||e.startMethod===`mcp.authLogin`)}catch{}}async sendCancellation(e,t=!1){if(this.isRetired(e))return;let n=t?`inputClosurePromise`:`cancellationPromise`;return e[n]||(e[n]=e.client.request(`wizard.cancel`,{sessionId:e.sessionId,...t?{closeInput:!0}:{}},{timeoutMs:D}).then(t=>((t.status===`cancelled`||t.status===`error`)&&this.reportTerminalResult(e,{done:!0,...t}),t)).finally(()=>{e[n]=void 0})),e[n]}reportTerminalResult(e,t){if(this.isRetired(e)||e.suspended)return;let n=t.status===`cancelled`||t.status===`error`||t.status===`not-admitted`;if(t.done&&(e===this.session||n))return e.onTerminalResult?.(t)}isRetired(e){return e.retired===!0||e.retirementGeneration!==this.retirementGeneration}setState(e){clearTimeout(this.session?.externalInputTimer),this.authLabel&&(e.authLabel=this.authLabel),this.currentState=e,this.options.onChange(e)}}})))()}function M(e){let{state:t}=e;if(t.phase===`idle`)return p;let n=t.phase===`starting`||t.phase===`step`,r=N[e.mode],i;return i=t.phase===`starting`?m`<div role="status">${d(r.starting)}</div>`:t.phase===`done`?m`<div role="status"> ${e.doneMessage??d(e.mode===`auth`?`modelSetup.wizard.connected`:`modelSetup.wizard.checking`)} </div>`:t.phase===`error`&&e.mode===`auth`?m`<div class="callout danger model-setup-wizard__error" role="alert"> <p class="model-setup-wizard__error-text">${t.message}</p> <div class="model-setup-wizard__error-copy"> ${b(t.message,d(`modelSetup.wizard.copy`))} </div> </div>`:t.phase===`error`||t.phase===`cancelled`?m`<div class="callout danger" role="alert">${t.message}</div>`:m` ${t.validationError?m`<div id="model-setup-wizard-validation-error" class="callout danger" role="alert"> ${t.validationError} </div>`:p} ${O({step:t.step,externalAuthInput:t.externalAuthInput,value:e.value,busy:t.busy,inputId:`model-setup-wizard-text-input`,validationErrorId:t.validationError?`model-setup-wizard-validation-error`:void 0,confirmAffirmativeLabel:e.mode===`prepare`&&t.step.type===`confirm`?d(`modelSetup.wizard.continue`):void 0,leadingAction:m`<button type="button" class="btn" @click=${e.onCancel}> ${d(`common.cancel`)} </button>`,onValueChange:e.onValueChange,onAnswer:e.onAnswer})} ${t.busy&&!t.step.externalUrl&&!t.step.deviceCode?m`<div role="status">${d(`modelSetup.wizard.working`)}</div>`:p} `,m` <openclaw-modal-dialog label=${d(r.dialog)} @modal-cancel=${n?e.onCancel:e.onClose} > <div class="model-setup-wizard"> <div class="model-setup-wizard__header"> <h2> ${t.authLabel||t.phase===`step`&&t.step.title||d(r.titleKey)} </h2> </div> <div class="model-setup-wizard__body"> ${[e.refreshWarning,e.cancellationNotice,t.phase===`starting`?t.notice:void 0].map(e=>e?m`<div class="callout warning" role="alert">${e}</div>`:p)} ${i} </div> ${t.phase===`step`?p:m` <div class="model-setup-wizard__footer"> <button type="button" class="btn" @click=${n?e.onCancel:e.onClose} > ${d(n?`common.cancel`:`common.close`)} </button> </div> `} </div> </openclaw-modal-dialog> `}var N;function P(){return(P=e((()=>{h(),x(),k(),n(),f(),N={auth:{dialog:`modelSetup.wizard.dialogLabel`,titleKey:`modelSetup.wizard.title`,starting:`modelSetup.wizard.starting`},prepare:{dialog:`modelSetup.wizard.prepareDialogLabel`,titleKey:`modelSetup.wizard.prepareTitle`,starting:`modelSetup.wizard.prepareStarting`},activate:{dialog:`modelSetup.heading`,titleKey:`modelSetup.heading`,starting:`modelSetup.wizard.checking`}}})))()}function F(){return(F=e((()=>{})))()}var I;function L(){return(L=e((()=>{h(),n(),C(),l(),T(),j(),P(),S(),I=class{constructor(e,t){this.host=e,this.options=t,this.cancelling=!1,this.stepId=null,this.generation=0,this.cancellationNotice=null,this.runner=new A({...t,onChange:t=>{t.phase===`starting`&&(this.generation+=1),t.phase!==`step`&&(this.cancelling=!1,this.cancellationNotice=null),t.phase===`step`&&t.step.id!==this.stepId?this.value=E(t.step):t.phase!==`step`&&(this.value=void 0),this.stepId=t.phase===`step`?t.step.id:null,e.requestUpdate()},cancelledMessage:()=>d(`modelSetup.wizard.cancelled`),gatewayNotRespondingMessage:()=>d(`modelSetup.wizard.gatewayNotResponding`)})}reset(){this.generation+=1,this.cancelling=!1,this.cancellationNotice=null,this.runner.cancel()}render(e={}){let t=this.runner.state;return m`<div @modal-cancel=${e=>e.preventDefault()}> ${M({mode:e.mode??`auth`,state:t.phase===`step`?{...t,busy:t.busy||!!e.busy}:t,refreshWarning:e.refreshWarning??null,doneMessage:e.doneMessage,cancellationNotice:this.cancellationNotice,value:this.value,onValueChange:e=>{this.value=e,this.host.requestUpdate()},onAnswer:this.options.onAnswer??((e,t)=>void this.runner.answer(e,t)),onCancel:()=>void this.cancel(),onClose:this.options.onClose})} </div>`}async cancel(){if(this.cancelling||this.runner.state.phase===`done`)return;let e=this.generation;this.cancelling=!0,this.cancellationNotice=null;try{let t=await this.runner.requestCancellation();if(e!==this.generation)return;t===`running`?this.cancellationNotice=d(`modelProviders.login.finishing`):t===`cancelled`&&this.options.onClose()}catch(t){e===this.generation&&(this.cancellationNotice=d(`modelSetup.wizard.cancelFailed`,{error:u(t,this.options.requestFailedMessage())}))}finally{e===this.generation&&(this.cancelling=!1,this.host.requestUpdate())}}}})))()}export{M as a,P as i,L as n,A as o,F as r,j as s,I as t};