openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
927 lines (926 loc) • 29.1 kB
JavaScript
import { l as normalizeOptionalString } from "../../string-coerce-CCIiB4H7.mjs";
import { a as resolveGlobalSingleton } from "../../global-singleton-D7yf05nR.mjs";
import { o as asRecord } from "../../record-coerce-CVPuDqcc.mjs";
import { t as createPluginRuntimeProcessEntrypoint } from "../../runtime-process-manifest-DmUAODRC.mjs";
import { n as coerceErrorMessage } from "../../error-coercion-hDrHOSGy.mjs";
import { t as formatErrorMessage } from "../../errors-BKzCeTYb.mjs";
import { a as canonicalPathFromExistingAncestor } from "../../fs-safe-BbWvmdVn.mjs";
import { a as resolveRuntimeWorkerUrl } from "../../runtime-worker-url-DRDkoS4J.mjs";
import { t as SqliteWorkerError } from "../../sqlite-worker-error-DEIJgRIz.mjs";
import { t as getDatabaseEngineInput } from "../../context-DE59wyBs.mjs";
import { t as canonicalizeBase64 } from "../../base64-CnKpkbff.mjs";
import { t as KeyedAsyncQueue } from "../../keyed-async-queue-DewLnYvW.mjs";
import { t as ErrorCodes } from "../../gateway-error-details-B69XiHdh.mjs";
import { p as errorShape } from "../../error-codes-BzF7aRQ0.mjs";
import "../../file-access-runtime-BD2Fjfbw.mjs";
import "../../string-coerce-runtime-BwAZZDf5.mjs";
import "../../process-runtime-DcBPEA8Y.mjs";
import "../../error-runtime-BM740gJj.mjs";
import "../../sqlite-runtime-lcoEVOL7.mjs";
import { c as validateCardCoverage, d as buildCardsCorrectionPrompt, f as buildCardsPrompt, h as dayKeyFor, i as parseObservationSegments, l as OBSERVATION_JSON_SCHEMA, m as buildStandupPrompt, n as CARD_LOOKBACK_MS, o as revisionWindow, p as buildObservationInstructions, r as parseCardsJson, s as selectBatchFrames, t as isLogbookWriteOperation, u as buildAskPrompt } from "../../store-contract-Cgumqrte.mjs";
import { t as definePluginEntry } from "../../plugin-entry-CiJdaHtx.mjs";
import "../../media-runtime-B-kyz_D7.mjs";
import "../../gateway-runtime-Du0olVch.mjs";
import { n as runEngineStoreOperation, t as openEngineWorkerStore } from "../../database-engine-runtime-Ce6gCGxR.mjs";
import { pathToFileURL } from "node:url";
import path from "node:path";
import { createHash } from "node:crypto";
import { mkdir, readFile, writeFile } from "node:fs/promises";
//#region extensions/logbook/src/config.ts
const DEFAULTS = {
captureIntervalSeconds: 30,
analysisIntervalMinutes: 15,
screenIndex: 0,
maxWidth: 1440,
retentionDays: 14
};
function clampNumber(e, t, n, r) {
return Math.min(r, Math.max(n, Math.round(typeof e === "number" && Number.isFinite(e) ? e : t)));
}
function resolveLogbookConfig(e) {
const t = asRecord(e);
return {
captureEnabled: t.captureEnabled !== false,
captureIntervalSeconds: clampNumber(t.captureIntervalSeconds, DEFAULTS.captureIntervalSeconds, 5, 600),
analysisIntervalMinutes: clampNumber(t.analysisIntervalMinutes, DEFAULTS.analysisIntervalMinutes, 3, 120),
nodeId: normalizeOptionalString(t.nodeId),
screenIndex: clampNumber(t.screenIndex, DEFAULTS.screenIndex, 0, 16),
maxWidth: clampNumber(t.maxWidth, DEFAULTS.maxWidth, 480, 3840),
visionModel: normalizeOptionalString(t.visionModel),
retentionDays: clampNumber(t.retentionDays, DEFAULTS.retentionDays, 1, 365)
};
}
/** Splits a "provider/model" ref; model ids may themselves contain slashes. */
function parseModelRef(e) {
const t = e.indexOf("/");
if (t <= 0 || t === e.length - 1) return null;
return {
provider: e.slice(0, t),
model: e.slice(t + 1)
};
}
//#endregion
//#region extensions/logbook/src/store.ts
const MAX_FRAME_OPERATIONS = 128;
/** Frame reads and pruning share admission while SQLite remains owned by the worker. */
function acquireLogbookFrameIo(e) {
const t = resolveGlobalSingleton(Symbol.for("openclaw.logbookFrameIo"), () => ({
queue: new KeyedAsyncQueue(),
pending: 0
}));
const n = /* @__PURE__ */ new Set();
let r;
return {
run(i) {
if (r) return Promise.reject(/* @__PURE__ */ new Error("Logbook frame I/O is closed"));
if (t.pending >= MAX_FRAME_OPERATIONS) return Promise.reject(Object.assign(/* @__PURE__ */ new Error("Logbook frame I/O queue capacity reached"), { code: "overloaded" }));
t.pending += 1;
const a = t.queue.enqueue(e, i);
n.add(a);
const settle = () => {
t.pending -= 1;
n.delete(a);
};
a.then(settle, settle);
return a;
},
close() {
r ??= Promise.allSettled(n).then(() => void 0);
return r;
}
};
}
var LogbookStore = class LogbookStore {
static async open(e, t) {
if (!e) throw new Error("Logbook data directory is required");
const n = await canonicalPathFromExistingAncestor(path.resolve(e));
const r = getDatabaseEngineInput("logbook");
const i = await openEngineWorkerStore({
moduleUrl: t,
databasePath: path.join(e, "logbook.sqlite"),
input: {
dataDir: n,
postgresInput: r
}
}, r);
return new LogbookStore(e, i, acquireLogbookFrameIo(n), r);
}
constructor(e, t, n, r) {
this.dataDir = e;
this.worker = t;
this.frameIo = n;
this.postgresInput = r;
this.framesDir = path.join(e, "frames");
}
close() {
this.closing ??= (async () => {
await this.frameIo.close();
await this.worker.close();
})();
return this.closing;
}
execute(e, t) {
if (this.closing) return Promise.reject(new SqliteWorkerError("Logbook store is closed", "closed"));
return this.executeWorker(e, t);
}
executeWorker(e, t) {
return runEngineStoreOperation(this.worker, this.postgresInput, isLogbookWriteOperation(e), (n) => n.execute({
type: e,
input: t
}), void 0, path.join(this.dataDir, "logbook.sqlite"));
}
frameFilePath(e, t) {
return path.join(this.framesDir, e, `${t}.jpg`);
}
unbatchedActiveFrames(e) {
return this.execute("unbatchedActiveFrames", { limit: e });
}
countUnbatchedActiveFrames() {
return this.execute("countUnbatchedActiveFrames", void 0);
}
framesInRange(e, t) {
return this.execute("framesInRange", {
startMs: e,
endMs: t
});
}
createBatch(e) {
return this.execute("createBatch", e);
}
setBatchStatus(e, t, n, r) {
return this.execute("setBatchStatus", {
batchId: e,
status: t,
error: n,
model: r
});
}
latestBatch() {
return this.execute("latestBatch", void 0);
}
resetRunningBatches() {
return this.execute("resetRunningBatches", void 0);
}
resetErrorBatches() {
return this.execute("resetErrorBatches", void 0);
}
nextPendingBatch() {
return this.execute("nextPendingBatch", void 0);
}
replaceObservations(e, t, n) {
return this.execute("replaceObservations", {
batchId: e,
day: t,
segments: n
});
}
observationsInRange(e, t, n, r) {
return this.execute("observationsInRange", {
day: e,
startMs: t,
endMs: n,
tailLimit: r
});
}
cardsForDay(e, t) {
return this.execute("cardsForDay", {
day: e,
window: t
});
}
countCardsForDay(e) {
return this.execute("countCardsForDay", { day: e });
}
replaceCardsInWindow(e, t, n, r) {
return this.execute("replaceCardsInWindow", {
day: e,
startMs: t,
endMs: n,
drafts: r
});
}
listDays() {
return this.execute("listDays", void 0);
}
timelineForDay(e) {
return this.execute("timelineForDay", { day: e });
}
getStandup(e) {
return this.execute("getStandup", { day: e });
}
saveStandup(e, t) {
return this.execute("saveStandup", {
day: e,
text: t
});
}
captureFrame(e) {
const { buffer: t } = e;
return this.frameIo.run(async () => {
const n = createHash("sha256").update(t).digest("hex");
const r = await this.executeWorker("lastFrame", void 0);
const i = this.frameFilePath(e.day, e.capturedAtMs);
await mkdir(path.dirname(i), {
recursive: true,
mode: 448
});
await writeFile(i, t, { mode: 384 });
return await this.executeWorker("insertFrame", {
capturedAtMs: e.capturedAtMs,
day: e.day,
path: i,
screenIndex: e.screenIndex,
width: e.width,
height: e.height,
byteSize: t.byteLength,
contentHash: n,
idle: r?.contentHash === n
});
});
}
framePayload(e) {
return this.frameIo.run(async () => {
const t = await this.executeWorker("frameById", { id: e });
if (!t) return null;
return {
frameId: t.id,
capturedAtMs: t.capturedAtMs,
width: t.width,
height: t.height,
format: "jpeg",
base64: (await readFile(t.path)).toString("base64")
};
});
}
batchImages(e) {
return this.frameIo.run(async () => {
const t = await this.executeWorker("sampledBatchFrames", { batchId: e });
const n = [];
for (const e of t) n.push({
frame: e,
buffer: await readFile(e.path)
});
return n;
});
}
pruneFrames(e) {
return this.frameIo.run(() => this.executeWorker("pruneFrames", { olderThanMs: e }));
}
};
//#endregion
//#region extensions/logbook/src/service.ts
const ANALYSIS_TICK_MS = 6e4;
const PRUNE_TICK_MS = 36e5;
const MODEL_MISSING_MESSAGE = "no vision model: set plugins.entries.logbook.config.visionModel or configure tools.media";
const MODEL_MISSING_LOG_INTERVAL_MS = 6e5;
const CAPTURE_FAILURE_PAUSE_TICKS = 10;
const CAPTURE_FAILURE_THRESHOLD = 3;
const JPEG_QUALITY = .6;
const STRUCTURED_MEDIA_PROVIDER = "codex";
/** node.invoke responses wrap the node result in {payload, payloadJSON}. */
function unwrapInvokePayload(e) {
if (!e || typeof e !== "object") return null;
const t = e;
if (t.payload && typeof t.payload === "object") return t.payload;
if (typeof t.payloadJSON === "string" && t.payloadJSON.length > 0) try {
return JSON.parse(t.payloadJSON);
} catch {
return null;
}
return null;
}
/** Capture commands in preference order: app nodes first, headless node hosts second. */
const CAPTURE_COMMANDS = ["screen.snapshot", "logbook.snapshot"];
var LogbookService = class {
constructor(e, t) {
this.config = e;
this.deps = t;
this.store = null;
this.operations = /* @__PURE__ */ new Set();
this.analysisInFlight = false;
this.capturePaused = false;
this.captureFailures = 0;
this.captureBackoffTicks = 0;
this.lastModelMissingLogMs = 0;
this.cachedNode = null;
this.failedNodeIds = /* @__PURE__ */ new Set();
}
async start() {
const e = await LogbookStore.open(this.deps.dataDir, this.deps.workerModuleUrl);
this.store = e;
try {
if (this.deps.scheduler.signal.aborted) return;
await e.resetRunningBatches();
if (this.deps.scheduler.signal.aborted) return;
await this.pruneStore(e);
if (this.deps.scheduler.signal.aborted) return;
for (const [e, t, n] of [
[
"capture",
this.config.captureIntervalSeconds * 1e3,
() => this.captureTick()
],
[
"analysis",
ANALYSIS_TICK_MS,
() => this.analysisTick()
],
[
"prune",
PRUNE_TICK_MS,
() => this.prune()
]
]) this.deps.scheduler.schedule({
id: e,
delayMs: t,
everyMs: t,
run: n
});
this.deps.logger.info(`logbook: started (capture every ${this.config.captureIntervalSeconds}s, analysis window ${this.config.analysisIntervalMinutes}m, data ${this.deps.dataDir})`);
} catch (t) {
this.store = null;
await e.close();
throw t;
}
}
stop() {
if (this.stopping) return this.stopping;
this.deps.scheduler.beginClose();
this.stopping = Promise.allSettled([this.deps.scheduler.stop(), ...this.operations]).then(async () => {
const e = this.store;
this.store = null;
await e?.close();
});
return this.stopping;
}
trackOperation(e) {
const t = Promise.resolve().then(e);
this.operations.add(t);
const settled = () => this.operations.delete(t);
t.then(settled, settled);
return t;
}
requireStore() {
if (this.deps.scheduler.signal.aborted || !this.store) throw new Error("Logbook service is not running");
return this.store;
}
setCapturePaused(e) {
this.capturePaused = e;
if (!e) {
this.captureBackoffTicks = 0;
this.captureFailures = 0;
}
}
async resolveNode() {
if (this.cachedNode) return { node: this.cachedNode };
const { nodes: e } = await this.deps.runtime.nodes.list({ connected: true });
const captureCommand = (e) => CAPTURE_COMMANDS.find((t) => (e.commands ?? []).includes(t));
const commandRank = (e) => CAPTURE_COMMANDS.indexOf(captureCommand(e));
const t = e.filter((e) => captureCommand(e) !== void 0).toSorted((e, t) => commandRank(e) - commandRank(t) || e.nodeId.localeCompare(t.nodeId));
const n = this.config.nodeId?.toLowerCase();
let r = t.filter((e) => !this.failedNodeIds.has(e.nodeId));
if (r.length === 0) {
this.failedNodeIds.clear();
r = t;
}
const i = n ? t.find((e) => e.nodeId.toLowerCase() === n || e.displayName?.toLowerCase() === n) : r[0];
const a = i ? captureCommand(i) : void 0;
if (!i || !a) {
const t = e.map((e) => `${e.displayName ?? e.nodeId}(${(e.commands ?? []).join("/") || "no commands"})`).join(", ") || "none";
return { reason: `no connected node exposes ${CAPTURE_COMMANDS.join(" or ")}; connected: ${t}` };
}
this.cachedNode = {
nodeId: i.nodeId,
displayName: i.displayName,
command: a
};
return { node: this.cachedNode };
}
async captureTick() {
const e = this.store;
if (this.deps.scheduler.signal.aborted || !this.config.captureEnabled || this.capturePaused || !e) return;
if (this.captureBackoffTicks > 0) {
this.captureBackoffTicks -= 1;
return;
}
return this.trackOperation(async () => {
try {
const t = await this.resolveNode();
if ("reason" in t) {
if (this.lastCaptureError !== t.reason) this.deps.logger.warn(`logbook: ${t.reason}`);
this.lastCaptureError = t.reason;
return;
}
const n = t.node;
const r = unwrapInvokePayload(await this.deps.runtime.nodes.invoke({
nodeId: n.nodeId,
command: n.command,
params: {
screenIndex: this.config.screenIndex,
maxWidth: this.config.maxWidth,
quality: JPEG_QUALITY,
format: "jpeg"
},
timeoutMs: 3e4
}));
if (r?.error) throw new Error(r.error);
const i = r?.base64;
if (i === void 0 || i === "") throw new Error(`${n.command} returned no image payload`);
if (typeof i !== "string") throw new Error(`${n.command} returned invalid image payload`);
const a = canonicalizeBase64(i);
if (!a) throw new Error(`${n.command} returned invalid image payload`);
const o = Buffer.from(a, "base64");
const s = Date.now();
const c = dayKeyFor(s);
await e.captureFrame({
capturedAtMs: s,
day: c,
screenIndex: this.config.screenIndex,
width: r?.width,
height: r?.height,
buffer: o
});
this.lastCaptureAtMs = s;
this.lastCaptureError = void 0;
this.captureFailures = 0;
this.failedNodeIds.clear();
} catch (e) {
this.captureFailures += 1;
if (this.cachedNode) this.failedNodeIds.add(this.cachedNode.nodeId);
this.cachedNode = null;
this.lastCaptureError = coerceErrorMessage(e);
if (this.captureFailures >= CAPTURE_FAILURE_THRESHOLD) {
this.captureBackoffTicks = CAPTURE_FAILURE_PAUSE_TICKS;
this.deps.logger.warn(`logbook: capture failing (${this.lastCaptureError}); backing off for ${CAPTURE_FAILURE_PAUSE_TICKS} ticks`);
}
}
});
}
resolveVisionModel() {
if (this.config.visionModel) {
const e = parseModelRef(this.config.visionModel);
return e ? {
ref: e,
source: "config"
} : { source: "missing" };
}
const e = this.deps.fullConfig.tools?.media;
if (e?.image?.enabled === false) return { source: "missing" };
const t = e?.models ?? [];
for (const e of t) if (e.type !== "cli" && e.provider?.trim().toLowerCase() === STRUCTURED_MEDIA_PROVIDER && typeof e.model === "string" && (!e.capabilities || e.capabilities.includes("image"))) return {
ref: {
provider: STRUCTURED_MEDIA_PROVIDER,
model: e.model,
profile: e.profile,
preferredProfile: e.preferredProfile
},
source: "media-defaults"
};
return { source: "missing" };
}
async analyzeNow() {
const e = this.requireStore();
if (this.analysisInFlight) return {
started: false,
reason: "analysis already running"
};
if (!this.resolveVisionModel().ref) return {
started: false,
reason: MODEL_MISSING_MESSAGE
};
this.analysisInFlight = true;
return this.trackOperation(async () => {
try {
await e.resetErrorBatches();
if (!await e.nextPendingBatch()) {
if (!await this.enqueueNextBatch(e, true)) return {
started: false,
reason: "no unanalyzed activity captured yet"
};
}
this.requireStore();
} finally {
this.analysisInFlight = false;
}
this.analysisTick();
return { started: true };
});
}
async analysisTick() {
const e = this.store;
if (this.deps.scheduler.signal.aborted || this.analysisInFlight || !e) return;
if (!this.resolveVisionModel().ref) {
const t = Date.now();
if (t - this.lastModelMissingLogMs > MODEL_MISSING_LOG_INTERVAL_MS) try {
if ((await e.countUnbatchedActiveFrames() > 0 || Boolean(await e.nextPendingBatch())) && !this.deps.scheduler.signal.aborted) {
this.lastModelMissingLogMs = t;
this.deps.logger.warn(`logbook: analysis paused; ${MODEL_MISSING_MESSAGE}`);
}
} catch (e) {
if (!this.deps.scheduler.signal.aborted) this.deps.logger.error(`logbook: analysis tick failed: ${String(e)}`);
}
return;
}
this.analysisInFlight = true;
return this.trackOperation(async () => {
try {
if (this.deps.scheduler.signal.aborted) return;
await this.enqueueElapsedWindow(e);
for (let t = 0; t < 4 && !this.deps.scheduler.signal.aborted; t += 1) {
const t = await e.nextPendingBatch();
if (!t || this.deps.scheduler.signal.aborted) return;
await this.runBatch(e, t);
}
} catch (e) {
this.deps.logger.error(`logbook: analysis tick failed: ${String(e)}`);
} finally {
this.analysisInFlight = false;
}
});
}
async enqueueNextBatch(e, t = false) {
const n = selectBatchFrames({
frames: await e.unbatchedActiveFrames(2e3),
windowMs: this.config.analysisIntervalMinutes * 6e4,
nowMs: Date.now(),
force: t
});
if (!n) return false;
await e.createBatch({
day: dayKeyFor(n.startMs),
startMs: n.startMs,
endMs: n.endMs,
frameIds: n.frameIds
});
return true;
}
async enqueueElapsedWindow(e) {
while (!this.deps.scheduler.signal.aborted && await this.enqueueNextBatch(e));
}
async runBatch(e, t) {
const n = this.resolveVisionModel();
if (!n.ref) return;
await e.setBatchStatus(t.id, "running", void 0, `${n.ref.provider}/${n.ref.model}`);
try {
const r = await e.batchImages(t.id);
const i = r.map(({ frame: e, buffer: t }) => ({
type: "image",
buffer: t,
fileName: path.basename(e.path),
mime: "image/jpeg"
}));
const a = await this.deps.runtime.mediaUnderstanding.extractStructuredWithModel({
provider: n.ref.provider,
model: n.ref.model,
profile: n.ref.profile,
preferredProfile: n.ref.preferredProfile,
input: i,
instructions: buildObservationInstructions({
frameTimes: r.map(({ frame: e }) => e.capturedAtMs),
startMs: t.startMs,
endMs: t.endMs
}),
schemaName: "logbook.observations",
jsonSchema: OBSERVATION_JSON_SCHEMA,
cfg: this.deps.fullConfig,
timeoutMs: 18e4
});
const o = parseObservationSegments({
raw: a.text ?? "",
day: t.day,
startMs: t.startMs,
endMs: t.endMs
});
if (o.length === 0) {
await e.setBatchStatus(t.id, "error", "vision model returned no usable segments");
return;
}
await e.replaceObservations(t.id, t.day, o);
await this.reviseCards(e, t);
await e.setBatchStatus(t.id, "done");
} catch (n) {
const r = coerceErrorMessage(n);
await e.setBatchStatus(t.id, "error", r);
this.deps.logger.warn(`logbook: batch ${t.id} failed: ${r}`);
}
}
async reviseCards(e, t) {
const n = t.startMs - CARD_LOOKBACK_MS;
const r = await e.cardsForDay(t.day, {
startMs: n,
endMs: t.endMs
});
const i = await e.observationsInRange(t.day, n, t.endMs);
const a = revisionWindow({
batchStartMs: t.startMs,
batchEndMs: t.endMs,
previousCards: r
});
const o = buildCardsPrompt({
day: t.day,
observations: i,
previousCards: r,
windowStartMs: a.startMs,
windowEndMs: a.endMs
});
const s = [...r.map((e) => ({
startMs: e.startMs,
endMs: e.endMs
})), {
startMs: t.startMs,
endMs: t.endMs
}];
const evaluate = (e) => {
const n = parseCardsJson({
raw: e,
day: t.day
});
if (!n.ok) return n;
const r = validateCardCoverage({
drafts: n.drafts,
requiredSpans: s,
windowStartMs: a.startMs,
windowEndMs: a.endMs
});
return r.ok ? n : {
ok: false,
error: r.error
};
};
const c = await this.deps.runtime.llm.complete({
messages: [{
role: "user",
content: o
}],
purpose: "logbook.cards",
maxTokens: 4e3
});
let l = evaluate(c.text);
if (!l.ok) l = evaluate((await this.deps.runtime.llm.complete({
messages: [
{
role: "user",
content: o
},
{
role: "assistant",
content: c.text
},
{
role: "user",
content: buildCardsCorrectionPrompt(l.error)
}
],
purpose: "logbook.cards.repair",
maxTokens: 4e3
})).text);
if (!l.ok) throw new Error(`card synthesis failed validation: ${l.error}`);
await e.replaceCardsInWindow(t.day, a.startMs, a.endMs, l.drafts);
}
async standup(e, t) {
const n = this.requireStore();
return this.trackOperation(async () => {
if (!t) {
const t = await n.getStandup(e);
if (t) return t;
}
const r = dayKeyFor((/* @__PURE__ */ new Date(`${e}T12:00:00`)).getTime() - 864e5);
const i = await this.deps.runtime.llm.complete({
messages: [{
role: "user",
content: buildStandupPrompt({
day: e,
cards: await n.cardsForDay(e),
previousDayCards: await n.cardsForDay(r)
})
}],
purpose: "logbook.standup",
maxTokens: 800
});
return await n.saveStandup(e, i.text.trim());
});
}
async ask(e, t) {
const n = this.requireStore();
return this.trackOperation(async () => {
const r = await n.observationsInRange(e, 0, Number.MAX_SAFE_INTEGER, 200);
return (await this.deps.runtime.llm.complete({
messages: [{
role: "user",
content: buildAskPrompt({
day: e,
cards: await n.cardsForDay(e),
observations: r,
question: t
})
}],
purpose: "logbook.ask",
maxTokens: 600
})).text.trim();
});
}
async timelineForDay(e) {
const t = this.requireStore();
return this.trackOperation(() => t.timelineForDay(e));
}
async listDays() {
const e = this.requireStore();
return this.trackOperation(() => e.listDays());
}
async framePayload(e) {
const t = this.requireStore();
return this.trackOperation(() => t.framePayload(e));
}
async framesInRange(e, t) {
const n = this.requireStore();
return this.trackOperation(() => n.framesInRange(e, t));
}
async status() {
const e = this.requireStore();
return this.trackOperation(async () => {
const t = dayKeyFor(Date.now());
const n = await e.latestBatch();
const r = this.resolveVisionModel();
return {
captureEnabled: this.config.captureEnabled,
capturePaused: this.capturePaused,
captureIntervalSeconds: this.config.captureIntervalSeconds,
analysisIntervalMinutes: this.config.analysisIntervalMinutes,
retentionDays: this.config.retentionDays,
nodeId: this.cachedNode?.nodeId ?? this.config.nodeId,
nodeName: this.cachedNode?.displayName,
lastCaptureAtMs: this.lastCaptureAtMs,
lastCaptureError: this.lastCaptureError,
pendingFrames: await e.countUnbatchedActiveFrames(),
analysisRunning: this.analysisInFlight,
lastBatch: n ? {
id: n.id,
day: n.day,
status: n.status,
endMs: n.endMs,
error: n.error
} : void 0,
visionModel: r.ref ? `${r.ref.provider}/${r.ref.model}` : void 0,
visionModelSource: r.source,
today: t,
todayCards: await e.countCardsForDay(t),
timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone
};
});
}
async prune() {
const e = this.store;
if (this.deps.scheduler.signal.aborted || !e) return;
return this.trackOperation(async () => {
try {
await this.pruneStore(e);
} catch (e) {
this.deps.logger.error(`logbook: pruning failed: ${String(e)}`);
}
});
}
async pruneStore(e) {
const t = Date.now() - this.config.retentionDays * 24 * 60 * 60 * 1e3;
const n = await e.pruneFrames(t);
if (n > 0) this.deps.logger.info(`logbook: pruned ${n} frames older than ${this.config.retentionDays}d`);
}
};
//#endregion
//#region extensions/logbook/index.ts
const DAY_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
const logbookConfigSchema = { parse: resolveLogbookConfig };
function readDayParam(e) {
const t = e?.day;
if (t === void 0) return dayKeyFor(Date.now());
if (typeof t !== "string" || !DAY_PATTERN.test(t)) throw new Error("day must be YYYY-MM-DD");
return t;
}
function readNumberParam(e, t) {
const n = e?.[t];
if (typeof n !== "number" || !Number.isFinite(n) || n <= 0) throw new Error(`${t} must be a positive number`);
return n;
}
const logbookNodeHostCommands = [{
command: "logbook.snapshot",
hasActiveWork: () => false,
cap: "screen",
dangerous: false,
handle: async (e) => {
const { handleLogbookSnapshot: t } = await import("../../node-host-DCBINwhp.mjs");
let n;
try {
n = e ? JSON.parse(e) : void 0;
} catch {
n = void 0;
}
return JSON.stringify(await t(n));
}
}];
var logbook_default = definePluginEntry({
id: "logbook",
name: "Logbook",
description: "Automatic work journal built from periodic screen snapshots",
configSchema: logbookConfigSchema,
nodeHostCommands: logbookNodeHostCommands,
register(e) {
const t = logbookConfigSchema.parse(e.pluginConfig);
let n = null;
const requireService = () => {
if (!n) throw new Error("Logbook service is not running");
return n;
};
const handle = (e) => async ({ params: t, respond: n }) => {
try {
n(true, await e(t));
} catch (e) {
const t = formatErrorMessage(e);
n(false, { error: t }, errorShape(ErrorCodes.UNAVAILABLE, t));
}
};
e.session.controls.registerControlUiDescriptor({
surface: "tab",
id: "logbook",
label: "Logbook",
description: "Your day as a timeline, built from screen snapshots.",
icon: "sun",
group: "control",
requiredScopes: ["operator.write"]
});
e.registerNodeInvokePolicy({
commands: ["logbook.snapshot"],
defaultPlatforms: ["macos"],
handle: async (e) => {
if ((e.config.gateway?.nodes?.commands?.deny ?? []).includes("screen.snapshot")) return {
ok: false,
code: "SCREEN_CAPTURE_DENIED",
message: "screen capture is denied by gateway.nodes.commands.deny (screen.snapshot); Logbook capture stays blocked until it is removed"
};
return await e.invokeNode();
}
});
e.registerService({
id: "logbook",
apiVersion: 2,
start: async (r) => {
if (!e.runtimeSource) throw new Error("Logbook requires an OpenClaw host with runtime entrypoint metadata");
const i = new LogbookService(t, {
runtime: e.runtime,
fullConfig: r.config,
logger: r.logger,
scheduler: r.scheduler,
dataDir: path.join(r.stateDir, "logbook"),
workerModuleUrl: resolveRuntimeWorkerUrl(createPluginRuntimeProcessEntrypoint("logbookStore", pathToFileURL(e.runtimeSource).href))
});
try {
await i.start();
n = i;
} catch (e) {
await i.stop();
throw e;
}
},
async stop() {
const e = n;
n = null;
await e?.stop();
}
});
const registerRead = (t, n) => e.registerGatewayMethod(t, handle(n), { scope: "operator.read" });
const registerWrite = (t, n) => e.registerGatewayMethod(t, handle(n), { scope: "operator.write" });
e.registerGatewayMethod("logbook.status", handle(() => requireService().status()), {
scope: "operator.read",
profileAccess: "independent"
});
registerRead("logbook.days", async () => ({ days: await requireService().listDays() }));
registerRead("logbook.timeline", (e) => requireService().timelineForDay(readDayParam(e)));
registerWrite("logbook.frames", async (e) => {
const t = readNumberParam(e, "startMs");
const n = readNumberParam(e, "endMs");
return { frames: await requireService().framesInRange(t, n) };
});
registerWrite("logbook.frame", async (e) => {
const t = readNumberParam(e, "frameId");
const n = await requireService().framePayload(t);
if (!n) throw new Error(`frame ${t} not found`);
return n;
});
registerWrite("logbook.standup", (e) => {
const t = e?.refresh === true;
return requireService().standup(readDayParam(e), t);
});
registerWrite("logbook.ask", async (e) => {
const t = e?.question;
if (typeof t !== "string" || t.trim().length === 0) throw new Error("question is required");
return { answer: await requireService().ask(readDayParam(e), t.trim()) };
});
registerWrite("logbook.capture.set", (e) => {
const t = e?.paused === true;
const n = requireService();
n.setCapturePaused(t);
return n.status();
});
registerWrite("logbook.analyze.now", () => requireService().analyzeNow());
}
});
//#endregion
export { logbook_default as default };