openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
945 lines (944 loc) • 32 kB
JavaScript
import { n as isPostgresSqlConnection } from "./sql-connection-Beiyg5Dt.mjs";
import { D as readSqliteDatabaseScopedWriteToken, G as withSqliteDatabaseWriteScope, T as readSqliteDatabasePendingScopedWriteToken, j as readSqliteDatabaseWriteRevision, st as supportsNodeSqliteExtensionLoading } from "./sqlite-database-admission-DQIqro3d.mjs";
import { i as executeSqliteQuerySync, s as getNodeSqliteKysely } from "./kysely-sync-YJo2lmGV.mjs";
import { o as getAdmittedSqliteSchemaFacts, t as admitSqliteSchema } from "./sqlite-schema-facts-B1bVE8IB.mjs";
import { a as tableExists } from "./openclaw-state-db-schema-helpers-nImZNMq_.mjs";
import { n as openNodeSqliteDatabase, r as resolveExistingSqliteFileUri } from "./node-sqlite-CU4puofF.mjs";
import { a as runSqliteImmediateTransactionSync, c as runSqliteSingleStatementSync } from "./sqlite-transaction-BHHu6P5-.mjs";
import { f as requestSqliteWorkerOperationAdmission } from "./sqlite-worker-operation-admission-9E_X-oRy.mjs";
import { a as admitStoreSearch } from "./adapters-D8O-uubH.mjs";
import { i as MEMORY_INDEX_PATHS_FTS_TABLE, r as MEMORY_INDEX_FTS_TABLE } from "./sqlite-search-schema-CLxKWxgk.mjs";
import { a as readOpenClawAgentDatabaseIdentity } from "./openclaw-agent-db-identity-C8MGU8lp.mjs";
import { a as stageMemoryIndexSchemaExtension, c as memoryVectorSearchSchema, g as MEMORY_INDEX_VECTOR_TABLE, h as MEMORY_INDEX_STATE_TABLE, i as readRepairedMemoryIndexSchema, p as MEMORY_INDEX_DERIVED_TABLES, r as publishRepairedMemoryIndexSchema, s as memoryTextSearchSchema, t as ensureMemoryIndexSchema } from "./memory-schema-B3FrMV9P.mjs";
import { n as loadSqliteVecExtensionFromPath, t as loadSqliteVecExtension } from "./sqlite-vec-2t4h9sP9.mjs";
import { t as bindSqliteWorkerDatabase } from "./sqlite-worker-binding-B4BB5u5i.mjs";
import { i as stopMemorySqliteWalMaintenance, n as configureMemorySqliteWalMaintenance, t as closeMemorySqliteWalMaintenance } from "./engine-storage-DobYcIKx.mjs";
import "./memory-core-host-engine-storage-DcaZNQQh.mjs";
import { t as stageOpenClawAgentDatabaseSchemaExtension } from "./sqlite-worker-runtime-CKocuU_N.mjs";
import { t as advanceMemoryIndexRevision } from "./memory-index-revision.worker-CQcqIl0f.mjs";
import { n as hasMemorySessionTombstone } from "./memory-session-tombstones-D5Byk7o_.mjs";
import { a as MEMORY_INDEX_META_KEY, b as upsertMemoryEmbeddingCache, d as refreshMemorySessionSourceState, h as countMemoryEmbeddingCache, o as readMemoryDatabaseFacts, p as clearMemoryEmbeddingCacheIdentities, t as MemorySourceIndexKernel, v as pruneMemoryEmbeddingCache, y as rekeyMemoryEmbeddingCache } from "./manager-source-index-kernel-BYD04WLI.mjs";
import "./memory-core-host-engine-schema-CXsNrexG.mjs";
import { n as markMemoryVectorIndexClean } from "./manager-vector-rebuild-state-BC2SVgRb.mjs";
import { t as readMemoryIndex } from "./manager-search-schema-D0PLUf4h.mjs";
import { t as admitMemoryVectorIndex } from "./manager-search-knn-Bc-4goWR.mjs";
import "./database-engine-worker-runtime-DzyfC3BE.mjs";
import "./sqlite-runtime-lcoEVOL7.mjs";
import { n as publishMemoryDatabaseTables, t as MemoryIndexRevisionConflictError } from "./manager-db-kernel-Dhsxnwme.mjs";
import { n as MEMORY_INDEX_WRITE_SCOPE, t as MEMORY_EMBEDDING_CACHE_WRITE_SCOPE } from "./manager-publication-task-B1g1hKrX.mjs";
import { n as readMemoryConnectionPragmas, r as readMemoryShadowIdentity, t as assertMemoryShadowIdentity } from "./manager-shadow-task-D4s6gAdr.mjs";
import { randomUUID } from "node:crypto";
//#region extensions/memory-core/src/memory/manager-index-metadata.ts
function writeMemoryIndexMetadata(e, t) {
const n = JSON.stringify(t);
executeSqliteQuerySync(e, getNodeSqliteKysely(e).insertInto("memory_index_meta").values({
key: MEMORY_INDEX_META_KEY,
value: n
}).onConflict((e) => e.column("key").doUpdateSet({ value: n })));
}
/** The publication owner holds one transaction for metadata and its cache namespace. */
function upgradeMemoryIndexProviderKey(e, { meta: t, providerKey: n }) {
if (!t.providerKey || t.providerKey === n) return false;
const r = executeSqliteQuerySync(e, getNodeSqliteKysely(e).updateTable("memory_index_meta").set({ value: JSON.stringify({
...t,
providerKey: n
}) }).where("key", "=", MEMORY_INDEX_META_KEY).where("value", "=", JSON.stringify(t)));
if (!Number(r.numAffectedRows)) return false;
if (tableExists(e, "memory_embedding_cache")) rekeyMemoryEmbeddingCache(e, {
provider: t.provider,
model: t.model,
providerKey: t.providerKey
}, n);
return true;
}
//#endregion
//#region extensions/memory-core/src/memory/manager-publication-postgres.ts
const reindexStages = /* @__PURE__ */ new WeakMap();
const embeddingCacheSizes$1 = /* @__PURE__ */ new WeakMap();
/** A connection-local spool bounds transfer memory and disappears with its owning worker. */
function bindPostgresMemoryPublication(e, t) {
const n = e.database;
if (!isPostgresSqlConnection(n) || !e.admitSearchExtensions) throw new Error("PostgreSQL memory publication requires agent-owned search admission");
const r = e.admitSearchExtensions;
let i = `memory_stage_${randomUUID().replaceAll("-", "")}`;
let a = false;
let o;
let s;
let c;
let l;
let u = t;
let d = reindexStages.get(n);
if (!d) {
d = /* @__PURE__ */ new Map();
reindexStages.set(n, d);
}
let f = t !== void 0 && d.has(t);
const restore = (e) => {
({spool: i, created: a, header: o, stageKind: s, rebuilding: c, metadata: l} = e);
};
if (t && d.has(t)) restore(d.get(t));
let p;
const readCacheSize = () => p ??= {
size: countMemoryEmbeddingCache(n),
exact: true
};
const retainCacheSize = (e, t) => {
if (e === void 0 || t === void 0) {
embeddingCacheSizes$1.delete(n);
return;
}
const r = readSqliteDatabaseScopedWriteToken(n, MEMORY_EMBEDDING_CACHE_WRITE_SCOPE);
if (r === void 0 || readSqliteDatabaseWriteRevision(n) !== t) embeddingCacheSizes$1.delete(n);
else embeddingCacheSizes$1.set(n, {
...e,
token: r
});
};
const write = (t, r) => {
let i = false;
let o = false;
const s = c && { ...c };
const u = l;
const d = a;
let f;
let m;
try {
const a = n.runTransaction(() => {
e.admit("transaction");
i = true;
m = readSqliteDatabaseWriteRevision(n);
const r = embeddingCacheSizes$1.get(n);
const a = readSqliteDatabaseScopedWriteToken(n, MEMORY_EMBEDDING_CACHE_WRITE_SCOPE);
p = r?.token === a ? r : void 0;
f = p;
return t();
}, { withCommit: (t) => {
e.admit("commit");
t();
o = true;
} });
if (r?.publishFacts) return {
ok: true,
value: a,
facts: c ?? readMemoryDatabaseFacts(n)
};
return {
ok: true,
value: a
};
} catch (e) {
if (!o) {
c = s;
l = u;
a = d;
p = f;
}
return {
ok: false,
entered: i,
committed: o,
error: {
name: e instanceof Error ? e.name : "Error",
message: e instanceof Error ? e.message : String(e)
}
};
} finally {
retainCacheSize(p, m === void 0 ? void 0 : m + Number(o) | 0);
}
};
const writeChangedIndex = (e) => write(() => {
const t = e();
if (t) advanceMemoryIndexRevision(n);
return t;
}, { publishFacts: true });
const ensureSpool = () => {
if (a) return;
n.exec(`CREATE TEMP TABLE ${i} (ordinal BIGINT GENERATED ALWAYS AS IDENTITY, lane TEXT NOT NULL, header TEXT, json TEXT, last INTEGER, PRIMARY KEY (lane, ordinal))`);
a = true;
};
const dropSpool = (e) => {
const t = readSqliteDatabaseWriteRevision(n);
const r = embeddingCacheSizes$1.get(n);
const i = readSqliteDatabaseScopedWriteToken(n, MEMORY_EMBEDDING_CACHE_WRITE_SCOPE);
const a = Number(!n.isTransaction);
n.exec(`DROP TABLE ${e}`);
retainCacheSize(r?.token === i ? r : void 0, t === void 0 ? void 0 : t + a | 0);
};
const append = (e, t, r) => {
ensureSpool();
if (r) n.prepare(`INSERT INTO ${i} (lane, header) VALUES (?, ?)`).run(e, JSON.stringify(r));
const a = Math.floor(21845);
for (let r = 0; r < t.length; r += a) {
const o = t.slice(r, r + a);
n.prepare(`INSERT INTO ${i} (lane, json, last) VALUES ${o.map(() => "(?, ?, ?)").join(", ")}`).run(...o.flatMap((t) => [
e,
t.json,
Number(t.last)
]));
}
};
function* records(e) {
let t = 0;
for (;;) {
const r = n.prepare(`SELECT ordinal, header, json, last FROM ${i} WHERE lane = ? AND ordinal > ? ORDER BY ordinal LIMIT 32`).all(e, t);
if (!r.length) return;
for (const e of r) {
t = Number(e.ordinal);
yield {
header: e.header,
json: e.json,
last: e.last
};
}
}
}
function* decode(e) {
let t = [];
for (const n of e) {
if (typeof n.json !== "string") continue;
t.push(n.json);
if (n.last) {
yield JSON.parse(t.join(""));
t = [];
}
}
if (t.length) throw new Error("Incomplete memory publication record");
}
const checkSource = (e) => {
if (e.source === "sessions" && hasMemorySessionTombstone(n, e.agentId, e.sessionId)) throw new Error("A session was forgotten while memory indexing was running; retry the memory index.");
};
const stageSource = (e, t) => {
checkSource(e);
append("reindex", t ?? [], e);
if (!t) n.exec(`INSERT INTO ${i} (lane, json, last) SELECT 'reindex', json, last FROM ${i} WHERE lane = 'source' ORDER BY ordinal`);
const r = t ? t.some((e) => e.last) : Boolean(n.prepare(`SELECT 1 FROM ${i} WHERE lane = 'source' AND last = 1 LIMIT 1`).get());
c.hasIndexedChunks ||= r;
c.hasSemanticChunks ||= r && e.model !== "fts-only";
};
const execute = (e) => {
if (e.type === "database.reset") return writeChangedIndex(() => {
const e = getNodeSqliteKysely(n);
let t = false;
for (const r of MEMORY_INDEX_DERIVED_TABLES) {
if (r === "memory_index_state" || !tableExists(n, r)) continue;
const i = executeSqliteQuerySync(n, e.deleteFrom(r));
t ||= (i.numAffectedRows ?? 0n) > 0n;
}
p = {
size: 0,
exact: true
};
return t;
});
if (t && !d.has(t) && e.type !== "database.stage.start") throw new Error("Memory reindex connection was lost; retry the full reindex.");
if (e.type === "database.stage.discard") {
const t = d.get(e.input.stageId);
if (t?.created) dropSpool(t.spool);
d.delete(e.input.stageId);
if (u === e.input.stageId) f = false;
return;
}
if (e.type === "database.stage.publish" && e.input.stageId) {
const t = d.get(e.input.stageId);
if (!t) throw new Error("Memory reindex connection was lost; retry the full reindex.");
u = e.input.stageId;
f = true;
restore(t);
}
if (e.type === "schema.admit") {
if (e.input.ftsEnabled) r({ "memory.text": memoryTextSearchSchema(e.input.ftsTokenizer ?? "unicode61") });
const t = c ?? readMemoryDatabaseFacts(n);
return {
ok: true,
facts: t,
value: {
ftsAvailable: e.input.ftsEnabled,
admission: {
engine: "postgres",
hasIndex: true,
ftsAvailable: e.input.ftsEnabled,
identity: readOpenClawAgentDatabaseIdentity({ db: n }),
facts: t
}
}
};
}
if (e.type === "vector.ensure") {
r({ "memory.vector": memoryVectorSearchSchema(e.input.dimensions) });
if (c) c.hasVectorTable = true;
return {
ok: true,
value: void 0,
facts: c ?? readMemoryDatabaseFacts(n)
};
}
if (e.type === "vector.prepare") return {
ok: true,
value: {
extensionPath: "",
retiredLegacy: false
}
};
if (e.type === "connection.inspect") throw new Error("PostgreSQL memory has no shadow file");
if (e.type === "database.publish") throw new Error("PostgreSQL memory publication requires its connection-local stage");
if (e.type === "database.stage.start") {
f = t !== void 0;
return write(() => {
ensureSpool();
c = {
...readMemoryDatabaseFacts(n),
meta: null,
serialized: null,
hasIndexedChunks: false,
hasSemanticChunks: false,
invalidatedSources: [],
vectorState: { state: "empty" }
};
}, { publishFacts: true });
}
if (e.type === "database.stage.publish") return write(() => {
if (!c || !l) throw new Error("Memory reindex stage is incomplete");
if (readMemoryDatabaseFacts(n).revision !== e.input.expectedRevision) throw new MemoryIndexRevisionConflictError("Memory index changed while full reindex was building; retry the full reindex.");
n.exec("DELETE FROM memory_index_chunks; DELETE FROM memory_index_sources");
function* sources() {
const e = records("reindex");
let t = e.next();
while (!t.done) {
if (typeof t.value.header !== "string") throw new Error("Memory reindex source header is missing");
const n = JSON.parse(t.value.header);
checkSource(n);
t = e.next();
function* fragments() {
while (!t.done && t.value.header === null) {
yield t.value;
t = e.next();
}
}
yield {
header: n,
rows: decode(fragments())
};
}
}
new MemorySourceIndexKernel(n, {
vector: {
enabled: true,
available: true
},
fts: {
enabled: true,
available: true
}
}).replaceGroup(sources());
writeMemoryIndexMetadata(n, l);
if (e.input.vectorIndexComplete) markMemoryVectorIndexClean(n);
advanceMemoryIndexRevision(n);
c = void 0;
}, { publishFacts: true });
if (e.type === "index.facts") return c ?? readMemoryDatabaseFacts(n);
if (e.type === "source.state" || e.type === "source.chunks") return c ? [] : readMemoryIndex(n, e).value;
if (e.type === "source.hash") return c ? void 0 : readMemoryIndex(n, e).value;
if (e.type === "cache.read") return readMemoryIndex(n, e).value;
if (e.type === "stage.start" || e.type === "cache.stage.start") {
const t = write(() => {
ensureSpool();
n.prepare(`DELETE FROM ${i} WHERE lane IN ('source', 'cache')`).run();
o = e.input.header;
s = e.type === "stage.start" ? "source" : "cache";
});
if (!t.ok) throw new Error(t.error.message);
return;
}
if (e.type === "stage.append") {
if (!s) throw new Error("Memory staging was not started");
const t = write(() => append(s, e.input.fragments));
if (!t.ok) throw new Error(t.error.message);
return;
}
if (e.type === "stage.discard") {
o = void 0;
s = void 0;
return;
}
if (e.type === "index.upgradeProviderKey") return c ? {
ok: true,
value: false
} : write(() => {
const t = upgradeMemoryIndexProviderKey(n, e.input);
if (t) p = void 0;
return t;
}, { publishFacts: true });
if (e.type === "index.writeMetadata") return write(() => {
if (c) {
l = e.input;
c.meta = l;
c.serialized = JSON.stringify(l);
} else writeMemoryIndexMetadata(n, e.input);
}, { publishFacts: true });
if (e.type === "source.refresh" || e.type === "source.delete") return c ? {
ok: true,
value: false
} : writeChangedIndex(() => e.type === "source.refresh" ? refreshMemorySessionSourceState(n, e.input) : new MemorySourceIndexKernel(n, e.input.state).deleteIfCurrent(e.input));
if (e.type === "cache.clear") return write(() => {
const t = clearMemoryEmbeddingCacheIdentities(n, e.input.identities);
if (p !== void 0) p = {
...p,
size: p.size - t
};
return true;
});
if (e.type === "cache.prune") return write(() => {
const t = readCacheSize();
if (t.size <= e.input.maxEntries) {
if (e.input.recount) {
p = {
size: countMemoryEmbeddingCache(n),
exact: true
};
return p.size > e.input.maxEntries;
}
return false;
}
p = pruneMemoryEmbeddingCache(n, t, e.input.maxEntries, e.input.unreferencedFirst);
return true;
});
if (e.type === "cache.write" || e.type === "cache.write.inline") return write(() => {
const t = e.type === "cache.write.inline" ? e.input.header : o;
if (!t) throw new Error("Memory cache staging was not started");
const readEntries = () => e.type === "cache.write.inline" ? e.input.entries : decode(records("cache"));
function* entries() {
for (const e of readEntries()) if (!e.sessionId || !hasMemorySessionTombstone(n, t.agentId, e.sessionId)) yield e;
}
const r = typeof t.maxEntries === "number" && Number.isFinite(t.maxEntries) && t.maxEntries > 0;
const i = upsertMemoryEmbeddingCache({
...t,
db: n,
cacheSize: r ? readCacheSize() : {
size: 0,
exact: false
},
entries
});
p = r ? i : void 0;
return true;
});
return write(() => {
const t = e.type === "source.replace.group" ? e.input.sources : e.type === "source.replace.inline" ? [e.input] : [{
header: o,
fragments: void 0
}];
function* replacements() {
for (const e of t) {
if (!e.header) throw new Error("Memory source staging was not started");
if (c) stageSource(e.header, e.fragments);
else {
checkSource(e.header);
yield {
header: e.header,
rows: decode(e.fragments ?? records("source"))
};
}
}
}
new MemorySourceIndexKernel(n, e.input.state).replaceGroup(replacements());
if (!c) advanceMemoryIndexRevision(n);
return true;
}, { publishFacts: true });
};
return bindSqliteWorkerDatabase(n, {
execute(e) {
try {
return execute(e);
} finally {
if (f && u) d.set(u, {
spool: i,
created: a,
header: o,
stageKind: s,
rebuilding: c,
metadata: l
});
}
},
close() {
if (!u && a && n.isOpen) dropSpool(i);
}
});
}
//#endregion
//#region extensions/memory-core/src/memory/manager-publication-rows.ts
function* readPublicationRows(e) {
const parse = (e) => JSON.parse(e.join(""));
let t = [];
for (const n of e) {
t.push(n.json);
if (n.last) {
yield parse(t);
t = [];
}
}
if (t.length) yield parse(t);
}
function stagePublicationRows(e, t) {
const n = [...e.tail, ...t];
const r = n.findLastIndex((e) => e.last) + 1;
for (const t of readPublicationRows(n.slice(0, r))) e.rows.push("embedding" in t && t.embedding.length > 0 && t.embedding.every((e) => typeof e === "number") ? {
row: {
...t,
embedding: []
},
vector: Float64Array.from(t.embedding)
} : { row: t });
e.tail = n.slice(r);
}
function* readStagedRows(e) {
for (const { row: t, vector: n } of e.rows) yield n ? {
...t,
embedding: Array.from(n)
} : t;
yield* readPublicationRows(e.tail);
}
//#endregion
//#region extensions/memory-core/src/memory/manager-publication.worker.ts
const agentConnectionPragmas = /* @__PURE__ */ new WeakMap();
const loadedExtensions = /* @__PURE__ */ new WeakMap();
const embeddingCacheSizes = /* @__PURE__ */ new WeakMap();
function failure(e) {
return {
name: e instanceof Error ? e.name : "Error",
message: e instanceof Error ? e.message : String(e),
...e && typeof e === "object" && "code" in e && typeof e.code === "string" ? { code: e.code } : {},
...e && typeof e === "object" && "errcode" in e && typeof e.errcode === "number" ? { errcode: e.errcode } : {}
};
}
function createSqliteWorkerBackend(e, t) {
return openShadowBackend(t.databasePath, e.allowExtension);
}
function openExistingSqliteWorkerBackend(e, t) {
return openShadowBackend(t.databasePath, true, e);
}
async function openShadowBackend(e, t, n) {
const r = openNodeSqliteDatabase(n ? resolveExistingSqliteFileUri(e) : e, { allowExtension: t && !process.permission && supportsNodeSqliteExtensionLoading() });
const close = async () => {
await stopMemorySqliteWalMaintenance(r);
try {
closeMemorySqliteWalMaintenance(r);
} finally {
if (r.isOpen) r.close();
}
};
try {
configureMemorySqliteWalMaintenance(r, {
busyTimeoutMs: 5e3,
databasePath: e
});
return {
...createPublicationBackend(n ?? {
fileIdentity: readMemoryShadowIdentity(e),
pragmas: readMemoryConnectionPragmas(r, "Invalid memory publication connection policy")
}, e, r, (e) => requestSqliteWorkerOperationAdmission({
stage: e,
facts: void 0
})),
close
};
} catch (e) {
await close();
throw e;
}
}
/** Agent publication borrows its executor connection; only private shadows open their own. */
function bindSqliteWorkerBackend(e, t) {
if (isPostgresSqlConnection(t.database)) return bindPostgresMemoryPublication(t, "kind" in e ? e.stageId : void 0);
const n = t.database;
let r = agentConnectionPragmas.get(n);
if ("kind" in e && !r) {
r = readMemoryConnectionPragmas(n, "Invalid memory publication connection policy");
agentConnectionPragmas.set(n, r);
}
return createPublicationBackend("kind" in e ? {
kind: "agent",
pragmas: r
} : e, t.databasePath, n, (e) => t.admit(e));
}
function createPublicationBackend(e, t, n, r) {
const i = admitMemoryVectorIndex(n);
function assertSourceCurrent(e) {
if (e.source === "sessions" && hasMemorySessionTombstone(n, e.agentId, e.sessionId)) throw new Error("A session was forgotten while memory indexing was running; retry the memory index.");
}
if (!("kind" in e)) assertMemoryShadowIdentity(t, e.fileIdentity);
let a;
const loadExtension = (e) => {
if (e && e !== loadedExtensions.get(n)) {
loadSqliteVecExtensionFromPath(n, e);
loadedExtensions.set(n, e);
}
};
const discard = () => {
a = void 0;
};
const finish = (e) => {
if (e.ok) discard();
return e;
};
const transact = (e) => {
let t = false;
let i = false;
let a;
try {
return {
ok: true,
value: e({
onBegin: () => {
t = true;
r("transaction");
},
withCommit: (e) => {
r("commit");
a = readSqliteDatabasePendingScopedWriteToken(n, MEMORY_INDEX_WRITE_SCOPE);
e();
i = true;
}
}),
writeToken: a
};
} catch (e) {
return {
ok: false,
error: failure(e),
entered: t,
committed: i
};
}
};
const write = (e, t = [MEMORY_INDEX_WRITE_SCOPE]) => transact((r) => runSqliteImmediateTransactionSync(n, () => {
r.onBegin();
return withSqliteDatabaseWriteScope(n, t, e);
}, { withCommit: r.withCommit }));
const writeSingleStatement = (e) => {
let t = false;
try {
r("transaction");
r("commit");
const i = withSqliteDatabaseWriteScope(n, [MEMORY_INDEX_WRITE_SCOPE], () => runSqliteSingleStatementSync(n, e));
t = true;
return {
ok: true,
value: i,
writeToken: readSqliteDatabaseScopedWriteToken(n, MEMORY_INDEX_WRITE_SCOPE)
};
} catch (e) {
return {
ok: false,
error: failure(e),
entered: true,
committed: t
};
}
};
const withFacts = (e, t = false) => {
if (!e.ok) return e;
const r = readMemoryDatabaseFacts(n);
const i = t && getAdmittedSqliteSchemaFacts(n).tableSql;
return {
...e,
facts: r,
...i ? { searchSchema: {
fts: i.get("memory_index_chunks_fts") ?? null,
paths: i.get("memory_index_paths_fts") ?? null,
vector: i.get("memory_index_chunks_vec") ?? null
} } : {}
};
};
const cacheSize = (e, t = readSqliteDatabaseScopedWriteToken(n, MEMORY_EMBEDDING_CACHE_WRITE_SCOPE)) => {
let r = embeddingCacheSizes.get(n);
if (!r || r.token !== t || e !== void 0 && r.size <= e) {
r = {
size: countMemoryEmbeddingCache(n),
exact: true,
token: t
};
embeddingCacheSizes.set(n, r);
}
return r;
};
const writeCache = (e, t) => {
const r = readSqliteDatabaseScopedWriteToken(n, MEMORY_EMBEDDING_CACHE_WRITE_SCOPE);
const i = write(() => e(cacheSize(t, r)), [MEMORY_EMBEDDING_CACHE_WRITE_SCOPE]);
if (!i.ok) return i;
embeddingCacheSizes.set(n, {
...i.value,
token: readSqliteDatabaseScopedWriteToken(n, MEMORY_EMBEDDING_CACHE_WRITE_SCOPE)
});
return {
...i,
value: true
};
};
return bindSqliteWorkerDatabase(n, {
async prepare(e) {
if (e.type !== "vector.prepare") return;
const t = e.input.state.extensionPath;
const r = loadedExtensions.get(n);
if (r && (!t || t === r)) return;
const i = await loadSqliteVecExtension({
db: n,
extensionPath: t
});
if (!i.ok || !i.extensionPath) throw new Error(i.error ?? "unknown sqlite-vec load error");
loadedExtensions.set(n, i.extensionPath);
},
execute(o) {
if (o.type === "database.reset") throw new Error("Worker memory reset requires PostgreSQL");
if (o.type === "database.stage.start" || o.type === "database.stage.publish" || o.type === "database.stage.discard") throw new Error("Connection-local memory staging requires PostgreSQL");
if (o.type === "connection.inspect") return "kind" in e ? {
fileIdentity: readMemoryShadowIdentity(t),
pragmas: readMemoryConnectionPragmas(n, "Invalid memory publication connection policy")
} : e;
if (o.type === "index.facts" || o.type === "source.state" || o.type === "source.hash" || o.type === "source.chunks" || o.type === "cache.read") return readMemoryIndex(n, o).value;
if (o.type === "schema.admit") {
r("transaction");
const t = {
...o.input,
db: n
};
const i = readSqliteDatabaseScopedWriteToken(n, MEMORY_INDEX_WRITE_SCOPE);
const a = readRepairedMemoryIndexSchema(t, i);
if (!a) n.exec("PRAGMA foreign_keys = OFF");
try {
const r = a ? {
ok: true,
value: a,
writeToken: i
} : write(() => {
stageOpenClawAgentDatabaseSchemaExtension(n);
return ensureMemoryIndexSchema(t);
});
if (r.ok && !a) {
admitSqliteSchema(n);
if (!t.ftsEnabled || r.value.ftsAvailable) publishRepairedMemoryIndexSchema(t, r.writeToken);
}
const o = withFacts(r, true);
return o.ok && "kind" in e ? {
...o,
value: {
...o.value,
admission: {
hasIndex: true,
ftsAvailable: o.value.ftsAvailable,
identity: readOpenClawAgentDatabaseIdentity({ db: n }),
facts: o.facts
}
}
} : o;
} finally {
if (!a && n.isOpen) n.exec(`PRAGMA foreign_keys = ${e.pragmas.foreign_keys}`);
}
}
if (o.type === "index.upgradeProviderKey") return withFacts(write(() => upgradeMemoryIndexProviderKey(n, o.input), [MEMORY_INDEX_WRITE_SCOPE, MEMORY_EMBEDDING_CACHE_WRITE_SCOPE]));
if (o.type === "index.writeMetadata") return withFacts(writeSingleStatement(() => writeMemoryIndexMetadata(n, o.input)));
if (o.type === "source.refresh") return withFacts(write(() => {
const e = refreshMemorySessionSourceState(n, o.input);
if (e) advanceMemoryIndexRevision(n);
return e;
}));
if (o.type === "stage.start" || o.type === "cache.stage.start") {
a = o.type === "stage.start" ? {
...o.input,
kind: "source",
rows: [],
tail: []
} : {
...o.input,
kind: "cache",
rows: [],
tail: []
};
return;
}
if (o.type === "stage.discard") {
discard();
return;
}
if (o.type === "stage.append") {
if (!a) throw new Error("Memory publication input was not started");
stagePublicationRows(a, o.input.fragments);
return;
}
if (o.type === "cache.prune") {
const { maxEntries: e, recount: t, unreferencedFirst: r } = o.input;
if (!t && cacheSize().size <= e) return {
ok: true,
value: false
};
let i = false;
const a = writeCache((t) => {
i = t.size > e;
return pruneMemoryEmbeddingCache(n, t, e, r);
}, t ? e : void 0);
return a.ok ? {
...a,
value: i
} : a;
}
if (o.type === "cache.clear") return writeCache((e) => ({
...e,
size: e.size - clearMemoryEmbeddingCacheIdentities(n, o.input.identities)
}));
if (o.type === "cache.write" || o.type === "cache.write.inline") {
let e;
let readEntries;
if (o.type === "cache.write.inline") {
e = o.input.header;
const t = o.input.entries;
readEntries = () => t;
} else {
if (a?.kind !== "cache") throw new Error("Memory cache input was not started");
e = a.header;
const t = a;
readEntries = () => readStagedRows(t);
}
const t = writeCache((t) => {
const r = /* @__PURE__ */ new Map();
function* entries() {
for (const t of readEntries()) {
if (t.sessionId) {
let i = r.get(t.sessionId);
if (i === void 0) {
i = !hasMemorySessionTombstone(n, e.agentId, t.sessionId);
r.set(t.sessionId, i);
}
if (!i) continue;
}
yield t;
}
}
return upsertMemoryEmbeddingCache({
...e,
db: n,
cacheSize: t,
entries
});
});
return o.type === "cache.write" ? finish(t) : t;
}
if (o.type === "vector.prepare") {
const e = loadedExtensions.get(n);
if (!e) throw new Error("Memory vector extension was not prepared");
if (!tableExists(n, "chunks_vec")) return {
ok: true,
value: {
extensionPath: e,
retiredLegacy: false
}
};
return withFacts(write(() => {
stageMemoryIndexSchemaExtension(n);
stageOpenClawAgentDatabaseSchemaExtension(n);
n.exec("DROP TABLE IF EXISTS chunks_vec");
return {
extensionPath: e,
retiredLegacy: true
};
}));
}
if (o.type === "vector.ensure") {
const { dimensions: e } = o.input;
if (!Number.isSafeInteger(e) || e <= 0) throw new Error("Memory vector dimensions must be a positive integer");
const { meta: t, hasIndexedChunks: r, hasVectorTable: a } = readMemoryDatabaseFacts(n);
if ((t ? t.vectorDims : o.input.currentDimensions) === e && a) {
loadExtension(o.input.state.extensionPath);
admitStoreSearch(n, memoryVectorSearchSchema(e), { extension: "memory.vector" });
return {
ok: true,
value: void 0
};
}
loadExtension(o.input.state.extensionPath);
return withFacts(write(() => {
stageMemoryIndexSchemaExtension(n);
stageOpenClawAgentDatabaseSchemaExtension(n);
if (a) i.capability.drop(i.index);
i.capability.create(i.index, e);
admitStoreSearch(n, memoryVectorSearchSchema(e), { extension: "memory.vector" });
if (t && !t.vectorDims && !r) writeMemoryIndexMetadata(n, {
...t,
vectorDims: e
});
}), true);
}
loadExtension(o.input.state.extensionPath);
if (o.type === "database.publish") {
const e = o.input;
return withFacts(transact((t) => {
assertMemoryShadowIdentity(e.sourcePath, e.sourceIdentity);
publishMemoryDatabaseTables({
...e,
targetDb: n,
onBegin: () => {
t.onBegin();
stageOpenClawAgentDatabaseSchemaExtension(n);
assertMemoryShadowIdentity(e.sourcePath, e.sourceIdentity);
},
withCommit: t.withCommit
});
}));
}
if (o.type === "source.delete") return withFacts(write(() => {
const e = new MemorySourceIndexKernel(n, o.input.state).deleteIfCurrent(o.input);
if (e) advanceMemoryIndexRevision(n);
return e;
}));
if (o.type === "source.replace.group") {
const e = write(() => {
const e = new MemorySourceIndexKernel(n, o.input.state);
const t = o.input.sources;
function* sources() {
for (const { header: e, fragments: n } of t) {
assertSourceCurrent(e);
yield {
header: e,
rows: readPublicationRows(n)
};
}
}
e.replaceGroup(sources());
advanceMemoryIndexRevision(n);
return true;
});
return e.ok ? {
...e,
facts: readMemoryDatabaseFacts(n, o.input.state.hasVectorTable)
} : e;
}
let s;
let c;
if (o.type === "source.replace.inline") {
s = o.input.header;
c = readPublicationRows(o.input.fragments);
} else {
if (a?.kind !== "source") throw new Error("Memory publication input was not started");
s = a.header;
c = readStagedRows(a);
}
let l;
const u = write(() => {
assertSourceCurrent(s);
new MemorySourceIndexKernel(n, o.input.state).replaceRows(s, c);
advanceMemoryIndexRevision(n);
l = readMemoryDatabaseFacts(n, o.input.state.hasVectorTable);
return true;
});
const d = u.ok ? {
...u,
facts: l
} : u;
return o.type === "source.replace.inline" ? d : finish(d);
},
close() {
discard();
}
});
}
//#endregion
export { createSqliteWorkerBackend as n, openExistingSqliteWorkerBackend as r, bindSqliteWorkerBackend as t };