UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

844 lines (843 loc) • 26.1 kB
import { a as asOptionalRecord } from "./record-coerce-CVPuDqcc.mjs"; import { i as withEngineStoreAdmission } from "./admission-scope-DmxaPNhm.mjs"; import { _t as parseSqliteTableDefinition, ut as FIRST_USE_ADDITIVE_AGENT_COLUMN_DEFINITIONS } from "./sqlite-database-admission-DQIqro3d.mjs"; import { c as normalizeSqlWhitespace, o as normalizeSchemaSql, u as readSqlToken } from "./sqlite-schema-sql-CPyk_2Hd.mjs"; import { t as OPENCLAW_AGENT_SCHEMA_SQL } from "./openclaw-agent-schema-BDRJZxWF.mjs"; import { t as OPENCLAW_AGENT_SCHEMA_VERSION } from "./openclaw-schema-versions-E_10NoI6.mjs"; import { t as _usingCtx } from "./usingCtx-rhpPzaNq.mjs"; import { a as executeSqliteQueryTakeFirstSync, i as executeSqliteQuerySync, s as getNodeSqliteKysely } from "./kysely-sync-YJo2lmGV.mjs"; import { B as pgSearchName, V as postgresSearchSql, o as getAdmittedSqliteSchemaFacts, t as admitSqliteSchema } from "./sqlite-schema-facts-B1bVE8IB.mjs"; import { n as ensureColumn } from "./openclaw-state-db-schema-helpers-nImZNMq_.mjs"; import { n as openNodeSqliteDatabase } from "./node-sqlite-CU4puofF.mjs"; import { r as readExistingAgentSchemaMeta } from "./openclaw-agent-db-metadata-C3YvwHLh.mjs"; import { a as runSqliteImmediateTransactionSync } from "./sqlite-transaction-BHHu6P5-.mjs"; import { n as resolveDatabaseFamilyEngines } from "./registry-Dd7FIY0t.mjs"; import { a as withDatabaseEngineSelection } from "./context-DE59wyBs.mjs"; import { n as withLegacyPostgresIndexOrdering } from "./postgres-index-ordering-CLLgXtNR.mjs"; import "./openclaw-agent-db-contract-aCH9b8Uc.mjs"; import { t as MEMORY_PATH_POSTGRES_INDEXES } from "./memory-path-postgres-BFFUO8hg.mjs"; import { _ as withoutAgentPostgresColdArchiveChunks, p as withLegacyAgentPostgresIndexes, r as withLegacyAgentPostgresTrajectoryStorage, s as LEGACY_MEMORY_REVISION_SQLITE_TRIGGERS, u as withLegacyAgentPostgresMemoryRevisionTriggers } from "./openclaw-agent-trajectory-storage-migration-BbWlWZSu.mjs"; import { i as assertSupportedAgentSchemaVersion, r as assertExistingAgentSchemaOwner } from "./openclaw-agent-db-schema-read-U5-_81Kg.mjs"; import { a as agentSearchPostgresRuntime, i as openAgentEngineStore, o as agentPostgresRuntime, r as agentEngineSchema, s as withLegacyAgentPostgresMemoryPaths } from "./openclaw-agent-db-engine-CFD02117.mjs"; import { t as agentTranscriptSearchSchema } from "./openclaw-agent-search-schema-Cl1T033f.mjs"; import { r as withLegacyAgentPostgresWriteLayout } from "./openclaw-agent-write-layout-migration-BPVNzU5a.mjs"; import { _ as runWithAgentDatabaseMaintenanceAuthority } from "./openclaw-agent-db-lease-BZhGt_sk.mjs"; import { c as memoryVectorSearchSchema, f as MEMORY_EMBEDDING_CACHE_TABLE, m as MEMORY_INDEX_META_TABLE, o as memoryStandingIntentSearchSchema, p as MEMORY_INDEX_DERIVED_TABLES, s as memoryTextSearchSchema } from "./memory-schema-B3FrMV9P.mjs"; import { t as AGENT_SCHEMA_COMPATIBILITY } from "./openclaw-agent-db-schema-compatibility-DMUbFiMM.mjs"; import { _ as getOpenClawAgentMigrationSchema } from "./openclaw-agent-progress-card-schema-CDOtPrpA.mjs"; import { a as assertOpenClawAgentSchemaContains, l as hasPendingCurrentVersionAgentDatabaseMigration } from "./openclaw-agent-outbox-sequence-migration-ATXcQD7n.mjs"; import { r as ensureOpenClawAgentDatabaseSchema } from "./openclaw-agent-db-schema-D-iWGl31.mjs"; import { _ as deriveTranscriptPredicateFields } from "./transcript-payload-Cb_Kmk8c.mjs"; import { n as readTranscriptPayload } from "./transcript-payload-read-Dd5D3FtH.mjs"; import { n as createSessionTranscriptFtsInserter, t as compilePostgresSessionTranscriptFtsBatch } from "./session-transcript-fts-DXZZeRW9.mjs"; import { a as prepareProjectionSource, o as prepareSessionTranscriptProjection, t as appendPreparedSessionTranscriptProjectionChunkInTransaction } from "./session-transcript-projection-rebuild-DeaQDPf4.mjs"; import { n as readTrajectoryPayload } from "./runtime-payload-DYnkaQPI.mjs"; import { t as DatabasePortDataError } from "./postgres-store-metadata-CcC14HrG.mjs"; import { r as pendingSqliteColumns } from "./port-descriptor-r7GHhJnm.mjs"; import { t as LEGACY_USAGE_COST_PARTITION_SCOPE } from "./session-cost-usage-partitions-Cufq4L2k.mjs"; import { t as minimumPostgresVersion } from "./manifest-UBZgCo-o.mjs"; import { isDeepStrictEqual } from "node:util"; //#region src/state/postgres-schema.generated/agent-port.json var tables = [ { "name": "acp_parent_stream_events", "identities": [] }, { "name": "auth_profile_state", "identities": [] }, { "name": "auth_profile_store", "identities": [] }, { "name": "board_tabs", "identities": [] }, { "name": "board_widgets", "identities": [] }, { "name": "cache_entries", "identities": [] }, { "name": "context_engine_turn_outbox", "identities": [{ "column": "enqueue_sequence", "autoIncrement": false }] }, { "name": "conversation_deliveries", "identities": [] }, { "name": "conversations", "identities": [] }, { "name": "heartbeat_outcomes", "identities": [] }, { "name": "memory_embedding_cache", "identities": [] }, { "name": "memory_entry_origins", "identities": [] }, { "name": "memory_index_chunk_provenance", "identities": [] }, { "name": "memory_index_chunk_recall_metadata", "identities": [] }, { "name": "memory_index_chunks", "identities": [{ "column": "chunk_rowid", "autoIncrement": false }] }, { "name": "memory_index_meta", "identities": [] }, { "name": "memory_index_sources", "identities": [{ "column": "id", "autoIncrement": false }] }, { "name": "memory_index_state", "identities": [{ "column": "id", "autoIncrement": false }] }, { "name": "memory_session_tombstones", "identities": [] }, { "name": "message_tool_run_outcomes", "identities": [{ "column": "id", "autoIncrement": false }] }, { "name": "schema_meta", "identities": [] }, { "name": "session_canonical_validation_pending", "identities": [] }, { "name": "session_conversations", "identities": [] }, { "name": "session_entry_snapshots", "identities": [] }, { "name": "session_goal_operations", "identities": [] }, { "name": "session_input_completions", "identities": [] }, { "name": "session_key_contract", "identities": [{ "column": "id", "autoIncrement": false }] }, { "name": "session_members", "identities": [] }, { "name": "session_nodes", "identities": [] }, { "name": "session_participants", "identities": [] }, { "name": "session_pending_inputs", "identities": [{ "column": "seq", "autoIncrement": true }] }, { "name": "session_progress_cards", "identities": [] }, { "name": "session_reactions", "identities": [] }, { "name": "session_suggestions", "identities": [] }, { "name": "session_transcript_active_events", "identities": [] }, { "name": "session_transcript_archives", "identities": [] }, { "name": "session_transcript_cold_archive_chunks", "identities": [] }, { "name": "session_transcript_cold_archives", "identities": [] }, { "name": "session_transcript_fts_rows", "identities": [{ "column": "id", "autoIncrement": false }] }, { "name": "session_transcript_index_state", "identities": [] }, { "name": "session_windows", "identities": [] }, { "name": "standing_intents", "identities": [{ "column": "intent_key", "autoIncrement": false }] }, { "name": "trajectory_runtime_events", "identities": [] }, { "name": "transcript_event_identities", "identities": [] }, { "name": "transcript_events", "identities": [] }, { "name": "transcript_rewrite_watermarks", "identities": [] } ]; var sqliteTables = [ { "name": "session_transcript_fts_content", "columns": [ { "name": "id", "type": "INTEGER" }, { "name": "c0", "type": "" }, { "name": "c1", "type": "" }, { "name": "c2", "type": "" }, { "name": "c3", "type": "" }, { "name": "c4", "type": "" } ], "pk": [], "identities": [] }, { "name": "session_transcript_fts", "columns": [ { "name": "text", "type": "" }, { "name": "session_id", "type": "" }, { "name": "message_id", "type": "" }, { "name": "role", "type": "" }, { "name": "timestamp", "type": "" } ], "pk": [], "identities": [] }, { "name": "session_transcript_fts_idx", "columns": [ { "name": "segid", "type": "" }, { "name": "term", "type": "" }, { "name": "pgno", "type": "" } ], "pk": [], "identities": [] }, { "name": "standing_intents_fts_config", "columns": [{ "name": "k", "type": "" }, { "name": "v", "type": "" }], "pk": [], "identities": [] }, { "name": "standing_intents_fts_docsize", "columns": [{ "name": "id", "type": "INTEGER" }, { "name": "sz", "type": "BLOB" }], "pk": [], "identities": [] }, { "name": "standing_intents_fts_idx", "columns": [ { "name": "segid", "type": "" }, { "name": "term", "type": "" }, { "name": "pgno", "type": "" } ], "pk": [], "identities": [] }, { "name": "standing_intents_fts_data", "columns": [{ "name": "id", "type": "INTEGER" }, { "name": "block", "type": "BLOB" }], "pk": [], "identities": [] }, { "name": "standing_intents_fts", "columns": [{ "name": "trigger_keywords", "type": "" }], "pk": [], "identities": [] }, { "name": "session_transcript_fts_docsize", "columns": [{ "name": "id", "type": "INTEGER" }, { "name": "sz", "type": "BLOB" }], "pk": [], "identities": [] }, { "name": "session_transcript_fts_config", "columns": [{ "name": "k", "type": "" }, { "name": "v", "type": "" }], "pk": [], "identities": [] }, { "name": "session_transcript_fts_data", "columns": [{ "name": "id", "type": "INTEGER" }, { "name": "block", "type": "BLOB" }], "pk": [], "identities": [] } ]; var triggers = [ { "name": "session_conversations_route_context_invalidate_after_update", "table": "session_conversations", "range": [10313, 10696] }, { "name": "session_entry_snapshots_after_delete", "table": "session_entry_snapshots", "range": [2884, 3108] }, { "name": "session_entry_snapshots_after_insert", "table": "session_entry_snapshots", "range": [2262, 2486] }, { "name": "session_entry_snapshots_after_update", "table": "session_entry_snapshots", "range": [2488, 2882] }, { "name": "session_transcript_fts_rows_after_delete", "table": "session_transcript_fts_rows", "range": [32173, 32356] }, { "name": "standing_intents_fts_after_delete", "table": "standing_intents", "range": [29713, 29960] }, { "name": "standing_intents_fts_after_insert", "table": "standing_intents", "range": [29496, 29711] }, { "name": "standing_intents_fts_after_update", "table": "standing_intents", "range": [29962, 30338] } ]; var preData = [0, 30229]; var postData = [30229, 45975]; //#endregion //#region src/infra/database-engine/agent-port-projections.ts const AGENT_PORT_PROJECTION_TABLES = [ "session_transcript_active_events", "session_transcript_fts_rows", "session_transcript_fts", "session_transcript_index_state", "standing_intents_fts", ...MEMORY_INDEX_DERIVED_TABLES.filter((e) => e !== "memory_embedding_cache" && e !== "memory_index_meta" && e !== "memory_index_chunks") ]; /** Reuse the transcript owner's branch and eligibility policy on the private port target. */ async function rebuildAgentPortProjections(e) { const t = e.engine === "sqlite" ? e.db.prepare("SELECT session_id FROM session_windows ORDER BY session_id").all() : (await e.db.query(`SELECT session.session_id, session.transcript_updated_at, rewrite.generation FROM session_windows AS session LEFT JOIN transcript_rewrite_watermarks AS rewrite ON rewrite.session_id = session.session_id ORDER BY session.session_id`)).rows; for (const n of t) { const t = String(n.session_id); let r; if (e.engine === "sqlite") r = prepareSessionTranscriptProjection(e.db, t); else { const i = (await e.db.query("SELECT event_json, seq, created_at FROM transcript_events WHERE session_id = $1 ORDER BY seq", [t])).rows.map((e) => ({ event_json: e.event_json, seq: Number(e.seq), created_at: Number(e.created_at) })); const a = new Map(i.map((e) => [e.seq, e])); r = prepareProjectionSource({ sessionId: t, transcriptGeneration: String(n.generation ?? "") || null, transcriptUpdatedAt: n.transcript_updated_at == null ? null : Number(n.transcript_updated_at), rows: () => i, row: (e) => a.get(e) }); } if (!r) continue; if (e.engine === "sqlite") { appendPreparedSessionTranscriptProjectionChunkInTransaction(e.db, { sessionId: t, activeRows: r.activeRows }); const n = createSessionTranscriptFtsInserter(e.db, t); for (const e of r.ftsRows) n([e]); } else { for (const n of r.activeRows) await e.db.query(`INSERT INTO session_transcript_active_events (session_id, active_position, event_seq, message_position, context_eligible) VALUES ($1, $2, $3, $4, $5)`, [ t, n.activePosition, n.eventSeq, n.messagePosition, n.contextEligible ]); let n = []; const flush = async () => { if (n.length === 0) return; const r = compilePostgresSessionTranscriptFtsBatch(t, n); n = []; await e.db.query(r.sql, [...r.parameters]); }; for (const e of r.ftsRows) { n.push(e); if (n.length === 512) await flush(); } await flush(); } const i = [ t, r.sourceIndexedSeq, r.leafEventId, r.activeEventCount, r.activeMessageCount, Date.now() ]; const a = `INSERT INTO session_transcript_index_state (session_id, indexed_seq, leaf_event_id, needs_rebuild, active_event_count, active_message_count, updated_at) VALUES ($1, $2, $3, 0, $4, $5, $6)`; if (e.engine === "sqlite") e.db.prepare(a.replace(/\$\d+/g, "?")).run(...i); else await e.db.query(a, i); } const n = "INSERT INTO memory_index_state (id, revision) VALUES (1, 0) ON CONFLICT (id) DO NOTHING"; if (e.engine === "sqlite") e.db.exec(`${n}; INSERT INTO standing_intents_fts(standing_intents_fts) VALUES ('rebuild')`); else await e.db.query(n); } //#endregion //#region src/infra/database-engine/agent-port-descriptor.ts function hasRetiredRecoveryColumn(e) { admitSqliteSchema(e); const t = getAdmittedSqliteSchemaFacts(e)?.tableSql.get("session_pending_inputs"); if (!t) return false; const n = parseSqliteTableDefinition(t, "session_pending_inputs").columns.get("recovery_intent_json"); const r = n && readSqlToken(n, 0); if (!n || !r) return false; return AGENT_SCHEMA_COMPATIBILITY.allowedColumnDefinitions["session_pending_inputs.recovery_intent_json"].some((e) => { const t = readSqlToken(e, 0); return t && normalizeSqlWhitespace(e.slice(t.end)).toUpperCase() === normalizeSqlWhitespace(n.slice(r.end)).toUpperCase(); }); } const agentSourceSearchPostData = async (e) => { const t = (await e.db.query(`SELECT to_jsonb(meta) AS metadata FROM ${pgSearchName(e.namespace)}.openclaw_schema_meta AS meta WHERE store = 'agent'`)).rows[0]; let n; try { n = JSON.parse(t?.metadata.search_extensions ?? "{}"); } catch { throw new DatabasePortDataError("Malformed agent search-extension metadata"); } const r = asOptionalRecord(n); if (!r) throw new DatabasePortDataError("Invalid agent search-extension metadata"); const i = []; for (const [e, t] of Object.entries(r)) { const n = asOptionalRecord(t); let r; if (e === "memory.text") { const e = asOptionalRecord(asOptionalRecord(n?.text)?.body); const t = asOptionalRecord(e?.postgres)?.mode; r = memoryTextSearchSchema(t === "trigram" ? "trigram" : "unicode61"); } else if (e === "memory.standing-intents") r = memoryStandingIntentSearchSchema; else if (e === "memory.vector") { const e = asOptionalRecord(asOptionalRecord(n?.vector)?.chunks); const t = asOptionalRecord(e?.postgres)?.dimensions; if (typeof t === "number" && Number.isInteger(t) && t >= 1 && t <= 16e3) r = memoryVectorSearchSchema(t); } if (!r || !isDeepStrictEqual(t, r)) throw new DatabasePortDataError("Unknown or changed agent search extension; matching memory owner required"); i.push(r); } if (!i.length) return; return (e) => { const n = { text: true, vector: false }; return i.map((r) => { const i = postgresSearchSql(r, e, n, t.metadata.version >= 32 ? 2 : 1, t.metadata.version >= 33 ? 2 : 1, t.metadata.version >= 38 ? 2 : 1); n.vector ||= Object.keys(r.vector ?? {}).length > 0; return i; }).join("\n;\n"); }; }; async function loadAgentPortDescriptor(e = agentEngineSchema.version) { if (e !== agentEngineSchema.version) { const t = agentEngineSchema.postgresMigrations?.find((t) => t.version === e + 1)?.backup; if (t?.version === e && t.id === "agent") return t; if (t || 38 !== 38 || ![ 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37 ].includes(e)) throw new DatabasePortDataError(`Missing agent PostgreSQL backup descriptor for version ${e}`); } const isColumn = (e) => e.kind === "column"; const t = e !== agentEngineSchema.version; const n = e < 37; const r = e < 30; const i = agentPostgresRuntime.expectedCatalog.filter((e) => !(n && e.table === "session_transcript_cold_archive_chunks") && (!r || e.table !== "trajectory_runtime_events" || !isColumn(e) || ![ "event_utf8_bytes", "event_payload", "event_codec" ].includes(e.value.name))); const a = i.filter(isColumn); const o = i.filter((e) => e.kind === "primaryKey"); const s = { id: "agent", version: 38, minimumPostgresVersion, sqlite: OPENCLAW_AGENT_SCHEMA_SQL.replace(/^INSERT OR IGNORE INTO[^;]+;/gm, ""), tables: [...tables.filter(({ name: e }) => !(n && e === "session_transcript_cold_archive_chunks")).map(({ name: e, identities: t }) => ({ name: e, identities: t, columns: a.filter((t) => t.table === e).map((e) => ({ name: e.value.name, type: e.value.type })), pk: o.find((t) => t.table === e)?.value ?? [] })), ...sqliteTables], triggers: triggers.map(({ name: e, table: t, range: n }) => ({ name: e, table: t, sql: OPENCLAW_AGENT_SCHEMA_SQL.slice(n[0], n[1]).replace("IF NOT EXISTS ", "").replace(/;$/, "") })), preData: agentPostgresRuntime.sql.slice(...preData) + agentSearchPostgresRuntime.sql, omittedSqliteTriggers: AGENT_SCHEMA_COMPATIBILITY.optionalCanonicalTriggerGroups.flatMap((e) => e.triggers.map((t) => ({ name: t.name, table: e.tableName, sql: normalizeSchemaSql(t.sql.replace("main.", "")) }))), postData: `DO $voice$ DECLARE cache_key text; BEGIN SELECT key INTO cache_key FROM cache_entries WHERE scope = 'talk-client-voice-sessions' AND value_json IS JSON AND NOT (value_json IS JSON WITH UNIQUE KEYS) LIMIT 1; IF FOUND THEN RAISE EXCEPTION 'Agent port refused duplicate-key voice JSON; cache key SHA-256 %', encode(sha256(convert_to(cache_key, 'UTF8')), 'hex') USING HINT = 'Repair through the voice store owner.'; END IF; END $voice$;\n` + agentPostgresRuntime.sql.slice(...postData), postgresPostData: (t) => postgresSearchSql(agentTranscriptSearchSchema, t, {}, 1, 1, e >= 38 ? 2 : 1), postgresSourcePostData: agentSourceSearchPostData, postgresDerivedTables: ["session_transcript_fts"], expectedCatalog: i, projections: [{ tables: [ ...AGENT_PORT_PROJECTION_TABLES, ...sqliteTables.map((e) => e.name), ...AGENT_PORT_PROJECTION_TABLES.flatMap((e) => [ "_data", "_idx", "_content", "_docsize", "_config", "_info", "_chunks", "_rowids", "_vector_chunks00" ].map((t) => e + t)) ], rebuild: rebuildAgentPortProjections }], decodeSqlite: { trajectory_runtime_events(e) { if (e.event_codec == null) return e; if (!(e.event_payload instanceof Uint8Array) || typeof e.event_codec !== "string") throw new DatabasePortDataError("Invalid compressed trajectory payload"); return { ...e, event_json: readTrajectoryPayload({ event_json: "", event_payload: e.event_payload, event_codec: e.event_codec, event_utf8_bytes: Number(e.event_utf8_bytes) }), event_payload: null, event_codec: null }; }, transcript_events(e) { let t = e; if (e.event_zstd != null) { if (!(e.event_zstd instanceof Uint8Array)) throw new DatabasePortDataError("Invalid compressed transcript payload"); t = { ...e, event_json: readTranscriptPayload({ event_json: null, event_zstd: e.event_zstd, event_utf8_bytes: Number(e.event_utf8_bytes) }), event_zstd: null }; } return t.navigation_type == null && t.navigation_valid !== 0 && t.navigation_valid !== 0n && typeof t.event_json === "string" ? { ...t, ...deriveTranscriptPredicateFields(t.event_json) } : t; } }, inspectSqliteSource(e) { admitSqliteSchema(e); const t = readExistingAgentSchemaMeta(e); if (!t?.agentId) throw new DatabasePortDataError("Agent port requires schema ownership metadata"); assertExistingAgentSchemaOwner(t, t.agentId, "agent port source"); const n = assertSupportedAgentSchemaVersion(e, "agent port source"); if (t.schemaVersion !== n) throw new DatabasePortDataError("Agent schema markers disagree; run openclaw doctor --fix before porting"); const r = assertOpenClawAgentSchemaContains(e, "agent port source", getOpenClawAgentMigrationSchema(n), n < 23 ? "legacy" : "current", true); const i = executeSqliteQueryTakeFirstSync(e, getNodeSqliteKysely(e).selectFrom("cache_entries").select("scope").where("scope", "=", LEGACY_USAGE_COST_PARTITION_SCOPE).limit(1)); return { version: n, migrationRequired: n !== 38 || r || Boolean(i) || hasRetiredRecoveryColumn(e) || hasPendingCurrentVersionAgentDatabaseMigration(e), pendingColumns: pendingSqliteColumns(e, FIRST_USE_ADDITIVE_AGENT_COLUMN_DEFINITIONS), pendingTables: AGENT_SCHEMA_COMPATIBILITY.allowedMissingTables.filter((t) => s.tables.some((e) => e.name === t) && !getAdmittedSqliteSchemaFacts(e)?.tables.has(t)) }; }, async migrateSqliteSource(e, t, n) { try { var r = _usingCtx(); const t = r.u(openNodeSqliteDatabase(e)); const i = readExistingAgentSchemaMeta(t)?.agentId; if (!i) throw new DatabasePortDataError("Private agent copy has no owner"); await withDatabaseEngineSelection({ effectiveEngines: resolveDatabaseFamilyEngines({ database: { engine: "sqlite" } }) }, () => runWithAgentDatabaseMaintenanceAuthority({ signal: new AbortController().signal, assertCurrent: n, assertOwned: n, assertOwnedInTransaction: n, renew: n }, e, async () => { ensureOpenClawAgentDatabaseSchema(t, { agentId: i, register: false }); for (const { tableName: e, columnName: n, dataType: r } of FIRST_USE_ADDITIVE_AGENT_COLUMN_DEFINITIONS) ensureColumn(t, e, `${n} ${r}`); runSqliteImmediateTransactionSync(t, () => { n(); if (hasRetiredRecoveryColumn(t)) t.exec("ALTER TABLE session_pending_inputs DROP COLUMN recovery_intent_json"); t.exec(s.sqlite); }); executeSqliteQuerySync(t, getNodeSqliteKysely(t).deleteFrom("cache_entries").where("scope", "=", LEGACY_USAGE_COST_PARTITION_SCOPE)); })); } catch (e) { r.e = e; } finally { r.d(); } }, async admit(e, t) { withDatabaseEngineSelection({ effectiveEngines: resolveDatabaseFamilyEngines({ database: { engine: t ? "postgres" : "sqlite" } }), postgres: t }, () => withEngineStoreAdmission(() => { try { var n = _usingCtx(); const r = n.u(openNodeSqliteDatabase(e)); if (t) { const t = openAgentEngineStore(r, void 0, e, true); if (t !== r) t.close(); } else { if (!readExistingAgentSchemaMeta(r)?.agentId) throw new DatabasePortDataError("Restored agent has no owner"); assertOpenClawAgentSchemaContains(r, e, OPENCLAW_AGENT_SCHEMA_SQL); } } catch (e) { n.e = e; } finally { n.d(); } })); } }; if (!t) return s; const c = e < 31; const withoutLegacyColdArchive = (e) => n ? withoutAgentPostgresColdArchiveChunks(e) : e; let l = c ? withLegacyAgentPostgresMemoryRevisionTriggers(s.postData) : s.postData; if (e < 36) l = withLegacyAgentPostgresMemoryPaths(l); if (e < 35) l = withLegacyPostgresIndexOrdering(l, e === 34 ? "schema-nullability" : "sqlite", s.preData); if (r) l = withLegacyAgentPostgresTrajectoryStorage(l); if (e < 29) l = withLegacyAgentPostgresIndexes(l); if (e < 28) l = withLegacyAgentPostgresWriteLayout(l); return { ...s, version: e, sqlite: getOpenClawAgentMigrationSchema(e).replace(/^INSERT OR IGNORE INTO[^;]+;/gm, ""), triggers: [...s.triggers ?? [], ...c ? LEGACY_MEMORY_REVISION_SQLITE_TRIGGERS.map((e) => ({ name: e.name, table: e.table, sql: e.sql.replace("IF NOT EXISTS ", "").replace(/;$/, "") })) : []], preData: withoutLegacyColdArchive(r ? withLegacyAgentPostgresTrajectoryStorage(s.preData) : s.preData), postData: withoutLegacyColdArchive(l), expectedCatalog: i.map((t) => e < 36 && t.kind === "indexes" && t.table === "memory_index_sources" ? { table: t.table, kind: t.kind, value: Number(t.value) - MEMORY_PATH_POSTGRES_INDEXES.length } : e < 29 && t.kind === "indexes" && (t.table === "session_nodes" || t.table === "session_reactions") ? { table: t.table, kind: t.kind, value: Number(t.value) + 1 } : e < 28 && t.table === "transcript_event_identities" && t.kind === "indexes" ? { table: t.table, kind: t.kind, value: 5 } : t), inspectSqliteSource: void 0, migrateSqliteSource: void 0, admit: void 0 }; } //#endregion export { loadAgentPortDescriptor };