UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

164 lines (163 loc) • 7.89 kB
import { i as executeSqliteQuerySync } from "./kysely-sync-YJo2lmGV.mjs"; import { n as withOpenClawAgentDatabaseReadOnly } from "./openclaw-agent-db-readonly-COYfV-vn.mjs"; import { t as buildConversationRef } from "./conversation-ref-BiSqlOTe.mjs"; import { s as runOpenClawAgentWriteTransaction } from "./openclaw-agent-db-CwXW4hGa.mjs"; import { i as toDatabaseOptions, t as getSessionKysely } from "./session-accessor.sqlite-scope-helpers-5_tKUULP.mjs"; import { a as resolveSqliteReadScope } from "./session-accessor.sqlite-read-scope-7Z2ARJnl.mjs"; import { s as runExclusiveSqliteSessionWrite } from "./session-accessor.sqlite-scope-Cbj2BdoG.mjs"; import { a as resolveAllAgentSessionStoreTargetsSync } from "./targets-BVE0__Jb.mjs"; import { o as readExactSessionEntryRow } from "./session-accessor.sqlite-entry-read-csOyyi3K.mjs"; import { c as writeSessionEntry } from "./session-accessor.sqlite-entry-store-DmqxH0lm.mjs"; import { i as projectExistingAgentDatabaseTargets } from "./session-sqlite-migration-readers-DbmEQzSW.mjs"; import { t as runDoctorAgentDatabaseOperation } from "./doctor-agent-database-operation-BYsIdRWr.mjs"; //#region src/commands/doctor-telegram-general-topic-conversations.ts /** Doctor repair for Telegram General-topic conversation identities written before #113063. */ const GENERAL_TOPIC_ID = "1"; const LEGACY_GENERAL_TARGET = /^telegram:(-?\d+):topic:1$/u; function canonicalIdentity(e) { const t = LEGACY_GENERAL_TARGET.exec(e.delivery_target); if (e.channel !== "telegram" || e.kind !== "group" || e.thread_id !== GENERAL_TOPIC_ID || e.parent_conversation_id !== null || !t || e.peer_id !== `${t[1]}:topic:${GENERAL_TOPIC_ID}`) return null; const n = t[1]; return { conversationId: buildConversationRef({ channel: e.channel, accountId: e.account_id, kind: "group", peerId: n, threadId: GENERAL_TOPIC_ID }), deliveryTarget: `telegram:${n}`, peerId: n }; } function listLegacyRows(e) { const t = getSessionKysely(e); return executeSqliteQuerySync(e, t.selectFrom("conversations").selectAll().where("channel", "=", "telegram").where("kind", "=", "group").where("thread_id", "=", GENERAL_TOPIC_ID).where("parent_conversation_id", "is", null)).rows.filter((e) => { const t = canonicalIdentity(e); return t && t.conversationId !== e.conversation_id; }); } function resolveRepairScopes(e, t) { return projectExistingAgentDatabaseTargets(resolveAllAgentSessionStoreTargetsSync(e, { env: t }), t, e).map((e) => { return { scope: resolveSqliteReadScope({ agentId: e.agentId, env: t, storePath: e.storePath }), storePath: e.storePath }; }); } /** Finds stale General-topic rows without creating or migrating agent databases. */ function detectTelegramGeneralTopicConversationRepairs(e) { const t = e.env ?? process.env; return resolveRepairScopes(e.cfg, t).flatMap(({ scope: e, storePath: t }) => { const n = toDatabaseOptions(e); const r = runDoctorAgentDatabaseOperation({ agentId: e.agentId, path: n.path ?? t, run: () => withOpenClawAgentDatabaseReadOnly((t) => listLegacyRows(t.db).map(() => ({ agentId: e.agentId })), n) }); return r.ok && r.value.found ? r.value.value : []; }); } const roleRank = { related: 0, participant: 1, primary: 2 }; function canonicalizeLegacySessionEntry(e, t, n) { const r = e.delivery; if (r?.kind !== "external" || r.context.channel !== "telegram" || String(r.context.threadId) !== GENERAL_TOPIC_ID || r.context.to !== t) return null; return { ...e, delivery: { ...r, context: { ...r.context, to: n }, route: { ...r.route, target: { ...r.route.target, to: n, ...r.route.target?.rawTo === t ? { rawTo: n } : {} } }, origin: r.origin.to === t ? { ...r.origin, to: n } : r.origin } }; } function repairLegacyRow(e, t) { const n = getSessionKysely(e.db); const r = executeSqliteQuerySync(e.db, n.selectFrom("conversations").selectAll().where("conversation_id", "=", t)).rows[0]; const i = r ? canonicalIdentity(r) : null; if (!r || !i || i.conversationId === r.conversation_id) return false; const a = executeSqliteQuerySync(e.db, n.selectFrom("conversations").selectAll().where("conversation_id", "=", i.conversationId)).rows[0]; if (a && (a.channel !== "telegram" || a.account_id !== r.account_id || a.kind !== "group" || a.peer_id !== i.peerId || a.thread_id !== GENERAL_TOPIC_ID || a.parent_conversation_id !== null)) throw new Error(`normalized Telegram conversation ID collision: ${i.conversationId}`); const o = { created_at: Math.min(a?.created_at ?? r.created_at, r.created_at), updated_at: Math.max(a?.updated_at ?? r.updated_at, r.updated_at), native_channel_id: a?.native_channel_id ?? r.native_channel_id, native_direct_user_id: a?.native_direct_user_id ?? r.native_direct_user_id, label: a?.label ?? r.label, metadata_json: a?.metadata_json ?? r.metadata_json }; executeSqliteQuerySync(e.db, n.insertInto("conversations").values({ ...a ?? r, ...o, conversation_id: i.conversationId, peer_id: i.peerId, delivery_target: i.deliveryTarget }).onConflict((e) => e.column("conversation_id").doUpdateSet(o))); const s = executeSqliteQuerySync(e.db, n.selectFrom("session_conversations as sc").innerJoin("session_windows as sw", "sw.session_id", "sc.session_id").select(["sw.session_id", "sw.session_key"]).where("sc.conversation_id", "=", r.conversation_id)).rows; for (const t of s) { const n = readExactSessionEntryRow(e, t.session_key); if (!n || n.entry.sessionId !== t.session_id) continue; const a = canonicalizeLegacySessionEntry(n.entry, r.delivery_target, i.deliveryTarget); if (a) writeSessionEntry(e, t.session_key, a, { previousEntry: n.entry }); } const c = [r.conversation_id, i.conversationId]; const l = executeSqliteQuerySync(e.db, n.selectFrom("session_conversations").selectAll().where("conversation_id", "in", c)).rows; const u = /* @__PURE__ */ new Map(); for (const e of l) { const t = u.get(e.session_id); const n = roleRank[t?.role] ?? -1; const r = (roleRank[e.role] ?? -1) > n ? e : t ?? e; u.set(e.session_id, { ...r, conversation_id: i.conversationId, first_seen_at: Math.min(t?.first_seen_at ?? e.first_seen_at, e.first_seen_at), last_seen_at: Math.max(t?.last_seen_at ?? e.last_seen_at, e.last_seen_at) }); } executeSqliteQuerySync(e.db, n.deleteFrom("session_conversations").where("conversation_id", "in", c)); if (u.size > 0) executeSqliteQuerySync(e.db, n.insertInto("session_conversations").values([...u.values()])); for (const t of [ n.updateTable("session_windows").set({ primary_conversation_id: i.conversationId }).where("primary_conversation_id", "=", r.conversation_id), n.updateTable("conversation_deliveries").set({ conversation_id: i.conversationId }).where("conversation_id", "=", r.conversation_id), n.updateTable("conversations").set({ parent_conversation_id: i.conversationId }).where("parent_conversation_id", "=", r.conversation_id) ]) executeSqliteQuerySync(e.db, t); executeSqliteQuerySync(e.db, n.deleteFrom("conversations").where("conversation_id", "=", r.conversation_id)); return true; } /** Canonicalizes stale rows and merges every durable reference in one transaction per agent DB. */ async function repairTelegramGeneralTopicConversations(e) { const t = e.env ?? process.env; let n = 0; for (const { scope: r } of resolveRepairScopes(e.cfg, t)) await runExclusiveSqliteSessionWrite(r, async () => { n += runOpenClawAgentWriteTransaction((e) => { let t = 0; for (const n of listLegacyRows(e.db)) if (repairLegacyRow(e, n.conversation_id)) t += 1; return t; }, toDatabaseOptions(r), { operationLabel: "doctor-telegram-general-topic" }); }, "doctor-telegram-general-topic"); return n; } //#endregion export { detectTelegramGeneralTopicConversationRepairs, repairTelegramGeneralTopicConversations };