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

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(core35, 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) => core35.extract(messages, { ...options, objectId, scope }),
12925
+ recall: (query, options) => core35.recall(query, { ...options, objectId, scope }),
12926
+ injectMemories: (messages, options) => core35.injectMemories(messages, { ...options, objectId, scope }),
12927
+ add: (entry) => core35.add({ ...entry, objectId, scope }),
12928
+ update: (memoryId, updates) => core35.update(memoryId, updates, accessScope),
12929
+ get: (memoryId) => core35.get(memoryId, accessScope),
12930
+ remove: (memoryId) => core35.remove(memoryId, accessScope),
12931
+ list: (options) => core35.list({ ...options, objectId, scope }),
12932
+ listPage: (options) => core35.listPage({ ...options, objectId, scope }),
12933
+ clear: (options) => core35.clear({ ...options, objectId, scope })
12918
12934
  };
12919
12935
  }
12920
- function createMemoryOperations(core33) {
12936
+ function createMemoryOperations(core35) {
12921
12937
  return {
12922
- ...core33,
12938
+ ...core35,
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 core35.clear(options);
12937
12953
  },
12938
- scoped: (binding) => createScopedMemory(core33, binding),
12954
+ scoped: (binding) => createScopedMemory(core35, 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 core35.clear();
12945
12961
  }
12946
12962
  }
12947
12963
  };
@@ -14168,13 +14184,267 @@ 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-scan" });
14188
+ var checkpointId = "scan";
14189
+ var pageSize = 64;
14190
+ var pollMs = 1e3;
14191
+ var roundPauseMs = 5e3;
14192
+ var failureRetryMs = 2e3;
14193
+ var leaseMs = 9e4;
14194
+ function createMemoryVectorScan(memory, state, vectors) {
14195
+ const currentIds = memory.getMemoryVectorIds?.bind(memory);
14196
+ const scan = vectors.scan?.bind(vectors);
14197
+ const remove = vectors.removeMany?.bind(vectors);
14198
+ if (!currentIds || !scan || !remove)
14199
+ return void 0;
14200
+ const lockedWrite = state.withWriteLock?.bind(state);
14201
+ const write = lockedWrite ?? ((update) => update(state));
14202
+ let timer;
14203
+ let active;
14204
+ let nextCheck = 0;
14205
+ const run = async () => {
14206
+ const now = await state.currentTime();
14207
+ const record = await state.readVersioned(checkpointId);
14208
+ if (record && record.data.updatedAt > now) {
14209
+ nextCheck = performance.now() + Math.min(record.data.updatedAt - now, roundPauseMs);
14210
+ return;
14211
+ }
14212
+ const claim = await write(async (checkpoint) => {
14213
+ const current = lockedWrite ? await checkpoint.readVersioned(checkpointId) : record;
14214
+ const claimedAt = lockedWrite ? await checkpoint.currentTime() : now;
14215
+ if (current && current.data.updatedAt > claimedAt) {
14216
+ nextCheck = performance.now() + Math.min(current.data.updatedAt - claimedAt, roundPauseMs);
14217
+ return void 0;
14218
+ }
14219
+ const cursor2 = current?.data.cursor;
14220
+ const deadline2 = claimedAt + leaseMs;
14221
+ const version2 = await checkpoint.compareAndSwap(checkpointId, {
14222
+ expectedVersion: current?.version,
14223
+ data: { cursor: cursor2, updatedAt: deadline2 }
14224
+ });
14225
+ return version2 ? { cursor: cursor2, version: version2, deadline: deadline2 } : void 0;
14226
+ });
14227
+ if (!claim) {
14228
+ nextCheck = Math.max(nextCheck, performance.now() + pollMs);
14229
+ return;
14230
+ }
14231
+ const { cursor, version, deadline } = claim;
14232
+ let nextCursor = cursor;
14233
+ let retryIn = failureRetryMs;
14234
+ try {
14235
+ const page = await scan({ cursor, limit: pageSize });
14236
+ if (page.items.length > pageSize || cursor !== void 0 && page.nextCursor === cursor)
14237
+ throw new Error("Invalid memory vector scan page");
14238
+ const ids = [
14239
+ ...new Set(page.items.map((point) => point.id))
14240
+ ];
14241
+ if (ids.length) {
14242
+ const current = new Set(await currentIds(ids));
14243
+ const obsolete = ids.filter((id3) => !current.has(id3));
14244
+ if (obsolete.length)
14245
+ await remove(obsolete);
14246
+ }
14247
+ nextCursor = page.nextCursor;
14248
+ retryIn = nextCursor === void 0 ? roundPauseMs : 0;
14249
+ } catch {
14250
+ logger24.warn("Memory vector scan page will retry");
14251
+ }
14252
+ await write(async (checkpoint) => {
14253
+ const completedAt = await checkpoint.currentTime();
14254
+ await checkpoint.compareAndSwap(checkpointId, {
14255
+ expectedVersion: version,
14256
+ data: { cursor: nextCursor, updatedAt: completedAt + retryIn },
14257
+ notAfter: deadline
14258
+ });
14259
+ });
14260
+ nextCheck = performance.now() + retryIn;
14261
+ };
14262
+ function kick() {
14263
+ if (active || performance.now() < nextCheck)
14264
+ return;
14265
+ active = run().catch(() => {
14266
+ nextCheck = performance.now() + failureRetryMs;
14267
+ logger24.warn("Memory vector scan checkpoint unavailable");
14268
+ }).finally(() => {
14269
+ active = void 0;
14270
+ });
14271
+ }
14272
+ return {
14273
+ start() {
14274
+ timer ??= setInterval(kick, pollMs);
14275
+ timer.unref();
14276
+ kick();
14277
+ },
14278
+ async close() {
14279
+ clearInterval(timer);
14280
+ timer = void 0;
14281
+ await active;
14282
+ }
14283
+ };
14284
+ }
14285
+
14286
+ // src/memory/ai-memory-vector-sync.ts
14287
+ var logger25 = core.logger.child({ module: "ai", scope: "memory-vector-sync" });
14288
+ var pollMs2 = 1e3;
14289
+ var inFlightRetryMs = 45e3;
14290
+ var lateWriteWindowMs = 6e4;
14291
+ var batchSize2 = 16;
14292
+ function backoff(attempts) {
14293
+ return Math.min(3e4, 1e3 * 2 ** Math.min(Math.max(attempts - 1, 0), 5));
14294
+ }
14295
+ function vectorId(memory) {
14296
+ return memory.vectorId ?? memory.id;
14297
+ }
14298
+ function createMemoryVectorSync(store, queue, vectors, scanStore) {
14299
+ const lock = store.withRelatedWriteLock?.bind(store);
14300
+ if (!lock || !queue.queryKeys)
14301
+ return void 0;
14302
+ const scan = scanStore && createMemoryVectorScan(store, scanStore, vectors);
14303
+ function write(run) {
14304
+ return lock(queue, run);
14305
+ }
14306
+ let active;
14307
+ let timer;
14308
+ async function reconcile(id3) {
14309
+ const claimed = await write(async (memory, pending) => {
14310
+ const job = await pending.get(id3);
14311
+ if (!job)
14312
+ return void 0;
14313
+ const now = await pending.currentTime();
14314
+ if (job.updatedAt > now)
14315
+ return void 0;
14316
+ const entry = await memory.get(job.memoryId);
14317
+ const current = entry?.vector && vectorId(entry) === id3 ? entry : void 0;
14318
+ if (current && job.cooldown) {
14319
+ await pending.remove(id3);
14320
+ return void 0;
14321
+ }
14322
+ const token = randomUUID();
14323
+ const next = {
14324
+ ...job,
14325
+ token,
14326
+ attempts: job.attempts + 1,
14327
+ updatedAt: now + inFlightRetryMs
14328
+ };
14329
+ await pending.save(id3, next);
14330
+ return { ...next, entry: current };
14331
+ });
14332
+ if (!claimed)
14333
+ return;
14334
+ let succeeded = false;
14335
+ try {
14336
+ if (claimed.entry?.vector) {
14337
+ await vectors.upsert(id3, claimed.entry.vector, {
14338
+ objectId: claimed.entry.objectId,
14339
+ type: claimed.entry.type
14340
+ });
14341
+ } else {
14342
+ await vectors.remove(id3);
14343
+ }
14344
+ succeeded = true;
14345
+ } catch {
14346
+ logger25.debug("Memory vector sync will retry", {
14347
+ operation: claimed.entry ? "upsert" : "delete"
14348
+ });
14349
+ }
14350
+ await write(async (_memory, pending) => {
14351
+ const job = await pending.get(id3);
14352
+ if (!job || job.token !== claimed.token)
14353
+ return;
14354
+ const now = await pending.currentTime();
14355
+ if (scan && !claimed.entry) {
14356
+ await pending.remove(id3);
14357
+ return;
14358
+ }
14359
+ if (!scan && succeeded && claimed.entry && job.attempts > 1) {
14360
+ await pending.save(id3, {
14361
+ ...job,
14362
+ token: void 0,
14363
+ cooldown: true,
14364
+ updatedAt: now + lateWriteWindowMs
14365
+ });
14366
+ return;
14367
+ }
14368
+ if (succeeded && (scan || !job.retireUntil || job.retireUntil <= now)) {
14369
+ await pending.remove(id3);
14370
+ return;
14371
+ }
14372
+ const delay3 = backoff(job.attempts);
14373
+ await pending.save(id3, {
14374
+ ...job,
14375
+ token: void 0,
14376
+ updatedAt: job.retireUntil && succeeded ? Math.min(now + delay3, job.retireUntil) : now + delay3
14377
+ });
14378
+ });
14379
+ }
14380
+ async function drain() {
14381
+ const now = await queue.currentTime();
14382
+ const due = await queue.queryKeys({ updatedBefore: now + 1, limit: batchSize2 });
14383
+ for (const { id: id3 } of due) {
14384
+ if (!timer)
14385
+ return;
14386
+ await reconcile(id3);
14387
+ }
14388
+ }
14389
+ function kick() {
14390
+ if (timer && !active) {
14391
+ active = drain().catch(() => {
14392
+ logger25.warn("Memory vector compensation storage unavailable");
14393
+ }).finally(() => {
14394
+ active = void 0;
14395
+ });
14396
+ }
14397
+ }
14398
+ return {
14399
+ write,
14400
+ kick,
14401
+ start() {
14402
+ if (!timer) {
14403
+ timer = setInterval(kick, pollMs2);
14404
+ timer.unref();
14405
+ kick();
14406
+ scan?.start();
14407
+ }
14408
+ },
14409
+ async close() {
14410
+ clearInterval(timer);
14411
+ timer = void 0;
14412
+ await Promise.all([
14413
+ active,
14414
+ scan?.close()
14415
+ ]);
14416
+ },
14417
+ async enqueue(pending, entry) {
14418
+ const now = await pending.currentTime();
14419
+ await pending.save(vectorId(entry), { memoryId: entry.id, updatedAt: now, attempts: 0 });
14420
+ },
14421
+ async retire(pending, entry) {
14422
+ const id3 = vectorId(entry);
14423
+ const prior = await pending.get(id3);
14424
+ if (prior?.attempts === 0) {
14425
+ await pending.remove(id3);
14426
+ return;
14427
+ }
14428
+ const now = await pending.currentTime();
14429
+ await pending.save(id3, {
14430
+ memoryId: entry.id,
14431
+ updatedAt: now,
14432
+ attempts: 0,
14433
+ ...!scan && prior && { retireUntil: now + lateWriteWindowMs }
14434
+ });
14435
+ }
14436
+ };
14437
+ }
14171
14438
 
