UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

9 lines • 25.2 kB
import{c as resolveUserPath}from"./home-dir-DEN5DisQ.mjs";import{t as safeParseJson}from"./json-coercion-DNNwq4_v.mjs";import{F as resolvePluginCandidateInstallOwner,M as isPluginCandidateInstallOwnerAmbiguous}from"./discovery-Bo4UPPd9.mjs";import{c as isGatewayPluginMetadataSnapshotActive,t as clearPluginMetadataLifecycleCaches}from"./plugin-metadata-lifecycle-Bdt91XXL.mjs";import{r as resolveInstalledPluginIndexInstallOwner,t as isInstalledPluginIndexInstallOwnerAmbiguous}from"./installed-plugin-index-install-owner-iRSOvGid.mjs";import{a as executeSqliteQueryTakeFirstSync,s as getNodeSqliteKysely,t as compileSqliteQueryBindings}from"./kysely-sync-R08Pt8qn.mjs";import{a as resolveCompatibilityHostVersion}from"./version-DrZ9Nfde.mjs";import{Fn as object,Nt as array,xn as literal}from"./schemas-DuCQi-Qb.mjs";import{s as resolveOpenClawStateSqlitePath}from"./openclaw-state-db.paths-CbgXfEg1.mjs";import{r as cloneEnvWithPlatformSemantics}from"./config-env-vars-DCDGIBtT.mjs";import{b as readOpenClawStateLease}from"./openclaw-state-db-transaction-B9Gj3UJV.mjs";import{r as captureOpenClawStateWorkerContext}from"./openclaw-state-worker-context-Dx8YjqO2.mjs";import{r as resolveActivePluginInstallRoots}from"./install-root-context-CqAZmMOW.mjs";import{n as hashStableJson,t as hashJson}from"./installed-plugin-index-hash-BPd0uDLE.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-B04a42mO.mjs";import{n as resolveInstalledPluginIndexStateDatabaseOptions,r as resolveInstalledPluginIndexStorePath,t as legacyInstalledPluginIndexUnsupportedMessage}from"./installed-plugin-index-store-path-Bf4Iuysu.mjs";import{o as serializePluginInstallRecordMap,r as getPluginInstallRecordMapEntry}from"./plugin-install-record-map-BULaY3LO.mjs";import{t as INSTALLED_PLUGIN_INDEX_STATE_KEY}from"./plugin-metadata-state.kernel-B4HP-_P3.mjs";import"./installed-plugin-index-row-DASEpCi8.mjs";import{n as inspectPersistedInstalledPluginIndexInstallRecords}from"./installed-plugin-index-record-state-Dlesa-xK.mjs";import{o as clearLoadInstalledPluginIndexInstallRecordsCache,t as findForeignManagedNpmInstallRecordPluginIds}from"./installed-plugin-index-record-reader-rJXlMUQ8.mjs";import{l as runOpenClawStateWriteTransaction}from"./openclaw-state-db-BlgxYkYw.mjs";import{t as preservePluginSourceAdmissions}from"./installed-plugin-index-source-admissions-Dj2tY3HV.mjs";import{i as readPersistedInstalledPluginIndexSync,t as parseInstalledPluginIndex}from"./installed-plugin-index-store-CP6OETa6.mjs";import{n as hasMissingInstalledPluginOwnerMetadata}from"./installed-plugin-package-ownership-Dw9mtnM_.mjs";import{t as pluginCohortPublicationContext}from"./update-plugin-cohort-context-CV-FghMb.mjs";import{D as pluginSourceSnapshotArtifactPath,E as PluginSourceSnapshotDescriptorSchema,m as recordPluginCohortIndexPublicationInDatabase}from"./update-run-recovery-store-k_2_R9pM.mjs";import{c as PLUGIN_LIFECYCLE_LEASE_IDENTITY,s as withPluginLifecycleLeaseAsync}from"./plugin-lifecycle-lease-D-y0xYkr.mjs";import{existsSync}from"node:fs";import{isDeepStrictEqual}from"node:util"; //!src/plugins/installed-plugin-index-source-snapshots.ts function reconcileRetiredPluginSourceSnapshots(e,t){const n=t.plugins.filter(e=>Object.hasOwn(e,`sourceSnapshot`)).map(e=>e.sourceSnapshot);const r=[...e?.retiredSourceSnapshots??[],...t.retiredSourceSnapshots??[],...e?.plugins.filter(e=>Object.hasOwn(e,`sourceSnapshot`)).map(e=>e.sourceSnapshot)??[]];const i=[];for(const e of r)if(!n.some(t=>isDeepStrictEqual(t,e))&&!i.some(t=>isDeepStrictEqual(t,e)))i.push(e);if(i.length)t.retiredSourceSnapshots=i;else delete t.retiredSourceSnapshots}function forgetCollectedPluginSourceSnapshots(e,t){for(const n of t)if(e.plugins.some(e=>isDeepStrictEqual(e.sourceSnapshot,n)))throw new Error(`Cannot acknowledge collection of an active plugin source snapshot`);const n=e.retiredSourceSnapshots?.filter(e=>!t.some(t=>isDeepStrictEqual(e,t)));if(n?.length)e.retiredSourceSnapshots=n;else delete e.retiredSourceSnapshots}function snapshotState(e){if(!e)return null;const t=resolveInstalledPluginIndexInstallOwner(e);return{...t?{installOwner:t}:{},rootDir:e.rootDir,...e.installRecordHash?{installRecordHash:e.installRecordHash}:{},...Object.hasOwn(e,`sourceSnapshot`)?{sourceSnapshot:e.sourceSnapshot}:{},...e.sourceSnapshotWarning?{sourceSnapshotWarning:e.sourceSnapshotWarning}:{}}}function diffPluginSourceSnapshotStates(e,t){const n=new Map(e?.plugins.map(e=>[e.pluginId,e]));const r=new Map(t.plugins.map(e=>[e.pluginId,e]));return[.../* @__PURE__ */ new Set([...n.keys(),...r.keys()])].flatMap(e=>{const t=snapshotState(n.get(e));const i=snapshotState(r.get(e));return[t,i].some(e=>e&&(Object.hasOwn(e,`sourceSnapshot`)||e.sourceSnapshotWarning))&&!isDeepStrictEqual(t,i)?[{pluginId:e,before:t,after:i}]:[]})}function foldPluginSourceSnapshotChanges(e){const t=/* @__PURE__ */ new Map;for(const n of e){const e=t.get(n.pluginId);if(e&&!isDeepStrictEqual(e.after,n.before))throw new Error(`Plugin ${n.pluginId} source snapshot changed between update publications.`);t.set(n.pluginId,{...n,before:e?e.before:n.before})}return[...t.values()]}function listLaterPluginSourceSnapshotChanges(e,t){const n=new Map(e?.plugins.map(e=>[e.pluginId,e]));return t.filter(e=>{const t=snapshotState(n.get(e.pluginId));return!isDeepStrictEqual(t,e.after)&&!isDeepStrictEqual(t,e.before)})}function restorePluginSourceSnapshotStates(e,t,n){const r=new Map(e?.plugins.map(e=>[e.pluginId,e]));const i=new Map(t.plugins.map(e=>[e.pluginId,e]));for(const e of n){const n=snapshotState(r.get(e.pluginId));if(!isDeepStrictEqual(n,e.after)&&!isDeepStrictEqual(n,e.before))throw new Error(`Plugin ${e.pluginId} source snapshot changed after the update; recovery preserved it.`);const a=i.get(e.pluginId);const o=e.before;if(!o){if(a)throw new Error(`Plugin ${e.pluginId} source snapshot restoration expected no plugin.`);continue}if(!a||a.rootDir!==o.rootDir||a.installRecordHash!==o.installRecordHash||resolveInstalledPluginIndexInstallOwner(a)!==o.installOwner)throw new Error(`Plugin ${e.pluginId} source snapshot restoration no longer matches its install record.`);const s=PluginSourceSnapshotDescriptorSchema.safeParse(o.sourceSnapshot);if(s.success){const n=o.installOwner?t.installRecords[o.installOwner]:void 0;const r=getPluginInstallRecordMapEntry(n?.sourceSnapshotDigests,e.pluginId);if(!n||hashJson(n)!==o.installRecordHash||s.data.installRecordHash!==o.installRecordHash||s.data.packageIntegrity!==(n.integrity??n.npmIntegrity)||s.data.contentDigest!==r?.contentDigest||s.data.dependencyClosureDigest!==r?.dependencyClosureDigest)throw new Error(`Plugin ${e.pluginId} source snapshot restoration differs from its install record.`)}delete a.sourceSnapshot;delete a.sourceSnapshotWarning;if(Object.hasOwn(o,`sourceSnapshot`))a.sourceSnapshot=o.sourceSnapshot;if(o.sourceSnapshotWarning)a.sourceSnapshotWarning=o.sourceSnapshotWarning}projectPluginSourceSnapshotWarnings(t)}function hasSameInstallOwner(e,t){const n=resolveInstalledPluginIndexInstallOwner(t);return Boolean(n&&resolveInstalledPluginIndexInstallOwner(e)===n&&t.installRecordHash&&e.installRecordHash===t.installRecordHash&&e.rootDir===t.rootDir)}function projectPluginSourceSnapshotWarnings(e){e.diagnostics=[...e.diagnostics.filter(e=>e.code!==`plugin-source-snapshot-invalid`),...e.plugins.flatMap(e=>e.sourceSnapshotWarning?[{level:`warn`,pluginId:e.pluginId,source:e.sourceSnapshotWarning.artifactPath,code:`plugin-source-snapshot-invalid`,message:`Source snapshot ${e.sourceSnapshotWarning.artifactPath}: ${e.sourceSnapshotWarning.message}`}]:[])]}function preservePluginSourceSnapshots(e,t){const n=new Map(e?.plugins.map(e=>[e.pluginId,e]));for(const e of t.plugins){const t=n.get(e.pluginId);delete e.sourceSnapshot;delete e.sourceSnapshotWarning;if(t&&hasSameInstallOwner(t,e)){if(Object.hasOwn(t,`sourceSnapshot`))e.sourceSnapshot=t.sourceSnapshot;if(t.sourceSnapshotWarning)e.sourceSnapshotWarning=t.sourceSnapshotWarning}}projectPluginSourceSnapshotWarnings(t)}function applyPluginSourceSnapshotChanges(e,t,n,r=false){const i=new Map(e.plugins.map(e=>[e.pluginId,e]));const a=/* @__PURE__ */ new Set;const takeRecord=(t,n,r,o)=>{if(a.has(t))throw new Error(`Duplicate source snapshot publication for plugin ${t}`);a.add(t);const s=i.get(t);const c=e.installRecords[n];if(!n||!o||!c||hashJson(c)!==o||!s||resolveInstalledPluginIndexInstallOwner(s)!==n||s.rootDir!==r||s.installRecordHash!==o)throw new Error(`Source snapshot no longer matches installed plugin ${t}`);return s};for(const e of n.sourceSnapshotRemovals??[]){const t=takeRecord(e.pluginId,e.installOwner,e.rootDir,e.installRecordHash);if(!Object.hasOwn(t,`sourceSnapshot`)||!isDeepStrictEqual(t.sourceSnapshot,e.expectedSnapshot))throw new Error(`Source snapshot changed before invalidating plugin ${e.pluginId}`);delete t.sourceSnapshot;t.sourceSnapshotWarning=e.warning}for(const i of n.sourceSnapshots??[]){const n=PluginSourceSnapshotDescriptorSchema.parse({...i.descriptor,installedRevision:t});const a=takeRecord(i.pluginId,i.installOwner,i.rootDir,n.installRecordHash);const o=e.installRecords[i.installOwner];if((o?.integrity??o?.npmIntegrity)!==n.packageIntegrity)throw new Error(`Source snapshot integrity differs from installed plugin ${i.pluginId}`);const s=getPluginInstallRecordMapEntry(o?.sourceSnapshotDigests,i.pluginId);if(!s||s.contentDigest!==n.contentDigest||s.dependencyClosureDigest!==n.dependencyClosureDigest)throw new Error(`Source snapshot content differs from installed plugin ${i.pluginId}`);a.sourceSnapshot=n;if(!r)delete a.sourceSnapshotWarning}for(const t of n.sourceSnapshotRetirements??[]){if([...e.plugins.map(e=>e.sourceSnapshot),...e.retiredSourceSnapshots??[]].some(e=>pluginSourceSnapshotArtifactPath(e)===t.artifact.path))continue;const n=PluginSourceSnapshotDescriptorSchema.parse({...t,installedRevision:0});e.retiredSourceSnapshots=[...e.retiredSourceSnapshots??[],n]}projectPluginSourceSnapshotWarnings(e)} //!src/plugins/installed-plugin-index-store-refresh.ts 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)})} //!src/plugins/installed-plugin-snapshot-candidates.kernel.ts const KEY=`plugins.installedSourceSnapshotCandidates`;const schema=object({version:literal(1),candidates:array(PluginSourceSnapshotDescriptorSchema)}).strict();function read(e){const t=executeSqliteQueryTakeFirstSync(e,getNodeSqliteKysely(e).selectFrom(`config_machine_state`).select(`value_json`).where(`state_key`,`=`,KEY));return t?schema.parse(JSON.parse(t.value_json)).candidates:[]}function write$1(e,t){const{compiled:n,bind:r}=compileSqliteQueryBindings(()=>getNodeSqliteKysely(e).insertInto(`config_machine_state`).values({state_key:KEY,value_json:JSON.stringify({version:1,candidates:t}),updated_at_ms:Date.now()}).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(n.sql).run(...r())}function same(e,t){return isDeepStrictEqual({...e,installedRevision:0},{...t,installedRevision:0})}function mutatePluginSnapshotCandidatesInDatabase(e,t){let n=read(e);if(t.operation===`read`)return n;const r=t.candidates.map(e=>PluginSourceSnapshotDescriptorSchema.parse(e));if(t.operation===`retain`)for(const e of r){const t=n.find(t=>t.artifact.path===e.artifact.path);if(t&&!same(t,e))throw new Error(`Snapshot candidate ownership changed`);if(!t)n.push(e)}else n=n.filter(e=>!r.some(t=>same(e,t)));write$1(e,n);return n}function forgetPublishedPluginSnapshotCandidates(e,t){const n=t.flatMap(e=>{const t=PluginSourceSnapshotDescriptorSchema.safeParse(e);return t.success?[t.data]:[]});if(!n.length)return;const r=read(e);const i=r.filter(e=>!n.some(t=>same(e,t)));if(i.length!==r.length)write$1(e,i)} //!src/plugins/installed-plugin-index-store-write.ts 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)),...t.retiredSourceSnapshots?.length?{retiredSourceSnapshots:t.retiredSourceSnapshots}:{},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());forgetPublishedPluginSnapshotCandidates(e,t.plugins.map(e=>e.sourceSnapshot));return{state_key:INSTALLED_PLUGIN_INDEX_STATE_KEY,value_json:i,updated_at_ms:n}}function writePersistedInstalledPluginIndexToSqlite(e,t,n,r=false,i,a={},o=false){assertWritableInstalledPluginIndexStoreOptions(t);const s=preparePersistedInstalledPluginIndex(e);return runOpenClawStateWriteTransaction(({db:t,path:c})=>{const l=readInstalledPluginIndexRow(t);const u=parseInstalledPluginIndexRow(l);const d=u?parseInstalledPluginIndex(u.index):null;let f=d?.installRecords;if(!d&&l&&(u||i)){const e=inspectPersistedInstalledPluginIndexInstallRecords({state:{status:`present`,value:safeParseJson(l.value_json)}});if(e.status===`invalid`)throw new Error(`Persisted plugin install records are invalid. Repair the state before writing plugin installation metadata.`);f=e.status===`valid`?e.records:{}}n.assertOwnedInTransaction(t);if(r){preservePluginSourceAdmissions(d,s);preservePluginSourceSnapshots(d,s)}const p=resolveNextInstalledPluginIndexRevision(u?u.revision:null);applyPluginSourceSnapshotChanges(s,p,a,o);if(a.sourceSnapshotRestorations)restorePluginSourceSnapshotStates(d,s,a.sourceSnapshotRestorations);reconcileRetiredPluginSourceSnapshots(d,s);forgetCollectedPluginSourceSnapshots(s,a.collectedSourceSnapshots??[]);if(i)recordPluginCohortIndexPublicationInDatabase(t,i,f??{},s.installRecords,diffPluginSourceSnapshotStates(d,s));e.diagnostics=s.diagnostics;e.retiredSourceSnapshots=s.retiredSourceSnapshots;const m=writePersistedInstalledPluginIndexRow(t,s,p);n.assertOwnedInTransaction(t,`commit`);return{previous:d,revision:p,mutation:{databasePath:c,before:l??null,after:m}}},{...resolveInstalledPluginIndexStateDatabaseOptions(t),database:t.database})}async function updateInstalledPluginSourceSnapshots(e){const t={sourceSnapshots:e.sourceSnapshots,sourceSnapshotRemovals:e.sourceSnapshotRemovals,sourceSnapshotRetirements:e.sourceSnapshotRetirements,collectedSourceSnapshots:e.collectedSourceSnapshots};const update=n=>runInstalledPluginIndexWrite(e,n,(e,n)=>e.execute({type:`plugins.metadata.index.sourceSnapshots`,input:{identity:n,changes:t}}),e.assertCurrent);return e.lease?update(e.lease):withPluginLifecycleLeaseAsync(resolveInstalledPluginIndexStateDatabaseOptions(e),update)}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,r)=>t.execute({type:`plugins.metadata.index.write`,input:{identity:n,index:e,...r?{pluginCohort:r}:{}}}));return n.filePath})}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,i)=>n.execute({type:`plugins.metadata.index.restore`,input:{identity:r,index:e,expectedRevision:t,...i?{pluginCohort:i}:{}}}))}function restorePersistedInstalledPluginIndexInDatabase(e,t,n,r,i){return runOpenClawStateWriteTransaction(({db:n})=>{r.assertOwnedInTransaction(n);const a=parseInstalledPluginIndexRow(readInstalledPluginIndexRow(n)??null??void 0);const o=a?a.revision:null;if(o!==t){r.assertOwnedInTransaction(n,`commit`);return false}if(i){const t=inspectPersistedInstalledPluginIndexInstallRecords({state:a?{status:`present`,value:{index:a.index}}:{status:`missing`}});if(t.status===`invalid`)throw new Error(`Plugin index compensation cannot journal invalid current records.`);recordPluginCohortIndexPublicationInDatabase(n,i,t.status===`valid`?t.records:{},e?.installRecords??{})}const s=a?parseInstalledPluginIndex(a.index):null;const c=e?preparePersistedInstalledPluginIndex(e):s?{...s,installRecords:{},plugins:[],diagnostics:[]}:null;if(c)reconcileRetiredPluginSourceSnapshots(s,c);if(c&&(e||c.retiredSourceSnapshots?.length))writePersistedInstalledPluginIndexRow(n,c,resolveNextInstalledPluginIndexRevision(o));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 o=pluginCohortPublicationContext.getStore();const s=o&&resolveOpenClawStateSqlitePath(o.env)===a.admission.databasePath?o:void 0;const c=s?{runId:s.runId,transactionId:s.transactionId,installKey:s.installKey}:void 0;const assertAuthority=()=>{t.assertCurrent();r?.();s?.assertCurrent()};assertAuthority();const{runWithOpenClawStateLeaseWorker:l}=await import(`./openclaw-state-lease-worker-operation-DwbLP-7q.mjs`);const u=await l(t.stateLease,a,(e,t)=>n(e,t,c),{assertCurrent:()=>t.assertCurrent(),beforeTransaction:assertAuthority,beforeCommit:assertAuthority});try{i?.(u)}finally{clearPersistedInstalledPluginIndexCaches()}assertAuthority();return u}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,sourceSnapshots:e.sourceSnapshots,sourceSnapshotRemovals:e.sourceSnapshotRemovals,artifactPreservingReadOnly:e.artifactPreservingReadOnly,sourceSnapshotRestorations:e.sourceSnapshotRestorations,env:{...o},installRoots:resolveActivePluginInstallRoots(o),...n?{nowMs:n().getTime()}:{}};const refresh=async e=>{return await runInstalledPluginIndexWrite(c,e,(e,t,n)=>e.execute({type:`plugins.metadata.index.refresh`,input:{identity:t,prepared:l,...n?{pluginCohort:n}:{}}}),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,e.pluginCohort,e);clearPersistedInstalledPluginIndexCaches();return{...i,index:r}}export{refreshPersistedInstalledPluginIndexWithLeaseSync as a,restorePersistedInstalledPluginIndexInDatabase as c,writePersistedInstalledPluginIndexToSqlite as d,mutatePluginSnapshotCandidatesInDatabase as f,refreshPersistedInstalledPluginIndex as i,updateInstalledPluginSourceSnapshots as l,listLaterPluginSourceSnapshotChanges as m,publishPluginSourceAdmissionInDatabase as n,refreshPersistedInstalledPluginIndexWithReceipt as o,foldPluginSourceSnapshotChanges as p,readInstalledPluginIndexRow as r,restorePersistedInstalledPluginIndexIfCurrent as s,parseInstalledPluginIndexRow as t,writePersistedInstalledPluginIndex as u};