openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
406 lines (405 loc) • 14.8 kB
JavaScript
import { a as executeSqliteQueryTakeFirstSync, i as executeSqliteQuerySync, s as getNodeSqliteKysely, u as prepareSqliteQuerySync } from "../../../kysely-sync-YJo2lmGV.mjs";
import { a as runSqliteImmediateTransactionSync } from "../../../sqlite-transaction-BHHu6P5-.mjs";
import { f as requestSqliteWorkerOperationAdmission } from "../../../sqlite-worker-operation-admission-9E_X-oRy.mjs";
import { i as runEngineWorkerWrite } from "../../../adapters-D8O-uubH.mjs";
import "../../../sqlite-worker-runtime-CKocuU_N.mjs";
import "../../../database-engine-worker-runtime-DzyfC3BE.mjs";
import { t as expectDefined } from "../../../expect-runtime-DT3P17Ul.mjs";
import { a as pickKeyframeId, t as isLogbookWriteOperation } from "../../../store-contract-Cgumqrte.mjs";
import { a as toFrame, i as toCard, n as createLogbookDatabase, r as toBatch, t as LOGBOOK_SQLITE_BUSY_TIMEOUT_MS } from "../../../store-schema-admission-CE1vGsO-.mjs";
import { chmodSync, mkdirSync, rmSync, rmdirSync } from "node:fs";
import path from "node:path";
//#region extensions/logbook/src/store.worker.ts
const WRITE_BATCH_SIZE = 64;
const FRAME_PRUNE_BATCH_SIZE = 64;
function runAdmittedTransaction(e, t) {
requestSqliteWorkerOperationAdmission({
stage: "transaction",
facts: void 0
});
return runSqliteImmediateTransactionSync(e, t, { withCommit(e) {
requestSqliteWorkerOperationAdmission({
stage: "commit",
facts: void 0
});
e();
} });
}
var LogbookDatabaseStore = class {
constructor(e, t, n) {
this.postgresInput = n;
mkdirSync(e, {
recursive: true,
mode: 448
});
chmodSync(e, 448);
this.framesDir = path.join(e, "frames");
mkdirSync(this.framesDir, {
recursive: true,
mode: 448
});
chmodSync(this.framesDir, 448);
const r = createLogbookDatabase(t, n);
const { db: i } = r;
try {
this.db = i;
this.database = r;
this.query = getNodeSqliteKysely(i);
const e = this.query.selectFrom("frames").select([
"id",
"captured_at_ms",
"day",
"path",
"screen_index",
"width",
"height",
"byte_size",
"idle"
]).orderBy("captured_at_ms", "asc").orderBy("id", "asc");
const t = prepareSqliteQuerySync(i, (t) => {
const n = this.query.with("ordered_frames", (e) => e.selectFrom("frames").select("id").select((e) => [e.fn.agg("row_number", []).over((e) => e.orderBy("captured_at_ms", "asc").orderBy("id", "asc")).as("ordinal"), e.fn.countAll().over().as("total")]).where("batch_id", "=", t((e) => e))).selectFrom("ordered_frames").select("id").where((e) => {
const t = e(e.cast(e("total", "-", e.val(1)), "real"), "/", e.val(16 - 1));
return e.or([e("total", "<=", 16), ...Array.from({ length: 16 }, (n, r) => e("ordinal", "=", e(e.cast(e.fn("floor", [e(e(e.val(r), "*", t), "+", e.val(.5))]), "integer"), "+", e.val(1))))]);
});
return e.where("id", "in", n);
});
this.framesQuery = e;
this.frameMetadataQuery = e.clearSelect().select([
"id",
"captured_at_ms",
"screen_index",
"width",
"height",
"byte_size",
"idle"
]);
this.batchesQuery = this.query.selectFrom("batches").select([
"id",
"day",
"start_ms",
"end_ms",
"status",
"error",
"frame_count",
"model"
]);
this.cardsQuery = this.query.selectFrom("cards");
this.statements = {
sampledBatchFrames: t,
insertFrame: prepareSqliteQuerySync(i, (e) => this.query.insertInto("frames").values({
captured_at_ms: e((e) => e.capturedAtMs),
day: e((e) => e.day),
path: e((e) => e.path),
screen_index: e((e) => e.screenIndex),
width: e((e) => e.width ?? null),
height: e((e) => e.height ?? null),
byte_size: e((e) => e.byteSize),
content_hash: e((e) => e.contentHash),
idle: e((e) => e.idle ? 1 : 0)
}).returning("id")),
insertBatch: prepareSqliteQuerySync(i, (e) => this.query.insertInto("batches").values({
day: e((e) => e.day),
start_ms: e((e) => e.startMs),
end_ms: e((e) => e.endMs),
status: "pending",
frame_count: e((e) => e.frameIds.length),
created_ms: e((e) => e.now),
updated_ms: e((e) => e.now)
}).returning("id")),
setBatchStatus: prepareSqliteQuerySync(i, (e) => this.query.updateTable("batches").set((t) => ({
status: e((e) => e.status),
error: e((e) => e.error ?? null),
model: t.fn.coalesce(e((e) => e.model ?? null), "model"),
updated_ms: e((e) => e.now)
})).where("id", "=", e((e) => e.batchId))),
resetRunningBatches: prepareSqliteQuerySync(i, (e) => this.query.updateTable("batches").set({
status: "pending",
updated_ms: e((e) => e)
}).where("status", "=", "running")),
resetErrorBatches: prepareSqliteQuerySync(i, (e) => this.query.updateTable("batches").set({
status: "pending",
error: null,
updated_ms: e((e) => e)
}).where("status", "=", "error")),
deleteObservations: prepareSqliteQuerySync(i, (e) => this.query.deleteFrom("observations").where("batch_id", "=", e((e) => e))),
deleteCards: prepareSqliteQuerySync(i, (e) => this.query.deleteFrom("cards").where("day", "=", e((e) => e.day)).where("end_ms", ">", e((e) => e.startMs)).where("start_ms", "<", e((e) => e.endMs))),
saveStandup: prepareSqliteQuerySync(i, (e) => this.query.insertInto("standups").values({
day: e((e) => e.day),
text: e((e) => e.text),
updated_ms: e((e) => e.now)
}).onConflict((e) => e.column("day").doUpdateSet((e) => ({
text: e.ref("excluded.text"),
updated_ms: e.ref("excluded.updated_ms")
}))))
};
} catch (e) {
r.close().catch(() => {});
throw e;
}
}
runTransaction(e, t) {
return runSqliteImmediateTransactionSync(this.db, t, {
busyTimeoutMs: LOGBOOK_SQLITE_BUSY_TIMEOUT_MS,
databaseLabel: "logbook",
operationLabel: e
});
}
get connection() {
return this.db;
}
close() {
return this.database.close();
}
insertFrame(e) {
const t = this.statements.insertFrame(e);
return expectDefined(t.rows[0], "Logbook inserted frame").id;
}
lastFrame() {
const e = executeSqliteQueryTakeFirstSync(this.db, this.query.selectFrom("frames").select(["captured_at_ms", "content_hash"]).orderBy("captured_at_ms", "desc").orderBy("id", "desc").limit(1));
return e ? {
capturedAtMs: e.captured_at_ms,
contentHash: e.content_hash
} : null;
}
unbatchedActiveFrames({ limit: e }) {
return executeSqliteQuerySync(this.db, this.frameMetadataQuery.where("batch_id", "is", null).where("idle", "=", 0).limit(e)).rows.map((e) => ({
id: e.id,
capturedAtMs: e.captured_at_ms
}));
}
countUnbatchedActiveFrames() {
const e = executeSqliteQueryTakeFirstSync(this.db, this.query.selectFrom("frames").select((e) => e.fn.countAll().as("n")).where("batch_id", "is", null).where("idle", "=", 0));
return expectDefined(e, "Logbook unbatched frame count").n;
}
frameById({ id: e }) {
const t = executeSqliteQueryTakeFirstSync(this.db, this.framesQuery.where("id", "=", e));
return t ? toFrame(t) : null;
}
framesInRange({ startMs: e, endMs: t }) {
return executeSqliteQuerySync(this.db, this.frameMetadataQuery.where("captured_at_ms", ">=", e).where("captured_at_ms", "<", t)).rows.map((e) => ({
id: e.id,
capturedAtMs: e.captured_at_ms,
idle: e.idle === 1
}));
}
createBatch(e) {
if (e.frameIds.length === 0) throw new Error("Logbook batch requires at least one frame");
const t = Date.now();
return this.runTransaction("logbook.batch.create", () => {
const n = this.statements.insertBatch({
...e,
now: t
});
const r = expectDefined(n.rows[0], "Logbook inserted batch").id;
for (let t = 0; t < e.frameIds.length; t += WRITE_BATCH_SIZE) {
const n = e.frameIds.slice(t, t + WRITE_BATCH_SIZE);
const i = executeSqliteQuerySync(this.db, this.query.updateTable("frames").set({ batch_id: r }).where("id", "in", n).where("batch_id", "is", null).returning("id"));
const a = new Set(i.rows.map((e) => e.id));
for (const e of n) if (!a.delete(e)) throw new Error(`Logbook frame ${e} is missing or already batched`);
}
return r;
});
}
setBatchStatus(e) {
this.statements.setBatchStatus({
...e,
now: Date.now()
});
}
latestBatch() {
const e = executeSqliteQueryTakeFirstSync(this.db, this.batchesQuery.orderBy("id", "desc").limit(1));
return e ? toBatch(e) : null;
}
/** Requeues batches stuck in `running` after a crash so frames are not orphaned. */
resetRunningBatches() {
this.statements.resetRunningBatches(Date.now());
}
/** Requeues failed batches for an explicit user-driven retry (analyze now). */
resetErrorBatches() {
const e = this.statements.resetErrorBatches(Date.now());
return Number(expectDefined(e.numAffectedRows, "Logbook reset batch count"));
}
nextPendingBatch() {
const e = executeSqliteQueryTakeFirstSync(this.db, this.batchesQuery.where("status", "=", "pending").orderBy("start_ms", "asc").orderBy("id", "asc").limit(1));
return e ? toBatch(e) : null;
}
sampledBatchFrames({ batchId: e }) {
return this.statements.sampledBatchFrames(e).rows.map(toFrame);
}
replaceObservations({ batchId: e, day: t, segments: n }) {
this.runTransaction("logbook.observations.replace", () => {
this.statements.deleteObservations(e);
for (let r = 0; r < n.length; r += WRITE_BATCH_SIZE) executeSqliteQuerySync(this.db, this.query.insertInto("observations").values(n.slice(r, r + WRITE_BATCH_SIZE).map((n) => ({
batch_id: e,
day: t,
start_ms: n.startMs,
end_ms: n.endMs,
text: n.text
}))));
});
}
observationsInRange({ day: e, startMs: t, endMs: n, tailLimit: r }) {
const i = r === void 0 ? "asc" : "desc";
let a = this.query.selectFrom("observations").selectAll().where("day", "=", e).where("end_ms", ">", t).where("start_ms", "<", n).orderBy("start_ms", i).orderBy("id", i);
if (r !== void 0) a = a.limit(r);
const o = executeSqliteQuerySync(this.db, a).rows;
if (r !== void 0) o.reverse();
return o.map((e) => ({
id: e.id,
batchId: e.batch_id,
day: e.day,
startMs: e.start_ms,
endMs: e.end_ms,
text: e.text
}));
}
cardsForDay({ day: e, window: t }) {
let n = this.cardsQuery.selectAll().where("day", "=", e).orderBy("start_ms", "asc").orderBy("id", "asc");
if (t) n = n.where("end_ms", ">", t.startMs).where("start_ms", "<", t.endMs);
return executeSqliteQuerySync(this.db, n).rows.map(toCard);
}
countCardsForDay({ day: e }) {
const t = executeSqliteQueryTakeFirstSync(this.db, this.cardsQuery.select((e) => e.fn.countAll().as("count")).where("day", "=", e));
return expectDefined(t, "Logbook card count").count;
}
replaceCardsInWindow({ day: e, startMs: t, endMs: n, drafts: r }) {
const i = Date.now();
this.runTransaction("logbook.cards.replace", () => {
const a = executeSqliteQuerySync(this.db, this.frameMetadataQuery.where("captured_at_ms", ">=", t).where("captured_at_ms", "<", n)).rows.map((e) => ({
id: e.id,
capturedAtMs: e.captured_at_ms
}));
this.statements.deleteCards({
day: e,
startMs: t,
endMs: n
});
for (let e = 0; e < r.length; e += WRITE_BATCH_SIZE) executeSqliteQuerySync(this.db, this.query.insertInto("cards").values(r.slice(e, e + WRITE_BATCH_SIZE).map((e) => ({
day: e.day,
start_ms: e.startMs,
end_ms: e.endMs,
title: e.title,
summary: e.summary,
detail: e.detail,
category: e.category,
app_primary: e.appPrimary ?? null,
app_secondary: e.appSecondary ?? null,
distractions: JSON.stringify(e.distractions),
keyframe_id: pickKeyframeId(e, a) ?? null,
updated_ms: i
}))));
});
}
listDays() {
return executeSqliteQuerySync(this.db, this.cardsQuery.select((e) => [
"day",
e.fn.countAll().as("cards"),
e.fn.min("start_ms").as("first_ms"),
e.fn.max("end_ms").as("last_ms")
]).groupBy("day").orderBy("day", "desc")).rows.map((e) => ({
day: e.day,
cards: e.cards,
firstMs: e.first_ms,
lastMs: e.last_ms
}));
}
timelineForDay({ day: e }) {
const t = this.cardsForDay({ day: e });
const n = /* @__PURE__ */ new Map();
const r = /* @__PURE__ */ new Map();
let i = 0;
let a = 0;
for (const e of t) {
const t = Math.max(0, e.endMs - e.startMs);
i += t;
n.set(e.category, (n.get(e.category) ?? 0) + t);
if (e.appPrimary) r.set(e.appPrimary, (r.get(e.appPrimary) ?? 0) + t);
for (const t of e.distractions) a += Math.max(0, t.endMs - t.startMs);
}
const byMsDesc = (e, t) => t.ms - e.ms;
return {
day: e,
cards: t,
stats: {
trackedMs: i,
distractionMs: a,
categories: [...n.entries()].map(([e, t]) => ({
category: e,
ms: t
})).toSorted(byMsDesc),
apps: [...r.entries()].map(([e, t]) => ({
domain: e,
ms: t
})).toSorted(byMsDesc)
}
};
}
getStandup({ day: e }) {
const t = executeSqliteQueryTakeFirstSync(this.db, this.query.selectFrom("standups").selectAll().where("day", "=", e));
return t ? {
day: t.day,
text: t.text,
updatedMs: t.updated_ms
} : null;
}
saveStandup({ day: e, text: t }) {
const n = Date.now();
this.statements.saveStandup({
day: e,
text: t,
now: n
});
return {
day: e,
text: t,
updatedMs: n
};
}
pruneFrames({ olderThanMs: e }) {
const t = executeSqliteQuerySync(this.db, this.query.selectFrom("frames").select([
"id",
"path",
"day"
]).where("captured_at_ms", "<", e)).rows;
if (t.length === 0) return 0;
if (this.postgresInput) requestSqliteWorkerOperationAdmission({
stage: "transaction",
facts: void 0
});
const n = /* @__PURE__ */ new Set();
for (const e of t) {
rmSync(e.path, { force: true });
n.add(e.day);
}
const deleteMetadata = () => {
let e = 0;
for (let n = 0; n < t.length; n += FRAME_PRUNE_BATCH_SIZE) {
const r = t.slice(n, n + FRAME_PRUNE_BATCH_SIZE).map((e) => e.id);
const i = executeSqliteQuerySync(this.db, this.query.deleteFrom("frames").where("id", "in", r));
e += Number(expectDefined(i.numAffectedRows, "Logbook pruned frame count"));
}
return e;
};
const r = this.postgresInput ? runAdmittedTransaction(this.db, deleteMetadata) : this.runTransaction("logbook.frames.prune", deleteMetadata);
for (const e of n) try {
rmdirSync(path.join(this.framesDir, e));
} catch {}
return r;
}
};
function createSqliteWorkerBackend(e, t) {
const n = new LogbookDatabaseStore(e.dataDir, t.databasePath, e.postgresInput);
const r = n;
function dispatch(e) {
return r[e.type](e.input);
}
return {
execute(t) {
const execute = () => dispatch(t);
return isLogbookWriteOperation(t.type) && t.type !== "pruneFrames" ? runEngineWorkerWrite(e.postgresInput, execute, (e) => runAdmittedTransaction(n.connection, e)) : execute();
},
close: () => n.close()
};
}
//#endregion
export { createSqliteWorkerBackend };