UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

412 lines (411 loc) • 18.2 kB
import { L as resolvePositiveTimerTimeoutMs, R as resolveTimerTimeoutMs, z as resolveTimestampMsToIsoString } from "./number-coercion-D6u-4YD8.mjs"; import { t as hasErrnoCode } from "./errno-DFcoqIT9.mjs"; import { n as resolveIdentityPathViaExistingAncestorSync } from "./boundary-path-C2gXEiXe.mjs"; import { r as resolveStateDir } from "./state-dir-DiG0gXzD.mjs"; import { m as resolveConfigPath, v as resolveGatewayLockDir } from "./paths-DAcAg5aV.mjs"; import { a as getOpenClawDatabaseMaintenanceScope } from "./openclaw-state-maintenance-context-D6i7Zdhn.mjs"; import { n as readProcessMachineIdentity } from "./current-machine-identity-DYZ3ln3p.mjs"; import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs"; import { s as resolveOpenClawStateSqlitePath } from "./openclaw-state-db.paths-R3ArRCcz.mjs"; import { n as createOpenClawDatabaseMaintenanceScope } from "./openclaw-state-db-async-lifecycle-CH8q4Sdl.mjs"; import { a as isPidDefinitelyDead, i as isPidAlive, t as getFileLockProcessStartTime } from "./pid-alive-D899x-ak.mjs"; import { D as LockPayloadSchema, M as parseGatewayLockPayload, N as readGatewayLockProcessNamespace, T as GatewayLockNamespaceError, d as resolveGatewayStateOwnerPath, f as tryAcquireGatewayStateOwner, j as describeGatewayLockHolder, k as classifyGatewayLockProcessNamespace, p as tryBorrowGatewayStateOwner, t as acquireGatewayStateOwner, w as GATEWAY_OWNER_HEARTBEAT_STALE_MS, x as createGatewayStateProjection } from "./gateway-state-owner-Bnv5owvG.mjs"; import { r as sha256HexPrefixCore } from "./node-crypto-B6yuTjmm.mjs"; import "./crypto-digest-B2m8wIBj.mjs"; import { t as GatewayStateOwnerContentionError } from "./gateway-state-owner-errors-DI3mhN4z.mjs"; import { t as acquireFileLockSync } from "./file-lock-manager-DJ_fctTe.mjs"; import { t as classifyOpenClawArgv } from "./gateway-process-argv-DBr2gU61.mjs"; import { t as acquireWithWait } from "./acquire-with-wait--M6IyZwQ.mjs"; import { t as ensureOpenClawStatePermissions } from "./openclaw-state-db-permissions-yFUWKbh-.mjs"; import { a as readGatewayLockProcessCmdline, n as assertGatewayOwnerLeaseStopped, o as readGatewayLockProcessStartTime, r as readGatewayOwnerLease, t as acquireGatewayOwnerLease } from "./gateway-owner-lease-I0ETcEQK.mjs"; import { a as assertDatabasePortStartupAllowed, i as assertDatabasePortRecoveryAllowed, t as DatabasePortRecoveryError } from "./database-port-recovery-DDaR-V_Q.mjs"; import fs from "node:fs"; import path from "node:path"; import { randomUUID } from "node:crypto"; import fs$1 from "node:fs/promises"; //#region src/infra/gateway-startup-owner.ts const GATEWAY_STARTUP_BUDGET_MS = 3e5; function captureStalledGatewayStartup(e = process.env) { const t = resolveOpenClawStateSqlitePath(e); const n = resolveGatewayStateOwnerPath(t); let r; try { r = fs.readFileSync(n, "utf8"); } catch (e) { if (hasErrnoCode(e, "ENOENT")) return; throw e; } const i = parseGatewayLockPayload(r); const a = Date.now() - Date.parse(i?.createdAt ?? ""); if (!i || (i.role ?? "gateway") !== "gateway" || i.pid === process.pid || !Number.isFinite(a) || a <= GATEWAY_STARTUP_BUDGET_MS || i.startTime === void 0 || !isPidAlive(i.pid) || classifyGatewayLockProcessNamespace(i, n) !== "same") return; const isListening = () => { const t = readGatewayOwnerLease({ env: e, current: true }); return t && t.owner === i.ownerId && (t.listeningAt !== void 0 || i.startupPhase === void 0); }; if (isListening()) return; const assertCurrent = () => { if (fs.readFileSync(n, "utf8") !== r || !isPidAlive(i.pid) || getFileLockProcessStartTime(i.pid, e) !== i.startTime || isListening()) throw new Error(`Gateway startup owner pid ${i.pid} changed; process preserved`); }; return { pid: i.pid, description: `Gateway pid ${i.pid} has been stuck in startup for ${Math.floor(a / 1e3)} s without a listening readiness fact`, assertCurrent, confirmStopped() { if (isPidAlive(i.pid)) throw new Error(`Gateway startup pid ${i.pid} exit could not be confirmed`); const e = tryAcquireGatewayStateOwner(t); if (!e) throw new Error("Gateway state ownership is still held after startup stop"); e.release(); } }; } //#endregion //#region src/infra/gateway-lock.ts const GATEWAY_LIFECYCLE_LOCK_TIMEOUT_MS = 3e5; const log = createSubsystemLogger("gateway"); function isSameGatewayLockIdentity(e, t) { if (e.ownerId && t.ownerId) return e.ownerId === t.ownerId; return e.pid === t.pid && e.createdAt === t.createdAt && e.startTime === t.startTime; } var GatewayLockError = class extends Error { constructor(e, t, n) { super(e); this.cause = t; this.databasePath = n; this.name = "GatewayLockError"; } }; function isGatewayLifecycleContentionError(e) { return e instanceof GatewayLockError && e.cause instanceof GatewayStateOwnerContentionError; } const CMDLINE_EXEC_TIMEOUT_MS = 1e3; function resolveGatewayOwnerStatusSync(e, t, n, r = {}) { const remainingTimeoutMs = () => { r.signal?.throwIfAborted(); const e = r.deadlineMs === void 0 ? CMDLINE_EXEC_TIMEOUT_MS : r.deadlineMs - performance.now(); if (e <= 0) throw new GatewayLockError("Gateway lock inspection deadline expired"); return Math.max(1, Math.min(CMDLINE_EXEC_TIMEOUT_MS, Math.ceil(e))); }; remainingTimeoutMs(); const i = classifyGatewayLockProcessNamespace(t, r.lockPath); if (i !== "same") return i; const a = t?.role ?? "gateway"; if (!isPidAlive(e)) return isPidDefinitelyDead(e) ? "dead" : "unknown"; const o = t?.startTime; if (Number.isFinite(o)) { const t = readGatewayLockProcessStartTime(e, n, remainingTimeoutMs()); remainingTimeoutMs(); if (t != null) return t === o ? "alive" : "dead"; } const s = a === "agent-embedded" || a === "sqlite-maintenance" || a === "skill-workshop-apply"; const c = readGatewayLockProcessCmdline(e, n, remainingTimeoutMs(), r.deadlineMs); remainingTimeoutMs(); if (!c) return s || n === "linux" || r.trustUnknownCmdlineOwner === false ? "unknown" : "alive"; const l = a === "agent-embedded" || a === "sqlite-maintenance" ? void 0 : a === "skill-workshop-apply" ? "skills" : "gateway"; const u = classifyOpenClawArgv(c, l ? { command: l, pid: e } : { pid: e }); remainingTimeoutMs(); return u.kind === "openclaw" ? "alive" : "unknown"; } async function resolveGatewayOwnerStatus(...e) { return resolveGatewayOwnerStatusSync(...e); } async function readLockPayload(e, t = false, n) { try { const r = parseGatewayLockPayload(await fs$1.readFile(e, { encoding: "utf8", signal: n })); if (t && !r) throw new GatewayLockError("Gateway lock payload could not be verified"); return r; } catch (e) { n?.throwIfAborted(); if (t && !hasErrnoCode(e, "ENOENT")) throw new GatewayLockError("Gateway lock inspection is unavailable", e); return null; } } /** Read the same lock contract while a synchronous mutation admission is held. */ function readLockPayloadSync(e, t = false) { try { const n = parseGatewayLockPayload(fs.readFileSync(e, "utf8")); if (t && !n) throw new GatewayLockError("Gateway lock payload could not be verified"); return n; } catch (e) { if (t && !hasErrnoCode(e, "ENOENT")) throw new GatewayLockError("Gateway lock inspection is unavailable", e); return null; } } function shouldReclaimGatewayLock(e) { if (classifyGatewayLockProcessNamespace(e.payload, e.lockPath) === "unknown") throw new GatewayLockNamespaceError(e.payload ?? {}, e.lockPath); const t = e.payload?.pid; const n = t ? resolveGatewayOwnerStatusSync(t, e.payload, e.platform, { lockPath: e.lockPath }) : "unknown"; if (t) return n === "dead"; return false; } function resolveGatewayLockPaths(e, t) { const n = resolveStateDir(e); const r = resolveIdentityPathViaExistingAncestorSync(n); const i = t ?? resolveGatewayLockDir(r); const a = resolveConfigPath(e, n); const o = sha256HexPrefixCore(a, 8); return { configLockPath: path.join(i, `gateway.${o}.lock`), configPath: a, stateDir: r, stateLockPath: path.join(i, "gateway.state.lock"), ownerLockPath: resolveGatewayStateOwnerPath(path.join(r, "state", "openclaw.sqlite")) }; } async function readActiveGatewayLockPort(e = {}) { return (await readActiveGatewayLockIdentity(e))?.port; } async function readActiveGatewayLockIdentity(e = {}) { const t = e.env ?? process.env; const n = e.timeoutMs === void 0 ? void 0 : performance.now() + Math.max(0, e.timeoutMs); const { configLockPath: r, stateLockPath: i, ownerLockPath: a } = resolveGatewayLockPaths(t, e.lockDir); const o = await readVerifiedGatewayLockIdentity(a, e, n); if (o) return o; return await readVerifiedGatewayLockIdentity(r, e, n) ?? await readVerifiedGatewayLockIdentity(i, e, n); } async function readVerifiedGatewayLockIdentity(e, t, n) { const assertActive = () => { t.signal?.throwIfAborted(); if (n !== void 0 && performance.now() >= n) throw new GatewayLockError("Gateway lock inspection deadline expired"); }; assertActive(); const r = await readLockPayload(e, t.requireInspection, t.signal); assertActive(); if (!r || r.role && r.role !== "gateway" && !(t.includeEmbedded && r.role === "agent-embedded")) return; if (t.requireInspection && classifyGatewayLockProcessNamespace(r, e) === "unknown") { const t = new GatewayLockNamespaceError(r, e); throw new GatewayLockError(t.message, t); } const i = await resolveGatewayOwnerStatus(r.pid, r, t.platform ?? process.platform, { trustUnknownCmdlineOwner: false, deadlineMs: n, signal: t.signal, lockPath: e }); assertActive(); if (t.requireInspection && i !== "dead" && (i === "unknown" || !t.includeEmbedded && !r.port)) throw new GatewayLockError("Gateway lock owner identity could not be verified"); if (i !== "alive" || !t.includeEmbedded && !r.port) return; return { pid: r.pid, ...r.ownerId ? { ownerId: r.ownerId } : {}, ...r.cronOwnerProjection ? { cronOwnerProjection: r.cronOwnerProjection } : {}, createdAt: r.createdAt, port: r.port, ...r.startTime !== void 0 ? { startTime: r.startTime } : {} }; } /** Older supported Gateways publish state-local sidecars; never start over their live owner. */ async function assertHistoricalGatewayOwnerStopped(e, t) { for (const n of [e.stateLockPath, e.configLockPath]) { const r = await readLockPayload(n, true); if (!r) continue; if (classifyGatewayLockProcessNamespace(r, n) === "unknown") throw new GatewayLockNamespaceError(r, n); const i = await resolveGatewayOwnerStatus(r.pid, r, t.platform ?? process.platform, { trustUnknownCmdlineOwner: false, lockPath: n }); if (i !== "dead") throw new GatewayStateOwnerContentionError(path.join(e.stateDir, "state", "openclaw.sqlite"), void 0, describeGatewayLockHolder(r, n, i === "alive" ? "live" : "unknown"), { pid: r.pid, role: r.role }); } } async function acquireGatewayLock(e = {}) { const t = e.env ?? process.env; if (e.allowInTests !== true && (t.VITEST || t.NODE_ENV === "test")) return null; const n = e.databaseAccess === "none" ? "sqlite-maintenance" : e.role ?? "gateway"; const r = resolveGatewayLockPaths(t, e.lockDir); const i = path.join(r.stateDir, "state", "openclaw.sqlite"); const a = e.now ?? performance.now.bind(performance); const o = a(); const s = GATEWAY_OWNER_HEARTBEAT_STALE_MS + 5e3; const c = o + s; const l = resolveTimerTimeoutMs(e.timeoutMs, n === "gateway" ? GATEWAY_LIFECYCLE_LOCK_TIMEOUT_MS : n === "sqlite-maintenance" ? s : 0, 0); const u = Math.min(e.lifecycleDeadlineMs ?? Infinity, o + l); const d = readGatewayLockProcessStartTime(process.pid, e.platform ?? process.platform, CMDLINE_EXEC_TIMEOUT_MS); const f = { pid: process.pid, ownerId: randomUUID(), createdAt: resolveTimestampMsToIsoString(Date.now()), ...n === "gateway" ? { startupPhase: "starting" } : {}, configPath: r.configPath, stateDir: r.stateDir, role: n, processNamespace: readGatewayLockProcessNamespace(), machineIdentity: process.platform === "darwin" ? readProcessMachineIdentity() : void 0, ...n === "gateway" ? { cronOwnerProjection: "dynamic-default-v1" } : {}, ...typeof e.port === "number" && Number.isInteger(e.port) && e.port > 0 && e.port <= 65535 ? { port: e.port } : {}, ...typeof d === "number" && Number.isFinite(d) ? { startTime: d } : {} }; const p = getOpenClawDatabaseMaintenanceScope(); let m; if (n === "sqlite-maintenance" && p?.ownsSchemaMaintenance) { p.assertAdmission(); m = tryBorrowGatewayStateOwner(i); } let h; let g = false; let _; let v; try { v = m ?? await acquireWithWait({ deadlineMs: u, pollIntervalMs: resolvePositiveTimerTimeoutMs(e.pollIntervalMs, 250), now: a, sleep: e.sleep, acquire: async () => { h = void 0; e.assertCurrent?.(); f.createdAt = resolveTimestampMsToIsoString(Date.now()); const a = acquireGatewayStateOwner({ databasePath: i, payload: f, projectionPath: r.stateLockPath, getProjection: () => _ }); try { if (e.databasePortRecovery) { if (n !== "agent-embedded" && n !== "sqlite-maintenance") throw new Error("Database port recovery requires exclusive offline ownership"); assertDatabasePortRecoveryAllowed(r.stateDir, e.databasePortRecovery); } else assertDatabasePortStartupAllowed(r.stateDir); await assertHistoricalGatewayOwnerStopped(r, e); if (!e.databasePortRecovery && e.databaseAccess !== "none") try { await a.run(() => { if (n === "gateway") ensureOpenClawStatePermissions(i, t, { createDirectory: true }); return assertGatewayOwnerLeaseStopped(t, a, n === "sqlite-maintenance"); }); } catch (e) { h = { error: e }; throw e; } return a; } catch (e) { a.release(); throw e; } }, shouldRetry: (t) => { if (t instanceof GatewayLockNamespaceError && (n === "gateway" || n === "sqlite-maintenance")) { const n = Math.min(u, c) - a(); if (n <= 0) return false; if (!g) (e.onWait ?? log.warn)(`Waiting up to ${Math.ceil(n / 1e3)} seconds for the previous Gateway to release state; an unverifiable owner will not be reclaimed automatically. ${t.message}`); g = true; return { delayMs: Math.min(5e3, n) }; } if (n === "sqlite-maintenance" || !(t instanceof GatewayStateOwnerContentionError)) return false; if (!g && u > o && n === "gateway") log.warn(`waiting for Gateway state ownership held by another OpenClaw process, up to ${Math.ceil((u - o) / 1e3)} s`); g = true; return true; } }); } catch (n) { e.assertCurrent?.(); const r = `failed to acquire gateway state ownership${g ? `; waited ${Math.round(a() - o)}ms for Gateway state ownership` : ""}`; const s = n instanceof GatewayStateOwnerContentionError ? `${r}: ${n.message}. ${captureStalledGatewayStartup(t)?.description ?? "Stop the Gateway or wait for the current OpenClaw operation to finish"}. Run \`openclaw gateway stop\`, then retry.` : n instanceof GatewayLockNamespaceError ? n.message : n instanceof DatabasePortRecoveryError ? `${r}: ${n.message}` : r; throw new GatewayLockError(s, n, h && h.error === n ? i : void 0); } if (g && n === "gateway") log.info(`Gateway state ownership acquired after ${((a() - o) / 1e3).toFixed(1)} s`); const assertStateOwnerCurrent = (e, t) => { if (m) p?.assertOwnerCurrent(t); v.assertCurrent(); if (n !== "gateway" && n !== "agent-embedded" && _ && !_.verifyStillHeld()) throw new Error("OpenClaw Gateway ownership projection is no longer current"); if (e) { v.run(e); assertStateOwnerCurrent(void 0, t); } }; const assertDatabaseAccess = (t) => { assertStateOwnerCurrent(); if (e.databaseAccess === "none") throw new Error("Config-only ownership does not admit database access"); v.assertDatabaseAccess(t); }; const y = n === "sqlite-maintenance" ? createOpenClawDatabaseMaintenanceScope({ schemaMaintenance: true, assertOwnerCurrent: (e) => assertStateOwnerCurrent(void 0, e), assertDatabaseAccess }) : void 0; let b; try { assertStateOwnerCurrent(e.assertCurrent); const shouldReclaim = ({ payload: t }) => shouldReclaimGatewayLock({ lockPath: r.stateLockPath, payload: LockPayloadSchema.safeParse(t).data ?? null, platform: e.platform ?? process.platform }); if (!m) _ = createGatewayStateProjection(acquireFileLockSync(r.stateLockPath, { lockPath: r.stateLockPath, timeoutMs: 0, retry: { retries: 0 }, staleRecovery: "remove-if-unchanged", reentrantOwner: f.ownerId, payload: () => n === "gateway" ? f : { ...f, role: "agent-embedded" }, shouldReclaim, shouldRemoveStaleLock: shouldReclaim })); assertStateOwnerCurrent(); if (n === "gateway" && e.listenerMode && e.port) try { b = acquireGatewayOwnerLease({ env: t, port: e.port, mode: e.listenerMode, supervisor: e.supervisor ?? null, owner: f.ownerId }); await b.ready; } catch (e) { h = { error: e }; throw e; } } catch (e) { await b?.release(); _?.release(); v.release(); throw new GatewayLockError("failed to acquire gateway state ownership", e, h && h.error === e ? i : void 0); } let x; return { previousOwner: b?.previousOwner, lockPath: v.path, stateLockPath: r.stateLockPath, stateDir: r.stateDir, assertCurrent: assertStateOwnerCurrent, assertDatabaseAccess, markListening: () => { assertStateOwnerCurrent(); try { b?.markListening(); } catch { assertStateOwnerCurrent(); log.warn("Gateway listener bound, but startup readiness could not be recorded"); } }, run: (e) => { if (y) return y.run(e); assertStateOwnerCurrent(); return e(); }, release: () => x ??= (async () => { await b?.release(); await y?.close(); _?.release(); _ = void 0; v.release(); })().catch((e) => { x = void 0; throw e; }) }; } //#endregion export { isSameGatewayLockIdentity as a, readLockPayload as c, resolveGatewayOwnerStatus as d, captureStalledGatewayStartup as f, isGatewayLifecycleContentionError as i, readLockPayloadSync as l, GatewayLockError as n, readActiveGatewayLockIdentity as o, acquireGatewayLock as r, readActiveGatewayLockPort as s, GATEWAY_LIFECYCLE_LOCK_TIMEOUT_MS as t, resolveGatewayLockPaths as u };