UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

4 lines • 11.4 kB
import{R as resolveTimerTimeoutMs}from"./number-coercion-B3CfI447.mjs";import{o as writeRuntimeJson,t as ExitError}from"./runtime-DIcLIHcp.mjs";import{t as createDeferredCore}from"./deferred-QsZCoVH-.mjs";import{n as sanitizeTerminalText}from"./safe-text-B_QTgn0s.mjs";import{t as sleep}from"./sleep-B4CgCyZu.mjs";import{i as GATEWAY_CLIENT_NAMES,r as GATEWAY_CLIENT_MODES}from"./client-info-Dr3-kuD1.mjs";import{i as PROTOCOL_VERSION,t as MIN_CLIENT_PROTOCOL_VERSION}from"./version-CNIg0CD7.mjs";import{r as openUrl}from"./browser-open-CC7rSZD8.mjs";import{n as WizardCancelledError}from"./prompts-BviNnQo2.mjs";import{t as GatewayClientRequestError}from"./request-error-DCrb--_5.mjs";import{a as projectGatewayUrlForDiagnostics}from"./connection-details-CL6thwAz.mjs";import{c as isGatewayUnreachableSocketError,i as createGatewayUnreachableTransportError}from"./transport-error-COMVGbZH.mjs";import{r as resolveGatewayLocalPortOverride}from"./gateway-port-option-DyC2pgY0.mjs";import{t as GatewayClient}from"./client-BH-Snzbs.mjs";import{t as startGatewayClientWhenEventLoopReady}from"./readiness-BGDb6KrA.mjs";import{n as readGatewayDispatchConfigWithShellEnvFallback}from"./gateway-dispatch-config-Dls5-KRg.mjs";import{n as normalizeEdgeAuthHeadersConfig,r as resolveEdgeAuthHeaders,t as gatewayEdgeAuthValueForTarget}from"./edge-auth-xjMGW-UQ.mjs";import{r as resolveGatewayClientBootstrap}from"./client-bootstrap-CqXnvtoQ.mjs";import{r as isTerminalInteractive}from"./terminal-interactivity-ijJuF5PT.mjs";import{t as createClackPrompter}from"./clack-prompter-CkhFfk2k.mjs";import{n as parseTimeoutMsWithFallback}from"./parse-timeout-euv6DhlU.mjs";import{t as resolveGatewayAuthOptions}from"./gateway-secret-options-UPUoON4Q.mjs";import{t as answerGatewayWizardStep}from"./gateway-wizard-step-DNjCz5Ow.mjs"; //!src/commands/models/accounts.ts const SESSION_DEFAULT_NOTE=`This default applies to new sessions. Existing sessions keep their selected account.`;async function selectAccountChoice(e,t,n,r){if(t.length===0)throw new Error(`No ${e.toLowerCase()} is available for personal accounts on this Gateway.`);const i=n?.trim()??(t.length===1?t[0]?.id:await r.select({message:e,options:t.map(e=>({value:e.id,label:sanitizeTerminalText(e.label),hint:e.hint&&sanitizeTerminalText(e.hint)})),searchable:true}));const a=t.find(e=>e.id===i);if(!a)throw new Error(`Unknown ${e.toLowerCase()} ${sanitizeTerminalText(i??``)}. Available: ${t.map(e=>sanitizeTerminalText(e.id)).join(`, `)}.`);return a}async function answerAccountStep(e,t){const n=createClackPrompter(process.stderr,t);t.throwIfAborted();const r=sanitizeTerminalText(e.message??e.title??`Continue`);const i=e.options?.map(e=>({...e,label:sanitizeTerminalText(e.label),hint:e.hint&&sanitizeTerminalText(e.hint)}))??[];if(e.type===`note`&&e.format===`plain`){await n.plain?.(r);return}return await answerGatewayWizardStep({...e,message:r,title:e.title&&sanitizeTerminalText(e.title),placeholder:e.placeholder&&sanitizeTerminalText(e.placeholder),initialValue:e.type===`text`&&typeof e.initialValue===`string`?sanitizeTerminalText(e.initialValue):e.initialValue,options:i},n,{searchable:true})}async function connectAccount(e,t,n,r){n.throwIfAborted();const i=await e.request(`users.authConnect.start`,t);const a={profileId:t.profileId,connectId:i.connectId};const readStatus=()=>e.request(`users.authConnect.status`,a,{signal:n});let o;let s;let c;const retirePrompt=async()=>{o?.controller.abort();await o?.answer;o=void 0};try{n.throwIfAborted();let t=await readStatus();while(t.status===`pending`){const i=t.step;if(o?.id!==i?.id)await retirePrompt();n.throwIfAborted();if(i?.externalUrl&&i.externalUrl!==c){r.error(`Open this URL to continue:\n${sanitizeTerminalText(i.externalUrl)}`);await openUrl(i.externalUrl);n.throwIfAborted();c=i.externalUrl}if(i?.type===`progress`||i?.type===`action`&&i.executor!==`client`){if(s!==i.id){r.error(sanitizeTerminalText(i.message??i.title??`Working…`));s=i.id}}else if(i&&!o){const e=new AbortController;o={id:i.id,controller:e,answer:answerAccountStep(i,AbortSignal.any([n,e.signal])).then(e=>({value:e}),e=>({error:e}))}}const l=new AbortController;let u;try{u=await Promise.race([sleep(1e3,AbortSignal.any([n,l.signal])).then(()=>void 0),...o?[o.answer]:[]])}finally{l.abort()}n.throwIfAborted();if(u&&o){const i=o.id;await retirePrompt();if(`error`in u)throw u.error;t=await e.request(`users.authConnect.answer`,{...a,stepId:i,value:u.value},{signal:n});if(t.status===`pending`&&t.error)r.error(sanitizeTerminalText(t.error))}else t=await readStatus()}return t}catch(t){await retirePrompt();let r;try{r=await e.request(`users.authConnect.cancel`,a,{timeoutMs:3e3});if(r.status===`pending`)throw new Error(`The sign-in operation is still pending.`,{cause:t})}catch(e){throw new Error("Could not confirm sign-in cancellation. The connection is closing; run `openclaw models accounts list` to check whether an account was saved.",{cause:e})}if(r.status===`connected`||t instanceof WizardCancelledError||n.aborted)return r;throw new Error("Sign-in did not complete. Re-run `openclaw models accounts login`.",{cause:t})}finally{await retirePrompt()}}async function modelsAccountsListCommand(e,t){await withModelsAccountsGateway(e,`read`,t,async({client:n,signal:r})=>{const i=await n.request(`users.listModelAccounts`,e.cursor?{cursor:e.cursor}:{},{signal:r});if(e.json){writeRuntimeJson(t,i);return}t.log(`Personal model accounts:`);if(i.accounts.length===0)t.log("No saved accounts on this page. Use `openclaw models accounts login`.");for(const e of i.accounts)t.log(`${e.selected?`*`:`-`} ${sanitizeTerminalText(e.authProfileId)} ${sanitizeTerminalText(e.provider)}/${e.authType} ${sanitizeTerminalText(e.label)}${e.selected?` (new-session default)`:``}`);t.log(SESSION_DEFAULT_NOTE);if(i.nextCursor)t.log(`Next page: openclaw models accounts list --cursor ${sanitizeTerminalText(i.nextCursor)}`)})}async function modelsAccountsLoginCommand(e,t){if(!isTerminalInteractive(process.stderr))throw new Error(`Personal account login requires an interactive terminal for protected input. Run this command in a terminal, or use Connected accounts in Profile. Never paste credentials or authorization codes into chat or command arguments.`);try{await withModelsAccountsGateway(e,`write`,t,async({client:n,signal:r,profile:i})=>{const a=i.id;const o=await n.request(`users.authConnect.catalog`,{profileId:a},{signal:r});r.throwIfAborted();const s=createClackPrompter(process.stderr,r);const c=await selectAccountChoice(`Provider`,o.providers,e.provider,s);const l=await selectAccountChoice(`Sign-in method`,c.methods,e.method,s);r.throwIfAborted();const u=await connectAccount(n,{profileId:a,provider:c.id,method:l.id},r,t);if(e.json)writeRuntimeJson(t,{profileId:a,provider:c.id,...u});if(u.status===`connected`){if(!e.json)t.log(`Signed in: ${sanitizeTerminalText(u.authProfileId)}. ${SESSION_DEFAULT_NOTE}`);return}if(u.status===`cancelled`){t.error(`Personal account sign-in cancelled.`);throw new ExitError(130)}if(e.json)throw new ExitError(1);const d=u.status===`failed`?` (${u.reason})`:``;throw new Error(`Personal account sign-in ${u.status}${d}. Re-run the login command.`)})}catch(e){if(e instanceof WizardCancelledError)throw new ExitError(130,`Personal account sign-in cancelled.`);throw e}}async function modelsAccountsUpdateDefaultCommand(e,t){await withModelsAccountsGateway(e,`write`,t,async({client:n,signal:r,profile:i})=>{const a=i.id;const o=await n.request(e.action===`use`?`users.selectModelAccount`:`users.unlinkAuthProfile`,{profileId:a,...e.action===`use`?{authProfileId:e.authProfileId}:{provider:e.provider}},{signal:r});if(e.json)writeRuntimeJson(t,{profileId:a,...o});else t.log(e.action===`use`?`Selected ${sanitizeTerminalText(e.authProfileId)}. ${SESSION_DEFAULT_NOTE}`:`Cleared the ${sanitizeTerminalText(e.provider)} new-session default. Saved credentials and existing session accounts are unchanged.`)})}async function withModelsAccountsGateway(e,t,n,r){const i=resolveGatewayLocalPortOverride(e);const a=resolveTimerTimeoutMs(parseTimeoutMsWithFallback(e.timeout,3e4,{invalidType:`error`}),3e4);const o=await readGatewayDispatchConfigWithShellEnvFallback();const{gatewayToken:s,gatewayPassword:c}=resolveGatewayAuthOptions(e);const l=await resolveGatewayClientBootstrap({config:o,gatewayUrl:e.url,localPortOverride:i,explicitAuth:{token:s,password:c}});const u=projectGatewayUrlForDiagnostics(l.url);n.error(`Scope: Personal\nGateway: ${sanitizeTerminalText(u)}`);const d=await resolveEdgeAuthHeaders({config:o,value:normalizeEdgeAuthHeadersConfig(gatewayEdgeAuthValueForTarget({config:o,targetUrl:l.url})),targetUrl:l.url,env:process.env});const f=new AbortController;const p=createDeferredCore();const fail=e=>{f.abort(e);p.reject(e);m.stop()};const m=new GatewayClient({url:l.url,deviceAuthScope:l.deviceAuthScope,...l.sshTunnel?{sshTunnel:l.sshTunnel}:{},token:l.auth.token,password:l.auth.password,edgeAuthHeaders:d,tlsFingerprint:l.tlsFingerprint,preauthHandshakeTimeoutMs:l.preauthHandshakeTimeoutMs,requestTimeoutMs:a,clientName:GATEWAY_CLIENT_NAMES.CLI,clientDisplayName:`openclaw models accounts`,mode:GATEWAY_CLIENT_MODES.CLI,role:`operator`,scopes:t===`write`?[`operator.read`,`operator.write`]:[`operator.read`],minProtocol:4,maxProtocol:4,notifyOnStartupRetry:true,onHelloOk:()=>p.resolve(),onConnectError:e=>fail(isGatewayUnreachableSocketError(e)?createGatewayUnreachableTransportError({cause:e,connectionDetails:l.connectionDetails}):e),onClose:()=>{fail(/* @__PURE__ */ new Error(`Gateway connection closed. Re-run the personal-account command.`))}});const cancel=()=>{const e=new ExitError(130,`Personal account operation cancelled.`);f.abort(e);p.reject(e)};process.once(`SIGINT`,cancel);process.once(`SIGTERM`,cancel);const h=setTimeout(()=>fail(/* @__PURE__ */ new Error(`Gateway connection timed out.`)),a);try{await Promise.all([p.promise,startGatewayClientWhenEventLoopReady(m,{timeoutMs:a,signal:f.signal,clientOptions:{preauthHandshakeTimeoutMs:l.preauthHandshakeTimeoutMs}}).then(e=>{if(!e.ready)throw f.signal.reason??/* @__PURE__ */ new Error(`Gateway connection timed out.`);return e})]);clearTimeout(h);f.signal.throwIfAborted();let e;try{({profile:e}=await m.request(`users.self`,{},{signal:f.signal}))}catch(e){f.signal.throwIfAborted();if(e instanceof GatewayClientRequestError&&e.gatewayCode===`FORBIDDEN`)throw new Error([`Personal model accounts require a signed-in person with access to this Gateway.`,`Use --url with its Tailscale Serve or trusted-proxy WSS address. Omit shared Gateway token/password credentials when using Tailscale identity.`,`For proxy client sign-in, see https://docs.openclaw.ai/gateway/remote#gateway-behind-an-identity-aware-proxy. Browser sign-in and device pairing alone do not identify this CLI; ask an administrator if access is denied.`,"For shared or agent-local credentials instead, use `openclaw models auth login`."].join(` `),{cause:e});throw e}f.signal.throwIfAborted();const t=e.displayName?.trim()||e.emails[0]||e.githubIdentity?.login||e.id;n.error(`Person: ${sanitizeTerminalText(t)}`);return await r({client:m,signal:f.signal,profile:e})}finally{clearTimeout(h);process.off(`SIGINT`,cancel);process.off(`SIGTERM`,cancel);f.abort();try{await m.stopAndWait({timeoutMs:1e3})}catch{m.stop()}}}export{modelsAccountsListCommand,modelsAccountsLoginCommand,modelsAccountsUpdateDefaultCommand};