openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
13 lines • 25.7 kB
JavaScript
import{l as normalizeOptionalString}from"./string-coerce-CpTFcSwY.mjs";import"./src-0ci69Prg.mjs";import{t as expectDefined}from"./expect-DkJCbmLj.mjs";import{l as isRecord}from"./record-coerce-BTbqdJ3-.mjs";import{t as ExitError}from"./runtime-DIcLIHcp.mjs";import"./utils-Dlk0IYAa.mjs";import"./model-ref-shared-T-aCqInj.mjs";import{t as formatCliCommand}from"./command-format-D7KhNLP0.mjs";import{r as normalizeProviderId}from"./provider-id-A-8WTtLA.mjs";import{f as resolveAgentWorkspaceDir}from"./agent-scope-config-CG9CFpGX.mjs";import{n as normalizeSecretInput}from"./normalize-secret-input-CEFJUjQX.mjs";import{r as normalizeAgentModelRefForConfig}from"./model-input-CJnF-FEy.mjs";import{i as resolveProviderIdForAuth}from"./provider-auth-aliases-BRA1A5Vm.mjs";import"./agent-scope-Dw5XRSEh.mjs";import{t as parseDurationMs}from"./parse-duration-BueP0M46.mjs";import{i as resolvePluginSetupRegistry,r as resolvePluginSetupProviderCore}from"./setup-registry-JeNUWxS6.mjs";import{t as resolveSharedMainAuthAgentDir}from"./shared-main-dir-CnBJA5xX.mjs";import{B as listRuntimeLocalProfileIds}from"./runtime-snapshots-DYK7vyJv.mjs";import{c as prepareUserProfileCatalog}from"./user-profile-list-DJsakwXy.mjs";import{t as isNamedOperatorRoleEnforcementEnabled}from"./operator-role-enforcement-FsaRvImR.mjs";import{r as resolvePluginProvidersCore}from"./providers.runtime-DBX2iu0m.mjs";import{t as isCliProvider}from"./model-selection-cli-K7oSL0Pc.mjs";import{g as loadAuthProfileStoreWithoutExternalProfilesAsync}from"./store-runtime-GNz-2GjY.mjs";import{t as runProviderPluginAuthMethodUnpersisted}from"./provider-auth-method-cNzE--nG.mjs";import{a as removeProviderAuthProfilesWithLock,d as upsertAuthProfileWithLockOrThrow,r as promoteAuthProfileInOrder}from"./profiles-Bp0-JifZ.mjs";import{r as logConfigUpdated}from"./logging-C183DMvG.mjs";import{n as ProviderCredentialsSavedError,t as ProviderAuthConfigApplyError}from"./provider-auth-result-BBq2IiCp.mjs";import"./auth-profiles-nMUErGRQ.mjs";import{t as applyPrimaryModel}from"./provider-model-primary-10d4qbG3.mjs";import{a as repairModelSelectionRuntimePlugins}from"./runtime-plugin-install-B9zy32i-.mjs";import{i as resolveProviderMatch,o as restorePriorAgentsDefaultsModelUnlessOptIn,r as pickAuthMethod,t as applyProviderAuthConfigPatchWithNormalization}from"./provider-auth-choice-helpers-DVN0Uqx5.mjs";import{t as applyAuthProfileConfig}from"./provider-auth-helpers-5o5rkp5c.mjs";import{n as persistProviderAuthProfilesAfterLogin}from"./provider-auth-persistence-C3GsdSL_.mjs";import{t as createClackPrompter}from"./clack-prompter-CkhFfk2k.mjs";import{i as loadValidConfigSnapshotOrThrow,l as resolveModelsTargetAgent,u as updateConfig}from"./shared-Sc7lnGKV.mjs";import{n as validateAnthropicSetupToken}from"./provider-auth-token-kKebY-yg.mjs";import{c as select$2,l as text$2,r as confirm$2,s as password$2}from"./configure.shared-B8OO46LH.mjs";import{t as withPluginMigrationProviders}from"./migration-provider-runtime-lHLy-ONV.mjs";import{t as buildMigrationContext}from"./context-DIgQQdr4.mjs";import{t as applyMigrationItemSelection}from"./item-selection-CarpN-9p.mjs";import{n as refreshRunningGatewayAuthState,r as refreshSavedAuthAfterSettingsFailure,t as refreshProviderAuthAfterLogin}from"./auth-refresh-B35YNJt_.mjs";import{a as resolveManualTokenExpiryMs,i as resolveDefaultTokenProfileId,n as normalizeManualAuthProvider,o as validateOpenAICodexApiKeyInput,r as readPipedStdin,t as looksLikeOpenAIApiKey}from"./auth-manual-input-Cy929dbG.mjs";import{a as withoutProviderModelPolicy,i as applyProviderLoginDefaultModel,n as allowLoginProviderModels,r as allowProviderModelsInConfig,t as saveModelProviderApiKey}from"./auth-api-key-c5ZXRfay.mjs";import{n as writeProviderAuthConfig,t as createProviderAuthConfigPatch}from"./provider-auth-config-BxgMLaPA.mjs";import path from"node:path";import{cancel}from"@clack/prompts";
//!src/commands/models/auth-credential-import.ts
async function tryImportProviderCredential(e){const t=e.method.credentialImport;if(!t)return;const n=normalizeProviderId(e.providerId);e.signal?.throwIfAborted();return await withPluginMigrationProviders({providerId:t.migrationProviderId,cfg:e.config},async r=>{const i=r.find(e=>e.id===t.migrationProviderId);if(!i)return;const a=buildMigrationContext({targetAgentId:e.agentId,itemKinds:[`auth`],includeSecrets:true,configOverride:e.config,providerOptions:{allowKeychainPrompt:true,credentialKind:t.credentialKind,configPatchMode:`none`},runtime:e.runtime});if(e.signal)a.signal=e.signal;const o=await i.plan(a);const s=o.items.filter(e=>e.id===t.itemId);if(s.length>1)throw new Error(`The credential import has an ambiguous item identity.`);const c=s[0];if(c?.status===`skipped`&&c.details?.credentialImportUnavailable===true)return c.message?{unavailableReason:c.message}:void 0;if(c?.kind!==`auth`||c.status!==`planned`||c.details?.credentialKind!==t.credentialKind)return;if(typeof c.details.provider!==`string`||normalizeProviderId(c.details.provider)!==n)throw new Error(`The credential import belongs to another provider.`);e.signal?.throwIfAborted();await e.beforePersistentEffect?.();e.signal?.throwIfAborted();const l=(await i.apply(a,applyMigrationItemSelection(o,[t.itemId]))).items.find(e=>e.id===t.itemId&&e.kind===`auth`&&e.status===`migrated`);const u=l?.details?.profileId;if(typeof u!==`string`||!u.trim()||typeof l?.details?.provider!==`string`||normalizeProviderId(l.details.provider)!==n||l.details.credentialKind!==t.credentialKind)throw new Error(`The existing provider credential changed during import. Start the sign-in again.`);return{profileId:u.trim(),provider:n,mode:t.credentialKind,configUpdated:l.details.configUpdated===true}})}
//!src/commands/models/auth-profile-promotion.ts
async function promotePersistedAuthProfile(e){const t=e.config;const n=resolveProviderIdForAuth(e.provider,{config:t});const r=Object.entries(t.auth?.order??{}).find(([e,r])=>r.length>0&&resolveProviderIdForAuth(e,{config:t})===n)?.[1]??Object.entries(t.auth?.profiles??{}).filter(([,e])=>resolveProviderIdForAuth(e.provider,{config:t,storedCredential:true})===n).map(([e])=>e);if(!(await promoteAuthProfileInOrder({agentDir:e.agentDir,provider:e.provider,profileId:e.profileId,assertCurrent:e.assertCurrent,createIfMissing:r.length>0,...r.length>0?{createFromOrder:r}:{}})).ok)throw new ProviderCredentialsSavedError(`The auth profile was saved, but its order could not be updated because the auth store is busy. Wait a moment, then retry the login.`)}
//!src/commands/models/auth-relogin-identity.ts
async function snapshotReloginAuthProfiles(e){if(!(e.method.matchesSharedAccount??e.method.matchesPersonalAccount))return;const t=path.resolve(e.agentDir)===path.resolve(resolveSharedMainAuthAgentDir())?void 0:e.agentDir;const n=await loadAuthProfileStoreWithoutExternalProfilesAsync(t);return Object.fromEntries(listRuntimeLocalProfileIds(n).flatMap(e=>{const t=n.profiles[e];return t?[[e,t]]:[]}))}function resolveReloginProfileIdentity(e){const t=e.requestedProfileId?.trim();if(t){if(e.profiles.length!==1)throw new Error(`--profile-id requires exactly one returned auth profile from the selected auth method.`);return{profiles:[{...expectDefined(e.profiles[0],`auth profile`),profileId:t}]}}const n=e.method?.canReplaceGeneratedProfile;const r={profiles:e.profiles,...n&&{validateCurrentCredential:(t,r)=>{if(!r)return;const i=e.profiles.find(e=>e.profileId===t);if(!i||r.provider!==i.credential.provider||!n(i.credential,r))throw new Error(`The automatic auth profile ID is already in use. Use a different profile ID with --profile-id when signing in from the CLI.`)}}};const i=e.method?.matchesSharedAccount??e.method?.matchesPersonalAccount;if(!i||!e.existingProfiles||e.profiles.length!==1)return r;const a=expectDefined(e.profiles[0],`auth profile`);const o=[];for(const[t,n]of Object.entries(e.existingProfiles))try{if(i(a.credential,n))o.push(t)}catch{return r}if(o.length!==1)return r;const s=expectDefined(o[0],`matched auth profile id`);return{profiles:[{...a,profileId:s}],validateCurrentCredential:(t,n)=>{let r=false;if(n)try{r=i(a.credential,n)}catch{r=false}if(t!==s||(n?!r:!e.allowMissingReusedProfile))throw new Error(`The existing auth profile identity changed during sign-in. Start the sign-in again.`)}}}
//!src/commands/models/auth-scope-note.ts
async function isSharedGatewayForCliLogin(e){const t=e.gateway;if(t?.mode===`remote`||t?.auth?.mode===`trusted-proxy`||isNamedOperatorRoleEnforcementEnabled(e)||Object.keys(t?.auth?.identityScopes??{}).length>0)return true;try{const e=await prepareUserProfileCatalog();try{return e.hasMultipleSessionSharingIdentities()}finally{e.release()}}catch{return true}}async function showModelsAuthScopeNote(e,t){await e.note([`Scope: System / agent`,`Agent: ${t}`,`Location: the machine running OpenClaw`,`For personal model accounts on a Gateway, run ${formatCliCommand(`openclaw models accounts login --help`)}.`].join(`
`),`Provider sign-in`)}
//!src/commands/models/auth.ts
function requireManualAuthProvider(e){const t=normalizeOptionalString(e);if(!t)throw new Error(`Missing --provider. Run ${formatCliCommand(`openclaw models status`)} or ${formatCliCommand(`openclaw plugins list`)} to choose a provider.`);return normalizeManualAuthProvider(t)}function guardCancel(e){if(typeof e===`symbol`){cancel(`Cancelled.`);throw new ExitError(0)}return e}const confirm$1=async e=>guardCancel(await confirm$2(e));const text$1=async e=>guardCancel(await text$2(e));const password$1=async e=>guardCancel(await password$2(e));const select$1=async e=>guardCancel(await select$2(e));async function readPastedSecret(e){const t=process.stdin.isTTY?await password$1(e):await readPipedStdin();const n=normalizeSecretInput(t);const r=e.validate(n);if(r)throw new Error(r);return n}function listProvidersWithTokenMethods(e){return e.filter(e=>e.auth.some(e=>e.kind===`token`))}async function resolveModelsAuthContext(e){const t=await loadValidConfigSnapshotOrThrow();const n=e?.config??t.runtimeConfig;const{agentId:r,agentDir:i}=resolveModelsTargetAgent(n,e?.rawAgentId??void 0,{kind:`mutation`});const a=resolveAgentWorkspaceDir(n,r);const o=e?.requestedProvider?.trim();const s=o?normalizeManualAuthProvider(o):void 0;const c=resolvePluginProvidersCore({config:n,workspaceDir:a,mode:`setup`,includeUntrustedWorkspacePlugins:false,...e?.ownerPluginId?{onlyPluginIds:[e.ownerPluginId]}:{},...s?{providerRefs:[s]}:{}});const l=e?.ownerPluginId;let u;if(!l&&s){const e=resolvePluginSetupProviderCore({provider:s,config:n,workspaceDir:a});u=e?[e]:[...c]}else{const e=resolvePluginSetupRegistry({config:n,workspaceDir:a,...l?{pluginIds:[l]}:{}}).providers.map(e=>e.provider);const t=new Map(e.map(e=>[normalizeProviderId(e.id),e]));const r=new Set(c.map(e=>normalizeProviderId(e.id)));u=[...c.map(e=>t.get(normalizeProviderId(e.id))??e),...e.filter(e=>!r.has(normalizeProviderId(e.id)))]}return{config:n,configSnapshot:t,agentId:r,agentDir:i,workspaceDir:a,providers:u}}function resolveRequestedLoginProviderOrThrow(e,t){const n=t?.trim();if(!n)return null;const r=resolveProviderMatch(e,n);if(r)return r;const i=e.map(e=>e.id).filter(Boolean).toSorted((e,t)=>e.localeCompare(t));const a=i.length>0?i.join(`, `):`(none)`;throw new Error(`Unknown provider "${n}". Loaded providers: ${a}. Verify plugins via \`${formatCliCommand(`openclaw plugins list --json`)}\`.`)}async function pickProviderAuthMethod(e){const t=e.requestedMethod?.trim();if(t)return pickAuthMethod(e.provider,t);const n=e.tokenOnly?e.provider.auth.filter(e=>e.kind===`token`):e.provider.auth;if(e.tokenOnly&&n.length===0)return null;const r=n.find(t=>e.tokenOnly?t.id===`setup-token`:t.kind===`oauth`);if(r)return r;if(n.length===1)return n[0]??null;return e.prompter.select({message:`${e.tokenOnly?`Token`:`Auth`} method for ${e.provider.label}`,options:n.map(e=>({value:e.id,label:e.label,hint:e.hint}))}).then(e=>n.find(t=>t.id===e)??null)}async function runProviderAuthMethod(e){e.signal?.throwIfAborted();e.assertCurrent?.();const t=await loadAuthProfileStoreWithoutExternalProfilesAsync(e.agentDir);const n=Object.entries(t.profiles).filter(([t,n])=>n.provider===e.provider.id&&(!e.profileId||t===e.profileId)).map(([e,t])=>({profileId:e,credential:t}));const r=await runProviderPluginAuthMethodUnpersisted({method:e.method,config:e.config,existingProfiles:n,credentialOnly:e.credentialOnly,assertCurrent:e.assertCurrent,env:e.env??process.env,agentDir:e.agentDir,workspaceDir:e.workspaceDir,prompter:e.prompter,runtime:e.runtime,allowSecretRefPrompt:false,isRemote:e.isRemote,signal:e.signal,openUrl:e.openUrl,browserAuthorization:e.browserAuthorization});e.signal?.throwIfAborted();const i=e.credentialOnly?{profiles:r.profiles,notes:r.notes,...r.configPatch?{configPatch:{...r.configPatch.models?.providers?{models:{providers:r.configPatch.models.providers}}:{},...r.configPatch.plugins?{plugins:r.configPatch.plugins}:{}}}:{}}:r;const a=resolveReloginProfileIdentity({profiles:i.profiles,requestedProfileId:e.profileId,existingProfiles:e.existingProfiles,method:e.method,allowMissingReusedProfile:e.allowMissingReusedProfile});const o=a.profiles;const s={...e,result:i,profiles:o,env:e.env??process.env,validateCurrentCredential:a.validateCurrentCredential};let c;const l=s.result.defaultModel?normalizeAgentModelRefForConfig(s.result.defaultModel):void 0;const u=[];const d=applyProviderAuthConfigPatchWithNormalization(s.config,{});const f=s.result.configPatch?createProviderAuthConfigPatch(d,restorePriorAgentsDefaultsModelUnlessOptIn({cfg:applyProviderAuthConfigPatchWithNormalization(d,o.length>0?withoutProviderModelPolicy(s.result.configPatch,d):s.result.configPatch,{replaceDefaultModels:s.result.replaceDefaultModels}),priorAgentsDefaultsModel:d.agents?.defaults?.model,setDefault:s.setDefault})):void 0;const p=isRecord(f)&&Object.keys(f).length>0||Boolean(s.setDefault&&l);if(o.length>0||p)await s.beforePersistentEffect?.();try{for(const e of o){const t=await persistProviderAuthProfilesAfterLogin({profiles:[e],beforeWrite:s.assertCurrent,validateCurrentCredential:s.validateCurrentCredential,config:s.config,env:s.env,agentDir:s.agentDir,...s.env?.OPENCLAW_STATE_DIR?{stateDir:s.env.OPENCLAW_STATE_DIR}:{}});const n=expectDefined(t[0],`persisted auth profile`);u.push(n);s.assertCurrent?.();await promotePersistedAuthProfile({config:s.config,agentDir:s.agentDir,provider:n.credential.provider,profileId:n.profileId,assertCurrent:s.assertCurrent})}if(p){const e=await writeProviderAuthConfig({config:s.config,configSnapshot:s.configSnapshot,configPatch:f,credentialsSaved:u.length>0,beforeCommit:s.assertCurrent,writeOptions:{assertCurrent:s.assertCurrent},finalizeConfig:(e,t)=>{const n=t.agents?.defaults?.model;const r=restorePriorAgentsDefaultsModelUnlessOptIn({cfg:e,priorAgentsDefaultsModel:n,setDefault:s.setDefault});if(s.setDefault&&l)return o.length>0?applyProviderLoginDefaultModel(r,l):applyPrimaryModel(r,l);return r}});if(l){const t=await repairModelSelectionRuntimePlugins({cfg:e,model:l});for(const e of t)s.runtime.error?.(e)}logConfigUpdated(s.runtime)}c=await refreshProviderAuthAfterLogin(s);for(const e of u)s.runtime.log(`Auth profile: ${e.profileId} (${e.credential.provider}/${e.credential.type})`);if(l)s.runtime.log(s.setDefault?`Default model set to ${l}`:`Default model available: ${l} (current default unchanged; run ${formatCliCommand(`openclaw models set ${l}`)} to apply)`);if(s.result.notes&&s.result.notes.length>0)await s.prompter.note(s.result.notes.join(`
`),`Provider notes`)}catch(e){if(e instanceof ProviderAuthConfigApplyError)await refreshSavedAuthAfterSettingsFailure(s);if(u.length>0&&!(e instanceof ProviderCredentialsSavedError))throw new ProviderCredentialsSavedError(e instanceof Error?`Provider credentials were saved, but sign-in did not finish: ${e.message}`:`Provider credentials were saved, but sign-in did not finish.`,{cause:e});throw e}const m=u.length>0?await allowLoginProviderModels(e,e.agentId,e.provider.id):void 0;return{result:i,profiles:u,authRefresh:c,modelAccess:m}}async function modelsAuthSetupTokenCommand(e,t){if(!process.stdin.isTTY)throw new Error(`setup-token requires an interactive TTY. In automation, use ${formatCliCommand(`openclaw models auth paste-token --provider <provider>`)} instead.`);const n=await resolveModelsAuthContext({requestedProvider:e.provider,rawAgentId:e.agent});const r=listProvidersWithTokenMethods(n.providers);if(r.length===0)throw new Error(`No provider token-auth plugins found. Install one via \`${formatCliCommand(`openclaw plugins install`)}\`.`);const i=resolveRequestedLoginProviderOrThrow(r,e.provider)??r[0];if(!e.yes){if(!await confirm$1({message:`Continue with ${i.label} token auth?`,initialValue:true}))return}const a=createClackPrompter();const o=await pickProviderAuthMethod({provider:i,prompter:a,tokenOnly:true});if(!o)throw new Error(`Provider "${i.id}" does not expose a token auth method.`);await runProviderAuthMethod({...n,provider:i,method:o,runtime:t,prompter:a})}async function modelsAuthPasteTokenCommand(e,t){await pasteManualAuthCredential(e,t,`token`)}async function modelsAuthPasteApiKeyCommand(e,t){await pasteManualAuthCredential(e,t,`api_key`)}async function pasteManualAuthCredential(e,t,n){const r=(await loadValidConfigSnapshotOrThrow()).runtimeConfig;const{agentId:i,agentDir:a}=resolveModelsTargetAgent(r,e.agent??void 0,{kind:`mutation`});const o=requireManualAuthProvider(e.provider);const s=n===`token`?normalizeOptionalString(e.profileId)||resolveDefaultTokenProfileId(o):void 0;const c=await readPastedSecret({message:`Paste ${n===`token`?`token`:`API key`} for ${o}`,validate:e=>{const t=e?.trim();if(!t)return`Required`;if(n===`api_key`)return o===`openai`?validateOpenAICodexApiKeyInput(t):void 0;if(o===`anthropic`)return validateAnthropicSetupToken(t.replaceAll(/\s+/g,``));if(o===`openai`&&looksLikeOpenAIApiKey(t))return`That looks like an OpenAI API key. Use ${formatCliCommand(`openclaw models auth paste-api-key --provider openai`)} for API-key auth.`}});let l=s;let u;let d;if(s!==void 0){const t=o===`anthropic`?c.replaceAll(/\s+/g,``).trim():normalizeOptionalString(c)??``;const n=resolveManualTokenExpiryMs(e.expiresIn);await upsertAuthProfileWithLockOrThrow({profileId:s,credential:{type:`token`,provider:o,token:t,...n?{expires:n}:{}},agentDir:a});await updateConfig(e=>{const t=applyAuthProfileConfig(e,{profileId:s,provider:o,mode:`token`});d=allowProviderModelsInConfig(t,i,o);return t})}else({profileId:l,warning:u,modelAccess:d}=await saveModelProviderApiKey({config:r,provider:o,apiKey:c,agentId:i,agentDir:a,profileId:normalizeOptionalString(e.profileId)}));await refreshRunningGatewayAuthState(i,`login`,t);if(u)t.error(u);logConfigUpdated(t);t.log(`Auth profile: ${l} (${o}/${n})`);if(d)t.log(d);if(n===`token`&&o===`anthropic`){t.log(`Anthropic setup-token auth is supported in OpenClaw.`);t.log(`OpenClaw prefers Claude CLI reuse when it is available on the host.`);t.log(`Anthropic staff told us this OpenClaw path is allowed again.`)}}async function modelsAuthAddCommand(e,t){const n=await resolveModelsAuthContext({rawAgentId:e.agent});const r=listProvidersWithTokenMethods(n.providers);const i=await select$1({message:`Token provider`,options:[...r.map(e=>({value:e.id,label:e.id,hint:e.docsPath?`Docs: ${e.docsPath}`:void 0})),{value:`custom`,label:`custom (type provider id)`}]});const a=i===`custom`?normalizeProviderId(await text$1({message:`Provider id`,validate:e=>e?.trim()?void 0:`Required`})):i;const o=i===`custom`?null:resolveRequestedLoginProviderOrThrow(r,a);if(o){const e=o.auth.filter(e=>e.kind===`token`);const r=await select$1({message:`Token method`,options:[...e.map(e=>({value:e.id,label:e.label,hint:e.hint})),{value:`paste`,label:`paste token`}]});if(r!==`paste`){const i=createClackPrompter();const a=e.find(e=>e.id===r);if(!a)throw new Error(`Unknown token auth method "${r}". Run ${formatCliCommand(`openclaw models auth login --provider `+o.id)} to choose interactively.`);await runProviderAuthMethod({...n,provider:o,method:a,runtime:t,prompter:i});return}}const s=resolveDefaultTokenProfileId(a);await modelsAuthPasteTokenCommand({provider:a,profileId:(await text$1({message:`Profile id`,initialValue:s,validate:e=>e?.trim()?void 0:`Required`})).trim(),expiresIn:await confirm$1({message:`Does this token expire?`,initialValue:false})?(await text$1({message:`Expires in (duration)`,initialValue:`365d`,validate:e=>{try{parseDurationMs(e??``,{defaultUnit:`d`});return}catch{return`Invalid duration (e.g. 365d, 12h, 30m)`}}})).trim():void 0,agent:e.agent},t)}async function runModelsAuthLoginFlowCore(e){return runModelsAuthLoginFlow(e,()=>true)}async function runModelsAuthLoginFlowForGateway(e){return runModelsAuthLoginFlow(e,t=>e.isRemote===false&&isSharedGatewayForCliLogin(t))}async function runModelsAuthLoginFlow(e,t){const n=e.provider?normalizeManualAuthProvider(e.provider):void 0;let r=await resolveModelsAuthContext({requestedProvider:n,rawAgentId:e.agent,config:e.config,ownerPluginId:e.ownerPluginId});const i=e.prompter;let a=r.providers.filter(e=>e.auth.length>0);let o=n?resolveProviderMatch(a,n):null;const s=!e.ownerPluginId&&n!==void 0&&o===null&&isCliProvider(n,r.config);if(s){r=await resolveModelsAuthContext({rawAgentId:e.agent,config:r.config});a=r.providers.filter(e=>e.auth.length>0)}if(a.length===0)throw new Error(`No provider plugins found. Install one via \`${formatCliCommand(`openclaw plugins install`)}\`.`);if(s)await i.note(`Provider "${n}" uses its own CLI login. Select a provider with an OpenClaw auth flow.`,`Provider auth`);else if(n&&!o)o=resolveRequestedLoginProviderOrThrow(a,n);if(await t(r.config))await showModelsAuthScopeNote(i,r.agentId);const c=o??await i.select({message:`Select a provider`,options:a.map(e=>({value:e.id,label:e.label,hint:e.docsPath?`Docs: ${e.docsPath}`:void 0}))}).then(e=>resolveProviderMatch(a,e));if(!c)throw new Error(`Unknown provider. Run ${formatCliCommand(`openclaw models status`)} or ${formatCliCommand(`openclaw plugins list`)} to see available provider plugins.`);if(e.ownerPluginId&&c.id!==e.provider)throw new Error(`The selected provider login is no longer available.`);const l=e.ownerPluginId?c.auth.find(t=>t.id===e.method):await pickProviderAuthMethod({provider:c,requestedMethod:e.method,prompter:i});if(!l)throw new Error(`Unknown auth method. Run ${formatCliCommand(`openclaw models auth login --provider `+c.id)} without --method to choose interactively.`);const u=await snapshotReloginAuthProfiles({agentDir:r.agentDir,method:l});const d=!e.credentialOnly&&!e.force&&!e.profileId&&!e.setDefault?await tryImportProviderCredential({method:l,providerId:c.id,config:r.config,agentId:r.agentId,runtime:e.runtime,signal:e.signal,beforePersistentEffect:e.beforePersistentEffect}):void 0;if(d&&`unavailableReason`in d)await i.note(d.unavailableReason,`Existing CLI sign-in`);else if(d){await promotePersistedAuthProfile({config:r.config,agentDir:r.agentDir,provider:d.provider,profileId:d.profileId,assertCurrent:e.assertCurrent});const t=await refreshProviderAuthAfterLogin({...e,agentId:r.agentId});if(d.configUpdated)logConfigUpdated(e.runtime);e.runtime.log(`Auth profile: ${d.profileId} (${d.provider}/${d.mode}, imported)`);const n=await allowLoginProviderModels({...e,config:r.config},r.agentId,c.id);return{providerId:c.id,methodId:l.id,authRefresh:t,...n?{modelAccess:n}:{},imported:true,profiles:[{profileId:d.profileId,provider:d.provider,mode:d.mode}]}}const f=Boolean(e.force);if(f){await e.beforePersistentEffect?.();try{if(!await removeProviderAuthProfilesWithLock({cfg:r.config,provider:c.id,agentDir:r.agentDir}))throw new Error(`auth store is busy; close other OpenClaw commands using this state directory and retry`);e.runtime.log(`Removed cached auth profiles for provider "${c.id}" (--force). Running fresh auth flow.`)}catch(e){const t=e instanceof Error?e.message:String(e);throw new Error(`Could not clear cached profiles for "${c.id}" before re-login: ${t}. Re-login was not started because --force must remove cached profiles first.`,{cause:e})}await refreshRunningGatewayAuthState(r.agentId,`logout`,e.runtime)}const{result:p,profiles:m,authRefresh:h,modelAccess:g}=await runProviderAuthMethod({...e,...r,provider:c,method:l,prompter:i,existingProfiles:u,allowMissingReusedProfile:f});if(c.id===`openai`)e.runtime.log(`Tip: Codex-capable models can use native Codex web search. Configure the \`web_search\` tool with \`${formatCliCommand(`openclaw configure --section web`)}\`. Docs: https://docs.openclaw.ai/tools/web`);return{providerId:c.id,methodId:l.id,authRefresh:h,...p.defaultModel?{defaultModel:p.defaultModel}:{},...g?{modelAccess:g}:{},profiles:m.map(e=>({profileId:e.profileId,provider:e.credential.provider,mode:e.credential.type}))}}async function modelsAuthLoginCommand(e,t){if(!process.stdin.isTTY)throw new Error(`models auth login requires an interactive TTY. In automation, use ${formatCliCommand(`openclaw models auth paste-token --provider <provider>`)} when token auth is available.`);const n=await runModelsAuthLoginFlow({...e,runtime:t,prompter:createClackPrompter(process.stdout,e.signal)},isSharedGatewayForCliLogin);if(e.refreshAfterLogin&&n.authRefresh!==`refreshed`)throw new ProviderCredentialsSavedError(`Sign-in was saved, but this session could not refresh its credentials. Restart the local TUI and retry your message.`)}export{modelsAuthSetupTokenCommand as a,runModelsAuthLoginFlowForGateway as c,modelsAuthPasteTokenCommand as i,modelsAuthLoginCommand as n,resolveRequestedLoginProviderOrThrow as o,modelsAuthPasteApiKeyCommand as r,runModelsAuthLoginFlowCore as s,modelsAuthAddCommand as t};