openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
1,373 lines • 50.7 kB
JavaScript
import { c as hasErrnoCode, f as coerceErrorMessage, h as extractErrorCode, n as resolveGatewayLockDir, r as resolveGatewayLockDirForCanonicalStateDir, u as isErrno, y as toErrorObject } from "./paths-0xDagtub.mjs";
import { p as isRecord } from "./utils-BclMknzT.mjs";
import { W as resolveGlobalSingleton, r as normalizeWindowsPathForComparison } from "./path-guards-quCEQx1i.mjs";
import { i as isPidDefinitelyDead, r as isPidAlive, t as getFileLockProcessStartTime } from "./pid-alive-TveEV-hP.mjs";
import { s as OPENCLAW_SQLITE_BUSY_TIMEOUT_MS } from "./openclaw-state-db-contract-DpFGI8ZZ.mjs";
import { _ as resolveIdentityPathViaExistingAncestor, v as resolveIdentityPathViaExistingAncestorSync } from "./redact-BRF0hr6G.mjs";
import { t as createSubsystemLogger } from "./subsystem-CeOCPr4l.mjs";
import { i as runInDetachedAsyncContext } from "./plugin-instance-invocation-DLc0_aJ8.mjs";
import { t as createDeferredCore } from "./deferred-D0La5CRk.mjs";
import { t as settlesWithin } from "./settle-within-xlNWuWou.mjs";
import { t as isPromiseLike } from "./promise-like-aMoWEh5w.mjs";
import { a as resolveOpenClawStateDirForDatabasePath } from "./openclaw-state-db.paths-5PCLNGIM.mjs";
import { l as runWithSqliteCleanup } from "./sqlite-lifecycle-errors-D4bxhyEQ.mjs";
import { a as requestCliParentTermination, i as getCliParentPid, o as RESPAWN_SIGNAL_FORCE_KILL_GRACE_MS } from "./cli-invocation-CSfpG5sl.mjs";
import { n as readProcessMachineIdentity } from "./current-machine-identity-DFuZQ9km.mjs";
import { t as normalizeSqliteNonNegativeInteger } from "./sqlite-busy-timeout-BbWQYMTz.mjs";
import { n as sha256HexPrefixCore } from "./node-crypto-CWAQhBWK.mjs";
import { l as getCommandPositionalsWithRootOptions, t as classifyOpenClawArgv } from "./gateway-process-argv-DB5Y-Mad.mjs";
import { r as resolveRuntimeWorkerThreadExecArgv } from "./runtime-worker-url-BEfqe_m6.mjs";
import { a as resolveRuntimeProcessEntrypointUrl } from "./runtime-process-url-sztU0Vcb.mjs";
import { n as createCpuTrackedWorker, p as captureRuntimeWorkerSource } from "./worker-cpu-sx0tpDpz.mjs";
import { s as getOpenClawDatabaseMaintenanceScope } from "./openclaw-state-db-async-lifecycle-DLH47xBr.mjs";
import { r as recordWorkerMessage } from "./worker-message-metrics-DnNsI1Wf.mjs";
import { d as object, h as union, m as string, o as discriminatedUnion, p as strictObject, r as array, s as literal, t as _enum, u as number } from "./schemas-DA6xYxQu.mjs";
import { a as StateDatabaseOfflineMaintenanceError, i as StateDatabaseMaintenanceScopeError, n as StateDatabaseAccessError, o as createGatewayStateProcessOwnerRetiredError, r as StateDatabaseAdmissionPendingError, t as GatewayStateOwnerContentionError } from "./gateway-state-owner-errors-ccLhqQIq.mjs";
import { AsyncLocalStorage } from "node:async_hooks";
import { spawnSync } from "node:child_process";
import fsSync, { chmodSync, fstatSync, statSync, unlinkSync, writeFileSync } from "node:fs";
import path from "node:path";
import { randomUUID } from "node:crypto";
import os from "node:os";
import { MessageChannel, isMainThread } from "node:worker_threads";
import { acquireFileLockSync } from "@openclaw/fs-safe/file-lock";
//#region src/utils/zod-parse.ts
/**
* Null-returning Zod parse helpers for plugin and runtime boundaries.
*
* Callers use these where invalid external payloads should be ignored or
* recovered from without constructing and catching validation errors.
*/
/** Safely validates an unknown value with a Zod schema, returning null on validation failure. */
function safeParseWithSchema(e, t) {
const n = e.safeParse(t);
return n.success ? n.data : null;
}
/** Parses JSON, then safely validates it with a Zod schema, returning null for parse or schema failures. */
function safeParseJsonWithSchema(e, t) {
try {
return safeParseWithSchema(e, JSON.parse(t));
} catch {
return null;
}
}
//#endregion
//#region src/infra/stale-lock-file.ts
function readLockFileOwnerPayload(e) {
if (!e) return null;
return {
pid: typeof e.pid === "number" && Number.isInteger(e.pid) && e.pid > 0 ? e.pid : void 0,
createdAt: typeof e.createdAt === "string" ? e.createdAt : void 0,
starttime: typeof e.starttime === "number" && Number.isInteger(e.starttime) && e.starttime >= 0 ? e.starttime : void 0
};
}
/** Capture only the bounded facts used by this exact stale decision. Never
* resample the owner after failure or copy arbitrary sidecar payload fields. */
function inspectStaleLockOwner(e) {
const t = readLockFileOwnerPayload(e.payload);
if (!t?.pid) return null;
if ((e.isPidDefinitelyDead ?? isPidDefinitelyDead)(t.pid)) return {
reason: "owner-process-exited",
pid: t.pid,
recordedStarttime: t.starttime ?? null,
observedStarttime: null
};
const n = t.starttime === void 0 ? null : (e.getProcessStartTime ?? getFileLockProcessStartTime)(t.pid);
const r = {
pid: t.pid,
recordedStarttime: t.starttime ?? null,
observedStarttime: n
};
const i = process.platform === "darwin" && t.starttime !== void 0 && t.starttime > 1e10 ? Math.floor(t.starttime / 1e6) : t.starttime;
if (n !== null && n !== i) return {
reason: "owner-starttime-changed",
...r
};
return null;
}
function isLockOwnerDefinitelyStale(e) {
return inspectStaleLockOwner(e) !== null;
}
//#endregion
//#region src/infra/update-managed-service-handoff-schema.ts
const text = string().min(1).max(4096);
const nativeProcessIdentityShape = {
pid: number().int().positive(),
startIdentity: text.max(128)
};
const processIdentitySchema = strictObject({
...nativeProcessIdentityShape,
startIdentitySource: literal("argv-sha256").nullable().optional()
}).refine(({ startIdentity: e, startIdentitySource: t }) => t === "argv-sha256" ? /^win32-argv-sha256:[a-f0-9]{64}$/.test(e) : !e.startsWith("win32-argv-sha256:"));
const managedHandoffBootSchema = union([
strictObject({
platform: _enum(["linux", "darwin"]),
identity: string().regex(/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i)
}),
strictObject({
platform: literal("win32"),
identity: string().regex(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{7}Z$/)
}),
strictObject({
platform: literal("freebsd"),
identity: string().regex(/^[a-f0-9]{32}$/)
})
]);
const nativeLifetimeSchema = strictObject({
kind: literal("native"),
unit: text,
scope: text,
placement: discriminatedUnion("kind", [strictObject({ kind: literal("pending") }), strictObject({
kind: literal("attached"),
invocation: string().regex(/^[a-f0-9]{32}$/i)
})])
});
const cancellationProtocol = literal("original-cancellation-v1");
const updateAction = strictObject({
kind: literal("update"),
mutationProtocol: cancellationProtocol
}).extend({
mutationProtocol: cancellationProtocol.optional(),
custody: _enum(["reserved", "bound"]).optional()
});
const actionSchema = discriminatedUnion("kind", [updateAction, strictObject({
kind: literal("triage"),
phase: _enum([
"reserved",
"running",
"closing",
"closed",
"uncertain"
]),
lifetime: discriminatedUnion("kind", [strictObject({
kind: literal("foreground"),
boot: managedHandoffBootSchema
}), nativeLifetimeSchema])
}).refine((e) => e.phase !== "running" || e.lifetime.kind !== "native" || e.lifetime.placement.kind === "attached")]);
const sourcePath = text.refine(path.isAbsolute, "Native source path must be absolute");
const digest = string().regex(/^[a-f0-9]{64}$/);
const nativeBorrowerSourceSchema = strictObject({
runId: text,
transactionId: text,
claimId: text,
revision: number().int().nonnegative(),
recordSha256: digest,
serviceKey: sourcePath,
configPaths: array(sourcePath).min(1).max(512),
lifetimeId: text
});
const nativeBorrowerSchema = strictObject({
id: string().uuid(),
phase: _enum(["reserved", "admitted"]),
source: nativeBorrowerSourceSchema
});
const commonPayload = {
executor: processIdentitySchema,
helper: processIdentitySchema,
action: actionSchema
};
const originalUpdateSchema = strictObject({
version: literal(2),
executor: processIdentitySchema,
helper: processIdentitySchema,
action: updateAction
});
const originalGenerationSchema = strictObject({
key: text,
owner: text,
payload: string().min(1),
updatedAt: number().int().nonnegative()
});
const cancellingPayloadSchema = strictObject({
version: literal(4),
executor: processIdentitySchema,
helper: processIdentitySchema,
action: updateAction,
cancellation: originalGenerationSchema
}).refine((e) => {
const t = safeParseJsonWithSchema(originalUpdateSchema, e.cancellation.payload);
return t !== null && JSON.stringify(t.helper) === JSON.stringify(e.helper) && JSON.stringify(t.executor) === JSON.stringify(e.executor) && JSON.stringify(t.action) === JSON.stringify(e.action) && (JSON.stringify(e.helper) === JSON.stringify(e.executor) || t.action.mutationProtocol === "original-cancellation-v1");
});
const currentPayloadSchema = strictObject({
version: literal(2),
...commonPayload,
mutationOriginal: originalGenerationSchema.optional()
}).refine((e) => {
if (!e.mutationOriginal) return true;
const t = safeParseJsonWithSchema(originalUpdateSchema, e.mutationOriginal.payload);
return t !== null && !e.mutationOriginal.key.includes("/.openclaw-update-child-") && t.action.mutationProtocol === "original-cancellation-v1";
});
const payloadSchema = discriminatedUnion("version", [
cancellingPayloadSchema,
currentPayloadSchema,
strictObject({
version: literal(3),
...commonPayload,
action: strictObject({ kind: literal("update") }),
nativeBorrower: nativeBorrowerSchema
})
]);
const retiredPayloadSchema = strictObject({
version: literal(1),
...nativeProcessIdentityShape
});
//#endregion
//#region src/infra/update-managed-service-handoff-boot.ts
/** Bind the lease environment without caching boot identity or selecting an OS early. */
function createManagedHandoffBootIdentityReader(e) {
return function bootIdentity() {
let t;
const n = process.platform === "android" ? "linux" : process.platform;
if (n === "linux") t = fsSync.readFileSync("/proc/sys/kernel/random/boot_id", "utf8").trim();
else if ([
"freebsd",
"darwin",
"win32"
].includes(process.platform)) {
const n = process.platform === "freebsd";
const r = process.platform === "win32";
const i = spawnSync(r ? "powershell.exe" : n ? "/sbin/sysctl" : "/usr/sbin/sysctl", r ? [
"-NoProfile",
"-NonInteractive",
"-Command",
"(Get-CimInstance -ClassName Win32_OperatingSystem).LastBootUpTime.ToUniversalTime().ToString('o')"
] : n ? ["-b", "kern.boot_id"] : ["-n", "kern.bootsessionuuid"], {
env: e,
...n ? { maxBuffer: 16 } : {
encoding: "utf8",
windowsHide: true
},
timeout: r ? 5e3 : 1e3,
killSignal: "SIGKILL",
stdio: [
"ignore",
"pipe",
"ignore"
]
});
if (!i.error && i.status === 0) t = n ? Buffer.isBuffer(i.stdout) && i.stdout.length === 16 ? i.stdout.toString("hex") : void 0 : i.stdout.toString().trim();
}
const r = {
platform: n,
identity: n === "win32" ? t : t?.toLowerCase()
};
const i = managedHandoffBootSchema.safeParse(r);
if (!i.success) throw new Error("OS boot identity unavailable; run openclaw triage manually");
return i.data;
};
}
//#endregion
//#region src/infra/gateway-lock-payload.ts
const GATEWAY_OWNER_HEARTBEAT_MS = 15e3;
const GATEWAY_OWNER_HEARTBEAT_STALE_MS = 9e4;
const [uuidBoot, windowsBoot, freebsdBoot] = managedHandoffBootSchema.options;
const host = string().min(1);
const MachineIdentitySchema = string().regex(/^[a-f0-9]{64}$/u);
const GatewayProcessNamespaceSchema = discriminatedUnion("platform", [
uuidBoot.extend({
host,
platform: literal("linux"),
pidNsInode: string().min(1)
}),
uuidBoot.extend({
host,
platform: literal("darwin")
}),
windowsBoot.extend({
host,
identity: windowsBoot.shape.identity.optional()
}),
freebsdBoot.extend({ host })
]);
let processNamespace;
/** Cache OS subprocess failures too; only Linux's cheap /proc probes remain retryable. */
function readGatewayLockProcessNamespace() {
if (processNamespace?.platform === process.platform && (processNamespace.value !== null || process.platform !== "linux" && process.platform !== "android")) return processNamespace.value;
try {
const e = process.platform === "win32" ? { platform: "win32" } : createManagedHandoffBootIdentityReader(process.env)();
const t = GatewayProcessNamespaceSchema.parse({
host: os.hostname(),
...e,
...e.platform === "linux" ? { pidNsInode: fsSync.readlinkSync("/proc/self/ns/pid").match(/^pid:\[(\d+)\]$/u)?.[1] } : {}
});
processNamespace = {
platform: process.platform,
value: t
};
return t;
} catch {
processNamespace = {
platform: process.platform,
value: null
};
return null;
}
}
/** Diagnostic facts never grant ownership; callers still classify the recorded holder. */
function describeGatewayLockHolder(e, t, n) {
const r = GatewayProcessNamespaceSchema.safeParse(e.processNamespace).data;
let i = e.heartbeatAt;
if (t) try {
i = fsSync.statSync(t).mtimeMs;
} catch {}
const a = i === void 0 ? void 0 : Date.now() - i;
const o = `${r?.host ?? e.host ?? "unknown host"}${r?.platform === "linux" ? `/pid-ns ${r.pidNsInode}` : ""}`;
const s = n === "live" ? `The holder ${e.pid} is alive on this host, stop it first` : n === "unknown" ? "Stop the holder before retrying; if it has already stopped, run `openclaw gateway recover-lock` to inspect and explicitly recover the unchanged owner" : "Run this command inside the Gateway container or with a shared PID namespace; if the holder has stopped, run `openclaw gateway recover-lock` to inspect and explicitly recover the unchanged owner";
return `holder ${e.pid ?? "unknown"} at ${o}, last renewed ${a === void 0 ? "at an unknown time" : `${Math.max(0, Math.floor(a / 1e3))} s ago`}. ${s}.`;
}
var GatewayLockNamespaceError = class extends Error {
constructor(e, t) {
super(`cannot verify Gateway ownership from this process; heartbeat age does not prove that the holder stopped. ${describeGatewayLockHolder(e, t)}`);
this.name = "GatewayLockNamespaceError";
}
};
/** File-lock recovery also covers pre-namespace Windows records from supported upgrades. */
function classifyGatewayLockProcessNamespace(e, t) {
if (process.platform === "win32" && e && e.processNamespace === void 0 && t) {
try {
if (Date.now() - fsSync.statSync(t).mtimeMs > 9e4 && isLockOwnerDefinitelyStale({ payload: {
pid: e.pid,
starttime: e.startTime
} })) return "dead";
} catch {}
return "unknown";
}
return classifyGatewayOwnerProcessNamespace(e?.processNamespace, { machineIdentity: e?.machineIdentity });
}
/** File locks and SQLite leases require comparable evidence of process death. */
function classifyGatewayOwnerProcessNamespace(e, t = {}) {
const n = GatewayProcessNamespaceSchema.safeParse(e).data;
if (!n || t.ownerHost !== void 0 && t.ownerHost !== n.host) return "unknown";
const r = readGatewayLockProcessNamespace();
if (!r) return "unknown";
if (n.platform !== r.platform) return "unknown";
if (n.platform === "darwin" && t.machineIdentity !== void 0) {
const e = MachineIdentitySchema.safeParse(t.machineIdentity).data;
const i = readProcessMachineIdentity();
if (e && i) {
if (e !== i) return "unknown";
if (n.identity !== r.identity) return "dead";
}
}
const i = n.platform === "darwin" && r.platform === "darwin" && n.identity === r.identity;
if (n.host !== r.host && !i) return "unknown";
if (n.platform === "win32") return "same";
if (n.identity !== r.identity) return "dead";
if (n.platform !== "linux" || r.platform === "linux" && n.pidNsInode === r.pidNsInode) return "same";
return "unknown";
}
const LockPayloadSchema = object({
pid: number(),
ownerId: string().min(1).optional(),
/** A cold opener may wait for this transient owner, never enter while it is held. */
stateOwnerKind: literal("schema").optional(),
/** Present when Gateway cron writes use the dynamic-default ownership projection. */
cronOwnerProjection: literal("dynamic-default-v1").optional(),
createdAt: string(),
startupPhase: literal("starting").optional(),
configPath: string(),
port: number().int().min(1).max(65535).optional(),
role: _enum([
"gateway",
"agent-embedded",
"skill-workshop-apply",
"sqlite-maintenance"
]).optional(),
stateDir: string().optional(),
startTime: number().optional(),
parentPid: number().int().positive().optional(),
parentStartTime: number().optional(),
processNamespace: GatewayProcessNamespaceSchema.nullable().optional(),
machineIdentity: MachineIdentitySchema.nullable().optional()
});
function parseGatewayLockPayload(e) {
return safeParseJsonWithSchema(LockPayloadSchema, e);
}
//#endregion
//#region src/infra/private-mode.ts
const CHMOD_UNSUPPORTED_CODES = /* @__PURE__ */ new Set([
"ENOTSUP",
"EOPNOTSUPP",
"EINVAL"
]);
const PRIVATE_PROBE_FILE_MODE = 384;
function hasRestrictivePermissions(e) {
try {
return (statSync(e).mode & 63) === 0;
} catch {
return false;
}
}
function filesystemRejectsChmod(e) {
let t;
try {
const n = statSync(e).isDirectory() ? e : path.dirname(e);
t = path.join(n, `.openclaw-chmod-probe-${randomUUID()}`);
writeFileSync(t, "", {
flag: "wx",
mode: PRIVATE_PROBE_FILE_MODE
});
} catch {
return false;
}
try {
chmodSync(t, PRIVATE_PROBE_FILE_MODE);
return false;
} catch (e) {
return isErrno(e) && e.code === "EPERM";
} finally {
try {
unlinkSync(t);
} catch {}
}
}
function canIgnorePrivateChmodError(e, t, n) {
if (t && CHMOD_UNSUPPORTED_CODES.has(t)) return true;
if (t !== "EROFS" && t !== "EPERM") return false;
return n || t === "EPERM" && filesystemRejectsChmod(e);
}
/**
* Applies a private POSIX mode, reporting unsupported filesystems without
* weakening real permission failures.
*/
function applyPrivateModeSync(e, t) {
if ((statSync(e).mode & 4095) === t) return { applied: true };
try {
chmodSync(e, t);
return { applied: true };
} catch (t) {
if (!canIgnorePrivateChmodError(e, isErrno(t) ? t.code : void 0, hasRestrictivePermissions(e))) throw t;
return {
applied: false,
error: t
};
}
}
//#endregion
//#region src/infra/gateway-state-owner-directory.ts
function ensureOwnerDirectory(e, t) {
const n = fsSync.mkdirSync(e, {
recursive: true,
mode: 448
});
if (n && t) {
const r = path.toNamespacedPath(n);
const i = [];
for (let t = e;;) {
const { dev: e, ino: n } = fsSync.lstatSync(t, { bigint: true });
i.push({
path: t,
dev: e,
ino: n
});
if (path.toNamespacedPath(t) === r) break;
const a = path.dirname(t);
if (a === t) throw new Error("Created state ownership directory is outside its expected ancestry");
t = a;
}
for (const e of i) {
const n = t.findIndex((t) => t.path === e.path);
if (n < 0) t.push(e);
else t[n] = e;
}
}
const r = fsSync.lstatSync(e);
const i = process.getuid?.();
if (!r.isDirectory() || i !== void 0 && r.uid !== i) throw new Error("State ownership directory must be a user-owned real directory");
if (process.platform !== "win32" && (r.mode & 4095) !== 448) {
applyPrivateModeSync(e, 448);
if ((fsSync.lstatSync(e).mode & 63) !== 0) throw new Error("State ownership directory permissions are not private");
}
}
function removeCreatedProjectionDirectories(e) {
let t = e[0];
while (t) {
try {
const e = fsSync.lstatSync(t.path, { bigint: true });
if (e.isDirectory() && e.dev === t.dev && e.ino === t.ino) fsSync.rmdirSync(t.path);
} catch (e) {
const t = extractErrorCode(e);
if (t !== "ENOENT" && t !== "ENOTEMPTY" && t !== "EEXIST") throw e;
}
e.shift();
t = e[0];
}
}
/** In-process identity is independent of the on-disk lock spelling used by older versions. */
function resolveStateOwnerIdentity(e) {
const t = resolveIdentityPathViaExistingAncestorSync(e);
return stateOwnerIdentity(t, resolveIdentityPathViaExistingAncestorSync(stateOwnerDirectory(t)));
}
async function resolveStateOwnerIdentityAsync(e) {
const t = await resolveIdentityPathViaExistingAncestor(e);
return stateOwnerIdentity(t, await resolveIdentityPathViaExistingAncestor(stateOwnerDirectory(t)));
}
function stateOwnerIdentity(e, t) {
return {
canonicalPath: e,
ownerPath: path.join(t, `state.${sha256HexPrefixCore(e, 16)}.lock`),
key: process.platform === "win32" ? normalizeWindowsPathForComparison(e) : e
};
}
function stateOwnerDirectory(e) {
const t = process.getuid?.();
return process.platform === "win32" ? path.join(os.homedir(), "AppData", "Local", "OpenClaw", "locks", t === void 0 ? "openclaw-state-owners" : `openclaw-state-owners-${t}`) : resolveGatewayLockDirForCanonicalStateDir(resolveOpenClawStateDirForDatabasePath(e));
}
//#endregion
//#region src/infra/gateway-state-owner-heartbeat.runtime.ts
/** Both I/O adapters compare the held descriptor, real leaf, and acquisition bytes. */
function isGatewayStateOwnerLockSnapshotCurrent(e, t, n, r) {
return t.isFile() && e.nlink !== 0n && e.dev === t.dev && e.ino === t.ino && r === n;
}
//#endregion
//#region src/infra/gateway-state-owner-heartbeat.ts
const now = Date.now.bind(Date);
function captureLock(e) {
const t = fsSync.readFileSync(e.lockPath, "utf8");
if (!e.verifyStillHeld()) throw new Error("OpenClaw state ownership is no longer current");
return t;
}
/** Process and schema owners share one renewal worker and one failure deadline. */
function startGatewayStateOwnerHeartbeat(e, t) {
const n = {};
for (const t of e) n[t.lockPath] = captureLock(t);
const r = Object.keys(n)[0];
if (!r) throw new Error("Gateway state ownership requires a held lock");
const i = fsSync.statSync(r, { bigint: true });
const { moduleUrl: a, runtimeGeneration: o } = captureRuntimeWorkerSource(resolveRuntimeProcessEntrypointUrl("gatewayStateOwnerHeartbeat"));
return runInDetachedAsyncContext(() => {
const s = new BigInt64Array(new SharedArrayBuffer(BigInt64Array.BYTES_PER_ELEMENT));
Atomics.store(s, 0, BigInt(now()));
const { port1: c, port2: l } = new MessageChannel();
const u = createCpuTrackedWorker(a, {
workerData: {
clock: "epoch",
locks: n,
intervalMs: GATEWAY_OWNER_HEARTBEAT_MS,
failureMs: 6e4,
lastBeat: s.buffer,
events: l
},
transferList: [l],
execArgv: resolveRuntimeWorkerThreadExecArgv(a)
});
const d = createDeferredCore();
u.on("message", (e) => {
if (e === "closed") d.resolve();
});
u.unref();
let f = 0;
const p = /* @__PURE__ */ new Map();
const rejectPending = (e) => {
for (const t of p.values()) t.reject(e);
p.clear();
c.unref();
};
c.on("message", (e) => {
recordWorkerMessage("lifecycle", "from_worker");
if (e === "parent-lost") requestCliParentTermination();
else if (e && typeof e === "object" && e.type === "lost") t(/* @__PURE__ */ new Error(`${e.error}; restart the Gateway.`), e.lockPath);
else if (e && typeof e === "object" && e.type === "verified") {
const t = p.get(e.id);
p.delete(e.id);
if (p.size === 0) c.unref();
if (e.error) t?.reject(new Error(e.error));
else t?.resolve(e.current);
}
});
c.unref();
u.on("error", (e) => {
const n = /* @__PURE__ */ new Error(`${coerceErrorMessage(e)}; restart Gateway.`);
rejectPending(n);
t(n);
});
u.once("exit", () => {
d.resolve();
rejectPending(/* @__PURE__ */ new Error("Gateway state ownership verification worker stopped"));
});
let m;
const remainingUntilInspection = () => {
const e = Atomics.load(s, 0);
const t = now() - Number(e);
return t < 0 ? 0 : 6e4 - t;
};
const inspect = () => {
const e = remainingUntilInspection();
if (e <= 0) throw new Error(`Gateway state ownership renewal is overdue at ${r}; retry after storage recovers.`);
return e;
};
const renewAsync = async () => {
const t = now();
const a = new Date(t);
for (const t of e) try {
const o = n[t.lockPath];
if (o === void 0) throw new Error("owner acquisition bytes were not registered");
const s = await fsSync.promises.open(t.lockPath, "r+");
try {
const n = await s.stat({ bigint: true });
const c = await fsSync.promises.lstat(t.lockPath, { bigint: true });
const l = Buffer.alloc(Buffer.byteLength(o) + 1);
const { bytesRead: u } = await s.read(l, 0, l.length, 0);
const d = await fsSync.promises.lstat(t.lockPath, { bigint: true });
if (m || !e.has(t)) continue;
if (!isGatewayStateOwnerLockSnapshotCurrent(n, c, o, l.subarray(0, u).toString("utf8")) || !d.isFile() || d.dev !== n.dev || d.ino !== n.ino || t.lockPath === r && (n.dev !== i.dev || n.ino !== i.ino)) {
if (t.lockPath !== r) continue;
throw new Error("owner lock was removed or replaced");
}
await s.utimes(a, a);
} finally {
await s.close();
}
} catch (e) {
if (t.lockPath !== r && hasErrnoCode(e, "ENOENT")) continue;
throw e;
}
if (!m && e.size > 0) Atomics.store(s, 0, BigInt(t));
};
let h;
let g;
const watch = () => {
const e = remainingUntilInspection();
if (e > 0) {
h = setTimeout(watch, e);
h.unref();
} else g ??= renewAsync().then(() => {
g = void 0;
if (!m) watch();
}, (e) => {
g = void 0;
if (!m) t(/* @__PURE__ */ new Error(`Gateway state ownership is no longer current at ${r}: ${coerceErrorMessage(e)}; restart the Gateway.`));
});
};
watch();
const stop = () => {
if (!m) {
clearTimeout(h);
rejectPending(/* @__PURE__ */ new Error("Gateway state ownership is no longer current"));
c.close();
u.ref();
u.postMessage("stop", []);
m = (async () => {
if (!await settlesWithin(d.promise, 1e3)) process.emitWarning(`Gateway state-owner heartbeat did not close within ${RESPAWN_SIGNAL_FORCE_KILL_GRACE_MS}ms; forcing termination. Lock file descriptors may remain open until process exit.`, { code: "GATEWAY_STATE_HEARTBEAT_CLOSE_TIMEOUT" });
return u.terminate();
})();
}
return Promise.all([m, g]).then(() => void 0);
};
o?.retain(u, async () => async () => {
await stop();
});
const assertActive = () => {
if (m || u.threadId === -1) throw new Error("Gateway state ownership verification worker stopped");
};
const _ = new Set(Object.keys(n));
return {
worker: u,
paths: _,
register(e) {
const t = captureLock(e);
n[e.lockPath] = t;
u.postMessage([e.lockPath, t], []);
_.add(e.lockPath);
},
inspect,
assertActive,
verify(e) {
assertActive();
const t = ++f;
return new Promise((n, r) => {
p.set(t, {
resolve: n,
reject: r
});
c.ref();
try {
u.postMessage({
type: "verify",
id: t,
paths: e
}, []);
} catch (e) {
p.delete(t);
if (p.size === 0) c.unref();
r(toErrorObject(e, "Gateway state ownership verification failed"));
}
});
},
stop
};
});
}
//#endregion
//#region src/infra/gateway-state-owner-lifecycle.ts
/** Carry the same physical sidecar through relocation and accepted schema work. */
function createGatewayStateProjection(e) {
let t = 1;
const reference = () => {
let n = false;
return {
lockPath: e.lockPath,
verifyStillHeld: () => !n && e.verifyStillHeld(),
retain() {
if (n || !e.verifyStillHeld()) throw new Error("Gateway state projection is no longer current");
t += 1;
return reference();
},
release() {
readOwnerPaths.clear();
if (n) return;
if (t === 1) e.release();
t -= 1;
n = true;
}
};
};
return reference();
}
function hasPhysicalOwnership(e) {
try {
return verifyOwnerLock(e, e.locks.values().next().value);
} catch (t) {
if (e.lost.signal.aborted) return false;
throw t;
}
}
function verifyOwnerLock(e, t) {
e.lost.signal.throwIfAborted();
e.heartbeat?.inspect();
if (!t) return false;
const n = e.getProjection?.();
if (n && e.heartbeat && !e.heartbeat.paths.has(n.lockPath)) e.heartbeat.register(n);
const r = e.payload.role ?? "gateway";
if (e.kind === "process" && e.accepting && (r === "gateway" || r === "agent-embedded") && e.heartbeat) {
e.heartbeat.assertActive();
return true;
}
if (!t.verifyStillHeld()) {
loseOwner(e, /* @__PURE__ */ new Error(`${t.lockPath}: no longer current; lock removed/replaced; restart the Gateway.`));
return false;
}
return true;
}
const log = createSubsystemLogger("gateway/state");
function loseOwner(e, t) {
if (e.lost.signal.aborted) return;
e.accepting = false;
readOwnerPaths.clear();
e.heartbeat?.stop();
log.error(t.message);
e.lost.abort(t);
}
function observeOwnerLoss(e, t, n) {
const r = [...e.locks, e.getProjection?.()];
if (!n || r.some((e) => e?.lockPath === n)) loseOwner(e, t);
}
const readOwnerPaths = resolveGlobalSingleton(Symbol.for("openclaw.gatewayStateReadOwnerPaths"), () => /* @__PURE__ */ new Map());
const owners = resolveGlobalSingleton(Symbol.for("openclaw.gatewayStateOwners"), () => /* @__PURE__ */ new Map());
//#endregion
//#region gateway-run-argv.mjs
const GATEWAY_RUN_VALUE_FLAGS = /* @__PURE__ */ new Set([
"--port",
"--bind",
"--token",
"--token-file",
"--auth",
"--password",
"--password-file",
"--tailscale",
"--ws-log",
"--raw-stream-path"
]);
const GATEWAY_RUN_BOOLEAN_FLAGS = /* @__PURE__ */ new Set([
"--tailscale-reset-on-exit",
"--allow-unconfigured",
"--dev",
"--ambient-channels",
"--dev-ambient-channels",
"--reset",
"--update-canary",
"--force",
"--verbose",
"--cli-backend-logs",
"--claude-cli-logs",
"--compact",
"--raw-stream"
]);
function isForegroundGatewayRunArgv(e) {
const t = getCommandPositionalsWithRootOptions(e, {
commandPath: ["gateway"],
booleanFlags: [...GATEWAY_RUN_BOOLEAN_FLAGS, "--task-supervisor"],
valueFlags: [...GATEWAY_RUN_VALUE_FLAGS, "--task-supervisor-child"],
mode: "command-path"
});
if (!t) return false;
return t.length === 0 || t.length === 1 && t[0] === "run";
}
//#endregion
//#region src/infra/gateway-state-owner-record.ts
const ownerInspections = new AsyncLocalStorage();
function comparableStateOwnerStaleReason(e, t) {
return t === "dead" ? "owner-process-exited" : t === "same" ? inspectStaleLockOwner({ payload: {
pid: e.pid,
starttime: e.startTime
} })?.reason : void 0;
}
/** Reclamation requires proof that the recorded owner stopped. */
function isGatewayStateOwnerDefinitelyStale(e, t) {
const n = isRecord(e) ? e : null;
if (!n) return false;
const r = classifyGatewayLockProcessNamespace(n, t);
if (r === "unknown") throw new GatewayLockNamespaceError(n, t);
return comparableStateOwnerStaleReason(n, r) !== void 0;
}
/** Persisted ownership can identify a holder but cannot lend this process maintenance authority. */
function assertPersistedStateDatabaseAccessAllowed(e) {
const { databasePath: t, ownerPath: n, assertMaintenance: r } = e;
const i = `OpenClaw state ownership at ${t} could not be verified from ${n}; restart the Gateway.`;
let a;
try {
a = fsSync.readFileSync(n, "utf8");
} catch (e) {
if (extractErrorCode(e) === "ENOENT") return;
throw new StateDatabaseAccessError(i, { cause: e });
}
const o = ownerInspections.getStore();
if (o?.deadOwner?.path === n && o.deadOwner.raw === a) return;
const s = parseGatewayLockPayload(a);
if (!s) throw new StateDatabaseAdmissionPendingError(t, i);
if (!Number.isSafeInteger(s.pid) || s.pid <= 0) throw new StateDatabaseAccessError(i);
const c = classifyGatewayLockProcessNamespace(s, n);
const l = comparableStateOwnerStaleReason(s, c);
if (l) {
if (o && l === "owner-process-exited") o.deadOwner = {
path: n,
raw: a
};
return;
}
if (c === "same" && s.pid === process.pid && !isMainThread) return;
if (c === "same" && !isPidAlive(s.pid)) throw new StateDatabaseAdmissionPendingError(t, i);
const u = s.role ?? "gateway";
if (u === "gateway" || u === "agent-embedded") return;
if (c === "same" && s.pid === process.pid) {
r();
return;
}
const d = `OpenClaw state at ${t} is undergoing offline maintenance by ${u} process ${s.pid} (ownerKind=${s.stateOwnerKind ?? "process"}); retry when it finishes. For update progress, run \`openclaw update status --json\`.`;
if (s.stateOwnerKind === "schema" && s.role === "sqlite-maintenance") throw new StateDatabaseAdmissionPendingError(t, d);
throw new StateDatabaseOfflineMaintenanceError(t, d);
}
function defaultPayload(e) {
const t = resolveOpenClawStateDirForDatabasePath(e);
const n = getFileLockProcessStartTime(process.pid);
const r = getCliParentPid();
const i = r === void 0 ? null : getFileLockProcessStartTime(r);
return {
pid: process.pid,
ownerId: randomUUID(),
createdAt: (/* @__PURE__ */ new Date()).toISOString(),
stateDir: t,
configPath: path.join(t, "openclaw.json"),
role: "sqlite-maintenance",
processNamespace: readGatewayLockProcessNamespace(),
machineIdentity: process.platform === "darwin" ? readProcessMachineIdentity() : void 0,
...r === void 0 ? {} : { parentPid: r },
...i === null ? {} : { parentStartTime: i },
...n === null ? {} : { startTime: n }
};
}
function assertGatewayRestorationPriority(e, t, n) {
if (n.role === "gateway") return;
let r;
try {
r = fsSync.readFileSync(t, "utf8");
} catch (e) {
if (extractErrorCode(e) === "ENOENT") return;
throw e;
}
const i = parseGatewayLockPayload(r);
if (isGatewayStateOwnerDefinitelyStale(i, t) || i?.pid === n.pid) return;
if (n.pid === process.pid && isForegroundGatewayRunArgv(process.argv) && classifyOpenClawArgv(process.argv, { command: "gateway" }).kind === "openclaw") return;
throw new StateDatabaseAdmissionPendingError(e, `Gateway restoration has priority for OpenClaw state at ${e}; retry when it finishes.`);
}
function acquireGatewayStateOwnerFile(e, t, n, r = 0, i) {
const a = performance.now() + r;
const o = `${resolveStateOwnerIdentity(e).ownerPath}.gateway-restoration`;
assertGatewayRestorationPriority(e, o, n);
ensureOwnerDirectory(path.dirname(t), i);
const s = { holder: null };
const stale = ({ payload: e }) => {
s.holder = LockPayloadSchema.safeParse(e).data ?? null;
return isGatewayStateOwnerDefinitelyStale(s.holder, t);
};
if (r > 0) try {
const n = s.holder = parseGatewayLockPayload(fsSync.readFileSync(t, "utf8"));
if (n && !isGatewayStateOwnerDefinitelyStale(n, t) && (n.pid === process.pid || (n.role ?? "gateway") === "gateway" && isPidAlive(n.pid))) throw new GatewayStateOwnerContentionError(e);
} catch (e) {
if (extractErrorCode(e) !== "ENOENT") throw e;
}
for (let c = false;;) try {
return acquireFileLockSync(t, {
lockPath: t,
retry: r > 0 ? {
factor: 1.25,
minTimeout: 10,
maxTimeout: 25,
randomize: false
} : { retries: 0 },
timeoutMs: Math.max(0, Math.ceil(a - performance.now())),
staleMs: Infinity,
staleRecovery: "remove-if-unchanged",
reentrantOwner: n.ownerId,
payload: () => {
assertGatewayRestorationPriority(e, o, n);
return n;
},
shouldReclaim: stale,
shouldRemoveStaleLock: stale
});
} catch (n) {
const r = extractErrorCode(n);
if (r === "ENOENT" && !c) {
c = true;
ensureOwnerDirectory(path.dirname(t), i);
continue;
}
if (r === "file_lock_timeout" || r === "file_lock_stale") {
const { holder: r } = s;
const i = describeGatewayLockHolder(r ?? {}, t, r && isPidAlive(r.pid) ? "live" : "unknown");
throw new GatewayStateOwnerContentionError(e, n, i, r ? {
pid: r.pid,
role: r.role
} : void 0);
}
throw n;
}
}
//#endregion
//#region src/infra/gateway-state-owner.ts
const schemaOwners = resolveGlobalSingleton(Symbol.for("openclaw.stateDatabaseSchemaOwners"), () => new AsyncLocalStorage());
/** The active lexical owner is live authority, not the existence of its sidecar. */
function getStateDatabaseSchemaLease(e) {
const t = schemaOwners.getStore()?.get(resolveStateOwnerIdentity(e).key);
if (t && !t.active) throw new Error("State schema maintenance scope is no longer current");
t?.lease.assertCurrent();
return t?.lease;
}
/** Retry cold admission only; the same budget covers opening and its first unentered write. */
function withStateDatabaseColdAdmission(e, t) {
const n = normalizeSqliteNonNegativeInteger(e.busyTimeoutMs, "busyTimeoutMs");
const r = performance.now() + n;
const i = resolveIdentityPathViaExistingAncestorSync(e.databasePath);
const remainingBusyTimeoutMs = () => Math.max(0, Math.ceil(r - performance.now()));
const a = new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));
for (;;) try {
assertStateDatabaseAccessAllowed(e.databasePath);
return t(remainingBusyTimeoutMs);
} catch (t) {
if (!(t instanceof StateDatabaseAdmissionPendingError) || resolveIdentityPathViaExistingAncestorSync(t.databasePath) !== i || e.canRetry?.() === false) throw t;
const n = r - performance.now();
if (n <= 0) throw t;
Atomics.wait(a, 0, 0, Math.min(10, n));
}
}
/** State cleanup preserves this owner until destructive work and native handles settle. */
function resolveGatewayStateOwnerPath(e) {
return resolveStateOwnerIdentity(e).ownerPath;
}
function leaseForFile(e, t, n, r) {
let i = false;
const holdsPhysicalLease = () => verifyOwnerLock(n, t) && (!r || r.verifyStillHeld());
function run(e) {
a.assertCurrent();
readOwnerPaths.clear();
const t = new Map(schemaOwners.getStore());
const r = {
lease: a,
active: true
};
t.set(n.key, r);
const leave = () => {
r.active = false;
readOwnerPaths.clear();
};
try {
const n = schemaOwners.run(t, e);
if (isPromiseLike(n)) return Promise.resolve(n).finally(leave);
leave();
return n;
} catch (e) {
leave();
throw e;
}
}
const a = {
path: e,
assertCurrent() {
if (i || !holdsPhysicalLease()) throw new Error("OpenClaw state ownership is no longer current");
},
assertDatabaseAccess(e) {
if (i || owners.get(n.key) !== n || resolveStateOwnerIdentity(e).key !== n.key || !holdsPhysicalLease()) throw new Error("OpenClaw state maintenance does not own this database");
},
run,
release() {
readOwnerPaths.clear();
if (!i) {
r?.release();
t.release();
i = true;
n.locks.delete(t);
if (r) n.locks.delete(r);
if (n.locks.size === 0 && owners.get(n.key) === n) {
n.heartbeat?.stop();
n.accepting = false;
owners.delete(n.key);
}
}
if (n.locks.size === 0) removeCreatedProjectionDirectories(n.projectionDirectories);
}
};
return a;
}
/** One root owns startup or maintenance; only its registered custody can lend schema access. */
function acquireGatewayStateOwner(e) {
const t = resolveStateOwnerIdentity(e.databasePath);
const n = t.ownerPath;
const r = owners.get(t.key);
if (r) throw new GatewayStateOwnerContentionError(e.databasePath, void 0, describeGatewayLockHolder(r.payload, n, "live"), {
pid: r.payload.pid,
role: r.payload.role
});
const i = e.payload ? {
...e.payload.role === "sqlite-maintenance" ? defaultPayload(e.databasePath) : {},
...e.payload,
ownerId: e.payload.ownerId ?? randomUUID()
} : defaultPayload(e.databasePath);
const a = {
key: t.key,
path: n,
kind: "process",
payload: i,
projectionPath: e.projectionPath,
getProjection: e.getProjection,
locks: /* @__PURE__ */ new Set(),
projectionDirectories: [],
lost: new AbortController(),
accepting: true
};
const o = acquireGatewayStateOwnerFile(e.databasePath, n, i);
a.locks.add(o);
readOwnerPaths.clear();
owners.set(a.key, a);
const s = leaseForFile(n, o, a);
try {
a.heartbeat = startGatewayStateOwnerHeartbeat(a.locks, (e, t) => observeOwnerLoss(a, e, t));
s.assertCurrent();
} catch (e) {
return runWithSqliteCleanup(s, "state process ownership verification", () => {
throw e;
});
}
return {
path: n,
assertCurrent() {
a.lost.signal.throwIfAborted();
if (!a.accepting || owners.get(a.key) !== a) throw createGatewayStateProcessOwnerRetiredError();
s.assertCurrent();
},
assertDatabaseAccess: s.assertDatabaseAccess,
run: s.run,
release() {
a.accepting = false;
s.release();
}
};
}
/** Accepted schema work retains the sidecar even when its process owner stops lending. */
function acquireStateDatabaseSchemaLease(e, t = {}) {
readOwnerPaths.clear();
const n = resolveStateOwnerIdentity(e);
let r = owners.get(n.key);
const i = r?.path ?? n.ownerPath;
if (r && (!r.accepting || !hasPhysicalOwnership(r))) throw new GatewayStateOwnerContentionError(e, r.lost.signal.reason);
if (r) assertStateDatabaseAccessAllowed(e);
const a = r?.payload ?? {
...defaultPayload(e),
stateOwnerKind: "schema"
};
let o;
const s = [];
try {
o = acquireGatewayStateOwnerFile(e, i, a, r ? 0 : t.busyTimeoutMs ?? 5e3, s);
} catch (t) {
if (t instanceof GatewayStateOwnerContentionError) try {
assertStateDatabaseAccessAllowed(e);
} catch (e) {
if (e instanceof StateDatabaseAdmissionPendingError) throw e;
}
throw t;
}
const c = r?.projectionPath ?? path.join(resolveGatewayLockDir(resolveOpenClawStateDirForDatabasePath(resolveIdentityPathViaExistingAncestorSync(e))), "gateway.state.lock");
let l;
try {
l = r?.getProjection?.()?.retain() ?? acquireGatewayStateOwnerFile(e, c, {
...a,
role: a.role === "gateway" ? "gateway" : "agent-embedded"
}, 0, s);
} catch (e) {
return runWithSqliteCleanup({ release() {
o.release();
removeCreatedProjectionDirectories(s);
} }, "state schema projection admission", () => {
throw e;
});
}
if (r) {
r.locks.add(o);
r.locks.add(l);
r.projectionDirectories.push(...s);
} else {
r = {
key: n.key,
path: i,
kind: "schema",
payload: a,
projectionPath: c,
locks: /* @__PURE__ */ new Set([o, l]),
projectionDirectories: s,
lost: new AbortController(),
accepting: true
};
owners.set(r.key, r);
}
const u = leaseForFile(i, o, r, l);
try {
const e = r.heartbeat ??= startGatewayStateOwnerHeartbeat(r.locks, (e, t) => observeOwnerLoss(r, e, t));
u.assertCurrent();
e.register(l);
return u;
} catch (e) {
return runWithSqliteCleanup(u, "state schema ownership verification", () => {
throw e;
});
}
}
/** A nested maintenance scope can retain only an already-held process root for its exact database. */
function tryBorrowGatewayStateOwner(e) {
const t = owners.get(resolveStateOwnerIdentity(e).key);
if (!t || t.kind !== "process") return;
if (!t.accepting || !hasPhysicalOwnership(t)) throw new GatewayStateOwnerContentionError(e, t.lost.signal.reason);
assertStateDatabaseAccessAllowed(e);
return acquireStateDatabaseSchemaLease(e);
}
/** Startup recovery requires this process's retained Gateway root, not a schema loan. */
function hasActiveGatewayStateOwner(e) {
const t = owners.get(resolveStateOwnerIdentity(e).key);
return t?.kind === "process" && t.accepting && (t.payload.role ?? "gateway") === "gateway" && hasPhysicalOwnership(t);
}
/** Capture registered process custody; a PID or copied lock payload grants no authority. */
function captureGatewayStateOwner(e) {
const t = resolveStateOwnerIdentity(e);
const { key: n } = t;
const r = owners.get(n);
if (!r || r.kind !== "process") return;
const assertCurrent = (i = e) => {
r.lost.signal.throwIfAborted();
const a = resolveIdentityPathViaExistingAncestorSync(i);
const o = process.platform === "win32" ? normalizeWindowsPathForComparison(a) : a;
if (owners.get(n) !== r || !r.accepting || o !== n) throw new GatewayStateOwnerContentionError(e);
assertStateDatabaseAccessAtOwnerPath(e, t, void 0);
};
assertCurrent();
return {
ownerId: r.payload.ownerId,
role: r.payload.role ?? "gateway",
assertCurrent,
prepareAccess: createStateDatabaseAccess(t, r).prepareAccess,
signal: r.lost.signal
};
}
/** Native generations qualify a fresh locator while retaining their original process owner. */
function captureGatewayStateOwnerAsync(e) {
return captureAdmittedGatewayStateOwner(e, true);
}
/** Warm reads consume this owner's existing path admission without another physical probe. */
function prepareStateDatabaseReadAccess(e) {
return captureAdmittedGatewayStateOwner(e, false);
}
async function captureAdmittedGatewayStateOwner(e, t) {
e.assertCurrent();
const n = e.identity.canonicalPath;
const r = process.platform === "win32" ? normalizeWindowsPathForComparison(n) : n;
const i = owners.get(r);
if (!i || i.kind !== "process") return;
const a = {
canonicalPath: n,
key: r,
ownerPath: i.path
};
const assertRegistered = () => {
e.assertCurrent();
i.lost.signal.throwIfAborted();
if (owners.get(r) !== i) throw createGatewayStateProcessOwnerRetiredError();
};
const assertCurrent = () => {
assertRegistered();
if (!i.accepting) throw createGatewayStateProcessOwnerRetiredError();
assertStateDatabaseAccessAtOwnerPath(n, a, void 0);
};
const o = createStateDatabaseAccess(a, i);
const assertReadAllowed = (e) => {
assertRegistered();
o.assertReadAllowed(e);
};
const s = path.resolve(e.databasePath);
const c = t ? assertCurrent : assertRegistered;
c();
if (t || readOwnerPaths.get(s) !== i) {
const t = await resolveIdentityPathViaExistingAncestor(s);
c();
if ((process.platform === "win32" ? normalizeWindowsPathForComparison(t) : t) !== r) throw new GatewayStateOwnerContentionError(e.databasePath);
}
if (!t) {
assertReadAllowed();
if (readOwnerPaths.get(path.resolve(n)) === i) readOwnerPaths.set(s, i);
}
return {
ownerId: i.payload.ownerId,
role: i.payload.role ?? "gateway",
signal: i.lost.signal,
assertCurrent,
assertReadAllowed,
prepareAccess: o.prepareAccess
};
}
/** Reads within an admission reuse process custody; the next admission verifies the lock. */
function assertStateDatabaseReadAllowed(e, t) {
assertStateDatabaseReadAtOwnerPath(e, t);
}
function assertStateDatabaseReadAtOwnerPath(e, t, n) {
if (owners.size === 0) {
assertStateDatabaseAccessAtOwnerPath(e, n ?? resolveStateOwnerIdentity(e), t);
return;
}
const r = path.resolve(e);
if (readOwnerPaths.get(r)?.accepting) return;
const i = n ?? resolveStateOwnerIdentity(e);
const a = owners.get(i.key);
const o = a?.payload.role ?? "gateway";
if (!a || a.kind !== "process" || !a.accepting || o !== "gateway" && o !== "agent-embedded") {
assertStateDatabaseAccessAtOwnerPath(e, i, t);
return;
}
if (!hasPhysicalOwnership(a)) {
a.lost.signal.throwIfAborted();
throw new Error(`OpenClaw state ownership at ${e} was lost: owner lock was removed or replaced; restart the Gateway.`);
}
readOwnerPaths.set(r, a);
}
/** Ordinary SQLite access observes maintenance; it never borrows schema authority. */
function assertStateDatabaseAccessAllowed(e, t) {
assertStateDatabaseAccessAtOwnerPath(e, resolveStateOwnerIdentity(e), t);
}
/** Retained handles keep their admitted paths; reopening captures a fresh identity. */
async function captureStateDatabaseAccess(e) {
return createStateDatabaseAccess(await resolveStateOwnerIdentityAsync(e));
}
function createStateDatabaseAccess(e, t) {
const { canonicalPath: n } = e;
const r = owners.get(e.key);
return {
canonicalPath: n,
processOwner: r?.kind === "process" ? {
role: r.payload.role ?? "gateway",
signal: r.lost.signal,
assertCurrent() {
r.lost.signal.throwIfAborted();
if (!r.accepting || owners.get(e.key) !== r) throw createGatewayStateProcessOwnerRetiredError();
}
} : void 0,
prepareAccess: async (r) => {
const i = t ?? owners.get(e.key);
const a = i?.payload.role ?? "gateway";
if (!i || i.kind !== "process" || !i.accepting || a !== "gateway" && a !== "agent-embedded") {
assertStateDatabaseAccessAtOwnerPath(n, e, r);
return (t = r) => {
if (i && owners.get(e.key) !== i) throw createGatewayStateProcessOwnerRetiredError();
assertStateDatabaseReadAtOwnerPath(n, t, e);
};
}
const o = i.heartbeat;
const s = i.locks.values().next().value;
const c = i.getProjection?.();
if (!o || !s) throw createGatewayStateProcessOwnerRetiredError();
const assertCurrent = (t = r) => {
i.lost.signal.throwIfAborted();
o.assertActive();
if (owners.get(e.key) !== i || i.heartbeat !== o) throw createGatewayStateProcessOwnerRetiredError();
if (!i.accepting) {
assertStateDatabaseAccessAtOwnerPath(n, e, t);
return;
}
if (!i.locks.has(s) || i.getProjection?.() !== c) throw createGatewayStateProcessOwnerRetiredError();
};
assertCurrent();
const l = [s.lockPath];
if (c) l.push(c.lockPath);
const u = await o.verify(l).catch((e) => {
i.lost.signal.throwIfAborted();
throw e;
});
assertCurrent();
if (!u) {
const e = /* @__PURE__ */ new Error(`${s.lockPath}: no longer current; lock removed/replaced; restart the Gateway.`);
loseOwner(i, e);
throw e;
}
readOwnerPaths.set(path.resolve(n), i);
return assertCurrent;
},
assertReadAllowed(t) {
assertStateDatabaseReadAtOwnerPath(n, t, e);
}
};
}
function assertStateDatabaseAccessAtOwnerPath(e, t, n) {
const assertMaintenance = () => {
const t = n ? n.schemaLease : getStateDatabaseSchemaLease(e);
if (t) {
t.assertDatabaseAccess(e);
return;
}
const r = n ? n.maintenanceScope : getOpenClawDatabaseMaintenanceScope();
if (!r) throw new StateDatabaseMaintenanceScopeError(e);
r.assertDatabaseAccess(e);
};
const r = owners.get(t.key);
if (r) {
if (!hasPhysicalOwnership(r)) {
r.lost.signal.throwIfAborted();
throw new Error(`OpenClaw state ownership at ${e} was lost: owner lock was removed or replaced; restart the Gateway.`);
}
const t = r.payload.role ?? "gateway";
if (!r.accepting || t !== "gateway" && t !== "agent-embedded") assertMaintenance();
return;
}
assertPersistedStateDatabaseAccessAllowed({
databasePath: e,
ownerPath: t.ownerPath,
assertMaintenance
});
}
/** Cleanup must compete with local roots too; it cannot borrow a live Gateway's authority. */
function tryAcquireGatewayStateOwner(e) {
try {
return acquireGatewayStateOwner({ databasePath: e });
} catch (e) {
if (e instanceof GatewayStateOwnerContentionError) return null;
throw e;
}
}
//#endregion
export { GatewayLockNamespaceError as _, captureGatewayStateOwner as a, classifyGatewayOwnerProcessNamespace as b, getStateDatabaseSchemaLease as c, resolveGatewayStateOwnerPath as d, tryAcquireGatewayStateOwner as f, applyPrivateModeSync as g, createGatewayStateProjection as h, assertStateDatabaseReadAllowed as i, hasActiveGatewayStateOwner as l, withStateDatabaseColdAdmission as m, acquireStateDatabaseSchemaLease as n, captureGatewayStateOwnerAsync as o, tryBorrowGatewayStateOwner as p, assertStateDatabaseAccessAllowed as r, captureStateDatabaseAccess as s, acquireGatewayStateOwner as t, prepareStateDatabaseReadAccess as u, GatewayProcessNamespaceSchema as v, parseGatewayLockPayload as x, MachineIdentitySchema as y };