UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

556 lines (555 loc) • 22.3 kB
import { y as toErrorObject } from "./paths-0xDagtub.mjs"; import { u as sqlitePrimaryResultCode } from "./sqlite-error-diagnostics-DXQCgyiD.mjs"; import { i as readSqliteUserVersion } from "./sqlite-user-version-D-rYjp-A.mjs"; import { n as isPostgresSqlConnection } from "./sql-connection-VmV9pnJI.mjs"; import { a as installStatementInvalidation, i as executeWithCachedStatement, n as disposeSqliteStatement, o as kyselyByDatabase, s as queryErrorHandlerByDatabase } from "./kysely-sync-cache-state-D75yJYFp.mjs"; import { $ as readTableConstraintKeyword, Ct as stageSqliteTransactionState, G as findSqlCharacter, K as findSqlClosingParenthesis, Q as readSqlToken, U as parseSqliteTableDefinition, Y as normalizeSqlIdentifier, _ as publishSqliteDatabaseAdmission, _t as retainSqliteReader, et as splitSqlList, l as hasPendingSqliteDatabaseSchemaMutation, o as getSqliteDatabaseAdmission, pt as captureSqliteReaderOwner, q as hasUnquotedSqlKeyword } from "./sqlite-database-admission-DMm34jqt.mjs"; import { a as isSqliteSchemaAdmissionCold, f as schemaAdmission, g as getPostgresPhysicalFacts, r as getAdmittedSqliteSchemaFacts, t as admitSqliteSchema } from "./sqlite-schema-facts-BFHoBJFZ.mjs"; import { toUSVString } from "node:util"; import { InsertQueryNode, Kysely, OperatorNode, PostgresDialect, PostgresQueryCompiler, RawNode, SelectQueryNode, SqliteDialect, ValueNode, sql } from "kysely"; //#region node-version.mjs const NODE_RELEASE_VERSION_RE = /^v?((?:0|[1-9]\d*))\.((?:0|[1-9]\d*))\.((?:0|[1-9]\d*))(?:-((?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*))*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/u; const NODE_RELEASE_FLOORS = [{ major: 24, minor: 16, patch: 0 }, { major: 26, minor: 1, patch: 0 }]; const HIGHEST_RELEASE_FLOOR = NODE_RELEASE_FLOORS[NODE_RELEASE_FLOORS.length - 1]; const SUPPORTED_NODE_VERSION_RANGE = NODE_RELEASE_FLOORS.map(({ major: e, minor: t, patch: n }, r) => `>=${e}.${t}.${n}${r < NODE_RELEASE_FLOORS.length - 1 ? ` <${e + 1}` : ""}`).join(" || "); const SUPPORTED_NODE_VERSIONS = `${SUPPORTED_NODE_VERSION_RANGE.replaceAll(" || ", ", ").replace(/, ([^,]+)$/, ", or $1")} (Node 26 recommended)`; /** Parses release SemVer; future-major prereleases use their numeric core for admission. */ function parseNodeReleaseVersion(e) { if (typeof e !== "string") return null; const t = NODE_RELEASE_VERSION_RE.exec(e.trim()); if (!t) return null; const n = { major: Number(t[1]), minor: Number(t[2]), patch: Number(t[3]) }; return Object.values(n).every(Number.isSafeInteger) && (!t[4] || n.major > HIGHEST_RELEASE_FLOOR.major) ? n : null; } function isNodeVersionAtLeast(e, t) { if (!e) return false; if (e.major !== t.major) return e.major > t.major; if (e.minor !== t.minor) return e.minor > t.minor; return e.patch >= t.patch; } function renderProcessNodeVersionCheck() { return `((value) => { if (typeof value !== "string") return false; const match = new RegExp(${JSON.stringify(NODE_RELEASE_VERSION_RE.source)}, "u").exec(value.trim()); if (!match) return false; const version = { major: Number(match[1]), minor: Number(match[2]), patch: Number(match[3]) }; if (!Object.values(version).every(Number.isSafeInteger)) return false; const floors = ${JSON.stringify(NODE_RELEASE_FLOORS)}; if (match[4] && version.major <= floors[floors.length - 1].major) return false; const minimum = floors.find((floor) => floor.major === version.major); const atLeast = (floor) => version.major > floor.major || (version.major === floor.major && (version.minor > floor.minor || (version.minor === floor.minor && version.patch >= floor.patch))); return minimum ? atLeast(minimum) : version.major > floors[floors.length - 1].major; })(process.versions.node)`; } const PROCESS_NODE_VERSION_CHECK = renderProcessNodeVersionCheck(); //#endregion //#region src/infra/sql-query-compiler.ts const templateFragments = (e, t) => e; const sqliteStringSetFragments = templateFragments`(SELECT value FROM json_each(${0}))`; const sqliteStringSetEntriesFragments = templateFragments`json_each(${0})`; function postgresStringArray(e) { if (!RawNode.is(e) || e.sqlFragments !== sqliteStringSetFragments || e.parameters.length !== 1) return; let t = e.parameters[0]; while (RawNode.is(t) && t.parameters.length === 1 && t.sqlFragments.length === 2 && t.sqlFragments.every((e) => e === "")) t = t.parameters[0]; if (!ValueNode.is(t) || t.immediate || typeof t.value !== "string") return; let n; try { n = JSON.parse(t.value); } catch { return; } if (!Array.isArray(n) || !n.every((e) => typeof e === "string")) return; return `{${n.map((e) => `"${e.replace(/["\\]/g, "\\$&")}"`).join(",")}}`; } /** Lower only the shared string-set primitive; arbitrary raw SQL stays caller-owned. */ var OpenClawPostgresQueryCompiler = class extends PostgresQueryCompiler { visitBinaryOperation(e) { if (OperatorNode.is(e.operator) && e.operator.operator === "in") { const t = postgresStringArray(e.rightOperand); if (t !== void 0) { this.visitNode(e.leftOperand); this.append(" = ANY("); this.appendValue(t); this.append("::text[])"); return; } } super.visitBinaryOperation(e); } visitRaw(e) { const t = e.sqlFragments === sqliteStringSetFragments; if (!t && e.sqlFragments !== sqliteStringSetEntriesFragments) { super.visitRaw(e); return; } this.append(t ? "(SELECT value FROM json_array_elements_text(" : "(SELECT ordinality - 1 AS key, value FROM json_array_elements_text("); this.compileList(e.parameters); this.append(t ? "::json) AS value)" : "::json) WITH ORDINALITY AS entries(value, ordinality))"); } }; var OpenClawPostgresDialect = class extends PostgresDialect { createQueryCompiler() { return new OpenClawPostgresQueryCompiler(); } }; //#endregion //#region src/infra/kysely-sync.ts const nodeVersion = parseNodeReleaseVersion(process.versions.node); const supportsRepreparedAll = !process.versions.bun && (nodeVersion?.major === 24 && isNodeVersionAtLeast(nodeVersion, { major: 24, minor: 20, patch: 0 }) || isNodeVersionAtLeast(nodeVersion, { major: 26, minor: 6, patch: 0 })); const compileOnlySqliteDialect = new SqliteDialect({ database: async () => { throw new Error("getNodeSqliteKysely() returns a compile-only Kysely facade; use executeSqliteQuerySync() to execute node:sqlite queries."); } }); const postgresKyselyByDatabase = /* @__PURE__ */ new WeakMap(); const compileOnlyPostgresDialect = new OpenClawPostgresDialect({ pool: async () => { throw new Error("getNodeSqliteKysely() returns a compile-only Kysely facade."); } }); function getNodeSqliteKysely(e) { if (isPostgresSqlConnection(e)) { let t = postgresKyselyByDatabase.get(e); if (!t) { t = new Kysely({ dialect: compileOnlyPostgresDialect }); postgresKyselyByDatabase.set(e, t); } return t; } const t = kyselyByDatabase.get(e); if (t) return t; const n = new Kysely({ dialect: compileOnlySqliteDialect }); kyselyByDatabase.set(e, n); return n; } function reportNodeSqliteKyselyQueryError(e, t) { try { queryErrorHandlerByDatabase.get(e)?.(t); } catch {} } function releaseSqliteIterator(e, t, n, r) { let i; try { e.return?.(); } catch (e) { i = e; } t.release(); if (!n && i !== void 0) throw toErrorObject(i, r); } /** Execute a compiled Kysely query synchronously against node:sqlite. */ function executeCompiledSqliteQuerySync(e, t, n = false, r = t.parameters) { if (isPostgresSqlConnection(e)) { const i = e.query(t.sql, r); const a = n ? i.rows.slice(0, 1) : i.rows; return i.columns.length > 0 ? { rows: a } : { rows: [], numAffectedRows: BigInt(i.rowCount) }; } try { const i = t.sql; installStatementInvalidation(e); return executeWithCachedStatement(e, i, r, (i) => { if (n && SelectQueryNode.is(t.query)) { const e = i.get(...r); return { rows: e === void 0 ? [] : [e] }; } if (SelectQueryNode.is(t.query) || i.columns().length > 0) { if (supportsRepreparedAll) return { rows: i.all(...r) }; const t = i.iterate(...r); const n = retainSqliteReader(e, "kysely eager query"); let a = false; let o; const s = []; try { for (const e of t) { n.progress(); s.push(e); } } catch (e) { a = true; o = e; } releaseSqliteIterator(t, n, a, "SQLite query cleanup failed"); if (a) throw toErrorObject(o, "SQLite query failed"); return { rows: s }; } i.setReadBigInts(true); let a; try { a = i.run(...r); } finally { i.setReadBigInts(false); } const { changes: o, lastInsertRowid: s } = a; const c = { numAffectedRows: BigInt(o), rows: [] }; if (InsertQueryNode.is(t.query) && o > 0) return { ...c, insertId: BigInt(s) }; return c; }); } catch (t) { reportNodeSqliteKyselyQueryError(e, t); throw t; } } /** Compile and execute a Kysely query synchronously. */ function executeSqliteQuerySync(e, t) { return executeCompiledSqliteQuerySync(e, t.compile()); } /** Cache compiled query functions or bundles by native connection. */ function createSqliteQueryCache(e) { const t = /* @__PURE__ */ new WeakMap(); return (n) => { let r = t.get(n); if (r === void 0) { r = e(n); t.set(n, r); } return r; }; } /** Compile fixed SQL and fresh bindings without taking ownership of a native statement. */ function compileSqliteQueryBindings(e) { const t = /* @__PURE__ */ new Map(); const n = e((e) => { const n = Symbol("sqlite-query-parameter"); t.set(n, e); return sql`${n}`; }).compile(); const r = n.parameters.map((e) => t.get(e) ?? (() => e)); return { compiled: n, bind: (e) => r.map((t) => t(e)) }; } /** Compile a fixed query once; bind fresh values through the normal sync executor on each call. */ function prepareSqliteQuerySync(e, t) { const { compiled: n, bind: r } = compileSqliteQueryBindings(t); return (t) => executeCompiledSqliteQuerySync(e, n, false, r(t)); } /** Compile and lazily iterate a Kysely query synchronously against node:sqlite. */ function iterateSqliteQuerySync(e, t) { if (isPostgresSqlConnection(e)) return (function* () { yield* executeCompiledSqliteQuerySync(e, t.compile()).rows; })(); const n = captureSqliteReaderOwner(); return (function* () { const r = t.compile(); let i; try { i = e.prepare(r.sql); if (!SelectQueryNode.is(r.query) && i.columns().length === 0) return; const t = r.parameters; const a = i.iterate(...t); const o = retainSqliteReader(e, "kysely iterator", n); let s = false; try { for (const e of a) { o.progress(); yield e; } } catch (e) { s = true; throw toErrorObject(e, "SQLite iterator failed"); } finally { releaseSqliteIterator(a, o, s, "SQLite iterator cleanup failed"); } } catch (t) { reportNodeSqliteKyselyQueryError(e, t); throw t; } finally { if (i) disposeSqliteStatement(i); } })(); } /** Execute a Kysely query synchronously and return its first row. */ function executeSqliteQueryTakeFirstSync(e, t) { return executeCompiledSqliteQuerySync(e, t.compile(), true).rows[0]; } //#endregion //#region src/infra/sqlite-schema-issues.ts /** A completed inspection proved schema drift; native read failures retain their own type. */ var SqliteSchemaMismatchError = class extends Error { constructor(...e) { super(...e); this.name = "SqliteSchemaMismatchError"; } }; const ISSUE_DESCRIPTIONS = { "missing-table": "missing table", "missing-column": "column definitions differ for", "unexpected-column": "column definitions differ for", "column-definition-drift": "column definitions differ for", "table-constraint-drift": "table constraints differ for", "table-definition-drift": "table definition differs for", "missing-or-drifted-index": "missing or drifted index", "unexpected-unique-index": "unexpected unique index", "missing-or-drifted-trigger": "missing or drifted trigger", "missing-or-drifted-view": "missing or drifted view", "unexpected-trigger": "unexpected trigger", "virtual-table-definition-drift": "virtual table definition differs for", "table-options-drift": "table options differ for" }; function isColumnIssue(e) { return e === "column-definition-drift" || e === "missing-column" || e === "unexpected-column"; } function defaultIssueMessage(e, t) { const n = isColumnIssue(e) ? t.split(".", 1)[0] : t; return `${ISSUE_DESCRIPTIONS[e]} ${n}`; } function createSqliteSchemaIssue(e, t, n) { return { code: e, objectName: t, message: n ?? defaultIssueMessage(e, t) }; } function legacySqliteSchemaIssueMessages(e) { const t = new Set(e.filter((e) => isColumnIssue(e.code)).map((e) => e.objectName.split(".", 1)[0])); return [...new Set(e.filter((e) => e.code !== "table-constraint-drift" || !t.has(e.objectName)).map((e) => e.message))]; } function throwSqliteSchemaMismatches(e, t) { const n = t.slice(0, 8); if (t.length > n.length) n.push(`${t.length - n.length} additional mismatch(es)`); throw new SqliteSchemaMismatchError(`SQLite schema is incomplete or noncanonical for ${e}: ${n.join("; ")}; run openclaw doctor --fix to repair it.`); } //#endregion //#region src/state/openclaw-state-db-admission.ts function getStateSchemaFacts(e) { return isPostgresSqlConnection(e) ? getPostgresPhysicalFacts(e) : getAdmittedSqliteSchemaFacts(e); } const versionKey = { name: "state.schema-version", lifetime: "process", schemaDependent: true, read(e) { if (typeof e === "object" && e !== null && "userVersion" in e && typeof e.userVersion === "number" && "contentVersion" in e && typeof e.contentVersion === "number") return { userVersion: e.userVersion, contentVersion: e.contentVersion }; } }; /** Row-backed metadata is valid only for its admitted schema, even if replacement DDL has the same shape. */ function createStateSchemaAdmission(e, t, n) { const r = { name: e, lifetime: n, schemaDependent: true, read(e) { if (typeof e !== "object" || e === null || !("value" in e) || !("admissionId" in e) || typeof e.admissionId !== "string") return; const n = t(e.value); return n === void 0 ? void 0 : { value: n, admissionId: e.admissionId }; } }; return { get(e) { if (hasPendingSqliteDatabaseSchemaMutation(e)) return; const t = getSqliteDatabaseAdmission(e, r); if (!t) return; const n = getStateSchemaFacts(e); return t.admissionId === n?.admissionId ? t.value : void 0; }, publish(e, t) { if (!isPostgresSqlConnection(e) && isSqliteSchemaAdmissionCold(e)) admitSqliteSchema(e); const n = getStateSchemaFacts(e); if (!n || !isPostgresSqlConnection(e) && getSqliteDatabaseAdmission(e, schemaAdmission)?.admissionId !== n.admissionId) return; getStateSchemaVersionAdmission(e); const i = { value: t, admissionId: n.admissionId }; publishSqliteDatabaseAdmission(e, r, i); } }; } const runtimeAdmission = createStateSchemaAdmission("state.runtime-schema", (e) => typeof e === "object" && e !== null && "startupReady" in e && typeof e.startupReady === "boolean" ? { startupReady: e.startupReady } : void 0, "process"); const connectionVersions = /* @__PURE__ */ new WeakMap(); function rememberConnectionVersion(e, t) { const n = connectionVersions.get(e); const install = (t) => { if (t) connectionVersions.set(e, t); else connectionVersions.delete(e); }; if (!stageSqliteTransactionState(e, { stage: () => install(t), commit: () => {}, rollback: () => install(n) })) install(t); } function schemaVersionKey(e) { return { name: `state.schema-version:${e}`, read: versionKey.read }; } function getStateSchemaVersionAdmission(e) { const t = getStateSchemaFacts(e); if (!t) return; const n = connectionVersions.get(e); if (n?.schema === t) return n.facts; const r = getSqliteDatabaseAdmission(e, schemaVersionKey(t.admissionId)); const i = r ? void 0 : getSqliteDatabaseAdmission(e, schemaAdmission); if (!r && !isPostgresSqlConnection(e) && i?.admissionId !== t.admissionId) return; const a = r ?? getSqliteDatabaseAdmission(e, versionKey); if (a) { rememberConnectionVersion(e, { schema: t, facts: a }); if (!r) publishSqliteDatabaseAdmission(e, schemaVersionKey(t.admissionId), a); } return a; } /** A cold snapshot may discover historical facts without replacing a newer publication. */ function rememberStateSchemaVersionAdmission(e, t) { const n = getStateSchemaFacts(e); if (!n) return; rememberConnectionVersion(e, { schema: n, facts: t }); const r = getSqliteDatabaseAdmission(e, schemaAdmission); if (!isPostgresSqlConnection(e) && r?.admissionId !== n.admissionId) return; publishSqliteDatabaseAdmission(e, schemaVersionKey(n.admissionId), t); publishSqliteDatabaseAdmission(e, versionKey, t); } function publishStateSchemaVersionAdmission(e, t) { publishSqliteDatabaseAdmission(e, versionKey, t); const n = getStateSchemaFacts(e); if (n) { rememberConnectionVersion(e, { schema: n, facts: t }); publishSqliteDatabaseAdmission(e, schemaVersionKey(n.admissionId), t); } else rememberConnectionVersion(e); } /** * A peer process (the Gateway's update-run watcher) may publish the deferred * 2026.9.2 schema version after this connection admitted its floor. Adopt it * only when the header and metadata both read current inside this connection. */ function adoptPeerPublishedStateSchemaVersion(e, t) { if (t?.schema_version !== 36 || readSqliteUserVersion(e) !== 36) return false; publishStateSchemaVersionAdmission(e, { userVersion: 36, contentVersion: 36 }); return true; } /** Runtime shape and integrity are physical-file facts, independent of live write authority. */ function getStateRuntimeSchemaAdmission(e) { return runtimeAdmission.get(e); } function publishStateRuntimeSchemaAdmission(e, t) { runtimeAdmission.publish(e, { startupReady: t }); } //#endregion //#region src/state/openclaw-state-db-schema-helpers.ts const tableColumns = /* @__PURE__ */ new WeakMap(); function readCanonicalTableDefinition(e, t) { if (!/^CREATE TABLE\b/iu.test(e) || hasUnquotedSqlKeyword(e, /\bAS\b/giu)) return; const n = parseSqliteTableDefinition(e, t); return [...n.columns.values()].every((e) => { const t = readSqlToken(e, 0); return t?.keyword !== "CONSTRAINT" && /^[a-z_][a-z0-9_]*$/u.test(t?.raw ?? ""); }) ? n : void 0; } function tableHasColumn(e, t, n) { return readTableColumns(e, t).has(n); } function readTableColumns(e, t) { if (isPostgresSqlConnection(e)) return new Set(getPostgresPhysicalFacts(e)?.catalog.flatMap((e) => e.table === t && e.kind === "column" && e.value && typeof e.value === "object" && "name" in e.value && typeof e.value.name === "string" ? [e.value.name] : []) ?? []); const n = getAdmittedSqliteSchemaFacts(e); const r = n?.tableSql.get(t); if (n && !r && ![...n.tables, ...n.views].some((e) => e.toLowerCase() === t.toLowerCase())) return /* @__PURE__ */ new Set(); if (n && r) { let e = tableColumns.get(n); const i = e?.get(t); if (i) return i; const a = readCanonicalTableDefinition(r, t); if (a) { const r = new Set(a.columns.keys()); if (!e) { e = /* @__PURE__ */ new Map(); tableColumns.set(n, e); } e.set(t, r); return r; } } const i = e.prepare(`PRAGMA table_info(${t})`).all(); return new Set(i.flatMap((e) => typeof e.name === "string" ? [e.name] : [])); } /** Inspect only failed queries; native unavailability must not become a schema refusal. */ function classifySqliteTableReadError(e, t, n, r) { if (isPostgresSqlConnection(e)) return r; if (sqlitePrimaryResultCode(r) !== 1) return r; try { const i = readTableColumns(e, t); if (i.size > 0 && n.some((e) => !i.has(e))) return new SqliteSchemaMismatchError(`SQLite table ${t} is missing required columns; run openclaw doctor --fix to repair it.`, { cause: r }); } catch {} return r; } function tablePrimaryKeyColumns(e, t) { if (isPostgresSqlConnection(e)) { const n = getPostgresPhysicalFacts(e)?.catalog.find((e) => e.table === t && e.kind === "primaryKey")?.value; return Array.isArray(n) ? n.filter((e) => typeof e === "string") : []; } const n = getAdmittedSqliteSchemaFacts(e)?.tableSql.get(t); const r = n && readCanonicalTableDefinition(n, t); if (r) { const e = r.constraints.find((e) => { const t = readSqlToken(e, 0); return t && readTableConstraintKeyword(e, t) === "PRIMARY"; }); if (!e) return [...r.columns].flatMap(([e, t]) => hasUnquotedSqlKeyword(t, /\bPRIMARY\s+KEY\b/giu) ? [e] : []); const t = findSqlCharacter(e, "("); const n = splitSqlList(e.slice(t + 1, findSqlClosingParenthesis(e, t))).map((e) => normalizeSqlIdentifier(readSqlToken(e, 0)?.raw ?? "")); if (n.every((e) => r.columns.has(e))) return [...new Set(n)]; } return e.prepare(`PRAGMA table_info(${t})`).all().filter((e) => Number(e.pk ?? 0) > 0 && typeof e.name === "string").toSorted((e, t) => Number(e.pk ?? 0) - Number(t.pk ?? 0)).map((e) => e.name); } function tableExists(e, t) { if (isPostgresSqlConnection(e)) return getPostgresPhysicalFacts(e)?.catalog.some((e) => e.table === t && e.kind === "table") ?? false; const n = getAdmittedSqliteSchemaFacts(e); if (n) return n.tables.has(t); return executeWithCachedStatement(e, "SELECT 1 AS ok FROM sqlite_master WHERE type = 'table' AND name = ?", [t], (e) => e.get(t))?.ok === 1; } function ensureColumn(e, t, n) { const r = n.trim().split(/\s+/, 1)[0]; if (!r || !tableExists(e, t) || tableHasColumn(e, t, r)) return false; e.exec(`ALTER TABLE ${t} ADD COLUMN ${n};`); return true; } //#endregion export { iterateSqliteQuerySync as C, getNodeSqliteKysely as S, throwSqliteSchemaMismatches as _, tableHasColumn as a, executeSqliteQuerySync as b, createStateSchemaAdmission as c, publishStateRuntimeSchemaAdmission as d, publishStateSchemaVersionAdmission as f, legacySqliteSchemaIssueMessages as g, createSqliteSchemaIssue as h, tableExists as i, getStateRuntimeSchemaAdmission as l, SqliteSchemaMismatchError as m, ensureColumn as n, tablePrimaryKeyColumns as o, rememberStateSchemaVersionAdmission as p, readTableColumns as r, adoptPeerPublishedStateSchemaVersion as s, classifySqliteTableReadError as t, getStateSchemaVersionAdmission as u, compileSqliteQueryBindings as v, prepareSqliteQuerySync as w, executeSqliteQueryTakeFirstSync as x, createSqliteQueryCache as y };