UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

297 lines (296 loc) • 14.3 kB
import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs"; import { r as resolveStateDir } from "./state-dir-DiG0gXzD.mjs"; import { p as shortenHomePath } from "./utils-C8YECn2Q.mjs"; import "./paths-DAcAg5aV.mjs"; import { r as normalizeProviderId } from "./provider-id-b5XGSf9C.mjs"; import { i as listAgentIds } from "./agent-roster-t1ooUdXp.mjs"; import { a as resolveAgentDir } from "./agent-scope-config-DmXgFGKP.mjs"; import { r as decodeUtf8Input } from "./utf8-input-BHczGT8v.mjs"; import "./user-model-account-authority-CRj924IP.mjs"; import "./agent-scope-BwB8YH6y.mjs"; import { a as mergeAuthProfileStores, f as removeRuntimeExternalProfileReferences, i as loadPersistedSharedAuthProfileStore, n as loadPersistedAuthProfileStore } from "./persisted-Dv3zNYHi.mjs"; import { t as resolveSharedMainAuthAgentDir } from "./shared-main-dir-C2ynhf4g.mjs"; import { d as resolveSharedAuthStorePath } from "./path-resolve-CpNl_n1M.mjs"; import { o as resolveConfiguredAgentDatabaseCandidatePaths } from "./targets-BVE0__Jb.mjs"; import { t as shellEscape } from "./shell-quote-DeRN90_2.mjs"; import { a as resolveAuthProfileOrder } from "./order-jOvee2J6.mjs"; import { l as isNonSecretApiKeyMarker } from "./model-auth-markers-4YSUG71a.mjs"; import { g as resolveProviderConfigSecretInput } from "./model-auth-provider-config-Bnc4upRS.mjs"; import { C as updateAuthProfileStoreWithLock } from "./store-runtime-dW0pXLJI.mjs"; import { n as createRetainedAgentDatabaseMatcher } from "./agent-deletion-discovery-BUESMyCH.mjs"; import { t as parseModelCatalogJson } from "./model-catalog-json-DfeKlndn.mjs"; import { n as isGeneratedPluginModelCatalog } from "./plugin-model-catalog-repair-B3GKtPvY.mjs"; import { r as loadPersistedPluginModelCatalogsReadOnly } from "./plugin-model-catalog-BafTZg7-.mjs"; import { t as note } from "./note-CnLgHvug.mjs"; import { t as listAgentModelsJsonPaths } from "./storage-scan-BUHFlvPI.mjs"; import { t as createAuthMigrationWarningRecorder } from "./auth-migration-findings-CsbyP_27.mjs"; import fs from "node:fs"; import path from "node:path"; import { isDeepStrictEqual } from "node:util"; //#region src/commands/doctor-model-catalog-credentials.ts /** Doctor-owned migration of plaintext model-catalog credentials into agent SQLite. */ function emptyStore() { return { version: 1, profiles: {} }; } function credentialMatches(e, { provider: t, key: n }) { if (normalizeProviderId(e?.provider ?? "") !== normalizeProviderId(t)) return false; return e?.type === "api_key" && e.key === n || e?.type === "token" && e.token === n; } function hasProviderSecretRef(e, t) { return Object.values(e.profiles).some((e) => normalizeProviderId(e.provider) === normalizeProviderId(t) && (e.type === "api_key" && e.keyRef !== void 0 || e.type === "token" && e.tokenRef !== void 0)); } function findProviderSecretRefProfiles(e, t) { return Object.entries(e.profiles).filter(([, e]) => { if (e.type !== "api_key" || !e.key) return false; const n = resolveProviderConfigSecretInput(t, e.provider).ref; const r = n?.id.trim(); return n?.source === "env" && [ r, `$${r}`, `\${${r}}` ].includes(e.key.trim()); }); } function collectCredentials(e, t, n = [], r, i = false) { if (!isRecord(e)) return []; return Object.entries(e).flatMap(([e, a]) => { if (!isRecord(a) || typeof a.apiKey !== "string") return []; const o = a.apiKey; const s = { provider: e, key: o, catalog: i }; if (!o.trim() || r && resolveProviderConfigSecretInput(r, e).ref || i && hasProviderSecretRef(t, e) || isNonSecretApiKeyMarker(o) || t.profiles[o] !== void 0 || findMatchingProfileId(t, s, n) !== void 0) return []; return [s]; }); } function uniqueCredentials(e) { return [...new Map(e.map((e) => [`${normalizeProviderId(e.provider)}\0${e.key}`, e])).values()]; } function findMatchingProfileId(e, t, n) { return Object.entries(e.profiles).find(([e, r]) => credentialMatches(r, t) && n.every((n) => n.profiles[e] === void 0 || credentialMatches(n.profiles[e], t)))?.[0]; } function allocateProfileId(e, t, n) { const r = normalizeProviderId(t.provider); for (let i = 1;; i += 1) { const a = i === 1 ? `${r}:default` : `${r}:models-json${i === 2 ? "" : `-${i}`}`; if ((!e.profiles[a] || credentialMatches(e.profiles[a], t)) && n.every((e) => !e.profiles[a] || credentialMatches(e.profiles[a], t))) return a; } } async function persistCredentials(e) { const t = uniqueCredentials(e.credentials); const { invalidProfiles: n } = e; if (t.length === 0 && n.length === 0) return { migrated: 0, removed: 0 }; const r = e.blockedStores ?? []; const i = /* @__PURE__ */ new Map(); let a = 0; let o; let s = []; if (!await updateAuthProfileStoreWithLock({ agentDir: e.agentDir, stateDir: resolveStateDir(e.env), saveOptions: { filterExternalAuthProfiles: false, syncExternalCli: false }, updater: (c, l, u) => { s = n.filter(([e, t]) => isDeepStrictEqual(c.profiles[e], t)); if (s.length > 0) Object.assign(c, removeRuntimeExternalProfileReferences({ store: c, profileIds: new Set(s.map(([e]) => e)) })); o = u; const d = u ? mergeAuthProfileStores(u, c) : c; for (const n of t) { if (n.catalog && hasProviderSecretRef(d, n.provider)) continue; if (n.catalog && (u || !e.agentDir) && e.skipCatalogCredential(n, u ?? c)) continue; const t = findMatchingProfileId(d, n, r) ?? allocateProfileId(d, n, r); i.set(t, n); if (credentialMatches(d.profiles[t], n)) continue; c.profiles[t] = { type: "api_key", provider: normalizeProviderId(n.provider), key: n.key }; d.profiles[t] = c.profiles[t]; a += 1; } return a > 0 || s.length > 0; } })) throw new Error("auth profile store could not be updated"); const c = e.agentDir ? loadPersistedAuthProfileStore(e.agentDir) : loadPersistedSharedAuthProfileStore(e.env); const l = o ? mergeAuthProfileStores(o, c ?? emptyStore()) : c; for (const [e, t] of s) if (isDeepStrictEqual(c?.profiles[e], t)) throw new Error(`credential cleanup verification failed for profile "${e}"`); for (const [e, t] of i) if (!credentialMatches(l?.profiles[e], t)) throw new Error(`credential verification failed for provider "${t.provider}"`); return { migrated: a, removed: s.length }; } function collectAgentCatalogs(e, t, n) { const r = createAuthMigrationWarningRecorder(t, n); const i = loadPersistedAuthProfileStore(e) ?? emptyStore(); const a = []; const o = path.join(e, "models.json"); try { const e = parseModelCatalogJson(decodeUtf8Input(fs.readFileSync(o), `Model catalog ${o}`)); if (isRecord(e) && isRecord(e.providers)) a.push(e.providers); } catch (e) { if (e.code !== "ENOENT") r(`Could not read model catalog ${shortenHomePath(o)}: ${e instanceof Error ? e.message : String(e)}`, "catalog-read-failed", "Keep the model catalog. Correct the reported file access or JSON error, then rerun openclaw doctor --fix to verify credential migration.", o); } try { for (const t of loadPersistedPluginModelCatalogsReadOnly(e)) try { const e = JSON.parse(t.contents); if (isGeneratedPluginModelCatalog(e) && isRecord(e) && isRecord(e.providers)) a.push(e.providers); } catch { r(`Could not parse generated model catalog for plugin ${t.pluginId}.`, "catalog-parse-failed", "Keep the agent database and recovery copy. Check the plugin catalog format with its maintainer before retrying openclaw doctor --fix; use openclaw models status to identify affected providers.", t.pluginId); } } catch (t) { r(`Could not read generated model catalogs for ${shortenHomePath(e)}: ${t instanceof Error ? t.message : String(t)}`, "catalog-owner-read-failed", "Keep the agent database and recovery copy. Correct the reported database access error before rerunning openclaw doctor --fix; do not delete the credential database.", e); } return { agentDir: e, localStore: i, providers: a }; } /** Copies and verifies catalog credentials before the runtime retires plaintext catalog auth. */ async function maybeMigrateModelCatalogCredentials(e) { const t = []; const n = []; const r = createAuthMigrationWarningRecorder(t, n, e.reportFindings); const i = e.env ?? process.env; const a = resolveStateDir(i); const o = resolveSharedMainAuthAgentDir(i); const s = createRetainedAgentDatabaseMatcher(i, () => listAgentIds(e.cfg).map((t) => ({ agentId: t, path: resolveAgentDir(e.cfg, t, i) })), { kind: "agent-directory", readDatabasePaths: () => resolveConfiguredAgentDatabaseCandidatePaths(e.cfg, { env: i }) }); const c = listAgentModelsJsonPaths(e.cfg, a, i).map((e) => path.dirname(e)).filter((e) => !s(e)); const l = loadPersistedSharedAuthProfileStore(i) ?? emptyStore(); const u = c.map((e) => collectAgentCatalogs(e, t, n)); const d = u.filter((e) => e.agentDir !== o).map((e) => e.localStore); const f = collectCredentials(e.cfg.models?.providers, l, d, e.cfg); const sharedProfileId = (t, n) => resolveAuthProfileOrder({ cfg: e.cfg, store: t, provider: n, readinessMode: "read-only" }).find((e) => t.profiles[e] !== void 0); const p = u.map(({ agentDir: t, localStore: n, providers: a }) => { const s = mergeAuthProfileStores(l, n); if (path.join(t, "openclaw-agent.sqlite") !== resolveSharedAuthStorePath(i)) for (const [a, o] of Object.entries(n.profiles)) { const n = normalizeProviderId(o.provider); const c = sharedProfileId(l, n); if (!a.startsWith(`${n}:models-json`) || !/^models-json(?:-\d+)?$/.test(a.slice(n.length + 1)) || !c || isDeepStrictEqual(o, l.profiles[c]) || sharedProfileId(s, n) !== a) continue; const u = listAgentIds(e.cfg).find((n) => resolveAgentDir(e.cfg, n, i) === t) ?? path.basename(path.dirname(t)); const d = `openclaw models auth logout ${shellEscape(a)} --agent ${shellEscape(u)} --yes`; r(`Agent-local auth profile "${a}" for provider "${n}" takes precedence over shared profile "${c}". Its migration origin is unrecorded; credentials were left untouched. After confirming the shared account is intended, remove the local profile with: ${d}`, "catalog-profile-shadows-shared", `Confirm the shared account is intended, then run ${d}.`, t); } const c = /* @__PURE__ */ new Set(); const skipCatalogCredential = (e, n) => { const i = sharedProfileId(n, e.provider); if (!i) return false; if (!c.has(e.provider)) { c.add(e.provider); r(`Skipped models.json credential for provider "${e.provider}" in ${shortenHomePath(t)}: shared auth profile "${i}" already provides effective credentials. The catalog source was left untouched.`, "catalog-credential-shared-auth", "Keep the shared auth profile and original catalog. Check openclaw models status for the intended account before changing credentials.", t, "recommended"); } return true; }; return { agentDir: t, credentials: uniqueCredentials(a.flatMap((t) => collectCredentials(t, s, [], e.cfg, true))).filter((e) => !skipCatalogCredential(e, l)), skipCatalogCredential, invalidProfiles: t === o ? [] : findProviderSecretRefProfiles(n, e.cfg) }; }); const m = findProviderSecretRefProfiles(l, e.cfg); const h = f.length + p.reduce((e, t) => e + t.credentials.length, 0); const g = m.length + p.reduce((e, t) => e + t.invalidProfiles.length, 0); e.reportFindings?.(n, t); for (const n of t) e.runtime.error(n); if (h === 0 && g === 0) return { detected: h, migrated: 0, removed: 0, warnings: t, findings: n }; if (h > 0) note(`Found ${h} plaintext model credential${h === 1 ? "" : "s"}. Run openclaw doctor --fix to copy and verify them in agent SQLite before plaintext catalog authentication is retired.`, "Model catalog credentials"); if (g > 0) note(`Found ${g} stored unresolved model credential marker${g === 1 ? "" : "s"}. Run openclaw doctor --fix to remove them from agent SQLite.`, "Model catalog credentials"); if (!(e.prompter.shouldRepair || await e.prompter.confirmAutoFix({ message: "Repair model credentials in agent SQLite now?", initialValue: true }))) { const r = [{ checkId: "core/doctor/auth-migration/model-credential-repair-pending", severity: "warning", category: "recommended", message: `${h} plaintext model credential${h === 1 ? "" : "s"} and ${g} unresolved marker${g === 1 ? "" : "s"} remain pending repair.`, fixHint: "Run openclaw doctor --fix to copy and verify plaintext credentials in agent SQLite and remove unresolved markers. This prepares for catalog auth retirement; keep the original catalog values until verification completes.", docsUrl: "https://docs.openclaw.ai/cli/doctor/running#auth-migration-recovery" }]; n.push(...r); e.reportFindings?.(r); return { detected: h, migrated: 0, removed: 0, warnings: t, findings: n }; } function* migrationTargets() { yield { description: "configured model credentials", blockedStores: d, credentials: f, invalidProfiles: m, skipCatalogCredential: () => false }; for (const { agentDir: e, credentials: t, invalidProfiles: n, skipCatalogCredential: r } of p) yield { description: `model credentials for ${shortenHomePath(e)}`, credentials: t, invalidProfiles: n, skipCatalogCredential: r, ...e === o ? {} : { agentDir: e } }; } let _ = 0; let v = 0; for (const { description: n, ...a } of migrationTargets()) try { const n = t.length; const r = await persistCredentials({ ...a, env: i }); for (const r of t.slice(n)) e.runtime.error(r); _ += r.migrated; v += r.removed; } catch (t) { const i = `Could not migrate ${n}: ${t instanceof Error ? t.message : String(t)}`; r(i, "credential-import-failed", "Keep the original catalog values and recovery copy. Correct the reported credential-store error and rerun openclaw doctor --fix. Check openclaw models status for the intended accounts.", n); e.runtime.error(i); } if (_ > 0) note(`Copied and verified ${_} model credential${_ === 1 ? "" : "s"} in agent SQLite. Existing catalog values remain active until the runtime migration lands.`, "Doctor changes"); if (v > 0) note(`Removed ${v} unresolved model credential marker${v === 1 ? "" : "s"} from agent SQLite.`, "Doctor changes"); return { detected: h, migrated: _, removed: v, warnings: t, findings: n }; } //#endregion export { maybeMigrateModelCatalogCredentials };