openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
173 lines (172 loc) • 7.43 kB
JavaScript
import { l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs";
import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs";
import { r as resolveStateDir } from "./state-dir-DiG0gXzD.mjs";
import "./paths-DAcAg5aV.mjs";
import { t as SqliteWorkerError } from "./sqlite-worker-error-DEIJgRIz.mjs";
import "./sqlite-worker-contract--dxXkOty.mjs";
import { a as observeSqliteWorkerCommittedFacts, i as createSqliteWorkerOperationAdmission } from "./sqlite-worker-operation-admission-9E_X-oRy.mjs";
import { n as executeExistingOpenClawStateRead } from "./openclaw-state-db-readonly-B6YHb1oF.mjs";
import { r as captureOpenClawStateWorkerContext } from "./openclaw-state-worker-context-DAKL_dnZ.mjs";
import { i as runOpenClawStateWorkerOperation } from "./openclaw-state-worker-store-2LoAv_8B.mjs";
import { r as logInfo } from "./logger-CIwfuhOU.mjs";
import { t as createPendingPromiseTracker } from "./pending-promises-DNsYFS1E.mjs";
import { i as normalizeStoredNodeHostConfig, n as normalizeGatewayConfig, r as normalizeNodeHostCommands, t as nodePreparedWorkspacePublication } from "./node-worker-prepared-workspace-publication-BHZAZGva.mjs";
import fs from "node:fs";
import path from "node:path";
import crypto from "node:crypto";
//#region src/node-host/node-worker-journal-worker.ts
/** Host custody lasts through delivery and native transaction settlement. */
var NodeWorkerJournalWorker = class {
constructor(e) {
this.options = e;
this.pending = /* @__PURE__ */ new Set();
this.trackPending = createPendingPromiseTracker(this.pending);
this.settlements = /* @__PURE__ */ new Set();
this.accepting = true;
}
operation(e) {
return (...t) => this.execute({
type: e,
input: t
});
}
execute(e, t) {
const n = structuredClone(e);
if (n.type === "nodeWorker.prepared.register" || n.type === "nodeWorker.prepared.bind" || n.type === "nodeWorker.prepared.retire" || n.type === "nodeWorker.prepared.completeMutation") {
if (!this.accepting) return Promise.reject(this.uncertain ?? /* @__PURE__ */ new Error("Node worker journal admission is closed"));
return this.runAdmitted((e) => e.execute(n), t, void 0, true);
}
if (n.type === "nodeWorker.turn.get" || n.type === "nodeWorker.launch.nonterminalCount") return this.runAdmitted((e) => e.execute(n), t);
return this.run((e) => e.execute(n), t);
}
run(e, t, n) {
if (!this.accepting) return Promise.reject(this.uncertain ?? /* @__PURE__ */ new Error("Node worker journal admission is closed"));
return n?.existingOnly ? this.runAdmitted(e, t, n) : this.runAdmitted(e, t);
}
runAdmitted(e, t, n, r) {
if (this.uncertain) return Promise.reject(this.uncertain);
const i = captureOpenClawStateWorkerContext(this.options);
const assertCurrent = () => {
if (this.uncertain) throw this.uncertain;
t?.assertCurrent();
};
const createAdmission = (e) => {
assertCurrent();
this.settlements.add(e.settled);
e.settled.then((t) => {
if (t.kind === "unknown") {
this.uncertain ??= Object.assign(new SqliteWorkerError("Node worker journal transaction outcome is unknown", "outcome-unknown"), { cause: t.error });
this.accepting = false;
}
this.settlements.delete(e.settled);
});
const t = createSqliteWorkerOperationAdmission((e, t) => {
assertCurrent();
t();
});
const n = r ? nodePreparedWorkspacePublication.begin({
get identity() {
return i.admission.identity.key;
},
assertCurrent: i.assertPublicationCurrent ?? i.admission.assertCurrent
}) : void 0;
observeSqliteWorkerCommittedFacts(t, ({ facts: e }) => {
if (n) {
if (!isRecord(e) || e.kind !== "node-prepared-workspace") throw new Error("Prepared workspace has no committed receipt");
n.committed(e.receipt);
}
});
e.settled.then((e) => n?.finish(e.kind === "completed"));
return {
nativeLocations: [i.admission.databasePath],
admission: t
};
};
const a = n?.existingOnly ? runOpenClawStateWorkerOperation(i, e, {
assertCurrent,
createAdmission,
existingOnly: true
}) : runOpenClawStateWorkerOperation(i, e, {
assertCurrent,
createAdmission
});
return this.trackPending(a);
}
async drain(e = {}) {
if (e.close !== false) this.accepting = false;
do {
await Promise.allSettled(this.pending);
await Promise.allSettled(this.settlements);
} while (this.pending.size > 0 || this.settlements.size > 0);
if (this.uncertain) throw this.uncertain;
}
};
//#endregion
//#region src/node-host/config.ts
/** Canonical shared-SQLite configuration for the node-host runner. */
const NODE_HOST_CONFIG_KEY = "nodeHost.config";
const LEGACY_NODE_HOST_CONFIG_FILE = "node.json";
const LEGACY_NODE_HOST_CONFIG_CLAIM_SUFFIX = ".doctor-importing";
function legacyPathMayExist(e) {
try {
fs.lstatSync(e);
return true;
} catch (t) {
if (t.code === "ENOENT") return false;
throw new Error(`unable to verify retired node-host state path ${e}`, { cause: t });
}
}
/** Runtime must not choose between canonical SQLite state and a retired file store. */
function assertNodeHostLegacyStateMigrated(e = process.env) {
const t = path.join(resolveStateDir(e), LEGACY_NODE_HOST_CONFIG_FILE);
const n = `${t}${LEGACY_NODE_HOST_CONFIG_CLAIM_SUFFIX}`;
if (!legacyPathMayExist(t) && !legacyPathMayExist(n)) return;
throw new Error(`retired node-host state remains at ${t}; stop the node host and run \`openclaw doctor --fix\``);
}
/** Read canonical node-host state without creating a store or joining its writable lifecycle. */
async function loadNodeHostConfig(e = process.env) {
const t = {
...e,
OPENCLAW_STATE_DIR: resolveStateDir(e)
};
assertNodeHostLegacyStateMigrated(t);
const n = await executeExistingOpenClawStateRead({ env: t }, { type: NODE_HOST_CONFIG_KEY });
if (!n) return null;
const r = n.row;
if (!r) return null;
const i = JSON.parse(r.value_json);
if (!Number.isSafeInteger(r.updated_at_ms) || r.updated_at_ms < 0) throw new Error("invalid node-host SQLite row: updated_at_ms must be a non-negative integer");
return normalizeStoredNodeHostConfig(i);
}
/**
* Atomically create or replace the complete node-host snapshot.
* Candidate facts are prepared before BEGIN; the transaction rereads the authoritative row.
*/
async function configureNodeHost(e) {
const t = e.env ?? process.env;
assertNodeHostLegacyStateMigrated(t);
const n = normalizeOptionalString(e.nodeId);
const r = normalizeOptionalString(e.displayName);
const i = normalizeOptionalString(e.fallbackDisplayName);
const a = e.candidateNodeId?.trim() || crypto.randomUUID();
const o = normalizeGatewayConfig(e.gateway);
const s = e.commands === void 0 ? void 0 : normalizeNodeHostCommands(e.commands);
const { config: c, clearedCommands: l } = await new NodeWorkerJournalWorker({ env: t }).execute({
type: "nodeWorker.configure",
input: [{
explicitNodeId: n,
explicitDisplayName: r,
fallbackDisplayName: i,
candidateNodeId: a,
gateway: o,
installedAppsSharing: e.installedAppsSharing,
commands: s,
allCommands: e.allCommands,
updatedAtMs: Date.now()
}]
});
if (l) logInfo("node-host: cleared saved command allowlist; advertising the full default command surface");
return c;
}
//#endregion
export { loadNodeHostConfig as a, configureNodeHost as i, LEGACY_NODE_HOST_CONFIG_FILE as n, NodeWorkerJournalWorker as o, NODE_HOST_CONFIG_KEY as r, LEGACY_NODE_HOST_CONFIG_CLAIM_SUFFIX as t };