openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
585 lines (584 loc) • 22.8 kB
JavaScript
import { l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs";
import { o as asDateTimestampMs, y as isFutureDateTimestampMs } from "./number-coercion-D6u-4YD8.mjs";
import { a as resolveGlobalSingleton } from "./global-singleton-D7yf05nR.mjs";
import { l as isRecord, u as isStringArray } from "./record-coerce-CVPuDqcc.mjs";
import { n as groupPluginRecords } from "./record-groups-DII71OvH.mjs";
import { n as notifyListeners, r as registerListener } from "./listeners-Cb2-CnP8.mjs";
import { r as sqlPublicationAnchor } from "./sql-connection-Beiyg5Dt.mjs";
import { a as publishSqliteCommittedState, o as stageSqliteCommittedPublication } from "./sqlite-post-commit-BrUVQObC.mjs";
import { m as sqliteStringSetEntries, n as createSqliteQueryCache, r as encodeSqliteStringSet, s as getNodeSqliteKysely, u as prepareSqliteQuerySync } from "./kysely-sync-YJo2lmGV.mjs";
import { u as registerNodeSqliteDisposeCallback } from "./kysely-sync-cache-state-Bb1gOqQO.mjs";
import { s as getSqliteReadOperationRevision } from "./sqlite-schema-facts-B1bVE8IB.mjs";
import { n as SQLITE_WORKER_MAX_MESSAGE_BYTES } from "./sqlite-worker-contract--dxXkOty.mjs";
import { a as deferSqliteWorkerCommitReceipt, s as observeSqliteWorkerAdmissionFinish } from "./sqlite-worker-operation-settlement-OZQM-wtd.mjs";
import { a as observeSqliteWorkerCommittedFacts } from "./sqlite-worker-operation-admission-9E_X-oRy.mjs";
import { a as readTrackedStateDatabaseIdentity } from "./openclaw-state-db-handle-BxpEWiaT.mjs";
import { r as readSqliteCommitReceipt, t as createSqliteCommitReceipt } from "./sqlite-commit-receipt-LVED9ktS.mjs";
import { r as normalizeConversationRef } from "./session-binding-normalization-c5CMRfx2.mjs";
import { randomUUID } from "node:crypto";
import { serialize } from "node:v8";
import { AsyncLocalStorage } from "node:async_hooks";
//#region src/plugins/conversation-binding-metadata.ts
function isPluginOwnedBindingMetadata(e) {
if (!e || typeof e !== "object") return false;
const t = e;
return t.pluginBindingOwner === "plugin" && typeof t.pluginId === "string" && typeof t.pluginRoot === "string";
}
function isPluginOwnedSessionBindingRecord(e) {
return isPluginOwnedBindingMetadata(e?.metadata);
}
//#endregion
//#region src/infra/outbound/current-conversation-bindings.publication.ts
const state = resolveGlobalSingleton(Symbol.for("openclaw.currentConversationBindingPublication"), () => ({
sources: /* @__PURE__ */ new WeakMap(),
capture: new AsyncLocalStorage(),
installingFacts: 0,
facts: /* @__PURE__ */ new Set()
}));
function sourceFor(e) {
const t = sqlPublicationAnchor(e);
let n = state.sources.get(t);
if (!n) {
n = {
identity: readTrackedStateDatabaseIdentity(t)?.key ?? Symbol("untracked-binding-database"),
incarnation: randomUUID()
};
state.sources.set(t, n);
}
return n;
}
function capturePublication(e, t) {
const n = new Map(t.map((e) => [e.key, e.current]));
return {
receipt: createSqliteCommitReceipt({
source: sourceFor(e),
domain: "current-conversation-bindings",
keys: [...n.keys()],
readFact(e) {
const t = n.get(e);
return t ? {
kind: "postimage",
value: t
} : { kind: "absent" };
}
}),
sessionKeys: [...new Set(t.flatMap((e) => [e.previousTargetSessionKey, e.currentTargetSessionKey ?? e.current?.targetSessionKey].filter((e) => e !== void 0)))]
};
}
function unknownPublication(e) {
return {
...e,
receipt: {
...e.receipt,
facts: new Map([...e.receipt.facts.keys()].map((e) => [e, { kind: "unknown" }]))
}
};
}
function installFacts(e) {
const t = [];
state.installingFacts++;
try {
notifyListeners(state.facts, e, (e) => t.push(e));
} finally {
state.installingFacts--;
}
if (t.length) throw new AggregateError(t, "Conversation binding fact installation failed");
}
function publicationState(e) {
let t = e;
return {
installFacts: () => installFacts(t),
invalidate() {
t = unknownPublication(e);
installFacts(t);
},
notify() {}
};
}
/** Owns binding-fact staging and observation; callers retain native/foreign authority guards. */
const currentConversationBindingPublication = {
stage: stageCurrentConversationBindingChanges,
/** Install/invalidate prepared facts only. */
subscribeFacts(e) {
return registerListener(state.facts, e);
}
};
/** Called inside the owning write transaction using rows already read by its kernel. */
function stageCurrentConversationBindingChanges(e, t) {
if (!t.length) return;
if (state.installingFacts) throw new Error("Conversation bindings cannot mutate during fact installation");
state.capture.getStore()?.push(...t);
const n = capturePublication(e, t);
if (!stageSqliteCommittedPublication(e, publicationState(n)) && !e.isTransaction) publishSqliteCommittedState(publicationState(n));
}
/** One receipt covers every changed row in this worker transaction, including mutating reads. */
function withCurrentConversationBindingWorkerReceipt(e, t) {
return state.capture.run([], () => {
const n = t();
const r = state.capture.getStore();
if (r.length) {
const t = capturePublication(e, r);
deferSqliteWorkerCommitReceipt(e, serialize(t).byteLength <= 33554432 ? t : {
kind: "unknown",
identity: t.receipt.source.identity
});
}
return n;
});
}
function readPublication(e) {
if (!isRecord(e) || !isStringArray(e.sessionKeys)) throw new Error("Conversation binding receipt is invalid");
return {
receipt: readSqliteCommitReceipt(e.receipt, {
domain: "current-conversation-bindings",
invalidReceiptMessage: "Conversation binding receipt has incomplete facts",
isFact: (e, t) => t.kind === "absent" || t.kind === "postimage" && isRecord(t.value) && typeof t.value.bindingId === "string" && typeof t.value.targetSessionKey === "string" && isRecord(t.value.conversation)
}),
sessionKeys: e.sessionKeys
};
}
/** Retain supersession until native settlement, independent of ordinary reply delivery. */
function withCurrentConversationBindingPublication(e, t, n) {
return (r) => {
const i = [];
notifyListeners(state.facts, {
kind: "pending",
identity: t(),
operation: r
}, (e) => i.push(e));
let a;
try {
if (i.length) throw new AggregateError(i, "Conversation binding pending installation failed");
a = e(r);
} catch (e) {
notifyListeners(state.facts, {
kind: "settled",
identity: t(),
operation: r,
outcome: "unknown"
});
throw e;
}
const o = /* @__PURE__ */ new Set();
let s = false;
let c = false;
let l = false;
const u = currentConversationBindingPublication.subscribeFacts((e) => {
if (s) return;
if (!("receipt" in e)) {
if (e.identity === t() && (e.kind === "unknown" || e.kind === "settled" && e.outcome === "unknown")) l = true;
return;
}
const { receipt: n } = e;
if (n.source.identity === t()) for (const e of n.facts.keys()) o.add(e);
});
let d = false;
observeSqliteWorkerAdmissionFinish(a.admission, () => {
if (!d) {
d = true;
u();
notifyListeners(state.facts, {
kind: "settled",
identity: t(),
operation: r,
outcome: !l && a.admission.settlement?.kind === "completed" ? c ? "published" : "unchanged" : "unknown"
});
}
});
observeSqliteWorkerCommittedFacts(a.admission, ({ facts: e }) => {
n();
if (isRecord(e) && e.kind === "unknown" && e.identity === t()) {
l = true;
s = true;
try {
installFacts({
kind: "unknown",
identity: t()
});
c = true;
} finally {
s = false;
}
return;
}
const r = readPublication(e);
if (r.receipt.source.identity !== t()) throw new Error("Conversation binding receipt changed its physical owner");
const i = {
...r,
receipt: {
...r.receipt,
facts: new Map([...r.receipt.facts].map(([e, t]) => [e, l || o.has(e) ? { kind: "unknown" } : t]))
}
};
s = true;
try {
publishSqliteCommittedState(publicationState(i));
c = true;
} finally {
s = false;
}
});
return a;
};
}
//#endregion
//#region src/infra/outbound/session-binding-errors.ts
var SessionBindingError = class extends Error {
constructor(e, t) {
super(t);
this.code = e;
this.name = "SessionBindingError";
}
};
function isSessionBindingError(e) {
return e instanceof SessionBindingError;
}
//#endregion
//#region src/infra/outbound/current-conversation-bindings.kernel.ts
const CURRENT_BINDINGS_ID_PREFIX = "generic:";
const CURRENT_BINDING_CONVERSATION_KIND = "current";
const MAX_RETAINED_BINDING_SELECTION = 128;
const retainedSelections = /* @__PURE__ */ new WeakMap();
function currentConversationBindingRow(e, t, n) {
return {
binding_key: n,
binding_id: e.bindingId,
target_session_key: e.targetSessionKey,
channel: t.channel,
account_id: t.accountId,
conversation_kind: "current",
parent_conversation_id: t.parentConversationId ?? null,
conversation_id: t.conversationId,
target_kind: e.targetKind,
status: e.status,
bound_at: e.boundAt,
expires_at: e.expiresAt ?? null,
metadata_json: e.metadata ? JSON.stringify(e.metadata) : null,
record_json: JSON.stringify(e),
updated_at: Date.now()
};
}
function createCurrentConversationBindingQueries(e) {
const t = getNodeSqliteKysely(e);
const n = t.selectFrom("current_conversation_bindings").select([
"binding_key",
"binding_id",
"target_session_key",
"record_json"
]);
function lists(t) {
const r = t ? n.where("binding_id", "like", `${CURRENT_BINDINGS_ID_PREFIX}%`) : n;
return {
bySessions: prepareSqliteQuerySync(e, (e) => {
const t = sqliteStringSetEntries(e((e) => encodeSqliteStringSet(e.targetSessionKeys))).as("requested");
return r.where("target_session_key", "in", (e) => e.selectFrom(t).select("requested.value")).where((t) => t.or([t(t.cast(e((e) => e.scope?.channel ?? null), "text"), "is", null), t.and([t(e((e) => e.scope?.channel ?? null), "=", t.ref("channel")), t(e((e) => e.scope?.accountId ?? null), "=", t.ref("account_id"))])])).orderBy("target_session_key", "asc").orderBy("binding_id", "asc");
}),
bySession: prepareSqliteQuerySync(e, (e) => r.where("target_session_key", "=", e((e) => e)).orderBy("binding_id", "asc")),
byScope: prepareSqliteQuerySync(e, (e) => r.where((t) => t.and({
target_session_key: e((e) => e.targetSessionKey),
channel: e((e) => e.scope.channel),
account_id: e((e) => e.scope.accountId)
})).orderBy("binding_id", "asc"))
};
}
return {
selection: prepareSqliteQuerySync(e, (e) => {
const n = e((e) => encodeSqliteStringSet(e.flatMap((e) => [
buildConversationKey(e),
e.channel,
e.accountId,
e.conversationId
])));
const r = sqliteStringSetEntries(n).as("field");
const i = t.with("requested", (e) => e.selectFrom(r).select((e) => {
const component = (t) => e.fn.max(e.case().when(e("field.key", "%", 4), "=", t).then(e.ref("field.value")).end());
return [
e.cast(e("field.key", "/", e.lit(4)), "integer").as("request_index"),
component(0).as("binding_key"),
component(1).as("channel"),
component(2).as("account_id"),
component(3).as("conversation_id")
];
}).groupBy((e) => e.cast(e("field.key", "/", e.lit(4)), "integer")));
const a = [
"requested.request_index",
"candidate.binding_key",
"candidate.binding_id",
"candidate.target_session_key",
"candidate.record_json"
];
return i.selectFrom("requested").innerJoin("current_conversation_bindings as candidate", "candidate.binding_key", "requested.binding_key").select(a).select((e) => e.val(1).as("is_exact")).unionAll((e) => e.selectFrom("requested").innerJoin("current_conversation_bindings as candidate", (e) => e.onRef("candidate.channel", "=", "requested.channel").onRef("candidate.account_id", "=", "requested.account_id").onRef("candidate.conversation_id", "=", "requested.conversation_id").on("candidate.conversation_kind", "=", CURRENT_BINDING_CONVERSATION_KIND)).select(a).select((e) => e.val(0).as("is_exact")).where((e) => e.not(e.exists(e.selectFrom("current_conversation_bindings as exact").select("exact.binding_key").whereRef("exact.binding_key", "=", "requested.binding_key"))))).orderBy("request_index");
}),
remove: prepareSqliteQuerySync(e, (e) => t.deleteFrom("current_conversation_bindings").where("binding_key", "=", e((e) => e))),
upsert: prepareSqliteQuerySync(e, (e) => {
const n = {
binding_key: e((e) => e.binding_key),
binding_id: e((e) => e.binding_id),
target_session_key: e((e) => e.target_session_key),
channel: e((e) => e.channel),
account_id: e((e) => e.account_id),
conversation_kind: e((e) => e.conversation_kind),
parent_conversation_id: e((e) => e.parent_conversation_id),
conversation_id: e((e) => e.conversation_id),
target_kind: e((e) => e.target_kind),
status: e((e) => e.status),
bound_at: e((e) => e.bound_at),
expires_at: e((e) => e.expires_at),
metadata_json: e((e) => e.metadata_json),
record_json: e((e) => e.record_json),
updated_at: e((e) => e.updated_at)
};
return t.insertInto("current_conversation_bindings").values(n).onConflict((e) => e.column("binding_key").doUpdateSet(n)).returning([
"binding_key",
"binding_id",
"target_session_key",
"record_json"
]);
}),
generic: lists(true),
all: lists(false)
};
}
const getCurrentConversationBindingQueries = createSqliteQueryCache(createCurrentConversationBindingQueries);
function buildConversationKey(e) {
return [
e.channel,
e.accountId,
e.parentConversationId ?? "",
e.conversationId
].join("␟");
}
function buildBindingId(e) {
return `${CURRENT_BINDINGS_ID_PREFIX}${buildConversationKey(e)}`;
}
function isBindingExpired(e, t = Date.now()) {
if (e.expiresAt === void 0) return false;
const n = asDateTimestampMs(e.expiresAt);
if (n === void 0) return true;
const r = asDateTimestampMs(t);
return r !== void 0 && !isFutureDateTimestampMs(n, { nowMs: r });
}
function bindingRowToRecord(e) {
try {
const t = JSON.parse(e.record_json);
if (!t?.bindingId || !t?.conversation?.conversationId) return null;
const n = normalizeConversationRef(t.conversation);
const r = t.targetSessionKey?.trim() ?? "";
if (!r) return null;
return {
...t,
bindingId: t.bindingId.startsWith("generic:") ? buildBindingId(n) : t.bindingId,
targetSessionKey: r,
conversation: n
};
} catch {
return null;
}
}
function readCurrentConversationBindingRows(e, t) {
if (t.length === 0) return [];
const n = t.length <= MAX_RETAINED_BINDING_SELECTION ? getSqliteReadOperationRevision(e) : void 0;
const r = n ? JSON.stringify(t.map((e) => [
e.channel,
e.accountId,
e.parentConversationId ?? "",
e.conversationId
])) : void 0;
const i = retainedSelections.get(e);
if (n && i?.revision === n && i.conversations === r) return i.rows;
const a = /* @__PURE__ */ new Map();
for (const n of getCurrentConversationBindingQueries(e).selection(t).rows) {
if (a.has(n.request_index)) continue;
const e = t[n.request_index];
const r = n.is_exact ? void 0 : bindingRowToRecord(n);
if (n.is_exact || r && buildConversationKey(r.conversation) === buildConversationKey(e)) a.set(n.request_index, n);
}
const o = t.map((e, t) => a.get(t));
if (n && r && getSqliteReadOperationRevision(e) === n) {
if (!i) {
const t = registerNodeSqliteDisposeCallback(sqlPublicationAnchor(e), () => {
retainedSelections.delete(e);
t();
});
}
retainedSelections.set(e, {
revision: n,
conversations: r,
rows: o
});
}
return o;
}
function updateCurrentConversationBindingRecordInDatabase(e, t, n) {
const r = normalizeConversationRef(t);
const i = buildConversationKey(r);
const a = readCurrentConversationBindingRows(e, [r])[0];
const o = a ? bindingRowToRecord(a) : null;
const s = o && !isBindingExpired(o) ? o : null;
const c = n(s);
if (c === void 0) return {
previous: s,
current: s
};
if (!c) {
if (a) {
getCurrentConversationBindingQueries(e).remove(a.binding_key);
currentConversationBindingPublication.stage(e, [{
key: a.binding_key,
current: null,
previousTargetSessionKey: a.target_session_key
}]);
}
return {
previous: s,
current: null
};
}
if (buildConversationKey(normalizeConversationRef(c.conversation)) !== i) throw new Error("Current conversation binding update changed its conversation owner");
if (a && a.binding_key !== i) getCurrentConversationBindingQueries(e).remove(a.binding_key);
const l = currentConversationBindingRow(c, r, i);
const u = getCurrentConversationBindingQueries(e).upsert(l).rows[0];
currentConversationBindingPublication.stage(e, [...a && a.binding_key !== i ? [{
key: a.binding_key,
current: null,
previousTargetSessionKey: a.target_session_key
}] : [], {
key: u.binding_key,
current: bindingRowToRecord(u),
currentTargetSessionKey: u.target_session_key,
previousTargetSessionKey: a?.target_session_key
}]);
return {
previous: s,
current: c
};
}
function inspectCurrentConversationBindingRecordsInDatabase(e, t, n = Date.now()) {
return readCurrentConversationBindingRows(e, t).map((e) => {
const t = e ? bindingRowToRecord(e) : null;
return t && !isBindingExpired(t, n) ? t : null;
});
}
function readCurrentConversationBindingResolutionInDatabase(e, t) {
const n = readCurrentConversationBindingRows(e, [t])[0];
const r = n ? bindingRowToRecord(n) : null;
return {
record: r ?? null,
repair: Boolean(n && r && (isBindingExpired(r) || n.binding_key !== buildConversationKey(r.conversation) || n.binding_id !== r.bindingId || n.target_session_key !== r.targetSessionKey))
};
}
function listCurrentConversationBindingRowsBySession(e, t, n, r = !n) {
const i = getCurrentConversationBindingQueries(e);
const a = r ? i.generic : i.all;
if (n) {
const e = normalizeConversationRef({
...n,
conversationId: "binding-scope"
});
return a.byScope({
targetSessionKey: t,
scope: e
}).rows;
}
return a.bySession(t).rows;
}
/** Warm listings avoid writer admission unless an expired record requires the existing repair. */
function readCurrentConversationBindingListInDatabase(e, t, n) {
const r = listCurrentConversationBindingRowsBySession(e, t, n).map(bindingRowToRecord).filter((e) => e !== null);
return {
records: r,
requiresPrune: r.some((e) => isBindingExpired(e))
};
}
/** Read every requested target from one SQLite statement, preserving request order and duplicates. */
function readCurrentConversationBindingListsInDatabase(e, t, n) {
if (t.length === 0) return [];
const r = n ? normalizeConversationRef({
...n,
conversationId: "binding-scope"
}) : void 0;
const i = getCurrentConversationBindingQueries(e);
const a = (n ? i.all : i.generic).bySessions({
targetSessionKeys: t,
scope: r
}).rows;
const o = groupPluginRecords(a, (e) => e.target_session_key);
return t.map((e) => {
const t = (o.get(e) ?? []).map(bindingRowToRecord).filter((e) => e !== null);
return {
records: t,
requiresPrune: t.some((e) => isBindingExpired(e))
};
});
}
/** Reread after writer admission; malformed rows keep the same expiry-triggered repair contract. */
function pruneCurrentConversationBindingListInTransaction(e, t, n) {
const r = listCurrentConversationBindingRowsBySession(e, t, n);
const i = [];
for (const t of r) {
const n = bindingRowToRecord(t);
if (!n || isBindingExpired(n)) {
getCurrentConversationBindingQueries(e).remove(t.binding_key);
currentConversationBindingPublication.stage(e, [{
key: t.binding_key,
current: null,
previousTargetSessionKey: t.target_session_key
}]);
} else i.push(n);
}
return i;
}
/** Same-target refreshes preserve committed metadata; target replacements do not inherit it. */
function bindCurrentConversationInDatabase(e, t, n) {
return updateCurrentConversationBindingRecordInDatabase(e, t.record.conversation, (e) => applyCurrentConversationBindingBind(e, t, n)).current;
}
function applyCurrentConversationBindingBind(e, t, n) {
const r = t.record;
assertExpectedCurrentBinding(e, t.expected);
const i = e?.targetSessionKey === r.targetSessionKey && e.targetKind === r.targetKind ? e : void 0;
const a = {
...i?.metadata,
...r.metadata
};
for (const e of t.metadataKeys ?? []) a[e] = r.metadata?.[e];
const o = normalizeOptionalString(r.metadata?.agentId);
const s = typeof i?.metadata?.agentId === "string" ? i.metadata.agentId : void 0;
const c = Boolean(t.accountPolicy && o === void 0 && s === void 0 && !isPluginOwnedBindingMetadata(a));
n?.(c);
if (t.accountPolicy) {
a.agentId = o ?? s ?? (c ? t.accountPolicy.inferredAgentId : void 0);
for (const e of ["label", "boundBy"]) a[e] = normalizeOptionalString(r.metadata?.[e]) ?? (typeof i?.metadata?.[e] === "string" ? i.metadata[e] : void 0);
}
return {
...r,
metadata: a
};
}
function removeCurrentConversationBindingsInDatabase(e, t) {
if ("conversation" in t) {
const { previous: n, current: r } = updateCurrentConversationBindingRecordInDatabase(e, t.conversation, (e) => {
assertExpectedCurrentBinding(e, t.expected);
return !t.bindingId || e?.bindingId === t.bindingId ? null : e ? void 0 : null;
});
return n && !r ? [n] : [];
}
const n = listCurrentConversationBindingRowsBySession(e, t.targetSessionKey, t.scope, t.genericOnly);
const r = [];
for (const i of n) {
const n = bindingRowToRecord(i);
if (t.genericOnly && !n?.bindingId.startsWith("generic:")) continue;
getCurrentConversationBindingQueries(e).remove(i.binding_key);
currentConversationBindingPublication.stage(e, [{
key: i.binding_key,
current: null,
previousTargetSessionKey: i.target_session_key
}]);
if (n && !isBindingExpired(n)) r.push(n);
}
return r;
}
function assertExpectedCurrentBinding(e, t) {
if (t !== void 0 && JSON.stringify(e) !== JSON.stringify(t)) throw new SessionBindingError("BINDING_CREATE_FAILED", "Conversation binding changed before the operation could commit; retry against the current binding");
}
//#endregion
export { withCurrentConversationBindingWorkerReceipt as _, inspectCurrentConversationBindingRecordsInDatabase as a, readCurrentConversationBindingListInDatabase as c, removeCurrentConversationBindingsInDatabase as d, updateCurrentConversationBindingRecordInDatabase as f, withCurrentConversationBindingPublication as g, currentConversationBindingPublication as h, buildBindingId as i, readCurrentConversationBindingListsInDatabase as l, isSessionBindingError as m, applyCurrentConversationBindingBind as n, isBindingExpired as o, SessionBindingError as p, bindCurrentConversationInDatabase as r, pruneCurrentConversationBindingListInTransaction as s, CURRENT_BINDINGS_ID_PREFIX as t, readCurrentConversationBindingResolutionInDatabase as u, isPluginOwnedBindingMetadata as v, isPluginOwnedSessionBindingRecord as y };