@anuma/sdk 3.0.0 → 3.1.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.
@@ -26,7 +26,6 @@ import {
26
26
  createConversationOp,
27
27
  createMemoryVaultSearchTool,
28
28
  createMessageOp,
29
- createSseClient,
30
29
  createSupersedingMemoryOp,
31
30
  createVaultEmbeddingCache,
32
31
  createVaultMemoriesBatchOp,
@@ -39,7 +38,6 @@ import {
39
38
  decryptField,
40
39
  decryptJsonField,
41
40
  deleteAllVaultMemoriesForUserOp,
42
- deleteApiV1WalletsBindingByAddress,
43
41
  deleteConversationOp,
44
42
  deleteVaultMemoryOp,
45
43
  eagerEmbedContent,
@@ -61,13 +59,6 @@ import {
61
59
  getAllFilesOp,
62
60
  getAllVaultMemoriesOp,
63
61
  getAllVaultMemoryContentsOp,
64
- getApiV1Config,
65
- getApiV1CreditsBalance,
66
- getApiV1CreditsPacks,
67
- getApiV1Models,
68
- getApiV1PhoneCallsByCallId,
69
- getApiV1SubscriptionsStatus,
70
- getApiV1WalletsBinding,
71
62
  getConversationOp,
72
63
  getConversationsByProjectLazyOp,
73
64
  getConversationsByProjectOp,
@@ -95,17 +86,6 @@ import {
95
86
  makeSyntheticStoredMessage,
96
87
  onClearAllEncryptionState,
97
88
  onKeyAvailable,
98
- postApiV1CreditsPurchase,
99
- postApiV1PhoneCalls,
100
- postApiV1SubscriptionsCancel,
101
- postApiV1SubscriptionsCreateCheckoutSession,
102
- postApiV1SubscriptionsCustomerPortal,
103
- postApiV1SubscriptionsRenew,
104
- postApiV1WalletsBinding,
105
- postApiV1WalletsBindingNonce,
106
- postAuthOauthByProviderExchange,
107
- postAuthOauthByProviderRefresh,
108
- postAuthOauthByProviderRevoke,
109
89
  preEmbedVaultMemories,
110
90
  recall,
111
91
  replaceMemoryEntitiesGuardedOp,
@@ -132,7 +112,7 @@ import {
132
112
  updateVaultMemoryOp,
133
113
  useEncryption,
134
114
  vaultMemoryToStored
135
- } from "./chunk-OSDVRDLI.mjs";
115
+ } from "./chunk-XVC7DWDN.mjs";
136
116
  import {
137
117
  PiiRedactor,
138
118
  createStreamingDeAnonymizer,
@@ -152,9 +132,145 @@ import {
152
132
  import {
153
133
  BASE_URL,
154
134
  MCP_R2_DOMAIN,
155
- __decorateClass
135
+ __decorateClass,
136
+ createClientConfig
156
137
  } from "./chunk-GYKJOWEO.mjs";
157
138
 
139
+ // src/client/core/serverSentEvents.gen.ts
140
+ var createSseClient = ({
141
+ onRequest,
142
+ onSseError,
143
+ onSseEvent,
144
+ responseTransformer,
145
+ responseValidator,
146
+ sseDefaultRetryDelay,
147
+ sseMaxRetryAttempts,
148
+ sseMaxRetryDelay,
149
+ sseSleepFn,
150
+ url,
151
+ ...options
152
+ }) => {
153
+ let lastEventId;
154
+ const sleep3 = sseSleepFn ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
155
+ const createStream = async function* () {
156
+ let retryDelay = sseDefaultRetryDelay ?? 3e3;
157
+ let attempt = 0;
158
+ const signal = options.signal ?? new AbortController().signal;
159
+ while (true) {
160
+ if (signal.aborted) break;
161
+ attempt++;
162
+ const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers);
163
+ if (lastEventId !== void 0) {
164
+ headers.set("Last-Event-ID", lastEventId);
165
+ }
166
+ try {
167
+ const requestInit = {
168
+ redirect: "follow",
169
+ ...options,
170
+ body: options.serializedBody,
171
+ headers,
172
+ signal
173
+ };
174
+ let request = new Request(url, requestInit);
175
+ if (onRequest) {
176
+ request = await onRequest(url, requestInit);
177
+ }
178
+ const _fetch = options.fetch ?? globalThis.fetch;
179
+ const response = await _fetch(request);
180
+ if (!response.ok)
181
+ throw new Error(
182
+ `SSE failed: ${response.status} ${response.statusText}`
183
+ );
184
+ if (!response.body) throw new Error("No body in SSE response");
185
+ const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
186
+ let buffer = "";
187
+ const abortHandler = () => {
188
+ try {
189
+ reader.cancel();
190
+ } catch {
191
+ }
192
+ };
193
+ signal.addEventListener("abort", abortHandler);
194
+ try {
195
+ while (true) {
196
+ const { done, value } = await reader.read();
197
+ if (done) break;
198
+ buffer += value;
199
+ const chunks = buffer.split("\n\n");
200
+ buffer = chunks.pop() ?? "";
201
+ for (const chunk of chunks) {
202
+ const lines = chunk.split("\n");
203
+ const dataLines = [];
204
+ let eventName;
205
+ for (const line of lines) {
206
+ if (line.startsWith("data:")) {
207
+ dataLines.push(line.replace(/^data:\s*/, ""));
208
+ } else if (line.startsWith("event:")) {
209
+ eventName = line.replace(/^event:\s*/, "");
210
+ } else if (line.startsWith("id:")) {
211
+ lastEventId = line.replace(/^id:\s*/, "");
212
+ } else if (line.startsWith("retry:")) {
213
+ const parsed = Number.parseInt(
214
+ line.replace(/^retry:\s*/, ""),
215
+ 10
216
+ );
217
+ if (!Number.isNaN(parsed)) {
218
+ retryDelay = parsed;
219
+ }
220
+ }
221
+ }
222
+ let data;
223
+ let parsedJson = false;
224
+ if (dataLines.length) {
225
+ const rawData = dataLines.join("\n");
226
+ try {
227
+ data = JSON.parse(rawData);
228
+ parsedJson = true;
229
+ } catch {
230
+ data = rawData;
231
+ }
232
+ }
233
+ if (parsedJson) {
234
+ if (responseValidator) {
235
+ await responseValidator(data);
236
+ }
237
+ if (responseTransformer) {
238
+ data = await responseTransformer(data);
239
+ }
240
+ }
241
+ onSseEvent?.({
242
+ data,
243
+ event: eventName,
244
+ id: lastEventId,
245
+ retry: retryDelay
246
+ });
247
+ if (dataLines.length) {
248
+ yield data;
249
+ }
250
+ }
251
+ }
252
+ } finally {
253
+ signal.removeEventListener("abort", abortHandler);
254
+ reader.releaseLock();
255
+ }
256
+ break;
257
+ } catch (error) {
258
+ onSseError?.(error);
259
+ if (sseMaxRetryAttempts !== void 0 && attempt >= sseMaxRetryAttempts) {
260
+ break;
261
+ }
262
+ const backoff = Math.min(
263
+ retryDelay * 2 ** (attempt - 1),
264
+ sseMaxRetryDelay ?? 3e4
265
+ );
266
+ await sleep3(backoff);
267
+ }
268
+ }
269
+ };
270
+ const stream = createStream();
271
+ return { stream };
272
+ };
273
+
158
274
  // src/lib/chat/runHooks.ts
159
275
  function composeHooks(hooks) {
160
276
  const handlers = hooks.filter((h) => h !== void 0 && h !== null);
@@ -7510,9 +7626,11 @@ function createChunkVectorCache(maxSize = DEFAULT_CHUNK_CACHE_SIZE) {
7510
7626
  return new LRUCache(maxSize);
7511
7627
  }
7512
7628
 
7513
- // src/lib/memory/recallTool.ts
7629
+ // src/lib/memory/recallConstants.ts
7514
7630
  var RECALL_TOOL_NAME = "recall_memory";
7515
7631
  var RECALL_MAX_LIMIT = 50;
7632
+
7633
+ // src/lib/memory/recallTool.ts
7516
7634
  var DEFAULT_LIMIT = 8;
7517
7635
  var DEFAULT_BUDGET = "low";
7518
7636
  function formatEventTime(start, end, kind) {
@@ -9210,7 +9328,7 @@ function getCachedServerTools() {
9210
9328
  if (!cached) return null;
9211
9329
  const parsed = JSON.parse(cached);
9212
9330
  if (parsed.version !== CACHE_VERSION) {
9213
- clearServerToolsCache();
9331
+ removeLocalStorageCache();
9214
9332
  return null;
9215
9333
  }
9216
9334
  return parsed;
@@ -9222,37 +9340,45 @@ function isCacheExpired(cache, expirationMs = DEFAULT_CACHE_EXPIRATION_MS) {
9222
9340
  if (!cache) return true;
9223
9341
  return Date.now() - cache.timestamp > expirationMs;
9224
9342
  }
9225
- function cacheServerTools(tools, checksum) {
9226
- if (typeof localStorage === "undefined") return;
9227
- const cacheData = {
9343
+ function buildCacheEntry(tools, checksum) {
9344
+ return {
9228
9345
  tools,
9229
9346
  timestamp: Date.now(),
9230
9347
  version: CACHE_VERSION,
9231
9348
  ...checksum && { checksum }
9232
9349
  };
9350
+ }
9351
+ function writeLocalStorageCache(entry) {
9352
+ if (typeof localStorage === "undefined") return;
9233
9353
  try {
9234
- localStorage.setItem(SERVER_TOOLS_CACHE_KEY, JSON.stringify(cacheData));
9354
+ localStorage.setItem(SERVER_TOOLS_CACHE_KEY, JSON.stringify(entry));
9235
9355
  } catch (error) {
9236
9356
  getLogger().warn("[serverTools] Failed to cache tools:", error);
9237
9357
  }
9238
9358
  }
9239
- function clearServerToolsCache() {
9359
+ function removeLocalStorageCache() {
9240
9360
  if (typeof localStorage === "undefined") return;
9241
9361
  localStorage.removeItem(SERVER_TOOLS_CACHE_KEY);
9242
9362
  }
9243
- function getToolsChecksum2() {
9244
- const cached = getCachedServerTools();
9245
- return cached?.checksum;
9363
+ var localStorageToolsCache = {
9364
+ get: getCachedServerTools,
9365
+ set: writeLocalStorageCache,
9366
+ clear: removeLocalStorageCache
9367
+ };
9368
+ function clearServerToolsCache(cache = localStorageToolsCache) {
9369
+ return cache.clear?.();
9370
+ }
9371
+ function getToolsChecksum2(cache = localStorageToolsCache) {
9372
+ const cached = cache.get();
9373
+ return cached instanceof Promise ? cached.then((c) => c?.checksum) : cached?.checksum;
9246
9374
  }
9247
- function shouldRefreshTools(responseChecksum) {
9375
+ function shouldRefreshTools(responseChecksum, cache = localStorageToolsCache) {
9248
9376
  if (!responseChecksum) {
9249
9377
  return false;
9250
9378
  }
9251
- const cachedChecksum = getToolsChecksum2();
9252
- if (!cachedChecksum) {
9253
- return true;
9254
- }
9255
- return cachedChecksum !== responseChecksum;
9379
+ const decide = (cachedChecksum2) => !cachedChecksum2 || cachedChecksum2 !== responseChecksum;
9380
+ const cachedChecksum = getToolsChecksum2(cache);
9381
+ return cachedChecksum instanceof Promise ? cachedChecksum.then(decide) : decide(cachedChecksum);
9256
9382
  }
9257
9383
  async function fetchServerToolsFromApi(baseUrl, token) {
9258
9384
  const response = await fetch(`${baseUrl}/api/v1/tools`, {
@@ -9274,9 +9400,23 @@ async function getServerTools(options) {
9274
9400
  cacheExpirationMs = DEFAULT_CACHE_EXPIRATION_MS,
9275
9401
  forceRefresh = false,
9276
9402
  getToken,
9277
- apiKey
9403
+ apiKey,
9404
+ cache = localStorageToolsCache
9278
9405
  } = options;
9279
- const cached = getCachedServerTools();
9406
+ const persistCache = async (entry) => {
9407
+ try {
9408
+ await cache.set(entry);
9409
+ } catch (error) {
9410
+ getLogger().warn("[serverTools] Cache write failed (non-fatal):", error);
9411
+ }
9412
+ };
9413
+ let rawCached = null;
9414
+ try {
9415
+ rawCached = await cache.get();
9416
+ } catch (error) {
9417
+ getLogger().warn("[serverTools] Cache read failed; falling through to server fetch:", error);
9418
+ }
9419
+ const cached = rawCached && rawCached.version === CACHE_VERSION ? rawCached : null;
9280
9420
  const cacheValid = !isCacheExpired(cached, cacheExpirationMs);
9281
9421
  if (cached && cacheValid && !forceRefresh) {
9282
9422
  return cached.tools;
@@ -9297,7 +9437,7 @@ async function getServerTools(options) {
9297
9437
  }
9298
9438
  const data = await response.json();
9299
9439
  const { tools: tools2, checksum: checksum2 } = convertServerToolsResponse(data);
9300
- cacheServerTools(tools2, checksum2);
9440
+ await persistCache(buildCacheEntry(tools2, checksum2));
9301
9441
  return tools2;
9302
9442
  }
9303
9443
  if (!getToken) {
@@ -9310,7 +9450,7 @@ async function getServerTools(options) {
9310
9450
  return cached?.tools ?? [];
9311
9451
  }
9312
9452
  const { tools, checksum } = await fetchServerToolsFromApi(effectiveBaseUrl, token);
9313
- cacheServerTools(tools, checksum);
9453
+ await persistCache(buildCacheEntry(tools, checksum));
9314
9454
  return tools;
9315
9455
  } catch (error) {
9316
9456
  getLogger().error("[serverTools] Failed to fetch server tools:", error);
@@ -9815,13 +9955,14 @@ async function selectServerToolsForPrompt(options) {
9815
9955
  baseUrl,
9816
9956
  embeddingModel,
9817
9957
  cacheExpirationMs,
9958
+ cache,
9818
9959
  deferLoading
9819
9960
  } = options;
9820
9961
  if (serverToolsFilter === void 0) return [];
9821
9962
  if (Array.isArray(serverToolsFilter) && serverToolsFilter.length === 0) return [];
9822
9963
  let allServerTools;
9823
9964
  try {
9824
- allServerTools = await getServerTools({ baseUrl, cacheExpirationMs, getToken });
9965
+ allServerTools = await getServerTools({ baseUrl, cacheExpirationMs, getToken, cache });
9825
9966
  } catch {
9826
9967
  return [];
9827
9968
  }
@@ -9845,6 +9986,123 @@ async function selectServerToolsForPrompt(options) {
9845
9986
  return filterServerTools(allServerTools, serverToolsFilter);
9846
9987
  }
9847
9988
 
9989
+ // src/lib/tools/clientToolSelection.ts
9990
+ function getToolName2(t) {
9991
+ const fn = t.function;
9992
+ return fn?.name || t.name || "";
9993
+ }
9994
+ function getToolDescription(t) {
9995
+ const fn = t.function;
9996
+ return fn?.description || t.description || getToolName2(t);
9997
+ }
9998
+ function computeToolGuidance(selectedServerTools, selectedClientTools, extraToolSets, activatedSetNames) {
9999
+ const names = [
10000
+ ...selectedServerTools.map((t) => t.name),
10001
+ ...(selectedClientTools ?? []).map(getToolName2)
10002
+ ].filter(Boolean);
10003
+ const toolSets = extraToolSets.length > 0 ? [...BUILT_IN_TOOL_SETS, ...extraToolSets] : BUILT_IN_TOOL_SETS;
10004
+ const prompts = toolSetSystemPrompts(names, toolSets, activatedSetNames);
10005
+ return prompts.length > 0 ? prompts.join("\n\n") : void 0;
10006
+ }
10007
+ async function autoFilterClientTools(clientTools, promptEmbeddings, cache, embeddingOptions, extraToolSets = [], activeToolSets = [], noEmbeddingsReason = "short-prompt") {
10008
+ const isMemoryTool = (t) => {
10009
+ const name = getToolName2(t);
10010
+ return name.startsWith("memory_vault_") || name === RECALL_TOOL_NAME;
10011
+ };
10012
+ const alwaysInclude = clientTools.filter(isMemoryTool);
10013
+ const filterCandidates = clientTools.filter((t) => !isMemoryTool(t));
10014
+ if (filterCandidates.length === 0) {
10015
+ return { tools: clientTools, activatedSetNames: /* @__PURE__ */ new Set() };
10016
+ }
10017
+ if (!promptEmbeddings && noEmbeddingsReason === "error") {
10018
+ return { tools: clientTools, activatedSetNames: /* @__PURE__ */ new Set() };
10019
+ }
10020
+ if (!promptEmbeddings) {
10021
+ if (activeToolSets.length === 0) {
10022
+ return { tools: [], activatedSetNames: /* @__PURE__ */ new Set() };
10023
+ }
10024
+ const allSets = extraToolSets.length > 0 ? [...BUILT_IN_TOOL_SETS, ...extraToolSets] : BUILT_IN_TOOL_SETS;
10025
+ const activeSets = allSets.filter((s) => activeToolSets.includes(s.name));
10026
+ const stickyMembers = new Set(activeSets.flatMap((s) => s.members));
10027
+ return {
10028
+ tools: [
10029
+ ...alwaysInclude,
10030
+ ...filterCandidates.filter((t) => stickyMembers.has(getToolName2(t)))
10031
+ ],
10032
+ activatedSetNames: new Set(activeSets.map((s) => s.name))
10033
+ };
10034
+ }
10035
+ const toolsNeedingEmbeddings = [];
10036
+ for (const t of filterCandidates) {
10037
+ const name = getToolName2(t);
10038
+ if (name && !cache.has(name)) {
10039
+ toolsNeedingEmbeddings.push({ name, description: getToolDescription(t) });
10040
+ }
10041
+ }
10042
+ if (toolsNeedingEmbeddings.length > 0) {
10043
+ try {
10044
+ const descriptions = toolsNeedingEmbeddings.map((t) => t.description);
10045
+ const embeddings = await generateEmbeddings(descriptions, embeddingOptions);
10046
+ for (let i = 0; i < toolsNeedingEmbeddings.length; i++) {
10047
+ cache.set(toolsNeedingEmbeddings[i].name, embeddings[i]);
10048
+ }
10049
+ } catch {
10050
+ return { tools: clientTools, activatedSetNames: /* @__PURE__ */ new Set() };
10051
+ }
10052
+ }
10053
+ const pseudoServerTools = [];
10054
+ for (const t of filterCandidates) {
10055
+ const name = getToolName2(t);
10056
+ const embedding = cache.get(name);
10057
+ if (!embedding) continue;
10058
+ const fn = t.function;
10059
+ const params = fn?.parameters || fn?.arguments || {
10060
+ type: "object",
10061
+ properties: {},
10062
+ required: []
10063
+ };
10064
+ pseudoServerTools.push({
10065
+ type: "function",
10066
+ name,
10067
+ description: getToolDescription(t),
10068
+ parameters: params,
10069
+ embedding
10070
+ });
10071
+ }
10072
+ const matches = findMatchingTools(promptEmbeddings, pseudoServerTools, {
10073
+ limit: MAX_CLIENT_TOOLS_AFTER_FILTER,
10074
+ minSimilarity: CLIENT_TOOLS_MIN_SIMILARITY,
10075
+ filterAmbiguous: true,
10076
+ // See CLIENT_TOOLS_RELEVANCE_RATIO: 0.75 admits the second intent of a
10077
+ // multi-intent prompt (which lands ~75-80% of the dominant match), while
10078
+ // still trimming the loose tail. The earlier 0.9 made a second intent
10079
+ // structurally unselectable; the anchorMinSimilarity gates (0.53-0.55)
10080
+ // remain the guard against borderline anchors activating a whole set.
10081
+ relevanceRatio: CLIENT_TOOLS_RELEVANCE_RATIO
10082
+ });
10083
+ const matchedNames = new Set(matches.map((m) => m.tool.name));
10084
+ const scores = scoreTools(promptEmbeddings, pseudoServerTools);
10085
+ const availableNames = new Set(filterCandidates.map(getToolName2));
10086
+ const toolSets = extraToolSets.length > 0 ? [...BUILT_IN_TOOL_SETS, ...extraToolSets] : BUILT_IN_TOOL_SETS;
10087
+ const activeSetNames = activeToolSets.length > 0 ? new Set(activeToolSets) : void 0;
10088
+ const finalNames = expandToolSetsAdditive(
10089
+ matchedNames,
10090
+ availableNames,
10091
+ scores,
10092
+ toolSets,
10093
+ activeSetNames
10094
+ );
10095
+ const activatedSetNames = activatedToolSetNames(scores, toolSets, activeSetNames);
10096
+ if (finalNames.size === 0) {
10097
+ return { tools: alwaysInclude, activatedSetNames };
10098
+ }
10099
+ const filtered = filterCandidates.filter((t) => {
10100
+ const name = getToolName2(t);
10101
+ return name && finalNames.has(name);
10102
+ });
10103
+ return { tools: [...alwaysInclude, ...filtered], activatedSetNames };
10104
+ }
10105
+
9848
10106
  // src/react/useChatMedia.ts
9849
10107
  import { useCallback as useCallback3 } from "react";
9850
10108
  function resolveMediaMeta(extractedKind, urlPath, reportedType) {
@@ -10094,165 +10352,51 @@ function useChatMedia(options) {
10094
10352
  }
10095
10353
 
10096
10354
  // src/react/useChatStorage.ts
10097
- function getToolName2(t) {
10098
- const fn = t.function;
10099
- return fn?.name || t.name || "";
10100
- }
10101
- function getToolDescription(t) {
10102
- const fn = t.function;
10103
- return fn?.description || t.description || getToolName2(t);
10104
- }
10105
- function computeToolGuidance(selectedServerTools, selectedClientTools, extraToolSets, activatedSetNames) {
10106
- const names = [
10107
- ...selectedServerTools.map((t) => t.name),
10108
- ...(selectedClientTools ?? []).map(getToolName2)
10109
- ].filter(Boolean);
10110
- const toolSets = extraToolSets.length > 0 ? [...BUILT_IN_TOOL_SETS, ...extraToolSets] : BUILT_IN_TOOL_SETS;
10111
- const prompts = toolSetSystemPrompts(names, toolSets, activatedSetNames);
10112
- return prompts.length > 0 ? prompts.join("\n\n") : void 0;
10113
- }
10114
- async function autoFilterClientTools(clientTools, promptEmbeddings, cache, embeddingOptions, extraToolSets = [], activeToolSets = [], noEmbeddingsReason = "short-prompt") {
10115
- const isMemoryTool = (t) => {
10116
- const name = getToolName2(t);
10117
- return name.startsWith("memory_vault_") || name === RECALL_TOOL_NAME;
10118
- };
10119
- const alwaysInclude = clientTools.filter(isMemoryTool);
10120
- const filterCandidates = clientTools.filter((t) => !isMemoryTool(t));
10121
- if (filterCandidates.length === 0) {
10122
- return { tools: clientTools, activatedSetNames: /* @__PURE__ */ new Set() };
10355
+ async function previewToolSelection(options) {
10356
+ const {
10357
+ prompt,
10358
+ clientTools = [],
10359
+ serverToolsFilter,
10360
+ serverToolsConfig,
10361
+ getToken,
10362
+ apiKey,
10363
+ baseUrl,
10364
+ embeddingModel = DEFAULT_API_EMBEDDING_MODEL,
10365
+ extraToolSets,
10366
+ activeToolSets,
10367
+ clientToolEmbeddingsCache
10368
+ } = options;
10369
+ if (!getToken && !apiKey) {
10370
+ throw new Error(
10371
+ "previewToolSelection requires either `getToken` (Bearer auth) or `apiKey` (X-API-Key auth) \u2014 without one, embeddings and the server tool catalog cannot be fetched."
10372
+ );
10123
10373
  }
10124
- if (!promptEmbeddings && noEmbeddingsReason === "error") {
10125
- return { tools: clientTools, activatedSetNames: /* @__PURE__ */ new Set() };
10374
+ if (!prompt.trim()) {
10375
+ return { clientToolNames: [], serverToolNames: [] };
10126
10376
  }
10127
- if (!promptEmbeddings) {
10128
- if (activeToolSets.length === 0) {
10129
- return { tools: [], activatedSetNames: /* @__PURE__ */ new Set() };
10130
- }
10131
- const allSets = extraToolSets.length > 0 ? [...BUILT_IN_TOOL_SETS, ...extraToolSets] : BUILT_IN_TOOL_SETS;
10132
- const activeSets = allSets.filter((s) => activeToolSets.includes(s.name));
10133
- const stickyMembers = new Set(activeSets.flatMap((s) => s.members));
10134
- return {
10135
- tools: [
10136
- ...alwaysInclude,
10137
- ...filterCandidates.filter((t) => stickyMembers.has(getToolName2(t)))
10138
- ],
10139
- activatedSetNames: new Set(activeSets.map((s) => s.name))
10140
- };
10141
- }
10142
- const toolsNeedingEmbeddings = [];
10143
- for (const t of filterCandidates) {
10144
- const name = getToolName2(t);
10145
- if (name && !cache.has(name)) {
10146
- toolsNeedingEmbeddings.push({ name, description: getToolDescription(t) });
10147
- }
10148
- }
10149
- if (toolsNeedingEmbeddings.length > 0) {
10150
- try {
10151
- const descriptions = toolsNeedingEmbeddings.map((t) => t.description);
10152
- const embeddings = await generateEmbeddings(descriptions, embeddingOptions);
10153
- for (let i = 0; i < toolsNeedingEmbeddings.length; i++) {
10154
- cache.set(toolsNeedingEmbeddings[i].name, embeddings[i]);
10155
- }
10156
- } catch {
10157
- return { tools: clientTools, activatedSetNames: /* @__PURE__ */ new Set() };
10158
- }
10159
- }
10160
- const pseudoServerTools = [];
10161
- for (const t of filterCandidates) {
10162
- const name = getToolName2(t);
10163
- const embedding = cache.get(name);
10164
- if (!embedding) continue;
10165
- const fn = t.function;
10166
- const params = fn?.parameters || fn?.arguments || {
10167
- type: "object",
10168
- properties: {},
10169
- required: []
10170
- };
10171
- pseudoServerTools.push({
10172
- type: "function",
10173
- name,
10174
- description: getToolDescription(t),
10175
- parameters: params,
10176
- embedding
10177
- });
10178
- }
10179
- const matches = findMatchingTools(promptEmbeddings, pseudoServerTools, {
10180
- limit: MAX_CLIENT_TOOLS_AFTER_FILTER,
10181
- minSimilarity: CLIENT_TOOLS_MIN_SIMILARITY,
10182
- filterAmbiguous: true,
10183
- // See CLIENT_TOOLS_RELEVANCE_RATIO: 0.75 admits the second intent of a
10184
- // multi-intent prompt (which lands ~75-80% of the dominant match), while
10185
- // still trimming the loose tail. The earlier 0.9 made a second intent
10186
- // structurally unselectable; the anchorMinSimilarity gates (0.53-0.55)
10187
- // remain the guard against borderline anchors activating a whole set.
10188
- relevanceRatio: CLIENT_TOOLS_RELEVANCE_RATIO
10189
- });
10190
- const matchedNames = new Set(matches.map((m) => m.tool.name));
10191
- const scores = scoreTools(promptEmbeddings, pseudoServerTools);
10192
- const availableNames = new Set(filterCandidates.map(getToolName2));
10193
- const toolSets = extraToolSets.length > 0 ? [...BUILT_IN_TOOL_SETS, ...extraToolSets] : BUILT_IN_TOOL_SETS;
10194
- const activeSetNames = activeToolSets.length > 0 ? new Set(activeToolSets) : void 0;
10195
- const finalNames = expandToolSetsAdditive(
10196
- matchedNames,
10197
- availableNames,
10198
- scores,
10199
- toolSets,
10200
- activeSetNames
10201
- );
10202
- const activatedSetNames = activatedToolSetNames(scores, toolSets, activeSetNames);
10203
- if (finalNames.size === 0) {
10204
- return { tools: alwaysInclude, activatedSetNames };
10205
- }
10206
- const filtered = filterCandidates.filter((t) => {
10207
- const name = getToolName2(t);
10208
- return name && finalNames.has(name);
10209
- });
10210
- return { tools: [...alwaysInclude, ...filtered], activatedSetNames };
10211
- }
10212
- async function previewToolSelection(options) {
10213
- const {
10214
- prompt,
10215
- clientTools = [],
10216
- serverToolsFilter,
10217
- serverToolsConfig,
10218
- getToken,
10219
- apiKey,
10220
- baseUrl,
10221
- embeddingModel = DEFAULT_API_EMBEDDING_MODEL,
10222
- extraToolSets,
10223
- activeToolSets,
10224
- clientToolEmbeddingsCache
10225
- } = options;
10226
- if (!getToken && !apiKey) {
10227
- throw new Error(
10228
- "previewToolSelection requires either `getToken` (Bearer auth) or `apiKey` (X-API-Key auth) \u2014 without one, embeddings and the server tool catalog cannot be fetched."
10229
- );
10230
- }
10231
- if (!prompt.trim()) {
10232
- return { clientToolNames: [], serverToolNames: [] };
10233
- }
10234
- if (prompt.length < MIN_CONTENT_LENGTH_FOR_TOOLS) {
10235
- const { tools: gatedTools } = await autoFilterClientTools(
10236
- clientTools,
10237
- null,
10238
- clientToolEmbeddingsCache ?? /* @__PURE__ */ new Map(),
10239
- { getToken, apiKey, baseUrl, model: embeddingModel },
10240
- extraToolSets ?? [],
10241
- activeToolSets ?? []
10242
- );
10243
- let gatedServerNames = [];
10244
- if (Array.isArray(serverToolsFilter) && serverToolsFilter.length > 0) {
10245
- try {
10246
- const allServerTools = await getServerTools({
10247
- baseUrl,
10248
- cacheExpirationMs: serverToolsConfig?.cacheExpirationMs,
10249
- getToken,
10250
- apiKey
10251
- });
10252
- const allow = new Set(serverToolsFilter);
10253
- gatedServerNames = allServerTools.filter((t) => allow.has(t.name)).map((t) => t.name);
10254
- } catch {
10255
- }
10377
+ if (prompt.length < MIN_CONTENT_LENGTH_FOR_TOOLS) {
10378
+ const { tools: gatedTools } = await autoFilterClientTools(
10379
+ clientTools,
10380
+ null,
10381
+ clientToolEmbeddingsCache ?? /* @__PURE__ */ new Map(),
10382
+ { getToken, apiKey, baseUrl, model: embeddingModel },
10383
+ extraToolSets ?? [],
10384
+ activeToolSets ?? []
10385
+ );
10386
+ let gatedServerNames = [];
10387
+ if (Array.isArray(serverToolsFilter) && serverToolsFilter.length > 0) {
10388
+ try {
10389
+ const allServerTools = await getServerTools({
10390
+ baseUrl,
10391
+ cacheExpirationMs: serverToolsConfig?.cacheExpirationMs,
10392
+ getToken,
10393
+ apiKey,
10394
+ cache: serverToolsConfig?.cache
10395
+ });
10396
+ const allow = new Set(serverToolsFilter);
10397
+ gatedServerNames = allServerTools.filter((t) => allow.has(t.name)).map((t) => t.name);
10398
+ } catch {
10399
+ }
10256
10400
  }
10257
10401
  return {
10258
10402
  clientToolNames: gatedTools.map(getToolName2).filter(Boolean),
@@ -10295,7 +10439,8 @@ async function previewToolSelection(options) {
10295
10439
  baseUrl,
10296
10440
  cacheExpirationMs: serverToolsConfig?.cacheExpirationMs,
10297
10441
  getToken,
10298
- apiKey
10442
+ apiKey,
10443
+ cache: serverToolsConfig?.cache
10299
10444
  });
10300
10445
  if (serverToolsConfig?.deferLoading?.enabled) {
10301
10446
  serverToolNames = allServerTools.map((t) => t.name);
@@ -11288,7 +11433,8 @@ function useChatStorage(options) {
11288
11433
  const allServerTools = await getServerTools({
11289
11434
  baseUrl,
11290
11435
  cacheExpirationMs: serverToolsConfig?.cacheExpirationMs,
11291
- getToken
11436
+ getToken,
11437
+ cache: serverToolsConfig?.cache
11292
11438
  });
11293
11439
  if (serverToolsConfig?.deferLoading?.enabled) {
11294
11440
  filteredServerTools2 = allServerTools;
@@ -11306,12 +11452,14 @@ function useChatStorage(options) {
11306
11452
  let filteredClientTools2 = clientTools;
11307
11453
  let clientActivatedSetNames2;
11308
11454
  if (clientToolsFilter && clientTools?.length) {
11309
- const clientToolNames = clientToolsFilter(skipStorageEmbeddings, clientTools);
11310
- filteredClientTools2 = clientTools.filter((t) => {
11311
- const fn = t.function;
11312
- const name = fn?.name || t.name;
11313
- return clientToolNames.includes(name);
11314
- });
11455
+ if (!skipStorageEmbeddingsFailed) {
11456
+ const clientToolNames = clientToolsFilter(skipStorageEmbeddings, clientTools);
11457
+ filteredClientTools2 = clientTools.filter((t) => {
11458
+ const fn = t.function;
11459
+ const name = fn?.name || t.name;
11460
+ return clientToolNames.includes(name);
11461
+ });
11462
+ }
11315
11463
  } else if (clientTools?.length && getToken) {
11316
11464
  const clientFilterResult = await autoFilterClientTools(
11317
11465
  clientTools,
@@ -11378,8 +11526,20 @@ function useChatStorage(options) {
11378
11526
  error: result2.error || "Unknown error"
11379
11527
  };
11380
11528
  }
11381
- if (getToken && shouldRefreshTools(getToolsChecksum(result2.data))) {
11382
- getServerTools({ baseUrl, getToken, forceRefresh: true }).catch((err) => {
11529
+ const refreshResponse = result2.data;
11530
+ if (getToken) {
11531
+ Promise.resolve().then(
11532
+ () => shouldRefreshTools(getToolsChecksum(refreshResponse), serverToolsConfig?.cache)
11533
+ ).then((refresh) => {
11534
+ if (refresh) {
11535
+ return getServerTools({
11536
+ baseUrl,
11537
+ getToken,
11538
+ forceRefresh: true,
11539
+ cache: serverToolsConfig?.cache
11540
+ });
11541
+ }
11542
+ }).catch((err) => {
11383
11543
  getLogger().warn("[useChatStorage] Failed to refresh server tools cache:", err);
11384
11544
  });
11385
11545
  }
@@ -11646,7 +11806,8 @@ function useChatStorage(options) {
11646
11806
  const allServerTools = await getServerTools({
11647
11807
  baseUrl,
11648
11808
  cacheExpirationMs: serverToolsConfig?.cacheExpirationMs,
11649
- getToken
11809
+ getToken,
11810
+ cache: serverToolsConfig?.cache
11650
11811
  });
11651
11812
  if (serverToolsConfig?.deferLoading?.enabled && effectiveApiType === "responses") {
11652
11813
  filteredServerTools = allServerTools;
@@ -11664,12 +11825,14 @@ function useChatStorage(options) {
11664
11825
  let filteredClientTools = clientTools;
11665
11826
  let clientActivatedSetNames;
11666
11827
  if (clientToolsFilter && clientTools?.length) {
11667
- const clientToolNames = clientToolsFilter(userMessageEmbeddings ?? null, clientTools);
11668
- filteredClientTools = clientTools.filter((t) => {
11669
- const fn = t.function;
11670
- const name = fn?.name || t.name;
11671
- return clientToolNames.includes(name);
11672
- });
11828
+ if (!userMessageEmbeddingsFailed) {
11829
+ const clientToolNames = clientToolsFilter(userMessageEmbeddings ?? null, clientTools);
11830
+ filteredClientTools = clientTools.filter((t) => {
11831
+ const fn = t.function;
11832
+ const name = fn?.name || t.name;
11833
+ return clientToolNames.includes(name);
11834
+ });
11835
+ }
11673
11836
  } else if (clientTools?.length && getToken) {
11674
11837
  const clientFilterResult = await autoFilterClientTools(
11675
11838
  clientTools,
@@ -11989,8 +12152,17 @@ Based on these results, continue with the task.`;
11989
12152
  } catch {
11990
12153
  }
11991
12154
  }
11992
- if (getToken && shouldRefreshTools(getToolsChecksum(responseData))) {
11993
- getServerTools({ baseUrl, getToken, forceRefresh: true }).catch((err) => {
12155
+ if (getToken) {
12156
+ Promise.resolve().then(() => shouldRefreshTools(getToolsChecksum(responseData), serverToolsConfig?.cache)).then((refresh) => {
12157
+ if (refresh) {
12158
+ return getServerTools({
12159
+ baseUrl,
12160
+ getToken,
12161
+ forceRefresh: true,
12162
+ cache: serverToolsConfig?.cache
12163
+ });
12164
+ }
12165
+ }).catch((err) => {
11994
12166
  getLogger().warn("[useChatStorage] Failed to refresh server tools cache:", err);
11995
12167
  });
11996
12168
  }
@@ -14085,6 +14257,7 @@ async function updateVaultFolderOp(ctx, id, opts) {
14085
14257
  if (record.isDeleted) return null;
14086
14258
  const scopeChanged = opts.scope !== void 0 && opts.scope !== record.scope;
14087
14259
  const updated = await ctx.database.write(async () => {
14260
+ const memories = scopeChanged ? await ctx.vaultMemoryCollection.query(Q9.where("folder_id", id), Q9.where("is_deleted", false)).fetch() : [];
14088
14261
  const updates = [];
14089
14262
  updates.push(
14090
14263
  record.prepareUpdate((r) => {
@@ -14092,15 +14265,12 @@ async function updateVaultFolderOp(ctx, id, opts) {
14092
14265
  if (opts.scope !== void 0) r._setRaw("scope", opts.scope);
14093
14266
  })
14094
14267
  );
14095
- if (scopeChanged) {
14096
- const memories = await ctx.vaultMemoryCollection.query(Q9.where("folder_id", id), Q9.where("is_deleted", false)).fetch();
14097
- for (const memory of memories) {
14098
- updates.push(
14099
- memory.prepareUpdate((r) => {
14100
- r._setRaw("scope", opts.scope);
14101
- })
14102
- );
14103
- }
14268
+ for (const memory of memories) {
14269
+ updates.push(
14270
+ memory.prepareUpdate((r) => {
14271
+ r._setRaw("scope", opts.scope);
14272
+ })
14273
+ );
14104
14274
  }
14105
14275
  await ctx.database.batch(...updates);
14106
14276
  return ctx.vaultFolderCollection.find(id);
@@ -15999,6 +16169,824 @@ function useVoice(options) {
15999
16169
 
16000
16170
  // src/react/useCredits.ts
16001
16171
  import { useCallback as useCallback12, useEffect as useEffect6, useRef as useRef6, useState as useState11 } from "react";
16172
+
16173
+ // src/client/core/bodySerializer.gen.ts
16174
+ var jsonBodySerializer = {
16175
+ bodySerializer: (body) => JSON.stringify(
16176
+ body,
16177
+ (_key, value) => typeof value === "bigint" ? value.toString() : value
16178
+ )
16179
+ };
16180
+
16181
+ // src/client/core/pathSerializer.gen.ts
16182
+ var separatorArrayExplode = (style) => {
16183
+ switch (style) {
16184
+ case "label":
16185
+ return ".";
16186
+ case "matrix":
16187
+ return ";";
16188
+ case "simple":
16189
+ return ",";
16190
+ default:
16191
+ return "&";
16192
+ }
16193
+ };
16194
+ var separatorArrayNoExplode = (style) => {
16195
+ switch (style) {
16196
+ case "form":
16197
+ return ",";
16198
+ case "pipeDelimited":
16199
+ return "|";
16200
+ case "spaceDelimited":
16201
+ return "%20";
16202
+ default:
16203
+ return ",";
16204
+ }
16205
+ };
16206
+ var separatorObjectExplode = (style) => {
16207
+ switch (style) {
16208
+ case "label":
16209
+ return ".";
16210
+ case "matrix":
16211
+ return ";";
16212
+ case "simple":
16213
+ return ",";
16214
+ default:
16215
+ return "&";
16216
+ }
16217
+ };
16218
+ var serializeArrayParam = ({
16219
+ allowReserved,
16220
+ explode,
16221
+ name,
16222
+ style,
16223
+ value
16224
+ }) => {
16225
+ if (!explode) {
16226
+ const joinedValues2 = (allowReserved ? value : value.map((v) => encodeURIComponent(v))).join(separatorArrayNoExplode(style));
16227
+ switch (style) {
16228
+ case "label":
16229
+ return `.${joinedValues2}`;
16230
+ case "matrix":
16231
+ return `;${name}=${joinedValues2}`;
16232
+ case "simple":
16233
+ return joinedValues2;
16234
+ default:
16235
+ return `${name}=${joinedValues2}`;
16236
+ }
16237
+ }
16238
+ const separator = separatorArrayExplode(style);
16239
+ const joinedValues = value.map((v) => {
16240
+ if (style === "label" || style === "simple") {
16241
+ return allowReserved ? v : encodeURIComponent(v);
16242
+ }
16243
+ return serializePrimitiveParam({
16244
+ allowReserved,
16245
+ name,
16246
+ value: v
16247
+ });
16248
+ }).join(separator);
16249
+ return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues;
16250
+ };
16251
+ var serializePrimitiveParam = ({
16252
+ allowReserved,
16253
+ name,
16254
+ value
16255
+ }) => {
16256
+ if (value === void 0 || value === null) {
16257
+ return "";
16258
+ }
16259
+ if (typeof value === "object") {
16260
+ throw new Error(
16261
+ "Deeply-nested arrays/objects aren\u2019t supported. Provide your own `querySerializer()` to handle these."
16262
+ );
16263
+ }
16264
+ return `${name}=${allowReserved ? value : encodeURIComponent(value)}`;
16265
+ };
16266
+ var serializeObjectParam = ({
16267
+ allowReserved,
16268
+ explode,
16269
+ name,
16270
+ style,
16271
+ value,
16272
+ valueOnly
16273
+ }) => {
16274
+ if (value instanceof Date) {
16275
+ return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`;
16276
+ }
16277
+ if (style !== "deepObject" && !explode) {
16278
+ let values = [];
16279
+ Object.entries(value).forEach(([key, v]) => {
16280
+ values = [
16281
+ ...values,
16282
+ key,
16283
+ allowReserved ? v : encodeURIComponent(v)
16284
+ ];
16285
+ });
16286
+ const joinedValues2 = values.join(",");
16287
+ switch (style) {
16288
+ case "form":
16289
+ return `${name}=${joinedValues2}`;
16290
+ case "label":
16291
+ return `.${joinedValues2}`;
16292
+ case "matrix":
16293
+ return `;${name}=${joinedValues2}`;
16294
+ default:
16295
+ return joinedValues2;
16296
+ }
16297
+ }
16298
+ const separator = separatorObjectExplode(style);
16299
+ const joinedValues = Object.entries(value).map(
16300
+ ([key, v]) => serializePrimitiveParam({
16301
+ allowReserved,
16302
+ name: style === "deepObject" ? `${name}[${key}]` : key,
16303
+ value: v
16304
+ })
16305
+ ).join(separator);
16306
+ return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues;
16307
+ };
16308
+
16309
+ // src/client/core/utils.gen.ts
16310
+ function getValidRequestBody(options) {
16311
+ const hasBody = options.body !== void 0;
16312
+ const isSerializedBody = hasBody && options.bodySerializer;
16313
+ if (isSerializedBody) {
16314
+ if ("serializedBody" in options) {
16315
+ const hasSerializedBody = options.serializedBody !== void 0 && options.serializedBody !== "";
16316
+ return hasSerializedBody ? options.serializedBody : null;
16317
+ }
16318
+ return options.body !== "" ? options.body : null;
16319
+ }
16320
+ if (hasBody) {
16321
+ return options.body;
16322
+ }
16323
+ return void 0;
16324
+ }
16325
+
16326
+ // src/client/core/auth.gen.ts
16327
+ var getAuthToken = async (auth, callback) => {
16328
+ const token = typeof callback === "function" ? await callback(auth) : callback;
16329
+ if (!token) {
16330
+ return;
16331
+ }
16332
+ if (auth.scheme === "bearer") {
16333
+ return `Bearer ${token}`;
16334
+ }
16335
+ if (auth.scheme === "basic") {
16336
+ return `Basic ${btoa(token)}`;
16337
+ }
16338
+ return token;
16339
+ };
16340
+
16341
+ // src/client/client/utils.gen.ts
16342
+ var PATH_PARAM_RE = /\{[^{}]+\}/g;
16343
+ var defaultPathSerializer = ({ path, url: _url }) => {
16344
+ let url = _url;
16345
+ const matches = _url.match(PATH_PARAM_RE);
16346
+ if (matches) {
16347
+ for (const match of matches) {
16348
+ let explode = false;
16349
+ let name = match.substring(1, match.length - 1);
16350
+ let style = "simple";
16351
+ if (name.endsWith("*")) {
16352
+ explode = true;
16353
+ name = name.substring(0, name.length - 1);
16354
+ }
16355
+ if (name.startsWith(".")) {
16356
+ name = name.substring(1);
16357
+ style = "label";
16358
+ } else if (name.startsWith(";")) {
16359
+ name = name.substring(1);
16360
+ style = "matrix";
16361
+ }
16362
+ const value = path[name];
16363
+ if (value === void 0 || value === null) {
16364
+ continue;
16365
+ }
16366
+ if (Array.isArray(value)) {
16367
+ url = url.replace(
16368
+ match,
16369
+ serializeArrayParam({ explode, name, style, value })
16370
+ );
16371
+ continue;
16372
+ }
16373
+ if (typeof value === "object") {
16374
+ url = url.replace(
16375
+ match,
16376
+ serializeObjectParam({
16377
+ explode,
16378
+ name,
16379
+ style,
16380
+ value,
16381
+ valueOnly: true
16382
+ })
16383
+ );
16384
+ continue;
16385
+ }
16386
+ if (style === "matrix") {
16387
+ url = url.replace(
16388
+ match,
16389
+ `;${serializePrimitiveParam({
16390
+ name,
16391
+ value
16392
+ })}`
16393
+ );
16394
+ continue;
16395
+ }
16396
+ const replaceValue = encodeURIComponent(
16397
+ style === "label" ? `.${value}` : value
16398
+ );
16399
+ url = url.replace(match, replaceValue);
16400
+ }
16401
+ }
16402
+ return url;
16403
+ };
16404
+ var createQuerySerializer = ({
16405
+ parameters = {},
16406
+ ...args
16407
+ } = {}) => {
16408
+ const querySerializer = (queryParams) => {
16409
+ const search = [];
16410
+ if (queryParams && typeof queryParams === "object") {
16411
+ for (const name in queryParams) {
16412
+ const value = queryParams[name];
16413
+ if (value === void 0 || value === null) {
16414
+ continue;
16415
+ }
16416
+ const options = parameters[name] || args;
16417
+ if (Array.isArray(value)) {
16418
+ const serializedArray = serializeArrayParam({
16419
+ allowReserved: options.allowReserved,
16420
+ explode: true,
16421
+ name,
16422
+ style: "form",
16423
+ value,
16424
+ ...options.array
16425
+ });
16426
+ if (serializedArray) search.push(serializedArray);
16427
+ } else if (typeof value === "object") {
16428
+ const serializedObject = serializeObjectParam({
16429
+ allowReserved: options.allowReserved,
16430
+ explode: true,
16431
+ name,
16432
+ style: "deepObject",
16433
+ value,
16434
+ ...options.object
16435
+ });
16436
+ if (serializedObject) search.push(serializedObject);
16437
+ } else {
16438
+ const serializedPrimitive = serializePrimitiveParam({
16439
+ allowReserved: options.allowReserved,
16440
+ name,
16441
+ value
16442
+ });
16443
+ if (serializedPrimitive) search.push(serializedPrimitive);
16444
+ }
16445
+ }
16446
+ }
16447
+ return search.join("&");
16448
+ };
16449
+ return querySerializer;
16450
+ };
16451
+ var getParseAs = (contentType) => {
16452
+ if (!contentType) {
16453
+ return "stream";
16454
+ }
16455
+ const cleanContent = contentType.split(";")[0]?.trim();
16456
+ if (!cleanContent) {
16457
+ return;
16458
+ }
16459
+ if (cleanContent.startsWith("application/json") || cleanContent.endsWith("+json")) {
16460
+ return "json";
16461
+ }
16462
+ if (cleanContent === "multipart/form-data") {
16463
+ return "formData";
16464
+ }
16465
+ if (["application/", "audio/", "image/", "video/"].some(
16466
+ (type) => cleanContent.startsWith(type)
16467
+ )) {
16468
+ return "blob";
16469
+ }
16470
+ if (cleanContent.startsWith("text/")) {
16471
+ return "text";
16472
+ }
16473
+ return;
16474
+ };
16475
+ var checkForExistence = (options, name) => {
16476
+ if (!name) {
16477
+ return false;
16478
+ }
16479
+ if (options.headers.has(name) || options.query?.[name] || options.headers.get("Cookie")?.includes(`${name}=`)) {
16480
+ return true;
16481
+ }
16482
+ return false;
16483
+ };
16484
+ var setAuthParams = async ({
16485
+ security,
16486
+ ...options
16487
+ }) => {
16488
+ for (const auth of security) {
16489
+ if (checkForExistence(options, auth.name)) {
16490
+ continue;
16491
+ }
16492
+ const token = await getAuthToken(auth, options.auth);
16493
+ if (!token) {
16494
+ continue;
16495
+ }
16496
+ const name = auth.name ?? "Authorization";
16497
+ switch (auth.in) {
16498
+ case "query":
16499
+ if (!options.query) {
16500
+ options.query = {};
16501
+ }
16502
+ options.query[name] = token;
16503
+ break;
16504
+ case "cookie":
16505
+ options.headers.append("Cookie", `${name}=${token}`);
16506
+ break;
16507
+ case "header":
16508
+ default:
16509
+ options.headers.set(name, token);
16510
+ break;
16511
+ }
16512
+ }
16513
+ };
16514
+ var buildUrl = (options) => {
16515
+ const url = getUrl({
16516
+ baseUrl: options.baseUrl,
16517
+ path: options.path,
16518
+ query: options.query,
16519
+ querySerializer: typeof options.querySerializer === "function" ? options.querySerializer : createQuerySerializer(options.querySerializer),
16520
+ url: options.url
16521
+ });
16522
+ return url;
16523
+ };
16524
+ var getUrl = ({
16525
+ baseUrl,
16526
+ path,
16527
+ query,
16528
+ querySerializer,
16529
+ url: _url
16530
+ }) => {
16531
+ const pathUrl = _url.startsWith("/") ? _url : `/${_url}`;
16532
+ let url = (baseUrl ?? "") + pathUrl;
16533
+ if (path) {
16534
+ url = defaultPathSerializer({ path, url });
16535
+ }
16536
+ let search = query ? querySerializer(query) : "";
16537
+ if (search.startsWith("?")) {
16538
+ search = search.substring(1);
16539
+ }
16540
+ if (search) {
16541
+ url += `?${search}`;
16542
+ }
16543
+ return url;
16544
+ };
16545
+ var mergeConfigs = (a, b) => {
16546
+ const config = { ...a, ...b };
16547
+ if (config.baseUrl?.endsWith("/")) {
16548
+ config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1);
16549
+ }
16550
+ config.headers = mergeHeaders(a.headers, b.headers);
16551
+ return config;
16552
+ };
16553
+ var headersEntries = (headers) => {
16554
+ const entries = [];
16555
+ headers.forEach((value, key) => {
16556
+ entries.push([key, value]);
16557
+ });
16558
+ return entries;
16559
+ };
16560
+ var mergeHeaders = (...headers) => {
16561
+ const mergedHeaders = new Headers();
16562
+ for (const header of headers) {
16563
+ if (!header || typeof header !== "object") {
16564
+ continue;
16565
+ }
16566
+ const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header);
16567
+ for (const [key, value] of iterator) {
16568
+ if (value === null) {
16569
+ mergedHeaders.delete(key);
16570
+ } else if (Array.isArray(value)) {
16571
+ for (const v of value) {
16572
+ mergedHeaders.append(key, v);
16573
+ }
16574
+ } else if (value !== void 0) {
16575
+ mergedHeaders.set(
16576
+ key,
16577
+ typeof value === "object" ? JSON.stringify(value) : value
16578
+ );
16579
+ }
16580
+ }
16581
+ }
16582
+ return mergedHeaders;
16583
+ };
16584
+ var Interceptors = class {
16585
+ constructor() {
16586
+ this.fns = [];
16587
+ }
16588
+ clear() {
16589
+ this.fns = [];
16590
+ }
16591
+ eject(id) {
16592
+ const index = this.getInterceptorIndex(id);
16593
+ if (this.fns[index]) {
16594
+ this.fns[index] = null;
16595
+ }
16596
+ }
16597
+ exists(id) {
16598
+ const index = this.getInterceptorIndex(id);
16599
+ return Boolean(this.fns[index]);
16600
+ }
16601
+ getInterceptorIndex(id) {
16602
+ if (typeof id === "number") {
16603
+ return this.fns[id] ? id : -1;
16604
+ }
16605
+ return this.fns.indexOf(id);
16606
+ }
16607
+ update(id, fn) {
16608
+ const index = this.getInterceptorIndex(id);
16609
+ if (this.fns[index]) {
16610
+ this.fns[index] = fn;
16611
+ return id;
16612
+ }
16613
+ return false;
16614
+ }
16615
+ use(fn) {
16616
+ this.fns.push(fn);
16617
+ return this.fns.length - 1;
16618
+ }
16619
+ };
16620
+ var createInterceptors = () => ({
16621
+ error: new Interceptors(),
16622
+ request: new Interceptors(),
16623
+ response: new Interceptors()
16624
+ });
16625
+ var defaultQuerySerializer = createQuerySerializer({
16626
+ allowReserved: false,
16627
+ array: {
16628
+ explode: true,
16629
+ style: "form"
16630
+ },
16631
+ object: {
16632
+ explode: true,
16633
+ style: "deepObject"
16634
+ }
16635
+ });
16636
+ var defaultHeaders = {
16637
+ "Content-Type": "application/json"
16638
+ };
16639
+ var createConfig = (override = {}) => ({
16640
+ ...jsonBodySerializer,
16641
+ headers: defaultHeaders,
16642
+ parseAs: "auto",
16643
+ querySerializer: defaultQuerySerializer,
16644
+ ...override
16645
+ });
16646
+
16647
+ // src/client/client/client.gen.ts
16648
+ var createClient = (config = {}) => {
16649
+ let _config = mergeConfigs(createConfig(), config);
16650
+ const getConfig = () => ({ ..._config });
16651
+ const setConfig = (config2) => {
16652
+ _config = mergeConfigs(_config, config2);
16653
+ return getConfig();
16654
+ };
16655
+ const interceptors = createInterceptors();
16656
+ const beforeRequest = async (options) => {
16657
+ const opts = {
16658
+ ..._config,
16659
+ ...options,
16660
+ fetch: options.fetch ?? _config.fetch ?? globalThis.fetch,
16661
+ headers: mergeHeaders(_config.headers, options.headers),
16662
+ serializedBody: void 0
16663
+ };
16664
+ if (opts.security) {
16665
+ await setAuthParams({
16666
+ ...opts,
16667
+ security: opts.security
16668
+ });
16669
+ }
16670
+ if (opts.requestValidator) {
16671
+ await opts.requestValidator(opts);
16672
+ }
16673
+ if (opts.body !== void 0 && opts.bodySerializer) {
16674
+ opts.serializedBody = opts.bodySerializer(opts.body);
16675
+ }
16676
+ if (opts.body === void 0 || opts.serializedBody === "") {
16677
+ opts.headers.delete("Content-Type");
16678
+ }
16679
+ const url = buildUrl(opts);
16680
+ return { opts, url };
16681
+ };
16682
+ const request = async (options) => {
16683
+ const { opts, url } = await beforeRequest(options);
16684
+ for (const fn of interceptors.request.fns) {
16685
+ if (fn) {
16686
+ await fn(opts);
16687
+ }
16688
+ }
16689
+ const _fetch = opts.fetch;
16690
+ const requestInit = {
16691
+ ...opts,
16692
+ body: getValidRequestBody(opts)
16693
+ };
16694
+ let response = await _fetch(url, requestInit);
16695
+ for (const fn of interceptors.response.fns) {
16696
+ if (fn) {
16697
+ response = await fn(response, opts);
16698
+ }
16699
+ }
16700
+ const result = {
16701
+ response
16702
+ };
16703
+ if (response.ok) {
16704
+ const parseAs = (opts.parseAs === "auto" ? getParseAs(response.headers.get("Content-Type")) : opts.parseAs) ?? "json";
16705
+ if (response.status === 204 || response.headers.get("Content-Length") === "0") {
16706
+ let emptyData;
16707
+ switch (parseAs) {
16708
+ case "arrayBuffer":
16709
+ case "blob":
16710
+ case "text":
16711
+ emptyData = await response[parseAs]();
16712
+ break;
16713
+ case "formData":
16714
+ emptyData = new FormData();
16715
+ break;
16716
+ case "stream":
16717
+ emptyData = response.body;
16718
+ break;
16719
+ case "json":
16720
+ default:
16721
+ emptyData = {};
16722
+ break;
16723
+ }
16724
+ return {
16725
+ data: emptyData,
16726
+ ...result
16727
+ };
16728
+ }
16729
+ let data;
16730
+ switch (parseAs) {
16731
+ case "arrayBuffer":
16732
+ case "blob":
16733
+ case "formData":
16734
+ case "json":
16735
+ case "text":
16736
+ data = await response[parseAs]();
16737
+ break;
16738
+ case "stream":
16739
+ return {
16740
+ data: response.body,
16741
+ ...result
16742
+ };
16743
+ }
16744
+ if (parseAs === "json") {
16745
+ if (opts.responseValidator) {
16746
+ await opts.responseValidator(data);
16747
+ }
16748
+ if (opts.responseTransformer) {
16749
+ data = await opts.responseTransformer(data);
16750
+ }
16751
+ }
16752
+ return {
16753
+ data,
16754
+ ...result
16755
+ };
16756
+ }
16757
+ const textError = await response.text();
16758
+ let jsonError;
16759
+ try {
16760
+ jsonError = JSON.parse(textError);
16761
+ } catch {
16762
+ }
16763
+ const error = jsonError ?? textError;
16764
+ let finalError = error;
16765
+ for (const fn of interceptors.error.fns) {
16766
+ if (fn) {
16767
+ finalError = await fn(error, response, opts);
16768
+ }
16769
+ }
16770
+ finalError = finalError || {};
16771
+ if (opts.throwOnError) {
16772
+ throw finalError;
16773
+ }
16774
+ return {
16775
+ error: finalError,
16776
+ ...result
16777
+ };
16778
+ };
16779
+ const makeMethodFn = (method) => (options) => request({ ...options, method });
16780
+ const makeSseFn = (method) => async (options) => {
16781
+ const { opts, url } = await beforeRequest(options);
16782
+ return createSseClient({
16783
+ ...opts,
16784
+ body: opts.body,
16785
+ headers: opts.headers,
16786
+ method,
16787
+ onRequest: async (url2, init) => {
16788
+ let request2 = new Request(url2, init);
16789
+ const requestInit = {
16790
+ ...init,
16791
+ method: init.method,
16792
+ url: url2
16793
+ };
16794
+ for (const fn of interceptors.request.fns) {
16795
+ if (fn) {
16796
+ await fn(requestInit);
16797
+ request2 = new Request(requestInit.url, requestInit);
16798
+ }
16799
+ }
16800
+ return request2;
16801
+ },
16802
+ url
16803
+ });
16804
+ };
16805
+ return {
16806
+ buildUrl,
16807
+ connect: makeMethodFn("CONNECT"),
16808
+ delete: makeMethodFn("DELETE"),
16809
+ get: makeMethodFn("GET"),
16810
+ getConfig,
16811
+ head: makeMethodFn("HEAD"),
16812
+ interceptors,
16813
+ options: makeMethodFn("OPTIONS"),
16814
+ patch: makeMethodFn("PATCH"),
16815
+ post: makeMethodFn("POST"),
16816
+ put: makeMethodFn("PUT"),
16817
+ request,
16818
+ setConfig,
16819
+ sse: {
16820
+ connect: makeSseFn("CONNECT"),
16821
+ delete: makeSseFn("DELETE"),
16822
+ get: makeSseFn("GET"),
16823
+ head: makeSseFn("HEAD"),
16824
+ options: makeSseFn("OPTIONS"),
16825
+ patch: makeSseFn("PATCH"),
16826
+ post: makeSseFn("POST"),
16827
+ put: makeSseFn("PUT"),
16828
+ trace: makeSseFn("TRACE")
16829
+ },
16830
+ trace: makeMethodFn("TRACE")
16831
+ };
16832
+ };
16833
+
16834
+ // src/client/client.gen.ts
16835
+ var client = createClient(createClientConfig(createConfig()));
16836
+
16837
+ // src/client/sdk.gen.ts
16838
+ var getApiV1Config = (options) => {
16839
+ return (options?.client ?? client).get({
16840
+ url: "/api/v1/config",
16841
+ ...options
16842
+ });
16843
+ };
16844
+ var getApiV1CreditsBalance = (options) => {
16845
+ return (options?.client ?? client).get({
16846
+ url: "/api/v1/credits/balance",
16847
+ ...options
16848
+ });
16849
+ };
16850
+ var getApiV1CreditsPacks = (options) => {
16851
+ return (options?.client ?? client).get({
16852
+ url: "/api/v1/credits/packs",
16853
+ ...options
16854
+ });
16855
+ };
16856
+ var postApiV1CreditsPurchase = (options) => {
16857
+ return (options.client ?? client).post({
16858
+ url: "/api/v1/credits/purchase",
16859
+ ...options,
16860
+ headers: {
16861
+ "Content-Type": "application/json",
16862
+ ...options.headers
16863
+ }
16864
+ });
16865
+ };
16866
+ var getApiV1Models = (options) => {
16867
+ return (options?.client ?? client).get({
16868
+ url: "/api/v1/models",
16869
+ ...options
16870
+ });
16871
+ };
16872
+ var postApiV1PhoneCalls = (options) => {
16873
+ return (options.client ?? client).post({
16874
+ url: "/api/v1/phone-calls",
16875
+ ...options,
16876
+ headers: {
16877
+ "Content-Type": "application/json",
16878
+ ...options.headers
16879
+ }
16880
+ });
16881
+ };
16882
+ var getApiV1PhoneCallsByCallId = (options) => {
16883
+ return (options.client ?? client).get({
16884
+ url: "/api/v1/phone-calls/{call_id}",
16885
+ ...options
16886
+ });
16887
+ };
16888
+ var postApiV1SubscriptionsCancel = (options) => {
16889
+ return (options?.client ?? client).post({
16890
+ url: "/api/v1/subscriptions/cancel",
16891
+ ...options,
16892
+ headers: {
16893
+ "Content-Type": "application/json",
16894
+ ...options?.headers
16895
+ }
16896
+ });
16897
+ };
16898
+ var postApiV1SubscriptionsCreateCheckoutSession = (options) => {
16899
+ return (options.client ?? client).post({
16900
+ url: "/api/v1/subscriptions/create-checkout-session",
16901
+ ...options,
16902
+ headers: {
16903
+ "Content-Type": "application/json",
16904
+ ...options.headers
16905
+ }
16906
+ });
16907
+ };
16908
+ var postApiV1SubscriptionsCustomerPortal = (options) => {
16909
+ return (options.client ?? client).post({
16910
+ url: "/api/v1/subscriptions/customer-portal",
16911
+ ...options,
16912
+ headers: {
16913
+ "Content-Type": "application/json",
16914
+ ...options.headers
16915
+ }
16916
+ });
16917
+ };
16918
+ var postApiV1SubscriptionsRenew = (options) => {
16919
+ return (options?.client ?? client).post({
16920
+ url: "/api/v1/subscriptions/renew",
16921
+ ...options
16922
+ });
16923
+ };
16924
+ var getApiV1SubscriptionsStatus = (options) => {
16925
+ return (options?.client ?? client).get({
16926
+ url: "/api/v1/subscriptions/status",
16927
+ ...options
16928
+ });
16929
+ };
16930
+ var getApiV1WalletsBinding = (options) => {
16931
+ return (options?.client ?? client).get({
16932
+ url: "/api/v1/wallets/binding",
16933
+ ...options
16934
+ });
16935
+ };
16936
+ var postApiV1WalletsBinding = (options) => {
16937
+ return (options.client ?? client).post({
16938
+ url: "/api/v1/wallets/binding",
16939
+ ...options,
16940
+ headers: {
16941
+ "Content-Type": "application/json",
16942
+ ...options.headers
16943
+ }
16944
+ });
16945
+ };
16946
+ var postApiV1WalletsBindingNonce = (options) => {
16947
+ return (options?.client ?? client).post({
16948
+ url: "/api/v1/wallets/binding/nonce",
16949
+ ...options
16950
+ });
16951
+ };
16952
+ var deleteApiV1WalletsBindingByAddress = (options) => {
16953
+ return (options.client ?? client).delete({
16954
+ url: "/api/v1/wallets/binding/{address}",
16955
+ ...options
16956
+ });
16957
+ };
16958
+ var postAuthOauthByProviderExchange = (options) => {
16959
+ return (options.client ?? client).post({
16960
+ url: "/auth/oauth/{provider}/exchange",
16961
+ ...options,
16962
+ headers: {
16963
+ "Content-Type": "application/json",
16964
+ ...options.headers
16965
+ }
16966
+ });
16967
+ };
16968
+ var postAuthOauthByProviderRefresh = (options) => {
16969
+ return (options.client ?? client).post({
16970
+ url: "/auth/oauth/{provider}/refresh",
16971
+ ...options,
16972
+ headers: {
16973
+ "Content-Type": "application/json",
16974
+ ...options.headers
16975
+ }
16976
+ });
16977
+ };
16978
+ var postAuthOauthByProviderRevoke = (options) => {
16979
+ return (options.client ?? client).post({
16980
+ url: "/auth/oauth/{provider}/revoke",
16981
+ ...options,
16982
+ headers: {
16983
+ "Content-Type": "application/json",
16984
+ ...options.headers
16985
+ }
16986
+ });
16987
+ };
16988
+
16989
+ // src/react/useCredits.ts
16002
16990
  function useCredits(options = {}) {
16003
16991
  const { getToken, baseUrl = BASE_URL, autoFetch = true, onError } = options;
16004
16992
  const [balance, setBalance] = useState11(null);