UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

195 lines (194 loc) • 8.45 kB
import { a as resolveGlobalSingleton } from "./global-singleton-D7yf05nR.mjs"; import { t as runInDetachedAsyncContext } from "./detached-async-context-D_mi-wUl.mjs"; import { t as hasErrnoCode } from "./errno-DFcoqIT9.mjs"; import { n as sanitizeTerminalText } from "./safe-text-C80HAQ2e.mjs"; import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs"; import { accessSync, constants, statSync } from "node:fs"; import path from "node:path"; import fs$1 from "node:fs/promises"; import { execFile, spawnSync } from "node:child_process"; //#region src/infra/child-runtime-viability.ts const runtime = resolveGlobalSingleton(Symbol.for("openclaw.childRuntimeViability"), () => ({ observations: /* @__PURE__ */ new Map(), initialPath: process.execPath, initialIdentity: executableIdentity(process.execPath) })); const loaderFailure = /(?:dyld[^\n]*:\s*Library not loaded:|error while loading shared libraries:)/i; const ambiguousLoaderFailure = /(?:dyld[^\n]*:\s*Symbol not found:|symbol lookup error:|Error loading shared library|version [`'"][^`'"\r\n]+[`'"] not found)/i; function executableIdentity(e) { try { return formatExecutableIdentity(statSync(e)); } catch { return; } } function formatExecutableIdentity({ dev: e, ino: t, size: n, mtimeMs: r, mode: i }) { return `${e}:${t}:${n}:${r}:${i}`; } function publishRuntimeViability(e, t) { if (hasErrnoCode(t, "ENOENT") || hasErrnoCode(t, "ENOTDIR")) recordUnavailableRuntime(e, t); return { execPath: e, available: !(runtime.execPath === e && runtime.failure) }; } /** Read the launch/diagnostic owner's verdict without starting filesystem or child work. */ function getRecordedChildRuntimeViability() { return publishRuntimeViability(process.execPath); } /** Retained for existing synchronous OOM and SQLite callers. */ function readChildRuntimeViability(e) { const t = e?.execPath ?? process.execPath; if (runtime.execPath === t && runtime.failure) return { execPath: t, available: false }; try { accessSync(t, constants.X_OK); } catch (e) { return publishRuntimeViability(t, e); } return publishRuntimeViability(t); } /** Observe external runtime replacement without blocking the Gateway thread. */ async function prepareChildRuntimeViability(e) { const t = e?.execPath ?? process.execPath; let n = runtime.observations.get(t); if (!n) { n = (async () => { let e = !(runtime.execPath === t && runtime.failure); if (e) try { const n = await probeChildRuntimeExecutable(t); const r = await fs$1.stat(t).then(formatExecutableIdentity, () => void 0); e = !classifyRuntimeProbe(t, n, r, n.error); } catch (n) { e = publishRuntimeViability(t, n).available; } return e; })().finally(() => runtime.observations.delete(t)); runtime.observations.set(t, n); } const r = await n; return { publish: () => ({ execPath: t, available: r && publishRuntimeViability(t).available }) }; } /** The run loop owns recovery; runtime observations publish the first diagnosis. */ function registerChildRuntimeRecovery(e) { runtime.recover = e; recoverUnavailableRuntime(); return () => { if (runtime.recover === e) runtime.recover = void 0; }; } function recoverUnavailableRuntime() { if (runtime.execPath !== process.execPath || !runtime.failure || !runtime.recover || runtime.recoveryStarted) return; runtime.recoveryStarted = true; const e = runtime.recover; runInDetachedAsyncContext(() => Promise.resolve().then(e).catch(() => ({ status: "report-only", reason: "Automatic runtime recovery is report-only: service or restart preparation failed. Inspect the service runtime and restart through its owner." })).then((e) => { createSubsystemLogger("gateway/runtime").warn(`${e.status}: ${e.reason}`); })); } function runtimeProbeOptions(e = {}) { return { encoding: "utf8", cwd: e.cwd ?? path.parse(process.execPath).root, env: e.env ?? { ...process.env, NODE_OPTIONS: void 0 }, timeout: 1e3, maxBuffer: 8192 }; } /** Native launch avoids recursing into the command owner's runtime diagnosis. */ function probeChildRuntimeExecutable(e, t = {}) { return new Promise((n) => { execFile(e, ["--version"], runtimeProbeOptions(t), (e, t, r) => n({ stdout: t, stderr: r, error: e ?? void 0, status: e ? typeof e.code === "number" ? e.code : null : 0, signal: e?.signal ?? null })); }); } function formatMissingChildRuntimeWarning(e) { return e.available ? void 0 : `The Node.js runtime this Gateway started with (${sanitizeTerminalText(e.execPath)}) can no longer start worker processes, likely because it was upgraded or removed. Restart the Gateway.`; } /** A permanent launch failure belongs to the runtime, not to any one worker pool. */ function assertChildRuntimeAvailable() { if (runtime.execPath === process.execPath && runtime.failure) throw runtime.failure; } function recordUnavailableRuntime(e, t, n) { if (runtime.execPath === e && runtime.failure) return runtime.failure; runtime.execPath = e; const r = formatMissingChildRuntimeWarning({ execPath: e, available: false }); const i = n?.trim(); runtime.failure = Object.assign(new Error(i ? `${r}\n${i}` : r, { cause: t }), { code: "NODE_RUNTIME_UNAVAILABLE" }); createSubsystemLogger("gateway/runtime").error(runtime.failure.message); recoverUnavailableRuntime(); return runtime.failure; } function needsRuntimeProbe(e) { return Boolean(e.error || e.signal === "SIGABRT" || ambiguousLoaderFailure.test(e.stderr ?? "")); } function classifyRuntimeProbe(e, t, n, r) { if (runtime.execPath === e && runtime.failure) return runtime.failure; const i = e !== runtime.initialPath || n !== runtime.initialIdentity; return loaderFailure.test(t.stderr) || ambiguousLoaderFailure.test(t.stderr) || hasErrnoCode(t.error, "ENOENT") || hasErrnoCode(t.error, "ENOTDIR") || i && (t.signal === "SIGABRT" || hasErrnoCode(t.error, "ENOEXEC") || hasErrnoCode(t.error, "EACCES") || hasErrnoCode(t.error, "EPERM")) ? recordUnavailableRuntime(e, r, t.stderr) : void 0; } /** The public synchronous SQLite reader retains immediate failure classification. */ function classifyChildRuntimeFailure(e) { if (e.started) return; const t = e.execPath ?? process.execPath; if (runtime.execPath === t && runtime.failure) return runtime.failure; if (loaderFailure.test(e.stderr ?? "") || e.error && !readChildRuntimeViability({ execPath: t }).available) return recordUnavailableRuntime(t, e.error, e.stderr); if (!needsRuntimeProbe(e)) return; return classifyRuntimeProbe(t, spawnSync(t, ["--version"], runtimeProbeOptions()), t === runtime.initialPath ? executableIdentity(t) : void 0, e.error); } async function prepareChildRuntimeFailure(e) { if (e.started) return; const t = e.execPath ?? process.execPath; if (runtime.execPath === t && runtime.failure) return runtime.failure; if (loaderFailure.test(e.stderr ?? "") || e.error && !(await prepareChildRuntimeViability({ execPath: t })).publish().available) return recordUnavailableRuntime(t, e.error, e.stderr); if (e.error || !needsRuntimeProbe(e)) return; return classifyRuntimeProbe(t, await probeChildRuntimeExecutable(t), t === runtime.initialPath ? await fs$1.stat(t).then(formatExecutableIdentity, () => void 0) : void 0, e.error); } /** Capture startup evidence; the owner reads the diagnosis after native completion. */ function observeChildRuntime(e, t = process.execPath) { let n = false; let r; let i = ""; e.once("message", () => { n = true; i = ""; }); e.on("error", (e) => { r ??= e; }); const captureStderr = (e) => { if (!n) i = (i + e.toString()).slice(-8192); }; e.stderr?.on("data", captureStderr); return () => e.exitCode === 0 && !r ? void 0 : classifyChildRuntimeFailure({ execPath: t, error: r, stderr: i, signal: e.signalCode, started: n }); } /** Missing commands and missing working directories are not runtime failures. */ function formatChildRuntimeSpawnWarning(e) { if (e instanceof Error && "path" in e && e.path === process.execPath) return classifyChildRuntimeFailure({ error: e })?.message; } //#endregion export { getRecordedChildRuntimeViability as a, prepareChildRuntimeViability as c, registerChildRuntimeRecovery as d, formatMissingChildRuntimeWarning as i, probeChildRuntimeExecutable as l, classifyChildRuntimeFailure as n, observeChildRuntime as o, formatChildRuntimeSpawnWarning as r, prepareChildRuntimeFailure as s, assertChildRuntimeAvailable as t, readChildRuntimeViability as u };