UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

599 lines (598 loc) • 18.6 kB
import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs"; import { t as hasErrnoCode } from "./errno-DFcoqIT9.mjs"; import { r as terminalText } from "./safe-text-C80HAQ2e.mjs"; import { d as pathExists$1, t as FsSafeError } from "./fs-safe-BbWvmdVn.mjs"; import { a as resolveInstallPublishTarget, n as assertCanonicalPathWithinBase, r as assertInstallBaseStable, t as INSTALL_BASE_CHANGED_ERROR_MESSAGE } from "./install-safe-path-DIFL0qYY.mjs"; import { f as writeJson, l as tryReadJson } from "./json-files-Cb1h8pYs.mjs"; import { n as runCommandWithTimeout } from "./exec-runner-Br73vG-X.mjs"; import "./exec-aRIvS9s4.mjs"; import { t as retainMutationAuthority } from "./mutation-authority-CnUaJq0v.mjs"; import { a as findExplicitNpmConfigKeys, i as createNpmProjectInstallEnv } from "./npm-install-env-DGs2GyHo.mjs"; import { t as resolveNpmCommand } from "./npm-command-kcBVU3OP.mjs"; import { n as resolveInstallWorkTimeoutMs } from "./install-mode-options-N6t-RB8t.mjs"; import { n as isRemovalIoError, r as removePathWithinRoot } from "./fs-safe-remove-mw1k_RwN.mjs"; import { t as withInstallActivity } from "./install-progress-DFtV5xZ5.mjs"; import { t as formatNpmCommandFailureOutput } from "./install-source-utils-yGloSiaw.mjs"; import { l as movePackageRoot } from "./package-update-filesystem-9kji2nfw.mjs"; import fs from "node:fs"; import path from "node:path"; import { randomUUID } from "node:crypto"; import fs$1 from "node:fs/promises"; import { assertDirectoryIdentitySync, readDirectoryIdentity } from "@openclaw/fs-safe/advanced"; //#region src/infra/safe-package-install.ts /** * Creates a project-local npm install environment for untrusted package dirs. * It disables lifecycle scripts, global/workspace leakage, prompts, and noisy * npm features while preserving caller-supplied process env values. */ function createSafeNpmInstallEnv(e, t = {}) { const n = { ...createNpmProjectInstallEnv(e, t), COREPACK_ENABLE_DOWNLOAD_PROMPT: "0", NPM_CONFIG_IGNORE_SCRIPTS: "true", npm_config_audit: "false", npm_config_fund: "false", npm_config_ignore_scripts: "true", npm_config_legacy_peer_deps: t.legacyPeerDeps ? "true" : "false", npm_config_package_lock: t.packageLock === true ? "true" : "false", npm_config_strict_peer_deps: "false", ...t.packageLock === true ? { npm_config_save: "true" } : {}, ...t.ignoreWorkspaces ? { npm_config_workspaces: "false" } : {} }; if (t.quiet) Object.assign(n, { npm_config_loglevel: "error", npm_config_progress: "false", npm_config_yes: "true" }); const r = findExplicitNpmConfigKeys(n, ["allow-git", "allow-remote"], t); if (!r.has("allow-git")) n.npm_config_allow_git = "all"; if (!r.has("allow-remote")) n.npm_config_allow_remote = "all"; return n; } function createSafeNpmInstallArgs(e = {}) { return [ "install", "--omit=dev", ...e.omitPeer ? ["--omit=peer"] : [], ...e.legacyPeerDeps ? ["--legacy-peer-deps"] : [], "--loglevel=error", "--ignore-scripts", ...e.ignoreWorkspaces ? ["--workspaces=false"] : [], ...e.noAudit ? ["--no-audit"] : [], ...e.noFund ? ["--no-fund"] : [] ]; } //#endregion //#region src/infra/windows-junction-copy.ts /** * `fs.cp` filter that keeps a Windows junction a junction. Node recreates a * copied junction as a directory symlink, which needs a privilege that junctions * do not. Relative links stay with Node's verbatim copy. */ function copyWindowsJunction(e, t) { if (process.platform !== "win32" || !fs.lstatSync(e).isSymbolicLink()) return true; const n = fs.readlinkSync(e); if (!path.isAbsolute(n) || !fs.statSync(e, { throwIfNoEntry: false })?.isDirectory()) return true; fs.symlinkSync(n, t, "junction"); return false; } //#endregion //#region src/infra/install-package-dir.ts const INSTALL_BASE_CHANGED_ABORT_WARNING = "Install base directory changed during install; aborting staged publish."; const INSTALL_BASE_CHANGED_BACKUP_WARNING = "Install base directory changed before backup cleanup; leaving backup in place."; const STAGED_NPM_PROJECT_CONFIG_NAME = ".npmrc"; const STAGED_NPM_PROJECT_CONFIG_PREFIX = ".openclaw-install-hidden-npmrc-"; function hasPackageRuntimeDependencies(e) { return Object.keys(e.dependencies ?? {}).length > 0 || Object.keys(e.optionalDependencies ?? {}).length > 0; } async function sanitizeManifestForNpmInstall(e, t) { const n = path.join(e, "package.json"); const r = await tryReadJson(n); if (!isRecord(r)) return () => Promise.resolve(); const i = r; const a = await fs$1.readFile(n); let o = false; if (Object.hasOwn(i, "devDependencies")) { delete i.devDependencies; o = true; } if (t) for (const e of [ "dependencies", "optionalDependencies", "peerDependencies", "peerDependenciesMeta" ]) { const t = i[e]; if (!isRecord(t) || !Object.hasOwn(t, "openclaw")) continue; delete t.openclaw; if (Object.keys(t).length === 0) delete i[e]; o = true; } if (o) { await writeJson(n, i, { trailingNewline: true }); return async () => { await fs$1.writeFile(n, a); }; } return () => Promise.resolve(); } async function hideProjectNpmConfigForInstall(e) { const t = path.join(e, STAGED_NPM_PROJECT_CONFIG_NAME); let n = ""; try { n = await fs$1.mkdtemp(path.join(e, STAGED_NPM_PROJECT_CONFIG_PREFIX)); const r = path.join(n, STAGED_NPM_PROJECT_CONFIG_NAME); await fs$1.rename(t, r); return { hiddenDir: n, originalPath: t, hiddenPath: r }; } catch (e) { if (n) await fs$1.rm(n, { recursive: true, force: true }).catch(() => void 0); if (hasErrnoCode(e, "ENOENT")) return null; throw e; } } async function restoreProjectNpmConfigAfterInstall(e) { if (!e) return; await fs$1.rename(e.hiddenPath, e.originalPath); await fs$1.rm(e.hiddenDir, { recursive: true, force: true }); } function isInstallBaseChangedError(e) { return e instanceof Error && e.message === "install base directory changed during install"; } const PACKAGE_DIR_INSTALL_TRANSACTION = Symbol.for("openclaw.packageDirInstallTransaction"); const PACKAGE_DIR_INSTALL_TRANSACTION_REQUEST = Symbol.for("openclaw.packageDirInstallTransactionRequest"); function requestDeferredPackageDirInstall(e, t, n) { Object.defineProperty(e, PACKAGE_DIR_INSTALL_TRANSACTION_REQUEST, { configurable: false, enumerable: true, value: { assertOwned: t, prepareSettlement: n } }); return e; } function copyPackageDirInstallTransactionRequest(e, t) { const n = resolvePackageDirInstallTransactionRequest(e); return n ? requestDeferredPackageDirInstall(t, n.assertOwned, n.prepareSettlement) : t; } function resolvePackageDirInstallTransactionRequest(e) { return e[PACKAGE_DIR_INSTALL_TRANSACTION_REQUEST]; } function attachPackageDirInstallTransaction(e, t) { Object.defineProperty(e, PACKAGE_DIR_INSTALL_TRANSACTION, { configurable: false, enumerable: true, value: t }); return e; } function resolvePackageDirInstallTransaction(e) { return e[PACKAGE_DIR_INSTALL_TRANSACTION]; } /** * Publishes a copied package or a privately prepared package directory into its install target. * Update mode backs up the existing target, runs optional validation hooks, * and rolls back when copy, dependency install, or validation fails. */ async function installPackageDir(e) { const t = resolvePackageDirInstallTransactionRequest(e); const n = t !== void 0; const r = t?.assertOwned; const i = t?.prepareSettlement; let a; const o = retainMutationAuthority(() => { if (a) throw a.error; r?.(); }); const prepareSettlement = async () => { o(); try { await i?.(); o(); } catch (e) { a = { error: e }; throw e; } }; const s = retainMutationAuthority((e) => { o(); e?.(); }); e.logger?.info?.(terminalText`Installing to ${e.targetDir}…`); const c = path.dirname(e.targetDir); let l; try { await fs$1.mkdir(c, { recursive: true }); l = await fs$1.realpath(c); await assertCanonicalPathWithinBase({ baseDir: c, candidatePath: e.targetDir, boundaryLabel: "install directory" }); } catch (t) { return { ok: false, error: `${e.copyErrorPrefix}: ${String(t)}` }; } let u; let d; try { ({installBaseRealPath: u, canonicalTargetDir: d} = await resolveInstallPublishTarget({ installBaseDir: c, targetDir: e.targetDir })); if (u !== l) throw new Error(INSTALL_BASE_CHANGED_ERROR_MESSAGE); } catch (t) { if (isInstallBaseChangedError(t)) e.logger?.warn?.(INSTALL_BASE_CHANGED_ABORT_WARNING); return { ok: false, error: `${e.copyErrorPrefix}: ${String(t)}` }; } const f = await readDirectoryIdentity(u); const assertDirectoryIdentity = (e, t) => { try { assertDirectoryIdentitySync(e, { dev: t.dev, ino: t.ino }); } catch (t) { if (t instanceof FsSafeError && t.category === "policy") throw new Error(`install directory changed: ${e}`, { cause: t }); throw t; } }; const assertRollbackOwned = (e = o) => { e(); assertDirectoryIdentity(u, f); }; const p = retainMutationAuthority(() => { assertRollbackOwned(); return e.beforePersistentApply?.(); }); const removeInstallTree = async (e) => { const t = retainMutationAuthority(() => { e.assertOwner(); assertDirectoryIdentity(u, f); if (fs.lstatSync(e.directory, { throwIfNoEntry: false })) assertDirectoryIdentity(e.directory, e.identity); }); try { await removePathWithinRoot({ rootDir: u, relativePath: path.relative(u, e.directory), recursive: e.recursive !== false, force: true, symlinks: "unlink", assertBeforeMutation: t }); } catch (n) { t(); if (!e.bestEffort || !isRemovalIoError(n)) throw n; } }; let m = null; let h; const g = { backup: null, install: null, restore: null }; const _ = e.sourceHardlinks === "package-manager" ? "allow" : "reject"; const warn = (t) => e.logger?.warn?.(t); let v; const rollback = async (e = o) => { const t = g.install; if (t) { assertRollbackOwned(e); if (g.backup && !g.restore) assertDirectoryIdentity(g.backup.path, g.backup); if (!v) { const n = await fs$1.mkdtemp(path.join(u, ".openclaw-install-rollback-")); const r = await readDirectoryIdentity(n); try { await prepareSettlement(); assertRollbackOwned(e); assertDirectoryIdentity(n, r); assertDirectoryIdentity(d, t); await fs$1.rename(d, path.join(n, "package")); v = { directory: n, identity: r }; } catch (e) { await fs$1.rmdir(n).catch(() => void 0); throw e; } } const n = v; await removeInstallTree({ directory: path.join(n.directory, "package"), identity: t, assertOwner: () => assertDirectoryIdentity(n.directory, n.identity) }); } await restoreBackup(e); if (v) await removeInstallTree({ directory: v.directory, identity: v.identity, assertOwner: () => {}, recursive: false }); g.install = null; }; const fail = async (t, n) => { const r = hasErrnoCode(n, "EBUSY") || hasErrnoCode(n, "EPERM") ? ". Files may be held by another process; stop the Gateway and retry this update." : ""; const i = isInstallBaseChangedError(n); let a; if (i) e.logger?.warn?.(INSTALL_BASE_CHANGED_ABORT_WARNING); else { try { await rollback(); } catch (e) { a = String(e); } if (m) { await fs$1.rm(m, { recursive: true, force: true }).catch(() => void 0); m = null; } } const o = [ a && `could not restore existing install: ${a}`, g.install && `install was published at ${g.install.path}; recovery incomplete`, g.backup && `backup recovery path: ${g.backup.path}` ].filter(Boolean); const s = Boolean(a || g.install || g.backup); return { ok: false, error: [t + r, ...o].join("; "), ...s ? { recoveryIncomplete: true } : {} }; }; const restoreBackup = async (e = o) => { if (!g.backup) return; const t = g.backup; try { await prepareSettlement(); assertRollbackOwned(e); if (!g.restore && fs.lstatSync(d, { throwIfNoEntry: false })) { if (!h) throw new Error(`install target changed during rollback: ${d}`); const n = h; await fs$1.cp(t.path, d, { recursive: true, verbatimSymlinks: true, force: false, mode: fs.constants.COPYFILE_EXCL, filter: (r, i) => { assertRollbackOwned(e); assertDirectoryIdentity(t.path, t); assertDirectoryIdentity(d, n); const a = fs.lstatSync(i, { throwIfNoEntry: false }); const o = fs.lstatSync(r); if (a && (a.isDirectory() !== o.isDirectory() || a.isSymbolicLink() !== o.isSymbolicLink())) throw new Error(`install entry changed during rollback: ${i}`); return !a || a.isDirectory(); } }); g.restore = { path: d, ...n }; } if (g.restore) { const n = g.restore; await removeInstallTree({ directory: t.path, identity: t, assertOwner: () => { assertDirectoryIdentity(d, n); assertRollbackOwned(e); } }); } else await movePackageRoot(t.path, d, { operation: "plugin restore", assertBeforeRename: () => { assertDirectoryIdentity(t.path, t); if (fs.lstatSync(d, { throwIfNoEntry: false })) throw new Error(`install target changed during rollback: ${d}`); }, assertCaller: () => { assertDirectoryIdentity(t.path, t); assertRollbackOwned(e); }, onPublished: (e) => { g.restore = e; }, sourceHardlinks: _, warn }); g.backup = null; } catch (e) { const n = g.restore ? `original install published at ${g.restore.path}; cleanup incomplete at ${t.path}` : `backup retained at ${t.path}`; throw new Error(`${String(e)}; ${n}`, { cause: e }); } }; try { await assertCanonicalPathWithinBase({ baseDir: u, candidatePath: d, boundaryLabel: "install directory" }); m = await fs$1.mkdtemp(path.join(u, ".openclaw-install-stage-")); if (e.sourceDir !== void 0) await withInstallActivity(e.logger, "files", () => fs$1.cp(e.sourceDir, m, { recursive: true, verbatimSymlinks: true, filter: copyWindowsJunction })); } catch (t) { return await fail(`${e.copyErrorPrefix}: ${String(t)}`, t); } try { await e.afterCopy?.(m); } catch (e) { return await fail(`post-copy validation failed: ${String(e)}`, e); } if (e.hasDeps) { const t = m; try { const n = await sanitizeManifestForNpmInstall(m, e.omitOpenClawHostDependency === true); let r; try { const n = await hideProjectNpmConfigForInstall(m); e.logger?.info?.(e.depsLogMessage); const i = await withInstallActivity(e.logger, "dependencies", async () => { try { return await runCommandWithTimeout(resolveNpmCommand(createSafeNpmInstallArgs({ ignoreWorkspaces: true })), { timeoutMs: resolveInstallWorkTimeoutMs(e.workTimeoutMs, Math.max(e.timeoutMs, 3e5)), cwd: t, env: createSafeNpmInstallEnv(process.env, { npmConfigCwd: t, ignoreWorkspaces: true }) }); } finally { await restoreProjectNpmConfigAfterInstall(n); } }, (e) => e.code === 0); if (i.code !== 0) r = `npm install failed: ${formatNpmCommandFailureOutput(i)}`; } finally { await n(); } if (r) return await fail(r); } catch (e) { return await fail(`npm install failed: ${String(e)}`, e); } } if (e.afterInstall) try { const t = await e.afterInstall(m); if (!t.ok) { const e = await fail(t.error); return { ...t, ...e }; } } catch (e) { return await fail(`post-install validation failed: ${String(e)}`, e); } const y = e.mode === "update" && await pathExists$1(d); if (e.requireExistingTarget && !y) return await fail(`${e.copyErrorPrefix}: required update target disappeared`); if (y) { const t = path.join(u, ".openclaw-install-backups"); const n = path.join(t, `${path.basename(d)}-${randomUUID()}`); try { await fs$1.mkdir(t, { recursive: true }); await assertCanonicalPathWithinBase({ baseDir: u, candidatePath: n, boundaryLabel: "install directory" }); await assertInstallBaseStable({ installBaseDir: c, expectedRealPath: u }); if (e.authorizeMutation) await e.authorizeMutation(); h = await readDirectoryIdentity(d); await movePackageRoot(d, n, { operation: "plugin backup", assertCaller: p, onPublished: (e) => { g.backup = e; }, sourceHardlinks: _, warn }); h = void 0; } catch (t) { return await fail(`${e.copyErrorPrefix}: ${String(t)}`, t); } } if (g.backup && e.afterBackup) try { const t = await e.afterBackup(g.backup.path); if (!t.ok) { const e = await fail(t.error); return { ...t, ...e }; } } catch (e) { return await fail(`backup validation failed: ${String(e)}`, e); } try { await assertInstallBaseStable({ installBaseDir: c, expectedRealPath: u }); if (e.authorizeMutation) await e.authorizeMutation(); await movePackageRoot(m, d, { operation: "plugin install", assertCaller: p, onPublished: (e) => { g.install = e; }, sourceHardlinks: _, warn }); m = null; } catch (t) { return await fail(`${e.copyErrorPrefix}: ${String(t)}`, t); } if (g.backup) try { await assertInstallBaseStable({ installBaseDir: c, expectedRealPath: u }); } catch (t) { if (isInstallBaseChangedError(t)) e.logger?.warn?.(INSTALL_BASE_CHANGED_BACKUP_WARNING); if (n) return await fail(`${e.copyErrorPrefix}: ${String(t)}`, t); g.backup = null; } if (g.backup && !n) await removeInstallTree({ directory: g.backup.path, identity: g.backup, assertOwner: p, bestEffort: true }); if (!n) return { ok: true }; let b; const settle = (e, t) => { b ??= Promise.resolve().then(() => { const assertCurrent = () => s(t); assertCurrent(); return e(assertCurrent); }).catch((e) => { b = void 0; throw e; }); return b; }; return attachPackageDirInstallTransaction({ ok: true }, { commit: (e) => settle(async (e) => { if (v) throw new Error("cannot commit an install after rollback has started"); e(); if (g.backup) { await prepareSettlement(); e(); await removeInstallTree({ directory: g.backup.path, identity: g.backup, assertOwner: () => assertRollbackOwned(e), bestEffort: true }); } }, e), rollback: (e) => settle(rollback, e) }); } //#endregion export { resolvePackageDirInstallTransaction as a, requestDeferredPackageDirInstall as i, hasPackageRuntimeDependencies as n, createSafeNpmInstallArgs as o, installPackageDir as r, createSafeNpmInstallEnv as s, copyPackageDirInstallTransactionRequest as t };