@anuma/sdk 7.0.5 → 7.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -13118,6 +13118,17 @@ async function decryptVaultMemoryFields(memory, address, signMessage, embeddedWa
13118
13118
  };
13119
13119
  }
13120
13120
 
13121
+ // src/lib/db/memoryVault/sourceChunkIds.ts
13122
+ var MAX_SOURCE_CHUNK_IDS_BYTES = 16 << 10;
13123
+ var utf8 = new TextEncoder();
13124
+ function serializeSourceChunkIds(ids) {
13125
+ const sizes = ids.map((id) => utf8.encode(JSON.stringify(id)).length + 1);
13126
+ let total = sizes.reduce((sum, size) => sum + size, 1);
13127
+ let start = 0;
13128
+ while (total > MAX_SOURCE_CHUNK_IDS_BYTES && start < ids.length) total -= sizes[start++];
13129
+ return JSON.stringify(ids.slice(start));
13130
+ }
13131
+
13121
13132
  // src/lib/db/memoryVault/types.ts
13122
13133
  var MEMORY_KINDS = [
13123
13134
  "display_name",
@@ -13265,15 +13276,15 @@ async function mapInBatches(items, fn) {
13265
13276
  return results;
13266
13277
  }
13267
13278
  function vaultMemoryToStoredRaw(memory) {
13268
- let sourceChunkIds = null;
13279
+ let sourceChunkIds2 = null;
13269
13280
  if (memory.sourceChunkIds) {
13270
13281
  try {
13271
13282
  const parsed = JSON.parse(memory.sourceChunkIds);
13272
13283
  if (Array.isArray(parsed)) {
13273
- sourceChunkIds = parsed.filter((s) => typeof s === "string");
13284
+ sourceChunkIds2 = parsed.filter((s) => typeof s === "string");
13274
13285
  }
13275
13286
  } catch {
13276
- sourceChunkIds = null;
13287
+ sourceChunkIds2 = null;
13277
13288
  }
13278
13289
  }
13279
13290
  return {
@@ -13287,7 +13298,7 @@ function vaultMemoryToStoredRaw(memory) {
13287
13298
  userId: memory.userId ?? null,
13288
13299
  embedding: memory.embedding ?? null,
13289
13300
  embeddingModel: memory.embeddingModel ?? null,
13290
- sourceChunkIds,
13301
+ sourceChunkIds: sourceChunkIds2,
13291
13302
  proofCount: memory.proofCount ?? null,
13292
13303
  source: memory.source ?? null,
13293
13304
  media: parseMedia(memory.media),
@@ -13336,7 +13347,7 @@ function populateNewVaultMemory(record2, ctx, opts, encryptedContent, encryptedK
13336
13347
  record2._setRaw("embedding_model", opts.embeddingModel ?? null);
13337
13348
  }
13338
13349
  if (opts.sourceChunkIds !== void 0) {
13339
- record2._setRaw("source_chunk_ids", JSON.stringify(opts.sourceChunkIds));
13350
+ record2._setRaw("source_chunk_ids", serializeSourceChunkIds(opts.sourceChunkIds));
13340
13351
  }
13341
13352
  record2._setRaw("proof_count", opts.proofCount ?? 1);
13342
13353
  record2._setRaw("source", opts.source ?? "manual");
@@ -13514,16 +13525,16 @@ async function getVaultMemoryOp(ctx, id) {
13514
13525
  }
13515
13526
  }
13516
13527
  function vaultMemoryRawToStoredRaw(raw) {
13517
- let sourceChunkIds = null;
13528
+ let sourceChunkIds2 = null;
13518
13529
  const rawChunks = raw.source_chunk_ids;
13519
13530
  if (typeof rawChunks === "string" && rawChunks) {
13520
13531
  try {
13521
13532
  const parsed = JSON.parse(rawChunks);
13522
13533
  if (Array.isArray(parsed)) {
13523
- sourceChunkIds = parsed.filter((s) => typeof s === "string");
13534
+ sourceChunkIds2 = parsed.filter((s) => typeof s === "string");
13524
13535
  }
13525
13536
  } catch {
13526
- sourceChunkIds = null;
13537
+ sourceChunkIds2 = null;
13527
13538
  }
13528
13539
  }
13529
13540
  return {
@@ -13537,7 +13548,7 @@ function vaultMemoryRawToStoredRaw(raw) {
13537
13548
  userId: raw.user_id ?? null,
13538
13549
  embedding: raw.embedding ?? null,
13539
13550
  embeddingModel: raw.embedding_model ?? null,
13540
- sourceChunkIds,
13551
+ sourceChunkIds: sourceChunkIds2,
13541
13552
  proofCount: raw.proof_count ?? null,
13542
13553
  source: raw.source ?? null,
13543
13554
  eventTimeStart: raw.event_time_start ?? null,
@@ -13834,7 +13845,7 @@ async function updateVaultMemoryOp(ctx, id, opts) {
13834
13845
  if (opts.sourceChunkIds !== void 0) {
13835
13846
  r._setRaw(
13836
13847
  "source_chunk_ids",
13837
- JSON.stringify(
13848
+ serializeSourceChunkIds(
13838
13849
  opts.observationSourceIds?.length ? [.../* @__PURE__ */ new Set([...observedSources, ...opts.sourceChunkIds])] : opts.sourceChunkIds
13839
13850
  )
13840
13851
  );
@@ -21172,11 +21183,15 @@ function memoryCipher(canonical) {
21172
21183
  };
21173
21184
  }
21174
21185
  async function reencryptMemoryField(value, canonical, fallbacks = []) {
21175
- const { encrypt } = memoryCipher(canonical);
21176
- if (!value.startsWith("enc:")) return encrypt(value);
21186
+ return memoryCipher(canonical).encrypt(
21187
+ await decryptMemoryField(value, [canonical, ...fallbacks])
21188
+ );
21189
+ }
21190
+ async function decryptMemoryField(value, rings) {
21191
+ if (!value.startsWith("enc:")) return value;
21177
21192
  if (!isEncrypted(value))
21178
21193
  throw new MemoryKeyError("Field has an encryption prefix but an invalid payload");
21179
- return encrypt(await decryptWith(value, [canonical, ...fallbacks]));
21194
+ return decryptWith(value, rings);
21180
21195
  }
21181
21196
 
21182
21197
  // src/lib/memory/store/remotePersistence.ts
@@ -21869,7 +21884,7 @@ function createRemoteMemoryPipeline(options) {
21869
21884
  embedding: storedVector(JSON.parse(input.embedding)),
21870
21885
  embedding_model: input.embeddingModel
21871
21886
  },
21872
- source_chunk_ids: JSON.stringify(input.sourceChunkIds ?? []),
21887
+ source_chunk_ids: serializeSourceChunkIds(input.sourceChunkIds ?? []),
21873
21888
  proof_count: input.proofCount ?? 1,
21874
21889
  source: input.source ?? "manual",
21875
21890
  ...input.eventTime && {
@@ -21928,7 +21943,7 @@ function createRemoteMemoryPipeline(options) {
21928
21943
  const observed = sourceIds(memory.source_chunk_ids);
21929
21944
  const replay = !!patch.observationSourceIds?.length && patch.observationSourceIds.every((id2) => observed.includes(id2));
21930
21945
  if (patch.sourceChunkIds !== void 0)
21931
- memory.source_chunk_ids = JSON.stringify(
21946
+ memory.source_chunk_ids = serializeSourceChunkIds(
21932
21947
  patch.observationSourceIds?.length ? [.../* @__PURE__ */ new Set([...observed, ...patch.sourceChunkIds])] : patch.sourceChunkIds
21933
21948
  );
21934
21949
  if (!replay) {
@@ -22035,6 +22050,8 @@ function createRemoteMemoryPipeline(options) {
22035
22050
 
22036
22051
  // src/lib/memory/store/remoteMigration.ts
22037
22052
  var IMPORT_BATCH = 50;
22053
+ var EMBED_BATCH = 100;
22054
+ var LOCAL_VECTOR_DIMS = 4096;
22038
22055
  var VERIFY_BATCH = 1e3;
22039
22056
  var QUERY_IDS = 1e3;
22040
22057
  var QUERY_PAGE = 200;
@@ -22060,7 +22077,7 @@ var SHORT_FIELDS = [
22060
22077
  "visibility",
22061
22078
  "geohash"
22062
22079
  ];
22063
- var utf8 = new TextEncoder();
22080
+ var utf82 = new TextEncoder();
22064
22081
  var METADATA_FIELDS = [
22065
22082
  "scope",
22066
22083
  "kind",
@@ -22111,17 +22128,34 @@ function revision(raw) {
22111
22128
  last_observed_at: num(raw.last_observed_at) ?? null
22112
22129
  };
22113
22130
  }
22114
- function embedding(raw) {
22131
+ function embedding(raw, model) {
22115
22132
  const value = text13(raw.embedding);
22116
22133
  if (!value) return void 0;
22117
22134
  try {
22118
- return storedVector(JSON.parse(value));
22135
+ const vector = JSON.parse(value);
22136
+ const stored2 = text13(raw.embedding_model);
22137
+ if (stored2 === void 0 ? vector.length !== LOCAL_VECTOR_DIMS : stored2 !== model)
22138
+ return void 0;
22139
+ return storedVector(vector);
22140
+ } catch {
22141
+ return void 0;
22142
+ }
22143
+ }
22144
+ function stringArray(value) {
22145
+ try {
22146
+ const parsed = JSON.parse(value);
22147
+ return Array.isArray(parsed) && parsed.every((id) => typeof id === "string") ? parsed : void 0;
22119
22148
  } catch {
22120
22149
  return void 0;
22121
22150
  }
22122
22151
  }
22152
+ function sourceChunkIds(raw) {
22153
+ const value = text13(raw.source_chunk_ids);
22154
+ const ids = value && stringArray(value);
22155
+ return ids ? serializeSourceChunkIds(ids) : value;
22156
+ }
22123
22157
  function bytes(value) {
22124
- return value === void 0 ? 0 : utf8.encode(value).length;
22158
+ return value === void 0 ? 0 : utf82.encode(value).length;
22125
22159
  }
22126
22160
  function fitsNearby(row) {
22127
22161
  return bytes(row.memory_id) <= MAX_ID_BYTES && bytes(row.content) <= MAX_CONTENT_BYTES && bytes(row.kind_value) <= MAX_CONTENT_BYTES && TEXT_FIELDS.every((field10) => bytes(row[field10]) <= MAX_TEXT_BYTES) && SHORT_FIELDS.every((field10) => bytes(row[field10]) <= MAX_SHORT_BYTES);
@@ -22130,16 +22164,16 @@ function invalid(raw) {
22130
22164
  const id = raw.id;
22131
22165
  return typeof id !== "string" || id === "" || bytes(id) > MAX_ID_BYTES || !text13(raw.scope) || (num(raw.created_at) ?? 0) <= 0 || (num(raw.updated_at) ?? 0) <= 0;
22132
22166
  }
22133
- function metadata(raw) {
22134
- const vector = embedding(raw);
22167
+ function metadata(raw, model) {
22168
+ const vector = embedding(raw, model);
22135
22169
  return {
22136
22170
  scope: raw.scope,
22137
22171
  kind: text13(raw.kind),
22138
22172
  level: text13(raw.level),
22139
22173
  folder_id: text13(raw.folder_id),
22140
22174
  is_deleted: bool(raw.is_deleted) ?? false,
22141
- ...vector && { embedding: vector, embedding_model: text13(raw.embedding_model) },
22142
- source_chunk_ids: text13(raw.source_chunk_ids),
22175
+ ...vector && { embedding: vector, embedding_model: model },
22176
+ source_chunk_ids: sourceChunkIds(raw),
22143
22177
  proof_count: num(raw.proof_count),
22144
22178
  source: text13(raw.source),
22145
22179
  event_time_start: num(raw.event_time_start),
@@ -22168,30 +22202,63 @@ function defined(value) {
22168
22202
  Object.entries(value).filter(([, field10]) => field10 !== void 0)
22169
22203
  );
22170
22204
  }
22171
- async function remoteRow(raw, canonical, fallbacks, updatedAt) {
22172
- const content = await reencryptMemoryField(
22173
- typeof raw.content === "string" ? raw.content : "",
22174
- canonical,
22175
- fallbacks
22176
- );
22177
- const kindValue = text13(raw.kind_value);
22178
- const encryptedKindValue = kindValue ? await reencryptMemoryField(kindValue, canonical, fallbacks) : void 0;
22205
+ async function prepareRow(raw, canonical, rings, model, updatedAt) {
22206
+ const deleted = bool(raw.is_deleted) ?? false;
22207
+ const { encrypt } = memoryCipher(canonical);
22208
+ const localKindValue = text13(raw.kind_value);
22209
+ let plaintext;
22210
+ let kindValue;
22211
+ try {
22212
+ plaintext = await decryptMemoryField(typeof raw.content === "string" ? raw.content : "", rings);
22213
+ kindValue = localKindValue && await decryptMemoryField(localKindValue, rings);
22214
+ } catch (error) {
22215
+ if (!deleted || !(error instanceof MemoryKeyError)) throw error;
22216
+ plaintext = void 0;
22217
+ kindValue = void 0;
22218
+ }
22179
22219
  const row = {
22180
- ...defined({ ...metadata(raw), kind_value: encryptedKindValue }),
22220
+ ...defined({
22221
+ ...metadata(raw, model),
22222
+ kind_value: kindValue === void 0 ? void 0 : await encrypt(kindValue)
22223
+ }),
22181
22224
  memory_id: raw.id,
22182
- content,
22225
+ content: await encrypt(plaintext ?? ""),
22183
22226
  scope: raw.scope,
22184
22227
  created_at: raw.created_at,
22185
22228
  updated_at: updatedAt,
22186
- is_deleted: bool(raw.is_deleted) ?? false
22229
+ is_deleted: deleted
22187
22230
  };
22188
- return fitsNearby(row) ? row : null;
22231
+ return { row, plaintext };
22232
+ }
22233
+ async function embedMissing(prepared, options, model, signal) {
22234
+ const needed = prepared.filter((p) => !p.row.embedding && p.plaintext);
22235
+ for (const batch of chunks(needed, EMBED_BATCH)) {
22236
+ if (signal?.aborted) throw aborted(signal);
22237
+ try {
22238
+ const vectors = await generateEmbeddings(
22239
+ batch.map((p) => p.plaintext),
22240
+ { ...options, taskType: "memory_retain_embed" }
22241
+ );
22242
+ if (vectors.length !== batch.length) throw new Error("Incomplete migration embeddings");
22243
+ const stored2 = vectors.map(storedVector);
22244
+ batch.forEach((p, i) => {
22245
+ p.row.embedding = stored2[i];
22246
+ p.row.embedding_model = model;
22247
+ });
22248
+ } catch (error) {
22249
+ getLogger().warn(
22250
+ `[memory/migration] Uploading ${batch.length} row(s) without a vector: embedding failed`,
22251
+ error
22252
+ );
22253
+ }
22254
+ }
22189
22255
  }
22190
- function sameMetadata(local, remote) {
22191
- const mine = metadata(local);
22256
+ function sameMetadata(local, remote, model) {
22257
+ const mine = metadata(local, model);
22192
22258
  return METADATA_FIELDS.every((field10) => {
22193
22259
  const a = mine[field10] ?? null;
22194
22260
  const b = remote[field10] ?? null;
22261
+ if (field10 === "embedding_model" && a === null) return true;
22195
22262
  if (field10 === "visibility") return (a ?? "private") === (b ?? "private");
22196
22263
  if (field10 === "is_deleted" || field10 === "topics_user_managed" || field10 === "twin_opt_in")
22197
22264
  return (a ?? false) === (b ?? false);
@@ -22287,7 +22354,8 @@ async function backfillTopics(ctx) {
22287
22354
  }
22288
22355
  async function migrateMemoriesToRemote(options) {
22289
22356
  const { canonical, signal } = options;
22290
- const fallbacks = options.fallbacks ?? [];
22357
+ const rings = [canonical, ...options.fallbacks ?? []];
22358
+ const model = options.embeddingOptions?.model ?? DEFAULT_API_EMBEDDING_MODEL;
22291
22359
  const request = createNearbyRequest(options);
22292
22360
  const account = await request("/account", {}, signal);
22293
22361
  if (typeof account.key_id === "string" && account.key_id !== canonical.keyId)
@@ -22298,8 +22366,13 @@ async function migrateMemoriesToRemote(options) {
22298
22366
  );
22299
22367
  const active = account.state === "active";
22300
22368
  let claimed = account.key_id === canonical.keyId;
22369
+ if (!active) await createDecaySweeper({ vaultCtx: options.vaultCtx }).runSweep();
22301
22370
  await backfillTopics(options.vaultCtx);
22302
22371
  const skipped = /* @__PURE__ */ new Map();
22372
+ const reembedded = /* @__PURE__ */ new Set();
22373
+ const unembedded = /* @__PURE__ */ new Set();
22374
+ const placeholders = /* @__PURE__ */ new Set();
22375
+ const truncated = /* @__PURE__ */ new Set();
22303
22376
  let imported = 0;
22304
22377
  for (let pass = 0; ; pass++) {
22305
22378
  const rows = await getAllVaultMemoryRowsOp(options.vaultCtx);
@@ -22315,9 +22388,10 @@ async function migrateMemoriesToRemote(options) {
22315
22388
  candidates.map((raw) => raw.id),
22316
22389
  signal
22317
22390
  );
22391
+ const needsVector = (raw, server) => !!options.embeddingOptions && !embedding(raw, model) && server.embedding_model !== model;
22318
22392
  for (const raw of candidates) {
22319
22393
  const server = remote.get(raw.id);
22320
- if (server && server.updated_at === raw.updated_at && !sameMetadata(raw, server))
22394
+ if (server && server.updated_at === raw.updated_at && (!sameMetadata(raw, server, model) || needsVector(raw, server)))
22321
22395
  pending.set(raw.id, raw.updated_at + 1);
22322
22396
  }
22323
22397
  }
@@ -22326,7 +22400,11 @@ async function migrateMemoriesToRemote(options) {
22326
22400
  state,
22327
22401
  total: rows.length,
22328
22402
  imported,
22329
- skipped: [...skipped].map(([memoryId, reason]) => ({ memoryId, reason }))
22403
+ skipped: [...skipped].map(([memoryId, reason]) => ({ memoryId, reason })),
22404
+ reembedded: reembedded.size,
22405
+ unembedded: unembedded.size,
22406
+ placeholderTombstones: placeholders.size,
22407
+ truncatedSourceChunkIds: truncated.size
22330
22408
  });
22331
22409
  if (skipped.size > 0 && !options.allowSkipped) return result("migrating");
22332
22410
  if (!claimed) await importBatch(request, canonical.keyId, [], signal);
@@ -22344,19 +22422,35 @@ async function migrateMemoriesToRemote(options) {
22344
22422
  409,
22345
22423
  "migration_incomplete"
22346
22424
  );
22347
- const upload = [];
22425
+ const prepared = [];
22348
22426
  for (const raw of candidates) {
22349
22427
  const updatedAt = pending.get(raw.id);
22350
22428
  if (updatedAt === void 0) continue;
22351
22429
  try {
22352
- const row = await remoteRow(raw, canonical, fallbacks, updatedAt);
22353
- if (row) upload.push(row);
22354
- else skipped.set(raw.id, "invalid");
22430
+ prepared.push(await prepareRow(raw, canonical, rings, model, updatedAt));
22355
22431
  } catch (error) {
22356
22432
  if (!(error instanceof MemoryKeyError)) throw error;
22357
22433
  skipped.set(raw.id, "unreadable");
22358
22434
  }
22359
22435
  }
22436
+ const usable = new Set(prepared.filter((p) => p.row.embedding).map((p) => p.row.memory_id));
22437
+ if (options.embeddingOptions)
22438
+ await embedMissing(prepared, options.embeddingOptions, model, signal);
22439
+ const local = new Map(candidates.map((raw) => [raw.id, raw]));
22440
+ const upload = [];
22441
+ for (const { row, plaintext } of prepared) {
22442
+ const id = row.memory_id;
22443
+ if (!fitsNearby(row)) {
22444
+ skipped.set(id, "invalid");
22445
+ continue;
22446
+ }
22447
+ upload.push(row);
22448
+ const track = (set, on) => on ? set.add(id) : set.delete(id);
22449
+ track(reembedded, !!row.embedding && !usable.has(id));
22450
+ track(unembedded, !row.embedding);
22451
+ track(placeholders, plaintext === void 0);
22452
+ track(truncated, row.source_chunk_ids !== text13(local.get(id).source_chunk_ids));
22453
+ }
22360
22454
  let sent = 0;
22361
22455
  options.onProgress?.({ imported: sent, toImport: upload.length });
22362
22456
  for (const batch of chunks(upload, IMPORT_BATCH)) {
@@ -29519,6 +29613,7 @@ function useChat(options) {
29519
29613
 
29520
29614
  // src/react/useChatStorage.ts
29521
29615
  import { useCallback as useCallback5, useEffect as useEffect4, useMemo as useMemo4, useRef as useRef4, useState as useState5 } from "react";
29616
+ import { v7 as uuidv77 } from "uuid";
29522
29617
 
29523
29618
  // src/lib/chat/assembleMessages.ts
29524
29619
  function assembleMessagesWithHistory(historyMessages, callerMessages, summarySystemMessage) {
@@ -31274,11 +31369,15 @@ function useChatStorage(options) {
31274
31369
  });
31275
31370
  const createConversation = useCallback5(
31276
31371
  async (opts) => {
31372
+ const conversationOpts = {
31373
+ ...opts,
31374
+ conversationId: opts?.conversationId || generateConversationId()
31375
+ };
31277
31376
  const { result, queued, queueId } = await writeOrQueue(
31278
31377
  "createConversation",
31279
- { conversationId: opts?.conversationId, title: opts?.title, projectId: opts?.projectId },
31280
- () => createConversationOp(storageCtx, opts, defaultConversationTitle),
31281
- () => makeSyntheticStoredConversation(opts, defaultConversationTitle)
31378
+ conversationOpts,
31379
+ () => createConversationOp(storageCtx, conversationOpts, defaultConversationTitle),
31380
+ () => makeSyntheticStoredConversation(conversationOpts, defaultConversationTitle)
31282
31381
  );
31283
31382
  if (queued) {
31284
31383
  syntheticConvIdsRef.current.add(result.conversationId);
@@ -31966,6 +32065,7 @@ function useChatStorage(options) {
31966
32065
  );
31967
32066
  }
31968
32067
  const userMsgOpts = {
32068
+ uniqueId: `msg_${uuidv77()}`,
31969
32069
  conversationId: convId,
31970
32070
  role: "user",
31971
32071
  content: contentForStorage,
@@ -32293,7 +32393,7 @@ function useChatStorage(options) {
32293
32393
  thinking: thinkingContent,
32294
32394
  parentMessageId: storedUserMessage.uniqueId,
32295
32395
  toolCallEvents: currentTurnToolCallEvents && currentTurnToolCallEvents.length > 0 ? currentTurnToolCallEvents : void 0,
32296
- uniqueId: assistantUniqueId
32396
+ uniqueId: assistantUniqueId || `msg_${uuidv77()}`
32297
32397
  };
32298
32398
  let storedAssistantMessage;
32299
32399
  let assistantMsgQueueId;
@@ -32340,6 +32440,7 @@ function useChatStorage(options) {
32340
32440
  let storedToolResultsMessage;
32341
32441
  if (autoToolResults && autoToolResults.length > 0) {
32342
32442
  const toolResultsOpts = {
32443
+ uniqueId: `msg_${uuidv77()}`,
32343
32444
  conversationId: convId,
32344
32445
  role: "user",
32345
32446
  content: buildToolResultContent(autoToolResults),
@@ -28199,6 +28199,17 @@ async function decryptVaultMemoryFields(memory, address, signMessage, embeddedWa
28199
28199
  };
28200
28200
  }
28201
28201
 
28202
+ // src/lib/db/memoryVault/sourceChunkIds.ts
28203
+ var MAX_SOURCE_CHUNK_IDS_BYTES = 16 << 10;
28204
+ var utf8 = new TextEncoder();
28205
+ function serializeSourceChunkIds(ids) {
28206
+ const sizes = ids.map((id) => utf8.encode(JSON.stringify(id)).length + 1);
28207
+ let total = sizes.reduce((sum, size) => sum + size, 1);
28208
+ let start = 0;
28209
+ while (total > MAX_SOURCE_CHUNK_IDS_BYTES && start < ids.length) total -= sizes[start++];
28210
+ return JSON.stringify(ids.slice(start));
28211
+ }
28212
+
28202
28213
  // src/lib/db/memoryVault/types.ts
28203
28214
  var MEMORY_KINDS = [
28204
28215
  "display_name",
@@ -28417,7 +28428,7 @@ function populateNewVaultMemory(record, ctx, opts, encryptedContent, encryptedKi
28417
28428
  record._setRaw("embedding_model", opts.embeddingModel ?? null);
28418
28429
  }
28419
28430
  if (opts.sourceChunkIds !== void 0) {
28420
- record._setRaw("source_chunk_ids", JSON.stringify(opts.sourceChunkIds));
28431
+ record._setRaw("source_chunk_ids", serializeSourceChunkIds(opts.sourceChunkIds));
28421
28432
  }
28422
28433
  record._setRaw("proof_count", opts.proofCount ?? 1);
28423
28434
  record._setRaw("source", opts.source ?? "manual");
@@ -28901,7 +28912,7 @@ async function updateVaultMemoryOp(ctx, id, opts) {
28901
28912
  if (opts.sourceChunkIds !== void 0) {
28902
28913
  r._setRaw(
28903
28914
  "source_chunk_ids",
28904
- JSON.stringify(
28915
+ serializeSourceChunkIds(
28905
28916
  opts.observationSourceIds?.length ? [.../* @__PURE__ */ new Set([...observedSources, ...opts.sourceChunkIds])] : opts.sourceChunkIds
28906
28917
  )
28907
28918
  );
@@ -26514,6 +26514,17 @@ async function decryptVaultMemoryFields(memory, address, signMessage, embeddedWa
26514
26514
  };
26515
26515
  }
26516
26516
 
26517
+ // src/lib/db/memoryVault/sourceChunkIds.ts
26518
+ var MAX_SOURCE_CHUNK_IDS_BYTES = 16 << 10;
26519
+ var utf8 = new TextEncoder();
26520
+ function serializeSourceChunkIds(ids) {
26521
+ const sizes = ids.map((id) => utf8.encode(JSON.stringify(id)).length + 1);
26522
+ let total = sizes.reduce((sum, size) => sum + size, 1);
26523
+ let start = 0;
26524
+ while (total > MAX_SOURCE_CHUNK_IDS_BYTES && start < ids.length) total -= sizes[start++];
26525
+ return JSON.stringify(ids.slice(start));
26526
+ }
26527
+
26517
26528
  // src/lib/db/memoryVault/types.ts
26518
26529
  var MEMORY_KINDS = [
26519
26530
  "display_name",
@@ -26732,7 +26743,7 @@ function populateNewVaultMemory(record, ctx, opts, encryptedContent, encryptedKi
26732
26743
  record._setRaw("embedding_model", opts.embeddingModel ?? null);
26733
26744
  }
26734
26745
  if (opts.sourceChunkIds !== void 0) {
26735
- record._setRaw("source_chunk_ids", JSON.stringify(opts.sourceChunkIds));
26746
+ record._setRaw("source_chunk_ids", serializeSourceChunkIds(opts.sourceChunkIds));
26736
26747
  }
26737
26748
  record._setRaw("proof_count", opts.proofCount ?? 1);
26738
26749
  record._setRaw("source", opts.source ?? "manual");
@@ -27216,7 +27227,7 @@ async function updateVaultMemoryOp(ctx, id, opts) {
27216
27227
  if (opts.sourceChunkIds !== void 0) {
27217
27228
  r._setRaw(
27218
27229
  "source_chunk_ids",
27219
- JSON.stringify(
27230
+ serializeSourceChunkIds(
27220
27231
  opts.observationSourceIds?.length ? [.../* @__PURE__ */ new Set([...observedSources, ...opts.sourceChunkIds])] : opts.sourceChunkIds
27221
27232
  )
27222
27233
  );
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@anuma/sdk",
3
- "version": "7.0.5",
3
+ "version": "7.0.7",
4
4
  "description": "",
5
5
  "main": "./dist/index.cjs",
6
6
  "module": "./dist/index.mjs",