openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
394 lines (393 loc) • 13.4 kB
JavaScript
import { r as resolveStateDir } from "./state-dir-DiG0gXzD.mjs";
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs";
import { n as materializeErrorStack } from "./error-graph-internal-DdjdM90N.mjs";
import { t as waitForAgentDatabasePreparation } from "./agent-database-preparation-context-CkVoUMTY.mjs";
import { n as normalizeAgentId } from "./agent-id-CQjtp2ft.mjs";
import "./session-key-CqAyZeVk.mjs";
import { c as resolveOpenClawAgentSqlitePath } from "./openclaw-agent-db.paths-DJxv80ws.mjs";
import { r as sqlPublicationAnchor } from "./sql-connection-Beiyg5Dt.mjs";
import { i as assertExistingDatabaseIdentity, u as normalizeDatabasePath } from "./sqlite-worker-identity-BH8ZkJU9.mjs";
import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs";
import { c as createSqliteLifecycleAggregateError, u as throwSqliteLifecycleErrors } from "./sqlite-lifecycle-errors-D8BU4VLa.mjs";
import { s as resolveOpenClawStateSqlitePath } from "./openclaw-state-db.paths-R3ArRCcz.mjs";
import { d as AgentDatabaseExecutionAdmissionClosedError, o as registerOpenClawAgentDatabaseAsyncResource } from "./openclaw-agent-db-resources-Dp8HvLsg.mjs";
import { i as createSqliteWorkerOperationAdmission } from "./sqlite-worker-operation-admission-9E_X-oRy.mjs";
import { b as registerOpenClawStateDatabaseAsyncResource, r as captureOpenClawStateDatabaseReadAdmission } from "./openclaw-state-db-cache-CkwtTqzF.mjs";
import { r as cloneEnvWithPlatformSemantics } from "./config-env-vars-ByeGN-9N.mjs";
import { l as reserveSqliteWorkerInputPreparation } from "./sqlite-worker-store-D51tD0Vp.mjs";
import { a as readOpenClawAgentDatabaseIdentity } from "./openclaw-agent-db-identity-C8MGU8lp.mjs";
import { c as getGatewayShutdownCleanupSignal, s as getGatewayRestartDrainSignal } from "./gateway-work-admission-79pid1hQ.mjs";
import { i as retainAgentDatabase, n as getOpenClawAgentDatabaseIfOpen } from "./openclaw-agent-db-borrower-BrziJlyo.mjs";
import "./openclaw-agent-db-lifecycle-DqaZZnYh.mjs";
import { i as runOpenClawAgentWorkerWrite } from "./session-worker-execution-source-H3bdawqM.mjs";
import "./openclaw-agent-db-CwXW4hGa.mjs";
import { t as warnPluginSdkDeprecation } from "./sdk-deprecation-D5N9acnu.mjs";
import { i as captureOpenClawAgentDatabasePreparationExecution, n as captureOpenClawAgentDatabaseExecution } from "./openclaw-agent-execution-C4FyHhb0.mjs";
import { randomUUID } from "node:crypto";
import { deserialize, serialize } from "node:v8";
import { addAbortListener } from "node:events";
//#region src/state/openclaw-agent-worker-store.ts
const log = createSubsystemLogger("state/agent-db");
function reportCompletedPublicationCleanupFailure(e) {
try {
log.warn(`Agent publication completed before cleanup failed: ${formatErrorMessage(e)}`);
} catch {}
}
/** Send a paired module's command through the caller's already-admitted executor. */
function executeOpenClawAgentWorkerPublication(e, t, n) {
const { command: r } = t;
if (typeof r.type !== "string") throw new Error("Agent publication commands require a string type");
return e.execute({
type: "database.domain.publish",
input: {
...t,
command: {
type: r.type,
input: r.input
}
}
}, n);
}
/** Retains a native borrow or checks a caller-held executor; each operation borrows the canonical executor. */
async function openOpenClawAgentSqliteWorkerStore(e, t, n) {
if (!("execution" in t)) warnPluginSdkDeprecation({
family: "sqlite-runtime-native-access",
method: "openOpenClawAgentSqliteWorkerStore(nativeDatabase)",
replacement: "openOpenClawAgentSqliteWorkerStoreV2"
});
return createOpenClawAgentSqliteWorkerStore(e, t, n);
}
/** A retained worker capability; no writable native handle leaves the storage owner. */
async function openOpenClawAgentSqliteWorkerStoreV2(e, t, n) {
if (t.version !== 2 || typeof t.assertCurrent !== "function") throw new Error("Agent worker storage requires V2 live authority");
return createOpenClawAgentSqliteWorkerStore(e, { authority: t }, n);
}
async function createOpenClawAgentSqliteWorkerStore(e, t, n) {
const r = cloneEnvWithPlatformSemantics(e.env ?? process.env);
r.OPENCLAW_STATE_DIR = resolveStateDir(r);
const i = {
...e,
agentId: normalizeAgentId(e.agentId),
env: r,
path: resolveOpenClawAgentSqlitePath({
...e,
env: r
})
};
const a = "authority" in t ? t.authority : void 0;
a?.assertCurrent();
if (a) {
const e = waitForAgentDatabasePreparation(i.agentId, { env: r });
if (e) {
await e;
a.assertCurrent();
}
}
const o = "execution" in t || "authority" in t ? void 0 : t;
const s = o ? readOpenClawAgentDatabaseIdentity({ db: o }) : void 0;
const c = s ? {
kind: "file",
physicalIdentity: s.identity,
nativeLocation: s.filename,
birthtime: s.birthtime
} : void 0;
const l = new URL(n.moduleUrl).href;
const u = structuredClone(n.input);
const d = captureOpenClawStateDatabaseReadAdmission(resolveOpenClawStateSqlitePath(i.env));
const f = a ? captureOpenClawAgentDatabaseExecution(i) : void 0;
const p = f ?? ("execution" in t ? t.execution : void 0);
let m = false;
const h = new AbortController();
let g;
let _;
let v;
let y;
let b;
let x;
const S = /* @__PURE__ */ new Set();
const C = getGatewayShutdownCleanupSignal();
const reportTerminal = (e) => {
if (g) return;
const t = e instanceof Error ? e : new Error(formatErrorMessage(e));
materializeErrorStack(t);
g = t;
m = true;
Promise.resolve().then(async () => {
await Promise.allSettled(S);
h.abort(t);
});
};
const w = f?.onTerminal(reportTerminal);
const releaseDrainExecution = async () => {
await v?.release();
v = void 0;
};
const assertHeld = (e = false) => {
if (m && !e) throw g ?? new AgentDatabaseExecutionAdmissionClosedError("Agent database Worker owner is closed");
try {
d.assertCurrent();
if (!e) a?.assertCurrent();
if (p) {
p.assertCurrent();
return;
}
} catch (t) {
if (!e) reportTerminal(t);
throw t;
}
const t = getOpenClawAgentDatabaseIfOpen(i);
if (!o || !t || t.db !== o || !o.isOpen || normalizeDatabasePath(sqlPublicationAnchor(o).location() ?? "") !== s?.filename) throw new Error("Borrowed agent database closed or changed before Worker admission");
};
const close = () => {
m = true;
T[Symbol.dispose]();
_ ??= (async () => {
await Promise.allSettled(S);
w?.();
await releaseDrainExecution();
if (a) await p?.release();
y?.();
y = void 0;
b?.();
x?.();
})().catch((e) => {
_ = void 0;
throw e;
});
return _;
};
const T = addAbortListener(C, () => {
const e = releaseDrainExecution();
S.add(e);
e.finally(() => S.delete(e)).catch(reportCompletedPublicationCleanupFailure);
});
try {
if (p && (p.agentId !== i.agentId || p.path !== i.path)) throw new Error("Agent publication source differs from its captured executor");
assertHeld();
if (c) assertExistingDatabaseIdentity(i.path, `file:${c.physicalIdentity}`, c.birthtime);
b = registerOpenClawAgentDatabaseAsyncResource({
agentId: i.agentId,
path: i.path,
revoke: () => {
reportTerminal(new AgentDatabaseExecutionAdmissionClosedError("Agent database Worker owner is closed: admission revoked"));
},
close
});
x = registerOpenClawStateDatabaseAsyncResource({
admission: d,
close: async () => {
reportTerminal(new AgentDatabaseExecutionAdmissionClosedError("Agent database Worker state admission closed"));
await close();
}
});
if (o) y = retainAgentDatabase(o);
} catch (e) {
try {
await close();
} catch (t) {
throw new AggregateError([e, t], "Agent publication setup and cleanup failed", { cause: t });
}
throw e;
}
const runPublication = (e, t, r, a = false) => {
if (m) return Promise.reject(g ?? new AgentDatabaseExecutionAdmissionClosedError("Agent database Worker owner is closed"));
const assert = () => {
assertHeld();
e();
assertHeld();
};
const o = a ? captureOpenClawAgentDatabasePreparationExecution(i, c) : captureOpenClawAgentDatabaseExecution(i, { expectedIdentity: c });
const s = {
assertCurrent: assert,
createAdmission(e) {
return (t) => {
const r = createSqliteWorkerOperationAdmission((t, r) => {
e.authorize(n.assertAdmission?.(t) ?? t);
if (!r(() => n.onAdmitted?.(t))) throw new Error("Agent publication authority expired");
}, e.attachment);
try {
n.observeAdmission?.(r, t);
} catch (e) {
r.finish();
throw e;
}
return {
nativeLocations: e.nativeLocations,
admission: r
};
};
}
};
const l = (async () => {
let e;
try {
e = {
ok: true,
value: await runOpenClawAgentWorkerWrite(i, () => t(o, s), void 0, r)
};
} catch (t) {
e = {
ok: false,
error: t
};
}
let n = o;
if (e.ok && !m && getGatewayRestartDrainSignal().aborted && !C.aborted) {
const e = v;
v = o;
n = e;
}
try {
await n?.release();
} catch (t) {
if (!e.ok) throw createSqliteLifecycleAggregateError([e.error, t], "Agent publication and executor release failed", e.error);
reportCompletedPublicationCleanupFailure(t);
}
if (!e.ok) throw e.error;
return e.value;
})();
S.add(l);
l.finally(() => S.delete(l)).catch(() => {});
return l;
};
const executeCommand = async (e, t, n, r) => {
r?.signal?.throwIfAborted();
if (typeof e.type !== "string") throw new Error("Agent publication commands require a string type");
const i = {
id: randomUUID(),
moduleUrl: l,
input: u,
command: {
type: e.type,
input: e.input
}
};
const a = serialize(i);
const o = reserveSqliteWorkerInputPreparation(a.byteLength, "snapshot");
try {
return await runPublication(t, async (e, t) => {
return n(await e.runExisting(t, async (e) => ({ value: await o.handoff(() => executeOpenClawAgentWorkerPublication(e, deserialize(a), r)) })));
}, r?.signal);
} finally {
o.release();
}
};
return {
terminalSignal: h.signal,
async prepare(e) {
e?.signal?.throwIfAborted();
return runPublication(() => {}, (t, n) => t.prepare(n, e?.signal), e?.signal, true);
},
execute(e, t, n) {
return executeCommand(e, t, (e) => {
if (!e) throw new Error("Agent database disappeared before publication");
return e.value;
}, n);
},
executeExisting(e, t, n) {
return executeCommand(e, t, (e) => e, n);
},
run(e, t) {
return runPublication(t, async (t, n) => {
const r = {
assertCurrent: () => assertHeld(true),
createAdmission(e) {
return () => ({
nativeLocations: e.nativeLocations,
admission: createSqliteWorkerOperationAdmission((t, n) => {
if (t.stage !== "prepare") throw new Error("Publication cleanup cannot open storage or admit a transaction");
e.authorize(t);
if (!n()) throw new Error("Agent publication cleanup authority expired");
}, e.attachment)
});
}
};
const i = randomUUID();
let a = false;
const o = [];
let s;
try {
const r = await t.runExisting(n, async (t) => {
await t.execute({
type: "database.domain.bind",
input: {
id: i,
moduleUrl: l,
input: u
}
});
a = true;
let n = true;
const r = /* @__PURE__ */ new Set();
const s = [];
let c;
try {
c = {
ok: true,
value: await e({ execute: (e, a) => {
if (!n) return Promise.reject(/* @__PURE__ */ new Error("Agent publication operation is closed"));
if (typeof e.type !== "string") return Promise.reject(/* @__PURE__ */ new Error("Agent publication commands require a string type"));
const o = t.execute({
type: "database.domain.execute",
input: {
id: i,
command: {
type: e.type,
input: e.input
}
}
}, a);
r.add(o);
o.then(() => r.delete(o), (e) => {
if (!s.includes(e)) s.push(e);
r.delete(o);
});
return o;
} })
};
} catch (e) {
c = {
ok: false,
error: e
};
}
n = false;
await Promise.allSettled(r);
if (!c.ok) o.push(c.error);
for (const e of s) if (!o.includes(e)) o.push(e);
if (!c.ok) throw c.error;
return { value: c.value };
});
s = r ? {
ok: true,
value: r.value
} : {
ok: false,
error: /* @__PURE__ */ new Error("Agent database disappeared before publication")
};
} catch (e) {
s = {
ok: false,
error: e
};
}
if (!s.ok && !o.includes(s.error)) o.push(s.error);
if (a) try {
await t.runExisting(r, (e) => e.execute({
type: "database.domain.close",
input: { id: i }
}), { retireNativeOnFailure: true });
} catch (e) {
if (e instanceof AgentDatabaseExecutionAdmissionClosedError) {} else if (s.ok && o.length === 0) reportCompletedPublicationCleanupFailure(e);
else o.push(e);
}
throwSqliteLifecycleErrors(o, "Agent publication and cleanup failed");
if (!s.ok) throw s.error;
return s.value;
});
},
close
};
}
//#endregion
export { openOpenClawAgentSqliteWorkerStore as n, openOpenClawAgentSqliteWorkerStoreV2 as r, executeOpenClawAgentWorkerPublication as t };