UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

324 lines (323 loc) • 15.2 kB
import { c as resolveUserPath } from "./home-dir-EKmgmdPG.mjs"; import { t as safeParseJson } from "./json-coercion-CaJLaav-.mjs"; import { g as isPluginCandidateInstallOwnerAmbiguous, y as resolvePluginCandidateInstallOwner } from "./discovery-DvJYrQFY.mjs"; import { o as isGatewayPluginMetadataSnapshotActive } from "./current-plugin-metadata-state-BmYo9Q7A.mjs"; import { r as resolveInstalledPluginIndexInstallOwner, t as isInstalledPluginIndexInstallOwnerAmbiguous } from "./installed-plugin-index-install-owner-DoEpptXw.mjs"; import { a as executeSqliteQueryTakeFirstSync, s as getNodeSqliteKysely, t as compileSqliteQueryBindings } from "./kysely-sync-YJo2lmGV.mjs"; import { a as resolveCompatibilityHostVersion } from "./version-GlxUMdxI.mjs"; import { r as cloneEnvWithPlatformSemantics } from "./config-env-vars-ByeGN-9N.mjs"; import { v as readOpenClawStateLease } from "./openclaw-state-db-existing-schema-C1h5v6Xh.mjs"; import { r as captureOpenClawStateWorkerContext } from "./openclaw-state-worker-context-DAKL_dnZ.mjs"; import { r as resolveActivePluginInstallRoots } from "./install-root-context-CeM6pu6m.mjs"; import { t as clearPluginMetadataLifecycleCaches } from "./plugin-metadata-lifecycle-C9EqhiS5.mjs"; import { n as hashStableJson } from "./installed-plugin-index-hash-BfBbMPjv.mjs"; import { b as resolveInstalledPluginIndexPolicyHash, c as refreshInstalledPluginIndex, l as INSTALLED_PLUGIN_INDEX_WARNING, m as hasMissingConfigPathActivationMetadata, p as extractPluginInstallRecordsFromInstalledPluginIndex, r as hasInstalledPluginIndexWorkspaceScopeMismatch, s as projectInstalledPluginIndexPolicy, y as resolveCompatRegistryVersion } from "./installed-plugin-index-DYqse_gE.mjs"; import { l as serializePluginInstallRecordMap, r as INSTALLED_PLUGIN_INDEX_STATE_KEY, s as inspectPluginInstallRecordMap } from "./installed-plugin-index-row-CdwQuK63.mjs"; import { n as resolveInstalledPluginIndexStateDatabaseOptions, r as resolveInstalledPluginIndexStorePath, t as legacyInstalledPluginIndexUnsupportedMessage } from "./installed-plugin-index-store-path-VYnur1Rc.mjs"; import { o as clearLoadInstalledPluginIndexInstallRecordsCache, t as findForeignManagedNpmInstallRecordPluginIds } from "./installed-plugin-index-record-reader-B-7uGQZ9.mjs"; import { l as runOpenClawStateWriteTransaction } from "./openclaw-state-db-ARhwdPJg.mjs"; import { t as preservePluginSourceAdmissions } from "./installed-plugin-index-source-admissions-Dc9OUryQ.mjs"; import { r as readPersistedInstalledPluginIndexSync, t as parseInstalledPluginIndex } from "./installed-plugin-index-store-fgfm3NWB.mjs"; import { n as hasMissingInstalledPluginOwnerMetadata } from "./installed-plugin-package-ownership-BAh5IZ9-.mjs"; import { c as PLUGIN_LIFECYCLE_LEASE_IDENTITY, s as withPluginLifecycleLeaseAsync } from "./plugin-lifecycle-lease-CXjHGDEI.mjs"; import { existsSync } from "node:fs"; import { isDeepStrictEqual } from "node:util"; //#region src/plugins/installed-plugin-index-store-write.ts /** Writes, restores, and refreshes the installed plugin index in the state database. */ function readInstalledPluginIndexRow(e) { return executeSqliteQueryTakeFirstSync(e, getNodeSqliteKysely(e).selectFrom("config_machine_state").select([ "state_key", "value_json", "updated_at_ms" ]).where("state_key", "=", INSTALLED_PLUGIN_INDEX_STATE_KEY)); } function parseInstalledPluginIndexRow(e) { if (!e) return; const t = safeParseJson(e.value_json); if (!t || typeof t !== "object" || typeof t.revision !== "number") return; return t; } function assertWritableInstalledPluginIndexStoreOptions(e) { if (e.filePath?.endsWith(".json")) throw new Error(legacyInstalledPluginIndexUnsupportedMessage(e.filePath)); } function preparePersistedInstalledPluginIndex(e) { return { ...e, warning: INSTALLED_PLUGIN_INDEX_WARNING }; } function resolveNextInstalledPluginIndexRevision(e) { return Math.max(Date.now(), (e ?? 0) + 1); } function writePersistedInstalledPluginIndexRow(e, t, n) { const r = { version: t.version, warning: t.warning ?? "DO NOT EDIT. This file is generated by OpenClaw from plugin manifests, install records, and config policy. Use `openclaw plugins registry --refresh`, `openclaw plugins install/update/uninstall`, or `openclaw plugins enable/disable` instead.", hostContractVersion: t.hostContractVersion, compatRegistryVersion: t.compatRegistryVersion, migrationVersion: t.migrationVersion, policyHash: t.policyHash, generatedAtMs: t.generatedAtMs, ...t.workspaceDir !== void 0 ? { workspaceDir: t.workspaceDir } : {}, ...t.refreshReason ? { refreshReason: t.refreshReason } : {}, installRecords: JSON.parse(serializePluginInstallRecordMap(t.installRecords)), plugins: t.plugins.map((e) => { const t = resolveInstalledPluginIndexInstallOwner(e); return { ...e, ...t ? { installOwner: t } : {}, ...isInstalledPluginIndexInstallOwnerAmbiguous(e) ? { installOwnerAmbiguous: true } : {} }; }), diagnostics: t.diagnostics.map((e) => e.level === "info" && e.code === "explicit-config-plugin-selection" ? { ...e, level: "warn" } : e) }; const i = JSON.stringify({ revision: n, index: r }); const { compiled: a, bind: o } = compileSqliteQueryBindings(() => getNodeSqliteKysely(e).insertInto("config_machine_state").values({ state_key: INSTALLED_PLUGIN_INDEX_STATE_KEY, value_json: i, updated_at_ms: n }).onConflict((e) => e.column("state_key").doUpdateSet((e) => ({ value_json: e.ref("excluded.value_json"), updated_at_ms: e.ref("excluded.updated_at_ms") })))); e.prepare(a.sql).run(...o()); return { state_key: INSTALLED_PLUGIN_INDEX_STATE_KEY, value_json: i, updated_at_ms: n }; } function writePersistedInstalledPluginIndexToSqlite(e, t, n, r = false) { assertWritableInstalledPluginIndexStoreOptions(t); const i = preparePersistedInstalledPluginIndex(e); return runOpenClawStateWriteTransaction(({ db: e, path: t }) => { const a = readInstalledPluginIndexRow(e); const o = parseInstalledPluginIndexRow(a); const s = o ? parseInstalledPluginIndex(o.index) : null; if (o && !s) { const e = o.index?.installRecords; if (e === void 0 || inspectPluginInstallRecordMap(e).status === "invalid") throw new Error("Persisted plugin install records are invalid. Repair the state before writing plugin installation metadata."); } n.assertOwnedInTransaction(e); if (r) preservePluginSourceAdmissions(s, i); const c = resolveNextInstalledPluginIndexRevision(o ? o.revision : null); const l = writePersistedInstalledPluginIndexRow(e, i, c); n.assertOwnedInTransaction(e, "commit"); return { previous: s, revision: c, mutation: { databasePath: t, before: a ?? null, after: l } }; }, { ...resolveInstalledPluginIndexStateDatabaseOptions(t), database: t.database }); } /** Merge prepared facts against the worker's current row, never the caller's old inventory. */ function publishPluginSourceAdmissionInDatabase(e, t) { if (readOpenClawStateLease(e, PLUGIN_LIFECYCLE_LEASE_IDENTITY)) return false; const n = parseInstalledPluginIndexRow(readInstalledPluginIndexRow(e)); const r = n ? parseInstalledPluginIndex(n.index) : null; const i = r?.plugins.find((e) => e.pluginId === t.pluginId); if (!n || !r || !i || i.rootDir !== t.rootDir || i.installRecordHash !== t.installRecordHash) return false; if (isDeepStrictEqual(i.sourceAdmissions?.[t.key], t.receipt)) return true; i.sourceAdmissions = { ...i.sourceAdmissions, [t.key]: t.receipt }; writePersistedInstalledPluginIndexRow(e, r, resolveNextInstalledPluginIndexRevision(n.revision)); return true; } function clearPersistedInstalledPluginIndexCaches() { if (!isGatewayPluginMetadataSnapshotActive()) clearPluginMetadataLifecycleCaches(); clearLoadInstalledPluginIndexInstallRecordsCache(); } async function writePersistedInstalledPluginIndex(e, t = {}) { assertWritableInstalledPluginIndexStoreOptions(t); const n = { ...t, env: cloneEnvWithPlatformSemantics(resolveInstalledPluginIndexStateDatabaseOptions(t).env ?? t.env ?? process.env), filePath: resolveInstalledPluginIndexStorePath(t) }; return await withPluginLifecycleLeaseAsync(resolveInstalledPluginIndexStateDatabaseOptions(n), async (t) => { await runInstalledPluginIndexWrite(n, t, (t, n) => t.execute({ type: "plugins.metadata.index.write", input: { identity: n, index: e } })); return n.filePath; }); } /** Restore a snapshot only while the caller's tentative write is still current. */ async function restorePersistedInstalledPluginIndexIfCurrent(e, t, n) { const { lease: r, ...i } = n; assertWritableInstalledPluginIndexStoreOptions(i); if (!existsSync(resolveInstalledPluginIndexStorePath(i))) return false; return runInstalledPluginIndexWrite(i, r, (n, r) => n.execute({ type: "plugins.metadata.index.restore", input: { identity: r, index: e, expectedRevision: t } })); } function restorePersistedInstalledPluginIndexInDatabase(e, t, n, r) { return runOpenClawStateWriteTransaction(({ db: n }) => { r.assertOwnedInTransaction(n); const i = parseInstalledPluginIndexRow(readInstalledPluginIndexRow(n) ?? null ?? void 0); const a = i ? i.revision : null; if (a !== t) { r.assertOwnedInTransaction(n, "commit"); return false; } if (e) writePersistedInstalledPluginIndexRow(n, preparePersistedInstalledPluginIndex(e), resolveNextInstalledPluginIndexRevision(a)); else { const { compiled: e, bind: t } = compileSqliteQueryBindings(() => getNodeSqliteKysely(n).deleteFrom("config_machine_state").where("state_key", "=", INSTALLED_PLUGIN_INDEX_STATE_KEY)); n.prepare(e.sql).run(...t()); } r.assertOwnedInTransaction(n, "commit"); return true; }, { database: n }); } async function runInstalledPluginIndexWrite(e, t, n, r, i) { const a = captureOpenClawStateWorkerContext(resolveInstalledPluginIndexStateDatabaseOptions(e)); const assertAuthority = () => { t.assertCurrent(); r?.(); }; assertAuthority(); const { runWithOpenClawStateLeaseWorker: o } = await import("./openclaw-state-lease-worker-operation-CWjSct81.mjs"); const s = await o(t.stateLease, a, n, { assertCurrent: () => t.assertCurrent(), beforeTransaction: assertAuthority, beforeCommit: assertAuthority }); try { i?.(s); } finally { clearPersistedInstalledPluginIndexCaches(); } assertAuthority(); return s; } function hasCompletePolicyRefreshProjection(e, t, n) { const r = new Set(e.plugins.map((e) => e.pluginId)); if (t?.some((e) => !r.has(e))) return false; const i = new Set(e.plugins.map(resolveInstalledPluginIndexInstallOwner)); return Object.entries(e.installRecords).every(([e, t]) => { if (i.has(e)) return true; const r = t.installPath?.trim() || t.sourcePath?.trim(); return !r || !existsSync(resolveUserPath(r, n)); }); } function canRefreshPersistedPolicyState(e, t) { if (!e || t.reason !== "policy-changed") return false; if ((t.diagnostics?.length ?? 0) > 0 || e.diagnostics.some((e) => e.code === "workspace-scope-omitted") || hasInstalledPluginIndexWorkspaceScopeMismatch(e, t.workspaceDir)) return false; const n = t.env ?? process.env; if (e.version !== 1 || e.hostContractVersion !== resolveCompatibilityHostVersion(n) || e.compatRegistryVersion !== resolveCompatRegistryVersion() || e.migrationVersion !== 1 || hasMissingConfigPathActivationMetadata(e) || hasMissingInstalledPluginOwnerMetadata(e, n)) return false; if (t.installRecords && hashStableJson(t.installRecords) !== hashStableJson(e.installRecords ?? {})) return false; return hasCompletePolicyRefreshProjection(e, t.policyPluginIds, n); } function refreshPersistedPolicyState(e, t) { const n = projectInstalledPluginIndexPolicy({ plugins: e.plugins, config: t.config, env: t.env ?? process.env }); return { ...e, policyHash: resolveInstalledPluginIndexPolicyHash(t.config, t.env), generatedAtMs: (t.now?.() ?? /* @__PURE__ */ new Date()).getTime(), refreshReason: t.reason, plugins: n }; } function resolveRefreshedPersistedInstalledPluginIndex(e) { const t = e.reason === "policy-changed" || !e.installRecords ? readPersistedInstalledPluginIndexSync(e) : null; if (canRefreshPersistedPolicyState(t, e)) return refreshPersistedPolicyState(t, e); if (e.reason === "manual" && !e.installRecords) { const n = findForeignManagedNpmInstallRecordPluginIds(extractPluginInstallRecordsFromInstalledPluginIndex(t), e); if (n.length > 0) throw new Error(`Plugin registry refresh cannot verify npm install ownership outside the selected state directory: ${n.join(", ")}. Reinstall copied plugins in this state directory, then run \`openclaw plugins registry --refresh\` again.`); } return refreshInstalledPluginIndex({ ...e, installRecords: e.installRecords ?? extractPluginInstallRecordsFromInstalledPluginIndex(t) }); } async function refreshPersistedInstalledPluginIndex(e) { return (await refreshPersistedInstalledPluginIndexWithReceipt(e)).index; } async function refreshPersistedInstalledPluginIndexWithReceipt(e) { const { lease: t, now: n, assertCurrent: r, onAcknowledged: i } = e; assertWritableInstalledPluginIndexStoreOptions(e); const a = resolveInstalledPluginIndexStateDatabaseOptions(e); const o = cloneEnvWithPlatformSemantics(a.env ?? e.env ?? process.env); const s = { ...a, env: o }; const c = { env: o, filePath: resolveInstalledPluginIndexStorePath(e) }; const prepareCandidates = (e) => e.map((e) => ({ candidate: e, installOwner: resolvePluginCandidateInstallOwner(e), ambiguous: isPluginCandidateInstallOwnerAmbiguous(e) })); const l = { config: e.config, workspaceDir: e.workspaceDir, stateDir: e.stateDir, filePath: e.filePath, pluginIndexFilePath: e.pluginIndexFilePath, installRecords: e.installRecords, candidates: e.candidates && prepareCandidates(e.candidates), diagnostics: e.diagnostics, discovery: e.discovery && { candidates: prepareCandidates(e.discovery.candidates), diagnostics: e.discovery.diagnostics }, reason: e.reason, policyPluginIds: e.policyPluginIds, artifactPreservingReadOnly: e.artifactPreservingReadOnly, env: { ...o }, installRoots: resolveActivePluginInstallRoots(o), ...n ? { nowMs: n().getTime() } : {} }; const refresh = async (e) => { return await runInstalledPluginIndexWrite(c, e, (e, t) => e.execute({ type: "plugins.metadata.index.refresh", input: { identity: t, prepared: l } }), r, i); }; return t ? refresh(t) : withPluginLifecycleLeaseAsync(s, refresh); } function refreshPersistedInstalledPluginIndexWithLeaseSync(e) { const { lease: t, ...n } = e; const r = resolveRefreshedPersistedInstalledPluginIndex(n); const i = writePersistedInstalledPluginIndexToSqlite(r, n, t, true); clearPersistedInstalledPluginIndexCaches(); return { ...i, index: r }; } //#endregion export { restorePersistedInstalledPluginIndexIfCurrent as a, writePersistedInstalledPluginIndexToSqlite as c, refreshPersistedInstalledPluginIndexWithReceipt as i, refreshPersistedInstalledPluginIndex as n, restorePersistedInstalledPluginIndexInDatabase as o, refreshPersistedInstalledPluginIndexWithLeaseSync as r, writePersistedInstalledPluginIndex as s, publishPluginSourceAdmissionInDatabase as t };