UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

324 lines (323 loc) • 13.6 kB
import { l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs"; import { S as parseDateStringTimestampMs } from "./number-coercion-D6u-4YD8.mjs"; import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs"; import { n as sha256Hex } from "./node-crypto-B6yuTjmm.mjs"; import { s as resolveAgentModelPrimaryValue } from "./model-input-DrM4DWHG.mjs"; import { g as loadAuthProfileStoreWithoutExternalProfilesAsync } from "./store-runtime-dW0pXLJI.mjs"; import { a as resolveOpenAICodexImportProfileName, i as resolveOpenAICodexAuthIdentity, r as resolveOpenAICodexAccessTokenExpiry, t as buildOpenAICodexCredentialExtra } from "./provider-openai-chatgpt-auth-Lx-WyDpB.mjs"; import "./string-coerce-runtime-BwAZZDf5.mjs"; import "./number-runtime-W4chuk8B.mjs"; import { r as AuthStorage } from "./sessions-G45sHB31.mjs"; import { r as applyAgentDefaultModelPrimary } from "./provider-onboard-Di5Hihl4.mjs"; import "./agent-runtime-DA4W1L0G.mjs"; import { d as markMigrationItemSkipped, l as markMigrationItemConflict, o as createMigrationItem, s as createMigrationManualItem, u as markMigrationItemError } from "./migration-C73lp9ea.mjs"; import "./provider-auth-D_oAZ3fr.mjs"; import { n as updateAuthProfileStoreWithLockCompat } from "./provider-auth-write-compat-a9sIepqY.mjs"; import { t as buildOauthProviderAuthResult } from "./provider-auth-result-Br3rDHr2.mjs"; import "./agent-sessions-C-CdVZCo.mjs"; import { n as hasAuthProfileConfigConflict, r as hasCurrentAuthProfileConfigConflict, t as applyAuthProfileConfigWithConflictCheck } from "./auth-config-36OX0rZe.mjs"; import { a as readJsonObject } from "./helpers-BrAeOFdd.mjs"; import { i as HERMES_REASON_CONFIG_RUNTIME_UNAVAILABLE, l as HERMES_REASON_SECRET_NO_LONGER_PRESENT, n as HERMES_REASON_AUTH_PROFILE_EXISTS, o as HERMES_REASON_INCLUDE_SECRETS, r as HERMES_REASON_AUTH_PROFILE_WRITE_FAILED, s as HERMES_REASON_MISSING_SECRET_METADATA } from "./items-CtQPQmTr.mjs"; //#region extensions/migrate-hermes/auth.ts const HERMES_OPENAI_CODEX_SOURCE_PROVIDER_ID = "openai-codex"; const HERMES_REAUTH_PROVIDER_MAPPINGS = [ { sourceProvider: "anthropic", targetProvider: "anthropic" }, { sourceProvider: "nous", targetProvider: "nous" }, { sourceProvider: "qwen-oauth", targetProvider: "qwen" }, { sourceProvider: "qwen-cli", targetProvider: "qwen" }, { sourceProvider: "qwen-portal", targetProvider: "qwen" }, { sourceProvider: "minimax-oauth", targetProvider: "minimax-portal" }, { sourceProvider: "xai-oauth", targetProvider: "xai" } ]; const HERMES_REAUTH_SOURCE_PROVIDERS = new Set(HERMES_REAUTH_PROVIDER_MAPPINGS.map((e) => e.sourceProvider)); async function readHermesCodexAuthCandidates(e) { if (!e) return []; const t = await readJsonObject(e); const n = isRecord(t.providers) ? t.providers : {}; const r = isRecord(n[HERMES_OPENAI_CODEX_SOURCE_PROVIDER_ID]) ? n[HERMES_OPENAI_CODEX_SOURCE_PROVIDER_ID] : void 0; const i = isRecord(t.credential_pool) ? t.credential_pool : {}; const a = Array.isArray(i[HERMES_OPENAI_CODEX_SOURCE_PROVIDER_ID]) ? i[HERMES_OPENAI_CODEX_SOURCE_PROVIDER_ID] : []; const o = []; for (const [t, n] of [["provider", r?.tokens], ...a.map((e) => ["pool", e])]) { if (!isRecord(n)) continue; const i = normalizeOptionalString(n.access_token); const a = normalizeOptionalString(n.refresh_token); if (!i || !a) continue; o.push({ access: i, refresh: a, sourceKind: "hermes-auth-json", sourceSlot: t, sourceLabel: t === "provider" ? "Hermes active OpenAI Codex provider" : normalizeOptionalString(n.label) ?? "Hermes OpenAI Codex credential pool", sourcePath: e, updatedAt: t === "provider" ? parseDateStringTimestampMs(r?.last_refresh) : parseDateStringTimestampMs(n.last_refresh) ?? parseDateStringTimestampMs(n.last_status_at) }); } o.sort((e, t) => (t.updatedAt ?? 0) - (e.updatedAt ?? 0)); o.forEach((e, t) => { e.sourceCredentialIndex = t; }); return o; } async function readHermesOAuthProviderIds(e) { const t = await readJsonObject(e); const n = isRecord(t.providers) ? Object.keys(t.providers).filter((e) => HERMES_REAUTH_SOURCE_PROVIDERS.has(e)) : []; const r = isRecord(t.credential_pool) ? Object.entries(t.credential_pool).flatMap(([e, t]) => Array.isArray(t) && t.some((e) => isRecord(e) && normalizeOptionalString(e.auth_type)?.toLowerCase() === "oauth") ? [e] : []) : []; return /* @__PURE__ */ new Set([...n, ...r]); } async function buildReauthenticationItems(e) { const t = await readHermesOAuthProviderIds(e.authPath); const n = await readHermesOAuthProviderIds(e.globalAuthPath); const r = HERMES_REAUTH_PROVIDER_MAPPINGS.flatMap(({ sourceProvider: r, targetProvider: i }) => { const a = t.has(r) ? e.authPath : n.has(r) ? e.globalAuthPath : void 0; if (!a) return []; return [createMigrationManualItem({ id: `manual:auth-reauthenticate:${i}`, source: a, message: `Hermes ${r} credentials cannot be reused safely by OpenClaw.`, recommendation: i === "qwen" ? "Authenticate qwen with an API key after migration: openclaw onboard --auth-choice qwen-api-key." : `Authenticate ${i} in OpenClaw after migration.` })]; }); return [...new Map(r.map((e) => [e.id, e])).values()]; } const OPENAI_PROVIDER_ID = "openai"; const OPENAI_CODEX_DEFAULT_MODEL = "openai/gpt-6-astra"; const HERMES_AUTH_DISPLAY_NAME = "Hermes import"; function sourceCredentialFingerprint(e) { return sha256Hex(`${e.sourceKind}\0${e.accountId ?? ""}\0${e.access}\0${e.refresh}\0`); } async function readOpenCodeOpenAICandidates(e) { if (!e) return []; const t = await readJsonObject(e); const n = isRecord(t.openai) ? t.openai : void 0; const r = normalizeOptionalString(n?.access); const i = normalizeOptionalString(n?.accountId); const a = normalizeOptionalString(n?.refresh); if (!r || !a) return []; return [{ access: r, ...i ? { accountId: i } : {}, refresh: a, sourceKind: "opencode-auth-json", sourceSlot: "opencode", sourceCredentialIndex: 0, sourceLabel: "OpenCode OpenAI OAuth credential", sourcePath: e }]; } function buildAuthResult(e, t = "hermes-import") { const n = resolveOpenAICodexAuthIdentity({ access: e.access, accountId: e.accountId }); return buildOauthProviderAuthResult({ providerId: OPENAI_PROVIDER_ID, defaultModel: OPENAI_CODEX_DEFAULT_MODEL, access: e.access, refresh: e.refresh, expires: resolveOpenAICodexAccessTokenExpiry(e.access), email: n.email, profileName: resolveOpenAICodexImportProfileName(n, t), displayName: HERMES_AUTH_DISPLAY_NAME, credentialExtra: buildOpenAICodexCredentialExtra(n) }); } function applyOAuthModelConfig(e) { return { ...e, agents: { ...e.agents, defaults: { ...e.agents?.defaults, models: { ...e.agents?.defaults?.models, [OPENAI_CODEX_DEFAULT_MODEL]: e.agents?.defaults?.models?.[OPENAI_CODEX_DEFAULT_MODEL] ?? {} } } } }; } function authProfileDedupeKey(e) { if (e.credential.accountId) return `${e.credential.provider}:account:${e.credential.accountId}`; if (e.credential.email) return `${e.credential.provider}:email:${e.credential.email}`; return `${e.credential.provider}:profile:${e.sourceProfileId}`; } async function readCodexAuthProfilesFromSource(e) { const t = await readHermesCodexAuthCandidates(e.authPath); const n = await readHermesCodexAuthCandidates(e.globalAuthPath); const r = t.find((e) => e.sourceSlot === "provider"); const i = t.filter((e) => e.sourceSlot === "pool"); const a = n.find((e) => e.sourceSlot === "provider"); const o = n.filter((e) => e.sourceSlot === "pool"); const s = [ ...r ? [r] : a ? [a] : [], ...i.length > 0 ? i : o, ...await readOpenCodeOpenAICandidates(e.opencodeAuthPath) ].toSorted((e, t) => (t.updatedAt ?? 0) - (e.updatedAt ?? 0)); const c = []; const l = /* @__PURE__ */ new Set(); for (const [e, t] of s.entries()) { const n = buildAuthResult(t, s.length === 1 ? "hermes-import" : `hermes-import-${e + 1}`).profiles[0]; if (!n || n.credential.type !== "oauth") continue; const r = { candidate: t, credential: n.credential, sourceProfileId: n.profileId }; const i = authProfileDedupeKey(r); if (l.has(i)) continue; l.add(i); c.push(r); } return c; } function findMatchingProfile(e, t) { for (const [n, r] of Object.entries(e.profiles)) { if (r.type !== "oauth" || r.provider !== t.provider) continue; if (t.accountId && r.accountId === t.accountId) return n; if ((!t.accountId || !r.accountId) && t.email && r.email === t.email) return n; } } function oauthAuthProfileConfig(e, t) { return { profileId: e, provider: t.provider, mode: "oauth", ...t.email ? { email: t.email } : {}, ...t.displayName ? { displayName: t.displayName } : {} }; } function findPlannedAuthProfile(e) { const t = e.profiles.find((t) => t.sourceProfileId === e.sourceProfileId); const n = e.sourceCredentialFingerprint; if (!n) return t; if (t && sourceCredentialFingerprint(t.candidate) === n) return t; const r = e.sourceCredentialIndex === void 0 ? void 0 : e.profiles.find((t) => t.candidate.sourceCredentialIndex === e.sourceCredentialIndex); if (r && sourceCredentialFingerprint(r.candidate) === n) return r; return e.profiles.find((e) => sourceCredentialFingerprint(e.candidate) === n); } async function buildAuthItems(e) { const t = []; t.push(...await buildReauthenticationItems(e.source)); const n = await readCodexAuthProfilesFromSource(e.source); if (n.length === 0) return t; const [r, i] = await Promise.all([loadAuthProfileStoreWithoutExternalProfilesAsync(e.targets.agentDir), AuthStorage.resolvePathForDisplayAsync(e.targets.agentDir)]); t.push(...n.map((t) => { const a = findMatchingProfile(r, t.credential); const o = a ?? t.sourceProfileId; const s = Boolean(r.profiles[o]); const c = !e.ctx.includeSecrets; const l = hasAuthProfileConfigConflict(e.ctx.config, oauthAuthProfileConfig(o, t.credential), Boolean(e.ctx.overwrite)); const u = (s && !a && !e.ctx.overwrite || l) && !c; const d = n.length === 1 ? `auth:${OPENAI_PROVIDER_ID}` : `auth:${OPENAI_PROVIDER_ID}:${t.sourceProfileId}`; return createMigrationItem({ id: d, kind: "auth", action: c ? "skip" : "create", source: t.candidate.sourcePath, target: `${i}#${o}`, status: c ? "skipped" : u ? "conflict" : "planned", sensitive: true, reason: c ? HERMES_REASON_INCLUDE_SECRETS : u ? HERMES_REASON_AUTH_PROFILE_EXISTS : void 0, message: c ? `OpenAI OAuth credentials detected in ${t.candidate.sourceKind === "hermes-auth-json" ? "Hermes" : "OpenCode"}.` : "Import OpenAI OAuth credentials and configure OpenAI models.", details: { provider: OPENAI_PROVIDER_ID, profileId: o, ...t.candidate.sourceCredentialIndex !== void 0 ? { sourceCredentialIndex: t.candidate.sourceCredentialIndex } : {}, sourceCredentialFingerprint: sourceCredentialFingerprint(t.candidate), sourceProfileId: t.sourceProfileId, sourceKind: t.candidate.sourceKind, sourceLabel: t.candidate.sourceLabel } }); })); return t; } async function applyAuthItem(e, t, n) { const r = t.source; const i = typeof t.details?.profileId === "string" ? t.details.profileId : ""; const a = typeof t.details?.sourceProfileId === "string" ? t.details.sourceProfileId : i; const o = typeof t.details?.sourceCredentialIndex === "number" ? t.details.sourceCredentialIndex : void 0; const s = typeof t.details?.sourceCredentialFingerprint === "string" ? t.details.sourceCredentialFingerprint : void 0; if (!r || !i) return markMigrationItemError(t, HERMES_REASON_MISSING_SECRET_METADATA); const c = findPlannedAuthProfile({ profiles: await readCodexAuthProfilesFromSource({ root: "", archivePaths: [], ...t.details?.sourceKind === "opencode-auth-json" ? { opencodeAuthPath: r } : { authPath: r } }), sourceProfileId: a, ...o === void 0 ? {} : { sourceCredentialIndex: o }, ...s ? { sourceCredentialFingerprint: s } : {} }); if (!c) return markMigrationItemSkipped(t, HERMES_REASON_SECRET_NO_LONGER_PRESENT); let l = false; let u = false; const d = { ...c.credential, displayName: "displayName" in c.credential && c.credential.displayName ? c.credential.displayName : HERMES_AUTH_DISPLAY_NAME }; const f = oauthAuthProfileConfig(i, d); if (hasCurrentAuthProfileConfigConflict(e, f)) return markMigrationItemConflict(t, HERMES_REASON_AUTH_PROFILE_EXISTS); const p = await updateAuthProfileStoreWithLockCompat({ agentDir: n.agentDir, stateDir: e.stateDir, updater: (t) => { const n = t.profiles[i]; if (!e.overwrite && n) { if (findMatchingProfile(t, d) !== i) { l = true; return false; } return false; } t.profiles[i] = d; u = true; return true; } }); if (l) return markMigrationItemConflict(t, HERMES_REASON_AUTH_PROFILE_EXISTS); if (!p?.profiles[i]) return markMigrationItemError(t, HERMES_REASON_AUTH_PROFILE_WRITE_FAILED); const m = await applyAuthProfileConfigWithConflictCheck({ ctx: e, profile: f, applyConfigPatch(e) { const t = applyOAuthModelConfig(e); return resolveAgentModelPrimaryValue(t.agents?.defaults?.model) === void 0 ? applyAgentDefaultModelPrimary(t, OPENAI_CODEX_DEFAULT_MODEL) : t; } }); if (m === "conflict") return markMigrationItemConflict(t, HERMES_REASON_AUTH_PROFILE_EXISTS); return { ...t, status: "migrated", message: m === "configured" ? t.message : `${t.message ?? "Imported auth profile."} ${HERMES_REASON_CONFIG_RUNTIME_UNAVAILABLE}.`, details: { ...t.details, wroteAuthProfile: u, configUpdated: m === "configured" } }; } //#endregion export { buildAuthItems as n, applyAuthItem as t };