@anuma/sdk 6.37.0 → 6.38.0

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.
@@ -4163,7 +4163,7 @@ function extractUserMessageFromMessages(messages) {
4163
4163
  }
4164
4164
 
4165
4165
  // src/lib/db/chat/operations.ts
4166
- function messageToStoredRaw(message, projection) {
4166
+ function messageToStoredRaw(message, projection2) {
4167
4167
  const convId = String(message._getRaw("conversation_id"));
4168
4168
  const parseJsonField = (rawValue) => {
4169
4169
  if (!rawValue) return void 0;
@@ -4177,7 +4177,7 @@ function messageToStoredRaw(message, projection) {
4177
4177
  }
4178
4178
  return rawValue;
4179
4179
  };
4180
- const skipEmbeddings = projection?.skipEmbeddings === true;
4180
+ const skipEmbeddings = projection2?.skipEmbeddings === true;
4181
4181
  const sourcesRaw = message._getRaw("sources");
4182
4182
  const vectorRaw = skipEmbeddings ? null : message._getRaw("vector");
4183
4183
  const chunksRaw = skipEmbeddings ? null : message._getRaw("chunks");
@@ -4211,8 +4211,8 @@ function messageToStoredRaw(message, projection) {
4211
4211
  origin: message.origin
4212
4212
  };
4213
4213
  }
4214
- async function messageToStored(message, walletAddress, signMessage, embeddedWalletSigner, projection) {
4215
- const baseMessage = messageToStoredRaw(message, projection);
4214
+ async function messageToStored(message, walletAddress, signMessage, embeddedWalletSigner, projection2) {
4215
+ const baseMessage = messageToStoredRaw(message, projection2);
4216
4216
  if (walletAddress) {
4217
4217
  return await decryptMessageFields(
4218
4218
  baseMessage,
@@ -4226,7 +4226,7 @@ async function messageToStored(message, walletAddress, signMessage, embeddedWall
4226
4226
  function rawDate(value) {
4227
4227
  return new Date(typeof value === "number" ? value : 0);
4228
4228
  }
4229
- function messageRawToStoredRaw(raw, projection) {
4229
+ function messageRawToStoredRaw(raw, projection2) {
4230
4230
  const parseJsonField = (rawValue) => {
4231
4231
  if (!rawValue) return void 0;
4232
4232
  if (typeof rawValue === "string") {
@@ -4239,7 +4239,7 @@ function messageRawToStoredRaw(raw, projection) {
4239
4239
  }
4240
4240
  return rawValue;
4241
4241
  };
4242
- const skipEmbeddings = projection?.skipEmbeddings === true;
4242
+ const skipEmbeddings = projection2?.skipEmbeddings === true;
4243
4243
  const vectorRaw = skipEmbeddings ? null : raw.vector;
4244
4244
  const chunksRaw = skipEmbeddings ? null : raw.chunks;
4245
4245
  return {
@@ -4270,8 +4270,8 @@ function messageRawToStoredRaw(raw, projection) {
4270
4270
  origin: raw.origin
4271
4271
  };
4272
4272
  }
4273
- async function messageRawToStored(raw, walletAddress, signMessage, embeddedWalletSigner, projection) {
4274
- const baseMessage = messageRawToStoredRaw(raw, projection);
4273
+ async function messageRawToStored(raw, walletAddress, signMessage, embeddedWalletSigner, projection2) {
4274
+ const baseMessage = messageRawToStoredRaw(raw, projection2);
4275
4275
  if (walletAddress) {
4276
4276
  return await decryptMessageFields(
4277
4277
  baseMessage,
@@ -14056,22 +14056,35 @@ async function vaultMemoryRawToStored(raw, walletAddress, signMessage, embeddedW
14056
14056
  return stored2;
14057
14057
  }
14058
14058
  async function getAllVaultMemoriesOp(ctx, options) {
14059
- const conditions = [
14059
+ const results = await ctx.vaultMemoryCollection.query(...vaultListConditions(ctx, options), ...vaultListOrder(options)).unsafeFetchRaw();
14060
+ return mapInBatches(
14061
+ results,
14062
+ (raw) => vaultMemoryRawToStored(raw, ctx.walletAddress, ctx.signMessage, ctx.embeddedWalletSigner)
14063
+ );
14064
+ }
14065
+ function vaultListConditions(ctx, options) {
14066
+ return [
14060
14067
  ...baseVaultConditions(ctx, options),
14061
14068
  ...options?.scopes?.length ? [Q8.where("scope", Q8.oneOf(options.scopes))] : [],
14062
14069
  ...visibilityConditions(options?.visibility),
14063
14070
  ...levelConditions(options?.levels),
14064
14071
  ...options?.kinds?.length ? [Q8.where("kind", Q8.oneOf(options.kinds))] : [],
14065
14072
  ...options?.folderId !== void 0 ? [Q8.where("folder_id", options.folderId)] : [],
14066
- ...options?.factTypes?.length ? [Q8.where("fact_type", Q8.oneOf(options.factTypes))] : [],
14073
+ ...options?.factTypes?.length ? [Q8.where("fact_type", Q8.oneOf(options.factTypes))] : []
14074
+ ];
14075
+ }
14076
+ function vaultListOrder(options) {
14077
+ return [
14067
14078
  Q8.sortBy(options?.since ? "updated_at" : "created_at", Q8.desc),
14068
14079
  ...options?.limit !== null && options?.limit !== void 0 && options.limit > 0 ? [Q8.take(options.limit)] : []
14069
14080
  ];
14070
- const results = await ctx.vaultMemoryCollection.query(...conditions).unsafeFetchRaw();
14071
- return mapInBatches(
14072
- results,
14073
- (raw) => vaultMemoryRawToStored(raw, ctx.walletAddress, ctx.signMessage, ctx.embeddedWalletSigner)
14074
- );
14081
+ }
14082
+ async function getVaultMemoryProjectionsOp(ctx, options) {
14083
+ const results = await ctx.vaultMemoryCollection.query(...vaultListConditions(ctx, options), ...vaultListOrder(options)).unsafeFetchRaw();
14084
+ return results.map((raw) => ({
14085
+ ...vaultMemoryRawToRankable(raw),
14086
+ topicsUserManaged: raw.topics_user_managed === true || raw.topics_user_managed === 1
14087
+ }));
14075
14088
  }
14076
14089
  function vaultMemoryRawToRankable(raw) {
14077
14090
  return {
@@ -21164,6 +21177,7 @@ function createLocalMemoryStore(options) {
21164
21177
  };
21165
21178
  const vaultCache = options.vaultCache ?? createVaultEmbeddingCache();
21166
21179
  const ownedBy = userId !== void 0 ? [Q15.where("user_id", userId)] : [];
21180
+ const linksOwnedBy = userId === void 0 ? [] : options.allowUnscopedRows ? [Q15.or(Q15.where("user_id", userId), Q15.where("user_id", null))] : [Q15.where("user_id", userId)];
21167
21181
  const watchedColumns = [
21168
21182
  "content",
21169
21183
  "scope",
@@ -21206,6 +21220,29 @@ function createLocalMemoryStore(options) {
21206
21220
  },
21207
21221
  memoriesByTopics: (names) => getMemoriesByEntityNamesOp(entityCtx, names),
21208
21222
  topicsByMemories: (memoryIds) => getEntitiesByMemoryIdsOp(entityCtx, memoryIds),
21223
+ listTopics: async () => {
21224
+ const links = await entityCtx.memoryEntityCollection.query(...linksOwnedBy).fetch();
21225
+ const members = /* @__PURE__ */ new Map();
21226
+ for (const link of links) {
21227
+ const entityId = String(link.entityId);
21228
+ const set = members.get(entityId) ?? /* @__PURE__ */ new Set();
21229
+ set.add(String(link.memoryId));
21230
+ members.set(entityId, set);
21231
+ }
21232
+ const entities = userId === void 0 ? await entityCtx.entityCollection.query().fetch() : members.size ? await entityCtx.entityCollection.query(Q15.where("id", Q15.oneOf([...members.keys()]))).fetch() : [];
21233
+ const byName = /* @__PURE__ */ new Map();
21234
+ for (const entity of entities) {
21235
+ const count2 = members.get(entity.id)?.size ?? 0;
21236
+ const existing = byName.get(entity.canonicalName);
21237
+ byName.set(entity.canonicalName, {
21238
+ name: entity.canonicalName,
21239
+ kind: existing?.kind ?? entity.kind ?? null,
21240
+ memoryCount: (existing?.memoryCount ?? 0) + count2
21241
+ });
21242
+ }
21243
+ return [...byName.values()].sort((a, b) => a.name.localeCompare(b.name));
21244
+ },
21245
+ listProjections: (listOptions) => getVaultMemoryProjectionsOp(vaultCtx, listOptions),
21209
21246
  create: async (input) => {
21210
21247
  const created = await createVaultMemoryOp(vaultCtx, input);
21211
21248
  if (input.embedding === void 0) embedInBackground(created);
@@ -21267,7 +21304,6 @@ function createLocalMemoryStore(options) {
21267
21304
  );
21268
21305
  const subscriptions = [memories.subscribe(afterFirst())];
21269
21306
  if (subscribeOptions?.topics) {
21270
- const linksOwnedBy = userId === void 0 ? [] : options.allowUnscopedRows ? [Q15.or(Q15.where("user_id", userId), Q15.where("user_id", null))] : [Q15.where("user_id", userId)];
21271
21307
  subscriptions.push(
21272
21308
  entityCtx.memoryEntityCollection.query(...linksOwnedBy).observe().subscribe(afterFirst())
21273
21309
  );
@@ -21677,6 +21713,31 @@ async function createRemoteMemoryPersistence(options) {
21677
21713
  throw new Error("Invalid nearby candidate response");
21678
21714
  return result;
21679
21715
  };
21716
+ const fetchQueryPage = async (queryOptions) => {
21717
+ const { signal, ...query } = queryOptions;
21718
+ if (query.limit !== void 0 && (!Number.isInteger(query.limit) || query.limit < 1 || query.limit > 200))
21719
+ throw new Error("Page limit must be 1\u2013200");
21720
+ for (const [key, max] of queryListLimits) {
21721
+ const values = query[key];
21722
+ if (values && values.length > max)
21723
+ throw new Error(`Query ${key} accepts at most ${max} entries (got ${values.length})`);
21724
+ }
21725
+ const page = await request(
21726
+ "/memories/query",
21727
+ {
21728
+ method: "POST",
21729
+ body: JSON.stringify(
21730
+ Object.fromEntries(
21731
+ queryFields.filter((key) => query[key] !== void 0).map((key) => [key, query[key]])
21732
+ )
21733
+ )
21734
+ },
21735
+ signal
21736
+ );
21737
+ if (!record(page) || !Array.isArray(page.items) || page.next_cursor !== void 0 && typeof page.next_cursor !== "string" || page.changes_cursor !== void 0 && typeof page.changes_cursor !== "string")
21738
+ throw new Error("Invalid nearby private-memory page");
21739
+ return page;
21740
+ };
21680
21741
  const candidateSet = async (embedding, candidateOptions = {}) => {
21681
21742
  const result = await fetchCandidates(embedding, candidateOptions, true);
21682
21743
  if (!Number.isSafeInteger(result.total_count) || result.total_count < 0 || !Number.isSafeInteger(result.unavailable_count) || result.unavailable_count < 0)
@@ -21755,34 +21816,27 @@ async function createRemoteMemoryPersistence(options) {
21755
21816
  return Promise.all(result.items.map((item, i) => decodeCommitted(item, prepared[i])));
21756
21817
  },
21757
21818
  query: async (queryOptions = {}) => {
21758
- const { signal, ...query } = queryOptions;
21759
- if (query.limit !== void 0 && (!Number.isInteger(query.limit) || query.limit < 1 || query.limit > 200))
21760
- throw new Error("Page limit must be 1\u2013200");
21761
- for (const [key, max] of queryListLimits) {
21762
- const values = query[key];
21763
- if (values && values.length > max)
21764
- throw new Error(`Query ${key} accepts at most ${max} entries (got ${values.length})`);
21765
- }
21766
- const page = await request(
21767
- "/memories/query",
21768
- {
21769
- method: "POST",
21770
- body: JSON.stringify(
21771
- Object.fromEntries(
21772
- queryFields.filter((key) => query[key] !== void 0).map((key) => [key, query[key]])
21773
- )
21774
- )
21775
- },
21776
- signal
21777
- );
21778
- if (!record(page) || !Array.isArray(page.items) || page.next_cursor !== void 0 && typeof page.next_cursor !== "string" || page.changes_cursor !== void 0 && typeof page.changes_cursor !== "string")
21779
- throw new Error("Invalid nearby private-memory page");
21819
+ const page = await fetchQueryPage(queryOptions);
21780
21820
  return {
21781
21821
  ...await decodeAll(page.items),
21782
21822
  ...page.next_cursor !== void 0 && { next_cursor: page.next_cursor },
21783
21823
  ...page.changes_cursor !== void 0 && { changes_cursor: page.changes_cursor }
21784
21824
  };
21785
21825
  },
21826
+ queryMetadata: async (queryOptions = {}) => {
21827
+ const page = await fetchQueryPage(queryOptions);
21828
+ return {
21829
+ items: page.items.map((item) => {
21830
+ const {
21831
+ memory: { content: _content, kind_value: _kindValue, ...memory },
21832
+ version,
21833
+ server_updated_at
21834
+ } = memoryRecord(item);
21835
+ return { memory, version, server_updated_at };
21836
+ }),
21837
+ ...page.next_cursor !== void 0 && { next_cursor: page.next_cursor }
21838
+ };
21839
+ },
21786
21840
  candidateSet,
21787
21841
  candidates: async (embedding, candidateOptions = {}) => decodeAll((await fetchCandidates(embedding, candidateOptions, false)).items)
21788
21842
  };
@@ -22173,6 +22227,19 @@ function createRemoteMemoryPipeline(options) {
22173
22227
 
22174
22228
  // src/lib/memory/store/remoteStore.ts
22175
22229
  import { v7 as uuidv76 } from "uuid";
22230
+ function projection({ memory }) {
22231
+ return {
22232
+ uniqueId: memory.memory_id,
22233
+ scope: memory.scope,
22234
+ folderId: memory.folder_id ?? null,
22235
+ embedding: memory.embedding?.length ? JSON.stringify(memory.embedding) : null,
22236
+ embeddingModel: memory.embedding_model ?? null,
22237
+ createdAt: new Date(memory.created_at),
22238
+ updatedAt: new Date(memory.updated_at),
22239
+ lastObservedAt: memory.last_observed_at ?? null,
22240
+ topicsUserManaged: memory.topics_user_managed ?? false
22241
+ };
22242
+ }
22176
22243
  function relevant(change, options) {
22177
22244
  return options.includeDeleted ? change === "membership" : change !== "embedding" || !!options.embeddings;
22178
22245
  }
@@ -22207,6 +22274,9 @@ function bounded(filters, key) {
22207
22274
  if (!values || values.length <= MAX_QUERY_FILTER) return [filters];
22208
22275
  return chunks(values, MAX_QUERY_FILTER).map((chunk) => ({ ...filters, [key]: chunk }));
22209
22276
  }
22277
+ function maxOf(options) {
22278
+ return options.limit && options.limit > 0 ? options.limit : Infinity;
22279
+ }
22210
22280
  function chunks(values, size) {
22211
22281
  const out = [];
22212
22282
  for (let i = 0; i < values.length; i += size) out.push(values.slice(i, i + size));
@@ -22278,26 +22348,49 @@ function createRemoteMemoryStore(options) {
22278
22348
  for (const subscriber of [...subscribers])
22279
22349
  if (relevant(change, subscriber.options)) safely(subscriber.onChange);
22280
22350
  };
22281
- const enumerate = async (filters, max = Infinity) => {
22351
+ const pages = async (read, filters, max = Infinity) => {
22282
22352
  const records = [];
22283
22353
  let cursor2;
22284
22354
  do {
22285
- const page = await persistence.query({
22355
+ const page = await read({
22286
22356
  ...filters,
22287
22357
  limit: Math.min(200, Math.max(1, max - records.length)),
22288
22358
  ...cursor2 && { cursor: cursor2 }
22289
22359
  });
22290
- warnFailed(page.failed);
22360
+ if (page.failed) warnFailed(page.failed);
22291
22361
  records.push(...page.items);
22292
22362
  cursor2 = page.next_cursor;
22293
22363
  } while (cursor2 && records.length < max);
22294
22364
  return records.slice(0, max);
22295
22365
  };
22296
- const enumerateIds = async (ids, filters) => (await Promise.all(
22366
+ const decrypted = (options2) => persistence.query(options2);
22367
+ const metadata = (options2) => persistence.queryMetadata(options2);
22368
+ const enumerate = (filters, max = Infinity) => pages(decrypted, filters, max);
22369
+ const enumerateIds = async (read, ids, filters) => (await Promise.all(
22297
22370
  chunks([...new Set(ids)], MAX_QUERY_IDS).map(
22298
- (memory_ids) => enumerate({ ...filters, memory_ids })
22371
+ (memory_ids) => pages(read, { ...filters, memory_ids })
22299
22372
  )
22300
22373
  )).flat();
22374
+ const listFilters = (listOptions) => ({
22375
+ ...stateFilters(listOptions),
22376
+ include_embeddings: true,
22377
+ order: listOptions.since ? "updated" : "created",
22378
+ ...listOptions.scopes?.length && { scopes: listOptions.scopes },
22379
+ ...listOptions.factTypes?.length && { fact_types: listOptions.factTypes },
22380
+ ...listOptions.visibility?.length && { visibility: listOptions.visibility },
22381
+ ...listOptions.since && { updated_after: listOptions.since.getTime() }
22382
+ });
22383
+ const listRows = async (read, listOptions, filters, max) => {
22384
+ const variants = bounded(filters, "scopes").flatMap((f) => bounded(f, "fact_types"));
22385
+ if (!listOptions.memoryIds && variants.length === 1) return pages(read, filters, max);
22386
+ const fetched = await Promise.all(
22387
+ variants.map(
22388
+ (variant) => listOptions.memoryIds ? enumerateIds(read, listOptions.memoryIds, variant) : pages(read, variant, max)
22389
+ )
22390
+ );
22391
+ const time = (row) => filters.order === "updated" ? row.memory.updated_at : row.memory.created_at;
22392
+ return [...new Map(fetched.flat().map((r) => [r.memory.memory_id, r])).values()].sort((a, b) => time(b) - time(a) || (a.memory.memory_id < b.memory.memory_id ? 1 : -1)).slice(0, max);
22393
+ };
22301
22394
  const queues = /* @__PURE__ */ new Map();
22302
22395
  const serialized = (id, task) => {
22303
22396
  const run = (queues.get(id) ?? Promise.resolve()).then(task, task);
@@ -22339,12 +22432,15 @@ function createRemoteMemoryStore(options) {
22339
22432
  };
22340
22433
  const newRow = (input) => {
22341
22434
  const now = Date.now();
22342
- const scope = input.scope ?? "private";
22435
+ const { level, scope } = resolveCreateLevel(input);
22436
+ assertValidKindLevel(input.kind, level);
22343
22437
  return {
22344
22438
  memory_id: uuidv76(),
22345
22439
  content: input.content,
22346
22440
  scope,
22347
- level: levelFromScope(scope),
22441
+ level,
22442
+ ...input.kind !== void 0 && input.kind !== null && { kind: input.kind },
22443
+ ...typeof input.kindValue === "string" && { kind_value: input.kindValue },
22348
22444
  created_at: now,
22349
22445
  updated_at: now,
22350
22446
  is_deleted: false,
@@ -22373,6 +22469,30 @@ function createRemoteMemoryStore(options) {
22373
22469
  return records.map((record2) => stored(record2.memory));
22374
22470
  };
22375
22471
  const asStored = (record2) => record2 ? stored(record2.memory) : null;
22472
+ const withKnownKinds = async (topics) => {
22473
+ const unkinded = [
22474
+ ...new Set(topics.filter((t) => !t.kind).map((t) => normalizeEntityName(t.name)))
22475
+ ];
22476
+ if (unkinded.length === 0) return topics;
22477
+ const kinds = /* @__PURE__ */ new Map();
22478
+ for (const names of chunks(unkinded, MAX_QUERY_TOPICS)) {
22479
+ for (const { memory } of await pages(metadata, {
22480
+ topics: names,
22481
+ include_archived: true,
22482
+ include_quarantined: true,
22483
+ include_superseded: true
22484
+ })) {
22485
+ for (const topic of parseTopics(memory.topics) ?? []) {
22486
+ const name = normalizeEntityName(topic.name);
22487
+ if (topic.kind && !kinds.has(name)) kinds.set(name, topic.kind);
22488
+ }
22489
+ }
22490
+ }
22491
+ return topics.map((topic) => {
22492
+ const kind = topic.kind ?? kinds.get(normalizeEntityName(topic.name));
22493
+ return kind ? { ...topic, kind } : topic;
22494
+ });
22495
+ };
22376
22496
  const everyState = {
22377
22497
  include_deleted: true,
22378
22498
  include_archived: true,
@@ -22449,30 +22569,34 @@ function createRemoteMemoryStore(options) {
22449
22569
  });
22450
22570
  };
22451
22571
  return {
22452
- list: async (listOptions = {}) => {
22453
- const order = listOptions.since ? "updated" : "created";
22454
- const filters = {
22455
- ...stateFilters(listOptions),
22456
- include_embeddings: true,
22457
- order,
22458
- ...listOptions.scopes?.length && { scopes: listOptions.scopes },
22459
- ...listOptions.factTypes?.length && { fact_types: listOptions.factTypes },
22460
- ...listOptions.visibility?.length && { visibility: listOptions.visibility },
22461
- ...listOptions.since && { updated_after: listOptions.since.getTime() }
22462
- };
22463
- const max = listOptions.limit && listOptions.limit > 0 ? listOptions.limit : Infinity;
22464
- const variants = bounded(filters, "scopes").flatMap((f) => bounded(f, "fact_types"));
22465
- if (!listOptions.memoryIds && variants.length === 1)
22466
- return (await enumerate(filters, max)).map((r) => stored(r.memory));
22467
- const fetched = await Promise.all(
22468
- variants.map(
22469
- (variant) => listOptions.memoryIds ? enumerateIds(listOptions.memoryIds, variant) : enumerate(variant, max)
22470
- )
22471
- );
22472
- const rows = [...new Map(fetched.flat().map((r) => [r.memory.memory_id, r])).values()].map((record2) => stored(record2.memory)).sort(
22473
- (a, b) => order === "updated" ? b.updatedAt.getTime() - a.updatedAt.getTime() || (a.uniqueId < b.uniqueId ? 1 : -1) : b.createdAt.getTime() - a.createdAt.getTime() || (a.uniqueId < b.uniqueId ? 1 : -1)
22474
- );
22475
- return rows.slice(0, max);
22572
+ list: async (listOptions = {}) => (await listRows(decrypted, listOptions, listFilters(listOptions), maxOf(listOptions))).map(
22573
+ (r) => stored(r.memory)
22574
+ ),
22575
+ listProjections: async (listOptions = {}) => (await listRows(metadata, listOptions, listFilters(listOptions), maxOf(listOptions))).map(
22576
+ projection
22577
+ ),
22578
+ listTopics: async () => {
22579
+ const topics = /* @__PURE__ */ new Map();
22580
+ for (const { memory } of await pages(metadata, {
22581
+ include_archived: true,
22582
+ include_quarantined: true,
22583
+ include_superseded: true
22584
+ })) {
22585
+ for (const topic of parseTopics(memory.topics) ?? []) {
22586
+ const name = normalizeEntityName(topic.name);
22587
+ if (!name) continue;
22588
+ const entry = topics.get(name) ?? {
22589
+ name,
22590
+ kind: null,
22591
+ memoryCount: 0,
22592
+ members: /* @__PURE__ */ new Set()
22593
+ };
22594
+ entry.kind ?? (entry.kind = topic.kind ?? null);
22595
+ entry.members.add(memory.memory_id);
22596
+ topics.set(name, entry);
22597
+ }
22598
+ }
22599
+ return [...topics.values()].map(({ members, ...topic }) => ({ ...topic, memoryCount: members.size })).sort((a, b) => a.name.localeCompare(b.name));
22476
22600
  },
22477
22601
  get: async (id) => asStored(await live(id)),
22478
22602
  listArchived: async () => (await enumerate({ archived_only: true, order: "archived", include_embeddings: true })).map(
@@ -22481,10 +22605,10 @@ function createRemoteMemoryStore(options) {
22481
22605
  memoriesByTopics: async (names) => {
22482
22606
  const wanted = new Set(names.map(normalizeEntityName).filter(Boolean));
22483
22607
  const out = /* @__PURE__ */ new Map();
22484
- const pages = await Promise.all(
22608
+ const pages2 = await Promise.all(
22485
22609
  chunks([...wanted], MAX_QUERY_TOPICS).map((topics) => enumerate({ topics }))
22486
22610
  );
22487
- for (const { memory } of pages.flat()) {
22611
+ for (const { memory } of pages2.flat()) {
22488
22612
  const matched = [...canonicalTopics(memory)].filter((name) => wanted.has(name));
22489
22613
  if (matched.length) out.set(memory.memory_id, new Set(matched));
22490
22614
  }
@@ -22492,7 +22616,7 @@ function createRemoteMemoryStore(options) {
22492
22616
  },
22493
22617
  topicsByMemories: async (memoryIds) => {
22494
22618
  const out = /* @__PURE__ */ new Map();
22495
- for (const { memory } of await enumerateIds(memoryIds, {
22619
+ for (const { memory } of await enumerateIds(decrypted, memoryIds, {
22496
22620
  include_archived: true,
22497
22621
  include_superseded: true,
22498
22622
  include_quarantined: true
@@ -22525,15 +22649,26 @@ function createRemoteMemoryStore(options) {
22525
22649
  update: async (id, patch) => {
22526
22650
  const saved = await mutate(id, "edit", (memory) => {
22527
22651
  if (memory.superseded_by) return null;
22652
+ const level = patch.level !== void 0 ? patch.level : patch.scope !== void 0 ? levelForScopeChange({ level: memory.level, scope: memory.scope }, patch.scope) : resolveMemoryLevel(memory.level, memory.scope);
22653
+ const kind = patch.kind !== void 0 ? patch.kind : memory.kind;
22654
+ assertValidKindLevel(kind, level);
22528
22655
  memory.content = patch.content;
22529
22656
  memory.updated_at = Date.now();
22530
- if (patch.scope !== void 0) {
22531
- memory.level = levelForScopeChange(
22532
- { level: memory.level, scope: memory.scope },
22533
- patch.scope
22534
- );
22657
+ if (patch.level !== void 0) {
22658
+ memory.level = level;
22659
+ memory.scope = scopeForLevel(level);
22660
+ } else if (patch.scope !== void 0) {
22661
+ memory.level = level;
22535
22662
  memory.scope = patch.scope;
22536
22663
  }
22664
+ if (patch.kind !== void 0) {
22665
+ if (patch.kind === null) delete memory.kind;
22666
+ else memory.kind = patch.kind;
22667
+ }
22668
+ if (patch.kindValue !== void 0) {
22669
+ if (patch.kindValue === null) delete memory.kind_value;
22670
+ else memory.kind_value = patch.kindValue;
22671
+ }
22537
22672
  if (patch.factType !== void 0) memory.fact_type = patch.factType ?? void 0;
22538
22673
  if (patch.eventTime !== void 0) {
22539
22674
  memory.event_time_start = patch.eventTime?.start ?? void 0;
@@ -22588,16 +22723,19 @@ function createRemoteMemoryStore(options) {
22588
22723
  notify("edit", [await persistence.put(memory, record2)]);
22589
22724
  return true;
22590
22725
  }),
22591
- setTopics: async (memoryId, topics) => asStored(
22592
- await mutate(memoryId, "edit", (memory) => ({
22593
- ...memory,
22594
- topics: serializeTopics(mergeTopics([], topicInputs(topics, "user"))),
22595
- topics_user_managed: true,
22596
- topics_updated_at: Date.now()
22597
- }))
22598
- ),
22726
+ setTopics: async (memoryId, topics) => {
22727
+ const chosen = await withKnownKinds(topicInputs(topics, "user"));
22728
+ return asStored(
22729
+ await mutate(memoryId, "edit", (memory) => ({
22730
+ ...memory,
22731
+ topics: serializeTopics(mergeTopics([], chosen)),
22732
+ topics_user_managed: true,
22733
+ topics_updated_at: Date.now()
22734
+ }))
22735
+ );
22736
+ },
22599
22737
  addTopics: async (memoryId, topics) => {
22600
- const added = topicInputs(topics, "auto");
22738
+ const added = await withKnownKinds(topicInputs(topics, "auto"));
22601
22739
  const saved = await mutate(memoryId, "edit", (memory) => ({
22602
22740
  ...memory,
22603
22741
  topics: serializeTopics(mergeTopics(parseTopics(memory.topics) ?? [], added)),
@@ -28093,22 +28093,35 @@ async function vaultMemoryRawToStored(raw, walletAddress, signMessage, embeddedW
28093
28093
  return stored;
28094
28094
  }
28095
28095
  async function getAllVaultMemoriesOp(ctx, options) {
28096
- const conditions = [
28096
+ const results = await ctx.vaultMemoryCollection.query(...vaultListConditions(ctx, options), ...vaultListOrder(options)).unsafeFetchRaw();
28097
+ return mapInBatches(
28098
+ results,
28099
+ (raw) => vaultMemoryRawToStored(raw, ctx.walletAddress, ctx.signMessage, ctx.embeddedWalletSigner)
28100
+ );
28101
+ }
28102
+ function vaultListConditions(ctx, options) {
28103
+ return [
28097
28104
  ...baseVaultConditions(ctx, options),
28098
28105
  ...options?.scopes?.length ? [import_watermelondb19.Q.where("scope", import_watermelondb19.Q.oneOf(options.scopes))] : [],
28099
28106
  ...visibilityConditions(options?.visibility),
28100
28107
  ...levelConditions(options?.levels),
28101
28108
  ...options?.kinds?.length ? [import_watermelondb19.Q.where("kind", import_watermelondb19.Q.oneOf(options.kinds))] : [],
28102
28109
  ...options?.folderId !== void 0 ? [import_watermelondb19.Q.where("folder_id", options.folderId)] : [],
28103
- ...options?.factTypes?.length ? [import_watermelondb19.Q.where("fact_type", import_watermelondb19.Q.oneOf(options.factTypes))] : [],
28110
+ ...options?.factTypes?.length ? [import_watermelondb19.Q.where("fact_type", import_watermelondb19.Q.oneOf(options.factTypes))] : []
28111
+ ];
28112
+ }
28113
+ function vaultListOrder(options) {
28114
+ return [
28104
28115
  import_watermelondb19.Q.sortBy(options?.since ? "updated_at" : "created_at", import_watermelondb19.Q.desc),
28105
28116
  ...options?.limit !== null && options?.limit !== void 0 && options.limit > 0 ? [import_watermelondb19.Q.take(options.limit)] : []
28106
28117
  ];
28107
- const results = await ctx.vaultMemoryCollection.query(...conditions).unsafeFetchRaw();
28108
- return mapInBatches(
28109
- results,
28110
- (raw) => vaultMemoryRawToStored(raw, ctx.walletAddress, ctx.signMessage, ctx.embeddedWalletSigner)
28111
- );
28118
+ }
28119
+ async function getVaultMemoryProjectionsOp(ctx, options) {
28120
+ const results = await ctx.vaultMemoryCollection.query(...vaultListConditions(ctx, options), ...vaultListOrder(options)).unsafeFetchRaw();
28121
+ return results.map((raw) => ({
28122
+ ...vaultMemoryRawToRankable(raw),
28123
+ topicsUserManaged: raw.topics_user_managed === true || raw.topics_user_managed === 1
28124
+ }));
28112
28125
  }
28113
28126
  function vaultMemoryRawToRankable(raw) {
28114
28127
  return {
@@ -34945,6 +34958,7 @@ function createLocalMemoryStore(options) {
34945
34958
  };
34946
34959
  const vaultCache = options.vaultCache ?? createVaultEmbeddingCache();
34947
34960
  const ownedBy = userId !== void 0 ? [import_watermelondb24.Q.where("user_id", userId)] : [];
34961
+ const linksOwnedBy = userId === void 0 ? [] : options.allowUnscopedRows ? [import_watermelondb24.Q.or(import_watermelondb24.Q.where("user_id", userId), import_watermelondb24.Q.where("user_id", null))] : [import_watermelondb24.Q.where("user_id", userId)];
34948
34962
  const watchedColumns = [
34949
34963
  "content",
34950
34964
  "scope",
@@ -34987,6 +35001,29 @@ function createLocalMemoryStore(options) {
34987
35001
  },
34988
35002
  memoriesByTopics: (names) => getMemoriesByEntityNamesOp(entityCtx, names),
34989
35003
  topicsByMemories: (memoryIds) => getEntitiesByMemoryIdsOp(entityCtx, memoryIds),
35004
+ listTopics: async () => {
35005
+ const links = await entityCtx.memoryEntityCollection.query(...linksOwnedBy).fetch();
35006
+ const members = /* @__PURE__ */ new Map();
35007
+ for (const link of links) {
35008
+ const entityId = String(link.entityId);
35009
+ const set = members.get(entityId) ?? /* @__PURE__ */ new Set();
35010
+ set.add(String(link.memoryId));
35011
+ members.set(entityId, set);
35012
+ }
35013
+ const entities = userId === void 0 ? await entityCtx.entityCollection.query().fetch() : members.size ? await entityCtx.entityCollection.query(import_watermelondb24.Q.where("id", import_watermelondb24.Q.oneOf([...members.keys()]))).fetch() : [];
35014
+ const byName = /* @__PURE__ */ new Map();
35015
+ for (const entity of entities) {
35016
+ const count = members.get(entity.id)?.size ?? 0;
35017
+ const existing = byName.get(entity.canonicalName);
35018
+ byName.set(entity.canonicalName, {
35019
+ name: entity.canonicalName,
35020
+ kind: existing?.kind ?? entity.kind ?? null,
35021
+ memoryCount: (existing?.memoryCount ?? 0) + count
35022
+ });
35023
+ }
35024
+ return [...byName.values()].sort((a, b) => a.name.localeCompare(b.name));
35025
+ },
35026
+ listProjections: (listOptions) => getVaultMemoryProjectionsOp(vaultCtx, listOptions),
34990
35027
  create: async (input) => {
34991
35028
  const created = await createVaultMemoryOp(vaultCtx, input);
34992
35029
  if (input.embedding === void 0) embedInBackground(created);
@@ -35048,7 +35085,6 @@ function createLocalMemoryStore(options) {
35048
35085
  );
35049
35086
  const subscriptions = [memories.subscribe(afterFirst())];
35050
35087
  if (subscribeOptions?.topics) {
35051
- const linksOwnedBy = userId === void 0 ? [] : options.allowUnscopedRows ? [import_watermelondb24.Q.or(import_watermelondb24.Q.where("user_id", userId), import_watermelondb24.Q.where("user_id", null))] : [import_watermelondb24.Q.where("user_id", userId)];
35052
35088
  subscriptions.push(
35053
35089
  entityCtx.memoryEntityCollection.query(...linksOwnedBy).observe().subscribe(afterFirst())
35054
35090
  );