UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

469 lines (468 loc) • 19.2 kB
import { t as ExitError } from "./runtime-B-SLYP-m.mjs"; import { h as resolveDefaultSecretProviderAlias } from "./ref-contract-b8L-9DrQ.mjs"; import { o as hasConfiguredSecretInput } from "./types.secrets-BmNLLnHp.mjs"; import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs"; import { t as formatCliCommand } from "./command-format-CqdwUgPk.mjs"; import { t as runBestEffortCleanup } from "./non-fatal-cleanup-CRJjL6BT.mjs"; import { s as resolveAgentModelPrimaryValue } from "./model-input-DrM4DWHG.mjs"; import { i as resolveUtilityModelSeparationError, n as materializeUtilityModelSeparation } from "./utility-model-separation-migration-BwGu2RZI.mjs"; import { r as enablePluginWithCapabilityConsent } from "./enable-BY2SJL8Z.mjs"; import { t as quoteCliArg } from "./quote-cli-arg-J7A9UE6m.mjs"; import { n as resolveManifestDeprecatedProviderAuthChoice, r as resolveManifestProviderAuthChoice } from "./provider-auth-choices-BfC_56hU.mjs"; import { n as buildProviderPluginMethodChoice, r as parseProviderPluginMethodChoice, t as PROVIDER_PLUGIN_CHOICE_PREFIX } from "./provider-plugin-choice-ByK6aXLG.mjs"; import { n as resolveProviderInstallCatalogEntries, t as resolveDeprecatedProviderInstallCatalogEntry } from "./provider-install-catalog-DH6EFiCw.mjs"; import { o as prepareAgentModelDefaults, s as projectAgentModelDefaults } from "./onboard-agent-target-D7VNwjZB.mjs"; import { t as createNonInteractiveLoggingPrompter } from "./non-interactive-prompter-DfC9Cfxv.mjs"; import { i as ensureModelSelectionRuntimePlugins, t as CODEX_RUNTIME_PLUGIN_ID } from "./runtime-plugin-install-CPmn8nK7.mjs"; import { r as formatAuthChoiceChoicesForCli } from "./auth-choice-options-BjS5hVuU.mjs"; import { t as resolveLegacyOnboardAuthChoice } from "./auth-choice-legacy-B9SvrCvt.mjs"; import { t as normalizeApiKeyTokenProviderAuthChoice } from "./auth-choice.apply.api-providers-C63Pjo2J.mjs"; import { t as resolvePreferredProviderForAuthChoice } from "./provider-auth-choice-preference-aJfNppcY.mjs"; import { h as resolveNonInteractiveCustomApiModelIds, l as parseNonInteractiveCustomApiFlags, m as resolveCustomProviderNoAuth, n as applyCustomApiConfig, p as resolveCustomProviderId, t as CustomApiError } from "./onboard-custom-config-Dmrcrtsp.mjs"; import { t as rejectOnboardingOption } from "./onboard-options-CrkNjPND.mjs"; import { t as resolveNonInteractiveApiKey } from "./api-keys-6HaBIv-a.mjs"; import path from "node:path"; import fs from "node:fs/promises"; import os from "node:os"; import { isDeepStrictEqual } from "node:util"; //#region src/commands/onboard-non-interactive/local/auth-choice.plugin-providers.ts /** Applies a plugin-defined auth choice, or returns undefined when it is not plugin-backed. */ async function applyNonInteractivePluginProviderChoice(e) { const { agentDir: t, workspaceDir: n } = e.target; const reject = (t) => { rejectOnboardingOption(e.opts, e.runtime, t); return null; }; let r = e.nextConfig; const i = parseProviderPluginMethodChoice(e.authChoice)?.providerId; if (i === "") return reject(`Auth choice ${JSON.stringify(e.authChoice)} is missing a provider id. Use "${PROVIDER_PLUGIN_CHOICE_PREFIX}<provider-id>".`); const a = i || await resolvePreferredProviderForAuthChoice({ choice: e.authChoice, config: r, workspaceDir: n, includeUntrustedWorkspacePlugins: false }); const o = resolveManifestProviderAuthChoice(e.authChoice, { config: r, workspaceDir: n, includeUntrustedWorkspacePlugins: false }); if (o) { if (o.modelTarget === "utility") { const t = resolveUtilityModelSeparationError(e.baseConfig); if (t) return reject(t); } const t = await enablePluginWithCapabilityConsent(r, o.pluginId, { workspaceDir: n }); if (!t.enabled) return reject(t.reason ?? "Provider plugin could not be enabled."); r = t.config; } const { resolveOwningPluginIdsForProviderRef: s, resolveProviderPluginChoice: c, resolvePluginProviders: l } = (await import("./auth-choice.plugin-providers.runtime.js")).authChoicePluginProvidersRuntime; const u = a ? s({ provider: a, config: r, workspaceDir: n }) : void 0; const resolveManifestMethodChoice = (e, t) => e.pluginId ? resolveManifestProviderAuthChoice(buildProviderPluginMethodChoice(e.id, t.id), { config: r, workspaceDir: n, pluginId: e.pluginId, includeUntrustedWorkspacePlugins: false }) : void 0; let d = c({ providers: l({ config: r, workspaceDir: n, onlyPluginIds: u, ...a ? { providerRefs: [a] } : {}, mode: "setup", includeUntrustedWorkspacePlugins: false }), choice: e.authChoice, manifestChoice: o, resolveManifestMethodChoice }); if (!d) { if (i) return reject([`Auth choice "${e.authChoice}" was not matched to a trusted provider plugin.`, "If this provider comes from a workspace plugin, trust/allow it first and retry."].join("\n")); if (!o && resolveManifestProviderAuthChoice(e.authChoice, { config: r, workspaceDir: n, includeUntrustedWorkspacePlugins: true })) return reject([`Auth choice "${e.authChoice}" matched a provider plugin that is not trusted or enabled for setup.`, "If this provider comes from a workspace plugin, trust/allow it first and retry."].join("\n")); const t = e.authChoice.trim(); if (!t) return; const a = resolveProviderInstallCatalogEntries({ config: r, workspaceDir: n, includeUntrustedWorkspacePlugins: false }); const s = a.find((e) => e.deprecatedChoiceIds?.includes(t)); if (s) return reject(`${JSON.stringify(e.authChoice)} is no longer supported. Use --auth-choice ${JSON.stringify(s.choiceId)} instead.`); const u = a.find((e) => e.choiceId === t); if (!u) return; if (u.modelTarget === "utility") { const t = resolveUtilityModelSeparationError(e.baseConfig); if (t) return reject(t); } const { ensureOnboardingPluginInstalled: f } = await import("./onboarding-plugin-install-lud95zdi.mjs"); const p = await f({ cfg: r, entry: { pluginId: u.pluginId, label: u.label, install: u.install, ...u.origin === "bundled" ? { trustedSourceLinkedOfficialInstall: true } : {} }, prompter: createNonInteractiveLoggingPrompter(e.runtime, (e) => `Non-interactive setup cannot prompt for plugin install: ${e}`), runtime: e.runtime, workspaceDir: n, promptInstall: false }); if (!p.installed) return reject(`Unable to install the ${u.label} plugin for non-interactive setup.`); r = p.cfg; d = c({ providers: l({ config: r, workspaceDir: n, onlyPluginIds: [u.pluginId], providerRefs: [u.providerId], mode: "setup", includeUntrustedWorkspacePlugins: false }), choice: e.authChoice, resolveManifestMethodChoice, manifestChoice: u }); if (!d) return reject(`Installed plugin "${u.label}" did not expose auth choice "${e.authChoice}".`); } if (d.wizard?.modelTarget === "utility") { const t = resolveUtilityModelSeparationError(e.baseConfig); if (t) return reject(t); } const f = await enablePluginWithCapabilityConsent(r, d.provider.pluginId ?? d.provider.id, { workspaceDir: n }); if (!f.enabled) return reject(`${d.provider.label} plugin is disabled (${f.reason ?? "blocked"}).`); const p = d.method; const m = d.wizard?.modelTarget; if (!p.runNonInteractive) return reject([`Auth choice "${e.authChoice}" requires interactive mode.`, `The ${d.provider.label} provider plugin does not implement non-interactive setup.`].join("\n")); const h = f.config.agents?.ownership === "explicit"; const g = h ? prepareAgentModelDefaults(f.config, e.target) : f.config; const projectProviderResult = (t) => { const n = h ? projectAgentModelDefaults(f.config, e.target, t) : t; return m === "utility" ? materializeUtilityModelSeparation(n, e.baseConfig).config : n; }; const _ = p.runNonInteractive; const v = { authChoice: e.authChoice, config: g, baseConfig: e.baseConfig, opts: e.opts, runtime: e.runtime, agentDir: t, workspaceDir: n, resolveApiKey: e.resolveApiKey, toApiKeyCredential: e.toApiKeyCredential }; const { isSetupCredentialReplacement: y, saveSetupCredential: b, selectSetupCredential: x } = await import("./setup-inference-credentials-B3fueqUf.mjs"); let S; if (await y({ provider: d.provider.id, baseConfig: e.baseConfig, agentDir: t })) { const [{ withAuthProfileStoreAgentDir: n, clearRuntimeAuthProfileStoreSnapshot: r }, { loadAuthProfileStoreWithoutExternalProfilesAsync: i, saveAuthProfileStore: a }, { loadPersistedAuthProfileStore: s }, { closeAuthProfileReadPool: c }, { closeOpenClawAgentDatabasesAsync: l }, { closeOpenClawStateDatabaseByPathAsync: u }, { resolveOpenClawStateSqlitePath: f }, { splitTrailingAuthProfile: h }, { resolveSetupModel: y }, { prepareCustomSetupCredentials: C }] = await Promise.all([ import("./store-CJvsKEuH.mjs"), import("./store-runtime-pgVSsSj7.mjs"), import("./persisted-Cl8yEkoi.mjs"), import("./sqlite-zfPAUB0i.mjs"), import("./openclaw-agent-db-UyfPGzTC.mjs"), import("./openclaw-state-db-Ds4jcYSd.mjs"), import("./openclaw-state-db.paths-DiM3pkKt.mjs"), import("./model-ref-profile-BwMeKozM.mjs"), import("./setup-inference-core-YRtsH50Y.mjs"), import("./setup-inference-custom-CSeDcBmt.mjs") ]); const w = await i(t); const T = { version: w.version, ...w.order ? { order: structuredClone(w.order) } : {}, profiles: Object.fromEntries(Object.entries(w.profiles).filter(([, e]) => e.type !== "oauth" && !e.setup?.replacement)) }; const E = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-setup-credential-")); const D = path.join(E, "agents", "setup", "agent"); let O; try { await fs.mkdir(D, { recursive: true }); S = await n(D, E, async () => { a(T, D, { syncExternalCli: false }); return await _({ ...v, agentDir: D, runtime: { ...e.runtime, exit: (e) => { throw new Error(`Provider setup exited with code ${e}; see its error above.`); } } }); }); if (!S) return null; const r = C({ config: structuredClone(S), providerId: d.provider.id }); const i = Object.entries(s(D)?.profiles ?? {}).filter(([e, t]) => !isDeepStrictEqual(t, T.profiles[e])).map(([e, t]) => ({ profileId: e, credential: t })); if (!isDeepStrictEqual(S.models?.providers?.[d.provider.id]?.apiKey, g.models?.providers?.[d.provider.id]?.apiKey)) i.push(...r.profiles); if (i.length > 0) { const n = m === "utility" ? resolveAgentModelPrimaryValue(S.agents?.defaults?.utilityModel) : resolveAgentModelPrimaryValue(S.agents?.defaults?.model); const a = y({ label: d.provider.label, providerId: d.provider.id, defaultModel: n && x(i, n, r.config) ? h(n).model : p.starterModel }); if (typeof a !== "string") throw new Error(a.error); const s = x(i, a, r.config); if (!s) throw new Error("Provider setup did not save a replacement credential. Your connection is unchanged."); O = (await b({ profile: s, config: projectProviderResult(r.config), baseConfig: e.baseConfig, agentDir: t, modelRef: a, authChoice: o?.choiceId ?? d.wizard?.choiceId, pluginId: d.provider.pluginId })).profile.profileId; } } finally { r(D); c({ kind: "root", rootPath: E }); await l(E); await u(f({ ...process.env, OPENCLAW_STATE_DIR: E })); await runBestEffortCleanup({ cleanup: () => fs.rm(E, { recursive: true, force: true, maxRetries: 3, retryDelay: 200 }), onError: (t) => e.runtime.error(`Warning: Could not remove setup credential staging directory ${E}: ${formatErrorMessage(t)}. Remove it manually if it persists.`) }); } if (O) return reject(`Replacement credential saved but inactive. Your connection is unchanged. Test and activate it with:\n${formatCliCommand(`openclaw models auth activate ${quoteCliArg(O)} --agent ${quoteCliArg(e.target.agentId)}`)}`); } else S = await _(v); if (!S) return S; const C = m === "utility" ? resolveAgentModelPrimaryValue(S.agents?.defaults?.utilityModel) : resolveAgentModelPrimaryValue(S.agents?.defaults?.model); if (m === "utility") { if (!C) return reject("This provider did not return a utility model for setup."); const { model: e, ...t } = S.agents?.defaults ?? {}; const n = g.agents?.defaults?.model; S = { ...S, agents: { ...S.agents, defaults: { ...t, ...n !== void 0 ? { model: n } : {} } } }; } if (!C) return projectProviderResult(S); const w = await ensureModelSelectionRuntimePlugins({ cfg: S, model: C, prompter: createNonInteractiveLoggingPrompter(e.runtime, (e) => e), runtime: e.runtime, workspaceDir: n, output: "silent" }); if (!w.ok) return reject(w.message); if (w.codexInstalled) { const { offerPostInstallMigrations: t } = await import("./setup.post-install-migration-DTYA2rl9.mjs"); await t({ config: w.cfg, runtime: e.runtime, installedPluginIds: [CODEX_RUNTIME_PLUGIN_ID], nonInteractive: true }); } return projectProviderResult(w.cfg); } //#endregion //#region src/commands/onboard-non-interactive/local/auth-choice.ts /** Applies a local non-interactive auth choice to the pending OpenClaw config. */ async function applyNonInteractiveAuthChoice(e) { const { opts: t, runtime: n, baseConfig: r } = e; const reject = (e) => { rejectOnboardingOption(t, n, e); return null; }; let i = normalizeApiKeyTokenProviderAuthChoice({ authChoice: e.authChoice, tokenProvider: t.tokenProvider, config: e.nextConfig, workspaceDir: e.target.workspaceDir, env: process.env }); const a = e.nextConfig; const toStoredSecretInput = (e) => { const { resolved: n } = e; if (t.secretInputMode !== "ref") return n.key; if (n.source !== "env" || !n.envVarName) { const t = e.envVarName ? `Set ${e.envVarName} in env and retry` : "Set the provider API key env var and retry"; return reject([`--secret-input-mode ref requires an explicit environment variable for provider "${e.provider}".`, `${t}, or use --secret-input-mode plaintext.`].join("\n")); } return { source: "env", provider: resolveDefaultSecretProviderAlias(r, "env", { preferFirstProviderForSource: true }), id: n.envVarName }; }; const resolveApiKey = (r) => resolveNonInteractiveApiKey({ ...r, cfg: a, runtime: n, agentDir: e.target.agentDir, workspaceDir: e.target.workspaceDir, secretInputMode: t.secretInputMode, json: t.json }); const toApiKeyCredential = (e) => { const t = toStoredSecretInput({ resolved: e.resolved, provider: e.provider }); if (!t) return null; return { type: "api_key", provider: e.provider, ...typeof t === "string" ? { key: t } : { keyRef: t }, ...e.email ? { email: e.email } : {}, ...e.metadata ? { metadata: e.metadata } : {} }; }; const o = { config: a, workspaceDir: e.target.workspaceDir, env: process.env }; const s = resolveLegacyOnboardAuthChoice(i, o); if (s.deprecated) { n.log(s.deprecated.message); i = s.authChoice; } const c = resolveManifestDeprecatedProviderAuthChoice(i, o); const l = c ? void 0 : resolveDeprecatedProviderInstallCatalogEntry(i, { ...o, includeUntrustedWorkspacePlugins: false }); const u = c?.choiceId ?? l?.choiceId; if (u) return reject(`${JSON.stringify(i)} is no longer supported. Use --auth-choice ${JSON.stringify(u)} instead.`); const d = formatAuthChoiceChoicesForCli(o).split("|"); if (!d.includes(i) && !i.startsWith("provider-plugin:")) return reject(`Unknown --auth-choice ${JSON.stringify(i)}. Valid choices: ${d.join(", ")}.`); const f = await applyNonInteractivePluginProviderChoice({ nextConfig: a, authChoice: i, opts: t, runtime: n, baseConfig: r, target: e.target, resolveApiKey, toApiKeyCredential }); if (f !== void 0) return f; if (i === "setup-token" || i === "token") return reject([`Auth choice "${e.authChoice}" was not matched to a provider setup flow.`, "For Anthropic legacy token auth, use \"--auth-choice setup-token --token-provider anthropic --token <token>\" or pass \"--auth-choice token --token-provider anthropic\"."].join("\n")); if (i === "custom-api-key") try { const i = parseNonInteractiveCustomApiFlags({ baseUrl: t.customBaseUrl, modelId: t.customModelId, compatibility: t.customCompatibility, apiKey: t.customApiKey, noAuth: t.customNoAuth, providerId: t.customProviderId, supportsImageInput: t.customImageInput }); const o = resolveCustomProviderId({ config: a, baseUrl: i.baseUrl, providerId: i.providerId }); const s = resolveCustomProviderNoAuth({ ...i, config: a, providerId: o.providerId, apiKey: i.apiKey ?? process.env.CUSTOM_API_KEY?.trim() }); const c = s ? void 0 : await resolveApiKey({ provider: o.providerId, flagValue: i.apiKey, flagName: "--custom-api-key", envVar: "CUSTOM_API_KEY", envVarName: "CUSTOM_API_KEY", allowProfile: !t.customModelIds && !hasConfiguredSecretInput(a.models?.providers?.[o.providerId]?.apiKey), required: false }); let l; if (c && (t.secretInputMode !== "ref" || c.source !== "profile")) { const e = toStoredSecretInput({ resolved: c, provider: o.providerId, envVarName: "CUSTOM_API_KEY" }); if (!e) return null; l = e; } const u = await resolveNonInteractiveCustomApiModelIds({ ...i, config: a, noAuth: s, apiKey: c?.key, agentDir: e.target.agentDir, modelIds: t.customModelIds }); const d = applyCustomApiConfig({ config: a, ...i, modelId: u[0] ?? "", modelIds: i.modelId ? void 0 : u, preserveExistingModelMetadata: !i.modelId, apiKey: l, target: e.target }); if (o.providerIdRenamedFrom) n.log(`Custom provider ID "${o.providerIdRenamedFrom}" already exists for a different base URL. Using "${d.providerId}".`); if (l !== void 0 && c?.source !== "profile") { const { isSetupCredentialReplacement: t, saveSetupCredential: n } = await import("./setup-inference-credentials-B3fueqUf.mjs"); if (await t({ provider: d.providerId, baseConfig: r, agentDir: e.target.agentDir })) { const { prepareCustomSetupCredentials: t } = await import("./setup-inference-custom-CSeDcBmt.mjs"); const i = t(d); const a = await n({ profile: i.profiles[0], config: i.config, baseConfig: r, agentDir: e.target.agentDir, modelRef: `${d.providerId}/${d.modelId}` }); return reject(`Replacement credential saved but inactive. Your connection is unchanged. Test and activate it with:\n${formatCliCommand(`openclaw models auth activate ${quoteCliArg(a.profile.profileId)} --agent ${quoteCliArg(e.target.agentId)}`)}`); } } return d.config; } catch (e) { if (e instanceof ExitError) throw e; return reject(e instanceof CustomApiError && (e.code === "missing_required" || e.code === "invalid_compatibility") ? e.message : `Invalid custom provider config: ${e instanceof CustomApiError ? e.message : formatErrorMessage(e)}`); } if (i === "chutes" || i === "minimax-global-oauth" || i === "minimax-cn-oauth") return reject("OAuth requires interactive mode."); return a; } //#endregion export { applyNonInteractiveAuthChoice };