openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
246 lines (245 loc) • 9.87 kB
JavaScript
import { o as redactSensitiveUrlLikeString } from "./redact-sensitive-url-D-E7DGoc.mjs";
import { n as resolveIdentityPathViaExistingAncestorSync } from "./boundary-path-C2gXEiXe.mjs";
import { r as resolveStateDir } from "./state-dir-DiG0gXzD.mjs";
import { m as resolveConfigPath } from "./paths-DAcAg5aV.mjs";
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs";
import { t as createDeferredCore } from "./deferred-D0La5CRk.mjs";
import { c as registerSignalExitGate } from "./signal-exit-barrier-BOGtFHQL.mjs";
import { i as hasCommandProcessCleanupError } from "./exec-result-DJMhztYN.mjs";
import { i as GATEWAY_CLIENT_NAMES, r as GATEWAY_CLIENT_MODES } from "./client-info-Cm1BcrMm.mjs";
import { t as GATEWAY_SERVER_CAPS } from "./server-capabilities-BDosLJeN.mjs";
import path from "node:path";
import { AsyncLocalStorage } from "node:async_hooks";
//#region src/cli/local-state-owner.ts
const localOwnerAssertion = new AsyncLocalStorage();
var LocalStateOwnerError = class extends Error {
constructor(e, t, n) {
super(t, { cause: n });
this.code = e;
this.name = "LocalStateOwnerError";
}
};
/** Select one owner before domain admission and retain offline custody through resource settlement. */
async function runWithLocalStateOwner(e) {
localOwnerAssertion.getStore()?.();
const t = e.databasePortRecovery ? { ...e.databasePortRecovery } : void 0;
const n = { ...process.env };
const r = resolveStateDir(n);
const i = resolveIdentityPathViaExistingAncestorSync(r);
const a = {
...n,
OPENCLAW_STATE_DIR: i,
OPENCLAW_CONFIG_PATH: resolveConfigPath(n, r)
};
const o = e.params;
const s = [...e.scopes ?? ["operator.admin"]];
const [{ acquireGatewayLock: c, isGatewayLifecycleContentionError: l, readActiveGatewayLockIdentity: u, readLockPayloadSync: d, resolveGatewayLockPaths: f }, { captureGatewayStateOwner: p, tryBorrowGatewayStateOwner: m }, { createOpenClawDatabaseMaintenanceScope: h }, { getScopedDatabaseEngineSelection: g, withDatabaseEngineSelection: _ }] = await Promise.all([
import("./gateway-lock-C8DzJkpV.mjs"),
import("./gateway-state-owner-D5aGeZ70.mjs"),
import("./openclaw-state-db-async-lifecycle-svBk4d27.mjs"),
import("./context-Dz_LKKUd.mjs")
]);
const v = f(a);
const y = path.join(v.stateDir, "state", "openclaw.sqlite");
const b = new AbortController();
const x = createDeferredCore();
const S = registerSignalExitGate(x.promise, () => b.abort());
const assertTargetCurrent = () => {
b.signal.throwIfAborted();
e.assertTargetCurrent?.();
};
const C = (e.onForeignOwner === "refuse" ? `This command is offline-only. ${e.onlineAlternative ? `${e.onlineAlternative} ` : ""}` : "Update the Gateway or fix authentication and retry. " + (e.requireLocalBackendSharedAuth ? "Provide the Gateway's shared secret through OPENCLAW_GATEWAY_TOKEN or OPENCLAW_GATEWAY_PASSWORD in this CLI process; device pairing is not a substitute. " : "")) + "To run offline, stop the Gateway through its service owner, wait for ownership to release, then rerun this exact command.";
const refuse = (t) => {
throw new LocalStateOwnerError("OWNER_UNAVAILABLE", `Cannot admit ${e.method} for ${e.target} in state root ${v.stateDir}: ${redactSensitiveUrlLikeString(formatErrorMessage(t))}. No local mutation was attempted. Inspect openclaw gateway status. ${C}`, t);
};
const discover = async () => {
try {
assertTargetCurrent();
const t = {
env: a,
requireInspection: true,
signal: b.signal
};
return e.onForeignOwner ? await u({
...t,
includeEmbedded: true
}) : await u(t);
} catch (e) {
return refuse(e);
}
};
const runLocal = async (t) => {
const assertCurrent = () => {
assertTargetCurrent();
t();
};
assertCurrent();
const { loadConfig: n } = await import("./config/config.js");
assertCurrent();
let r;
return await localOwnerAssertion.run(assertCurrent, () => e.runLocal({
env: a,
get config() {
assertCurrent();
r ??= n();
assertCurrent();
return r;
},
signal: b.signal,
assertCurrent
}));
};
const route = async (t) => {
const listenerPort = () => {
if (!t.ownerId) return refuse(/* @__PURE__ */ new Error("Gateway lacks the expected-owner contract; update the Gateway."));
if (t.port === void 0) return refuse(/* @__PURE__ */ new Error("The state owner has no Gateway listener"));
return t.port;
};
const requestGateway = async (n, r, i, a = i ? e.expectFinal : void 0) => {
const o = listenerPort();
const { callGateway: c, isGatewayClientRequestError: l } = await import("./call-CT5jlfNe.mjs");
let u = false;
try {
assertTargetCurrent();
return await c({
method: n,
configPath: v.configPath,
params: i ? {
...r,
expectedOwnerId: t.ownerId
} : r,
localPortOverride: o,
ignoreEnvUrlOverride: true,
requireLocalBackendSharedAuth: e.requireLocalBackendSharedAuth,
allowLocalBackendAuthNone: e.requireLocalBackendSharedAuth,
requiredMethods: [n],
requiredCapabilities: [GATEWAY_SERVER_CAPS.LOCAL_STATE_OWNER_ROUTING, ...e.requiredCapabilities ?? []],
timeoutMs: e.timeoutMs ?? 6e5,
expectFinal: a,
signal: b.signal,
scopes: s,
onSignalAbort: i ? e.onGatewaySignalAbort : void 0,
onResponse: i && e.onGatewayResponse ? async (n, r) => {
const guardedRequest = (e, r, i) => {
assertTargetCurrent();
const a = d(v.ownerLockPath, true);
if (!a || a.ownerId !== t.ownerId || a.pid !== t.pid) refuse(/* @__PURE__ */ new Error("Gateway owner changed during the operation"));
return n(e, r, i);
};
await e.onGatewayResponse(guardedRequest, AbortSignal.any([b.signal, r]));
} : void 0,
clientName: GATEWAY_CLIENT_NAMES.CLI,
mode: GATEWAY_CLIENT_MODES.CLI,
assertDispatchCurrent: () => {
assertTargetCurrent();
const e = d(v.ownerLockPath, true);
if (!e || e.ownerId !== t.ownerId || e.pid !== t.pid) refuse(/* @__PURE__ */ new Error("Gateway owner changed before dispatch"));
u = true;
}
});
} catch (t) {
const r = l(t) && typeof t.details === "object" && t.details !== null && "mutationAccepted" in t.details && t.details.mutationAccepted === false;
throw new LocalStateOwnerError(u && !r ? "OUTCOME_UNKNOWN" : "OWNER_REFUSED", `Gateway owning ${v.stateDir} on local port ${o} could not complete ${n} for ${e.target}: ${redactSensitiveUrlLikeString(formatErrorMessage(t))}. ` + (u && !r ? `The outcome may be partial; inspect ${e.recoveryCommand ?? "the operation's status"} and the target before retrying. No local fallback was attempted.` : `No local mutation was attempted. ${C}`), t);
}
};
if (typeof e.onForeignOwner === "function") {
assertTargetCurrent();
const t = await e.onForeignOwner({
env: a,
signal: b.signal,
assertCurrent: assertTargetCurrent,
requestOwner: (e, t, n) => requestGateway(e, t, false, n?.expectFinal)
});
assertTargetCurrent();
return t;
}
if (e.onForeignOwner === "refuse") return refuse(/* @__PURE__ */ new Error("This operation requires exclusive offline state ownership"));
listenerPort();
const n = typeof o === "function" ? await o(b.signal) : o;
return await requestGateway(e.method, n, true);
};
try {
assertTargetCurrent();
const n = p(y);
if (n) {
if (t) return refuse(/* @__PURE__ */ new Error("Database port recovery requires exclusive offline ownership"));
if (e.databaseAccess === "none") return refuse(/* @__PURE__ */ new Error("Config-only repair requires exclusive offline ownership"));
return await runLocal(n.assertCurrent);
}
const r = t ? void 0 : await discover();
if (r) return await route(r);
let i;
try {
i = await c({
env: a,
role: e.databasePortMaintenance ? "sqlite-maintenance" : "agent-embedded",
allowInTests: true,
databasePortRecovery: t,
databaseAccess: e.databaseAccess
});
} catch (e) {
if (!t && l(e)) {
const e = await discover();
if (e) return await route(e);
}
return refuse(e);
}
if (!i) return refuse(/* @__PURE__ */ new Error("Offline state ownership was not acquired"));
let o;
try {
if (e.databaseAccess !== "none" && e.databaseEngine === "configured" && !g()) {
const [{ createConfigIO: e }, t, { resolveDatabaseEngineSelection: n }, { loadDotEnvAsync: r }] = await Promise.all([
import("./io-DeTUDO0h.mjs"),
import("./io.invalid-config-DHUoEji6.mjs"),
import("./config-eNRW_vew.mjs"),
import("./dotenv-C8xNDyjL.mjs")
]);
i.assertCurrent();
assertTargetCurrent();
await r({ env: a });
i.assertCurrent();
assertTargetCurrent();
const s = await e({
env: a,
configPath: a.OPENCLAW_CONFIG_PATH,
observe: false,
pluginValidation: "core-only"
}).readConfigFileSnapshot();
if (t.isConfigReadFailure(s)) throw t.createConfigReadError(s);
if (!s.valid) throw t.createInvalidConfigError(s.path, t.formatInvalidConfigDetails(s.issues));
i.assertCurrent();
assertTargetCurrent();
o = await n(s.config, a);
i.assertCurrent();
assertTargetCurrent();
}
} catch (e) {
await i.release();
throw e;
}
const runOwned = async () => {
const t = e.databasePortMaintenance || e.databaseAccess === "none" ? void 0 : h({
assertOwnerCurrent: () => i.assertCurrent(),
assertDatabaseAccess: i.assertDatabaseAccess
});
let n = false;
try {
return await (t ?? i).run(() => runLocal(i.assertCurrent));
} catch (e) {
n = hasCommandProcessCleanupError(e);
throw e;
} finally {
await t?.close();
const e = n ? m(y) : void 0;
await i.release();
e?.assertCurrent();
}
};
return o ? await _(o, runOwned) : await runOwned();
} finally {
x.resolve();
S();
}
}
//#endregion
export { runWithLocalStateOwner as t };