openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
255 lines (254 loc) • 11.9 kB
JavaScript
import { c as withSqlitePostCommitPublications } from "../sqlite-post-commit-BrUVQObC.mjs";
import { i as executeSqliteQuerySync, n as createSqliteQueryCache, s as getNodeSqliteKysely, u as prepareSqliteQuerySync } from "../kysely-sync-YJo2lmGV.mjs";
import "../openclaw-state-db-schema-helpers-nImZNMq_.mjs";
import { a as runSqliteImmediateTransactionSync, l as runSqliteWorkerTransactionSync, o as runSqliteReadSnapshotSync } from "../sqlite-transaction-BHHu6P5-.mjs";
import { a as getSqliteWorkerStateContext } from "../sqlite-worker-state-context-CR8h__Vh.mjs";
import { o as sessionChanges, t as captureSessionRowChanges } from "../session-row-changes-BA4BqVwF.mjs";
import { n as getOpenClawAgentDatabaseIfOpen } from "../openclaw-agent-db-borrower-BrziJlyo.mjs";
import { j as ensureOpenClawAgentBoardSchemaInTransaction } from "../openclaw-agent-outbox-sequence-migration-ATXcQD7n.mjs";
import "../openclaw-agent-db-CwXW4hGa.mjs";
import { i as applyBoardOps, r as BoardValidationError, s as normalizeOwnedBoardLayout } from "../board-layout-C0d9b7cg.mjs";
import { a as normalizeBoardWidgetPutParams, i as createBoardWidgetPutSnapshot, n as createBoardGrantSnapshot, r as createBoardWidgetPutResult } from "../board-store-32jhOjw-.mjs";
import { t as bindSqliteWorkerDatabase } from "../sqlite-worker-binding-B4BB5u5i.mjs";
import { a as parsePluginContent, c as rowToTab, d as updateManifestHeightMode, i as parseManifest, l as rowToWidget, n as createBoardWidgetContentFields, o as resolveSqliteBoardWidgetPutParams, r as parseDescriptor, s as rowToHtmlViewMetadata, t as BOARD_WIDGET_SNAPSHOT_COLUMNS, u as serializeManifest } from "../sqlite-board-codec-C7odCXMU.mjs";
//#region src/boards/sqlite-board-read-queries.ts
function createBoardReadQueries(e) {
const t = getNodeSqliteKysely(e);
return {
session: prepareSqliteQuerySync(e, (e) => t.selectFrom("session_nodes").select("entry_json").where("session_key", "=", e((e) => e)).limit(1)),
tabs: prepareSqliteQuerySync(e, (e) => t.selectFrom("board_tabs").selectAll().where("session_key", "=", e((e) => e)).orderBy("position", "asc").orderBy("tab_id", "asc")),
widgets: prepareSqliteQuerySync(e, (e) => t.selectFrom("board_widgets").select(BOARD_WIDGET_SNAPSHOT_COLUMNS).where("session_key", "=", e((e) => e)).orderBy("tab_id", "asc").orderBy("position", "asc").orderBy("name", "asc"))
};
}
const getBoardReadQueries = createSqliteQueryCache(createBoardReadQueries);
//#endregion
//#region src/boards/sqlite-board-store.kernel.ts
const ensuredBoardDatabases = /* @__PURE__ */ new WeakSet();
const BOARD_WRITE_BATCH_SIZE = 64;
function ensureBoardSchema(e) {
if (ensuredBoardDatabases.has(e.db)) return;
if (e.db.isTransaction) throw new Error("board schema must be ensured before the write transaction starts");
runSqliteImmediateTransactionSync(e.db, () => ensureOpenClawAgentBoardSchemaInTransaction(e.db), {
databaseLabel: e.path,
operationLabel: "board.ensure-schema"
});
ensuredBoardDatabases.add(e.db);
}
function readStoredBoard(e, t) {
const read = () => {
const n = getBoardReadQueries(e.db);
const r = n.tabs(t).rows;
const i = n.widgets(t).rows.map((e) => ({
row: e,
manifest: parseManifest(e.manifest)
})).filter(({ row: e, manifest: t }) => {
if (e.content_kind !== "mcp-app") return true;
return t.mcpAppInteractive !== void 0 && t.mcpAppInstanceId !== void 0;
});
const a = /* @__PURE__ */ new Map();
for (const { row: e, manifest: t } of i) {
const n = rowToHtmlViewMetadata(e, t);
if (n) a.set(e.name, n);
}
const o = normalizeOwnedBoardLayout({
tabs: r.map(rowToTab),
widgets: i.map(({ row: e, manifest: t }) => rowToWidget(e, t))
});
return {
snapshot: {
sessionKey: t,
revision: r.reduce((e, t) => Math.max(e, t.revision), 0),
...o
},
tabRows: r,
widgetRows: i.map(({ row: e }) => e),
htmlViewMetadata: a
};
};
return e.db.isTransaction ? read() : runSqliteReadSnapshotSync(e.db, read, {
databaseLabel: e.path,
operationLabel: "board.read"
});
}
function upsertTabs(e, t, n) {
const r = getNodeSqliteKysely(e.db);
const i = new Map(t.tabRows.map((e) => [e.tab_id, e.created_by]));
for (let t = 0; t < n.tabs.length; t += BOARD_WRITE_BATCH_SIZE) executeSqliteQuerySync(e.db, r.insertInto("board_tabs").values(n.tabs.slice(t, t + BOARD_WRITE_BATCH_SIZE).map((e) => ({
session_key: n.sessionKey,
tab_id: e.tabId,
title: e.title,
position: e.position,
chat_dock: e.chatDock,
created_by: i.get(e.tabId) ?? "agent",
revision: n.revision
}))).onConflict((e) => e.columns(["session_key", "tab_id"]).doUpdateSet({
title: (e) => e.ref("excluded.title"),
position: (e) => e.ref("excluded.position"),
chat_dock: (e) => e.ref("excluded.chat_dock"),
revision: (e) => e.ref("excluded.revision")
})));
sessionChanges.emit({
sessionKey: n.sessionKey,
storePath: e.path,
facts: { kind: "unchanged" }
}, e.db);
}
function updateWidgetLayouts(e, t, n, r, i) {
const a = getNodeSqliteKysely(e.db);
const o = new Map(t.widgetRows.map((e) => [e.name, e]));
for (const t of n.widgets) {
const s = o.get(t.name);
if (t.name === i || s && s.tab_id === t.tabId && s.title === (t.title ?? null) && s.size_w === t.sizeW && s.size_h === t.sizeH && s.position === t.position) continue;
executeSqliteQuerySync(e.db, a.updateTable("board_widgets").set({
tab_id: t.tabId,
title: t.title ?? null,
size_w: t.sizeW,
size_h: t.sizeH,
position: t.position,
updated_at: r
}).where("session_key", "=", n.sessionKey).where("name", "=", t.name));
}
}
function updateWidgetHeightModes(e, t, n) {
const r = getNodeSqliteKysely(e.db);
for (const i of n) {
if (i.kind !== "widget_resize") continue;
const n = t.widgetRows.find((e) => e.name === i.name);
if (!n) continue;
executeSqliteQuerySync(e.db, r.updateTable("board_widgets").set({ manifest: updateManifestHeightMode(n.manifest, i.heightMode ?? "fixed") }).where("session_key", "=", t.snapshot.sessionKey).where("name", "=", i.name));
}
}
function deleteRemovedBoardRows(e, t, n, r, i) {
const a = getNodeSqliteKysely(e.db);
const o = new Set(i);
const s = r.filter((e) => !o.has(e));
const [c, l] = n;
for (let n = 0; n < s.length; n += BOARD_WRITE_BATCH_SIZE) executeSqliteQuerySync(e.db, a.deleteFrom(c).where("session_key", "=", t.sessionKey).where(l, "in", s.slice(n, n + BOARD_WRITE_BATCH_SIZE)));
}
function hasBoardSession(e, t, n) {
const r = getBoardReadQueries(e.db).session(t).rows[0];
if (!r) return false;
try {
const e = JSON.parse(r.entry_json);
return Boolean(e && typeof e === "object" && !Array.isArray(e) && "sessionId" in e && typeof e.sessionId === "string" && (!n || e.sessionId === n.sessionId && ("lifecycleRevision" in e ? e.lifecycleRevision : void 0) === n.lifecycleRevision));
} catch {
return false;
}
}
function readRequiredBoard(e, t, n) {
if (!hasBoardSession(e, t, n)) throw new BoardValidationError(n ? "invalid_operation" : "not_found", n ? "board session changed; retry" : `board session not found: ${t}`);
return readStoredBoard(e, t);
}
function applyBoardOpsToDatabase(e, t, n, r) {
const i = readRequiredBoard(e, t, r);
const a = applyBoardOps(i.snapshot, n);
const o = {
sessionKey: t,
revision: i.snapshot.revision + 1,
...a
};
const s = Date.now();
upsertTabs(e, i, o);
deleteRemovedBoardRows(e, o, ["board_widgets", "name"], i.widgetRows.map((e) => e.name), o.widgets.map((e) => e.name));
updateWidgetLayouts(e, i, o, s);
updateWidgetHeightModes(e, i, n);
deleteRemovedBoardRows(e, o, ["board_tabs", "tab_id"], i.tabRows.map((e) => e.tab_id), o.tabs.map((e) => e.tabId));
return o;
}
function putBoardWidgetInDatabase(e, t, n, r, i) {
const a = readRequiredBoard(e, t, i);
const o = resolveSqliteBoardWidgetPutParams(a.snapshot, n, a.widgetRows);
const s = a.widgetRows.find((e) => e.name === o.name);
const c = s ? s.content_kind === "html" ? o.content.kind === "html" : s.content_kind === "mcp-app" ? s.descriptor_json !== null && o.content.kind === "mcp-app" && parseDescriptor(s.descriptor_json).serverName === o.content.descriptor.serverName : s.descriptor_json !== null && o.content.kind === "plugin" && parsePluginContent(s.descriptor_json).pluginKind === o.content.pluginKind : true;
const l = createBoardWidgetPutSnapshot(a.snapshot, o, {
grantScopeMatches: c,
grantedSha256: s?.granted_sha ?? void 0,
instanceId: r
});
const u = l.widgets.find((e) => e.name === o.name);
const d = Date.now();
upsertTabs(e, a, l);
const f = getNodeSqliteKysely(e.db);
const p = createBoardWidgetContentFields(o, {
presentation: u.presentation,
heightMode: u.heightMode
}, u.revision, u.grantState, u.instanceId, d);
executeSqliteQuerySync(e.db, f.insertInto("board_widgets").values({
session_key: t,
name: o.name,
tab_id: u.tabId,
title: u.title ?? null,
size_w: u.sizeW,
size_h: u.sizeH,
position: u.position,
created_by: s?.created_by ?? "agent",
created_at: s?.created_at ?? d,
...p
}).onConflict((e) => e.columns(["session_key", "name"]).doUpdateSet({
tab_id: u.tabId,
title: u.title ?? null,
size_w: u.sizeW,
size_h: u.sizeH,
position: u.position,
...p
})));
updateWidgetLayouts(e, a, l, d, o.name);
return createBoardWidgetPutResult(l, o.name);
}
function grantBoardWidgetInDatabase(e, t, n, r, i, a, o) {
const s = readRequiredBoard(e, t, o);
const c = createBoardGrantSnapshot(s.snapshot, n, r, i, a);
upsertTabs(e, s, c);
const l = c.widgets.find((e) => e.name === n);
if (!l.contentOwner || l.contentOwner === "registered") throw new BoardValidationError("invalid_operation", `board widget ${n} content ownership is unavailable`);
const u = s.widgetRows.find((e) => e.name === n);
const d = parseManifest(u.manifest);
const f = d.declared;
const p = getNodeSqliteKysely(e.db);
executeSqliteQuerySync(e.db, p.updateTable("board_widgets").set({
grant_state: r,
granted_sha: r === "granted" ? u.sha256 : null,
manifest: serializeManifest({ contentOwner: l.contentOwner }, f, r, d.mcpAppInteractive !== void 0 && d.mcpAppInstanceId ? {
kind: "mcp-app",
interactive: d.mcpAppInteractive,
instanceId: d.mcpAppInstanceId
} : void 0, {
presentation: d.presentation,
heightMode: d.heightMode
}, d.nameIdentity),
updated_at: Date.now()
}).where("session_key", "=", t).where("name", "=", n));
return c;
}
//#endregion
//#region src/boards/sqlite-board-store.worker.ts
function bindSqliteWorkerBackend(e, t) {
const n = {
db: t.database,
path: t.databasePath
};
const r = e && getOpenClawAgentDatabaseIfOpen({
agentId: e.agentId,
path: t.databasePath,
env: getSqliteWorkerStateContext().environment
});
if (e && (!r || r.db !== t.database)) throw new Error("Board publication lost its canonical database owner");
ensureBoardSchema(n);
return bindSqliteWorkerDatabase(n.db, { execute(r) {
if (e && r.input.sessionKey !== e.sessionKey) throw new BoardValidationError("invalid_operation", "board session changed; retry");
const { result: i, changes: a } = captureSessionRowChanges(n.db, () => withSqlitePostCommitPublications(n.db, () => runSqliteWorkerTransactionSync(t, () => {
if (r.type === "boards.applyOps") return applyBoardOpsToDatabase(n, r.input.sessionKey, r.input.ops, e?.expectedSession);
if (r.type === "boards.putWidget") return putBoardWidgetInDatabase(n, r.input.sessionKey, normalizeBoardWidgetPutParams(r.input.params, r.input.sessionKey), r.input.viewGeneration, e?.expectedSession);
return grantBoardWidgetInDatabase(n, r.input.sessionKey, r.input.name, r.input.decision, r.input.revision, r.input.instanceId, e?.expectedSession);
}, {
databaseLabel: n.path,
operationLabel: r.type
})));
return {
value: i,
changes: a.filter((e) => "sessionKey" in e && e.sessionKey === r.input.sessionKey && e.storePath === n.path)
};
} });
}
//#endregion
export { bindSqliteWorkerBackend };