UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

749 lines (748 loc) • 31.3 kB
import { c as resolveUserPath } from "./home-dir-EKmgmdPG.mjs"; import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs"; import { b as uniqueStrings } from "./string-normalization-DLmfYZXI.mjs"; import { r as defaultRuntime } from "./runtime-B-SLYP-m.mjs"; import { r as isPathInside } from "./path-guards-TIjxtj6H.mjs"; import { p as shortenHomePath } from "./utils-C8YECn2Q.mjs"; import { g as isPluginCandidateInstallOwnerAmbiguous, n as discoverOpenClawPlugins, s as tracePluginLifecyclePhaseAsync, y as resolvePluginCandidateInstallOwner } from "./discovery-DvJYrQFY.mjs"; import { i as createPluginCache, w as withPluginCache } from "./plugin-cache-B_eRuqTM.mjs"; import { t as _usingCtx } from "./usingCtx-rhpPzaNq.mjs"; import { a as resolveCompatibilityHostVersion, t as VERSION } from "./version-GlxUMdxI.mjs"; import { a as safeRealpathSync } from "./path-safety-CTChYC4Z.mjs"; import { c as normalizePluginId, u as normalizePluginsConfig } from "./config-state-B1JlHgba.mjs"; import { a as loadInstalledPluginIndex } from "./installed-plugin-index-DYqse_gE.mjs"; import { a as resolveDefaultPluginExtensionsDir } from "./install-paths-Bwm0P5EG.mjs"; import { C as NpmChannelResolutionError, D as resolveClawHubInstallSpecsForUpdateChannel, M as parseClawHubPluginSpec, T as installWithSourceFallback, i as getOfficialExternalPluginCatalogEntryForPackage, k as resolveNpmInstallSpecsForUpdateChannel, w as installWithChannelFallback } from "./official-external-plugin-catalog-DtkWz1Xo.mjs"; import { s as parseRegistryNpmSpec, t as buildNpmResolutionFields } from "./npm-registry-spec-HKkAvl6N.mjs"; import { i as resolvePluginManifestInstallOwner, r as isPluginManifestInstallOwnerAmbiguous } from "./manifest-registry-build-BbYTyBDW.mjs"; import { o as clearLoadInstalledPluginIndexInstallRecordsCache, r as loadInstalledPluginIndexInstallRecords } from "./installed-plugin-index-record-reader-B-7uGQZ9.mjs"; import { c as normalizeUpdateChannel, u as resolveRegistryUpdateChannel } from "./update-channels-CDc4OFaS.mjs"; import { r as isUnavailableClawHubTarget } from "./clawhub-error-codes-5kIjtf6h.mjs"; import { n as isUnavailableNpmTarget, t as PLUGIN_INSTALL_ERROR_CODE } from "./install-types-BBbGKapR.mjs"; import { t as loadPluginManifestRegistryCore } from "./manifest-registry-CuWv8ibc.mjs"; import { t as ConfigMutationConflictError } from "./mutation-conflict-Bs0nsNWn.mjs"; import { n as composeConfigWriteAssertions } from "./write-authority-l37tp55r.mjs"; import { c as loadPluginMetadataSnapshot } from "./plugin-metadata-snapshot-By9ySblt.mjs"; import { u as readDeferredPluginMigrationsAsync } from "./deferred-plugin-migrations-C_CU0aKR.mjs"; import { n as validateJsonSchemaValue } from "./schema-validator-NvoOmaWr.mjs"; import { t as ensurePluginAllowlisted } from "./plugins-allowlist-DW5H7gQB.mjs"; import { i as prepareConfigForDisabledInstall, n as enablePluginInConfig } from "./enable-BY2SJL8Z.mjs"; import { l as readConfigFileSnapshotForWrite } from "./io.runtime-DsJ2dLCQ.mjs"; import "./config-CMA-J084.mjs"; import { r as theme } from "./theme-BOI0xyRZ.mjs"; import { s as withPluginLifecycleLeaseAsync } from "./plugin-lifecycle-lease-CXjHGDEI.mjs"; import { i as withoutPluginInstallRecords, l as recordPluginInstallInRecords, s as reconcileNpmPluginLoadPath } from "./installed-plugin-index-records-MNCNSlg8.mjs"; import { o as isDefaultClawHubBaseUrl, v as resolveClawHubBaseUrl } from "./clawhub-client-BLg-dsn2.mjs"; import { t as installPluginFromGitSpec } from "./git-install-BejJds3T.mjs"; import { L as requestDeferredPluginInstall, U as takePluginInstallTransaction } from "./npm-managed-root-BtsiBsIh.mjs"; import { a as installPluginFromNpmPackArchive, n as installPluginFromPath, r as installPluginFromNpmSpec } from "./install-Xai3w73h.mjs"; import { t as inspectPluginGenerationSources } from "./plugin-generation-source-inspection-Dl35lAMP.mjs"; import { r as prepareManagedPluginArtifactConsentHandler } from "./capability-consent-ByRkpzSz.mjs"; import { t as buildClawHubPluginInstallRecordFields } from "./clawhub-install-records-DSHcVKgw.mjs"; import { t as installPluginFromClawHub } from "./clawhub-CBghJS2i.mjs"; import { t as installPluginFromMarketplace } from "./marketplace-QnLV2Vxy.mjs"; import { n as realpathViaExistingPrefixSync } from "./path-containment-DaLrXKK_.mjs"; import { a as recordPluginPackageUninstallPlan, r as planPluginUninstall, t as applyPluginUninstallDirectoryRemoval } from "./uninstall-jiiZcP78.mjs"; import { i as getRetainedPluginInstallPublication, r as commitPluginInstallRecordsWithConfig } from "./install-record-commit-BBhtfevs.mjs"; import { n as refreshPluginRegistryAfterConfigMutation } from "./registry-refresh-Bfs6LAit.mjs"; import { t as PluginInstallPersistedError } from "./lifecycle-eIKo4FGP.mjs"; import { i as refreshManagedPluginMetadata, l as resolvePluginConfigEnablement } from "./management-service-jpAFCXsG.mjs"; import { t as applySlotSelectionForPlugin } from "./slot-selection-DOD904vP.mjs"; import { s as buildPluginSnapshotReportAsync } from "./status-dU3VsouW.mjs"; import { t as withPluginSourceCleanup } from "./source-cleanup-Bg55Ow2j.mjs"; import path from "node:path"; //#region 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("\n"), `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; try { const r = await tracePluginLifecyclePhaseAsync("install records load", () => loadInstalledPluginIndexInstallRecords(), { command: "install" }); return await withPluginCache(createPluginCache(), async () => { try { var i = _usingCtx(); const a = e.runtime ?? defaultRuntime; const warn = (t, n) => { e.persistenceLogger?.warn?.(n); a.log(theme.warn(t)); }; const o = r[e.pluginId]; const s = resolveReplacedManagedInstallRemoval({ pluginId: e.pluginId, previousInstall: o, nextInstall: e.install }); const c = recordPluginInstallInRecords(r, { pluginId: e.pluginId, ...e.install }); let l = reconcileNpmPluginLoadPath({ config: e.snapshot.config, previousInstall: o, nextInstall: e.install }); const u = discoverOpenClawPlugins({ extraPaths: l.plugins?.load?.paths, installRecords: c }); const d = /* @__PURE__ */ new Map(); const f = new Set([e.install.installPath, e.install.sourcePath].filter((e) => Boolean(e?.trim())).map((e) => { const t = resolveUserPath(e, process.env); return safeRealpathSync(t, d) ?? path.resolve(t); })); const p = u.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, d) ?? path.resolve(r); return f.has(i); }); if (p.some(isPluginCandidateInstallOwnerAmbiguous)) throw new Error(`Plugin package "${e.pluginId}" has ambiguous install ownership. Refresh the plugin registry or reinstall the package before retrying.`); const m = loadPluginManifestRegistryCore({ config: l, candidates: p, diagnostics: u.diagnostics, installRecords: c }); if (m.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 h = m.plugins.filter((t) => resolvePluginManifestInstallOwner(t) === e.pluginId); if (h.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 g = Object.fromEntries(h.flatMap((e) => e.contextEngineIds ? [[e.id, [...e.contextEngineIds]]] : [])); const _ = c[e.pluginId]; if (!_) throw new Error(`Missing install record for "${e.pluginId}".`); if (Object.keys(g).length > 0) _.contextEngineIdsByPlugin = g; else delete _.contextEngineIdsByPlugin; const v = h.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-COlDPCf8.mjs"); return await i({ config: l, snapshot: r.snapshot, installRecords: c, installOwners: [e.pluginId], assertCurrent: () => { t.assertCurrent(); e.beforePersistentApply?.(); e.snapshot.writeOptions.assertConfigPathForWrite?.(); } }); }; const y = i.a(o ? await prepareMigration() : void 0); l = y?.config ?? l; const b = new Map(h.map((e) => [e.id, e])); const x = new Map(v.map((e) => [e, resolvePluginConfigEnablement({ config: l, pluginId: e, manifest: b.get(e) })])); for (const [e, t] of x) 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 S = l; const C = []; const w = normalizePluginsConfig(l.plugins).entries; for (const t of v) { const n = x.get(t) ?? { mode: "ready" }; const r = w[normalizePluginId(t)]?.enabled === false; if (n.mode === "missing") S = prepareConfigForDisabledInstall(S, t); if (e.enable === false) continue; if (S.plugins?.allow?.length) S = ensurePluginAllowlisted(S, t); S = removeInstalledPluginFromDenylist(S, t); if (n.mode !== "ready" || r) continue; const i = enablePluginInConfig(S, t, { updateChannelConfig: false }); S = i.config; if (i.enabled) C.push(t); } const T = C.length ? loadPluginMetadataSnapshot({ allowCurrent: false, config: S, index: loadInstalledPluginIndex({ config: S, candidates: p, diagnostics: u.diagnostics, installRecords: c }) }) : void 0; const E = T ? discoverOpenClawPlugins({ extraPaths: S.plugins?.load?.paths, installRecords: c }) : void 0; const D = T && E ? [...loadPluginManifestRegistryCore({ config: S, candidates: E.candidates, diagnostics: E.diagnostics, installRecords: c }).plugins.filter((e) => !T.byPluginId.has(e.id)), ...T.plugins] : void 0; for (const t of C) S = await tracePluginLifecyclePhaseAsync("slot selection", async () => { e.beforePersistentApply?.(); return applySlotSelectionForPlugin(S, t, T, e.beforePersistentApply, (e) => warn(e, e), D); }, { command: "install", pluginId: t }); S = withoutPluginInstallRecords(S); const O = new Set(C); const k = e.deferRuntime ? inspectPluginGenerationSources(h.filter((e) => O.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; const commit = () => tracePluginLifecyclePhaseAsync("config mutation", () => commitPluginInstallRecordsWithConfig({ previousInstallRecords: r, nextInstallRecords: c, nextConfig: S, baseHash: e.snapshot.baseHash, beforePersistentEffect: e.beforePersistentEffect, writeOptions: { ...e.snapshot.writeOptions, deferredPluginMigrations: y?.deferredPluginMigrations, afterWrite: e.applyRuntime || e.deferRuntime || y?.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 A = y ? await y.publish(S, commit) : await commit(); n = true; const j = y?.activationWarning; if (j) warn(j, j); else { e.deferRuntime?.record({ operation: "install", pluginId: e.pluginId, sourceDigests: k?.sourceDigests ?? {}, write: A }); await refreshManagedPluginMetadata({ config: S, assertCurrent: e.beforePersistentApply }); await t.assertOwned(); await e.applyRuntime?.({ config: S, write: A.configWrite, pluginIds: v, reason: "install", assertInvokerOwned: e.beforePersistentApply }); } if (s && !j) { 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(s, t), { command: "install", pluginId: e.pluginId }); for (const e of r.warnings) n(e); if (r.directoryRemoved) a.log(theme.muted(`Removed previous plugin install directory: ${shortenHomePath(s.target)}`)); }; if (e.deferRuntime) e.deferRuntime.deferCleanup(cleanup, s.target); else await withPluginSourceCleanup(s.target, { configPath: A.configWrite.path, env: e.env, assertCurrent: e.beforePersistentApply }, cleanup); } await refreshPluginRegistryAfterConfigMutation({ configPath: A.configWrite.path, reason: "source-changed", installRecords: c, invalidateRuntimeCache: j ? false : e.invalidateRuntimeCache, traceCommand: "install", logger: { warn: (e) => warn(e, "Plugin registry refresh or runtime cache invalidation failed. Restart the gateway.") } }); const M = [...x].filter(([, e]) => e.mode === "missing").map(([e]) => e); const N = e.enable !== false && M.length > 0 ? M.length === 1 ? `Installed plugin "${M[0]}" without enabling it because it requires configuration first. Configure it, then run \`openclaw plugins enable ${M[0]}\`.` : `Installed plugin entries ${M.join(", ")} without enabling them because they require configuration first. Configure each entry, then run \`openclaw plugins enable <plugin-id>\`.` : void 0; const P = [e.warningMessage, N].filter(Boolean).join("\n"); if (P) warn(P, N ?? "Plugin installation reported a warning. Run `openclaw plugins doctor`."); a.log(e.successMessage ?? (v.length > 1 ? `Installed plugin package ${e.pluginId}: ${v.join(", ")}` : `Installed plugin: ${e.pluginId}`)); await logShadowedNpmInstallWarning({ config: S, pluginId: e.pluginId, install: e.install, warn }); return S; } catch (e) { i.e = e; } finally { await i.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(); } } //#endregion //#region 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("\n") } : {} }); return { pluginId: e.bundledSource.pluginId, warnings: o, config: s }; } //#endregion //#region src/plugins/management-install.ts /** Apply the shared release-channel policy while preserving operator pins. */ 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 }) : await resolveNpmInstallSpecsForUpdateChannel({ spec: t.spec, updateChannel: i, officialPackageName: r, coreVersion: VERSION }); return a.installSpec === t.spec || a.installSpec === t.recordSpec ? null : { ...a, 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 s = await installWithChannelFallback({ ...a, install: (e) => installResolvedManagedPluginSource({ ...i, request: { ...t, spec: e, recordSpec: t.recordSpec ?? t.spec, expectedIntegrity: e === t.spec ? t.expectedIntegrity : void 0 } }, r, prepareSettlement), isRetryable: (e) => !e.ok && o(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.` }; }); } /** Execute one resolved plugin source through the shared install-and-persist pipeline. */ 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, 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 }) }); } 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) }) }); } //#endregion export { installManagedPluginSource };