UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

1,319 lines (1,318 loc) • 46.5 kB
import { l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs"; import { c as resolveUserPath } from "./home-dir-EKmgmdPG.mjs"; import { r as terminalText } from "./safe-text-C80HAQ2e.mjs"; import "./utils-C8YECn2Q.mjs"; import { n as resolvePreferredOpenClawTmpDir } from "./tmp-openclaw-dir-Bf0oU1Cn.mjs"; import { r as sha256HexPrefixCore } from "./node-crypto-B6yuTjmm.mjs"; import "./crypto-digest-B2m8wIBj.mjs"; import { i as validatePackageExtensionEntriesForInstall } from "./package-entry-resolution-CDVAv_m5.mjs"; import { i as packageNameMatchesId, s as safeDirName } from "./install-safe-path-DIFL0qYY.mjs"; import { i as matchesExpectedPluginId, m as validatePluginId, s as resolveDefaultPluginNpmDir, t as encodePluginInstallDirName } from "./install-paths-Bwm0P5EG.mjs"; import { a as linkOpenClawPeerDependencies, c as relinkOpenClawPeerDependenciesInManagedNpmRoot, l as resolveOpenClawHostDependency, t as auditDeclaredOpenClawHostDependency } from "./plugin-peer-link-KsX3OiLh.mjs"; import { r as normalizePluginDependencySpecs, t as buildManagedPluginDependencyStatus } from "./status-dependencies-core-BbL--1ba.mjs"; import { a as isPrereleaseResolutionAllowed, c as parseRegistryNpmSpecResult, o as isPrereleaseSemverVersion, r as formatPrereleaseResolutionError, s as parseRegistryNpmSpec, t as buildNpmResolutionFields } from "./npm-registry-spec-HKkAvl6N.mjs"; import { t as PLUGIN_INSTALL_ERROR_CODE } from "./install-types-BBbGKapR.mjs"; import { t as isOfficialCatalogLookupPluginIdReplacement } from "./official-external-install-records-DHqBi8wk.mjs"; import { n as runCommandWithTimeout } from "./exec-runner-Br73vG-X.mjs"; import "./exec-aRIvS9s4.mjs"; import { n as inspectBundlePluginArtifact, r as inspectNativePluginArtifact } from "./install-artifact-inspection-CWGsODru.mjs"; import { t as resolveNpmCommand } from "./npm-command-kcBVU3OP.mjs"; import { n as resolveInstallWorkTimeoutMs } from "./install-mode-options-N6t-RB8t.mjs"; import { t as withInstallActivity } from "./install-progress-DFtV5xZ5.mjs"; import { n as loadNpmPackageVersions, o as resolveNpmPackArchiveMetadata, s as resolveNpmSpecMetadata, t as formatNpmCommandFailureOutput } from "./install-source-utils-yGloSiaw.mjs"; import { a as resolvePackageDirInstallTransaction, i as requestDeferredPackageDirInstall, n as hasPackageRuntimeDependencies, o as createSafeNpmInstallArgs, r as installPackageDir, s as createSafeNpmInstallEnv } from "./install-package-dir-_Rv9x8R0.mjs"; import { r as preflightPluginNpmInstallPolicy } from "./install-security-scan-BjcurHAj.mjs"; import { A as validateOpenClawPackageInstallCompatibility, B as resolvePluginInstallTransactionRequest, C as installPluginDirectoryIntoExtensions, D as runInstallSourceScan, E as resolvePreparedDirectoryInstallTarget, F as attachPluginInstallTransaction, I as copyPluginInstallTransactionRequest, O as sourceFamilyForInstallPolicyKind, S as formatUnresolvedOpenClawPeerLinkError, T as readOptionalPackageManifest, _ as buildDirectoryInstallResult, a as resolveManagedNpmRootDependencySpec, b as ensureInstallTargetAvailableForMode, c as copyManagedNpmProjectInputs, d as isNpmAliasOverrideCompatibilityError, f as listManagedNpmRootPackageNames, g as resolveRequiredPlatformPackageNames, h as resolveManagedNpmRootPackageDir, i as repairManagedNpmRootOpenClawPeer, k as sourceFamilyForInstallPolicySource, l as formatManagedNpmProjectQuarantineArtifacts, m as resolveManagedNpmInstallPlan, n as readManagedNpmRootInstalledDependency, o as syncManagedNpmRootPeerDependencies, p as quarantineManagedNpmProjectRebuildArtifacts, r as readOpenClawManagedNpmRootOverrides, s as upsertManagedNpmRootDependency, t as listMissingRequiredPlatformPackages, u as isManagedNpmProjectCorruptionInstallFailure, v as defaultLogger, w as loadPluginInstallRuntime, x as ensureOpenClawExtensions, y as emitSuccessfulPluginInstallSecurityEvent } from "./npm-managed-root-BtsiBsIh.mjs"; import { t as resolveNpmIntegrityDriftWithDefaultMessage } from "./npm-integrity-CW0aDdA3.mjs"; import { t as comparePackageUpdateVersions } from "./package-update-utils-9Q0D2cR2.mjs"; import path from "node:path"; import fs from "node:fs/promises"; import { clean } from "semver"; import { tempWorkspace, withTempWorkspace } from "@openclaw/fs-safe/temp"; //#region src/plugins/install-installed-package.ts async function validatePackagePluginInstallSource(e) { const t = e.manifest ? { ok: true, manifest: e.manifest } : await readOptionalPackageManifest({ runtime: e.runtime, packageDir: e.packageDir }); if (!t.ok) return t; const n = t.manifest; if (!n) return { ok: false, error: "extracted package missing package.json" }; const r = normalizeOptionalString(n.name) ?? ""; const i = r || "plugin"; const a = e.runtime.loadPluginManifest(e.packageDir); if (!a.ok && e.requirePluginManifest) return { ok: false, error: `package missing valid openclaw.plugin.json: ${a.error}`, code: PLUGIN_INSTALL_ERROR_CODE.MISSING_PLUGIN_MANIFEST }; const o = a.ok && a.manifest.id ? a.manifest.id.trim() : void 0; const s = o ?? i; const c = validatePluginId(s); if (c) return { ok: false, error: c }; if (!matchesExpectedPluginId({ expectedPluginId: e.expectedPluginId, pluginId: s, manifestPluginId: o, npmPluginId: i })) return { ok: false, error: `plugin id mismatch: expected ${e.expectedPluginId}, got ${s}`, code: PLUGIN_INSTALL_ERROR_CODE.PLUGIN_ID_MISMATCH }; if (o && !packageNameMatchesId(i, o)) e.logger.info?.(terminalText`Plugin manifest id "${o}" differs from npm package name "${i}"; using manifest id as the config key.`); const l = e.runtime.getPackageManifestMetadata(n); const u = validateOpenClawPackageInstallCompatibility({ runtime: e.runtime, pluginId: s, packageMetadata: l }); if (u) return u; const d = ensureOpenClawExtensions({ manifest: n }); if (!d.ok) return d; const f = d.entries; const p = await validatePackageExtensionEntriesForInstall({ packageDir: e.packageDir, extensions: f, manifest: n, allowSourceTypeScriptEntries: e.allowSourceTypeScriptEntries }); if (!p.ok) return { ok: false, error: p.error, code: PLUGIN_INSTALL_ERROR_CODE.INVALID_OPENCLAW_EXTENSIONS }; const m = e.resolveEffectiveMode ? await e.resolveEffectiveMode(s) : e.mode; const h = await runInstallSourceScan({ subject: `Plugin "${s}"`, pluginId: s, mode: m, sourceFamily: sourceFamilyForInstallPolicySource(e.installPolicyRequest?.source, sourceFamilyForInstallPolicyKind(e.installPolicyRequest?.kind, "installed-package")), scan: async () => await e.runtime.scanPackageInstallSource({ onInstallPolicyWarning: e.onInstallPolicyWarning, trustedSourceLinkedOfficialInstall: e.trustedSourceLinkedOfficialInstall, packageDir: e.packageDir, config: e.config, pluginId: s, logger: e.logger, extensions: f, requestKind: e.installPolicyRequest?.kind, requestedSpecifier: e.installPolicyRequest?.requestedSpecifier, source: e.installPolicyRequest?.source, mode: m, packageName: r || void 0, manifestId: o, version: typeof n.version === "string" ? n.version : void 0 }) }); if (h) return h; const g = resolveOpenClawHostDependency(n); return { ok: true, plugin: { pluginId: s, manifestName: r || void 0, version: typeof n.version === "string" ? n.version : void 0, extensions: f, ...a.ok && a.manifest.setup ? { setup: a.manifest.setup } : {}, hasRuntimeDependencies: hasPackageRuntimeDependencies(n), peerDependencies: g ? { openclaw: g.spec } : {} } }; } async function scanAndLinkInstalledPackage(e) { const t = await runInstallSourceScan({ subject: `Plugin "${e.pluginId}"`, pluginId: e.pluginId, mode: e.mode, sourceFamily: sourceFamilyForInstallPolicySource(e.source, sourceFamilyForInstallPolicyKind(e.requestKind, "installed-package")), scan: async () => await e.runtime.scanInstalledPackageDependencyTree({ ...e.additionalDependencyPackageDirs ? { additionalPackageDirs: e.additionalDependencyPackageDirs } : {}, allowManagedNpmRootPackagePeerSymlinks: e.dependencyScanRootDir !== void 0 && path.resolve(e.dependencyScanRootDir) !== path.resolve(e.installedDir), onInstallPolicyWarning: e.onInstallPolicyWarning, dependencyScanRootDir: e.dependencyScanRootDir, logger: e.logger, mode: e.mode, packageDir: e.installedDir, pluginId: e.pluginId, config: e.config, ...e.requestKind ? { requestKind: e.requestKind } : {}, requestedSpecifier: e.requestedSpecifier, source: e.source, trustedSourceLinkedOfficialInstall: e.trustedSourceLinkedOfficialInstall }) }); if (t) return t; if ((await linkOpenClawPeerDependencies({ installedDir: e.installedDir, peerDependencies: e.peerDependencies, logger: e.logger })).skipped > 0) return { ok: false, error: formatUnresolvedOpenClawPeerLinkError(e.pluginId) }; return null; } async function installPluginFromInstalledPackageDir(e) { const t = await loadPluginInstallRuntime(); const { logger: n } = t.resolveTimedInstallModeOptions(e, defaultLogger); const r = await validatePackagePluginInstallSource({ runtime: t, packageDir: e.packageDir, expectedPluginId: e.expectedPluginId, requirePluginManifest: e.requirePluginManifest, allowSourceTypeScriptEntries: e.allowSourceTypeScriptEntries, onInstallPolicyWarning: e.onInstallPolicyWarning, trustedSourceLinkedOfficialInstall: e.trustedSourceLinkedOfficialInstall, config: e.config, installPolicyRequest: e.installPolicyRequest, logger: n, mode: e.mode ?? "install" }); if (!r.ok) return r; const i = await scanAndLinkInstalledPackage({ runtime: t, installedDir: e.packageDir, ...e.additionalDependencyPackageDirs ? { additionalDependencyPackageDirs: e.additionalDependencyPackageDirs } : {}, dependencyScanRootDir: e.dependencyScanRootDir, pluginId: r.plugin.pluginId, peerDependencies: r.plugin.peerDependencies, onInstallPolicyWarning: e.onInstallPolicyWarning, trustedSourceLinkedOfficialInstall: e.trustedSourceLinkedOfficialInstall, config: e.config, mode: e.mode ?? "install", ...e.installPolicyRequest?.kind ? { requestKind: e.installPolicyRequest.kind } : {}, requestedSpecifier: e.installPolicyRequest?.requestedSpecifier, source: e.installPolicyRequest?.source, logger: n }); if (i) return i; return buildDirectoryInstallResult({ ...r.plugin, targetDir: e.packageDir }); } //#endregion //#region src/plugins/install-managed-npm.ts function verifyInstalledNpmResolution(e) { const { installed: t, expected: n, packageName: r } = e; if (!t) return { kind: "incomplete", error: `npm install did not record package-lock metadata for ${r}` }; for (const [e, i] of [["version", "to version"], ["integrity", "with integrity"]]) if (n[e] && t[e] && t[e] !== n[e]) return { kind: "conflict", error: `npm install resolved ${r} ${i} ${t[e]}, expected ${n[e]}` }; const i = ["version", "integrity"].find((e) => n[e] && !t[e]); if (i) return { kind: "incomplete", error: `npm install recorded incomplete package-lock metadata for ${r}: ${i} missing` }; return { kind: "ok" }; } async function installPluginFromManagedNpmRoot(e) { const t = await loadPluginInstallRuntime(); const { logger: n, timeoutMs: r, workTimeoutMs: i, mode: a, dryRun: o } = t.resolveTimedInstallModeOptions(e, defaultLogger); const s = e.expectedPluginId; const c = e.npmDir ? resolveUserPath(e.npmDir) : resolveDefaultPluginNpmDir(); const { npmRoot: l, installRoot: u, targetMode: d, policyMode: f } = await resolveManagedNpmInstallPlan({ runtime: t, npmBaseDir: c, packageName: e.packageName, requestedMode: a, npmResolution: e.npmResolution }); const p = await ensureInstallTargetAvailableForMode({ runtime: t, targetPath: u, mode: d }); if (!p.ok) return p; const m = e.policyPreflightSourcePath; if (m) { const t = await runInstallSourceScan({ subject: `Plugin "${s ?? e.packageName}"`, pluginId: s ?? e.packageName, mode: f, sourceFamily: sourceFamilyForInstallPolicySource(e.installPolicyRequest.source, "npm"), scan: async () => await preflightPluginNpmInstallPolicy({ config: e.config, onInstallPolicyWarning: e.onInstallPolicyWarning, logger: n, mode: f, packageName: e.packageName, ...s ? { pluginId: s } : {}, requestedSpecifier: e.installPolicyRequest.requestedSpecifier ?? e.displaySpec, source: e.installPolicyRequest.source, sourcePath: m }) }); if (t) return t; } if (o) return { ok: true, pluginId: s ?? e.packageName, targetDir: u, extensions: [], npmResolution: e.npmResolution }; e.signal?.throwIfAborted(); let h; const runManagedNpmInstall = async (o) => { const c = resolveManagedNpmRootPackageDir(o, e.packageName); let l; try { l = await e.prepareDependencySpec({ npmRoot: o }); } catch (e) { return { ok: false, error: e instanceof Error ? e.message : String(e) }; } n.info?.(terminalText`Installing ${e.displaySpec} into ${o}…`); const repairOpenClawPeer = async (t) => { if (e.packageName === "openclaw") return; if (await repairManagedNpmRootOpenClawPeer({ npmRoot: o, timeoutMs: r, workTimeoutMs: i, signal: e.signal, logger: n })) n.info?.(terminalText`Repaired stale openclaw peer dependency in ${o}${t}`); }; await repairOpenClawPeer(""); const p = await readOpenClawManagedNpmRootOverrides(); const quarantineForRecovery = async (e) => { try { h = { cause: e, quarantine: await quarantineManagedNpmProjectRebuildArtifacts({ npmRoot: o }) }; } catch (t) { return { ok: false, error: `${e.error}, but OpenClaw could not quarantine ${o} for rebuild: ${String(t)}` }; } n.warn?.(terminalText`${e.error}; quarantined ${formatManagedNpmProjectQuarantineArtifacts(h.quarantine.movedArtifactNames)} at ${h.quarantine.quarantineDir} and rebuilding once before retrying.`); return null; }; let m = false; const syncManagedPeerDependenciesForInstall = async () => { try { return { ok: true, changed: await syncManagedNpmRootPeerDependencies({ npmRoot: o, managedOverrides: p, omitNpmAliasOverrides: m, timeoutMs: r, workTimeoutMs: i, signal: e.signal }) }; } catch (e) { return { ok: false, error: `npm peer dependency planning failed: ${e instanceof Error ? e.message : String(e)}` }; } }; const prepareManagedDependencies = async () => { await upsertManagedNpmRootDependency({ npmRoot: o, packageName: e.packageName, dependencySpec: l, managedOverrides: p, omitNpmAliasOverrides: m }); return await syncManagedPeerDependenciesForInstall(); }; const g = await prepareManagedDependencies(); if (!g.ok) return g; const _ = resolveNpmCommand(createSafeNpmInstallArgs({ omitPeer: true, legacyPeerDeps: true, noAudit: true, noFund: true })); const v = { cwd: o, timeoutMs: resolveInstallWorkTimeoutMs(i, Math.max(r, 3e5)), signal: e.signal, killProcessTree: true, env: createSafeNpmInstallEnv(process.env, { legacyPeerDeps: true, npmConfigCwd: o, packageLock: true, quiet: true }) }; let y = await runCommandWithTimeout(_, v); if (y.code !== 0 && isNpmAliasOverrideCompatibilityError(y)) { n.warn?.("npm rejected managed npm overrides; retrying plugin install without npm-incompatible overrides for this npm version."); m = true; const e = await prepareManagedDependencies(); if (!e.ok) return e; y = await runCommandWithTimeout(_, v); } if (!h && y.code !== 0 && isManagedNpmProjectCorruptionInstallFailure(y)) { const e = await quarantineForRecovery({ kind: "npm-corruption", error: `npm install failed with a managed npm project corruption signature. Original npm error: ${formatNpmCommandFailureOutput(y)}` }); if (e) return e; return await runManagedNpmInstall(o); } if (y.code !== 0) return { ok: false, error: h ? `npm install failed after managed npm project recovery (quarantine: ${h.quarantine.quarantineDir}): ${formatNpmCommandFailureOutput(y)}. Original ${h.cause.kind === "npm-corruption" ? "npm" : "verification"} error: ${h.cause.error}` : `npm install failed: ${formatNpmCommandFailureOutput(y)}` }; for (let e = 0;; e += 1) { const t = await syncManagedPeerDependenciesForInstall(); if (!t.ok) return t; if (!t.changed) break; if (e === 10) return { ok: false, error: "npm install could not settle managed peer dependencies after 10 sync passes; refusing to leave a partially reconciled plugin dependency tree." }; y = await runCommandWithTimeout(_, v); if (y.code !== 0) return { ok: false, error: `npm install failed after syncing managed peer dependencies: ${formatNpmCommandFailureOutput(y)}` }; } const b = await readOptionalPackageManifest({ runtime: t, packageDir: c }); if (!b.ok) return b; const x = resolveRequiredPlatformPackageNames(b.manifest ? t.getPackageManifestMetadata(b.manifest) : void 0); if (!x.ok) return x; let S; try { S = await listMissingRequiredPlatformPackages({ npmRoot: o, requiredPackageNames: x.packageNames }); } catch (t) { return { ok: false, error: `Failed to verify platform-specific npm dependencies for ${e.packageName}: ${String(t)}` }; } if (S.length > 0) { const t = S.map((e) => e.name); n.warn?.(terminalText`npm left current-platform package(s) ${t.join(", ")} missing or incomplete; retrying once with a fresh cache.`); let r; try { await Promise.all(S.map(({ packagePath: e }) => fs.rm(e, { recursive: true, force: true }))); r = await tempWorkspace({ rootDir: resolvePreferredOpenClawTmpDir(), prefix: "openclaw-npm-cache-" }); y = await runCommandWithTimeout(_, { ...v, env: { ...v.env, NPM_CONFIG_CACHE: r.dir, npm_config_cache: r.dir } }); } catch (e) { return { ok: false, error: `Failed to repair missing or incomplete current-platform package(s) ${t.join(", ")}: ${String(e)}` }; } finally { await r?.cleanup().catch((e) => { n.warn?.(terminalText`Failed to remove temporary npm cache ${r?.dir}: ${String(e)}`); }); } if (y.code !== 0) return { ok: false, error: `npm install failed while repairing missing or incomplete current-platform package(s) ${t.join(", ")}: ${formatNpmCommandFailureOutput(y)}` }; let i; try { i = await listMissingRequiredPlatformPackages({ npmRoot: o, requiredPackageNames: x.packageNames }); } catch (t) { return { ok: false, error: `Failed to verify repaired platform-specific npm dependencies for ${e.packageName}: ${String(t)}` }; } if (i.length > 0) return { ok: false, error: `npm install reported success but left required current-platform package(s) missing or incomplete: ${i.map((e) => e.name).join(", ")}` }; } await repairOpenClawPeer(" after npm install"); try { await relinkOpenClawPeerDependenciesInManagedNpmRoot({ npmRoot: o, logger: n }); } catch (e) { return { ok: false, error: `Failed to repair openclaw peer links after npm install: ${String(e)}` }; } if (await auditDeclaredOpenClawHostDependency({ packageDir: c })) return { ok: false, error: formatUnresolvedOpenClawPeerLinkError(e.packageName) }; let C; try { C = await readManagedNpmRootInstalledDependency({ npmRoot: o, packageName: e.packageName }); } catch (t) { return { ok: false, error: `Failed to verify npm install metadata for ${e.packageName}: ${String(t)}` }; } const w = verifyInstalledNpmResolution({ packageName: e.packageName, expected: e.npmResolution, installed: C }); if (w.kind === "conflict") return { ok: false, error: w.error }; if (w.kind === "incomplete") { if (!h) { const e = await quarantineForRecovery({ kind: "incomplete-metadata", error: w.error }); if (e) return e; return await runManagedNpmInstall(o); } return { ok: false, error: `npm install metadata remained incomplete after managed npm project recovery (quarantine: ${h.quarantine.quarantineDir}): ${w.error}` }; } const { missing: T } = buildManagedPluginDependencyStatus({ rootDir: c, dependencyRootDir: o, ...normalizePluginDependencySpecs(b.manifest ?? {}) }); if (T.length > 0) return { ok: false, error: `npm install reported success but left required dependencies missing for ${e.packageName}: ${T.join(", ")}` }; const E = [...await listManagedNpmRootPackageNames(o)].map((e) => resolveManagedNpmRootPackageDir(o, e)).toSorted((e, t) => e.localeCompare(t)); let D = s; if (a === "update" && e.trustedSourceLinkedOfficialInstall === true && s && e.expectedReplacementPluginId) { const n = t.loadPluginManifest(c); if (n.ok && n.manifest.id === e.expectedReplacementPluginId && (n.manifest.legacyPluginIds?.includes(s) || isOfficialCatalogLookupPluginIdReplacement({ expectedPluginId: s, expectedReplacementPluginId: e.expectedReplacementPluginId }))) D = e.expectedReplacementPluginId; } const O = await installPluginFromInstalledPackageDir({ onInstallPolicyWarning: e.onInstallPolicyWarning, config: e.config, additionalDependencyPackageDirs: E, packageDir: c, dependencyScanRootDir: o, logger: n, expectedPluginId: D, requirePluginManifest: e.trustedSourceLinkedOfficialInstall, trustedSourceLinkedOfficialInstall: e.trustedSourceLinkedOfficialInstall, mode: f, installPolicyRequest: e.installPolicyRequest }); if (!O.ok) return O; if (O.manifestName !== e.packageName) return { ok: false, error: `npm install produced package ${O.manifestName ?? "<missing>"}, expected ${e.packageName}` }; const k = e.npmResolution.version; if (k && O.version !== k) { const t = O.version ? clean(O.version, { loose: true }) : null; if (!t || t !== clean(k, { loose: true })) return { ok: false, error: `npm install produced ${e.packageName} version ${O.version ?? "<missing>"}, expected ${k}` }; } await e.onBeforePluginArtifactCommit?.({ pluginId: O.pluginId, ...d === "update" ? { currentArtifactDir: u } : {}, stagedArtifactDir: c, mode: f, ...e.installPolicyRequest.source?.kind === "npm" ? { sourceRecord: { source: "npm", spec: e.displaySpec, ...buildNpmResolutionFields(e.npmResolution) } } : {} }); return { ...O, npmResolution: e.npmResolution }; }; const g = {}; const _ = resolvePluginInstallTransactionRequest(e); const v = await installPackageDir(requestDeferredPackageDirInstall({ targetDir: l, mode: "update", timeoutMs: r, logger: n, copyErrorPrefix: "Failed to publish managed npm project", beforePersistentApply: () => { e.signal?.throwIfAborted(); return e.beforePersistentApply?.(); }, hasDeps: false, sourceHardlinks: "package-manager", depsLogMessage: "", afterCopy: (e) => copyManagedNpmProjectInputs({ npmRoot: l, stageDir: e }), afterInstall: async (e) => { try { g.result = await withInstallActivity(n, "dependencies", () => runManagedNpmInstall(e)); return g.result; } catch (e) { g.failure = { cause: e }; return { ok: false, error: String(e) }; } } }, _?.assertOwned, _?.prepareSettlement)); if (g.failure) throw g.failure.cause; if (!v.ok) return v; if (!g.result?.ok) throw new Error("Managed npm project published without a validated plugin"); const y = resolvePackageDirInstallTransaction(v); const b = { ...g.result, targetDir: u }; if (_) return attachPluginInstallTransaction(b, y); await y.commit(); return b; } //#endregion //#region src/plugins/install-npm-pack.ts const MANAGED_NPM_PACK_ARCHIVE_DIR = "_openclaw-pack-archives"; async function installPluginFromNpmPackArchive(e) { const t = await loadPluginInstallRuntime(); const { logger: n, timeoutMs: r, workTimeoutMs: i, mode: a, dryRun: o } = t.resolveTimedInstallModeOptions(e, defaultLogger); const s = await resolveNpmPackArchiveMetadata({ archivePath: e.archivePath, timeoutMs: r, signal: e.signal }); if (!s.ok) return s; const c = { ...s.metadata, resolvedAt: (/* @__PURE__ */ new Date()).toISOString() }; const l = await resolveNpmIntegrityDriftWithDefaultMessage({ spec: s.archivePath, expectedIntegrity: e.expectedIntegrity, resolution: c, onIntegrityDrift: e.onIntegrityDrift, warn: (e) => n.warn?.(e) }); if (l.error) return { ok: false, error: l.error }; const u = s.metadata.name; if (!u) return { ok: false, error: "npm pack metadata missing package name", code: PLUGIN_INSTALL_ERROR_CODE.INVALID_NPM_SPEC }; const d = parseRegistryNpmSpec(u); if (!d || d.selectorKind !== "none") return { ok: false, error: `unsupported npm pack package name: ${u}`, code: PLUGIN_INSTALL_ERROR_CODE.INVALID_NPM_SPEC }; const f = d.name; const p = e.npmDir ? resolveUserPath(e.npmDir) : resolveDefaultPluginNpmDir(); const { policyMode: m } = await resolveManagedNpmInstallPlan({ runtime: t, npmBaseDir: p, packageName: f, requestedMode: a, npmResolution: c }); const h = await installPluginFromManagedNpmRoot(copyPluginInstallTransactionRequest(e, { onInstallPolicyWarning: e.onInstallPolicyWarning, trustedSourceLinkedOfficialInstall: e.trustedSourceLinkedOfficialInstall, config: e.config, packageName: f, prepareDependencySpec: async ({ npmRoot: e }) => { try { const t = s.archivePath; const n = path.join(e, MANAGED_NPM_PACK_ARCHIVE_DIR); const r = s.metadata.integrity ?? s.metadata.shasum ?? s.tarballName; const i = sha256HexPrefixCore(r, 16); const a = `${safeDirName(f) || "plugin"}-${safeDirName(s.metadata.version ?? "pack") || "pack"}-${i}.tgz`; await fs.mkdir(n, { recursive: true }); await fs.copyFile(t, path.join(n, a)); return `file:./${path.posix.join(MANAGED_NPM_PACK_ARCHIVE_DIR, a)}`; } catch (e) { throw new Error(`Failed to stage npm pack archive in managed npm root: ${String(e)}`, { cause: e }); } }, displaySpec: s.archivePath, installPolicyRequest: { kind: "plugin-npm", requestedSpecifier: `npm-pack:${s.archivePath}`, source: { kind: "archive", authority: "user", mutable: true, network: false } }, policyPreflightSourcePath: s.archivePath, extensionsDir: e.extensionsDir, npmDir: p, timeoutMs: r, workTimeoutMs: i, signal: e.signal, logger: n, mode: a, dryRun: o, expectedPluginId: e.expectedPluginId, onBeforePluginArtifactCommit: e.onBeforePluginArtifactCommit, beforePersistentApply: e.beforePersistentApply, npmResolution: c })); emitSuccessfulPluginInstallSecurityEvent(h, { dryRun: o, mode: m, sourceFamily: "archive", trustedSourceLinkedOfficialInstall: e.trustedSourceLinkedOfficialInstall }); return { ...h, ...h.ok ? { npmTarballName: s.tarballName } : {} }; } //#endregion //#region src/plugins/install-npm-metadata.ts function isNpmPackageNotFoundMessage(e) { const t = e.trim(); if (t.startsWith("Package not found on npm:")) return true; return /E404|404 not found|not in this registry/i.test(t); } async function resolveTrustedOfficialPrereleaseResolution(e) { if (!e.spec.name.startsWith("@openclaw/")) return null; const t = await loadNpmPackageVersions({ packageName: e.spec.name, timeoutMs: e.timeoutMs, signal: e.signal, killProcessTree: e.killProcessTree }); if (!t) return null; const n = t.filter((e) => !isPrereleaseSemverVersion(e)).toSorted(comparePackageUpdateVersions).at(-1); let r = n; if (!n) { const n = t.toSorted(comparePackageUpdateVersions).at(-1); if (!n) return null; if (n === e.resolvedPrereleaseVersion) return { kind: "allow-prerelease-only", resolvedPrereleaseVersion: e.resolvedPrereleaseVersion, warning: `Resolved ${e.spec.raw} to prerelease version ${e.resolvedPrereleaseVersion}; allowing it because this trusted official OpenClaw package has no stable npm versions yet.` }; r = n; } const i = `${e.spec.name}@${r}`; const a = await resolveNpmSpecMetadata({ spec: i, timeoutMs: e.timeoutMs, signal: e.signal }); if (!a.ok) return null; return { kind: n ? "stable" : "prerelease-only", resolution: a.metadata, resolvedPrereleaseVersion: e.resolvedPrereleaseVersion, warning: n ? `Resolved ${e.spec.raw} to prerelease version ${e.resolvedPrereleaseVersion}; falling back to stable ${i} for this trusted official OpenClaw install.` : `Resolved ${e.spec.raw} to prerelease version ${e.resolvedPrereleaseVersion}; using newest prerelease ${i} because this trusted official OpenClaw package has no stable npm versions yet.` }; } function shouldResolveLatestCompatibleNpmVersion(e) { return e.selectorKind === "none" || e.selectorKind === "tag" && (e.selector ?? "").toLowerCase() === "latest"; } function shouldResolveCompatiblePrereleaseNpmVersion(e) { if (!isPrereleaseSemverVersion(e.currentVersion)) return false; if (e.spec.selectorKind === "none") return true; return e.spec.selectorKind === "tag" && (e.spec.selector ?? "").toLowerCase() !== "latest"; } function resolvePrereleaseChannel(e) { if (!isPrereleaseSemverVersion(e)) return null; return /^\s*v?\d+\.\d+\.\d+-([0-9A-Za-z]+)(?:[.-]|$)/.exec(e)?.[1]?.toLowerCase() ?? null; } function canResolveAroundCompatibilityError(e) { return e.code === PLUGIN_INSTALL_ERROR_CODE.INCOMPATIBLE_HOST_VERSION || e.code === PLUGIN_INSTALL_ERROR_CODE.INCOMPATIBLE_PLUGIN_API; } function validateNpmResolutionCompatibility(e) { return validateOpenClawPackageInstallCompatibility({ runtime: e.runtime, pluginId: e.expectedPluginId ?? e.resolution.name ?? e.parsedSpec.name, packageMetadata: e.resolution.packageOpenClaw }); } async function resolveLatestCompatibleNpmResolution(e) { if (!e.currentResolution.version) return null; const t = e.currentResolution.version; const n = shouldResolveCompatiblePrereleaseNpmVersion({ spec: e.parsedSpec, currentVersion: t }); const r = n ? resolvePrereleaseChannel(t) : null; if (!shouldResolveLatestCompatibleNpmVersion(e.parsedSpec) && !n) return null; const i = await loadNpmPackageVersions({ packageName: e.parsedSpec.name, timeoutMs: e.timeoutMs, signal: e.signal, killProcessTree: true }); if (!i) return null; const a = i.filter((e) => n ? resolvePrereleaseChannel(e) === r : !isPrereleaseSemverVersion(e)).filter((e) => comparePackageUpdateVersions(e, t) < 0).toSorted(comparePackageUpdateVersions).toReversed(); for (const n of a) { const r = `${e.parsedSpec.name}@${n}`; const i = await resolveNpmSpecMetadata({ spec: r, timeoutMs: e.timeoutMs, signal: e.signal }); if (!i.ok) { e.logger.warn?.(terminalText`Could not inspect ${r} while looking for a compatible plugin version: ${i.error}`); continue; } if (!validateNpmResolutionCompatibility({ runtime: e.runtime, parsedSpec: e.parsedSpec, expectedPluginId: e.expectedPluginId, resolution: i.metadata })) { e.logger.warn?.(terminalText`Resolved ${e.parsedSpec.raw} to ${e.currentResolution.resolvedSpec ?? t}, but that version is incompatible with this OpenClaw runtime; using newest compatible ${i.metadata.resolvedSpec ?? r}.`); return i.metadata; } } return null; } //#endregion //#region src/plugins/install-npm.ts async function installPluginFromNpmSpec(e) { const t = await loadPluginInstallRuntime(); const { logger: n, timeoutMs: r, workTimeoutMs: i, mode: a, dryRun: o } = t.resolveTimedInstallModeOptions(e, defaultLogger); const s = e.expectedPluginId; const c = e.spec.trim(); const l = parseRegistryNpmSpecResult(c); if (!l.ok) return { ok: false, error: l.error, code: PLUGIN_INSTALL_ERROR_CODE.INVALID_NPM_SPEC }; const u = l.parsed; const d = e.npmMetadata?.spec === c ? e.npmMetadata : void 0; const f = d ? { ok: true, metadata: d.metadata } : await withInstallActivity(n, "resolve", () => resolveNpmSpecMetadata({ spec: c, timeoutMs: r, signal: e.signal })); if (!f.ok) return { ok: false, error: f.error, ...isNpmPackageNotFoundMessage(f.error) ? { code: PLUGIN_INSTALL_ERROR_CODE.NPM_PACKAGE_NOT_FOUND } : f.category === "metadata-env" ? { code: PLUGIN_INSTALL_ERROR_CODE.NPM_METADATA_FAILURE } : {} }; const p = { ...f.metadata, resolvedAt: (/* @__PURE__ */ new Date()).toISOString() }; if (p.version && !isPrereleaseResolutionAllowed({ spec: u, resolvedVersion: p.version })) { const t = d?.trustedPrereleaseResolution; const i = e.trustedSourceLinkedOfficialInstall ? t?.resolvedPrereleaseVersion === p.version ? t : await resolveTrustedOfficialPrereleaseResolution({ spec: u, resolvedPrereleaseVersion: p.version, timeoutMs: r, signal: e.signal, killProcessTree: true }) : null; if (i) n.warn?.(i.warning); if (i?.kind === "stable" || i?.kind === "prerelease-only") Object.assign(p, i.resolution, { resolvedAt: p.resolvedAt }); else if (i?.kind === "allow-prerelease-only") {} else return { ok: false, error: formatPrereleaseResolutionError({ spec: u, resolvedVersion: p.version }) }; } let m = validateNpmResolutionCompatibility({ runtime: t, parsedSpec: u, expectedPluginId: s, resolution: p }); if (m && canResolveAroundCompatibilityError(m)) { const i = await resolveLatestCompatibleNpmResolution({ runtime: t, parsedSpec: u, expectedPluginId: s, currentResolution: p, timeoutMs: r, signal: e.signal, logger: n }); if (i) { Object.assign(p, i, { resolvedAt: p.resolvedAt }); m = null; } } if (m) return m; const h = { kind: "npm", authority: e.trustedSourceLinkedOfficialInstall ? "official" : "third-party", mutable: false, network: true }; const g = await resolveNpmIntegrityDriftWithDefaultMessage({ spec: c, expectedIntegrity: e.expectedIntegrity, resolution: p, onIntegrityDrift: e.onIntegrityDrift, warn: (e) => n.warn?.(e) }); if (g.error) return { ok: false, error: g.error }; const _ = e.npmDir ? resolveUserPath(e.npmDir) : resolveDefaultPluginNpmDir(); const { policyMode: v } = await resolveManagedNpmInstallPlan({ runtime: t, npmBaseDir: _, packageName: u.name, requestedMode: a, npmResolution: p }); const y = await withTempWorkspace({ rootDir: resolvePreferredOpenClawTmpDir(), prefix: "openclaw-npm-policy-", mode: 438 & ~process.umask() }, async (t) => { const r = await t.writeJson("npm-package-metadata.json", { packageName: u.name, requestedSpecifier: c, resolution: p }); return await runInstallSourceScan({ subject: `Plugin "${s ?? u.name}"`, pluginId: s ?? u.name, mode: v, sourceFamily: "npm", scan: async () => await preflightPluginNpmInstallPolicy({ config: e.config, onInstallPolicyWarning: e.onInstallPolicyWarning, logger: n, mode: v, packageName: u.name, ...s ? { pluginId: s } : {}, requestedSpecifier: c, source: h, sourcePath: r }) }); }); if (y) return y; const b = await installPluginFromManagedNpmRoot(copyPluginInstallTransactionRequest(e, { onInstallPolicyWarning: e.onInstallPolicyWarning, trustedSourceLinkedOfficialInstall: e.trustedSourceLinkedOfficialInstall, config: e.config, packageName: u.name, prepareDependencySpec: async () => resolveManagedNpmRootDependencySpec({ parsedSpec: u, resolution: p }), displaySpec: c, installPolicyRequest: { kind: "plugin-npm", requestedSpecifier: c, source: h }, extensionsDir: e.extensionsDir, npmDir: e.npmDir, timeoutMs: r, workTimeoutMs: i, signal: e.signal, logger: n, mode: a, dryRun: o, expectedPluginId: s, expectedReplacementPluginId: e.expectedReplacementPluginId, onBeforePluginArtifactCommit: e.onBeforePluginArtifactCommit, beforePersistentApply: e.beforePersistentApply, npmResolution: p })); emitSuccessfulPluginInstallSecurityEvent(b, { dryRun: o, mode: v, sourceFamily: "npm", trustedSourceLinkedOfficialInstall: e.trustedSourceLinkedOfficialInstall }); return b; } //#endregion //#region src/plugins/install-package.ts const PLUGIN_ARCHIVE_ROOT_MARKERS = [ "package.json", "openclaw.plugin.json", ".codex-plugin/plugin.json", ".claude-plugin/plugin.json", ".cursor-plugin/plugin.json", "plugin.json" ]; function installPolicyRequestForPath(e, t) { const n = e.installPolicyRequest?.kind === "plugin-git" && t === "plugin-dir" ? "plugin-git" : t; return { kind: n, requestedSpecifier: e.installPolicyRequest?.requestedSpecifier ?? e.path, source: e.installPolicyRequest?.source ?? localPluginInstallPolicySource(n) }; } function localPluginInstallPolicySource(e) { if (e === "plugin-archive") return { kind: "archive", authority: "user", mutable: true, network: false }; if (e === "plugin-git") return { kind: "git", authority: "third-party", mutable: true, network: true }; return { kind: "local-path", authority: "user", mutable: true, network: false }; } async function installBundleFromSourceDir(e) { const t = await loadPluginInstallRuntime(); const n = t.detectBundleManifestFormat(e.sourceDir); if (!n) return null; const { logger: r, timeoutMs: i, workTimeoutMs: a, mode: o, dryRun: s } = t.resolveTimedInstallModeOptions(e, defaultLogger); const c = t.loadBundleManifest({ rootDir: e.sourceDir, bundleFormat: n, rejectHardlinks: true }); if (!c.ok) return { ok: false, error: c.error }; const l = c.manifest.id; const u = validatePluginId(l); if (u) return { ok: false, error: u }; if (e.expectedPluginId && e.expectedPluginId !== l) return { ok: false, error: `plugin id mismatch: expected ${e.expectedPluginId}, got ${l}`, code: PLUGIN_INSTALL_ERROR_CODE.PLUGIN_ID_MISMATCH }; const d = await readOptionalPackageManifest({ runtime: t, packageDir: e.sourceDir }); if (!d.ok) return d; const f = d.manifest ? t.getPackageManifestMetadata(d.manifest) : void 0; const p = validateOpenClawPackageInstallCompatibility({ runtime: t, pluginId: l, packageMetadata: f }); if (p) return p; const m = await resolvePreparedDirectoryInstallTarget({ runtime: t, pluginId: l, extensionsDir: e.extensionsDir, requestedMode: o }); if (!m.ok) return { ok: false, error: m.error }; e.onEffectiveMode?.(m.target.effectiveMode); const h = await runInstallSourceScan({ subject: `Bundle "${l}"`, pluginId: l, mode: m.target.effectiveMode, sourceFamily: sourceFamilyForInstallPolicyKind(e.installPolicyRequest?.kind, "archive"), scan: async () => await t.scanBundleInstallSource({ onInstallPolicyWarning: e.onInstallPolicyWarning, config: e.config, sourceDir: e.sourceDir, pluginId: l, logger: r, requestKind: e.installPolicyRequest?.kind, requestedSpecifier: e.installPolicyRequest?.requestedSpecifier, source: e.installPolicyRequest?.source, mode: m.target.effectiveMode, version: c.manifest.version }) }); if (h) return h; const g = await installPluginDirectoryIntoExtensions(copyPluginInstallTransactionRequest(e, { sourceDir: e.sourceDir, pluginId: l, manifestName: c.manifest.name, version: c.manifest.version, extensions: [], targetDir: m.target.targetPath, extensionsDir: e.extensionsDir, logger: r, timeoutMs: i, workTimeoutMs: a, mode: m.target.effectiveMode, dryRun: s, copyErrorPrefix: "failed to copy plugin bundle", hasDeps: false, depsLogMessage: "", onPluginArtifactInspect: e.onPluginArtifactInspect, onBeforePluginArtifactCommit: e.onBeforePluginArtifactCommit, beforePersistentApply: e.beforePersistentApply })); return g.ok ? { ...g, artifactInspection: inspectBundlePluginArtifact({ format: c.manifest.bundleFormat, capabilities: c.manifest.capabilities }) } : g; } async function installPluginFromSourceDir(e) { const t = await detectNativePackageInstallSource(e.sourceDir); if (!t) { const t = await installBundleFromSourceDir(e); if (t) return t; } const n = await installPluginFromPackageDir({ ...e, packageDir: e.sourceDir, packageManifest: t }); return n.ok ? { ...n, artifactInspection: inspectNativePluginArtifact() } : n; } async function detectNativePackageInstallSource(e) { const t = await loadPluginInstallRuntime(); const n = await readOptionalPackageManifest({ runtime: t, packageDir: e }); const r = n.ok ? n.manifest : void 0; return r && ensureOpenClawExtensions({ manifest: r }).ok ? r : void 0; } async function installPluginFromPackageDir(e) { const t = await loadPluginInstallRuntime(); const { logger: n, timeoutMs: r, workTimeoutMs: i, mode: a, dryRun: o } = t.resolveTimedInstallModeOptions(e, defaultLogger); let s; const resolvePreparedTargetForPluginId = async (n) => { if (!s) { const r = await resolvePreparedDirectoryInstallTarget({ runtime: t, pluginId: n, extensionsDir: e.extensionsDir, requestedMode: a, nameEncoder: encodePluginInstallDirName }); if (!r.ok) throw new Error(r.error); s = r.target; } return s; }; const c = await validatePackagePluginInstallSource({ runtime: t, packageDir: e.packageDir, manifest: e.packageManifest, expectedPluginId: e.expectedPluginId, requirePluginManifest: e.requirePluginManifest, allowSourceTypeScriptEntries: e.allowSourceTypeScriptEntries, onInstallPolicyWarning: e.onInstallPolicyWarning, trustedSourceLinkedOfficialInstall: e.trustedSourceLinkedOfficialInstall, config: e.config, installPolicyRequest: e.installPolicyRequest, logger: n, mode: a, resolveEffectiveMode: async (e) => (await resolvePreparedTargetForPluginId(e)).effectiveMode }); if (!c.ok) return c; const { plugin: l } = c; s = await resolvePreparedTargetForPluginId(l.pluginId); const u = s.effectiveMode; e.onEffectiveMode?.(u); const d = l.hasRuntimeDependencies && e.installPolicyRequest?.kind === "plugin-archive"; return await installPluginDirectoryIntoExtensions(copyPluginInstallTransactionRequest(e, { sourceDir: e.packageDir, pluginId: l.pluginId, manifestName: l.manifestName, version: l.version, extensions: l.extensions, setup: l.setup, targetDir: s.targetPath, extensionsDir: e.extensionsDir, logger: n, timeoutMs: r, workTimeoutMs: i, mode: u, dryRun: o, copyErrorPrefix: "failed to copy plugin", hasDeps: d, sourceHardlinks: d ? "package-manager" : "reject", depsLogMessage: "Installing plugin dependencies…", nameEncoder: encodePluginInstallDirName, onPluginArtifactInspect: e.onPluginArtifactInspect, onBeforePluginArtifactCommit: e.onBeforePluginArtifactCommit, beforePersistentApply: e.beforePersistentApply, afterInstall: async (r) => { return await scanAndLinkInstalledPackage({ runtime: t, installedDir: r, pluginId: l.pluginId, peerDependencies: l.peerDependencies, onInstallPolicyWarning: e.onInstallPolicyWarning, trustedSourceLinkedOfficialInstall: e.trustedSourceLinkedOfficialInstall, config: e.config, mode: u, ...e.installPolicyRequest?.kind ? { requestKind: e.installPolicyRequest.kind } : {}, requestedSpecifier: e.installPolicyRequest?.requestedSpecifier, source: e.installPolicyRequest?.source, logger: n }); } })); } async function installPluginFromArchive(e) { const t = await loadPluginInstallRuntime(); const { logger: n, timeoutMs: r, workTimeoutMs: i, mode: a } = t.resolveTimedInstallModeOptions(e, defaultLogger); const o = e.installPolicyRequest ?? { kind: "plugin-archive", requestedSpecifier: e.archivePath, source: localPluginInstallPolicySource("plugin-archive") }; const s = await t.resolveArchiveSourcePath(e.archivePath); if (!s.ok) return s; const c = s.path; let l = a; const u = await t.withExtractedArchiveRoot({ archivePath: c, tempDirPrefix: "openclaw-plugin-", timeoutMs: r, workTimeoutMs: i, logger: n, verification: e.verification, rootMarkers: PLUGIN_ARCHIVE_ROOT_MARKERS, onExtracted: async (t) => await installPluginFromSourceDir(copyPluginInstallTransactionRequest(e, { sourceDir: t, onInstallPolicyWarning: e.onInstallPolicyWarning, extensionsDir: e.extensionsDir, timeoutMs: r, workTimeoutMs: i, logger: n, mode: a, dryRun: e.dryRun, config: e.config, expectedPluginId: e.expectedPluginId, trustedSourceLinkedOfficialInstall: e.trustedSourceLinkedOfficialInstall, requirePluginManifest: true, installPolicyRequest: o, onPluginArtifactInspect: e.onPluginArtifactInspect, onBeforePluginArtifactCommit: e.onBeforePluginArtifactCommit, beforePersistentApply: e.beforePersistentApply, onEffectiveMode: (e) => { l = e; } })) }); if (u.ok) emitSuccessfulPluginInstallSecurityEvent(u, { dryRun: e.dryRun, mode: l, sourceFamily: "archive", trustedSourceLinkedOfficialInstall: e.trustedSourceLinkedOfficialInstall }); return u; } async function installPluginFromPath(e) { const t = await loadPluginInstallRuntime(); const n = await t.resolveExistingInstallPath(e.path); if (!n.ok) return n; const { resolvedPath: r, stat: i } = n; if (i.isDirectory()) { const t = installPolicyRequestForPath(e, "plugin-dir"); let n = e.mode ?? "install"; const i = await installPluginFromSourceDir({ ...e, sourceDir: r, installPolicyRequest: t, onEffectiveMode: (e) => { n = e; } }); emitSuccessfulPluginInstallSecurityEvent(i, { dryRun: e.dryRun, mode: n, sourceFamily: sourceFamilyForInstallPolicyKind(t.kind, "directory"), trustedSourceLinkedOfficialInstall: e.trustedSourceLinkedOfficialInstall }); return i; } if (t.resolveArchiveKind(r)) return await installPluginFromArchive({ ...e, archivePath: r, installPolicyRequest: installPolicyRequestForPath(e, "plugin-archive") }); return { ok: false, code: PLUGIN_INSTALL_ERROR_CODE.UNSUPPORTED_PLAIN_FILE_PLUGIN, error: "Plain file plugin installs are not supported. Install a plugin directory or archive that contains openclaw.plugin.json, or list standalone plugin files in plugins.load.paths." }; } //#endregion export { installPluginFromNpmPackArchive as a, resolveTrustedOfficialPrereleaseResolution as i, installPluginFromPath as n, installPluginFromInstalledPackageDir as o, installPluginFromNpmSpec as r, validatePackagePluginInstallSource as s, installPluginFromArchive as t };