@anuma/sdk 3.8.5 → 3.9.1

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.
@@ -16583,6 +16583,85 @@ async function getAllVaultMemoriesOp(ctx, options) {
16583
16583
  (raw) => vaultMemoryRawToStored(raw, ctx.walletAddress, ctx.signMessage, ctx.embeddedWalletSigner)
16584
16584
  );
16585
16585
  }
16586
+ function baseVaultSql(ctx) {
16587
+ const clauses = [
16588
+ '"is_deleted" = 0',
16589
+ '"archived_at" is null',
16590
+ `"trust_tier" is not 'quarantined'`,
16591
+ '"superseded_by" is null'
16592
+ ];
16593
+ const args = [];
16594
+ if (ctx.userId !== void 0) {
16595
+ clauses.push('"user_id" = ?');
16596
+ args.push(ctx.userId);
16597
+ }
16598
+ return { sql: clauses.join(" and "), args };
16599
+ }
16600
+ async function getVaultCandidateKeysOp(ctx, options) {
16601
+ const mapRaw = (raw) => ({
16602
+ uniqueId: raw.id,
16603
+ folderId: raw.folder_id ?? null,
16604
+ scope: raw.scope ?? "",
16605
+ embeddingModel: raw.embedding_model ?? null,
16606
+ updatedAt: new Date(raw.updated_at)
16607
+ });
16608
+ try {
16609
+ const base = baseVaultSql(ctx);
16610
+ const clauses = [base.sql];
16611
+ const args = [...base.args];
16612
+ if (options?.scopes?.length) {
16613
+ clauses.push(`"scope" in (${options.scopes.map(() => "?").join(",")})`);
16614
+ args.push(...options.scopes);
16615
+ }
16616
+ if (options?.folderId !== void 0) {
16617
+ clauses.push(options.folderId === null ? '"folder_id" is null' : '"folder_id" = ?');
16618
+ if (options.folderId !== null) args.push(options.folderId);
16619
+ }
16620
+ const sql = `select "id", "scope", "folder_id", "embedding_model", "updated_at" from "memory_vault" where ${clauses.join(" and ")}`;
16621
+ const rows = await ctx.vaultMemoryCollection.query(import_watermelondb3.Q.unsafeSqlQuery(sql, args)).unsafeFetchRaw();
16622
+ return rows.map(mapRaw);
16623
+ } catch (err) {
16624
+ getLogger().debug(
16625
+ "memoryVault: getVaultCandidateKeysOp projected SQL unavailable, using full-load fallback: " + (err instanceof Error ? err.message : String(err))
16626
+ );
16627
+ const conditions = [
16628
+ ...baseVaultConditions(ctx),
16629
+ ...options?.scopes?.length ? [import_watermelondb3.Q.where("scope", import_watermelondb3.Q.oneOf(options.scopes))] : [],
16630
+ ...options?.folderId !== void 0 ? [import_watermelondb3.Q.where("folder_id", options.folderId)] : []
16631
+ ];
16632
+ const rows = await ctx.vaultMemoryCollection.query(...conditions).unsafeFetchRaw();
16633
+ return rows.map(mapRaw);
16634
+ }
16635
+ }
16636
+ async function getVaultEmbeddingsByIdsOp(ctx, ids) {
16637
+ if (ids.length === 0) return [];
16638
+ const mapRaw = (raw) => ({
16639
+ uniqueId: raw.id,
16640
+ embedding: raw.embedding ?? null,
16641
+ embeddingModel: raw.embedding_model ?? null
16642
+ });
16643
+ try {
16644
+ const base = baseVaultSql(ctx);
16645
+ const sql = `select "id", "embedding", "embedding_model" from "memory_vault" where ${base.sql} and "id" in (${ids.map(() => "?").join(",")})`;
16646
+ const rows = await ctx.vaultMemoryCollection.query(import_watermelondb3.Q.unsafeSqlQuery(sql, [...base.args, ...ids])).unsafeFetchRaw();
16647
+ return rows.map(mapRaw);
16648
+ } catch (err) {
16649
+ getLogger().debug(
16650
+ "memoryVault: getVaultEmbeddingsByIdsOp projected SQL unavailable, using full-load fallback: " + (err instanceof Error ? err.message : String(err))
16651
+ );
16652
+ const rows = await ctx.vaultMemoryCollection.query(...baseVaultConditions(ctx), import_watermelondb3.Q.where("id", import_watermelondb3.Q.oneOf(ids))).unsafeFetchRaw();
16653
+ return rows.map(mapRaw);
16654
+ }
16655
+ }
16656
+ async function getVaultMemoriesByIdsOp(ctx, ids) {
16657
+ if (ids.length === 0) return [];
16658
+ const conditions = [...baseVaultConditions(ctx), import_watermelondb3.Q.where("id", import_watermelondb3.Q.oneOf(ids))];
16659
+ const results = await ctx.vaultMemoryCollection.query(...conditions).unsafeFetchRaw();
16660
+ return mapInBatches(
16661
+ results,
16662
+ (raw) => vaultMemoryRawToStored(raw, ctx.walletAddress, ctx.signMessage, ctx.embeddedWalletSigner)
16663
+ );
16664
+ }
16586
16665
  async function getAllVaultMemoryContentsOp(ctx, options) {
16587
16666
  const results = await ctx.vaultMemoryCollection.query(...baseVaultConditions(ctx, options)).unsafeFetchRaw();
16588
16667
  return mapInBatches(results, async (raw) => {
@@ -19262,80 +19341,97 @@ async function eagerEmbedContent(content, embeddingOptions, cache, vaultCtx, mem
19262
19341
  );
19263
19342
  }
19264
19343
  }
19265
- async function searchVaultMemoriesWithSize(query, vaultCtx, embeddingOptions, cache, searchOptions) {
19266
- const limit = searchOptions?.limit ?? 5;
19267
- const minSimilarity = searchOptions?.minSimilarity ?? 0.1;
19268
- const scopes = searchOptions?.scopes;
19269
- if (!query || typeof query !== "string") {
19270
- return { results: [], vaultSize: 0, reranked: false, hadV2Head: false };
19271
- }
19272
- const folderId = searchOptions?.folderId;
19273
- const queryOpts = {};
19274
- if (scopes?.length) queryOpts.scopes = scopes;
19275
- if (folderId !== void 0) queryOpts.folderId = folderId;
19276
- if (searchOptions?.factTypes?.length) queryOpts.factTypes = searchOptions.factTypes;
19277
- if (searchOptions?.includeArchived) queryOpts.includeArchived = true;
19278
- const loaded = await getAllVaultMemoriesOp(
19344
+ function admitVaultProjections(queryEmbedding, vectored, k) {
19345
+ return vectored.map((it) => ({ it, score: cosineSimilarity(queryEmbedding, it.embedding) })).sort((a, b) => b.score - a.score || b.it.updatedAt.getTime() - a.it.updatedAt.getTime()).slice(0, k).map((s) => s.it.uniqueId);
19346
+ }
19347
+ async function buildProjectedCorpus(query, vaultCtx, embeddingOptions, cache, queryOpts, opts) {
19348
+ const keys = await getVaultCandidateKeysOp(
19279
19349
  vaultCtx,
19280
19350
  Object.keys(queryOpts).length > 0 ? queryOpts : void 0
19281
19351
  );
19282
- const memories = loaded.filter((m) => !isEncrypted(m.content));
19283
- if (memories.length < loaded.length) {
19284
- getLogger().warn(
19285
- `memoryVault: ${loaded.length - memories.length}/${loaded.length} memories still encrypted (key unavailable?) \u2014 excluded from search`
19286
- );
19287
- }
19288
- if (memories.length === 0) {
19289
- return { results: [], vaultSize: loaded.length, reranked: false, hadV2Head: false };
19352
+ const vaultSize = keys.length;
19353
+ if (keys.length === 0) {
19354
+ return { memories: [], embeddedItems: [], queryEmbedding: [], vaultSize: 0 };
19290
19355
  }
19291
19356
  const queryEmbedding = await generateEmbedding(query, embeddingOptions);
19292
19357
  const currentModel = embeddingOptions.model ?? DEFAULT_API_EMBEDDING_MODEL;
19293
- const uncachedTexts = [];
19294
- const uncachedIndices = [];
19295
- let staleReembedCount = 0;
19296
- for (let i = 0; i < memories.length; i++) {
19297
- const content = memories[i].content;
19298
- const memoryId = memories[i].uniqueId;
19299
- const cached = cache.get(memoryId);
19300
- if (cached && cached.length === queryEmbedding.length) continue;
19301
- if (cached) cache.delete(memoryId);
19302
- const storedModel = memories[i].embeddingModel;
19303
- const modelCompatible = (storedModel ?? currentModel) === currentModel;
19304
- if (memories[i].embedding && modelCompatible) {
19358
+ const vectored = [];
19359
+ const missIds = [];
19360
+ const noVectorIds = [];
19361
+ const keyById = new Map(keys.map((k2) => [k2.uniqueId, k2]));
19362
+ for (const k2 of keys) {
19363
+ const cached = cache.get(k2.uniqueId);
19364
+ if (cached && cached.length === queryEmbedding.length) {
19365
+ vectored.push({ uniqueId: k2.uniqueId, embedding: cached, updatedAt: k2.updatedAt });
19366
+ continue;
19367
+ }
19368
+ const modelCompatible = (k2.embeddingModel ?? currentModel) === currentModel;
19369
+ if (modelCompatible) missIds.push(k2.uniqueId);
19370
+ else noVectorIds.push(k2.uniqueId);
19371
+ }
19372
+ if (missIds.length > 0) {
19373
+ const rows = await getVaultEmbeddingsByIdsOp(vaultCtx, missIds);
19374
+ const gotVector = /* @__PURE__ */ new Set();
19375
+ for (const r of rows) {
19376
+ if (!r.embedding) continue;
19305
19377
  try {
19306
- const parsed = JSON.parse(memories[i].embedding);
19378
+ const parsed = JSON.parse(r.embedding);
19307
19379
  if (Array.isArray(parsed) && parsed.length === queryEmbedding.length) {
19308
- cache.set(memoryId, Float32Array.from(parsed));
19309
- continue;
19380
+ const vec = Float32Array.from(parsed);
19381
+ cache.set(r.uniqueId, vec);
19382
+ const k2 = keyById.get(r.uniqueId);
19383
+ vectored.push({ uniqueId: r.uniqueId, embedding: vec, updatedAt: k2.updatedAt });
19384
+ gotVector.add(r.uniqueId);
19310
19385
  }
19311
19386
  } catch {
19312
19387
  }
19313
19388
  }
19314
- if (memories[i].embedding && !modelCompatible) staleReembedCount++;
19315
- uncachedTexts.push(content);
19316
- uncachedIndices.push(i);
19389
+ for (const id of missIds) if (!gotVector.has(id)) noVectorIds.push(id);
19317
19390
  }
19318
- if (staleReembedCount > 0) {
19319
- getLogger().warn(
19320
- `memoryVault: re-embedding ${staleReembedCount} memories whose stored embedding model differs from the current model (${currentModel}) \u2014 embedding-model change detected`
19391
+ if (noVectorIds.length > 0) {
19392
+ const laneIds = noVectorIds.slice(0, opts.unembeddedCap);
19393
+ if (noVectorIds.length > laneIds.length) {
19394
+ getLogger().warn(
19395
+ `memoryVault: projected search un-embedded lane capped at ${laneIds.length}/${noVectorIds.length}`
19396
+ );
19397
+ }
19398
+ const laneRows = (await getVaultMemoriesByIdsOp(vaultCtx, laneIds)).filter(
19399
+ (m) => !isEncrypted(m.content)
19321
19400
  );
19322
- }
19323
- if (uncachedTexts.length > 0) {
19324
- const newEmbeddings = await generateEmbeddings(uncachedTexts, embeddingOptions);
19325
- for (let j = 0; j < uncachedTexts.length; j++) {
19326
- cache.set(memories[uncachedIndices[j]].uniqueId, Float32Array.from(newEmbeddings[j]));
19327
- updateVaultMemoryEmbeddingOp(
19328
- vaultCtx,
19329
- memories[uncachedIndices[j]].uniqueId,
19330
- JSON.stringify(newEmbeddings[j]),
19331
- currentModel
19332
- ).catch(
19333
- // Silently swallow – SDK must not use console.*; embedding will be retried on next search
19334
- () => {
19335
- }
19401
+ if (laneRows.length > 0) {
19402
+ const laneVecs = await generateEmbeddings(
19403
+ laneRows.map((m) => m.content),
19404
+ embeddingOptions
19336
19405
  );
19406
+ laneRows.forEach((m, i) => {
19407
+ const vec = Float32Array.from(laneVecs[i]);
19408
+ cache.set(m.uniqueId, vec);
19409
+ vectored.push({ uniqueId: m.uniqueId, embedding: vec, updatedAt: m.updatedAt });
19410
+ updateVaultMemoryEmbeddingOp(
19411
+ vaultCtx,
19412
+ m.uniqueId,
19413
+ JSON.stringify(laneVecs[i]),
19414
+ currentModel
19415
+ ).catch(() => {
19416
+ });
19417
+ });
19418
+ }
19419
+ }
19420
+ const k = Math.max(opts.limit * opts.admitFactor, opts.admitFloor);
19421
+ const admittedIds = admitVaultProjections(queryEmbedding, vectored, k);
19422
+ const admissionSet = new Set(admittedIds);
19423
+ if (opts.forceIncludeIds) {
19424
+ for (const id of opts.forceIncludeIds) {
19425
+ if (keyById.has(id)) admissionSet.add(id);
19337
19426
  }
19338
19427
  }
19428
+ const admittedRows = await getVaultMemoriesByIdsOp(vaultCtx, [...admissionSet]);
19429
+ const memories = admittedRows.filter((m) => !isEncrypted(m.content));
19430
+ if (memories.length < admittedRows.length) {
19431
+ getLogger().warn(
19432
+ `memoryVault: ${admittedRows.length - memories.length}/${admittedRows.length} admitted memories still encrypted (key unavailable?) \u2014 excluded from projected search`
19433
+ );
19434
+ }
19339
19435
  const embeddedItems = memories.map((m) => ({
19340
19436
  id: m.uniqueId,
19341
19437
  content: m.content,
@@ -19350,6 +19446,125 @@ async function searchVaultMemoriesWithSize(query, vaultCtx, embeddingOptions, ca
19350
19446
  eventTimeKind: normalizeEventTimeKind(m.eventTimeKind),
19351
19447
  factType: m.factType
19352
19448
  }));
19449
+ return { memories, embeddedItems, queryEmbedding, vaultSize };
19450
+ }
19451
+ async function searchVaultMemoriesWithSize(query, vaultCtx, embeddingOptions, cache, searchOptions) {
19452
+ const limit = searchOptions?.limit ?? 5;
19453
+ const minSimilarity = searchOptions?.minSimilarity ?? 0.1;
19454
+ const scopes = searchOptions?.scopes;
19455
+ if (!query || typeof query !== "string") {
19456
+ return { results: [], vaultSize: 0, reranked: false, hadV2Head: false };
19457
+ }
19458
+ const folderId = searchOptions?.folderId;
19459
+ const queryOpts = {};
19460
+ if (scopes?.length) queryOpts.scopes = scopes;
19461
+ if (folderId !== void 0) queryOpts.folderId = folderId;
19462
+ if (searchOptions?.factTypes?.length) queryOpts.factTypes = searchOptions.factTypes;
19463
+ if (searchOptions?.includeArchived) queryOpts.includeArchived = true;
19464
+ const ADMIT_FACTOR = searchOptions?.admitFactor ?? 3;
19465
+ const ADMIT_FLOOR = searchOptions?.admitFloor ?? 30;
19466
+ const UNEMBEDDED_CAP = 200;
19467
+ let memories;
19468
+ let embeddedItems;
19469
+ let queryEmbedding;
19470
+ let vaultSize;
19471
+ if (searchOptions?.decryptLast) {
19472
+ const forceIncludeIds = [
19473
+ ...searchOptions.entityRanking ?? [],
19474
+ ...searchOptions.temporalRanking ?? []
19475
+ ];
19476
+ const corpus = await buildProjectedCorpus(query, vaultCtx, embeddingOptions, cache, queryOpts, {
19477
+ limit,
19478
+ admitFactor: ADMIT_FACTOR,
19479
+ admitFloor: ADMIT_FLOOR,
19480
+ unembeddedCap: UNEMBEDDED_CAP,
19481
+ ...forceIncludeIds.length > 0 && { forceIncludeIds }
19482
+ });
19483
+ if (corpus.vaultSize === 0) {
19484
+ return { results: [], vaultSize: 0, reranked: false, hadV2Head: false };
19485
+ }
19486
+ ({ memories, embeddedItems, queryEmbedding, vaultSize } = corpus);
19487
+ if (memories.length === 0) {
19488
+ return { results: [], vaultSize, reranked: false, hadV2Head: false };
19489
+ }
19490
+ } else {
19491
+ const loaded = await getAllVaultMemoriesOp(
19492
+ vaultCtx,
19493
+ Object.keys(queryOpts).length > 0 ? queryOpts : void 0
19494
+ );
19495
+ vaultSize = loaded.length;
19496
+ memories = loaded.filter((m) => !isEncrypted(m.content));
19497
+ if (memories.length < loaded.length) {
19498
+ getLogger().warn(
19499
+ `memoryVault: ${loaded.length - memories.length}/${loaded.length} memories still encrypted (key unavailable?) \u2014 excluded from search`
19500
+ );
19501
+ }
19502
+ if (memories.length === 0) {
19503
+ return { results: [], vaultSize: loaded.length, reranked: false, hadV2Head: false };
19504
+ }
19505
+ queryEmbedding = await generateEmbedding(query, embeddingOptions);
19506
+ const currentModel = embeddingOptions.model ?? DEFAULT_API_EMBEDDING_MODEL;
19507
+ const uncachedTexts = [];
19508
+ const uncachedIndices = [];
19509
+ let staleReembedCount = 0;
19510
+ for (let i = 0; i < memories.length; i++) {
19511
+ const content = memories[i].content;
19512
+ const memoryId = memories[i].uniqueId;
19513
+ const cached = cache.get(memoryId);
19514
+ if (cached && cached.length === queryEmbedding.length) continue;
19515
+ if (cached) cache.delete(memoryId);
19516
+ const storedModel = memories[i].embeddingModel;
19517
+ const modelCompatible = (storedModel ?? currentModel) === currentModel;
19518
+ if (memories[i].embedding && modelCompatible) {
19519
+ try {
19520
+ const parsed = JSON.parse(memories[i].embedding);
19521
+ if (Array.isArray(parsed) && parsed.length === queryEmbedding.length) {
19522
+ cache.set(memoryId, Float32Array.from(parsed));
19523
+ continue;
19524
+ }
19525
+ } catch {
19526
+ }
19527
+ }
19528
+ if (memories[i].embedding && !modelCompatible) staleReembedCount++;
19529
+ uncachedTexts.push(content);
19530
+ uncachedIndices.push(i);
19531
+ }
19532
+ if (staleReembedCount > 0) {
19533
+ getLogger().warn(
19534
+ `memoryVault: re-embedding ${staleReembedCount} memories whose stored embedding model differs from the current model (${currentModel}) \u2014 embedding-model change detected`
19535
+ );
19536
+ }
19537
+ if (uncachedTexts.length > 0) {
19538
+ const newEmbeddings = await generateEmbeddings(uncachedTexts, embeddingOptions);
19539
+ for (let j = 0; j < uncachedTexts.length; j++) {
19540
+ cache.set(memories[uncachedIndices[j]].uniqueId, Float32Array.from(newEmbeddings[j]));
19541
+ updateVaultMemoryEmbeddingOp(
19542
+ vaultCtx,
19543
+ memories[uncachedIndices[j]].uniqueId,
19544
+ JSON.stringify(newEmbeddings[j]),
19545
+ currentModel
19546
+ ).catch(
19547
+ // Silently swallow – SDK must not use console.*; embedding will be retried on next search
19548
+ () => {
19549
+ }
19550
+ );
19551
+ }
19552
+ }
19553
+ embeddedItems = memories.map((m) => ({
19554
+ id: m.uniqueId,
19555
+ content: m.content,
19556
+ embedding: cache.get(m.uniqueId) ?? [],
19557
+ createdAt: m.createdAt,
19558
+ updatedAt: m.updatedAt,
19559
+ proofCount: m.proofCount,
19560
+ lastObservedAt: m.lastObservedAt,
19561
+ eventTimeStart: m.eventTimeStart,
19562
+ sourceChunkIds: m.sourceChunkIds,
19563
+ eventTimeEnd: m.eventTimeEnd,
19564
+ eventTimeKind: normalizeEventTimeKind(m.eventTimeKind),
19565
+ factType: m.factType
19566
+ }));
19567
+ }
19353
19568
  if (queryEmbedding.length > 0) {
19354
19569
  const mismatched = embeddedItems.filter(
19355
19570
  (it) => it.embedding.length > 0 && it.embedding.length !== queryEmbedding.length
@@ -19435,7 +19650,7 @@ async function searchVaultMemoriesWithSize(query, vaultCtx, embeddingOptions, ca
19435
19650
  });
19436
19651
  return stampTimestamps({
19437
19652
  results: composite,
19438
- vaultSize: loaded.length,
19653
+ vaultSize,
19439
19654
  reranked: rerankStats.applied,
19440
19655
  hadV2Head: v2HeadStats.hadResults
19441
19656
  });
@@ -19460,7 +19675,7 @@ async function searchVaultMemoriesWithSize(query, vaultCtx, embeddingOptions, ca
19460
19675
  });
19461
19676
  return stampTimestamps({
19462
19677
  results: results2,
19463
- vaultSize: loaded.length,
19678
+ vaultSize,
19464
19679
  reranked: rerankStats.applied,
19465
19680
  hadV2Head: v2HeadStats.hadResults
19466
19681
  });
@@ -19473,7 +19688,7 @@ async function searchVaultMemoriesWithSize(query, vaultCtx, embeddingOptions, ca
19473
19688
  ...searchOptions?.entityRanking && { entityRanking: searchOptions.entityRanking },
19474
19689
  ...searchOptions?.temporalRanking && { temporalRanking: searchOptions.temporalRanking }
19475
19690
  });
19476
- return stampTimestamps({ results: results2, vaultSize: loaded.length, hadV2Head: results2.length > 0 });
19691
+ return stampTimestamps({ results: results2, vaultSize, hadV2Head: results2.length > 0 });
19477
19692
  }
19478
19693
  const results = rankVaultMemories(query, queryEmbedding, embeddedItems, {
19479
19694
  limit,
@@ -19485,7 +19700,7 @@ async function searchVaultMemoriesWithSize(query, vaultCtx, embeddingOptions, ca
19485
19700
  supersessionWindow: searchOptions.supersessionWindow
19486
19701
  }
19487
19702
  });
19488
- return stampTimestamps({ results, vaultSize: loaded.length, hadV2Head: results.length > 0 });
19703
+ return stampTimestamps({ results, vaultSize, hadV2Head: results.length > 0 });
19489
19704
  }
19490
19705
  async function searchVaultMemories(query, vaultCtx, embeddingOptions, cache, searchOptions) {
19491
19706
  const { results } = await searchVaultMemoriesWithSize(
@@ -19574,7 +19789,7 @@ function createMemoryVaultSearchTool(vaultCtx, embeddingOptions, cache, searchOp
19574
19789
  legacy.map((r) => ({ id: r.uniqueId, content: r.content, score: r.similarity }))
19575
19790
  );
19576
19791
  }
19577
- const { recall: recall2 } = await import("./recall-VDMDNQNB.mjs");
19792
+ const { recall: recall2 } = await import("./recall-NLJNELJY.mjs");
19578
19793
  const result = await recall2(
19579
19794
  query,
19580
19795
  { vaultCtx, embeddingOptions, vaultCache: cache },
@@ -20221,6 +20436,7 @@ async function recall(query, ctx, options = {}) {
20221
20436
  bm25AdmissionDivisor: options.bm25AdmissionDivisor
20222
20437
  },
20223
20438
  ...options.rrfK !== void 0 && { rrfK: options.rrfK },
20439
+ ...options.decryptLast !== void 0 && { decryptLast: options.decryptLast },
20224
20440
  ...decomposeAvailable && {
20225
20441
  decompose: "llm",
20226
20442
  decomposeOptions: options.decomposeOptions