openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
298 lines (297 loc) • 9.65 kB
JavaScript
import { p as toErrorObject } from "./error-coercion-hDrHOSGy.mjs";
import { r as resolveStateDir } from "./state-dir-DiG0gXzD.mjs";
import { a as resolveRuntimeWorkerUrl } from "./runtime-worker-url-DRDkoS4J.mjs";
import { i as ensureSqliteLibrarySelected } from "./bun-sqlite-library-BvzuPYCx.mjs";
import { Y as DatabaseSearchCapabilityUnavailableError } from "./sqlite-schema-facts-B1bVE8IB.mjs";
import { t as WorkerTaskPool } from "./worker-task-pool-BshJjv1P.mjs";
import "./process-runtime-DcBPEA8Y.mjs";
import "./error-runtime-BM740gJj.mjs";
import "./memory-core-host-engine-knn-CywcE63C.mjs";
import "./memory-core-host-engine-storage-DcaZNQQh.mjs";
import { n as sessionIndexPages } from "./manager-session-index-preparation-3h_bst18.mjs";
import { t as memoryCpuProcessEntrypoints } from "./manager-cpu-entrypoints-CEJDRP3Q.mjs";
import "./memory-core-host-engine-foundation-CvV28XoZ.mjs";
//#region extensions/memory-core/src/memory/manager-cpu-worker-runtime.ts
const MEMORY_INDEX_WORKER_INPUT_LIMIT_BYTES = 268435456;
const SESSION_INDEX_PAGE_INPUT_BYTES = 65536;
const retrieval = new WorkerTaskPool({
workerUrl: resolveRuntimeWorkerUrl(memoryCpuProcessEntrypoints.search),
workerClass: "reader",
sharedCompute: true
});
const indexing = new WorkerTaskPool({
workerUrl: resolveRuntimeWorkerUrl(memoryCpuProcessEntrypoints.index),
workerClass: "compute",
sharedCompute: true,
maxPendingBytes: MEMORY_INDEX_WORKER_INPUT_LIMIT_BYTES
});
const sessionIndexing = new WorkerTaskPool({
workerUrl: resolveRuntimeWorkerUrl(memoryCpuProcessEntrypoints.index),
workerClass: "compute",
maxWorkers: 1,
maxPendingBytes: MEMORY_INDEX_WORKER_INPUT_LIMIT_BYTES
});
function hasResultKind(e, t) {
return e.kind === t;
}
async function runRetrieval(e, t, n) {
ensureSqliteLibrarySelected();
const r = await retrieval.run(e, t);
if (!hasResultKind(r, e.kind)) throw new Error(`Invalid memory ${n} worker result`);
return r;
}
async function runMemoryForgetIndexPlan(e) {
let t = 2 * (e.agentId.length + e.databasePath.length + e.stateDir.length);
for (const n of [
e.changedPaths,
e.removedPaths,
e.sessionIds,
e.excludedSessionIds,
e.entryKeys,
e.corpusSnippets
]) for (const e of n) t += e.length * 2;
return (await runRetrieval(e, { inputBytes: t }, "Forget index plan")).plan;
}
async function runMemoryOriginRead(e) {
return runRetrieval(e, { inputBytes: 2 * (e.agentId.length + e.databasePath.length + e.stateDir.length + (e.entryKeys?.reduce((e, t) => e + t.length, 0) ?? 0) + (e.sessionIds?.reduce((e, t) => e + t.length, 0) ?? 0)) }, {
"origin-rows": "origin rows",
"session-tombstones": "tombstone rows"
}[e.kind]);
}
async function prewarmMemorySearchWorker() {
ensureSqliteLibrarySelected();
await retrieval.run({ kind: "prewarm" }, {});
}
async function runMemoryIndexState(e, t) {
return (await runRetrieval({
...e,
kind: "index-state"
}, { signal: t }, "index state")).state;
}
async function runMemoryDatabaseAdmission(e) {
return (await runRetrieval({
...e,
kind: "admission"
}, {}, "database admission")).admission;
}
async function runMemoryStatus(e, t) {
return (await runRetrieval({
...e,
kind: "status",
query: t
}, {}, "status")).snapshot;
}
async function runMemoryVectorLoad(e, t) {
if (!e?.agentId || !e.path) throw new Error("Memory vector inspection requires its captured database target");
const n = (await runRetrieval({
agentId: e.agentId,
databasePath: e.path,
kind: "vector-load",
extensionPath: t
}, {}, "vector capability")).result;
if (!n.ok || !n.extensionPath) throw new Error(n.error ?? "unknown sqlite-vec load error");
return {
extensionPath: n.extensionPath,
retiredLegacy: false
};
}
async function runMemoryRecallMetadata(e, t, n) {
return runRetrieval({
...e,
kind: "recall-metadata",
...t
}, {
signal: n,
inputBytes: t.candidates.reduce((e, t) => e + (t.id.length + t.path.length + t.source.length) * 2, 0)
}, "recall metadata");
}
async function runMemoryIndexRead(e, t) {
const n = await runRetrieval({
...e,
kind: "index-read",
command: t
}, { inputBytes: JSON.stringify(t).length * 2 }, "index read");
if (n.read.type !== t.type) throw new Error("Memory index reader returned another operation");
return n.read.value;
}
async function runMemoryCuratedCandidates(e, t) {
return runRetrieval({
...e,
kind: "curated",
...t
}, { inputBytes: t.activeProjectKeys?.reduce((e, t) => e + t.length * 2, 0) ?? 0 }, "curated candidates");
}
async function runMemoryPresenceInspection(e, t) {
return (await runRetrieval({
kind: "presence",
databasePath: e,
agentId: t
}, { inputBytes: e.length * 2 }, "presence")).present;
}
async function runMemoryKeywordSearch(e, t, n, r = false) {
return runRetrieval({
...e,
kind: "keyword",
query: t,
includeIndexState: r
}, {
signal: n,
inputBytes: 2 * (t.body.query.length + t.path.query.length) + (t.body.sourceFilter.excludedSessionPaths?.reduce((e, t) => e + t.length * 2, 0) ?? 0) + (t.path.sourceFilter.excludedSessionPaths?.reduce((e, t) => e + t.length * 2, 0) ?? 0)
}, "keyword");
}
async function runMemoryVectorFallback(e, t, n) {
const r = await runRetrieval({
...e,
kind: "vector",
query: t
}, {
signal: n,
inputBytes: t.queryVec.length * 8 + (t.candidateIds?.reduce((e, t) => e + t.length * 2, 0) ?? 0) + (t.sourceFilter.excludedSessionPaths?.reduce((e, t) => e + t.length * 2, 0) ?? 0)
}, "vector");
if (r.capabilityError) throw new DatabaseSearchCapabilityUnavailableError(r.capabilityError.capability, r.capabilityError.message);
return r.rows;
}
async function prepareMemoryIndexInWorker(e) {
if (e.source === "sessions") throw new Error("Session sources stream through prepareSessionIndexInWorker");
const t = await indexing.run({
kind: "prepare",
input: e
}, { inputBytes: e.content.length * 2 });
if (t.kind !== "prepared") throw new Error("Invalid memory indexing worker result");
return t.value;
}
/** Hands export pages to the index worker one at a time; the producer waits until each is taken. */
var SessionIndexPageHandoff = class {
constructor() {
this.pages = [];
}
offer(e) {
if (this.aborted) return Promise.reject(this.aborted);
if (e.length === 0) return Promise.resolve();
this.pages.push(...e);
this.wake();
return new Promise((e, t) => {
this.onTaken = {
resolve: e,
reject: t
};
});
}
close(e) {
this.end = e === void 0 ? {} : { error: toErrorObject(e, "Session export failed") };
this.wake();
}
/** The consumer failed; release a waiting producer. */
abort(e) {
this.aborted = toErrorObject(e, "Session indexing failed");
this.pages.length = 0;
this.onTaken?.reject(this.aborted);
this.onTaken = void 0;
}
async take() {
for (;;) {
const e = this.pages.shift();
if (e) {
if (this.pages.length === 0) {
this.onTaken?.resolve();
this.onTaken = void 0;
}
return e;
}
if (this.end) {
if (this.end.error) throw this.end.error;
return;
}
await new Promise((e) => {
this.onAvailable = e;
});
}
}
wake() {
const e = this.onAvailable;
this.onAvailable = void 0;
e?.();
}
};
/**
* Chunks a session while its export streams: neither the export nor the index worker holds more
* than one page of transcript text. Returns null when the transcript disappeared.
*/
async function prepareSessionIndexInWorker(e, t) {
const n = [];
const r = new SessionIndexPageHandoff();
let i;
const startIndexing = () => {
if (!i) {
i = chunkSessionPages(e, r, n).catch((e) => {
r.abort(e);
throw e;
});
i.catch(() => void 0);
}
return i;
};
const a = await t({
onPage: (e) => {
startIndexing();
return r.offer(sessionIndexPages(e));
},
onReset: () => {
startIndexing();
return r.offer([{
lines: [],
done: false,
reset: true
}]);
}
}).then((e) => {
r.close();
return e;
}, async (e) => {
r.close(e);
await i;
throw e;
});
if (!a && !i) return null;
await startIndexing();
return a ? { chunks: n } : null;
}
async function chunkSessionPages(e, t, n) {
if ((await sessionIndexing.run({
kind: "prepare-session",
input: e
}, {
inputBytes: SESSION_INDEX_PAGE_INPUT_BYTES,
onRequest: async (e) => {
const r = e;
for (const e of r.chunks) n.push(e);
const i = await t.take() ?? {
lines: [],
done: true
};
if (i.reset) n.length = 0;
return {
input: i,
timeoutMs: 6e4
};
}
})).kind !== "prepared") throw new Error("Invalid memory indexing worker result");
}
/** Startup scans use the background indexing pool under the shared compute limit. */
async function readMemoryTranscriptStatsInWorker(e) {
if (e.length === 0) return [];
ensureSqliteLibrarySelected();
const t = {
OPENCLAW_STATE_DIR: resolveStateDir(),
OPENCLAW_SUPERVISOR_MODE: process.env.OPENCLAW_SUPERVISOR_MODE
};
const n = await indexing.run({
kind: "transcript-stats",
scopes: e,
env: t
}, { inputBytes: 2 * (JSON.stringify(e).length + JSON.stringify(t).length) });
if (n.kind !== "transcript-stats") throw new Error("Invalid memory transcript stats worker result");
return n.stats;
}
//#endregion
export { runMemoryCuratedCandidates as a, runMemoryIndexRead as c, runMemoryOriginRead as d, runMemoryPresenceInspection as f, runMemoryVectorLoad as g, runMemoryVectorFallback as h, readMemoryTranscriptStatsInWorker as i, runMemoryIndexState as l, runMemoryStatus as m, prepareSessionIndexInWorker as n, runMemoryDatabaseAdmission as o, runMemoryRecallMetadata as p, prewarmMemorySearchWorker as r, runMemoryForgetIndexPlan as s, prepareMemoryIndexInWorker as t, runMemoryKeywordSearch as u };