UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

713 lines (712 loc) • 28.6 kB
import { l as normalizeOptionalString, p as normalizeStringifiedOptionalString } from "./string-coerce-CCIiB4H7.mjs"; import { A as resolveExpiresAtMsFromDurationMs } from "./number-coercion-D6u-4YD8.mjs"; import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs"; import "./src-H3RMXyFL.mjs"; import { t as expectDefined } from "./expect-DDakjvvQ.mjs"; import { t as ExitError } from "./runtime-B-SLYP-m.mjs"; import "./utils-C8YECn2Q.mjs"; import "./model-ref-shared-DqE2RqZv.mjs"; import { t as formatCliCommand } from "./command-format-CqdwUgPk.mjs"; import { r as normalizeProviderId } from "./provider-id-b5XGSf9C.mjs"; import { f as resolveAgentWorkspaceDir } from "./agent-scope-config-DmXgFGKP.mjs"; import { n as normalizeSecretInput } from "./normalize-secret-input-Cxkx67Fv.mjs"; import { r as normalizeAgentModelRefForConfig } from "./model-input-DrM4DWHG.mjs"; import { i as resolveProviderIdForAuth } from "./provider-auth-aliases-CgGlzANu.mjs"; import "./agent-scope-BwB8YH6y.mjs"; import { t as parseDurationMs } from "./parse-duration-D6UJm52I.mjs"; import { i as resolvePluginSetupRegistry, r as resolvePluginSetupProviderCore } from "./setup-registry-CgyZCdrJ.mjs"; import { t as resolveSharedMainAuthAgentDir } from "./shared-main-dir-C2ynhf4g.mjs"; import { B as listRuntimeLocalProfileIds } from "./runtime-snapshots-1lyYKb7Y.mjs"; import { t as isCliProvider } from "./model-selection-cli-CkH04Wst.mjs"; import { g as loadAuthProfileStoreWithoutExternalProfilesAsync } from "./store-runtime-dW0pXLJI.mjs"; import { t as runProviderPluginAuthMethodUnpersisted } from "./provider-auth-method-Bgbv8Sbe.mjs"; import { r as resolvePluginProvidersCore } from "./providers.runtime-6wA04_U8.mjs"; import { a as removeProviderAuthProfilesWithLock, d as upsertAuthProfileWithLockOrThrow, r as promoteAuthProfileInOrder } from "./profiles-DbLHYG1P.mjs"; import { n as ProviderCredentialsSavedError, t as ProviderAuthConfigApplyError } from "./provider-auth-result-Cm5Twlfj.mjs"; import "./auth-profiles-VRLhewIH.mjs"; import { t as applyPrimaryModel } from "./provider-model-primary-C2E-I43s.mjs"; import { a as repairModelSelectionRuntimePlugins } from "./runtime-plugin-install-CPmn8nK7.mjs"; import { i as resolveProviderMatch, o as restorePriorAgentsDefaultsModelUnlessOptIn, r as pickAuthMethod, t as applyProviderAuthConfigPatchWithNormalization } from "./provider-auth-choice-helpers-BHHQcecj.mjs"; import { t as applyAuthProfileConfig } from "./provider-auth-helpers-ByDXB7Po.mjs"; import { n as persistProviderAuthProfilesAfterLogin } from "./provider-auth-persistence-qfBTNlSU.mjs"; import { t as createClackPrompter } from "./clack-prompter-oqVcatgQ.mjs"; import { r as logConfigUpdated } from "./logging-D0RirHBi.mjs"; import { i as loadValidConfigSnapshotOrThrow, l as resolveModelsTargetAgent, u as updateConfig } from "./shared-jZuoMzdG.mjs"; import { n as validateAnthropicSetupToken } from "./provider-auth-token-CEoV5Js5.mjs"; import { c as select$2, l as text$2, r as confirm$2, s as password$2 } from "./configure.shared-BGU6WxUW.mjs"; import { t as withPluginMigrationProviders } from "./migration-provider-runtime-DwgVXsrn.mjs"; import { t as buildMigrationContext } from "./context-BwDZNbEs.mjs"; import { t as applyMigrationItemSelection } from "./item-selection-CrW1-Zuf.mjs"; import { n as refreshRunningGatewayAuthState, r as throwProviderAuthLoginError, t as refreshProviderAuthAfterLogin } from "./auth-refresh-CoYY69-l.mjs"; import { a as validateOpenAICodexApiKeyInput, i as resolveDefaultTokenProfileId, n as normalizeManualAuthProvider, r as readPipedStdin, t as looksLikeOpenAIApiKey } from "./auth-manual-input-DeJ4s3kg.mjs"; import { t as saveModelProviderApiKey } from "./auth-api-key-L7Xuyi5K.mjs"; import { a as withoutProviderModelPolicy, i as prepareProviderModelAccess, n as applyProviderLoginDefaultModel, r as completeProviderModelAccess } from "./auth-model-policy-CtjtbGzO.mjs"; import { n as writeProviderAuthConfig, t as createProviderAuthConfigPatch } from "./provider-auth-config-CcmAiHm8.mjs"; import path from "node:path"; import { cancel } from "@clack/prompts"; //#region src/commands/models/auth-credential-import.ts /** Imports only the credential item declared by the selected login method. */ 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 }; }); } //#endregion //#region 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."); } //#endregion //#region src/commands/models/auth-relogin-identity.ts async function snapshotReloginAuthProfiles(e) { if (!e.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.matchesPersonalAccount; if (!n || !e.existingProfiles || e.profiles.length !== 1) return { profiles: e.profiles }; const r = expectDefined(e.profiles[0], "auth profile"); const i = []; for (const [t, a] of Object.entries(e.existingProfiles)) try { if (n(r.credential, a)) i.push(t); } catch { return { profiles: e.profiles }; } if (i.length !== 1) return { profiles: e.profiles }; const a = expectDefined(i[0], "matched auth profile id"); return { profiles: [{ ...r, profileId: a }], validateCurrentCredential: (t, i) => { let o = false; if (i) try { o = n(r.credential, i); } catch { o = false; } if (t !== a || (i ? !o : !e.allowMissingReusedProfile)) throw new Error("The existing auth profile identity changed during sign-in. Start the sign-in again."); } }; } //#endregion //#region src/commands/models/auth.ts function resolveManualTokenExpiryMs(e) { const t = normalizeStringifiedOptionalString(e); if (!t) return; const n = parseDurationMs(t, { defaultUnit: "d" }); const r = resolveExpiresAtMsFromDurationMs(n); if (r === void 0) throw new Error("Invalid expiry duration: resulting token expiry is outside Date range."); return r; } 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 = prepareProviderModelAccess({ config: e.config, agentId: e.agentId, provider: e.provider.id, providerLabel: e.provider.label }); const n = await loadAuthProfileStoreWithoutExternalProfilesAsync(e.agentDir); const r = Object.entries(n.profiles).filter(([t, n]) => n.provider === e.provider.id && (!e.profileId || t === e.profileId)).map(([e, t]) => ({ profileId: e, credential: t })); const i = await runProviderPluginAuthMethodUnpersisted({ method: e.method, config: e.config, existingProfiles: r, 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 a = e.credentialOnly ? { profiles: i.profiles, notes: i.notes, ...i.configPatch ? { configPatch: { ...i.configPatch.models?.providers ? { models: { providers: i.configPatch.models.providers } } : {}, ...i.configPatch.plugins ? { plugins: i.configPatch.plugins } : {} } } : {} } : i; const o = resolveReloginProfileIdentity({ profiles: a.profiles, requestedProfileId: e.profileId, existingProfiles: e.existingProfiles, matchesPersonalAccount: e.method.matchesPersonalAccount, allowMissingReusedProfile: e.allowMissingReusedProfile }); const s = o.profiles; const c = { ...e, result: a, profiles: s, env: e.env ?? process.env, validateCurrentCredential: o.validateCurrentCredential }; let l; const u = c.result.defaultModel ? normalizeAgentModelRefForConfig(c.result.defaultModel) : void 0; const d = []; const f = applyProviderAuthConfigPatchWithNormalization(c.config, {}); const p = c.result.configPatch ? createProviderAuthConfigPatch(f, restorePriorAgentsDefaultsModelUnlessOptIn({ cfg: applyProviderAuthConfigPatchWithNormalization(f, s.length > 0 ? withoutProviderModelPolicy(c.result.configPatch, f) : c.result.configPatch, { replaceDefaultModels: c.result.replaceDefaultModels }), priorAgentsDefaultsModel: f.agents?.defaults?.model, setDefault: c.setDefault })) : void 0; const m = isRecord(p) && Object.keys(p).length > 0 || Boolean(c.setDefault && u); if (s.length > 0 || m) await c.beforePersistentEffect?.(); try { for (const e of s) { const t = await persistProviderAuthProfilesAfterLogin({ profiles: [e], beforeWrite: c.assertCurrent, validateCurrentCredential: c.validateCurrentCredential, config: c.config, env: c.env, agentDir: c.agentDir, ...c.env?.OPENCLAW_STATE_DIR ? { stateDir: c.env.OPENCLAW_STATE_DIR } : {} }); const n = expectDefined(t[0], "persisted auth profile"); d.push(n); c.assertCurrent?.(); await promotePersistedAuthProfile({ config: c.config, agentDir: c.agentDir, provider: n.credential.provider, profileId: n.profileId, assertCurrent: c.assertCurrent }); } if (m) { const e = await writeProviderAuthConfig({ config: c.config, configSnapshot: c.configSnapshot, configPatch: p, credentialsSaved: d.length > 0, beforeCommit: c.assertCurrent, writeOptions: { assertCurrent: c.assertCurrent }, finalizeConfig: (e, t) => { const n = t.agents?.defaults?.model; const r = restorePriorAgentsDefaultsModelUnlessOptIn({ cfg: e, priorAgentsDefaultsModel: n, setDefault: c.setDefault }); if (c.setDefault && u) return s.length > 0 ? applyProviderLoginDefaultModel(r, u) : applyPrimaryModel(r, u); return r; } }); if (u) { const t = await repairModelSelectionRuntimePlugins({ cfg: e, model: u }); for (const e of t) c.runtime.error?.(e); } logConfigUpdated(c.runtime); } l = await refreshProviderAuthAfterLogin(c); for (const e of d) c.runtime.log(`Auth profile: ${e.profileId} (${e.credential.provider}/${e.credential.type})`); if (u) c.runtime.log(c.setDefault ? `Default model set to ${u}` : `Default model available: ${u} (current default unchanged; run ${formatCliCommand(`openclaw models set ${u}`)} to apply)`); if (c.result.notes && c.result.notes.length > 0) await c.prompter.note(c.result.notes.join("\n"), "Provider notes"); } catch (e) { return throwProviderAuthLoginError(e, c, d.length > 0); } if (d.length > 0) await completeLoginModelAccess(e, t); return { result: a, profiles: d, authRefresh: l }; } function completeLoginModelAccess(e, t) { return completeProviderModelAccess({ prepared: t, prompter: e.prompter, onRequested: e.onModelAccessRequested, runtime: e.runtime, assertCurrent: () => { e.signal?.throwIfAborted(); e.assertCurrent?.(); } }).catch((e) => { throw new ProviderAuthConfigApplyError(e); }); } 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; 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) => applyAuthProfileConfig(e, { profileId: s, provider: o, mode: "token" })); } else ({profileId: l, warning: u} = await saveModelProviderApiKey({ config: r, provider: o, apiKey: c, 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 (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, e.isRemote === false); } 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 (t) await i.note([ "Scope: System / agent", `Agent: ${r.agentId}`, "Location: the machine running OpenClaw", `For personal model accounts on a Gateway, run ${formatCliCommand("openclaw models accounts login --help")}.` ].join("\n"), "Provider sign-in"); 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 = prepareProviderModelAccess({ config: r.config, agentId: r.agentId, provider: c.id, providerLabel: c.label }); const d = await snapshotReloginAuthProfiles({ agentDir: r.agentDir, matchesPersonalAccount: l.matchesPersonalAccount }); const f = !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 (f && "unavailableReason" in f) await i.note(f.unavailableReason, "Existing CLI sign-in"); else if (f) { await promotePersistedAuthProfile({ config: r.config, agentDir: r.agentDir, provider: f.provider, profileId: f.profileId, assertCurrent: e.assertCurrent }); const t = await refreshProviderAuthAfterLogin({ ...e, agentId: r.agentId }); if (f.configUpdated) logConfigUpdated(e.runtime); e.runtime.log(`Auth profile: ${f.profileId} (${f.provider}/${f.mode}, imported)`); await completeLoginModelAccess(e, u); return { providerId: c.id, methodId: l.id, authRefresh: t, imported: true, profiles: [{ profileId: f.profileId, provider: f.provider, mode: f.mode }] }; } const p = Boolean(e.force); if (p) { 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: m, profiles: h, authRefresh: g } = await runProviderAuthMethod({ ...e, ...r, provider: c, method: l, prompter: i, existingProfiles: d, allowMissingReusedProfile: p }); 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: g, ...m.defaultModel ? { defaultModel: m.defaultModel } : {}, profiles: h.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.`); await runModelsAuthLoginFlowCore({ ...e, runtime: t, prompter: createClackPrompter() }); } //#endregion 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 };