openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
852 lines (851 loc) • 34.9 kB
JavaScript
import { i as recordWorkerMessage } from "./worker-message-metrics-d3pS8muz.mjs";
import { t as assertEngineStoreExecutionAllowed } from "./admission-scope-DmxaPNhm.mjs";
import { r as truncateUtf16Safe } from "./utf16-slice-CuDyEXgS.mjs";
import { s as redactSensitiveText } from "./redact-Mj7pppxC.mjs";
import { n as isPostgresSqlConnection, r as sqlPublicationAnchor, t as assertSyncTransactionResult } from "./sql-connection-Beiyg5Dt.mjs";
import { f as invalidateLocalSqliteSchemaAdmissions, i as finishSqliteDatabaseWrite, t as beginSqliteDatabaseWrite, x as publishSqliteDatabaseSchemaChange } from "./sqlite-database-admission-DQIqro3d.mjs";
import { C as preparePostgresQuery, S as isPostgresConnectionError, b as decodePostgresError, w as validatePostgresBindings, x as decodePostgresRows } from "./sqlite-error-diagnostics-6_hREUnq.mjs";
import { r as hasSqliteWorkerOutcomeUnknown, t as SqliteWorkerError } from "./sqlite-worker-error-DEIJgRIz.mjs";
import { c as withSqlitePostCommitPublications, i as prepareSqliteTransactionCommit, n as discardSqliteTransactionState, s as stageSqliteTransactionState } from "./sqlite-post-commit-BrUVQObC.mjs";
import { _ as sql, i as executeSqliteQuerySync, s as getNodeSqliteKysely, y as createFunctionModule } from "./kysely-sync-YJo2lmGV.mjs";
import { B as pgSearchName, E as publishPostgresSearchExtensionFacts, F as verifyAndRecordPostgresSchema, I as verifyPostgresSchema, J as searchConfig, K as publishPostgresSearch, L as withPostgresSearchExtensions, N as readPostgresSchema, P as retainPostgresSchema, R as admitPostgresSearch, U as postgresSearchTokenSeparators, V as postgresSearchSql, j as postgresSchemaSql, k as getAdmittedPostgresSchema, q as rebuildPostgresSearch, r as beginPostgresReadSnapshotScope, w as getPostgresPhysicalFacts, z as assertPostgresSearchAdmitted } from "./sqlite-schema-facts-B1bVE8IB.mjs";
import { o as runSqliteReadSnapshotSync, r as runSqliteDeferredTransactionSync } from "./sqlite-transaction-BHHu6P5-.mjs";
import { i as recordPostgresPoolFailure } from "./pool-state-CmEL_mgq.mjs";
import "./sqlite-worker-contract--dxXkOty.mjs";
import { r as currentSqliteWorkerOperationAdmission } from "./sqlite-worker-operation-settlement-OZQM-wtd.mjs";
import { a as retainIdlePostgresBridge, c as POSTGRES_STATEMENT_TIMEOUT_MS, i as takePreparedPostgresBridge, n as postgresBridgeReuseKey, o as takeIdlePostgresBridge, s as POSTGRES_LOCK_TIMEOUT_MS, t as createPostgresBridge } from "./bridge-prestart-C7GHqvs8.mjs";
import { i as matchesVectorRow, r as admitSqliteMemoryVectorSearch, t as bindSqliteVectorCapability } from "./sqlite-vector-D8zMkMR6.mjs";
import { s as admitSqliteMemoryTextSearch } from "./sqlite-search-schema-CLxKWxgk.mjs";
import { createHash } from "node:crypto";
import { receiveMessageOnPort, threadId } from "node:worker_threads";
import { channel } from "node:diagnostics_channel";
//#region src/infra/database-engine/observation.ts
const channels = {
statement: channel("openclaw.database.statement"),
request: channel("openclaw.database.request")
};
const observedConnections = /* @__PURE__ */ new WeakSet();
function normalizeSql(e, t) {
let n = "";
for (let r = 0; r < t.length;) {
const i = t.slice(r);
if (i.startsWith("/*")) {
let e = 1;
r += 2;
while (r < t.length && e) if (t.startsWith("/*", r)) {
e++;
r += 2;
} else if (t.startsWith("*/", r)) {
e--;
r += 2;
} else r++;
n += " ";
continue;
}
const a = /^--[^\r\n]*/.exec(i)?.[0];
const o = (e === "postgres" ? /^[eE]'(?:\\[\s\S]|''|[^'\\])*(?:'|$)/.exec(i)?.[0] : void 0) ?? /^(?:[uU]&)?'(?:''|[^'])*(?:'|$)/.exec(i)?.[0];
const s = /^\$(?:[A-Za-z_][\w]*)?\$/.exec(i)?.[0];
const c = /^(?:"(?:""|[^"])*"|`(?:``|[^`])*`|\[[^\]]*\])/.exec(i)?.[0];
const l = !/[\w$]/.test(t[r - 1] ?? "") ? /^(?:0x[\da-f]+|\d+(?:\.\d*)?(?:e[+-]?\d+)?)(?!\w)/i.exec(i)?.[0] : void 0;
if (s) {
const e = t.indexOf(s, r + s.length);
r = e < 0 ? t.length : e + s.length;
n += "?";
} else if (a || o || c || l) {
const e = a ?? o ?? c ?? l ?? "";
r += e.length;
n += a ? " " : c ? e : "?";
} else n += t[r++];
}
return n.replace(/\s+/g, " ").trim();
}
function observeDatabaseOperation(e, t, n, r) {
const i = channels[t];
if (!i.hasSubscribers) return r();
const a = performance.now();
let o = "error";
try {
const e = r();
o = "ok";
return e;
} finally {
const t = performance.now() - a;
i.publish({
engine: e,
sql: n === void 0 ? void 0 : normalizeSql(e, n),
threadId,
outcome: o,
durationMs: t
});
}
}
function observeDatabaseRequest(e, t) {
const n = channels.request;
if (!n.hasSubscribers) return t();
return (async () => {
const r = performance.now();
let i = "error";
try {
const e = await t();
i = "ok";
return e;
} finally {
n.publish({
engine: e,
threadId,
outcome: i,
durationMs: performance.now() - r
});
}
})();
}
function observeConnection(e) {
if (observedConnections.has(e)) return e;
observedConnections.add(e);
const t = e.exec.bind(e);
const n = e.prepare.bind(e);
e.exec = (e) => observeDatabaseOperation("sqlite", "statement", e, () => t(e));
e.prepare = (e) => {
const t = n(e);
for (const n of [
"get",
"all",
"run"
]) {
const r = t[n].bind(t);
Object.defineProperty(t, n, {
configurable: true,
writable: true,
value: (...t) => observeDatabaseOperation("sqlite", "statement", e, () => r(...t))
});
}
const r = t.iterate.bind(t);
t.iterate = (...t) => {
const n = r(...t);
if (!channels.statement.hasSubscribers) return n;
let i = 0;
let a = false;
let o = false;
const finish = (t) => {
if (o) return;
o = true;
if (a) channels.statement.publish({
engine: "sqlite",
sql: normalizeSql("sqlite", e),
threadId,
outcome: t,
durationMs: i
});
};
const step = (e) => {
if (o) return e();
const t = performance.now();
try {
const n = e();
i += performance.now() - t;
if (n.done) finish("ok");
return n;
} catch (e) {
i += performance.now() - t;
finish("error");
throw e;
}
};
const s = {
next: (...e) => {
a = true;
return step(() => n.next(...e));
},
return: (e) => step(() => n.return?.(e) ?? {
done: true,
value: e
}),
[Symbol.iterator]() {
return this;
}
};
Object.setPrototypeOf(s, Object.getPrototypeOf(n));
return s;
};
return t;
};
return e;
}
//#endregion
//#region src/infra/postgres-sync/transaction.ts
function assertPostgresOperationCurrent() {
const e = currentSqliteWorkerOperationAdmission.getStore();
if (e && (!e.active || e.owner.refusal)) throw e.owner.refusal ?? /* @__PURE__ */ new Error("PostgreSQL worker operation is no longer active");
}
function runPostgresTransactionSync(e, t, n, r = false, i = false) {
assertPostgresOperationCurrent();
const a = sqlPublicationAnchor(e);
return withSqlitePostCommitPublications(a, () => {
const a = e.isTransaction && !i;
let o = false;
let s;
try {
if (a) e.exec("SAVEPOINT openclaw_tx_nested");
else if (!e.isTransaction) e.exec(r ? "BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY" : `BEGIN ISOLATION LEVEL READ COMMITTED; SELECT pg_advisory_xact_lock(${e.advisoryLockKey})`);
if (r && !a) s = beginPostgresReadSnapshotScope(e);
const i = t();
assertSyncTransactionResult(i);
if (a) e.exec("RELEASE SAVEPOINT openclaw_tx_nested");
else {
const commit = () => {
assertPostgresOperationCurrent();
if (!r) prepareSqliteTransactionCommit(e);
e.exec(r ? "ROLLBACK" : "COMMIT");
o = !r;
};
if (n?.withCommit) assertSyncTransactionResult(n.withCommit(commit));
else commit();
}
return i;
} catch (t) {
let n = hasSqliteWorkerOutcomeUnknown(t) || o;
if (!n) try {
if (a) {
e.exec("ROLLBACK TO SAVEPOINT openclaw_tx_nested");
e.exec("RELEASE SAVEPOINT openclaw_tx_nested");
} else if (e.isTransaction) e.exec("ROLLBACK");
} catch {
n = true;
}
if (n) try {
discardSqliteTransactionState(e, t, "unknown");
} finally {
try {
e.close();
} catch {}
}
throw t;
} finally {
s?.();
}
});
}
//#endregion
//#region src/infra/postgres-sync/connection.ts
var PostgresSyncConnection = class {
constructor(e, t, n, r, i) {
this.schema = t;
this.anchor = n;
this.storeId = r;
this.isOpen = true;
this.isTransaction = false;
this.mutationRevision = 0;
this.idleCheckout = false;
this.lastResponseAt = Date.now();
this.outcomeUnknown = true;
this.readOnlyTransaction = false;
this.pendingWrite = false;
this.mainThread = threadId === 0;
assertEngineStoreExecutionAllowed();
Object.defineProperty(this, Symbol.for("openclaw.postgres-sync-connection"), { value: true });
this.advisoryLockKey = createHash("sha256").update(r).digest().readBigInt64BE();
this.bridgeParameters = {
url: e,
schema: t,
storeId: r,
...i
};
this.reuseKey = i?.reuse ? postgresBridgeReuseKey(this.bridgeParameters) : void 0;
this.connect();
}
connect() {
const e = this.reuseKey ? takeIdlePostgresBridge(this.reuseKey) : void 0;
const t = e ?? takePreparedPostgresBridge(this.bridgeParameters) ?? createPostgresBridge(this.bridgeParameters);
this.bridge = t;
this.idleCheckout = e !== void 0;
t.port.unref();
if (e) return t;
try {
this.request({
operation: "connect",
schema: this.schema
});
} catch (e) {
this.isOpen = false;
this.isTransaction = false;
this.bridge = void 0;
t.port.close();
throw e;
}
return t;
}
runTransaction(e, t, ...n) {
return runPostgresTransactionSync(this, e, t, ...n);
}
readRecoveryGeneration(e = false) {
return this.request({
operation: "recovery-generation",
schema: this.schema,
storeId: this.storeId,
lock: e
}, false);
}
loseConnection() {
if (!this.failure && this.outcomeUnknown) {
this.pendingWrite = true;
beginSqliteDatabaseWrite(sqlPublicationAnchor(this), true);
}
this.finishWrite();
this.failure ??= this.outcomeUnknown ? new SqliteWorkerError("PostgreSQL connection lost; outcome unknown", "outcome-unknown") : /* @__PURE__ */ new Error("PostgreSQL connection lost; transaction rolled back");
const e = this.bridge;
if (e?.nextStep && !this.failure.message.includes(e.nextStep)) this.failure.message += ` Run ${e.nextStep}.`;
if (e && Atomics.load(e.service, 1)) recordPostgresPoolFailure(this.failure);
this.isOpen = false;
this.isTransaction = false;
e?.port.close();
this.bridge = void 0;
return this.failure;
}
finishWrite() {
if (this.pendingWrite) {
this.pendingWrite = false;
finishSqliteDatabaseWrite(sqlPublicationAnchor(this));
}
}
assertOpen() {
if (this.failure) throw this.failure;
if (!this.isOpen) throw new Error("PostgreSQL connection is closed");
}
request(e, t = true) {
if (this.mainThread && e.operation !== "close" && e.operation !== "release") assertEngineStoreExecutionAllowed();
this.assertOpen();
const n = this.bridge ?? this.connect();
this.outcomeUnknown = t;
const r = ++n.requestId;
if (r > 2147483647) throw this.loseConnection();
const i = performance.now() + 12e4;
const a = n.inTransaction === false;
const o = (this.idleCheckout || a) && (e.operation === "query" || e.operation === "recovery-generation");
const s = o && (this.idleCheckout || a && Date.now() - this.lastResponseAt >= 1e3);
n.inTransaction = void 0;
this.idleCheckout = false;
n.port.postMessage({
...e,
...o ? { reconnectIfIdle: o } : {},
...s ? { validateIfIdle: s } : {},
id: r
}, []);
recordWorkerMessage("sqlite_request", "to_worker");
for (let e = Atomics.load(n.control, 0); e !== r; e = Atomics.load(n.control, 0)) {
if (Atomics.load(n.service, 1)) throw this.loseConnection();
const t = i - performance.now();
if (t <= 0) {
Atomics.store(n.service, 1, 1);
Atomics.notify(n.service, 1);
throw this.loseConnection();
}
Atomics.wait(n.control, 0, e, Math.min(t, 50));
}
const c = receiveMessageOnPort(n.port)?.message;
if (c) recordWorkerMessage("sqlite_reply", "from_worker");
if (!c || c.id !== r) throw this.loseConnection();
if ("error" in c) {
if (e.operation === "connect") throw decodePostgresError(c.error);
if (isPostgresConnectionError(c.error.code)) throw this.loseConnection();
if (e.operation === "query" && /^\s*COMMIT\b/i.test(e.sql)) {
this.isTransaction = false;
this.finishWrite();
}
throw decodePostgresError(c.error);
}
this.lastResponseAt = Date.now();
if ("reusable" in c) {
n.inTransaction = !c.reusable;
return c.reusable;
}
n.inTransaction = "generation" in c ? c.inTransaction : c.result.inTransaction;
return "generation" in c ? c.generation : c.result;
}
query(e, t = [], n = false) {
return observeDatabaseOperation("postgres", "statement", e, () => this.execute(preparePostgresQuery(e), t, n));
}
execute({ sql: e, mutation: t }, n, r) {
validatePostgresBindings(n);
const i = this.isTransaction;
if (/^\s*BEGIN\b/i.test(e)) this.isTransaction = true;
const a = this.request({
operation: "query",
schema: this.schema,
sql: e,
parameters: n
}, !i || /^\s*COMMIT\b/i.test(e));
const o = this.readOnlyTransaction;
this.isTransaction = a.inTransaction;
this.readOnlyTransaction = this.isTransaction && (o || /^\s*BEGIN\b[^;]*\bREAD\s+ONLY\b/i.test(e));
if (/^\s*COMMIT\s*;?\s*$/i.test(e) && a.command !== "COMMIT") {
this.finishWrite();
throw new Error("PostgreSQL transaction rolled back instead of committing");
}
const s = a.mutation === "unscoped" || t === "unscoped" ? "unscoped" : a.mutation ?? t;
const c = s !== void 0;
if (c) {
if (o || this.readOnlyTransaction) throw new Error("PostgreSQL read snapshot cannot execute a mutation");
this.mutationRevision++;
this.pendingWrite = true;
beginSqliteDatabaseWrite(sqlPublicationAnchor(this), s === "unscoped");
}
if (!this.isTransaction && (c || i)) withSqlitePostCommitPublications(sqlPublicationAnchor(this), () => {
this.finishWrite();
});
this.outcomeUnknown = !this.isTransaction;
return {
rows: decodePostgresRows(a, r),
rowCount: a.rowCount,
columns: a.fields.map(({ name: e }) => ({ name: e }))
};
}
exec(e) {
this.query(e);
}
prepare(e) {
this.assertOpen();
const t = preparePostgresQuery(e);
let n = false;
let r = [];
const execute = (i) => {
const a = observeDatabaseOperation("postgres", "statement", e, () => this.execute(t, i, n));
r = a.columns;
return a;
};
return {
get: (...e) => execute(e).rows[0],
all: (...e) => execute(e).rows,
iterate: (...e) => execute(e).rows[Symbol.iterator](),
run: (...e) => ({
changes: execute(e).rowCount,
lastInsertRowid: 0
}),
columns: () => r,
setReadBigInts: (e) => {
n = e;
}
};
}
/** Release only the idle backend; the logical reader keeps its admitted facts and anchor. */
releaseIdleTransport() {
const e = this.bridge;
if (!this.isOpen || !e || !this.reuseKey || this.isTransaction) return;
let t = false;
try {
if (e.inTransaction === false || this.request({ operation: "release" })) {
retainIdlePostgresBridge(this.reuseKey, e);
t = true;
} else {
this.isOpen = false;
this.finishWrite();
}
} finally {
this.bridge = void 0;
if (!t) e.port.close();
}
}
close() {
if (!this.isOpen) return;
try {
if (this.reuseKey && !this.isTransaction) this.releaseIdleTransport();
else if (this.bridge) this.request({ operation: "close" });
} finally {
this.finishWrite();
this.isOpen = false;
this.isTransaction = false;
this.bridge?.port.close();
this.bridge = void 0;
}
}
};
//#endregion
//#region src/infra/database-engine/postgres-vector.ts
function bindPostgresVector(e, t, n) {
const r = getNodeSqliteKysely(e);
const i = pgSearchName(n.extensionSchema ?? "public");
const a = getAdmittedPostgresSchema(e)?.postgresVectorSearchVersion === 2;
const own = (n) => {
if (!e.isOpen || n.store !== t) throw new Error("Vector index is not admitted to this open store");
return n.postgres;
};
const write = (t) => {
const n = own(t);
if (!e.isTransaction) throw new Error("Vector mutation requires the owner's transaction");
return n;
};
return {
idSet(e, t) {
own(e);
return sql`SELECT value FROM json_array_elements_text(${JSON.stringify(t)}::json)`;
},
prepareExists(t) {
own(t);
const n = e.prepare(`SELECT id FROM ${pgSearchName(t.table)} WHERE id = ?`);
return (e) => Boolean(n.get(e));
},
async nearest(t) {
const n = own(t.index);
t.signal?.throwIfAborted();
if (t.vector.length !== n.dimensions || t.vector.some((e) => !Number.isFinite(e) || !Number.isFinite(Math.fround(e))) || !t.vector.some((e) => Math.fround(e) !== 0)) throw new Error("PostgreSQL cosine query requires a finite nonzero vector matching the admitted dimensions; rebuild for a changed embedding model.");
const o = `[${t.vector.map(Math.fround).join(",")}]`;
const s = sql.ref(`${t.index.alias}.embedding`);
const c = sql`${sql.ref(`${t.index.alias}.embedding`)} ${sql.raw(`OPERATOR(${i}.<=>)`)} ${o}::${sql.raw(i)}.vector`;
const l = sql.ref(`${t.index.alias}.embedding_bits`);
const u = a ? sql`${l} IS NOT NULL` : sql`${sql.raw(i)}.vector_norm(${s}) > 0`;
const d = a ? t.candidates?.({
match: u,
distance: sql`${l} ${sql.raw(`OPERATOR(${i}.<~>)`)} ${sql.raw(i)}.binary_quantize(${o}::${sql.raw(i)}.vector)`,
limit: t.limit * 8
}) : void 0;
const f = t.query({
match: d ? sql`${sql.ref(`${t.index.alias}.id`)} IN (SELECT id FROM openclaw_vector_candidates)` : u,
distance: c
});
const p = d ? sql`WITH openclaw_vector_candidates AS MATERIALIZED (${d})` : sql``;
const m = executeSqliteQuerySync(e, { compile: () => sql`${p} SELECT * FROM (${f}) AS openclaw_candidates LIMIT ${t.limit}`.compile(r) }).rows;
if (!m.every(t.isRow) || !m.every((e) => matchesVectorRow(e, t.index.rowShape))) throw new Error("PostgreSQL vector query returned an invalid row");
for (const e of m) {
const n = t.textPrefix;
if (n && e && typeof e === "object") {
const t = Reflect.get(e, n.column);
if (typeof t === "string") Reflect.set(e, n.column, truncateUtf16Safe(t, n.maxChars));
}
}
return {
rows: m,
fallbackScanRequired: false
};
},
remove(t, n) {
write(t);
const i = "toOperationNode" in n ? sql`${n}` : sql`SELECT value FROM json_array_elements_text(${JSON.stringify(n)}::json)`;
executeSqliteQuerySync(e, { compile: () => sql`DELETE FROM ${sql.table(t.table)} WHERE id IN (${i})`.compile(r) });
},
drop() {
throw new Error("PostgreSQL vector DDL belongs to store schema admission; rebuild the projection instead");
},
create(e, t) {
if (write(e).dimensions !== t) throw new Error("PostgreSQL vector dimensions changed; reopen with the new search schema and rebuild");
},
write(t, n) {
const r = write(t);
const i = e.prepare(`INSERT INTO ${pgSearchName(t.table)}(id, embedding) SELECT ${pgSearchName(r.key)}, openclaw_vector(${pgSearchName(r.embedding)}, ${r.dimensions}) FROM ${pgSearchName(r.source)} WHERE ${pgSearchName(r.key)} = ? AND octet_length(${pgSearchName(r.embedding)}) > 0 ON CONFLICT (id) DO UPDATE SET embedding = excluded.embedding`);
for (const e of n) i.run(e.id);
}
};
}
//#endregion
//#region src/infra/database-engine/postgres-search.ts
/** Query text parses through the same separator split as the stored vector. */
function searchTextFor(e) {
const t = postgresSearchTokenSeparators;
return e === 2 ? (e) => sql`regexp_replace(${e}, ${t}, ' ', 'g')` : (e) => sql`${e}`;
}
function tsquery(e, t, n) {
if (e.kind === "contains") throw new Error("Contains is only available on an admitted trigram index");
if (e.kind !== "term" && e.kind !== "phrase") {
if (e.clauses.every((e) => e.kind === "term" || e.kind === "phrase")) {
const r = e.kind === "all" ? " & " : " | ";
return sql`coalesce((
SELECT string_agg('(' || nullif(parsed.value::text, '') ||
CASE WHEN atom.prefix THEN ':*' ELSE '' END || ')', ${r})
FROM json_to_recordset(${JSON.stringify(e.clauses)}::json)
AS atom(kind text, text text, prefix boolean)
CROSS JOIN LATERAL (SELECT CASE WHEN atom.kind = 'term'
THEN plainto_tsquery(${sql.lit(t)}::regconfig, ${n(sql`atom.text`)})
ELSE phraseto_tsquery(${sql.lit(t)}::regconfig, ${n(sql`atom.text`)})
END AS value) AS parsed
), '')::tsquery`;
}
const r = e.clauses.map((e) => tsquery(e, t, n));
return r.length ? sql`(${sql.join(r, sql.raw(e.kind === "all" ? " && " : " || "))})` : sql`''::tsquery`;
}
const r = e.kind === "term" ? sql`plainto_tsquery(${sql.lit(t)}::regconfig, ${n(e.text)})` : sql`phraseto_tsquery(${sql.lit(t)}::regconfig, ${n(e.text)})`;
return e.kind === "phrase" && e.prefix ? sql`coalesce((nullif(${r}::text, '') || ':*')::tsquery, ''::tsquery)` : r;
}
function bindPostgresSearch(e, t) {
assertPostgresSearchAdmitted(e, t);
const n = `${pgSearchName(getPostgresPhysicalFacts(e).namespace)}.${pgSearchName(searchConfig)}`;
const r = pgSearchName(t.extensionSchema ?? "public");
const i = getAdmittedPostgresSchema(e)?.postgresTextSearchVersion;
const a = searchTextFor(i);
const o = {};
const s = Object.fromEntries(Object.entries(t.text ?? {}).map(([e, t]) => [e, {
...t,
store: o
}]));
const c = Object.fromEntries(Object.entries(t.vector ?? {}).map(([e, t]) => [e, {
...t,
store: o
}]));
const relation = (t, n = "openclaw_search") => {
if (!e.isOpen || t.store !== o) throw new Error("Text index is not admitted to this open store");
return sql.ref(`${t.alias ?? t.table}.${n}`);
};
const requireQuery = (e) => {
if (!e) throw new Error("PostgreSQL rank and snippet require the literal search query");
return tsquery(e, n, a);
};
return {
text: s,
vectors: c,
diagnostics: [],
rebuild: () => rebuildPostgresSearch(e, t),
fullText: Object.keys(s).length ? {
match(e, t) {
const r = relation(e, t.kind === "contains" ? e.fields[0] : void 0);
if (t.kind === "any" && t.clauses.length > 128 && t.clauses.every((e) => e.kind === "phrase" && !e.prefix)) {
const e = t.clauses.map((e) => e.text);
return sql`EXISTS (SELECT 1 FROM json_array_elements_text(${JSON.stringify(e)}::json) AS search_terms(value) WHERE ${r} @@ phraseto_tsquery(${sql.lit(n)}::regconfig, ${a(sql`search_terms.value`)}))`;
}
if (t.kind === "contains") {
if (e.postgres?.mode !== "trigram") throw new Error("Contains requires a declared PostgreSQL trigram index");
const n = `%${t.text.replaceAll("\\", "\\\\").replaceAll("%", "\\%").replaceAll("_", "\\_")}%`;
return sql`${r} ILIKE ${n} ESCAPE '\\'`;
}
return sql`${r} @@ ${tsquery(t, n, a)}`;
},
rank(e, t, n) {
if (t?.kind === "contains") {
if (e.postgres?.mode !== "trigram") throw new Error("Contains requires a declared PostgreSQL trigram index");
return {
value: sql`${sql.raw(r)}.word_similarity(${t.text}, ${relation(e, e.fields[0])})`,
order: "desc",
toRank: (e) => e
};
}
const i = relation(e);
const a = n?.postgres?.rank === "frequency" ? sql`ts_rank` : sql`ts_rank_cd`;
return {
value: sql`${a}(${i}, ${requireQuery(t)}, ${n?.postgres?.normalization ?? 2})`,
order: "desc",
toRank: (e) => e
};
},
snippet(e, t, r, a, o = 500) {
if (r < 2) throw new Error("PostgreSQL snippets require at least two tokens");
if (!e.fields.includes(t)) throw new Error(`Text index has no field ${t}`);
const s = `StartSel='', StopSel='', MaxWords=${Math.max(1, Math.min(48, Math.trunc(r)))}, MinWords=1, MaxFragments=1, FragmentDelimiter=' … '`;
const c = Math.max(1, Math.min(500, Math.trunc(o)));
const l = relation(e, t);
if (i !== 2) return sql`left(ts_headline(${sql.lit(n)}::regconfig, ${l}, ${requireQuery(a)}, ${s}), ${c})`;
const u = sql`regexp_replace(${l}, '[[:punct:]]', ' ', 'g')`;
const d = sql`ts_headline(${sql.lit(n)}::regconfig, ${u}, ${requireQuery(a)}, ${s})`;
return sql`left(substr(${l}, strpos(${u}, ${d}), length(${d})), ${c})`;
},
identity: (e) => sql`${relation(e, e.postgres.identity)}`,
allocatedIdentity() {
throw new Error("PostgreSQL insert identities must use RETURNING");
}
} : null,
vector: t.mode === "keyword-only" || !Object.keys(c).length ? null : bindPostgresVector(e, o, t)
};
}
//#endregion
//#region src/infra/database-engine/sqlite-full-text.ts
function literalQuery(e) {
if (e.kind === "contains") throw new Error("Literal contains requires the owner's SQLite substring policy");
if (e.kind === "term" || e.kind === "phrase") return `"${e.kind === "term" ? e.text.replaceAll("\"", "") : e.text.replaceAll("\"", "\"\"")}"${e.kind === "phrase" && e.prefix ? "*" : ""}`;
let t = e.kind === "any" ? " OR " : " AND ";
if (e.kind === "all" && e.clauses.every((e) => e.kind === "phrase")) t = " ";
return e.clauses.map((e) => e.kind === "any" ? `(${literalQuery(e)})` : literalQuery(e)).join(t);
}
function bindSqliteFullText(e, t) {
const relation = (n) => {
if (n.store !== e || t && !t.isOpen) throw new Error("Text index is not admitted to this open store");
return n.alias ?? n.table;
};
return {
match(e, t) {
const n = relation(e);
const r = literalQuery(t);
return e.matchField ? sql`${sql.ref(`${n}.${e.matchField}`)} match ${r}` : sql`${sql.raw(n)} MATCH ${r}${sql.raw(e.hiddenRank ? ` AND ${n}.rank MATCH 'bm25()'` : "")}`;
},
rank(e) {
const t = relation(e);
return {
value: sql`${sql.raw(e.hiddenRank ? `${t}.rank` : `bm25(${t})`)}`,
order: "asc",
toRank: (e) => Number.isFinite(e) ? -e : 0
};
},
snippet(e, t, n) {
const r = relation(e);
const i = e.fields.indexOf(t);
if (i < 0) throw new Error(`Text index has no field ${t}`);
return sql`${sql.raw(`snippet(${r}, ${i}, '', '', ' … ', ${n})`)}`;
},
identity: (e) => sql`${sql.raw(`${relation(e)}.rowid`)}`,
allocatedIdentity: (e) => {
relation(e);
return sql`${createFunctionModule()("last_insert_rowid", [])}`;
}
};
}
//#endregion
//#region src/infra/database-engine/search.ts
/** @experimental Bind once alongside the owner's admission, using its declared indexes. */
function bindStoreSearch(e, t) {
if ("databasePath" in e ? Boolean(e.input) : isPostgresSqlConnection(e)) {
if ("databasePath" in e || !isPostgresSqlConnection(e)) throw new Error("PostgreSQL search requires the admitted worker connection");
return bindPostgresSearch(e, t);
}
const n = "databasePath" in e || isPostgresSqlConnection(e) ? void 0 : e;
const r = "databasePath" in e ? e.databasePath : n?.location() ?? "";
const i = {};
const bindIndexes = (e = {}) => Object.fromEntries(Object.entries(e).map(([e, t]) => [e, {
...t,
store: i
}]));
return {
fullText: bindSqliteFullText(i, n),
vector: bindSqliteVectorCapability({
store: i,
databasePath: r
}, n),
text: bindIndexes(t.text),
vectors: bindIndexes(t.vector),
diagnostics: []
};
}
//#endregion
//#region src/infra/database-engine/search-extension.ts
var SearchExtensionDefinitionChangedError = class extends Error {
constructor(...e) {
super(...e);
this.name = "SearchExtensionDefinitionChangedError";
}
};
/** Definition preflight only; binding still checks the store's search capability admission. */
function arePostgresSearchExtensionsAdmitted(e, t) {
const n = getAdmittedPostgresSchema(e);
return Boolean(n && getPostgresPhysicalFacts(e) && Object.entries(t).every(([e, t]) => JSON.stringify(n.searchExtensions?.[e]) === JSON.stringify(t)));
}
/** Register only at the owner's admission boundary; SQLite retains its existing derived lifecycle. */
function admitStoreSearchExtension(e, t, n) {
if (!isPostgresSqlConnection(e)) {
if (t === "memory.vector") admitSqliteMemoryVectorSearch(e, n);
return bindStoreSearch(e, t === "memory.text" ? admitSqliteMemoryTextSearch(e, n) : n);
}
const r = getAdmittedPostgresSchema(e);
const i = getPostgresPhysicalFacts(e);
if (!r || !i) throw new Error("Search extensions require an admitted PostgreSQL store");
if (JSON.stringify(r.searchExtensions?.[t]) === JSON.stringify(n)) return bindStoreSearch(e, n);
if (r.searchExtensions?.[t]) throw new SearchExtensionDefinitionChangedError(`Search extension ${t} changed. Restore its previous definition, or rebuild the derived extension from canonical source data before using the new definition.`);
e.runTransaction(() => {
admitPostgresSearch(e, n, i.namespace, r.postgresVectorSearchVersion);
const a = [r.search, ...Object.values(r.searchExtensions ?? {})].filter((e) => e !== void 0);
if (a.some((e) => (e.extensionSchema ?? "public") !== (n.extensionSchema ?? "public"))) throw new Error("Search extensions must use the store's admitted extension schema");
const o = {
...r,
searchExtensions: {
...r.searchExtensions,
[t]: n
}
};
e.exec(postgresSearchSql(n, i.namespace, {
text: a.some((e) => Object.keys(e.text ?? {}).length > 0),
vector: a.some((e) => e.mode !== "keyword-only" && Object.keys(e.vector ?? {}).length > 0)
}, r.postgresVectorDecoderVersion, r.postgresVectorSearchVersion, r.postgresTextSearchVersion));
if (!Object.keys(r.searchExtensions ?? {}).length) e.exec("ALTER TABLE openclaw_schema_meta ADD COLUMN IF NOT EXISTS search_extensions TEXT");
e.prepare("UPDATE openclaw_schema_meta SET search_extensions = ? WHERE store = ?").run(JSON.stringify(o.searchExtensions), r.id);
const s = verifyAndRecordPostgresSchema(e, i.namespace, o);
invalidateLocalSqliteSchemaAdmissions(e);
stageSqliteTransactionState(e, { commit: () => publishSqliteDatabaseSchemaChange(e) });
retainPostgresSchema(e, o);
publishPostgresSearchExtensionFacts(e, i, s.catalog);
for (const t of [o.search, ...Object.values(o.searchExtensions)].filter((e) => e !== void 0)) publishPostgresSearch(e, t, r.postgresVectorSearchVersion);
});
return bindStoreSearch(e, n);
}
//#endregion
//#region src/infra/database-engine/search-admission.ts
/** @experimental Admit an owner's extension, or bind its already admitted indexes. */
function admitStoreSearch(e, t, n) {
if (n) {
if ("databasePath" in e) throw new Error("Search extension admission requires the owner's connection");
return admitStoreSearchExtension(e, n.extension, t);
}
return bindStoreSearch(e, t);
}
//#endregion
//#region src/infra/database-engine/adapters.ts
const databaseEngineAdapters = {
sqlite: {
openConnection: ({ anchor: e }) => observeConnection(e),
schema: { bootstrap: (e) => e.openSqlite() }
},
postgres: {
openConnection: (e) => {
if (!e.input || !e.storeId || !e.namespace) throw new Error("PostgreSQL store is not admitted");
try {
return new PostgresSyncConnection(e.input.connection, e.namespace, e.anchor, e.storeId, {
reuse: e.reusePostgresConnection,
lockTimeoutMs: POSTGRES_LOCK_TIMEOUT_MS,
statementTimeoutMs: POSTGRES_STATEMENT_TIMEOUT_MS
});
} catch (t) {
const n = t instanceof Error && "code" in t && typeof t.code === "string" ? `${t.code}: ` : "";
const r = redactSensitiveText(`${n}${t instanceof Error ? t.message : String(t)}`.replaceAll(e.input.connection, "[REDACTED]"), { mode: "tools" });
throw new Error(`Cannot open PostgreSQL connection: ${r}; verify database.postgres.connection and server availability.`, { cause: t });
}
},
schema: {
bootstrap: (e, t) => {
if (!e.schema.postgres) throw new Error("Store has no PostgreSQL schema");
t.exec(postgresSchemaSql(e.schema, e.namespace));
t.prepare("INSERT INTO openclaw_schema_meta (store, version, store_id) VALUES (?, ?, ?)").run(e.schema.id, e.schema.version, e.storeId);
},
migrate: (e, t, n) => {
if (t > e.schema.version) throw new Error(`PostgreSQL ${e.schema.id} schema ${t} is newer than this build (expected ${e.schema.version}); use a compatible binary, or reverse-port with a compatible binary before downgrading.`);
for (let r = t + 1; r <= e.schema.version; r++) {
const t = e.schema.postgresMigrations?.find((e) => e.version === r);
if (!t) throw new Error(`Missing PostgreSQL ${e.schema.id} migration to version ${r}; use a compatible binary or restore a matching backup.`);
const i = readPostgresSchema(n, e.namespace, e.schema.id);
const a = withPostgresSearchExtensions(e.schema, i);
verifyPostgresSchema(n, e.namespace, {
...a,
version: r - 1,
postgres: t.fromSchema.postgres,
postgresFragments: t.fromSchema.postgresFragments,
postgresVectorDecoderVersion: t.fromSchema.postgresVectorDecoderVersion,
postgresVectorSearchVersion: t.fromSchema.postgresVectorSearchVersion,
postgresTextSearchVersion: t.fromSchema.postgresTextSearchVersion
}, i);
if (t.schema.postgresVectorSearchVersion === 2 && t.fromSchema.postgresVectorSearchVersion !== 2) {
for (const t of [a.search, ...Object.values(a.searchExtensions ?? {})]) if (t) admitPostgresSearch(n, t, e.namespace, 2);
}
e.beforeMigrate?.(n, r - 1, new Set(i.catalog.filter((e) => e.kind === "table").map((e) => e.table)));
n.exec(t.sql);
n.prepare("UPDATE openclaw_schema_meta SET version = ? WHERE store = ?").run(r, e.schema.id);
verifyAndRecordPostgresSchema(n, e.namespace, {
...a,
version: r,
postgres: t.schema.postgres,
postgresFragments: t.schema.postgresFragments,
postgresVectorDecoderVersion: t.schema.postgresVectorDecoderVersion,
postgresVectorSearchVersion: t.schema.postgresVectorSearchVersion,
postgresTextSearchVersion: t.schema.postgresTextSearchVersion
});
}
}
}
}
};
/** Worker envelopes need a transaction only on PostgreSQL; native SQLite statements stay identical. */
function runEngineWorkerWrite(e, t, n) {
return e ? n(t) : t();
}
function runEngineStoreReadSnapshot(e, t) {
return isPostgresSqlConnection(e) ? runSqliteReadSnapshotSync(e, t) : runSqliteDeferredTransactionSync(e, t);
}
/** Dedicated streaming readers retain this snapshot until their last host acknowledgement. */
function beginEngineStoreReadSnapshot(e) {
if (e.isTransaction) throw new Error("Streaming read snapshot requires a dedicated connection");
e.exec(isPostgresSqlConnection(e) ? "BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY" : "BEGIN DEFERRED");
return { close() {
if (e.isTransaction) e.exec("ROLLBACK");
} };
}
//#endregion
export { admitStoreSearch as a, observeDatabaseRequest as c, runEngineWorkerWrite as i, databaseEngineAdapters as n, arePostgresSearchExtensionsAdmitted as o, runEngineStoreReadSnapshot as r, observeConnection as s, beginEngineStoreReadSnapshot as t };