@anuma/sdk 1.0.0-next.20260224164627

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.
package/dist/index.cjs ADDED
@@ -0,0 +1,1718 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __esm = (fn, res) => function __init() {
7
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
8
+ };
9
+ var __export = (target, all) => {
10
+ for (var name in all)
11
+ __defProp(target, name, { get: all[name], enumerable: true });
12
+ };
13
+ var __copyProps = (to, from, except, desc) => {
14
+ if (from && typeof from === "object" || typeof from === "function") {
15
+ for (let key of __getOwnPropNames(from))
16
+ if (!__hasOwnProp.call(to, key) && key !== except)
17
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
18
+ }
19
+ return to;
20
+ };
21
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
22
+
23
+ // src/clientConfig.ts
24
+ var clientConfig_exports = {};
25
+ __export(clientConfig_exports, {
26
+ BASE_URL: () => BASE_URL,
27
+ MCP_R2_DOMAIN: () => MCP_R2_DOMAIN,
28
+ createClientConfig: () => createClientConfig
29
+ });
30
+ var BASE_URL, MCP_R2_DOMAIN, createClientConfig;
31
+ var init_clientConfig = __esm({
32
+ "src/clientConfig.ts"() {
33
+ "use strict";
34
+ BASE_URL = "https://portal.anuma-dev.ai";
35
+ MCP_R2_DOMAIN = "ai-image-mcp-images.4cf0e0ea50b97e72386fcf2f92a2d4e8.r2.cloudflarestorage.com";
36
+ createClientConfig = (config) => ({
37
+ ...config,
38
+ baseUrl: BASE_URL
39
+ });
40
+ }
41
+ });
42
+
43
+ // src/index.ts
44
+ var index_exports = {};
45
+ __export(index_exports, {
46
+ deleteApiV1AdminAppsByAppIdApiKeysById: () => deleteApiV1AdminAppsByAppIdApiKeysById,
47
+ deleteApiV1AdminAppsById: () => deleteApiV1AdminAppsById,
48
+ getApiV1AdminApps: () => getApiV1AdminApps,
49
+ getApiV1AdminAppsByAppIdApiKeys: () => getApiV1AdminAppsByAppIdApiKeys,
50
+ getApiV1AdminAppsByAppIdApiKeysById: () => getApiV1AdminAppsByAppIdApiKeysById,
51
+ getApiV1AdminAppsById: () => getApiV1AdminAppsById,
52
+ getApiV1Config: () => getApiV1Config,
53
+ getApiV1CreditsBalance: () => getApiV1CreditsBalance,
54
+ getApiV1CreditsPacks: () => getApiV1CreditsPacks,
55
+ getApiV1DocsSwaggerJson: () => getApiV1DocsSwaggerJson,
56
+ getApiV1Models: () => getApiV1Models,
57
+ getApiV1SubscriptionsPlans: () => getApiV1SubscriptionsPlans,
58
+ getApiV1SubscriptionsStatus: () => getApiV1SubscriptionsStatus,
59
+ getApiV1Tasks: () => getApiV1Tasks,
60
+ getApiV1Tools: () => getApiV1Tools,
61
+ getHealth: () => getHealth,
62
+ postApiV1AdminAddCredits: () => postApiV1AdminAddCredits,
63
+ postApiV1AdminApps: () => postApiV1AdminApps,
64
+ postApiV1AdminAppsByAppIdApiKeys: () => postApiV1AdminAppsByAppIdApiKeys,
65
+ postApiV1AdminSeedApps: () => postApiV1AdminSeedApps,
66
+ postApiV1AdminSubscriptionTier: () => postApiV1AdminSubscriptionTier,
67
+ postApiV1ChatCompletions: () => postApiV1ChatCompletions,
68
+ postApiV1CreditsClaimDaily: () => postApiV1CreditsClaimDaily,
69
+ postApiV1CreditsPurchase: () => postApiV1CreditsPurchase,
70
+ postApiV1CreditsSyncSnag: () => postApiV1CreditsSyncSnag,
71
+ postApiV1Embeddings: () => postApiV1Embeddings,
72
+ postApiV1Responses: () => postApiV1Responses,
73
+ postApiV1SubscriptionsCancel: () => postApiV1SubscriptionsCancel,
74
+ postApiV1SubscriptionsCreateCheckoutSession: () => postApiV1SubscriptionsCreateCheckoutSession,
75
+ postApiV1SubscriptionsCustomerPortal: () => postApiV1SubscriptionsCustomerPortal,
76
+ postApiV1SubscriptionsRenew: () => postApiV1SubscriptionsRenew,
77
+ postApiV1SubscriptionsWebhook: () => postApiV1SubscriptionsWebhook,
78
+ postAuthOauthByProviderExchange: () => postAuthOauthByProviderExchange,
79
+ postAuthOauthByProviderRefresh: () => postAuthOauthByProviderRefresh,
80
+ postAuthOauthByProviderRevoke: () => postAuthOauthByProviderRevoke,
81
+ putApiV1AdminAppsByAppIdApiKeysById: () => putApiV1AdminAppsByAppIdApiKeysById,
82
+ putApiV1AdminAppsById: () => putApiV1AdminAppsById,
83
+ selectServerSideTools: () => selectServerSideTools
84
+ });
85
+ module.exports = __toCommonJS(index_exports);
86
+
87
+ // src/client/core/bodySerializer.gen.ts
88
+ var jsonBodySerializer = {
89
+ bodySerializer: (body) => JSON.stringify(
90
+ body,
91
+ (_key, value) => typeof value === "bigint" ? value.toString() : value
92
+ )
93
+ };
94
+
95
+ // src/client/core/params.gen.ts
96
+ var extraPrefixesMap = {
97
+ $body_: "body",
98
+ $headers_: "headers",
99
+ $path_: "path",
100
+ $query_: "query"
101
+ };
102
+ var extraPrefixes = Object.entries(extraPrefixesMap);
103
+
104
+ // src/client/core/serverSentEvents.gen.ts
105
+ var createSseClient = ({
106
+ onRequest,
107
+ onSseError,
108
+ onSseEvent,
109
+ responseTransformer,
110
+ responseValidator,
111
+ sseDefaultRetryDelay,
112
+ sseMaxRetryAttempts,
113
+ sseMaxRetryDelay,
114
+ sseSleepFn,
115
+ url,
116
+ ...options
117
+ }) => {
118
+ let lastEventId;
119
+ const sleep = sseSleepFn ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
120
+ const createStream = async function* () {
121
+ let retryDelay = sseDefaultRetryDelay ?? 3e3;
122
+ let attempt = 0;
123
+ const signal = options.signal ?? new AbortController().signal;
124
+ while (true) {
125
+ if (signal.aborted) break;
126
+ attempt++;
127
+ const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers);
128
+ if (lastEventId !== void 0) {
129
+ headers.set("Last-Event-ID", lastEventId);
130
+ }
131
+ try {
132
+ const requestInit = {
133
+ redirect: "follow",
134
+ ...options,
135
+ body: options.serializedBody,
136
+ headers,
137
+ signal
138
+ };
139
+ let request = new Request(url, requestInit);
140
+ if (onRequest) {
141
+ request = await onRequest(url, requestInit);
142
+ }
143
+ const _fetch = options.fetch ?? globalThis.fetch;
144
+ const response = await _fetch(request);
145
+ if (!response.ok)
146
+ throw new Error(
147
+ `SSE failed: ${response.status} ${response.statusText}`
148
+ );
149
+ if (!response.body) throw new Error("No body in SSE response");
150
+ const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
151
+ let buffer = "";
152
+ const abortHandler = () => {
153
+ try {
154
+ reader.cancel();
155
+ } catch {
156
+ }
157
+ };
158
+ signal.addEventListener("abort", abortHandler);
159
+ try {
160
+ while (true) {
161
+ const { done, value } = await reader.read();
162
+ if (done) break;
163
+ buffer += value;
164
+ const chunks = buffer.split("\n\n");
165
+ buffer = chunks.pop() ?? "";
166
+ for (const chunk of chunks) {
167
+ const lines = chunk.split("\n");
168
+ const dataLines = [];
169
+ let eventName;
170
+ for (const line of lines) {
171
+ if (line.startsWith("data:")) {
172
+ dataLines.push(line.replace(/^data:\s*/, ""));
173
+ } else if (line.startsWith("event:")) {
174
+ eventName = line.replace(/^event:\s*/, "");
175
+ } else if (line.startsWith("id:")) {
176
+ lastEventId = line.replace(/^id:\s*/, "");
177
+ } else if (line.startsWith("retry:")) {
178
+ const parsed = Number.parseInt(
179
+ line.replace(/^retry:\s*/, ""),
180
+ 10
181
+ );
182
+ if (!Number.isNaN(parsed)) {
183
+ retryDelay = parsed;
184
+ }
185
+ }
186
+ }
187
+ let data;
188
+ let parsedJson = false;
189
+ if (dataLines.length) {
190
+ const rawData = dataLines.join("\n");
191
+ try {
192
+ data = JSON.parse(rawData);
193
+ parsedJson = true;
194
+ } catch {
195
+ data = rawData;
196
+ }
197
+ }
198
+ if (parsedJson) {
199
+ if (responseValidator) {
200
+ await responseValidator(data);
201
+ }
202
+ if (responseTransformer) {
203
+ data = await responseTransformer(data);
204
+ }
205
+ }
206
+ onSseEvent?.({
207
+ data,
208
+ event: eventName,
209
+ id: lastEventId,
210
+ retry: retryDelay
211
+ });
212
+ if (dataLines.length) {
213
+ yield data;
214
+ }
215
+ }
216
+ }
217
+ } finally {
218
+ signal.removeEventListener("abort", abortHandler);
219
+ reader.releaseLock();
220
+ }
221
+ break;
222
+ } catch (error) {
223
+ onSseError?.(error);
224
+ if (sseMaxRetryAttempts !== void 0 && attempt >= sseMaxRetryAttempts) {
225
+ break;
226
+ }
227
+ const backoff = Math.min(
228
+ retryDelay * 2 ** (attempt - 1),
229
+ sseMaxRetryDelay ?? 3e4
230
+ );
231
+ await sleep(backoff);
232
+ }
233
+ }
234
+ };
235
+ const stream = createStream();
236
+ return { stream };
237
+ };
238
+
239
+ // src/client/core/pathSerializer.gen.ts
240
+ var separatorArrayExplode = (style) => {
241
+ switch (style) {
242
+ case "label":
243
+ return ".";
244
+ case "matrix":
245
+ return ";";
246
+ case "simple":
247
+ return ",";
248
+ default:
249
+ return "&";
250
+ }
251
+ };
252
+ var separatorArrayNoExplode = (style) => {
253
+ switch (style) {
254
+ case "form":
255
+ return ",";
256
+ case "pipeDelimited":
257
+ return "|";
258
+ case "spaceDelimited":
259
+ return "%20";
260
+ default:
261
+ return ",";
262
+ }
263
+ };
264
+ var separatorObjectExplode = (style) => {
265
+ switch (style) {
266
+ case "label":
267
+ return ".";
268
+ case "matrix":
269
+ return ";";
270
+ case "simple":
271
+ return ",";
272
+ default:
273
+ return "&";
274
+ }
275
+ };
276
+ var serializeArrayParam = ({
277
+ allowReserved,
278
+ explode,
279
+ name,
280
+ style,
281
+ value
282
+ }) => {
283
+ if (!explode) {
284
+ const joinedValues2 = (allowReserved ? value : value.map((v) => encodeURIComponent(v))).join(separatorArrayNoExplode(style));
285
+ switch (style) {
286
+ case "label":
287
+ return `.${joinedValues2}`;
288
+ case "matrix":
289
+ return `;${name}=${joinedValues2}`;
290
+ case "simple":
291
+ return joinedValues2;
292
+ default:
293
+ return `${name}=${joinedValues2}`;
294
+ }
295
+ }
296
+ const separator = separatorArrayExplode(style);
297
+ const joinedValues = value.map((v) => {
298
+ if (style === "label" || style === "simple") {
299
+ return allowReserved ? v : encodeURIComponent(v);
300
+ }
301
+ return serializePrimitiveParam({
302
+ allowReserved,
303
+ name,
304
+ value: v
305
+ });
306
+ }).join(separator);
307
+ return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues;
308
+ };
309
+ var serializePrimitiveParam = ({
310
+ allowReserved,
311
+ name,
312
+ value
313
+ }) => {
314
+ if (value === void 0 || value === null) {
315
+ return "";
316
+ }
317
+ if (typeof value === "object") {
318
+ throw new Error(
319
+ "Deeply-nested arrays/objects aren\u2019t supported. Provide your own `querySerializer()` to handle these."
320
+ );
321
+ }
322
+ return `${name}=${allowReserved ? value : encodeURIComponent(value)}`;
323
+ };
324
+ var serializeObjectParam = ({
325
+ allowReserved,
326
+ explode,
327
+ name,
328
+ style,
329
+ value,
330
+ valueOnly
331
+ }) => {
332
+ if (value instanceof Date) {
333
+ return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`;
334
+ }
335
+ if (style !== "deepObject" && !explode) {
336
+ let values = [];
337
+ Object.entries(value).forEach(([key, v]) => {
338
+ values = [
339
+ ...values,
340
+ key,
341
+ allowReserved ? v : encodeURIComponent(v)
342
+ ];
343
+ });
344
+ const joinedValues2 = values.join(",");
345
+ switch (style) {
346
+ case "form":
347
+ return `${name}=${joinedValues2}`;
348
+ case "label":
349
+ return `.${joinedValues2}`;
350
+ case "matrix":
351
+ return `;${name}=${joinedValues2}`;
352
+ default:
353
+ return joinedValues2;
354
+ }
355
+ }
356
+ const separator = separatorObjectExplode(style);
357
+ const joinedValues = Object.entries(value).map(
358
+ ([key, v]) => serializePrimitiveParam({
359
+ allowReserved,
360
+ name: style === "deepObject" ? `${name}[${key}]` : key,
361
+ value: v
362
+ })
363
+ ).join(separator);
364
+ return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues;
365
+ };
366
+
367
+ // src/client/core/utils.gen.ts
368
+ function getValidRequestBody(options) {
369
+ const hasBody = options.body !== void 0;
370
+ const isSerializedBody = hasBody && options.bodySerializer;
371
+ if (isSerializedBody) {
372
+ if ("serializedBody" in options) {
373
+ const hasSerializedBody = options.serializedBody !== void 0 && options.serializedBody !== "";
374
+ return hasSerializedBody ? options.serializedBody : null;
375
+ }
376
+ return options.body !== "" ? options.body : null;
377
+ }
378
+ if (hasBody) {
379
+ return options.body;
380
+ }
381
+ return void 0;
382
+ }
383
+
384
+ // src/client/core/auth.gen.ts
385
+ var getAuthToken = async (auth, callback) => {
386
+ const token = typeof callback === "function" ? await callback(auth) : callback;
387
+ if (!token) {
388
+ return;
389
+ }
390
+ if (auth.scheme === "bearer") {
391
+ return `Bearer ${token}`;
392
+ }
393
+ if (auth.scheme === "basic") {
394
+ return `Basic ${btoa(token)}`;
395
+ }
396
+ return token;
397
+ };
398
+
399
+ // src/client/client/utils.gen.ts
400
+ var PATH_PARAM_RE = /\{[^{}]+\}/g;
401
+ var defaultPathSerializer = ({ path, url: _url }) => {
402
+ let url = _url;
403
+ const matches = _url.match(PATH_PARAM_RE);
404
+ if (matches) {
405
+ for (const match of matches) {
406
+ let explode = false;
407
+ let name = match.substring(1, match.length - 1);
408
+ let style = "simple";
409
+ if (name.endsWith("*")) {
410
+ explode = true;
411
+ name = name.substring(0, name.length - 1);
412
+ }
413
+ if (name.startsWith(".")) {
414
+ name = name.substring(1);
415
+ style = "label";
416
+ } else if (name.startsWith(";")) {
417
+ name = name.substring(1);
418
+ style = "matrix";
419
+ }
420
+ const value = path[name];
421
+ if (value === void 0 || value === null) {
422
+ continue;
423
+ }
424
+ if (Array.isArray(value)) {
425
+ url = url.replace(
426
+ match,
427
+ serializeArrayParam({ explode, name, style, value })
428
+ );
429
+ continue;
430
+ }
431
+ if (typeof value === "object") {
432
+ url = url.replace(
433
+ match,
434
+ serializeObjectParam({
435
+ explode,
436
+ name,
437
+ style,
438
+ value,
439
+ valueOnly: true
440
+ })
441
+ );
442
+ continue;
443
+ }
444
+ if (style === "matrix") {
445
+ url = url.replace(
446
+ match,
447
+ `;${serializePrimitiveParam({
448
+ name,
449
+ value
450
+ })}`
451
+ );
452
+ continue;
453
+ }
454
+ const replaceValue = encodeURIComponent(
455
+ style === "label" ? `.${value}` : value
456
+ );
457
+ url = url.replace(match, replaceValue);
458
+ }
459
+ }
460
+ return url;
461
+ };
462
+ var createQuerySerializer = ({
463
+ parameters = {},
464
+ ...args
465
+ } = {}) => {
466
+ const querySerializer = (queryParams) => {
467
+ const search = [];
468
+ if (queryParams && typeof queryParams === "object") {
469
+ for (const name in queryParams) {
470
+ const value = queryParams[name];
471
+ if (value === void 0 || value === null) {
472
+ continue;
473
+ }
474
+ const options = parameters[name] || args;
475
+ if (Array.isArray(value)) {
476
+ const serializedArray = serializeArrayParam({
477
+ allowReserved: options.allowReserved,
478
+ explode: true,
479
+ name,
480
+ style: "form",
481
+ value,
482
+ ...options.array
483
+ });
484
+ if (serializedArray) search.push(serializedArray);
485
+ } else if (typeof value === "object") {
486
+ const serializedObject = serializeObjectParam({
487
+ allowReserved: options.allowReserved,
488
+ explode: true,
489
+ name,
490
+ style: "deepObject",
491
+ value,
492
+ ...options.object
493
+ });
494
+ if (serializedObject) search.push(serializedObject);
495
+ } else {
496
+ const serializedPrimitive = serializePrimitiveParam({
497
+ allowReserved: options.allowReserved,
498
+ name,
499
+ value
500
+ });
501
+ if (serializedPrimitive) search.push(serializedPrimitive);
502
+ }
503
+ }
504
+ }
505
+ return search.join("&");
506
+ };
507
+ return querySerializer;
508
+ };
509
+ var getParseAs = (contentType) => {
510
+ if (!contentType) {
511
+ return "stream";
512
+ }
513
+ const cleanContent = contentType.split(";")[0]?.trim();
514
+ if (!cleanContent) {
515
+ return;
516
+ }
517
+ if (cleanContent.startsWith("application/json") || cleanContent.endsWith("+json")) {
518
+ return "json";
519
+ }
520
+ if (cleanContent === "multipart/form-data") {
521
+ return "formData";
522
+ }
523
+ if (["application/", "audio/", "image/", "video/"].some(
524
+ (type) => cleanContent.startsWith(type)
525
+ )) {
526
+ return "blob";
527
+ }
528
+ if (cleanContent.startsWith("text/")) {
529
+ return "text";
530
+ }
531
+ return;
532
+ };
533
+ var checkForExistence = (options, name) => {
534
+ if (!name) {
535
+ return false;
536
+ }
537
+ if (options.headers.has(name) || options.query?.[name] || options.headers.get("Cookie")?.includes(`${name}=`)) {
538
+ return true;
539
+ }
540
+ return false;
541
+ };
542
+ var setAuthParams = async ({
543
+ security,
544
+ ...options
545
+ }) => {
546
+ for (const auth of security) {
547
+ if (checkForExistence(options, auth.name)) {
548
+ continue;
549
+ }
550
+ const token = await getAuthToken(auth, options.auth);
551
+ if (!token) {
552
+ continue;
553
+ }
554
+ const name = auth.name ?? "Authorization";
555
+ switch (auth.in) {
556
+ case "query":
557
+ if (!options.query) {
558
+ options.query = {};
559
+ }
560
+ options.query[name] = token;
561
+ break;
562
+ case "cookie":
563
+ options.headers.append("Cookie", `${name}=${token}`);
564
+ break;
565
+ case "header":
566
+ default:
567
+ options.headers.set(name, token);
568
+ break;
569
+ }
570
+ }
571
+ };
572
+ var buildUrl = (options) => {
573
+ const url = getUrl({
574
+ baseUrl: options.baseUrl,
575
+ path: options.path,
576
+ query: options.query,
577
+ querySerializer: typeof options.querySerializer === "function" ? options.querySerializer : createQuerySerializer(options.querySerializer),
578
+ url: options.url
579
+ });
580
+ return url;
581
+ };
582
+ var getUrl = ({
583
+ baseUrl,
584
+ path,
585
+ query,
586
+ querySerializer,
587
+ url: _url
588
+ }) => {
589
+ const pathUrl = _url.startsWith("/") ? _url : `/${_url}`;
590
+ let url = (baseUrl ?? "") + pathUrl;
591
+ if (path) {
592
+ url = defaultPathSerializer({ path, url });
593
+ }
594
+ let search = query ? querySerializer(query) : "";
595
+ if (search.startsWith("?")) {
596
+ search = search.substring(1);
597
+ }
598
+ if (search) {
599
+ url += `?${search}`;
600
+ }
601
+ return url;
602
+ };
603
+ var mergeConfigs = (a, b) => {
604
+ const config = { ...a, ...b };
605
+ if (config.baseUrl?.endsWith("/")) {
606
+ config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1);
607
+ }
608
+ config.headers = mergeHeaders(a.headers, b.headers);
609
+ return config;
610
+ };
611
+ var headersEntries = (headers) => {
612
+ const entries = [];
613
+ headers.forEach((value, key) => {
614
+ entries.push([key, value]);
615
+ });
616
+ return entries;
617
+ };
618
+ var mergeHeaders = (...headers) => {
619
+ const mergedHeaders = new Headers();
620
+ for (const header of headers) {
621
+ if (!header || typeof header !== "object") {
622
+ continue;
623
+ }
624
+ const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header);
625
+ for (const [key, value] of iterator) {
626
+ if (value === null) {
627
+ mergedHeaders.delete(key);
628
+ } else if (Array.isArray(value)) {
629
+ for (const v of value) {
630
+ mergedHeaders.append(key, v);
631
+ }
632
+ } else if (value !== void 0) {
633
+ mergedHeaders.set(
634
+ key,
635
+ typeof value === "object" ? JSON.stringify(value) : value
636
+ );
637
+ }
638
+ }
639
+ }
640
+ return mergedHeaders;
641
+ };
642
+ var Interceptors = class {
643
+ constructor() {
644
+ this.fns = [];
645
+ }
646
+ clear() {
647
+ this.fns = [];
648
+ }
649
+ eject(id) {
650
+ const index = this.getInterceptorIndex(id);
651
+ if (this.fns[index]) {
652
+ this.fns[index] = null;
653
+ }
654
+ }
655
+ exists(id) {
656
+ const index = this.getInterceptorIndex(id);
657
+ return Boolean(this.fns[index]);
658
+ }
659
+ getInterceptorIndex(id) {
660
+ if (typeof id === "number") {
661
+ return this.fns[id] ? id : -1;
662
+ }
663
+ return this.fns.indexOf(id);
664
+ }
665
+ update(id, fn) {
666
+ const index = this.getInterceptorIndex(id);
667
+ if (this.fns[index]) {
668
+ this.fns[index] = fn;
669
+ return id;
670
+ }
671
+ return false;
672
+ }
673
+ use(fn) {
674
+ this.fns.push(fn);
675
+ return this.fns.length - 1;
676
+ }
677
+ };
678
+ var createInterceptors = () => ({
679
+ error: new Interceptors(),
680
+ request: new Interceptors(),
681
+ response: new Interceptors()
682
+ });
683
+ var defaultQuerySerializer = createQuerySerializer({
684
+ allowReserved: false,
685
+ array: {
686
+ explode: true,
687
+ style: "form"
688
+ },
689
+ object: {
690
+ explode: true,
691
+ style: "deepObject"
692
+ }
693
+ });
694
+ var defaultHeaders = {
695
+ "Content-Type": "application/json"
696
+ };
697
+ var createConfig = (override = {}) => ({
698
+ ...jsonBodySerializer,
699
+ headers: defaultHeaders,
700
+ parseAs: "auto",
701
+ querySerializer: defaultQuerySerializer,
702
+ ...override
703
+ });
704
+
705
+ // src/client/client/client.gen.ts
706
+ var createClient = (config = {}) => {
707
+ let _config = mergeConfigs(createConfig(), config);
708
+ const getConfig = () => ({ ..._config });
709
+ const setConfig = (config2) => {
710
+ _config = mergeConfigs(_config, config2);
711
+ return getConfig();
712
+ };
713
+ const interceptors = createInterceptors();
714
+ const beforeRequest = async (options) => {
715
+ const opts = {
716
+ ..._config,
717
+ ...options,
718
+ fetch: options.fetch ?? _config.fetch ?? globalThis.fetch,
719
+ headers: mergeHeaders(_config.headers, options.headers),
720
+ serializedBody: void 0
721
+ };
722
+ if (opts.security) {
723
+ await setAuthParams({
724
+ ...opts,
725
+ security: opts.security
726
+ });
727
+ }
728
+ if (opts.requestValidator) {
729
+ await opts.requestValidator(opts);
730
+ }
731
+ if (opts.body !== void 0 && opts.bodySerializer) {
732
+ opts.serializedBody = opts.bodySerializer(opts.body);
733
+ }
734
+ if (opts.body === void 0 || opts.serializedBody === "") {
735
+ opts.headers.delete("Content-Type");
736
+ }
737
+ const url = buildUrl(opts);
738
+ return { opts, url };
739
+ };
740
+ const request = async (options) => {
741
+ const { opts, url } = await beforeRequest(options);
742
+ for (const fn of interceptors.request.fns) {
743
+ if (fn) {
744
+ await fn(opts);
745
+ }
746
+ }
747
+ const _fetch = opts.fetch;
748
+ const requestInit = {
749
+ ...opts,
750
+ body: getValidRequestBody(opts)
751
+ };
752
+ let response = await _fetch(url, requestInit);
753
+ for (const fn of interceptors.response.fns) {
754
+ if (fn) {
755
+ response = await fn(response, opts);
756
+ }
757
+ }
758
+ const result = {
759
+ response
760
+ };
761
+ if (response.ok) {
762
+ const parseAs = (opts.parseAs === "auto" ? getParseAs(response.headers.get("Content-Type")) : opts.parseAs) ?? "json";
763
+ if (response.status === 204 || response.headers.get("Content-Length") === "0") {
764
+ let emptyData;
765
+ switch (parseAs) {
766
+ case "arrayBuffer":
767
+ case "blob":
768
+ case "text":
769
+ emptyData = await response[parseAs]();
770
+ break;
771
+ case "formData":
772
+ emptyData = new FormData();
773
+ break;
774
+ case "stream":
775
+ emptyData = response.body;
776
+ break;
777
+ case "json":
778
+ default:
779
+ emptyData = {};
780
+ break;
781
+ }
782
+ return {
783
+ data: emptyData,
784
+ ...result
785
+ };
786
+ }
787
+ let data;
788
+ switch (parseAs) {
789
+ case "arrayBuffer":
790
+ case "blob":
791
+ case "formData":
792
+ case "json":
793
+ case "text":
794
+ data = await response[parseAs]();
795
+ break;
796
+ case "stream":
797
+ return {
798
+ data: response.body,
799
+ ...result
800
+ };
801
+ }
802
+ if (parseAs === "json") {
803
+ if (opts.responseValidator) {
804
+ await opts.responseValidator(data);
805
+ }
806
+ if (opts.responseTransformer) {
807
+ data = await opts.responseTransformer(data);
808
+ }
809
+ }
810
+ return {
811
+ data,
812
+ ...result
813
+ };
814
+ }
815
+ const textError = await response.text();
816
+ let jsonError;
817
+ try {
818
+ jsonError = JSON.parse(textError);
819
+ } catch {
820
+ }
821
+ const error = jsonError ?? textError;
822
+ let finalError = error;
823
+ for (const fn of interceptors.error.fns) {
824
+ if (fn) {
825
+ finalError = await fn(error, response, opts);
826
+ }
827
+ }
828
+ finalError = finalError || {};
829
+ if (opts.throwOnError) {
830
+ throw finalError;
831
+ }
832
+ return {
833
+ error: finalError,
834
+ ...result
835
+ };
836
+ };
837
+ const makeMethodFn = (method) => (options) => request({ ...options, method });
838
+ const makeSseFn = (method) => async (options) => {
839
+ const { opts, url } = await beforeRequest(options);
840
+ return createSseClient({
841
+ ...opts,
842
+ body: opts.body,
843
+ headers: opts.headers,
844
+ method,
845
+ onRequest: async (url2, init) => {
846
+ let request2 = new Request(url2, init);
847
+ const requestInit = {
848
+ ...init,
849
+ method: init.method,
850
+ url: url2
851
+ };
852
+ for (const fn of interceptors.request.fns) {
853
+ if (fn) {
854
+ await fn(requestInit);
855
+ request2 = new Request(requestInit.url, requestInit);
856
+ }
857
+ }
858
+ return request2;
859
+ },
860
+ url
861
+ });
862
+ };
863
+ return {
864
+ buildUrl,
865
+ connect: makeMethodFn("CONNECT"),
866
+ delete: makeMethodFn("DELETE"),
867
+ get: makeMethodFn("GET"),
868
+ getConfig,
869
+ head: makeMethodFn("HEAD"),
870
+ interceptors,
871
+ options: makeMethodFn("OPTIONS"),
872
+ patch: makeMethodFn("PATCH"),
873
+ post: makeMethodFn("POST"),
874
+ put: makeMethodFn("PUT"),
875
+ request,
876
+ setConfig,
877
+ sse: {
878
+ connect: makeSseFn("CONNECT"),
879
+ delete: makeSseFn("DELETE"),
880
+ get: makeSseFn("GET"),
881
+ head: makeSseFn("HEAD"),
882
+ options: makeSseFn("OPTIONS"),
883
+ patch: makeSseFn("PATCH"),
884
+ post: makeSseFn("POST"),
885
+ put: makeSseFn("PUT"),
886
+ trace: makeSseFn("TRACE")
887
+ },
888
+ trace: makeMethodFn("TRACE")
889
+ };
890
+ };
891
+
892
+ // src/client/client.gen.ts
893
+ init_clientConfig();
894
+ var client = createClient(createClientConfig(createConfig()));
895
+
896
+ // src/client/sdk.gen.ts
897
+ var postApiV1AdminAddCredits = (options) => {
898
+ return (options.client ?? client).post({
899
+ url: "/api/v1/admin/add-credits",
900
+ ...options,
901
+ headers: {
902
+ "Content-Type": "application/json",
903
+ ...options.headers
904
+ }
905
+ });
906
+ };
907
+ var getApiV1AdminApps = (options) => {
908
+ return (options.client ?? client).get({
909
+ url: "/api/v1/admin/apps",
910
+ ...options
911
+ });
912
+ };
913
+ var postApiV1AdminApps = (options) => {
914
+ return (options.client ?? client).post({
915
+ url: "/api/v1/admin/apps",
916
+ ...options,
917
+ headers: {
918
+ "Content-Type": "application/json",
919
+ ...options.headers
920
+ }
921
+ });
922
+ };
923
+ var getApiV1AdminAppsByAppIdApiKeys = (options) => {
924
+ return (options.client ?? client).get({
925
+ url: "/api/v1/admin/apps/{app_id}/api-keys",
926
+ ...options
927
+ });
928
+ };
929
+ var postApiV1AdminAppsByAppIdApiKeys = (options) => {
930
+ return (options.client ?? client).post({
931
+ url: "/api/v1/admin/apps/{app_id}/api-keys",
932
+ ...options,
933
+ headers: {
934
+ "Content-Type": "application/json",
935
+ ...options.headers
936
+ }
937
+ });
938
+ };
939
+ var deleteApiV1AdminAppsByAppIdApiKeysById = (options) => {
940
+ return (options.client ?? client).delete({
941
+ url: "/api/v1/admin/apps/{app_id}/api-keys/{id}",
942
+ ...options
943
+ });
944
+ };
945
+ var getApiV1AdminAppsByAppIdApiKeysById = (options) => {
946
+ return (options.client ?? client).get({
947
+ url: "/api/v1/admin/apps/{app_id}/api-keys/{id}",
948
+ ...options
949
+ });
950
+ };
951
+ var putApiV1AdminAppsByAppIdApiKeysById = (options) => {
952
+ return (options.client ?? client).put({
953
+ url: "/api/v1/admin/apps/{app_id}/api-keys/{id}",
954
+ ...options,
955
+ headers: {
956
+ "Content-Type": "application/json",
957
+ ...options.headers
958
+ }
959
+ });
960
+ };
961
+ var deleteApiV1AdminAppsById = (options) => {
962
+ return (options.client ?? client).delete({
963
+ url: "/api/v1/admin/apps/{id}",
964
+ ...options
965
+ });
966
+ };
967
+ var getApiV1AdminAppsById = (options) => {
968
+ return (options.client ?? client).get({
969
+ url: "/api/v1/admin/apps/{id}",
970
+ ...options
971
+ });
972
+ };
973
+ var putApiV1AdminAppsById = (options) => {
974
+ return (options.client ?? client).put({
975
+ url: "/api/v1/admin/apps/{id}",
976
+ ...options,
977
+ headers: {
978
+ "Content-Type": "application/json",
979
+ ...options.headers
980
+ }
981
+ });
982
+ };
983
+ var postApiV1AdminSeedApps = (options) => {
984
+ return (options.client ?? client).post({
985
+ url: "/api/v1/admin/seed-apps",
986
+ ...options,
987
+ headers: {
988
+ "Content-Type": "application/json",
989
+ ...options.headers
990
+ }
991
+ });
992
+ };
993
+ var postApiV1AdminSubscriptionTier = (options) => {
994
+ return (options.client ?? client).post({
995
+ url: "/api/v1/admin/subscription-tier",
996
+ ...options,
997
+ headers: {
998
+ "Content-Type": "application/json",
999
+ ...options.headers
1000
+ }
1001
+ });
1002
+ };
1003
+ var postApiV1ChatCompletions = (options) => {
1004
+ return (options.client ?? client).post({
1005
+ url: "/api/v1/chat/completions",
1006
+ ...options,
1007
+ headers: {
1008
+ "Content-Type": "application/json",
1009
+ ...options.headers
1010
+ }
1011
+ });
1012
+ };
1013
+ var getApiV1Config = (options) => {
1014
+ return (options?.client ?? client).get({
1015
+ url: "/api/v1/config",
1016
+ ...options
1017
+ });
1018
+ };
1019
+ var getApiV1CreditsBalance = (options) => {
1020
+ return (options?.client ?? client).get({
1021
+ url: "/api/v1/credits/balance",
1022
+ ...options
1023
+ });
1024
+ };
1025
+ var postApiV1CreditsClaimDaily = (options) => {
1026
+ return (options?.client ?? client).post({
1027
+ url: "/api/v1/credits/claim-daily",
1028
+ ...options
1029
+ });
1030
+ };
1031
+ var getApiV1CreditsPacks = (options) => {
1032
+ return (options?.client ?? client).get({
1033
+ url: "/api/v1/credits/packs",
1034
+ ...options
1035
+ });
1036
+ };
1037
+ var postApiV1CreditsPurchase = (options) => {
1038
+ return (options.client ?? client).post({
1039
+ url: "/api/v1/credits/purchase",
1040
+ ...options,
1041
+ headers: {
1042
+ "Content-Type": "application/json",
1043
+ ...options.headers
1044
+ }
1045
+ });
1046
+ };
1047
+ var postApiV1CreditsSyncSnag = (options) => {
1048
+ return (options?.client ?? client).post({
1049
+ url: "/api/v1/credits/sync-snag",
1050
+ ...options
1051
+ });
1052
+ };
1053
+ var getApiV1DocsSwaggerJson = (options) => {
1054
+ return (options?.client ?? client).get({
1055
+ url: "/api/v1/docs/swagger.json",
1056
+ ...options
1057
+ });
1058
+ };
1059
+ var postApiV1Embeddings = (options) => {
1060
+ return (options.client ?? client).post({
1061
+ url: "/api/v1/embeddings",
1062
+ ...options,
1063
+ headers: {
1064
+ "Content-Type": "application/json",
1065
+ ...options.headers
1066
+ }
1067
+ });
1068
+ };
1069
+ var getApiV1Models = (options) => {
1070
+ return (options?.client ?? client).get({
1071
+ url: "/api/v1/models",
1072
+ ...options
1073
+ });
1074
+ };
1075
+ var postApiV1Responses = (options) => {
1076
+ return (options.client ?? client).post({
1077
+ url: "/api/v1/responses",
1078
+ ...options,
1079
+ headers: {
1080
+ "Content-Type": "application/json",
1081
+ ...options.headers
1082
+ }
1083
+ });
1084
+ };
1085
+ var postApiV1SubscriptionsCancel = (options) => {
1086
+ return (options?.client ?? client).post({
1087
+ url: "/api/v1/subscriptions/cancel",
1088
+ ...options
1089
+ });
1090
+ };
1091
+ var postApiV1SubscriptionsCreateCheckoutSession = (options) => {
1092
+ return (options.client ?? client).post({
1093
+ url: "/api/v1/subscriptions/create-checkout-session",
1094
+ ...options,
1095
+ headers: {
1096
+ "Content-Type": "application/json",
1097
+ ...options.headers
1098
+ }
1099
+ });
1100
+ };
1101
+ var postApiV1SubscriptionsCustomerPortal = (options) => {
1102
+ return (options.client ?? client).post({
1103
+ url: "/api/v1/subscriptions/customer-portal",
1104
+ ...options,
1105
+ headers: {
1106
+ "Content-Type": "application/json",
1107
+ ...options.headers
1108
+ }
1109
+ });
1110
+ };
1111
+ var getApiV1SubscriptionsPlans = (options) => {
1112
+ return (options?.client ?? client).get({
1113
+ url: "/api/v1/subscriptions/plans",
1114
+ ...options
1115
+ });
1116
+ };
1117
+ var postApiV1SubscriptionsRenew = (options) => {
1118
+ return (options?.client ?? client).post({
1119
+ url: "/api/v1/subscriptions/renew",
1120
+ ...options
1121
+ });
1122
+ };
1123
+ var getApiV1SubscriptionsStatus = (options) => {
1124
+ return (options?.client ?? client).get({
1125
+ url: "/api/v1/subscriptions/status",
1126
+ ...options
1127
+ });
1128
+ };
1129
+ var postApiV1SubscriptionsWebhook = (options) => {
1130
+ return (options.client ?? client).post({
1131
+ url: "/api/v1/subscriptions/webhook",
1132
+ ...options,
1133
+ headers: {
1134
+ "Content-Type": "application/json",
1135
+ ...options.headers
1136
+ }
1137
+ });
1138
+ };
1139
+ var getApiV1Tasks = (options) => {
1140
+ return (options?.client ?? client).get({
1141
+ url: "/api/v1/tasks",
1142
+ ...options
1143
+ });
1144
+ };
1145
+ var getApiV1Tools = (options) => {
1146
+ return (options?.client ?? client).get({
1147
+ url: "/api/v1/tools",
1148
+ ...options
1149
+ });
1150
+ };
1151
+ var postAuthOauthByProviderExchange = (options) => {
1152
+ return (options.client ?? client).post({
1153
+ url: "/auth/oauth/{provider}/exchange",
1154
+ ...options,
1155
+ headers: {
1156
+ "Content-Type": "application/json",
1157
+ ...options.headers
1158
+ }
1159
+ });
1160
+ };
1161
+ var postAuthOauthByProviderRefresh = (options) => {
1162
+ return (options.client ?? client).post({
1163
+ url: "/auth/oauth/{provider}/refresh",
1164
+ ...options,
1165
+ headers: {
1166
+ "Content-Type": "application/json",
1167
+ ...options.headers
1168
+ }
1169
+ });
1170
+ };
1171
+ var postAuthOauthByProviderRevoke = (options) => {
1172
+ return (options.client ?? client).post({
1173
+ url: "/auth/oauth/{provider}/revoke",
1174
+ ...options,
1175
+ headers: {
1176
+ "Content-Type": "application/json",
1177
+ ...options.headers
1178
+ }
1179
+ });
1180
+ };
1181
+ var getHealth = (options) => {
1182
+ return (options?.client ?? client).get({
1183
+ url: "/health",
1184
+ ...options
1185
+ });
1186
+ };
1187
+
1188
+ // src/lib/memoryRetrieval/chunking.ts
1189
+ var DEFAULT_CHUNK_SIZE = 400;
1190
+ var DEFAULT_CHUNK_OVERLAP = 50;
1191
+ var DEFAULT_MIN_CHUNK_SIZE = 50;
1192
+ function splitIntoSentences(text) {
1193
+ const sentenceRegex = /[.!?]+[\s"')}\]]*(?=\s|$)/g;
1194
+ const sentences = [];
1195
+ let lastIndex = 0;
1196
+ let match;
1197
+ while ((match = sentenceRegex.exec(text)) !== null) {
1198
+ const endIndex = match.index + match[0].length;
1199
+ const sentence = text.slice(lastIndex, endIndex).trim();
1200
+ if (sentence) {
1201
+ sentences.push(sentence);
1202
+ }
1203
+ lastIndex = endIndex;
1204
+ }
1205
+ const remaining = text.slice(lastIndex).trim();
1206
+ if (remaining) {
1207
+ sentences.push(remaining);
1208
+ }
1209
+ return sentences;
1210
+ }
1211
+ function chunkText(text, options) {
1212
+ const {
1213
+ chunkSize = DEFAULT_CHUNK_SIZE,
1214
+ chunkOverlap: requestedOverlap = DEFAULT_CHUNK_OVERLAP,
1215
+ minChunkSize = DEFAULT_MIN_CHUNK_SIZE
1216
+ } = options ?? {};
1217
+ const chunkOverlap = Math.min(requestedOverlap, chunkSize - 1);
1218
+ if (text.length <= chunkSize) {
1219
+ return [
1220
+ {
1221
+ text: text.trim(),
1222
+ startOffset: 0,
1223
+ endOffset: text.length
1224
+ }
1225
+ ];
1226
+ }
1227
+ const sentences = splitIntoSentences(text);
1228
+ const chunks = [];
1229
+ let currentChunkSentences = [];
1230
+ let currentChunkStart = 0;
1231
+ let currentOffset = 0;
1232
+ for (let i = 0; i < sentences.length; i++) {
1233
+ const sentence = sentences[i];
1234
+ let sentenceStart = text.indexOf(sentence, currentOffset);
1235
+ if (sentenceStart === -1) {
1236
+ sentenceStart = currentOffset;
1237
+ }
1238
+ const sentenceEnd = sentenceStart + sentence.length;
1239
+ if (sentence.length > chunkSize) {
1240
+ if (currentChunkSentences.length > 0) {
1241
+ const chunkText2 = currentChunkSentences.join(" ");
1242
+ chunks.push({
1243
+ text: chunkText2,
1244
+ startOffset: currentChunkStart,
1245
+ endOffset: currentOffset
1246
+ });
1247
+ currentChunkSentences = [];
1248
+ }
1249
+ for (let j = 0; j < sentence.length; j += chunkSize - chunkOverlap) {
1250
+ const chunkEnd = Math.min(j + chunkSize, sentence.length);
1251
+ const chunk = sentence.slice(j, chunkEnd);
1252
+ if (chunk.length >= minChunkSize) {
1253
+ chunks.push({
1254
+ text: chunk,
1255
+ startOffset: sentenceStart + j,
1256
+ endOffset: sentenceStart + chunkEnd
1257
+ });
1258
+ }
1259
+ }
1260
+ currentChunkStart = sentenceEnd;
1261
+ currentOffset = sentenceEnd;
1262
+ continue;
1263
+ }
1264
+ const currentText = currentChunkSentences.join(" ");
1265
+ const potentialLength = currentText.length + (currentText ? 1 : 0) + sentence.length;
1266
+ if (potentialLength > chunkSize && currentChunkSentences.length > 0) {
1267
+ chunks.push({
1268
+ text: currentText,
1269
+ startOffset: currentChunkStart,
1270
+ endOffset: currentOffset
1271
+ });
1272
+ const overlapSentences = [];
1273
+ let overlapLength = 0;
1274
+ for (let j = currentChunkSentences.length - 1; j >= 0 && overlapLength < chunkOverlap; j--) {
1275
+ overlapSentences.unshift(currentChunkSentences[j]);
1276
+ overlapLength += currentChunkSentences[j].length + 1;
1277
+ }
1278
+ if (overlapSentences.length > 0) {
1279
+ currentChunkSentences = [...overlapSentences, sentence];
1280
+ const overlapText = overlapSentences[0];
1281
+ const overlapStart = text.lastIndexOf(overlapText, currentOffset);
1282
+ currentChunkStart = overlapStart === -1 ? sentenceStart : overlapStart;
1283
+ } else {
1284
+ currentChunkSentences = [sentence];
1285
+ currentChunkStart = sentenceStart;
1286
+ }
1287
+ } else {
1288
+ if (currentChunkSentences.length === 0) {
1289
+ currentChunkStart = sentenceStart;
1290
+ }
1291
+ currentChunkSentences.push(sentence);
1292
+ }
1293
+ currentOffset = sentenceEnd;
1294
+ }
1295
+ if (currentChunkSentences.length > 0) {
1296
+ const chunkText2 = currentChunkSentences.join(" ");
1297
+ if (chunkText2.length >= minChunkSize) {
1298
+ chunks.push({
1299
+ text: chunkText2,
1300
+ startOffset: currentChunkStart,
1301
+ endOffset: text.length
1302
+ });
1303
+ }
1304
+ }
1305
+ if (chunks.length === 0) {
1306
+ const trimmedText = text.trim();
1307
+ if (trimmedText.length > 0) {
1308
+ return [
1309
+ {
1310
+ text: trimmedText,
1311
+ startOffset: 0,
1312
+ endOffset: text.length
1313
+ }
1314
+ ];
1315
+ }
1316
+ }
1317
+ return chunks;
1318
+ }
1319
+ function shouldChunkMessage(content, chunkSize = DEFAULT_CHUNK_SIZE) {
1320
+ return content.length > chunkSize;
1321
+ }
1322
+
1323
+ // src/lib/memoryRetrieval/embeddings.ts
1324
+ init_clientConfig();
1325
+
1326
+ // src/lib/db/chat/operations.ts
1327
+ var import_watermelondb = require("@nozbe/watermelondb");
1328
+ var import_uuid2 = require("uuid");
1329
+
1330
+ // src/lib/db/chat/types.ts
1331
+ var import_uuid = require("uuid");
1332
+
1333
+ // src/lib/memoryRetrieval/constants.ts
1334
+ var DEFAULT_API_EMBEDDING_MODEL = "fireworks/accounts/fireworks/models/qwen3-embedding-8b";
1335
+
1336
+ // src/lib/memoryRetrieval/embeddings.ts
1337
+ async function generateEmbedding(text, options) {
1338
+ const { baseUrl = BASE_URL, getToken, apiKey, model } = options;
1339
+ let headers;
1340
+ if (apiKey) {
1341
+ headers = { "X-API-Key": apiKey };
1342
+ } else if (getToken) {
1343
+ const token = await getToken();
1344
+ if (!token) {
1345
+ throw new Error("No token available for embedding generation");
1346
+ }
1347
+ headers = { Authorization: `Bearer ${token}` };
1348
+ } else {
1349
+ throw new Error("Either apiKey or getToken must be provided");
1350
+ }
1351
+ const response = await postApiV1Embeddings({
1352
+ baseUrl,
1353
+ body: {
1354
+ input: text,
1355
+ model: model ?? DEFAULT_API_EMBEDDING_MODEL
1356
+ },
1357
+ headers
1358
+ });
1359
+ if (response.error) {
1360
+ throw new Error(
1361
+ typeof response.error === "object" && response.error && "error" in response.error ? response.error.error : "API embedding failed"
1362
+ );
1363
+ }
1364
+ if (!response.data?.data?.[0]?.embedding) {
1365
+ throw new Error("No embedding returned from API");
1366
+ }
1367
+ return response.data.data[0].embedding;
1368
+ }
1369
+ async function generateEmbeddings(texts, options) {
1370
+ if (texts.length === 0) return [];
1371
+ const { baseUrl = BASE_URL, getToken, apiKey, model } = options;
1372
+ let headers;
1373
+ if (apiKey) {
1374
+ headers = { "X-API-Key": apiKey };
1375
+ } else if (getToken) {
1376
+ const token = await getToken();
1377
+ if (!token) {
1378
+ throw new Error("No token available for embedding generation");
1379
+ }
1380
+ headers = { Authorization: `Bearer ${token}` };
1381
+ } else {
1382
+ throw new Error("Either apiKey or getToken must be provided");
1383
+ }
1384
+ const response = await postApiV1Embeddings({
1385
+ baseUrl,
1386
+ body: {
1387
+ input: texts,
1388
+ model: model ?? DEFAULT_API_EMBEDDING_MODEL
1389
+ },
1390
+ headers
1391
+ });
1392
+ if (response.error) {
1393
+ throw new Error(
1394
+ typeof response.error === "object" && response.error && "error" in response.error ? response.error.error : "API embedding failed"
1395
+ );
1396
+ }
1397
+ if (!response.data?.data) {
1398
+ throw new Error("No embeddings returned from API");
1399
+ }
1400
+ return response.data.data.map((item) => item.embedding ?? []);
1401
+ }
1402
+
1403
+ // src/lib/tools/serverTools.ts
1404
+ var DEFAULT_CACHE_EXPIRATION_MS = 24 * 60 * 60 * 1e3;
1405
+ var SERVER_TOOLS_CACHE_KEY = "sdk_server_tools_cache";
1406
+ var CACHE_VERSION = "1.3";
1407
+ var MIN_CONTENT_LENGTH_FOR_TOOLS = 5;
1408
+ function isNewToolFormat(tool) {
1409
+ return "schema" in tool && tool.schema !== void 0;
1410
+ }
1411
+ function isNewResponseFormat(response) {
1412
+ return "checksum" in response && "tools" in response && typeof response.checksum === "string";
1413
+ }
1414
+ function convertServerToolsResponse(response) {
1415
+ let toolsMap;
1416
+ let checksum;
1417
+ if (isNewResponseFormat(response)) {
1418
+ toolsMap = response.tools;
1419
+ checksum = response.checksum;
1420
+ } else {
1421
+ toolsMap = response;
1422
+ }
1423
+ const tools = Object.values(toolsMap).map((tool) => {
1424
+ if (isNewToolFormat(tool)) {
1425
+ return {
1426
+ type: "function",
1427
+ name: tool.schema.name,
1428
+ description: tool.schema.description,
1429
+ parameters: tool.schema.parameters,
1430
+ ...tool.embedding && { embedding: tool.embedding }
1431
+ };
1432
+ }
1433
+ return {
1434
+ type: "function",
1435
+ name: tool.name,
1436
+ description: tool.description,
1437
+ parameters: tool.parameters
1438
+ };
1439
+ });
1440
+ return { tools, checksum };
1441
+ }
1442
+ function toCompletionsFormat(tool) {
1443
+ return {
1444
+ type: "function",
1445
+ function: {
1446
+ name: tool.name,
1447
+ description: tool.description,
1448
+ parameters: tool.parameters
1449
+ }
1450
+ };
1451
+ }
1452
+ function toResponsesFormat(tool) {
1453
+ return {
1454
+ type: "function",
1455
+ name: tool.name,
1456
+ description: tool.description,
1457
+ parameters: tool.parameters
1458
+ };
1459
+ }
1460
+ function getCachedServerTools() {
1461
+ if (typeof window === "undefined") return null;
1462
+ try {
1463
+ const cached = localStorage.getItem(SERVER_TOOLS_CACHE_KEY);
1464
+ if (!cached) return null;
1465
+ const parsed = JSON.parse(cached);
1466
+ if (parsed.version !== CACHE_VERSION) {
1467
+ clearServerToolsCache();
1468
+ return null;
1469
+ }
1470
+ return parsed;
1471
+ } catch {
1472
+ return null;
1473
+ }
1474
+ }
1475
+ function isCacheExpired(cache, expirationMs = DEFAULT_CACHE_EXPIRATION_MS) {
1476
+ if (!cache) return true;
1477
+ return Date.now() - cache.timestamp > expirationMs;
1478
+ }
1479
+ function cacheServerTools(tools, checksum) {
1480
+ if (typeof window === "undefined") return;
1481
+ const cacheData = {
1482
+ tools,
1483
+ timestamp: Date.now(),
1484
+ version: CACHE_VERSION,
1485
+ ...checksum && { checksum }
1486
+ };
1487
+ try {
1488
+ localStorage.setItem(SERVER_TOOLS_CACHE_KEY, JSON.stringify(cacheData));
1489
+ } catch (error) {
1490
+ console.warn("[serverTools] Failed to cache tools:", error);
1491
+ }
1492
+ }
1493
+ function clearServerToolsCache() {
1494
+ if (typeof window === "undefined") return;
1495
+ localStorage.removeItem(SERVER_TOOLS_CACHE_KEY);
1496
+ }
1497
+ async function fetchServerToolsFromApi(baseUrl, token) {
1498
+ const response = await fetch(`${baseUrl}/api/v1/tools`, {
1499
+ method: "GET",
1500
+ headers: {
1501
+ Authorization: `Bearer ${token}`,
1502
+ "Content-Type": "application/json"
1503
+ }
1504
+ });
1505
+ if (!response.ok) {
1506
+ throw new Error(`Failed to fetch server tools: ${response.status}`);
1507
+ }
1508
+ const data = await response.json();
1509
+ return convertServerToolsResponse(data);
1510
+ }
1511
+ async function getServerTools(options) {
1512
+ const {
1513
+ baseUrl,
1514
+ cacheExpirationMs = DEFAULT_CACHE_EXPIRATION_MS,
1515
+ forceRefresh = false,
1516
+ getToken,
1517
+ apiKey
1518
+ } = options;
1519
+ const cached = getCachedServerTools();
1520
+ const cacheValid = !isCacheExpired(cached, cacheExpirationMs);
1521
+ if (cached && cacheValid && !forceRefresh) {
1522
+ return cached.tools;
1523
+ }
1524
+ try {
1525
+ const { BASE_URL: BASE_URL2 } = await Promise.resolve().then(() => (init_clientConfig(), clientConfig_exports));
1526
+ const effectiveBaseUrl = baseUrl ?? BASE_URL2;
1527
+ if (apiKey) {
1528
+ const response = await fetch(`${effectiveBaseUrl}/api/v1/tools`, {
1529
+ method: "GET",
1530
+ headers: {
1531
+ "X-API-Key": apiKey,
1532
+ "Content-Type": "application/json"
1533
+ }
1534
+ });
1535
+ if (!response.ok) {
1536
+ throw new Error(`Failed to fetch server tools: ${response.status}`);
1537
+ }
1538
+ const data = await response.json();
1539
+ const { tools: tools2, checksum: checksum2 } = convertServerToolsResponse(data);
1540
+ cacheServerTools(tools2, checksum2);
1541
+ return tools2;
1542
+ }
1543
+ if (!getToken) {
1544
+ console.warn("[serverTools] No auth method available for fetching tools");
1545
+ return cached?.tools ?? [];
1546
+ }
1547
+ const token = await getToken();
1548
+ if (!token) {
1549
+ console.warn("[serverTools] No auth token available for fetching tools");
1550
+ return cached?.tools ?? [];
1551
+ }
1552
+ const { tools, checksum } = await fetchServerToolsFromApi(effectiveBaseUrl, token);
1553
+ cacheServerTools(tools, checksum);
1554
+ return tools;
1555
+ } catch (error) {
1556
+ console.error("[serverTools] Failed to fetch server tools:", error);
1557
+ if (cached?.tools) {
1558
+ console.warn("[serverTools] Using stale cached tools due to fetch error");
1559
+ return cached.tools;
1560
+ }
1561
+ return [];
1562
+ }
1563
+ }
1564
+ function cosineSimilarity(a, b) {
1565
+ if (a.length !== b.length) {
1566
+ throw new Error("Vectors must have the same length");
1567
+ }
1568
+ let dotProduct = 0;
1569
+ let normA = 0;
1570
+ let normB = 0;
1571
+ for (let i = 0; i < a.length; i++) {
1572
+ dotProduct += a[i] * b[i];
1573
+ normA += a[i] * a[i];
1574
+ normB += b[i] * b[i];
1575
+ }
1576
+ const denominator = Math.sqrt(normA) * Math.sqrt(normB);
1577
+ if (denominator === 0) {
1578
+ return 0;
1579
+ }
1580
+ return dotProduct / denominator;
1581
+ }
1582
+ var DEFAULT_TOOL_MATCH_OPTIONS = {
1583
+ limit: 10,
1584
+ minSimilarity: 0.3
1585
+ };
1586
+ function findMatchingTools(promptEmbeddings, tools, options) {
1587
+ const { limit, minSimilarity } = {
1588
+ ...DEFAULT_TOOL_MATCH_OPTIONS,
1589
+ ...options
1590
+ };
1591
+ if (!promptEmbeddings || promptEmbeddings.length === 0) {
1592
+ return [];
1593
+ }
1594
+ if (!tools || tools.length === 0) {
1595
+ return [];
1596
+ }
1597
+ const embeddings = Array.isArray(promptEmbeddings[0]) ? promptEmbeddings : [promptEmbeddings];
1598
+ const results = [];
1599
+ for (const tool of tools) {
1600
+ if (!tool.embedding || tool.embedding.length === 0) {
1601
+ continue;
1602
+ }
1603
+ try {
1604
+ let maxSimilarity = -Infinity;
1605
+ for (const embedding of embeddings) {
1606
+ const similarity = cosineSimilarity(embedding, tool.embedding);
1607
+ if (similarity > maxSimilarity) {
1608
+ maxSimilarity = similarity;
1609
+ }
1610
+ }
1611
+ if (maxSimilarity >= minSimilarity) {
1612
+ results.push({ tool, similarity: maxSimilarity });
1613
+ }
1614
+ } catch {
1615
+ continue;
1616
+ }
1617
+ }
1618
+ return results.sort((a, b) => b.similarity - a.similarity).slice(0, limit);
1619
+ }
1620
+ async function selectServerSideTools(options) {
1621
+ const {
1622
+ prompt,
1623
+ getToken,
1624
+ apiKey,
1625
+ baseUrl,
1626
+ cacheExpirationMs,
1627
+ forceRefresh,
1628
+ embeddingModel,
1629
+ limit,
1630
+ minSimilarity,
1631
+ apiType = "responses"
1632
+ } = options;
1633
+ if (!getToken && !apiKey) {
1634
+ throw new Error("Either getToken or apiKey must be provided");
1635
+ }
1636
+ if (!prompt || prompt.trim().length < MIN_CONTENT_LENGTH_FOR_TOOLS) {
1637
+ return [];
1638
+ }
1639
+ const tools = await getServerTools({
1640
+ getToken,
1641
+ apiKey,
1642
+ baseUrl,
1643
+ cacheExpirationMs,
1644
+ forceRefresh
1645
+ });
1646
+ if (tools.length === 0) {
1647
+ return [];
1648
+ }
1649
+ const embeddingOptions = {
1650
+ getToken,
1651
+ apiKey,
1652
+ baseUrl,
1653
+ model: embeddingModel
1654
+ };
1655
+ let promptEmbeddings;
1656
+ if (shouldChunkMessage(prompt, DEFAULT_CHUNK_SIZE)) {
1657
+ const chunks = chunkText(prompt);
1658
+ promptEmbeddings = await generateEmbeddings(
1659
+ chunks.map((c) => c.text),
1660
+ embeddingOptions
1661
+ );
1662
+ } else {
1663
+ promptEmbeddings = await generateEmbedding(prompt, embeddingOptions);
1664
+ }
1665
+ const matchOptions = {};
1666
+ if (limit !== void 0) matchOptions.limit = limit;
1667
+ if (minSimilarity !== void 0) matchOptions.minSimilarity = minSimilarity;
1668
+ const matches = findMatchingTools(promptEmbeddings, tools, matchOptions);
1669
+ if (matches.length === 0) {
1670
+ return [];
1671
+ }
1672
+ const matchedTools = matches.map((m) => m.tool);
1673
+ if (apiType === "completions") {
1674
+ return matchedTools.map((t) => toCompletionsFormat(t));
1675
+ }
1676
+ return matchedTools.map(toResponsesFormat);
1677
+ }
1678
+ // Annotate the CommonJS export names for ESM import in node:
1679
+ 0 && (module.exports = {
1680
+ deleteApiV1AdminAppsByAppIdApiKeysById,
1681
+ deleteApiV1AdminAppsById,
1682
+ getApiV1AdminApps,
1683
+ getApiV1AdminAppsByAppIdApiKeys,
1684
+ getApiV1AdminAppsByAppIdApiKeysById,
1685
+ getApiV1AdminAppsById,
1686
+ getApiV1Config,
1687
+ getApiV1CreditsBalance,
1688
+ getApiV1CreditsPacks,
1689
+ getApiV1DocsSwaggerJson,
1690
+ getApiV1Models,
1691
+ getApiV1SubscriptionsPlans,
1692
+ getApiV1SubscriptionsStatus,
1693
+ getApiV1Tasks,
1694
+ getApiV1Tools,
1695
+ getHealth,
1696
+ postApiV1AdminAddCredits,
1697
+ postApiV1AdminApps,
1698
+ postApiV1AdminAppsByAppIdApiKeys,
1699
+ postApiV1AdminSeedApps,
1700
+ postApiV1AdminSubscriptionTier,
1701
+ postApiV1ChatCompletions,
1702
+ postApiV1CreditsClaimDaily,
1703
+ postApiV1CreditsPurchase,
1704
+ postApiV1CreditsSyncSnag,
1705
+ postApiV1Embeddings,
1706
+ postApiV1Responses,
1707
+ postApiV1SubscriptionsCancel,
1708
+ postApiV1SubscriptionsCreateCheckoutSession,
1709
+ postApiV1SubscriptionsCustomerPortal,
1710
+ postApiV1SubscriptionsRenew,
1711
+ postApiV1SubscriptionsWebhook,
1712
+ postAuthOauthByProviderExchange,
1713
+ postAuthOauthByProviderRefresh,
1714
+ postAuthOauthByProviderRevoke,
1715
+ putApiV1AdminAppsByAppIdApiKeysById,
1716
+ putApiV1AdminAppsById,
1717
+ selectServerSideTools
1718
+ });