UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

14 lines • 28.8 kB
import{c as resolveUserPath}from"./home-dir-DEN5DisQ.mjs";import{l as isRecord}from"./record-coerce-BTbqdJ3-.mjs";import{b as uniqueStrings}from"./string-normalization-D_oBUpO3.mjs";import{r as defaultRuntime}from"./runtime-DIcLIHcp.mjs";import{o as throwSettledAggregate}from"./error-graph-internal-Bt2pFJBM.mjs";import{i as createPluginCache,w as withPluginCache}from"./plugin-cache-B6QVpzXr.mjs";import{r as isPathInside}from"./path-guards-DGttsOJI.mjs";import{f as shortenHomePath}from"./utils-Dlk0IYAa.mjs";import{h as safeRealpathSync}from"./plugin-cache-files-BGuripl0.mjs";import{c as normalizePluginId,u as normalizePluginsConfig}from"./config-state-C1eV6UWf.mjs";import{a as realpathViaExistingPrefixSync}from"./path-containment-Drv7Ulmz.mjs";import{F as resolvePluginCandidateInstallOwner,M as isPluginCandidateInstallOwnerAmbiguous,n as discoverOpenClawPlugins,s as tracePluginLifecyclePhaseAsync}from"./discovery-Bo4UPPd9.mjs";import{t as _usingCtx}from"./usingCtx-CUVyQ_FT.mjs";import{a as resolveCompatibilityHostVersion,t as VERSION}from"./version-DrZ9Nfde.mjs";import{r as resolveActivePluginInstallRoots}from"./install-root-context-CqAZmMOW.mjs";import{a as loadInstalledPluginIndex}from"./installed-plugin-index-B04a42mO.mjs";import{n as isUnavailableNpmTarget,t as PLUGIN_INSTALL_ERROR_CODE}from"./install-types-RCuA30Kq.mjs";import{a as resolveDefaultPluginExtensionsDir}from"./install-paths-BDaSzd4l.mjs";import{n as createPluginInstallRecordMap,s as setPluginInstallRecordMapEntry}from"./plugin-install-record-map-BULaY3LO.mjs";import{C as NpmChannelResolutionError,D as resolveClawHubInstallSpecsForUpdateChannel,G as parseClawHubPluginSpec,T as installWithSourceFallback,V as resolveRegistryUpdateChannel,i as getOfficialExternalPluginCatalogEntryForPackage,k as resolveNpmInstallSpecsForUpdateChannel,w as installWithChannelFallback,z as normalizeUpdateChannel}from"./official-external-plugin-catalog-BkSwu5lo.mjs";import{s as parseRegistryNpmSpec,t as buildNpmResolutionFields}from"./npm-registry-spec-D06XlvdA.mjs";import{i as resolvePluginManifestInstallOwner,r as isPluginManifestInstallOwnerAmbiguous}from"./manifest-registry-build-DSmHjL9c.mjs";import{o as clearLoadInstalledPluginIndexInstallRecordsCache,r as loadInstalledPluginIndexInstallRecords}from"./installed-plugin-index-record-reader-rJXlMUQ8.mjs";import{r as isUnavailableClawHubTarget}from"./clawhub-error-codes-CofJzQFq.mjs";import{t as loadPluginManifestRegistryCore}from"./manifest-registry-BHN0dk30.mjs";import{t as ConfigMutationConflictError}from"./mutation-conflict-qTMp0e4U.mjs";import{n as composeConfigWriteAssertions}from"./write-authority-YzEjC_aZ.mjs";import{c as loadPluginMetadataSnapshot}from"./plugin-metadata-snapshot-CDKhemiT.mjs";import{u as readDeferredPluginMigrationsAsync}from"./deferred-plugin-migrations-D_BIDN9_.mjs";import{n as validateJsonSchemaValue}from"./schema-validator-_8KiTdxO.mjs";import{t as ensurePluginAllowlisted}from"./plugins-allowlist-BoS9lnYy.mjs";import{i as prepareConfigForDisabledInstall,n as enablePluginInConfig}from"./enable-DLQhpAs1.mjs";import{l as readConfigFileSnapshotForWrite}from"./io.runtime-BvSeVFIY.mjs";import"./config-DkZ8y8Gv.mjs";import{r as theme}from"./theme-DS2CtI9X.mjs";import{s as withPluginLifecycleLeaseAsync}from"./plugin-lifecycle-lease-D-y0xYkr.mjs";import{i as withoutPluginInstallRecords,l as recordPluginInstallInRecords,s as reconcileNpmPluginLoadPath}from"./installed-plugin-index-records-DMOoWiOF.mjs";import{o as isDefaultClawHubBaseUrl,v as resolveClawHubBaseUrl}from"./clawhub-client-BqChQ9oR.mjs";import{t as installPluginFromGitSpec}from"./git-install-D5rgS26L.mjs";import{B as takePluginInstallTransaction,F as requestDeferredPluginInstall}from"./npm-managed-root-BH-RZlFm.mjs";import{i as installPluginFromNpmSpec,n as installPluginFromPath,o as installPluginFromNpmPackArchive}from"./install-BIl_Ot-i.mjs";import{i as preparePluginSourceSnapshot,t as inspectPluginGenerationSourcesAsync}from"./plugin-generation-worker-C-6GHz8i.mjs";import{i as getRetainedPluginInstallPublication,r as commitPluginInstallRecordsWithConfig}from"./install-record-commit-reY_I7xC.mjs";import{a as recordPluginPackageUninstallPlan,r as planPluginUninstall,t as applyPluginUninstallDirectoryRemoval}from"./uninstall-DiGrh7jf.mjs";import{r as prepareManagedPluginArtifactConsentHandler}from"./capability-consent-K8-8AsH0.mjs";import{t as buildClawHubPluginInstallRecordFields}from"./clawhub-install-records-C3hXxakn.mjs";import{t as installPluginFromClawHub}from"./clawhub-DnaA_iz9.mjs";import{t as installPluginFromMarketplace}from"./marketplace-CBNnm5T7.mjs";import{n as refreshPluginRegistryAfterConfigMutation}from"./registry-refresh-CYG2vk18.mjs";import{t as PluginInstallPersistedError}from"./lifecycle-Dmj8QlO9.mjs";import{c as resolvePluginConfigEnablement,i as refreshManagedPluginMetadata}from"./management-service-C6Ox73Ne.mjs";import{t as applySlotSelectionForPlugin}from"./slot-selection-BjybsanD.mjs";import{s as buildPluginSnapshotReportAsync}from"./status-BHzK174N.mjs";import{t as withPluginSourceCleanup}from"./source-cleanup-WWUYoOJY.mjs";import{t as collectInstalledPluginSourceSnapshots}from"./plugin-source-snapshot-collection-DstMAu02.mjs";import path from"node:path"; //!src/plugins/plugin-source-snapshot-options.ts function isManagedPluginSnapshotSource(e){return e.source!==`path`&&Boolean(e.installPath?.trim())} //!src/plugins/plugin-source-snapshot-install.ts async function preparePluginInstallSourceSnapshots(e){const t=/* @__PURE__ */ new Map;const n=[];const dispose=async()=>{const e=await Promise.allSettled([...t.values()].map(e=>e.disposeAsync()));t.clear();throwSettledAggregate(e,`Plugin source snapshot preparation cleanup failed`)};try{delete e.installRecord.sourceSnapshotDigests;if(isManagedPluginSnapshotSource(e.installRecord)){const n=createPluginInstallRecordMap();for(const r of e.manifests){if(r.origin===`bundled`||r.format===`bundle`)continue;await e.assertCurrent();const i=await preparePluginSourceSnapshot({rootDir:r.rootDir,stateDir:e.stateDir});t.set(r.id,i);await e.assertCurrent();setPluginInstallRecordMapEntry(n,r.id,{contentDigest:i.contentDigest,dependencyClosureDigest:i.dependencyClosureDigest})}if(t.size)e.installRecord.sourceSnapshotDigests=n}return{sourceSnapshots:n,[Symbol.asyncDispose]:dispose}}catch(e){const t=[e];try{await dispose()}catch(e){t.push(e)}if(t.length>1)throw new AggregateError(t,`Plugin snapshot preparation and cleanup failed`,{cause:e});throw e}} //!src/plugins/install-persistence.ts function removeInstalledPluginFromDenylist(e,t){const n=e.plugins?.deny;const r=normalizePluginId(t);if(!Array.isArray(n)||!n.some(e=>normalizePluginId(e)===r))return e;const i=n.filter(e=>normalizePluginId(e)!==r);const a={...e.plugins,...i.length>0?{deny:i}:{}};if(i.length===0)delete a.deny;return{...e,plugins:a}}async function logShadowedNpmInstallWarning(e){if(e.install.source!==`npm`)return;const t=e.install.installPath??e.install.sourcePath;if(!t)return;const n=(await buildPluginSnapshotReportAsync({config:e.config,onlyPluginIds:[e.pluginId]})).plugins.find(t=>t.id===e.pluginId);if(!n||n.origin!==`config`)return;const r=resolveUserPath(n.source);const i=resolveUserPath(t);if(r===i||isPathInside(i,r))return;e.warn([`Warning: installed plugin "${e.pluginId}" is not the active source because a config-selected plugin with the same id is currently selected:`,` active config source: ${shortenHomePath(n.source)}`,` installed npm source: ${shortenHomePath(t)}`,"Run `openclaw plugins doctor` for repair options."].join(` `),`Installed plugin "${e.pluginId}" is shadowed by a configured plugin source. Run \`openclaw plugins doctor\`.`)}function shouldPreserveReplacedInstallPath(e){const t=realpathViaExistingPrefixSync(resolveUserPath(e.removalTarget));const n=realpathViaExistingPrefixSync(resolveUserPath(e.nextInstallPath));if(!t||!n)return true;return isPathInside(t,n)||isPathInside(n,t)}function resolveReplacedManagedInstallRemoval(e){if(!e.previousInstall)return null;const t=e.previousInstall.installPath??e.previousInstall.sourcePath;const n=e.nextInstall.installPath??e.nextInstall.sourcePath;if(!t||!n)return null;if(e.previousInstall.source===`npm`&&e.nextInstall.source===`npm`)return null;if(shouldPreserveReplacedInstallPath({removalTarget:t,nextInstallPath:n}))return null;const r=planPluginUninstall(recordPluginPackageUninstallPlan({config:{plugins:{installs:{[e.pluginId]:e.previousInstall}}},pluginId:e.pluginId,deleteFiles:true},{runtimePluginIds:[]}));if(!r.ok||!r.directoryRemoval)return null;if(shouldPreserveReplacedInstallPath({removalTarget:r.directoryRemoval.target,nextInstallPath:n}))return null;return r.directoryRemoval}async function persistPluginInstall(e){return await withPluginLifecycleLeaseAsync({env:e.env},async t=>persistPluginInstallOwned({...e,beforePersistentApply:composeConfigWriteAssertions(e.beforePersistentApply,t.assertCurrent),beforePersistentEffect:async()=>{await e.beforePersistentEffect?.();await t.assertOwned()}},t))}async function persistPluginInstallOwned(e,t){let n=false;let r=false;let i=[];try{const r=await tracePluginLifecyclePhaseAsync(`install records load`,()=>loadInstalledPluginIndexInstallRecords(),{command:`install`});return await withPluginCache(createPluginCache(),async()=>{try{var a=_usingCtx();const o=e.runtime??defaultRuntime;const warn=(t,n)=>{e.persistenceLogger?.warn?.(n);o.log(theme.warn(t))};const s=r[e.pluginId];const c=resolveReplacedManagedInstallRemoval({pluginId:e.pluginId,previousInstall:s,nextInstall:e.install});const l=recordPluginInstallInRecords(r,{pluginId:e.pluginId,...e.install});let u=reconcileNpmPluginLoadPath({config:e.snapshot.config,previousInstall:s,nextInstall:e.install});const d=discoverOpenClawPlugins({extraPaths:u.plugins?.load?.paths,installRecords:l});const f=/* @__PURE__ */ new Map;const p=new Set([e.install.installPath,e.install.sourcePath].filter(e=>Boolean(e?.trim())).map(e=>{const t=resolveUserPath(e,process.env);return safeRealpathSync(t,f)??path.resolve(t)}));const m=d.candidates.filter(t=>{if(resolvePluginCandidateInstallOwner(t)===e.pluginId)return true;const n=t.packageDir??t.rootDir;const r=resolveUserPath(n,process.env);const i=safeRealpathSync(r,f)??path.resolve(r);return p.has(i)});if(m.some(isPluginCandidateInstallOwnerAmbiguous))throw new Error(`Plugin package "${e.pluginId}" has ambiguous install ownership. Refresh the plugin registry or reinstall the package before retrying.`);const h=loadPluginManifestRegistryCore({config:u,candidates:m,diagnostics:d.diagnostics,installRecords:l});if(h.plugins.some(isPluginManifestInstallOwnerAmbiguous))throw new Error(`Plugin package "${e.pluginId}" has ambiguous install ownership. Refresh the plugin registry or reinstall the package before retrying.`);const g=h.plugins.filter(t=>resolvePluginManifestInstallOwner(t)===e.pluginId);if(g.length===0)throw new Error(`Plugin package "${e.pluginId}" has no authoritative runtime child list. Refresh the plugin registry, then reinstall the package or run openclaw doctor before retrying.`);const _=Object.fromEntries(g.flatMap(e=>e.contextEngineIds?[[e.id,[...e.contextEngineIds]]]:[]));const v=l[e.pluginId];if(!v)throw new Error(`Missing install record for "${e.pluginId}".`);if(Object.keys(_).length>0)v.contextEngineIdsByPlugin=_;else delete v.contextEngineIdsByPlugin;const y=g.map(e=>e.id).toSorted();const prepareMigration=async()=>{const n=await readDeferredPluginMigrationsAsync();await t.assertOwned();e.beforePersistentApply?.();const r=await readConfigFileSnapshotForWrite({deferredPluginMigrations:n});await t.assertOwned();e.beforePersistentApply?.();if(e.snapshot.baseHash!==void 0&&r.snapshot.hash!==e.snapshot.baseHash)throw new ConfigMutationConflictError(`config changed since last load`);const{preparePluginUpdateConfigMigration:i}=await import(`./plugin-update-config-migration-BcCZKK64.mjs`);return await i({config:u,snapshot:r.snapshot,installRecords:l,installOwners:[e.pluginId],assertCurrent:()=>{t.assertCurrent();e.beforePersistentApply?.();e.snapshot.writeOptions.assertConfigPathForWrite?.()}})};const b=a.a(s?await prepareMigration():void 0);u=b?.config??u;const x=new Map(g.map(e=>[e.id,e]));const S=new Map(y.map(e=>[e,resolvePluginConfigEnablement({config:u,pluginId:e,manifest:x.get(e)})]));for(const[e,t]of S)if(t.mode===`invalid`)throw new Error(`Plugin "${e}" has invalid configured settings: ${t.error}. Fix plugins.entries.${e}.config, then rerun the install.`);let C=u;const w=[];const T=normalizePluginsConfig(u.plugins).entries;for(const t of y){const n=S.get(t)??{mode:`ready`};const r=T[normalizePluginId(t)]?.enabled===false;if(n.mode===`missing`)C=prepareConfigForDisabledInstall(C,t);if(e.enable===false)continue;if(C.plugins?.allow?.length)C=ensurePluginAllowlisted(C,t);C=removeInstalledPluginFromDenylist(C,t);if(n.mode!==`ready`||r)continue;const i=enablePluginInConfig(C,t,{updateChannelConfig:false});C=i.config;if(i.enabled)w.push(t)}const E=w.length?loadPluginMetadataSnapshot({allowCurrent:false,config:C,index:loadInstalledPluginIndex({config:C,candidates:m,diagnostics:d.diagnostics,installRecords:l})}):void 0;const D=E?discoverOpenClawPlugins({extraPaths:C.plugins?.load?.paths,installRecords:l}):void 0;const O=E&&D?[...loadPluginManifestRegistryCore({config:C,candidates:D.candidates,diagnostics:D.diagnostics,installRecords:l}).plugins.filter(e=>!E.byPluginId.has(e.id)),...E.plugins]:void 0;for(const t of w)C=await tracePluginLifecyclePhaseAsync(`slot selection`,async()=>{e.beforePersistentApply?.();return applySlotSelectionForPlugin(C,t,E,e.beforePersistentApply,e=>warn(e,e),O)},{command:`install`,pluginId:t});C=withoutPluginInstallRecords(C);const k=a.a(await preparePluginInstallSourceSnapshots({installOwner:e.pluginId,installRecord:v,manifests:g,stateDir:resolveActivePluginInstallRoots(e.env).stateDir,assertCurrent:async()=>{await t.assertOwned();e.beforePersistentApply?.()},assertCleanupOwned:t.assertOwned}));i=k.sourceSnapshots.map(e=>e.descriptor);const A=new Set(w);const j=e.deferRuntime?await inspectPluginGenerationSourcesAsync(g.filter(e=>A.has(e.id)&&e.origin!==`bundled`).map(e=>({pluginId:e.id,rootDir:e.rootDir,entryFile:e.manifestPath===e.source?e.source:void 0}))):void 0;if(e.deferRuntime){await t.assertOwned();e.beforePersistentApply?.()}const commit=()=>tracePluginLifecyclePhaseAsync(`config mutation`,()=>commitPluginInstallRecordsWithConfig({previousInstallRecords:r,nextInstallRecords:l,sourceSnapshots:k.sourceSnapshots,nextConfig:C,baseHash:e.snapshot.baseHash,beforePersistentEffect:e.beforePersistentEffect,writeOptions:{...e.snapshot.writeOptions,deferredPluginMigrations:b?.deferredPluginMigrations,afterWrite:e.applyRuntime||e.deferRuntime||b?.activationWarning?{mode:`none`,reason:`plugin lifecycle applies runtime`}:{mode:`restart`,reason:`plugin source changed`},...e.beforePersistentApply?{assertConfigPathForWrite:composeConfigWriteAssertions(e.snapshot.writeOptions.assertConfigPathForWrite,e.beforePersistentApply)}:{}}}),{command:`install`});const M=b?await b.publish(C,commit):await commit();n=true;const N=b?.activationWarning;if(N)warn(N,N);else{e.deferRuntime?.record({operation:`install`,pluginId:e.pluginId,sourceDigests:j?.sourceDigests??{},write:M});await refreshManagedPluginMetadata({config:C,assertCurrent:e.beforePersistentApply});await t.assertOwned();await e.applyRuntime?.({config:C,write:M.configWrite,pluginIds:y,reason:`install`,assertInvokerOwned:e.beforePersistentApply})}if(c&&!N){const cleanup=async(t,n=e=>warn(e,"A previous plugin installation could not be fully cleaned up. Run `openclaw plugins doctor`."))=>{const r=await tracePluginLifecyclePhaseAsync(`replaced install cleanup`,()=>applyPluginUninstallDirectoryRemoval(c,t),{command:`install`,pluginId:e.pluginId});for(const e of r.warnings)n(e);if(r.directoryRemoved)o.log(theme.muted(`Removed previous plugin install directory: ${shortenHomePath(c.target)}`))};if(e.deferRuntime)e.deferRuntime.deferCleanup(cleanup,c.target);else await withPluginSourceCleanup(c.target,{configPath:M.configWrite.path,env:e.env,assertCurrent:e.beforePersistentApply},cleanup)}await refreshPluginRegistryAfterConfigMutation({configPath:M.configWrite.path,reason:`source-changed`,installRecords:l,invalidateRuntimeCache:N?false:e.invalidateRuntimeCache,traceCommand:`install`,logger:{warn:e=>warn(e,`Plugin registry refresh or runtime cache invalidation failed. Restart the gateway.`)}});const P=[...S].filter(([,e])=>e.mode===`missing`).map(([e])=>e);const F=e.enable!==false&&P.length>0?P.length===1?`Installed plugin "${P[0]}" without enabling it because it requires configuration first. Configure it, then run \`openclaw plugins enable ${P[0]}\`.`:`Installed plugin entries ${P.join(`, `)} without enabling them because they require configuration first. Configure each entry, then run \`openclaw plugins enable <plugin-id>\`.`:void 0;const I=[e.warningMessage,F].filter(Boolean).join(` `);if(I)warn(I,F??"Plugin installation reported a warning. Run `openclaw plugins doctor`.");o.log(e.successMessage??(y.length>1?`Installed plugin package ${e.pluginId}: ${y.join(`, `)}`:`Installed plugin: ${e.pluginId}`));await logShadowedNpmInstallWarning({config:C,pluginId:e.pluginId,install:e.install,warn});return C}catch(e){a.e=e}finally{await a.d()}})}catch(t){if(n)throw new PluginInstallPersistedError(e.pluginId,t);const i=getRetainedPluginInstallPublication(t);if(i){r=true;if(i.current)throw new PluginInstallPersistedError(e.pluginId,t);throw t}try{await e.transaction?.rollback()}catch(e){const n=new AggregateError([t,e],`Plugin install failed and payload rollback failed`);n.cause=t;throw n}throw t}finally{if(n||r)await e.transaction?.commit().catch(()=>{const t=`Plugin install committed, but backup cleanup failed.`;e.persistenceLogger?.warn?.(t);e.runtime?.log(t)});clearLoadInstalledPluginIndexInstallRecordsCache();await collectInstalledPluginSourceSnapshots(resolveActivePluginInstallRoots(e.env).stateDir,i)}} //!src/plugins/bundled-install.ts function resolveBundledPluginConfigEnablement(e){if(!e.bundledSource.requiresConfig)return{mode:`ready`};const t=isRecord(e.existingEntry)?e.existingEntry:void 0;if(!t||!Object.hasOwn(t,`config`))return{mode:`missing`};const n=t.config;if(!e.bundledSource.configSchema)return isRecord(n)&&Object.keys(n).length>0?{mode:`ready`}:{mode:`invalid`,error:`config must be a non-empty object`};const r=validateJsonSchemaValue({schema:e.bundledSource.configSchema,cacheKey:`bundled-install:${e.bundledSource.pluginId}`,value:n,applyDefaults:true});return r.ok?{mode:`ready`}:{mode:`invalid`,error:r.errors[0]?.text??`invalid plugin config`}}async function installBundledPluginSource(e){const t=e.snapshot.config.plugins?.entries?.[e.bundledSource.pluginId];const n=resolveBundledPluginConfigEnablement({bundledSource:e.bundledSource,existingEntry:t});if(n.mode===`invalid`)throw new Error(`Plugin "${e.bundledSource.pluginId}" has invalid configured settings: ${n.error}. Fix plugins.entries.${e.bundledSource.pluginId}.config, then rerun the install.`);const r=n.mode===`ready`;const i=r?e.snapshot.config:prepareConfigForDisabledInstall(e.snapshot.config,e.bundledSource.pluginId);const a=r?void 0:`Installed bundled plugin "${e.bundledSource.pluginId}" without enabling it because it requires configuration first. Configure it, then run \`openclaw plugins enable ${e.bundledSource.pluginId}\`.`;const o=[e.warning,a].filter(e=>Boolean(e));const s=await persistPluginInstall({...e,snapshot:{...e.snapshot,config:i},pluginId:e.bundledSource.pluginId,install:{source:`path`,spec:e.rawSpec,sourcePath:e.bundledSource.localPath,installPath:e.bundledSource.localPath},enable:e.enable!==false&&r,...o.length>0?{warningMessage:o.join(` `)}:{}});return{pluginId:e.bundledSource.pluginId,warnings:o,config:s}} //!src/plugins/management-install.ts async function resolveOfficialManagedInstallSpec(e){const{request:t}=e;const n=t.trustedSourceLinkedOfficialInstall===true;if(!n&&(t.source===`npm`||!isDefaultClawHubBaseUrl(t.clawhubUrl)))return null;if(t.expectedIntegrity&&!(t.source===`clawhub`&&t.recordSpec))return null;const r=t.source===`clawhub`?parseClawHubPluginSpec(t.spec)?.name:parseRegistryNpmSpec(t.spec)?.name;if(!r||!n&&!getOfficialExternalPluginCatalogEntryForPackage(r))return null;const i=resolveRegistryUpdateChannel({configChannel:normalizeUpdateChannel(e.config.update?.channel),currentVersion:VERSION});if(t.source===`npm`&&i!==`beta`&&i!==`extended-stable`)return null;const a=t.source===`clawhub`?resolveClawHubInstallSpecsForUpdateChannel({spec:t.recordSpec??t.spec,updateChannel:i,officialPackageName:r,coreVersion:resolveCompatibilityHostVersion(),preferCoreVersion:true}):void 0;const o=a??await resolveNpmInstallSpecsForUpdateChannel({spec:t.spec,updateChannel:i,officialPackageName:r,coreVersion:VERSION});return o.installSpec===t.spec||o.installSpec===t.recordSpec?null:{...o,fallbackSpec:i===`stable`&&a?.fallbackSpec?t.spec:void 0}}async function installManagedPluginSource(e){const t=e.request.source===`clawhub`||e.request.source===`official`?{...e.request,clawhubUrl:resolveClawHubBaseUrl(e.request.clawhubUrl,e.env)}:e.request;return await withPluginLifecycleLeaseAsync({env:e.env},async n=>{const r=n.assertCurrent;const prepareSettlement=()=>n.assertOwned();const i={...e,request:t,beforePersistentApply:composeConfigWriteAssertions(e.beforePersistentApply,r),beforePersistentEffect:async()=>{await e.beforePersistentEffect?.();await n.assertOwned()}};if(t.source===`official`){const{attempt:e,source:n}=await installWithSourceFallback({sources:t.pin?t.installSources.filter(e=>e.source===`npm`):t.installSources,install:async e=>{const n=e.source===`clawhub`?parseClawHubPluginSpec(e.spec):null;return await installManagedPluginSource({...i,request:{source:e.source,spec:e.spec,...n?{recordSpec:`clawhub:${n.name}`}:{},mode:t.mode,expectedPluginId:t.expectedPluginId,trustedSourceLinkedOfficialInstall:true,...e.source===`clawhub`?{clawhubUrl:t.clawhubUrl}:{},...e.expectedIntegrity?{expectedIntegrity:e.expectedIntegrity}:{},...e.source===`npm`&&t.pin?{pin:true}:{}}})},result:e=>e,onFallback:e=>i.logger?.warn?.(e)});return e.ok?e:{...e,installSource:n}}if(t.source!==`npm`&&t.source!==`clawhub`)return await installResolvedManagedPluginSource({...i,request:t},r,prepareSettlement);let a;try{a=await resolveOfficialManagedInstallSpec({request:t,config:i.snapshot.config})}catch(e){if(!(e instanceof NpmChannelResolutionError))throw e;return{ok:false,error:e.message,code:e.code}}if(!a)return await installResolvedManagedPluginSource({...i,request:t},r,prepareSettlement);const o=t.source===`clawhub`?isUnavailableClawHubTarget:isUnavailableNpmTarget;const install=e=>installResolvedManagedPluginSource({...i,request:{...t,spec:e,recordSpec:t.recordSpec??t.spec,expectedIntegrity:e===t.spec?t.expectedIntegrity:void 0}},r,prepareSettlement);const s=t.source===`npm`?await install(a.installSpec):await installWithChannelFallback({...a,install,isRetryable:e=>!e.ok&&isUnavailableClawHubTarget(e),onFallback:e=>i.logger?.warn?.(e)});if(s.ok||!o(s))return s;return{...s,code:PLUGIN_INSTALL_ERROR_CODE.RELEASE_COHORT_UNAVAILABLE,error:`No ${a.installSpec} release is published for this gateway. Installing ${t.spec} would resolve a build from another release; pass an explicit version to install one anyway.`}})}async function installResolvedManagedPluginSource(e,t,n){const{request:r}=e;const i=e.env??process.env;const a=resolveDefaultPluginExtensionsDir(i);if(r.source===`bundled`)return{ok:true,...await installBundledPluginSource({...e,rawSpec:r.rawSpec,bundledSource:r.bundledSource,warning:r.warning})};const o=r.source===`local`&&r.bundledOrigin===true&&!e.requireCapabilityConsent;const s=r.source===`local`?r.recordSource:r.source===`npm-pack`?`npm`:r.source;const c=e.requireCapabilityConsent&&(e.onBeforePluginArtifactCommit||e.beforePersistentEffect)?async t=>{await e.beforePersistentEffect?.();await e.onBeforePluginArtifactCommit?.(t,e.snapshot.config)}:void 0;const l=o?void 0:await prepareManagedPluginArtifactConsentHandler({config:e.snapshot.config,env:i,source:s,...r.source===`marketplace`?{spec:`${r.plugin}@${r.marketplace}`}:`spec`in r?{spec:r.spec}:{},...`expectedIntegrity`in r&&r.expectedIntegrity?{expectedIntegrity:r.expectedIntegrity}:{},acknowledgeCapabilities:e.acknowledgeCapabilities,onCapabilityConsent:e.onCapabilityConsent,requireCapabilityConsent:e.requireCapabilityConsent,...c?{beforePersistentEffect:c}:{}});const u=requestDeferredPluginInstall({...e.safetyOverrides,...r.source===`local`&&r.policySource?{installPolicyRequest:{kind:`plugin-archive`,source:r.policySource}}:{},config:e.snapshot.config,extensionsDir:a,logger:e.logger,beforePersistentApply:e.beforePersistentApply,...l||e.onBeforePluginArtifactCommit||e.beforePersistentEffect?{onBeforePluginArtifactCommit:async t=>{await l?.onBeforePluginArtifactCommit(t);if(!c){await e.onBeforePluginArtifactCommit?.(t,e.snapshot.config);await e.beforePersistentEffect?.()}}}:{}},void 0,t,n);const complete=async(t,n)=>{const i=await t;if(!i.ok)return i;const a=i;if(r.source===`local`&&r.link)await l?.onBeforePluginArtifactCommit({pluginId:a.pluginId,stagedArtifactDir:r.path,mode:r.mode??`install`});const o=takePluginInstallTransaction(a);if(n.expectedPluginId&&a.pluginId!==n.expectedPluginId){await o?.rollback();return{ok:false,error:`official catalog plugin id mismatch: expected ${n.expectedPluginId}, got ${a.pluginId}`}}const s=[];const c=await persistPluginInstall({persistenceLogger:{warn:e=>s.push(e)},...e,snapshot:n.snapshot??e.snapshot,pluginId:a.pluginId,install:l?l.applyAcceptedSurface(a.pluginId,n.install(a)):n.install(a),transaction:o,successMessage:n.successMessage,beforePersistentApply:e.beforePersistentApply});return{...a,config:c,...s.length>0?{warnings:[...new Set(s)]}:{}}};if(r.source===`local`){const t=r.link?r.path:void 0;const n=r.link?{...e.snapshot,config:{...e.snapshot.config,plugins:{...e.snapshot.config.plugins,load:{...e.snapshot.config.plugins?.load,paths:uniqueStrings([...e.snapshot.config.plugins?.load?.paths??[],r.path])}}}}:e.snapshot;return await complete(installPluginFromPath({...u,path:r.path,mode:r.mode,...r.link?{dryRun:true,allowSourceTypeScriptEntries:true}:{}}),{snapshot:n,successMessage:r.successMessage,install:e=>({source:r.recordSource,sourcePath:r.recordPath??r.path,installPath:t??e.targetDir,version:e.version,...r.expectedIntegrity?{integrity:r.expectedIntegrity}:{}})})}if(r.source===`marketplace`)return await complete(installPluginFromMarketplace({...u,marketplace:r.marketplace,plugin:r.plugin,mode:r.mode}),{install:e=>({source:`marketplace`,installPath:e.targetDir,version:e.version,marketplaceName:e.marketplaceName,marketplaceSource:e.marketplaceSource,marketplacePlugin:e.marketplacePlugin})});if(r.source===`npm-pack`)return await complete(installPluginFromNpmPackArchive({...u,archivePath:r.archivePath,mode:r.mode}),{install:e=>({source:`npm`,spec:e.npmResolution?.resolvedSpec??e.manifestName??e.pluginId,sourcePath:r.archivePath,installPath:e.targetDir,...e.version?{version:e.version}:{},...buildNpmResolutionFields(e.npmResolution),artifactKind:`npm-pack`,artifactFormat:`tgz`,...e.npmResolution?.integrity?{npmIntegrity:e.npmResolution.integrity}:{},...e.npmResolution?.shasum?{npmShasum:e.npmResolution.shasum}:{},...e.npmTarballName?{npmTarballName:e.npmTarballName}:{}})});if(r.source===`git`)return await complete(installPluginFromGitSpec({...u,spec:r.spec,mode:r.mode}),{install:e=>({source:`git`,spec:r.spec,installPath:e.targetDir,version:e.version,resolvedAt:e.git.resolvedAt,gitUrl:e.git.url,gitRef:e.git.ref,gitCommit:e.git.commit})});if(r.source===`clawhub`)return await complete(installPluginFromClawHub({...u,baseUrl:r.clawhubUrl,spec:r.spec,mode:r.mode,...r.expectedPluginId?{expectedPluginId:r.expectedPluginId}:{},...r.expectedIntegrity?{expectedIntegrity:r.expectedIntegrity}:{},...r.confirmInstall?{confirmInstall:r.confirmInstall}:{},...e.requireCapabilityConsent?{confirmOnUpdate:true}:{},...e.requireClawHubTrust?{requireClawHubTrust:true}:{}}),{expectedPluginId:r.expectedPluginId,install:e=>({...buildClawHubPluginInstallRecordFields(e.clawhub),spec:r.recordSpec??r.spec,installPath:e.targetDir})});const d=r.expectedPluginId;return await complete(installPluginFromNpmSpec({...u,spec:r.spec,mode:r.mode,...r.trustedSourceLinkedOfficialInstall?{trustedSourceLinkedOfficialInstall:true}:{},...d?{expectedPluginId:d}:{},...r.expectedIntegrity?{expectedIntegrity:r.expectedIntegrity}:{}}),{expectedPluginId:d,install:e=>({source:`npm`,spec:r.pin?e.npmResolution?.resolvedSpec??r.spec:r.recordSpec??r.spec,installPath:e.targetDir,...e.version?{version:e.version}:{},...buildNpmResolutionFields(e.npmResolution)})})}export{installManagedPluginSource};