openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
196 lines (195 loc) • 7.72 kB
JavaScript
import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs";
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs";
import { c as iterateSqliteQuerySync } from "./kysely-sync-YJo2lmGV.mjs";
import { a as tableExists, o as tableHasColumn } from "./openclaw-state-db-schema-helpers-nImZNMq_.mjs";
import { n as openNodeSqliteDatabase } from "./node-sqlite-CU4puofF.mjs";
import { r as beginUpdateDoctorHistoricalScan } from "./update-doctor-scan-receipts-DDzDb0Mp.mjs";
import "./transcript-payload-Cb_Kmk8c.mjs";
import { n as readTranscriptPayload, r as transcriptEventJsonSql } from "./transcript-payload-read-Dd5D3FtH.mjs";
import { t as getSessionKysely } from "./session-accessor.sqlite-scope-helpers-5_tKUULP.mjs";
import "./session-accessor.sqlite-scope-Cbj2BdoG.mjs";
import { a as resolveAllAgentSessionStoreTargetsSync } from "./targets-BVE0__Jb.mjs";
import { i as projectExistingAgentDatabaseTargets, u as resolveTargetSqliteOptions } from "./session-sqlite-migration-readers-DbmEQzSW.mjs";
import { t as note } from "./note-CnLgHvug.mjs";
//#region src/commands/doctor-session-sqlite-transcript-readers.ts
function resetReadIterator(e) {
try {
e?.return?.();
} catch {}
}
var ReadOnlySqliteTranscriptReader = class {
constructor(e) {
this.database = e;
this.compressed = tableHasColumn(e, "transcript_events", "event_zstd");
this.eventJsonSql = this.compressed ? transcriptEventJsonSql(e).compile(getSessionKysely(e)).sql : "event_json";
this.labelRowsSql = `SELECT ${this.eventJsonSql} AS event_json, seq FROM transcript_events WHERE session_id = ? ORDER BY seq ASC`;
this.labelDetectionSql = this.compressed ? "SELECT event_json, navigation_json, seq FROM transcript_events WHERE session_id = ? ORDER BY seq ASC" : this.labelRowsSql;
}
sessionIds() {
if (!tableExists(this.database, "transcript_events")) return [];
return this.database.prepare("SELECT DISTINCT session_id FROM transcript_events ORDER BY session_id ASC").all().flatMap((e) => typeof e.session_id === "string" ? [e.session_id] : []);
}
/** Decode one first row per session, closing enumeration before any repair opens a writer. */
headerlessSessionIds(e) {
if (!tableExists(this.database, "transcript_events")) return [];
const t = getSessionKysely(this.database);
const n = t.selectFrom("transcript_events").select("session_id").select((e) => e.fn.min("seq").as("seq")).groupBy("session_id").as("first");
const r = t.selectFrom("transcript_events as event").innerJoin(n, (e) => e.onRef("event.session_id", "=", "first.session_id").onRef("event.seq", "=", "first.seq")).select(["event.session_id", "event.event_json"]);
const i = this.compressed ? r.select(["event.event_zstd", "event.event_utf8_bytes"]) : r.select((e) => [e.val(null).as("event_zstd"), e.val(null).as("event_utf8_bytes")]);
const a = [];
for (const t of iterateSqliteQuerySync(this.database, i)) {
if (typeof t.session_id !== "string") continue;
let n;
try {
n = this.compressed ? readTranscriptPayload(t) : t.event_json;
} catch (n) {
e(t.session_id, n);
continue;
}
if (typeof n !== "string") {
a.push(t.session_id);
continue;
}
let r;
try {
r = JSON.parse(n);
} catch {
continue;
}
if (isRecord(r) && r.type !== "session") a.push(t.session_id);
}
return a.toSorted((e, t) => Buffer.compare(Buffer.from(e), Buffer.from(t)));
}
labelRepairSnapshot(e, t, n) {
let r;
try {
this.labelDetection ??= this.database.prepare(this.labelDetectionSql);
r = this.labelDetection.iterate(e);
for (const i of r) {
if (typeof i.seq !== "number") continue;
let a = i.event_json;
if (typeof a !== "string") {
if (typeof i.navigation_json === "string") {
const { navigation: e } = JSON.parse(i.navigation_json);
if (!isRecord(e) || e.type !== "message" || !isRecord(e.message) || e.message.role !== "user" && e.message.role !== "assistant") continue;
}
this.labelCandidate ??= this.database.prepare(`SELECT ${this.eventJsonSql} AS event_json FROM transcript_events WHERE session_id = ? AND seq = ?`);
a = this.labelCandidate.get(e, i.seq)?.event_json ?? null;
}
if (typeof a !== "string" || !n(a)) continue;
let o;
try {
o = JSON.parse(a);
} catch {
continue;
}
if (!t(o)) continue;
const s = [];
this.labelSnapshot ??= this.database.prepare(this.labelRowsSql);
r = this.labelSnapshot.iterate(e);
for (const e of r) if (typeof e.event_json === "string" && typeof e.seq === "number") s.push({
eventJson: e.event_json,
seq: e.seq
});
return {
ok: true,
rows: s
};
}
return {
ok: true,
rows: []
};
} catch (e) {
resetReadIterator(r);
return {
ok: false,
error: e
};
}
}
/** Reads exact row metadata for a guarded transcript replacement without opening a writer. */
headerlessSnapshot(e, t) {
let n;
try {
this.sessionKey ??= this.database.prepare("SELECT session_key FROM session_windows WHERE session_id = ? LIMIT 1");
const r = this.sessionKey.get(e);
const i = [];
this.headerSnapshot ??= this.database.prepare(`SELECT created_at, ${this.eventJsonSql} AS event_json, seq FROM transcript_events WHERE session_id = ? ORDER BY seq ASC`);
n = this.headerSnapshot.iterate(e);
for (const r of n) {
if (typeof r.created_at !== "number" || typeof r.event_json !== "string" || typeof r.seq !== "number") return {
ok: false,
error: /* @__PURE__ */ new Error(`Invalid transcript row metadata for session ${e}`)
};
const n = {
createdAt: r.created_at,
eventJson: r.event_json,
seq: r.seq
};
if (!t(n)) return {
ok: true,
rows: []
};
i.push(n);
}
return {
ok: true,
rows: i,
...typeof r?.session_key === "string" ? { sessionKey: r.session_key } : {}
};
} catch (e) {
resetReadIterator(n);
return {
ok: false,
error: e
};
}
}
};
//#endregion
//#region src/commands/doctor-session-transcript-scan.ts
/** Each snapshot closes its cursors before a repair; each pass owns only its read connection. */
function scanDoctorSessionTranscripts(e, t) {
const reportError = (t, n) => note(`${t}: ${formatErrorMessage(n).replace(/\s+/g, " ").trim()}`, e.title);
for (const n of projectExistingAgentDatabaseTargets(resolveAllAgentSessionStoreTargetsSync(e.cfg, { env: e.env }), e.env, e.cfg)) {
const r = e.cleanScanIdentity ? beginUpdateDoctorHistoricalScan(n.sqlitePath, e.cleanScanIdentity(n)) : void 0;
if (r?.reused) {
r.complete();
continue;
}
const i = r ? {
...n,
sqlitePath: r.databasePath
} : n;
let a = true;
const reportTargetError = (e, t) => {
a = false;
reportError(e, t);
};
const o = resolveTargetSqliteOptions(i, e.env);
let s;
try {
s = openNodeSqliteDatabase(i.sqlitePath, { readOnly: true });
const n = new ReadOnlySqliteTranscriptReader(s);
const r = e.selectSessionIds ? e.selectSessionIds(n, (e, t) => reportTargetError(`- Failed to read transcript ${e} (${i.agentId})`, t)) : n.sessionIds();
for (const e of r) if (t({
reader: n,
sessionId: e,
target: i,
databaseOptions: o,
reportError: reportTargetError
}) === false) a = false;
} catch (t) {
reportTargetError(`- ${e.failureLabel} for ${i.agentId} (${i.sqlitePath})`, t);
} finally {
s?.close();
}
if (a) r?.complete();
}
}
function transcriptSnapshotsMatch(e, t, n = false) {
return e.length === t.length && e.every((e, r) => e.seq === t[r]?.seq && (!n || e.createdAt === t[r]?.createdAt) && e.eventJson === t[r]?.eventJson);
}
//#endregion
export { transcriptSnapshotsMatch as n, scanDoctorSessionTranscripts as t };