UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

408 lines (407 loc) • 17.2 kB
import { t as canAccess } from "./path-existence-Co7-GyVr.mjs"; import { r as isPathInside } from "./path-guards-TIjxtj6H.mjs"; import { r as resolveInstalledPluginIndexInstallOwner } from "./installed-plugin-index-install-owner-DoEpptXw.mjs"; import { a as readPluginMetadataStateRow } from "./bundled-discovery-state-Bb0zCvZZ.mjs"; import { p as resolvePluginNpmProjectsDir, s as resolveDefaultPluginNpmDir } from "./install-paths-Bwm0P5EG.mjs"; import { a as createPluginInstallRecordMap, i as copyPluginInstallRecordMap, o as getPluginInstallRecordMapEntry, u as setPluginInstallRecordMapEntry } from "./installed-plugin-index-row-CdwQuK63.mjs"; import { a as markRetainedManagedNpmInstall, c as restoreRetainedManagedNpmInstallMarkers, d as RETAINED_MANAGED_NPM_KEEP_FILES_REASON, n as clearRetainedManagedNpmInstallMarker, o as resolveRetainedManagedNpmInstallMarkerPath, s as resolveRetainedManagedNpmInstallPackageInfo } from "./managed-npm-retention-1zEp6KL9.mjs"; import { r as loadInstalledPluginIndexInstallRecords } from "./installed-plugin-index-record-reader-B-7uGQZ9.mjs"; import { b as resolveConfigWriteAfterWrite } from "./runtime-snapshot-WbwbY5b7.mjs"; import { n as composeConfigWriteAssertions } from "./write-authority-l37tp55r.mjs"; import { n as readPersistedInstalledPluginIndex } from "./installed-plugin-index-store-fgfm3NWB.mjs"; import { t as ConfigWritePostCommitError } from "./io.write-errors-CuPAqPbq.mjs"; import { C as copyRuntimeConfigWriteApplication, s as readConfigFileSnapshot } from "./io.runtime-DsJ2dLCQ.mjs"; import { o as transformConfigFileWithRetry, r as replaceConfigFile } from "./mutate-DhAOi0-2.mjs"; import "./config-CMA-J084.mjs"; import { s as withPluginLifecycleLeaseAsync } from "./plugin-lifecycle-lease-CXjHGDEI.mjs"; import { a as restorePersistedInstalledPluginIndexIfCurrent } from "./installed-plugin-index-store-write-D9fWnpon.mjs"; import { a as writePersistedInstalledPluginIndexInstallRecordsWithLease, i as withoutPluginInstallRecords, t as PLUGIN_INSTALLS_CONFIG_PATH } from "./installed-plugin-index-records-MNCNSlg8.mjs"; import { n as realpathViaExistingPrefixSync } from "./path-containment-DaLrXKK_.mjs"; import { a as recordPluginPackageUninstallPlan, r as planPluginUninstall } from "./uninstall-jiiZcP78.mjs"; import fs from "node:fs"; import path from "node:path"; import { isDeepStrictEqual } from "node:util"; //#region src/plugins/install-record-commit.ts const retainedPublications = /* @__PURE__ */ new WeakMap(); /** Recorded disposition of this failure, not authority to activate or overwrite a newer index. */ function getRetainedPluginInstallPublication(e) { return e instanceof Error ? retainedPublications.get(e) : void 0; } /** Find pending install records that match the base config and can be stripped as unchanged. */ function unchangedPendingPluginInstallRecordIds(e, t) { const n = e.plugins?.installs ?? {}; return Object.entries(t.plugins?.installs ?? {}).filter(([e, t]) => isDeepStrictEqual(getPluginInstallRecordMapEntry(n, e), t)).map(([e]) => e); } /** Remove pending plugin install records from config, optionally only for selected ids. */ function stripPendingPluginInstallRecords(e, t) { if (!t) return withoutPluginInstallRecords(e); const n = new Set(t); if (n.size === 0 || !e.plugins?.installs) return e; const r = createPluginInstallRecordMap(); for (const [t, i] of Object.entries(e.plugins.installs)) if (!n.has(t)) setPluginInstallRecordMapEntry(r, t, i); if (Object.keys(r).length === 0) return withoutPluginInstallRecords(e); return { ...e, plugins: { ...e.plugins, installs: r } }; } function mergeAfterWrite(e, t) { if (t === void 0) return e; return copyRuntimeConfigWriteApplication(e, { ...e, afterWrite: t }); } function isMissingInstallPathError(e) { const t = e.code; return t === "ENOENT" || t === "ENOTDIR"; } function installPathsOverlap(e, t) { const n = realpathViaExistingPrefixSync(path.resolve(e)); const r = realpathViaExistingPrefixSync(path.resolve(t)); if (!n || !r) return true; return n === r || isPathInside(n, r) || isPathInside(r, n); } function resolveRetainedManagedNpmInstallMarkerTarget(e) { if (e.previousRecord?.source !== "npm") return null; const t = e.previousRecord.installPath?.trim(); const n = e.nextRecord?.installPath?.trim(); if (!t) return null; if (e.nextRecord && (!n || installPathsOverlap(t, n))) return null; if (e.nextRecord?.source !== "npm") { const e = resolveRetainedManagedNpmInstallPackageInfo(t); if (!e) return null; try { const n = path.resolve(resolveDefaultPluginNpmDir()); const r = fs.realpathSync(n); const i = path.resolve(e.projectRoot); const a = fs.realpathSync(i); const o = fs.realpathSync(t); if (path.relative(n, i) !== path.relative(r, a) || path.relative(i, path.resolve(t)) !== path.relative(a, o)) return null; if (a === r) return t; const s = fs.realpathSync(resolvePluginNpmProjectsDir(r)); return path.dirname(a) === s ? t : null; } catch (e) { if (isMissingInstallPathError(e)) return null; throw e; } } const r = createPluginInstallRecordMap(); setPluginInstallRecordMapEntry(r, e.pluginId, e.previousRecord); const i = planPluginUninstall(recordPluginPackageUninstallPlan({ config: { plugins: { installs: r } }, pluginId: e.pluginId, deleteFiles: true }, { runtimePluginIds: [] })); if (!i.ok || !i.directoryRemoval || i.directoryRemoval.cleanup?.kind !== "npm") return null; return t; } function resolveNpmInstallRecordPackageName(e) { if (e.source !== "npm" || !e.installPath?.trim()) return null; return resolveRetainedManagedNpmInstallPackageInfo(e.installPath)?.packageName ?? null; } function findReplacementNpmRecordForRemovedRecord(e) { const t = resolveNpmInstallRecordPackageName(e.previousRecord); if (!t) return null; for (const n of Object.values(e.nextInstallRecords)) if (resolveNpmInstallRecordPackageName(n) === t) return n; return null; } async function markRetiredManagedNpmInstallRecords(e) { const t = Object.values(e.nextInstallRecords).flatMap((e) => { const t = e.installPath?.trim(); return t ? [t] : []; }); const markRetiredInstall = async (n, r, i) => { const a = r?.installPath?.trim(); if (a && t.some((e) => installPathsOverlap(a, e))) return; const o = resolveRetainedManagedNpmInstallMarkerTarget({ pluginId: n, previousRecord: r, nextRecord: i }); if (!o) return; const s = resolveRetainedManagedNpmInstallMarkerPath(o); const c = await canAccess(s); if (await markRetainedManagedNpmInstall({ packageDir: o, pluginId: n, assertCurrent: e.prepareEffect, reason: i?.source === "npm" ? "replaced-by-managed-npm-generation-update" : i ? "replaced-by-plugin-source-change" : "removed-managed-npm-install-retained" }) && !c) e.createdMarkerPaths.push(s); }; for (const [t, n] of Object.entries(e.nextInstallRecords)) await markRetiredInstall(t, getPluginInstallRecordMapEntry(e.previousInstallRecords, t), n); for (const [t, n] of Object.entries(e.previousInstallRecords)) { if (getPluginInstallRecordMapEntry(e.nextInstallRecords, t)) continue; await markRetiredInstall(t, n, findReplacementNpmRecordForRemovedRecord({ previousRecord: n, nextInstallRecords: e.nextInstallRecords }) ?? void 0); } } async function clearActiveRetainedManagedNpmInstallMarkers(e, t, n) { for (const r of Object.values(e)) { if (r.source !== "npm" || !r.installPath?.trim()) continue; let e; try { e = resolveRetainedManagedNpmInstallMarkerPath(r.installPath); } catch { continue; } let i; try { i = await fs.promises.readFile(e, "utf8"); } catch (e) { if (e.code === "ENOENT") continue; throw e; } t.push({ markerPath: e, contents: i }); await clearRetainedManagedNpmInstallMarker(r.installPath, n); } } /** Recheck staged enablement at its config writer, after any intervening plugin update. */ async function assertPluginConfigActivationConsent(e) { const t = e.nextInstallRecords ?? await loadInstalledPluginIndexInstallRecords(); if (Object.keys(t).length === 0) return; const { resolvePluginMetadataSnapshot: n } = await import("./plugin-metadata-snapshot-PjL6_oGE.mjs"); const { resolvePluginCapabilityConsent: r } = await import("./capability-consent-DtN_u18Y.mjs"); const { resolvePluginControlPlaneWorkspace: i } = await import("./control-plane-workspace-B4roGk11.mjs"); const a = await readConfigFileSnapshot(); const metadataForConfig = (e) => n({ config: e, allowCurrent: false, workspaceDir: i({ config: e }).workspaceDir }); const o = metadataForConfig(a.config); const s = metadataForConfig(e.nextConfig); const c = new Set(o.index.plugins.filter((e) => a.valid && e.enabled).map((e) => e.pluginId)); for (const n of s.index.plugins) { if (!n.enabled || n.origin === "bundled") continue; const i = resolveInstalledPluginIndexInstallOwner(n) ?? n.pluginId; const a = t[i]; const o = e.previousInstallRecords?.[i]; if (e.previousInstallRecords !== void 0 && (!o || a?.acceptedSurface !== void 0) && !isDeepStrictEqual(o, a) || !c.has(n.pluginId)) await r({ config: e.nextConfig, pluginId: n.pluginId, metadata: s }); } } async function commitPluginInstallRecordsWithWriter(e) { return await withPluginLifecycleLeaseAsync({}, async (t) => { const n = t.assertOwned; const r = composeConfigWriteAssertions(t.assertCurrent, e.writeOptions?.assertConfigPathForWrite); const prepareEffect = async () => { await n(); r(); }; let i; const a = []; const o = []; try { const n = { filePath: t.databasePath }; const s = await e.prepareInstallRecords(n); await e.beforePersistentEffect?.(); await prepareEffect(); i = await writePersistedInstalledPluginIndexInstallRecordsWithLease(s.nextInstallRecords, { ...n, config: e.nextConfig, lease: t, assertCurrent: e.writeOptions?.assertConfigPathForWrite, onAcknowledged: (e) => { i = e; } }); if (e.recheckStagedActivation) { const t = await readPersistedInstalledPluginIndex(n); if (!t || t.plugins.some((e) => e.enabled && e.origin !== "bundled")) await assertPluginConfigActivationConsent({ nextConfig: e.nextConfig, previousInstallRecords: s.previousInstallRecords, nextInstallRecords: s.nextInstallRecords }); } await markRetiredManagedNpmInstallRecords({ previousInstallRecords: s.previousInstallRecords, nextInstallRecords: s.nextInstallRecords, createdMarkerPaths: a, prepareEffect }); await clearActiveRetainedManagedNpmInstallMarkers(s.nextInstallRecords, o, prepareEffect); const c = copyRuntimeConfigWriteApplication(e.writeOptions, { ...e.writeOptions, assertConfigPathForWrite: r, beforeCommit: async () => { await e.writeOptions?.beforeCommit?.(); await e.beforePersistentEffect?.(); await prepareEffect(); }, unsetPaths: [...e.writeOptions?.unsetPaths ?? [], Array.from(PLUGIN_INSTALLS_CONFIG_PATH)] }); return { committed: await e.commit(e.nextConfig, c), indexWrite: i }; } catch (e) { if (i && e instanceof ConfigWritePostCommitError && e.rollbackStatus !== "restored") { try { await n(); const r = await readPluginMetadataStateRow("installed-index", { path: t.databasePath }); await n(); retainedPublications.set(e, { current: r?.value_json === i.mutation.after.value_json }); } catch (t) { const n = new AggregateError([e, t], "Config publication could not be rolled back and its package records could not be inspected.", { cause: t }); retainedPublications.set(n, { current: false }); throw n; } throw e; } await n(); const r = [e]; const s = i; if (s) try { if (await restorePersistedInstalledPluginIndexIfCurrent(s.previous, s.revision, { filePath: t.databasePath, lease: t })) await restoreRetainedManagedNpmInstallMarkers({ clearedMarkerSnapshots: o, createdMarkerPaths: a, assertCurrent: n }); } catch (e) { await n(); r.push(e); } if (r.length > 1) throw new AggregateError(r, `${String(e)}; Failed to commit plugin install records and could not roll back tentative plugin state`, { cause: e }); throw e; } }); } /** Persist plugin install records and commit the matching config update to disk. */ async function commitPluginInstallRecordsWithConfig(e) { const t = await commitPluginInstallRecordsWithWriter({ prepareInstallRecords: async (t) => ({ previousInstallRecords: e.previousInstallRecords ?? await loadInstalledPluginIndexInstallRecords(t), nextInstallRecords: e.nextInstallRecords }), nextConfig: e.nextConfig, beforePersistentEffect: e.beforePersistentEffect, ...e.writeOptions ? { writeOptions: e.writeOptions } : {}, commit: async (t, n) => { return await replaceConfigFile({ nextConfig: t, ...e.baseHash !== void 0 ? { baseHash: e.baseHash } : {}, ...n ? { writeOptions: n } : {} }); } }); return { ...t.indexWrite, configWrite: t.committed }; } /** Persist plugin install records without rewriting the user-authored config file. */ async function commitPluginInstallRecordsOnly(e) { return (await commitPluginInstallRecordsWithWriter({ beforePersistentEffect: e.beforePersistentEffect, prepareInstallRecords: async (t) => ({ previousInstallRecords: e.previousInstallRecords ?? await loadInstalledPluginIndexInstallRecords(t), nextInstallRecords: e.nextInstallRecords }), nextConfig: e.nextConfig, commit: async () => { await e.verifyConfigFresh?.(); } })).indexWrite; } /** Commit config while migrating any pending install records into the install index. */ async function commitConfigWriteWithPendingPluginInstalls(e) { const t = e.sourceConfig?.plugins?.installs ?? {}; const n = e.sourceConfig ? stripPendingPluginInstallRecords(e.nextConfig, unchangedPendingPluginInstallRecordIds(e.nextConfig, { plugins: { installs: t } })) : e.nextConfig; if (Object.keys(t).length === 0 && Object.keys(n.plugins?.installs ?? {}).length === 0) return { ...await withPluginLifecycleLeaseAsync({}, async (t) => { await assertPluginConfigActivationConsent({ nextConfig: e.nextConfig }); await t.assertOwned(); return await e.commit(e.nextConfig, copyRuntimeConfigWriteApplication(e.writeOptions, { ...e.writeOptions, assertConfigPathForWrite: composeConfigWriteAssertions(e.writeOptions?.assertConfigPathForWrite, t.assertCurrent), beforeCommit: async () => { await e.writeOptions?.beforeCommit?.(); await t.assertOwned(); } })); }), movedInstallRecords: false }; const r = n.plugins?.installs ?? {}; return { ...(await commitPluginInstallRecordsWithWriter({ prepareInstallRecords: async (e) => { const n = await loadInstalledPluginIndexInstallRecords(e); const i = copyPluginInstallRecordMap(t); for (const e of [n, r]) for (const [t, n] of Object.entries(e)) setPluginInstallRecordMapEntry(i, t, n); return { previousInstallRecords: n, nextInstallRecords: i }; }, nextConfig: withoutPluginInstallRecords(e.nextConfig), recheckStagedActivation: true, ...e.writeOptions ? { writeOptions: e.writeOptions } : {}, commit: e.commit })).committed, movedInstallRecords: true }; } /** Replace the config file after moving pending plugin install records into the install index. */ async function commitConfigWithPendingPluginInstalls(e) { return await commitConfigWriteWithPendingPluginInstalls({ nextConfig: e.sourceConfig ?? e.nextConfig, ...e.writeOptions ? { writeOptions: e.writeOptions } : {}, commit: async (t, n) => { return await replaceConfigFile({ ...e.sourceConfig ? { sourceConfig: t } : { nextConfig: t }, ...e.baseHash !== void 0 ? { baseHash: e.baseHash } : {}, ...n ? { writeOptions: n } : {} }); } }); } /** Transform config with retry support while preserving plugin install index consistency. */ async function transformConfigWithPendingPluginInstalls(e) { const commit = async ({ nextConfig: t, snapshot: n, baseHash: r, writeOptions: i }) => { const a = e.afterWrite ?? e.writeOptions?.afterWrite; const o = await commitConfigWriteWithPendingPluginInstalls({ nextConfig: t, sourceConfig: n.sourceConfig, ...i ? { writeOptions: mergeAfterWrite(i, e.afterWrite) } : {}, commit: async (e, t) => { return await replaceConfigFile({ nextConfig: e, snapshot: n, writeOptions: t ?? {}, ...r !== void 0 ? { baseHash: r } : {} }); } }); const s = resolveConfigWriteAfterWrite(a); return { config: o.nextConfig, persistedHash: o.persistedHash, persistedSourceConfig: o.persistedSourceConfig, afterWrite: s }; }; return await withPluginLifecycleLeaseAsync({}, async () => { return await transformConfigFileWithRetry({ ...e, commit }); }); } //#endregion export { stripPendingPluginInstallRecords as a, getRetainedPluginInstallPublication as i, commitPluginInstallRecordsOnly as n, transformConfigWithPendingPluginInstalls as o, commitPluginInstallRecordsWithConfig as r, commitConfigWithPendingPluginInstalls as t };