14172
14439
  // src/memory/providers/ai-memory-provider-native.ts
14173
- var logger24 = core.logger.child({ module: "ai", scope: "memory-native" });
14440
+ var logger26 = core.logger.child({ module: "ai", scope: "memory-native" });
14174
14441
  var EVICTION_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1e3;
14175
14442
  var EVICTION_CANDIDATES = 64;
14176
14443
  function generateId() {
14177
- return `mem_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`;
14444
+ return `mem_${randomUUID()}`;
14445
+ }
14446
+ function publicEntry({ vectorId: _vectorId, ...entry }) {
14447
+ return entry;
14178
14448
  }
14179
14449
  function cosineSimilarity(a, b) {
14180
14450
  if (a.length !== b.length)
@@ -14195,12 +14465,27 @@ function matchScope2(entry, scope) {
14195
14465
  return false;
14196
14466
  return Object.entries(scope).every(([k, v]) => entry.scope[k] === v);
14197
14467
  }
14198
- function createNativeMemoryOperations(config, llm, embedding, store, vectorStore) {
14468
+ function assembleNativeMemory(config, llm, embedding, store, vectorStore, vectorQueue, vectorScan) {
14469
+ const sync = vectorQueue && createMemoryVectorSync(store, vectorQueue, vectorStore, vectorScan);
14470
+ const maxPending = Math.max(1024, config.maxEntriesGlobal * 2);
14471
+ async function ensureVectorCapacity(pending) {
14472
+ if (pending && await pending.count() >= maxPending)
14473
+ throw new Error("Memory vector synchronization backlog is full");
14474
+ }
14475
+ async function deleteEntry(activeStore, entry, pending) {
14476
+ if (sync && pending) {
14477
+ if (entry.vector)
14478
+ await sync.retire(pending, entry);
14479
+ } else {
14480
+ await vectorStore.remove(entry.id);
14481
+ }
14482
+ return activeStore.remove(entry.id);
14483
+ }
14199
14484
  async function protect(operation) {
14200
14485
  try {
14201
14486
  return await operation();
14202
14487
  } catch (error) {
14203
- logger24.error("Memory storage operation failed", {
14488
+ logger26.error("Memory storage operation failed", {
14204
14489
  error: core.sanitize.sanitizeSensitiveFields(error)
14205
14490
  });
14206
14491
  return err(HaiAIError.MEMORY_STORE_FAILED, aiM("ai_memoryOperationFailed"));
@@ -14232,23 +14517,21 @@ function createNativeMemoryOperations(config, llm, embedding, store, vectorStore
14232
14517
  const result = await embedding.embedText(text);
14233
14518
  if (result.success)
14234
14519
  return result.data;
14235
- logger24.warn("Failed to compute embedding for memory", { error: result.error });
14520
+ logger26.warn("Failed to compute embedding for memory", { error: result.error });
14236
14521
  return void 0;
14237
14522
  }
14238
- async function evictLowest(activeStore, candidates, count) {
14523
+ async function evictLowest(activeStore, candidates, count, pending) {
14239
14524
  const now = Date.now();
14240
14525
  const ranked = candidates.map((entry) => {
14241
14526
  const age = now - entry.createdAt;
14242
14527
  const recency = Math.max(0, 1 - age / EVICTION_MAX_AGE_MS);
14243
- return { id: entry.id, score: entry.importance * 0.7 + recency * 0.3 };
14528
+ return { entry, score: entry.importance * 0.7 + recency * 0.3 };
14244
14529
  }).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
- }
14530
+ for (const { entry } of ranked)
14531
+ await deleteEntry(activeStore, entry, pending);
14249
14532
  return ranked.length;
14250
14533
  }
14251
- async function evictIfNeeded(activeStore, objectId) {
14534
+ async function evictIfNeeded(activeStore, objectId, pending) {
14252
14535
  if (objectId) {
14253
14536
  const objectTotal = await activeStore.count({ objectId });
14254
14537
  if (objectTotal >= config.maxEntriesPerObject) {
@@ -14258,7 +14541,7 @@ function createNativeMemoryOperations(config, llm, embedding, store, vectorStore
14258
14541
  limit: EVICTION_CANDIDATES
14259
14542
  });
14260
14543
  const needed = objectTotal - config.maxEntriesPerObject + 1;
14261
- if (await evictLowest(activeStore, objectEntries, needed) < needed)
14544
+ if (await evictLowest(activeStore, objectEntries, needed, pending) < needed)
14262
14545
  return false;
14263
14546
  }
14264
14547
  }
@@ -14269,12 +14552,17 @@ function createNativeMemoryOperations(config, llm, embedding, store, vectorStore
14269
14552
  limit: EVICTION_CANDIDATES
14270
14553
  });
14271
14554
  const needed = globalTotal - config.maxEntriesGlobal + 1;
14272
- return await evictLowest(activeStore, candidates, needed) >= needed;
14555
+ return await evictLowest(activeStore, candidates, needed, pending) >= needed;
14273
14556
  }
14274
14557
  return true;
14275
14558
  }
14276
14559
  let localWrites = Promise.resolve();
14277
- function writeMemory(write) {
14560
+ async function writeMemory(write) {
14561
+ if (sync) {
14562
+ const written = await sync.write(write);
14563
+ sync.kick();
14564
+ return written;
14565
+ }
14278
14566
  if (store.withWriteLock)
14279
14567
  return store.withWriteLock(write);
14280
14568
  const pending = localWrites.then(() => write(store));
@@ -14298,51 +14586,81 @@ function createNativeMemoryOperations(config, llm, embedding, store, vectorStore
14298
14586
  lastAccessedAt: now,
14299
14587
  accessCount: 0
14300
14588
  };
14301
- return writeMemory(async (activeStore) => {
14302
- if (!await evictIfNeeded(activeStore, input.objectId))
14589
+ return writeMemory(async (activeStore, pending) => {
14590
+ await ensureVectorCapacity(pending);
14591
+ if (!await evictIfNeeded(activeStore, input.objectId, pending))
14303
14592
  return void 0;
14593
+ if (sync && pending && vector) {
14594
+ entry.vectorId = randomUUID();
14595
+ await sync.enqueue(pending, entry);
14596
+ }
14304
14597
  await activeStore.save(entry.id, entry, { objectId: entry.objectId });
14305
14598
  if (vector) {
14306
- await vectorStore.upsert(entry.id, vector, { objectId: entry.objectId, type: entry.type });
14599
+ if (!pending)
14600
+ await vectorStore.upsert(entry.id, vector, { objectId: entry.objectId, type: entry.type });
14307
14601
  }
14308
- return entry;
14602
+ return publicEntry(entry);
14309
14603
  });
14310
14604
  }
14311
14605
  async function updateEntry(memoryId, updates, accessScope) {
14312
14606
  try {
14313
- const record = await store.readVersioned(memoryId);
14314
- if (!record || isMemoryAccessDenied(record.data, accessScope)) {
14607
+ const before = await store.get(memoryId);
14608
+ if (!before || isMemoryAccessDenied(before, accessScope)) {
14315
14609
  return err(HaiAIError.MEMORY_NOT_FOUND, aiM("ai_memoryNotFound", {
14316
14610
  params: { id: memoryId }
14317
14611
  }));
14318
14612
  }
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 });
14613
+ const vector = updates.content !== void 0 ? await computeVector(updates.content) : void 0;
14614
+ const existing = await writeMemory(async (active, pending) => {
14615
+ const record = await active.readVersioned(memoryId);
14616
+ if (!record || isMemoryAccessDenied(record.data, accessScope))
14617
+ return void 0;
14618
+ const previous = record.data;
14619
+ const changed = {
14620
+ ...previous,
14621
+ ...updates.type !== void 0 && { type: updates.type },
14622
+ ...updates.importance !== void 0 && { importance: updates.importance },
14623
+ ...updates.metadata !== void 0 && { metadata: updates.metadata },
14624
+ ...updates.content !== void 0 && { content: updates.content },
14625
+ ...updates.content !== void 0 && { vector }
14626
+ };
14627
+ const changesVector = updates.content !== void 0 || updates.type !== void 0 && updates.type !== previous.type;
14628
+ if (changesVector && sync && pending) {
14629
+ if (previous.vector)
14630
+ await sync.retire(pending, previous);
14631
+ changed.vectorId = changed.vector ? randomUUID() : void 0;
14632
+ if (changed.vector) {
14633
+ await ensureVectorCapacity(pending);
14634
+ await sync.enqueue(pending, changed);
14635
+ }
14636
+ }
14637
+ if (!await active.compareAndSwap(memoryId, {
14638
+ expectedVersion: record.version,
14639
+ data: changed,
14640
+ scope: { objectId: changed.objectId }
14641
+ })) {
14642
+ throw new Error("Memory was concurrently changed or deleted");
14643
+ }
14644
+ if (changesVector && !pending) {
14645
+ if (changed.vector)
14646
+ await vectorStore.upsert(memoryId, changed.vector, { objectId: changed.objectId, type: changed.type });
14647
+ else if (previous.vector)
14648
+ await vectorStore.remove(memoryId);
14649
+ }
14650
+ return publicEntry(changed);
14651
+ });
14652
+ if (!existing) {
14653
+ return err(HaiAIError.MEMORY_NOT_FOUND, aiM("ai_memoryNotFound", {
14654
+ params: { id: memoryId }
14655
+ }));
14341
14656
  }
14342
- logger24.trace("Memory updated", { id: memoryId });
14657
+ logger26.trace("Memory updated", { id: memoryId });
14343
14658
  return ok(existing);
14344
14659
  } catch (error) {
14345
- logger24.error("Memory update failed", { id: memoryId, error });
14660
+ logger26.error("Memory update failed", {
14661
+ id: memoryId,
14662
+ error: core.sanitize.sanitizeSensitiveFields(error)
14663
+ });
14346
14664
  return err(HaiAIError.MEMORY_STORE_FAILED, aiM("ai_memoryOperationFailed"));
14347
14665
  }
14348
14666
  }
@@ -14350,7 +14668,7 @@ function createNativeMemoryOperations(config, llm, embedding, store, vectorStore
14350
14668
  const topK = options?.topK ?? config.defaultTopK;
14351
14669
  const recencyWeight = options?.recencyWeight ?? 1 - config.recencyDecay;
14352
14670
  const candidateMultiplier = Math.max(1, options?.candidateMultiplier ?? config.candidateMultiplier);
14353
- logger24.trace("Recalling memories", {
14671
+ logger26.trace("Recalling memories", {
14354
14672
  query: query.slice(0, 100),
14355
14673
  topK,
14356
14674
  updateAccessStats
@@ -14384,17 +14702,22 @@ function createNativeMemoryOperations(config, llm, embedding, store, vectorStore
14384
14702
  }
14385
14703
  const vectorScores = /* @__PURE__ */ new Map();
14386
14704
  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);
14705
+ try {
14706
+ const vectorResults = await vectorStore.search(queryVector, {
14707
+ topK: topK * candidateMultiplier,
14708
+ filter: options?.objectId ? { objectId: options.objectId } : void 0
14709
+ });
14710
+ for (const r of vectorResults)
14711
+ vectorScores.set(r.id, r.score);
14712
+ } catch (error) {
14713
+ if (!sync)
14714
+ throw error;
14715
+ logger26.debug("Memory vector search unavailable; using persisted embeddings");
14393
14716
  }
14394
14717
  }
14395
14718
  const now = Date.now();
14396
14719
  const scored = candidates.map((entry) => {
14397
- let similarity = vectorScores.get(entry.id) ?? 0;
14720
+ let similarity = entry.vector ? vectorScores.get(entry.vectorId ?? entry.id) ?? 0 : 0;
14398
14721
  if (!similarity && queryVector && entry.vector) {
14399
14722
  similarity = cosineSimilarity(queryVector, entry.vector);
14400
14723
  } else if (!similarity) {
@@ -14414,19 +14737,19 @@ function createNativeMemoryOperations(config, llm, embedding, store, vectorStore
14414
14737
  if (updateAccessStats) {
14415
14738
  const updated = await touchEntry(entry.id, options?.objectId ? { objectId: options.objectId, scope: options.scope } : void 0);
14416
14739
  if (updated && (!options?.scope || matchScope2(updated, options.scope)) && (!options?.types?.length || options.types.includes(updated.type)))
14417
- results.push(updated);
14740
+ results.push(publicEntry(updated));
14418
14741
  continue;
14419
14742
  }
14420
- results.push({ ...entry });
14743
+ results.push(publicEntry(entry));
14421
14744
  }
14422
- logger24.trace("Memory recall completed", {
14745
+ logger26.trace("Memory recall completed", {
14423
14746
  query: query.slice(0, 50),
14424
14747
  resultCount: results.length,
14425
14748
  updateAccessStats
14426
14749
  });
14427
14750
  return ok(results);
14428
14751
  } catch (error) {
14429
- logger24.error("Memory recall failed", {
14752
+ logger26.error("Memory recall failed", {
14430
14753
  error: core.sanitize.sanitizeSensitiveFields(error)
14431
14754
  });
14432
14755
  return err(HaiAIError.MEMORY_RECALL_FAILED, aiM("ai_memoryOperationFailed"));
@@ -14478,10 +14801,10 @@ function createNativeMemoryOperations(config, llm, embedding, store, vectorStore
14478
14801
  const stored = await saveEntry(entry, vector);
14479
14802
  if (!stored)
14480
14803
  return err(HaiAIError.MEMORY_STORE_FAILED, aiM("ai_memoryOperationFailed"));
14481
- logger24.trace("Memory added", { id: stored.id, type: stored.type });
14804
+ logger26.trace("Memory added", { id: stored.id, type: stored.type });
14482
14805
  return ok(stored);
14483
14806
  } catch (error) {
14484
- logger24.error("Memory add failed", {
14807
+ logger26.error("Memory add failed", {
14485
14808
  error: core.sanitize.sanitizeSensitiveFields(error)
14486
14809
  });
14487
14810
  return err(HaiAIError.MEMORY_STORE_FAILED, aiM("ai_memoryOperationFailed"));
@@ -14507,7 +14830,7 @@ function createNativeMemoryOperations(config, llm, embedding, store, vectorStore
14507
14830
  params: { id: memoryId }
14508
14831
  }));
14509
14832
  }
14510
- return ok(entry);
14833
+ return ok(publicEntry(entry));
14511
14834
  },
14512
14835
  /**
14513
14836
  * 根据 ID 删除一条记忆(同时清理关系存储与向量库)
@@ -14517,20 +14840,18 @@ function createNativeMemoryOperations(config, llm, embedding, store, vectorStore
14517
14840
  * @returns `ok(undefined)` 删除成功;ID 不存在或归属不符时返回 `MEMORY_NOT_FOUND`
14518
14841
  */
14519
14842
  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);
14843
+ const removed2 = await writeMemory(async (active, pending) => {
14844
+ const existing = await active.get(memoryId);
14845
+ if (!existing || isMemoryAccessDenied(existing, accessScope))
14846
+ return false;
14847
+ return deleteEntry(active, existing, pending);
14848
+ });
14528
14849
  if (!removed2) {
14529
14850
  return err(HaiAIError.MEMORY_NOT_FOUND, aiM("ai_memoryNotFound", {
14530
14851
  params: { id: memoryId }
14531
14852
  }));
14532
14853
  }
14533
- logger24.trace("Memory removed", { id: memoryId });
14854
+ logger26.trace("Memory removed", { id: memoryId });
14534
14855
  return ok(void 0);
14535
14856
  },
14536
14857
  /**
@@ -14556,9 +14877,9 @@ function createNativeMemoryOperations(config, llm, embedding, store, vectorStore
14556
14877
  limit: options?.scope ? void 0 : options?.limit
14557
14878
  });
14558
14879
  if (!options?.scope)
14559
- return ok(results);
14880
+ return ok(results.map(publicEntry));
14560
14881
  const filtered = results.filter((e) => matchScope2(e, options.scope));
14561
- return ok(options.limit ? filtered.slice(0, options.limit) : filtered);
14882
+ return ok((options.limit ? filtered.slice(0, options.limit) : filtered).map(publicEntry));
14562
14883
  },
14563
14884
  /**
14564
14885
  * 分页列出记忆条目
@@ -14586,7 +14907,10 @@ function createNativeMemoryOperations(config, llm, embedding, store, vectorStore
14586
14907
  },
14587
14908
  { offset, limit }
14588
14909
  );
14589
- return ok(page);
14910
+ return ok({
14911
+ ...page,
14912
+ items: page.items.map(publicEntry)
14913
+ });
14590
14914
  }
14591
14915
  const all = await store.query({
14592
14916
  objectId: options?.objectId,
@@ -14596,7 +14920,7 @@ function createNativeMemoryOperations(config, llm, embedding, store, vectorStore
14596
14920
  });
14597
14921
  const filtered = all.filter((e) => matchScope2(e, options.scope));
14598
14922
  return ok({
14599
- items: filtered.slice(offset, offset + limit),
14923
+ items: filtered.slice(offset, offset + limit).map(publicEntry),
14600
14924
  total: filtered.length
14601
14925
  });
14602
14926
  },
@@ -14610,46 +14934,62 @@ function createNativeMemoryOperations(config, llm, embedding, store, vectorStore
14610
14934
  * @returns `ok(undefined)` 操作成功
14611
14935
  */
14612
14936
  async clear(options) {
14613
- if (!options?.types && !options?.objectId && !options?.scope) {
14937
+ if (!sync && !options?.types && !options?.objectId && !options?.scope) {
14614
14938
  await vectorStore.clear();
14615
14939
  await store.clear();
14616
- logger24.debug("All memories cleared");
14940
+ logger26.debug("All memories cleared");
14617
14941
  return ok(void 0);
14618
14942
  }
14619
14943
  const where = {};
14620
- if (options.types && options.types.length === 1)
14944
+ if (options?.types && options.types.length === 1)
14621
14945
  where.type = options.types[0];
14622
- else if (options.types && options.types.length > 1)
14946
+ else if (options?.types && options.types.length > 1)
14623
14947
  where.type = { $in: options.types };
14624
- const candidates = await store.query({
14625
- objectId: options.objectId,
14626
- scope: options.scope,
14948
+ const filter = {
14949
+ objectId: options?.objectId,
14950
+ scope: options?.scope,
14627
14951
  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);
14952
+ };
14953
+ const scope = options?.scope;
14954
+ let removed2 = 0;
14955
+ let afterId = "";
14956
+ while (true) {
14957
+ const batch = await writeMemory(async (active, pending) => {
14958
+ const rows = await active.query(sync ? { ...filter, afterId, limit: EVICTION_CANDIDATES } : filter);
14959
+ const selected = scope ? rows.filter((e) => matchScope2(e, scope)) : rows;
14960
+ for (const entry of selected)
14961
+ await deleteEntry(active, entry, pending);
14962
+ return { nextId: rows.at(-1)?.id, total: rows.length, selected: selected.length };
14963
+ });
14964
+ removed2 += batch.selected;
14965
+ if (!sync || batch.total < EVICTION_CANDIDATES || !batch.nextId)
14966
+ break;
14967
+ if (batch.nextId === afterId)
14968
+ throw new Error("Memory store did not advance the primary-key cursor");
14969
+ afterId = batch.nextId;
14633
14970
  }
14634
- logger24.debug("Memories cleared", {
14635
- removed: toRemove.length,
14636
- objectId: options.objectId,
14637
- types: options.types,
14638
- scoped: Boolean(options.scope)
14971
+ logger26.debug("Memories cleared", {
14972
+ removed: removed2,
14973
+ objectId: options?.objectId,
14974
+ types: options?.types,
14975
+ scoped: Boolean(scope)
14639
14976
  });
14640
14977
  return ok(void 0);
14641
14978
  }
14642
14979
  };
14643
14980
  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))
14981
+ sync,
14982
+ operations: {
14983
+ ...operations2,
14984
+ get: (id3, scope) => protect(() => operations2.get(id3, scope)),
14985
+ remove: (id3, scope) => protect(() => operations2.remove(id3, scope)),
14986
+ list: (options) => protect(() => operations2.list(options)),
14987
+ listPage: (options) => protect(() => operations2.listPage(options)),
14988
+ clear: (options) => protect(() => operations2.clear(options))
14989
+ }
14650
14990
  };
14651
14991
  }
14652
- var logger25 = core.logger.child({ module: "ai", scope: "persona" });
14992
+ var logger27 = core.logger.child({ module: "ai", scope: "persona" });
14653
14993
  var DEFAULT_OBJECT_ID2 = "system";
14654
14994
  function personaKey(objectId, id3) {
14655
14995
  return JSON.stringify([objectId, id3]);
@@ -14668,7 +15008,7 @@ function createPersonaOperations(store) {
14668
15008
  try {
14669
15009
  return await operation();
14670
15010
  } catch (error) {
14671
- logger25.error("Persona storage operation failed", {
15011
+ logger27.error("Persona storage operation failed", {
14672
15012
  error: core.sanitize.sanitizeSensitiveFields(error)
14673
15013
  });
14674
15014
  return err(HaiAIError.PERSONA_SAVE_FAILED, aiM("ai_personaOperationFailed"));
@@ -14692,10 +15032,10 @@ function createPersonaOperations(store) {
14692
15032
  updatedAt: now
14693
15033
  };
14694
15034
  await store.save(key, profile, { objectId });
14695
- logger25.trace("Persona saved", { id: profile.id, objectId });
15035
+ logger27.trace("Persona saved", { id: profile.id, objectId });
14696
15036
  return ok(profile);
14697
15037
  } catch (error) {
14698
- logger25.error("Persona save failed", {
15038
+ logger27.error("Persona save failed", {
14699
15039
  error: core.sanitize.sanitizeSensitiveFields(error)
14700
15040
  });
14701
15041
  return err(HaiAIError.PERSONA_SAVE_FAILED, aiM("ai_personaOperationFailed"));
@@ -14732,7 +15072,7 @@ function createPersonaOperations(store) {
14732
15072
  await store.save(key, profile, { objectId });
14733
15073
  return ok(profile);
14734
15074
  } catch (error) {
14735
- logger25.error("Persona update failed", {
15075
+ logger27.error("Persona update failed", {
14736
15076
  error: core.sanitize.sanitizeSensitiveFields(error)
14737
15077
  });
14738
15078
  return err(HaiAIError.PERSONA_SAVE_FAILED, aiM("ai_personaOperationFailed"));
@@ -14771,7 +15111,7 @@ function createPersonaOperations(store) {
14771
15111
  compose: (id3, options) => protect(() => operations2.compose(id3, options))
14772
15112
  };
14773
15113
  }
14774
- var logger26 = core.logger.child({ module: "ai", scope: "rag" });
15114
+ var logger28 = core.logger.child({ module: "ai", scope: "rag" });
14775
15115
  var DEFAULT_RAG_SYSTEM_PROMPT = `You are a helpful assistant. Answer the user's question based on the provided context.
14776
15116
  If the context doesn't contain relevant information, say so honestly.
14777
15117
  When using information from the context, cite the source by its number, e.g. [1] or [2].`;
@@ -14800,7 +15140,7 @@ function createRagOperations(llm, retrieval) {
14800
15140
  * @returns `ok(RagResult)` 含 answer、context 列表与引用信源;检索或生成失败时返回错误
14801
15141
  */
14802
15142
  async query(query, options) {
14803
- logger26.trace("Starting RAG query", {
15143
+ logger28.trace("Starting RAG query", {
14804
15144
  query: query.slice(0, 100)
14805
15145
  });
14806
15146
  try {
@@ -14855,7 +15195,7 @@ ${contextText}
14855
15195
  }
14856
15196
  const choice = chatResult.data.choices[0];
14857
15197
  const answer = choice?.message?.content ?? "";
14858
- logger26.trace("RAG query completed", {
15198
+ logger28.trace("RAG query completed", {
14859
15199
  contextCount: contextItems.length,
14860
15200
  model: chatResult.data.model
14861
15201
  });
@@ -14882,7 +15222,7 @@ ${contextText}
14882
15222
  } : void 0
14883
15223
  });
14884
15224
  } catch (error) {
14885
- logger26.error("RAG query failed", { error });
15225
+ logger28.error("RAG query failed", { error });
14886
15226
  return err(HaiAIError.RAG_FAILED, aiM("ai_internalError", {
14887
15227
  params: {
14888
15228
  error: String(error)
@@ -14894,7 +15234,7 @@ ${contextText}
14894
15234
  * 流式 RAG 查询:先产出 context,再逐 chunk 产出 delta,最后 done
14895
15235
  */
14896
15236
  async *queryStream(query, options) {
14897
- logger26.trace("Starting RAG stream", {
15237
+ logger28.trace("Starting RAG stream", {
14898
15238
  query: query.slice(0, 100)
14899
15239
  });
14900
15240
  const retrieveResult = await retrieval.retrieve({
@@ -14978,7 +15318,7 @@ ${contextText}
14978
15318
  }
14979
15319
  };
14980
15320
  }
14981
- var logger27 = core.logger.child({ module: "ai", scope: "reasoning" });
15321
+ var logger29 = core.logger.child({ module: "ai", scope: "reasoning" });
14982
15322
  var REACT_SYSTEM_PROMPT = `You are a reasoning agent that follows the ReAct (Reasoning and Acting) framework.
14983
15323
  For each step:
14984
15324
  1. Think: Analyze what you know and what you need to find out.
@@ -15228,7 +15568,7 @@ ${query}` }
15228
15568
  return {
15229
15569
  async run(query, options) {
15230
15570
  const strategy = options?.strategy ?? "react";
15231
- logger27.trace("Starting reasoning", { strategy, maxRounds: options?.maxRounds });
15571
+ logger29.trace("Starting reasoning", { strategy, maxRounds: options?.maxRounds });
15232
15572
  try {
15233
15573
  switch (strategy) {
15234
15574
  case "react":
@@ -15243,7 +15583,7 @@ ${query}` }
15243
15583
  }));
15244
15584
  }
15245
15585
  } catch (error) {
15246
- logger27.error("Reasoning failed", { error });
15586
+ logger29.error("Reasoning failed", { error });
15247
15587
  return err(HaiAIError.REASONING_FAILED, aiM("ai_internalError", {
15248
15588
  params: {
15249
15589
  error: String(error)
@@ -15275,7 +15615,7 @@ ${query}` }
15275
15615
  }
15276
15616
  };
15277
15617
  }
15278
- var logger28 = core.logger.child({ module: "ai", scope: "rerank" });
15618
+ var logger30 = core.logger.child({ module: "ai", scope: "rerank" });
15279
15619
  function createRerankOperations(config, loadModels = () => config.llm) {
15280
15620
  function normalizeDocuments(documents) {
15281
15621
  if (documents.length === 0) {
@@ -15320,7 +15660,7 @@ function createRerankOperations(config, loadModels = () => config.llm) {
15320
15660
  if (request2.returnDocuments) {
15321
15661
  body.return_documents = true;
15322
15662
  }
15323
- logger28.trace("Calling rerank API", { model: resolved.model, documentCount: texts.length, topN: request2.topN });
15663
+ logger30.trace("Calling rerank API", { model: resolved.model, documentCount: texts.length, topN: request2.topN });
15324
15664
  try {
15325
15665
  const response = await fetch(`${resolved.baseUrl}/v1/rerank`, {
15326
15666
  method: "POST",
@@ -15335,7 +15675,7 @@ function createRerankOperations(config, loadModels = () => config.llm) {
15335
15675
  const requestId = response.headers.get("x-request-id");
15336
15676
  await response.body?.cancel().catch(() => {
15337
15677
  });
15338
- logger28.error("Rerank API request failed", {
15678
+ logger30.error("Rerank API request failed", {
15339
15679
  status: response.status,
15340
15680
  providerRequestId: requestId && /^[\w.:-]{1,128}$/.test(requestId) ? requestId : void 0
15341
15681
  });
@@ -15350,11 +15690,11 @@ function createRerankOperations(config, loadModels = () => config.llm) {
15350
15690
  relevanceScore: item2.relevance_score,
15351
15691
  document: item2.document?.text
15352
15692
  }));
15353
- logger28.trace("Rerank completed", { resultCount: results.length });
15693
+ logger30.trace("Rerank completed", { resultCount: results.length });
15354
15694
  return ok({ model: resolved.model, results });
15355
15695
  } catch (error) {
15356
15696
  const causeName = error instanceof Error ? error.name : void 0;
15357
- logger28.error("Rerank API call failed", { causeName });
15697
+ logger30.error("Rerank API call failed", { causeName });
15358
15698
  return err(HaiAIError.RERANK_API_ERROR, aiM("ai_rerankApiFailed", {
15359
15699
  params: {
15360
15700
  error: causeName ?? core.i18n.coreM("core_errorInternal")
@@ -15390,7 +15730,7 @@ function createRerankOperations(config, loadModels = () => config.llm) {
15390
15730
  }
15391
15731
  };
15392
15732
  }
15393
- var logger29 = core.logger.child({ module: "ai", scope: "retrieval" });
15733
+ var logger31 = core.logger.child({ module: "ai", scope: "retrieval" });
15394
15734
  function createRetrievalOperations(embeddingOps, storeProvider, sourceStore, rerankOps, registry) {
15395
15735
  const vectorStoreCache = /* @__PURE__ */ new Map();
15396
15736
  function getVectorStore(collection) {
@@ -15423,7 +15763,7 @@ function createRetrievalOperations(embeddingOps, storeProvider, sourceStore, rer
15423
15763
  }));
15424
15764
  }
15425
15765
  await sourceStore.save(source.id, source);
15426
- logger29.debug("Retrieval source added", { sourceId: source.id, collection: source.collection });
15766
+ logger31.debug("Retrieval source added", { sourceId: source.id, collection: source.collection });
15427
15767
  return ok(void 0);
15428
15768
  },
15429
15769
  /**
@@ -15444,7 +15784,7 @@ function createRetrievalOperations(embeddingOps, storeProvider, sourceStore, rer
15444
15784
  }));
15445
15785
  }
15446
15786
  await sourceStore.remove(sourceId);
15447
- logger29.debug("Retrieval source removed", { sourceId });
15787
+ logger31.debug("Retrieval source removed", { sourceId });
15448
15788
  return ok(void 0);
15449
15789
  },
15450
15790
  /**
@@ -15531,21 +15871,21 @@ function createRetrievalOperations(embeddingOps, storeProvider, sourceStore, rer
15531
15871
  allItems.length = 0;
15532
15872
  allItems.push(...reranked);
15533
15873
  } else {
15534
- logger29.warn("Rerank failed, falling back to vector scores", { error: rerankResult.error });
15874
+ logger31.warn("Rerank failed, falling back to vector scores", { error: rerankResult.error });
15535
15875
  }
15536
15876
  }
15537
15877
  allItems.sort((a, b) => b.score - a.score);
15538
15878
  const topK = request2.topK ?? 10;
15539
15879
  const limitedItems = allItems.slice(0, topK);
15540
15880
  const duration = Date.now() - startTime;
15541
- logger29.trace("Retrieval completed", { queryLength: request2.query.length, resultCount: limitedItems.length, duration });
15881
+ logger31.trace("Retrieval completed", { queryLength: request2.query.length, resultCount: limitedItems.length, duration });
15542
15882
  return ok({
15543
15883
  items: limitedItems,
15544
15884
  query: request2.query,
15545
15885
  duration
15546
15886
  });
15547
15887
  } catch (error) {
15548
- logger29.error("Retrieval failed", { error });
15888
+ logger31.error("Retrieval failed", { error });
15549
15889
  return err(HaiAIError.RETRIEVAL_FAILED, aiM("ai_internalError", {
15550
15890
  params: {
15551
15891
  error: String(error)
@@ -15555,7 +15895,7 @@ function createRetrievalOperations(embeddingOps, storeProvider, sourceStore, rer
15555
15895
  }
15556
15896
  };
15557
15897
  }
15558
- var logger30 = core.logger.child({ module: "ai", scope: "summary" });
15898
+ var logger32 = core.logger.child({ module: "ai", scope: "summary" });
15559
15899
  var SUMMARIZE_SYSTEM_PROMPT = `You are a conversation summarizer. Create a concise summary of the conversation that preserves:
15560
15900
  1. Key facts and decisions made
15561
15901
  2. Important context and background information
@@ -15613,7 +15953,7 @@ ${INCREMENTAL_SUMMARIZE_SUFFIX.replace("{previousSummary}", options.previousSumm
15613
15953
  return ok(chatResult.data.choices[0]?.message?.content ?? "");
15614
15954
  }
15615
15955
  async function summarize(messages, options) {
15616
- logger30.trace("Summarizing messages", { messageCount: messages.length });
15956
+ logger32.trace("Summarizing messages", { messageCount: messages.length });
15617
15957
  try {
15618
15958
  const result = await generate(messages, options);
15619
15959
  if (!result.success)
@@ -15625,7 +15965,7 @@ ${INCREMENTAL_SUMMARIZE_SUFFIX.replace("{previousSummary}", options.previousSumm
15625
15965
  coveredMessages: messages.filter((m) => m.role !== "system").length
15626
15966
  });
15627
15967
  } catch (error) {
15628
- logger30.error("Context summarization failed", { error });
15968
+ logger32.error("Context summarization failed", { error });
15629
15969
  return err(HaiAIError.CONTEXT_SUMMARIZE_FAILED, aiM("ai_contextSummarizeFailed", {
15630
15970
  params: {
15631
15971
  error: String(error)
@@ -15691,8 +16031,10 @@ async function createAISubsystems(config, deps) {
15691
16031
  const memoryStore = useMem0Oss ? null : storeProvider.createRelStore("hai_ai_memory", {
15692
16032
  hasObjectId: true,
15693
16033
  hasScopeIndex: true,
16034
+ hasMemoryVectorIndex: true,
15694
16035
  serializeWrites: true
15695
16036
  });
16037
+ const memoryVectorQueue = memoryStore?.withRelatedWriteLock ? storeProvider.createRelStore("hai_ai_memory_vector_outbox", { hasUpdatedAtIndex: true }) : void 0;
15696
16038
  const contextStore = storeProvider.createRelStore(
15697
16039
  "hai_ai_context",
15698
16040
  { hasObjectId: true, hasSessionId: true }
@@ -15703,6 +16045,7 @@ async function createAISubsystems(config, deps) {
15703
16045
  );
15704
16046
  const a2aStores = config.a2a ? createA2AStores(storeProvider) : null;
15705
16047
  const memoryVectorStore = useMem0Oss ? null : storeProvider.createVectorStore("hai_ai_memory_vectors");
16048
+ const memoryVectorScan = memoryStore?.getMemoryVectorIds && memoryVectorStore?.scan && memoryVectorStore.removeMany ? storeProvider.createRelStore("hai_ai_memory_vector_scan", { serializeWrites: true }) : void 0;
15706
16049
  let registriesOpen = true;
15707
16050
  const isOpen = () => registriesOpen;
15708
16051
  const llmModels = createResourceRegistry(
@@ -15867,13 +16210,8 @@ async function createAISubsystems(config, deps) {
15867
16210
  datapipeDep,
15868
16211
  knowledgeStore
15869
16212
  );
15870
- const memoryCore = memoryStore && memoryVectorStore ? createNativeMemoryOperations(
15871
- memoryParsed,
15872
- llm,
15873
- embedding,
15874
- memoryStore,
15875
- memoryVectorStore
15876
- ) : await createMem0MemoryOperations({
16213
+ const nativeMemory = memoryStore && memoryVectorStore ? assembleNativeMemory(memoryParsed, llm, embedding, memoryStore, memoryVectorStore, memoryVectorQueue, memoryVectorScan) : void 0;
16214
+ const memoryCore = nativeMemory?.operations ?? await createMem0MemoryOperations({
15877
16215
  config: memoryParsed,
15878
16216
  embedding,
15879
16217
  llm,
@@ -15980,10 +16318,12 @@ async function createAISubsystems(config, deps) {
15980
16318
  servers: managedMCPServers,
15981
16319
  services: mcpServices.operations
15982
16320
  });
16321
+ nativeMemory?.sync?.start();
15983
16322
  return {
15984
- closeRegistries: () => {
16323
+ closeRegistries: async () => {
15985
16324
  mcpServices.close();
15986
16325
  registriesOpen = false;
16326
+ await nativeMemory?.sync?.close();
15987
16327
  },
15988
16328
  a2aStores,
15989
16329
  llm,
@@ -16380,7 +16720,7 @@ function documentInfo(document) {
16380
16720
  }
16381
16721
 
16382
16722
  // src/store/providers/ai-store-provider-db.ts
16383
- var logger31 = core.logger.child({ module: "ai", scope: "store-provider-db" });
16723
+ var logger33 = core.logger.child({ module: "ai", scope: "store-provider-db" });
16384
16724
  function requireSqlSuccess(result) {
16385
16725
  if (!result.success)
16386
16726
  throw new Error(result.error.message, { cause: result.error });
@@ -16393,20 +16733,28 @@ function dataTimestamp(data, field, fallback) {
16393
16733
  const value = data[field];
16394
16734
  return typeof value === "number" && Number.isFinite(value) ? value : fallback;
16395
16735
  }
16396
- function isMysqlDuplicateIndex(error) {
16736
+ function isMysqlError(error, code, errno) {
16397
16737
  const seen = /* @__PURE__ */ new Set();
16398
16738
  let current = error;
16399
16739
  while (current !== null && typeof current === "object" && !seen.has(current)) {
16400
16740
  seen.add(current);
16401
16741
  const details = current;
16402
- if (details.code === "ER_DUP_KEYNAME" && details.errno === 1061)
16742
+ if (details.code === code && details.errno === errno)
16403
16743
  return true;
16404
16744
  current = details.cause;
16405
16745
  }
16406
16746
  return false;
16407
16747
  }
16748
+ function memoryVectorKey(type) {
16749
+ if (type === "postgresql")
16750
+ return `(CASE WHEN jsonb_typeof(data->'vector') = 'array' THEN COALESCE(data->>'vectorId', id) END)`;
16751
+ if (type === "mysql")
16752
+ return "memory_vector_key";
16753
+ return `(CASE WHEN json_type(data, '$.vector') = 'array' THEN COALESCE(json_extract(data, '$.vectorId'), id) END)`;
16754
+ }
16408
16755
  var ReldbAIRelStore = class _ReldbAIRelStore {
16409
16756
  sql;
16757
+ connection;
16410
16758
  table;
16411
16759
  jsonOps;
16412
16760
  dbType;
@@ -16417,8 +16765,12 @@ var ReldbAIRelStore = class _ReldbAIRelStore {
16417
16765
  hasScopeIndex;
16418
16766
  hasUpdatedAtIndex;
16419
16767
  gate;
16768
+ memoryVectorKey;
16420
16769
  withWriteLock;
16770
+ withRelatedWriteLock;
16771
+ getMemoryVectorIds;
16421
16772
  constructor(sql, table, jsonOps, dbType, options, tx) {
16773
+ this.connection = sql;
16422
16774
  this.sql = {
16423
16775
  ...sql,
16424
16776
  execute: (query, params) => sql.execute(query, params).then(requireSqlSuccess),
@@ -16434,15 +16786,48 @@ var ReldbAIRelStore = class _ReldbAIRelStore {
16434
16786
  this.hasRefId = options?.hasRefId ?? false;
16435
16787
  this.hasScopeIndex = options?.hasScopeIndex ?? false;
16436
16788
  this.hasUpdatedAtIndex = options?.hasUpdatedAtIndex ?? false;
16789
+ if (options?.hasMemoryVectorIndex) {
16790
+ const key = memoryVectorKey(dbType);
16791
+ this.memoryVectorKey = key;
16792
+ this.getMemoryVectorIds = async (ids) => {
16793
+ if (!ids.length)
16794
+ return [];
16795
+ if (ids.length > 128)
16796
+ throw new RangeError("Too many memory vector keys");
16797
+ const readIds = async (connection) => requireSqlSuccess(await connection.query(
16798
+ `SELECT ${key} AS vector_id FROM ${table} WHERE ${key} IN (${ids.map(() => "?").join(", ")})`,
16799
+ ids
16800
+ )).data.map((row) => row.vector_id);
16801
+ if (dbType === "sqlite" && tx)
16802
+ return requireSqlSuccess(await tx.wrap(readIds)).data;
16803
+ return readIds(this.sql);
16804
+ };
16805
+ }
16437
16806
  if (options?.serializeWrites && tx) {
16438
16807
  const gate = `${table}_write_gate`;
16439
16808
  this.gate = gate;
16440
- this.withWriteLock = async (write) => requireSqlSuccess(await tx.wrap(async (connection) => {
16809
+ const lockedWrite = async (write) => requireSqlSuccess(await tx.wrap(async (connection) => {
16441
16810
  const locked = requireSqlSuccess(await connection.execute(`UPDATE ${gate} SET marker = 1 - marker WHERE id = 1`));
16442
16811
  if (locked.data.changes !== 1)
16443
16812
  throw new Error("Missing AI store write gate");
16444
- return write(new _ReldbAIRelStore(connection, table, jsonOps, dbType, options));
16813
+ return write(connection);
16445
16814
  })).data;
16815
+ this.withWriteLock = (write) => lockedWrite((connection) => write(new _ReldbAIRelStore(connection, table, jsonOps, dbType, options)));
16816
+ this.withRelatedWriteLock = (related, write) => {
16817
+ if (!(related instanceof _ReldbAIRelStore) || related.connection !== sql || related.dbType !== dbType || related.jsonOps !== jsonOps)
16818
+ throw new TypeError("Related AI stores must share a database");
16819
+ return lockedWrite((connection) => write(
16820
+ new _ReldbAIRelStore(connection, table, jsonOps, dbType, options),
16821
+ new _ReldbAIRelStore(connection, related.table, jsonOps, dbType, {
16822
+ hasObjectId: related.hasObjectId,
16823
+ hasSessionId: related.hasSessionId,
16824
+ hasStatus: related.hasStatus,
16825
+ hasRefId: related.hasRefId,
16826
+ hasScopeIndex: related.hasScopeIndex,
16827
+ hasUpdatedAtIndex: related.hasUpdatedAtIndex
16828
+ })
16829
+ ));
16830
+ };
16446
16831
  }
16447
16832
  }
16448
16833
  /** 创建表及索引(幂等) */
@@ -16462,6 +16847,8 @@ var ReldbAIRelStore = class _ReldbAIRelStore {
16462
16847
  if (this.hasRefId)
16463
16848
  cols.push(`ref_id ${scopeType}`);
16464
16849
  cols.push("version VARCHAR(36) NOT NULL", `data ${dataType} NOT NULL`, `created_at BIGINT NOT NULL`, `updated_at BIGINT NOT NULL`);
16850
+ if (db === "mysql" && this.memoryVectorKey)
16851
+ cols.push(this.mysqlMemoryVectorColumn(this.memoryVectorKey));
16465
16852
  await this.sql.execute(`CREATE TABLE IF NOT EXISTS ${t} (${cols.join(", ")})`);
16466
16853
  if (this.gate) {
16467
16854
  await this.sql.execute(`CREATE TABLE IF NOT EXISTS ${this.gate} (id INTEGER PRIMARY KEY, marker INTEGER NOT NULL)`);
@@ -16480,9 +16867,41 @@ var ReldbAIRelStore = class _ReldbAIRelStore {
16480
16867
  await this.createIndex(`idx_${t}_ref_id`, "ref_id");
16481
16868
  if (this.hasUpdatedAtIndex)
16482
16869
  await this.createIndex(`idx_${t}_updated_at`, "updated_at, id");
16870
+ if (this.memoryVectorKey)
16871
+ await this.createMemoryVectorIndex(this.memoryVectorKey);
16483
16872
  if (this.hasScopeIndex && db === "postgresql")
16484
16873
  await this.sql.execute(`CREATE INDEX IF NOT EXISTS idx_${t}_data_gin ON ${t} USING GIN (data jsonb_path_ops)`);
16485
16874
  }
16875
+ /** MySQL 在新表中直接创建生成列,已有表在首次升级时添加该列。 */
16876
+ mysqlMemoryVectorColumn(key) {
16877
+ return `${key} VARCHAR(512) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin GENERATED ALWAYS AS (
16878
+ CASE WHEN JSON_TYPE(JSON_EXTRACT(data, '$.vector')) = 'ARRAY'
16879
+ THEN COALESCE(NULLIF(JSON_UNQUOTE(JSON_EXTRACT(data, '$.vectorId')), 'null'), id) END
16880
+ ) VIRTUAL`;
16881
+ }
16882
+ /** 索引覆盖旧记录,无需逐条回写。MySQL 查询使用命名生成列以命中索引。 */
16883
+ async createMemoryVectorIndex(key) {
16884
+ const name = `idx_${this.table}_vector_key`;
16885
+ if (this.dbType !== "mysql") {
16886
+ await this.sql.execute(`CREATE INDEX IF NOT EXISTS ${name} ON ${this.table}((${key}))`);
16887
+ return;
16888
+ }
16889
+ const read = async () => requireSqlSuccess(await this.sql.get(
16890
+ "SELECT EXTRA AS extra FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ? AND COLUMN_NAME = ?",
16891
+ [this.table, key]
16892
+ )).data;
16893
+ if (!await read()) {
16894
+ try {
16895
+ await this.sql.execute(`ALTER TABLE ${this.table} ADD COLUMN ${this.mysqlMemoryVectorColumn(key)}`);
16896
+ } catch (error) {
16897
+ if (!isMysqlError(error, "ER_DUP_FIELDNAME", 1060))
16898
+ throw error;
16899
+ }
16900
+ }
16901
+ if ((await read())?.extra !== "VIRTUAL GENERATED")
16902
+ throw new Error(aiM("ai_storeIndexMismatch"));
16903
+ await this.createIndex(name, key);
16904
+ }
16486
16905
  /**
16487
16906
  * MySQL 并发首次创建只接受明确的重复名称错误,并重读结构,权限/DDL/不匹配仍失败。
16488
16907
  */
@@ -16503,7 +16922,7 @@ var ReldbAIRelStore = class _ReldbAIRelStore {
16503
16922
  try {
16504
16923
  await this.sql.execute(`CREATE INDEX ${name} ON ${this.table}(${columns})`);
16505
16924
  } catch (error) {
16506
- if (!isMysqlDuplicateIndex(error))
16925
+ if (!isMysqlError(error, "ER_DUP_KEYNAME", 1061))
16507
16926
  throw error;
16508
16927
  if (!matches(await read()))
16509
16928
  throw new Error(aiM("ai_storeIndexMismatch"), { cause: error });
@@ -16678,7 +17097,7 @@ var ReldbAIRelStore = class _ReldbAIRelStore {
16678
17097
  return count;
16679
17098
  }
16680
17099
  async count(filter) {
16681
- if (!filter?.where && !filter?.objectId && !filter?.sessionId && !filter?.status && !filter?.refId && !filter?.scope && filter?.updatedBefore === void 0) {
17100
+ if (!filter?.where && !filter?.objectId && !filter?.sessionId && !filter?.status && !filter?.refId && !filter?.scope && filter?.updatedBefore === void 0 && filter?.afterId === void 0) {
16682
17101
  const result2 = await this.sql.get(`SELECT COUNT(*) as cnt FROM ${this.table}`);
16683
17102
  return result2.success && result2.data != null ? Number(result2.data.cnt) : 0;
16684
17103
  }
@@ -16691,7 +17110,7 @@ var ReldbAIRelStore = class _ReldbAIRelStore {
16691
17110
  return result.success && result.data != null ? Number(result.data.cnt) : 0;
16692
17111
  }
16693
17112
  async clear(filter) {
16694
- if (!filter?.where && !filter?.objectId && !filter?.sessionId && !filter?.status && !filter?.refId) {
17113
+ if (!filter?.where && !filter?.objectId && !filter?.sessionId && !filter?.status && !filter?.refId && !filter?.scope && filter?.updatedBefore === void 0 && filter?.afterId === void 0) {
16695
17114
  await this.sql.execute(`DELETE FROM ${this.table}`);
16696
17115
  return;
16697
17116
  }
@@ -16766,7 +17185,9 @@ var ReldbAIRelStore = class _ReldbAIRelStore {
16766
17185
  const conditions = this.buildAllConditions(filter, params);
16767
17186
  if (conditions.length > 0)
16768
17187
  sql += ` WHERE ${conditions.join(" AND ")}`;
16769
- if (filter.orderBy) {
17188
+ if (filter.afterId !== void 0) {
17189
+ sql += " ORDER BY id ASC";
17190
+ } else if (filter.orderBy) {
16770
17191
  const dir = filter.orderBy.direction === "asc" ? "ASC" : "DESC";
16771
17192
  const field = String(filter.orderBy.field);
16772
17193
  if (field === "createdAt") {
@@ -16789,6 +17210,10 @@ var ReldbAIRelStore = class _ReldbAIRelStore {
16789
17210
  }
16790
17211
  buildAllConditions(filter, params) {
16791
17212
  const conditions = [];
17213
+ if (filter.afterId !== void 0) {
17214
+ conditions.push("id > ?");
17215
+ params.push(filter.afterId);
17216
+ }
16792
17217
  if (filter.updatedBefore !== void 0) {
16793
17218
  conditions.push("updated_at < ?");
16794
17219
  params.push(filter.updatedBefore);
@@ -16913,9 +17338,19 @@ async function ensureVecdbCollection(database, name, dimension) {
16913
17338
  var VecdbAIVectorStore = class {
16914
17339
  vecdb;
16915
17340
  collection;
17341
+ scan;
16916
17342
  constructor(vecdb2, collection) {
16917
17343
  this.vecdb = vecdb2;
16918
17344
  this.collection = collection;
17345
+ const scan = vecdb2.vector.scan?.bind(vecdb2.vector);
17346
+ if (scan) {
17347
+ this.scan = async (options) => {
17348
+ const result = await scan(collection, options);
17349
+ if (!result.success && result.error.code === HaiVecdbError.COLLECTION_NOT_FOUND.code)
17350
+ return { items: [] };
17351
+ return requireVecdbSuccess(result);
17352
+ };
17353
+ }
16919
17354
  }
16920
17355
  async upsert(id3, vector, metadata) {
16921
17356
  await ensureVecdbCollection(this.vecdb, this.collection, vector.length);
@@ -16931,6 +17366,11 @@ var VecdbAIVectorStore = class {
16931
17366
  return;
16932
17367
  requireVecdbSuccess(await this.vecdb.vector.delete(this.collection, [id3]));
16933
17368
  }
17369
+ async removeMany(ids) {
17370
+ const result = await this.vecdb.vector.delete(this.collection, ids);
17371
+ if (!result.success && result.error.code !== HaiVecdbError.COLLECTION_NOT_FOUND.code)
17372
+ requireVecdbSuccess(result);
17373
+ }
16934
17374
  async clear(_filter) {
16935
17375
  const exists = requireVecdbSuccess(await this.vecdb.collection.exists(this.collection));
16936
17376
  if (exists)
@@ -16987,7 +17427,7 @@ function createDbStoreProvider(deps) {
16987
17427
  if (result.status === "rejected")
16988
17428
  throw result.reason;
16989
17429
  }
16990
- logger31.debug("DB store provider initialized", { tableCount: relStores.size });
17430
+ logger33.debug("DB store provider initialized", { tableCount: relStores.size });
16991
17431
  }
16992
17432
  },
16993
17433
  async close() {
@@ -17078,8 +17518,15 @@ function matchesRecord(record, filter) {
17078
17518
  }
17079
17519
  function createRelStore(records) {
17080
17520
  function select(filter) {
17081
- let values = Array.from(records.values()).filter((record) => matchesRecord(record, filter)).map((record) => structuredClone(record.data));
17082
- if (filter.orderBy) {
17521
+ const afterId = filter.afterId;
17522
+ let entries = [
17523
+ ...records.entries()
17524
+ ].filter(([id3, record]) => (afterId === void 0 || id3 > afterId) && matchesRecord(record, filter));
17525
+ if (afterId !== void 0) {
17526
+ entries = entries.sort(([left], [right]) => left < right ? -1 : Number(left > right));
17527
+ }
17528
+ let values = entries.map(([, record]) => structuredClone(record.data));
17529
+ if (filter.orderBy && afterId === void 0) {
17083
17530
  const { field, direction } = filter.orderBy;
17084
17531
  const multiplier = direction === "asc" ? 1 : -1;
17085
17532
  values = values.sort((left, right) => compare(left[field], right[field]) * multiplier);
@@ -17151,13 +17598,13 @@ function createRelStore(records) {
17151
17598
  async queryKeys(filter, cursor) {
17152
17599
  return [
17153
17600
  ...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);
17601
+ ].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
17602
  },
17156
17603
  async removeIfUnchanged(id3, version) {
17157
17604
  return records.get(id3)?.version === version && records.delete(id3);
17158
17605
  },
17159
17606
  async removeBy(filter) {
17160
- const ids = Array.from(records.entries()).filter(([, record]) => matchesRecord(record, filter)).map(([id3]) => id3);
17607
+ const ids = Array.from(records.entries()).filter(([id3, record]) => (filter.afterId === void 0 || id3 > filter.afterId) && matchesRecord(record, filter)).map(([id3]) => id3);
17161
17608
  for (const id3 of ids)
17162
17609
  records.delete(id3);
17163
17610
  return ids.length;
@@ -17170,7 +17617,7 @@ function createRelStore(records) {
17170
17617
  records.clear();
17171
17618
  return;
17172
17619
  }
17173
- const ids = Array.from(records.entries()).filter(([, record]) => matchesRecord(record, filter)).map(([id3]) => id3);
17620
+ const ids = Array.from(records.entries()).filter(([id3, record]) => (filter.afterId === void 0 || id3 > filter.afterId) && matchesRecord(record, filter)).map(([id3]) => id3);
17174
17621
  for (const id3 of ids)
17175
17622
  records.delete(id3);
17176
17623
  }
@@ -17260,7 +17707,7 @@ function createMemoryStoreProvider() {
17260
17707
  }
17261
17708
 
17262
17709
  // src/ai-main.ts
17263
- var logger32 = core.logger.child({ module: "ai", scope: "main" });
17710
+ var logger34 = core.logger.child({ module: "ai", scope: "main" });
17264
17711
  var initInProgress = false;
17265
17712
  var initCompletion = null;
17266
17713
  var closingPromise = null;
@@ -17411,7 +17858,7 @@ async function resetAllState() {
17411
17858
  await currentA2AImpl?.close();
17412
17859
  await currentACP?.close();
17413
17860
  currentLLM = null;
17414
- currentRegistriesClose?.();
17861
+ await currentRegistriesClose?.();
17415
17862
  currentRegistriesClose = null;
17416
17863
  currentACP = null;
17417
17864
  currentMCP = null;
@@ -17439,7 +17886,7 @@ async function resetAllState() {
17439
17886
  try {
17440
17887
  await storeProvider.close();
17441
17888
  } catch (error) {
17442
- logger32.error("AI store provider close failed", { error });
17889
+ logger34.error("AI store provider close failed", { error });
17443
17890
  }
17444
17891
  }
17445
17892
  }
@@ -17456,7 +17903,7 @@ var streamOperations = {
17456
17903
  var ai = {
17457
17904
  async init(config, options) {
17458
17905
  if (initInProgress || closingPromise) {
17459
- logger32.warn("AI init already in progress, skipping concurrent call");
17906
+ logger34.warn("AI init already in progress, skipping concurrent call");
17460
17907
  return err(HaiAIError.INIT_IN_PROGRESS, aiM("ai_initInProgress"));
17461
17908
  }
17462
17909
  initInProgress = true;
@@ -17467,15 +17914,15 @@ var ai = {
17467
17914
  let closingPrevious = false;
17468
17915
  try {
17469
17916
  if (currentConfig) {
17470
- logger32.warn("AI module is already initialized, reinitializing");
17917
+ logger34.warn("AI module is already initialized, reinitializing");
17471
17918
  closingPrevious = true;
17472
17919
  await resetAllState();
17473
17920
  closingPrevious = false;
17474
17921
  }
17475
- logger32.info("Initializing AI module");
17922
+ logger34.info("Initializing AI module");
17476
17923
  const parseResult = AIConfigSchema.safeParse(config ?? {});
17477
17924
  if (!parseResult.success) {
17478
- logger32.error("AI config validation failed", { error: parseResult.error.message });
17925
+ logger34.error("AI config validation failed", { error: parseResult.error.message });
17479
17926
  return err(
17480
17927
  HaiAIError.CONFIGURATION_ERROR,
17481
17928
  aiM("ai_configError", {
@@ -17492,7 +17939,7 @@ var ai = {
17492
17939
  storeProvider = createDbStoreProviderFromModules();
17493
17940
  } else {
17494
17941
  storeProvider = createMemoryStoreProvider();
17495
- logger32.warn("AI is using the ephemeral in-memory store; initialize reldb and vecdb before ai.init() for persistent data");
17942
+ logger34.warn("AI is using the ephemeral in-memory store; initialize reldb and vecdb before ai.init() for persistent data");
17496
17943
  }
17497
17944
  if (core.module.requiresSharedState(process2.env) && storeProvider.stateScope !== "shared")
17498
17945
  return err(HaiAIError.CONFIGURATION_ERROR, aiM("ai_sharedBackendRequired"));
@@ -17528,17 +17975,17 @@ var ai = {
17528
17975
  currentA2AConfig = parsed.a2a;
17529
17976
  currentA2AStores = subs.a2aStores;
17530
17977
  currentConfig = parsed;
17531
- logger32.info("AI module initialized", { model: parsed.llm?.model });
17978
+ logger34.info("AI module initialized", { model: parsed.llm?.model });
17532
17979
  return ok(void 0);
17533
17980
  } catch (error) {
17534
17981
  if (!closingPrevious) {
17535
17982
  try {
17536
17983
  await resetAllState();
17537
17984
  } catch (cleanupError) {
17538
- logger32.error("AI initialization cleanup failed", { error: cleanupError });
17985
+ logger34.error("AI initialization cleanup failed", { error: cleanupError });
17539
17986
  }
17540
17987
  }
17541
- logger32.error("AI module initialization failed", { error });
17988
+ logger34.error("AI module initialization failed", { error });
17542
17989
  return err(
17543
17990
  HaiAIError.CONFIGURATION_ERROR,
17544
17991
  aiM("ai_initFailed", {
@@ -17628,9 +18075,9 @@ var ai = {
17628
18075
  closingPromise = (async () => {
17629
18076
  if (initCompletion)
17630
18077
  await initCompletion;
17631
- logger32.info("Closing AI module");
18078
+ logger34.info("Closing AI module");
17632
18079
  await resetAllState();
17633
- logger32.info("AI module closed");
18080
+ logger34.info("AI module closed");
17634
18081
  })().finally(() => {
17635
18082
  closingPromise = null;
17636
18083
  });