openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
306 lines (305 loc) • 11.8 kB
JavaScript
import { d as resolveStandaloneSidecarRoot, l as resolveRuntimeScriptEnv } from "./cli-invocation-ZSPsKRWa.mjs";
import { a as resolveGlobalSingleton } from "./global-singleton-D7yf05nR.mjs";
import { c as runtimeProcessScriptEntrypoints } from "./runtime-process-manifest-DmUAODRC.mjs";
import { t as isSqliteWalResetSafeVersion } from "./node-sqlite-capabilities-DSS2XxGc.mjs";
import { t as SQLITE_DATABASE_ADMISSIONS_KEY } from "./sqlite-database-admission-key-CHKIncOy.mjs";
import { t as PROCESS_MACHINE_IDENTITY_KEY } from "./current-machine-identity-DYZ3ln3p.mjs";
import { t as parseDiagnosticEnvFlags } from "./diagnostic-flags-env-D8tNaNPv.mjs";
import { createRequire } from "node:module";
import fs, { existsSync } from "node:fs";
import { fileURLToPath, pathToFileURL } from "node:url";
import path, { posix } from "node:path";
import fs$1 from "node:fs/promises";
import os from "node:os";
import { getEnvironmentData, isMainThread, setEnvironmentData } from "node:worker_threads";
import { spawnSync } from "node:child_process";
//#region src/infra/bun-sqlite-library-probe.generated.ts
const BUN_SQLITE_LIBRARY_PROBE_SOURCE = "import{createRequire}from\"node:module\";try{const candidate=process.argv[2];if(!candidate||process.argv.length!==3){throw new Error(\"Expected one SQLite library path\")}const require2=createRequire(import.meta.url);const{Database}=require2(\"bun:sqlite\");Database.setCustomSQLite(candidate);const database=new Database(\":memory:\");let facts;try{facts=database.query(\"SELECT sqlite_version() AS version, sqlite_compileoption_used('OMIT_LOAD_EXTENSION') AS omitted\").get()}finally{database.close()}process.stdout.write(JSON.stringify({protocol:1,version:facts.version,extensionLoadingSupported:facts.omitted===0}))}catch(error){process.stdout.write(JSON.stringify({protocol:1,error:(error instanceof Error?error.message:String(error)).slice(0,512)}));process.exitCode=1}\n";
//#endregion
//#region src/infra/runtime-process-script-file.ts
/** The generated bootstrap binds this operation to declared, built program sources. */
function materializeRuntimeProcessScriptFile(e, t = {}) {
const n = fs.mkdtempSync(path.join(t.parentDirectory ?? os.tmpdir(), "openclaw-script-"));
const r = path.join(n, e.fileName);
let i = false;
const dispose = () => {
if (i) return;
try {
fs.rmSync(n, {
recursive: true,
force: true
});
i = true;
} catch (e) {
process.emitWarning(`Runtime script cleanup failed at ${n}: ${e instanceof Error ? e.message : String(e)}`);
}
};
try {
fs.writeFileSync(r, e.source, {
mode: 384,
flag: "wx"
});
return {
url: pathToFileURL(r),
dispose
};
} catch (e) {
dispose();
throw e;
}
}
//#endregion
//#region src/infra/bun-sqlite-library-probe.ts
/** Each candidate gets a fresh process because Bun's SQLite selection is one-shot. */
function probeBunSqliteLibrary(e) {
const t = materializeRuntimeProcessScriptFile({
fileName: runtimeProcessScriptEntrypoints.bunSqliteLibraryProbe.fileName,
source: BUN_SQLITE_LIBRARY_PROBE_SOURCE
});
try {
const n = fileURLToPath(t.url);
const r = path.dirname(n);
const i = path.join(r, "bunfig.toml");
fs.writeFileSync(i, "", {
mode: 384,
flag: "wx"
});
const a = {};
for (const e of [
"SystemRoot",
"SYSTEMROOT",
"WINDIR",
"TEMP",
"TMP",
"TMPDIR"
]) if (process.env[e]) a[e] = process.env[e];
const o = spawnSync(process.execPath, [
"--no-install",
"--no-env-file",
`--config=${i}`,
n,
path.resolve(e)
], {
cwd: r,
env: resolveRuntimeScriptEnv(a),
encoding: "utf8",
stdio: [
"ignore",
"pipe",
"pipe"
],
timeout: 5e3,
killSignal: "SIGKILL",
maxBuffer: 4096
});
if (o.error) throw o.error;
let s;
try {
s = JSON.parse(o.stdout);
} catch {
throw new Error("SQLite library probe returned invalid output");
}
if (typeof s !== "object" || s === null || Array.isArray(s) || !("protocol" in s) || s.protocol !== 1) throw new Error("SQLite library probe returned invalid output");
if (o.status !== 0) throw new Error("error" in s && typeof s.error === "string" ? s.error.slice(0, 512) : `SQLite library probe failed (${o.signal ?? o.status})`);
if (!("version" in s) || typeof s.version !== "string" || s.version.length > 64 || !("extensionLoadingSupported" in s) || typeof s.extensionLoadingSupported !== "boolean") throw new Error("SQLite library probe returned invalid output");
return {
version: s.version,
extensionLoadingSupported: s.extensionLoadingSupported
};
} finally {
t.dispose();
}
}
//#endregion
//#region src/infra/bun-sqlite-library.ts
const WORKER_SELECTION_KEY = "openclaw.bunSqliteLibrarySelection";
const WORKER_CAPABILITIES_KEY = "openclaw.sqliteRuntimeCapabilities";
const SQLITE_NATIVE_RUNTIME_ADMISSION_KEY = "openclaw.sqliteNativeRuntimeAdmission";
function createCapabilities(e) {
let t;
let n;
let r = 0;
const i = Object.freeze({
explicitSqliteCloseReleasesNativeResources: false,
decided: false,
reason: "SQLite close capability has not been decided"
});
function decide(e) {
if (!t) {
t = Object.freeze(e);
setEnvironmentData(WORKER_CAPABILITIES_KEY, t);
if (t.explicitSqliteCloseReleasesNativeResources && r > 0) process.emitWarning(`SQLite close became capable after ${r} topology owners were created; those owners remain conservative`, { code: "SQLITE_EARLY_TOPOLOGY" });
}
return t;
}
function conservative(e) {
return {
explicitSqliteCloseReleasesNativeResources: false,
decided: true,
reason: e
};
}
function settled() {
if (t) return t;
if (!process.versions.bun) return decide({
explicitSqliteCloseReleasesNativeResources: true,
decided: true,
reason: "Node runtime"
});
if (process.platform === "win32") return decide(conservative("Bun Windows native-close conformance is not qualified"));
if (!isMainThread) return decide({
...i,
reason: "Parent did not complete SQLite close admission",
...getEnvironmentData(WORKER_CAPABILITIES_KEY)
});
}
return {
get() {
return settled() ?? i;
},
capture() {
const e = settled() ?? i;
if (!e.decided) r += 1;
return e.explicitSqliteCloseReleasesNativeResources;
},
initialize() {
n ??= (async () => {
e();
const t = settled();
if (t) return t;
try {
if (parseDiagnosticEnvFlags(process.env.OPENCLAW_DIAGNOSTICS).flags.some((e) => e.toLowerCase() === "sqlite.close.conservative")) return decide(conservative("SQLite close optimization disabled by internal diagnostic flag"));
const { probeSqliteNativeClose: e } = await import("./bun-sqlite-close-probe-B5lMS0mP.mjs");
return decide({
...await e(),
decided: true
});
} catch (e) {
return decide(conservative(`SQLite close check failed: ${String(e)}`));
}
})();
return n;
}
};
}
function selectLibrary(e) {
const { Database: t } = createRequire(import.meta.url)("bun:sqlite");
t.setCustomSQLite(e);
}
function createSelector() {
let e;
let t;
return (n = {}) => {
if (t) throw t;
if (e) return e;
const r = n.explicitPath ?? (process.env.OPENCLAW_SQLITE_LIBRARY?.trim() || void 0);
if (!process.versions.bun || process.platform !== "darwin") {
e = r ? {
source: "runtime",
ignoredOverride: "OPENCLAW_SQLITE_LIBRARY requires Bun on macOS"
} : { source: "runtime" };
return e;
}
const i = n.standaloneRoot ?? resolveStandaloneSidecarRoot();
const a = r === void 0 && i !== void 0 ? posix.join(i, "lib/libsqlite3.dylib") : void 0;
const o = process.env.HOMEBREW_PREFIX?.trim();
const s = r !== void 0 ? [r] : [.../* @__PURE__ */ new Set([
...a ? [a] : [],
...o ? [posix.join(o, "opt/sqlite/lib/libsqlite3.dylib")] : [],
"/opt/homebrew/opt/sqlite/lib/libsqlite3.dylib",
"/usr/local/opt/sqlite/lib/libsqlite3.dylib",
"/opt/local/lib/libsqlite3.dylib"
])];
const c = [];
for (const n of s) {
const i = r !== void 0 ? "env" : n === a ? "bundled" : "discovered";
let o;
let s = true;
try {
try {
o = probeBunSqliteLibrary(n);
} catch (e) {
s = existsSync(n);
throw s ? e : new Error("missing file", { cause: e });
}
if (!isSqliteWalResetSafeVersion(o.version)) throw new Error(`SQLite version ${o.version} below the WAL safety floor`);
if (!o.extensionLoadingSupported) throw new Error("built with SQLITE_OMIT_LOAD_EXTENSION");
} catch (e) {
if (r === void 0) {
if (s || n === a) c.push(`${n} (${e instanceof Error ? e.message : String(e)})`);
continue;
}
t = selectionError(n, e, i === "bundled");
throw t;
}
try {
selectLibrary(n);
} catch (e) {
t = selectionError(n, e, i === "bundled");
throw t;
}
e = {
source: i,
path: n,
version: o.version,
extensionLoadingSupported: true
};
return e;
}
t = /* @__PURE__ */ new Error(`No supported SQLite library for Bun on macOS (${process.arch})` + (c.length > 0 ? `; unusable: ${c.join(", ")}` : "") + ". Apple's system SQLite fails OpenClaw's read-only database connections. " + (a ? "Rebuild or replace the complete standalone artifact to restore its bundled SQLite library. " : "") + `Install one with brew install sqlite, or set OPENCLAW_SQLITE_LIBRARY to a libsqlite3.dylib built for ${process.arch}.`);
throw t;
};
}
function selectionError(e, t, n = false) {
const r = n ? "Rebuild or replace the complete standalone artifact (openclaw and runtime/), or set OPENCLAW_SQLITE_LIBRARY to a supported library." : "Fix or unset OPENCLAW_SQLITE_LIBRARY; install a supported library with brew install sqlite.";
return new Error(`Cannot use ${n ? "bundled " : ""}SQLite library ${e}: ${t instanceof Error ? t.message : String(t)}. ${r}`, { cause: t });
}
function createRuntimeSelector() {
const e = Boolean(process.versions.bun) && process.platform === "darwin";
let t;
if (e && !isMainThread) t = getEnvironmentData(WORKER_SELECTION_KEY);
const n = createSelector();
let r = false;
return (i) => {
const a = t ?? n(i);
if (e && isMainThread && !r) {
setEnvironmentData(WORKER_SELECTION_KEY, Object.freeze({ ...a }));
r = true;
}
return a;
};
}
function runtimeSelector() {
return resolveGlobalSingleton(Symbol.for("openclaw.bunSqliteLibrarySelection"), createRuntimeSelector);
}
function capabilities() {
const e = runtimeSelector();
return e.capabilities ??= createCapabilities(e);
}
function getSqliteRuntimeCapabilities() {
return capabilities().get();
}
/** A topology owner keeps this snapshot for placement and paired native retirement. */
function captureSqliteWorkerClosePolicy() {
return capabilities().capture();
}
/** Retained supervisors forward the caller's current facts when creating each descendant. */
function captureSqliteWorkerEnvironmentData(e = getEnvironmentData(SQLITE_DATABASE_ADMISSIONS_KEY)) {
return [
[WORKER_SELECTION_KEY, ensureSqliteLibrarySelected()],
[WORKER_CAPABILITIES_KEY, getSqliteRuntimeCapabilities()],
[SQLITE_NATIVE_RUNTIME_ADMISSION_KEY, getEnvironmentData(SQLITE_NATIVE_RUNTIME_ADMISSION_KEY)],
[SQLITE_DATABASE_ADMISSIONS_KEY, e],
[PROCESS_MACHINE_IDENTITY_KEY, getEnvironmentData(PROCESS_MACHINE_IDENTITY_KEY)]
];
}
/** Await at runtime admission, before any consumer chooses a worker topology. */
function initializeSqliteRuntimeCapabilities() {
return capabilities().initialize();
}
/** Select once, before any SQLite open; shared across CLI and bundled SDK module graphs. */
function ensureSqliteLibrarySelected(e) {
return runtimeSelector()(e);
}
//#endregion
export { getSqliteRuntimeCapabilities as a, ensureSqliteLibrarySelected as i, captureSqliteWorkerClosePolicy as n, initializeSqliteRuntimeCapabilities as o, captureSqliteWorkerEnvironmentData as r, SQLITE_NATIVE_RUNTIME_ADMISSION_KEY as t };