UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

652 lines (651 loc) • 37.4 kB
import { l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs"; import { a as asOptionalRecord, l as isRecord } from "./record-coerce-CVPuDqcc.mjs"; import { n as safeParseJsonRecord } from "./json-coercion-CaJLaav-.mjs"; import { n as normalizeAgentId } from "./agent-id-CQjtp2ft.mjs"; import "./session-key-CqAyZeVk.mjs"; import { n as normalizeAccountId } from "./account-id-BqKT3GuY.mjs"; import { n as isPostgresSqlConnection } from "./sql-connection-Beiyg5Dt.mjs"; import { mt as hasPendingAgentStartupColumns, pt as STARTUP_ADDITIVE_AGENT_COLUMN_DEFINITIONS } from "./sqlite-database-admission-DQIqro3d.mjs"; import { t as extractSqliteTableSchema } from "./sqlite-schema-sql-CPyk_2Hd.mjs"; import { t as OPENCLAW_AGENT_SCHEMA_SQL } from "./openclaw-agent-schema-BDRJZxWF.mjs"; import { c as iterateSqliteQuerySync, i as executeSqliteQuerySync, s as getNodeSqliteKysely } from "./kysely-sync-YJo2lmGV.mjs"; import { _ as captureSqliteSchemaFacts, o as getAdmittedSqliteSchemaFacts } from "./sqlite-schema-facts-B1bVE8IB.mjs"; import { a as tableExists, c as SqliteSchemaMismatchError, d as legacySqliteSchemaIssueMessages, f as throwSqliteSchemaMismatches, n as ensureColumn, o as tableHasColumn } from "./openclaw-state-db-schema-helpers-nImZNMq_.mjs"; import { o as readSqliteUserVersion } from "./sqlite-user-version-C02a4KwH.mjs"; import { t as VERSION } from "./version-GlxUMdxI.mjs"; import { n as publishAgentSchemaMetadata, r as readExistingAgentSchemaMeta } from "./openclaw-agent-db-metadata-C3YvwHLh.mjs"; import { i as assertSqliteTableIntegrity } from "./sqlite-integrity-CCmEgO_m.mjs"; import { i as collectSqliteSchemaIssues, n as assertSqliteSchemaTablesPresent, o as getCanonicalSqliteNamedIndexNames, s as getCanonicalSqliteTableNames, t as assertSqliteSchemaContains } from "./sqlite-schema-contract-D3pR9vZs.mjs"; import { n as SESSION_PARTICIPANTS_TABLE } from "./openclaw-agent-db-contract-aCH9b8Uc.mjs"; import { b as repairCanonicalSqliteIndexes } from "./openclaw-state-db-ARhwdPJg.mjs"; import { t as createSqliteSchemaEnsurer } from "./sqlite-schema-ensure-B6yDrFvM.mjs"; import { n as assertCurrentAgentSchemaMetadata, r as assertExistingAgentSchemaOwner } from "./openclaw-agent-db-schema-read-U5-_81Kg.mjs"; import { y as hasLegacyMemoryRecallMetadataColumns } from "./memory-schema-B3FrMV9P.mjs"; import { t as AGENT_SCHEMA_COMPATIBILITY } from "./openclaw-agent-db-schema-compatibility-DMUbFiMM.mjs"; import { a as AGENT_V14_ADDITIVE_SCHEMA_SQL, c as AGENT_V14_SESSION_SHARING_SCHEMA_SQL, d as LEGACY_PARTICIPANTS_SCHEMA, f as LEGACY_PARTICIPANT_OPTIONAL_COLUMNS, i as AGENT_PROGRESS_CARD_SCHEMA_SQL, l as LEGACY_CANONICAL_VALIDATION_TRIGGER_NAMES, m as RETIRED_AGENT_STATE_LEASE_SCHEMA_SQL, n as AGENT_JSON_PREDICATE_COLUMNS, o as AGENT_V14_BOARD_SCHEMA_SQL, p as OPENCLAW_AGENT_BOARD_SCHEMA_SQL, r as AGENT_JSON_PREDICATE_COLUMN_DECLARATIONS, s as AGENT_V14_CORE_SCHEMA_SQL, t as ensureOpenClawAgentProgressCardSchemaInTransaction, u as LEGACY_ENTRY_VALIDITY_TRIGGERS_SQL, v as sessionParticipantsSchemaSql } from "./openclaw-agent-progress-card-schema-CDOtPrpA.mjs"; import { a as parseSqliteSessionEntryRecord } from "./session-entry-json-BctywCJg.mjs"; import { t as normalizeChatType } from "./chat-type-CL5nBDaO.mjs"; import { n as normalizeConversationPeerId, t as buildConversationRef } from "./conversation-ref-BiSqlOTe.mjs"; import { t as deriveSessionChatTypeFromKey } from "./session-chat-type-shared-BP82uKBg.mjs"; //#region src/state/openclaw-agent-board-schema.ts const BOARD_WIDGETS_SCHEMA_START = "CREATE TABLE IF NOT EXISTS board_widgets ("; const BOARD_WIDGETS_MIGRATION_TABLE = "board_widgets_plugin_kind_migration_new"; const PLUGIN_CONTENT_KIND_CLAUSE_PATTERN = /content_kind\s+IN\s*\(\s*'html'\s*,\s*'mcp-app'\s*,\s*'plugin'\s*\)/iu; const PLUGIN_PAYLOAD_BRANCH_PATTERN = /\s+OR\s+\(content_kind\s*=\s*'plugin'\s+AND\s+html\s+IS\s+NULL\s+AND\s+descriptor_json\s+IS\s+NOT\s+NULL\s+AND\s+view_generation\s+IS\s+NULL\)/iu; const ensureBoardTables = createSqliteSchemaEnsurer(() => OPENCLAW_AGENT_BOARD_SCHEMA_SQL, { tables: ["board_tabs", "board_widgets"], indexes: ["idx_agent_board_widgets_tab_position"] }); function canonicalBoardWidgetsCreateSql() { return extractSqliteTableSchema(OPENCLAW_AGENT_BOARD_SCHEMA_SQL, "board_widgets", { endMarker: "CREATE INDEX IF NOT EXISTS idx_agent_board_widgets_tab_position", includeEndMarker: false, errorMessage: "OpenClaw agent board widget schema markers are missing." }).trim(); } function legacyBoardWidgetsCreateSql() { const e = canonicalBoardWidgetsCreateSql(); const t = e.replace(PLUGIN_CONTENT_KIND_CLAUSE_PATTERN, "content_kind IN ('html', 'mcp-app')").replace(PLUGIN_PAYLOAD_BRANCH_PATTERN, ""); if (t === e) throw new Error("OpenClaw agent board widget legacy schema derivation failed."); return t; } function normalizeBoardWidgetsCreateSql(e) { return e.replace(/^CREATE TABLE(?: IF NOT EXISTS)?\s+(?:board_widgets|"board_widgets"|`board_widgets`|\[board_widgets\])\s*\(/iu, "CREATE TABLE board_widgets (").replace(/\s+/gu, " ").replace(/;\s*$/u, "").trim(); } /** Repair the v14 board constraint inside the caller's schema/write transaction. */ function ensureOpenClawAgentBoardSchemaInTransaction(e) { if (!e.isTransaction) throw new Error("board schema ensure requires an active transaction"); if (isPostgresSqlConnection(e)) return; ensureBoardTables(e); const t = getAdmittedSqliteSchemaFacts(e)?.tableSql.get("board_widgets") ?? e.prepare("SELECT sql FROM sqlite_schema WHERE type = 'table' AND name = 'board_widgets'").get()?.sql; if (typeof t !== "string") throw new Error("OpenClaw agent board widget schema is missing after ensure."); const n = normalizeBoardWidgetsCreateSql(t); if (n === normalizeBoardWidgetsCreateSql(canonicalBoardWidgetsCreateSql())) return; if (n !== normalizeBoardWidgetsCreateSql(legacyBoardWidgetsCreateSql())) throw new Error("OpenClaw agent board widget schema has an unsupported content-kind constraint."); if (e.prepare("SELECT 1 FROM sqlite_schema WHERE type = 'table' AND name = ?").get(BOARD_WIDGETS_MIGRATION_TABLE)) throw new Error(`OpenClaw agent board migration table already exists: ${BOARD_WIDGETS_MIGRATION_TABLE}`); const r = canonicalBoardWidgetsCreateSql().replace(BOARD_WIDGETS_SCHEMA_START, `CREATE TABLE ${BOARD_WIDGETS_MIGRATION_TABLE} (`); e.exec(` ${r} INSERT INTO ${BOARD_WIDGETS_MIGRATION_TABLE} ( session_key, name, tab_id, title, content_kind, html, descriptor_json, sha256, view_generation, revision, size_w, size_h, position, manifest, grant_state, granted_sha, created_by, created_at, updated_at ) SELECT session_key, name, tab_id, title, content_kind, html, descriptor_json, sha256, view_generation, revision, size_w, size_h, position, manifest, grant_state, granted_sha, created_by, created_at, updated_at FROM board_widgets; DROP TABLE board_widgets; ALTER TABLE ${BOARD_WIDGETS_MIGRATION_TABLE} RENAME TO board_widgets; `); e.exec(OPENCLAW_AGENT_BOARD_SCHEMA_SQL); } //#endregion //#region src/state/openclaw-agent-canonical-validation-migration.ts /** Legacy shape repair precedes the historical schema assertion during offline migration. */ function ensureLegacySessionEntryValidityTriggers(e) { e.exec(LEGACY_ENTRY_VALIDITY_TRIGGERS_SQL); } /** The offline schema owner retires raw-writer tracking before publishing schema 25. */ function migrateCanonicalSessionWriterValidation(e) { for (const t of LEGACY_CANONICAL_VALIDATION_TRIGGER_NAMES) e.exec(`DROP TRIGGER IF EXISTS ${t}`); ensureColumn(e, "session_key_contract", "canonical_ready TEXT"); e.exec(` INSERT INTO session_canonical_validation_pending (session_key) SELECT session_key FROM session_nodes WHERE true ON CONFLICT (session_key) DO NOTHING; UPDATE session_key_contract SET canonical_ready = NULL WHERE id = 1; `); } function seedCanonicalSessionValidationPending(e) { e.exec(` INSERT INTO session_canonical_validation_pending (session_key) SELECT node.session_key FROM session_nodes AS node WHERE NOT EXISTS ( SELECT 1 FROM session_canonical_validation_pending AS pending WHERE pending.session_key = node.session_key ); `); } //#endregion //#region src/state/openclaw-agent-db-metadata-write.ts function persistAgentSchemaMetadata(e, t, n) { const r = Date.now(); const i = { role: "agent", schema_version: n, agent_id: t, app_version: VERSION }; executeSqliteQuerySync(e, getNodeSqliteKysely(e).insertInto("schema_meta").values({ meta_key: "primary", ...i, created_at: r, updated_at: r }).onConflict((e) => e.column("meta_key").doUpdateSet({ ...i, updated_at: r }).where((e) => e.or([ e("schema_meta.schema_version", "!=", n), e("schema_meta.app_version", "is", null), e("schema_meta.app_version", "!=", VERSION), e("schema_meta.agent_id", "!=", t) ])))); publishAgentSchemaMetadata(e, { role: "agent", schemaVersion: n, agentId: t }); } //#endregion //#region src/state/creator-namespace-migration.ts /** Doctor and versioned upgrades alone may qualify historical creation seams. */ function migrateLegacySessionCreator(e) { const t = e; const n = e.createdActor ?? (isRecord(t.createdBy) ? { ...t.createdBy, type: "human", source: "unknown" } : void 0); if (n?.type !== "human") return e; const r = n.source === "profile" || n.source === "channel" || n.source === "unknown" ? n.source : e.createdVia === "operator" || e.createdVia === "run" ? "profile" : e.createdVia === "channel" ? "channel" : "unknown"; if (n === e.createdActor && r === n.source && !t.createdBy) return e; const i = { ...t, createdActor: { ...n, source: r } }; delete i.createdBy; return i; } //#endregion //#region src/state/openclaw-agent-db-session-migrations.ts function assertSupportedAgentMigrationSchemas(e, t, n) { if (n < 8 && [ "sessions", "session_entries", "transcript_events" ].some((t) => tableExists(e, t)) || tableExists(e, "session_transcript_files") || readSqliteTableColumns(e, "session_transcript_fts")?.has("session_key")) throw new SqliteSchemaMismatchError(`OpenClaw agent database ${t} contains an unreleased session schema (version ${n}). Preserve a complete copy of your state directory and configuration, including shared agent registration. Run "openclaw doctor --fix" with OpenClaw 2026.9.7 against that copy. If a store is held, follow Doctor's explicit agent-restoration instructions, then rerun Doctor before retrying the upgrade.`); const r = readSqliteTableColumns(e, "acp_parent_stream_events"); const i = readSqliteTableColumns(e, "trajectory_runtime_events"); const a = readSqliteTableColumns(e, "memory_index_sources"); if (r && !r.has("session_id") || i?.has("event_id") || a?.has("source_kind")) throw new SqliteSchemaMismatchError(`OpenClaw agent database ${t} has an unsupported legacy schema. Upgrades from pre-July-2026 state are no longer migrated; restore a backup produced by a July 2026 or newer release before retrying.`); } /** Backfill one generation token without copying or rewriting transcript rows. */ function migrateSessionTranscriptGenerations(e, t) { if (t >= 13) return; const n = e.prepare(`INSERT OR IGNORE INTO transcript_rewrite_watermarks (session_id, generation, updated_at) SELECT session_id, lower(hex(randomblob(16))), ? FROM transcript_events GROUP BY session_id`); n.setReadBigInts(true); n.run(Date.now()); } function migrateSessionTranscriptActiveProjection(e, t) { if (t >= 10) return; const n = readSqliteTableColumns(e, "session_transcript_index_state"); if (n && !n.has("active_event_count")) e.exec("ALTER TABLE session_transcript_index_state ADD COLUMN active_event_count INTEGER NOT NULL DEFAULT 0;"); if (n && !n.has("active_message_count")) e.exec("ALTER TABLE session_transcript_index_state ADD COLUMN active_message_count INTEGER NOT NULL DEFAULT 0;"); e.exec(` DELETE FROM session_transcript_active_events; UPDATE session_transcript_index_state SET needs_rebuild = 1, active_event_count = 0, active_message_count = 0, updated_at = ${Date.now()}; `); } function inferMigratedChatType(e) { const t = normalizeChatType(normalizeOptionalString(e.entry.chatType)) ?? normalizeChatType(e.persistedChatType); if (t) return t; const n = deriveSessionChatTypeFromKey(e.sessionKey); if (n !== "unknown") return n; const r = e.deliveryTarget?.toLowerCase(); if (r?.startsWith("channel:") || /^[^:]+:channel:/u.test(r ?? "")) return "channel"; if (/^(?:[^:]+:)?(?:group|room):/u.test(r ?? "") || normalizeOptionalString(e.entry.groupId)) return "group"; return "direct"; } function migratedConversation(e, t, n) { const r = asOptionalRecord(e.delivery); const i = asOptionalRecord(r?.context) ?? asOptionalRecord(e.deliveryContext); const a = asOptionalRecord(r?.origin) ?? asOptionalRecord(e.origin); const o = normalizeOptionalString(i?.to); const s = normalizeOptionalString(a?.from); const c = inferMigratedChatType({ entry: e, persistedChatType: t, sessionKey: n, deliveryTarget: o ?? s }); const l = o ?? (c === "direct" ? s : void 0); if (!l) return; const u = Boolean(o); const d = (u ? normalizeOptionalString(i?.channel) ?? normalizeOptionalString(e.channel) ?? normalizeOptionalString(e.lastChannel) ?? normalizeOptionalString(a?.provider) : normalizeOptionalString(a?.provider))?.toLowerCase(); const f = normalizeAccountId(u ? normalizeOptionalString(i?.accountId) ?? normalizeOptionalString(e.lastAccountId) ?? normalizeOptionalString(a?.accountId) : normalizeOptionalString(a?.accountId)); const p = u ? i?.threadId : a?.threadId; const m = typeof p === "number" && Number.isFinite(p) ? String(p) : normalizeOptionalString(p); const h = d ? normalizeConversationPeerId(d, l) : void 0; if (!d || !h) return; return { conversationRef: buildConversationRef({ channel: d, accountId: f, kind: c, peerId: h, threadId: m }), channel: d, accountId: f, kind: c, peerId: h, deliveryTarget: l, threadId: m, nativeChannelId: normalizeOptionalString(a?.nativeChannelId), nativeDirectUserId: normalizeOptionalString(a?.nativeDirectUserId), label: normalizeOptionalString(e.displayName) ?? normalizeOptionalString(e.label) ?? normalizeOptionalString(e.subject) ?? normalizeOptionalString(e.groupId) }; } /** Backfills canonical external addresses once when conversation routing becomes active. */ function backfillSessionConversations(e) { if (!readSqliteTableColumns(e, "session_entries") || !readSqliteTableColumns(e, "sessions") || !readSqliteTableColumns(e, "conversations")) return; if (!readSqliteTableColumns(e, "session_conversations")) e.exec(` CREATE TABLE session_conversations ( session_id TEXT NOT NULL, conversation_id TEXT NOT NULL, role TEXT NOT NULL DEFAULT 'primary' CHECK (role IN ('primary', 'participant', 'related')), route_context_json TEXT, first_seen_at INTEGER NOT NULL, last_seen_at INTEGER NOT NULL, PRIMARY KEY (session_id, conversation_id, role), FOREIGN KEY (session_id) REFERENCES sessions(session_id) ON DELETE CASCADE, FOREIGN KEY (conversation_id) REFERENCES conversations(conversation_id) ON DELETE CASCADE ); `); e.exec(` UPDATE sessions SET primary_conversation_id = NULL WHERE primary_conversation_id IN ( SELECT conversation_id FROM conversations WHERE delivery_target = '' ); DELETE FROM session_conversations WHERE conversation_id IN ( SELECT conversation_id FROM conversations WHERE delivery_target = '' ); DELETE FROM conversations WHERE delivery_target = ''; `); const t = e.prepare(` SELECT se.session_id, se.entry_json, se.session_key, se.updated_at, s.session_scope, CASE WHEN se.session_key = s.session_key THEN s.chat_type END AS persisted_chat_type FROM session_entries AS se INNER JOIN sessions AS s ON s.session_id = se.session_id ORDER BY se.updated_at ASC, se.session_key ASC; `).all(); const n = e.prepare(` INSERT INTO conversations ( conversation_id, channel, account_id, kind, peer_id, delivery_target, parent_conversation_id, thread_id, native_channel_id, native_direct_user_id, label, metadata_json, created_at, updated_at ) VALUES (?, ?, ?, ?, ?, ?, NULL, ?, ?, ?, ?, NULL, ?, ?) ON CONFLICT(conversation_id) DO UPDATE SET channel = excluded.channel, account_id = excluded.account_id, kind = excluded.kind, peer_id = excluded.peer_id, delivery_target = excluded.delivery_target, thread_id = excluded.thread_id, native_channel_id = excluded.native_channel_id, native_direct_user_id = excluded.native_direct_user_id, label = excluded.label, updated_at = excluded.updated_at; `); const r = e.prepare(` DELETE FROM session_conversations WHERE session_id = ? AND conversation_id = ? AND role = 'related'; `); const i = e.prepare(` UPDATE session_conversations SET role = 'related', last_seen_at = ? WHERE session_id = ? AND role = 'primary'; `); const a = e.prepare(` INSERT INTO session_conversations ( session_id, conversation_id, role, first_seen_at, last_seen_at ) VALUES (?, ?, ?, ?, ?) ON CONFLICT(session_id, conversation_id, role) DO UPDATE SET last_seen_at = excluded.last_seen_at; `); const o = e.prepare("UPDATE sessions SET primary_conversation_id = ? WHERE session_id = ?"); for (const e of [ n, r, i, a, o ]) e.setReadBigInts(true); for (const e of t) { const t = normalizeOptionalString(e.session_id); const s = typeof e.entry_json === "string" ? safeParseJsonRecord(e.entry_json) : void 0; const c = typeof e.updated_at === "number" ? e.updated_at : Date.now(); const l = s ? migratedConversation(s, normalizeOptionalString(e.persisted_chat_type), normalizeOptionalString(e.session_key)) : void 0; if (!t || !l) continue; const u = e.session_scope === "shared-main" && l.kind === "direct" ? "participant" : "primary"; n.run(l.conversationRef, l.channel, l.accountId, l.kind, l.peerId, l.deliveryTarget, l.threadId ?? null, l.nativeChannelId ?? null, l.nativeDirectUserId ?? null, l.label ?? null, c, c); if (u === "primary") { i.run(c, t); r.run(t, l.conversationRef); } a.run(t, l.conversationRef, u, c, c); if (u === "primary") o.run(l.conversationRef, t); } } function readSqliteTableColumns(e, t) { if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(t)) throw new Error(`invalid SQLite table identifier: ${t}`); if (!tableExists(e, t)) return null; const n = e.prepare(`PRAGMA table_info(${t})`).all(); return new Set(n.flatMap((e) => typeof e.name === "string" ? [e.name] : [])); } /** Installs same-version session projections on first updated-binary open. */ function ensureSessionAdditiveColumns(e) { for (const { tableName: t, columnName: n, dataType: r } of STARTUP_ADDITIVE_AGENT_COLUMN_DEFINITIONS) ensureColumn(e, t, `${n} ${r}`); if (tableExists(e, "session_conversations") && !getAdmittedSqliteSchemaFacts(e)?.triggers.has("session_conversations_route_context_invalidate_after_update")) e.exec(` CREATE TRIGGER IF NOT EXISTS session_conversations_route_context_invalidate_after_update AFTER UPDATE OF role, last_seen_at ON session_conversations WHEN NEW.route_context_json IS OLD.route_context_json BEGIN UPDATE session_conversations SET route_context_json = NULL WHERE session_id = NEW.session_id AND conversation_id = NEW.conversation_id AND role = NEW.role; END; `); } /** Adds the v11 exact delivery target before the conversation backfill writes canonical rows. */ function migrateConversationDeliveryTargetColumn(e) { ensureColumn(e, "conversations", "delivery_target TEXT NOT NULL DEFAULT ''"); } /** Adds the validity projection and settles only rows left pending by older writers. */ function ensureSessionEntryValidityProjection(e) { const t = readSqliteTableColumns(e, "session_nodes"); if (!t) return; if (!t.has("entry_valid")) e.exec("ALTER TABLE session_nodes ADD COLUMN entry_valid INTEGER NOT NULL DEFAULT 0 CHECK (entry_valid IN (-1, 0, 1))"); const n = e.prepare("SELECT current_session_id, entry_json, session_key, updated_at FROM session_nodes WHERE entry_valid = 0 ORDER BY session_key LIMIT 256"); const r = e.prepare("UPDATE session_nodes SET entry_valid = ? WHERE session_key = ?"); r.setReadBigInts(true); while (true) { const e = n.all(); if (e.length === 0) break; for (const t of e) r.run(parseSqliteSessionEntryRecord(t) ? 1 : -1, t.session_key); } } function migrateSessionCreatorNamespaces(e, t) { if (t >= 19 || !tableExists(e, "session_nodes")) return; const n = e.prepare("UPDATE session_nodes SET entry_json = ?, created_actor_type = ?, created_actor_id = ? WHERE session_key = ?"); n.setReadBigInts(true); const r = e.prepare(`SELECT session_key, entry_json FROM session_nodes WHERE json_valid(entry_json) AND (json_extract(entry_json, '$.createdActor.type') = 'human' OR (json_type(entry_json, '$.createdActor') IS NULL AND json_type(entry_json, '$.createdBy') = 'object'))`); for (const e of r.all()) { const t = migrateLegacySessionCreator(JSON.parse(e.entry_json)); n.run(JSON.stringify(t), t.createdActor?.type ?? null, t.createdActor?.id ?? null, e.session_key); } } //#endregion //#region src/state/openclaw-agent-session-participants-schema.ts const ensureNativeSessionParticipantsSchema = createSqliteSchemaEnsurer(sessionParticipantsSchemaSql, { tables: [SESSION_PARTICIPANTS_TABLE] }); function ensureSessionParticipantsSchema(e) { if (!isPostgresSqlConnection(e)) ensureNativeSessionParticipantsSchema(e); } //#endregion //#region src/state/openclaw-agent-participants-migration.ts const MIGRATION_TABLE = "session_participants_identity_migration"; function migrateSessionParticipantsSchema(e, t) { if (!tableExists(e, "session_participants")) return; assertSqliteSchemaContains(e, t, LEGACY_PARTICIPANTS_SCHEMA, { allowedMissingColumns: LEGACY_PARTICIPANT_OPTIONAL_COLUMNS }); if (tableExists(e, MIGRATION_TABLE)) throw new Error(`Participant migration table already exists: ${MIGRATION_TABLE}`); if (e.prepare(`SELECT name FROM sqlite_schema WHERE (type IN ('trigger', 'index') AND tbl_name = 'session_participants' AND sql IS NOT NULL) OR (type IN ('view', 'trigger') AND sql LIKE '%session_participants%')`).all().length > 0) throw new Error("Participant migration cannot rebuild unknown indexes, views, or triggers."); for (const t of e.prepare("SELECT name FROM sqlite_schema WHERE type = 'table'").all()) if (e.prepare(`PRAGMA foreign_key_list("${String(t.name).replaceAll("\"", "\"\"")}")`).all().some((e) => e.table === "session_participants")) throw new Error("Participant migration cannot rebuild a table referenced by an unknown foreign key."); const n = tableHasColumn(e, "session_participants", "actor_source") ? "actor_source" : "NULL"; const r = tableHasColumn(e, "session_participants", "contribution_count") ? "coalesce(contribution_count, 1)" : "1"; const i = `actor_type = 'agent' AND ${n} = 'agent' AND actor_id <> ''`; const a = `(${i}) OR (actor_type = 'human' AND ${n} = 'channel')`; e.exec(` ${sessionParticipantsSchemaSql().replace("IF NOT EXISTS session_participants", MIGRATION_TABLE)} INSERT INTO ${MIGRATION_TABLE} (session_key, identity_namespace, actor_id, contribution_count, first_prompted_at, last_prompted_at) SELECT session_key, CASE WHEN actor_type = 'human' AND ${n} = 'profile' AND actor_id <> '' THEN json_object('type', 'profile') WHEN ${i} THEN json_object('type', 'agent') ELSE json_object('type', 'legacy', 'actorType', actor_type, 'source', ${n}) END, actor_id, ${r}, CASE WHEN ${a} THEN first_prompted_at ELSE NULL END, CASE WHEN ${a} THEN last_prompted_at ELSE NULL END FROM session_participants; DROP TABLE session_participants; ALTER TABLE ${MIGRATION_TABLE} RENAME TO session_participants; `); } //#endregion //#region src/state/openclaw-agent-db-schema-helpers.ts /** beta.6 wrote v16 before the derived validity column and triggers existed. */ function repairAndAssertOpenClawAgentV16Validity(e, t, n) { const r = getAdmittedSqliteSchemaFacts(e) ?? captureSqliteSchemaFacts(e); if ([ "session_nodes_entry_valid_after_insert", "session_nodes_entry_valid_after_entry_update", "session_nodes_entry_valid_after_identity_update" ].every((e) => r.triggers.has(e))) return; const i = iterateSqliteQuerySync(e, getNodeSqliteKysely(e).selectFrom("session_nodes").select([ "current_session_id", "entry_json", "updated_at" ])); for (const e of i) if (!parseSqliteSessionEntryRecord(e)) throw new SqliteSchemaMismatchError(`Cannot repair v16 validity triggers for ${t}: invalid session entry identity or JSON. Stop the Gateway and preserve the database and SQLite sidecars; restore a verified backup or contact OpenClaw support to repair the affected rows. No session rows were changed.`); ensureLegacySessionEntryValidityTriggers(e); assertSqliteSchemaContains(e, t, n, { ...AGENT_SCHEMA_COMPATIBILITY, allowCompatibleAdditiveColumns: false, allowedMissingColumns: [...AGENT_SCHEMA_COMPATIBILITY.allowedMissingColumns, ...LEGACY_PARTICIPANT_OPTIONAL_COLUMNS], allowedMissingTables: [...AGENT_SCHEMA_COMPATIBILITY.allowedMissingTables, "session_transcript_cold_archives"] }); if (r.tables.has("state_leases")) assertSqliteSchemaContains(e, t, RETIRED_AGENT_STATE_LEASE_SCHEMA_SQL); const a = /* @__PURE__ */ new Set([...getCanonicalSqliteTableNames(n), "state_leases"]); const o = /* @__PURE__ */ new Set([ ...getCanonicalSqliteNamedIndexNames(n), "idx_agent_state_leases_expiry", "idx_agent_state_leases_owner", "idx_memory_index_chunks_path" ]); for (const [e, n, i] of [[ "table", r.tables, a ], [ "index", r.indexes, o ]]) for (const r of n) if (!r.startsWith("sqlite_") && !i.has(r)) throw new SqliteSchemaMismatchError(`Cannot repair v16 validity triggers for ${t}: unexpected ${e} ${r}. Preserve the database and SQLite sidecars and contact OpenClaw support; the unknown schema needs inspection before migration.`); } function migratedSessionColumn(e, t, n) { return e.has(t) ? t : n; } function hasRetiredAgentStateLeaseSchema(e) { return Boolean(e.prepare("SELECT 1 FROM main.sqlite_schema WHERE name = 'state_leases'").get()); } function assertOpenClawAgentSchemaContains(e, t, n, r = "current", i = false, a) { const o = { ...AGENT_SCHEMA_COMPATIBILITY, allowedMissingTables: [...AGENT_SCHEMA_COMPATIBILITY.allowedMissingTables, ...r === "legacy" ? ["session_transcript_cold_archives"] : []], allowedMissingColumns: [...AGENT_SCHEMA_COMPATIBILITY.allowedMissingColumns, ...r === "legacy" ? LEGACY_PARTICIPANT_OPTIONAL_COLUMNS : []] }; if (!i) { assertSqliteSchemaContains(e, t, n, o, a); return false; } const s = new Set(getCanonicalSqliteNamedIndexNames(n)); const c = collectSqliteSchemaIssues(e, n, o, a); if (c.some((e) => e.code !== "missing-or-drifted-index" || !s.has(e.objectName))) throwSqliteSchemaMismatches(t, legacySqliteSchemaIssueMessages(c)); return c.length > 0; } function assertOpenClawAgentCurrentRuntimeSchema(e, t, n) { const r = normalizeAgentId(t.agentId); const i = readExistingAgentSchemaMeta(e); assertCurrentAgentSchemaMetadata(i, r, t.pathname); if (hasRetiredAgentStateLeaseSchema(e)) throw new SqliteSchemaMismatchError(`OpenClaw agent database ${t.pathname} retains retired state_leases storage; run openclaw doctor --fix before using it.`); assertOpenClawAgentSchemaContains(e, t.pathname, OPENCLAW_AGENT_SCHEMA_SQL, "current", false, n); } function hasAnyCanonicalTable(e, t) { const n = getCanonicalSqliteTableNames(t); const r = n.map(() => "?").join(", "); return Boolean(e.prepare(`SELECT 1 FROM main.sqlite_schema WHERE type = 'table' AND name IN (${r}) LIMIT 1`).get(...n)); } function repairAndAssertAgentSchemaGroup(e, t, n) { repairCanonicalSqliteIndexes(e, t, n, { verifyPhysicalIntegrity: false }); assertOpenClawAgentSchemaContains(e, t, n, "legacy"); } /** Ensure the additive session-key contract table inside the caller's transaction. */ function ensureSessionKeyContractSchemaInTransaction(e) { if (tableExists(e, "session_key_contract") && e.prepare("SELECT 1 FROM session_key_contract WHERE id = 1").get()) return; e.exec(extractSqliteTableSchema(OPENCLAW_AGENT_SCHEMA_SQL, "session_key_contract", { endMarker: "CREATE TABLE IF NOT EXISTS session_windows (", includeEndMarker: false, errorMessage: "OpenClaw agent session-key contract schema markers are missing." })); } function ensureSessionReactionsSchemaInTransaction(e) { if (getAdmittedSqliteSchemaFacts(e)?.tables.has("session_reactions")) return; e.exec(extractSqliteTableSchema(OPENCLAW_AGENT_SCHEMA_SQL, "session_reactions", { endMarker: "CREATE TABLE IF NOT EXISTS board_tabs (", includeEndMarker: false, errorMessage: "OpenClaw agent session-reactions schema markers are missing." })); } function repairAndAssertOpenClawAgentV14SchemaForMigration(e, t) { const n = readSqliteUserVersion(e); if (n !== 14) throw new SqliteSchemaMismatchError(`OpenClaw agent database ${t.pathname} uses schema version ${n}; expected 14 before migrating it.`); const r = normalizeAgentId(t.agentId); const i = readExistingAgentSchemaMeta(e); if (!i) throw new SqliteSchemaMismatchError(`OpenClaw agent database ${t.pathname} has no schema ownership metadata. Run openclaw doctor --fix to inspect and repair its ownership.`); assertExistingAgentSchemaOwner(i, r, t.pathname); if (i.schemaVersion !== 14) throw new SqliteSchemaMismatchError(`OpenClaw agent database ${t.pathname} metadata schema version ${i.schemaVersion ?? "invalid"} does not match 14; repair the ownership metadata before migrating it.`); ensureSessionAdditiveColumns(e); ensureSessionEntryValidityProjection(e); ensureLegacySessionEntryValidityTriggers(e); ensureSessionKeyContractSchemaInTransaction(e); repairAndAssertAgentSchemaGroup(e, t.pathname, AGENT_V14_CORE_SCHEMA_SQL); if (hasAnyCanonicalTable(e, AGENT_V14_SESSION_SHARING_SCHEMA_SQL)) repairAndAssertAgentSchemaGroup(e, t.pathname, AGENT_V14_SESSION_SHARING_SCHEMA_SQL); if (hasAnyCanonicalTable(e, AGENT_V14_ADDITIVE_SCHEMA_SQL)) repairAndAssertAgentSchemaGroup(e, t.pathname, AGENT_V14_ADDITIVE_SCHEMA_SQL); if (hasAnyCanonicalTable(e, AGENT_V14_BOARD_SCHEMA_SQL)) { assertSqliteSchemaTablesPresent(e, t.pathname, AGENT_V14_BOARD_SCHEMA_SQL); ensureOpenClawAgentBoardSchemaInTransaction(e); repairAndAssertAgentSchemaGroup(e, t.pathname, AGENT_V14_BOARD_SCHEMA_SQL); } if (hasAnyCanonicalTable(e, AGENT_PROGRESS_CARD_SCHEMA_SQL)) { assertSqliteSchemaTablesPresent(e, t.pathname, AGENT_PROGRESS_CARD_SCHEMA_SQL); ensureOpenClawAgentProgressCardSchemaInTransaction(e); repairAndAssertAgentSchemaGroup(e, t.pathname, AGENT_PROGRESS_CARD_SCHEMA_SQL); } } function migrateRetiredAgentStateLeaseSchema(e, t, n) { if (n < 17 || !hasRetiredAgentStateLeaseSchema(e)) return; assertSqliteSchemaContains(e, t, RETIRED_AGENT_STATE_LEASE_SCHEMA_SQL); e.exec("DROP TABLE state_leases;"); } function assertAgentSchemaVersion(e, t, n) { const r = readExistingAgentSchemaMeta(e); assertExistingAgentSchemaOwner(r, t.agentId, t.pathname); if (readSqliteUserVersion(e) !== t.version || r?.schemaVersion !== t.version) throw new SqliteSchemaMismatchError(`OpenClaw agent database ${t.pathname} did not converge on schema version ${t.version}.`); assertOpenClawAgentSchemaContains(e, t.pathname, n, t.version < 18 ? "legacy" : "current"); } function finishAgentSchemaMigration(e, t, n, r, i, a, o, s) { e.exec(`PRAGMA user_version = ${r};`); persistAgentSchemaMetadata(e, t, r); assertAgentSchemaVersion(e, { agentId: t, pathname: n, version: r }, i); for (const t of s ?? []) if (tableExists(e, t)) assertSqliteTableIntegrity(e, n, t); if (a && e.prepare("PRAGMA foreign_key_check").all().length > 0) throw new Error(`Agent schema migration failed foreign key validation for ${n}.`); o(); } function hasLegacyMemoryChunkProvenanceTrigger(e) { return Boolean(e.prepare("SELECT 1 FROM sqlite_schema WHERE type = 'trigger' AND name = 'memory_index_chunk_provenance_after_insert'").get()); } function hasPendingMemoryChunkMetadataMigration(e) { return hasLegacyMemoryRecallMetadataColumns(e) || hasLegacyMemoryChunkProvenanceTrigger(e); } function hasPendingSessionKeyContractSchemaMigration(e) { const t = readSqliteTableColumns(e, "session_nodes"); if (!t) return false; const n = tableExists(e, "session_key_contract"); return !t.has("entry_valid") || !n; } function hasPendingCurrentVersionAgentDatabaseMigration(e) { return !tableExists(e, "session_reactions") || hasPendingMemoryChunkMetadataMigration(e) || hasPendingSessionKeyContractSchemaMigration(e) || hasRetiredAgentStateLeaseSchema(e) || hasPendingAgentStartupColumns((getAdmittedSqliteSchemaFacts(e) ?? captureSqliteSchemaFacts(e)).tableSql); } //#endregion //#region src/state/openclaw-agent-json-predicate-schema.ts /** Runs once inside the versioned migration transaction, never on runtime reads. */ function migrateAgentJsonPredicatesInTransaction(e) { ensureColumn(e, "session_nodes", "session_started_at INTEGER"); ensureColumn(e, "session_nodes", "has_optional_references INTEGER NOT NULL DEFAULT 0"); e.exec(` UPDATE session_nodes SET session_started_at = CASE WHEN json_valid(entry_json) THEN CAST(json_extract(entry_json, '$.sessionStartedAt') AS INTEGER) END, has_optional_references = CASE WHEN NOT json_valid(entry_json) OR instr(entry_json, char(0)) > 0 THEN 1 WHEN json_type(entry_json, '$.previousSessionId') IS NOT NULL OR json_type(entry_json, '$.usageFamilySessionIds') IS NOT NULL OR json_type(entry_json, '$.compactionCheckpoints') IS NOT NULL THEN 1 ELSE 0 END; `); if (tableExists(e, "context_engine_turn_outbox")) { ensureColumn(e, "context_engine_turn_outbox", "payload_state TEXT"); e.exec(` UPDATE context_engine_turn_outbox SET payload_state = CASE WHEN json_valid(payload_json) THEN CASE WHEN json_type(payload_json, '$.state') = 'text' THEN json_extract(payload_json, '$.state') END END; `); } for (const t of AGENT_JSON_PREDICATE_COLUMNS.transcript_events) ensureColumn(e, "transcript_events", `${t} ${AGENT_JSON_PREDICATE_COLUMN_DECLARATIONS[t]}`); } //#endregion //#region src/state/openclaw-agent-outbox-sequence-migration.ts /** Rebuild within the schema owner's exclusive migration transaction. */ function migrateOutboxEnqueueSequenceInTransaction(e) { if (!tableExists(e, "context_engine_turn_outbox") || tableHasColumn(e, "context_engine_turn_outbox", "enqueue_sequence")) return null; const t = performance.now(); const n = getAdmittedSqliteSchemaFacts(e) ?? captureSqliteSchemaFacts(e); const r = [...n.indexDefinitions.values(), ...n.triggers.values()].filter(({ table: e }) => e === "context_engine_turn_outbox"); const i = extractSqliteTableSchema(OPENCLAW_AGENT_SCHEMA_SQL, "context_engine_turn_outbox"); e.exec(` ${i.replace("IF NOT EXISTS context_engine_turn_outbox", "context_engine_turn_outbox_sequence_migration")} INSERT INTO context_engine_turn_outbox_sequence_migration (enqueue_sequence, advancement_key, engine_id, owner_plugin_id, session_id, payload_json, payload_state, attempt_count, last_attempt_at, last_error, created_at) SELECT rowid, advancement_key, engine_id, owner_plugin_id, session_id, payload_json, payload_state, attempt_count, last_attempt_at, last_error, created_at FROM context_engine_turn_outbox; DROP TABLE context_engine_turn_outbox; ALTER TABLE context_engine_turn_outbox_sequence_migration RENAME TO context_engine_turn_outbox; `); for (const t of r) if (t.sql !== null) e.exec(t.sql); return performance.now() - t; } //#endregion export { seedCanonicalSessionValidationPending as A, migrateSessionTranscriptActiveProjection as C, persistAgentSchemaMetadata as D, migrateLegacySessionCreator as E, ensureLegacySessionEntryValidityTriggers as O, migrateSessionCreatorNamespaces as S, readSqliteTableColumns as T, assertSupportedAgentMigrationSchemas as _, assertOpenClawAgentSchemaContains as a, ensureSessionEntryValidityProjection as b, finishAgentSchemaMigration as c, migrateRetiredAgentStateLeaseSchema as d, migratedSessionColumn as f, ensureSessionParticipantsSchema as g, migrateSessionParticipantsSchema as h, assertOpenClawAgentCurrentRuntimeSchema as i, ensureOpenClawAgentBoardSchemaInTransaction as j, migrateCanonicalSessionWriterValidation as k, hasPendingCurrentVersionAgentDatabaseMigration as l, repairAndAssertOpenClawAgentV16Validity as m, migrateAgentJsonPredicatesInTransaction as n, ensureSessionKeyContractSchemaInTransaction as o, repairAndAssertOpenClawAgentV14SchemaForMigration as p, assertAgentSchemaVersion as r, ensureSessionReactionsSchemaInTransaction as s, migrateOutboxEnqueueSequenceInTransaction as t, hasPendingMemoryChunkMetadataMigration as u, backfillSessionConversations as v, migrateSessionTranscriptGenerations as w, migrateConversationDeliveryTargetColumn as x, ensureSessionAdditiveColumns as y };