@anuma/sdk 6.38.0 → 6.39.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.
@@ -1511,6 +1511,7 @@ __export(index_exports, {
1511
1511
  clearKeyPair: () => clearKeyPair,
1512
1512
  clearLazyTitleCache: () => clearLazyTitleCache,
1513
1513
  clearMemoryTopicsOverrideOp: () => clearMemoryTopicsOverrideOp,
1514
+ clearModelsCache: () => clearModelsCache,
1514
1515
  clearNotionToken: () => clearNotionToken,
1515
1516
  clearServerToolsCache: () => clearServerToolsCache,
1516
1517
  consoleLogger: () => consoleLogger,
@@ -7869,15 +7870,17 @@ Build ONLY when the user gives an explicit instruction to build, create, generat
7869
7870
 
7870
7871
  Once the user HAS given an explicit build instruction, you are in App Builder mode: you produce polished, production-quality React apps that feel designed \u2014 not generic.
7871
7872
 
7872
- DESIGN: on the initial build, before writing code, briefly state (2-3 sentences) what you want this app to feel like \u2014 name the specific fonts, the palette in hex, and one signature detail. Be concrete: "Fraunces display + Inter body + JetBrains Mono metadata, terracotta #b75432 accent on bone #f3efe6, paper-grain texture via inline SVG noise" is the kind of specificity that anchors the build. Default to nothing: don't pick "safe modern productivity" unless the brief literally asks for utilitarian. On later turns, state a design brief only when the change is visual (a restyle, new theme, or new UI); for a logic, data, or behavior-only change, skip the brief and just make the change.
7873
+ DESIGN: on the initial build, before writing code, briefly state (2-3 sentences) what you want this app to feel like \u2014 name the specific fonts, the palette in hex, and one signature detail. Be concrete: "Fraunces display + Inter body + JetBrains Mono metadata, terracotta #b75432 accent on bone #f3efe6, paper-grain texture via inline SVG noise" is the kind of specificity that anchors the build. Default to nothing: don't pick "safe modern productivity" unless the brief literally asks for utilitarian. On later turns, state a design brief only when the change is visual (a restyle, new theme, or new UI); for a text, logic, data, or behavior-only change, skip the brief and just make the change.
7874
+
7875
+ EDIT SCOPE: Change only the files and lines required by the current user request. A title rename is a text edit, not a design change. Preserve styles, dependencies, and unrelated logic on text edits. Design feedback does not authorize unrelated edits.
7873
7876
 
7874
7877
  WORKFLOW:
7875
7878
  1. NEVER output code as text or markdown. ALWAYS use tools.
7876
7879
  2. Initial build: state your design brief, then create_file with a "files" array writing ALL files in one call. The preview renders automatically.
7877
7880
  3. patch_file requires read_file for that path earlier in the conversation (or create_file in the same conversation, which counts). read_file output is numbered "42: <text>" \u2014 the prefix is display-only; never copy it into "find". Each "find" must match exactly one location \u2014 include 2-3 lines of surrounding context. Pass multiple patches per call to change distinct locations.
7878
7881
  4. Prefer patch_file for changes to existing files \u2014 surgical, reviewable, preserves surrounding code. Reserve create_file overwrites for substantial restructuring. Inserts: find the line before, replace with that line + the new line. Deletes: empty replace.
7879
- 5. After substantial changes, call critique_design first (taste, hierarchy, distinctiveness, weakest decision) and then audit_design (mechanical: tokens, focus states, aria-labels, alt, heading order). Patch what each surfaces. critique catches taste issues no checklist would; audit catches mechanics you'd miss. Run both; act on both.
7880
- 6. Before declaring done, call verify_app. The host's preview runtime reports whether your app actually mounted and surfaces any errors it captured \u2014 hallucinated imports, syntax the bundler rejected, undefined components, runtime crashes. If \`rendered\` is false or \`errors\` is non-empty, fix every error before the next message. If the response includes a \`note\` that verify_app isn't wired in this host, skip \u2014 audit + critique are your feedback in that case.
7882
+ 5. On the initial build, when adding new UI, or after user-requested design changes, call critique_design first and then audit_design. Critique checks taste, hierarchy, and distinctiveness. Audit checks tokens, focus states, aria-labels, alt text, and heading order. Patch only issues within the current user request. For text, logic, or data edits, skip both design tools.
7883
+ 6. Before declaring done, call verify_app. The host's preview runtime reports whether your app actually mounted and surfaces any errors it captured \u2014 hallucinated imports, syntax the bundler rejected, undefined components, runtime crashes. If \`rendered\` is false or \`errors\` is non-empty, fix every error before the next message. If the response includes a \`note\` that verify_app isn't wired in this host, skip runtime verification. An unavailable runtime verifier does not authorize design changes. Use audit_design and critique_design only for the initial build, adding new UI, or user-requested design changes.
7881
7884
  7. Keep responses to a sentence or two. Exception: when responding to critique_design, write a substantive paragraph per rubric question.
7882
7885
 
7883
7886
  STRUCTURE:
@@ -8044,12 +8047,13 @@ function isCacheExpired(cache, expirationMs = DEFAULT_CACHE_EXPIRATION_MS) {
8044
8047
  if (!cache) return true;
8045
8048
  return Date.now() - cache.timestamp > expirationMs;
8046
8049
  }
8047
- function buildCacheEntry(tools, checksum) {
8050
+ function buildCacheEntry(tools, checksum, etag) {
8048
8051
  return {
8049
8052
  tools,
8050
8053
  timestamp: Date.now(),
8051
8054
  version: CACHE_VERSION,
8052
- ...checksum && { checksum }
8055
+ ...checksum && { checksum },
8056
+ ...etag && { etag }
8053
8057
  };
8054
8058
  }
8055
8059
  function writeLocalStorageCache(entry) {
@@ -8084,19 +8088,36 @@ function shouldRefreshTools(responseChecksum, cache = localStorageToolsCache) {
8084
8088
  const cachedChecksum = getToolsChecksum2(cache);
8085
8089
  return cachedChecksum instanceof Promise ? cachedChecksum.then(decide) : decide(cachedChecksum);
8086
8090
  }
8087
- async function fetchServerToolsFromApi(baseUrl, token) {
8088
- const response = await fetch(`${baseUrl}/api/v1/tools`, {
8091
+ async function fetchServerToolsFromApi(baseUrl, authHeaders, etag) {
8092
+ const request = (validator) => fetch(`${baseUrl}/api/v1/tools`, {
8089
8093
  method: "GET",
8090
8094
  headers: {
8091
- Authorization: `Bearer ${token}`,
8092
- "Content-Type": "application/json"
8095
+ ...authHeaders,
8096
+ "Content-Type": "application/json",
8097
+ ...validator && { "If-None-Match": validator }
8093
8098
  }
8094
8099
  });
8100
+ let response;
8101
+ try {
8102
+ response = await request(etag);
8103
+ } catch (error) {
8104
+ if (!etag || !(error instanceof TypeError)) throw error;
8105
+ etag = void 0;
8106
+ response = await request();
8107
+ }
8108
+ if (etag && response.status === 304) {
8109
+ return { notModified: true };
8110
+ }
8095
8111
  if (!response.ok) {
8096
8112
  throw new Error(`Failed to fetch server tools: ${response.status}`);
8097
8113
  }
8098
8114
  const data = await response.json();
8099
- return convertServerToolsResponse(data);
8115
+ const responseEtag = response.headers?.get("ETag") ?? void 0;
8116
+ return {
8117
+ notModified: false,
8118
+ ...convertServerToolsResponse(data),
8119
+ ...responseEtag && { etag: responseEtag }
8120
+ };
8100
8121
  }
8101
8122
  async function getServerTools(options) {
8102
8123
  const {
@@ -8128,34 +8149,30 @@ async function getServerTools(options) {
8128
8149
  try {
8129
8150
  const { BASE_URL: BASE_URL2 } = await Promise.resolve().then(() => (init_clientConfig(), clientConfig_exports));
8130
8151
  const effectiveBaseUrl = baseUrl ?? BASE_URL2;
8152
+ const validator = cached && !forceRefresh ? cached.etag : void 0;
8153
+ let authHeaders;
8131
8154
  if (apiKey) {
8132
- const response = await fetch(`${effectiveBaseUrl}/api/v1/tools`, {
8133
- method: "GET",
8134
- headers: {
8135
- "X-API-Key": apiKey,
8136
- "Content-Type": "application/json"
8137
- }
8138
- });
8139
- if (!response.ok) {
8140
- throw new Error(`Failed to fetch server tools: ${response.status}`);
8155
+ authHeaders = { "X-API-Key": apiKey };
8156
+ } else {
8157
+ if (!getToken) {
8158
+ getLogger().warn("[serverTools] No auth method available for fetching tools");
8159
+ return cached?.tools ?? [];
8141
8160
  }
8142
- const data = await response.json();
8143
- const { tools: tools2, checksum: checksum2 } = convertServerToolsResponse(data);
8144
- await persistCache(buildCacheEntry(tools2, checksum2));
8145
- return tools2;
8146
- }
8147
- if (!getToken) {
8148
- getLogger().warn("[serverTools] No auth method available for fetching tools");
8149
- return cached?.tools ?? [];
8161
+ const token = await getToken();
8162
+ if (!token) {
8163
+ getLogger().warn("[serverTools] No auth token available for fetching tools");
8164
+ return cached?.tools ?? [];
8165
+ }
8166
+ authHeaders = { Authorization: `Bearer ${token}` };
8150
8167
  }
8151
- const token = await getToken();
8152
- if (!token) {
8153
- getLogger().warn("[serverTools] No auth token available for fetching tools");
8154
- return cached?.tools ?? [];
8168
+ const result = await fetchServerToolsFromApi(effectiveBaseUrl, authHeaders, validator);
8169
+ if (result.notModified) {
8170
+ const confirmed = cached;
8171
+ await persistCache({ ...confirmed, timestamp: Date.now() });
8172
+ return confirmed.tools;
8155
8173
  }
8156
- const { tools, checksum } = await fetchServerToolsFromApi(effectiveBaseUrl, token);
8157
- await persistCache(buildCacheEntry(tools, checksum));
8158
- return tools;
8174
+ await persistCache(buildCacheEntry(result.tools, result.checksum, result.etag));
8175
+ return result.tools;
8159
8176
  } catch (error) {
8160
8177
  getLogger().error("[serverTools] Failed to fetch server tools:", error);
8161
8178
  if (cached?.tools) {
@@ -22076,7 +22093,6 @@ async function recall(query, ctx, options = {}) {
22076
22093
  }
22077
22094
  const needsChunkEmbedding = types.includes("chunk") && ctx.storageCtx;
22078
22095
  const wantsTemporal = types.includes("fact") && (ctx.factSource || ctx.vaultCtx);
22079
- const graphRefiner = flags.traverse && options.graphRefine && options.decomposeOptions ? createLlmNeighborRefiner(options.decomposeOptions) : void 0;
22080
22096
  const queryEmbedTotalTimeoutMs = options.queryEmbedTotalTimeoutMs ?? DEFAULT_QUERY_EMBED_TOTAL_TIMEOUT_MS;
22081
22097
  const prepStart = nowMs2();
22082
22098
  let sharedEmbedMs = 0;
@@ -22105,13 +22121,12 @@ async function recall(query, ctx, options = {}) {
22105
22121
  safeLane(
22106
22122
  "graph",
22107
22123
  () => graphLaneFailed = true,
22108
- () => ctx.factSource ? ctx.factSource.graphRanking(query, flags.traverse, options) : buildGraphLaneRanking(query, ctx, flags.traverse, {
22109
- ...options.maxHops !== void 0 && { maxHops: options.maxHops },
22110
- ...options.entityFanout !== void 0 && { entityFanout: options.entityFanout },
22111
- ...options.nodeBudget !== void 0 && { nodeBudget: options.nodeBudget },
22112
- ...options.rrfK !== void 0 && { rrfK: options.rrfK },
22113
- ...graphRefiner && { refineNeighbors: graphRefiner }
22114
- })
22124
+ () => ctx.factSource ? ctx.factSource.graphRanking(query, flags.traverse, options) : buildGraphLaneRanking(
22125
+ query,
22126
+ ctx,
22127
+ flags.traverse,
22128
+ graphTraversalOptions(options, flags.traverse)
22129
+ )
22115
22130
  ),
22116
22131
  wantsTemporal ? safeLane(
22117
22132
  "temporal",
@@ -22330,6 +22345,16 @@ function toFactMemory(r, now) {
22330
22345
  updatedAt: r.updatedAt ?? /* @__PURE__ */ new Date(0)
22331
22346
  };
22332
22347
  }
22348
+ function graphTraversalOptions(options, traverse) {
22349
+ const refineNeighbors = traverse && options.graphRefine && options.decomposeOptions ? createLlmNeighborRefiner(options.decomposeOptions) : void 0;
22350
+ return {
22351
+ ...options.maxHops !== void 0 && { maxHops: options.maxHops },
22352
+ ...options.entityFanout !== void 0 && { entityFanout: options.entityFanout },
22353
+ ...options.nodeBudget !== void 0 && { nodeBudget: options.nodeBudget },
22354
+ ...options.rrfK !== void 0 && { rrfK: options.rrfK },
22355
+ ...refineNeighbors && { refineNeighbors }
22356
+ };
22357
+ }
22333
22358
  async function buildGraphLaneRanking(query, ctx, traverse = false, traversalOptions = {}) {
22334
22359
  const entityCtx = ctx.entityCtx ?? ctx.vaultCtx?.entityCtx;
22335
22360
  if (!entityCtx) return [];
@@ -22495,24 +22520,33 @@ function isDumpQuery(query) {
22495
22520
  return false;
22496
22521
  }
22497
22522
  async function listRecentFacts(ctx, limit, toolOptions) {
22523
+ const store = toolOptions?.memoryStore;
22498
22524
  const vaultCtx = ctx.vaultCtx;
22499
- if (!vaultCtx) return [];
22500
- const ordered = await getVaultRankingProjectionsOp(vaultCtx, {
22525
+ if (!vaultCtx && !store) return [];
22526
+ const read = (ids) => store ? store.list({ memoryIds: ids }) : getVaultMemoriesByIdsOp(vaultCtx, ids);
22527
+ const filters = {
22501
22528
  ...toolOptions?.scopes && { scopes: toolOptions.scopes },
22502
- ...toolOptions?.memoryIds !== void 0 && { memoryIds: toolOptions.memoryIds },
22529
+ ...toolOptions?.memoryIds !== void 0 && { memoryIds: toolOptions.memoryIds }
22530
+ };
22531
+ const project = (size) => store ? store.listProjections({ ...filters, limit: size }) : getVaultRankingProjectionsOp(vaultCtx, {
22532
+ ...filters,
22503
22533
  ...toolOptions?.folderId !== void 0 && { folderId: toolOptions.folderId }
22504
22534
  });
22505
22535
  const readable = [];
22506
- for (let i = 0; i < ordered.length && readable.length < limit; i += limit) {
22507
- const batch = ordered.slice(i, i + limit).map((p) => p.uniqueId);
22508
- const byId = new Map(
22509
- (await getVaultMemoriesByIdsOp(vaultCtx, batch)).map((m) => [m.uniqueId, m])
22510
- );
22511
- for (const id of batch) {
22512
- const m = byId.get(id);
22513
- if (m && !isEncrypted(m.content)) readable.push(m);
22514
- if (readable.length >= limit) break;
22536
+ let start = 0;
22537
+ for (let size = limit; readable.length < limit; size *= 2) {
22538
+ const ordered = await project(size);
22539
+ for (let i = start; i < ordered.length && readable.length < limit; i += limit) {
22540
+ const batch = ordered.slice(i, i + limit).map((p) => p.uniqueId);
22541
+ const byId = new Map((await read(batch)).map((m) => [m.uniqueId, m]));
22542
+ for (const id of batch) {
22543
+ const m = byId.get(id);
22544
+ if (m && !isEncrypted(m.content)) readable.push(m);
22545
+ if (readable.length >= limit) break;
22546
+ }
22515
22547
  }
22548
+ if (!store || ordered.length < size) break;
22549
+ start = ordered.length;
22516
22550
  }
22517
22551
  return readable.map((m) => ({
22518
22552
  id: m.uniqueId,
@@ -22529,6 +22563,8 @@ async function listRecentFacts(ctx, limit, toolOptions) {
22529
22563
  }));
22530
22564
  }
22531
22565
  function createRecallTool(ctx, toolOptions, callbacks) {
22566
+ if (toolOptions?.memoryStore && toolOptions.folderId !== void 0)
22567
+ throw new Error("Folders are not supported with a memoryStore");
22532
22568
  const defaultTypes = toolOptions?.types ?? ["fact", "chunk"];
22533
22569
  const defaultLimit = toolOptions?.limit ?? DEFAULT_LIMIT2;
22534
22570
  const defaultBudget = toolOptions?.budget ?? DEFAULT_BUDGET2;
@@ -22600,7 +22636,7 @@ function createRecallTool(ctx, toolOptions, callbacks) {
22600
22636
  let surfaced = 0;
22601
22637
  try {
22602
22638
  let recallDegraded = [];
22603
- const wantsRecent = args.sort === "recent" && defaultTypes.includes("fact") && ctx.vaultCtx !== void 0;
22639
+ const wantsRecent = args.sort === "recent" && defaultTypes.includes("fact") && (ctx.vaultCtx !== void 0 || toolOptions?.memoryStore !== void 0);
22604
22640
  let result;
22605
22641
  if (wantsRecent) {
22606
22642
  result = { memories: await listRecentFacts(ctx, effectiveLimit, toolOptions) };
@@ -23110,6 +23146,7 @@ function createLocalMemoryStore(options) {
23110
23146
  });
23111
23147
  };
23112
23148
  return {
23149
+ masksEmbeddingInput: options.embeddingOptions.maskInput !== void 0,
23113
23150
  list: (listOptions) => getAllVaultMemoriesOp(vaultCtx, listOptions),
23114
23151
  get: (id) => getVaultMemoryOp(vaultCtx, id),
23115
23152
  listArchived: async () => {
@@ -23191,6 +23228,22 @@ function createLocalMemoryStore(options) {
23191
23228
  { vaultCtx, embeddingOptions: options.embeddingOptions, vaultCache },
23192
23229
  retainOptions
23193
23230
  ),
23231
+ factSource: {
23232
+ search: (query, searchOptions) => searchVaultMemoriesWithSize(
23233
+ query,
23234
+ vaultCtx,
23235
+ options.embeddingOptions,
23236
+ vaultCache,
23237
+ searchOptions
23238
+ ),
23239
+ graphRanking: (query, traverse, recallOptions) => buildGraphLaneRanking(
23240
+ query,
23241
+ { vaultCtx, entityCtx, embeddingOptions: options.embeddingOptions },
23242
+ traverse,
23243
+ graphTraversalOptions(recallOptions, traverse)
23244
+ ),
23245
+ temporalRanking: (query, now) => buildTemporalLaneRanking(query, vaultCtx, now)
23246
+ },
23194
23247
  subscribe: (onChange, subscribeOptions) => {
23195
23248
  const afterFirst = () => {
23196
23249
  let first = true;
@@ -24078,38 +24131,31 @@ function createRemoteMemoryPipeline(options) {
24078
24131
  };
24079
24132
  return { prepare, port };
24080
24133
  };
24081
- return {
24082
- recall: async (query, recallOptions = {}) => {
24134
+ const factSource = {
24135
+ graphRanking: options.graphRanking,
24136
+ temporalRanking: options.temporalRanking,
24137
+ search: async (text13, searchOptions) => {
24083
24138
  const { prepare } = operation("recall");
24084
- return recall(
24085
- query,
24086
- {
24087
- embeddingOptions,
24088
- factSource: {
24089
- graphRanking: options.graphRanking,
24090
- temporalRanking: options.temporalRanking,
24091
- search: async (text13, searchOptions) => {
24092
- const prepared = await prepare(text13, searchOptions);
24093
- const ranked = await rankPreparedVaultCandidates(
24094
- text13,
24095
- prepared,
24096
- embeddingOptions,
24097
- searchOptions
24098
- );
24099
- return {
24100
- ...ranked,
24101
- rankedOnCosine: prepared.memories.length > 0 && !prepared.embeddingsUnavailable,
24102
- decryptLast: true,
24103
- rowsDecrypted: prepared.rowsDecrypted,
24104
- queryEmbedMs: prepared.queryEmbedMs,
24105
- rowsEmbedded: 0
24106
- };
24107
- }
24108
- }
24109
- },
24110
- { ...recallOptions, types: ["fact"] }
24139
+ const prepared = await prepare(text13, searchOptions);
24140
+ const ranked = await rankPreparedVaultCandidates(
24141
+ text13,
24142
+ prepared,
24143
+ embeddingOptions,
24144
+ searchOptions
24111
24145
  );
24112
- },
24146
+ return {
24147
+ ...ranked,
24148
+ rankedOnCosine: prepared.memories.length > 0 && !prepared.embeddingsUnavailable,
24149
+ decryptLast: true,
24150
+ rowsDecrypted: prepared.rowsDecrypted,
24151
+ queryEmbedMs: prepared.queryEmbedMs,
24152
+ rowsEmbedded: 0
24153
+ };
24154
+ }
24155
+ };
24156
+ return {
24157
+ factSource,
24158
+ recall: async (query, recallOptions = {}) => recall(query, { embeddingOptions, factSource }, { ...recallOptions, types: ["fact"] }),
24113
24159
  retain: async (content, retainOptions) => {
24114
24160
  const { port } = operation("retain");
24115
24161
  return retainWithPersistence(
@@ -24471,6 +24517,7 @@ function createRemoteMemoryStore(options) {
24471
24517
  });
24472
24518
  };
24473
24519
  return {
24520
+ masksEmbeddingInput: embeddingOptions.maskInput !== void 0,
24474
24521
  list: async (listOptions = {}) => (await listRows(decrypted, listOptions, listFilters(listOptions), maxOf(listOptions))).map(
24475
24522
  (r) => stored(r.memory)
24476
24523
  ),
@@ -24666,6 +24713,7 @@ function createRemoteMemoryStore(options) {
24666
24713
  })
24667
24714
  ),
24668
24715
  recall: (query, recallOptions) => pipeline.recall(query, recallOptions),
24716
+ factSource: pipeline.factSource,
24669
24717
  retain: async (content, retainOptions) => {
24670
24718
  const result = await pipeline.retain(content, retainOptions);
24671
24719
  if (result.action === "create" || result.action === "supersede") notify("membership");
@@ -26434,19 +26482,20 @@ function createMemoryVaultSearchTool(vaultCtx, embeddingOptions, cache, searchOp
26434
26482
  const budget = wantsDecompose ? "high" : searchOptions?.rerank ? "mid" : "low";
26435
26483
  const folderId = searchOptions?.folderId ?? argFolderId;
26436
26484
  if (searchOptions?.useFusion === false) {
26437
- const { results: legacy, embeddingsUnavailable } = await searchVaultMemoriesWithSize(
26485
+ const legacyOptions = {
26486
+ limit: requestLimit,
26487
+ minSimilarity,
26488
+ useFusion: false,
26489
+ ...tuningForward,
26490
+ ...folderId !== void 0 && { folderId },
26491
+ ...searchOptions?.scopes && { scopes: searchOptions.scopes }
26492
+ };
26493
+ const { results: legacy, embeddingsUnavailable } = "retain" in vaultCtx ? await vaultCtx.factSource.search(query, legacyOptions) : await searchVaultMemoriesWithSize(
26438
26494
  query,
26439
26495
  vaultCtx,
26440
26496
  embeddingOptions,
26441
26497
  cache,
26442
- {
26443
- limit: requestLimit,
26444
- minSimilarity,
26445
- useFusion: false,
26446
- ...tuningForward,
26447
- ...folderId !== void 0 && { folderId },
26448
- ...searchOptions?.scopes && { scopes: searchOptions.scopes }
26449
- }
26498
+ legacyOptions
26450
26499
  );
26451
26500
  if (legacy.length === 0) {
26452
26501
  return embeddingsUnavailable ? EMBEDDINGS_DEGRADED_EMPTY_NO_LEXICAL : "No relevant memories found in the vault.";
@@ -26465,7 +26514,7 @@ function createMemoryVaultSearchTool(vaultCtx, embeddingOptions, cache, searchOp
26465
26514
  let recallDegraded = [];
26466
26515
  const result = await recall(
26467
26516
  query,
26468
- { vaultCtx, embeddingOptions, vaultCache: cache },
26517
+ "retain" in vaultCtx ? { factSource: vaultCtx.factSource, embeddingOptions } : { vaultCtx, embeddingOptions, vaultCache: cache },
26469
26518
  {
26470
26519
  onDiagnostics: (d) => {
26471
26520
  recallDegraded = d.degraded;
@@ -26545,8 +26594,10 @@ function describeWriteOutcome(outcome2) {
26545
26594
  }
26546
26595
  }
26547
26596
  function createMemoryVaultTool(vaultCtx, options, embeddingOptions, cache) {
26597
+ const store = "retain" in vaultCtx ? vaultCtx : void 0;
26598
+ const ctx = "retain" in vaultCtx ? void 0 : vaultCtx;
26548
26599
  const hasOnSave = !!options?.onSave;
26549
- const folderNames = options?.folderMap ? Array.from(options.folderMap.keys()) : [];
26600
+ const folderNames = !store && options?.folderMap ? Array.from(options.folderMap.keys()) : [];
26550
26601
  return {
26551
26602
  type: "function",
26552
26603
  function: {
@@ -26591,7 +26642,7 @@ function createMemoryVaultTool(vaultCtx, options, embeddingOptions, cache) {
26591
26642
  let previousContent;
26592
26643
  const scope = options?.scope ?? "private";
26593
26644
  if (isUpdate) {
26594
- const existing = await getVaultMemoryOp(vaultCtx, id);
26645
+ const existing = store ? await store.get(id) : await getVaultMemoryOp(ctx, id);
26595
26646
  if (!existing) {
26596
26647
  return `Error: Memory with ID "${id}" not found. Creating a new memory instead would require a separate call without an ID.`;
26597
26648
  }
@@ -26612,9 +26663,18 @@ function createMemoryVaultTool(vaultCtx, options, embeddingOptions, cache) {
26612
26663
  return isUpdate ? `Memory update was cancelled by the user. The memory "${id}" was not modified.` : "Memory save was cancelled by the user. No memory was created.";
26613
26664
  }
26614
26665
  }
26615
- if (isUpdate) {
26666
+ if (isUpdate && store) {
26667
+ const updated = await store.update(id, {
26668
+ content,
26669
+ ...factType !== void 0 && { factType }
26670
+ });
26671
+ if (!updated) {
26672
+ return `Error: Failed to update memory "${id}".`;
26673
+ }
26674
+ return `Memory updated successfully (ID: ${updated.uniqueId}).`;
26675
+ } else if (isUpdate) {
26616
26676
  const folderId = folderName ? options?.folderMap?.get(folderName) : void 0;
26617
- const updated = await updateVaultMemoryOp(vaultCtx, id, {
26677
+ const updated = await updateVaultMemoryOp(ctx, id, {
26618
26678
  content,
26619
26679
  embedding: null,
26620
26680
  folderId,
@@ -26629,7 +26689,7 @@ function createMemoryVaultTool(vaultCtx, options, embeddingOptions, cache) {
26629
26689
  content,
26630
26690
  embeddingOptions,
26631
26691
  cache,
26632
- vaultCtx,
26692
+ ctx,
26633
26693
  id,
26634
26694
  updated.updatedAt
26635
26695
  ).catch(() => {
@@ -26649,18 +26709,22 @@ function createMemoryVaultTool(vaultCtx, options, embeddingOptions, cache) {
26649
26709
  await notifyWritten(options, input, outcome2);
26650
26710
  return describeWriteOutcome(outcome2);
26651
26711
  }
26652
- const created = await createVaultMemoryOp(vaultCtx, {
26712
+ const created = store ? await store.create({
26713
+ content,
26714
+ scope,
26715
+ ...factType !== void 0 && { factType }
26716
+ }) : await createVaultMemoryOp(ctx, {
26653
26717
  content,
26654
26718
  scope,
26655
26719
  folderId,
26656
26720
  ...factType !== void 0 && { factType }
26657
26721
  });
26658
- if (embeddingOptions && cache) {
26722
+ if (ctx && embeddingOptions && cache) {
26659
26723
  eagerEmbedContent(
26660
26724
  content,
26661
26725
  embeddingOptions,
26662
26726
  cache,
26663
- vaultCtx,
26727
+ ctx,
26664
26728
  created.uniqueId,
26665
26729
  created.updatedAt
26666
26730
  ).catch(() => {
@@ -33644,6 +33708,8 @@ async function storedToLlmapiMessage(stored2, encryptionKey, resolveMediaByIds)
33644
33708
  }
33645
33709
  var CONVERSATION_REDACTOR_LIMIT = 50;
33646
33710
  var NO_CONVERSATION_KEY = "__no_conversation__";
33711
+ var NO_STORE_FOLDERS = "Folders are not supported with a memoryStore";
33712
+ var NO_STORE_MASK = "piiRedaction needs a memoryStore built with embeddingOptions.maskInput";
33647
33713
  var conversationRedactors = /* @__PURE__ */ new Map();
33648
33714
  function getConversationRedactor(conversationId, nerDetector) {
33649
33715
  const key = conversationId ?? NO_CONVERSATION_KEY;
@@ -33687,6 +33753,7 @@ function useChatStorage(options) {
33687
33753
  signMessage,
33688
33754
  embeddedWalletSigner,
33689
33755
  getWalletAddress,
33756
+ memoryStore,
33690
33757
  enableQueue = true,
33691
33758
  autoFlushOnKeyAvailable = true,
33692
33759
  extraToolSets,
@@ -33732,6 +33799,7 @@ function useChatStorage(options) {
33732
33799
  () => ({ getToken, baseUrl, model: embeddingModel, maskInput: maskEmbeddingInput }),
33733
33800
  [getToken, baseUrl, embeddingModel, maskEmbeddingInput]
33734
33801
  );
33802
+ const storeMaskMissing = memoryStore !== void 0 && maskEmbeddingInput !== void 0 && !memoryStore.masksEmbeddingInput;
33735
33803
  const blobManagerRef = (0, import_react6.useRef)(new BlobUrlManager());
33736
33804
  (0, import_react6.useEffect)(() => {
33737
33805
  const manager = blobManagerRef.current;
@@ -34008,6 +34076,15 @@ function useChatStorage(options) {
34008
34076
  );
34009
34077
  const retainVaultMemory = (0, import_react6.useCallback)(
34010
34078
  async (input) => {
34079
+ if (memoryStore) {
34080
+ if (storeMaskMissing) throw new Error(NO_STORE_MASK);
34081
+ if (input.folderId !== void 0) throw new Error(NO_STORE_FOLDERS);
34082
+ return memoryStore.retain(input.content, {
34083
+ source: "manual",
34084
+ scope: input.scope,
34085
+ ...input.factType !== void 0 && { factType: input.factType }
34086
+ });
34087
+ }
34011
34088
  if (!getToken) {
34012
34089
  throw new Error("getToken is required to retain a vault memory");
34013
34090
  }
@@ -34026,28 +34103,44 @@ function useChatStorage(options) {
34026
34103
  }
34027
34104
  );
34028
34105
  },
34029
- [vaultCtx, getToken, vaultEmbeddingOptions, vaultEmbeddingCache]
34106
+ [vaultCtx, getToken, vaultEmbeddingOptions, vaultEmbeddingCache, memoryStore, storeMaskMissing]
34030
34107
  );
34031
34108
  const createMemoryVaultTool2 = (0, import_react6.useCallback)(
34032
34109
  (options2) => {
34110
+ if (storeMaskMissing) throw new Error(NO_STORE_MASK);
34033
34111
  const embOpts = getToken ? vaultEmbeddingOptions : void 0;
34034
34112
  return createMemoryVaultTool(
34035
- vaultCtx,
34036
- embOpts ? { write: retainVaultMemory, ...options2 } : options2,
34113
+ memoryStore ?? vaultCtx,
34114
+ embOpts || memoryStore ? { write: retainVaultMemory, ...options2 } : options2,
34037
34115
  embOpts,
34038
34116
  embOpts ? vaultEmbeddingCache : void 0
34039
34117
  );
34040
34118
  },
34041
- [vaultCtx, getToken, vaultEmbeddingOptions, vaultEmbeddingCache, retainVaultMemory]
34119
+ [
34120
+ vaultCtx,
34121
+ getToken,
34122
+ vaultEmbeddingOptions,
34123
+ vaultEmbeddingCache,
34124
+ retainVaultMemory,
34125
+ memoryStore,
34126
+ storeMaskMissing
34127
+ ]
34042
34128
  );
34043
34129
  const getVaultMemories = (0, import_react6.useCallback)(
34044
34130
  (options2) => {
34045
- return getAllVaultMemoriesOp(vaultCtx, options2);
34131
+ if (!memoryStore) return getAllVaultMemoriesOp(vaultCtx, options2);
34132
+ const { folderId, levels, kinds, ...listOptions } = options2 ?? {};
34133
+ if (folderId !== void 0) throw new Error(NO_STORE_FOLDERS);
34134
+ if (levels !== void 0 || kinds !== void 0)
34135
+ throw new Error("level and kind filters are not supported with a memoryStore");
34136
+ return memoryStore.list(listOptions);
34046
34137
  },
34047
- [vaultCtx]
34138
+ [vaultCtx, memoryStore]
34048
34139
  );
34049
34140
  const createVaultMemory = (0, import_react6.useCallback)(
34050
34141
  async (content, scope) => {
34142
+ if (storeMaskMissing) throw new Error(NO_STORE_MASK);
34143
+ if (memoryStore) return memoryStore.create({ content, scope });
34051
34144
  const result = await createVaultMemoryOp(vaultCtx, { content, scope });
34052
34145
  if (getToken) {
34053
34146
  eagerEmbedContent(
@@ -34063,10 +34156,12 @@ function useChatStorage(options) {
34063
34156
  }
34064
34157
  return result;
34065
34158
  },
34066
- [vaultCtx, getToken, vaultEmbeddingOptions, vaultEmbeddingCache]
34159
+ [vaultCtx, getToken, vaultEmbeddingOptions, vaultEmbeddingCache, memoryStore, storeMaskMissing]
34067
34160
  );
34068
34161
  const updateVaultMemory = (0, import_react6.useCallback)(
34069
34162
  async (id, content, scope) => {
34163
+ if (storeMaskMissing) throw new Error(NO_STORE_MASK);
34164
+ if (memoryStore) return memoryStore.update(id, { content, scope });
34070
34165
  const existing = await getVaultMemoryOp(vaultCtx, id);
34071
34166
  const result = await updateVaultMemoryOp(vaultCtx, id, { content, scope, embedding: null });
34072
34167
  if (result && getToken) {
@@ -34086,10 +34181,11 @@ function useChatStorage(options) {
34086
34181
  }
34087
34182
  return result;
34088
34183
  },
34089
- [vaultCtx, getToken, vaultEmbeddingOptions, vaultEmbeddingCache]
34184
+ [vaultCtx, getToken, vaultEmbeddingOptions, vaultEmbeddingCache, memoryStore, storeMaskMissing]
34090
34185
  );
34091
34186
  const deleteVaultMemory = (0, import_react6.useCallback)(
34092
34187
  async (id) => {
34188
+ if (memoryStore) return memoryStore.delete(id);
34093
34189
  const existing = await getVaultMemoryOp(vaultCtx, id);
34094
34190
  const result = await deleteVaultMemoryOp(vaultCtx, id);
34095
34191
  if (result && existing) {
@@ -34097,19 +34193,19 @@ function useChatStorage(options) {
34097
34193
  }
34098
34194
  return result;
34099
34195
  },
34100
- [vaultCtx, vaultEmbeddingCache]
34196
+ [vaultCtx, vaultEmbeddingCache, memoryStore]
34101
34197
  );
34102
34198
  const chunkVectorCacheRef = (0, import_react6.useRef)(createChunkVectorCache());
34103
34199
  const clientToolEmbeddingsCacheRef = (0, import_react6.useRef)(/* @__PURE__ */ new Map());
34104
34200
  (0, import_react6.useEffect)(() => {
34105
- if (!getToken) return;
34201
+ if (!getToken || memoryStore) return;
34106
34202
  void (async () => {
34107
34203
  try {
34108
34204
  await preEmbedVaultMemories(vaultCtx, vaultEmbeddingOptions, vaultEmbeddingCache);
34109
34205
  } catch {
34110
34206
  }
34111
34207
  })();
34112
- }, [vaultCtx, getToken, vaultEmbeddingOptions, vaultEmbeddingCache]);
34208
+ }, [vaultCtx, getToken, vaultEmbeddingOptions, vaultEmbeddingCache, memoryStore]);
34113
34209
  (0, import_react6.useEffect)(() => {
34114
34210
  return onClearAllEncryptionState(() => {
34115
34211
  vaultEmbeddingCache.clear();
@@ -34118,26 +34214,35 @@ function useChatStorage(options) {
34118
34214
  }, [vaultEmbeddingCache]);
34119
34215
  const createMemoryVaultSearchTool2 = (0, import_react6.useCallback)(
34120
34216
  (searchOptions) => {
34121
- if (!getToken) {
34217
+ if (!getToken && !memoryStore) {
34122
34218
  throw new Error("getToken is required for memory vault search tool");
34123
34219
  }
34220
+ if (storeMaskMissing) throw new Error(NO_STORE_MASK);
34124
34221
  return createMemoryVaultSearchTool(
34125
- vaultCtx,
34222
+ memoryStore ?? vaultCtx,
34126
34223
  vaultEmbeddingOptions,
34127
34224
  vaultEmbeddingCache,
34128
34225
  searchOptions
34129
34226
  );
34130
34227
  },
34131
- [vaultCtx, getToken, vaultEmbeddingOptions, vaultEmbeddingCache]
34228
+ [vaultCtx, getToken, vaultEmbeddingOptions, vaultEmbeddingCache, memoryStore, storeMaskMissing]
34132
34229
  );
34133
34230
  const createRecallTool2 = (0, import_react6.useCallback)(
34134
34231
  (toolOptions, callbacks) => {
34135
- if (!getToken) {
34232
+ if (!getToken && !memoryStore) {
34136
34233
  throw new Error("getToken is required for recall tool");
34137
34234
  }
34235
+ if (storeMaskMissing) throw new Error(NO_STORE_MASK);
34138
34236
  const resolvedToolOptions = toolOptions?.excludeConversationId !== void 0 || !currentConversationId ? toolOptions : { ...toolOptions, excludeConversationId: currentConversationId };
34237
+ if (memoryStore && resolvedToolOptions?.folderId !== void 0)
34238
+ throw new Error(NO_STORE_FOLDERS);
34139
34239
  return createRecallTool(
34140
- {
34240
+ memoryStore ? {
34241
+ factSource: memoryStore.factSource,
34242
+ ...getToken && { storageCtx },
34243
+ embeddingOptions: vaultEmbeddingOptions,
34244
+ chunkCache: chunkVectorCacheRef.current
34245
+ } : {
34141
34246
  vaultCtx,
34142
34247
  storageCtx,
34143
34248
  embeddingOptions: vaultEmbeddingOptions,
@@ -34145,7 +34250,7 @@ function useChatStorage(options) {
34145
34250
  chunkCache: chunkVectorCacheRef.current,
34146
34251
  entityCtx
34147
34252
  },
34148
- resolvedToolOptions,
34253
+ memoryStore ? { ...resolvedToolOptions, memoryStore } : resolvedToolOptions,
34149
34254
  callbacks
34150
34255
  );
34151
34256
  },
@@ -34156,11 +34261,15 @@ function useChatStorage(options) {
34156
34261
  getToken,
34157
34262
  vaultEmbeddingOptions,
34158
34263
  vaultEmbeddingCache,
34159
- currentConversationId
34264
+ currentConversationId,
34265
+ memoryStore,
34266
+ storeMaskMissing
34160
34267
  ]
34161
34268
  );
34162
34269
  const searchVaultMemoriesFn = (0, import_react6.useCallback)(
34163
34270
  async (query, searchOptions) => {
34271
+ if (storeMaskMissing) throw new Error(NO_STORE_MASK);
34272
+ if (memoryStore) return (await memoryStore.factSource.search(query, searchOptions)).results;
34164
34273
  if (!getToken) return [];
34165
34274
  return searchVaultMemories(
34166
34275
  query,
@@ -34170,11 +34279,11 @@ function useChatStorage(options) {
34170
34279
  searchOptions
34171
34280
  );
34172
34281
  },
34173
- [vaultCtx, getToken, vaultEmbeddingOptions, vaultEmbeddingCache]
34282
+ [vaultCtx, getToken, vaultEmbeddingOptions, vaultEmbeddingCache, memoryStore, storeMaskMissing]
34174
34283
  );
34175
34284
  const recallFn = (0, import_react6.useCallback)(
34176
34285
  async (query, options2) => {
34177
- if (!getToken) {
34286
+ if (!getToken && !memoryStore) {
34178
34287
  return {
34179
34288
  memories: [],
34180
34289
  usedBudget: options2?.budget ?? "low",
@@ -34183,9 +34292,16 @@ function useChatStorage(options) {
34183
34292
  };
34184
34293
  }
34185
34294
  const resolvedOptions = options2?.excludeConversationId !== void 0 || !currentConversationId ? options2 : { ...options2, excludeConversationId: currentConversationId };
34295
+ if (storeMaskMissing) throw new Error(NO_STORE_MASK);
34296
+ if (memoryStore && resolvedOptions?.folderId !== void 0) throw new Error(NO_STORE_FOLDERS);
34186
34297
  return recall(
34187
34298
  query,
34188
- {
34299
+ memoryStore ? {
34300
+ factSource: memoryStore.factSource,
34301
+ ...getToken && { storageCtx },
34302
+ embeddingOptions: vaultEmbeddingOptions,
34303
+ chunkCache: chunkVectorCacheRef.current
34304
+ } : {
34189
34305
  vaultCtx,
34190
34306
  storageCtx,
34191
34307
  embeddingOptions: vaultEmbeddingOptions,
@@ -34203,7 +34319,9 @@ function useChatStorage(options) {
34203
34319
  getToken,
34204
34320
  currentConversationId,
34205
34321
  vaultEmbeddingOptions,
34206
- vaultEmbeddingCache
34322
+ vaultEmbeddingCache,
34323
+ memoryStore,
34324
+ storeMaskMissing
34207
34325
  ]
34208
34326
  );
34209
34327
  const {
@@ -36626,6 +36744,128 @@ function useICloudBackup(options) {
36626
36744
  // src/react/useModels.ts
36627
36745
  var import_react17 = require("react");
36628
36746
  init_clientConfig();
36747
+ var MODELS_CACHE_TTL_MS = 5 * 60 * 1e3;
36748
+ var modelsCache = /* @__PURE__ */ new Map();
36749
+ var modelsInFlight = /* @__PURE__ */ new Map();
36750
+ var cacheGeneration = 0;
36751
+ function clearModelsCache() {
36752
+ cacheGeneration++;
36753
+ modelsCache.clear();
36754
+ modelsInFlight.clear();
36755
+ }
36756
+ function pruneStaleTokenEntries(newKey) {
36757
+ const [newBaseUrl, newProvider] = JSON.parse(newKey);
36758
+ for (const existingKey of modelsCache.keys()) {
36759
+ if (existingKey === newKey) continue;
36760
+ const [existingBaseUrl, existingProvider] = JSON.parse(existingKey);
36761
+ if (existingBaseUrl === newBaseUrl && existingProvider === newProvider) {
36762
+ modelsCache.delete(existingKey);
36763
+ }
36764
+ }
36765
+ }
36766
+ function fingerprintToken(token) {
36767
+ if (!token) return "anon";
36768
+ let h1 = 3735928559;
36769
+ let h2 = 1103547991;
36770
+ for (let i = 0; i < token.length; i++) {
36771
+ const ch = token.charCodeAt(i);
36772
+ h1 = Math.imul(h1 ^ ch, 2654435761);
36773
+ h2 = Math.imul(h2 ^ ch, 1597334677);
36774
+ }
36775
+ h1 = Math.imul(h1 ^ h1 >>> 16, 2246822507) ^ Math.imul(h2 ^ h2 >>> 13, 3266489909);
36776
+ h2 = Math.imul(h2 ^ h2 >>> 16, 2246822507) ^ Math.imul(h1 ^ h1 >>> 13, 3266489909);
36777
+ return (4294967296 * (2097151 & h2) + (h1 >>> 0)).toString(36);
36778
+ }
36779
+ function modelsCacheKey(baseUrl, provider, token) {
36780
+ return JSON.stringify([baseUrl, provider ?? null, fingerprintToken(token)]);
36781
+ }
36782
+ async function fetchAllModelPages(baseUrl, provider, headers, previous, signal) {
36783
+ const pages = /* @__PURE__ */ new Map();
36784
+ const models = [];
36785
+ let pageToken;
36786
+ do {
36787
+ const pageKey = pageToken ?? "";
36788
+ const stored2 = previous?.pages.get(pageKey);
36789
+ const request = (etag) => getApiV1Models({
36790
+ baseUrl,
36791
+ headers: etag ? { ...headers, "If-None-Match": etag } : headers,
36792
+ query: { provider, page_token: pageToken },
36793
+ signal
36794
+ });
36795
+ let response = await request(stored2?.etag);
36796
+ if (stored2?.etag && !response.response && response.error) {
36797
+ response = await request();
36798
+ }
36799
+ let page;
36800
+ if (response.response?.status === 304) {
36801
+ if (!stored2) throw new Error("Failed to fetch models");
36802
+ page = stored2;
36803
+ } else {
36804
+ if (response.error) {
36805
+ const errorMsg = response.error.error ?? "Failed to fetch models";
36806
+ throw new Error(errorMsg);
36807
+ }
36808
+ page = {
36809
+ body: response.data ?? {},
36810
+ etag: response.response?.headers?.get("ETag") ?? void 0
36811
+ };
36812
+ }
36813
+ pages.set(pageKey, page);
36814
+ models.push(...page.body.data || []);
36815
+ pageToken = page.body.next_page_token;
36816
+ } while (pageToken);
36817
+ return { pages, models, fetchedAt: Date.now() };
36818
+ }
36819
+ function loadModels(key, baseUrl, provider, headers, force, signal) {
36820
+ const cached = modelsCache.get(key);
36821
+ if (cached && !force && Date.now() - cached.fetchedAt < MODELS_CACHE_TTL_MS) {
36822
+ return Promise.resolve([...cached.models]);
36823
+ }
36824
+ const shared = (force ? void 0 : modelsInFlight.get(key)) ?? startSharedRequest(key, baseUrl, provider, headers, cached);
36825
+ return waitForSharedRequest(key, shared, signal).then((models) => [...models]);
36826
+ }
36827
+ function startSharedRequest(key, baseUrl, provider, headers, previous) {
36828
+ const controller = new AbortController();
36829
+ const generation = cacheGeneration;
36830
+ const shared = {
36831
+ controller,
36832
+ waiters: 0,
36833
+ promise: Promise.resolve([])
36834
+ };
36835
+ shared.promise = fetchAllModelPages(baseUrl, provider, headers, previous, controller.signal).then((entry) => {
36836
+ if (modelsInFlight.get(key) === shared && generation === cacheGeneration) {
36837
+ pruneStaleTokenEntries(key);
36838
+ modelsCache.set(key, entry);
36839
+ }
36840
+ return entry.models;
36841
+ }).finally(() => {
36842
+ if (modelsInFlight.get(key) === shared) modelsInFlight.delete(key);
36843
+ });
36844
+ modelsInFlight.set(key, shared);
36845
+ return shared;
36846
+ }
36847
+ function waitForSharedRequest(key, shared, signal) {
36848
+ shared.waiters++;
36849
+ let left = false;
36850
+ const leave = () => {
36851
+ if (left) return;
36852
+ left = true;
36853
+ shared.waiters--;
36854
+ if (shared.waiters === 0) {
36855
+ shared.controller.abort();
36856
+ if (modelsInFlight.get(key) === shared) modelsInFlight.delete(key);
36857
+ }
36858
+ };
36859
+ if (signal.aborted) {
36860
+ leave();
36861
+ } else {
36862
+ signal.addEventListener("abort", leave, { once: true });
36863
+ }
36864
+ return shared.promise.finally(() => {
36865
+ left = true;
36866
+ signal.removeEventListener("abort", leave);
36867
+ });
36868
+ }
36629
36869
  function useModels(options = {}) {
36630
36870
  const { getToken, baseUrl = BASE_URL, provider, autoFetch = true } = options;
36631
36871
  const [models, setModels] = (0, import_react17.useState)([]);
@@ -36648,7 +36888,7 @@ function useModels(options = {}) {
36648
36888
  }
36649
36889
  };
36650
36890
  }, []);
36651
- const fetchModels = (0, import_react17.useCallback)(async () => {
36891
+ const fetchModels = (0, import_react17.useCallback)(async (force = false) => {
36652
36892
  if (abortControllerRef.current) {
36653
36893
  abortControllerRef.current.abort();
36654
36894
  }
@@ -36667,35 +36907,17 @@ function useModels(options = {}) {
36667
36907
  if (token) {
36668
36908
  headers["Authorization"] = `Bearer ${token}`;
36669
36909
  }
36670
- let allModels = [];
36671
- let nextPageToken;
36672
- do {
36673
- if (signal.aborted) return;
36674
- const response = await getApiV1Models({
36675
- baseUrl: baseUrlRef.current,
36676
- headers,
36677
- query: {
36678
- provider: providerRef.current,
36679
- page_token: nextPageToken
36680
- },
36681
- signal
36682
- });
36683
- if (response.error) {
36684
- const errorMsg = response.error.error ?? "Failed to fetch models";
36685
- throw new Error(errorMsg);
36686
- }
36687
- if (response.data) {
36688
- const newModels = response.data.data || [];
36689
- allModels = [...allModels, ...newModels];
36690
- nextPageToken = response.data.next_page_token;
36691
- }
36692
- } while (nextPageToken);
36910
+ const baseUrl2 = baseUrlRef.current;
36911
+ const provider2 = providerRef.current;
36912
+ const key = modelsCacheKey(baseUrl2, provider2, token);
36913
+ const allModels = await loadModels(key, baseUrl2, provider2, headers, force, signal);
36693
36914
  if (signal.aborted) return;
36694
36915
  setModels(allModels);
36695
36916
  } catch (err) {
36696
36917
  if (err instanceof Error && err.name === "AbortError") {
36697
36918
  return;
36698
36919
  }
36920
+ if (signal.aborted) return;
36699
36921
  setError(err instanceof Error ? err : new Error(String(err)));
36700
36922
  } finally {
36701
36923
  if (!signal.aborted) {
@@ -36708,7 +36930,7 @@ function useModels(options = {}) {
36708
36930
  }, []);
36709
36931
  const refetch = (0, import_react17.useCallback)(async () => {
36710
36932
  setModels([]);
36711
- await fetchModels();
36933
+ await fetchModels(true);
36712
36934
  }, [fetchModels]);
36713
36935
  const hasFetchedRef = (0, import_react17.useRef)(false);
36714
36936
  (0, import_react17.useEffect)(() => {
@@ -38760,6 +38982,7 @@ function useWalletBinding(options = {}) {
38760
38982
  clearKeyPair,
38761
38983
  clearLazyTitleCache,
38762
38984
  clearMemoryTopicsOverrideOp,
38985
+ clearModelsCache,
38763
38986
  clearNotionToken,
38764
38987
  clearServerToolsCache,
38765
38988
  consoleLogger,