openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
6,300 lines • 227 kB
JavaScript
import { l as normalizeOptionalString } from "../../string-coerce-CCIiB4H7.mjs";
import { R as resolveTimerTimeoutMs } from "../../number-coercion-D6u-4YD8.mjs";
import { a as resolveGlobalSingleton } from "../../global-singleton-D7yf05nR.mjs";
import { c as resolveUserPath } from "../../home-dir-EKmgmdPG.mjs";
import { n as createCpuTrackedWorker } from "../../worker-cpu-dNstslyu.mjs";
import { a as asOptionalRecord } from "../../record-coerce-CVPuDqcc.mjs";
import { d as readErrorName, p as toErrorObject } from "../../error-coercion-hDrHOSGy.mjs";
import { x as uniqueValues } from "../../string-normalization-DLmfYZXI.mjs";
import { s as redactSensitiveText } from "../../redact-Mj7pppxC.mjs";
import { r as resolveStateDir } from "../../state-dir-DiG0gXzD.mjs";
import { r as isPathInside } from "../../path-guards-TIjxtj6H.mjs";
import { d as sleepWithAbort } from "../../src-BPmQBLJp.mjs";
import { t as formatErrorMessage } from "../../errors-BKzCeTYb.mjs";
import { n as materializeErrorStack } from "../../error-graph-internal-DdjdM90N.mjs";
import { t as createDeferredCore } from "../../deferred-D0La5CRk.mjs";
import { n as normalizeAgentId } from "../../agent-id-CQjtp2ft.mjs";
import { l as resolveSessionStorePathCore } from "../../paths-DvQ5AJvD.mjs";
import { a as resolveAgentDir, f as resolveAgentWorkspaceDir, r as resolveAgentConfig } from "../../agent-scope-config-DmXgFGKP.mjs";
import { a as resolveRuntimeWorkerUrl } from "../../runtime-worker-url-DRDkoS4J.mjs";
import { O as readSqliteDatabaseScopedWriteTokenForPath } from "../../sqlite-database-admission-DQIqro3d.mjs";
import { t as createSubsystemLogger } from "../../subsystem-BHJiy01V.mjs";
import { a as WorkerTaskError } from "../../src-Dkfkl2Oz.mjs";
import { i as runQueuedStoreWrite } from "../../store-writer-queue-B36_RXST.mjs";
import { i as MEMORY_INDEX_PATHS_FTS_TABLE, r as MEMORY_INDEX_FTS_TABLE } from "../../sqlite-search-schema-CLxKWxgk.mjs";
import { c as openSqliteWorkerStore, f as runSqliteWorkerStoreWrite } from "../../sqlite-worker-store-D51tD0Vp.mjs";
import { a as readOpenClawAgentDatabaseIdentity } from "../../openclaw-agent-db-identity-C8MGU8lp.mjs";
import { n as enqueueKeyedTask } from "../../keyed-async-queue-DewLnYvW.mjs";
import { i as onInternalSessionTranscriptUpdate } from "../../transcript-events-BHwlF03q.mjs";
import { t as warnPluginSdkDeprecation } from "../../sdk-deprecation-D5N9acnu.mjs";
import { t as retryAsync } from "../../retry-D-ulnYII.mjs";
import { n as captureOpenClawAgentDatabaseExecution, s as supportsOpenClawAgentDatabaseExecution } from "../../openclaw-agent-execution-C4FyHhb0.mjs";
import { r as openOpenClawAgentSqliteWorkerStoreV2 } from "../../openclaw-agent-worker-store-Do41NaPe.mjs";
import { n as createMemorySearchDeadlineControl, t as MEMORY_SEARCH_DEADLINE_CONTROL } from "../../search-deadline-control-D-IPgGBJ.mjs";
import { i as getAgentWorkspaceAccess } from "../../workspace-access-CnjZBg1i.mjs";
import "../../file-access-runtime-BD2Fjfbw.mjs";
import "../../string-coerce-runtime-BwAZZDf5.mjs";
import { a as createDeferred } from "../../extension-shared-CJ4teJ7p.mjs";
import "../../security-runtime-C-zE_Zy_.mjs";
import "../../process-runtime-DcBPEA8Y.mjs";
import "../../retry-runtime-DOUvdfOa.mjs";
import "../../number-runtime-W4chuk8B.mjs";
import "../../error-runtime-BM740gJj.mjs";
import "../../memory-core-host-engine-storage-DcaZNQQh.mjs";
import { n as estimateUtf8Bytes, t as estimateStructuredEmbeddingInputBytes } from "../../embedding-input-limits-C6s74CMk.mjs";
import { c as matchesExtraMemoryPathEntry, i as buildMultimodalChunkForIndexing, l as normalizeExtraMemoryPathEntries, n as readMemoryFile, o as hashText, r as buildFileEntry } from "../../read-file-_FfN9cuw.mjs";
import { t as isFileMissingError } from "../../fs-utils-Co3SFHW_.mjs";
import { n as classifyMemoryMultimodalPath } from "../../multimodal-CD7YKC3g.mjs";
import { t as retryTransientMemoryRead } from "../../read-retry-CS_FAhEQ.mjs";
import { t as MEMORY_CHUNKING_VERSION } from "../../markdown-chunks-DoKq_kBI.mjs";
import { t as INVALID_PROJECT_ANNOTATION_KEY } from "../../curated-annotations-GumWCHHf.mjs";
import { t as runWithConcurrency } from "../../concurrency-Ctrz5le_.mjs";
import { i as readMemorySearchManagerStatus, t as formatMemoryIndexRebuildGuidance } from "../../types-Bo5s7TN4.mjs";
import { t as isActiveMemoryRecallSession } from "../../active-memory-recall-session-Do4T_kZm.mjs";
import { n as resolveMemorySessionStartupState, r as resolveMemorySessionSyncPlan, t as isMemorySessionIndexable } from "../../manager-session-sync-state-Cc-NPg3B.mjs";
import { a as MEMORY_INDEX_META_KEY, f as resolveMemorySourceFileEntries, g as isValidMemoryEmbedding, l as inspectMemorySourceState, m as collectMemoryCachedEmbeddings, n as memoryChunkRowId } from "../../manager-source-index-kernel-BYD04WLI.mjs";
import { i as resolveEmbeddingInputFormatVersion, r as hasNonTextEmbeddingParts, t as formatEmbeddingModelInput } from "../../embedding-inputs-BGMBVJOW.mjs";
import "../../memory-core-host-engine-indexing-EQMS_Jzx.mjs";
import { n as searchMemoryVectorIndex, r as buildMemorySourceFilter, t as admitMemoryVectorIndex } from "../../manager-search-knn-Bc-4goWR.mjs";
import { l as tokenizeFtsQuery, n as resolveStatusProviderInfo, o as searchVector, r as prepareExactPathMatcher, t as collectMemoryStatusSnapshot } from "../../manager-status-state-C5DHmlg_.mjs";
import { i as resolveChunkProvenance } from "../../manager-session-index-preparation-3h_bst18.mjs";
import { o as sdkOpenNodeSqliteDatabase } from "../../sqlite-runtime-lcoEVOL7.mjs";
import { t as MemoryIndexRevisionConflictError } from "../../manager-db-kernel-Dhsxnwme.mjs";
import { n as MEMORY_INDEX_WRITE_SCOPE } from "../../manager-publication-task-B1g1hKrX.mjs";
import { r as readMemoryShadowIdentity, t as assertMemoryShadowIdentity } from "../../manager-shadow-task-D4s6gAdr.mjs";
import { i as resolveWorkspaceWorkerUrl, r as resolveWorkspaceWorkerExecArgv } from "../../agent-workspace-runtime-DsxJXUf2.mjs";
import "../../concurrency-runtime-CY4L3doa.mjs";
import "../../runtime-env-D-Pa5lD6.mjs";
import { t as expectDefined } from "../../expect-runtime-DT3P17Ul.mjs";
import { t as memoryCpuProcessEntrypoints } from "../../manager-cpu-entrypoints-CEJDRP3Q.mjs";
import "../../routing-DmgGYTrU.mjs";
import "../../agent-scope-runtime-CDpr-vor.mjs";
import "../../session-store-paths-BDXaSNEL.mjs";
import { t as extractTranscriptIdentityFromSessionsMemoryHit } from "../../session-transcript-hit-BWkZP1HW.mjs";
import { t as createPluginRuntimeStore } from "../../runtime-store-BRjhAEZt.mjs";
import { r as listRegisteredMemoryEmbeddingProviderAdapters } from "../../memory-embedding-provider-runtime-XHJ-dZvt.mjs";
import "../../memory-core-host-embedding-registry-COy3_PjY.mjs";
import { S as isEmbeddingBatchUnavailableError } from "../../memory-core-host-engine-embeddings-CX_qB4Zn.mjs";
import { n as resolveMemorySearchConfig } from "../../memory-search-dZuH_5z-.mjs";
import { t as observeAgentRunActivity } from "../../agent-run-activity-Dk2yUxdl.mjs";
import "../../memory-core-host-engine-foundation-CvV28XoZ.mjs";
import { c as streamSessionEntry, i as sessionPathForFile, o as statSessionEntrySync, s as streamSessionEntries, u as sessionPathForSessionIdentity } from "../../session-files-agcHHm9h.mjs";
import { n as listSessionTranscriptCorpusEntriesForAgent, s as loadMemorySessionMetadataBatchAsync } from "../../memory-core-host-engine-sessions-DAG-vYby.mjs";
import { t as listSessionTranscriptArchivesInWorker } from "../../session-transcript-inventory-runtime-0nKdYI_m.mjs";
import { n as getMemoryManagerLifecycle, r as markMemoryIndexingLive, t as MemoryManagerReloadError } from "../../lifecycle-CCh9W0s9.mjs";
import { nt as withMemoryWorkspacePreparation, tt as withMemoryWorkspaceLock } from "../../dreaming-dreams-file-Cbm7FmRe.mjs";
import { n as preparedTextSimilarity, t as prepareSimilarityText } from "../../tokenize-Cj8uCWRq.mjs";
import { t as findForgottenMemorySessionIds } from "../../memory-entry-origins-DE0zsEvo.mjs";
import { n as readSessionResetRecallCutoffMetadata } from "../../session-reset-recall-metadata-D7M93uYL.mjs";
import { a as runMemoryCuratedCandidates, c as runMemoryIndexRead, g as runMemoryVectorLoad, h as runMemoryVectorFallback, i as readMemoryTranscriptStatsInWorker, l as runMemoryIndexState, m as runMemoryStatus, n as prepareSessionIndexInWorker, o as runMemoryDatabaseAdmission, p as runMemoryRecallMetadata, t as prepareMemoryIndexInWorker, u as runMemoryKeywordSearch } from "../../manager-cpu-worker-runtime-Dx8HioTC.mjs";
import { d as acquireMemoryIndexReadGeneration, f as withMemoryIndexGeneration, i as closeMemoryDatabase, n as logMemoryVectorDegradedWrite, o as openMemoryDatabaseReadOnlyAtPath, r as cleanupAgedMemoryReindexTempFiles, s as removeMemoryDatabaseFiles, u as waitForMemoryReindexLock } from "../../manager-vector-warning-0Pyg32Ro.mjs";
import { a as resolveEmbeddingProviderIndexIdentity, i as resolveEmbeddingProviderFallbackRemote, n as resolveEmbeddingProviderAdapterTransport, r as resolveEmbeddingProviderFallbackModel, t as createEmbeddingProvider } from "../../embeddings-DPNowtTV.mjs";
import { t as resolveMemoryPathClassification } from "../../memory-path-provenance-BZx9HXoh.mjs";
import { n as runEmbeddingOperationWithTimeout } from "../../paused-deadline-CbQcpkat.mjs";
import path from "node:path";
import { randomUUID } from "node:crypto";
import fs from "node:fs/promises";
import { AsyncLocalStorage } from "node:async_hooks";
import { setImmediate as setImmediate$1 } from "node:timers/promises";
//#region extensions/memory-core/src/memory/manager-database-admission.ts
function captureMemoryDatabaseWriteOptions(e, t, n) {
const r = { ...n?.writeOptions?.env ?? process.env };
r.OPENCLAW_STATE_DIR = resolveStateDir(r);
return {
agentId: e,
path: n?.writeOptions?.path ?? resolveUserPath(t),
env: r
};
}
//#endregion
//#region extensions/memory-core/src/memory/manager-publication-transfer.ts
const FRAGMENT_CHARS = 16384;
const BATCH_BYTES = 524288;
const NUMERIC_PART_ITEMS = 512;
/** Bound the direct command before serializing; oversized vectors retain streamed staging. */
function memoryEmbeddingCacheFitsInline(e, t) {
let n = 512 + 2 * (e.agentId.length + e.provider.id.length + e.provider.model.length + e.providerKey.length);
for (const e of t) {
n += 128 + 2 * (e.hash.length + (e.sessionId?.length ?? 0)) + 32 * e.embedding.length;
if (n > BATCH_BYTES) return false;
}
return n <= BATCH_BYTES && t.every((e) => e.embedding.every(Number.isFinite));
}
function* jsonParts(e, t) {
if (typeof e === "string") {
yield "\"";
for (let t = 0; t < e.length; t += FRAGMENT_CHARS) yield JSON.stringify(e.slice(t, t + FRAGMENT_CHARS)).slice(1, -1);
yield "\"";
} else if (Array.isArray(e)) {
yield "[";
for (let n = 0; n < e.length; n++) {
if (n) yield ",";
const r = e[n] ?? null;
if (typeof r === "number") {
const r = Math.min(e.length, n + NUMERIC_PART_ITEMS);
let i = n + 1;
while (i < r && typeof e[i] === "number") i++;
const a = e.slice(n, i);
yield t ? a.map((e) => Object.is(e, -0) ? "-0" : JSON.stringify(e)).join(",") : JSON.stringify(a).slice(1, -1);
n = i - 1;
} else yield* jsonParts(r, t);
}
yield "]";
} else if (e && typeof e === "object") {
yield "{";
let n = true;
for (const [r, i] of Object.entries(e)) {
if (i === void 0) continue;
if (!n) yield ",";
n = false;
yield JSON.stringify(r) + ":";
yield* jsonParts(i, t);
}
yield "}";
} else yield JSON.stringify(e) ?? "null";
}
function* rowFragments(e, t) {
let n = "";
for (const r of jsonParts(e, t)) {
n += r;
while (n.length >= FRAGMENT_CHARS) {
let e = FRAGMENT_CHARS;
const t = n.charCodeAt(e - 1);
const r = n.charCodeAt(e);
if (t >= 55296 && t <= 56319 && r >= 56320 && r <= 57343) e--;
yield n.slice(0, e);
n = n.slice(e);
}
}
if (n) yield n;
}
function memoryPublicationHeader(e) {
const { chunks: t, embeddings: n, retained: r, removedIds: i, ...a } = e;
return {
...a,
delta: i !== void 0
};
}
const publicationProbes = /* @__PURE__ */ new WeakMap();
/** Drop the printed fragments once a publication settles; a late call only reprints. */
function releaseMemoryPublication(e) {
for (const t of Array.isArray(e) ? e : [e]) publicationProbes.delete(t.chunks);
}
function* memoryPublicationBatches(e) {
const t = publicationProbes.get(e.chunks);
if (!t?.staged) {
yield* printPublicationBatches(e);
return;
}
const { head: n, rest: r } = t.staged;
t.staged = void 0;
yield* n;
yield* r;
}
function* printPublicationBatches(e) {
function* rows() {
for (const t of e.removedIds ?? []) yield { removedId: t };
for (const t of e.retained ?? []) yield {
chunk: {
...row(t),
text: ""
},
embedding: [],
retained: true
};
for (const [t, n] of e.chunks.entries()) yield {
chunk: row(n),
embedding: e.embeddings[t] ?? []
};
}
function row(e) {
return {
startLine: e.startLine,
endLine: e.endLine,
text: e.text,
hash: e.hash,
importance: e.importance,
triggers: e.triggers,
projectKey: e.projectKey,
...e.provenance ? { provenance: { ...e.provenance } } : {}
};
}
yield* publicationBatches(rows());
}
/** Ordinary sources fit one bounded command; larger sources retain chunked transfer. */
function memoryPublicationInline(e) {
let t = publicationProbes.get(e.chunks);
if (!t) {
const n = printPublicationBatches(e);
const r = [];
while (r.length < 2) {
const e = n.next();
if (e.done) break;
r.push(e.value);
}
t = r.length < 2 ? { fragments: r[0] ?? [] } : { staged: {
head: r,
rest: n
} };
publicationProbes.set(e.chunks, t);
}
return t.fragments ? {
header: memoryPublicationHeader(e),
fragments: t.fragments
} : void 0;
}
/** A group shares one bounded worker request and one native transaction. */
function memoryPublicationGroup(e) {
const t = [];
let n = 0;
for (const r of e) {
const e = memoryPublicationInline(r);
if (!e) return;
n += JSON.stringify(e.header).length * 2;
for (const t of e.fragments) n += Math.max(Buffer.byteLength(t.json), t.json.length * 2) + 128;
if (n > BATCH_BYTES) return;
t.push(e);
}
return t;
}
function* memoryEmbeddingCacheBatches(e) {
yield* publicationBatches(e, true);
}
function* publicationBatches(e, t = false) {
let n = [];
let r = 0;
for (const i of e) {
const e = rowFragments(i, t);
let a = e.next();
while (!a.done) {
const t = e.next();
const i = Math.max(Buffer.byteLength(a.value), a.value.length * 2) + 128;
if (n.length && r + i > BATCH_BYTES) {
yield n;
n = [];
r = 0;
}
n.push({
json: a.value,
last: t.done === true
});
r += i;
a = t;
}
}
if (n.length) yield n;
}
//#endregion
//#region extensions/memory-core/src/memory/manager-publication.ts
async function initializePublishedMemory(e, t, n) {
const r = await openOpenClawAgentSqliteWorkerStoreV2(e, {
version: 2,
assertCurrent: n
}, {
moduleUrl: resolveRuntimeWorkerUrl(memoryCpuProcessEntrypoints.publication),
input: { kind: "agent" }
});
try {
await r.prepare();
return {
worker: r,
admitted: t ? await runMemoryPublication({
run: () => r.execute({
type: "schema.admit",
input: t
}, n),
prepare: async () => true
}) : void 0
};
} catch (e) {
await r.close();
throw e;
}
}
async function withPublishedMemoryExecution(e, t, n) {
let r;
if (e && supportsOpenClawAgentDatabaseExecution(e)) {
if (!t) throw new Error("Memory publication requires its live file owner");
r = captureOpenClawAgentDatabaseExecution(e, { expectedIdentity: {
kind: "file",
physicalIdentity: t.identity,
nativeLocation: t.filename,
birthtime: t.birthtime
} });
}
const i = [];
for (const e of [n, () => r?.release()]) try {
await e();
} catch (e) {
i.push(e);
}
if (i.length === 1) throw i[0];
if (i.length > 1) throw new AggregateError(i, `${String(i[0])}; Memory sync cleanup failed`, { cause: i[0] });
}
async function runMemoryPublication(e) {
if (!await e.prepare()) return;
const t = await e.run();
if (t.ok) return t;
throw Object.assign(t.error.name === "MemoryIndexRevisionConflictError" ? new MemoryIndexRevisionConflictError(t.error.message) : new Error(t.error.message), t.error, {
entered: t.entered,
committed: t.committed
});
}
/** Small publications use one request; larger inputs retain their bounded transfer scope. */
async function publishMemorySource(e) {
const t = Array.isArray(e.replacement) ? [...e.replacement] : e.replacement;
try {
return await publishMemorySourceOnce(e);
} finally {
releaseMemoryPublication(t);
}
}
async function publishMemorySourceOnce(e) {
const { replacement: t, state: n, execute: r, run: i, publish: a, prepare: o, assertPublished: s } = e;
if (Array.isArray(t)) return a(() => {
const e = memoryPublicationGroup(t);
if (!e) throw new Error("Memory publication group exceeds its bounded transfer");
return r({
type: "source.replace.group",
input: {
sources: e,
state: n()
}
});
}, o);
const c = memoryPublicationInline(t);
if (c) return a(() => r({
type: "source.replace.inline",
input: {
...c,
state: n()
}
}), o);
return i(async (e) => {
const r = memoryPublicationHeader(t);
await e.execute({
type: "stage.start",
input: { header: r }
});
for (const n of memoryPublicationBatches(t)) await e.execute({
type: "stage.append",
input: { fragments: n }
});
const i = await a(() => e.execute({
type: "source.replace",
input: { state: n() }
}), o);
s?.();
if (i === void 0) await e.execute({
type: "stage.discard",
input: void 0
});
return i;
});
}
/** Cache entries are content-addressed; the worker excludes forgotten sessions. */
async function publishMemoryEmbeddingCache(e) {
const { scope: t, mutation: n, prepare: r, publish: i } = e;
const preparePublication = async () => r();
if (n.kind === "clear") return await i(() => t.execute({
type: "cache.clear",
input: { identities: n.identities }
}), preparePublication);
if (memoryEmbeddingCacheFitsInline(n.header, n.entries)) return await i(() => t.execute({
type: "cache.write.inline",
input: {
header: n.header,
entries: n.entries
}
}), preparePublication);
await t.execute({
type: "cache.stage.start",
input: { header: n.header }
});
for (const e of memoryEmbeddingCacheBatches(n.entries)) await t.execute({
type: "stage.append",
input: { fragments: e }
});
const a = await i(() => t.execute({
type: "cache.write",
input: void 0
}), preparePublication);
if (a === void 0) await t.execute({
type: "stage.discard",
input: void 0
});
return a;
}
//#endregion
//#region extensions/memory-core/src/memory/manager-database-context.ts
const log$13 = createSubsystemLogger("memory");
var MemoryIndexDatabase = class MemoryIndexDatabase {
static async openPublished(e) {
let t;
if (!e.readOnly) t = await initializePublishedMemory(e.writeOptions, e.maintenanceSource ? void 0 : e.schema, () => {
const t = e.maintenanceSource;
if (t && !t.isOpen) throw new Error("Memory maintenance source connection changed");
});
let n;
try {
const r = t?.admitted;
const i = e.readOnly ? await runMemoryDatabaseAdmission({
databasePath: e.writeOptions.path,
agentId: e.agentId
}) : e.maintenanceSource?.admission ?? r?.value.admission;
if (!i) throw new Error("Memory worker did not publish database admission");
n = new MemoryIndexDatabase(void 0, void 0, e.readOnly, e.writeOptions, i.hasIndex, i);
if (t) {
n.terminalSignal = t.worker.terminalSignal;
n.publicationWorker = Promise.resolve({ store: t.worker });
}
n.fts.enabled = e.schema.ftsEnabled;
if (e.maintenanceSource) n.installFacts(e.maintenanceSource.facts, e.maintenanceSource.factsToken);
if (e.maintenanceSource && (!n.fts.enabled || e.maintenanceSource.fts.available)) Object.assign(n.fts, e.maintenanceSource.fts);
else if (e.readOnly) {
n.fts.available = n.hasIndex && n.fts.enabled && i.ftsAvailable;
if (i.facts) n.installFacts(i.facts);
} else if (r) {
if (r.facts) n.installFacts(r.facts, r.writeToken);
n.fts.available = r.value.ftsAvailable;
n.fts.loadError = r.value.ftsError;
if (e.schema.ftsEnabled && r.value.ftsError) log$13.warn(`fts unavailable: ${r.value.ftsError}`);
}
return n;
} catch (e) {
try {
await t?.worker.close();
} finally {
n?.release();
}
throw e;
}
}
static async openShadow(e, t) {
const n = await openSqliteWorkerStore({
moduleUrl: resolveRuntimeWorkerUrl(memoryCpuProcessEntrypoints.publication),
databasePath: e,
input: { allowExtension: t }
});
let r;
try {
const i = await n.execute({
type: "connection.inspect",
input: void 0
});
assertMemoryShadowIdentity(e, i.fileIdentity);
r = sdkOpenNodeSqliteDatabase(e, {
readOnly: true,
allowExtension: t
});
const a = new MemoryIndexDatabase(r);
a.shadow = {
path: e,
identity: i.fileIdentity,
pragmas: i.pragmas
};
a.publicationWorker = Promise.resolve(a.bindShadowWorker(n));
return a;
} catch (e) {
try {
await n.close();
} finally {
r?.close();
}
throw e;
}
}
constructor(e, t, n = false, r, i = true, a) {
this.readOnly = n;
this.writeOptions = r;
this.hasIndex = i;
this.admission = a;
this.privateQueues = /* @__PURE__ */ new Map();
this.nativeWriterActive = false;
this.shadowReleased = false;
this.vector = {
enabled: false,
available: null
};
this.fts = {
enabled: false,
available: false
};
this.vectorReady = null;
this.facts = {
meta: null,
serialized: null,
revision: 0,
hasIndexedChunks: false,
hasSemanticChunks: false,
invalidatedSources: [],
hasVectorTable: false,
vectorState: { state: "empty" }
};
this.searchSchema = {
fts: null,
paths: null,
vector: null
};
this.vectorDegradedWriteWarningShown = false;
this.closed = false;
this.nativeDb = e;
this.nativeRelease = t ?? (e ? () => closeMemoryDatabase(e) : void 0);
}
get isOpen() {
return !this.closed && !this.terminalSignal?.aborted && this.nativeDb?.isOpen !== false;
}
get supportsReindexSuspension() {
return this.admission?.engine !== "postgres";
}
/** Released synchronous status compatibility; runtime callers use worker reads. */
get db() {
if (!this.isOpen) throw new Error("Memory database owner is closed");
if (!this.nativeDb) {
const e = this.writeOptions;
if (!e?.agentId || !e.path) throw new Error("Memory compatibility reader requires its captured target");
const t = openMemoryDatabaseReadOnlyAtPath(e.path, false, e.agentId);
this.nativeDb = t.db;
this.nativeRelease = t.release;
}
return this.nativeDb;
}
release() {
this.nativeRelease?.();
this.closed = true;
}
writeToken() {
const e = this.shadow?.path ?? this.writeOptions?.path;
return e ? readSqliteDatabaseScopedWriteTokenForPath(e, MEMORY_INDEX_WRITE_SCOPE) : void 0;
}
installFacts(e, t) {
this.facts = e;
this.factsToken = t;
}
async refreshFacts() {
if (!this.hasIndex || this.readOnly) return;
const e = this.writeToken();
if (e !== void 0 && e === this.factsToken) return;
this.installFacts(await this.read({
type: "index.facts",
input: void 0
}, () => {
if (!this.isOpen) throw new Error("Memory database owner closed before reading index facts");
}), e);
}
async writeMetadata(e) {
if (this.facts.serialized === JSON.stringify(e)) return;
await this.settlePublication(() => this.executePublication({
type: "index.writeMetadata",
input: e
}, () => {
if (!this.isOpen) throw new Error("Memory database owner closed before writing index metadata");
}));
}
get isShadow() {
return this.shadow !== void 0 || this.postgresStageId !== void 0;
}
assertShadowPath() {
if (this.shadow) assertMemoryShadowIdentity(this.shadow.path, this.shadow.identity);
}
withPrivateAccess(e, t = {}) {
if (this.closed) return Promise.reject(/* @__PURE__ */ new Error("Memory reindex database owner is closed"));
return runQueuedStoreWrite({
queues: this.privateQueues,
storePath: this.shadow?.path ?? "memory-index",
label: "private memory index access",
reentrant: t.reentrant === true && !this.nativeWriterActive,
fn: async () => {
if (!this.isOpen) throw new Error("Memory reindex database owner is closed");
this.assertShadowPath();
if (t.nativeWriter) this.nativeWriterActive = true;
try {
return await e();
} finally {
if (t.nativeWriter) this.nativeWriterActive = false;
}
}
});
}
async drainPrivateAccess() {
while (this.privateQueues.size > 0) await Promise.allSettled(Array.from(this.privateQueues.values()).flatMap((e) => e.drainPromise ? [e.drainPromise] : []));
}
publicationState() {
return {
vector: {
enabled: this.vector.enabled,
available: this.vector.available
},
fts: {
enabled: this.fts.enabled,
available: this.fts.available
},
hasVectorTable: this.facts.hasVectorTable,
...this.vector.available && this.vector.extensionPath ? { extensionPath: this.vector.extensionPath } : {}
};
}
assertPublishedFileCurrent() {
if (!this.isOpen || !this.writeOptions?.path) throw new Error("Memory publication owner closed or changed");
const e = this.admission?.identity ?? (this.nativeDb ? readOpenClawAgentDatabaseIdentity({ db: this.nativeDb }) : void 0);
const t = readMemoryShadowIdentity(this.writeOptions.path);
if (e?.identity !== `${t.device}:${t.inode}`) throw new Error("Memory publication source file changed");
}
getPublicationWorker() {
this.publicationWorker ??= (async () => {
const e = this.shadow?.path ?? this.writeOptions?.path;
if (!e || this.readOnly || this.closed) throw new Error("Memory publication requires its live file owner");
if (this.writeOptions) {
this.assertPublishedFileCurrent();
const e = await openOpenClawAgentSqliteWorkerStoreV2(this.writeOptions, {
version: 2,
assertCurrent: () => {
if (!this.isOpen) throw new Error("Memory publication owner closed");
}
}, {
moduleUrl: resolveRuntimeWorkerUrl(memoryCpuProcessEntrypoints.publication),
input: {
kind: "agent",
stageId: this.postgresStageId
}
});
this.terminalSignal = e.terminalSignal;
return { store: e };
}
const t = this.shadow.pragmas;
const n = {
moduleUrl: resolveRuntimeWorkerUrl(memoryCpuProcessEntrypoints.publication),
input: {
fileIdentity: this.shadow?.identity ?? readMemoryShadowIdentity(e),
pragmas: t
}
};
const r = await openSqliteWorkerStore({
...n,
databasePath: e,
existingOnly: true,
admission: {
identity: `file:${this.shadow.identity.device}:${this.shadow.identity.inode}`,
assertCurrent: () => {
if (!this.isOpen) throw new Error("Memory shadow owner closed before Worker open");
this.assertShadowPath();
}
}
});
if (!r) throw new Error("Memory shadow disappeared before publication Worker open");
return this.bindShadowWorker(r);
})().catch((e) => {
this.publicationWorker = void 0;
throw e;
});
return this.publicationWorker;
}
bindShadowWorker(e) {
const run = (t, n) => runSqliteWorkerStoreWrite(e, t, () => {
if (!this.isOpen) throw new Error("Memory shadow owner closed");
this.assertShadowPath();
n();
}, [this.shadow.path]);
return { store: {
run,
execute: (e, t, n) => run((t) => t.execute(e, n), t),
close: () => e.close()
} };
}
withPublicationWorker(e, t) {
const run = async () => {
t();
try {
return await e((await this.getPublicationWorker()).store);
} catch (e) {
const [t] = await Promise.allSettled([this.retirePublicationWorker()]);
if (t.status === "rejected") throw new AggregateError([e, t.reason], `${String(e)}; Memory publication cleanup failed: ${String(t.reason)}`, { cause: e });
throw e;
}
};
return this.withPrivateAccess(run, {
nativeWriter: true,
reentrant: true
});
}
runPublication(e, t) {
return this.withPublicationWorker((n) => n.run(e, t), t);
}
executePublication(e, t) {
return this.withPublicationWorker((n) => n.execute(e, t), t);
}
async settlePublication(e, t = async () => true) {
const n = await runMemoryPublication({
run: e,
prepare: t
});
if (n?.facts) {
this.installFacts(n.facts, n.writeToken);
this.searchSchema = n.searchSchema ?? this.searchSchema;
}
return n?.value;
}
async read(e, t) {
if (this.isShadow || !this.readOnly && this.admission?.engine === "postgres") return this.executePublication(e, t);
const n = this.writeOptions;
if (!n?.agentId || !n.path) throw new Error("Memory index reads require their captured database target");
t();
return runMemoryIndexRead({
agentId: n.agentId,
databasePath: n.path
}, e);
}
admitSchema(e) {
this.schemaAdmission ??= this.settlePublication(() => this.executePublication({
type: "schema.admit",
input: e
}, () => {
if (!this.isOpen) throw new Error("Memory database owner closed before schema admission");
})).then((t) => {
if (!t) throw new Error("Memory schema admission did not complete");
this.fts.enabled = e.ftsEnabled;
this.fts.available = t.ftsAvailable;
this.fts.loadError = t.ftsError;
if (e.ftsEnabled && t.ftsError) log$13.warn(`fts unavailable: ${t.ftsError}`);
});
return this.schemaAdmission;
}
async readSourceState(e) {
const assertCurrent = () => {
if (!this.isOpen) throw new Error("Memory source owner closed during source preparation");
this.assertShadowPath();
};
if (!this.hasIndex) return [];
return this.read({
type: "source.state",
input: e
}, assertCurrent);
}
async pruneEmbeddingCache(e, t) {
t();
return await this.settlePublication(() => this.executePublication({
type: "cache.prune",
input: e
}, t)) ?? false;
}
async mutateEmbeddingCache(e, t, n) {
const publish = (t) => publishMemoryEmbeddingCache({
scope: t,
mutation: e,
prepare: n,
publish: (e, t) => this.settlePublication(e, t)
});
return e.kind === "clear" || memoryEmbeddingCacheFitsInline(e.header, e.entries) ? publish({ execute: (e) => this.executePublication(e, t) }) : this.runPublication(publish, t);
}
async replaceSource(e, t, n) {
return this.withSourceMutation(() => publishMemorySource({
replacement: e,
state: () => this.publicationState(),
execute: (e) => this.executePublication(e, t),
run: (e) => this.runPublication(e, t),
publish: (e, t) => this.settlePublication(e, t),
prepare: n,
assertPublished: this.isShadow ? t : void 0
}));
}
async deleteSource(e, t) {
return this.withSourceMutation(() => this.settlePublication(() => this.executePublication({
type: "source.delete",
input: {
...e,
state: this.publicationState()
}
}, t)));
}
refreshSourceState(e, t) {
return this.withSourceMutation(() => this.settlePublication(() => this.executePublication({
type: "source.refresh",
input: e
}, t)));
}
async prepareVector(e, t) {
return this.readOnly ? runMemoryVectorLoad(this.writeOptions, e) : this.settlePublication(() => this.executePublication({
type: "vector.prepare",
input: { state: {
...this.publicationState(),
extensionPath: e
} }
}, t));
}
async updateIndexStructure(e, t) {
return this.settlePublication(() => this.executePublication(e, t));
}
withSourceMutation(e) {
return this.writeOptions?.path ? withMemoryIndexGeneration(this.writeOptions.path, "mutation", e) : e();
}
async publishShadow(e, t) {
await this.settlePublication(() => this.executePublication({
type: "database.publish",
input: {
...e,
state: {
...this.publicationState(),
extensionPath: e.sourceSchema.vector ? e.extensionPath : void 0
}
}
}, t));
}
async retirePublicationWorker() {
await (await this.publicationWorker)?.store.close();
this.publicationWorker = void 0;
}
closePublicationWorker() {
return runQueuedStoreWrite({
queues: this.privateQueues,
storePath: this.shadow?.path ?? "memory-index",
label: "memory publication worker retirement",
fn: () => this.retirePublicationWorker()
});
}
async withPublicationGeneration(e) {
if (!this.isOpen) throw new Error("Memory publication requires its live file owner");
await withPublishedMemoryExecution(this.readOnly ? void 0 : this.writeOptions, this.admission?.identity ?? (this.nativeDb ? readOpenClawAgentDatabaseIdentity({ db: this.nativeDb }) : void 0), e);
}
closeShadow() {
this.closed = true;
this.shadowClose ??= (async () => {
await this.drainPrivateAccess();
await this.closePublicationWorker();
this.release();
this.shadowReleased = true;
})().catch((e) => {
this.shadowClose = void 0;
throw e;
});
return this.shadowClose;
}
};
//#endregion
//#region extensions/memory-core/src/memory/manager-embedding-errors.ts
const MEMORY_EMBEDDING_OPERATION_ERROR_CODE = "MEMORY_EMBEDDING_OPERATION_FAILED";
function createMemoryEmbeddingOperationError(e) {
const t = formatErrorMessage(e.cause);
const n = new Error(t);
n.code = MEMORY_EMBEDDING_OPERATION_ERROR_CODE;
n.operation = e.operation;
if (e.providerId) n.providerId = e.providerId;
n.cause = e.cause;
return n;
}
function isMemoryEmbeddingOperationError(e) {
return e instanceof Error && e.code === MEMORY_EMBEDDING_OPERATION_ERROR_CODE;
}
//#endregion
//#region extensions/memory-core/src/memory/manager-embedding-policy.ts
function resolveMemoryIndexConcurrency(e, t) {
if (e.enabled) return e.concurrency;
const n = t?.inlineIndexConcurrency;
return n !== void 0 && Number.isSafeInteger(n) && n > 0 ? n : 4;
}
function embedMemoryQuery(e, t, n, r) {
const i = n.queryInstruction || n.inputFormat?.query;
return e.embed(i !== void 0 ? `${i}${t}` : formatEmbeddingModelInput(t, e.model, "query"), {
...r,
inputType: "query",
...i !== void 0 ? { queryInstructionApplied: true } : {}
});
}
function embedMemoryDocuments(e, t, n, r) {
return e.embedBatch(t.map((t) => formatEmbeddingModelInput(t, e.model, "document", n)), {
...r,
inputType: "document",
...n ? { documentFormatApplied: true } : {}
});
}
async function runMemoryEmbeddingBatchTimeoutRetry(e) {
let t = 1;
while (true) {
try {
return {
kind: "success",
value: await e.run()
};
} catch (e) {
if (t === 2 || !/timed out|timeout/i.test(formatErrorMessage(e))) return {
kind: "failure",
error: e,
attempts: t
};
}
e.onRetry();
t = 2;
}
}
function formatMemoryEmbeddingChunks(e, t, n) {
if (!n && !resolveEmbeddingInputFormatVersion(t)) return e;
return e.map((e) => ({
...e,
...formatEmbeddingModelInput(e, t, "document", n),
...e.embeddingInput ? { embeddingInput: formatEmbeddingModelInput(e.embeddingInput, t, "document", n) } : {}
}));
}
function buildMemoryEmbeddingBatches(e, t) {
const n = [];
let r = [];
let i = 0;
for (const a of e) {
const e = a.embeddingInput ? estimateStructuredEmbeddingInputBytes(a.embeddingInput) : estimateUtf8Bytes(a.text);
if (r.length > 0 && i + e > t) {
n.push(r);
r = [];
i = 0;
}
r.push(a);
i += e;
}
if (r.length > 0) n.push(r);
return n;
}
const RATE_LIMITED_MEMORY_EMBEDDING_ERROR_RE = /(rate[_ ]limit|too many requests|\b429\b|resource has been exhausted|tokens per day)/i;
const RETRYABLE_MEMORY_EMBEDDING_SERVICE_ERROR_RE = /\b5\d\d\b|cloudflare/i;
const RETRYABLE_MEMORY_EMBEDDING_TRANSPORT_ERROR_RE = /(fetch failed|other side closed|ECONNRESET|ECONNREFUSED|ETIMEDOUT|EPIPE|UND_ERR_|socket hang up|socket terminated|network error|read ECONN|timed out|connection (?:reset|refused|aborted|timed out)|EHOSTUNREACH|ENETUNREACH|ECONNABORTED|EAI_AGAIN)/i;
const SPLITTABLE_MEMORY_EMBEDDING_BATCH_ERROR_RE = /(^memory embeddings batch timed out\b|too many tokens overall,?\s*split into more batches|request_headers_too_large|request header fields too large|other side closed|ECONNRESET|EPIPE|UND_ERR_SOCKET|socket hang up|socket terminated|read ECONN|connection (?:reset|aborted)|\bembeddings (?:api input limit exceeded:\s*max\s+\d+\s*,\s*got\s+\d+|max input length is\s+\d+)\b|\bbatch size is invalid,?\s+it should not be larger than\s+\d+\b|\binput array max\s+\d+(?=\s*(?:["'}]|$))|input\s*数组最大不得超过\s*\d+\s*条)/i;
const SHORT_MEMORY_EMBEDDING_RETRY_BUDGET = {
attempts: 3,
baseDelayMs: 500,
maxDelayMs: 8e3
};
const MEMORY_EMBEDDING_RETRY_PROFILES = {
index: {
transient: SHORT_MEMORY_EMBEDDING_RETRY_BUDGET,
rateLimit: {
attempts: 5,
baseDelayMs: 5e3,
maxDelayMs: 6e4
},
maxTotalWaitMs: Number.POSITIVE_INFINITY
},
query: {
transient: SHORT_MEMORY_EMBEDDING_RETRY_BUDGET,
rateLimit: SHORT_MEMORY_EMBEDDING_RETRY_BUDGET,
maxTotalWaitMs: 8e3
}
};
const MEMORY_EMBEDDING_BATCH_ITEM_LIMIT_RE = /\b(?:embeddings api input limit exceeded:\s*max\s+(\d+)\s*,\s*got\s+\d+|embeddings max input length is\s+(\d+(?:\.\d+)?)|batch size is invalid,?\s+it should not be larger than\s+(\d+(?:\.\d+)?)|input array max\s+(\d+)(?=\s*(?:["'}]|$))|input\s*数组最大不得超过\s*(\d+)\s*条)/gi;
function parseMemoryEmbeddingBatchItemLimit(e) {
const t = /* @__PURE__ */ new Set();
for (const n of e.matchAll(MEMORY_EMBEDDING_BATCH_ITEM_LIMIT_RE)) {
const e = Number(n[1] ?? n[2] ?? n[3] ?? n[4] ?? n[5]);
if (!Number.isSafeInteger(e) || e <= 0) return;
t.add(e);
}
return t.size === 1 ? t.values().next().value : void 0;
}
function isInvalidEmbeddingResponse(e) {
return asOptionalRecord(e)?.code === "INVALID_EMBEDDING_RESPONSE";
}
function embeddingRetryMessage(e) {
const t = asOptionalRecord(e);
const n = t?.embeddingErrorMessage;
const r = typeof t?.errorBody === "string" ? t.errorBody : void 0;
return [typeof n === "string" ? n : formatErrorMessage(e), r].filter((e) => Boolean(e)).join("\n");
}
function resolveMemoryEmbeddingRetryBudget(e, t) {
if (isInvalidEmbeddingResponse(t)) return;
const n = asOptionalRecord(t);
const r = embeddingRetryMessage(t);
if (r.startsWith("memory embeddings batch timed out")) return;
const i = n?.retryAfterMs;
const a = typeof i === "number" && Number.isSafeInteger(i) && i >= 0 ? i : void 0;
const o = [n?.status, n?.statusCode].find((e) => typeof e === "number" && Number.isInteger(e));
if ([
n?.errorCode,
n?.code,
n?.errorType
].some((e) => {
const t = normalizeOptionalString(e)?.toLowerCase();
return t === "quota_exceeded" || t === "insufficient_quota";
}) && a === void 0) return;
if (o === 429) return {
...e.rateLimit,
retryAfterMs: a
};
if (o !== void 0) return o >= 500 && o <= 599 ? e.transient : void 0;
if (RETRYABLE_MEMORY_EMBEDDING_TRANSPORT_ERROR_RE.test(r)) return e.transient;
if (SPLITTABLE_MEMORY_EMBEDDING_BATCH_ERROR_RE.test(r)) return;
if (RATE_LIMITED_MEMORY_EMBEDDING_ERROR_RE.test(r)) return {
...e.rateLimit,
retryAfterMs: a
};
return RETRYABLE_MEMORY_EMBEDDING_SERVICE_ERROR_RE.test(r) ? e.transient : void 0;
}
async function runMemoryEmbeddingRetryLoop(e) {
const t = MEMORY_EMBEDDING_RETRY_PROFILES[e.profile];
let n = t.maxTotalWaitMs;
return await retryAsync(e.run, {
attempts: t.rateLimit.attempts,
minDelayMs: t.transient.baseDelayMs,
maxDelayMs: t.rateLimit.maxDelayMs,
retryAfterMaxDelayMs: t.rateLimit.maxDelayMs,
jitter: .2,
shouldRetry: (n, r) => {
if (e.signal?.aborted) return false;
const i = resolveMemoryEmbeddingRetryBudget(t, n);
return i !== void 0 && r < i.attempts;
},
delayMs: ({ attempt: e, err: n }) => {
const r = resolveMemoryEmbeddingRetryBudget(t, n);
return r ? Math.min(r.maxDelayMs, r.baseDelayMs * 2 ** (e - 1)) : 0;
},
retryAfterMs: (e) => resolveMemoryEmbeddingRetryBudget(t, e)?.retryAfterMs,
sleep: async (t) => {
const r = Math.min(t, n);
n -= r;
await e.waitForRetry(r);
}
});
}
async function runMemoryEmbeddingBatchRetryWithSplit(e) {
const split = async (t) => {
const n = [];
for (let r = 0; r < e.items.length; r += t) n.push(...await runMemoryEmbeddingBatchRetryWithSplit({
...e,
items: e.items.slice(r, r + t)
}));
return n;
};
const t = e.maxInputsPerRequest;
if (t !== void 0 && Number.isSafeInteger(t) && t > 0 && e.items.length > t) return await split(t);
let n;
try {
n = await runMemoryEmbeddingRetryLoop({
profile: "index",
run: async () => await e.run(e.items),
waitForRetry: e.waitForRetry
});
} catch (t) {
const n = embeddingRetryMessage(t);
if (isInvalidEmbeddingResponse(t) || e.items.length <= 1 || !SPLITTABLE_MEMORY_EMBEDDING_BATCH_ERROR_RE.test(n)) throw t;
const r = parseMemoryEmbeddingBatchItemLimit(n);
const i = r !== void 0 && r < e.items.length ? r : Math.ceil(e.items.length / 2);
e.onSplit?.({
itemCount: e.items.length,
splitAt: i,
message: n
});
return await split(i);
}
await e.onSuccess?.(e.items, n);
return n;
}
//#endregion
//#region extensions/memory-core/src/memory/active-memory-session-sources.ts
/** Classify indexed identities, without rendering transcripts or querying an embedding provider. */
async function resolveActiveMemoryRecallSources(e) {
const t = /* @__PURE__ */ new Set();
const n = /* @__PURE__ */ new Map();
for (const r of e.rows) {
const i = r.path.replace(/\\/g, "/");
const a = extractTranscriptIdentityFromSessionsMemoryHit(/^sessions\/[^/]+\/[^/.]+$/.test(i) ? `${i}.jsonl` : i);
if (!a) continue;
if (isActiveMemoryRecallSession({ sessionId: a.stem })) {
t.add(r.path);
continue;
}
const o = a.ownerAgentId ?? e.agentId;
const s = n.get(o) ?? {
live: /* @__PURE__ */ new Map(),
archives: /* @__PURE__ */ new Map()
};
n.set(o, s);
const c = a.archived ? s.archives : s.live;
const l = a.archived ? path.posix.basename(i) : a.stem;
const u = c.get(l) ?? [];
u.push(r.path);
c.set(l, u);
}
for (const [r, i] of n) {
const n = resolveSessionStorePathCore(e.cfg.session?.store, { agentId: r });
const [a, o] = await Promise.all([i.live.size ? loadMemorySessionMetadataBatchAsync({
agentId: r,
storePath: n,
sessions: [...i.live.keys()].map((e) => ({ sessionId: e }))
}) : [], i.archives.size ? listSessionTranscriptArchivesInWorker({
agentId: r,
storePath: n,
archiveNames: [...i.archives.keys()]
}) : []]);
for (const e of a) if (isActiveMemoryRecallSession(e)) for (const n of i.live.get(e.sessionId) ?? []) t.add(n);
for (const e of o) if (isActiveMemoryRecallSession(e)) for (const n of i.archives.get(e.archiveName) ?? []) t.add(n);
}
return e.rows.filter((e) => t.has(e.path));
}
//#endregion
//#region extensions/memory-core/src/memory/manager-provider-state.ts
function resolveMemoryProviderLifecycle(e) {
if (e.provider && e.fallbackFrom) return {
mode: "fallback-active",
providerId: e.provider.id,
fallbackFrom: e.fallbackFrom,
reason: e.fallbackReason ?? "fallback activated"
};
if (e.provider) return {
mode: "active",
providerId: e.provider.id
};
return {
mode: "fts-only",
reason: e.providerUnavailableReason ?? "No embedding provider available",
attemptedProviderId: e.requestedProvider
};
}
function resolveFallbackCurrentProviderId(e) {
if (e.provider) return e.provider.id;
if (e.lifecycle.mode === "degraded") return e.lifecycle.providerId;
return null;
}
function resolveMemoryPrimaryProviderRequest(e) {
return {
provider: e.settings.provider,
model: e.settings.model,
remote: e.settings.remote,
inputType: e.settings.inputType,
queryInputType: e.settings.queryInputType,
documentInputType: e.settings.documentInputType,
outputDimensionality: e.settings.outputDimensionality,
fallback: e.settings.fallback,
local: e.settings.local
};
}
function resolveMemoryFallbackProviderRequest(e) {
const t = e.settings.fallback;
if (!t || t === "none" || !e.currentProviderId || t === e.currentProviderId) return null;
return {
...resolveMemoryPrimaryProviderRequest({ settings: e.settings }),
provider: t,
model: resolveEmbeddingProviderFallbackModel(t, e.settings.model, e.cfg),
remote: resolveEmbeddingProviderFallbackRemote(e.settings.remote),
fallback: "none"
};
}
//#endregion
//#region extensions/memory-core/src/memory/manager-postgres-reindex.ts
/** Retain the agent connection, but release its writer queue between staging batches. */
async function withPostgresMemoryReindex(e, t) {
const assertCurrent = () => {
if (!e.isOpen) throw new Error("Memory publication owner closed during reindex");
};
const n = new MemoryIndexDatabase(void 0, void 0, false, e.writeOptions, true, e.admission);
const r = randomUUID();
n.postgresStageId = r;
Object.assign(n.vector, e.vector);
Object.assign(n.fts, e.fts);
try {
await n.settlePublication(() => n.executePublication({
type: "database.stage.start",
input: void 0
}, assertCurrent));
return await t(n);
} finally {
await n.closeShadow();
if (e.isOpen) await e.executePublication({
type: "database.stage.discard",
input: { stageId: r }
}, assertCurrent);
}
}
async function publishPostgresMemoryStage(e, t, n, r, i) {
const a = t.postgresStageId;
if (!a) throw new Error("Memory reindex has no PostgreSQL stage");
await e.settlePublication(() => e.executePublication({
type: "database.stage.publish",
input: {
stageId: a,
expectedRevision: n,
vectorIndexComplete: r
}
}, i));
}
//#endregion
//#region extensions/memory-core/src/memory/manager-reindex-state.ts
const MEMORY_INDEX_PROVENANCE_VERSION = 1;
function canUpgradeMemoryIndexProviderKey(e, t, n) {
const [r, ...i] = n;
if (!r || t.provider !== r.provider || t.model !== r.model || !t.providerKey || t.providerKey === r.providerKey || !i.some((e) => e.provider === t.provider && e.model === t.model && e.providerKey === t.providerKey)) return false;
return e.status === "valid" || e.status === "mismatched" && e.owner === "openclaw" && e.code === "chunking_version" && e.versionOrder === "older" && e.chunkingVersionOnly === true && (t.embeddingInputFormatVersion ?? 0) === resolveEmbeddingInputFormatVersion(r.model);
}
function resolveMemoryIndexProviderIdentities(e) {
const t = e.provider ?? {
id: "none",
model: "fts-only"
};
const n = [{
model: t.model,
cacheKeyData: e.cacheKeyData ?? {
provider: t.id,
model: t.model
}
}, ...e.provider ? e.aliases ?? [] : []];
const r = resolveEmbeddingInputFormatVersion(t.model);
const i = e.provider ? e.documentPrefix : void 0;
const a = /* @__PURE__ */ new Set();
const o = [];
for (const [e, s] of n.entries()) {
const n = r || i !== void 0 ? {
provider: s.cacheKeyData,
embeddingInputFormatVersion: r,
...i !== void 0 ? { documentPrefix: i } : {}
} : s.cacheKeyData;
const c = hashText(JSON.stringify(n));
const l = `${s.model}\u0000${c}`;
if (e > 0 && !s.model || a.has(l)) continue;
a.add(l);
o.push({
provider: t.id,
model: s.model,
providerKey: c
});
}
return o;
}
function resolveConfiguredSourcesForMeta(e) {
const t = Array.from(e).filter((e) => e === "memory" || e === "sessions").toSorted((e, t) => e.localeCompare(t));
return t.length > 0 ? t : ["memory"];
}
function normalizeMetaSources(e) {
return resolveConfiguredSourcesForMeta(new Set(Array.isArray(e.sources) ? e.sources : []));
}
function configuredMetaSourcesDiffer(e) {
const t = normalizeMetaSources(e.meta);
if (t.length !== e.configuredSources.length) return true;
return t.some((t, n) => t !== e.configuredSources[n]);
}
function openClawIndexMismatch(e, t, n) {
return {
status: "mismatched",
reason: t,
code: e,
owner: "openclaw",
versionOrder: n
};
}
function configuredIndexMismatch(e, t) {
return {
status: "mismatched",
reason: t,
code: e,
owner: "configuration"
};
}
function resolveConfiguredScopeHash(e) {
const t = normalizeExtraMemoryPathEntries(e.workspaceDir, e.extraPaths).map((e) => {
const t = e.path.replaceAll("\\", "/");
return e.pattern ? {
path: t,
pattern: e.pattern
} : t;
}).toSorted((e, t) => JSON.stringify(e).localeCompare(JSON.stringify(t)));
return hashText(JSON.stringify({
extraPaths: t,
multimodal: {
enabled: e.multimodal.enabled,
modalities: [...e.multimodal.modalities].toSorted(),
maxFileBytes: e.multimodal.maxFileBytes
}
}));
}
function resolveConfigurationIndexIdentityState(e, t) {
const n = e.provider && e.provider.model === void 0 ? void 0 : e.provider?.model?.trim() || "fts-only";
const r = [{
model: n,
providerKey: e.providerKey
}, ...e.providerAliases ?? []].filter((e) => e.model === t.model);
if (n !== void 0 && r.length === 0) return configuredIndexMismatch("model", `index was built for model ${t.model}, expected ${n}`);
const i = e.provider ? e.provider.id : "none";
if (t.provider !== i) return configuredIndexMismatch("provider", `index was built for provider ${t.provider}, expected ${i}`);
if (n !== void 0 && e.providerKeyKnown !== false && !r.some((e) => e.providerKey === t.providerKey)) return configuredIndexMismatch("provider_settings", "index provider settings changed");
const a = resolveContentScopeIdentityState(e, t);
if (a.status !== "valid") return a;
if (e.vectorReady && e.hasIndexedChunks !== false && !t.vectorDims) return configuredIndexMismatch("vector_dims", "index vector dimensions are missing");
return { status: "valid" };
}
function resolveContentScopeIdentityState(e, t) {
if (configuredMetaSourcesDiffer({
meta: t,
configuredSources: e.configuredSources
})) return configuredIndexMismatch("sources", "index sources changed");
if (t.scopeHash !== e.configuredScopeHash) return configuredIndexMismatch("scope", "index scope changed");
if (t.chunkTokens !== e.chunkTokens || t.chunkOverlap !== e.chunkOverlap) return configuredIndexMismatch("chunking", "index chunking changed");
if ((t.ftsTokenizer ?? "unicode61") !== e.ftsTokenizer) return configuredIndexMismatch("fts_tokenizer", "index FTS tokenizer changed");
return { status: "valid" };
}
function resolveMemoryIndexIdentityState(e) {
const { meta: t } = e;
if (!t) return {
status: "missing",
reason: "index metadata is missing",
code: "metadata_missing",
owner: "openclaw"
};
const n = t.provider === e.provider?.id && e.providerAliases?.some(({ model: e }) => e === t.model) ? e.provider?.model ?? t.model : t.model;
const r = resolveEmbeddingInputFormatVersion(n);
const i = (t.provenanceVersion ?? 0) > 1 ? "provenance_version" : (t.chunkingVersion ?? 0) > 6 ? "chunking_version" : (t.embeddingInputFormatVersion ?? 0) > r ? "embedding_input_format" : void 0;
if (i) return openClawIndexMismatch(i, "the index was written by a newer OpenClaw version; upgrade OpenClaw or reindex explicitly", "newer");
if ((t.provenanceVersion ?? 0) < 1) return openClawIndexMismatch("provenance_version", "index provenance classifier changed", "older");
const a = (t.chunkingVersion ?? 0) < 6 ? "chunking_version" : (t.embeddingInputFormatVersion ?? 0) < r ? "embedding_input_format" : void 0;
if (a) return {
...openClawIndexMismatch(a, a === "chunking_version" ? "index chunking implementation changed" : "index embedding input format changed", "older"),
...resolveContentScopeIdentityState(e, t).status === "valid" ? a === "chunking_version" ? { chunkingVersionOnly: true } : { lexicalCompatible: true } : {}
};
return resolveConfigurationIndexIdentityState(e, t);
}
//#endregion
//#region extensions/memory-core/src/memory/manager-sync-control.ts
var MemoryBackgroundRebuildInterruptedError = class extends Error {
constructor() {
super("Memory background rebuild interrupted by foreground activity");
this.name = "MemoryBackgroundRebuildInterruptedError";
}
};
function hasTargetedSessionSyncParams(e) {
return Boolean(e?.sessions?.some((e) => e.sessionId.trim().length > 0) || e?.archiveFiles?.some((e) => e.trim().length > 0));
}
var MemoryTargetedSessionSyncQueue = class {
constructor(e) {
this.owner = e;
this.archiveFiles = /* @__PURE__ */ new Set();
this.sessions = /* @__PURE__ */ new Map();
this.progressCallbacks = /* @__PURE__ */ new Set();
this.force = false;
this.pending = null;
}
get hasPending() {
return this.pending !== null || this.archiveFiles.size > 0 || this.sessions.size > 0;
}
clear() {
this.archiveFiles.clear();
this.sessions.clear();
this.force = false;
this.progressCallbacks.clear();
}
enqueue(e) {
for (const t of e?.archiveFiles ?? []) {
const e = t.trim();
if (e) this.archiveFiles.add(e);
}
for (const t of e?.sessions ?? []) {
const e = normalizeQueuedMemorySessionSyncTarget(t);
if (e) this.sessions.set(memorySessionSyncTargetKey(e), e);
}
if (this.archiveFiles.size === 0 && this.sessions.size === 0) return this.owner.getSyncing() ?? Promise.resolve();
if (e?.force) this.force = true;
if (e?.progress) this.progressCallbacks.add(e.progress);
if (!this.pending) this.pending = (async () => {
try {
await this.owner.getSyncing()?.catch(() => void 0);
while (!this.owner.isClosed() && (this.archiveFiles.size > 0 || this.sessions.size > 0)) {
const e = Array.from(this.archiveFiles);
const t = Array.from(this.sessions.values());
const n = this.force;
const r = Array.from(this.progressCallbacks);
this.clear();
const i = r.length > 0 ? (e) => {
for (const t of r) t(e);
} : void 0;
try {
await this.owner.sync({
reason: "queued-sessions",
...n ? { force: true } : {},
sessions: t,
archiveFiles: e,
...i ? { progress: i } : {}
});
} catch (r) {
for (const t of e) this.archiveFiles.add(t);
for (const e of t) this.sessions.set(memorySessionSyncTargetKey(e), e);
if (n) this.force = true;
this.progressCallbacks.clear();
throw r;
}
}
} finally {
if (this.owner.isClosed()) this.clear();
this.pending = null;
}
})();
return this.pending ?? Promise.resolve();
}
};
function normalizeQueuedMemorySessionSyncTarget(e) {
const t = e.sessionId.trim();
if (!t) return null;
const n = e.agentId?.trim();
const r = e.sessionKey?.trim();
return {
...n ? { agentId: n } : {},
sessionId: t,
...r ? { sessionKey: r } : {}
};
}
function memorySessionSyncTargetKey(e) {
return [
e.agentId ?? "",
e.sessionId,
e.sessionKey ?? ""
].join("\0");
}
//#endregion
//#region extensions/memory-core/src/memory/local-file-watcher.ts
const log$12 = createSubsystemLogger("memory");
const owner = resolveGlobalSingleton(Symbol.for("openclaw.memory.localWatchTransport"), () => ({}));
const RESTART_DELAYS_MS = [
500,
2e3,
5e3
];
const FAILURE_WINDOW_MS = 6e4;
var MemoryWatchTransport = class {
constructor() {
this.subscriptions = /* @__PURE__ */ new Map();
this.nextId = 0;
this.failures = [];
}
get retiring() {
return Boolean(this.retirement);
}
startWorker() {
let e;
try {
e = {
worker: createCpuTrackedWorker(resolveWorkspaceWorkerUrl("memory"), {
execArgv: resolveWorkspaceWorkerExecArgv("memory"),
name: "memory-files"
}),
exited: createDeferred()
};
} catch (e) {
this.recover(toErrorObject(e, "Memory file worker failed to start"));
return;
}
this.run = e;
this.failure = void 0;
e.worker.on("message", (t) => {
if (t.type === "shutdown") {
if (t.error) {
e.failure = new Error(t.error);
materializeErrorStack(e.failure);
e.worker.terminate().catch((t) => e.exited.reject(t));
}
} else this.subscriptions.get(t.id)?.watcher.receive(t);
});
e.worker.on("error", (t) => {
e.failure = toErrorObject(t, "Memory file worker failed");
materializeErrorStack(e.failure);
});
e.worker.on("exit", (t) => {
this.run = void 0;
if (!this.retiring || t !== 0) {
e.failure ??= /* @__PURE__ */ new Error(`Memory file worker exited unexpectedly (${t})`);
materializeErrorStack(e.failure);
}
e.exited.resolve();
if (!this.retiring && e.failure) this.recover(e.failure);
});
for (const [t, { watcher: n, closing: r }] of this.subscriptions) if (!r) e.worker.postMessage(n.openCommand(t), []);
}
recover(e) {
if (![...this.subscriptions.values()].some((e) => !e.closing)) return;
const t = Date.now();
this.failures = this.failures.filter((e) => t - e < FAILURE_WINDOW_MS);
this.failures.push(t);
const n = RESTART_DELAYS_MS[this.failures.length - 1];
const r = n === void 0 ? `Memory file worker unavailable after repeated failures; restart the Gateway to retry: ${e.message}` : `Memory file worker unavailable; restarting in ${n} ms: ${e.message}`;
log$12.warn(r);
const i = new Error(r);
materializeErrorStack(i);
this.failure = {
error: i,
exhausted: n === void 0
};
for (const { watcher: e, closing: t } of this.subscriptions.values()) if (!t) e.failed(i, n === void 0);
if (n !== void 0) {
this.restartTimer = setTimeout(() => {
this.restartTimer = void 0;
this.startWorker();
}, n);
this.restartTimer.unref();
}
}
add(e) {
const t = ++this.nextId;
this.subscriptions.set(t, {
watcher: e,
closing: false
});
if (this.failure) e.failed(this.failure.error, this.failure.exhausted);
else if (this.run) this.run.worker.postMessage(e.openCommand(t), []);
else if (!this.restartTimer) this.startWorker();
return t;
}
async remove(e, t) {
this.subscriptions.get(e).closing = true;
const n = this.run;
try {
if (n) {
if (!n.failure) n.worker.postMessage({
type: "close",
id: e
}, []);
await Promise.race([t, n.exited.promise]);
if (n.failure) {
await n.exited.promise;
throw n.failure;
}
}
} finally {
this.subscriptions.delete(e);
if (!this.subscriptions.size) {
clearTimeout(this.restartTimer);
this.restartTimer = void 0;
this.retirement = (async () => {
const e = this.run;
try {
if (e) {
e.worker.postMessage({ type: "shutdown" }, []);
await e.exited.promise;
if (e.failure) throw e.failure;
}
} finally {
owner.transport = void 0;
}
})();
await this.retirement;
}
}
}
async waitForExit() {
await this.retirement;
}
};
/** Local proxy; the shared file worker owns traversal, native watches and settling. */
var LocalMemoryFileWatcher = class {
constructor(e) {
this.options = e;
this.facts = {
health: [],
capacityDegraded: false
};
this.ready = createDeferred();
this.retired = createDeferred();
this.closed = false;
this.settled = false;
this.ready.promise.catch(() => void 0);
this.retired.promise.catch(() => void 0);
}
get capacityDegraded() {
return this.facts.capacityDegraded;
}
health() {
return this.facts.health;
}
start() {
if (this.starting) return this.starting;
this.attachment = (async () => {
while (owner.transport?.retiring) await owner.transport.waitForExit();
if (this.closed) {
this.ready.resolve();
return;
}
const e = owner.transport ??= new MemoryWatchTransport();
this.transport = e;
this.id = e.add(this);
})();
this.starting = this.attachment.then(() => this.ready.promise);
return this.starting;
}
openCommand(e) {
return {
type: "open",
id: e,
workspaceDir: this.options.workspaceDir,
request: {
agentId: this.options.agentId,
settings: {
extraPaths: this.options.settings.extraPaths,
multimodal: this.options.settings.multimodal,
sync: { watchDebounceMs: this.options.settings.sync.watchDebounceMs }
}
}
};
}
receive(e) {
if (e.type === "closed") {
if (e.error) {
const t = new Error(e.error);
materializeErrorStack(t);
this.ready.reject(t);
this.retired.reject(t);
} else {
this.ready.resolve();
this.retired.resolve();
}
return;
}
if (e.type === "started") this.ready.resolve();
if (e.type === "started" || e.type === "state") this.facts = e.facts;
if (this.closed) return;
try {
this.options.runInBackgroundContext(() => {
switch (e.type) {
case "started":
case "state":
this.options.onState?.(e.facts);
break;
case "dirty":
this.settled = false;
this.options.onDirty?.();
break;
case "change":
this.settled = true;
this.drainChanges();
break;
case "unavailable": this.options.onUnavailable();
}
});
} catch (e) {
log$12.warn(`memory watch callback failed: ${String(e)}`);
}
}
drainChanges() {
if (this.syncing || !this.settled || this.closed) return;
this.settled = false;
this.syncing = Promise.resolve().then(() => this.options.runInBackgroundContext(() => this.options.onChange())).catch((e) => {
log$12.warn(`memory sync failed (watch): ${String(e)}`);
}).finally(() => {
this.syncing = void 0;
this.drainChanges();
});
}
failed(e, t) {
const n = this.facts.health.length ? this.facts.health : [{
state: "unavailable",
mode: "events",
directories: 0,
failure: void 0,
pollingFallback: false,
pollIntervalMs: 0
}];
this.receive({
id: this.id,
type: "state",
facts: {
capacityDegraded: true,
health: n.map((t) => ({
state: "unavailable",
mode: t.mode,
directories: 0,
pollingFallback: t.pollingFallback,
pollIntervalMs: t.pollIntervalMs,
failure: {
operation: "watch",
code: "worker-unavailable",
error: e.message
}
}))
}
});
if (t) this.ready.reject(e);
this.receive({
id: this.id,
type: "dirty"
});
this.receive({
id: this.id,
type: "unavailable"
});
}
close() {
if (this.closing) return this.closing;
this.closed = true;
this.closing = (async () => {
try {
await this.attachment;
if (this.transport && this.id !== void 0) await this.transport.remove(this.id, this.retired.promise);
} finally {
this.ready.resolve();
await this.syncing;
}
})();
return this.closing;
}
};
//#endregion
//#region extensions/memory-core/src/memory/manager-sync-outcome.ts
/** Outcome of a sync pass that skipped its work on purpose, reported by detached maintenance. */
const MEMORY_SYNC_DEFERRED = Symbol("memory-sync-deferred");
var MemorySyncOutcomeLedger = class {
async track(e) {
const t = this.latestFailure;
try {
const n = await e();
if (n === MEMORY_SYNC_DEFERRED) return;
if (n) this.recordFailure(n);
else if (this.latestFailure === t) this.latestFailure = void 0;
} catch (e) {
this.recordFailure(e);
throw e;
}
}
get lastError() {
return this.latestFailure?.reason;
}
recordFailure(e) {
this.latestFailure = { reason: redactSensitiveText(formatErrorMessage(e), { mode: "tools" }) };
}
};
//#endregion
//#region extensions/memory-core/src/memory/manager-sync-base.ts
const VECTOR_LOAD_TIMEOUT_MS = 3e4;
const FULL_REINDEX_RETRY_INITIAL_DELAY_MS = 3e4;
const FULL_REINDEX_RETRY_MAX_DELAY_MS = 18e5;
const log$11 = createSubsystemLogger("memory");
const reindexDatabase = new AsyncLocalStorage();
var MemoryManagerSyncBase = class {
constructor() {
this.closed = false;
this.syncProviderGeneration = null;
this.memoryWatchUnavailable = false;
this.closing = false;
this.activeManagerOperations = 0;
this.managerIdleWaiters = /* @__PURE__ */ new Set();
this.provider = null;
this.sources = /* @__PURE__ */ new Set();
this.sourceInspections = /* @__PURE__ */ new Map();
this.providerKey = null;
this.sessionWatchTimer = null;
this.sessionUnsubscribe = null;
this.dirty = false;
this.memoryWatchGeneration = 0;
this.syncOutcomes = new MemorySyncOutcomeLedger();
this.memorySourceProvenanceRepairPending = false;
this.memoryFullRetryDirty = false;
this.fullReindexRetryBackoff = {
attempts: 0,
retryAt: 0,
failedWithEmbeddings: false
};
this.sessionsDirty = false;
this.sessionsFullRetryDirty = false;
this.sessionsReconcileDirty = false;
this.sessionsDirtyFiles = /* @__PURE__ */ new Set();
this.sessionPendingFiles = /* @__PURE__ */ new Set();
this.sessionPendingTargets = /* @__PURE__ */ new Map();
this.sessionAgentBusy = false;
this.sessionBackgroundIndexing = false;
this.syncIsBackground = false;
}
assertDatabaseMutationCurrent(e) {
if (this.closed || !e.isOpen || this.database !== e) throw new Error("Memory database owner closed or changed before write admission");
if (e.readOnly) throw new Error("Memory status managers are read-only");
}
get database() {
const e = reindexDatabase.getStore();
const t = e?.manager === this ? e.database : void 0;
if (t?.closed) throw new Error("Memory reindex database context is closed");
return t ?? this.publishedDatabase;
}
get db() {
return this.database.db;
}
get vector() {
return this.database.vector;
}
get fts() {
return this.database.fts;
}
withPublishedDatabase(e) {
return reindexDatabase.exit(e);
}
async withReindexDatabase(e, t) {
return await reindexDatabase.run({
manager: this,
database: e
}, t);
}
shouldYieldSessionIndexing() {
const e = this.syncIsBackground && (this.sessionAgentBusy || this.closing || this.closed);
if (e && this.database !== this.publishedDatabase) {
if (!this.database.supportsReindexSuspension) throw new MemoryBackgroundRebuildInterruptedError();
this.reindexProgress.yielded = true;
}
return e;
}
markMemoryWatchDirty() {
this.memoryWatchGeneration += 1;
this.dirty = true;
}
async withManagerOperation(e) {
this.memoryFiles?.assertCurrent();
if (this.closing || this.closed) throw new Error("Memory index manager is closed");
this.activeManagerOperations += 1;
try {
const t = await this.withPublishedDatabase(e);
this.memoryFiles?.assertCurrent();
return t;
} finally {
this.activeManagerOperations -= 1;
if (this.activeManagerOperations === 0) {
const e = Array.from(this.managerIdleWaiters);
this.managerIdleWaiters.clear();
for (const t of e) t();
}
}
}
snapshotReindexRetryState() {
return {
dirty: this.dirty,
memoryFullRetryDirty: this.memoryFullRetryDirty,
fullReindexRetryBackoff: this.fullReindexRetryBackoff,
sessionsDirty: this.sessionsDirty,
sessionsFullRetryDirty: this.sessionsFullRetryDirty,
sessionsReconcileDirty: this.sessionsReconcileDirty,
sessionsDirtyFiles: new Set(this.sessionsDirtyFiles)
};
}
takeReindexRetryStateForMaintenance() {
const e = this.snapshotReindexRetryState();
this.clearMemoryRetryState();
this.clearSessionRetryState();
return e;
}
adoptReindexRetryState(e) {
this.dirty = e.dirty || this.dirty;
this.memoryFullRetryDirty = e.memoryFullRetryDirty || this.memoryFullRetryDirty;
if (e.fullReindexRetryBackoff.retryAt >= this.fullReindexRetryBackoff.retryAt) this.fullReindexRetryBackoff = e.fullReindexRetryBackoff;
this.sessionsFullRetryDirty = e.sessionsFullRetryDirty || this.sessionsFullRetryDirty;
this.sessionsReconcileDirty = e.sessionsReconcileDirty || this.sessionsReconcileDirty;
this.sessionsDirtyFiles = /* @__PURE__ */ new Set([...e.sessionsDirtyFiles, ...this.sessionsDirtyFiles]);
this.sessionsDirty = e.sessionsDirty || this.sessionsDirty || this.sessionsFullRetryDirty || this.sessionsReconcileDirty || this.sessionsDirtyFiles.size > 0;
}
markFailedFullReindexRetry(e) {
if (e.memory) {
this.dirty = true;
this.memoryFullRetryDirty = true;
}
if (e.sessions) {
this.sessionsDirty = true;
this.sessionsFullRetryDirty = true;
}
}
recordFullReindexFailure(e) {
this.fullReindexRetryBackoff.attempts += 1;
this.fullReindexRetryBackoff.failedWithEmbeddings = e;
const t = Math.min(FULL_REINDEX_RETRY_INITIAL_DELAY_MS * 2 ** Math.min(this.fullReindexRetryBackoff.attempts - 1, 30), FULL_REINDEX_RETRY_MAX_DELAY_MS);
this.fullReindexRetryBackoff.retryAt = performance.now() + t;
}
clearFullReindexRetryBackoff() {
this.fullReindexRetryBackoff.attempts = 0;
this.fullReindexRetryBackoff.retryAt = 0;
this.fullReindexRetryBackoff.failedWithEmbeddings = false;
}
clearSessionRetryState() {
this.sessionsDirty = false;
this.sessionsFullRetryDirty = false;
this.sessionsReconcileDirty = false;
this.sessionsDirtyFiles.clear();
}
clearMemoryRetryState() {
this.dirty = false;
this.memoryFullRetryDirty = false;
}
refreshSessionDirtyFlag() {
this.sessionsDirty = this.sessionsFullRetryDirty || this.sessionsReconcileDirty || this.sessionsDirtyFiles.size > 0;
}
advanceSyncProgress(e, t = 1) {
if (!e) return;
e.completed += t;
e.report({
completed: e.completed,
total: e.total
});
}
async indexQueuedFiles(e, t, n) {
if (e.length === 0) return [];
if (t && n) t.report({
completed: t.completed,
total: t.total,
label: n
});
const r = await this.indexFiles(e);
if (this.reindexProgress) {
const t = new Set(r);
for (const n of e) if (n.source === "sessions" && !t.has(n)) this.reindexProgress.completedSessionFiles.add(n.entry.absPath);
}
this.advanceSyncProgress(t, e.length - r.length);
return r;
}
async executeSourceSync(e) {
const t = this.shouldDeferSourceWideBatch();
const n = this.reindexProgress;
const r = e.shouldSyncMemory ? (t && !this.dirty ? n?.memoryPlan : void 0) ?? await this.syncMemoryFiles({
needsFullReindex: e.needsFullReindex,
progress: e.progress,
...t ? { deferIndex: true } : {}
}) : void 0;
if (e.shouldSyncMemory && !t && n) n.memoryComplete = true;
if (e.shouldSyncSessions) {
await this.syncArchiveFiles({
needsFullReindex: e.needsFullSessionReindex ?? e.needsFullReindex,
targetArchiveFiles: e.targetArchiveFiles,
progress: e.progress,
...t ? { prefixIndexItems: r?.indexItems } : {}
});
if (r && !this.dirty) r.indexItems = [];
} else if (t) {
const t = await this.indexQueuedFiles(r?.indexItems ?? [], e.progress);
if (r) r.indexItems = t;
}
if (n?.yielded) {
n.memoryPlan = this.dirty ? void 0 : r;
return;
}
if (t) {
await r?.finalize();
if (e.shouldSyncMemory && n) {
n.memoryPlan = void 0;
n.memoryComplete = true;
}
}
if (e.shouldSyncSessions) this.clearSessionRetryState();
else this.refreshSessionDirtyFlag();
}
resolveConfiguredMemoryScopeHash() {
return resolveConfiguredScopeHash({
workspaceDir: this.workspaceDir,
extraPaths: this.settings.extraPaths,
multimodal: this.settings.multimodal
});
}
resolveConfiguredIndexIdentity() {
if (this.settings.provider === "none") return;
return resolveEmbeddingProviderIndexIdentity({
config: this.cfg,
agentDir: resolveAgentDir(this.cfg, this.agentId),
...resolveMemoryPrimaryProviderRequest({ settings: this.settings })
});
}
resolveCurrentIndexIdentityState(e) {
const t = e.provider !== void 0;
const n = !t && !this.provider && this.settings.provider !== "none" ? this.resolveConfiguredIndexIdentity() : void 0;
const r = this.settings.provider === "none" ? null : {
id: n?.provider.id ?? this.settings.provider,
model: (n?.provider.model ?? this.settings.model.trim()) || void 0
};
const i = t ? e.provider : this.provider ? {
id: this.provider.id,
model: this.provider.model
} : r;
const a = e.vectorReady ?? this.vector.available === true;
const o = i && this.provider && i.id === this.provider.id && i.model === this.provider.model ? this.resolveProviderIndexIdentities() : [];
const s = n?.cacheKeyData ? resolveMemoryIndexProviderIdentities({
provider: n.provider,
cacheKeyData: n.cacheKeyData,
aliases: n.aliases,
documentPrefix: this.settings.inputFormat?.document
}) : [];
const c = o.length > 0 ? o : s;
const l = s.length > 0;
return resolveMemoryIndexIdentityState({
meta: e.meta === void 0 ? this.database.facts.meta : e.meta,
provider: i,
providerKey: l ? c[0]?.providerKey : e.providerKeyKnown === false ? void 0 : this.providerKey ?? void 0,
providerAliases: c.slice(1),
providerKeyKnown: l ? true : e.providerKeyKnown,
configuredSources: resolveConfiguredSourcesForMeta(this.sources),
configuredScopeHash: this.resolveConfiguredMemoryScopeHash(),
chunkTokens: this.settings.chunking.tokens,
chunkOverlap: this.settings.chunking.overlap,
vectorReady: a,
hasIndexedChunks: e.hasIndexedChunks ?? this.database.facts.hasIndexedChunks,
ftsTokenizer: this.settings.store.fts.tokenizer
});
}
resetVectorState(e) {
const t = e && this.vector.available === true;
this.database.vectorReady = t ? Promise.resolve(true) : null;
if (!t) {
this.vector.available = null;
this.vector.loadError = void 0;
}
this.database.ensuredVectorDimensions = void 0;
this.vector.semanticAvailable = void 0;
this.vector.dims = void 0;
this.database.vectorDegradedWriteWarningShown = false;
}
async ensureVectorReady(e) {
if (!this.vector.enabled) return false;
if (!this.database.vectorReady) {
const e = this.database;
const t = e.isShadow ? e.withPrivateAccess(() => this.loadVectorExtension(), { reentrant: true }) : this.loadVectorExtension();
e.vectorReady = this.withTimeout(t, VECTOR_LOAD_TIMEOUT_MS, `sqlite-vec load timed out after ${Math.round(VECTOR_LOAD_TIMEOUT_MS / 1e3)}s`);
}
let t;
try {
t = await this.database.vectorReady || false;
} catch (e) {
const t = formatErrorMessage(e);
this.vector.available = false;
this.vector.loadError = t;
this.database.vectorReady = null;
log$11.warn(`sqlite-vec unavailable: ${t}`);
return false;
}
if (t && typeof e === "number" && e > 0 && this.database.ensuredVectorDimensions !== e) {
const t = this.database;
await t.updateIndexStructure({
type: "vector.ensure",
input: {
dimensions: e,
currentDimensions: this.vector.dims,
state: {
vector: this.vector,
fts: this.fts,
extensionPath: this.vector.extensionPath
}
}
}, () => this.assertDatabaseMutationCurrent(t));
t.ensuredVectorDimensions = e;
this.vector.dims = e;
}
return t;
}
async loadVectorExtension() {
if (this.vector.available === false) return false;
if (!this.vector.enabled) {
this.vector.available = false;
return false;
}
try {
const e = this.vector.extensionPath?.trim() ? resolveUserPath(this.vector.extensionPath) : void 0;
const t = this.database;
const n = await t.prepareVector(e, () => {
if (this.closed || !t.isOpen) throw new Error("Memory database owner closed before vector preparation");
});
if (!n) throw new Error("Memory vector preparation did not complete");
this.vector.extensionPath = n.extensionPath;
this.vector.available = true;
if (["incomplete", "unverified"].includes(t.facts.vectorState.state)) {
this.markConfiguredSourcesForFullReindex();
return false;
}
if (n.retiredLegacy) {
this.dirty = true;
this.memoryFullRetryDirty = true;
}
return true;
} catch (e) {
const t = formatErrorMessage(e);
this.vector.available = false;
this.vector.loadError = t;
log$11.warn(`sqlite-vec unavailable: ${t}`);
return false;
}
}
markConfiguredSourcesForFullReindex() {
this.memoryFullRetryDirty = true;
if (this.sources.has("memory")) this.dirty = true;
if (this.sources.has("sessions")) {
this.sessionsDirty = true;
this.sessionsFullRetryDirty = true;
}
}
buildSourceFilter(e, t, n) {
const r = t ?? Array.from(this.sources);
return buildMemorySourceFilter(e, r, n);
}
};
//#endregion
//#region extensions/memory-core/src/memory/manager-watch-ops.ts
const log$10 = createSubsystemLogger("memory");
var MemoryManagerWatchOps = class extends MemoryManagerSyncBase {
constructor(...e) {
super(...e);
this.memoryWatcherReady = Promise.resolve();
}
get memoryWatchCapacityDegraded() {
return this.fileWatcher?.capacityDegraded ?? false;
}
get memoryWatcherHealth() {
return this.fileWatcher?.health();
}
ensureWatcher() {
if (!this.sources.has("memory") || this.closed) return;
if (this.memoryFiles) {
if (this.memoryWatchSubscription || this.memoryWatchUnavailable) return;
const e = new AbortController();
this.memoryWatchSubscription = e;
const markDirty = (t) => {
if (e.signal.aborted || this.closed) return;
this.markMemoryWatchDirty();
this.memoryWatchUnavailable ||= t === "unavailable";
this.syncInBackground({ reason: "watch" });
};
this.remoteWatchRetirement = this.memoryFiles.watch({
agentId: this.agentId,
settings: {
extraPaths: this.settings.extraPaths,
multimodal: this.settings.multimodal,
sync: { watchDebounceMs: this.settings.sync.watchDebounceMs }
}
}, markDirty, e.signal).then(() => markDirty("unavailable"), (t) => {
markDirty("unavailable");
if (!e.signal.aborted) log$10.warn(`memory workspace watcher unavailable: ${String(t)}`);
else if (t !== e.signal.reason) {
materializeErrorStack(t);
this.remoteWatchCloseFailure = { error: t };
}
});
return;
}
if (this.fileWatcher) return;
this.fileWatcher = new LocalMemoryFileWatcher({
runInBackgroundContext: this.runInBackgroundContext,
workspaceDir: this.workspaceDir,
agentId: this.agentId,
settings: this.settings,
onDirty: () => this.markMemoryWatchDirty(),
onChange: () => {
this.markMemoryWatchDirty();
return this.syncBackground({ reason: "watch" });
},
onState: ({ health: e }) => {
if (e.length && e.every((e) => e.state === "ready")) this.memoryWatchUnavailable = false;
},
onUnavailable: () => {
this.memoryWatchUnavailable = true;
this.dirty = true;
}
});
this.memoryWatcherReady = this.fileWatcher.start().catch((e) => {
if (!this.closed) {
this.memoryWatchUnavailable = true;
this.dirty = true;
log$10.warn(`memory workspace watcher unavailable: ${String(e)}`);
}
});
}
async closeWatchResources() {
if (this.sessionWatchTimer) {
clearTimeout(this.sessionWatchTimer);
this.sessionWatchTimer = null;
}
this.memoryWatchSubscription?.abort();
this.memoryWatchSubscription = void 0;
const e = (await Promise.allSettled([
(async () => {
await this.remoteWatchRetirement;
if (this.remoteWatchCloseFailure) throw this.remoteWatchCloseFailure.error;
this.remoteWatchRetirement = void 0;
})(),
(async () => {
await this.fileWatcher?.close();
this.fileWatcher = void 0;
})(),
(async () => {
this.sessionUnsubscribe?.();
this.sessionUnsubscribe = null;
})()
])).flatMap((e) => e.status === "rejected" ? [e.reason] : []);
if (e.length === 1) throw e[0];
if (e.length > 1) throw new AggregateError(e, "Memory watch resources cleanup failed");
}
syncInBackground(e, t = e.reason) {
const failed = (e) => {
log$10.warn(`memory sync failed (${t}): ${String(e)}`);
};
try {
this.runInBackgroundContext(() => {
this.runInBackgroundContext(() => this.syncBackground(e)).catch(failed);
});
} catch (e) {
failed(e);
}
}
};
//#endregion
//#region extensions/memory-core/src/memory/manager-session-sync-ops.ts
const SESSION_QUIET_PERIOD_MS = 3e4;
const SESSION_MAX_DEFERRAL_MS = 3e5;
const SESSION_RETRY_DELAYS_MS = [
6e4,
3e5,
9e5
];
const SESSION_INSPECTION_BATCH_SIZE = 32;
const log$9 = createSubsystemLogger("memory");
var MemoryManagerSessionSyncOps = class extends MemoryManagerWatchOps {
constructor(...e) {
super(...e);
this.sessionLastActivity = 0;
this.sessionFullSyncPending = false;
this.sessionRetryAttempt = 0;
this.sessionRetryAt = 0;
this.sessionIndexRetryRequested = false;
}
async inspectDiagnosticSourceState() {
if (this.sources.has("memory")) try {
const e = this.database;
const t = await inspectMemorySourceState({
files: this.memoryFiles,
readIndexedRows: () => e.readSourceState({ source: "memory" }),
workspaceDir: this.workspaceDir,
settings: this.settings,
concurrency: this.getIndexConcurrency()
});
this.sourceInspections.set("memory", t);
this.dirty ||= t.dirty;
} catch (e) {
this.sourceInspections.set("memory", {
eligible: null,
issues: [String(e)]
});
this.dirty = true;
}
if (this.sources.has("sessions")) try {
await this.markSessionStartupCatchupDirtyFiles(true);
} catch (e) {
this.sourceInspections.set("sessions", {
eligible: null,
issues: [String(e)]
});
this.sessionsDirty = true;
}
}
async listSessionCorpusEntries(e) {
let t = await listSessionTranscriptCorpusEntriesForAgent(this.agentId, {
config: this.cfg,
includeContentRevision: false,
readOnly: this.database.readOnly
});
t = t.filter((e) => {
const t = e.artifactKind === "archive-artifact" ? e.sessionKey : void 0;
return isMemorySessionIndexable(e, t);
});
if (e) {
const n = /* @__PURE__ */ new Set([...this.normalizeTargetArchiveFiles(e.archiveFiles, t) ?? [], ...this.resolveArchiveFilesForSyncTargets(e.sessions, t)]);
const r = new Set(t.filter((e) => n.has(e.sessionFile) || e.transcriptSource !== "sqlite" && n.has(path.resolve(e.sessionFile))).map((e) => e.sessionId));
t = t.filter((e) => r.has(e.sessionId));
}
const n = await findForgottenMemorySessionIds({
agentId: this.agentId,
sessionIds: t.map((e) => e.sessionId)
});
return t.filter((e) => !n.has(e.sessionId));
}
sessionPathForCorpusEntry(e) {
return e.transcriptSource === "sqlite" ? sessionPathForSessionIdentity(e.agentId, e.sessionId) : sessionPathForFile(e.sessionFile);
}
legacyExtensionlessSessionPathForIdentity(e, t) {
return path.join("sessions", normalizeAgentId(e), t).replace(/\\/g, "/");
}
buildSessionEntryOptions(e) {
return {
generatedByDreamingNarrative: e.generatedByDreamingNarrative === true,
generatedByCronRun: e.generatedByCronRun === true,
...e.sessionKind ? { sessionKind: e.sessionKind } : {},
...e.transcriptSource === "sqlite" && e.storePath ? {
agentId: e.agentId,
sessionId: e.sessionId,
storePath: e.storePath
} : {},
...e.sessionKey ? { sessionKey: e.sessionKey } : {},
...e.updatedAtMs !== void 0 ? { updatedAtMs: e.updatedAtMs } : {}
};
}
ensureSessionListener() {
if (!this.sources.has("sessions") || this.sessionUnsubscribe) return;
const e = observeAgentRunActivity(this.agentId, (e) => {
this.runInBackgroundContext(() => {
this.sessionAgentBusy = e;
this.noteSessionIndexActivity();
this.scheduleSessionIndexPass();
});
});
const t = onInternalSessionTranscriptUpdate((e) => {
this.runInBackgroundContext(() => {
if (this.closing || this.closed) return;
const t = this.resolveSessionTranscriptUpdateSyncTarget(e);
if (t) {
this.scheduleSessionDirty(t);
return;
}
if (e.sessionFile) {
const t = e.sessionFile;
this.runInBackgroundContext(() => this.withManagerOperation(() => this.scheduleCorpusSessionFileDirty(t))).catch((e) => {
log$9.warn(`memory session corpus update failed: ${String(e)}`);
});
}
});
});
this.sessionUnsubscribe = () => {
e();
t();
};
}
async scheduleCorpusSessionFileDirty(e) {
const t = path.resolve(e);
if ((await this.listSessionCorpusEntries({ archiveFiles: [t] })).length > 0 || this.reindexProgress?.corpusEntries?.some((e) => e.sessionFile === t)) this.scheduleSessionDirty(t);
}
async ensureSessionStartupCatchup() {
if (!this.sources.has("sessions") || this.closing || this.closed) return;
await this.withManagerOperation(() => this.runSessionStartupCatchup());
}
async markSessionStartupCatchupDirtyFiles(e = false, t = () => this.closed) {
if (!this.sources.has("sessions") || t()) return [];
const n = await this.listSessionCorpusEntries();
if (t()) return [];
const r = await this.database.readSourceState({ source: "sessions" });
const i = e ? new Set(r.map((e) => e.path)) : void 0;
const a = n.filter((e) => e.transcriptSource === "sqlite");
const o = await readMemoryTranscriptStatsInWorker(a.map((e) => ({
agentId: e.agentId,
sessionId: e.sessionId,
...e.sessionKey ? { sessionKey: e.sessionKey } : {},
...e.storePath ? { storePath: e.storePath } : {}
})));
if (t()) return [];
const s = new Map(a.map((e, t) => [e, o[t]]));
const c = /* @__PURE__ */ new Set();
if (i) {
const e = n.filter((e) => !i.has(this.sessionPathForCorpusEntry(e)));
for (let n = 0; n < e.length; n += SESSION_INSPECTION_BATCH_SIZE) {
if (t()) return [];
const r = e.slice(n, n + SESSION_INSPECTION_BATCH_SIZE);
(await streamSessionEntries(r.map((e) => ({
absPath: e.sessionFile,
options: this.buildSessionEntryOptions(e)
})))).forEach((e, t) => {
if (e && !isMemorySessionIndexable(e)) c.add(r[t]);
});
}
}
const l = (await runWithConcurrency(n.map((e) => async () => {
if (t()) return null;
if (c.has(e)) return null;
if (e.transcriptSource === "sqlite") {
const t = s.get(e);
return t ? statSessionEntrySync(e.sessionFile, this.buildSessionEntryOptions(e), t) : null;
}
const n = e.sessionFile;
try {
const t = await fs.stat(n);
if (!t.isFile()) return null;
return {
absPath: n,
path: this.sessionPathForCorpusEntry(e),
mtimeMs: t.mtimeMs,
size: t.size
};
} catch (e) {
if (isFileMissingError(e)) return null;
throw e;
}
}), this.getIndexConcurrency())).filter((e) => e !== null);
const { dirtyFiles: u, hasStaleIndexedPaths: d } = resolveMemorySessionStartupState({
files: l,
existingRows: r
});
if (e) this.sourceInspections.set("sessions", {
eligible: l.length,
issues: l.length === 0 ? ["no eligible session transcripts found"] : []
});
if (t()) return u;
if (d) {
this.sessionsDirty = true;
this.sessionsReconcileDirty = true;
}
for (const e of u) this.sessionsDirtyFiles.add(e);
if (u.length > 0) this.sessionsDirty = true;
return u;
}
async runSessionStartupCatchup() {
const e = await this.markSessionStartupCatchupDirtyFiles(false, () => this.closing);
if (!this.sessionsDirty || this.closing || this.closed) return e;
this.sessionFullSyncPending = true;
this.deferSessionIndexFiles(e);
return e;
}
scheduleSessionDirty(e) {
if (this.closing || this.closed) return;
if (typeof e === "string") {
this.sessionPendingFiles.add(e);
this.reindexProgress?.changedSessionFiles.add(e);
} else {
this.sessionPendingTargets.set(memorySessionSyncTargetKey(e), e);
this.reindexProgress?.changedSessionTargets.set(memorySessionSyncTargetKey(e), e);
}
this.sessionPendingSince ??= performance.now();
this.noteSessionIndexActivity();
this.scheduleSessionIndexPass();
}
noteSessionIndexActivity() {
this.sessionLastActivity = performance.now();
if (this.sessionRetryAt === Infinity) {
this.sessionRetryAttempt = 0;
this.sessionRetryAt = 0;
}
}
requestSessionIndexRetry(e = false) {
if (this.sessionBackgroundIndexing) {
this.sessionIndexRetryRequested = true;
if (e) {
this.sessionFullSyncPending = true;
this.sessionsFullRetryDirty = true;
}
}
}
deferSessionIndexFiles(e, t = []) {
if (this.reindexProgress?.yielded) {
this.sessionFullSyncPending = true;
this.sessionPendingSince ??= performance.now();
return;
}
const n = new Map(t.map((e) => [e.sessionFile, e]));
for (const t of e) {
const e = n.get(t);
if (e?.transcriptSource === "sqlite") {
const t = {
agentId: e.agentId,
sessionId: e.sessionId,
...e.sessionKey ? { sessionKey: e.sessionKey } : {}
};
this.sessionPendingTargets.set(memorySessionSyncTargetKey(t), t);
} else this.sessionPendingFiles.add(t);
}
this.sessionPendingSince ??= performance.now();
this.sessionLastActivity = performance.now();
this.scheduleSessionIndexPass();
}
scheduleSessionIndexPass() {
if (this.sessionWatchTimer) {
clearTimeout(this.sessionWatchTimer);
this.sessionWatchTimer = null;
}
if (this.sessionPendingSince === void 0 || this.sessionRetryAt === Infinity || this.sessionAgentBusy || this.sessionBackgroundIndexing || this.closing || this.closed) return;
const e = Math.max(this.sessionRetryAt, Math.min(this.sessionLastActivity + SESSION_QUIET_PERIOD_MS, this.sessionPendingSince + SESSION_MAX_DEFERRAL_MS));
this.sessionWatchTimer = setTimeout(() => {
this.sessionWatchTimer = null;
if (this.closing || this.closed) return;
const failed = (e) => {
log$9.warn(`memory session update failed: ${String(e)}`);
};
try {
this.runInBackgroundContext(() => this.withManagerOperation(() => this.processSessionUpdateBatch())).catch(failed);
} catch (e) {
failed(e);
}
}, Math.max(0, e - performance.now()));
this.sessionWatchTimer.unref();
}
async processSessionUpdateBatch() {
if (this.sessionAgentBusy) {
this.scheduleSessionIndexPass();
return;
}
if (!this.sessionFullSyncPending && this.sessionPendingFiles.size === 0 && this.sessionPendingTargets.size === 0) return;
const e = this.sessionFullSyncPending;
this.sessionFullSyncPending = false;
const t = Array.from(this.sessionPendingFiles);
const n = Array.from(this.sessionPendingTargets.values());
const r = this.sessionPendingSince;
this.sessionPendingFiles.clear();
this.sessionPendingTargets.clear();
this.sessionPendingSince = void 0;
for (const e of t) this.sessionsDirtyFiles.add(e);
if (e || t.length > 0 || n.length > 0) {
this.sessionsDirty = true;
this.sessionBackgroundIndexing = true;
this.sessionIndexRetryRequested = false;
let i = false;
let a = false;
try {
await this.syncBackground(e ? { reason: "session-startup-catchup" } : {
reason: "session-delta",
sessions: n,
archiveFiles: t
});
i = !this.sessionIndexRetryRequested;
} catch (e) {
if (!(e instanceof MemoryBackgroundRebuildInterruptedError)) throw e;
a = true;
this.sessionFullSyncPending = true;
} finally {
if (i) {
this.sessionRetryAttempt = 0;
this.sessionRetryAt = 0;
} else {
this.sessionFullSyncPending ||= e;
this.sessionPendingFiles = /* @__PURE__ */ new Set([...t, ...this.sessionPendingFiles]);
this.sessionPendingTargets = new Map([...n.map((e) => [memorySessionSyncTargetKey(e), e]), ...this.sessionPendingTargets]);
this.sessionPendingSince = r ?? this.sessionPendingSince ?? performance.now();
if (!a) {
const e = SESSION_RETRY_DELAYS_MS[this.sessionRetryAttempt++];
this.sessionRetryAt = e === void 0 ? Infinity : performance.now() + e;
if (this.sessionRetryAttempt === SESSION_RETRY_DELAYS_MS.length) this.sessionRetryAt = Math.max(this.sessionRetryAt, this.fullReindexRetryBackoff.retryAt);
}
}
this.sessionBackgroundIndexing = false;
this.scheduleSessionIndexPass();
}
}
}
resolveSessionTranscriptUpdateSyncTarget(e) {
if (!e.target) return null;
const t = e.target.agentId.trim();
const n = e.target.sessionId.trim();
const r = e.target.sessionKey.trim();
if (!t || !n || normalizeAgentId(t) !== normalizeAgentId(this.agentId)) return null;
return {
agentId: t,
sessionId: n,
...r ? { sessionKey: r } : {}
};
}
normalizeTargetArchiveFiles(e, t = [], n = false) {
if (!e || e.length === 0) return null;
const r = /* @__PURE__ */ new Set();
const i = new Map(t.filter((e) => n || e.transcriptSource !== "sqlite").map((e) => [e.transcriptSource === "sqlite" ? e.sessionFile : path.resolve(e.sessionFile), e.sessionFile]));
for (const t of e) {
const e = t.trim();
if (!e) continue;
const n = i.get(e) ?? i.get(path.resolve(e));
if (n) r.add(n);
}
return r.size > 0 ? r : null;
}
resolveArchiveFilesForSyncTargets(e, t) {
const n = /* @__PURE__ */ new Set();
const r = Array.from(e ?? []);
const i = normalizeAgentId(this.agentId);
let a;
if (r.length > 1) {
a = /* @__PURE__ */ new Map();
for (const e of r) {
const t = e.sessionId.trim();
if (t) a.set(t, []);
}
for (const e of t) a.get(e.sessionId)?.push(e);
}
for (const e of r) {
const r = e.sessionId.trim();
const o = e.agentId?.trim() || this.agentId;
if (!r || normalizeAgentId(o) !== i) continue;
const s = e.sessionKey?.trim();
const c = (a ? a.get(r) ?? [] : t).filter((e) => e.sessionId === r && normalizeAgentId(e.agentId) === i && (!s || e.sessionKey === s));
for (const e of c) n.add(e.transcriptSource === "sqlite" ? e.sessionFile : path.resolve(e.sessionFile));
}
return n;
}
async resolveTargetSessionSyncPlan(e) {
const t = await this.listSessionCorpusEntries(e);
const n = /* @__PURE__ */ new Set([...this.normalizeTargetArchiveFiles(e.archiveFiles, t) ?? [], ...this.resolveArchiveFilesForSyncTargets(e.sessions, t)]);
return n.size > 0 ? {
corpusEntries: t,
targetArchiveFiles: n
} : null;
}
shouldSyncSessions(e, t = false) {
if (!this.sources.has("sessions")) return false;
if (e?.reason === "search" && !e.force) return false;
if (hasTargetedSessionSyncParams(e) || e?.force || t || this.sessionsFullRetryDirty) return true;
return e?.reason !== "session-start" && e?.reason !== "watch" && this.sessionsDirty;
}
};
//#endregion
//#region extensions/memory-core/src/memory/manager-source-sync-ops.ts
const SOURCE_SYNC_YIELD_INTERVAL_MS = 12;
const SOURCE_WIDE_SESSION_INDEX_FLUSH_FILES = 128;
const log$8 = createSubsystemLogger("memory");
function createSourceSyncYield(e) {
let t = 0;
let n = performance.now();
let r;
return async () => {
t += 1;
if (!r && t < e && performance.now() - n >= SOURCE_SYNC_YIELD_INTERVAL_MS) r = new Promise((e) => {
setImmediate(() => {
n = performance.now();
r = void 0;
e();
});
});
if (r) await r;
};
}
var MemoryManagerSourceSyncOps = class extends MemoryManagerSessionSyncOps {
async deleteIndexedFile(e, t, n) {
await withMemoryWorkspaceLock(this.workspaceDir, async () => {
const r = this.database;
const assertCurrent = () => {
if (this.closed || r.closed || r.readOnly || !r.isOpen || this.database !== r) throw new Error("Memory source owner changed before deletion");
};
const i = n === void 0 ? await r.read({
type: "source.hash",
input: {
path: e,
source: t
}
}, assertCurrent) : n ?? void 0;
assertCurrent();
await r.deleteSource({
path: e,
source: t,
expectedHash: i
}, assertCurrent);
});
}
async deleteStaleSourceFiles(e, t, n) {
if (n === null) return;
const r = createSourceSyncYield(t.length);
for (const i of t) try {
if (!n.has(i.path)) await this.deleteIndexedFile(i.path, e, i.hash);
} finally {
await r();
}
}
async syncMemoryFiles(e) {
this.clearMemoryRetryState();
const t = await resolveMemorySourceFileEntries({
files: this.memoryFiles,
workspaceDir: this.workspaceDir,
settings: this.settings,
concurrency: this.getIndexConcurrency()
});
log$8.debug("memory sync: indexing memory files", {
files: t.length,
needsFullReindex: e.needsFullReindex,
batch: this.batch.enabled,
concurrency: this.getIndexConcurrency()
});
const n = await this.database.readSourceState({ source: "memory" });
const r = new Map(n.map((e) => [e.path, e]));
const i = new Set(t.map((e) => e.path));
if (e.progress) {
e.progress.total += t.length;
e.progress.report({
completed: e.progress.completed,
total: e.progress.total,
label: this.batch.enabled ? "Indexing memory files (batch)..." : "Indexing memory files…"
});
}
const deleteStaleRows = () => this.deleteStaleSourceFiles("memory", n, i);
const a = [];
for (const n of t) {
const t = r.get(n.path);
if (!e.needsFullReindex && t?.hash === n.hash && t.mtime === n.mtimeMs && t.size === n.size) {
this.advanceSyncProgress(e.progress);
continue;
}
a.push({
entry: n,
source: "memory"
});
}
if (this.batch.enabled) {
if (e.deferIndex) return {
indexItems: a,
finalize: deleteStaleRows
};
await this.indexQueuedFiles(a, e.progress);
} else {
const t = a.map(({ entry: t }) => async () => {
await this.indexFile(t, "memory");
this.advanceSyncProgress(e.progress);
});
await runWithConcurrency(t, this.getIndexConcurrency());
}
await deleteStaleRows();
}
async syncArchiveFiles(e) {
const t = this.reindexProgress;
if (t && (t.changedSessionFiles.size || t.changedSessionTargets.size)) {
const e = t.corpusEntries ?? [];
const n = [...this.normalizeTargetArchiveFiles([...t.changedSessionFiles], e, true) ?? [], ...this.resolveArchiveFilesForSyncTargets(t.changedSessionTargets.values(), e)];
for (const e of n) t.completedSessionFiles.delete(e);
t.corpusEntries = void 0;
for (const e of t.changedSessionFiles) this.sessionPendingFiles.delete(e);
for (const e of t.changedSessionTargets.keys()) this.sessionPendingTargets.delete(e);
t.changedSessionFiles.clear();
t.changedSessionTargets.clear();
}
const n = e.corpusEntries ?? t?.corpusEntries ?? await this.listSessionCorpusEntries();
if (t) t.corpusEntries = n;
const r = e.needsFullReindex ? null : this.normalizeTargetArchiveFiles(e.targetArchiveFiles, n, true);
const i = new Map(n.map((e) => [e.sessionFile, e]));
const corpusEntryForPath = (e) => {
const t = i.get(e);
if (!t) throw new Error(`Missing session corpus entry for ${e}`);
return t;
};
const a = r ? Array.from(r) : n.map((e) => e.sessionFile);
const o = t ? a.filter((e) => !t.completedSessionFiles.has(e)) : a;
const { activePaths: s, existingRows: c, indexAll: l } = resolveMemorySessionSyncPlan({
needsFullReindex: e.needsFullReindex,
files: a,
targetSessionFiles: r,
existingRows: r ? null : await this.database.readSourceState({ source: "sessions" }),
sessionPathForFile: (e) => this.sessionPathForCorpusEntry(corpusEntryForPath(e))
});
const u = new Map((c ?? await this.database.readSourceState({
source: "sessions",
paths: o.map((e) => this.sessionPathForCorpusEntry(corpusEntryForPath(e)))
})).map((e) => [e.path, e]));
log$8.debug("memory sync: indexing session files", {
files: o.length,
indexAll: l,
dirtyFiles: this.sessionsDirtyFiles.size,
targetedFiles: r?.size ?? 0,
batch: this.batch.enabled,
concurrency: this.getIndexConcurrency()
});
if (e.progress) {
e.progress.total += o.length;
e.progress.report({
completed: e.progress.completed,
total: e.progress.total,
label: this.batch.enabled ? "Indexing session files (batch)..." : "Indexing session files…"
});
}
const d = createSourceSyncYield(o.length);
const deleteStaleRows = () => this.deleteStaleSourceFiles("sessions", c ?? [], s);
const deleteTargetArchiveStaleLiveRows = async () => {
if (!r) return;
const e = new Set(n.filter((e) => e.artifactKind === "active-session").map((e) => this.sessionPathForCorpusEntry(e)));
const t = Array.from(r).flatMap((e) => {
const { agentId: t, sessionId: n } = corpusEntryForPath(e);
return [sessionPathForSessionIdentity(t, n), this.legacyExtensionlessSessionPathForIdentity(t, n)];
}).filter((t) => !e.has(t));
const i = new Map((await this.database.readSourceState({
source: "sessions",
paths: t
})).map((e) => [e.path, e.hash]));
for (const e of t) {
if (!i.has(e)) continue;
await this.deleteIndexedFile(e, "sessions", i.get(e));
}
};
const resolveSessionIndexEntry = async (t, n) => {
if (!n) {
this.advanceSyncProgress(e.progress);
return null;
}
if (!isMemorySessionIndexable(n)) {
if (!this.database.isShadow || u.has(n.path)) await this.deleteIndexedFile(n.path, "sessions", u.get(n.path)?.hash ?? null);
this.advanceSyncProgress(e.progress);
return null;
}
const r = this.database;
const assertCurrent = () => {
if (this.closed || !r.isOpen || this.database !== r) throw new Error("Memory source owner changed during hash lookup");
};
const i = u.get(n.path);
const a = i?.hash;
const o = n.revisionMs === void 0 ? n.hash : `sqlite:${n.revisionMs}:${n.hash}`;
const s = a?.startsWith("sqlite:") ? a.slice(a.lastIndexOf(":") + 1) : a;
if (!e.needsFullReindex && i !== void 0 && s === n.hash) {
if ((i.hash !== o || i.mtime !== n.mtimeMs || i.size !== n.size) && !await r.refreshSourceState({
path: n.path,
hash: o,
mtime: n.mtimeMs,
size: n.size,
expectedHash: i.hash
}, assertCurrent)) throw new MemoryIndexRevisionConflictError(`Memory session source ${n.path} changed during metadata refresh; retry incremental sync.`);
this.advanceSyncProgress(e.progress);
return null;
}
const c = corpusEntryForPath(t);
const l = this.buildSessionEntryOptions(c);
return Object.assign(n, {
hash: o,
sessionId: c.sessionId,
streamSessionExport: (e) => streamSessionEntry(t, l, e)
});
};
const syncFiles = async (n) => {
const r = n.filter((t) => {
if (l || this.sessionsDirtyFiles.has(t)) return true;
this.advanceSyncProgress(e.progress);
return false;
});
const i = await streamSessionEntries(r.map((e) => ({
absPath: e,
options: this.buildSessionEntryOptions(corpusEntryForPath(e))
})));
return await runWithConcurrency(r.map((e, n) => async () => {
try {
const r = await resolveSessionIndexEntry(e, i[n] ?? null);
if (!r) t?.completedSessionFiles.add(e);
return r;
} finally {
await d();
}
}), this.getIndexConcurrency());
};
const deferItems = (e) => {
if (e.some((e) => e.source === "memory")) this.dirty = true;
this.deferSessionIndexFiles(e.filter((e) => e.source === "sessions").map((e) => e.entry.absPath), n);
};
{
const t = [...e.prefixIndexItems ?? []];
const flushPendingIndexItems = async () => {
if (t.length === 0) return false;
const n = t.splice(0);
const r = new Set(n.map((e) => e.source));
const i = await this.indexQueuedFiles(n, e.progress, r.size > 1 ? "Indexing memory sources (batch)..." : void 0);
if (i.length > 0) {
deferItems(i);
return true;
}
return false;
};
const r = this.syncIsBackground ? 8 : SOURCE_WIDE_SESSION_INDEX_FLUSH_FILES;
for (let e = 0; e < o.length; e += r) {
if (this.shouldYieldSessionIndexing()) {
deferItems(t);
this.deferSessionIndexFiles(o.slice(e), n);
return;
}
const i = (await syncFiles(o.slice(e, e + r))).filter((e) => e !== null);
t.push(...i.map((e) => ({
entry: e,
source: "sessions"
})));
if (t.length >= r) {
if (await flushPendingIndexItems()) {
this.deferSessionIndexFiles(o.slice(e + r), n);
return;
}
}
}
if (await flushPendingIndexItems()) return;
}
await deleteTargetArchiveStaleLiveRows();
await deleteStaleRows();
}
};
//#endregion
//#region extensions/memory-core/src/memory/manager-reindex-ops.ts
const log$7 = createSubsystemLogger("memory");
var MemoryManagerReindexOps = class extends MemoryManagerSourceSyncOps {
get reindexProgress() {
return this.reindexState?.progress;
}
async discardReindex() {
const e = this.reindexState;
if (!e) return;
try {
if (e.progress.cachePrunePending) await this.withPublishedDatabase(() => this.pruneEmbeddingCacheIfNeeded(true));
} finally {
await e.shadow.closeShadow();
this.reindexState = void 0;
if (!e.shadow.postgresStageId) {
e.shadow.assertShadowPath();
await removeMemoryDatabaseFiles(e.tempDbPath);
}
}
}
async resumeReindex(e) {
if (this.reindexState) {
const t = this.reindexState;
if (t.shadow.closed || t.providerKey !== (this.syncProviderGeneration?.providerKey ?? this.providerKey) || t.publishedIdentity !== this.publishedDatabase.facts.serialized || e?.force && !hasTargetedSessionSyncParams(e)) {
this.adoptReindexRetryState(t.originalRetryState);
this.markFailedFullReindexRetry({
memory: this.sources.has("memory"),
sessions: this.sources.has("sessions")
});
await this.discardReindex();
} else {
for (const n of e?.archiveFiles ?? []) t.progress.changedSessionFiles.add(n);
for (const n of e?.sessions ?? []) t.progress.changedSessionTargets.set(memorySessionSyncTargetKey(n), n);
return true;
}
}
return false;
}
async runInPlaceReindex(e, t) {
if (this.publishedDatabase.admission?.engine === "postgres" && !t) return withPostgresMemoryReindex(this.publishedDatabase, (t) => this.runInPlaceReindex(e, t));
const n = resolveUserPath(this.settings.store.databasePath);
const r = this.reindexState;
const i = r?.tempDbPath ?? `${n}.memory-reindex-${randomUUID()}`;
const a = r?.originalDatabase ?? this.database;
const o = r?.originalRetryState ?? this.snapshotReindexRetryState();
const s = this.syncProviderGeneration?.kind === "semantic";
const c = this.sources.has("memory");
const l = this.shouldSyncSessions(void 0, true);
let u = false;
try {
if (!t && !r) await cleanupAgedMemoryReindexTempFiles(n);
const s = r?.originalRevision ?? this.database.facts.revision;
const d = r?.shadow ?? t ?? await MemoryIndexDatabase.openShadow(i, this.settings.store.vector.enabled);
const f = this.reindexState ??= {
shadow: d,
tempDbPath: i,
originalDatabase: a,
originalRevision: s,
originalRetryState: o,
providerKey: this.syncProviderGeneration?.providerKey ?? this.providerKey,
publishedIdentity: a.facts.serialized,
progress: {
memoryComplete: false,
cachePrunePending: false,
completedSessionFiles: /* @__PURE__ */ new Set(),
changedSessionFiles: /* @__PURE__ */ new Set(),
changedSessionTargets: /* @__PURE__ */ new Map(),
yielded: false
}
};
f.progress.yielded = false;
if (!r) {
d.vector.enabled = this.vector.enabled;
d.vector.extensionPath = this.vector.extensionPath;
d.fts.enabled = this.fts.enabled;
}
const p = await this.withReindexDatabase(d, async () => {
if (!r) await d.admitSchema({
cacheEnabled: this.cache.enabled,
ftsEnabled: d.fts.enabled,
ftsTokenizer: this.settings.store.fts.tokenizer,
fresh: t ? void 0 : true
});
let n;
do {
n = this.memoryWatchGeneration;
await this.executeSourceSync({
shouldSyncMemory: c && (!f.progress.memoryComplete || this.dirty),
shouldSyncSessions: l,
needsFullReindex: false,
needsFullSessionReindex: true,
progress: e
});
if (f.progress.yielded) {
u = true;
return;
}
} while (d.supportsReindexSuspension && (this.memoryWatchGeneration !== n || f.progress.changedSessionFiles.size || f.progress.changedSessionTargets.size));
const i = this.syncProviderGeneration ? this.syncProviderGeneration.provider : this.provider;
const a = i === null || !d.facts.hasIndexedChunks || this.vector.available === true;
const o = {
model: i?.model ?? "fts-only",
provider: i?.id ?? "none",
providerKey: this.syncProviderGeneration ? this.syncProviderGeneration.providerKey : this.providerKey,
sources: resolveConfiguredSourcesForMeta(this.sources),
scopeHash: this.resolveConfiguredMemoryScopeHash(),
chunkTokens: this.settings.chunking.tokens,
chunkOverlap: this.settings.chunking.overlap,
chunkingVersion: 6,
embeddingInputFormatVersion: resolveEmbeddingInputFormatVersion(i?.model ?? ""),
ftsTokenizer: this.settings.store.fts.tokenizer,
provenanceVersion: 1
};
const s = this.syncProviderGeneration?.kind === "semantic" ? this.syncProviderGeneration.embeddingDimensions : void 0;
if (s) o.vectorDims = s;
else if (this.vector.available && this.vector.dims) o.vectorDims = this.vector.dims;
await this.database.writeMetadata(o);
return {
nextMeta: o,
vectorIndexComplete: a
};
});
if (!p) return;
await d.closeShadow();
await withMemoryWorkspaceLock(this.workspaceDir, async () => {
await withMemoryIndexGeneration(n, "write", async () => {
if (t) {
await publishPostgresMemoryStage(this.publishedDatabase, t, s, p.vectorIndexComplete, () => {
if (this.closed || this.publishedDatabase !== a || !a.isOpen) throw new Error("Memory publication owner changed before reindex publication");
});
return;
}
await this.publishedDatabase.publishShadow({
sourcePath: i,
sourceIdentity: readMemoryShadowIdentity(i),
metaKey: MEMORY_INDEX_META_KEY,
expectedRevision: s,
sourceSchema: d.searchSchema,
vectorIndexComplete: p.vectorIndexComplete,
extensionPath: d.vector.extensionPath
}, () => {
if (this.closed || this.publishedDatabase.closed || this.publishedDatabase.readOnly || this.publishedDatabase !== a || !a.isOpen) throw new Error("Memory publication owner changed before reindex publication");
d.assertShadowPath();
});
});
});
this.resetVectorState(p.vectorIndexComplete);
this.fts.available = d.fts.available;
this.fts.loadError = d.fts.loadError;
this.vector.dims = p.nextMeta.vectorDims;
await this.pruneEmbeddingCacheIfNeeded(true);
f.progress.cachePrunePending = false;
this.clearFullReindexRetryBackoff();
} catch (e) {
this.adoptReindexRetryState(o);
this.markFailedFullReindexRetry({
memory: c,
sessions: l
});
if (!(e instanceof MemoryBackgroundRebuildInterruptedError)) this.recordFullReindexFailure(s);
throw e;
} finally {
try {
if (!u) await this.discardReindex();
} catch (e) {
log$7.warn(`failed to remove memory reindex shadow database: ${formatErrorMessage(e)}`);
}
}
}
};
//#endregion
//#region extensions/memory-core/src/memory/manager-sync-ops.ts
const log$6 = createSubsystemLogger("memory");
var MemoryManagerSyncOps = class extends MemoryManagerReindexOps {
constructor(e) {
super();
this.fallbackProviderInitPromise = null;
this.providerInitialized = false;
this.automaticRebuildNotice = e ?? {
sequence: 0,
warning: ""
};
}
recordAutomaticRebuild() {
this.automaticRebuildNotice.sequence += 1;
this.automaticRebuildNotice.warning = `Automatic memory index repair was requested. To rebuild manually, run: ${formatMemoryIndexRebuildGuidance({ requestedProvider: this.settings.provider }, this.agentId)}`;
}
takeSearchMaintenanceRequest() {
const e = this.takeReindexRetryStateForMaintenance();
if (e.memoryFullRetryDirty || e.sessionsFullRetryDirty) this.recordAutomaticRebuild();
return e;
}
shouldDeferSourceWideBatch() {
const e = this.syncProviderGeneration;
const t = e ? e.provider : this.provider;
const n = e ? e.kind === "semantic" ? e.runtime : void 0 : this.providerRuntime;
return Boolean(this.batch.enabled && t && n?.batchEmbed && n.sourceWideBatchEmbed === true);
}
applyProviderResult(e) {
this.provider = e.provider;
this.fallbackFrom = e.fallbackFrom;
this.fallbackReason = e.fallbackReason;
this.providerUnavailableReason = e.providerUnavailableReason;
this.providerLifecycle = resolveMemoryProviderLifecycle(e);
this.providerRuntime = e.runtime;
this.providerInitialized = true;
this.providerKey = this.computeProviderKey();
this.batch = this.resolveBatchConfig();
}
createConfiguredEmbeddingProvider(e = resolveMemoryPrimaryProviderRequest({ settings: this.settings })) {
return createEmbeddingProvider({
createProvider: this.createProvider,
config: this.cfg,
agentDir: resolveAgentDir(this.cfg, this.agentId),
...this.acquireLocalService ? { acquireLocalService: this.acquireLocalService } : {},
...e
});
}
resolveConfiguredFallbackProvider() {
const e = resolveFallbackCurrentProviderId({
provider: this.provider,
lifecycle: this.providerLifecycle
});
return {
currentProviderId: e,
fallbackRequest: resolveMemoryFallbackProviderRequest({
cfg: this.cfg,
settings: this.settings,
currentProviderId: e
})
};
}
createSyncProgress(e) {
const t = {
completed: 0,
total: 0,
label: void 0,
report: (n) => {
if (n.label) t.label = n.label;
const r = n.total > 0 && t.label ? `${t.label} ${n.completed}/${n.total}` : t.label;
e({
completed: n.completed,
total: n.total,
label: r
});
}
};
return t;
}
assertFtsOnlySyncAllowed() {
if (this.syncProviderGeneration ? this.syncProviderGeneration.provider : this.provider) return;
this.assertRequiredProviderAvailable("sync");
const e = this.database.facts.meta;
if (!e || e.model === "fts-only" || !this.settings.provider || this.settings.provider === "none") return;
const t = this.providerUnavailableReason;
this.resetProviderInitializationForRetry();
throw new Error(`Memory sync aborted: embedding provider "${this.settings.provider}" is configured but unavailable. Refusing to run sync in fts-only fallback mode to protect existing vector index (current model: ${e.model}).` + (t ? ` Provider failure: ${t}` : ""));
}
async runSync(e) {
const t = hasTargetedSessionSyncParams(e);
let n = Boolean(e?.force && !t);
const r = e?.reason === "search-bootstrap";
const i = this.syncProviderGeneration ? this.syncProviderGeneration.provider : this.provider;
const a = e?.progress ? this.createSyncProgress(e.progress) : void 0;
let o = t;
let s = false;
let c = false;
try {
if (await this.resumeReindex(e)) {
n = true;
o = false;
c = true;
await this.runInPlaceReindex(a);
return;
}
if (!n && this.sources.has("sessions")) {
const e = await resolveActiveMemoryRecallSources({
rows: await this.database.readSourceState({ source: "sessions" }),
cfg: this.cfg,
agentId: this.agentId
});
for (const t of e) await this.deleteIndexedFile(t.path, "sessions", t.hash);
}
this.assertFtsOnlySyncAllowed();
if (a) a.report({
completed: a.completed,
total: a.total,
label: "Loading vector extension…"
});
const l = i ? await this.ensureVectorReady() : false;
const u = this.database.facts.meta;
if (this.database.ensuredVectorDimensions !== u?.vectorDims) this.database.ensuredVectorDimensions = void 0;
const d = t ? await this.resolveTargetSessionSyncPlan({
sessions: e?.sessions,
archiveFiles: e?.archiveFiles
}) : null;
const f = d?.targetArchiveFiles ?? null;
o = f !== null;
if (e?.reason === "cli" && !e.force && !o) await this.markSessionStartupCatchupDirtyFiles();
const p = this.syncProviderGeneration ? this.syncProviderGeneration.providerKey : this.providerKey;
const m = this.syncProviderGeneration?.identities ?? this.resolveProviderIndexIdentities();
const h = this.database.facts.hasIndexedChunks;
const g = resolveMemoryIndexIdentityState({
meta: u,
provider: i ? {
id: i.id,
model: i.model
} : null,
providerKey: p ?? void 0,
providerAliases: m.slice(1),
configuredSources: resolveConfiguredSourcesForMeta(this.sources),
configuredScopeHash: this.resolveConfiguredMemoryScopeHash(),
chunkTokens: this.settings.chunking.tokens,
chunkOverlap: this.settings.chunking.overlap,
vectorReady: l,
hasIndexedChunks: h,
ftsTokenizer: this.settings.store.fts.tokenizer
});
if (u && p && canUpgradeMemoryIndexProviderKey(g, u, m)) {
const e = this.database;
if (!await e.updateIndexStructure({
type: "index.upgradeProviderKey",
input: {
meta: u,
providerKey: p
}
}, () => this.assertDatabaseMutationCurrent(e))) return MEMORY_SYNC_DEFERRED;
}
if (t && !o) return;
if (g.status === "mismatched" && g.owner === "openclaw" && g.versionOrder === "newer" && e?.reason !== "cli") {
n = true;
return;
}
const _ = g.status !== "valid" && !h;
const v = g.status === "missing" && h && i === null && Boolean(this.settings.provider) && this.settings.provider !== "none" && !this.database.facts.hasSemanticChunks;
const y = i !== null || !this.settings.provider || this.settings.provider === "none" || v;
const b = g.status === "missing" && !o && y;
const x = e?.reason === "cli" && g.status !== "valid" && !o;
const S = g.status === "mismatched" && g.owner === "openclaw" && !o;
const C = g.status !== "missing" || _ || y;
const w = this.memoryFullRetryDirty || this.sessionsFullRetryDirty;
const T = o && w;
const E = w && (!e?.force || e.reason === "embedding-bootstrap-recovery") && !(this.fullReindexRetryBackoff.failedWithEmbeddings && !i) && performance.now() < this.fullReindexRetryBackoff.retryAt && !x;
if (E && !o) {
this.requestSessionIndexRetry();
return MEMORY_SYNC_DEFERRED;
}
n = e?.force && !o || x || !E && (_ || b || S) || !o && !E && (this.memoryFullRetryDirty && C || this.sessionsFullRetryDirty && g.status !== "valid" && C);
const D = n || this.sessionsFullRetryDirty && !o && !E || r;
if (g.status !== "valid" && !n) {
this.dirty = true;
if (this.markTargetArchiveFilesDirty(f)) this.sessionsDirty = true;
return T ? MEMORY_SYNC_DEFERRED : void 0;
}
if (!D) {
if (this.sources.has("sessions") && f) this.sessionsDirty = this.markTargetArchiveFilesDirty(f);
if (await this.syncTargetedSessions(f, d?.corpusEntries, a)) return T ? MEMORY_SYNC_DEFERRED : void 0;
}
c = true;
if (n) {
if (e?.reason !== "cli") this.recordAutomaticRebuild();
await this.runInPlaceReindex(a);
return;
}
const O = this.sources.has("memory") && (this.dirty || r);
const k = this.shouldSyncSessions(e, D);
s = this.sessionsFullRetryDirty && k;
await this.executeSourceSync({
shouldSyncMemory: O,
shouldSyncSessions: k,
needsFullReindex: n,
needsFullSessionReindex: D,
targetArchiveFiles: f ? Array.from(f) : void 0,
progress: a ?? void 0
});
if (s && !this.memoryFullRetryDirty) this.clearFullReindexRetryBackoff();
} catch (e) {
if (!c) throw e;
this.dirty ||= this.sources.has("memory");
if (s && !this.memoryFullRetryDirty) {
this.markFailedFullReindexRetry({
memory: false,
sessions: true
});
this.recordFullReindexFailure(i !== null);
}
const t = formatErrorMessage(e);
const l = isMemoryEmbeddingOperationError(e);
if (l) this.endSyncProviderGeneration();
if (l && await this.activateFallbackProvider(t)) {
if ((n || r) && !o) {
n = true;
this.beginSyncProviderGeneration();
await this.runInPlaceReindex(a);
} else this.requestSessionIndexRetry(true);
return;
}
if (!this.provider && this.fts.enabled && isMemoryEmbeddingOperationError(e)) {
this.requestSessionIndexRetry();
this.syncOutcomes.recordFailure(e);
log$6.warn(`memory embeddings unavailable; leaving memory index dirty: ${t}`);
return;
}
throw e;
} finally {
if (!n) await this.pruneEmbeddingCacheIfNeeded();
}
}
markTargetArchiveFilesDirty(e) {
for (const t of e ?? []) this.sessionsDirtyFiles.add(t);
return this.sessionsDirtyFiles.size > 0;
}
async syncTargetedSessions(e, t, n) {
if (!this.sources.has("sessions") || !e) return false;
const { sessionsDirtyFiles: r, sessionsFullRetryDirty: i, sessionsReconcileDirty: a } = this;
let o;
try {
await this.syncArchiveFiles({
needsFullReindex: false,
targetArchiveFiles: Array.from(e),
progress: n,
corpusEntries: t
});
for (const t of e) r.delete(t);
} catch (t) {
const n = formatErrorMessage(t);
const i = isMemoryEmbeddingOperationError(t);
if (i) this.endSyncProviderGeneration();
if (!i || !await this.activateFallbackProvider(n)) throw t;
for (const t of e) r.add(t);
o = { error: t };
}
this.sessionsDirty = i || a || r.size > 0 || this.sessionPendingFiles.size > 0 || this.sessionPendingTargets.size > 0;
if (o) {
this.requestSessionIndexRetry(true);
this.syncOutcomes.recordFailure(o.error);
}
return true;
}
resolveBatchConfig() {
const e = this.settings.remote?.batch;
return {
enabled: Boolean(e?.enabled && this.provider && this.providerRuntime?.batchEmbed),
wait: e?.wait ?? true,
concurrency: Math.max(1, e?.concurrency ?? 2),
pollIntervalMs: e?.pollIntervalMs ?? 2e3,
timeoutMs: resolveTimerTimeoutMs((e?.timeoutMinutes ?? 60) * 60 * 1e3, 36e5)
};
}
async activateFallbackProvider(e) {
if (this.closed) return false;
const t = this.fallbackProviderInitPromise;
if (t) return await t;
const n = this.activateFallbackProviderOnce(e);
this.fallbackProviderInitPromise = n;
try {
return await n;
} finally {
if (this.fallbackProviderInitPromise === n) this.fallbackProviderInitPromise = null;
}
}
async activateFallbackProviderOnce(e) {
const { currentProviderId: t, fallbackRequest: n } = this.resolveConfiguredFallbackProvider();
if (!n || !t) return false;
if (this.fallbackFrom) return false;
this.providerLifecycle = {
mode: "degraded",
providerId: t,
reason: e
};
await this.retireCurrentProvider();
if (this.closed) return false;
let r;
try {
r = await this.createConfiguredEmbeddingProvider(n);
} catch (e) {
this.resetProviderInitializationForRetry();
throw e;
}
if (!r.provider) {
this.resetProviderInitializationForRetry();
return false;
}
this.applyProviderResult({
...r,
requestedProvider: t,
fallbackFrom: t,
fallbackReason: e,
providerUnavailableReason: void 0
});
log$6.warn(`memory embeddings: switched to fallback provider (${n.provider})`, { reason: e });
return true;
}
};
//#endregion
//#region extensions/memory-core/src/memory/manager-embedding-cache-ops.ts
const CACHE_READ_PAGE_BYTES = 8388608;
const CACHE_READ_DEFAULT_DIMENSIONS = 4096;
var MemoryManagerEmbeddingCacheOps = class extends MemoryManagerSyncOps {
async pruneEmbeddingCacheIfNeeded(e = false) {
const t = this.cache.maxEntries;
if (!this.cache.enabled || !t || t <= 0) return;
const n = this.database;
const assertCurrent = () => {
if (this.closed || !n.isOpen || this.database !== n) throw new Error("Memory database owner closed or changed before write admission");
};
const r = { identities: this.syncProviderGeneration?.identities ?? this.resolveProviderIndexIdentities() };
while (!this.closing && await n.pruneEmbeddingCache({
maxEntries: t,
unreferencedFirst: r,
...e ? { recount: true } : {}
}, assertCurrent)) await setImmediate$1();
}
async collectCachedEmbeddings(e, t) {
const n = e.map((e) => e.chunk.hash);
const r = t.database.facts.meta;
const i = t.identities.filter((e, t) => t === 0 || e.provider === r?.provider && e.model === r.model && e.providerKey === r.providerKey);
const a = /* @__PURE__ */ new Map();
for (const { source: t, entry: n, chunk: r } of e) {
const e = a.get(r.hash);
const i = {
source: t,
path: n.path,
hash: r.hash
};
if (e) e.push(i);
else a.set(r.hash, [i]);
}
const o = Math.max(1, Math.floor(CACHE_READ_PAGE_BYTES / (16 * (t.embeddingDimensions ?? r?.vectorDims ?? CACHE_READ_DEFAULT_DIMENSIONS))));
const s = [...a.keys()];
const c = /* @__PURE__ */ new Map();
for (let e = 0; e < s.length; e += o) {
const n = s.slice(e, e + o);
const r = await t.database.read({
type: "cache.read",
input: {
providerIdentities: i,
hashes: n,
cacheEnabled: this.cache.enabled,
published: {
chunks: n.flatMap((e) => a.get(e) ?? []),
dimensions: t.embeddingDimensions
}
}
}, () => {
if (!t.database.isOpen) throw new Error("Memory database owner is closed");
});
for (const [e, n] of r) if (isValidMemoryEmbedding(n, t.embeddingDimensions)) {
t.embeddingDimensions ??= n.length;
c.set(e, n);
}
}
const l = collectMemoryCachedEmbeddings({
hashes: n,
cached: c
});
return {
...l,
missingCandidates: l.missing.map((t) => expectDefined(e[t], "missing memory embedding candidate"))
};
}
async embedChunksInBatches(e, t, n, r) {
const { embeddings: i, missing: a, missingCandidates: o } = r ?? await this.collectCachedEmbeddings(e, t);
if (a.length === 0) return i;
const s = buildMemoryEmbeddingBatches(o.map((e) => e.chunk), n);
let c = 0;
for (const e of s) {
const n = o.slice(c, c + e.length);
const r = e.map((e) => e.embeddingInput ?? { text: e.text });
const s = r.some((e) => hasNonTextEmbeddingParts(e));
const l = await this.embedBatchWithRetry(s ? r : e.map((e) => e.text), t, n);
for (let t = 0; t < e.length; t += 1) {
const e = a[c + t];
const n = l[t] ?? [];
if (e !== void 0) i[e] = n;
}
c += e.length;
}
return i;
}
async withGeneratedEmbeddingCacheWrite(e, t) {
await this.withPublishedDatabase(async () => {
if (!this.canWriteEmbeddingCache(e) || this.database !== e.database) return;
const assertCurrent = () => {
if (this.closed || e.database.closed || !e.database.isOpen || this.database !== e.database) throw new Error("Memory database owner closed or changed before write admission");
};
await e.database.mutateEmbeddingCache(t, assertCurrent, () => {
assertCurrent();
return this.canWriteEmbeddingCache(e);
});
});
}
canWriteEmbeddingCache(e) {
return this.syncProviderGeneration === e && !e.cacheWritesInvalidated && !e.database.closed;
}
async persistGeneratedEmbeddings(e, t, n) {
if (e.length === 0 || !this.canWriteEmbeddingCache(n)) return;
const r = n.embeddingDimensions ?? t[0]?.length;
if (t.length !== e.length || !t.every((e) => isValidMemoryEmbedding(e, r))) {
if (this.cache.enabled && n.embeddingDimensions !== void 0 && t.some((e) => isValidMemoryEmbedding(e) && e.length !== n.embeddingDimensions)) await withMemoryWorkspaceLock(this.workspaceDir, async () => {
try {
await this.withGeneratedEmbeddingCacheWrite(n, {
kind: "clear",
identities: n.identities
});
} finally {
n.cacheWritesInvalidated = true;
}
});
const i = t.findIndex((e) => !isValidMemoryEmbedding(e, r));
const a = t[i];
let o = `expected ${e.length} vectors, got ${t.length}`;
if (t.length === e.length) {
if (!Array.isArray(a)) o = `missing embedding array at position ${i}`;
else if (a.length === 0) o = `empty embedding at position ${i}`;
else if (a.length !== r) o = `expected ${r} dimensions, got ${a.length} at position ${i}`;
else o = `non-finite or non-numeric coordinate at position ${i}`;
}
throw new Error(`${n.provider.id} embeddings failed (model: ${n.provider.model}, batch size: ${e.length}): ${o}`);
}
n.embeddingDimensions = r;
if (!this.cache.enabled) return;
await withMemoryWorkspaceLock(this.workspaceDir, async () => {
if (!this.canWriteEmbeddingCache(n)) return;
const r = [];
for (const [n, i] of e.entries()) {
if (i.source === "sessions" && !i.entry.sessionId) continue;
r.push({
hash: i.chunk.hash,
embedding: t[n] ?? [],
...i.source === "sessions" ? { sessionId: i.entry.sessionId } : {}
});
}
if (r.length === 0) return;
const i = this.reindexProgress;
if (i) i.cachePrunePending = true;
await this.withGeneratedEmbeddingCacheWrite(n, {
kind: "upsert",
header: {
agentId: this.agentId,
provider: {
id: n.provider.id,
model: n.provider.model
},
providerKey: n.providerKey,
maxEntries: this.cache.maxEntries === void 0 ? void 0 : this.cache.maxEntries * (this.reindexProgress ? 2 : 1),
unreferencedFirst: { identities: n.identities }
},
entries: r
});
});
}
};
//#endregion
//#region extensions/memory-core/src/memory/manager-index-source.ts
async function readMemoryIndexSource({ absolutePath: e, workspaceDir: t, source: n, memoryFiles: r }) {
const i = n === "memory" && r ? await retryTransientMemoryRead(() => r.readForIndexing(e), `read workspace memory for indexing ${e}`).catch((e) => {
if (!isFileMissingError(e)) throw e;
return null;
}) : void 0;
if (i === null) return null;
const a = await resolveMemoryPathClassification({
absolutePath: e,
source: n,
workspaceDir: t,
readSource: i
});
const o = i?.content ?? await retryTransientMemoryRead(() => fs.readFile(e, "utf-8"), `read memory markdown for indexing ${e}`).catch((e) => {
if (n !== "memory" || !isFileMissingError(e)) throw e;
return null;
});
if (o === null) return null;
return {
content: o,
pathClassification: a
};
}
/**
* Chunks a session by streaming its export again under the indexed entry's hash and reset
* boundary; neither the export nor the index worker holds the whole transcript. A later change
* differs from that hash, so the next sync reindexes it.
*/
async function prepareSessionIndexSource(e, t, n) {
if (!e.streamSessionExport) throw new Error("Session index entries stream their export");
const r = readSessionResetRecallCutoffMetadata(e);
return await prepareSessionIndexInWorker({
...t,
cutoffLine: r.state === "valid" ? r.cutoffLine : void 0,
pathClassification: await resolveMemoryPathClassification({
absolutePath: e.absPath,
source: "sessions",
workspaceDir: n
})
}, e.streamSessionExport);
}
//#endregion
//#region extensions/memory-core/src/memory/manager-session-delta.ts
async function retainIndexedSessionChunks(e, t, n, r) {
const { entry: i, source: a, chunks: o } = e;
if (i.kind === "multimodal" || o.length === 0 || t.isShadow) return e;
const s = await t.read({
type: "source.chunks",
input: {
source: a,
path: i.path
}
}, r);
const c = n?.kind === "semantic";
const l = new Map(s.filter((e) => e.embedded || !c).map((e) => [e.id, e]));
if (l.size === 0) return e;
const u = n?.provider?.model ?? "fts-only";
const d = [];
const f = [];
const p = /* @__PURE__ */ new Set();
for (const e of o) {
const t = memoryChunkRowId(a, i.path, e, u);
if (!p.has(t)) {
p.add(t);
const n = l.get(t);
if (!n) d.push(e);
else if (n.importance !== e.importance || n.triggers !== e.triggers || n.projectKey !== e.projectKey || n.originClass !== (e.provenance?.originClass ?? "untrusted") || n.sessionKind !== (e.provenance?.sessionKind ?? "unknown") || e.provenance && n.observedAt !== e.provenance.observedAt || n.supersedesKey !== (e.provenance?.supersedesKey ?? null)) f.push(e);
}
}
if (a === "memory" && d.length === p.size) return e;
return {
...e,
chunks: d,
retained: f,
removedIds: s.filter((e) => !p.has(e.id)).map((e) => e.id)
};
}
//#endregion
//#region extensions/memory-core/src/memory/manager-embedding-ops.ts
const EMBEDDING_BATCH_MAX_TOKENS = 8e3;
const EMBEDDING_TIMEOUTS_MS = {
query: {
remote: 6e4,
local: 3e5
},
batch: {
remote: 12e4,
local: 6e5
}
};
const SOURCE_PUBLICATION_MAX_FILES = 8;
const SOURCE_PUBLICATION_MAX_ROWS = 128;
const SOURCE_WIDE_BATCH_MAX_FILES = 2048;
const SOURCE_WIDE_BATCH_MAX_REQUESTS = 5e4;
const log$5 = createSubsystemLogger("memory");
var MemoryManagerEmbeddingOps = class extends MemoryManagerEmbeddingCacheOps {
constructor(...e) {
super(...e);
this.batchFailureLimit = 2;
this.batchFailure = { count: 0 };
this.activeProviderUses = /* @__PURE__ */ new Map();
this.syncProviderGenerationRelease = null;
this.syncProviderGenerationOwners = 0;
}
acquireProviderUse(e) {
const t = createDeferredCore();
const n = this.activeProviderUses.get(e) ?? /* @__PURE__ */ new Set();
n.add(t.promise);
this.activeProviderUses.set(e, n);
return () => {
if (!n.delete(t.promise)) return;
t.resolve();
if (n.size === 0) this.activeProviderUses.delete(e);
};
}
async awaitProviderIdle(e) {
const t = this.activeProviderUses.get(e);
if (t) await Promise.all(t);
}
beginSyncProviderGeneration(e) {
if (this.syncProviderGeneration) {
this.syncProviderGenerationOwners += 1;
return;
}
const t = e?.forceFtsOnly ? null : this.provider;
const n = t ? this.providerRuntime : void 0;
const r = resolveMemoryIndexProviderIdentities({
provider: t,
cacheKeyData: n?.cacheKeyData,
aliases: n?.indexIdentityAliases,
documentPrefix: this.settings.inputFormat?.document
});
const i = {
database: this.database,
cacheWritesInvalidated: false,
providerKey: expectDefined(r.at(0), "primary memory provider identity").providerKey,
identities: r,
...t ? { embeddingDimensions: t.dimensions } : {}
};
this.syncProviderGeneration = t ? {
...i,
kind: "semantic",
provider: t,
...n ? { runtime: n } : {}
} : {
...i,
kind: "fts-only",
provider: null
};
this.syncProviderGenerationRelease = t ? this.acquireProviderUse(t) : null;
this.syncProviderGenerationOwners = 1;
}
endSyncProviderGeneration() {
if (this.syncProviderGenerationOwners > 1) {
this.syncProviderGenerationOwners -= 1;
return;
}
this.syncProviderGenerationOwners = 0;
this.syncProviderGeneration = null;
this.syncProviderGenerationRelease?.();
this.syncProviderGenerationRelease = null;
}
computeProviderKey() {
return expectDefined(this.resolveProviderIndexIdentities().at(0), "primary memory provider identity").providerKey;
}
resolveProviderIndexIdentities() {
return resolveMemoryIndexProviderIdentities({
provider: this.provider,
cacheKeyData: this.providerRuntime?.cacheKeyData,
aliases: this.providerRuntime?.indexIdentityAliases,
documentPrefix: this.settings.inputFormat?.document
});
}
async embedChunksWithBatch(e, t, n, r = {}, i) {
const a = n.provider;
const o = n.runtime?.batchEmbed;
if (!this.batch.enabled || !o) return this.embedChunksInBatches(e, n, EMBEDDING_BATCH_MAX_TOKENS, i);
const { embeddings: s, missing: c, missingCandidates: l } = i ?? await this.collectCachedEmbeddings(e, n);
if (c.length === 0) return s;
const u = l.map((e) => e.chunk);
const d = this.batch.enabled ? await runMemoryEmbeddingBatchTimeoutRetry({
onRetry: () => log$5.warn(`memory embeddings: ${a.id} batch timed out; retrying once`),
run: () => o({
agentId: this.agentId,
chunks: formatMemoryEmbeddingChunks(u, a.model, this.settings.inputFormat),
...this.settings.inputFormat ? { documentFormatApplied: true } : {},
wait: this.batch.wait,
concurrency: this.batch.concurrency,
pollIntervalMs: this.batch.pollIntervalMs,
timeoutMs: this.batch.timeoutMs,
debug: (n, i) => log$5.debug(n, {
...i,
source: t,
chunks: e.length,
...r
})
})
}) : null;
let f;
if (d?.kind === "success") {
if (this.batchFailure.count > 0) log$5.debug("memory embeddings: batch recovered; resetting failure count");
this.batchFailure = { count: 0 };
if (!d.value) return this.embedChunksInBatches(e, n, EMBEDDING_BATCH_MAX_TOKENS, {
embeddings: s,
missing: c,
missingCandidates: l
});
f = d.value;
await this.persistGeneratedEmbeddings(l, f, n);
} else {
if (d) {
const e = formatErrorMessage(d.error);
const t = isEmbeddingBatchUnavailableError(d.error);
if (this.batch.enabled) {
const n = this.batchFailure.count + (t ? this.batchFailureLimit : d.attempts);
this.batchFailure = {
count: n,
lastError: e,
lastProvider: a.id
};
this.batch.enabled = !(t || n >= this.batchFailureLimit);
}
const n = this.batch.enabled ? "keeping batch enabled" : "disabling batch";
log$5.warn(`memory embeddings: ${a.id} batch failed (${this.batchFailure.count}/${this.batchFailureLimit}); ${n}; falling back to non-batch embeddings: ${e}`);
}
return this.embedChunksInBatches(e, n, EMBEDDING_BATCH_MAX_TOKENS, {
embeddings: s,
missing: c,
missingCandidates: l
});
}
for (const [e, t] of c.entries()) s[t] = f[e] ?? [];
return s;
}
async embedBatchWithRetry(e, t, n) {
if (e.length === 0) return [];
const r = t?.provider ?? this.provider;
if (!r) throw new Error("Cannot embed batch in FTS-only mode (no embedding provider)");
const i = e.some((e) => typeof e !== "string");
const a = i ? "structured batch" : "batch";
const o = e.map((e, t) => ({
input: e,
cacheCandidate: n?.[t]
}));
try {
return await runMemoryEmbeddingBatchRetryWithSplit({
items: o,
maxInputsPerRequest: r.maxInputsPerRequest,
run: async (e) => {
const n = this.resolveEmbeddingTimeout("batch", r, t?.runtime);
log$5.debug(`memory embeddings: ${a} start`, {
provider: r.id,
items: e.length,
timeoutMs: n
});
const o = await runEmbeddingOperationWithTimeout({
timeoutMs: n,
message: `memory embeddings batch timed out after ${Math.round(n / 1e3)}s`,
run: async (t) => await embedMemoryDocuments(r, e.map((e) => e.input), this.settings.inputFormat, { signal: t })
});
if (!i) log$5.debug("memory embeddings: batch completed", {
provider: r.id,
items: e.length
});
return o;
},
onSuccess: async (e, n) => {
if (!t) return;
const r = e.flatMap((e) => e.cacheCandidate ? [e.cacheCandidate] : []);
if (r.length !== e.length) return;
await this.persistGeneratedEmbeddings(r, n, t);
},
waitForRetry: async (e) => {
await this.waitForEmbeddingRetry(e, i ? "retrying structured batch" : "retrying");
},
onSplit: ({ itemCount: e, splitAt: t }) => {
log$5.warn(`memory embeddings ${a} failed; splitting ${e} inputs into ${Math.ceil(e / t)} batches of at most ${t}`);
}
});
} catch (e) {
if (!i) log$5.debug("memory embeddings: batch failed", {
provider: r.id,
error: formatErrorMessage(e)
});
this.markLocalEmbeddingProviderDegraded(e);
throw createMemoryEmbeddingOperationError({
operation: i ? "structured-batch" : "batch",
providerId: r.id,
cause: e
});
}
}
async waitForEmbeddingRetry(e, t, n) {
log$5.warn(`memory embeddings retryable error; ${t} in ${e}ms`);
await sleepWithAbort(e, n);
}
resolveEmbeddingTimeout(e, t = this.provider, n = this.providerRuntime) {
const r = EMBEDDING_TIMEOUTS_MS[e];
const i = e === "query" ? n?.inlineQueryTimeoutMs : n?.inlineBatchTimeoutMs;
return typeof i === "number" && i > 0 ? resolveTimerTimeoutMs(i, r.remote) : r[t?.id === "local" ? "local" : "remote"];
}
async probeEmbeddingProvider(e, t) {
const n = this.resolveEmbeddingTimeout("query", e, t);
const r = createMemorySearchDeadlineControl();
try {
await runEmbeddingOperationWithTimeout({
timeoutMs: n,
message: `memory embedding probe timed out after ${Math.round(n / 1e3)}s`,
deadlineControl: r,
run: (t) => embedMemoryQuery(e, "ping", this.settings, {
signal: t,
[MEMORY_SEARCH_DEADLINE_CONTROL]: r
})
});
} catch (t) {
if (e === this.provider) this.markLocalEmbeddingProviderDegraded(t);
throw t;
}
}
async embedQueryWithRetry(e, t, n, r, i) {
const a = n ?? this.provider;
const o = n ? r : this.providerRuntime;
if (!a) throw new Error("Cannot embed query in FTS-only mode (no embedding provider)");
try {
return await runMemoryEmbeddingRetryLoop({
profile: "query",
run: async () => {
t?.throwIfAborted();
const n = this.resolveEmbeddingTimeout("query", a, o);
log$5.debug("memory embeddings: query start", {
provider: a.id,
timeoutMs: n
});
return await runEmbeddingOperationWithTimeout({
timeoutMs: n,
message: `memory embeddings query timed out after ${Math.round(n / 1e3)}s`,
signal: t,
deadlineControl: i,
run: async (t) => await embedMemoryQuery(a, e, this.settings, {
signal: t,
...i ? { [MEMORY_SEARCH_DEADLINE_CONTROL]: i } : {}
})
});
},
signal: t,
waitForRetry: async (e) => {
await this.waitForEmbeddingRetry(e, "retrying query", t);
}
});
} catch (e) {
throw createMemoryEmbeddingOperationError({
operation: "query",
providerId: a.id,
cause: e
});
}
}
async withTimeout(e, t, n) {
return await runEmbeddingOperationWithTimeout({
timeoutMs: t,
message: n,
run: () => e
});
}
getIndexConcurrency() {
const e = this.syncProviderGeneration ? this.syncProviderGeneration.kind === "semantic" ? this.syncProviderGeneration.runtime : void 0 : this.providerRuntime;
return resolveMemoryIndexConcurrency(this.batch, e);
}
sourceReplacement({ prepared: { entry: e, source: t, chunks: n, retained: r, removedIds: i }, embeddings: a, vectorReady: o }, s) {
return {
entry: {
path: e.path,
hash: e.hash,
mtimeMs: e.mtimeMs,
size: e.size
},
chunks: n,
embeddings: a,
model: s?.provider?.model ?? "fts-only",
now: Date.now(),
vectorReady: o,
retained: r,
removedIds: i,
...t === "sessions" ? {
source: t,
agentId: this.agentId,
sessionId: expectDefined(e.sessionId, "memory index session identity")
} : { source: t }
};
}
async writeChunkGroup(e, t) {
const n = this.database;
const r = t?.database ?? this.publishedDatabase;
await withMemoryWorkspaceLock(this.workspaceDir, async () => {
const assertCurrent = () => {
this.memoryFiles?.assertCurrent();
if (this.closed || n.closed || !n.isOpen || this.database !== n || r !== this.publishedDatabase || r.closed || !r.isOpen || t && this.syncProviderGeneration !== t) throw new Error("Memory source owner changed before replacement");
};
const i = [...e];
const a = i.map((e) => this.sourceReplacement(e, t));
const prepare = async () => {
for (let e = i.length - 1; e >= 0; e--) {
const { prepared: { entry: t, source: n } } = i[e];
if (n !== "memory") continue;
if ((await (this.memoryFiles?.inspectFile ?? buildFileEntry)(t.absPath, this.workspaceDir, this.settings.multimodal))?.hash !== t.hash) {
this.dirty = true;
log$5.debug("memory source changed while indexing; queued incremental retry", { path: t.path });
i.splice(e, 1);
a.splice(e, 1);
}
}
assertCurrent();
return a.length > 0;
};
if (!(a.length > 1 && memoryPublicationGroup(a) ? await n.replaceSource(a, assertCurrent, prepare) : await n.replaceSource(expectDefined(a[0], "memory source publication"), assertCurrent, prepare))) return;
for (const { prepared: { chunks: e }, vectorReady: t } of i) n.vectorDegradedWriteWarningShown = logMemoryVectorDegradedWrite({
vectorEnabled: this.vector.enabled,
vectorReady: t,
chunkCount: e.length,
warningShown: n.vectorDegradedWriteWarningShown,
loadError: this.vector.loadError,
warn: (e) => log$5.warn(e)
});
}).catch((t) => {
this.markFailedFullReindexRetry({
memory: false,
sessions: e.some((e) => e.prepared.source === "sessions")
});
throw t;
});
}
async prepareIndexEntry(e, t, n, r = true) {
const i = e.kind;
const prepare = async () => {
if (i === "multimodal") {
const n = await (this.memoryFiles?.buildMultimodalChunk ?? buildMultimodalChunkForIndexing)(e);
if (!n) {
this.dirty = true;
await this.deleteIndexedFile(e.path, t);
return null;
}
const r = await resolveMemoryPathClassification({
absolutePath: e.absPath,
source: t,
workspaceDir: this.workspaceDir,
readSource: this.memoryFiles ? n : void 0
});
const i = {
...n.chunk,
importance: null,
triggers: null,
projectKey: null
};
i.provenance = resolveChunkProvenance(e, t, i, r.originClass);
return {
entry: e,
source: t,
chunks: [i],
structuredInputBytes: n.structuredInputBytes
};
}
const r = {
entry: {
path: e.path,
mtimeMs: e.mtimeMs
},
chunking: this.settings.chunking,
provider: n?.kind === "semantic" ? {
id: n.provider.id,
maxInputTokens: n.provider.maxInputTokens
} : void 0,
hardMaxInputTokens: EMBEDDING_BATCH_MAX_TOKENS
};
if (t === "sessions" && e.streamSessionExport) {
const n = await prepareSessionIndexSource(e, r, this.workspaceDir);
this.dirty ||= !n;
return n && {
entry: e,
source: t,
chunks: n.chunks
};
}
const a = await readMemoryIndexSource({
absolutePath: e.absPath,
workspaceDir: this.workspaceDir,
source: t,
memoryFiles: this.memoryFiles
});
if (!a) {
this.dirty = true;
return null;
}
const o = await prepareMemoryIndexInWorker({
...r,
source: t,
content: a.content,
pathClassification: a.pathClassification
});
return {
entry: o.contentHash !== void 0 ? {
...e,
hash: o.contentHash
} : e,
source: t,
chunks: o.chunks
};
};
const a = t === "sessions" && i !== "multimodal" && e.streamSessionExport ? await withMemoryWorkspacePreparation(this.workspaceDir, prepare) : await withMemoryWorkspaceLock(this.workspaceDir, prepare);
if (!a || !r) return a;
const o = this.database;
return await retainIndexedSessionChunks(a, o, n, () => {
if (this.closed || o.closed || this.database !== o) throw new Error("Memory source owner changed before delta planning");
});
}
async indexFiles(e) {
if (e.length === 0) return [];
this.beginSyncProviderGeneration();
try {
return await this.indexFilesWithGeneration(e, this.syncProviderGeneration);
} finally {
this.endSyncProviderGeneration();
}
}
async indexFilesWithGeneration(e, t) {
const n = [];
let r = 0;
let i = 0;
while (i < e.length && n.length < SOURCE_WIDE_BATCH_MAX_FILES) {
if (this.shouldYieldSessionIndexing()) return [...n.map((e) => e.work), ...e.slice(i)];
const a = e[i++];
if (a.entry.kind === "multimodal") {
await this.indexFileWithGeneration(a.entry, a.source, t);
continue;
}
const o = await this.prepareIndexEntry(a.entry, a.source, t);
if (o) {
n.push({
work: a,
value: o
});
r += o.chunks.length;
if (r >= SOURCE_WIDE_BATCH_MAX_REQUESTS) break;
}
}
if (this.shouldYieldSessionIndexing()) return [...n.map((e) => e.work), ...e.slice(i)];
const a = n.flatMap(({ value: e }) => e.chunks.map((t) => ({
chunk: t,
entry: e.entry,
source: e.source
})));
let o = [];
if (t?.kind === "semantic" && a.length > 0) {
const e = await this.collectCachedEmbeddings(a, t);
if (!this.batch.enabled) o = await this.embedChunksInBatches(a, t, EMBEDDING_BATCH_MAX_TOKENS, e);
else {
const r = t.runtime?.sourceWideBatchEmbed === true;
const i = r ? Array.from({ length: Math.ceil(a.length / SOURCE_WIDE_BATCH_MAX_REQUESTS) }, (e, t) => Math.min(SOURCE_WIDE_BATCH_MAX_REQUESTS, a.length - t * SOURCE_WIDE_BATCH_MAX_REQUESTS)) : n.map((e) => e.value.chunks.length);
const s = new Map(a.flatMap((t, n) => e.embeddings[n]?.length ? [[t.chunk.hash, e.embeddings[n]]] : []));
let c = 0;
const l = i.map((e) => {
const n = a.slice(c, c + e);
c += e;
return async () => {
const e = n.map((e) => s.get(e.chunk.hash) ?? []);
const r = e.flatMap((e, t) => e.length > 0 ? [] : [t]);
const i = await this.embedChunksWithBatch(n, n[0]?.source ?? "unknown", t, {}, {
embeddings: e,
missing: r,
missingCandidates: r.map((e) => n[e])
});
for (const [e, t] of n.entries()) {
const n = i[e];
if (n?.length) s.set(t.chunk.hash, n);
}
return i;
};
});
o = (await runWithConcurrency(l, r ? 1 : this.getIndexConcurrency())).flat();
}
}
const s = o.find((e) => e.length > 0);
const c = s ? await this.ensureVectorReady(s.length) : false;
let l = 0;
let u = 0;
while (u < n.length) {
if (this.shouldYieldSessionIndexing()) return [...n.slice(u).map((e) => e.work), ...e.slice(i)];
const r = [];
const a = l;
let s = 0;
while (u < n.length && r.length < SOURCE_PUBLICATION_MAX_FILES) {
const e = n[u].value;
const i = e.chunks.length + (e.retained?.length ?? 0) + (e.removedIds?.length ?? 0);
const a = {
prepared: e,
embeddings: o.slice(l, l + e.chunks.length),
vectorReady: c
};
if (r.length > 0 && (r[0].prepared.source !== e.source || s + i > SOURCE_PUBLICATION_MAX_ROWS || !memoryPublicationGroup([...r, a].map((e) => this.sourceReplacement(e, t))))) break;
r.push(a);
s += i;
l += e.chunks.length;
u++;
}
await this.writeChunkGroup(r, t);
o.fill([], a, l);
for (const e of r) e.embeddings = [];
}
return i < e.length ? await this.indexFilesWithGeneration(e.slice(i), t) : [];
}
async indexFile(e, t) {
this.beginSyncProviderGeneration();
try {
await this.indexFileWithGeneration(e, t, this.syncProviderGeneration);
} finally {
this.endSyncProviderGeneration();
}
}
async indexFileWithGeneration(e, t, n, r = true) {
if (n?.kind !== "semantic" && e.kind === "multimodal") return;
const i = await this.prepareIndexEntry(e, t, n, r);
if (!i) return;
if (n?.kind !== "semantic" || i.chunks.length === 0) return await this.writeChunkGroup([{
prepared: i,
embeddings: [],
vectorReady: false
}], n);
let a;
try {
const e = i.chunks.map((e) => ({
chunk: e,
entry: i.entry,
source: i.source
}));
a = await this.embedChunksWithBatch(e, t, n);
} catch (t) {
const r = formatErrorMessage(t);
if (e.kind === "multimodal" && /(413|payload too large|request too large|input too large|too many tokens|input limit|request size)/i.test(r)) {
log$5.warn("memory embeddings: skipping multimodal file rejected as too large", {
path: e.path,
bytes: i.structuredInputBytes,
provider: n.provider.id,
model: n.provider.model,
error: r
});
return await this.writeChunkGroup([{
prepared: {
...i,
chunks: []
},
embeddings: [],
vectorReady: false
}], n);
}
throw t;
}
const o = a.find((e) => e.length > 0);
const s = o ? await this.ensureVectorReady(o.length) : false;
await this.writeChunkGroup([{
prepared: i,
embeddings: a,
vectorReady: s
}], n);
}
};
//#endregion
//#region extensions/memory-core/src/memory/manager-provider-lifecycle.ts
const EMBEDDING_PROBE_CACHE_TTL_MS = 3e4;
const log$4 = createSubsystemLogger("memory");
function resolveEffectiveMemorySearchSettings(e) {
if (e.provider !== "none" || !e.store.vector.enabled) return e;
return {
...e,
store: {
...e.store,
vector: {
...e.store.vector,
enabled: false
}
}
};
}
function resolveMemoryEmbeddingProviderRequirement(e) {
const t = (resolveAgentConfig(e.cfg, normalizeAgentId(e.agentId))?.memory?.search?.provider ?? e.cfg.memory?.search?.provider)?.trim();
if (e.settings.provider === "none" || t?.toLowerCase() === "none") return {
mode: "fts-only",
provider: e.settings.provider
};
const n = resolveEmbeddingProviderAdapterTransport(e.settings.provider, e.cfg);
if (!t || t.toLowerCase() === "auto" || n === "local") return {
mode: "optional",
provider: e.settings.provider
};
return {
mode: "required",
provider: e.settings.provider,
configuredProvider: t
};
}
var MemoryProviderLifecycle = class extends MemoryManagerEmbeddingOps {
constructor(...e) {
super(...e);
this.providerInitPromise = null;
this.providerRetirementPromise = Promise.resolve();
this.providersPendingRetirement = /* @__PURE__ */ new Set();
this.activeBackgroundSearchSyncs = /* @__PURE__ */ new Set();
this.indexIdentityDirty = false;
this.primaryRecoveryPromise = null;
this.primaryRecoveryRetryAt = 0;
}
async syncBackground(e) {
if (this.closing || this.closed) return;
return await this.withManagerOperation(() => this.syncAdmitted(e, {
background: true,
queuedSessionOwner: true
}));
}
markEmbeddingBootstrapFailure(e, t) {
if (e instanceof MemoryManagerReloadError) throw e;
const n = readErrorName(e).trim();
const r = /^[A-Za-z][A-Za-z0-9_.-]{0,63}$/.test(n) ? n : "";
const i = redactSensitiveText(formatErrorMessage(e), { mode: "tools" }).trim() || "embedding provider initialization failed";
const a = redactSensitiveText(r && r !== "Error" ? `${r}: ${i}` : i, { mode: "tools" });
const o = t?.provider ?? this.provider?.id ?? this.settings.provider;
const s = {
ok: false,
provider: o,
reason: a,
degradedTo: "keyword-only"
};
if (!t?.retainProvider) {
this.provider = null;
this.providerRuntime = void 0;
}
this.providerInitialized = true;
this.providerUnavailableReason = a;
this.providerLifecycle = {
mode: "degraded",
providerId: o,
reason: a
};
this.embeddingBootstrapFailure = s;
this.providerKey = this.computeProviderKey();
this.batch = this.resolveBatchConfig();
this.vector.semanticAvailable = false;
this.cacheProbeResult({
ok: false,
error: a
});
return s;
}
async ensureEmbeddingProviderForSearch(e, t) {
let n = e;
await this.recoverPrimaryProviderForSearch(n);
const r = this.embeddingBootstrapFailure;
if (r) {
if (this.getCachedEmbeddingAvailability()?.ok === false) {
t?.({
backend: "builtin",
embeddingBootstrap: r
});
return true;
}
}
try {
await this.ensureProviderInitialized();
} catch (e) {
if (this.providerRequirement.mode !== "optional") throw e;
const n = this.markEmbeddingBootstrapFailure(e);
t?.({
backend: "builtin",
embeddingBootstrap: n
});
return true;
}
if (!r) return false;
if (!this.provider) {
const e = this.refreshEmbeddingBootstrapFailure(r);
t?.({
backend: "builtin",
embeddingBootstrap: e
});
return true;
}
const i = this.refreshIndexIdentityDirty({
providerKeyKnown: true,
indexState: n
});
let a = r;
if (i.status !== "valid") {
try {
await this.syncAdmitted({
reason: "embedding-bootstrap-recovery",
force: true
});
} catch (e) {
const t = redactSensitiveText(formatErrorMessage(e), { mode: "tools" });
log$4.warn(`memory sync failed (embedding-bootstrap-recovery): ${t}`);
a = this.markEmbeddingBootstrapFailure(e, { retainProvider: true });
}
n = await this.readRetrievalIndexState();
}
if (this.refreshIndexIdentityDirty({
providerKeyKnown: true,
indexState: n
}).status === "valid" && await this.confirmEmbeddingBootstrapRecovery()) {
this.vector.semanticAvailable = this.vector.enabled && this.vector.available === true && n.vectorState.state === "complete";
this.clearEmbeddingBootstrapFailureAfterRecovery();
return false;
}
a = this.embeddingBootstrapFailure ?? a;
t?.({
backend: "builtin",
embeddingBootstrap: a
});
return true;
}
refreshEmbeddingBootstrapFailure(e) {
const t = {
...e,
reason: this.providerUnavailableReason ?? e.reason
};
this.embeddingBootstrapFailure = t;
this.cacheProbeResult({
ok: false,
error: t.reason
});
return t;
}
clearEmbeddingBootstrapFailureAfterRecovery() {
this.embeddingBootstrapFailure = void 0;
this.providerUnavailableReason = void 0;
if (this.provider) this.providerLifecycle = resolveMemoryProviderLifecycle({
provider: this.provider,
requestedProvider: this.settings.provider,
fallbackFrom: this.fallbackFrom,
fallbackReason: this.fallbackReason
});
this.embeddingProbeCache.delete(this.cacheKey);
}
async adoptPublishedFallbackProviderIfMatched(e) {
if (this.fallbackFrom || !this.provider) return false;
const { fallbackRequest: t } = this.resolveConfiguredFallbackProvider();
const n = e ? e.meta : this.database.facts.meta;
if (!t || !n || n.provider !== t.provider || n.model !== t.model) return false;
return await this.activateFallbackProvider("published memory index uses the configured fallback provider") && this.refreshIndexIdentityDirty({
providerKeyKnown: this.providerInitialized,
indexState: e
}).status === "valid";
}
async confirmEmbeddingBootstrapRecovery() {
const e = this.getCachedEmbeddingAvailability();
if (e) return e.ok;
const t = this.provider;
if (!t) return false;
try {
await this.probeEmbeddingProvider(t, this.providerRuntime);
this.cacheProbeResult({ ok: true });
return true;
} catch (e) {
this.markEmbeddingBootstrapFailure(e, {
retainProvider: true,
provider: t.id
});
return false;
}
}
async recoverPrimaryProviderForSearch(e) {
if (this.primaryRecoveryPromise) {
await this.primaryRecoveryPromise;
return;
}
const t = this.provider;
const n = e.meta;
if (!t || !this.fallbackFrom || !n || this.closed || this.syncProviderGeneration || Date.now() < this.primaryRecoveryRetryAt || this.refreshIndexIdentityDirty({
providerKeyKnown: true,
indexState: e
}).status === "valid") return;
this.primaryRecoveryRetryAt = Date.now() + EMBEDDING_PROBE_CACHE_TTL_MS;
const r = (async () => {
let e = null;
try {
const r = await this.createConfiguredEmbeddingProvider({
...resolveMemoryPrimaryProviderRequest({ settings: this.settings }),
fallback: "none"
});
e = r.provider;
if (!e || !resolveMemoryIndexProviderIdentities({
provider: e,
cacheKeyData: r.runtime?.cacheKeyData,
aliases: r.runtime?.indexIdentityAliases,
documentPrefix: this.settings.inputFormat?.document
}).some((e) => e.provider === n.provider && e.model === n.model && e.providerKey === n.providerKey)) return;
await this.probeEmbeddingProvider(e, r.runtime);
if (this.closed || this.provider !== t || this.syncProviderGeneration || this.fallbackProviderInitPromise) return;
this.applyProviderResult(r);
e = null;
this.clearEmbeddingBootstrapFailureAfterRecovery();
await this.retireProvider(t);
} catch (e) {
if (e instanceof MemoryManagerReloadError) throw e;
log$4.debug(`memory embeddings: primary recovery deferred: ${formatErrorMessage(e)}`);
} finally {
if (e) await this.retireProvider(e);
}
})();
this.primaryRecoveryPromise = r;
try {
await r;
} finally {
this.primaryRecoveryPromise = null;
}
}
async ensureProviderInitialized() {
if (this.providerInitialized) {
if (!(this.embeddingBootstrapFailure !== void 0 && !this.provider && this.getCachedEmbeddingAvailability() === null)) {
await this.fallbackProviderInitPromise?.catch(() => void 0);
return;
}
this.resetProviderInitializationForRetry();
}
if (this.settings.provider === "none") {
this.applyProviderResult({
provider: null,
requestedProvider: "none",
providerUnavailableReason: "No embedding provider available (FTS-only mode)"
});
return;
}
if (!this.providerInitPromise) this.providerInitPromise = (async () => {
await this.fallbackProviderInitPromise?.catch(() => void 0);
await this.retireCurrentProvider();
if (this.closed) return;
const e = await this.createConfiguredEmbeddingProvider();
this.applyProviderResult(e);
})();
try {
await this.providerInitPromise;
} catch (e) {
this.providerInitPromise = null;
throw e;
} finally {
if (this.providerInitialized) this.providerInitPromise = null;
}
}
resetProviderInitializationForRetry() {
this.retireCurrentProvider();
this.providerInitialized = false;
this.providerInitPromise = null;
this.providerUnavailableReason = void 0;
this.providerLifecycle = {
mode: "pending",
requestedProvider: this.settings.provider
};
}
markLocalEmbeddingProviderDegraded(e) {
if (this.provider?.id !== "local") return;
const t = formatErrorMessage(e);
const n = this.provider;
this.retireCurrentProvider();
this.providerUnavailableReason = `Local embeddings degraded: ${t}`;
this.providerLifecycle = {
mode: "degraded",
providerId: n.id,
reason: t
};
this.embeddingProbeCache.delete(this.cacheKey);
this.providerKey = this.computeProviderKey();
this.batch = this.resolveBatchConfig();
this.vector.semanticAvailable = false;
log$4.warn("memory embeddings: local provider degraded after transport failure", { error: t });
}
retireCurrentProvider() {
const e = this.provider;
if (e) {
this.provider = null;
this.providerRuntime = void 0;
}
return this.retireProvider(e);
}
retireProvider(e) {
if (e) this.providersPendingRetirement.add(e);
if (this.providersPendingRetirement.size === 0) return this.providerRetirementPromise;
const t = this.providerRetirementPromise.catch(() => {}).then(async () => {
let e;
let t = false;
for (const n of this.providersPendingRetirement) try {
await this.awaitProviderIdle(n);
await n.close?.();
this.providersPendingRetirement.delete(n);
} catch (n) {
if (!t) e = n;
t = true;
}
if (t) throw toErrorObject(e, "Embedding provider retirement failed");
});
this.providerRetirementPromise = t;
t.catch((e) => {
log$4.warn(`memory embeddings: failed to close previous provider: ${formatErrorMessage(e)}`);
});
return t;
}
async drainPendingProviderRetirements() {
try {
await this.retireCurrentProvider();
return [];
} catch (e) {
log$4.warn(`memory close: pending manager work failed: ${formatErrorMessage(e)}`);
return [e];
}
}
buildRequiredProviderUnavailableError(e) {
const t = listRegisteredMemoryEmbeddingProviderAdapters().map((e) => e.id).toSorted();
const n = t.length > 0 ? t.join(",") : "none";
const r = this.providerUnavailableReason ?? (this.providerLifecycle.mode === "fts-only" ? this.providerLifecycle.reason : "provider is unavailable");
return /* @__PURE__ */ new Error(`Memory ${e} unavailable: embedding provider "${this.settings.provider}" is configured but unavailable. Reason: ${r}. agentId=${this.agentId} purpose=${this.purpose} lifecycle=${JSON.stringify(this.providerLifecycle)} registeredMemoryEmbeddingProviders=${n}`);
}
assertRequiredProviderAvailable(e) {
if (this.providerRequirement.mode === "required" && !this.provider) {
const t = this.buildRequiredProviderUnavailableError(e);
this.resetProviderInitializationForRetry();
throw t;
}
}
async publishedRetrievalState() {
if (this.database.readOnly) return;
await this.database.refreshFacts();
const { meta: e, hasIndexedChunks: t, vectorState: n } = this.database.facts;
if (!t) return;
return {
meta: e,
hasIndexedChunks: t,
hasFtsContent: false,
vectorState: this.database.admission?.engine === "postgres" || e && e.provider !== "none" ? n : { state: "empty" }
};
}
async readRetrievalIndexState(e) {
return await this.publishedRetrievalState() ?? await runMemoryIndexState({
agentId: this.agentId,
databasePath: resolveUserPath(this.settings.store.databasePath)
}, e);
}
refreshIndexIdentityDirty(e) {
const t = this.settings.provider === "none" ? null : this.providerInitialized && this.providerLifecycle.mode !== "degraded" ? this.provider : void 0;
const n = this.resolveCurrentIndexIdentityState({
...t !== void 0 ? { provider: t } : {},
providerKeyKnown: e?.providerKeyKnown,
...e?.indexState ? {
meta: e.indexState.meta,
hasIndexedChunks: e.indexState.hasIndexedChunks
} : {}
});
return this.updateIndexIdentityState(n, e?.indexState);
}
refreshKeywordFallbackIndexIdentity(e) {
const t = e ? e.meta : this.database.facts.meta;
const n = this.resolveCurrentIndexIdentityState({
meta: t,
provider: t && t.provider !== "none" ? {
id: t.provider,
model: t.model
} : null,
providerKeyKnown: false,
vectorReady: false,
...e ? { hasIndexedChunks: e.hasIndexedChunks } : {}
});
return this.updateIndexIdentityState(n, e);
}
updateIndexIdentityState(e, t) {
if (t) this.database.facts = {
...this.database.facts,
meta: t.meta,
serialized: t.meta ? JSON.stringify(t.meta) : null,
hasIndexedChunks: t.hasIndexedChunks,
vectorState: t.vectorState
};
this.indexIdentityState = e;
this.indexIdentityDirty = e.status === "mismatched" || e.status === "missing" && (this.sources.has("memory") || this.database.facts.hasIndexedChunks);
return e;
}
async awaitManagerIdle() {
if (this.activeManagerOperations > 0) await new Promise((e) => {
this.managerIdleWaiters.add(e);
});
while (this.activeBackgroundSearchSyncs.size > 0) await Promise.all(Array.from(this.activeBackgroundSearchSyncs));
}
async probeVectorAvailability() {
return await this.withManagerOperation(async () => {
if (!this.vector.enabled) {
this.vector.semanticAvailable = false;
return false;
}
await this.ensureProviderInitialized();
if (!this.provider) {
this.vector.semanticAvailable = false;
return false;
}
const e = await this.probeVectorStoreAvailabilityAdmitted();
this.vector.semanticAvailable = e;
return e;
});
}
async probeVectorStoreAvailability() {
return await this.withManagerOperation(() => this.probeVectorStoreAvailabilityAdmitted());
}
async probeVectorStoreAvailabilityAdmitted() {
if (!this.vector.enabled) {
this.vector.available = false;
return false;
}
return await this.ensureVectorReady();
}
cacheProbeResult(e) {
const t = Date.now();
this.embeddingProbeCache.set(this.cacheKey, {
result: e,
adapters: this.getEmbeddingProbeOwners(),
checkedAtMs: t,
expireAtMs: t + EMBEDDING_PROBE_CACHE_TTL_MS
});
return e;
}
getCachedEmbeddingAvailability() {
const e = this.embeddingProbeCache.get(this.cacheKey);
if (!e) return null;
if (Date.now() >= e.expireAtMs) {
this.embeddingProbeCache.delete(this.cacheKey);
return null;
}
return {
...e.result,
checked: true,
cached: true,
checkedAtMs: e.checkedAtMs,
cacheExpiresAtMs: e.expireAtMs
};
}
async probeEmbeddingAvailability() {
return await this.withManagerOperation(async () => {
const e = this.getCachedEmbeddingAvailability();
if (e) return e;
await this.ensureProviderInitialized();
await this.adoptPublishedFallbackProviderIfMatched();
if (!this.provider) return this.cacheProbeResult({
ok: false,
error: this.providerUnavailableReason ?? "No embedding provider available (FTS-only mode)"
});
try {
await this.probeEmbeddingProvider(this.provider, this.providerRuntime);
return this.cacheProbeResult({ ok: true });
} catch (e) {
const t = formatErrorMessage(e);
return this.cacheProbeResult({
ok: false,
error: t
});
}
});
}
};
//#endregion
//#region extensions/memory-core/src/memory/manager-provider-runtime-facts.ts
const LOCAL_EMBEDDING_RUNTIME_FACTS = Symbol.for("openclaw.localEmbeddingRuntimeFacts");
function getLocalEmbeddingRuntimeFacts(e) {
if (!e) return;
const t = Reflect.get(e, LOCAL_EMBEDDING_RUNTIME_FACTS);
return typeof t === "function" ? t() : void 0;
}
//#endregion
//#region extensions/memory-core/src/memory/embedding-local-service.ts
const LOCAL_SERVICE_HOST_IDENTITIES = resolveGlobalSingleton(Symbol.for("openclaw.memoryLocalServiceHostIdentities"), () => ({
ids: /* @__PURE__ */ new WeakMap(),
nextId: 1
}));
function resolveMemoryCoreLocalServiceHostIdentity(e) {
if (!e) return "none";
let t = LOCAL_SERVICE_HOST_IDENTITIES.ids.get(e);
if (t === void 0) {
t = LOCAL_SERVICE_HOST_IDENTITIES.nextId;
LOCAL_SERVICE_HOST_IDENTITIES.nextId += 1;
LOCAL_SERVICE_HOST_IDENTITIES.ids.set(e, t);
}
return String(t);
}
//#endregion
//#region extensions/memory-core/src/memory/manager-registry.ts
const log$3 = createSubsystemLogger("memory");
function normalizeMemoryIndexManagerPurpose(e) {
return e === "status" || e === "cli" || e === "maintenance" ? e : "default";
}
function resolveMemoryIndexManagerCacheKey(e) {
return [
e.agentId,
e.workspaceDir,
JSON.stringify(e.settings),
JSON.stringify(e.providerRequirement),
resolveMemoryCoreLocalServiceHostIdentity(e.acquireLocalService),
e.purpose
].join(":");
}
var MemoryManagerRegistry = class {
constructor(e = {}) {
this.lifecycle = e;
this.embeddingProbeCache = /* @__PURE__ */ new Map();
this.cache = /* @__PURE__ */ new Map();
this.scopeOperations = /* @__PURE__ */ new Map();
this.closePromise = null;
this.managers = /* @__PURE__ */ new Map();
e.prepare = (e) => this.prepareManagersForReload(e);
}
get reload() {
return this.lifecycle.reload;
}
track(e, t) {
let n = this.managers.get(e);
if (!n) {
n = {
key: t,
adapters: /* @__PURE__ */ new Set(),
retiring: false
};
this.managers.set(e, n);
}
return n;
}
async createProvider(e, t, n) {
const r = this.managers.get(e);
if (!r) throw new Error("Memory manager has no lifecycle owner");
if (r.retiring || this.reload?.retireRuntime || this.reload?.adapters.has(t)) throw new MemoryManagerReloadError();
r.adapters.add(t);
return await n();
}
getProbeOwners(e) {
const t = this.managers.get(e);
return t ? [...t.adapters] : [];
}
prepareManagersForReload(e) {
for (const [t, n] of this.embeddingProbeCache) if (e.retireRuntime || n.adapters.some((t) => e.adapters.has(t))) this.embeddingProbeCache.delete(t);
return async () => {
const t = [...this.managers].filter(([t, n]) => n.retiring || e.retireRuntime || e.adapters.size > 0 && n.adapters.size === 0 || this.getProbeOwners(t).some((t) => e.adapters.has(t)));
for (const [e, n] of t) {
n.retiring = true;
if (this.cache.get(n.key) === e) this.cache.delete(n.key);
this.embeddingProbeCache.delete(n.key);
}
return { errors: (await Promise.allSettled([...e.retireRuntime ? this.scopeOperations.values() : [], ...t.map(([e, t]) => this.closeEntry(t.key, e))])).flatMap((e) => e.status === "rejected" ? [e.reason] : []) };
};
}
async acquire(e, t) {
if (e.purpose === "maintenance" && (this.reload?.retireRuntime || this.closePromise)) return null;
if (this.reload?.retireRuntime) throw new MemoryManagerReloadError();
return await this.runScopeOperation(e, async () => {
const n = await t.prepare();
if (!n) return null;
const create = async () => {
const e = await n.create();
this.track(e, n.key);
return e;
};
if (e.purpose !== "default") return await create();
const r = this.cache.get(n.key);
await this.closeScopeUnlocked({
agentId: e.agentId,
purpose: e.purpose,
...r && n.reuse(r) ? { exceptKey: n.key } : {}
});
const i = this.cache.get(n.key);
if (i) return i;
const a = await create();
this.cache.set(n.key, a);
return a;
});
}
async closeAll() {
const e = this.closePromise ?? Promise.resolve();
const operation = () => this.closeAllUnlocked();
const t = e.then(operation, operation);
this.closePromise = t;
await t;
if (this.closePromise === t) this.closePromise = null;
}
async closeForAgent(e) {
const t = {
agentId: normalizeAgentId(e.agentId),
purpose: e.purpose
};
await this.runScopeOperation(t, () => this.closeScopeUnlocked(t));
}
deleteIfCurrent(e, t) {
this.managers.delete(t);
if (this.cache.get(e) === t) this.cache.delete(e);
}
async runScopeOperation(e, t) {
await this.closePromise;
return await enqueueKeyedTask({
tails: this.scopeOperations,
key: JSON.stringify([e.agentId, e.purpose]),
task: t
});
}
async closeAllUnlocked() {
const e = Array.from(this.scopeOperations.values());
if (e.length > 0) await Promise.allSettled(e);
await this.closeEntries([...this.managers].filter(([e, t]) => t.retiring || this.cache.get(t.key) === e).map(([e, t]) => [t.key, e]));
}
async closeScopeUnlocked(e) {
const isScopedKey = (t) => t !== e.exceptKey && t.startsWith(`${e.agentId}:`) && t.endsWith(`:${e.purpose}`);
await this.closeEntries(Array.from(this.cache.entries()).filter(([e]) => isScopedKey(e)), e.agentId);
}
async closeEntry(e, t) {
await t.close();
this.deleteIfCurrent(e, t);
}
async closeEntries(e, t) {
let n;
for (const [r, i] of e) try {
await this.closeEntry(r, i);
} catch (e) {
n ??= e;
const r = t ? ` for agent ${t}` : "";
log$3.warn(`failed to close memory index manager${r}: ${String(e)}`);
}
if (n !== void 0) throw toErrorObject(n, "Failed to close memory index manager");
}
};
//#endregion
//#region extensions/memory-core/src/memory/manager-search-maintenance.ts
async function runMemorySearchMaintenance(e) {
const t = e.takeDirtyGeneration();
let n;
try {
n = await e.acquireManager();
} catch (n) {
e.restoreDirtyGeneration(t);
throw toErrorObject(n, "Memory search maintenance manager acquisition failed");
}
if (!n) {
e.restoreDirtyGeneration(t);
return;
}
let r;
let i;
try {
n.adoptReindexRetryState(t);
try {
await n.sync({ reason: e.reason });
} catch (t) {
if (!(t instanceof MemoryIndexRevisionConflictError)) throw t;
await n.sync({
reason: e.reason,
force: true
});
}
const r = await readMemorySearchManagerStatus(n);
if (r.dirty === true) {
const t = n.takeReindexRetryStateForMaintenance();
e.restoreDirtyGeneration(t);
i = r.lastSyncError ?? (t.memoryFullRetryDirty || t.sessionsFullRetryDirty ? MEMORY_SYNC_DEFERRED : void 0);
}
} catch (n) {
e.restoreDirtyGeneration(t);
r = toErrorObject(n, "Memory search maintenance failed");
}
try {
await n.close();
} catch (e) {
r ??= toErrorObject(e, "Memory search maintenance close failed");
}
if (r) throw r;
return i;
}
//#endregion
//#region extensions/memory-core/src/memory/mmr.ts
function applyMMRToHybridResults(e, t) {
if (e.length === 0) return e;
if (e.length === 1) return [...e];
if (t === 1) return e.toSorted((e, t) => t.score - e.score);
const n = e.map((e) => ({
item: e,
score: e.score,
text: prepareSimilarityText(e.snippet),
relevance: 0,
maxSimilarity: 0
}));
const r = Math.max(...n.map((e) => e.score));
const i = Math.min(...n.map((e) => e.score));
const a = r - i;
for (const e of n) e.relevance = a === 0 ? 1 : (e.score - i) / a;
const o = new Set(n);
const s = [];
while (o.size > 0) {
let e = null;
let n = -Infinity;
for (const r of o) {
const i = t * r.relevance - (1 - t) * r.maxSimilarity;
if (i > n || i === n && r.score > (e?.score ?? -Infinity)) {
n = i;
e = r;
}
}
if (!e) break;
s.push(e.item);
o.delete(e);
for (const t of o) {
const n = preparedTextSimilarity(t.text, e.text);
if (n > t.maxSimilarity) t.maxSimilarity = n;
}
}
return s;
}
//#endregion
//#region extensions/memory-core/src/memory/project-ranking.ts
function prepareActiveProjectKeys(e) {
return e?.length ? new Set(e) : void 0;
}
function projectScoreMultiplier(e, t) {
if (!e || !t || t.size === 0) return 1;
return e.split(";").map((e) => e.trim()).filter(Boolean).every((e) => t.has(e)) ? 1.15 : .9;
}
/** Chunks with a malformed project annotation never reach retrieval results. */
function hasValidProjectAnnotation(e) {
return !e.projectKey?.split(";").map((e) => e.trim()).includes(INVALID_PROJECT_ANNOTATION_KEY);
}
function applyRetrievalRanking(e, t) {
return e.filter(hasValidProjectAnnotation).map((e) => {
const n = e.importance;
const r = n === null || n === void 0 ? 1 : .75 + Math.max(1, Math.min(10, Math.floor(n))) * .05;
return Object.assign({}, e, { score: e.score * r * projectScoreMultiplier(e.projectKey, t) });
});
}
//#endregion
//#region extensions/memory-core/src/memory/temporal-decay.ts
const DAY_MS = 864e5;
const DATED_MEMORY_PATH_RE = /(?:^|\/)memory\/(?:[^/]+\/)*(\d{4})-(\d{2})-(\d{2})(?:-[^/]+)?\.md$/;
function applyTemporalDecayToScore(e) {
const { halfLifeDays: t } = e;
const n = Math.max(0, e.ageInDays);
if (!Number.isFinite(n)) return e.score;
return e.score * Math.exp(-(Math.LN2 / t) * n);
}
async function extractTimestamp(e) {
if (e.source === "sessions") {
const t = e.sessionSourceMtimes?.get(e.filePath);
return t !== void 0 && Number.isFinite(t) ? new Date(t) : null;
}
const t = e.filePath.replaceAll("\\", "/").replace(/^\.\//, "");
const n = e.workspaceDir ? path.resolve(e.workspaceDir, e.filePath) : void 0;
const r = n && e.workspaceDir ? path.relative(e.workspaceDir, n).replaceAll("\\", "/").replace(/^\.\//, "") : t;
const i = r === "MEMORY.md" || r === "USER.md" || r.startsWith("memory/");
if (e.source === "memory" && !i && n !== void 0 && e.evergreenExtraPaths?.some((e) => (n === e.path || isPathInside(e.path, n)) && matchesExtraMemoryPathEntry(e, n))) return null;
const a = DATED_MEMORY_PATH_RE.exec(t);
if (a) {
const e = Number(a[1]);
const t = Number(a[2]);
const n = Number(a[3]);
const r = new Date(Date.UTC(e, t - 1, n));
if (r.getUTCFullYear() === e && r.getUTCMonth() === t - 1 && r.getUTCDate() === n) return r;
}
if (e.source === "memory" && (t === "MEMORY.md" || t === "USER.md" || t.startsWith("memory/") && !a)) return null;
if (e.source === "memory" && e.memorySourceMtimes) {
const t = e.memorySourceMtimes.get(e.filePath);
return t !== void 0 && Number.isFinite(t) ? new Date(t) : null;
}
if (!n) return null;
try {
const e = await fs.stat(n);
if (!Number.isFinite(e.mtimeMs)) return null;
return new Date(e.mtimeMs);
} catch {
return null;
}
}
async function applyTemporalDecayToHybridResults(e) {
const t = e.temporalDecay;
if (!t.enabled) return [...e.results];
const n = e.workspaceDir ? normalizeExtraMemoryPathEntries(e.workspaceDir, e.extraPaths).filter((e) => e.evergreen === true) : [];
const r = e.nowMs ?? Date.now();
const i = /* @__PURE__ */ new Map();
return Promise.all(e.results.map(async (a) => {
const o = `${a.source}:${a.path}`;
let s = i.get(o);
if (!s) {
s = extractTimestamp({
filePath: a.path,
source: a.source,
workspaceDir: e.workspaceDir,
evergreenExtraPaths: n,
sessionSourceMtimes: e.sessionSourceMtimes,
memorySourceMtimes: e.memorySourceMtimes
});
i.set(o, s);
}
const c = await s;
if (!c) return a;
const l = applyTemporalDecayToScore({
score: a.score,
ageInDays: (r - c.getTime()) / DAY_MS,
halfLifeDays: t.halfLifeDays
});
return {
...a,
score: l
};
}));
}
//#endregion
//#region extensions/memory-core/src/memory/hybrid.ts
function scoreExactPathTieForTemporalDecay(e) {
return (1 + Math.max(0, Math.min(1, e))) / 2;
}
function createKeywordScoreScale(e, t) {
if (t === 0) return (e) => e;
const relevance = (e) => e / (1 - e);
const n = Math.max(0, ...e.filter((e) => e < 1).map(relevance));
return (e) => {
if (e <= 0) return e;
const r = e >= 1 ? 1 : relevance(e) / n;
return Math.min(e, r * t);
};
}
async function mergeHybridResults(e) {
const { mmr: t, temporalDecay: n } = e;
const createCandidate = (e) => ({
...e,
vectorScore: 0,
textScore: 0,
rankingScore: 0,
pathScore: 0,
exactPathSpecificity: e.exactPathSpecificity ?? 0,
hasBodyMatch: false,
hasVector: false,
hasKeyword: false
});
const r = /* @__PURE__ */ new Map();
for (const t of e.vector) r.set(t.id, {
...createCandidate(t),
vectorScore: t.vectorScore,
hasVector: true
});
for (const t of e.keyword) {
const e = t.exactPathSpecificity ?? 0;
const n = r.get(t.id) ?? createCandidate(t);
n.textScore = t.textScore;
n.hasBodyMatch = t.hasBodyMatch ?? t.textScore > 0;
n.rankingScore = t.rankingScore ?? t.textScore;
n.pathScore = t.pathScore ?? 0;
n.exactPathSpecificity = Math.max(n.exactPathSpecificity, e);
n.hasKeyword = true;
n.importance ??= t.importance;
n.triggers ??= t.triggers;
n.projectKey ??= t.projectKey;
if (!n.provenance && t.provenance) n.provenance = t.provenance;
if (t.snippet && t.snippet.length > 0) n.snippet = t.snippet;
r.set(t.id, n);
}
const i = Array.from(r.values()).filter(hasValidProjectAnnotation);
const keywordScoreOf = (e) => e.textScore > 0 ? e.rankingScore : e.exactPathSpecificity > 0 ? 0 : e.pathScore;
const a = createKeywordScoreScale(i.map(keywordScoreOf), e.vectorWeight > 0 ? Math.max(0, ...i.map((e) => e.vectorScore)) : 0);
const o = i.map((t) => {
const r = a(keywordScoreOf(t));
const i = t.hasVector && !t.hasKeyword && e.vectorWeight > 0 && e.isNonTextMediaPath?.(t.path) === true ? t.vectorScore : e.vectorWeight * t.vectorScore + e.textWeight * r;
const o = t.hasBodyMatch && t.textScore === 0 ? t.rankingScore : 0;
const s = t.exactPathSpecificity > 0 ? n.enabled ? scoreExactPathTieForTemporalDecay(i) : i > 0 ? i : 1 : i === 0 ? o : i;
return Object.assign({
path: t.path,
startLine: t.startLine,
endLine: t.endLine,
score: s,
vectorScore: t.vectorScore,
textScore: t.textScore,
exactPathSpecificity: t.exactPathSpecificity,
contentScore: i,
lexicalRank: o,
snippet: t.snippet,
source: t.source,
importance: t.importance,
triggers: t.triggers,
projectKey: t.projectKey
}, t.provenance ? { provenance: t.provenance } : {});
});
const s = prepareActiveProjectKeys(e.activeProjectKeys);
const c = applyRetrievalRanking(o, s).map((e) => Object.assign(e, { eligibilityScore: e.exactPathSpecificity > 0 ? projectScoreMultiplier(e.projectKey, s) : e.contentScore === 0 ? 0 : e.score }));
const l = (await applyTemporalDecayToHybridResults({
results: c,
temporalDecay: n,
workspaceDir: e.workspaceDir,
extraPaths: e.extraPaths,
sessionSourceMtimes: e.sessionSourceMtimes,
memorySourceMtimes: e.memorySourceMtimes,
nowMs: e.nowMs
})).map((e) => {
const t = e.score;
return Object.assign(e, {
rankingScore: t,
score: e.exactPathSpecificity > 0 ? projectScoreMultiplier(e.projectKey, s) : e.contentScore === 0 ? 0 : e.score
});
});
const compareRankingScores = (e, t) => t.rankingScore - e.rankingScore || t.lexicalRank - e.lexicalRank || e.path.localeCompare(t.path) || e.startLine - t.startLine || e.endLine - t.endLine;
const u = l.filter((e) => e.exactPathSpecificity === 0).sort((e, t) => t.score - e.score || compareRankingScores(e, t));
const rerankExactGroup = (e) => {
if (!t.enabled) return e;
return applyMMRToHybridResults(e.map((e) => Object.assign(e, { score: e.rankingScore })), t.lambda).map((e) => Object.assign(e, { score: projectScoreMultiplier(e.projectKey, s) }));
};
return [...[
3,
2,
1
].flatMap((e) => {
const t = l.filter((t) => t.exactPathSpecificity === e).sort(compareRankingScores);
if (n.enabled) return rerankExactGroup(t);
const r = t.filter((e) => e.contentScore > 0 || e.lexicalRank > 0);
const i = t.filter((e) => !(e.contentScore > 0) && e.lexicalRank === 0);
return rerankExactGroup(r).concat(rerankExactGroup(i));
}), ...t.enabled ? applyMMRToHybridResults(u, t.lambda) : u].map(({ exactPathSpecificity: e, rankingScore: t, contentScore: n, lexicalRank: r, ...i }) => i);
}
function hybridResultRangeKey(e) {
return `${e.source}:${e.path}:${e.startLine}:${e.endLine}`;
}
function selectHybridSearchResults(e) {
const t = e.merged.filter((t) => t.eligibilityScore >= e.minScore);
const n = t.slice(0, e.maxResults);
if (e.keyword.length === 0 || n.length === e.maxResults) return n.map(({ eligibilityScore: e, ...t }) => t);
const r = new Set(e.keyword.map((e) => hybridResultRangeKey(e)));
const isLexicalCandidate = (e) => e.eligibilityScore >= 0 && r.has(hybridResultRangeKey(e));
if (t.length === 0) return e.merged.filter(isLexicalCandidate).slice(0, e.maxResults).map(({ eligibilityScore: e, ...t }) => t);
const i = new Set(e.vectorCandidates.map(hybridResultRangeKey));
const a = new Set(n.map((e) => hybridResultRangeKey(e)));
for (const t of e.merged) {
if (n.length === e.maxResults) break;
const r = hybridResultRangeKey(t);
if (t.eligibilityScore < e.minScore && (t.vectorScore === 0 || !i.has(r)) && isLexicalCandidate(t) && !a.has(r)) {
a.add(r);
n.push(t);
}
}
return n.map(({ eligibilityScore: e, ...t }) => t);
}
//#endregion
//#region extensions/memory-core/src/memory/manager-search-retrieval.ts
const SNIPPET_MAX_CHARS = 700;
const EXACT_PATH_CANDIDATE_LIMIT = 200;
const log$2 = createSubsystemLogger("memory");
function projectRecallMetadata(e) {
return {
...typeof e?.importance === "number" ? { importance: e.importance } : {},
...typeof e?.triggers === "string" && e.triggers.trim() ? { triggers: e.triggers.trim() } : {},
...typeof e?.project_key === "string" && e.project_key.trim() ? { projectKey: e.project_key.trim() } : {}
};
}
function compareKeywordSearchHits(e, t, n = true) {
const r = t.exactPathSpecificity - e.exactPathSpecificity;
if (r !== 0) return r;
if (n && e.exactPathSpecificity > 0) {
const n = Number(t.hasBodyMatch) - Number(e.hasBodyMatch);
if (n !== 0) return n;
}
const i = t.score - e.score;
if (i !== 0) return i;
const a = t.textScore - e.textScore;
if (a !== 0) return a;
if (e.exactPathSpecificity === 0) {
const n = t.pathScore - e.pathScore;
if (n !== 0) return n;
}
return e.path.localeCompare(t.path) || e.startLine - t.startLine || e.id.localeCompare(t.id);
}
var MemorySearchRetrieval = class extends MemoryProviderLifecycle {
async listTriggerCandidates(e) {
return await this.readCuratedMemoryCandidates(e, false);
}
async listCuratedProjectCandidates(e) {
return await this.readCuratedMemoryCandidates(e, true);
}
async readCuratedMemoryCandidates(e, t) {
const n = Math.max(1, Math.min(512, Math.floor(e?.limit ?? (t ? 48 : 512))));
return await this.withManagerOperation(async () => {
const r = await runMemoryCuratedCandidates({
agentId: this.agentId,
databasePath: resolveUserPath(this.settings.store.databasePath)
}, {
limit: n,
projectsOnly: t,
activeProjectKeys: e?.activeProjectKeys,
checkProvenanceRepair: this.memorySourceProvenanceRepairPending
});
this.memorySourceProvenanceRepairPending = r.provenanceRepairPending;
if (this.memorySourceProvenanceRepairPending) {
this.withManagerOperation(() => this.syncAdmitted({ reason: "search" }, {
allowEmbeddingBootstrapFallback: true,
background: true
})).catch((e) => {
log$2.warn(`memory sync failed (automatic candidates): ${formatErrorMessage(e)}`);
});
return [];
}
return r.rows.map((e) => {
const t = {
path: e.path,
startLine: e.start_line,
endLine: e.end_line,
score: 0,
snippet: e.text,
source: "memory"
};
Object.assign(t, projectRecallMetadata(e));
t.provenance = {
originClass: e.origin_class,
sessionKind: e.session_kind,
observedAt: e.observed_at
};
if (typeof e.supersedes_key === "string") t.provenance.supersedesKey = e.supersedes_key;
return t;
});
});
}
async finalizeKeywordOnlyResults(e) {
const t = e.temporalDecay.enabled;
const n = t ? e.results.map((e) => {
if (e.exactPathSpecificity === 0) return e;
const t = e.hasBodyMatch ? e.score : 0;
return {
...e,
score: scoreExactPathTieForTemporalDecay(t)
};
}) : e.results;
const r = prepareActiveProjectKeys(e.activeProjectKeys);
const i = applyRetrievalRanking(n, r);
const a = i.filter((t) => (t.exactPathSpecificity > 0 ? projectScoreMultiplier(t.projectKey, r) : t.score) >= e.minScore);
const o = a.length > 0 ? a : i.filter((e) => e.score >= 0);
const s = (await applyTemporalDecayToHybridResults({
results: o,
temporalDecay: e.temporalDecay,
workspaceDir: this.workspaceDir,
extraPaths: this.settings.extraPaths,
sessionSourceMtimes: this.loadSourceMtimes("sessions", e.results),
memorySourceMtimes: this.loadSourceMtimes("memory", e.results)
})).toSorted((e, n) => compareKeywordSearchHits(e, n, !t)).map((e) => e.exactPathSpecificity > 0 ? Object.assign(e, { score: projectScoreMultiplier(e.projectKey, r) }) : e);
return this.toMemorySearchResults(s.slice(0, e.maxResults));
}
loadSourceMtimes(e, t) {
if (e === "memory" && !this.memoryFiles) return;
const n = t.filter((t) => t.source === e);
if (n.length === 0) return;
return new Map(n.map((e) => [e.path, e.sourceMtime]));
}
async attachRecallMetadata(e, t) {
if (e.length === 0) return e;
const n = {
candidates: e.map(({ id: e, path: t, source: n }) => ({
id: e,
path: t,
source: n
})),
includeMemoryMtimes: Boolean(this.memoryFiles)
};
const r = await runMemoryRecallMetadata({
agentId: this.agentId,
databasePath: resolveUserPath(this.settings.store.databasePath)
}, n, t);
return this.applyRecallMetadata(e, r);
}
applyRecallMetadata(e, { rows: t, sourceMtimes: n }) {
return e.filter((e) => t.has(e.id)).map((e) => {
const r = t.get(e.id);
return Object.assign(e, {
sourceMtime: n[e.source].get(e.path),
...projectRecallMetadata(r),
...r?.provenance ? { provenance: r.provenance } : {}
});
});
}
buildKeywordSearchQuery(e, t, n, r) {
return {
includeRecallMetadata: n?.fuseRecallMetadata,
body: {
ftsTable: MEMORY_INDEX_FTS_TABLE,
query: e,
ftsTokenizer: this.settings.store.fts.tokenizer,
limit: t,
snippetMaxChars: SNIPPET_MAX_CHARS,
sourceFilter: this.buildSourceFilter(void 0, r, n?.excludedSessionPaths),
boostFallbackRanking: n?.boostFallbackRanking
},
path: {
pathFtsTable: MEMORY_INDEX_PATHS_FTS_TABLE,
query: e,
exactPathLimit: EXACT_PATH_CANDIDATE_LIMIT,
ftsTokenizer: this.settings.store.fts.tokenizer,
limit: t,
snippetMaxChars: SNIPPET_MAX_CHARS,
sourceFilter: this.buildSourceFilter(MEMORY_INDEX_PATHS_FTS_TABLE, r, n?.excludedSessionPaths)
}
};
}
async prepareKeywordSearch(e, t, n, r) {
const i = await this.publishedRetrievalState();
const a = await runMemoryKeywordSearch({
agentId: this.agentId,
databasePath: resolveUserPath(this.settings.store.databasePath)
}, this.buildKeywordSearchQuery(e, t, n, r), n.signal, i === void 0);
const o = i ?? a.indexState;
if (!o) throw new Error("Memory keyword preparation returned no index state");
return {
indexState: o,
keyword: a
};
}
resolveKeywordSearchResult(e, t, n) {
if (e.body.error) log$2.warn(`memory search: body keyword query failed: ${e.body.error}`);
if (e.path.error) log$2.warn(`memory search: path keyword query failed: ${e.path.error}`);
const r = e.body.rows;
const i = e.path.rows;
const a = this.mergeKeywordSearchHits([r.map((e) => Object.assign(e, { pathScore: 0 })), i], t);
const o = this.limitKeywordSearchHits(a, n);
return e.recallData ? this.applyRecallMetadata(o, e.recallData) : o;
}
async searchKeyword(e, t, n, r, i) {
if (!this.fts.enabled || !this.fts.available) return [];
const a = i ?? await runMemoryKeywordSearch({
agentId: this.agentId,
databasePath: resolveUserPath(this.settings.store.databasePath)
}, this.buildKeywordSearchQuery(e, t, n, r), n?.signal);
n?.signal?.throwIfAborted();
const o = this.resolveKeywordSearchResult(a, e, t);
return n?.fuseRecallMetadata ? o : this.attachRecallMetadata(o, n?.signal);
}
mergeKeywordSearchHits(e, t) {
const n = prepareExactPathMatcher(t);
const r = /* @__PURE__ */ new Map();
for (const t of e) for (const e of t) {
const t = r.get(e.id);
if (!t) {
r.set(e.id, Object.assign(e, { exactPathSpecificity: n(e.path) }));
continue;
}
const i = t.hasBodyMatch;
const a = e.hasBodyMatch;
const o = i ? t.score : 0;
const s = a ? e.score : 0;
t.textScore = Math.max(t.textScore, e.textScore);
t.pathScore = Math.max(t.pathScore, e.pathScore);
t.hasBodyMatch ||= e.hasBodyMatch;
const c = Math.max(o, s);
t.score = c > 0 ? c : t.pathScore;
if (a && !i || a === i && e.snippet.length > t.snippet.length) t.snippet = e.snippet;
}
const i = [...r.values()];
for (const e of i) if (!e.hasBodyMatch) e.score = e.exactPathSpecificity > 0 ? 1 : e.pathScore;
return i;
}
limitKeywordSearchHits(e, t) {
const n = e.toSorted(compareKeywordSearchHits);
const r = n.filter((e) => e.exactPathSpecificity > 0 && e.hasBodyMatch).slice(0, t);
const i = n.filter((e) => e.exactPathSpecificity > 0 && !e.hasBodyMatch);
const a = r.concat(i).toSorted(compareKeywordSearchHits);
const o = /* @__PURE__ */ new Set();
for (const e of a) {
o.add(`${e.source}:${e.path}`);
if (o.size === EXACT_PATH_CANDIDATE_LIMIT) break;
}
const s = a.filter((e) => o.has(`${e.source}:${e.path}`));
const c = n.filter((e) => e.exactPathSpecificity === 0).slice(0, t);
return s.concat(c);
}
toMemorySearchResults(e) {
return e.map(({ id: e, pathScore: t, exactPathSpecificity: n, hasBodyMatch: r, path: i, startLine: a, endLine: o, score: s, textScore: c, snippet: l, source: u, ...d }) => Object.assign({
path: i,
startLine: a,
endLine: o,
score: s,
textScore: c,
snippet: l,
source: u
}, d));
}
handleRetrievalError(e, t, n) {
n?.throwIfAborted();
if (t instanceof WorkerTaskError && t.code === "overloaded") throw t;
if (readErrorName(t) === "DatabaseSearchCapabilityUnavailableError") throw t;
log$2.warn(`memory search: ${e} query failed: ${formatErrorMessage(t)}`);
return [];
}
async searchVector(e, t, n, r, i, a, o, s) {
const c = {
providerModel: r.model,
providerModelAliases: r.aliases,
queryVec: e,
limit: t,
snippetMaxChars: SNIPPET_MAX_CHARS
};
const readVectorRows = (e) => runMemoryVectorFallback({
agentId: this.agentId,
databasePath: resolveUserPath(this.settings.store.databasePath)
}, {
...c,
candidateIds: e,
limit: e?.length ?? t,
sourceFilter: this.buildSourceFilter(void 0, n, o)
}, s);
let l;
if (this.publishedDatabase.admission?.engine === "postgres") {
l = await readVectorRows();
this.vector.available = true;
this.vector.semanticAvailable = true;
this.vector.dims = e.length;
this.vector.loadError = void 0;
} else {
const t = admitMemoryVectorIndex({ databasePath: resolveUserPath(this.settings.store.databasePath) });
l = await searchVector({
...c,
signal: s,
ensureVectorReady: async () => {
if (o.length > 0) return false;
if (!this.vector.enabled) return false;
if (i.vectorState.state === "incomplete" || i.vectorState.state === "unverified") {
this.markConfiguredSourcesForFullReindex();
return false;
}
return i.vectorState.state === "complete";
},
runFallback: readVectorRows,
runVectorKnn: async (n, r) => {
const i = await searchMemoryVectorIndex(t.capability, t.index, n, {
extensionPath: this.vector.extensionPath,
signal: r
});
if (!i.fallbackScanRequired) {
this.vector.available = true;
this.vector.semanticAvailable = true;
this.vector.dims = e.length;
this.vector.loadError = void 0;
}
return i;
},
sourceFilterVec: this.buildSourceFilter("c", n, o)
});
}
const u = [...l];
const d = new Set(u.map((e) => e.id));
const f = a.filter((e) => !d.has(e));
if (f.length > 0) l.push(...await readVectorRows(f).catch((e) => this.handleRetrievalError("vector", e, s)));
return {
results: await this.attachRecallMetadata(l, s),
candidates: u
};
}
};
//#endregion
//#region extensions/memory-core/src/memory/manager-search-orchestration.ts
const SEARCH_CANDIDATE_UNIVERSE = 200;
const log$1 = createSubsystemLogger("memory");
var MemorySearchOrchestration = class extends MemorySearchRetrieval {
async search(e, t) {
const n = e.trim();
if (!n) return [];
const r = this.publishedDatabase.admission?.engine === "postgres";
if (r && n.length > 4096) throw new Error("PostgreSQL memory search query must not exceed 4096 characters");
if (r && tokenizeFtsQuery(n).length > 128) throw new Error("PostgreSQL memory search query must not exceed 128 terms");
const i = t?.maxResults ?? this.settings.query.maxResults;
const a = r ? Math.min(200, i) : i;
const o = t?.minScore ?? this.settings.query.minScore;
const s = (t?.activeProjectKeys?.length ?? 0) > 0 ? SEARCH_CANDIDATE_UNIVERSE : Math.max(SEARCH_CANDIDATE_UNIVERSE, a);
const selectResults = (e) => e.slice(0, a).map(({ sourceMtime: e, ...t }) => t);
return selectResults(await this.searchCandidates(n, {
...t,
maxResults: s,
minScore: o,
onPartialResults: t?.onPartialResults ? (e) => t.onPartialResults?.(e && selectResults(e)) : void 0
}));
}
async readFile(e) {
const t = this.memoryFiles ? void 0 : getAgentWorkspaceAccess(this.workspaceDir, "memoryFiles");
const n = this.memoryFiles ?? t?.memoryFiles;
n?.assertCurrent();
return await (n?.readFile ?? readMemoryFile)({
workspaceDir: this.workspaceDir,
extraPaths: this.settings.extraPaths,
relPath: e.relPath,
from: e.from,
lines: e.lines
});
}
async searchCandidates(e, t) {
const n = t?.minScore ?? this.settings.query.minScore;
const r = t?.maxResults ?? this.settings.query.maxResults;
const i = t?.sources && t.sources.length > 0 ? uniqueValues(t.sources).filter((e) => this.sources.has(e)) : void 0;
const a = !t?.sources?.length || (i?.length ?? 0) > 0;
const o = i ?? this.settings.searchSources;
const s = this.settings.query.hybrid;
const c = Math.min(200, Math.max(1, Math.floor(r * s.candidateMultiplier)));
const l = (t?.lexicalOnly === true || this.providerRequirement.mode === "fts-only") && o.length === 1 && o[0] === "sessions";
const u = {
boostFallbackRanking: true,
signal: t?.signal,
fuseRecallMetadata: l,
excludedSessionPaths: new Array()
};
const d = /* @__PURE__ */ new Map();
const f = this.publishedDatabase;
const assertReadOwner = () => {
t?.signal?.throwIfAborted();
if (!f.isOpen || this.publishedDatabase !== f) throw new Error("Memory retrieval changed its captured database owner");
};
let p;
let m;
const releaseReadGeneration = async () => {
const e = m;
m = void 0;
p = void 0;
await e?.();
};
const readIndexState = async () => {
m ??= await acquireMemoryIndexReadGeneration(this.settings.store.databasePath, t?.signal);
assertReadOwner();
p = void 0;
const n = a && o.includes("sessions") ? await resolveActiveMemoryRecallSources({
rows: await f.readSourceState({ source: "sessions" }),
cfg: this.cfg,
agentId: this.agentId
}) : [];
assertReadOwner();
u.excludedSessionPaths = n.map((e) => e.path);
for (const e of n) d.set(e.path, e);
if (a && this.fts.enabled && this.fts.available && (t?.lexicalOnly || s.enabled || this.providerRequirement.mode === "fts-only" || this.providerInitialized && !this.provider || this.embeddingBootstrapFailure !== void 0)) {
const t = await this.prepareKeywordSearch(e, c, u, o);
p = t.keyword;
return t.indexState;
}
return await this.readRetrievalIndexState(t?.signal);
};
const runSearch = async () => {
t?.onDebug?.({ backend: "builtin" });
if (this.providerRequirement.mode === "required") {
await this.ensureProviderInitialized();
this.assertRequiredProviderAvailable("search");
}
let i = await readIndexState();
let d = this.hasIndexedContent(i);
if (!d) {
await releaseReadGeneration();
try {
await this.syncAdmitted({ reason: "search-bootstrap" }, { allowEmbeddingBootstrapFallback: true });
} catch (e) {
if (e instanceof WorkerTaskError && e.code === "overloaded") throw e;
if (readErrorName(e) === "DatabaseSearchCapabilityUnavailableError") throw e;
if (this.providerRequirement.mode === "optional" && isMemoryEmbeddingOperationError(e)) {
const t = this.provider?.id ?? this.settings.provider;
await this.retireCurrentProvider().catch((e) => {
const t = redactSensitiveText(formatErrorMessage(e), { mode: "tools" });
log$1.warn(`memory search-bootstrap: failed to retire embedding provider: ${t}`);
});
this.markEmbeddingBootstrapFailure(e, { provider: t });
await this.syncAdmitted({ reason: "search-bootstrap" }).catch((e) => {
if (e instanceof WorkerTaskError && e.code === "overloaded") throw e;
if (readErrorName(e) === "DatabaseSearchCapabilityUnavailableError") throw e;
const t = redactSensitiveText(formatErrorMessage(e), { mode: "tools" });
log$1.warn(`memory sync failed (search-bootstrap-fallback): ${t}`);
});
} else log$1.warn(`memory sync failed (search-bootstrap): ${String(e)}`);
}
i = await readIndexState();
d = this.hasIndexedContent(i);
}
if (!d) {
if (this.embeddingBootstrapFailure) t?.onDebug?.({
backend: "builtin",
embeddingBootstrap: this.embeddingBootstrapFailure
});
return [];
}
const f = this.embeddingBootstrapFailure !== void 0;
if (f || l && !this.providerInitialized) await releaseReadGeneration();
const h = await this.ensureEmbeddingProviderForSearch(i, t?.onDebug);
const refreshSearchIdentity = () => h ? this.refreshKeywordFallbackIndexIdentity(i) : this.refreshIndexIdentityDirty({
providerKeyKnown: this.providerInitialized,
indexState: i
});
if (f) i = await readIndexState();
const g = this.purpose === "default" || this.purpose === "cli";
if (!h && !this.provider && (this.providerLifecycle.mode === "pending" || this.providerLifecycle.mode === "degraded" && this.providerLifecycle.providerId !== this.settings.provider)) {
this.resetProviderInitializationForRetry();
if (l) await releaseReadGeneration();
await this.ensureProviderInitialized();
}
this.assertRequiredProviderAvailable("search");
if (!h && !this.provider && this.providerLifecycle.mode === "degraded") {
if (l) await releaseReadGeneration();
if (await this.activateSearchFallback(this.providerLifecycle.reason)) refreshSearchIdentity();
}
const _ = refreshSearchIdentity();
const v = d && (_.status === "missing" || g && _.status === "mismatched" && _.owner === "openclaw" && _.versionOrder === "older");
const y = _.status === "valid" && this.provider && i.meta?.model === this.provider.model && i.meta.providerKey && i.meta.providerKey !== this.providerKey && g;
if (v || y) {
await releaseReadGeneration();
if (v) this.recordAutomaticRebuild();
await this.syncAdmitted({ reason: "search" }, { allowEmbeddingBootstrapFallback: true }).catch((e) => {
if (y || e instanceof WorkerTaskError && e.code === "overloaded" || readErrorName(e) === "DatabaseSearchCapabilityUnavailableError") throw e;
log$1.warn(`memory sync failed (search-identity-repair): ${formatErrorMessage(e)}`);
});
i = await readIndexState();
}
let b = v || y ? refreshSearchIdentity() : _;
if (b.status === "mismatched" && !h && await this.adoptPublishedFallbackProviderIfMatched(i)) b = refreshSearchIdentity();
const formatUpgradePendingKeywordOnly = (e) => e.status === "mismatched" && e.owner === "openclaw" && e.versionOrder === "older" && (e.chunkingVersionOnly === true || e.lexicalCompatible === true) && this.fts.enabled && this.fts.available;
if (b.status !== "valid") {
if (!formatUpgradePendingKeywordOnly(b)) return [];
log$1.warn("memory search: format upgrade rebuild is pending; serving the existing keyword index");
}
if (this.memoryWatchCapacityDegraded || this.memoryWatchUnavailable) this.dirty = true;
const x = (this.memoryWatchCapacityDegraded || this.memoryWatchUnavailable) && this.activeBackgroundSearchSyncs.size > 0;
if (g && !x && !formatUpgradePendingKeywordOnly(b) && this.dirty) {
const e = this.syncPublishedIndexInBackground({ reason: "search" }).catch((e) => {
log$1.warn(`memory sync failed (search): ${String(e)}`);
}).finally(() => {
this.activeBackgroundSearchSyncs.delete(e);
});
this.activeBackgroundSearchSyncs.add(e);
}
let S = b;
for (let e = 0; e < 2; e += 1) {
if (!m) i = await readIndexState();
const t = refreshSearchIdentity();
S = t;
if (t.status === "valid" || formatUpgradePendingKeywordOnly(t)) break;
await releaseReadGeneration();
if (h || e > 0 || t.status !== "mismatched" || !await this.adoptPublishedFallbackProviderIfMatched(i)) return [];
}
if (!a) return [];
const finalizeKeywords = (e) => this.finalizeKeywordOnlyResults({
results: e,
temporalDecay: s.temporalDecay,
maxResults: r,
minScore: n,
activeProjectKeys: t?.activeProjectKeys
});
const C = h || formatUpgradePendingKeywordOnly(S) || !this.provider || t?.lexicalOnly;
if (formatUpgradePendingKeywordOnly(S)) t?.onDebug?.({
backend: "builtin",
effectiveMode: "keyword-only"
});
const loadKeywordResults = async () => {
const n = p;
p = void 0;
const r = (C || s.enabled) && this.fts.enabled && this.fts.available ? await this.searchKeyword(e, c, u, o, n).catch((e) => this.handleRetrievalError("FTS keyword", e, t?.signal)) : [];
if (!C && t?.onPartialResults) {
const e = r.filter((e) => e.source === "memory");
if (e.length > 0) t.onPartialResults(await finalizeKeywords(e));
}
return r;
};
if (C || !this.provider) {
this.assertRequiredProviderAvailable("search");
if (!this.fts.enabled || !this.fts.available) {
log$1.warn("memory search: keyword-only search has no available FTS index");
return [];
}
return await finalizeKeywords(await loadKeywordResults());
}
let w = this.provider;
let T;
let E = [];
let D;
for (let n = false;; n = true) {
const r = this.providerRuntime;
T = {
model: w.model,
aliases: this.resolveProviderIndexIdentities().slice(1).map((e) => e.model)
};
const a = this.acquireProviderUse(w);
try {
E = await loadKeywordResults();
try {
D = await this.embedQueryWithRetry(e, t?.signal, w, r, t?.[MEMORY_SEARCH_DEADLINE_CONTROL]);
const n = i.meta?.vectorDims;
if (n !== void 0 && D.length !== n) throw createMemoryEmbeddingOperationError({
operation: "query",
providerId: w.id,
cause: /* @__PURE__ */ new Error(`query embedding has ${D.length} dimensions, but the memory index expects ${n}; rebuild with openclaw memory index --force --agent ${this.agentId}`)
});
break;
} catch (e) {
a();
if (t?.signal?.aborted) throw e;
if (n) {
this.markLocalEmbeddingProviderDegraded(e);
throw e;
}
t?.onPartialResults?.(null);
this.markLocalEmbeddingProviderDegraded(e);
const r = formatErrorMessage(e);
if (isMemoryEmbeddingOperationError(e) && await this.activateSearchFallback(r)) {
if (refreshSearchIdentity().status !== "valid" || !this.provider) return [];
w = this.provider;
} else if ((!this.provider || this.providerRequirement.mode !== "required") && this.fts.enabled && this.fts.available) {
this.assertRequiredProviderAvailable("search");
log$1.warn(`memory search: embeddings unavailable; using keyword-only results: ${r}`);
return await finalizeKeywords(E);
} else throw e;
}
} finally {
a();
}
}
const O = D.some((e) => e !== 0);
if (!O) log$1.warn(`memory search: query embedding from ${w.id} is all zeros; vector recall skipped; check the embedding service and retry`);
const k = O ? await this.searchVector(D, c, o, T, i, E.map((e) => e.id), u.excludedSessionPaths, t?.signal).catch((e) => ({
results: this.handleRetrievalError("vector", e, t?.signal),
candidates: []
})) : {
results: [],
candidates: []
};
const A = k.results;
if (!s.enabled || !this.fts.enabled || !this.fts.available) {
const e = prepareActiveProjectKeys(t?.activeProjectKeys);
const i = applyRetrievalRanking(A, e).filter((e) => e.score >= n);
return (await applyTemporalDecayToHybridResults({
results: i,
temporalDecay: s.temporalDecay,
workspaceDir: this.workspaceDir,
extraPaths: this.settings.extraPaths,
sessionSourceMtimes: this.loadSourceMtimes("sessions", A),
memorySourceMtimes: this.loadSourceMtimes("memory", A)
})).toSorted((e, t) => t.score - e.score || e.path.localeCompare(t.path) || e.startLine - t.startLine || e.endLine - t.endLine).slice(0, r);
}
const j = prepareExactPathMatcher(e);
const M = await mergeHybridResults({
vector: A.map((e) => ({
...e,
vectorScore: e.score,
exactPathSpecificity: j(e.path)
})),
keyword: E.map((e) => ({
...e,
rankingScore: e.score
})),
vectorWeight: s.vectorWeight,
textWeight: s.textWeight,
isNonTextMediaPath: (e) => classifyMemoryMultimodalPath(e, this.settings.multimodal) !== null,
mmr: s.mmr,
temporalDecay: s.temporalDecay,
activeProjectKeys: t?.activeProjectKeys,
workspaceDir: this.workspaceDir,
extraPaths: this.settings.extraPaths,
sessionSourceMtimes: this.loadSourceMtimes("sessions", [...E, ...A]),
memorySourceMtimes: this.loadSourceMtimes("memory", [...E, ...A])
});
return selectHybridSearchResults({
merged: M,
keyword: E,
vectorCandidates: k.candidates,
maxResults: r,
minScore: n
});
};
return await this.withManagerOperation(async () => {
try {
const e = await runSearch();
assertReadOwner();
return e;
} finally {
await releaseReadGeneration();
if (d.size > 0 && !f.readOnly) {
const e = this.withManagerOperation(async () => {
for (const e of d.values()) await this.deleteIndexedFile(e.path, "sessions", e.hash);
}).catch((e) => {
log$1.warn(`memory recall source cleanup failed: ${formatErrorMessage(e)}`);
}).finally(() => this.activeBackgroundSearchSyncs.delete(e));
this.activeBackgroundSearchSyncs.add(e);
}
}
});
}
async activateSearchFallback(e) {
return await this.activateFallbackProvider(e).catch((e) => {
log$1.warn(`memory search: failed to activate fallback provider: ${formatErrorMessage(e)}`);
return false;
});
}
hasIndexedContent(e) {
return e.hasIndexedChunks || this.fts.enabled && this.fts.available && e.hasFtsContent;
}
};
//#endregion
//#region extensions/memory-core/src/memory/manager.ts
const log = createSubsystemLogger("memory");
var MemoryIndexManager = class MemoryIndexManager extends MemorySearchOrchestration {
getEmbeddingProbeOwners() {
return this.managerRegistry.getProbeOwners(this);
}
get embeddingProbeCache() {
return this.managerRegistry.embeddingProbeCache;
}
static async get(e) {
const t = e.maintenanceSource;
const n = t?.memoryFiles ?? e.memoryFiles;
n?.assertCurrent();
const r = t?.cfg ?? e.cfg;
const i = t?.agentId ?? normalizeAgentId(e.agentId);
const a = normalizeMemoryIndexManagerPurpose(e.purpose);
const o = t?.managerRegistry ?? getMemoryIndexManagerRegistry();
return await o.acquire({
agentId: i,
purpose: a
}, { prepare: () => {
const s = t?.settings ?? resolveMemorySearchConfig(r, i);
if (!s) return null;
const c = t?.workspaceDir ?? resolveAgentWorkspaceDir(r, i);
const l = t?.providerRequirement ?? resolveMemoryEmbeddingProviderRequirement({
cfg: r,
agentId: i,
settings: s
});
const u = resolveMemoryIndexManagerCacheKey({
agentId: i,
workspaceDir: c,
settings: s,
providerRequirement: l,
purpose: a,
acquireLocalService: e.acquireLocalService
});
const d = captureMemoryDatabaseWriteOptions(i, s.store.databasePath, t?.publishedDatabase);
return {
key: u,
create: async () => {
let f;
let p;
try {
if (t && (!t.publishedDatabase.isOpen || a !== "maintenance")) throw new Error("Memory maintenance source connection is unavailable");
const m = resolveEffectiveMemorySearchSettings(s);
p = await MemoryIndexDatabase.openPublished({
agentId: i,
writeOptions: d,
readOnly: a === "status",
allowExtension: m.store.vector.enabled,
maintenanceSource: t?.publishedDatabase,
schema: {
cacheEnabled: m.cache.enabled,
ftsEnabled: m.query.hybrid.enabled,
ftsTokenizer: m.store.fts.tokenizer
}
});
f = new MemoryIndexManager({
managerRegistry: o,
cacheKey: u,
cfg: r,
agentId: i,
workspaceDir: c,
memoryFiles: n,
settings: s,
providerRequirement: l,
purpose: a,
acquireLocalService: e.acquireLocalService,
runInBackgroundContext: t?.backgroundRunner ?? e.runInBackgroundContext,
maintenanceSource: t,
databaseOptions: d,
publishedDatabase: p
});
o.track(f, u);
await f.memoryWatcherReady;
if (e.inspectSources) await f.inspectDiagnosticSourceState();
n?.assertCurrent();
return f;
} catch (e) {
try {
if (f) await f.close();
else if (p) try {
await p.closePublicationWorker();
} finally {
p.release();
}
} catch (t) {
throw new AggregateError([e, t], "Memory manager preparation cleanup failed", { cause: t });
}
throw e;
}
},
reuse: ({ closing: r, closed: i, publishedDatabase: a, memoryFiles: o, backgroundRunner: s }) => !r && !i && a.isOpen && o === n && s === (t?.backgroundRunner ?? e.runInBackgroundContext)
};
} });
}
constructor(e) {
super(e.maintenanceSource?.automaticRebuildNotice);
this.createProvider = (e, t) => this.managerRegistry.createProvider(this, e, t);
this.runInBackgroundContext = (e) => {
if (!this.backgroundRunner) throw new Error("Memory background work requires a plugin lifecycle owner");
return this.backgroundRunner(e);
};
this.closePromise = null;
this.publishedDatabaseReleased = false;
this.syncing = null;
this.syncingMemoryWatchGeneration = 0;
this.sessionSyncQueue = new MemoryTargetedSessionSyncQueue({
isClosed: () => this.closing || this.closed,
getSyncing: () => this.syncing,
sync: (e) => this.syncAdmitted(e, { queuedSessionOwner: true })
});
this.managerRegistry = e.managerRegistry;
const t = resolveEffectiveMemorySearchSettings(e.settings);
const n = e.databaseOptions.path;
this.cacheKey = e.cacheKey;
this.acquireLocalService = e.acquireLocalService;
this.backgroundRunner = e.runInBackgroundContext;
this.purpose = e.purpose;
this.cfg = e.cfg;
this.agentId = e.agentId;
this.workspaceDir = e.workspaceDir;
this.memoryFiles = e.memoryFiles;
this.settings = {
...t,
store: {
...t.store,
databasePath: n
}
};
this.providerRequirement = e.providerRequirement;
this.providerLifecycle = {
mode: "pending",
requestedProvider: this.settings.provider
};
const r = e.maintenanceSource;
const i = r?.embeddingProbeCache.get(r.cacheKey);
if (r?.embeddingBootstrapFailure && i?.result.ok === false && i.expireAtMs > Date.now()) {
this.embeddingBootstrapFailure = r.embeddingBootstrapFailure;
this.providerUnavailableReason = r.embeddingBootstrapFailure.reason;
this.embeddingProbeCache.set(this.cacheKey, i);
}
for (const e of t.sources) this.sources.add(e);
this.publishedDatabase = e.publishedDatabase;
this.providerKey = this.computeProviderKey();
this.cache = {
enabled: t.cache.enabled,
maxEntries: t.cache.maxEntries
};
this.vector.enabled = t.store.vector.enabled;
this.vector.extensionPath = t.store.vector.extensionPath;
const a = this.database.facts.meta;
if (a?.vectorDims) this.vector.dims = a.vectorDims;
this.indexIdentityState = this.resolveCurrentIndexIdentityState({
meta: a,
providerKeyKnown: false
});
this.indexIdentityDirty = this.indexIdentityState.status === "mismatched" || this.indexIdentityState.status === "missing" && this.sources.has("memory");
const o = this.purpose !== "default";
const s = new Set(this.database.facts.invalidatedSources);
this.memorySourceProvenanceRepairPending = this.sources.has("memory") && s.has("memory");
this.dirty = this.sources.has("memory") && (!o || !a) || this.memorySourceProvenanceRepairPending;
if (this.sources.has("sessions") && s.has("sessions")) {
this.sessionsDirty = true;
this.sessionsFullRetryDirty = true;
}
this.batch = this.resolveBatchConfig();
if (!o) {
markMemoryIndexingLive(this.agentId);
this.runInBackgroundContext(() => {
this.ensureWatcher();
this.ensureSessionListener();
this.runInBackgroundContext(() => this.ensureSessionStartupCatchup()).catch((e) => {
log.warn("memory session startup catch-up failed: " + String(e));
});
});
}
}
async sync(e) {
if (this.purpose === "status") throw new Error("Memory status managers are read-only");
if (this.closing || this.closed) return;
return await this.withManagerOperation(async () => {
if (hasTargetedSessionSyncParams(e) && this.sessionSyncQueue.hasPending) return await this.sessionSyncQueue.enqueue(e);
return await this.syncAdmitted(e);
});
}
async syncPublishedIndexInBackground(e) {
if (this.syncing || this.reindexProgress) return await this.syncBackground(e);
await this.syncOutcomes.track(() => runMemorySearchMaintenance({
reason: e.reason,
takeDirtyGeneration: () => this.takeSearchMaintenanceRequest(),
restoreDirtyGeneration: (e) => this.adoptReindexRetryState(e),
acquireManager: () => MemoryIndexManager.get({
cfg: this.cfg,
agentId: this.agentId,
purpose: "maintenance",
acquireLocalService: this.acquireLocalService,
maintenanceSource: this
})
}).catch((e) => {
if (this.providerRequirement.mode === "optional" && isMemoryEmbeddingOperationError(e)) this.markEmbeddingBootstrapFailure(e, { retainProvider: this.provider !== null });
throw e;
}));
}
async syncAdmitted(e, t) {
if (this.syncing) {
if (hasTargetedSessionSyncParams(e)) {
if (t?.queuedSessionOwner) {
await this.syncing.catch(() => void 0);
if (this.closing || this.closed) return;
return await this.syncAdmitted(e, t);
}
return this.sessionSyncQueue.enqueue(e);
}
try {
const n = this.syncingMemoryWatchGeneration;
await this.syncing;
if (!this.closing && !this.closed) {
const r = this.syncing;
if (r !== null && this.syncingMemoryWatchGeneration > n) return await r;
if (this.dirty && this.memoryWatchGeneration > n) return await this.syncAdmitted(e, t);
}
return;
} catch (n) {
if (t?.allowEmbeddingBootstrapFallback && this.providerRequirement.mode === "optional" && (!this.providerInitialized || this.embeddingBootstrapFailure !== void 0)) {
if (!this.embeddingBootstrapFailure) this.markEmbeddingBootstrapFailure(n);
return await this.syncAdmitted(e, t);
}
throw n;
}
}
this.syncingMemoryWatchGeneration = this.memoryWatchGeneration;
const run = async () => {
this.syncIsBackground = t?.background ?? false;
let n;
await this.publishedDatabase.withPublicationGeneration(async () => {
const r = this.embeddingBootstrapFailure !== void 0;
let i = this.embeddingBootstrapFailure !== void 0 && this.getCachedEmbeddingAvailability()?.ok === false;
if (!i) {
try {
await this.ensureProviderInitialized();
} catch (e) {
if (this.providerRequirement.mode !== "optional") throw e;
this.markEmbeddingBootstrapFailure(e);
i = true;
}
if (r && !this.provider) {
this.refreshEmbeddingBootstrapFailure(this.embeddingBootstrapFailure);
i = true;
}
}
const runGeneration = async (t) => {
const n = resolveUserPath(this.settings.store.databasePath);
const r = await waitForMemoryReindexLock(n, { waitForActive: true });
try {
try {
await this.publishedDatabase.refreshFacts();
} catch (t) {
if (e?.force && !hasTargetedSessionSyncParams(e)) {
this.markFailedFullReindexRetry({
memory: this.sources.has("memory"),
sessions: this.sources.has("sessions")
});
this.recordFullReindexFailure(this.provider !== null);
}
throw t;
}
await this.publishedDatabase.closePublicationWorker();
this.beginSyncProviderGeneration({ forceFtsOnly: t });
try {
return await this.runSync(e).then(async (e) => {
await this.publishedDatabase.closePublicationWorker();
return e;
}, async (e) => {
const [t] = await Promise.allSettled([this.publishedDatabase.closePublicationWorker()]);
if (t.status === "rejected") throw new AggregateError([e, t.reason], `${String(e)}; Memory sync cleanup failed: ${String(t.reason)}`, { cause: e });
throw e;
});
} finally {
this.endSyncProviderGeneration();
}
} finally {
await r.release();
}
};
try {
n = await runGeneration(i);
} catch (e) {
if (!(this.providerRequirement.mode === "optional" && isMemoryEmbeddingOperationError(e))) throw e;
const a = this.provider?.id ?? this.settings.provider;
this.markEmbeddingBootstrapFailure(e, {
retainProvider: this.provider !== null,
provider: a
});
if (!t?.allowEmbeddingBootstrapFallback && !r) throw e;
i = true;
n = await runGeneration(true);
}
if (r && !i && this.provider && this.refreshIndexIdentityDirty({ providerKeyKnown: true }).status === "valid" && await this.confirmEmbeddingBootstrapRecovery()) this.clearEmbeddingBootstrapFailureAfterRecovery();
});
return n;
};
this.syncing = this.syncOutcomes.track(run).finally(() => {
this.syncing = null;
});
return this.syncing;
}
/** @deprecated Use statusAsync. Final compatibility day: 2026-12-31. Removal in the first January 2027 stable release. */
status() {
warnPluginSdkDeprecation({
family: "memory-status",
method: "MemorySearchManager.status",
replacement: "MemorySearchManager.statusAsync"
});
if (this.closing || this.closed) throw new Error("Memory index manager is closed");
if (this.database.admission?.engine === "postgres") return this.publishedStatus();
return this.withPublishedDatabase(() => this.publishedStatus(collectMemoryStatusSnapshot(this.database.hasIndex ? this.db : void 0, resolveUserPath(this.settings.store.databasePath), this.statusQuery())));
}
statusAsync(e) {
return this.withManagerOperation(async () => {
if (e?.includeCounts === false) return this.publishedStatus();
const { agentId: t, path: n } = this.publishedDatabase.writeOptions ?? {};
if (!t || !n) throw new Error("Memory status requires its captured database target");
const r = await runMemoryStatus({
agentId: t,
databasePath: n
}, this.statusQuery());
return this.publishedStatus(r);
});
}
statusQuery() {
return {
sources: Array.from(this.sources),
cacheEnabled: this.cache.enabled,
includeStorage: this.sourceInspections.size > 0
};
}
publishedStatus(e) {
const t = e?.aggregate;
if (this.embeddingBootstrapFailure) this.refreshKeywordFallbackIndexIdentity();
else this.refreshIndexIdentityDirty({ providerKeyKnown: this.providerInitialized });
const n = resolveStatusProviderInfo({
provider: this.embeddingBootstrapFailure ? null : this.provider,
providerInitialized: this.embeddingBootstrapFailure ? true : this.providerInitialized,
requestedProvider: this.settings.provider,
resolveConfiguredModel: () => this.resolveConfiguredIndexIdentity()?.provider.model || this.settings.model
});
return {
backend: "builtin",
files: t?.files,
chunks: t?.chunks,
dirty: this.dirty || this.sessionsDirty || this.indexIdentityDirty || this.syncing !== null || this.activeBackgroundSearchSyncs.size > 0,
lastSyncError: this.syncOutcomes.lastError,
workspaceDir: this.workspaceDir,
dbPath: this.settings.store.databasePath,
storage: e?.storage,
provider: n.provider,
model: n.model,
requestedProvider: this.settings.provider,
sources: Array.from(this.sources),
extraPaths: this.settings.extraPaths,
sourceCounts: t?.sourceCounts.map((e) => Object.assign(e, this.sourceInspections.get(e.source) ?? {})),
cache: this.cache.enabled ? {
enabled: true,
entries: e?.cacheEntries,
maxEntries: this.cache.maxEntries
} : {
enabled: false,
maxEntries: this.cache.maxEntries
},
fts: {
enabled: this.fts.enabled,
available: this.fts.available,
error: this.fts.loadError
},
fallback: this.fallbackReason ? {
from: this.fallbackFrom ?? "local",
reason: this.fallbackReason
} : void 0,
vector: {
enabled: this.vector.enabled,
index: this.database.facts.vectorState,
storeAvailable: this.vector.available ?? void 0,
semanticAvailable: this.vector.semanticAvailable,
available: this.vector.semanticAvailable,
extensionPath: this.vector.extensionPath,
loadError: this.vector.loadError,
dims: this.vector.dims
},
batch: {
enabled: this.batch.enabled,
failures: this.batchFailure.count,
limit: this.batchFailureLimit,
wait: this.batch.wait,
concurrency: this.batch.concurrency,
pollIntervalMs: this.batch.pollIntervalMs,
timeoutMs: this.batch.timeoutMs,
lastError: this.batchFailure.lastError,
lastProvider: this.batchFailure.lastProvider
},
custom: {
watcher: this.memoryWatcherHealth,
llamaCppRuntime: getLocalEmbeddingRuntimeFacts(this.provider),
searchMode: n.searchMode,
providerState: this.providerLifecycle,
providerUnavailableReason: this.providerUnavailableReason,
indexIdentity: this.indexIdentityState,
automaticRebuildNotice: this.automaticRebuildNotice
}
};
}
async close() {
if (this.closePromise) return this.closePromise;
this.closePromise = this.withPublishedDatabase(() => this.publishedDatabaseReleased ? this.retryFailedClose() : this.closeOnce());
try {
await this.closePromise;
this.managerRegistry.deleteIfCurrent(this.cacheKey, this);
} catch (e) {
this.closePromise = null;
throw e;
}
}
async retryFailedClose() {
const e = [];
await this.closeWatchResources().catch((t) => e.push(t));
await this.discardReindex().catch((t) => e.push(t));
const t = await this.drainPendingProviderRetirements();
if (this.providersPendingRetirement.size > 0) e.push(toErrorObject(t.at(-1), "Embedding provider retirement failed"));
if (!this.publishedDatabaseReleased) try {
await this.publishedDatabase.closePublicationWorker();
this.publishedDatabase.release();
this.publishedDatabaseReleased = true;
} catch (t) {
e.push(t);
}
if (e.length === 1) throw e[0];
if (e.length > 1) throw new AggregateError(e, "Memory manager cleanup failed");
}
async closeOnce() {
this.closing = true;
this.sessionSyncQueue.clear();
await this.awaitManagerIdle();
this.closed = true;
const e = this.providerInitPromise;
const t = this.fallbackProviderInitPromise;
const reportPendingWorkError = (e) => {
log.warn(`memory close: pending manager work failed: ${formatErrorMessage(e)}`);
};
await e?.catch(reportPendingWorkError);
await t?.catch(reportPendingWorkError);
await this.syncing?.catch(reportPendingWorkError);
await this.retryFailedClose();
}
};
const managerRegistryStore = createPluginRuntimeStore({
key: "memory-core:manager-registry",
errorMessage: "Memory manager registry is not initialized"
});
function getMemoryIndexManagerRegistry() {
let e = managerRegistryStore.tryGetRuntime();
if (!e) {
e = new MemoryManagerRegistry(getMemoryManagerLifecycle());
managerRegistryStore.setRuntime(e);
}
return e;
}
//#endregion
//#region extensions/memory-core/src/memory/manager-runtime.ts
async function closeAllMemoryIndexManagers() {
const e = getMemoryIndexManagerRegistry();
e.embeddingProbeCache.clear();
await e.closeAll();
}
async function closeMemoryIndexManagersForAgent(e) {
const t = getMemoryIndexManagerRegistry();
for (const n of ["default", "maintenance"]) await t.closeForAgent({
...e,
purpose: n
});
}
//#endregion
export { MemoryIndexManager, closeAllMemoryIndexManagers, closeMemoryIndexManagersForAgent };