UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

673 lines (672 loc) • 28.3 kB
import { i as asOptionalObjectRecord, r as asNullableRecord } from "./record-coerce-CVPuDqcc.mjs"; import { m as normalizeTrimmedStringList } from "./string-normalization-DLmfYZXI.mjs"; import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs"; import { r as normalizeProviderId } from "./provider-id-b5XGSf9C.mjs"; import { a as parseProviderModelRef } from "./model-catalog-refs-Bk2MNoCv.mjs"; import { t as discoverConfiguredPluginLoadPaths } from "./discovery-DvJYrQFY.mjs"; import { t as PluginDependencyLinkError } from "./plugin-instance-error-BCRn5qri.mjs"; import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs"; import { r as withArtifactPreservingStateReads } from "./artifact-preserving-state-reads-BfhmBr-V.mjs"; import { Et as _enum, Fn as object, Jn as string, Nt as array, Pn as number, qn as strictObject, xn as literal } from "./schemas-Cy6abvsu.mjs"; import { o as withPluginSourceCaptureStorage } from "./plugin-source-capture-context-BU9oGeml.mjs"; import { i as coerceDoctorSessionRouteStateOwners } from "./manifest-Y5vPZPOf.mjs"; import { t as areBundledPluginsDisabled } from "./bundled-dir-BKvdAqkP.mjs"; import { t as normalizePluginPolicyId } from "./plugin-policy-id-CkilMowp.mjs"; import { u as normalizePluginsConfig } from "./config-state-B1JlHgba.mjs"; import { n as findUninspectedPluginDiagnostic } from "./discovery-availability-DtlJ7XvT.mjs"; import { t as resolvePluginDoctorContractArtifact } from "./doctor-contract-artifact-DcW-zBOM.mjs"; import { n as loadBundledPluginManifestRegistry } from "./manifest-registry-build-BbYTyBDW.mjs"; import { r as collectConfiguredModelRefs } from "./configured-model-refs-DtaDJ1Vw.mjs"; import { t as discoverConfigWidePluginManifestRegistry } from "./io.plugin-metadata-CBwzHw3m.mjs"; import { n as isChannelConfigMetadataKey } from "./config-metadata-BVUrt758.mjs"; import { n as isActivatedManifestOwner } from "./manifest-owner-policy-B8Brw4Zo.mjs"; import { n as loadPluginManifestRegistryForPluginRegistry } from "./plugin-registry-contributions-iAw3gSDD.mjs"; import { n as hasPluginConfigMigrationSource } from "./config-contract-matches-BYS12x_-.mjs"; import { t as GENERATED_BUNDLED_CHANNEL_CONFIG_METADATA } from "./bundled-channel-config-metadata.generated-BoM67BKX.mjs"; import { a as resolveBundledPluginScanDir } from "./bundled-plugin-scan-VUxPP72r.mjs"; import { t as getPluginSetupModuleLoader } from "./plugin-setup-module-D_W6TtnO.mjs"; import { t as loadBundledPluginPublicArtifactModuleFromCandidatesSync } from "./public-surface-loader-DENdCm5a.mjs"; import { n as applyResolvedPluginDoctorCompatibilityMigrations } from "./doctor-compatibility-migration-Be-t21B8.mjs"; import { n as unwrapDefaultModuleExport } from "./module-export-DTZ89pa-.mjs"; import "./plugin-registry-BrQav-kR.mjs"; import { i as resolveSetupChannelRegistration, t as channelPluginIdBelongsToManifest } from "./loader-channel-setup-C8SFP0j7.mjs"; import { t as shouldIncludeChannelSetupFeatureForConfig } from "./bundled-setup-policy-aGGzBRJW.mjs"; import { t as definePluginDoctorMigrationFromPlans } from "./doctor-migration-plan-adapter-CQwwvGNR.mjs"; import path from "node:path"; import { AsyncLocalStorage } from "node:async_hooks"; //#region src/plugins/doctor-contract-legacy-setup.ts const log$1 = createSubsystemLogger("plugins/doctor-contracts"); function loadLegacyChannelStateMigrationDetector(e, t) { const n = e.setupSource; if (!n) return null; try { const r = getPluginSetupModuleLoader(e, n, e.rootDir); return r.initialize(() => { const i = unwrapDefaultModuleExport(r(n)); if (i?.kind !== "bundled-channel-setup-entry") { const { plugin: t } = resolveSetupChannelRegistration(i); if (!t?.id || !channelPluginIdBelongsToManifest({ channelId: t.id, pluginId: e.id, manifestChannels: e.channels })) return null; const n = t.lifecycle?.detectLegacyStateMigrations; if (n === void 0) return null; if (typeof n !== "function") throw new Error(`Plugin ${e.id} legacy migration detector is not a function.`); return n; } if (typeof i.loadSetupPlugin !== "function") return null; if (typeof i.loadLegacyStateMigrationDetector === "function") { const t = i.loadLegacyStateMigrationDetector(); if (typeof t !== "function") throw new Error(`Plugin ${e.id} legacy migration loader did not return a detector.`); return t; } if (i.features?.legacyStateMigrations !== true) { t?.(e.id); return null; } const a = i.loadSetupPlugin().lifecycle?.detectLegacyStateMigrations; return typeof a === "function" ? a : null; }); } catch (t) { log$1.warn(`failed to load legacy state migration for ${e.id} from ${e.setupSource}: ${formatErrorMessage(t)}`); return null; } } //#endregion //#region src/plugins/doctor-contract-module.ts function coerceLegacyConfigRules(e) { if (!Array.isArray(e)) return []; return e.filter((e) => { const t = asOptionalObjectRecord(e); return Array.isArray(t?.path) && typeof t?.message === "string"; }); } function coerceNormalizeCompatibilityConfig(e) { return typeof e === "function" ? e : void 0; } function coerceSessionStoreAgentIdsResolver(e) { return typeof e === "function" ? e : void 0; } function isPluginDoctorStateMigration(e) { const t = asOptionalObjectRecord(e); return typeof t?.id === "string" && t.id.trim().length > 0 && typeof t.label === "string" && t.label.trim().length > 0 && typeof t.detectLegacyState === "function" && typeof t.migrateLegacyState === "function"; } function coercePluginDoctorStateMigrations(e) { if (!Array.isArray(e)) return []; return e.filter(isPluginDoctorStateMigration).map((e) => { const t = { id: e.id.trim(), label: e.label.trim(), doctorOnly: e.doctorOnly === true ? true : void 0, phase: e.phase === "after-session-repair" ? e.phase : void 0, collectBackupResources: e.collectBackupResources, detectLegacyState: e.detectLegacyState, migrateLegacyState: e.migrateLegacyState }; if (e.sqliteOnly !== void 0) t.sqliteOnly = strictObject({ family: _enum([ "state", "agent", "workboard", "logbook", "team-reports" ]), postgresNote: string().trim().min(1).optional() }).parse(e.sqliteOnly); return t; }); } function coerceProviderRenames(e) { return array(object({ from: string().regex(/^[a-z0-9][a-z0-9._-]*$/), to: string().regex(/^[a-z0-9][a-z0-9._-]*$/), baseUrl: string().url() }).refine(({ from: e, to: t }) => e !== t)).parse(e ?? []); } /** Only callability is required; registration ignores results and keeps source-bound identity. */ function isPluginDoctorRecoveryCliRegistrar(e) { return typeof e === "function"; } function declaresPluginDoctorContractSurface(e, t) { const n = e?.[t]; return n === true || t === "stateMigrations" && Array.isArray(n) || t === "recoveryCli" && Array.isArray(n) && n.length > 0; } /** Coerce a loaded doctor contract once for both registry use and declaration validation. */ function coercePluginDoctorContractModule(e, t) { const n = e.default; const r = object({ channelId: string().trim().min(1).refine((e) => !t || t.includes(e), "Historical webhook listener channel must belong to the plugin"), port: number().int().min(1).max(65535), host: string().trim().min(1).optional(), preserveAuthoredActivation: literal(true).optional() }).optional().parse(e.historicalWebhookListener === void 0 ? n?.historicalWebhookListener : e.historicalWebhookListener); const i = coerceLegacyConfigRules(n?.legacyConfigRules ?? e.legacyConfigRules); const a = coerceNormalizeCompatibilityConfig(e.normalizeCompatibilityConfig ?? n?.normalizeCompatibilityConfig); const o = coerceNormalizeCompatibilityConfig(e.normalizeHistoricalWebhookConfig ?? n?.normalizeHistoricalWebhookConfig); const s = coerceSessionStoreAgentIdsResolver(e.resolveSessionStoreAgentIds ?? n?.resolveSessionStoreAgentIds); const c = coerceDoctorSessionRouteStateOwners(e.sessionRouteStateOwners ?? n?.sessionRouteStateOwners); const l = coercePluginDoctorStateMigrations(e.stateMigrations ?? n?.stateMigrations); const u = e.registerRecoveryCli ?? n?.registerRecoveryCli; if (u !== void 0 && !isPluginDoctorRecoveryCliRegistrar(u)) throw new Error("Doctor registerRecoveryCli must be a function"); const d = u; const f = coerceProviderRenames(e.providerRenames ?? n?.providerRenames); return { historicalWebhookListener: r, normalizeHistoricalWebhookConfig: o, rules: i, normalizeCompatibilityConfig: a, providerRenames: f, resolveSessionStoreAgentIds: s, sessionRouteStateOwners: c, stateMigrations: l, registerRecoveryCli: d, summary: { recoveryCli: Boolean(d), configRepair: i.length > 0 || Boolean(a) || f.length > 0, resolveSessionStoreAgentIds: Boolean(s), sessionRouteStateOwners: c.length > 0, stateMigrations: l.length > 0 } }; } //#endregion //#region src/plugins/doctor-contract-relevance.ts function hasScopedProviderAuthAlias(e, t) { return Object.entries(e.providerAuthAliases ?? {}).some(([n, r]) => { if (typeof r !== "string") return false; const i = normalizeProviderId(r); return t.has(normalizeProviderId(n)) && i !== "" && e.providers.some((e) => normalizeProviderId(e) === i); }); } function hasLegacyElevenLabsTalkFields(e) { const t = asNullableRecord(asNullableRecord(e)?.talk); if (!t) return false; return [ "voiceId", "voiceAliases", "modelId", "outputFormat", "apiKey" ].some((e) => Object.hasOwn(t, e)); } function collectMediaProviderIds(e, t) { const n = asNullableRecord(asNullableRecord(e.tools)?.media); if (!n) return; const r = [ n.models, asNullableRecord(n.audio)?.models, asNullableRecord(n.image)?.models, asNullableRecord(n.video)?.models ]; for (const e of r) { if (!Array.isArray(e)) continue; for (const n of e) { const e = asNullableRecord(n)?.provider; if (typeof e === "string" && e.trim()) t.add(normalizeProviderId(e)); } } } function collectConfiguredModelProviderIds(e) { const addRef = (t) => { const n = typeof t === "string" ? parseProviderModelRef(t) : null; if (n) e.ids.add(normalizeProviderId(n.provider)); }; for (const t of collectConfiguredModelRefs(e.root)) addRef(t.value); const collectAgentPolicy = (e) => { const t = asNullableRecord(asNullableRecord(e)?.modelPolicy)?.allow; if (Array.isArray(t)) t.forEach(addRef); }; const t = asNullableRecord(e.root.agents) ?? {}; collectAgentPolicy(t.defaults); if (Object.hasOwn(t, "entries")) { const e = asNullableRecord(t.entries); if (e) Object.values(e).forEach(collectAgentPolicy); } else if (Array.isArray(t.list)) t.list.forEach(collectAgentPolicy); } function collectRelevantDoctorPluginIds(e) { const t = /* @__PURE__ */ new Set(); const n = asNullableRecord(e); if (!n) return []; const r = asNullableRecord(n.channels); if (r) for (const e of Object.keys(r)) { const n = e.trim(); if (n && !isChannelConfigMetadataKey(n)) t.add(n); } const i = asNullableRecord(asNullableRecord(n.plugins)?.entries); if (i) for (const e of Object.keys(i)) t.add(e); const a = asNullableRecord(asNullableRecord(n.models)?.providers); if (a) for (const e of Object.keys(a)) t.add(e); collectMediaProviderIds(n, t); collectConfiguredModelProviderIds({ root: n, ids: t }); if (hasLegacyElevenLabsTalkFields(n)) t.add("elevenlabs"); return [...t].toSorted(); } function collectRelevantDoctorPluginIdsForTouchedPaths(e) { const t = asNullableRecord(e.raw); if (!t) return []; const n = /* @__PURE__ */ new Set(); collectConfiguredModelProviderIds({ root: t, ids: n }); for (const r of e.touchedPaths) { const [i, a, o] = r; if (i === "channels") { if (!a) return collectRelevantDoctorPluginIds(e.raw); const t = a.trim(); if (t && !isChannelConfigMetadataKey(t)) n.add(t); continue; } if (i === "plugins" || i === "models") { if (a !== (i === "plugins" ? "entries" : "providers") || !o) return collectRelevantDoctorPluginIds(e.raw); n.add(o); continue; } if (i === "tools" && a === "media") { collectMediaProviderIds(t, n); continue; } if (i === "talk" && hasLegacyElevenLabsTalkFields(t)) n.add("elevenlabs"); } return [...n].toSorted(); } //#endregion //#region src/plugins/doctor-contract-registry.ts const log = createSubsystemLogger("plugins/doctor-contracts"); const deferredPluginMigrations = new AsyncLocalStorage(); /** Defer unavailable plugin repairs while retaining host-owned historical listener facts. */ function withDeferredPluginDoctorMigrations(e, t) { return deferredPluginMigrations.run(new Set(e), t); } function isPluginDoctorMigrationDeferred(e) { const t = normalizePluginPolicyId(e); return [...deferredPluginMigrations.getStore() ?? []].some((n) => n === e || normalizePluginPolicyId(n) === t); } function isTrustedForDurableStores(e) { return e.origin === "bundled" || e.trustedOfficialInstall === true; } /** Include manifest-owned legacy roots for config repair, never session ownership. */ function collectDoctorConfigRepairPluginIds(e, t) { const n = asNullableRecord(e); if (!n) return []; const r = new Set(t ? collectRelevantDoctorPluginIdsForTouchedPaths({ raw: e, touchedPaths: t }) : collectRelevantDoctorPluginIds(e)); const i = loadPluginManifestRegistryForPluginRegistry({ config: n, includeDisabled: true }); for (const n of i.plugins) if (hasPluginConfigMigrationSource({ root: e, pathPatterns: n.configContracts?.compatibilityMigrationPaths, touchedPaths: t })) r.add(n.id); return [...r].toSorted(); } function loadPluginDoctorContractEntry(e, t) { const n = e.doctorContract; if (n && !declaresPluginDoctorContractSurface(n, t)) return null; const r = resolvePluginDoctorContractArtifact(e); if (!r) return null; try { const n = getPluginSetupModuleLoader(e, r.modulePath, r.boundaryRoot, { stateOperations: false }); const { summary: i, ...a } = n.initialize(() => coercePluginDoctorContractModule(n(r.modulePath), e.channels)); if (a.providerRenames.some(({ from: t, to: n }) => !e.providers.includes(t) || !e.providers.includes(n))) throw new Error("Provider renames must belong to the plugin's declared providers."); if (!Object.values(i).some(Boolean) && t !== "stateMigrations") return null; return { pluginId: e.id, ...a, origin: e.origin }; } catch (t) { log.warn(`failed to load doctor contract for ${e.id} from ${r.modulePath}: ${formatErrorMessage(t)}`); return t instanceof PluginDependencyLinkError ? t : null; } } /** The CLI owner supplies the exact enabled artifact withheld for a pending migration. */ function loadPluginDoctorRecoveryCliRegistrar(e) { if (!declaresPluginDoctorContractSurface(e.doctorContract, "recoveryCli")) return; const t = loadPluginDoctorContractEntry(e, "recoveryCli"); return t && !(t instanceof PluginDependencyLinkError) ? t.registerRecoveryCli : void 0; } function resolvePluginDoctorManifestRecords(e, t = false) { if (e?.pluginIds && e.pluginIds.length === 0) return []; return filterPluginDoctorRecordsByScope((e.manifestRegistry ?? loadPluginManifestRegistryForPluginRegistry({ config: e?.config, workspaceDir: e?.workspaceDir, env: e.env ?? process.env, includeDisabled: true, artifactPreservingReadOnly: e.artifactPreservingReadOnly })).plugins, e.pluginIds, t); } function filterPluginDoctorRecordsByScope(e, t, n = false) { const r = t ? new Set(t) : null; const i = t ? new Set(t.map(normalizePluginPolicyId)) : null; const a = t ? new Set(t.map(normalizeProviderId).filter(Boolean)) : null; return e.filter((e) => (n || !isPluginDoctorMigrationDeferred(e.id)) && !(r && !r.has(e.id) && !(i && i.has(normalizePluginPolicyId(e.id))) && !(e.packageName && r.has(e.packageName)) && !e.legacyPluginIds?.some((e) => r.has(e)) && !e.channels.some((e) => r.has(e)) && !e.providers.some((e) => r.has(e)) && !(a && hasScopedProviderAuthAlias(e, a)))); } function resolvePluginDoctorContracts(e) { const t = e.config?.plugins?.load?.paths ?? []; if (e.surface === "configRepair" && t.length > 0) { const n = findUninspectedPluginDiagnostic(discoverConfiguredPluginLoadPaths({ loadPaths: t, env: e.env }).diagnostics); if (n) { log.warn(n.message); return []; } } const n = e.surface === "configRepair"; const r = resolvePluginDoctorManifestRecords(e, n); const i = loadPluginDoctorContractEntries({ records: n ? r.filter((e) => !isPluginDoctorMigrationDeferred(e.id)) : r, surface: e.surface }); if (e.surface !== "configRepair") return i; for (const { channelId: t, pluginId: n } of GENERATED_BUNDLED_CHANNEL_CONFIG_METADATA) { const a = r.find((e) => e.id === n || e.channels.includes(t)); const o = e.historicalWebhookListeners && a?.id === n && a.trustedOfficialInstall === true ? i.find((e) => e.pluginId === n && !e.historicalWebhookListener) : void 0; const s = e.historicalWebhookListeners && a?.id === n && a.trustedOfficialInstall === true && isPluginDoctorMigrationDeferred(n); if (isPluginDoctorMigrationDeferred(n) && !e.historicalWebhookListeners || !e.historicalWebhookListeners && !Object.hasOwn(e.config?.channels ?? {}, t) && !Object.hasOwn(e.config?.plugins?.entries ?? {}, n) || a && !o && !s || e.pluginIds && !e.pluginIds.includes(t) && !e.pluginIds.includes(n)) continue; const c = loadBundledPluginPublicArtifactModuleFromCandidatesSync({ dirName: t, artifactCandidates: ["config-doctor-api.js"], env: e.env }); if (!c) continue; const { summary: l, ...u } = coercePluginDoctorContractModule(c, [t]); if (o && u.historicalWebhookListener && u.normalizeCompatibilityConfig) { o.historicalWebhookListener = u.historicalWebhookListener; o.historicalWebhookNormalizer = u.normalizeCompatibilityConfig; } else if (!a || s) { if (isPluginDoctorMigrationDeferred(n)) { const e = u.normalizeHistoricalWebhookConfig; if (!u.historicalWebhookListener || !e) continue; i.push({ pluginId: n, ...u, origin: a?.origin ?? "bundled", rules: [], providerRenames: [], normalizeCompatibilityConfig: e }); } else i.push({ pluginId: n, ...u, providerRenames: [], origin: "bundled" }); } } return i; } function loadPluginDoctorContractEntries(e) { return e.records.flatMap((t) => { const n = loadPluginDoctorContractEntry(t, e.surface); return n && !(n instanceof PluginDependencyLinkError) ? [n] : []; }); } function listPluginDoctorLegacyConfigRules(e) { return (e?.activeOnly ? loadPluginDoctorContractEntries({ records: resolvePluginDoctorStateMigrationRecords(e), surface: "configRepair" }) : resolvePluginDoctorContracts({ ...e, surface: "configRepair" })).flatMap((e) => e.rules); } /** Resolve only the selected config-repair owners, including their deferral policy. */ function resolvePluginDoctorProviderRenames(e) { return resolvePluginDoctorContracts({ ...e, pluginIds: e.pluginIds ?? collectRelevantDoctorPluginIds(e.config ?? {}), surface: "configRepair" }).flatMap((e) => e.providerRenames); } function listPluginDoctorSessionRouteStateOwners(e) { const t = /* @__PURE__ */ new Map(); const n = resolvePluginDoctorManifestRecords(e ?? {}); const r = n.flatMap((e) => e.sessionRouteStateOwners ?? []); const i = loadPluginDoctorContractEntries({ records: n.filter((e) => e.sessionRouteStateOwners === void 0), surface: "sessionRouteStateOwners" }).flatMap((e) => e.sessionRouteStateOwners); for (const e of [...r, ...i]) if (!t.has(e.id)) t.set(e.id, e); return [...t.values()].toSorted((e, t) => e.id.localeCompare(t.id)); } /** Resolve plugin-owned agent IDs whose core session stores need migration. */ function listPluginDoctorSessionStoreAgentIds(e) { const t = e?.config ?? {}; const n = /* @__PURE__ */ new Set(); for (const r of resolvePluginDoctorContracts({ ...e, surface: "resolveSessionStoreAgentIds" })) { let e; try { e = r.resolveSessionStoreAgentIds?.({ cfg: t }); } catch { continue; } for (const t of normalizeTrimmedStringList(e)) n.add(t); } return [...n].toSorted(); } var PluginDoctorStateMigrationDeclarationError = class extends Error {}; function listPluginDoctorStateMigrationEntries(e) { return loadPluginDoctorStateMigrationEntries(e?.inventory?.records ?? resolvePluginDoctorStateMigrationRecords(e ?? {}), e?.validateDeclarations, e?.onInspectedPlugin, e?.onInspectedStatelessPlugin, e?.onSelectedPlugin, e?.onUnavailablePlugin); } function loadPluginDoctorStateMigrationEntries(e, t = true, n, r, i, a) { const o = []; for (const s of e) { i?.(s.id); const e = loadPluginDoctorContractEntry(s, "stateMigrations"); if (e instanceof PluginDependencyLinkError) { a?.(s.id, e); continue; } const c = s.doctorContract?.stateMigrations; const l = e?.stateMigrations ?? []; if (t && Array.isArray(c) && (c.length !== l.length || c.some((e, t) => { const n = l[t]; return e.id !== n?.id || e.doctorOnly === true !== (n?.doctorOnly === true) || e.phase !== n?.phase; }))) throw new PluginDoctorStateMigrationDeclarationError(`Refused plugin migrations that do not match the immutable action order and authority declared by ${s.id}.`); if (e?.stateMigrations.length) { n?.(s.id); for (const t of e.stateMigrations) o.push({ pluginId: e.pluginId, channelIds: s.channels, trustedForDurableStores: isTrustedForDurableStores(s), migration: t }); continue; } if (declaresPluginDoctorContractSurface(s.doctorContract, "stateMigrations")) { if (e && Array.isArray(c) && c.length === 0) r?.(s.id); continue; } if (s.channels.length === 0 || s.origin === "bundled") { if (e) r?.(s.id); continue; } const u = loadLegacyChannelStateMigrationDetector(s, r); if (!u) { if (e && !s.setupSource) r?.(s.id); continue; } n?.(s.id); o.push({ pluginId: s.id, channelIds: s.channels, trustedForDurableStores: isTrustedForDurableStores(s), migration: definePluginDoctorMigrationFromPlans({ id: `${s.id}-legacy-channel-state`, label: `${s.id} legacy channel state`, resolvePlans: u }) }); } return o; } function resolvePluginDoctorStateMigrationRecords(e) { if (e.pluginIds?.length === 0) return []; return filterPluginDoctorStateMigrationRecords(filterPluginDoctorRecordsByScope((e.manifestRegistry ?? discoverConfigWidePluginManifestRegistry(e)).plugins, e.pluginIds), e.config, e.includeDisabled); } function filterPluginDoctorStateMigrationRecords(e, t, n = false) { const r = []; const i = normalizePluginsConfig(t?.plugins); for (const a of e) { if (deferredPluginMigrations.getStore()?.has(a.id)) continue; if (!n && a.channels.length > 0 && !shouldIncludeChannelSetupFeatureForConfig({ plugin: a, config: t, normalizedConfig: i })) continue; if (!n && a.origin !== "bundled" && !isActivatedManifestOwner({ plugin: a, normalizedConfig: i, rootConfig: t })) continue; r.push(a); } return r.toSorted((e, t) => e.id.localeCompare(t.id)); } /** * Read candidate-bundled migration identities without importing Doctor contract modules. * Installed plugin artifacts are outside the candidate and copied-state identity boundary; * candidate staging must bind them before their descriptors can authorize execution. */ function listPluginDoctorStateMigrationInventory(e) { const t = []; const n = []; const r = []; const i = []; const a = e?.candidateRoot ? resolveBundledPluginScanDir({ packageRoot: path.resolve(e.candidateRoot), runningFromBuiltArtifact: true }) : void 0; const o = e?.candidateRoot ? a && !areBundledPluginsDisabled(e.env) ? loadBundledPluginManifestRegistry({ env: { ...e.env, OPENCLAW_DISABLE_BUNDLED_SOURCE_OVERLAYS: "1" }, bundledRoot: a }).plugins : [] : loadBundledPluginManifestRegistry({ env: e?.env }).plugins; t.push(...o.map((e) => e.id)); for (const t of filterPluginDoctorStateMigrationRecords(o, e?.config)) { if (t.doctorContract?.resolveSessionStoreAgentIds === true) n.push(t.id); const e = t.doctorContract?.stateMigrations; if (Array.isArray(e)) { r.push(...e.map((e) => Object.assign({ pluginId: t.id }, e))); continue; } if (e === true) i.push(t.id); } return { knownPluginIds: t, sessionStoreOwnerPluginIds: n, descriptors: r, unresolvedPluginIds: i }; } /** Resolve the bundled action inventory plus every configured owner that is not identity-bound. */ function resolvePluginDoctorStateMigrationInventory(e) { const t = listPluginDoctorStateMigrationInventory(e); const n = e.config.plugins?.load?.paths?.some((e) => e.trim().length > 0) === true; let r = /* @__PURE__ */ new Set(); try { r = new Set(resolvePluginDoctorManifestRecords(e).filter((e) => e.origin !== "bundled").map((e) => e.id)); } catch {} const i = collectRelevantDoctorPluginIds(e.config); const a = t.knownPluginIds.filter((e) => !r.has(e)); const o = t.sessionStoreOwnerPluginIds.filter((e) => !r.has(e)); const s = t.descriptors.filter((e) => !r.has(e.pluginId)); const c = /* @__PURE__ */ new Set([ ...a, ...s.map((e) => e.pluginId), ...t.unresolvedPluginIds ]); const l = [ ...t.unresolvedPluginIds, ...r, ...i.filter((e) => !c.has(e)) ]; if (n) l.push("configured-load-paths"); return { knownPluginIds: a, sessionStoreOwnerPluginIds: o, descriptors: s, unresolvedPluginIds: [...new Set(l)].toSorted() }; } /** Freeze the live registry's selected migration actions before state mutation. */ function resolveLivePluginDoctorStateMigrationInventory(e) { const t = listPluginDoctorStateMigrationInventory(e); let n; try { n = resolvePluginDoctorStateMigrationRecords({ ...e, artifactPreservingReadOnly: true }); } catch (e) { return { ...t, unresolvedPluginIds: [], resolutionFailure: { code: "plugin-inventory-unavailable", message: `Could not resolve live plugin migration inventory: ${formatErrorMessage(e)}` } }; } const r = []; for (const e of n) { const t = e.doctorContract?.stateMigrations; if (Array.isArray(t)) { r.push(...t.map((t) => Object.assign({ pluginId: e.id }, t))); continue; } r.push(...loadPluginDoctorStateMigrationEntries([e]).map(({ pluginId: e, migration: t }) => Object.assign({ pluginId: e, id: t.id }, t.doctorOnly === true ? { doctorOnly: true } : {}, t.phase === "after-session-repair" ? { phase: t.phase } : {}))); } return { records: n, knownPluginIds: [.../* @__PURE__ */ new Set([...t.knownPluginIds, ...n.map((e) => e.id)])], sessionStoreOwnerPluginIds: n.filter((e) => e.doctorContract?.resolveSessionStoreAgentIds === true).map((e) => e.id), descriptors: r, unresolvedPluginIds: [] }; } function applyPluginDoctorCompatibilityMigrations(e, t) { return applyResolvedPluginDoctorCompatibilityMigrations(e, resolvePluginDoctorContracts({ ...t, config: t?.config ?? e, surface: "configRepair" }), { ...t, isDeferred: isPluginDoctorMigrationDeferred }); } /** Inspect plugin-owned migration paths before the updater captures its recovery set. */ async function preparePluginDoctorMigrationBackupResources(e) { return await withArtifactPreservingStateReads(() => withPluginSourceCaptureStorage({ stateDir: e.stateDir, placement: "temporary" }, async () => { const t = loadPluginDoctorStateMigrationEntries(resolvePluginDoctorStateMigrationRecords({ ...e, artifactPreservingReadOnly: true })); const { preparePluginDoctorMigrationResources: n } = await import("./doctor-migration-resources-BScT6Yx0.mjs"); return await n(t, e); })); } //#endregion export { collectRelevantDoctorPluginIds as _, isTrustedForDurableStores as a, listPluginDoctorSessionStoreAgentIds as c, preparePluginDoctorMigrationBackupResources as d, resolveLivePluginDoctorStateMigrationInventory as f, withDeferredPluginDoctorMigrations as g, resolvePluginDoctorStateMigrationRecords as h, isPluginDoctorMigrationDeferred as i, listPluginDoctorStateMigrationEntries as l, resolvePluginDoctorStateMigrationInventory as m, applyPluginDoctorCompatibilityMigrations as n, listPluginDoctorLegacyConfigRules as o, resolvePluginDoctorProviderRenames as p, collectDoctorConfigRepairPluginIds as r, listPluginDoctorSessionRouteStateOwners as s, PluginDoctorStateMigrationDeclarationError as t, loadPluginDoctorRecoveryCliRegistrar as u };