UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

481 lines (480 loc) • 17.6 kB
import { d as isMissingPathError } from "./paths-0xDagtub.mjs"; import { l as asNullableRecord } from "./utils-BclMknzT.mjs"; import { B as normalizeOptionalString, L as normalizeLowercaseStringOrEmpty, o as LruCache } from "./path-guards-quCEQx1i.mjs"; import { o as OPENCLAW_DATABASE_SCHEMA_DOCS_URL } from "./openclaw-state-db-contract-DpFGI8ZZ.mjs"; import { g as escapeRegExp } from "./redact-BRF0hr6G.mjs"; import "./errors-hqLS1E8Y.mjs"; import { t as resolveOpenClawPackageRootSync } from "./openclaw-root-l-fyeuXJ.mjs"; import { i as executeWithCachedStatement } from "./kysely-sync-cache-state-D75yJYFp.mjs"; import { createRequire } from "node:module"; import fsSync from "node:fs"; import path from "node:path"; import { fileURLToPath } from "node:url"; import { readFileDescriptorBoundedSync, readFileWindowFullySync } from "@openclaw/fs-safe/advanced"; import { safeStatSync } from "@openclaw/fs-safe/path"; import { isUtf8 } from "node:buffer"; //#region scripts/lib/release-version.mjs const RELEASE_VERSION_REGEX = /^(?<year>\d{4})\.(?<month>[1-9]\d?)\.(?<patch>[1-9]\d*)(?:-(?:(?<channel>alpha|beta)\.(?<prerelease>[1-9]\d*)|(?<correction>[1-9]\d*)))?$/; /** * @typedef {object} ParsedReleaseVersion * @property {string} version * @property {string} baseVersion * @property {"stable" | "alpha" | "beta"} channel * @property {number} year * @property {number} month * @property {number} patch * @property {number | undefined} [alphaNumber] * @property {number | undefined} [betaNumber] * @property {number | undefined} [correctionNumber] */ /** * @typedef {"alpha" | "beta" | "stable" | "extended-stable" | "unsupported-extended-stable-correction"} ReleaseTrain */ /** * @param {string} version * @returns {ParsedReleaseVersion | null} */ function parseReleaseVersion(e) { const t = e.trim(); const n = RELEASE_VERSION_REGEX.exec(t)?.groups; if (!n) return null; const r = Number(n.year); const i = Number(n.month); const a = Number(n.patch); const o = n.prerelease === void 0 ? void 0 : Number(n.prerelease); const s = n.correction === void 0 ? void 0 : Number(n.correction); if (!Number.isSafeInteger(r) || !Number.isSafeInteger(i) || !Number.isSafeInteger(a) || i < 1 || i > 12 || a < 1 || o !== void 0 && !Number.isSafeInteger(o) || s !== void 0 && !Number.isSafeInteger(s)) return null; const c = n.channel === "alpha" ? "alpha" : n.channel === "beta" ? "beta" : "stable"; return { version: t, baseVersion: `${r}.${i}.${a}`, channel: c, year: r, month: i, patch: a, alphaNumber: c === "alpha" ? o : void 0, betaNumber: c === "beta" ? o : void 0, ...s === void 0 ? {} : { correctionNumber: s } }; } /** * @param {string} left * @param {string} right * @returns {number | null} */ function compareReleaseVersions(e, t) { const n = parseReleaseVersion(e); const r = parseReleaseVersion(t); if (n === null || r === null) return null; if (n.year !== r.year) return Math.sign(n.year - r.year); if (n.month !== r.month) return Math.sign(n.month - r.month); if (n.patch !== r.patch) return Math.sign(n.patch - r.patch); if (n.channel !== r.channel) { const e = { alpha: 0, beta: 1, stable: 2 }; return Math.sign(e[n.channel] - e[r.channel]); } if (n.channel === "alpha" && r.channel === "alpha") return Math.sign((n.alphaNumber ?? 0) - (r.alphaNumber ?? 0)); if (n.channel === "beta" && r.channel === "beta") return Math.sign((n.betaNumber ?? 0) - (r.betaNumber ?? 0)); return Math.sign((n.correctionNumber ?? 0) - (r.correctionNumber ?? 0)); } //#endregion //#region src/infra/git-root.ts function walkUpFrom(e, t, n) { let r = path.resolve(e); for (let e = 0; t.maxDepth === void 0 || e < t.maxDepth; e += 1) { const e = n(r); if (e !== null && e !== void 0) return e; const t = path.dirname(r); if (t === r) break; r = t; } return null; } function readGitMetadataFile(e, t = 1048576) { const n = fsSync.openSync(e, fsSync.constants.O_RDONLY | (fsSync.constants.O_NONBLOCK ?? 0)); try { const e = fsSync.fstatSync(n); if (!e.isFile() || e.size > t) throw new Error("Git metadata is not a bounded regular file"); const r = readFileDescriptorBoundedSync(n, Math.min(e.size, t)); if (r.length !== e.size) throw new Error("Git metadata changed during its read"); return r; } finally { fsSync.closeSync(n); } } function readGitDirectoryPointerTarget(e, t = "") { const n = readGitMetadataFile(e); const r = n.toString("utf8").replace(/[\r\n]+$/u, ""); if (!isUtf8(n) || !r.startsWith(t) || r.length === t.length || r.includes("\0")) throw new Error("Git directory pointer is incomplete or malformed"); const i = r.slice(t.length); return path.isAbsolute(i) ? i : `${path.dirname(e)}${path.sep}${i}`; } function readGitDirectoryPointer(e, t = "") { return fsSync.realpathSync.native(readGitDirectoryPointerTarget(e, t)); } function resolveGitDirFromMarker(e) { const t = path.join(e, ".git"); try { const e = fsSync.statSync(t); if (e.isDirectory()) return t; if (!e.isFile()) return null; return readGitDirectoryPointer(t, "gitdir: "); } catch { return null; } } function resolveGitHeadPath(e, t = {}) { return walkUpFrom(e, t, (e) => { const t = resolveGitDirFromMarker(e); return t ? path.join(t, "HEAD") : null; }); } /** Read at most `limit` bytes from Git or build metadata. */ function readGitMetadataPrefix(e, t = 256) { const n = fsSync.openSync(e, fsSync.constants.O_RDONLY | (fsSync.constants.O_NONBLOCK ?? 0)); try { if (!fsSync.fstatSync(n).isFile()) throw new Error("Git metadata is not a regular file"); const e = Buffer.alloc(t); const r = readFileWindowFullySync(n, e, 0); return e.subarray(0, r).toString("utf-8"); } finally { fsSync.closeSync(n); } } function readGitHead(e, t = {}) { const n = resolveGitHeadPath(e, t); if (!n) return; const r = readGitMetadataFile(n).toString("utf8").trim(); if (!r.startsWith("ref:")) return { headPath: n, ref: null, value: r || null }; const i = r.replace(/^ref:\s*/i, "").trim(); const a = resolveGitRefsBase(n); return { headPath: n, ref: i, value: readGitRefs(a, [i]).get(i) ?? null, refsBase: a }; } function resolveGitRefsBase(e) { const t = path.dirname(e); const n = path.join(t, "commondir"); try { return readGitDirectoryPointer(n); } catch (e) { if (!isMissingPathError(e) || fsSync.lstatSync(n, { throwIfNoEntry: false })) throw e; } return t; } /** Raw ref contents, sharing one packed inventory across the requested names. */ function readGitRefs(e, t) { const n = new Map(t.map((e) => [e, null])); const r = /* @__PURE__ */ new Set(); for (const i of t) { const t = resolveRefPath(e, i); if (!t) continue; try { n.set(i, readGitMetadataPrefix(t).trim()); } catch (e) { if (!isMissingPathError(e)) throw e; r.add(i); } } if (r.size === 0) return n; try { const t = readGitMetadataFile(path.join(e, "packed-refs"), Number.MAX_SAFE_INTEGER).toString("utf8"); const i = new RegExp(`^(?![#^])[^\\S\\r\\n]*(\\S+)[^\\S\\r\\n]+(${[...r].map(escapeRegExp).join("|")})(?=\\s|$)`, "gm"); for (const [, e, a] of t.matchAll(i)) if (r.delete(a)) n.set(a, e); } catch (e) { if (!isMissingPathError(e)) throw e; } return n; } /** Safely resolve a Git ref path, rejecting traversal from a crafted HEAD file. */ function resolveRefPath(e, t) { if (!t.startsWith("refs/")) return null; if (t.split(/[/]/).includes("..")) return null; const n = path.resolve(e, t); const r = path.relative(e, n); if (!r || r.startsWith("..") || path.isAbsolute(r)) return null; return n; } //#endregion //#region src/infra/git-commit.ts const formatCommit = (e) => { const t = e?.match(/[0-9a-fA-F]{7,40}/); return t ? normalizeLowercaseStringOrEmpty(t[0].slice(0, 7)) : null; }; const cachedGitCommitBySearchDir = new LruCache(256); const resolveCommitSearchDir = (e) => { if (e.cwd) return path.resolve(e.cwd); if (e.moduleUrl) try { return path.dirname(fileURLToPath(e.moduleUrl)); } catch {} return process.cwd(); }; const cacheGitCommit = (e, t) => { cachedGitCommitBySearchDir.set(e, t); return t; }; const resolveGitLookupDepth = (e, t) => { if (!t) return; const n = path.relative(t, e); if (n.startsWith("..") || path.isAbsolute(n)) return; return (n ? n.split(path.sep).filter(Boolean).length : 0) + 1; }; const readCommitFromGit = (e, t) => { const n = readGitHead(e, { maxDepth: resolveGitLookupDepth(e, t) }); return n === void 0 ? void 0 : formatCommit(n.value); }; const readCommitFromPackageJson = () => { try { const e = createRequire(import.meta.url)("../../package.json"); return formatCommit(e.gitHead ?? e.githead ?? null); } catch { return null; } }; const readCommitProbe = (e, t, n) => { try { for (const r of t) { const t = fileURLToPath(new URL(r, e)); let i; try { i = readGitMetadataPrefix(t, 1024); } catch (e) { if (isMissingPathError(e)) continue; return null; } try { const e = asNullableRecord(JSON.parse(i))?.[n]; return typeof e === "string" ? formatCommit(e) : null; } catch { return null; } } } catch {} }; const readCommitFromBuildInfo = (e = import.meta.url) => { return readCommitProbe(e, ["../build-info.json", "./build-info.json"], "commit") ?? null; }; const readLoadedCommit = (e) => { const t = readCommitProbe(e, ["../.buildstamp", "./.buildstamp"], "head"); const n = readCommitProbe(e, ["../.runtime-postbuildstamp", "./.runtime-postbuildstamp"], "head"); if (t !== void 0 || n !== void 0) { if (t || n) return t && t === n ? t : null; return readCommitFromBuildInfo(e); } return readCommitProbe(e, ["../build-info.json", "./build-info.json"], "commit"); }; const resolveCommitHash = (e = {}) => { const t = e.env ?? process.env; const n = t.GIT_COMMIT?.trim() || t.GIT_SHA?.trim(); const r = formatCommit(n); if (r) return r; const i = resolveCommitSearchDir(e); const a = cachedGitCommitBySearchDir.get(i); if (a !== void 0) return a; const o = resolveOpenClawPackageRootSync({ cwd: e.cwd, moduleUrl: e.moduleUrl }); try { const e = readCommitFromGit(i, o); if (e !== void 0) return cacheGitCommit(i, e); } catch {} const s = readCommitFromBuildInfo(); if (s) return cacheGitCommit(i, s); const c = readCommitFromPackageJson(); if (c) return cacheGitCommit(i, c); return cacheGitCommit(i, null); }; /** Resolve the commit that produced the loaded artifact, not the checkout's current revision. */ function resolveLoadedCommitHash(e = {}) { const t = e.moduleUrl ?? import.meta.url; const n = readLoadedCommit(t); return n === void 0 ? resolveCommitHash({ moduleUrl: t, ...e.env ? { env: e.env } : {} }) : n; } //#endregion //#region src/version.ts const CORE_PACKAGE_NAME = "openclaw"; const PACKAGE_JSON_CANDIDATES = [ "../package.json", "../../package.json", "../../../package.json", "./package.json" ]; const BUILD_INFO_CANDIDATES = [ "../build-info.json", "../../build-info.json", "./build-info.json" ]; function readStringFromJsonCandidates(e, t, n, r = false) { try { const i = createRequire(e); for (const e of t) try { const t = i(e); const a = normalizeOptionalString(t[n]); if (!a) continue; if (r && t.name !== CORE_PACKAGE_NAME) continue; return a; } catch {} return null; } catch { return null; } } function firstNonEmpty(...e) { for (const t of e) { const e = normalizeOptionalString(t); if (e && e.toLowerCase() !== "undefined" && e.toLowerCase() !== "null") return e; } } function readVersionFromPackageJsonForModuleUrl(e) { return readStringFromJsonCandidates(e, PACKAGE_JSON_CANDIDATES, "version", true); } function readVersionFromBuildInfoForModuleUrl(e) { return readStringFromJsonCandidates(e, BUILD_INFO_CANDIDATES, "version"); } function readBuildProvenanceForModuleUrl(e) { try { const t = createRequire(e); for (const e of BUILD_INFO_CANDIDATES) try { const n = t(e); const r = normalizeOptionalString(n.buildId); if (r && r.length <= 96) { const i = { buildId: r }; for (const e of [ "version", "commit", "builtAt" ]) { const t = normalizeOptionalString(n[e]); if (t) i[e] = t; } try { i.buildInfoPath = t.resolve(e); } catch {} return i; } } catch {} } catch {} return null; } function resolveVersionFromModuleUrl(e) { return readVersionFromBuildInfoForModuleUrl(e) || readVersionFromPackageJsonForModuleUrl(e); } function resolveBinaryVersion(e) { return resolveVersionFromModuleUrl(e.moduleUrl) || firstNonEmpty(e.bundledVersion) || "0.0.0"; } const RUNTIME_SERVICE_VERSION_FALLBACK = "unknown"; function resolveUsableRuntimeVersion(e) { const t = normalizeOptionalString(e); if (!t || t === "0.0.0") return; return t; } function resolveVersionFromRuntimeSources(e) { return firstNonEmpty(...e.preference === "env-first" ? [e.env["OPENCLAW_VERSION"], e.runtimeVersion] : [e.runtimeVersion, e.env["OPENCLAW_VERSION"]], e.env["npm_package_version"]) ?? e.fallback; } const RUNTIME_SERVICE_BUILD = readBuildProvenanceForModuleUrl(import.meta.url); const RUNTIME_SERVICE_COMMIT = resolveLoadedCommitHash({ moduleUrl: import.meta.url }); function resolveRuntimeServiceCommit() { return RUNTIME_SERVICE_COMMIT; } function resolveCompatibilityHostVersion(e = process.env) { const t = firstNonEmpty(e.OPENCLAW_COMPATIBILITY_HOST_VERSION); if (t) return t; return resolveVersionFromRuntimeSources({ env: e, runtimeVersion: resolveUsableRuntimeVersion(VERSION), fallback: RUNTIME_SERVICE_VERSION_FALLBACK, preference: e === process.env ? "runtime-first" : "env-first" }); } const VERSION = resolveBinaryVersion({ moduleUrl: import.meta.url, bundledVersion: process.env.OPENCLAW_BUNDLED_VERSION }); //#endregion //#region src/infra/startup-maintenance-required.ts const GATEWAY_STARTUP_MAINTENANCE_REQUIRED_REASON = "gateway.maintenance_required"; const maintenanceReasons = { "state-migrations": "state migration", "newer-schema": "a newer OpenClaw build", "agent-media": "offline media migration", "audit-events-v2": "state database schema migration", "legacy-workshop-review-index": "state database schema migration", "legacy-cron-run-logs": "cron run history migration", "legacy-workspace": "workspace setup state migration", "legacy-session-store": "session store migration" }; var StartupMaintenanceRequiredError = class extends Error { constructor(e, t, n) { super(t, n); this.kind = e; this.code = GATEWAY_STARTUP_MAINTENANCE_REQUIRED_REASON; this.name = "StartupMaintenanceRequiredError"; } get reason() { return maintenanceReasons[this.kind]; } }; //#endregion //#region src/infra/sqlite-user-version.ts const SQLITE_SCHEMA_VERSION_ERROR_NAME = "SqliteSchemaVersionError"; var SqliteSchemaVersionError = class extends StartupMaintenanceRequiredError { constructor(e) { super("newer-schema", e); this.name = SQLITE_SCHEMA_VERSION_ERROR_NAME; } }; function isSqliteSchemaVersionError(e) { return e instanceof SqliteSchemaVersionError || e instanceof Error && e.name === SQLITE_SCHEMA_VERSION_ERROR_NAME; } function readSqliteUserVersion(e) { const t = executeWithCachedStatement(e, "PRAGMA user_version", [], (e) => e.get()); return Number(t?.user_version ?? 0); } function readSqliteWriterAppVersion(e) { try { const t = executeWithCachedStatement(e, "SELECT app_version FROM schema_meta WHERE meta_key = 'primary' LIMIT 1", [], (e) => e.get()); return typeof t?.app_version === "string" && t.app_version.length > 0 ? t.app_version : void 0; } catch { return; } } function writeSqliteUserVersion(e, t) { if (!Number.isInteger(t) || t < 0 || t > 2147483647) throw new RangeError("SQLite user_version must be an integer from 0 through 2147483647."); e.exec(`PRAGMA user_version = ${t}`); } /** * Name the refusing build from immutable loaded metadata, plus its install root. * The path remains actionable when multiple installs share a version or build. */ function describeRunningOpenClawBuild() { const e = resolveRuntimeServiceCommit(); const t = resolveOpenClawPackageRootSync({ moduleUrl: import.meta.url }); const n = e ? `OpenClaw ${VERSION} (${e})` : `OpenClaw ${VERSION}`; return t ? `${n} installed at ${t}` : n; } function isNewerSqliteWriterVersion(e) { return (compareReleaseVersions(e ?? "", VERSION) ?? 0) > 0; } function createNewerSqliteSchemaVersionError(e, t, n, r, i, a = "runtime") { const o = isNewerSqliteWriterVersion(i); const s = o ? `; it is newer than this Gateway (${VERSION}).` : a === "runtime" ? "; run openclaw doctor --fix to inspect this database." : "."; return new SqliteSchemaVersionError(`This OpenClaw build cannot open your existing data. ${e} ${t} uses newer schema version ${n}; this build supports ${r}.\n` + (i && (a === "runtime" || i !== VERSION) ? `It was written by OpenClaw ${i}${s}\n` : "") + `Refused by ${describeRunningOpenClawBuild()}.\n` + (o ? `Use the newer install that supports schema ${n} or newer, or run openclaw update to update this Gateway service before restarting. To use an older build, restore your pre-update backup created with openclaw backup create.\n` : `Use a build that supports schema ${n} or newer with this state directory. To use an older build, restore your pre-update backup created with openclaw backup create.\n`) + `See ${OPENCLAW_DATABASE_SCHEMA_DOCS_URL}.`); } //#endregion export { readSqliteWriterAppVersion as a, VERSION as c, readSqliteUserVersion as i, resolveCompatibilityHostVersion as l, createNewerSqliteSchemaVersionError as n, writeSqliteUserVersion as o, isSqliteSchemaVersionError as r, StartupMaintenanceRequiredError as s, SqliteSchemaVersionError as t };