@openclaw/memory-lancedb 2026.9.6 → 2026.9.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3,12 +3,14 @@ import { dropMediaNoteLines } from "./memory-capture-sanitization.js";
3
3
  import { cleanMemorySearchResults, formatRelevantMemoriesContext, normalizeRecallQuery } from "./memory-policy.js";
4
4
  import { startMemoryRecall } from "./recall-service.js";
5
5
  import { formatErrorMessage } from "openclaw/plugin-sdk/error-runtime";
6
+ import { isIncognitoSessionKey } from "openclaw/plugin-sdk/routing";
6
7
  //#region extensions/memory-lancedb/auto-recall.ts
7
8
  const AUTO_RECALL_TIMEOUT_MS = 15e3;
8
9
  const AUTO_RECALL_OVERFETCH_LIMIT = 10;
9
10
  const AUTO_RECALL_RESULT_CAP = 3;
10
11
  function createAutoRecallHook(params) {
11
12
  return async (event, ctx) => {
13
+ if (isIncognitoSessionKey(ctx.sessionKey)) return;
12
14
  const currentCfg = params.resolveCurrentConfig();
13
15
  const recallMaxChars = currentCfg.recallMaxChars;
14
16
  if (!currentCfg.autoRecall) return;
package/dist/config.js CHANGED
@@ -1,5 +1,6 @@
1
+ import { isRecord } from "openclaw/plugin-sdk/string-coerce-runtime";
1
2
  import { join } from "node:path";
2
- import { parseFiniteNumber } from "openclaw/plugin-sdk/number-runtime";
3
+ import { parseFiniteNumber, resolveOptionalIntegerOption } from "openclaw/plugin-sdk/number-runtime";
3
4
  import { homedir } from "node:os";
4
5
  //#region extensions/memory-lancedb/config.ts
5
6
  const MEMORY_CATEGORIES = [
@@ -34,9 +35,9 @@ function vectorDimsForModel(model) {
34
35
  if (!dims) throw new Error(`Unsupported embedding model: ${model}`);
35
36
  return dims;
36
37
  }
37
- function resolveEnvVars(value) {
38
+ function resolveEnvVars(value, env = process.env) {
38
39
  return value.replace(/\$\{([^}]+)\}/g, (_, envVar) => {
39
- const envValue = process.env[envVar];
40
+ const envValue = env[envVar];
40
41
  if (!envValue) throw new Error(`Environment variable ${envVar} is not set`);
41
42
  return envValue;
42
43
  });
@@ -46,13 +47,8 @@ function resolveEmbeddingModel(embedding, dimensions) {
46
47
  if (dimensions === void 0) vectorDimsForModel(model);
47
48
  return model;
48
49
  }
49
- function resolveFiniteIntegerConfig(value) {
50
- if (typeof value !== "number") return;
51
- const parsed = parseFiniteNumber(value);
52
- return parsed === void 0 ? void 0 : Math.floor(parsed);
53
- }
54
50
  function resolveBoundedIntegerConfig(params) {
55
- const resolved = resolveFiniteIntegerConfig(params.value) ?? params.fallback;
51
+ const resolved = resolveOptionalIntegerOption(params.value) ?? params.fallback;
56
52
  if (resolved < params.min || resolved > params.max) throw new Error(`${params.label} must be between ${params.min} and ${params.max}`);
57
53
  return resolved;
58
54
  }
@@ -63,7 +59,7 @@ function resolveEmbeddingDimensions(embedding) {
63
59
  return dimensions;
64
60
  }
65
61
  const memoryConfigSchema = { parse(value) {
66
- if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("memory config required");
62
+ if (!isRecord(value)) throw new Error("memory config required");
67
63
  const cfg = value;
68
64
  assertAllowedKeys(cfg, [
69
65
  "embedding",
@@ -77,7 +73,7 @@ const memoryConfigSchema = { parse(value) {
77
73
  "storageOptions"
78
74
  ], "memory config");
79
75
  const embedding = cfg.embedding;
80
- if (!embedding || typeof embedding !== "object" || Array.isArray(embedding)) throw new Error("embedding config required");
76
+ if (!isRecord(embedding)) throw new Error("embedding config required");
81
77
  assertAllowedKeys(embedding, [...EMBEDDING_CONFIG_KEYS], "embedding config");
82
78
  if (Object.keys(embedding).length === 0) throw new Error("embedding config must include at least one setting");
83
79
  const dimensions = resolveEmbeddingDimensions(embedding);
@@ -110,13 +106,12 @@ const memoryConfigSchema = { parse(value) {
110
106
  });
111
107
  if (customTriggers.length > 50) throw new Error("customTriggers must include at most 50 entries");
112
108
  }
113
- const dreaming = cfg.dreaming === void 0 ? void 0 : cfg.dreaming && typeof cfg.dreaming === "object" && !Array.isArray(cfg.dreaming) ? cfg.dreaming : (() => {
114
- throw new Error("dreaming config must be an object");
115
- })();
109
+ const dreaming = cfg.dreaming;
110
+ if (dreaming !== void 0 && !isRecord(dreaming)) throw new Error("dreaming config must be an object");
116
111
  let storageOptions;
117
112
  const storageOpts = cfg.storageOptions;
118
113
  if (storageOpts !== void 0 && storageOpts !== null) {
119
- if (!storageOpts || typeof storageOpts !== "object" || Array.isArray(storageOpts)) throw new Error("storageOptions must be an object");
114
+ if (!isRecord(storageOpts)) throw new Error("storageOptions must be an object");
120
115
  storageOptions = {};
121
116
  for (const [key, valueLocal] of Object.entries(storageOpts)) {
122
117
  if (typeof valueLocal !== "string") throw new Error(`storageOptions.${key} must be a string`);
@@ -142,4 +137,4 @@ const memoryConfigSchema = { parse(value) {
142
137
  };
143
138
  } };
144
139
  //#endregion
145
- export { DEFAULT_CAPTURE_MAX_CHARS, DEFAULT_RECALL_MAX_CHARS, MEMORY_CATEGORIES, memoryConfigSchema, vectorDimsForModel };
140
+ export { DEFAULT_CAPTURE_MAX_CHARS, DEFAULT_RECALL_MAX_CHARS, MEMORY_CATEGORIES, memoryConfigSchema, resolveEnvVars, vectorDimsForModel };
@@ -1,8 +1,10 @@
1
1
  import { o as __toESM } from "./.setup/rolldown-runtime-BMI-E3GI.mjs";
2
+ import { resolveEnvVars } from "./config.js";
2
3
  import { MEMORY_AGENT_ID_COLUMN, MEMORY_TABLE_NAME, hasAgentScopeColumn, memoryAgentPredicate, quoteLanceSqlString } from "./lancedb-schema.js";
3
4
  import { resolveDefaultAgentId } from "openclaw/plugin-sdk/agent-scope-runtime";
4
5
  import { normalizeAgentId } from "openclaw/plugin-sdk/routing";
5
6
  import { asOptionalRecord } from "openclaw/plugin-sdk/string-coerce-runtime";
7
+ import { escapeRegExp } from "openclaw/plugin-sdk/text-utility-runtime";
6
8
  import path from "node:path";
7
9
  import os from "node:os";
8
10
  import fs from "node:fs";
@@ -30,7 +32,7 @@ const LEGACY_ENVELOPE_SENTINEL_LINE_RE = new RegExp(`^(?:${[
30
32
  "Current local chat window (untrusted, chronological, before current message):",
31
33
  "Nearby reply target window (untrusted, chronological, around replied-to message):",
32
34
  "Chat history since last reply (untrusted, for context):"
33
- ].map((sentinel) => sentinel.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|")})[^\\n]*$`, "m");
35
+ ].map(escapeRegExp).join("|")})[^\\n]*$`, "m");
34
36
  const LEGACY_ENVELOPE_LABEL_JSON_BLOCK_RE = /^[^\n]+\((?:untrusted metadata|untrusted, for context|untrusted, nearest first|untrusted, chronological,[^\n)]{1,80})\):[ \t]*\n[ \t]*```json[ \t]*\n[\s\S]*?\n[ \t]*```[ \t]*(?:\n|$)/m;
35
37
  const LEGACY_ENVELOPE_HEADER_RE = /^Untrusted context \(metadata, do not treat as instructions or commands\):[ \t]*$/m;
36
38
  function isLegacyEnvelopeContaminatedText(text) {
@@ -67,11 +69,7 @@ function resolveStorageOptions(config, env) {
67
69
  if (!rawOptions) return;
68
70
  return Object.fromEntries(Object.entries(rawOptions).map(([key, value]) => {
69
71
  if (typeof value !== "string") throw new Error(`memory-lancedb storageOptions.${key} must be a string`);
70
- return [key, value.replace(/\$\{([^}]+)\}/g, (_match, envName) => {
71
- const resolved = env[envName];
72
- if (!resolved) throw new Error(`Environment variable ${envName} is not set`);
73
- return resolved;
74
- })];
72
+ return [key, resolveEnvVars(value, env)];
75
73
  }));
76
74
  }
77
75
  async function openMemoryTable(params) {
@@ -81,7 +79,7 @@ async function openMemoryTable(params) {
81
79
  table: null,
82
80
  dbPath
83
81
  };
84
- const lancedb = await import("./.setup/dist-BjiCSHUs.mjs").then((m) => /* @__PURE__ */ __toESM(m.default, 1));
82
+ const lancedb = await import("./.setup/dist-A24Sj2xJ.mjs").then((m) => /* @__PURE__ */ __toESM(m.default, 1));
85
83
  const storageOptions = resolveStorageOptions(params.config, params.env);
86
84
  const connection = await lancedb.connect(dbPath, storageOptions ? { storageOptions } : {});
87
85
  return {
@@ -90,31 +88,35 @@ async function openMemoryTable(params) {
90
88
  dbPath
91
89
  };
92
90
  }
91
+ async function withMemoryTable(params, run) {
92
+ const opened = await openMemoryTable(params);
93
+ try {
94
+ return await run(opened);
95
+ } finally {
96
+ opened.table?.close();
97
+ opened.connection?.close();
98
+ }
99
+ }
93
100
  function createMemoryLanceDbStateMigrations(pluginRoot = DEFAULT_PLUGIN_ROOT) {
94
101
  return [{
95
102
  id: "memory-lancedb-agent-scope",
96
103
  label: "Memory LanceDB per-agent isolation",
97
104
  async detectLegacyState(params) {
98
- const opened = await openMemoryTable({
105
+ return await withMemoryTable({
99
106
  ...params,
100
107
  pluginRoot
101
- });
102
- try {
108
+ }, async (opened) => {
103
109
  if (!opened.table || hasAgentScopeColumn(await opened.table.schema())) return null;
104
110
  const owner = resolveLegacyMemoryOwner(params.config);
105
111
  const count = await opened.table.countRows();
106
112
  return { preview: [`- Memory LanceDB: assign ${count} legacy ${count === 1 ? "row" : "rows"} at ${opened.dbPath} to ${owner.label} agent ${owner.agentId}`] };
107
- } finally {
108
- opened.table?.close();
109
- opened.connection?.close();
110
- }
113
+ });
111
114
  },
112
115
  async migrateLegacyState(params) {
113
- const opened = await openMemoryTable({
116
+ return await withMemoryTable({
114
117
  ...params,
115
118
  pluginRoot
116
- });
117
- try {
119
+ }, async (opened) => {
118
120
  if (!opened.table || hasAgentScopeColumn(await opened.table.schema())) return {
119
121
  changes: [],
120
122
  warnings: []
@@ -130,36 +132,28 @@ function createMemoryLanceDbStateMigrations(pluginRoot = DEFAULT_PLUGIN_ROOT) {
130
132
  changes: [`Assigned ${rowCount} legacy Memory LanceDB ${rowCount === 1 ? "row" : "rows"} to ${owner.label} agent ${owner.agentId}`],
131
133
  warnings: []
132
134
  };
133
- } finally {
134
- opened.table?.close();
135
- opened.connection?.close();
136
- }
135
+ });
137
136
  }
138
137
  }, {
139
138
  id: "memory-lancedb-legacy-envelope-rows",
140
139
  label: "Memory LanceDB legacy envelope contamination",
141
140
  doctorOnly: true,
142
141
  async detectLegacyState(params) {
143
- const opened = await openMemoryTable({
142
+ return await withMemoryTable({
144
143
  ...params,
145
144
  pluginRoot
146
- });
147
- try {
145
+ }, async (opened) => {
148
146
  if (!opened.table) return null;
149
147
  const contaminatedIds = await scanLegacyEnvelopeRowIds(opened.table);
150
148
  if (contaminatedIds.length === 0) return null;
151
149
  return { preview: [`- Memory LanceDB: delete ${contaminatedIds.length} memory ${contaminatedIds.length === 1 ? "row" : "rows"} contaminated with legacy envelope metadata at ${opened.dbPath}`] };
152
- } finally {
153
- opened.table?.close();
154
- opened.connection?.close();
155
- }
150
+ });
156
151
  },
157
152
  async migrateLegacyState(params) {
158
- const opened = await openMemoryTable({
153
+ return await withMemoryTable({
159
154
  ...params,
160
155
  pluginRoot
161
- });
162
- try {
156
+ }, async (opened) => {
163
157
  if (!opened.table) return {
164
158
  changes: [],
165
159
  warnings: []
@@ -178,10 +172,7 @@ function createMemoryLanceDbStateMigrations(pluginRoot = DEFAULT_PLUGIN_ROOT) {
178
172
  changes: [`Deleted ${contaminatedIds.length} Memory LanceDB ${contaminatedIds.length === 1 ? "row" : "rows"} contaminated with legacy envelope metadata`],
179
173
  warnings: []
180
174
  };
181
- } finally {
182
- opened.table?.close();
183
- opened.connection?.close();
184
- }
175
+ });
185
176
  }
186
177
  }];
187
178
  }
@@ -181,31 +181,28 @@ var ProviderAdapterEmbeddings = class {
181
181
  async createProvider(config, agentDir, embedding) {
182
182
  return await runProviderAdapterLifecycle(async () => {
183
183
  await drainRetainedProviders();
184
- return await this.createProviderAfterRetirement(config, agentDir, embedding);
184
+ const providerId = embedding.provider;
185
+ const { getMemoryEmbeddingProvider, registerRuntimeAuthProfileStoreMutationListener } = await loadMemoryEmbeddingProviderModule();
186
+ if (!this.closed && !this.unregisterAuthMutationListener) this.unregisterAuthMutationListener = registerRuntimeAuthProfileStoreMutationListener((event) => this.invalidateProvidersForAuthMutation(event));
187
+ const adapter = getMemoryEmbeddingProvider(providerId, config);
188
+ if (!adapter) throw new Error(`Unknown memory embedding provider: ${providerId}`);
189
+ const remote = embedding.apiKey || embedding.baseUrl ? {
190
+ ...embedding.apiKey ? { apiKey: embedding.apiKey } : {},
191
+ ...embedding.baseUrl ? { baseUrl: embedding.baseUrl } : {}
192
+ } : void 0;
193
+ const result = await adapter.create({
194
+ config,
195
+ agentDir,
196
+ provider: providerId,
197
+ fallback: "none",
198
+ model: embedding.model,
199
+ ...remote ? { remote } : {},
200
+ ...typeof embedding.dimensions === "number" ? { dimensions: embedding.dimensions } : {}
201
+ });
202
+ if (!result.provider) throw new Error(`Memory embedding provider ${providerId} is unavailable.`);
203
+ return result.provider;
185
204
  });
186
205
  }
187
- async createProviderAfterRetirement(config, agentDir, embedding) {
188
- const providerId = embedding.provider;
189
- const { getMemoryEmbeddingProvider, registerRuntimeAuthProfileStoreMutationListener } = await loadMemoryEmbeddingProviderModule();
190
- if (!this.closed && !this.unregisterAuthMutationListener) this.unregisterAuthMutationListener = registerRuntimeAuthProfileStoreMutationListener((event) => this.invalidateProvidersForAuthMutation(event));
191
- const adapter = getMemoryEmbeddingProvider(providerId, config);
192
- if (!adapter) throw new Error(`Unknown memory embedding provider: ${providerId}`);
193
- const remote = embedding.apiKey || embedding.baseUrl ? {
194
- ...embedding.apiKey ? { apiKey: embedding.apiKey } : {},
195
- ...embedding.baseUrl ? { baseUrl: embedding.baseUrl } : {}
196
- } : void 0;
197
- const result = await adapter.create({
198
- config,
199
- agentDir,
200
- provider: providerId,
201
- fallback: "none",
202
- model: embedding.model,
203
- ...remote ? { remote } : {},
204
- ...typeof embedding.dimensions === "number" ? { dimensions: embedding.dimensions } : {}
205
- });
206
- if (!result.provider) throw new Error(`Memory embedding provider ${providerId} is unavailable.`);
207
- return result.provider;
208
- }
209
206
  async embed(agentId, text, embeddingConfig, timeoutMs) {
210
207
  if (this.closed) throw new Error("memory-lancedb embeddings are closed");
211
208
  const embedding = { ...embeddingConfig };
package/dist/index.js CHANGED
@@ -1,4 +1,3 @@
1
- import { definePluginEntry } from "./api.js";
2
1
  import { MemoryRecallEmbeddingError, buildMemoryRecallUnavailableResult, createEmbeddings, isMemoryRecallTimeoutError, normalizeEmbeddingVector } from "./embeddings.js";
3
2
  import { looksLikeEnvelopeSludge, sanitizeForMemoryCapture } from "./memory-capture-sanitization.js";
4
3
  import { MEMORY_CATEGORIES, memoryConfigSchema, vectorDimsForModel } from "./config.js";
@@ -13,6 +12,7 @@ import { enqueueKeyedTask } from "openclaw/plugin-sdk/keyed-async-queue";
13
12
  import { createLazyRuntimeModule } from "openclaw/plugin-sdk/lazy-runtime";
14
13
  import { readFiniteNumberParam, readPositiveIntegerParam } from "openclaw/plugin-sdk/param-readers";
15
14
  import { resolveLivePluginConfigObject } from "openclaw/plugin-sdk/plugin-config-runtime";
15
+ import { definePluginEntry } from "openclaw/plugin-sdk/plugin-entry";
16
16
  import { isIncognitoSessionKey, normalizeAgentId } from "openclaw/plugin-sdk/routing";
17
17
  import { asOptionalRecord } from "openclaw/plugin-sdk/string-coerce-runtime";
18
18
  import { truncateUtf16Safe } from "openclaw/plugin-sdk/text-utility-runtime";
@@ -316,7 +316,10 @@ var memory_lancedb_default = definePluginEntry({
316
316
  }
317
317
  };
318
318
  }, { name: "memory_forget" });
319
- registerMemoryCli(api, db, embeddings, resolveCliAgentId, resolveCurrentHookConfig);
319
+ registerMemoryCli(api, db, embeddings, resolveCliAgentId, resolveCurrentHookConfig, {
320
+ dbPath: resolvedDbPath,
321
+ storageOptions: cfg.storageOptions
322
+ });
320
323
  api.on("before_prompt_build", createAutoRecallHook({
321
324
  logger: api.logger,
322
325
  db,
@@ -7,9 +7,6 @@ function buildLoadFailureMessage(error) {
7
7
  String(error)
8
8
  ].join(" ");
9
9
  }
10
- function isUnsupportedNativePlatform(params) {
11
- return params.platform === "darwin" && params.arch === "x64";
12
- }
13
10
  function buildUnsupportedNativePlatformMessage(params) {
14
11
  return [
15
12
  `memory-lancedb: LanceDB runtime is unavailable on ${params.platform}-${params.arch}.`,
@@ -21,12 +18,9 @@ const platform = process.platform;
21
18
  const arch = process.arch;
22
19
  let loadPromise = null;
23
20
  async function loadLanceDbModule() {
24
- if (!loadPromise) loadPromise = import("./.setup/dist-BjiCSHUs.mjs").then((m) => /* @__PURE__ */ __toESM(m.default, 1)).catch((error) => {
21
+ if (!loadPromise) loadPromise = import("./.setup/dist-A24Sj2xJ.mjs").then((m) => /* @__PURE__ */ __toESM(m.default, 1)).catch((error) => {
25
22
  loadPromise = null;
26
- if (isUnsupportedNativePlatform({
27
- platform,
28
- arch
29
- })) throw new Error(buildUnsupportedNativePlatformMessage({
23
+ if (platform === "darwin" && arch === "x64") throw new Error(buildUnsupportedNativePlatformMessage({
30
24
  platform,
31
25
  arch
32
26
  }), { cause: error });
@@ -1,9 +1,10 @@
1
1
  import { loadLanceDbModule } from "./lancedb-runtime.js";
2
2
  import { MEMORY_TABLE_NAME, hasAgentScopeColumn, legacyMemorySchemaError, memoryAgentPredicate, quoteLanceSqlString } from "./lancedb-schema.js";
3
+ import { createRequire } from "node:module";
3
4
  import { randomUUID } from "node:crypto";
4
5
  import { setTimeout } from "node:timers/promises";
5
- import { Field, FixedSizeList, Float32, Float64, Schema, Utf8 } from "apache-arrow";
6
6
  //#region extensions/memory-lancedb/lancedb-store.ts
7
+ const { Field, FixedSizeList, Float32, Float64, Schema, Utf8 } = createRequire(import.meta.url)("apache-arrow");
7
8
  const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
8
9
  const TABLE_INITIALIZATION_ATTEMPTS = 3;
9
10
  const MEMORY_QUERY_COLUMNS = [
@@ -119,16 +120,10 @@ var MemoryDB = class {
119
120
  }).filter((result) => result.score >= minScore);
120
121
  }
121
122
  async list(agentId, limit, options = {}) {
122
- await this.ensureInitialized();
123
- let query = this.table.query().where(memoryAgentPredicate(agentId)).select([
124
- "id",
125
- "text",
126
- "importance",
127
- "category",
128
- "createdAt"
129
- ]);
130
- if (!options.orderByCreatedAt && limit !== void 0) query = query.limit(limit);
131
- const entries = (await query.toArray()).map((row) => ({
123
+ const entries = (await this.query(agentId, {
124
+ columns: [...MEMORY_QUERY_COLUMNS],
125
+ limit: options.orderByCreatedAt ? void 0 : limit
126
+ })).map((row) => ({
132
127
  id: row.id,
133
128
  text: row.text,
134
129
  importance: row.importance,
@@ -154,10 +149,6 @@ var MemoryDB = class {
154
149
  });
155
150
  return (await this.table.delete(predicate)).numDeletedRows > 0;
156
151
  }
157
- async count(agentId) {
158
- await this.ensureInitialized();
159
- return await this.table.countRows(memoryAgentPredicate(agentId));
160
- }
161
152
  close() {
162
153
  this.table?.close();
163
154
  this.db?.close();
@@ -1,29 +1,16 @@
1
- import { truncateUtf16Safe } from "openclaw/plugin-sdk/text-utility-runtime";
1
+ import { escapeRegExp, truncateUtf16Safe } from "openclaw/plugin-sdk/text-utility-runtime";
2
2
  import { BUNDLED_CHAT_CHANNEL_ENVELOPE_PREFIXES } from "openclaw/plugin-sdk/chat-channel-ids";
3
3
  import { expectDefined } from "openclaw/plugin-sdk/expect-runtime";
4
4
  import { MESSAGE_TOOL_DELIVERY_HINTS } from "openclaw/plugin-sdk/message-tool-delivery-hints";
5
5
  //#region extensions/memory-lancedb/memory-capture-sanitization.ts
6
6
  const MEDIA_NOTE_HEADER = /^\[media attached(?: \d+\/\d+)?: /;
7
- function stripMediaNoteLine(line) {
8
- return MEDIA_NOTE_HEADER.test(line) && line.endsWith("]") ? null : line;
9
- }
10
7
  function dropMediaNoteLines(text) {
11
- return text.split("\n").map(stripMediaNoteLine).filter((line) => line !== null).join("\n");
8
+ return text.split("\n").filter((line) => !(MEDIA_NOTE_HEADER.test(line) && line.endsWith("]"))).join("\n");
12
9
  }
13
- /**
14
- * Provenance marker appended to every OpenClaw-injected inbound context header
15
- * by `buildInboundUserContextPrefix`. `sanitizeForMemoryCapture` and
16
- * `looksLikeEnvelopeSludge` key on this marker rather than on label text, so
17
- * detection is label-agnostic (arbitrary plugin `ChannelStructuredContext`
18
- * labels are covered) and never collides with a user's own `<heading>:` + JSON.
19
- * The marker glyph is duplicated inline in the regexes below because extensions
20
- * must not import core internals; keep byte-identical with
21
- * `src/auto-reply/reply/inbound-context-marker.ts`.
22
- */
23
10
  const MARKER_HEADER_LINE_RE = /^[^\n]*⟦openclaw:ctx⟧[ \t]*$/m;
24
11
  const MARKER_JSON_BLOCK_RE = /^[^\n]*⟦openclaw:ctx⟧[ \t]*\n[ \t]*```json[ \t]*\n[\s\S]*?\n[ \t]*```[ \t]*\n?/gm;
25
12
  const LEADING_CHRONOLOGICAL_MARKER_HEADER_RE = /^\s*[^\n]*chronological[^\n]*⟦openclaw:ctx⟧[ \t]*(?:\n|$)/;
26
- const MESSAGE_TOOL_DELIVERY_HINT_RE = new RegExp(`^\\s*(?:${MESSAGE_TOOL_DELIVERY_HINTS.map((hint) => hint.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|")})\\s*$`, "m");
13
+ const MESSAGE_TOOL_DELIVERY_HINT_RE = new RegExp(`^\\s*(?:${MESSAGE_TOOL_DELIVERY_HINTS.map(escapeRegExp).join("|")})\\s*$`, "m");
27
14
  const HISTORY_CONTEXT_MARKER = "[Chat messages since your last reply - for context]";
28
15
  const CURRENT_MESSAGE_MARKER = "[Current message - respond to this]";
29
16
  const HISTORY_CONTEXT_MARKERS = [
@@ -42,83 +29,10 @@ const LEADING_CURRENT_MESSAGE_CONTEXT_RE = /^\s*Current message:[ \t]*(?:\n|$)/;
42
29
  const LEADING_CURRENT_MESSAGE_REPLY_LINE_RE = /^\s*\[Replying to:[^\n]{0,1000}\]\s*\n/;
43
30
  const LEADING_CURRENT_MESSAGE_ID_SENDER_RE = /^#\d+\s+[^\n:]{1,100}:\s*/;
44
31
  const CONTEXT_HEADER_RE = /^Context:[ \t]*⟦openclaw:ctx⟧[ \t]*$/m;
45
- /**
46
- * Matches JSON blobs that look like OpenClaw transport envelope metadata.
47
- * Orthogonal to the header marker: it catches a bare envelope payload by its
48
- * compound keys even when no marker header precedes it (e.g. a fragment that
49
- * leaked outside its ```json fence). Core's `formatContextJsonBlock` emits
50
- * compact single-line JSON; the optional-newline branch also catches legacy
51
- * pretty-printed blocks. Key list mirrors envelope identifiers used by
52
- * `buildInboundUserContextPrefix` and stays narrow to avoid false-positives on
53
- * legitimate user JSON with bare keys like "conversation" or "sender".
54
- */
55
32
  const ENVELOPE_JSON_LINE_RE = /^\s*\{\s*(?:\n\s*)?"(?:chat_id|message_id|reply_to_id|sender_id|conversation_label|conversation_info|sender_name|channel_id|channel_type|group_subject|group_channel|group_space|topic_id|thread_label)"\s*:/m;
56
- /**
57
- * Leading bracketed envelope header injected by `formatAgentEnvelope` /
58
- * `formatInboundEnvelope` (src/auto-reply/envelope.ts). Real shape, with parts
59
- * joined by spaces inside a single `[...]`:
60
- *
61
- * `[<channel> <from> +<elapsed>? <host>? <ip>? <Wkd YYYY-MM-DD HH:MM TZ>?] <body>`
62
- *
63
- * Examples:
64
- * `[Telegram Alice +5m] I prefer dark mode`
65
- * `[Telegram Group id:123 Alice +5m Mon 2026-05-17 14:30 EDT] Alice: text`
66
- * `[Discord #general user +0s Mon 2026-05-17T14:30Z] text`
67
- *
68
- * Detection keys on the load-bearing parts that mark this header as an
69
- * envelope (rather than arbitrary user-typed `[brackets]`): an elapsed marker
70
- * `+<n><unit>` produced by `formatTimeAgo({suffix:false})` (units: s/m/h/d, or
71
- * the literal `just now` fallback), or a weekday + ISO date pair produced by
72
- * `formatEnvelopeTimestamp`. Either marker is unique enough that quoting
73
- * `[5m]` or `[Mon 2026-05-17]` mid-sentence will not look like an envelope
74
- * prefix because the regex is anchored to start-of-string and requires the
75
- * marker to live inside the leading bracket followed by `]<space>`.
76
- *
77
- * Capture group 1 is the inside-bracket text, used by the sender-prefix
78
- * gating logic in `sanitizeForMemoryCapture` to scope which body labels we
79
- * are willing to strip. Header part length is capped at 300 chars to avoid
80
- * catastrophic backtracking on pathological inputs; real envelopes are well
81
- * under that.
82
- */
83
33
  const INBOUND_ENVELOPE_PREFIX_RE = /^\[([^\]\n]{0,300}?(?:\s\+(?:\d+[smhdwy]|just now)\b|\s[A-Za-z]{3}\s\d{4}-\d{2}-\d{2})[^\]\n]{0,200})\]\s/;
84
- /**
85
- * Marker-free leading envelope header. The elapsed/date marker regex above
86
- * misses envelopes where `formatAgentEnvelope` drops every optional marker.
87
- * Because channel labels can also be ordinary words, callers only accept this
88
- * match after `matchKnownChannelMarkerFreeEnvelopePrefix` finds a stronger
89
- * group/thread or body-sender signal.
90
- *
91
- * Anchoring on a known bundled/official channel prefix from
92
- * `BUNDLED_CHAT_CHANNEL_ENVELOPE_PREFIXES` keeps the detector and formatter in
93
- * sync across callers that pass either ids or display labels like `Google Chat`.
94
- * Case insensitive because the formatter does not lowercase `params.channel`
95
- * itself; production paths feed mixed ids and labels.
96
- *
97
- * From-label must be at least one non-whitespace token so user prose like
98
- * `[note]` or `[telegram] ...` (no following label) is not mistaken for an
99
- * envelope. Capture group 1 is the inside-bracket text (channel + from-label
100
- * and any remaining header parts), used by the sender-prefix gating logic in
101
- * `sanitizeForMemoryCapture`. Header part length is capped at 300 chars to
102
- * match the marker-aware regex above and avoid catastrophic backtracking.
103
- *
104
- * Guarded against an empty `BUNDLED_CHAT_CHANNEL_ENVELOPE_PREFIXES` so the
105
- * alternation never degenerates into `(?:)` (which would match the empty string
106
- * and flag every `[...]` prefix as an envelope). When the bundled list is empty the
107
- * known-channel detector is disabled and only the marker-aware regex above
108
- * applies.
109
- */
110
- const ENVELOPE_KNOWN_CHANNEL_PATTERN = BUNDLED_CHAT_CHANNEL_ENVELOPE_PREFIXES.map((prefix) => prefix.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|");
34
+ const ENVELOPE_KNOWN_CHANNEL_PATTERN = BUNDLED_CHAT_CHANNEL_ENVELOPE_PREFIXES.map(escapeRegExp).join("|");
111
35
  const INBOUND_ENVELOPE_KNOWN_CHANNEL_PREFIX_RE = ENVELOPE_KNOWN_CHANNEL_PATTERN ? new RegExp(`^\\[((?:${ENVELOPE_KNOWN_CHANNEL_PATTERN})\\s+[^\\]\\n\\s][^\\]\\n]{0,299})\\]\\s`, "i") : null;
112
- /**
113
- * Group-chat envelope bodies prepend `<Sender>: ` to the raw user text (see
114
- * `formatInboundEnvelope`). After stripping the leading envelope bracket,
115
- * this pattern matches that body sender prefix; capture group 1 is the label
116
- * itself so the gated strip in `sanitizeForMemoryCapture` can compare it
117
- * against the envelope header before removing it. Sender label is capped at
118
- * the same length as `sanitizeEnvelopeHeaderPart` would produce in practice
119
- * (the envelope formatter does not truncate, but a 120-char ceiling keeps the
120
- * regex bounded and matches realistic display names).
121
- */
122
36
  const ENVELOPE_BODY_SENDER_PREFIX_RE = /^([^\n:]{1,120}):\s/;
123
37
  const ENVELOPE_BODY_DIRECT_PREFIX = "(sender)";
124
38
  const ENVELOPE_BODY_SELF_PREFIX = "(self)";
@@ -134,45 +48,17 @@ function matchKnownChannelMarkerFreeEnvelopePrefix(text, options) {
134
48
  if (stripEnvelopeBodySenderPrefix(body, headerInside) !== body) return match;
135
49
  return options?.allowAmbiguousDirect ? match : null;
136
50
  }
137
- /**
138
- * Returns true if `text` looks like it contains OpenClaw-injected envelope or
139
- * transport metadata that should never be persisted as a long-term memory.
140
- */
141
51
  function looksLikeEnvelopeSludge(text) {
142
- if (!text) return false;
143
- if (MARKER_HEADER_LINE_RE.test(text)) return true;
144
- if (MESSAGE_TOOL_DELIVERY_HINT_RE.test(text)) return true;
145
- if (HISTORY_CONTEXT_MARKERS.some((marker) => text.includes(marker)) || CURRENT_MESSAGE_MARKERS.some((marker) => text.includes(marker))) return true;
146
- if (ACTIVE_TURN_RECOVERY_RE.test(text)) return true;
147
- if (ENVELOPE_JSON_LINE_RE.test(text)) return true;
148
- return INBOUND_ENVELOPE_PREFIX_RE.test(text) || matchKnownChannelMarkerFreeEnvelopePrefix(text) !== null;
52
+ return MARKER_HEADER_LINE_RE.test(text) || MESSAGE_TOOL_DELIVERY_HINT_RE.test(text) || HISTORY_CONTEXT_MARKERS.some((marker) => text.includes(marker)) || CURRENT_MESSAGE_MARKERS.some((marker) => text.includes(marker)) || ACTIVE_TURN_RECOVERY_RE.test(text) || ENVELOPE_JSON_LINE_RE.test(text) || INBOUND_ENVELOPE_PREFIX_RE.test(text) || matchKnownChannelMarkerFreeEnvelopePrefix(text) !== null;
149
53
  }
150
- /**
151
- * Timestamp prefix pattern injected by `injectTimestamp`.
152
- * Canonical source: src/auto-reply/reply/strip-inbound-meta.ts
153
- */
154
54
  const LEADING_TIMESTAMP_PREFIX_RE = /^\[[A-Za-z]{3} \d{4}-\d{2}-\d{2} \d{2}:\d{2}[^\]]*\] */;
155
- /**
156
- * Decide whether a `<X>: ` body prefix that follows a stripped envelope
157
- * bracket was emitted by the formatter (vs being user-typed prose). The
158
- * formatter contract in `src/auto-reply/envelope.ts` only ever prepends:
159
- * - `(self): ` for direct chats with `fromMe`, OR
160
- * - `<resolvedSender>: ` for non-direct chats with a sender label.
161
- *
162
- * Some channel paths call `formatInboundEnvelope` and therefore put the room in
163
- * the header while keeping the sender as the body label, for example
164
- * `[Slack #general] Alice: text`. Generic `formatAgentEnvelope` callers and
165
- * direct `formatInboundEnvelope` bodies do not add that body label, so require
166
- * structural non-direct markers and preserve common user-authored labels like
167
- * `TODO:`.
168
- */
169
55
  function stripEnvelopeBodySenderPrefix(body, headerInside) {
170
56
  const match = body.match(ENVELOPE_BODY_SENDER_PREFIX_RE);
171
57
  if (!match) return body;
172
58
  const label = expectDefined(match[1], "envelope body sender capture");
173
59
  if (label === ENVELOPE_BODY_SELF_PREFIX || label === ENVELOPE_BODY_DIRECT_PREFIX) return body.slice(match[0].length);
174
60
  if (SENDER_PREFIXED_ENVELOPE_CHANNEL_RE.test(headerInside) && NON_DIRECT_ENVELOPE_HEADER_RE.test(headerInside) && !USER_AUTHORED_BODY_LABEL_RE.test(label)) return body.slice(match[0].length);
175
- if (headerInside.split(/\s+/).includes(label) || headerInside.includes(label)) return body.slice(match[0].length);
61
+ if (headerInside.includes(label)) return body.slice(match[0].length);
176
62
  return body;
177
63
  }
178
64
  function stripLeadingMessageToolDeliveryHints(text) {
@@ -206,9 +92,7 @@ function findFirstInboundEnvelopeIndex(text, options) {
206
92
  function stripPendingHistoryContextBeforeCurrentMessage(text) {
207
93
  const candidateText = text.trimStart();
208
94
  if (!HISTORY_CONTEXT_MARKERS.some((marker) => candidateText.startsWith(marker))) return text;
209
- const currentMarker = findLastContextMarker(candidateText, CURRENT_MESSAGE_MARKERS);
210
- if (!currentMarker) return text;
211
- return candidateText.slice(currentMarker.index + currentMarker.marker.length);
95
+ return stripToCurrentMessageMarker(candidateText) ?? text;
212
96
  }
213
97
  function stripToCurrentMessageMarker(text) {
214
98
  const currentMarker = findLastContextMarker(text, CURRENT_MESSAGE_MARKERS);
@@ -294,11 +178,7 @@ function stripLeadingChronologicalContextBlocks(text) {
294
178
  }
295
179
  return cleaned;
296
180
  }
297
- /**
298
- * Strips OpenClaw-injected envelope metadata from a user message so that only
299
- * the user's actual intent text remains. Returns empty string if nothing
300
- * meaningful survives.
301
- */
181
+ /** Remove injected transport context before capture; empty means no user text survived. */
302
182
  function sanitizeForMemoryCapture(text) {
303
183
  if (!text) return "";
304
184
  const MAX_SANITIZE_CHARS = 1e4;
@@ -51,7 +51,7 @@ function parseMemoryCliFilter(rawValue) {
51
51
  value
52
52
  };
53
53
  }
54
- function registerMemoryCli(api, db, embeddings, resolveCliAgentId, resolveConfig) {
54
+ function registerMemoryCli(api, db, embeddings, resolveCliAgentId, resolveConfig, statsSource) {
55
55
  api.registerCli(({ program }) => {
56
56
  const memory = program.command("ltm").description("LanceDB memory plugin commands");
57
57
  memory.command("list").description("List memories").option("--agent <id>", "Agent id (default: configured default agent)").option("--limit <n>", "Max results").option("--order-by-created-at", "Order memories by createdAt descending", false).action(async (opts) => {
@@ -61,8 +61,7 @@ function registerMemoryCli(api, db, embeddings, resolveCliAgentId, resolveConfig
61
61
  defaultRuntime.writeJson(entries);
62
62
  });
63
63
  memory.command("search").description("Search memories").argument("<query>", "Search query").option("--agent <id>", "Agent id (default: configured default agent)").option("--limit <n>", "Max results", "5").action(async (query, opts) => {
64
- let operationError;
65
- let operationFailed = false;
64
+ let failure;
66
65
  try {
67
66
  const agentId = resolveCliAgentId(opts.agent);
68
67
  const limit = parsePositiveIntegerOption(opts.limit, "--limit");
@@ -76,20 +75,15 @@ function registerMemoryCli(api, db, embeddings, resolveCliAgentId, resolveConfig
76
75
  score: r.score
77
76
  }));
78
77
  defaultRuntime.writeJson(output);
79
- } catch (err) {
80
- operationError = err;
81
- operationFailed = true;
78
+ } catch (error) {
79
+ failure = { error };
82
80
  }
83
- let closeError;
84
- let closeFailed = false;
85
81
  try {
86
82
  await embeddings.close?.();
87
- } catch (err) {
88
- closeError = err;
89
- closeFailed = true;
83
+ } catch (error) {
84
+ failure ??= { error };
90
85
  }
91
- if (operationFailed) throw operationError;
92
- if (closeFailed) throw closeError;
86
+ if (failure) throw failure.error;
93
87
  });
94
88
  memory.command("query").description("Query memories (non-vector search)").option("--agent <id>", "Agent id (default: configured default agent)").option("--cols <columns>", "Columns to select, comma-separated").option("--filter <condition>", "Filter condition").option("--limit <n>", "Limit number of results", "10").option("--order-by <order>", "Order by column and direction (e.g., createdAt:desc)").action(async (opts) => {
95
89
  const agentId = resolveCliAgentId(opts.agent);
@@ -116,8 +110,8 @@ function registerMemoryCli(api, db, embeddings, resolveCliAgentId, resolveConfig
116
110
  defaultRuntime.writeJson(rows.map((row) => Object.fromEntries(outputColumns.map((column) => [column, row[column]]))));
117
111
  });
118
112
  memory.command("stats").description("Show memory statistics").option("--agent <id>", "Agent id (default: configured default agent)").action(async (opts) => {
119
- const agentId = resolveCliAgentId(opts.agent);
120
- const count = await db.count(agentId);
113
+ const { readMemoryStats } = await import("./memory-stats.js");
114
+ const count = await readMemoryStats(statsSource, resolveCliAgentId(opts.agent));
121
115
  console.log(`Total memories: ${count}`);
122
116
  });
123
117
  }, {