@h-ai/ai 1.0.0-beta.25 → 1.0.0-beta.26

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.
package/dist/index.js CHANGED
@@ -897,6 +897,12 @@ function acpError(error) {
897
897
  }
898
898
 
899
899
  // src/acp/ai-acp-adapters.ts
900
+ var deepSeekChatModels = /* @__PURE__ */ new Set([
901
+ "deepseek-flash",
902
+ "deepseek-v4-pro",
903
+ "deepseek-v4-flash",
904
+ "deepseek-v4-flash-vision-exp"
905
+ ]);
900
906
  function resolveAgentModels(agent, config) {
901
907
  return agent.modelIds.map((id3) => {
902
908
  const entry = config.llm?.models?.find((model) => model.id === id3);
@@ -964,6 +970,7 @@ var nativeAdapters = {
964
970
  throw new ACPFailure("model", { modelId });
965
971
  }
966
972
  const key = "HAI_ACP_MODEL_0";
973
+ const deepSeekChat = model.protocol === "chat" && (URL.parse(model.baseUrl)?.hostname === "api.deepseek.com" || deepSeekChatModels.has(model.model));
967
974
  const providers = {
968
975
  "hai-0": {
969
976
  apiKeyEnv: key,
@@ -973,6 +980,15 @@ var nativeAdapters = {
973
980
  responses: "openai-responses",
974
981
  anthropic: "anthropic-messages"
975
982
  }[model.protocol],
983
+ ...deepSeekChat && {
984
+ compat: {
985
+ supportsDeveloperRole: false,
986
+ supportsStore: false,
987
+ maxTokensField: "max_tokens",
988
+ thinkingFormat: "deepseek",
989
+ requiresReasoningContentOnAssistantMessages: true
990
+ }
991
+ },
976
992
  // 输出容量是能力声明;单轮预算沿用 Hai 模型的 maxTokens。
977
993
  defaultMaxTokens: Math.min(model.maxTokens, caps.maxOutputTokens),
978
994
  defaultContextWindow: caps.contextWindow,
@@ -8938,16 +8954,16 @@ function createEmbeddingOperations(config, loadModels = () => config.llm) {
8938
8954
  if (!resolved.success)
8939
8955
  return resolved;
8940
8956
  const input = Array.isArray(request2.input) ? request2.input : [request2.input];
8941
- const batchSize2 = embeddingConfig.batchSize;
8942
- if (input.length <= batchSize2) {
8957
+ const batchSize3 = embeddingConfig.batchSize;
8958
+ if (input.length <= batchSize3) {
8943
8959
  return callEmbeddingAPI(request2, resolved.data);
8944
8960
  }
8945
8961
  const allData = [];
8946
8962
  let totalPromptTokens = 0;
8947
8963
  let totalTokens = 0;
8948
8964
  let resultModel = "";
8949
- for (let i = 0; i < input.length; i += batchSize2) {
8950
- const batch = input.slice(i, i + batchSize2);
8965
+ for (let i = 0; i < input.length; i += batchSize3) {
8966
+ const batch = input.slice(i, i + batchSize3);
8951
8967
  const result = await callEmbeddingAPI({ ...request2, input: batch }, resolved.data);
8952
8968
  if (!result.success)
8953
8969
  return result;
@@ -12899,27 +12915,27 @@ function createMCPServiceOperations(read, runner, files, configuredServices = []
12899
12915
  }
12900
12916
  };
12901
12917
  }
12902
- function createScopedMemory(core33, binding) {
12918
+ function createScopedMemory(core34, binding) {
12903
12919
  if (typeof binding.objectId !== "string" || !binding.objectId.trim())
12904
12920
  throw new TypeError(aiM("ai_memoryScopeInvalid"));
12905
12921
  const { objectId, scope } = binding;
12906
12922
  const accessScope = { objectId, scope };
12907
12923
  return {
12908
- extract: (messages, options) => core33.extract(messages, { ...options, objectId, scope }),
12909
- recall: (query, options) => core33.recall(query, { ...options, objectId, scope }),
12910
- injectMemories: (messages, options) => core33.injectMemories(messages, { ...options, objectId, scope }),
12911
- add: (entry) => core33.add({ ...entry, objectId, scope }),
12912
- update: (memoryId, updates) => core33.update(memoryId, updates, accessScope),
12913
- get: (memoryId) => core33.get(memoryId, accessScope),
12914
- remove: (memoryId) => core33.remove(memoryId, accessScope),
12915
- list: (options) => core33.list({ ...options, objectId, scope }),
12916
- listPage: (options) => core33.listPage({ ...options, objectId, scope }),
12917
- clear: (options) => core33.clear({ ...options, objectId, scope })
12924
+ extract: (messages, options) => core34.extract(messages, { ...options, objectId, scope }),
12925
+ recall: (query, options) => core34.recall(query, { ...options, objectId, scope }),
12926
+ injectMemories: (messages, options) => core34.injectMemories(messages, { ...options, objectId, scope }),
12927
+ add: (entry) => core34.add({ ...entry, objectId, scope }),
12928
+ update: (memoryId, updates) => core34.update(memoryId, updates, accessScope),
12929
+ get: (memoryId) => core34.get(memoryId, accessScope),
12930
+ remove: (memoryId) => core34.remove(memoryId, accessScope),
12931
+ list: (options) => core34.list({ ...options, objectId, scope }),
12932
+ listPage: (options) => core34.listPage({ ...options, objectId, scope }),
12933
+ clear: (options) => core34.clear({ ...options, objectId, scope })
12918
12934
  };
12919
12935
  }
12920
- function createMemoryOperations(core33) {
12936
+ function createMemoryOperations(core34) {
12921
12937
  return {
12922
- ...core33,
12938
+ ...core34,
12923
12939
  /**
12924
12940
  * 清空记忆(空过滤保护)。
12925
12941
  *
@@ -12933,15 +12949,15 @@ function createMemoryOperations(core33) {
12933
12949
  if (!hasFilter) {
12934
12950
  return err(HaiAIError.MEMORY_STORE_FAILED, aiM("ai_memoryClearRequiresFilter"));
12935
12951
  }
12936
- return core33.clear(options);
12952
+ return core34.clear(options);
12937
12953
  },
12938
- scoped: (binding) => createScopedMemory(core33, binding),
12954
+ scoped: (binding) => createScopedMemory(core34, binding),
12939
12955
  admin: {
12940
12956
  async clearAll(options) {
12941
12957
  if (options?.confirm !== true) {
12942
12958
  return err(HaiAIError.MEMORY_STORE_FAILED, aiM("ai_memoryClearAllUnconfirmed"));
12943
12959
  }
12944
- return core33.clear();
12960
+ return core34.clear();
12945
12961
  }
12946
12962
  }
12947
12963
  };
@@ -14168,13 +14184,158 @@ async function extractAndConsolidate(deps, messages, options) {
14168
14184
  });
14169
14185
  return ok(applyResult.data);
14170
14186
  }
14187
+ var logger24 = core.logger.child({ module: "ai", scope: "memory-vector-sync" });
14188
+ var pollMs = 1e3;
14189
+ var inFlightRetryMs = 45e3;
14190
+ var lateWriteWindowMs = 6e4;
14191
+ var batchSize2 = 16;
14192
+ function backoff(attempts) {
14193
+ return Math.min(3e4, 1e3 * 2 ** Math.min(Math.max(attempts - 1, 0), 5));
14194
+ }
14195
+ function vectorId(memory) {
14196
+ return memory.vectorId ?? memory.id;
14197
+ }
14198
+ function createMemoryVectorSync(store, queue, vectors) {
14199
+ const lock = store.withRelatedWriteLock?.bind(store);
14200
+ if (!lock || !queue.queryKeys)
14201
+ return void 0;
14202
+ function write(run) {
14203
+ return lock(queue, run);
14204
+ }
14205
+ let active;
14206
+ let timer;
14207
+ async function reconcile(id3) {
14208
+ const claimed = await write(async (memory, pending) => {
14209
+ const job = await pending.get(id3);
14210
+ if (!job)
14211
+ return void 0;
14212
+ const now = await pending.currentTime();
14213
+ if (job.updatedAt > now)
14214
+ return void 0;
14215
+ const entry = await memory.get(job.memoryId);
14216
+ const current = entry?.vector && vectorId(entry) === id3 ? entry : void 0;
14217
+ if (current && job.cooldown) {
14218
+ await pending.remove(id3);
14219
+ return void 0;
14220
+ }
14221
+ const token = randomUUID();
14222
+ const next = {
14223
+ ...job,
14224
+ token,
14225
+ attempts: job.attempts + 1,
14226
+ updatedAt: now + inFlightRetryMs
14227
+ };
14228
+ await pending.save(id3, next);
14229
+ return { ...next, entry: current };
14230
+ });
14231
+ if (!claimed)
14232
+ return;
14233
+ let succeeded = false;
14234
+ try {
14235
+ if (claimed.entry?.vector) {
14236
+ await vectors.upsert(id3, claimed.entry.vector, {
14237
+ objectId: claimed.entry.objectId,
14238
+ type: claimed.entry.type
14239
+ });
14240
+ } else {
14241
+ await vectors.remove(id3);
14242
+ }
14243
+ succeeded = true;
14244
+ } catch {
14245
+ logger24.debug("Memory vector sync will retry", {
14246
+ operation: claimed.entry ? "upsert" : "delete"
14247
+ });
14248
+ }
14249
+ await write(async (_memory, pending) => {
14250
+ const job = await pending.get(id3);
14251
+ if (!job || job.token !== claimed.token)
14252
+ return;
14253
+ const now = await pending.currentTime();
14254
+ if (succeeded && claimed.entry && job.attempts > 1) {
14255
+ await pending.save(id3, {
14256
+ ...job,
14257
+ token: void 0,
14258
+ cooldown: true,
14259
+ updatedAt: now + lateWriteWindowMs
14260
+ });
14261
+ return;
14262
+ }
14263
+ if (succeeded && (!job.retireUntil || job.retireUntil <= now)) {
14264
+ await pending.remove(id3);
14265
+ return;
14266
+ }
14267
+ const delay3 = backoff(job.attempts);
14268
+ await pending.save(id3, {
14269
+ ...job,
14270
+ token: void 0,
14271
+ updatedAt: job.retireUntil && succeeded ? Math.min(now + delay3, job.retireUntil) : now + delay3
14272
+ });
14273
+ });
14274
+ }
14275
+ async function drain() {
14276
+ const now = await queue.currentTime();
14277
+ const due = await queue.queryKeys({ updatedBefore: now + 1, limit: batchSize2 });
14278
+ for (const { id: id3 } of due) {
14279
+ if (!timer)
14280
+ return;
14281
+ await reconcile(id3);
14282
+ }
14283
+ }
14284
+ function kick() {
14285
+ if (timer && !active) {
14286
+ active = drain().catch(() => {
14287
+ logger24.warn("Memory vector compensation storage unavailable");
14288
+ }).finally(() => {
14289
+ active = void 0;
14290
+ });
14291
+ }
14292
+ }
14293
+ return {
14294
+ write,
14295
+ kick,
14296
+ start() {
14297
+ if (!timer) {
14298
+ timer = setInterval(kick, pollMs);
14299
+ timer.unref();
14300
+ kick();
14301
+ }
14302
+ },
14303
+ async close() {
14304
+ clearInterval(timer);
14305
+ timer = void 0;
14306
+ await active;
14307
+ },
14308
+ async enqueue(pending, entry) {
14309
+ const now = await pending.currentTime();
14310
+ await pending.save(vectorId(entry), { memoryId: entry.id, updatedAt: now, attempts: 0 });
14311
+ },
14312
+ async retire(pending, entry) {
14313
+ const id3 = vectorId(entry);
14314
+ const prior = await pending.get(id3);
14315
+ if (prior?.attempts === 0) {
14316
+ await pending.remove(id3);
14317
+ return;
14318
+ }
14319
+ const now = await pending.currentTime();
14320
+ await pending.save(id3, {
14321
+ memoryId: entry.id,
14322
+ updatedAt: now,
14323
+ attempts: 0,
14324
+ ...prior && { retireUntil: now + lateWriteWindowMs }
14325
+ });
14326
+ }
14327
+ };
14328
+ }
14171
14329
 
14172
14330
  // src/memory/providers/ai-memory-provider-native.ts
14173
- var logger24 = core.logger.child({ module: "ai", scope: "memory-native" });
14331
+ var logger25 = core.logger.child({ module: "ai", scope: "memory-native" });
14174
14332
  var EVICTION_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1e3;
14175
14333
  var EVICTION_CANDIDATES = 64;
14176
14334
  function generateId() {
14177
- return `mem_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`;
14335
+ return `mem_${randomUUID()}`;
14336
+ }
14337
+ function publicEntry({ vectorId: _vectorId, ...entry }) {
14338
+ return entry;
14178
14339
  }
14179
14340
  function cosineSimilarity(a, b) {
14180
14341
  if (a.length !== b.length)
@@ -14195,12 +14356,27 @@ function matchScope2(entry, scope) {
14195
14356
  return false;
14196
14357
  return Object.entries(scope).every(([k, v]) => entry.scope[k] === v);
14197
14358
  }
14198
- function createNativeMemoryOperations(config, llm, embedding, store, vectorStore) {
14359
+ function assembleNativeMemory(config, llm, embedding, store, vectorStore, vectorQueue) {
14360
+ const sync = vectorQueue && createMemoryVectorSync(store, vectorQueue, vectorStore);
14361
+ const maxPending = Math.max(1024, config.maxEntriesGlobal * 2);
14362
+ async function ensureVectorCapacity(pending) {
14363
+ if (pending && await pending.count() >= maxPending)
14364
+ throw new Error("Memory vector synchronization backlog is full");
14365
+ }
14366
+ async function deleteEntry(activeStore, entry, pending) {
14367
+ if (sync && pending) {
14368
+ if (entry.vector)
14369
+ await sync.retire(pending, entry);
14370
+ } else {
14371
+ await vectorStore.remove(entry.id);
14372
+ }
14373
+ return activeStore.remove(entry.id);
14374
+ }
14199
14375
  async function protect(operation) {
14200
14376
  try {
14201
14377
  return await operation();
14202
14378
  } catch (error) {
14203
- logger24.error("Memory storage operation failed", {
14379
+ logger25.error("Memory storage operation failed", {
14204
14380
  error: core.sanitize.sanitizeSensitiveFields(error)
14205
14381
  });
14206
14382
  return err(HaiAIError.MEMORY_STORE_FAILED, aiM("ai_memoryOperationFailed"));
@@ -14232,23 +14408,21 @@ function createNativeMemoryOperations(config, llm, embedding, store, vectorStore
14232
14408
  const result = await embedding.embedText(text);
14233
14409
  if (result.success)
14234
14410
  return result.data;
14235
- logger24.warn("Failed to compute embedding for memory", { error: result.error });
14411
+ logger25.warn("Failed to compute embedding for memory", { error: result.error });
14236
14412
  return void 0;
14237
14413
  }
14238
- async function evictLowest(activeStore, candidates, count) {
14414
+ async function evictLowest(activeStore, candidates, count, pending) {
14239
14415
  const now = Date.now();
14240
14416
  const ranked = candidates.map((entry) => {
14241
14417
  const age = now - entry.createdAt;
14242
14418
  const recency = Math.max(0, 1 - age / EVICTION_MAX_AGE_MS);
14243
- return { id: entry.id, score: entry.importance * 0.7 + recency * 0.3 };
14419
+ return { entry, score: entry.importance * 0.7 + recency * 0.3 };
14244
14420
  }).sort((left, right) => left.score - right.score).slice(0, count);
14245
- for (const { id: id3 } of ranked) {
14246
- await vectorStore.remove(id3);
14247
- await activeStore.remove(id3);
14248
- }
14421
+ for (const { entry } of ranked)
14422
+ await deleteEntry(activeStore, entry, pending);
14249
14423
  return ranked.length;
14250
14424
  }
14251
- async function evictIfNeeded(activeStore, objectId) {
14425
+ async function evictIfNeeded(activeStore, objectId, pending) {
14252
14426
  if (objectId) {
14253
14427
  const objectTotal = await activeStore.count({ objectId });
14254
14428
  if (objectTotal >= config.maxEntriesPerObject) {
@@ -14258,7 +14432,7 @@ function createNativeMemoryOperations(config, llm, embedding, store, vectorStore
14258
14432
  limit: EVICTION_CANDIDATES
14259
14433
  });
14260
14434
  const needed = objectTotal - config.maxEntriesPerObject + 1;
14261
- if (await evictLowest(activeStore, objectEntries, needed) < needed)
14435
+ if (await evictLowest(activeStore, objectEntries, needed, pending) < needed)
14262
14436
  return false;
14263
14437
  }
14264
14438
  }
@@ -14269,12 +14443,17 @@ function createNativeMemoryOperations(config, llm, embedding, store, vectorStore
14269
14443
  limit: EVICTION_CANDIDATES
14270
14444
  });
14271
14445
  const needed = globalTotal - config.maxEntriesGlobal + 1;
14272
- return await evictLowest(activeStore, candidates, needed) >= needed;
14446
+ return await evictLowest(activeStore, candidates, needed, pending) >= needed;
14273
14447
  }
14274
14448
  return true;
14275
14449
  }
14276
14450
  let localWrites = Promise.resolve();
14277
- function writeMemory(write) {
14451
+ async function writeMemory(write) {
14452
+ if (sync) {
14453
+ const written = await sync.write(write);
14454
+ sync.kick();
14455
+ return written;
14456
+ }
14278
14457
  if (store.withWriteLock)
14279
14458
  return store.withWriteLock(write);
14280
14459
  const pending = localWrites.then(() => write(store));
@@ -14298,51 +14477,81 @@ function createNativeMemoryOperations(config, llm, embedding, store, vectorStore
14298
14477
  lastAccessedAt: now,
14299
14478
  accessCount: 0
14300
14479
  };
14301
- return writeMemory(async (activeStore) => {
14302
- if (!await evictIfNeeded(activeStore, input.objectId))
14480
+ return writeMemory(async (activeStore, pending) => {
14481
+ await ensureVectorCapacity(pending);
14482
+ if (!await evictIfNeeded(activeStore, input.objectId, pending))
14303
14483
  return void 0;
14484
+ if (sync && pending && vector) {
14485
+ entry.vectorId = randomUUID();
14486
+ await sync.enqueue(pending, entry);
14487
+ }
14304
14488
  await activeStore.save(entry.id, entry, { objectId: entry.objectId });
14305
14489
  if (vector) {
14306
- await vectorStore.upsert(entry.id, vector, { objectId: entry.objectId, type: entry.type });
14490
+ if (!pending)
14491
+ await vectorStore.upsert(entry.id, vector, { objectId: entry.objectId, type: entry.type });
14307
14492
  }
14308
- return entry;
14493
+ return publicEntry(entry);
14309
14494
  });
14310
14495
  }
14311
14496
  async function updateEntry(memoryId, updates, accessScope) {
14312
14497
  try {
14313
- const record = await store.readVersioned(memoryId);
14314
- if (!record || isMemoryAccessDenied(record.data, accessScope)) {
14498
+ const before = await store.get(memoryId);
14499
+ if (!before || isMemoryAccessDenied(before, accessScope)) {
14315
14500
  return err(HaiAIError.MEMORY_NOT_FOUND, aiM("ai_memoryNotFound", {
14316
14501
  params: { id: memoryId }
14317
14502
  }));
14318
14503
  }
14319
- const existing = record.data;
14320
- if (updates.content !== void 0)
14321
- existing.content = updates.content;
14322
- if (updates.type !== void 0)
14323
- existing.type = updates.type;
14324
- if (updates.importance !== void 0)
14325
- existing.importance = updates.importance;
14326
- if (updates.metadata !== void 0)
14327
- existing.metadata = updates.metadata;
14328
- if (updates.content !== void 0) {
14329
- const vector = await computeVector(updates.content);
14330
- existing.vector = vector;
14331
- }
14332
- if (!await store.compareAndSwap(memoryId, {
14333
- expectedVersion: record.version,
14334
- data: existing,
14335
- scope: { objectId: existing.objectId }
14336
- })) {
14337
- throw new Error("Memory was concurrently changed or deleted");
14338
- }
14339
- if (updates.content !== void 0 && existing.vector) {
14340
- await vectorStore.upsert(memoryId, existing.vector, { objectId: existing.objectId, type: existing.type });
14504
+ const vector = updates.content !== void 0 ? await computeVector(updates.content) : void 0;
14505
+ const existing = await writeMemory(async (active, pending) => {
14506
+ const record = await active.readVersioned(memoryId);
14507
+ if (!record || isMemoryAccessDenied(record.data, accessScope))
14508
+ return void 0;
14509
+ const previous = record.data;
14510
+ const changed = {
14511
+ ...previous,
14512
+ ...updates.type !== void 0 && { type: updates.type },
14513
+ ...updates.importance !== void 0 && { importance: updates.importance },
14514
+ ...updates.metadata !== void 0 && { metadata: updates.metadata },
14515
+ ...updates.content !== void 0 && { content: updates.content },
14516
+ ...updates.content !== void 0 && { vector }
14517
+ };
14518
+ const changesVector = updates.content !== void 0 || updates.type !== void 0 && updates.type !== previous.type;
14519
+ if (changesVector && sync && pending) {
14520
+ if (previous.vector)
14521
+ await sync.retire(pending, previous);
14522
+ changed.vectorId = changed.vector ? randomUUID() : void 0;
14523
+ if (changed.vector) {
14524
+ await ensureVectorCapacity(pending);
14525
+ await sync.enqueue(pending, changed);
14526
+ }
14527
+ }
14528
+ if (!await active.compareAndSwap(memoryId, {
14529
+ expectedVersion: record.version,
14530
+ data: changed,
14531
+ scope: { objectId: changed.objectId }
14532
+ })) {
14533
+ throw new Error("Memory was concurrently changed or deleted");
14534
+ }
14535
+ if (changesVector && !pending) {
14536
+ if (changed.vector)
14537
+ await vectorStore.upsert(memoryId, changed.vector, { objectId: changed.objectId, type: changed.type });
14538
+ else if (previous.vector)
14539
+ await vectorStore.remove(memoryId);
14540
+ }
14541
+ return publicEntry(changed);
14542
+ });
14543
+ if (!existing) {
14544
+ return err(HaiAIError.MEMORY_NOT_FOUND, aiM("ai_memoryNotFound", {
14545
+ params: { id: memoryId }
14546
+ }));
14341
14547
  }
14342
- logger24.trace("Memory updated", { id: memoryId });
14548
+ logger25.trace("Memory updated", { id: memoryId });
14343
14549
  return ok(existing);
14344
14550
  } catch (error) {
14345
- logger24.error("Memory update failed", { id: memoryId, error });
14551
+ logger25.error("Memory update failed", {
14552
+ id: memoryId,
14553
+ error: core.sanitize.sanitizeSensitiveFields(error)
14554
+ });
14346
14555
  return err(HaiAIError.MEMORY_STORE_FAILED, aiM("ai_memoryOperationFailed"));
14347
14556
  }
14348
14557
  }
@@ -14350,7 +14559,7 @@ function createNativeMemoryOperations(config, llm, embedding, store, vectorStore
14350
14559
  const topK = options?.topK ?? config.defaultTopK;
14351
14560
  const recencyWeight = options?.recencyWeight ?? 1 - config.recencyDecay;
14352
14561
  const candidateMultiplier = Math.max(1, options?.candidateMultiplier ?? config.candidateMultiplier);
14353
- logger24.trace("Recalling memories", {
14562
+ logger25.trace("Recalling memories", {
14354
14563
  query: query.slice(0, 100),
14355
14564
  topK,
14356
14565
  updateAccessStats
@@ -14384,17 +14593,22 @@ function createNativeMemoryOperations(config, llm, embedding, store, vectorStore
14384
14593
  }
14385
14594
  const vectorScores = /* @__PURE__ */ new Map();
14386
14595
  if (queryVector) {
14387
- const vectorResults = await vectorStore.search(queryVector, {
14388
- topK: topK * candidateMultiplier,
14389
- filter: options?.objectId ? { objectId: options.objectId } : void 0
14390
- });
14391
- for (const r of vectorResults) {
14392
- vectorScores.set(r.id, r.score);
14596
+ try {
14597
+ const vectorResults = await vectorStore.search(queryVector, {
14598
+ topK: topK * candidateMultiplier,
14599
+ filter: options?.objectId ? { objectId: options.objectId } : void 0
14600
+ });
14601
+ for (const r of vectorResults)
14602
+ vectorScores.set(r.id, r.score);
14603
+ } catch (error) {
14604
+ if (!sync)
14605
+ throw error;
14606
+ logger25.debug("Memory vector search unavailable; using persisted embeddings");
14393
14607
  }
14394
14608
  }
14395
14609
  const now = Date.now();
14396
14610
  const scored = candidates.map((entry) => {
14397
- let similarity = vectorScores.get(entry.id) ?? 0;
14611
+ let similarity = entry.vector ? vectorScores.get(entry.vectorId ?? entry.id) ?? 0 : 0;
14398
14612
  if (!similarity && queryVector && entry.vector) {
14399
14613
  similarity = cosineSimilarity(queryVector, entry.vector);
14400
14614
  } else if (!similarity) {
@@ -14414,19 +14628,19 @@ function createNativeMemoryOperations(config, llm, embedding, store, vectorStore
14414
14628
  if (updateAccessStats) {
14415
14629
  const updated = await touchEntry(entry.id, options?.objectId ? { objectId: options.objectId, scope: options.scope } : void 0);
14416
14630
  if (updated && (!options?.scope || matchScope2(updated, options.scope)) && (!options?.types?.length || options.types.includes(updated.type)))
14417
- results.push(updated);
14631
+ results.push(publicEntry(updated));
14418
14632
  continue;
14419
14633
  }
14420
- results.push({ ...entry });
14634
+ results.push(publicEntry(entry));
14421
14635
  }
14422
- logger24.trace("Memory recall completed", {
14636
+ logger25.trace("Memory recall completed", {
14423
14637
  query: query.slice(0, 50),
14424
14638
  resultCount: results.length,
14425
14639
  updateAccessStats
14426
14640
  });
14427
14641
  return ok(results);
14428
14642
  } catch (error) {
14429
- logger24.error("Memory recall failed", {
14643
+ logger25.error("Memory recall failed", {
14430
14644
  error: core.sanitize.sanitizeSensitiveFields(error)
14431
14645
  });
14432
14646
  return err(HaiAIError.MEMORY_RECALL_FAILED, aiM("ai_memoryOperationFailed"));
@@ -14478,10 +14692,10 @@ function createNativeMemoryOperations(config, llm, embedding, store, vectorStore
14478
14692
  const stored = await saveEntry(entry, vector);
14479
14693
  if (!stored)
14480
14694
  return err(HaiAIError.MEMORY_STORE_FAILED, aiM("ai_memoryOperationFailed"));
14481
- logger24.trace("Memory added", { id: stored.id, type: stored.type });
14695
+ logger25.trace("Memory added", { id: stored.id, type: stored.type });
14482
14696
  return ok(stored);
14483
14697
  } catch (error) {
14484
- logger24.error("Memory add failed", {
14698
+ logger25.error("Memory add failed", {
14485
14699
  error: core.sanitize.sanitizeSensitiveFields(error)
14486
14700
  });
14487
14701
  return err(HaiAIError.MEMORY_STORE_FAILED, aiM("ai_memoryOperationFailed"));
@@ -14507,7 +14721,7 @@ function createNativeMemoryOperations(config, llm, embedding, store, vectorStore
14507
14721
  params: { id: memoryId }
14508
14722
  }));
14509
14723
  }
14510
- return ok(entry);
14724
+ return ok(publicEntry(entry));
14511
14725
  },
14512
14726
  /**
14513
14727
  * 根据 ID 删除一条记忆(同时清理关系存储与向量库)
@@ -14517,20 +14731,18 @@ function createNativeMemoryOperations(config, llm, embedding, store, vectorStore
14517
14731
  * @returns `ok(undefined)` 删除成功;ID 不存在或归属不符时返回 `MEMORY_NOT_FOUND`
14518
14732
  */
14519
14733
  async remove(memoryId, accessScope) {
14520
- const existing = await store.get(memoryId);
14521
- if (!existing || isMemoryAccessDenied(existing, accessScope)) {
14522
- return err(HaiAIError.MEMORY_NOT_FOUND, aiM("ai_memoryNotFound", {
14523
- params: { id: memoryId }
14524
- }));
14525
- }
14526
- await vectorStore.remove(memoryId);
14527
- const removed2 = await store.remove(memoryId);
14734
+ const removed2 = await writeMemory(async (active, pending) => {
14735
+ const existing = await active.get(memoryId);
14736
+ if (!existing || isMemoryAccessDenied(existing, accessScope))
14737
+ return false;
14738
+ return deleteEntry(active, existing, pending);
14739
+ });
14528
14740
  if (!removed2) {
14529
14741
  return err(HaiAIError.MEMORY_NOT_FOUND, aiM("ai_memoryNotFound", {
14530
14742
  params: { id: memoryId }
14531
14743
  }));
14532
14744
  }
14533
- logger24.trace("Memory removed", { id: memoryId });
14745
+ logger25.trace("Memory removed", { id: memoryId });
14534
14746
  return ok(void 0);
14535
14747
  },
14536
14748
  /**
@@ -14556,9 +14768,9 @@ function createNativeMemoryOperations(config, llm, embedding, store, vectorStore
14556
14768
  limit: options?.scope ? void 0 : options?.limit
14557
14769
  });
14558
14770
  if (!options?.scope)
14559
- return ok(results);
14771
+ return ok(results.map(publicEntry));
14560
14772
  const filtered = results.filter((e) => matchScope2(e, options.scope));
14561
- return ok(options.limit ? filtered.slice(0, options.limit) : filtered);
14773
+ return ok((options.limit ? filtered.slice(0, options.limit) : filtered).map(publicEntry));
14562
14774
  },
14563
14775
  /**
14564
14776
  * 分页列出记忆条目
@@ -14586,7 +14798,10 @@ function createNativeMemoryOperations(config, llm, embedding, store, vectorStore
14586
14798
  },
14587
14799
  { offset, limit }
14588
14800
  );
14589
- return ok(page);
14801
+ return ok({
14802
+ ...page,
14803
+ items: page.items.map(publicEntry)
14804
+ });
14590
14805
  }
14591
14806
  const all = await store.query({
14592
14807
  objectId: options?.objectId,
@@ -14596,7 +14811,7 @@ function createNativeMemoryOperations(config, llm, embedding, store, vectorStore
14596
14811
  });
14597
14812
  const filtered = all.filter((e) => matchScope2(e, options.scope));
14598
14813
  return ok({
14599
- items: filtered.slice(offset, offset + limit),
14814
+ items: filtered.slice(offset, offset + limit).map(publicEntry),
14600
14815
  total: filtered.length
14601
14816
  });
14602
14817
  },
@@ -14610,46 +14825,62 @@ function createNativeMemoryOperations(config, llm, embedding, store, vectorStore
14610
14825
  * @returns `ok(undefined)` 操作成功
14611
14826
  */
14612
14827
  async clear(options) {
14613
- if (!options?.types && !options?.objectId && !options?.scope) {
14828
+ if (!sync && !options?.types && !options?.objectId && !options?.scope) {
14614
14829
  await vectorStore.clear();
14615
14830
  await store.clear();
14616
- logger24.debug("All memories cleared");
14831
+ logger25.debug("All memories cleared");
14617
14832
  return ok(void 0);
14618
14833
  }
14619
14834
  const where = {};
14620
- if (options.types && options.types.length === 1)
14835
+ if (options?.types && options.types.length === 1)
14621
14836
  where.type = options.types[0];
14622
- else if (options.types && options.types.length > 1)
14837
+ else if (options?.types && options.types.length > 1)
14623
14838
  where.type = { $in: options.types };
14624
- const candidates = await store.query({
14625
- objectId: options.objectId,
14626
- scope: options.scope,
14839
+ const filter = {
14840
+ objectId: options?.objectId,
14841
+ scope: options?.scope,
14627
14842
  where: Object.keys(where).length > 0 ? where : void 0
14628
- });
14629
- const toRemove = options.scope ? candidates.filter((e) => matchScope2(e, options.scope)) : candidates;
14630
- for (const entry of toRemove) {
14631
- await vectorStore.remove(entry.id);
14632
- await store.remove(entry.id);
14843
+ };
14844
+ const scope = options?.scope;
14845
+ let removed2 = 0;
14846
+ let afterId = "";
14847
+ while (true) {
14848
+ const batch = await writeMemory(async (active, pending) => {
14849
+ const rows = await active.query(sync ? { ...filter, afterId, limit: EVICTION_CANDIDATES } : filter);
14850
+ const selected = scope ? rows.filter((e) => matchScope2(e, scope)) : rows;
14851
+ for (const entry of selected)
14852
+ await deleteEntry(active, entry, pending);
14853
+ return { nextId: rows.at(-1)?.id, total: rows.length, selected: selected.length };
14854
+ });
14855
+ removed2 += batch.selected;
14856
+ if (!sync || batch.total < EVICTION_CANDIDATES || !batch.nextId)
14857
+ break;
14858
+ if (batch.nextId === afterId)
14859
+ throw new Error("Memory store did not advance the primary-key cursor");
14860
+ afterId = batch.nextId;
14633
14861
  }
14634
- logger24.debug("Memories cleared", {
14635
- removed: toRemove.length,
14636
- objectId: options.objectId,
14637
- types: options.types,
14638
- scoped: Boolean(options.scope)
14862
+ logger25.debug("Memories cleared", {
14863
+ removed: removed2,
14864
+ objectId: options?.objectId,
14865
+ types: options?.types,
14866
+ scoped: Boolean(scope)
14639
14867
  });
14640
14868
  return ok(void 0);
14641
14869
  }
14642
14870
  };
14643
14871
  return {
14644
- ...operations2,
14645
- get: (id3, scope) => protect(() => operations2.get(id3, scope)),
14646
- remove: (id3, scope) => protect(() => operations2.remove(id3, scope)),
14647
- list: (options) => protect(() => operations2.list(options)),
14648
- listPage: (options) => protect(() => operations2.listPage(options)),
14649
- clear: (options) => protect(() => operations2.clear(options))
14872
+ sync,
14873
+ operations: {
14874
+ ...operations2,
14875
+ get: (id3, scope) => protect(() => operations2.get(id3, scope)),
14876
+ remove: (id3, scope) => protect(() => operations2.remove(id3, scope)),
14877
+ list: (options) => protect(() => operations2.list(options)),
14878
+ listPage: (options) => protect(() => operations2.listPage(options)),
14879
+ clear: (options) => protect(() => operations2.clear(options))
14880
+ }
14650
14881
  };
14651
14882
  }
14652
- var logger25 = core.logger.child({ module: "ai", scope: "persona" });
14883
+ var logger26 = core.logger.child({ module: "ai", scope: "persona" });
14653
14884
  var DEFAULT_OBJECT_ID2 = "system";
14654
14885
  function personaKey(objectId, id3) {
14655
14886
  return JSON.stringify([objectId, id3]);
@@ -14668,7 +14899,7 @@ function createPersonaOperations(store) {
14668
14899
  try {
14669
14900
  return await operation();
14670
14901
  } catch (error) {
14671
- logger25.error("Persona storage operation failed", {
14902
+ logger26.error("Persona storage operation failed", {
14672
14903
  error: core.sanitize.sanitizeSensitiveFields(error)
14673
14904
  });
14674
14905
  return err(HaiAIError.PERSONA_SAVE_FAILED, aiM("ai_personaOperationFailed"));
@@ -14692,10 +14923,10 @@ function createPersonaOperations(store) {
14692
14923
  updatedAt: now
14693
14924
  };
14694
14925
  await store.save(key, profile, { objectId });
14695
- logger25.trace("Persona saved", { id: profile.id, objectId });
14926
+ logger26.trace("Persona saved", { id: profile.id, objectId });
14696
14927
  return ok(profile);
14697
14928
  } catch (error) {
14698
- logger25.error("Persona save failed", {
14929
+ logger26.error("Persona save failed", {
14699
14930
  error: core.sanitize.sanitizeSensitiveFields(error)
14700
14931
  });
14701
14932
  return err(HaiAIError.PERSONA_SAVE_FAILED, aiM("ai_personaOperationFailed"));
@@ -14732,7 +14963,7 @@ function createPersonaOperations(store) {
14732
14963
  await store.save(key, profile, { objectId });
14733
14964
  return ok(profile);
14734
14965
  } catch (error) {
14735
- logger25.error("Persona update failed", {
14966
+ logger26.error("Persona update failed", {
14736
14967
  error: core.sanitize.sanitizeSensitiveFields(error)
14737
14968
  });
14738
14969
  return err(HaiAIError.PERSONA_SAVE_FAILED, aiM("ai_personaOperationFailed"));
@@ -14771,7 +15002,7 @@ function createPersonaOperations(store) {
14771
15002
  compose: (id3, options) => protect(() => operations2.compose(id3, options))
14772
15003
  };
14773
15004
  }
14774
- var logger26 = core.logger.child({ module: "ai", scope: "rag" });
15005
+ var logger27 = core.logger.child({ module: "ai", scope: "rag" });
14775
15006
  var DEFAULT_RAG_SYSTEM_PROMPT = `You are a helpful assistant. Answer the user's question based on the provided context.
14776
15007
  If the context doesn't contain relevant information, say so honestly.
14777
15008
  When using information from the context, cite the source by its number, e.g. [1] or [2].`;
@@ -14800,7 +15031,7 @@ function createRagOperations(llm, retrieval) {
14800
15031
  * @returns `ok(RagResult)` 含 answer、context 列表与引用信源;检索或生成失败时返回错误
14801
15032
  */
14802
15033
  async query(query, options) {
14803
- logger26.trace("Starting RAG query", {
15034
+ logger27.trace("Starting RAG query", {
14804
15035
  query: query.slice(0, 100)
14805
15036
  });
14806
15037
  try {
@@ -14855,7 +15086,7 @@ ${contextText}
14855
15086
  }
14856
15087
  const choice = chatResult.data.choices[0];
14857
15088
  const answer = choice?.message?.content ?? "";
14858
- logger26.trace("RAG query completed", {
15089
+ logger27.trace("RAG query completed", {
14859
15090
  contextCount: contextItems.length,
14860
15091
  model: chatResult.data.model
14861
15092
  });
@@ -14882,7 +15113,7 @@ ${contextText}
14882
15113
  } : void 0
14883
15114
  });
14884
15115
  } catch (error) {
14885
- logger26.error("RAG query failed", { error });
15116
+ logger27.error("RAG query failed", { error });
14886
15117
  return err(HaiAIError.RAG_FAILED, aiM("ai_internalError", {
14887
15118
  params: {
14888
15119
  error: String(error)
@@ -14894,7 +15125,7 @@ ${contextText}
14894
15125
  * 流式 RAG 查询:先产出 context,再逐 chunk 产出 delta,最后 done
14895
15126
  */
14896
15127
  async *queryStream(query, options) {
14897
- logger26.trace("Starting RAG stream", {
15128
+ logger27.trace("Starting RAG stream", {
14898
15129
  query: query.slice(0, 100)
14899
15130
  });
14900
15131
  const retrieveResult = await retrieval.retrieve({
@@ -14978,7 +15209,7 @@ ${contextText}
14978
15209
  }
14979
15210
  };
14980
15211
  }
14981
- var logger27 = core.logger.child({ module: "ai", scope: "reasoning" });
15212
+ var logger28 = core.logger.child({ module: "ai", scope: "reasoning" });
14982
15213
  var REACT_SYSTEM_PROMPT = `You are a reasoning agent that follows the ReAct (Reasoning and Acting) framework.
14983
15214
  For each step:
14984
15215
  1. Think: Analyze what you know and what you need to find out.
@@ -15228,7 +15459,7 @@ ${query}` }
15228
15459
  return {
15229
15460
  async run(query, options) {
15230
15461
  const strategy = options?.strategy ?? "react";
15231
- logger27.trace("Starting reasoning", { strategy, maxRounds: options?.maxRounds });
15462
+ logger28.trace("Starting reasoning", { strategy, maxRounds: options?.maxRounds });
15232
15463
  try {
15233
15464
  switch (strategy) {
15234
15465
  case "react":
@@ -15243,7 +15474,7 @@ ${query}` }
15243
15474
  }));
15244
15475
  }
15245
15476
  } catch (error) {
15246
- logger27.error("Reasoning failed", { error });
15477
+ logger28.error("Reasoning failed", { error });
15247
15478
  return err(HaiAIError.REASONING_FAILED, aiM("ai_internalError", {
15248
15479
  params: {
15249
15480
  error: String(error)
@@ -15275,7 +15506,7 @@ ${query}` }
15275
15506
  }
15276
15507
  };
15277
15508
  }
15278
- var logger28 = core.logger.child({ module: "ai", scope: "rerank" });
15509
+ var logger29 = core.logger.child({ module: "ai", scope: "rerank" });
15279
15510
  function createRerankOperations(config, loadModels = () => config.llm) {
15280
15511
  function normalizeDocuments(documents) {
15281
15512
  if (documents.length === 0) {
@@ -15320,7 +15551,7 @@ function createRerankOperations(config, loadModels = () => config.llm) {
15320
15551
  if (request2.returnDocuments) {
15321
15552
  body.return_documents = true;
15322
15553
  }
15323
- logger28.trace("Calling rerank API", { model: resolved.model, documentCount: texts.length, topN: request2.topN });
15554
+ logger29.trace("Calling rerank API", { model: resolved.model, documentCount: texts.length, topN: request2.topN });
15324
15555
  try {
15325
15556
  const response = await fetch(`${resolved.baseUrl}/v1/rerank`, {
15326
15557
  method: "POST",
@@ -15335,7 +15566,7 @@ function createRerankOperations(config, loadModels = () => config.llm) {
15335
15566
  const requestId = response.headers.get("x-request-id");
15336
15567
  await response.body?.cancel().catch(() => {
15337
15568
  });
15338
- logger28.error("Rerank API request failed", {
15569
+ logger29.error("Rerank API request failed", {
15339
15570
  status: response.status,
15340
15571
  providerRequestId: requestId && /^[\w.:-]{1,128}$/.test(requestId) ? requestId : void 0
15341
15572
  });
@@ -15350,11 +15581,11 @@ function createRerankOperations(config, loadModels = () => config.llm) {
15350
15581
  relevanceScore: item2.relevance_score,
15351
15582
  document: item2.document?.text
15352
15583
  }));
15353
- logger28.trace("Rerank completed", { resultCount: results.length });
15584
+ logger29.trace("Rerank completed", { resultCount: results.length });
15354
15585
  return ok({ model: resolved.model, results });
15355
15586
  } catch (error) {
15356
15587
  const causeName = error instanceof Error ? error.name : void 0;
15357
- logger28.error("Rerank API call failed", { causeName });
15588
+ logger29.error("Rerank API call failed", { causeName });
15358
15589
  return err(HaiAIError.RERANK_API_ERROR, aiM("ai_rerankApiFailed", {
15359
15590
  params: {
15360
15591
  error: causeName ?? core.i18n.coreM("core_errorInternal")
@@ -15390,7 +15621,7 @@ function createRerankOperations(config, loadModels = () => config.llm) {
15390
15621
  }
15391
15622
  };
15392
15623
  }
15393
- var logger29 = core.logger.child({ module: "ai", scope: "retrieval" });
15624
+ var logger30 = core.logger.child({ module: "ai", scope: "retrieval" });
15394
15625
  function createRetrievalOperations(embeddingOps, storeProvider, sourceStore, rerankOps, registry) {
15395
15626
  const vectorStoreCache = /* @__PURE__ */ new Map();
15396
15627
  function getVectorStore(collection) {
@@ -15423,7 +15654,7 @@ function createRetrievalOperations(embeddingOps, storeProvider, sourceStore, rer
15423
15654
  }));
15424
15655
  }
15425
15656
  await sourceStore.save(source.id, source);
15426
- logger29.debug("Retrieval source added", { sourceId: source.id, collection: source.collection });
15657
+ logger30.debug("Retrieval source added", { sourceId: source.id, collection: source.collection });
15427
15658
  return ok(void 0);
15428
15659
  },
15429
15660
  /**
@@ -15444,7 +15675,7 @@ function createRetrievalOperations(embeddingOps, storeProvider, sourceStore, rer
15444
15675
  }));
15445
15676
  }
15446
15677
  await sourceStore.remove(sourceId);
15447
- logger29.debug("Retrieval source removed", { sourceId });
15678
+ logger30.debug("Retrieval source removed", { sourceId });
15448
15679
  return ok(void 0);
15449
15680
  },
15450
15681
  /**
@@ -15531,21 +15762,21 @@ function createRetrievalOperations(embeddingOps, storeProvider, sourceStore, rer
15531
15762
  allItems.length = 0;
15532
15763
  allItems.push(...reranked);
15533
15764
  } else {
15534
- logger29.warn("Rerank failed, falling back to vector scores", { error: rerankResult.error });
15765
+ logger30.warn("Rerank failed, falling back to vector scores", { error: rerankResult.error });
15535
15766
  }
15536
15767
  }
15537
15768
  allItems.sort((a, b) => b.score - a.score);
15538
15769
  const topK = request2.topK ?? 10;
15539
15770
  const limitedItems = allItems.slice(0, topK);
15540
15771
  const duration = Date.now() - startTime;
15541
- logger29.trace("Retrieval completed", { queryLength: request2.query.length, resultCount: limitedItems.length, duration });
15772
+ logger30.trace("Retrieval completed", { queryLength: request2.query.length, resultCount: limitedItems.length, duration });
15542
15773
  return ok({
15543
15774
  items: limitedItems,
15544
15775
  query: request2.query,
15545
15776
  duration
15546
15777
  });
15547
15778
  } catch (error) {
15548
- logger29.error("Retrieval failed", { error });
15779
+ logger30.error("Retrieval failed", { error });
15549
15780
  return err(HaiAIError.RETRIEVAL_FAILED, aiM("ai_internalError", {
15550
15781
  params: {
15551
15782
  error: String(error)
@@ -15555,7 +15786,7 @@ function createRetrievalOperations(embeddingOps, storeProvider, sourceStore, rer
15555
15786
  }
15556
15787
  };
15557
15788
  }
15558
- var logger30 = core.logger.child({ module: "ai", scope: "summary" });
15789
+ var logger31 = core.logger.child({ module: "ai", scope: "summary" });
15559
15790
  var SUMMARIZE_SYSTEM_PROMPT = `You are a conversation summarizer. Create a concise summary of the conversation that preserves:
15560
15791
  1. Key facts and decisions made
15561
15792
  2. Important context and background information
@@ -15613,7 +15844,7 @@ ${INCREMENTAL_SUMMARIZE_SUFFIX.replace("{previousSummary}", options.previousSumm
15613
15844
  return ok(chatResult.data.choices[0]?.message?.content ?? "");
15614
15845
  }
15615
15846
  async function summarize(messages, options) {
15616
- logger30.trace("Summarizing messages", { messageCount: messages.length });
15847
+ logger31.trace("Summarizing messages", { messageCount: messages.length });
15617
15848
  try {
15618
15849
  const result = await generate(messages, options);
15619
15850
  if (!result.success)
@@ -15625,7 +15856,7 @@ ${INCREMENTAL_SUMMARIZE_SUFFIX.replace("{previousSummary}", options.previousSumm
15625
15856
  coveredMessages: messages.filter((m) => m.role !== "system").length
15626
15857
  });
15627
15858
  } catch (error) {
15628
- logger30.error("Context summarization failed", { error });
15859
+ logger31.error("Context summarization failed", { error });
15629
15860
  return err(HaiAIError.CONTEXT_SUMMARIZE_FAILED, aiM("ai_contextSummarizeFailed", {
15630
15861
  params: {
15631
15862
  error: String(error)
@@ -15693,6 +15924,7 @@ async function createAISubsystems(config, deps) {
15693
15924
  hasScopeIndex: true,
15694
15925
  serializeWrites: true
15695
15926
  });
15927
+ const memoryVectorQueue = memoryStore?.withRelatedWriteLock ? storeProvider.createRelStore("hai_ai_memory_vector_outbox", { hasUpdatedAtIndex: true }) : void 0;
15696
15928
  const contextStore = storeProvider.createRelStore(
15697
15929
  "hai_ai_context",
15698
15930
  { hasObjectId: true, hasSessionId: true }
@@ -15867,13 +16099,8 @@ async function createAISubsystems(config, deps) {
15867
16099
  datapipeDep,
15868
16100
  knowledgeStore
15869
16101
  );
15870
- const memoryCore = memoryStore && memoryVectorStore ? createNativeMemoryOperations(
15871
- memoryParsed,
15872
- llm,
15873
- embedding,
15874
- memoryStore,
15875
- memoryVectorStore
15876
- ) : await createMem0MemoryOperations({
16102
+ const nativeMemory = memoryStore && memoryVectorStore ? assembleNativeMemory(memoryParsed, llm, embedding, memoryStore, memoryVectorStore, memoryVectorQueue) : void 0;
16103
+ const memoryCore = nativeMemory?.operations ?? await createMem0MemoryOperations({
15877
16104
  config: memoryParsed,
15878
16105
  embedding,
15879
16106
  llm,
@@ -15980,10 +16207,12 @@ async function createAISubsystems(config, deps) {
15980
16207
  servers: managedMCPServers,
15981
16208
  services: mcpServices.operations
15982
16209
  });
16210
+ nativeMemory?.sync?.start();
15983
16211
  return {
15984
- closeRegistries: () => {
16212
+ closeRegistries: async () => {
15985
16213
  mcpServices.close();
15986
16214
  registriesOpen = false;
16215
+ await nativeMemory?.sync?.close();
15987
16216
  },
15988
16217
  a2aStores,
15989
16218
  llm,
@@ -16380,7 +16609,7 @@ function documentInfo(document) {
16380
16609
  }
16381
16610
 
16382
16611
  // src/store/providers/ai-store-provider-db.ts
16383
- var logger31 = core.logger.child({ module: "ai", scope: "store-provider-db" });
16612
+ var logger32 = core.logger.child({ module: "ai", scope: "store-provider-db" });
16384
16613
  function requireSqlSuccess(result) {
16385
16614
  if (!result.success)
16386
16615
  throw new Error(result.error.message, { cause: result.error });
@@ -16407,6 +16636,7 @@ function isMysqlDuplicateIndex(error) {
16407
16636
  }
16408
16637
  var ReldbAIRelStore = class _ReldbAIRelStore {
16409
16638
  sql;
16639
+ connection;
16410
16640
  table;
16411
16641
  jsonOps;
16412
16642
  dbType;
@@ -16418,7 +16648,9 @@ var ReldbAIRelStore = class _ReldbAIRelStore {
16418
16648
  hasUpdatedAtIndex;
16419
16649
  gate;
16420
16650
  withWriteLock;
16651
+ withRelatedWriteLock;
16421
16652
  constructor(sql, table, jsonOps, dbType, options, tx) {
16653
+ this.connection = sql;
16422
16654
  this.sql = {
16423
16655
  ...sql,
16424
16656
  execute: (query, params) => sql.execute(query, params).then(requireSqlSuccess),
@@ -16437,12 +16669,28 @@ var ReldbAIRelStore = class _ReldbAIRelStore {
16437
16669
  if (options?.serializeWrites && tx) {
16438
16670
  const gate = `${table}_write_gate`;
16439
16671
  this.gate = gate;
16440
- this.withWriteLock = async (write) => requireSqlSuccess(await tx.wrap(async (connection) => {
16672
+ const lockedWrite = async (write) => requireSqlSuccess(await tx.wrap(async (connection) => {
16441
16673
  const locked = requireSqlSuccess(await connection.execute(`UPDATE ${gate} SET marker = 1 - marker WHERE id = 1`));
16442
16674
  if (locked.data.changes !== 1)
16443
16675
  throw new Error("Missing AI store write gate");
16444
- return write(new _ReldbAIRelStore(connection, table, jsonOps, dbType, options));
16676
+ return write(connection);
16445
16677
  })).data;
16678
+ this.withWriteLock = (write) => lockedWrite((connection) => write(new _ReldbAIRelStore(connection, table, jsonOps, dbType, options)));
16679
+ this.withRelatedWriteLock = (related, write) => {
16680
+ if (!(related instanceof _ReldbAIRelStore) || related.connection !== sql || related.dbType !== dbType || related.jsonOps !== jsonOps)
16681
+ throw new TypeError("Related AI stores must share a database");
16682
+ return lockedWrite((connection) => write(
16683
+ new _ReldbAIRelStore(connection, table, jsonOps, dbType, options),
16684
+ new _ReldbAIRelStore(connection, related.table, jsonOps, dbType, {
16685
+ hasObjectId: related.hasObjectId,
16686
+ hasSessionId: related.hasSessionId,
16687
+ hasStatus: related.hasStatus,
16688
+ hasRefId: related.hasRefId,
16689
+ hasScopeIndex: related.hasScopeIndex,
16690
+ hasUpdatedAtIndex: related.hasUpdatedAtIndex
16691
+ })
16692
+ ));
16693
+ };
16446
16694
  }
16447
16695
  }
16448
16696
  /** 创建表及索引(幂等) */
@@ -16678,7 +16926,7 @@ var ReldbAIRelStore = class _ReldbAIRelStore {
16678
16926
  return count;
16679
16927
  }
16680
16928
  async count(filter) {
16681
- if (!filter?.where && !filter?.objectId && !filter?.sessionId && !filter?.status && !filter?.refId && !filter?.scope && filter?.updatedBefore === void 0) {
16929
+ if (!filter?.where && !filter?.objectId && !filter?.sessionId && !filter?.status && !filter?.refId && !filter?.scope && filter?.updatedBefore === void 0 && filter?.afterId === void 0) {
16682
16930
  const result2 = await this.sql.get(`SELECT COUNT(*) as cnt FROM ${this.table}`);
16683
16931
  return result2.success && result2.data != null ? Number(result2.data.cnt) : 0;
16684
16932
  }
@@ -16691,7 +16939,7 @@ var ReldbAIRelStore = class _ReldbAIRelStore {
16691
16939
  return result.success && result.data != null ? Number(result.data.cnt) : 0;
16692
16940
  }
16693
16941
  async clear(filter) {
16694
- if (!filter?.where && !filter?.objectId && !filter?.sessionId && !filter?.status && !filter?.refId) {
16942
+ if (!filter?.where && !filter?.objectId && !filter?.sessionId && !filter?.status && !filter?.refId && !filter?.scope && filter?.updatedBefore === void 0 && filter?.afterId === void 0) {
16695
16943
  await this.sql.execute(`DELETE FROM ${this.table}`);
16696
16944
  return;
16697
16945
  }
@@ -16766,7 +17014,9 @@ var ReldbAIRelStore = class _ReldbAIRelStore {
16766
17014
  const conditions = this.buildAllConditions(filter, params);
16767
17015
  if (conditions.length > 0)
16768
17016
  sql += ` WHERE ${conditions.join(" AND ")}`;
16769
- if (filter.orderBy) {
17017
+ if (filter.afterId !== void 0) {
17018
+ sql += " ORDER BY id ASC";
17019
+ } else if (filter.orderBy) {
16770
17020
  const dir = filter.orderBy.direction === "asc" ? "ASC" : "DESC";
16771
17021
  const field = String(filter.orderBy.field);
16772
17022
  if (field === "createdAt") {
@@ -16789,6 +17039,10 @@ var ReldbAIRelStore = class _ReldbAIRelStore {
16789
17039
  }
16790
17040
  buildAllConditions(filter, params) {
16791
17041
  const conditions = [];
17042
+ if (filter.afterId !== void 0) {
17043
+ conditions.push("id > ?");
17044
+ params.push(filter.afterId);
17045
+ }
16792
17046
  if (filter.updatedBefore !== void 0) {
16793
17047
  conditions.push("updated_at < ?");
16794
17048
  params.push(filter.updatedBefore);
@@ -16987,7 +17241,7 @@ function createDbStoreProvider(deps) {
16987
17241
  if (result.status === "rejected")
16988
17242
  throw result.reason;
16989
17243
  }
16990
- logger31.debug("DB store provider initialized", { tableCount: relStores.size });
17244
+ logger32.debug("DB store provider initialized", { tableCount: relStores.size });
16991
17245
  }
16992
17246
  },
16993
17247
  async close() {
@@ -17078,8 +17332,15 @@ function matchesRecord(record, filter) {
17078
17332
  }
17079
17333
  function createRelStore(records) {
17080
17334
  function select(filter) {
17081
- let values = Array.from(records.values()).filter((record) => matchesRecord(record, filter)).map((record) => structuredClone(record.data));
17082
- if (filter.orderBy) {
17335
+ const afterId = filter.afterId;
17336
+ let entries = [
17337
+ ...records.entries()
17338
+ ].filter(([id3, record]) => (afterId === void 0 || id3 > afterId) && matchesRecord(record, filter));
17339
+ if (afterId !== void 0) {
17340
+ entries = entries.sort(([left], [right]) => left < right ? -1 : Number(left > right));
17341
+ }
17342
+ let values = entries.map(([, record]) => structuredClone(record.data));
17343
+ if (filter.orderBy && afterId === void 0) {
17083
17344
  const { field, direction } = filter.orderBy;
17084
17345
  const multiplier = direction === "asc" ? 1 : -1;
17085
17346
  values = values.sort((left, right) => compare(left[field], right[field]) * multiplier);
@@ -17151,13 +17412,13 @@ function createRelStore(records) {
17151
17412
  async queryKeys(filter, cursor) {
17152
17413
  return [
17153
17414
  ...records.entries()
17154
- ].filter(([id3, record]) => matchesRecord(record, filter) && (!cursor || record.updatedAt > cursor.updatedAt || record.updatedAt === cursor.updatedAt && id3 > cursor.id)).map(([id3, { updatedAt, version }]) => ({ id: id3, updatedAt, version })).sort((left, right) => left.updatedAt - right.updatedAt || (left.id < right.id ? -1 : Number(left.id > right.id))).slice(0, filter.limit ?? 64);
17415
+ ].filter(([id3, record]) => (filter.afterId === void 0 || id3 > filter.afterId) && matchesRecord(record, filter) && (!cursor || record.updatedAt > cursor.updatedAt || record.updatedAt === cursor.updatedAt && id3 > cursor.id)).map(([id3, { updatedAt, version }]) => ({ id: id3, updatedAt, version })).sort((left, right) => left.updatedAt - right.updatedAt || (left.id < right.id ? -1 : Number(left.id > right.id))).slice(0, filter.limit ?? 64);
17155
17416
  },
17156
17417
  async removeIfUnchanged(id3, version) {
17157
17418
  return records.get(id3)?.version === version && records.delete(id3);
17158
17419
  },
17159
17420
  async removeBy(filter) {
17160
- const ids = Array.from(records.entries()).filter(([, record]) => matchesRecord(record, filter)).map(([id3]) => id3);
17421
+ const ids = Array.from(records.entries()).filter(([id3, record]) => (filter.afterId === void 0 || id3 > filter.afterId) && matchesRecord(record, filter)).map(([id3]) => id3);
17161
17422
  for (const id3 of ids)
17162
17423
  records.delete(id3);
17163
17424
  return ids.length;
@@ -17170,7 +17431,7 @@ function createRelStore(records) {
17170
17431
  records.clear();
17171
17432
  return;
17172
17433
  }
17173
- const ids = Array.from(records.entries()).filter(([, record]) => matchesRecord(record, filter)).map(([id3]) => id3);
17434
+ const ids = Array.from(records.entries()).filter(([id3, record]) => (filter.afterId === void 0 || id3 > filter.afterId) && matchesRecord(record, filter)).map(([id3]) => id3);
17174
17435
  for (const id3 of ids)
17175
17436
  records.delete(id3);
17176
17437
  }
@@ -17260,7 +17521,7 @@ function createMemoryStoreProvider() {
17260
17521
  }
17261
17522
 
17262
17523
  // src/ai-main.ts
17263
- var logger32 = core.logger.child({ module: "ai", scope: "main" });
17524
+ var logger33 = core.logger.child({ module: "ai", scope: "main" });
17264
17525
  var initInProgress = false;
17265
17526
  var initCompletion = null;
17266
17527
  var closingPromise = null;
@@ -17411,7 +17672,7 @@ async function resetAllState() {
17411
17672
  await currentA2AImpl?.close();
17412
17673
  await currentACP?.close();
17413
17674
  currentLLM = null;
17414
- currentRegistriesClose?.();
17675
+ await currentRegistriesClose?.();
17415
17676
  currentRegistriesClose = null;
17416
17677
  currentACP = null;
17417
17678
  currentMCP = null;
@@ -17439,7 +17700,7 @@ async function resetAllState() {
17439
17700
  try {
17440
17701
  await storeProvider.close();
17441
17702
  } catch (error) {
17442
- logger32.error("AI store provider close failed", { error });
17703
+ logger33.error("AI store provider close failed", { error });
17443
17704
  }
17444
17705
  }
17445
17706
  }
@@ -17456,7 +17717,7 @@ var streamOperations = {
17456
17717
  var ai = {
17457
17718
  async init(config, options) {
17458
17719
  if (initInProgress || closingPromise) {
17459
- logger32.warn("AI init already in progress, skipping concurrent call");
17720
+ logger33.warn("AI init already in progress, skipping concurrent call");
17460
17721
  return err(HaiAIError.INIT_IN_PROGRESS, aiM("ai_initInProgress"));
17461
17722
  }
17462
17723
  initInProgress = true;
@@ -17467,15 +17728,15 @@ var ai = {
17467
17728
  let closingPrevious = false;
17468
17729
  try {
17469
17730
  if (currentConfig) {
17470
- logger32.warn("AI module is already initialized, reinitializing");
17731
+ logger33.warn("AI module is already initialized, reinitializing");
17471
17732
  closingPrevious = true;
17472
17733
  await resetAllState();
17473
17734
  closingPrevious = false;
17474
17735
  }
17475
- logger32.info("Initializing AI module");
17736
+ logger33.info("Initializing AI module");
17476
17737
  const parseResult = AIConfigSchema.safeParse(config ?? {});
17477
17738
  if (!parseResult.success) {
17478
- logger32.error("AI config validation failed", { error: parseResult.error.message });
17739
+ logger33.error("AI config validation failed", { error: parseResult.error.message });
17479
17740
  return err(
17480
17741
  HaiAIError.CONFIGURATION_ERROR,
17481
17742
  aiM("ai_configError", {
@@ -17492,7 +17753,7 @@ var ai = {
17492
17753
  storeProvider = createDbStoreProviderFromModules();
17493
17754
  } else {
17494
17755
  storeProvider = createMemoryStoreProvider();
17495
- logger32.warn("AI is using the ephemeral in-memory store; initialize reldb and vecdb before ai.init() for persistent data");
17756
+ logger33.warn("AI is using the ephemeral in-memory store; initialize reldb and vecdb before ai.init() for persistent data");
17496
17757
  }
17497
17758
  if (core.module.requiresSharedState(process2.env) && storeProvider.stateScope !== "shared")
17498
17759
  return err(HaiAIError.CONFIGURATION_ERROR, aiM("ai_sharedBackendRequired"));
@@ -17528,17 +17789,17 @@ var ai = {
17528
17789
  currentA2AConfig = parsed.a2a;
17529
17790
  currentA2AStores = subs.a2aStores;
17530
17791
  currentConfig = parsed;
17531
- logger32.info("AI module initialized", { model: parsed.llm?.model });
17792
+ logger33.info("AI module initialized", { model: parsed.llm?.model });
17532
17793
  return ok(void 0);
17533
17794
  } catch (error) {
17534
17795
  if (!closingPrevious) {
17535
17796
  try {
17536
17797
  await resetAllState();
17537
17798
  } catch (cleanupError) {
17538
- logger32.error("AI initialization cleanup failed", { error: cleanupError });
17799
+ logger33.error("AI initialization cleanup failed", { error: cleanupError });
17539
17800
  }
17540
17801
  }
17541
- logger32.error("AI module initialization failed", { error });
17802
+ logger33.error("AI module initialization failed", { error });
17542
17803
  return err(
17543
17804
  HaiAIError.CONFIGURATION_ERROR,
17544
17805
  aiM("ai_initFailed", {
@@ -17628,9 +17889,9 @@ var ai = {
17628
17889
  closingPromise = (async () => {
17629
17890
  if (initCompletion)
17630
17891
  await initCompletion;
17631
- logger32.info("Closing AI module");
17892
+ logger33.info("Closing AI module");
17632
17893
  await resetAllState();
17633
- logger32.info("AI module closed");
17894
+ logger33.info("AI module closed");
17634
17895
  })().finally(() => {
17635
17896
  closingPromise = null;
17636
17897
  });