@anuma/sdk 2.7.0 → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -43,956 +43,6 @@ var __decorateClass = (decorators, target, key, kind) => {
43
43
  return result;
44
44
  };
45
45
 
46
- // src/client/core/bodySerializer.gen.ts
47
- var jsonBodySerializer;
48
- var init_bodySerializer_gen = __esm({
49
- "src/client/core/bodySerializer.gen.ts"() {
50
- "use strict";
51
- jsonBodySerializer = {
52
- bodySerializer: (body) => JSON.stringify(
53
- body,
54
- (_key, value) => typeof value === "bigint" ? value.toString() : value
55
- )
56
- };
57
- }
58
- });
59
-
60
- // src/client/core/serverSentEvents.gen.ts
61
- var createSseClient;
62
- var init_serverSentEvents_gen = __esm({
63
- "src/client/core/serverSentEvents.gen.ts"() {
64
- "use strict";
65
- createSseClient = ({
66
- onRequest,
67
- onSseError,
68
- onSseEvent,
69
- responseTransformer,
70
- responseValidator,
71
- sseDefaultRetryDelay,
72
- sseMaxRetryAttempts,
73
- sseMaxRetryDelay,
74
- sseSleepFn,
75
- url,
76
- ...options
77
- }) => {
78
- let lastEventId;
79
- const sleep4 = sseSleepFn ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
80
- const createStream = async function* () {
81
- let retryDelay = sseDefaultRetryDelay ?? 3e3;
82
- let attempt = 0;
83
- const signal = options.signal ?? new AbortController().signal;
84
- while (true) {
85
- if (signal.aborted) break;
86
- attempt++;
87
- const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers);
88
- if (lastEventId !== void 0) {
89
- headers.set("Last-Event-ID", lastEventId);
90
- }
91
- try {
92
- const requestInit = {
93
- redirect: "follow",
94
- ...options,
95
- body: options.serializedBody,
96
- headers,
97
- signal
98
- };
99
- let request = new Request(url, requestInit);
100
- if (onRequest) {
101
- request = await onRequest(url, requestInit);
102
- }
103
- const _fetch = options.fetch ?? globalThis.fetch;
104
- const response = await _fetch(request);
105
- if (!response.ok)
106
- throw new Error(
107
- `SSE failed: ${response.status} ${response.statusText}`
108
- );
109
- if (!response.body) throw new Error("No body in SSE response");
110
- const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
111
- let buffer = "";
112
- const abortHandler = () => {
113
- try {
114
- reader.cancel();
115
- } catch {
116
- }
117
- };
118
- signal.addEventListener("abort", abortHandler);
119
- try {
120
- while (true) {
121
- const { done, value } = await reader.read();
122
- if (done) break;
123
- buffer += value;
124
- const chunks = buffer.split("\n\n");
125
- buffer = chunks.pop() ?? "";
126
- for (const chunk of chunks) {
127
- const lines = chunk.split("\n");
128
- const dataLines = [];
129
- let eventName;
130
- for (const line of lines) {
131
- if (line.startsWith("data:")) {
132
- dataLines.push(line.replace(/^data:\s*/, ""));
133
- } else if (line.startsWith("event:")) {
134
- eventName = line.replace(/^event:\s*/, "");
135
- } else if (line.startsWith("id:")) {
136
- lastEventId = line.replace(/^id:\s*/, "");
137
- } else if (line.startsWith("retry:")) {
138
- const parsed = Number.parseInt(
139
- line.replace(/^retry:\s*/, ""),
140
- 10
141
- );
142
- if (!Number.isNaN(parsed)) {
143
- retryDelay = parsed;
144
- }
145
- }
146
- }
147
- let data;
148
- let parsedJson = false;
149
- if (dataLines.length) {
150
- const rawData = dataLines.join("\n");
151
- try {
152
- data = JSON.parse(rawData);
153
- parsedJson = true;
154
- } catch {
155
- data = rawData;
156
- }
157
- }
158
- if (parsedJson) {
159
- if (responseValidator) {
160
- await responseValidator(data);
161
- }
162
- if (responseTransformer) {
163
- data = await responseTransformer(data);
164
- }
165
- }
166
- onSseEvent?.({
167
- data,
168
- event: eventName,
169
- id: lastEventId,
170
- retry: retryDelay
171
- });
172
- if (dataLines.length) {
173
- yield data;
174
- }
175
- }
176
- }
177
- } finally {
178
- signal.removeEventListener("abort", abortHandler);
179
- reader.releaseLock();
180
- }
181
- break;
182
- } catch (error) {
183
- onSseError?.(error);
184
- if (sseMaxRetryAttempts !== void 0 && attempt >= sseMaxRetryAttempts) {
185
- break;
186
- }
187
- const backoff = Math.min(
188
- retryDelay * 2 ** (attempt - 1),
189
- sseMaxRetryDelay ?? 3e4
190
- );
191
- await sleep4(backoff);
192
- }
193
- }
194
- };
195
- const stream = createStream();
196
- return { stream };
197
- };
198
- }
199
- });
200
-
201
- // src/client/core/pathSerializer.gen.ts
202
- var separatorArrayExplode, separatorArrayNoExplode, separatorObjectExplode, serializeArrayParam, serializePrimitiveParam, serializeObjectParam;
203
- var init_pathSerializer_gen = __esm({
204
- "src/client/core/pathSerializer.gen.ts"() {
205
- "use strict";
206
- separatorArrayExplode = (style) => {
207
- switch (style) {
208
- case "label":
209
- return ".";
210
- case "matrix":
211
- return ";";
212
- case "simple":
213
- return ",";
214
- default:
215
- return "&";
216
- }
217
- };
218
- separatorArrayNoExplode = (style) => {
219
- switch (style) {
220
- case "form":
221
- return ",";
222
- case "pipeDelimited":
223
- return "|";
224
- case "spaceDelimited":
225
- return "%20";
226
- default:
227
- return ",";
228
- }
229
- };
230
- separatorObjectExplode = (style) => {
231
- switch (style) {
232
- case "label":
233
- return ".";
234
- case "matrix":
235
- return ";";
236
- case "simple":
237
- return ",";
238
- default:
239
- return "&";
240
- }
241
- };
242
- serializeArrayParam = ({
243
- allowReserved,
244
- explode,
245
- name,
246
- style,
247
- value
248
- }) => {
249
- if (!explode) {
250
- const joinedValues2 = (allowReserved ? value : value.map((v) => encodeURIComponent(v))).join(separatorArrayNoExplode(style));
251
- switch (style) {
252
- case "label":
253
- return `.${joinedValues2}`;
254
- case "matrix":
255
- return `;${name}=${joinedValues2}`;
256
- case "simple":
257
- return joinedValues2;
258
- default:
259
- return `${name}=${joinedValues2}`;
260
- }
261
- }
262
- const separator = separatorArrayExplode(style);
263
- const joinedValues = value.map((v) => {
264
- if (style === "label" || style === "simple") {
265
- return allowReserved ? v : encodeURIComponent(v);
266
- }
267
- return serializePrimitiveParam({
268
- allowReserved,
269
- name,
270
- value: v
271
- });
272
- }).join(separator);
273
- return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues;
274
- };
275
- serializePrimitiveParam = ({
276
- allowReserved,
277
- name,
278
- value
279
- }) => {
280
- if (value === void 0 || value === null) {
281
- return "";
282
- }
283
- if (typeof value === "object") {
284
- throw new Error(
285
- "Deeply-nested arrays/objects aren\u2019t supported. Provide your own `querySerializer()` to handle these."
286
- );
287
- }
288
- return `${name}=${allowReserved ? value : encodeURIComponent(value)}`;
289
- };
290
- serializeObjectParam = ({
291
- allowReserved,
292
- explode,
293
- name,
294
- style,
295
- value,
296
- valueOnly
297
- }) => {
298
- if (value instanceof Date) {
299
- return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`;
300
- }
301
- if (style !== "deepObject" && !explode) {
302
- let values = [];
303
- Object.entries(value).forEach(([key, v]) => {
304
- values = [
305
- ...values,
306
- key,
307
- allowReserved ? v : encodeURIComponent(v)
308
- ];
309
- });
310
- const joinedValues2 = values.join(",");
311
- switch (style) {
312
- case "form":
313
- return `${name}=${joinedValues2}`;
314
- case "label":
315
- return `.${joinedValues2}`;
316
- case "matrix":
317
- return `;${name}=${joinedValues2}`;
318
- default:
319
- return joinedValues2;
320
- }
321
- }
322
- const separator = separatorObjectExplode(style);
323
- const joinedValues = Object.entries(value).map(
324
- ([key, v]) => serializePrimitiveParam({
325
- allowReserved,
326
- name: style === "deepObject" ? `${name}[${key}]` : key,
327
- value: v
328
- })
329
- ).join(separator);
330
- return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues;
331
- };
332
- }
333
- });
334
-
335
- // src/client/core/utils.gen.ts
336
- function getValidRequestBody(options) {
337
- const hasBody = options.body !== void 0;
338
- const isSerializedBody = hasBody && options.bodySerializer;
339
- if (isSerializedBody) {
340
- if ("serializedBody" in options) {
341
- const hasSerializedBody = options.serializedBody !== void 0 && options.serializedBody !== "";
342
- return hasSerializedBody ? options.serializedBody : null;
343
- }
344
- return options.body !== "" ? options.body : null;
345
- }
346
- if (hasBody) {
347
- return options.body;
348
- }
349
- return void 0;
350
- }
351
- var init_utils_gen = __esm({
352
- "src/client/core/utils.gen.ts"() {
353
- "use strict";
354
- }
355
- });
356
-
357
- // src/client/core/auth.gen.ts
358
- var getAuthToken;
359
- var init_auth_gen = __esm({
360
- "src/client/core/auth.gen.ts"() {
361
- "use strict";
362
- getAuthToken = async (auth, callback) => {
363
- const token = typeof callback === "function" ? await callback(auth) : callback;
364
- if (!token) {
365
- return;
366
- }
367
- if (auth.scheme === "bearer") {
368
- return `Bearer ${token}`;
369
- }
370
- if (auth.scheme === "basic") {
371
- return `Basic ${btoa(token)}`;
372
- }
373
- return token;
374
- };
375
- }
376
- });
377
-
378
- // src/client/client/utils.gen.ts
379
- var PATH_PARAM_RE, defaultPathSerializer, createQuerySerializer, getParseAs, checkForExistence, setAuthParams, buildUrl, getUrl, mergeConfigs, headersEntries, mergeHeaders, Interceptors, createInterceptors, defaultQuerySerializer, defaultHeaders, createConfig;
380
- var init_utils_gen2 = __esm({
381
- "src/client/client/utils.gen.ts"() {
382
- "use strict";
383
- init_auth_gen();
384
- init_bodySerializer_gen();
385
- init_pathSerializer_gen();
386
- PATH_PARAM_RE = /\{[^{}]+\}/g;
387
- defaultPathSerializer = ({ path, url: _url }) => {
388
- let url = _url;
389
- const matches = _url.match(PATH_PARAM_RE);
390
- if (matches) {
391
- for (const match of matches) {
392
- let explode = false;
393
- let name = match.substring(1, match.length - 1);
394
- let style = "simple";
395
- if (name.endsWith("*")) {
396
- explode = true;
397
- name = name.substring(0, name.length - 1);
398
- }
399
- if (name.startsWith(".")) {
400
- name = name.substring(1);
401
- style = "label";
402
- } else if (name.startsWith(";")) {
403
- name = name.substring(1);
404
- style = "matrix";
405
- }
406
- const value = path[name];
407
- if (value === void 0 || value === null) {
408
- continue;
409
- }
410
- if (Array.isArray(value)) {
411
- url = url.replace(
412
- match,
413
- serializeArrayParam({ explode, name, style, value })
414
- );
415
- continue;
416
- }
417
- if (typeof value === "object") {
418
- url = url.replace(
419
- match,
420
- serializeObjectParam({
421
- explode,
422
- name,
423
- style,
424
- value,
425
- valueOnly: true
426
- })
427
- );
428
- continue;
429
- }
430
- if (style === "matrix") {
431
- url = url.replace(
432
- match,
433
- `;${serializePrimitiveParam({
434
- name,
435
- value
436
- })}`
437
- );
438
- continue;
439
- }
440
- const replaceValue = encodeURIComponent(
441
- style === "label" ? `.${value}` : value
442
- );
443
- url = url.replace(match, replaceValue);
444
- }
445
- }
446
- return url;
447
- };
448
- createQuerySerializer = ({
449
- parameters = {},
450
- ...args
451
- } = {}) => {
452
- const querySerializer = (queryParams) => {
453
- const search = [];
454
- if (queryParams && typeof queryParams === "object") {
455
- for (const name in queryParams) {
456
- const value = queryParams[name];
457
- if (value === void 0 || value === null) {
458
- continue;
459
- }
460
- const options = parameters[name] || args;
461
- if (Array.isArray(value)) {
462
- const serializedArray = serializeArrayParam({
463
- allowReserved: options.allowReserved,
464
- explode: true,
465
- name,
466
- style: "form",
467
- value,
468
- ...options.array
469
- });
470
- if (serializedArray) search.push(serializedArray);
471
- } else if (typeof value === "object") {
472
- const serializedObject = serializeObjectParam({
473
- allowReserved: options.allowReserved,
474
- explode: true,
475
- name,
476
- style: "deepObject",
477
- value,
478
- ...options.object
479
- });
480
- if (serializedObject) search.push(serializedObject);
481
- } else {
482
- const serializedPrimitive = serializePrimitiveParam({
483
- allowReserved: options.allowReserved,
484
- name,
485
- value
486
- });
487
- if (serializedPrimitive) search.push(serializedPrimitive);
488
- }
489
- }
490
- }
491
- return search.join("&");
492
- };
493
- return querySerializer;
494
- };
495
- getParseAs = (contentType) => {
496
- if (!contentType) {
497
- return "stream";
498
- }
499
- const cleanContent = contentType.split(";")[0]?.trim();
500
- if (!cleanContent) {
501
- return;
502
- }
503
- if (cleanContent.startsWith("application/json") || cleanContent.endsWith("+json")) {
504
- return "json";
505
- }
506
- if (cleanContent === "multipart/form-data") {
507
- return "formData";
508
- }
509
- if (["application/", "audio/", "image/", "video/"].some(
510
- (type) => cleanContent.startsWith(type)
511
- )) {
512
- return "blob";
513
- }
514
- if (cleanContent.startsWith("text/")) {
515
- return "text";
516
- }
517
- return;
518
- };
519
- checkForExistence = (options, name) => {
520
- if (!name) {
521
- return false;
522
- }
523
- if (options.headers.has(name) || options.query?.[name] || options.headers.get("Cookie")?.includes(`${name}=`)) {
524
- return true;
525
- }
526
- return false;
527
- };
528
- setAuthParams = async ({
529
- security,
530
- ...options
531
- }) => {
532
- for (const auth of security) {
533
- if (checkForExistence(options, auth.name)) {
534
- continue;
535
- }
536
- const token = await getAuthToken(auth, options.auth);
537
- if (!token) {
538
- continue;
539
- }
540
- const name = auth.name ?? "Authorization";
541
- switch (auth.in) {
542
- case "query":
543
- if (!options.query) {
544
- options.query = {};
545
- }
546
- options.query[name] = token;
547
- break;
548
- case "cookie":
549
- options.headers.append("Cookie", `${name}=${token}`);
550
- break;
551
- case "header":
552
- default:
553
- options.headers.set(name, token);
554
- break;
555
- }
556
- }
557
- };
558
- buildUrl = (options) => {
559
- const url = getUrl({
560
- baseUrl: options.baseUrl,
561
- path: options.path,
562
- query: options.query,
563
- querySerializer: typeof options.querySerializer === "function" ? options.querySerializer : createQuerySerializer(options.querySerializer),
564
- url: options.url
565
- });
566
- return url;
567
- };
568
- getUrl = ({
569
- baseUrl,
570
- path,
571
- query,
572
- querySerializer,
573
- url: _url
574
- }) => {
575
- const pathUrl = _url.startsWith("/") ? _url : `/${_url}`;
576
- let url = (baseUrl ?? "") + pathUrl;
577
- if (path) {
578
- url = defaultPathSerializer({ path, url });
579
- }
580
- let search = query ? querySerializer(query) : "";
581
- if (search.startsWith("?")) {
582
- search = search.substring(1);
583
- }
584
- if (search) {
585
- url += `?${search}`;
586
- }
587
- return url;
588
- };
589
- mergeConfigs = (a, b) => {
590
- const config = { ...a, ...b };
591
- if (config.baseUrl?.endsWith("/")) {
592
- config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1);
593
- }
594
- config.headers = mergeHeaders(a.headers, b.headers);
595
- return config;
596
- };
597
- headersEntries = (headers) => {
598
- const entries = [];
599
- headers.forEach((value, key) => {
600
- entries.push([key, value]);
601
- });
602
- return entries;
603
- };
604
- mergeHeaders = (...headers) => {
605
- const mergedHeaders = new Headers();
606
- for (const header of headers) {
607
- if (!header || typeof header !== "object") {
608
- continue;
609
- }
610
- const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header);
611
- for (const [key, value] of iterator) {
612
- if (value === null) {
613
- mergedHeaders.delete(key);
614
- } else if (Array.isArray(value)) {
615
- for (const v of value) {
616
- mergedHeaders.append(key, v);
617
- }
618
- } else if (value !== void 0) {
619
- mergedHeaders.set(
620
- key,
621
- typeof value === "object" ? JSON.stringify(value) : value
622
- );
623
- }
624
- }
625
- }
626
- return mergedHeaders;
627
- };
628
- Interceptors = class {
629
- constructor() {
630
- this.fns = [];
631
- }
632
- clear() {
633
- this.fns = [];
634
- }
635
- eject(id) {
636
- const index = this.getInterceptorIndex(id);
637
- if (this.fns[index]) {
638
- this.fns[index] = null;
639
- }
640
- }
641
- exists(id) {
642
- const index = this.getInterceptorIndex(id);
643
- return Boolean(this.fns[index]);
644
- }
645
- getInterceptorIndex(id) {
646
- if (typeof id === "number") {
647
- return this.fns[id] ? id : -1;
648
- }
649
- return this.fns.indexOf(id);
650
- }
651
- update(id, fn) {
652
- const index = this.getInterceptorIndex(id);
653
- if (this.fns[index]) {
654
- this.fns[index] = fn;
655
- return id;
656
- }
657
- return false;
658
- }
659
- use(fn) {
660
- this.fns.push(fn);
661
- return this.fns.length - 1;
662
- }
663
- };
664
- createInterceptors = () => ({
665
- error: new Interceptors(),
666
- request: new Interceptors(),
667
- response: new Interceptors()
668
- });
669
- defaultQuerySerializer = createQuerySerializer({
670
- allowReserved: false,
671
- array: {
672
- explode: true,
673
- style: "form"
674
- },
675
- object: {
676
- explode: true,
677
- style: "deepObject"
678
- }
679
- });
680
- defaultHeaders = {
681
- "Content-Type": "application/json"
682
- };
683
- createConfig = (override = {}) => ({
684
- ...jsonBodySerializer,
685
- headers: defaultHeaders,
686
- parseAs: "auto",
687
- querySerializer: defaultQuerySerializer,
688
- ...override
689
- });
690
- }
691
- });
692
-
693
- // src/client/client/client.gen.ts
694
- var createClient;
695
- var init_client_gen = __esm({
696
- "src/client/client/client.gen.ts"() {
697
- "use strict";
698
- init_serverSentEvents_gen();
699
- init_utils_gen();
700
- init_utils_gen2();
701
- createClient = (config = {}) => {
702
- let _config = mergeConfigs(createConfig(), config);
703
- const getConfig = () => ({ ..._config });
704
- const setConfig = (config2) => {
705
- _config = mergeConfigs(_config, config2);
706
- return getConfig();
707
- };
708
- const interceptors = createInterceptors();
709
- const beforeRequest = async (options) => {
710
- const opts = {
711
- ..._config,
712
- ...options,
713
- fetch: options.fetch ?? _config.fetch ?? globalThis.fetch,
714
- headers: mergeHeaders(_config.headers, options.headers),
715
- serializedBody: void 0
716
- };
717
- if (opts.security) {
718
- await setAuthParams({
719
- ...opts,
720
- security: opts.security
721
- });
722
- }
723
- if (opts.requestValidator) {
724
- await opts.requestValidator(opts);
725
- }
726
- if (opts.body !== void 0 && opts.bodySerializer) {
727
- opts.serializedBody = opts.bodySerializer(opts.body);
728
- }
729
- if (opts.body === void 0 || opts.serializedBody === "") {
730
- opts.headers.delete("Content-Type");
731
- }
732
- const url = buildUrl(opts);
733
- return { opts, url };
734
- };
735
- const request = async (options) => {
736
- const { opts, url } = await beforeRequest(options);
737
- for (const fn of interceptors.request.fns) {
738
- if (fn) {
739
- await fn(opts);
740
- }
741
- }
742
- const _fetch = opts.fetch;
743
- const requestInit = {
744
- ...opts,
745
- body: getValidRequestBody(opts)
746
- };
747
- let response = await _fetch(url, requestInit);
748
- for (const fn of interceptors.response.fns) {
749
- if (fn) {
750
- response = await fn(response, opts);
751
- }
752
- }
753
- const result = {
754
- response
755
- };
756
- if (response.ok) {
757
- const parseAs = (opts.parseAs === "auto" ? getParseAs(response.headers.get("Content-Type")) : opts.parseAs) ?? "json";
758
- if (response.status === 204 || response.headers.get("Content-Length") === "0") {
759
- let emptyData;
760
- switch (parseAs) {
761
- case "arrayBuffer":
762
- case "blob":
763
- case "text":
764
- emptyData = await response[parseAs]();
765
- break;
766
- case "formData":
767
- emptyData = new FormData();
768
- break;
769
- case "stream":
770
- emptyData = response.body;
771
- break;
772
- case "json":
773
- default:
774
- emptyData = {};
775
- break;
776
- }
777
- return {
778
- data: emptyData,
779
- ...result
780
- };
781
- }
782
- let data;
783
- switch (parseAs) {
784
- case "arrayBuffer":
785
- case "blob":
786
- case "formData":
787
- case "json":
788
- case "text":
789
- data = await response[parseAs]();
790
- break;
791
- case "stream":
792
- return {
793
- data: response.body,
794
- ...result
795
- };
796
- }
797
- if (parseAs === "json") {
798
- if (opts.responseValidator) {
799
- await opts.responseValidator(data);
800
- }
801
- if (opts.responseTransformer) {
802
- data = await opts.responseTransformer(data);
803
- }
804
- }
805
- return {
806
- data,
807
- ...result
808
- };
809
- }
810
- const textError = await response.text();
811
- let jsonError;
812
- try {
813
- jsonError = JSON.parse(textError);
814
- } catch {
815
- }
816
- const error = jsonError ?? textError;
817
- let finalError = error;
818
- for (const fn of interceptors.error.fns) {
819
- if (fn) {
820
- finalError = await fn(error, response, opts);
821
- }
822
- }
823
- finalError = finalError || {};
824
- if (opts.throwOnError) {
825
- throw finalError;
826
- }
827
- return {
828
- error: finalError,
829
- ...result
830
- };
831
- };
832
- const makeMethodFn = (method) => (options) => request({ ...options, method });
833
- const makeSseFn = (method) => async (options) => {
834
- const { opts, url } = await beforeRequest(options);
835
- return createSseClient({
836
- ...opts,
837
- body: opts.body,
838
- headers: opts.headers,
839
- method,
840
- onRequest: async (url2, init) => {
841
- let request2 = new Request(url2, init);
842
- const requestInit = {
843
- ...init,
844
- method: init.method,
845
- url: url2
846
- };
847
- for (const fn of interceptors.request.fns) {
848
- if (fn) {
849
- await fn(requestInit);
850
- request2 = new Request(requestInit.url, requestInit);
851
- }
852
- }
853
- return request2;
854
- },
855
- url
856
- });
857
- };
858
- return {
859
- buildUrl,
860
- connect: makeMethodFn("CONNECT"),
861
- delete: makeMethodFn("DELETE"),
862
- get: makeMethodFn("GET"),
863
- getConfig,
864
- head: makeMethodFn("HEAD"),
865
- interceptors,
866
- options: makeMethodFn("OPTIONS"),
867
- patch: makeMethodFn("PATCH"),
868
- post: makeMethodFn("POST"),
869
- put: makeMethodFn("PUT"),
870
- request,
871
- setConfig,
872
- sse: {
873
- connect: makeSseFn("CONNECT"),
874
- delete: makeSseFn("DELETE"),
875
- get: makeSseFn("GET"),
876
- head: makeSseFn("HEAD"),
877
- options: makeSseFn("OPTIONS"),
878
- patch: makeSseFn("PATCH"),
879
- post: makeSseFn("POST"),
880
- put: makeSseFn("PUT"),
881
- trace: makeSseFn("TRACE")
882
- },
883
- trace: makeMethodFn("TRACE")
884
- };
885
- };
886
- }
887
- });
888
-
889
- // src/client/client/index.ts
890
- var init_client = __esm({
891
- "src/client/client/index.ts"() {
892
- "use strict";
893
- init_client_gen();
894
- init_utils_gen2();
895
- }
896
- });
897
-
898
- // src/clientConfig.ts
899
- var clientConfig_exports = {};
900
- __export(clientConfig_exports, {
901
- BASE_URL: () => BASE_URL,
902
- MCP_R2_DOMAIN: () => MCP_R2_DOMAIN,
903
- createClientConfig: () => createClientConfig,
904
- resolveBaseUrl: () => resolveBaseUrl
905
- });
906
- function readGlobal(key) {
907
- if (typeof globalThis === "undefined") return void 0;
908
- const value = globalThis[key];
909
- return typeof value === "string" && value.length > 0 ? value : void 0;
910
- }
911
- function resolveBaseUrl() {
912
- const fromProcess = typeof process !== "undefined" ? process.env.API_URL || process.env.NEXT_PUBLIC_API_URL || process.env.EXPO_PUBLIC_API_URL : void 0;
913
- const fromGlobal = readGlobal("API_URL") ?? readGlobal("NEXT_PUBLIC_API_URL") ?? readGlobal("EXPO_PUBLIC_API_URL");
914
- return (fromProcess || fromGlobal || DEFAULT_BASE_URL).replace(/\/+$/, "");
915
- }
916
- var DEFAULT_BASE_URL, BASE_URL, MCP_R2_DOMAIN, createClientConfig;
917
- var init_clientConfig = __esm({
918
- "src/clientConfig.ts"() {
919
- "use strict";
920
- DEFAULT_BASE_URL = "https://portal.anuma-dev.ai";
921
- BASE_URL = resolveBaseUrl();
922
- MCP_R2_DOMAIN = "4cf0e0ea50b97e72386fcf2f92a2d4e8.r2.cloudflarestorage.com";
923
- createClientConfig = (config) => ({
924
- ...config,
925
- baseUrl: BASE_URL
926
- });
927
- }
928
- });
929
-
930
- // src/client/client.gen.ts
931
- var client;
932
- var init_client_gen2 = __esm({
933
- "src/client/client.gen.ts"() {
934
- "use strict";
935
- init_client();
936
- init_clientConfig();
937
- client = createClient(createClientConfig(createConfig()));
938
- }
939
- });
940
-
941
- // src/client/sdk.gen.ts
942
- var getApiV1CreditsBalance, getApiV1CreditsPacks, postApiV1CreditsPurchase, postApiV1Embeddings, getApiV1Models;
943
- var init_sdk_gen = __esm({
944
- "src/client/sdk.gen.ts"() {
945
- "use strict";
946
- init_client_gen2();
947
- getApiV1CreditsBalance = (options) => {
948
- return (options?.client ?? client).get({
949
- url: "/api/v1/credits/balance",
950
- ...options
951
- });
952
- };
953
- getApiV1CreditsPacks = (options) => {
954
- return (options?.client ?? client).get({
955
- url: "/api/v1/credits/packs",
956
- ...options
957
- });
958
- };
959
- postApiV1CreditsPurchase = (options) => {
960
- return (options.client ?? client).post({
961
- url: "/api/v1/credits/purchase",
962
- ...options,
963
- headers: {
964
- "Content-Type": "application/json",
965
- ...options.headers
966
- }
967
- });
968
- };
969
- postApiV1Embeddings = (options) => {
970
- return (options.client ?? client).post({
971
- url: "/api/v1/embeddings",
972
- ...options,
973
- headers: {
974
- "Content-Type": "application/json",
975
- ...options.headers
976
- }
977
- });
978
- };
979
- getApiV1Models = (options) => {
980
- return (options?.client ?? client).get({
981
- url: "/api/v1/models",
982
- ...options
983
- });
984
- };
985
- }
986
- });
987
-
988
- // src/client/index.ts
989
- var init_client2 = __esm({
990
- "src/client/index.ts"() {
991
- "use strict";
992
- init_sdk_gen();
993
- }
994
- });
995
-
996
46
  // src/lib/logger.ts
997
47
  function setLogger(logger) {
998
48
  currentLogger = logger;
@@ -1894,6 +944,12 @@ function getToolCallEvents(r) {
1894
944
  }
1895
945
  return r.tool_call_events;
1896
946
  }
947
+ function getToolsChecksum(r) {
948
+ if (isChatCompletionResponse(r)) {
949
+ return r.portal?.tools_checksum ?? r.tools_checksum;
950
+ }
951
+ return r.tools_checksum;
952
+ }
1897
953
  function getCostMicroUsd(r) {
1898
954
  if (isChatCompletionResponse(r)) {
1899
955
  return r.portal?.cost_micro_usd ?? r.usage?.cost_micro_usd;
@@ -2101,6 +1157,67 @@ async function messageToStored(message, walletAddress, signMessage, embeddedWall
2101
1157
  }
2102
1158
  return baseMessage;
2103
1159
  }
1160
+ function rawDate(value) {
1161
+ return new Date(typeof value === "number" ? value : 0);
1162
+ }
1163
+ function messageRawToStoredRaw(raw, projection) {
1164
+ const parseJsonField = (rawValue) => {
1165
+ if (!rawValue) return void 0;
1166
+ if (typeof rawValue === "string") {
1167
+ if (rawValue.startsWith("enc:")) return rawValue;
1168
+ try {
1169
+ return JSON.parse(rawValue);
1170
+ } catch {
1171
+ return void 0;
1172
+ }
1173
+ }
1174
+ return rawValue;
1175
+ };
1176
+ const skipEmbeddings = projection?.skipEmbeddings === true;
1177
+ const vectorRaw = skipEmbeddings ? null : raw.vector;
1178
+ const chunksRaw = skipEmbeddings ? null : raw.chunks;
1179
+ return {
1180
+ uniqueId: raw.id,
1181
+ messageId: raw.message_id,
1182
+ conversationId: raw.conversation_id ?? "",
1183
+ role: raw.role ?? "",
1184
+ content: raw.content ?? "",
1185
+ model: raw.model,
1186
+ imageModel: raw.image_model,
1187
+ files: parseJsonField(raw.files),
1188
+ fileIds: parseJsonField(raw.file_ids),
1189
+ createdAt: rawDate(raw.created_at),
1190
+ updatedAt: rawDate(raw.updated_at),
1191
+ vector: skipEmbeddings ? void 0 : parseJsonField(vectorRaw),
1192
+ embeddingModel: raw.embedding_model,
1193
+ chunks: skipEmbeddings ? void 0 : parseJsonField(chunksRaw),
1194
+ usage: parseJsonField(raw.usage),
1195
+ sources: parseJsonField(raw.sources),
1196
+ responseDuration: raw.response_duration,
1197
+ // `was_stopped` is an OPTIONAL boolean: an unset row sanitizes to null, and the Model path
1198
+ // (message.wasStopped) returns that null verbatim. Preserve it (don't collapse to false) so the
1199
+ // raw path is byte-identical. When set, coerce SQLite 0/1 and LokiJS true/false alike.
1200
+ wasStopped: raw.was_stopped === null || raw.was_stopped === void 0 ? raw.was_stopped : raw.was_stopped === true || raw.was_stopped === 1,
1201
+ error: raw.error,
1202
+ thoughtProcess: parseJsonField(raw.thought_process),
1203
+ thinking: raw.thinking,
1204
+ parentMessageId: raw.parent_message_id,
1205
+ feedback: raw.feedback || null,
1206
+ toolCallEvents: parseJsonField(raw.tool_call_events)
1207
+ };
1208
+ }
1209
+ async function messageRawToStored(raw, walletAddress, signMessage, embeddedWalletSigner, projection) {
1210
+ const baseMessage = messageRawToStoredRaw(raw, projection);
1211
+ if (walletAddress) {
1212
+ return await decryptMessageFields(
1213
+ baseMessage,
1214
+ walletAddress,
1215
+ signMessage,
1216
+ embeddedWalletSigner
1217
+ );
1218
+ }
1219
+ return baseMessage;
1220
+ }
2104
1221
  function conversationToStoredRaw(conversation) {
2105
1222
  return {
2106
1223
  uniqueId: conversation.id,
@@ -2125,6 +1242,33 @@ async function conversationToStored(conversation, walletAddress, signMessage, em
2125
1242
  }
2126
1243
  return baseConversation;
2127
1244
  }
1245
+ function conversationRawToStoredRaw(raw) {
1246
+ const pinnedAt = raw.pinned_at;
1247
+ return {
1248
+ uniqueId: raw.id,
1249
+ conversationId: raw.conversation_id ?? "",
1250
+ title: raw.title ?? "",
1251
+ projectId: raw.project_id,
1252
+ createdAt: rawDate(raw.created_at),
1253
+ updatedAt: rawDate(raw.updated_at),
1254
+ // SQLite stores booleans as 0/1, LokiJS as true/false — coerce both.
1255
+ isDeleted: raw.is_deleted === true || raw.is_deleted === 1,
1256
+ // @date maps a non-number raw column (incl. an explicit unpin null) to null; a number → Date.
1257
+ pinnedAt: typeof pinnedAt === "number" ? new Date(pinnedAt) : null
1258
+ };
1259
+ }
1260
+ async function conversationRawToStored(raw, walletAddress, signMessage, embeddedWalletSigner) {
1261
+ const baseConversation = conversationRawToStoredRaw(raw);
1262
+ if (walletAddress) {
1263
+ return await decryptConversationFields(
1264
+ baseConversation,
1265
+ walletAddress,
1266
+ signMessage,
1267
+ embeddedWalletSigner
1268
+ );
1269
+ }
1270
+ return baseConversation;
1271
+ }
2128
1272
  async function createConversationOp(ctx, opts, defaultTitle = "New Conversation") {
2129
1273
  const convId = opts?.conversationId || generateConversationId();
2130
1274
  const title = opts?.title || defaultTitle;
@@ -2164,36 +1308,51 @@ async function getConversationOp(ctx, id) {
2164
1308
  ) : null;
2165
1309
  }
2166
1310
  async function getConversationsOp(ctx) {
2167
- const results = await ctx.conversationsCollection.query(import_watermelondb.Q.where("is_deleted", false), import_watermelondb.Q.sortBy("created_at", import_watermelondb.Q.desc)).fetch();
1311
+ const results = await ctx.conversationsCollection.query(import_watermelondb.Q.where("is_deleted", false), import_watermelondb.Q.sortBy("created_at", import_watermelondb.Q.desc)).unsafeFetchRaw();
2168
1312
  return Promise.all(
2169
1313
  results.map(
2170
- (conv) => conversationToStored(conv, ctx.walletAddress, ctx.signMessage, ctx.embeddedWalletSigner)
1314
+ (raw) => conversationRawToStored(raw, ctx.walletAddress, ctx.signMessage, ctx.embeddedWalletSigner)
2171
1315
  )
2172
1316
  );
2173
1317
  }
2174
- function conversationToLazyStored(conversation) {
1318
+ function conversationRawToLazyStored(raw) {
1319
+ const pinnedAt = raw.pinned_at;
2175
1320
  return {
2176
- uniqueId: conversation.id,
2177
- conversationId: conversation.conversationId,
2178
- encryptedTitle: conversation.title,
2179
- projectId: conversation.projectId,
2180
- createdAt: conversation.createdAt,
2181
- updatedAt: conversation.updatedAt,
2182
- isDeleted: conversation.isDeleted,
2183
- pinnedAt: conversation.pinnedAt
1321
+ uniqueId: raw.id,
1322
+ conversationId: raw.conversation_id ?? "",
1323
+ encryptedTitle: raw.title ?? "",
1324
+ projectId: raw.project_id,
1325
+ createdAt: rawDate(raw.created_at),
1326
+ updatedAt: rawDate(raw.updated_at),
1327
+ isDeleted: raw.is_deleted === true || raw.is_deleted === 1,
1328
+ pinnedAt: typeof pinnedAt === "number" ? new Date(pinnedAt) : null
2184
1329
  };
2185
1330
  }
2186
1331
  async function getConversationsLazyOp(ctx) {
2187
- const results = await ctx.conversationsCollection.query(import_watermelondb.Q.where("is_deleted", false), import_watermelondb.Q.sortBy("created_at", import_watermelondb.Q.desc)).fetch();
2188
- return results.map(conversationToLazyStored);
1332
+ const results = await ctx.conversationsCollection.query(import_watermelondb.Q.where("is_deleted", false), import_watermelondb.Q.sortBy("created_at", import_watermelondb.Q.desc)).unsafeFetchRaw();
1333
+ return results.map(conversationRawToLazyStored);
1334
+ }
1335
+ async function getConversationsPageOp(ctx, options) {
1336
+ const limit = Math.floor(options?.limit ?? 200);
1337
+ if (!Number.isFinite(limit) || limit < 1) return [];
1338
+ const exclude = new Set(options?.boundaryExcludeUniqueIds ?? []);
1339
+ const clauses = [import_watermelondb.Q.where("is_deleted", false)];
1340
+ if (options?.before !== void 0) {
1341
+ clauses.push(
1342
+ exclude.size > 0 ? import_watermelondb.Q.where("created_at", import_watermelondb.Q.lte(options.before)) : import_watermelondb.Q.where("created_at", import_watermelondb.Q.lt(options.before))
1343
+ );
1344
+ }
1345
+ const fetched = await ctx.conversationsCollection.query(...clauses, import_watermelondb.Q.sortBy("created_at", import_watermelondb.Q.desc), import_watermelondb.Q.take(limit + exclude.size)).unsafeFetchRaw();
1346
+ const results = exclude.size > 0 ? fetched.filter((raw) => !exclude.has(raw.id)) : fetched;
1347
+ return results.slice(0, limit).map(conversationRawToLazyStored);
2189
1348
  }
2190
1349
  async function getConversationsByProjectLazyOp(ctx, projectId) {
2191
1350
  const results = await ctx.conversationsCollection.query(
2192
1351
  import_watermelondb.Q.where("project_id", projectId === null ? "" : projectId),
2193
1352
  import_watermelondb.Q.where("is_deleted", false),
2194
1353
  import_watermelondb.Q.sortBy("created_at", import_watermelondb.Q.desc)
2195
- ).fetch();
2196
- return results.map(conversationToLazyStored);
1354
+ ).unsafeFetchRaw();
1355
+ return results.map(conversationRawToLazyStored);
2197
1356
  }
2198
1357
  async function updateConversationTitleOp(ctx, id, title) {
2199
1358
  const results = await ctx.conversationsCollection.query(import_watermelondb.Q.where("conversation_id", id), import_watermelondb.Q.where("is_deleted", false)).fetch();
@@ -2239,10 +1398,10 @@ async function updateConversationPinnedOp(ctx, id, pinned) {
2239
1398
  return false;
2240
1399
  }
2241
1400
  async function getMessagesOp(ctx, convId) {
2242
- const results = await ctx.messagesCollection.query(import_watermelondb.Q.where("conversation_id", convId), import_watermelondb.Q.sortBy("message_id", import_watermelondb.Q.asc)).fetch();
1401
+ const results = await ctx.messagesCollection.query(import_watermelondb.Q.where("conversation_id", convId), import_watermelondb.Q.sortBy("message_id", import_watermelondb.Q.asc)).unsafeFetchRaw();
2243
1402
  return Promise.all(
2244
1403
  results.map(
2245
- (msg) => messageToStored(msg, ctx.walletAddress, ctx.signMessage, ctx.embeddedWalletSigner)
1404
+ (raw) => messageRawToStored(raw, ctx.walletAddress, ctx.signMessage, ctx.embeddedWalletSigner)
2246
1405
  )
2247
1406
  );
2248
1407
  }
@@ -2259,39 +1418,40 @@ async function getMessagesPageOp(ctx, convId, opts) {
2259
1418
  exclude.size > 0 ? import_watermelondb.Q.where("message_id", import_watermelondb.Q.lte(opts.beforeMessageId)) : import_watermelondb.Q.where("message_id", import_watermelondb.Q.lt(opts.beforeMessageId))
2260
1419
  );
2261
1420
  }
2262
- const fetched = await ctx.messagesCollection.query(...clauses, import_watermelondb.Q.sortBy("message_id", import_watermelondb.Q.desc), import_watermelondb.Q.take(limit + exclude.size)).fetch();
2263
- const results = (exclude.size > 0 ? fetched.filter((msg) => !exclude.has(msg.id)) : fetched).slice(0, limit);
1421
+ const fetched = await ctx.messagesCollection.query(...clauses, import_watermelondb.Q.sortBy("message_id", import_watermelondb.Q.desc), import_watermelondb.Q.take(limit + exclude.size)).unsafeFetchRaw();
1422
+ const results = (exclude.size > 0 ? fetched.filter((raw) => !exclude.has(raw.id)) : fetched).slice(0, limit);
2264
1423
  results.reverse();
2265
1424
  return Promise.all(
2266
1425
  results.map(
2267
- (msg) => messageToStored(msg, ctx.walletAddress, ctx.signMessage, ctx.embeddedWalletSigner, {
1426
+ (raw) => messageRawToStored(raw, ctx.walletAddress, ctx.signMessage, ctx.embeddedWalletSigner, {
2268
1427
  skipEmbeddings: true
2269
1428
  })
2270
1429
  )
2271
1430
  );
2272
1431
  }
2273
1432
  async function getMessageSkeletonsOp(ctx, convId) {
2274
- const results = await ctx.messagesCollection.query(import_watermelondb.Q.where("conversation_id", convId), import_watermelondb.Q.sortBy("message_id", import_watermelondb.Q.asc)).fetch();
1433
+ const results = await ctx.messagesCollection.query(import_watermelondb.Q.where("conversation_id", convId), import_watermelondb.Q.sortBy("message_id", import_watermelondb.Q.asc)).unsafeFetchRaw();
2275
1434
  const roleById = /* @__PURE__ */ new Map();
2276
- for (const msg of results) {
2277
- roleById.set(msg.id, msg.role);
2278
- }
2279
- const skeletons = results.map((msg) => ({
2280
- uniqueId: msg.id,
2281
- messageId: msg.messageId,
2282
- conversationId: String(msg._getRaw("conversation_id")),
2283
- role: msg.role,
2284
- createdAt: msg.createdAt,
1435
+ for (const raw of results) {
1436
+ roleById.set(raw.id, raw.role);
1437
+ }
1438
+ const skeletons = results.map((raw) => ({
1439
+ uniqueId: raw.id,
1440
+ messageId: raw.message_id,
1441
+ conversationId: raw.conversation_id ?? "",
1442
+ role: raw.role ?? "",
1443
+ createdAt: rawDate(raw.created_at),
2285
1444
  // WatermelonDB surfaces unset text columns as null at runtime — normalize
2286
1445
  // to undefined so `parentMessageId ?? undefined` keying works everywhere.
2287
- parentMessageId: msg.parentMessageId ?? void 0,
2288
- model: msg.model ?? void 0
1446
+ parentMessageId: raw.parent_message_id ?? void 0,
1447
+ model: raw.model ?? void 0
2289
1448
  }));
2290
1449
  const artifactIndices = [];
2291
1450
  for (let i = 0; i < results.length; i++) {
2292
- const msg = results[i];
2293
- if (msg.role !== "user" || !msg.parentMessageId) continue;
2294
- if (roleById.get(msg.parentMessageId) === "user") {
1451
+ const raw = results[i];
1452
+ const parentMessageId = raw.parent_message_id;
1453
+ if (raw.role !== "user" || !parentMessageId) continue;
1454
+ if (roleById.get(parentMessageId) === "user") {
2295
1455
  artifactIndices.push(i);
2296
1456
  }
2297
1457
  }
@@ -2876,7 +2036,39 @@ var init_constants = __esm({
2876
2036
  }
2877
2037
  });
2878
2038
 
2879
- // src/lib/memoryEngine/embeddings.ts
2039
+ // src/clientConfig.ts
2040
+ var clientConfig_exports = {};
2041
+ __export(clientConfig_exports, {
2042
+ BASE_URL: () => BASE_URL,
2043
+ MCP_R2_DOMAIN: () => MCP_R2_DOMAIN,
2044
+ createClientConfig: () => createClientConfig,
2045
+ resolveBaseUrl: () => resolveBaseUrl
2046
+ });
2047
+ function readGlobal(key) {
2048
+ if (typeof globalThis === "undefined") return void 0;
2049
+ const value = globalThis[key];
2050
+ return typeof value === "string" && value.length > 0 ? value : void 0;
2051
+ }
2052
+ function resolveBaseUrl() {
2053
+ const fromProcess = typeof process !== "undefined" ? process.env.API_URL || process.env.NEXT_PUBLIC_API_URL || process.env.EXPO_PUBLIC_API_URL : void 0;
2054
+ const fromGlobal = readGlobal("API_URL") ?? readGlobal("NEXT_PUBLIC_API_URL") ?? readGlobal("EXPO_PUBLIC_API_URL");
2055
+ return (fromProcess || fromGlobal || DEFAULT_BASE_URL).replace(/\/+$/, "");
2056
+ }
2057
+ var DEFAULT_BASE_URL, BASE_URL, MCP_R2_DOMAIN, createClientConfig;
2058
+ var init_clientConfig = __esm({
2059
+ "src/clientConfig.ts"() {
2060
+ "use strict";
2061
+ DEFAULT_BASE_URL = "https://portal.anuma-dev.ai";
2062
+ BASE_URL = resolveBaseUrl();
2063
+ MCP_R2_DOMAIN = "4cf0e0ea50b97e72386fcf2f92a2d4e8.r2.cloudflarestorage.com";
2064
+ createClientConfig = (config) => ({
2065
+ ...config,
2066
+ baseUrl: BASE_URL
2067
+ });
2068
+ }
2069
+ });
2070
+
2071
+ // src/lib/memoryEngine/generate.ts
2880
2072
  async function withEmbeddingRetry(call) {
2881
2073
  let last;
2882
2074
  let lastThrown;
@@ -2912,7 +2104,7 @@ async function generateEmbedding(text12, options) {
2912
2104
  const { baseUrl = BASE_URL, getToken, apiKey, model, cache } = options;
2913
2105
  if (cache) {
2914
2106
  const cached = cache.get(text12);
2915
- if (cached) return cached;
2107
+ if (cached) return Array.from(cached);
2916
2108
  }
2917
2109
  let headers;
2918
2110
  if (apiKey) {
@@ -2927,7 +2119,7 @@ async function generateEmbedding(text12, options) {
2927
2119
  throw new Error("Either apiKey or getToken must be provided");
2928
2120
  }
2929
2121
  const response = await withEmbeddingRetry(
2930
- () => postApiV1Embeddings({
2122
+ () => (0, import_client.postApiV1Embeddings)({
2931
2123
  baseUrl,
2932
2124
  body: {
2933
2125
  // Mask PII from the request body only — the cache above still keys on
@@ -2951,14 +2143,15 @@ async function generateEmbedding(text12, options) {
2951
2143
  totalTokens: response.data.usage.total_tokens ?? 0
2952
2144
  });
2953
2145
  }
2146
+ const f32Embedding = Float32Array.from(embedding);
2954
2147
  if (cache) {
2955
- cache.set(text12, embedding);
2148
+ cache.set(text12, f32Embedding);
2956
2149
  }
2957
- return embedding;
2150
+ return Array.from(f32Embedding);
2958
2151
  }
2959
2152
  async function generateEmbeddingsBatch(texts, headers, baseUrl, model, onUsage, maskInput) {
2960
2153
  const response = await withEmbeddingRetry(
2961
- () => postApiV1Embeddings({
2154
+ () => (0, import_client.postApiV1Embeddings)({
2962
2155
  baseUrl,
2963
2156
  // Mask PII from the request body only; cache/order still key on originals.
2964
2157
  body: { input: maskInput ? texts.map(maskInput) : texts, model },
@@ -2990,7 +2183,7 @@ async function generateEmbeddings(texts, options) {
2990
2183
  if (cache) {
2991
2184
  const cached = cache.get(texts[i]);
2992
2185
  if (cached) {
2993
- results[i] = cached;
2186
+ results[i] = Array.from(cached);
2994
2187
  continue;
2995
2188
  }
2996
2189
  }
@@ -3051,13 +2244,35 @@ async function generateEmbeddings(texts, options) {
3051
2244
  newEmbeddings = allEmbeddings.flat();
3052
2245
  }
3053
2246
  for (let i = 0; i < uncachedIndices.length; i++) {
3054
- results[uncachedIndices[i]] = newEmbeddings[i];
2247
+ const f32Embedding = Float32Array.from(newEmbeddings[i]);
2248
+ results[uncachedIndices[i]] = Array.from(f32Embedding);
3055
2249
  if (cache) {
3056
- cache.set(uncachedTexts[i], newEmbeddings[i]);
2250
+ cache.set(uncachedTexts[i], f32Embedding);
3057
2251
  }
3058
2252
  }
3059
2253
  return results;
3060
2254
  }
2255
+ var import_client, EMBED_MAX_ATTEMPTS, EmbeddingHttpError, DEFAULT_EMBEDDING_BATCH_SIZE, DEFAULT_EMBEDDING_BATCH_CONCURRENCY;
2256
+ var init_generate = __esm({
2257
+ "src/lib/memoryEngine/generate.ts"() {
2258
+ "use strict";
2259
+ import_client = require("@anuma/sdk");
2260
+ init_clientConfig();
2261
+ init_constants();
2262
+ EMBED_MAX_ATTEMPTS = 4;
2263
+ EmbeddingHttpError = class extends Error {
2264
+ constructor(message, status) {
2265
+ super(message);
2266
+ this.name = "EmbeddingHttpError";
2267
+ this.status = status;
2268
+ }
2269
+ };
2270
+ DEFAULT_EMBEDDING_BATCH_SIZE = 100;
2271
+ DEFAULT_EMBEDDING_BATCH_CONCURRENCY = 3;
2272
+ }
2273
+ });
2274
+
2275
+ // src/lib/memoryEngine/embeddings.ts
3061
2276
  async function embedMessage(ctx, messageId, options) {
3062
2277
  let message;
3063
2278
  const conversations = await getConversationsOp(ctx);
@@ -3213,27 +2428,17 @@ async function chunkAndEmbedAllMessages(ctx, options, filter) {
3213
2428
  }
3214
2429
  return embeddedCount;
3215
2430
  }
3216
- var DEFAULT_MIN_CONTENT_LENGTH, EMBED_MAX_ATTEMPTS, EmbeddingHttpError, DEFAULT_EMBEDDING_BATCH_SIZE, DEFAULT_EMBEDDING_BATCH_CONCURRENCY;
2431
+ var DEFAULT_MIN_CONTENT_LENGTH;
3217
2432
  var init_embeddings = __esm({
3218
2433
  "src/lib/memoryEngine/embeddings.ts"() {
3219
2434
  "use strict";
3220
- init_client2();
3221
- init_clientConfig();
3222
2435
  init_operations();
3223
2436
  init_logger();
3224
2437
  init_chunking();
3225
2438
  init_constants();
2439
+ init_generate();
2440
+ init_generate();
3226
2441
  DEFAULT_MIN_CONTENT_LENGTH = 10;
3227
- EMBED_MAX_ATTEMPTS = 4;
3228
- EmbeddingHttpError = class extends Error {
3229
- constructor(message, status) {
3230
- super(message);
3231
- this.name = "EmbeddingHttpError";
3232
- this.status = status;
3233
- }
3234
- };
3235
- DEFAULT_EMBEDDING_BATCH_SIZE = 100;
3236
- DEFAULT_EMBEDDING_BATCH_CONCURRENCY = 3;
3237
2442
  }
3238
2443
  });
3239
2444
 
@@ -7153,6 +6358,7 @@ __export(index_exports, {
7153
6358
  getConversationMemoriesOp: () => getConversationMemoriesOp,
7154
6359
  getConversationsByProjectLazyOp: () => getConversationsByProjectLazyOp,
7155
6360
  getConversationsLazyOp: () => getConversationsLazyOp,
6361
+ getConversationsPageOp: () => getConversationsPageOp,
7156
6362
  getLogger: () => getLogger,
7157
6363
  getMemoriesNeedingTopicExtractionOp: () => getMemoriesNeedingTopicExtractionOp,
7158
6364
  getServerTools: () => getServerTools,
@@ -7377,16 +6583,150 @@ function createWebSearchPreProcessor(options = {}) {
7377
6583
  const wrapped = wrapAsUserText("Web search context:", results);
7378
6584
  return wrapped.length === 0 ? void 0 : wrapped;
7379
6585
  }
7380
- if (results.length === 0) return;
7381
- return results;
6586
+ if (results.length === 0) return;
6587
+ return results;
6588
+ };
6589
+ }
6590
+
6591
+ // src/lib/chat/resumeStream.ts
6592
+ init_clientConfig();
6593
+
6594
+ // src/client/core/serverSentEvents.gen.ts
6595
+ var createSseClient = ({
6596
+ onRequest,
6597
+ onSseError,
6598
+ onSseEvent,
6599
+ responseTransformer,
6600
+ responseValidator,
6601
+ sseDefaultRetryDelay,
6602
+ sseMaxRetryAttempts,
6603
+ sseMaxRetryDelay,
6604
+ sseSleepFn,
6605
+ url,
6606
+ ...options
6607
+ }) => {
6608
+ let lastEventId;
6609
+ const sleep4 = sseSleepFn ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
6610
+ const createStream = async function* () {
6611
+ let retryDelay = sseDefaultRetryDelay ?? 3e3;
6612
+ let attempt = 0;
6613
+ const signal = options.signal ?? new AbortController().signal;
6614
+ while (true) {
6615
+ if (signal.aborted) break;
6616
+ attempt++;
6617
+ const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers);
6618
+ if (lastEventId !== void 0) {
6619
+ headers.set("Last-Event-ID", lastEventId);
6620
+ }
6621
+ try {
6622
+ const requestInit = {
6623
+ redirect: "follow",
6624
+ ...options,
6625
+ body: options.serializedBody,
6626
+ headers,
6627
+ signal
6628
+ };
6629
+ let request = new Request(url, requestInit);
6630
+ if (onRequest) {
6631
+ request = await onRequest(url, requestInit);
6632
+ }
6633
+ const _fetch = options.fetch ?? globalThis.fetch;
6634
+ const response = await _fetch(request);
6635
+ if (!response.ok)
6636
+ throw new Error(
6637
+ `SSE failed: ${response.status} ${response.statusText}`
6638
+ );
6639
+ if (!response.body) throw new Error("No body in SSE response");
6640
+ const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
6641
+ let buffer = "";
6642
+ const abortHandler = () => {
6643
+ try {
6644
+ reader.cancel();
6645
+ } catch {
6646
+ }
6647
+ };
6648
+ signal.addEventListener("abort", abortHandler);
6649
+ try {
6650
+ while (true) {
6651
+ const { done, value } = await reader.read();
6652
+ if (done) break;
6653
+ buffer += value;
6654
+ const chunks = buffer.split("\n\n");
6655
+ buffer = chunks.pop() ?? "";
6656
+ for (const chunk of chunks) {
6657
+ const lines = chunk.split("\n");
6658
+ const dataLines = [];
6659
+ let eventName;
6660
+ for (const line of lines) {
6661
+ if (line.startsWith("data:")) {
6662
+ dataLines.push(line.replace(/^data:\s*/, ""));
6663
+ } else if (line.startsWith("event:")) {
6664
+ eventName = line.replace(/^event:\s*/, "");
6665
+ } else if (line.startsWith("id:")) {
6666
+ lastEventId = line.replace(/^id:\s*/, "");
6667
+ } else if (line.startsWith("retry:")) {
6668
+ const parsed = Number.parseInt(
6669
+ line.replace(/^retry:\s*/, ""),
6670
+ 10
6671
+ );
6672
+ if (!Number.isNaN(parsed)) {
6673
+ retryDelay = parsed;
6674
+ }
6675
+ }
6676
+ }
6677
+ let data;
6678
+ let parsedJson = false;
6679
+ if (dataLines.length) {
6680
+ const rawData = dataLines.join("\n");
6681
+ try {
6682
+ data = JSON.parse(rawData);
6683
+ parsedJson = true;
6684
+ } catch {
6685
+ data = rawData;
6686
+ }
6687
+ }
6688
+ if (parsedJson) {
6689
+ if (responseValidator) {
6690
+ await responseValidator(data);
6691
+ }
6692
+ if (responseTransformer) {
6693
+ data = await responseTransformer(data);
6694
+ }
6695
+ }
6696
+ onSseEvent?.({
6697
+ data,
6698
+ event: eventName,
6699
+ id: lastEventId,
6700
+ retry: retryDelay
6701
+ });
6702
+ if (dataLines.length) {
6703
+ yield data;
6704
+ }
6705
+ }
6706
+ }
6707
+ } finally {
6708
+ signal.removeEventListener("abort", abortHandler);
6709
+ reader.releaseLock();
6710
+ }
6711
+ break;
6712
+ } catch (error) {
6713
+ onSseError?.(error);
6714
+ if (sseMaxRetryAttempts !== void 0 && attempt >= sseMaxRetryAttempts) {
6715
+ break;
6716
+ }
6717
+ const backoff = Math.min(
6718
+ retryDelay * 2 ** (attempt - 1),
6719
+ sseMaxRetryDelay ?? 3e4
6720
+ );
6721
+ await sleep4(backoff);
6722
+ }
6723
+ }
7382
6724
  };
7383
- }
7384
-
7385
- // src/lib/chat/resumeStream.ts
7386
- init_clientConfig();
6725
+ const stream = createStream();
6726
+ return { stream };
6727
+ };
7387
6728
 
7388
6729
  // src/lib/chat/toolLoop.ts
7389
- init_serverSentEvents_gen();
7390
6730
  init_clientConfig();
7391
6731
  init_embeddings();
7392
6732
  init_redactor();
@@ -10798,49 +10138,745 @@ var xhrTransport = (options) => {
10798
10138
  push({ type: "data", value: chunk });
10799
10139
  }
10800
10140
  }
10801
- if (xhr.status >= 200 && xhr.status < 300) {
10802
- push({ type: "done" });
10803
- } else {
10804
- const body = (xhr.responseText || "").slice(0, 500);
10805
- const detail = body ? `: ${body}` : "";
10806
- const error = new Error(sseFailureMessage(xhr.status, xhr.statusText, detail));
10807
- if (options.onSseError) options.onSseError(error);
10808
- push({ type: "done" });
10141
+ if (xhr.status >= 200 && xhr.status < 300) {
10142
+ push({ type: "done" });
10143
+ } else {
10144
+ const body = (xhr.responseText || "").slice(0, 500);
10145
+ const detail = body ? `: ${body}` : "";
10146
+ const error = new Error(sseFailureMessage(xhr.status, xhr.statusText, detail));
10147
+ if (options.onSseError) options.onSseError(error);
10148
+ push({ type: "done" });
10149
+ }
10150
+ finished = true;
10151
+ };
10152
+ xhr.onerror = () => {
10153
+ options.signal?.removeEventListener("abort", abortHandler);
10154
+ const error = new Error("Network error");
10155
+ if (options.onSseError) options.onSseError(error);
10156
+ push({ type: "done" });
10157
+ finished = true;
10158
+ };
10159
+ xhr.onabort = () => {
10160
+ options.signal?.removeEventListener("abort", abortHandler);
10161
+ push({ type: "error", error: makeAbortError() });
10162
+ finished = true;
10163
+ };
10164
+ xhr.send(options.body !== void 0 ? JSON.stringify(options.body) : void 0);
10165
+ }
10166
+ async function* createStream() {
10167
+ if (options.signal?.aborted) throw makeAbortError();
10168
+ while (true) {
10169
+ await waitForItem();
10170
+ while (queue.length > 0) {
10171
+ const item = queue.shift();
10172
+ if (item.type === "done") return;
10173
+ if (item.type === "error") throw item.error;
10174
+ yield item.value;
10175
+ }
10176
+ }
10177
+ }
10178
+ return { stream: createStream() };
10179
+ };
10180
+
10181
+ // src/react/useCredits.ts
10182
+ var import_react = require("react");
10183
+
10184
+ // src/client/core/bodySerializer.gen.ts
10185
+ var jsonBodySerializer = {
10186
+ bodySerializer: (body) => JSON.stringify(
10187
+ body,
10188
+ (_key, value) => typeof value === "bigint" ? value.toString() : value
10189
+ )
10190
+ };
10191
+
10192
+ // src/client/core/pathSerializer.gen.ts
10193
+ var separatorArrayExplode = (style) => {
10194
+ switch (style) {
10195
+ case "label":
10196
+ return ".";
10197
+ case "matrix":
10198
+ return ";";
10199
+ case "simple":
10200
+ return ",";
10201
+ default:
10202
+ return "&";
10203
+ }
10204
+ };
10205
+ var separatorArrayNoExplode = (style) => {
10206
+ switch (style) {
10207
+ case "form":
10208
+ return ",";
10209
+ case "pipeDelimited":
10210
+ return "|";
10211
+ case "spaceDelimited":
10212
+ return "%20";
10213
+ default:
10214
+ return ",";
10215
+ }
10216
+ };
10217
+ var separatorObjectExplode = (style) => {
10218
+ switch (style) {
10219
+ case "label":
10220
+ return ".";
10221
+ case "matrix":
10222
+ return ";";
10223
+ case "simple":
10224
+ return ",";
10225
+ default:
10226
+ return "&";
10227
+ }
10228
+ };
10229
+ var serializeArrayParam = ({
10230
+ allowReserved,
10231
+ explode,
10232
+ name,
10233
+ style,
10234
+ value
10235
+ }) => {
10236
+ if (!explode) {
10237
+ const joinedValues2 = (allowReserved ? value : value.map((v) => encodeURIComponent(v))).join(separatorArrayNoExplode(style));
10238
+ switch (style) {
10239
+ case "label":
10240
+ return `.${joinedValues2}`;
10241
+ case "matrix":
10242
+ return `;${name}=${joinedValues2}`;
10243
+ case "simple":
10244
+ return joinedValues2;
10245
+ default:
10246
+ return `${name}=${joinedValues2}`;
10247
+ }
10248
+ }
10249
+ const separator = separatorArrayExplode(style);
10250
+ const joinedValues = value.map((v) => {
10251
+ if (style === "label" || style === "simple") {
10252
+ return allowReserved ? v : encodeURIComponent(v);
10253
+ }
10254
+ return serializePrimitiveParam({
10255
+ allowReserved,
10256
+ name,
10257
+ value: v
10258
+ });
10259
+ }).join(separator);
10260
+ return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues;
10261
+ };
10262
+ var serializePrimitiveParam = ({
10263
+ allowReserved,
10264
+ name,
10265
+ value
10266
+ }) => {
10267
+ if (value === void 0 || value === null) {
10268
+ return "";
10269
+ }
10270
+ if (typeof value === "object") {
10271
+ throw new Error(
10272
+ "Deeply-nested arrays/objects aren\u2019t supported. Provide your own `querySerializer()` to handle these."
10273
+ );
10274
+ }
10275
+ return `${name}=${allowReserved ? value : encodeURIComponent(value)}`;
10276
+ };
10277
+ var serializeObjectParam = ({
10278
+ allowReserved,
10279
+ explode,
10280
+ name,
10281
+ style,
10282
+ value,
10283
+ valueOnly
10284
+ }) => {
10285
+ if (value instanceof Date) {
10286
+ return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`;
10287
+ }
10288
+ if (style !== "deepObject" && !explode) {
10289
+ let values = [];
10290
+ Object.entries(value).forEach(([key, v]) => {
10291
+ values = [
10292
+ ...values,
10293
+ key,
10294
+ allowReserved ? v : encodeURIComponent(v)
10295
+ ];
10296
+ });
10297
+ const joinedValues2 = values.join(",");
10298
+ switch (style) {
10299
+ case "form":
10300
+ return `${name}=${joinedValues2}`;
10301
+ case "label":
10302
+ return `.${joinedValues2}`;
10303
+ case "matrix":
10304
+ return `;${name}=${joinedValues2}`;
10305
+ default:
10306
+ return joinedValues2;
10307
+ }
10308
+ }
10309
+ const separator = separatorObjectExplode(style);
10310
+ const joinedValues = Object.entries(value).map(
10311
+ ([key, v]) => serializePrimitiveParam({
10312
+ allowReserved,
10313
+ name: style === "deepObject" ? `${name}[${key}]` : key,
10314
+ value: v
10315
+ })
10316
+ ).join(separator);
10317
+ return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues;
10318
+ };
10319
+
10320
+ // src/client/core/utils.gen.ts
10321
+ function getValidRequestBody(options) {
10322
+ const hasBody = options.body !== void 0;
10323
+ const isSerializedBody = hasBody && options.bodySerializer;
10324
+ if (isSerializedBody) {
10325
+ if ("serializedBody" in options) {
10326
+ const hasSerializedBody = options.serializedBody !== void 0 && options.serializedBody !== "";
10327
+ return hasSerializedBody ? options.serializedBody : null;
10328
+ }
10329
+ return options.body !== "" ? options.body : null;
10330
+ }
10331
+ if (hasBody) {
10332
+ return options.body;
10333
+ }
10334
+ return void 0;
10335
+ }
10336
+
10337
+ // src/client/core/auth.gen.ts
10338
+ var getAuthToken = async (auth, callback) => {
10339
+ const token = typeof callback === "function" ? await callback(auth) : callback;
10340
+ if (!token) {
10341
+ return;
10342
+ }
10343
+ if (auth.scheme === "bearer") {
10344
+ return `Bearer ${token}`;
10345
+ }
10346
+ if (auth.scheme === "basic") {
10347
+ return `Basic ${btoa(token)}`;
10348
+ }
10349
+ return token;
10350
+ };
10351
+
10352
+ // src/client/client/utils.gen.ts
10353
+ var PATH_PARAM_RE = /\{[^{}]+\}/g;
10354
+ var defaultPathSerializer = ({ path, url: _url }) => {
10355
+ let url = _url;
10356
+ const matches = _url.match(PATH_PARAM_RE);
10357
+ if (matches) {
10358
+ for (const match of matches) {
10359
+ let explode = false;
10360
+ let name = match.substring(1, match.length - 1);
10361
+ let style = "simple";
10362
+ if (name.endsWith("*")) {
10363
+ explode = true;
10364
+ name = name.substring(0, name.length - 1);
10365
+ }
10366
+ if (name.startsWith(".")) {
10367
+ name = name.substring(1);
10368
+ style = "label";
10369
+ } else if (name.startsWith(";")) {
10370
+ name = name.substring(1);
10371
+ style = "matrix";
10372
+ }
10373
+ const value = path[name];
10374
+ if (value === void 0 || value === null) {
10375
+ continue;
10376
+ }
10377
+ if (Array.isArray(value)) {
10378
+ url = url.replace(
10379
+ match,
10380
+ serializeArrayParam({ explode, name, style, value })
10381
+ );
10382
+ continue;
10383
+ }
10384
+ if (typeof value === "object") {
10385
+ url = url.replace(
10386
+ match,
10387
+ serializeObjectParam({
10388
+ explode,
10389
+ name,
10390
+ style,
10391
+ value,
10392
+ valueOnly: true
10393
+ })
10394
+ );
10395
+ continue;
10396
+ }
10397
+ if (style === "matrix") {
10398
+ url = url.replace(
10399
+ match,
10400
+ `;${serializePrimitiveParam({
10401
+ name,
10402
+ value
10403
+ })}`
10404
+ );
10405
+ continue;
10406
+ }
10407
+ const replaceValue = encodeURIComponent(
10408
+ style === "label" ? `.${value}` : value
10409
+ );
10410
+ url = url.replace(match, replaceValue);
10411
+ }
10412
+ }
10413
+ return url;
10414
+ };
10415
+ var createQuerySerializer = ({
10416
+ parameters = {},
10417
+ ...args
10418
+ } = {}) => {
10419
+ const querySerializer = (queryParams) => {
10420
+ const search = [];
10421
+ if (queryParams && typeof queryParams === "object") {
10422
+ for (const name in queryParams) {
10423
+ const value = queryParams[name];
10424
+ if (value === void 0 || value === null) {
10425
+ continue;
10426
+ }
10427
+ const options = parameters[name] || args;
10428
+ if (Array.isArray(value)) {
10429
+ const serializedArray = serializeArrayParam({
10430
+ allowReserved: options.allowReserved,
10431
+ explode: true,
10432
+ name,
10433
+ style: "form",
10434
+ value,
10435
+ ...options.array
10436
+ });
10437
+ if (serializedArray) search.push(serializedArray);
10438
+ } else if (typeof value === "object") {
10439
+ const serializedObject = serializeObjectParam({
10440
+ allowReserved: options.allowReserved,
10441
+ explode: true,
10442
+ name,
10443
+ style: "deepObject",
10444
+ value,
10445
+ ...options.object
10446
+ });
10447
+ if (serializedObject) search.push(serializedObject);
10448
+ } else {
10449
+ const serializedPrimitive = serializePrimitiveParam({
10450
+ allowReserved: options.allowReserved,
10451
+ name,
10452
+ value
10453
+ });
10454
+ if (serializedPrimitive) search.push(serializedPrimitive);
10455
+ }
10456
+ }
10457
+ }
10458
+ return search.join("&");
10459
+ };
10460
+ return querySerializer;
10461
+ };
10462
+ var getParseAs = (contentType) => {
10463
+ if (!contentType) {
10464
+ return "stream";
10465
+ }
10466
+ const cleanContent = contentType.split(";")[0]?.trim();
10467
+ if (!cleanContent) {
10468
+ return;
10469
+ }
10470
+ if (cleanContent.startsWith("application/json") || cleanContent.endsWith("+json")) {
10471
+ return "json";
10472
+ }
10473
+ if (cleanContent === "multipart/form-data") {
10474
+ return "formData";
10475
+ }
10476
+ if (["application/", "audio/", "image/", "video/"].some(
10477
+ (type) => cleanContent.startsWith(type)
10478
+ )) {
10479
+ return "blob";
10480
+ }
10481
+ if (cleanContent.startsWith("text/")) {
10482
+ return "text";
10483
+ }
10484
+ return;
10485
+ };
10486
+ var checkForExistence = (options, name) => {
10487
+ if (!name) {
10488
+ return false;
10489
+ }
10490
+ if (options.headers.has(name) || options.query?.[name] || options.headers.get("Cookie")?.includes(`${name}=`)) {
10491
+ return true;
10492
+ }
10493
+ return false;
10494
+ };
10495
+ var setAuthParams = async ({
10496
+ security,
10497
+ ...options
10498
+ }) => {
10499
+ for (const auth of security) {
10500
+ if (checkForExistence(options, auth.name)) {
10501
+ continue;
10502
+ }
10503
+ const token = await getAuthToken(auth, options.auth);
10504
+ if (!token) {
10505
+ continue;
10506
+ }
10507
+ const name = auth.name ?? "Authorization";
10508
+ switch (auth.in) {
10509
+ case "query":
10510
+ if (!options.query) {
10511
+ options.query = {};
10512
+ }
10513
+ options.query[name] = token;
10514
+ break;
10515
+ case "cookie":
10516
+ options.headers.append("Cookie", `${name}=${token}`);
10517
+ break;
10518
+ case "header":
10519
+ default:
10520
+ options.headers.set(name, token);
10521
+ break;
10522
+ }
10523
+ }
10524
+ };
10525
+ var buildUrl = (options) => {
10526
+ const url = getUrl({
10527
+ baseUrl: options.baseUrl,
10528
+ path: options.path,
10529
+ query: options.query,
10530
+ querySerializer: typeof options.querySerializer === "function" ? options.querySerializer : createQuerySerializer(options.querySerializer),
10531
+ url: options.url
10532
+ });
10533
+ return url;
10534
+ };
10535
+ var getUrl = ({
10536
+ baseUrl,
10537
+ path,
10538
+ query,
10539
+ querySerializer,
10540
+ url: _url
10541
+ }) => {
10542
+ const pathUrl = _url.startsWith("/") ? _url : `/${_url}`;
10543
+ let url = (baseUrl ?? "") + pathUrl;
10544
+ if (path) {
10545
+ url = defaultPathSerializer({ path, url });
10546
+ }
10547
+ let search = query ? querySerializer(query) : "";
10548
+ if (search.startsWith("?")) {
10549
+ search = search.substring(1);
10550
+ }
10551
+ if (search) {
10552
+ url += `?${search}`;
10553
+ }
10554
+ return url;
10555
+ };
10556
+ var mergeConfigs = (a, b) => {
10557
+ const config = { ...a, ...b };
10558
+ if (config.baseUrl?.endsWith("/")) {
10559
+ config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1);
10560
+ }
10561
+ config.headers = mergeHeaders(a.headers, b.headers);
10562
+ return config;
10563
+ };
10564
+ var headersEntries = (headers) => {
10565
+ const entries = [];
10566
+ headers.forEach((value, key) => {
10567
+ entries.push([key, value]);
10568
+ });
10569
+ return entries;
10570
+ };
10571
+ var mergeHeaders = (...headers) => {
10572
+ const mergedHeaders = new Headers();
10573
+ for (const header of headers) {
10574
+ if (!header || typeof header !== "object") {
10575
+ continue;
10576
+ }
10577
+ const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header);
10578
+ for (const [key, value] of iterator) {
10579
+ if (value === null) {
10580
+ mergedHeaders.delete(key);
10581
+ } else if (Array.isArray(value)) {
10582
+ for (const v of value) {
10583
+ mergedHeaders.append(key, v);
10584
+ }
10585
+ } else if (value !== void 0) {
10586
+ mergedHeaders.set(
10587
+ key,
10588
+ typeof value === "object" ? JSON.stringify(value) : value
10589
+ );
10590
+ }
10591
+ }
10592
+ }
10593
+ return mergedHeaders;
10594
+ };
10595
+ var Interceptors = class {
10596
+ constructor() {
10597
+ this.fns = [];
10598
+ }
10599
+ clear() {
10600
+ this.fns = [];
10601
+ }
10602
+ eject(id) {
10603
+ const index = this.getInterceptorIndex(id);
10604
+ if (this.fns[index]) {
10605
+ this.fns[index] = null;
10606
+ }
10607
+ }
10608
+ exists(id) {
10609
+ const index = this.getInterceptorIndex(id);
10610
+ return Boolean(this.fns[index]);
10611
+ }
10612
+ getInterceptorIndex(id) {
10613
+ if (typeof id === "number") {
10614
+ return this.fns[id] ? id : -1;
10615
+ }
10616
+ return this.fns.indexOf(id);
10617
+ }
10618
+ update(id, fn) {
10619
+ const index = this.getInterceptorIndex(id);
10620
+ if (this.fns[index]) {
10621
+ this.fns[index] = fn;
10622
+ return id;
10623
+ }
10624
+ return false;
10625
+ }
10626
+ use(fn) {
10627
+ this.fns.push(fn);
10628
+ return this.fns.length - 1;
10629
+ }
10630
+ };
10631
+ var createInterceptors = () => ({
10632
+ error: new Interceptors(),
10633
+ request: new Interceptors(),
10634
+ response: new Interceptors()
10635
+ });
10636
+ var defaultQuerySerializer = createQuerySerializer({
10637
+ allowReserved: false,
10638
+ array: {
10639
+ explode: true,
10640
+ style: "form"
10641
+ },
10642
+ object: {
10643
+ explode: true,
10644
+ style: "deepObject"
10645
+ }
10646
+ });
10647
+ var defaultHeaders = {
10648
+ "Content-Type": "application/json"
10649
+ };
10650
+ var createConfig = (override = {}) => ({
10651
+ ...jsonBodySerializer,
10652
+ headers: defaultHeaders,
10653
+ parseAs: "auto",
10654
+ querySerializer: defaultQuerySerializer,
10655
+ ...override
10656
+ });
10657
+
10658
+ // src/client/client/client.gen.ts
10659
+ var createClient = (config = {}) => {
10660
+ let _config = mergeConfigs(createConfig(), config);
10661
+ const getConfig = () => ({ ..._config });
10662
+ const setConfig = (config2) => {
10663
+ _config = mergeConfigs(_config, config2);
10664
+ return getConfig();
10665
+ };
10666
+ const interceptors = createInterceptors();
10667
+ const beforeRequest = async (options) => {
10668
+ const opts = {
10669
+ ..._config,
10670
+ ...options,
10671
+ fetch: options.fetch ?? _config.fetch ?? globalThis.fetch,
10672
+ headers: mergeHeaders(_config.headers, options.headers),
10673
+ serializedBody: void 0
10674
+ };
10675
+ if (opts.security) {
10676
+ await setAuthParams({
10677
+ ...opts,
10678
+ security: opts.security
10679
+ });
10680
+ }
10681
+ if (opts.requestValidator) {
10682
+ await opts.requestValidator(opts);
10683
+ }
10684
+ if (opts.body !== void 0 && opts.bodySerializer) {
10685
+ opts.serializedBody = opts.bodySerializer(opts.body);
10686
+ }
10687
+ if (opts.body === void 0 || opts.serializedBody === "") {
10688
+ opts.headers.delete("Content-Type");
10689
+ }
10690
+ const url = buildUrl(opts);
10691
+ return { opts, url };
10692
+ };
10693
+ const request = async (options) => {
10694
+ const { opts, url } = await beforeRequest(options);
10695
+ for (const fn of interceptors.request.fns) {
10696
+ if (fn) {
10697
+ await fn(opts);
10698
+ }
10699
+ }
10700
+ const _fetch = opts.fetch;
10701
+ const requestInit = {
10702
+ ...opts,
10703
+ body: getValidRequestBody(opts)
10704
+ };
10705
+ let response = await _fetch(url, requestInit);
10706
+ for (const fn of interceptors.response.fns) {
10707
+ if (fn) {
10708
+ response = await fn(response, opts);
10709
+ }
10710
+ }
10711
+ const result = {
10712
+ response
10713
+ };
10714
+ if (response.ok) {
10715
+ const parseAs = (opts.parseAs === "auto" ? getParseAs(response.headers.get("Content-Type")) : opts.parseAs) ?? "json";
10716
+ if (response.status === 204 || response.headers.get("Content-Length") === "0") {
10717
+ let emptyData;
10718
+ switch (parseAs) {
10719
+ case "arrayBuffer":
10720
+ case "blob":
10721
+ case "text":
10722
+ emptyData = await response[parseAs]();
10723
+ break;
10724
+ case "formData":
10725
+ emptyData = new FormData();
10726
+ break;
10727
+ case "stream":
10728
+ emptyData = response.body;
10729
+ break;
10730
+ case "json":
10731
+ default:
10732
+ emptyData = {};
10733
+ break;
10734
+ }
10735
+ return {
10736
+ data: emptyData,
10737
+ ...result
10738
+ };
10739
+ }
10740
+ let data;
10741
+ switch (parseAs) {
10742
+ case "arrayBuffer":
10743
+ case "blob":
10744
+ case "formData":
10745
+ case "json":
10746
+ case "text":
10747
+ data = await response[parseAs]();
10748
+ break;
10749
+ case "stream":
10750
+ return {
10751
+ data: response.body,
10752
+ ...result
10753
+ };
10754
+ }
10755
+ if (parseAs === "json") {
10756
+ if (opts.responseValidator) {
10757
+ await opts.responseValidator(data);
10758
+ }
10759
+ if (opts.responseTransformer) {
10760
+ data = await opts.responseTransformer(data);
10761
+ }
10762
+ }
10763
+ return {
10764
+ data,
10765
+ ...result
10766
+ };
10767
+ }
10768
+ const textError = await response.text();
10769
+ let jsonError;
10770
+ try {
10771
+ jsonError = JSON.parse(textError);
10772
+ } catch {
10773
+ }
10774
+ const error = jsonError ?? textError;
10775
+ let finalError = error;
10776
+ for (const fn of interceptors.error.fns) {
10777
+ if (fn) {
10778
+ finalError = await fn(error, response, opts);
10809
10779
  }
10810
- finished = true;
10811
- };
10812
- xhr.onerror = () => {
10813
- options.signal?.removeEventListener("abort", abortHandler);
10814
- const error = new Error("Network error");
10815
- if (options.onSseError) options.onSseError(error);
10816
- push({ type: "done" });
10817
- finished = true;
10818
- };
10819
- xhr.onabort = () => {
10820
- options.signal?.removeEventListener("abort", abortHandler);
10821
- push({ type: "error", error: makeAbortError() });
10822
- finished = true;
10780
+ }
10781
+ finalError = finalError || {};
10782
+ if (opts.throwOnError) {
10783
+ throw finalError;
10784
+ }
10785
+ return {
10786
+ error: finalError,
10787
+ ...result
10823
10788
  };
10824
- xhr.send(options.body !== void 0 ? JSON.stringify(options.body) : void 0);
10825
- }
10826
- async function* createStream() {
10827
- if (options.signal?.aborted) throw makeAbortError();
10828
- while (true) {
10829
- await waitForItem();
10830
- while (queue.length > 0) {
10831
- const item = queue.shift();
10832
- if (item.type === "done") return;
10833
- if (item.type === "error") throw item.error;
10834
- yield item.value;
10835
- }
10789
+ };
10790
+ const makeMethodFn = (method) => (options) => request({ ...options, method });
10791
+ const makeSseFn = (method) => async (options) => {
10792
+ const { opts, url } = await beforeRequest(options);
10793
+ return createSseClient({
10794
+ ...opts,
10795
+ body: opts.body,
10796
+ headers: opts.headers,
10797
+ method,
10798
+ onRequest: async (url2, init) => {
10799
+ let request2 = new Request(url2, init);
10800
+ const requestInit = {
10801
+ ...init,
10802
+ method: init.method,
10803
+ url: url2
10804
+ };
10805
+ for (const fn of interceptors.request.fns) {
10806
+ if (fn) {
10807
+ await fn(requestInit);
10808
+ request2 = new Request(requestInit.url, requestInit);
10809
+ }
10810
+ }
10811
+ return request2;
10812
+ },
10813
+ url
10814
+ });
10815
+ };
10816
+ return {
10817
+ buildUrl,
10818
+ connect: makeMethodFn("CONNECT"),
10819
+ delete: makeMethodFn("DELETE"),
10820
+ get: makeMethodFn("GET"),
10821
+ getConfig,
10822
+ head: makeMethodFn("HEAD"),
10823
+ interceptors,
10824
+ options: makeMethodFn("OPTIONS"),
10825
+ patch: makeMethodFn("PATCH"),
10826
+ post: makeMethodFn("POST"),
10827
+ put: makeMethodFn("PUT"),
10828
+ request,
10829
+ setConfig,
10830
+ sse: {
10831
+ connect: makeSseFn("CONNECT"),
10832
+ delete: makeSseFn("DELETE"),
10833
+ get: makeSseFn("GET"),
10834
+ head: makeSseFn("HEAD"),
10835
+ options: makeSseFn("OPTIONS"),
10836
+ patch: makeSseFn("PATCH"),
10837
+ post: makeSseFn("POST"),
10838
+ put: makeSseFn("PUT"),
10839
+ trace: makeSseFn("TRACE")
10840
+ },
10841
+ trace: makeMethodFn("TRACE")
10842
+ };
10843
+ };
10844
+
10845
+ // src/client/client.gen.ts
10846
+ init_clientConfig();
10847
+ var client = createClient(createClientConfig(createConfig()));
10848
+
10849
+ // src/client/sdk.gen.ts
10850
+ var getApiV1CreditsBalance = (options) => {
10851
+ return (options?.client ?? client).get({
10852
+ url: "/api/v1/credits/balance",
10853
+ ...options
10854
+ });
10855
+ };
10856
+ var getApiV1CreditsPacks = (options) => {
10857
+ return (options?.client ?? client).get({
10858
+ url: "/api/v1/credits/packs",
10859
+ ...options
10860
+ });
10861
+ };
10862
+ var postApiV1CreditsPurchase = (options) => {
10863
+ return (options.client ?? client).post({
10864
+ url: "/api/v1/credits/purchase",
10865
+ ...options,
10866
+ headers: {
10867
+ "Content-Type": "application/json",
10868
+ ...options.headers
10836
10869
  }
10837
- }
10838
- return { stream: createStream() };
10870
+ });
10871
+ };
10872
+ var getApiV1Models = (options) => {
10873
+ return (options?.client ?? client).get({
10874
+ url: "/api/v1/models",
10875
+ ...options
10876
+ });
10839
10877
  };
10840
10878
 
10841
10879
  // src/react/useCredits.ts
10842
- var import_react = require("react");
10843
- init_sdk_gen();
10844
10880
  init_clientConfig();
10845
10881
  function useCredits(options = {}) {
10846
10882
  const { getToken, baseUrl = BASE_URL, autoFetch = true, onError } = options;
@@ -10999,7 +11035,6 @@ function useCredits(options = {}) {
10999
11035
 
11000
11036
  // src/react/useModels.ts
11001
11037
  var import_react2 = require("react");
11002
- init_sdk_gen();
11003
11038
  init_clientConfig();
11004
11039
  function useModels(options = {}) {
11005
11040
  const { getToken, baseUrl = BASE_URL, provider, autoFetch = true } = options;
@@ -11238,6 +11273,7 @@ function useChat(options) {
11238
11273
  memoryContext,
11239
11274
  searchContext,
11240
11275
  fileContext,
11276
+ toolGuidance,
11241
11277
  // Responses API options
11242
11278
  temperature,
11243
11279
  maxOutputTokens,
@@ -11309,6 +11345,13 @@ function useChat(options) {
11309
11345
  };
11310
11346
  messagesWithContext = [fileSystemMessage, ...messagesWithContext];
11311
11347
  }
11348
+ if (toolGuidance) {
11349
+ const toolGuidanceMessage = {
11350
+ role: "system",
11351
+ content: [{ type: "text", text: toolGuidance }]
11352
+ };
11353
+ messagesWithContext = [toolGuidanceMessage, ...messagesWithContext];
11354
+ }
11312
11355
  const result = await runToolLoop({
11313
11356
  messages: messagesWithContext,
11314
11357
  model,
@@ -13851,8 +13894,12 @@ init_recall();
13851
13894
 
13852
13895
  // src/lib/memory/recallTool.ts
13853
13896
  init_recall();
13897
+
13898
+ // src/lib/memory/recallConstants.ts
13854
13899
  var RECALL_TOOL_NAME = "recall_memory";
13855
13900
  var RECALL_MAX_LIMIT = 50;
13901
+
13902
+ // src/lib/memory/recallTool.ts
13856
13903
  var DEFAULT_LIMIT2 = 8;
13857
13904
  var DEFAULT_BUDGET2 = "low";
13858
13905
  function formatEventTime(start, end, kind) {
@@ -14644,12 +14691,121 @@ function createMemoryVaultTool(vaultCtx, options, embeddingOptions, cache) {
14644
14691
  // src/expo/useChatStorage.ts
14645
14692
  init_redactor();
14646
14693
 
14694
+ // src/lib/tools/clientToolSelection.ts
14695
+ init_generate();
14696
+
14697
+ // src/tools/appBuilderPrompt.ts
14698
+ var APP_BUILDER_PROMPT = `App Builder tools (create_file, patch_file, and the rest described below) are available this turn, but they are OPTIONAL \u2014 having them does not mean you should build anything.
14699
+
14700
+ Build ONLY when the user gives an explicit instruction to build, create, generate, or change an app, tool, or UI \u2014 e.g. "build a todo app", "make a snake game", "add a footer to the app", "change the background to blue". A bare app name or feature reference is NOT a build instruction: if the user just says "todo app", "a snake game", or "qr code", or asks a question about an app, do NOT generate anything \u2014 reply normally, or ask what they'd like you to build. The same holds for greetings, questions, stories, explanations, advice, or code that isn't a runnable app: respond normally and do not create files. When it's unclear whether the user actually wants an app built, ask instead of building.
14701
+
14702
+ Once the user HAS given an explicit build instruction, you are in App Builder mode: you produce polished, production-quality React apps that feel designed \u2014 not generic.
14703
+
14704
+ DESIGN: on the initial build, before writing code, briefly state (2-3 sentences) what you want this app to feel like \u2014 name the specific fonts, the palette in hex, and one signature detail. Be concrete: "Fraunces display + Inter body + JetBrains Mono metadata, terracotta #b75432 accent on bone #f3efe6, paper-grain texture via inline SVG noise" is the kind of specificity that anchors the build. Default to nothing: don't pick "safe modern productivity" unless the brief literally asks for utilitarian. On later turns, state a design brief only when the change is visual (a restyle, new theme, or new UI); for a logic, data, or behavior-only change, skip the brief and just make the change.
14705
+
14706
+ WORKFLOW:
14707
+ 1. NEVER output code as text or markdown. ALWAYS use tools.
14708
+ 2. Initial build: state your design brief, then create_file with a "files" array writing ALL files in one call. The preview renders automatically.
14709
+ 3. patch_file requires read_file for that path earlier in the conversation (or create_file in the same conversation, which counts). read_file output is numbered "42: <text>" \u2014 the prefix is display-only; never copy it into "find". Each "find" must match exactly one location \u2014 include 2-3 lines of surrounding context. Pass multiple patches per call to change distinct locations.
14710
+ 4. Prefer patch_file for changes to existing files \u2014 surgical, reviewable, preserves surrounding code. Reserve create_file overwrites for substantial restructuring. Inserts: find the line before, replace with that line + the new line. Deletes: empty replace.
14711
+ 5. After substantial changes, call critique_design first (taste, hierarchy, distinctiveness, weakest decision) and then audit_design (mechanical: tokens, focus states, aria-labels, alt, heading order). Patch what each surfaces. critique catches taste issues no checklist would; audit catches mechanics you'd miss. Run both; act on both.
14712
+ 6. Before declaring done, call verify_app. The host's preview runtime reports whether your app actually mounted and surfaces any errors it captured \u2014 hallucinated imports, syntax the bundler rejected, undefined components, runtime crashes. If \`rendered\` is false or \`errors\` is non-empty, fix every error before the next message. If the response includes a \`note\` that verify_app isn't wired in this host, skip \u2014 audit + critique are your feedback in that case.
14713
+ 7. Keep responses to a sentence or two. Exception: when responding to critique_design, write a substantive paragraph per rubric question.
14714
+
14715
+ STRUCTURE:
14716
+ - App.js: default-export React component. For non-trivial apps, define small co-located helpers (Header, CardList, Card, EditDialog, \u2026) above the default export rather than one giant App.
14717
+ - App.css: all styles, imported in App.js. No inline style objects.
14718
+ - package.json: list ALL imported packages including react. No CDN script tags. Versions are auto-pinned.
14719
+ - Do NOT create index.js or index.html (auto-generated).
14720
+
14721
+ STATE & PERSISTENCE:
14722
+ - The code runs in the user's browser \u2014 standard browser APIs available (localStorage, URL hash, Date, fetch).
14723
+ - Persist user-created data (todos, cards, notes, settings) with localStorage so it survives refresh. Use a versioned key ("kanban.v1") and JSON.parse inside try/catch on read.
14724
+ - Treat persisted data as untrusted and possibly stale: a saved record may predate a field you just added (a timestamp, id, or setting), so default-fill or skip missing fields on read \u2014 never assume a loaded record has every field the current code expects. Bump the key version when the shape changes.
14725
+ - Lift state to App when multiple children need it; keep it local otherwise. Extract non-trivial logic into custom hooks (useTodos, useTimer).
14726
+ - useReducer for state shapes with several interrelated fields (cards + columns + filters + drag state).
14727
+
14728
+ FILE & IMAGE UPLOAD:
14729
+ - Picker: \`<input type="file" accept="image/*" multiple>\` (vary accept by use case: \`.csv,text/csv\`, \`.txt,.md,text/plain\`, etc.).
14730
+ - Drag-and-drop: call \`e.preventDefault()\` in onDragOver (otherwise drop never fires); read files from \`event.dataTransfer.files\`. Drop and picker should coexist.
14731
+ - Previews: \`<img src={URL.createObjectURL(file)} />\`. Call \`URL.revokeObjectURL\` on unmount or before replacing \u2014 otherwise the browser leaks memory.
14732
+ - localStorage cannot hold large binary. Persist only metadata for big files; re-upload on next visit (or use IndexedDB if you really need durable binary storage).
14733
+ - Validate size and type before processing; reject files larger than the app can hold in memory.
14734
+
14735
+ AI CAPABILITIES \u2014 \`window.app.complete(prompt: string): Promise<string>\` is available in this environment. Build for the real call.
14736
+ - When the app's core purpose is conversation, generation, grading, recommendation, or any natural-language task, this IS the implementation \u2014 call it. NEVER fake it: no hardcoded or canned replies, no random or \`setTimeout\` "thinking", no demo-mode stub. A chat app, tutor, or assistant that doesn't call \`window.app.complete\` is wrong, not a placeholder.
14737
+ - Don't force it where it isn't needed \u2014 a calculator, todo list, or timer has no reason to call it. Match the implementation to what the app actually does.
14738
+ - Async: wrap in try/catch, show a loading state, and disable dependent inputs while waiting. Surface failures gracefully ("Couldn't reach the AI \u2014 try again").
14739
+ - Structure prompts with clear sections (Role / Context / Task / Format) and pass the relevant state (e.g. the running conversation) as context. Render the response as untrusted text: \`white-space: pre-wrap\`, never dangerouslySetInnerHTML.
14740
+ - Skip the call only when the answer is genuinely static \u2014 no language or reasoning needed. Cache repeated prompts in component state when sensible.
14741
+
14742
+ CODE QUALITY \u2014 write as a senior engineer would:
14743
+ - Handle edge cases (empty inputs, division by zero, invalid data). Show helpful error states, not crashes.
14744
+ - Never let formatting throw during render: guard \`new Date(x)\` / \`Intl\` / \`toLocaleString\` / \`.toFixed\` against missing or invalid values (e.g. \`Number.isNaN(d.getTime())\`) and return a fallback \u2014 one bad value from storage or state must not blank the whole app.
14745
+ - Semantic HTML: real headings, labels, buttons (not divs with onClick), form elements.
14746
+ - Accessible: aria-labels on icon buttons, focus-visible styles, keyboard navigable.
14747
+ - Extract into custom hooks or helpers when a component grows past ~80 lines.
14748
+
14749
+ STYLING \u2014 Tailwind is the CHASSIS, custom CSS carries the IDENTITY:
14750
+ - Tailwind (via Play CDN) for layout, spacing, state (hover/focus), responsive prefixes \u2014 uniform structure.
14751
+ - App.css carries the identity: @import the Google Fonts, declare CSS custom properties (--bg, --panel, --card, --ink, --muted, --accent, --hairline, --radius, --radius-sm, --shadow-card, --shadow-card-hi) in :root, gradients/textures/signature animations Tailwind can't express. Reference tokens from Tailwind via arbitrary values (\`className="bg-[var(--bg)]"\`) when needed. A well-designed app has 60-200 lines of App.css \u2014 not zero.
14752
+ - Modern CSS is how apps stop reading as generic-AI-output: \`color-mix(in oklab, var(--accent) 14%, transparent)\` for tinting, \`oklch()\` / \`oklab()\` for perceptually-uniform color, \`:has()\`, \`conic-gradient\` / \`radial-gradient\`, \`backdrop-filter\`, \`@container\` queries, inline SVG \`feTurbulence\` for texture.
14753
+ - Don't pull additional CSS frameworks. Tailwind + custom CSS is enough.
14754
+
14755
+ VISUAL DESIGN \u2014 every app should look like a real product, not a wireframe:
14756
+ - Let the chosen aesthetic drive every decision. "Editorial" wants italic display type and restrained color; "retro arcade" wants chunky shadows and saturated gradients. No safe-modern defaults.
14757
+ - Atmospheric depth: subtle radial wash, paper grain (inline SVG noise), warm/cool tint \u2014 every canvas should feel like a designed space, not a #fff rectangle.
14758
+ - Three shadow tiers (rest / hover / active). Pair drop shadows with inset highlights (\`box-shadow: 0 1px 0 rgba(255,255,255,.9) inset, 0 6px 14px -10px ...\`) for tactile feel.
14759
+ - Typography hierarchy: display font for headlines (italic accents on key words via \`<em>\`), body font for content, mono for metadata/labels \u2014 different families telegraph different information types.
14760
+ - Interactive polish: hover/active/focus on every clickable element, 200-300ms cubic-bezier transitions, keyboard shortcuts where natural (Esc to cancel, Cmd/Ctrl+Enter to commit), focus-visible rings keyed to the accent.
14761
+ - Light/dark mode if reasonable: a single CSS variable inversion under \`[data-theme="dark"]\`.
14762
+ - Customization affordance for multi-session apps: small "Tweaks" panel with theme / density / accent. Skip for throwaway demos.
14763
+ - Responsive: Tailwind responsive prefixes (\`sm:\`, \`md:\`, \`lg:\`) and \`@media\` in App.css. Mobile-first.`;
14764
+
14765
+ // src/tools/document/documentBuilderPrompt.ts
14766
+ var DOCUMENT_BUILDER_PROMPT = `Document tools (create_document, read_document, patch_document) are available this turn, but they are OPTIONAL \u2014 having them does not mean you should produce a document.
14767
+
14768
+ Use them ONLY when the user explicitly asks you to draft, write, compose, or generate a document \u2014 a contract, agreement, NDA, letter, cover letter, memo, essay, report, brief, proposal, or resume \u2014 e.g. "draft me a service agreement", "write a cover letter for this job", "make a one-page memo about X". A bare topic, a question, a request for an explanation, or a request for a slide deck or an interactive app is NOT a document instruction: respond normally and do not call these tools. When it's unclear whether the user wants a finished document, ask instead.
14769
+
14770
+ When you DO author a document, the document body goes entirely into the tool \u2014 NEVER write the document text as chat prose. The tool renders your source to a real, paginated PDF and attaches it to your reply automatically. AFTER the tool returns, briefly confirm in ONE short sentence what you made (e.g. "Drafted a cover letter for the product manager role \u2014 see the attached PDF."). Do not restate the document's contents.
14771
+
14772
+ AUTHORING \u2014 write the "source" as a single @react-pdf/renderer JSX expression (this is react-pdf, NOT HTML and NOT a slide deck):
14773
+ - Root is exactly one <Document> with at least one <Page>. Its only children are <Page> elements. Add more <Page> elements for longer documents \u2014 react-pdf also paginates overflow automatically.
14774
+ - Inside a <Page>: use <View> as flex containers and <Text> for ALL text. Raw text is only allowed inside <Text> (and <Link>); a <View> or <Page> may not contain bare text.
14775
+ - <Text> may nest <Text>, <Link>, or <Note> for inline styling, hyperlinks, and (rarely) a PDF comment annotation. A <Link> src must be an ordinary web link \u2014 http(s), mailto, tel, or a relative/anchor link; javascript:/data:/file: links are rejected. <Image> is self-closing and its src MUST be an inline "data:" URI \u2014 remote image URLs are rejected for privacy. Vector primitives (<Rect>/<Circle>/<Path>/etc.) must live inside an <Svg>.
14776
+ - Styling is react-pdf style objects only: style={{ marginTop: 12, fontSize: 11, fontFamily: "Times-Roman", flexDirection: "column" }}. Flexbox only \u2014 there is NO CSS grid, float, or box-shadow. Use camelCase react-pdf keys (margin/padding, flex*, width/height, color/backgroundColor, border*, text*, etc.).
14777
+ - fontFamily must be a built-in PDF font: Helvetica, Times-Roman, or Courier (with -Bold / -Oblique / -Italic / -BoldOblique variants), or Symbol / ZapfDingbats. Custom fonts are not supported.
14778
+ - LITERAL VALUES ONLY: no variables, no JS expressions, no .map(), no event handlers (onClick, \u2026), no spreads. Every attribute is a literal string, number, boolean, or a style object of literals.
14779
+
14780
+ A minimal example:
14781
+
14782
+ <Document>
14783
+ <Page size="A4" style={{ paddingVertical: 56, paddingHorizontal: 64, fontFamily: "Times-Roman", fontSize: 11, lineHeight: 1.5 }}>
14784
+ <Text style={{ fontSize: 18, fontFamily: "Times-Bold", marginBottom: 16, textAlign: "center" }}>MUTUAL NON-DISCLOSURE AGREEMENT</Text>
14785
+ <Text style={{ marginBottom: 10 }}>This Mutual Non-Disclosure Agreement (the "Agreement") is entered into as of the date of last signature below.</Text>
14786
+ <View style={{ marginTop: 14 }}>
14787
+ <Text style={{ fontFamily: "Times-Bold", marginBottom: 4 }}>1. Confidential Information</Text>
14788
+ <Text>Each party may disclose certain confidential and proprietary information to the other party.</Text>
14789
+ </View>
14790
+ </Page>
14791
+ </Document>
14792
+
14793
+ WORKFLOW:
14794
+ 1. To create or fully restructure a document, call create_document with the complete source.
14795
+ 2. To revise an existing document, call read_document first (its output is line-numbered "42: <text>" \u2014 the prefix is display-only, never copy it into a "find"), then patch_document with small find/replace edits. Each "find" must match exactly one location; add 2-3 lines of surrounding context if needed. Prefer patching over rewriting.
14796
+ 3. To attach several separate documents in one reply, call create_document multiple times with distinct documentId slugs (e.g. "nda", "cover-letter"). Each renders to its own PDF.
14797
+ 4. If a tool reports a DSL error (with line:col) or a render failure, fix the source and retry \u2014 do not give up or fall back to writing the document as chat text.`;
14798
+
14647
14799
  // src/lib/tools/serverTools.ts
14648
14800
  init_logger();
14649
14801
  init_vector();
14650
14802
  var DEFAULT_CACHE_EXPIRATION_MS = 24 * 60 * 60 * 1e3;
14651
14803
  var SERVER_TOOLS_CACHE_KEY = "sdk_server_tools_cache";
14652
14804
  var CACHE_VERSION = "1.3";
14805
+ var MIN_CONTENT_LENGTH_FOR_TOOLS = 5;
14806
+ var MAX_CLIENT_TOOLS_AFTER_FILTER = 10;
14807
+ var CLIENT_TOOLS_MIN_SIMILARITY = 0.53;
14808
+ var CLIENT_TOOLS_RELEVANCE_RATIO = 0.75;
14653
14809
  function isNewToolFormat(tool) {
14654
14810
  return "schema" in tool && tool.schema !== void 0;
14655
14811
  }
@@ -14709,7 +14865,7 @@ function getCachedServerTools() {
14709
14865
  if (!cached) return null;
14710
14866
  const parsed = JSON.parse(cached);
14711
14867
  if (parsed.version !== CACHE_VERSION) {
14712
- clearServerToolsCache();
14868
+ removeLocalStorageCache();
14713
14869
  return null;
14714
14870
  }
14715
14871
  return parsed;
@@ -14721,24 +14877,46 @@ function isCacheExpired(cache, expirationMs = DEFAULT_CACHE_EXPIRATION_MS) {
14721
14877
  if (!cache) return true;
14722
14878
  return Date.now() - cache.timestamp > expirationMs;
14723
14879
  }
14724
- function cacheServerTools(tools, checksum) {
14725
- if (typeof localStorage === "undefined") return;
14726
- const cacheData = {
14880
+ function buildCacheEntry(tools, checksum) {
14881
+ return {
14727
14882
  tools,
14728
14883
  timestamp: Date.now(),
14729
14884
  version: CACHE_VERSION,
14730
14885
  ...checksum && { checksum }
14731
14886
  };
14887
+ }
14888
+ function writeLocalStorageCache(entry) {
14889
+ if (typeof localStorage === "undefined") return;
14732
14890
  try {
14733
- localStorage.setItem(SERVER_TOOLS_CACHE_KEY, JSON.stringify(cacheData));
14891
+ localStorage.setItem(SERVER_TOOLS_CACHE_KEY, JSON.stringify(entry));
14734
14892
  } catch (error) {
14735
14893
  getLogger().warn("[serverTools] Failed to cache tools:", error);
14736
14894
  }
14737
14895
  }
14738
- function clearServerToolsCache() {
14896
+ function removeLocalStorageCache() {
14739
14897
  if (typeof localStorage === "undefined") return;
14740
14898
  localStorage.removeItem(SERVER_TOOLS_CACHE_KEY);
14741
14899
  }
14900
+ var localStorageToolsCache = {
14901
+ get: getCachedServerTools,
14902
+ set: writeLocalStorageCache,
14903
+ clear: removeLocalStorageCache
14904
+ };
14905
+ function clearServerToolsCache(cache = localStorageToolsCache) {
14906
+ return cache.clear?.();
14907
+ }
14908
+ function getToolsChecksum2(cache = localStorageToolsCache) {
14909
+ const cached = cache.get();
14910
+ return cached instanceof Promise ? cached.then((c) => c?.checksum) : cached?.checksum;
14911
+ }
14912
+ function shouldRefreshTools(responseChecksum, cache = localStorageToolsCache) {
14913
+ if (!responseChecksum) {
14914
+ return false;
14915
+ }
14916
+ const decide = (cachedChecksum2) => !cachedChecksum2 || cachedChecksum2 !== responseChecksum;
14917
+ const cachedChecksum = getToolsChecksum2(cache);
14918
+ return cachedChecksum instanceof Promise ? cachedChecksum.then(decide) : decide(cachedChecksum);
14919
+ }
14742
14920
  async function fetchServerToolsFromApi(baseUrl, token) {
14743
14921
  const response = await fetch(`${baseUrl}/api/v1/tools`, {
14744
14922
  method: "GET",
@@ -14759,9 +14937,23 @@ async function getServerTools(options) {
14759
14937
  cacheExpirationMs = DEFAULT_CACHE_EXPIRATION_MS,
14760
14938
  forceRefresh = false,
14761
14939
  getToken,
14762
- apiKey
14940
+ apiKey,
14941
+ cache = localStorageToolsCache
14763
14942
  } = options;
14764
- const cached = getCachedServerTools();
14943
+ const persistCache = async (entry) => {
14944
+ try {
14945
+ await cache.set(entry);
14946
+ } catch (error) {
14947
+ getLogger().warn("[serverTools] Cache write failed (non-fatal):", error);
14948
+ }
14949
+ };
14950
+ let rawCached = null;
14951
+ try {
14952
+ rawCached = await cache.get();
14953
+ } catch (error) {
14954
+ getLogger().warn("[serverTools] Cache read failed; falling through to server fetch:", error);
14955
+ }
14956
+ const cached = rawCached && rawCached.version === CACHE_VERSION ? rawCached : null;
14765
14957
  const cacheValid = !isCacheExpired(cached, cacheExpirationMs);
14766
14958
  if (cached && cacheValid && !forceRefresh) {
14767
14959
  return cached.tools;
@@ -14782,7 +14974,7 @@ async function getServerTools(options) {
14782
14974
  }
14783
14975
  const data = await response.json();
14784
14976
  const { tools: tools2, checksum: checksum2 } = convertServerToolsResponse(data);
14785
- cacheServerTools(tools2, checksum2);
14977
+ await persistCache(buildCacheEntry(tools2, checksum2));
14786
14978
  return tools2;
14787
14979
  }
14788
14980
  if (!getToken) {
@@ -14795,7 +14987,7 @@ async function getServerTools(options) {
14795
14987
  return cached?.tools ?? [];
14796
14988
  }
14797
14989
  const { tools, checksum } = await fetchServerToolsFromApi(effectiveBaseUrl, token);
14798
- cacheServerTools(tools, checksum);
14990
+ await persistCache(buildCacheEntry(tools, checksum));
14799
14991
  return tools;
14800
14992
  } catch (error) {
14801
14993
  getLogger().error("[serverTools] Failed to fetch server tools:", error);
@@ -15011,6 +15203,158 @@ function scoreTools(promptEmbeddings, tools) {
15011
15203
  }
15012
15204
  return scores;
15013
15205
  }
15206
+ var BUILT_IN_TOOL_SETS = [
15207
+ {
15208
+ name: "app-generation",
15209
+ // Appended to the base prompt (not replacing it) whenever this set
15210
+ // activates, so the App Builder guidance — including the window.app.complete
15211
+ // runtime-AI contract — rides in with the app-gen tools via the same
15212
+ // semantic selection that includes them. Collected by toolSetSystemPrompts.
15213
+ systemPrompt: APP_BUILDER_PROMPT,
15214
+ // Must stay in sync with APP_FILE_TOOL_NAMES in src/tools/appGeneration.ts.
15215
+ // If a new app-gen tool ships there but isn't added here, semantic
15216
+ // selection will exclude it on every request — the model literally
15217
+ // doesn't see it. The quality tools (audit_design / critique_design /
15218
+ // verify_app) are non-obvious to a user prompt ("build me a kanban")
15219
+ // and rely entirely on set expansion to reach the model.
15220
+ members: [
15221
+ "create_file",
15222
+ "patch_file",
15223
+ "delete_file",
15224
+ "read_file",
15225
+ "list_files",
15226
+ "audit_design",
15227
+ "critique_design",
15228
+ "verify_app"
15229
+ ],
15230
+ // Anchors stay limited to the primary entry-point tools. Users phrase
15231
+ // app intent as "build / make / fix" → semantic match on create_file
15232
+ // or patch_file → full set pulled in. The quality tools fire later in
15233
+ // the workflow and don't anchor on their own; including them as
15234
+ // anchors would risk pulling the set in on unrelated "audit my code"
15235
+ // prompts that have nothing to do with app generation.
15236
+ anchors: ["create_file", "patch_file"],
15237
+ // 0.55: above the global filter floor (0.53) so a barely-relevant match
15238
+ // can't pull in the whole toolkit, but no higher — and we tried higher.
15239
+ // create_file scores chitchat ("what's up" ~0.56, "...about programming"
15240
+ // ~0.57) in the SAME band as legitimate app-EDIT prompts: "Edit the app to
15241
+ // change the background…" measured create_file 0.56 on one e2e run. Raising
15242
+ // the floor to 0.575 to exclude the chitchat therefore also stripped the
15243
+ // file tools from real edit requests — leaving the model unable to touch the
15244
+ // app at all. The bands genuinely overlap; there is no clean cut. So we keep
15245
+ // 0.55 (max recall) and rely on two safety nets instead: APP_BUILDER_PROMPT
15246
+ // is conditional (it no-ops unless the user is actually asking for an app),
15247
+ // and very short greetings ("hey") are filtered out earlier by the
15248
+ // MIN_CONTENT_LENGTH_FOR_TOOLS length gate before embeddings even run.
15249
+ anchorMinSimilarity: 0.55
15250
+ },
15251
+ {
15252
+ name: "slides",
15253
+ members: ["plan_deck", "add_slide", "read_slides", "patch_slides"],
15254
+ anchors: ["plan_deck", "patch_slides"],
15255
+ // Match the client-tool floor (0.53). Short colloquial prompts like
15256
+ // "make me a powerpoint about X" score plan_deck around 0.535 — above
15257
+ // the global floor but inside any anchor gap. plan_deck and patch_slides
15258
+ // are specific enough names that 0.53 won't false-positive in practice.
15259
+ anchorMinSimilarity: 0.53
15260
+ },
15261
+ {
15262
+ name: "documents",
15263
+ // Conditional rider (no-ops unless the user actually asks for a document),
15264
+ // attached so the Document Builder guidance rides in with the document
15265
+ // tools via the same semantic selection that includes them.
15266
+ systemPrompt: DOCUMENT_BUILDER_PROMPT,
15267
+ members: ["create_document", "read_document", "patch_document"],
15268
+ // Entry-point tools anchor; read_document rides in via set expansion.
15269
+ anchors: ["create_document", "patch_document"],
15270
+ // 0.53: match the client-tool floor. "draft me a contract", "write a cover
15271
+ // letter", "make a memo" should pull the set in. Like app-gen's create_file,
15272
+ // document intent ("write me X") overlaps generic chitchat in this band, so
15273
+ // the same two safety nets apply: DOCUMENT_BUILDER_PROMPT is conditional and
15274
+ // the MIN_CONTENT_LENGTH_FOR_TOOLS gate drops bare greetings before
15275
+ // embeddings run. Tune empirically against the tool-selection parity suite.
15276
+ anchorMinSimilarity: 0.53
15277
+ },
15278
+ {
15279
+ name: "github",
15280
+ members: ["github_get_authenticated_user", "github_api"],
15281
+ anchors: ["github_api"],
15282
+ anchorMinSimilarity: 0.55
15283
+ },
15284
+ // Connector sets (#587). Connector chat tools belong to no set, so per-message
15285
+ // semantic filtering silently prunes them on vague prompts ("check my email").
15286
+ // Grouping each connector's tools behind a search/action anchor keeps the
15287
+ // whole connector reachable once any one of its tools matches. Mirrors github:
15288
+ // no systemPrompt rider — per-set prompt guidance is a follow-up.
15289
+ {
15290
+ name: "gmail",
15291
+ members: [
15292
+ "gmail_search_messages",
15293
+ "gmail_get_message",
15294
+ "gmail_create_draft",
15295
+ "gmail_send_message"
15296
+ ],
15297
+ anchors: ["gmail_search_messages", "gmail_send_message"],
15298
+ anchorMinSimilarity: 0.53
15299
+ },
15300
+ {
15301
+ name: "google-calendar",
15302
+ members: [
15303
+ "google_calendar_list_events",
15304
+ "google_calendar_create_event",
15305
+ "google_calendar_update_event"
15306
+ ],
15307
+ anchors: ["google_calendar_list_events", "google_calendar_create_event"],
15308
+ anchorMinSimilarity: 0.53
15309
+ },
15310
+ {
15311
+ name: "google-drive",
15312
+ members: [
15313
+ "google_drive_search",
15314
+ "google_drive_list_recent",
15315
+ "google_drive_get_content",
15316
+ "google_drive_create_file",
15317
+ "google_drive_update_file"
15318
+ ],
15319
+ anchors: ["google_drive_search", "google_drive_get_content", "google_drive_create_file"],
15320
+ anchorMinSimilarity: 0.53
15321
+ },
15322
+ {
15323
+ name: "notion",
15324
+ members: ["notion-search", "notion-fetch", "notion-create-pages", "notion-update-page"],
15325
+ anchors: ["notion-search", "notion-create-pages"],
15326
+ anchorMinSimilarity: 0.53
15327
+ },
15328
+ {
15329
+ name: "x",
15330
+ members: ["x_get_me", "x_get_my_posts"],
15331
+ anchors: ["x_get_me", "x_get_my_posts"],
15332
+ anchorMinSimilarity: 0.53
15333
+ },
15334
+ {
15335
+ name: "slack",
15336
+ members: [
15337
+ "slack_get_me",
15338
+ "slack_list_channels",
15339
+ "slack_search_messages",
15340
+ "slack_list_users",
15341
+ "slack_get_channel_history",
15342
+ "slack_get_thread_replies",
15343
+ "slack_post_message"
15344
+ ],
15345
+ // search is the primary entry point; list_channels also anchors so "what
15346
+ // channels am I in" reaches the set without going through search. post_message
15347
+ // anchors too so post-only prompts surface the write tool past the cutoff.
15348
+ anchors: ["slack_search_messages", "slack_list_channels", "slack_post_message"],
15349
+ anchorMinSimilarity: 0.53
15350
+ },
15351
+ {
15352
+ name: "dropbox",
15353
+ members: ["dropbox_list_folders", "dropbox_get_file_content", "dropbox_search"],
15354
+ anchors: ["dropbox_list_folders", "dropbox_search"],
15355
+ anchorMinSimilarity: 0.53
15356
+ }
15357
+ ];
15014
15358
  function expandToolSetsAdditive(matchedNames, availableNames, scores, toolSets, activeSetNames) {
15015
15359
  const result = new Set(matchedNames);
15016
15360
  for (const ts of toolSets) {
@@ -15028,6 +15372,35 @@ function expandToolSetsAdditive(matchedNames, availableNames, scores, toolSets,
15028
15372
  }
15029
15373
  return result;
15030
15374
  }
15375
+ function activatedToolSetNames(scores, toolSets = BUILT_IN_TOOL_SETS, activeSetNames) {
15376
+ const activated = /* @__PURE__ */ new Set();
15377
+ for (const ts of toolSets) {
15378
+ if (activeSetNames?.has(ts.name)) {
15379
+ activated.add(ts.name);
15380
+ continue;
15381
+ }
15382
+ const minSim = ts.anchorMinSimilarity ?? 0.6;
15383
+ if (ts.anchors.some((a) => (scores.get(a) ?? 0) >= minSim)) {
15384
+ activated.add(ts.name);
15385
+ }
15386
+ }
15387
+ return activated;
15388
+ }
15389
+ function toolSetSystemPrompts(selectedToolNames, toolSets = BUILT_IN_TOOL_SETS, activatedSetNames) {
15390
+ const selected = selectedToolNames instanceof Set ? selectedToolNames : new Set(selectedToolNames);
15391
+ const prompts = [];
15392
+ const seen = /* @__PURE__ */ new Set();
15393
+ for (const ts of toolSets) {
15394
+ const prompt = ts.systemPrompt;
15395
+ if (!prompt || seen.has(prompt)) continue;
15396
+ const active = activatedSetNames ? activatedSetNames.has(ts.name) : ts.anchors.some((anchor) => selected.has(anchor));
15397
+ if (active) {
15398
+ prompts.push(prompt);
15399
+ seen.add(prompt);
15400
+ }
15401
+ }
15402
+ return prompts;
15403
+ }
15031
15404
  function createServerToolsFilter(options = {}) {
15032
15405
  const exclude = new Set(options.excludeTools ?? []);
15033
15406
  const sets = options.toolSets ?? [];
@@ -15112,11 +15485,129 @@ var defaultServerToolsFilter = createServerToolsFilter({
15112
15485
  toolSets: SERVER_TOOL_DEPENDENCY_SETS
15113
15486
  });
15114
15487
 
15488
+ // src/lib/tools/clientToolSelection.ts
15489
+ function getToolName2(t) {
15490
+ const fn = t.function;
15491
+ return fn?.name || t.name || "";
15492
+ }
15493
+ function getToolDescription(t) {
15494
+ const fn = t.function;
15495
+ return fn?.description || t.description || getToolName2(t);
15496
+ }
15497
+ function computeToolGuidance(selectedServerTools, selectedClientTools, extraToolSets, activatedSetNames) {
15498
+ const names = [
15499
+ ...selectedServerTools.map((t) => t.name),
15500
+ ...(selectedClientTools ?? []).map(getToolName2)
15501
+ ].filter(Boolean);
15502
+ const toolSets = extraToolSets.length > 0 ? [...BUILT_IN_TOOL_SETS, ...extraToolSets] : BUILT_IN_TOOL_SETS;
15503
+ const prompts = toolSetSystemPrompts(names, toolSets, activatedSetNames);
15504
+ return prompts.length > 0 ? prompts.join("\n\n") : void 0;
15505
+ }
15506
+ async function autoFilterClientTools(clientTools, promptEmbeddings, cache, embeddingOptions, extraToolSets = [], activeToolSets = [], noEmbeddingsReason = "short-prompt") {
15507
+ const isMemoryTool = (t) => {
15508
+ const name = getToolName2(t);
15509
+ return name.startsWith("memory_vault_") || name === RECALL_TOOL_NAME;
15510
+ };
15511
+ const alwaysInclude = clientTools.filter(isMemoryTool);
15512
+ const filterCandidates = clientTools.filter((t) => !isMemoryTool(t));
15513
+ if (filterCandidates.length === 0) {
15514
+ return { tools: clientTools, activatedSetNames: /* @__PURE__ */ new Set() };
15515
+ }
15516
+ if (!promptEmbeddings && noEmbeddingsReason === "error") {
15517
+ return { tools: clientTools, activatedSetNames: /* @__PURE__ */ new Set() };
15518
+ }
15519
+ if (!promptEmbeddings) {
15520
+ if (activeToolSets.length === 0) {
15521
+ return { tools: [], activatedSetNames: /* @__PURE__ */ new Set() };
15522
+ }
15523
+ const allSets = extraToolSets.length > 0 ? [...BUILT_IN_TOOL_SETS, ...extraToolSets] : BUILT_IN_TOOL_SETS;
15524
+ const activeSets = allSets.filter((s) => activeToolSets.includes(s.name));
15525
+ const stickyMembers = new Set(activeSets.flatMap((s) => s.members));
15526
+ return {
15527
+ tools: [
15528
+ ...alwaysInclude,
15529
+ ...filterCandidates.filter((t) => stickyMembers.has(getToolName2(t)))
15530
+ ],
15531
+ activatedSetNames: new Set(activeSets.map((s) => s.name))
15532
+ };
15533
+ }
15534
+ const toolsNeedingEmbeddings = [];
15535
+ for (const t of filterCandidates) {
15536
+ const name = getToolName2(t);
15537
+ if (name && !cache.has(name)) {
15538
+ toolsNeedingEmbeddings.push({ name, description: getToolDescription(t) });
15539
+ }
15540
+ }
15541
+ if (toolsNeedingEmbeddings.length > 0) {
15542
+ try {
15543
+ const descriptions = toolsNeedingEmbeddings.map((t) => t.description);
15544
+ const embeddings = await generateEmbeddings(descriptions, embeddingOptions);
15545
+ for (let i = 0; i < toolsNeedingEmbeddings.length; i++) {
15546
+ cache.set(toolsNeedingEmbeddings[i].name, embeddings[i]);
15547
+ }
15548
+ } catch {
15549
+ return { tools: clientTools, activatedSetNames: /* @__PURE__ */ new Set() };
15550
+ }
15551
+ }
15552
+ const pseudoServerTools = [];
15553
+ for (const t of filterCandidates) {
15554
+ const name = getToolName2(t);
15555
+ const embedding = cache.get(name);
15556
+ if (!embedding) continue;
15557
+ const fn = t.function;
15558
+ const params = fn?.parameters || fn?.arguments || {
15559
+ type: "object",
15560
+ properties: {},
15561
+ required: []
15562
+ };
15563
+ pseudoServerTools.push({
15564
+ type: "function",
15565
+ name,
15566
+ description: getToolDescription(t),
15567
+ parameters: params,
15568
+ embedding
15569
+ });
15570
+ }
15571
+ const matches = findMatchingTools(promptEmbeddings, pseudoServerTools, {
15572
+ limit: MAX_CLIENT_TOOLS_AFTER_FILTER,
15573
+ minSimilarity: CLIENT_TOOLS_MIN_SIMILARITY,
15574
+ filterAmbiguous: true,
15575
+ // See CLIENT_TOOLS_RELEVANCE_RATIO: 0.75 admits the second intent of a
15576
+ // multi-intent prompt (which lands ~75-80% of the dominant match), while
15577
+ // still trimming the loose tail. The earlier 0.9 made a second intent
15578
+ // structurally unselectable; the anchorMinSimilarity gates (0.53-0.55)
15579
+ // remain the guard against borderline anchors activating a whole set.
15580
+ relevanceRatio: CLIENT_TOOLS_RELEVANCE_RATIO
15581
+ });
15582
+ const matchedNames = new Set(matches.map((m) => m.tool.name));
15583
+ const scores = scoreTools(promptEmbeddings, pseudoServerTools);
15584
+ const availableNames = new Set(filterCandidates.map(getToolName2));
15585
+ const toolSets = extraToolSets.length > 0 ? [...BUILT_IN_TOOL_SETS, ...extraToolSets] : BUILT_IN_TOOL_SETS;
15586
+ const activeSetNames = activeToolSets.length > 0 ? new Set(activeToolSets) : void 0;
15587
+ const finalNames = expandToolSetsAdditive(
15588
+ matchedNames,
15589
+ availableNames,
15590
+ scores,
15591
+ toolSets,
15592
+ activeSetNames
15593
+ );
15594
+ const activatedSetNames = activatedToolSetNames(scores, toolSets, activeSetNames);
15595
+ if (finalNames.size === 0) {
15596
+ return { tools: alwaysInclude, activatedSetNames };
15597
+ }
15598
+ const filtered = filterCandidates.filter((t) => {
15599
+ const name = getToolName2(t);
15600
+ return name && finalNames.has(name);
15601
+ });
15602
+ return { tools: [...alwaysInclude, ...filtered], activatedSetNames };
15603
+ }
15604
+
15115
15605
  // src/expo/useChatStorage.ts
15116
15606
  init_useEncryption();
15117
15607
  var CONVERSATION_REDACTOR_LIMIT = 50;
15118
15608
  var NO_CONVERSATION_KEY = "__no_conversation__";
15119
15609
  var conversationRedactors = /* @__PURE__ */ new Map();
15610
+ var clientToolFilterCache = /* @__PURE__ */ new Map();
15120
15611
  function getConversationRedactor(conversationId, nerDetector) {
15121
15612
  const key = conversationId ?? NO_CONVERSATION_KEY;
15122
15613
  const cached = conversationRedactors.get(key);
@@ -15232,6 +15723,8 @@ function useChatStorage(options) {
15232
15723
  getWalletAddress,
15233
15724
  enableQueue = true,
15234
15725
  autoFlushOnKeyAvailable = true,
15726
+ extraToolSets,
15727
+ activeToolSets,
15235
15728
  serverTools: serverToolsConfig,
15236
15729
  autoEmbedMessages = true,
15237
15730
  embeddingModel = DEFAULT_API_EMBEDDING_MODEL,
@@ -15240,6 +15733,7 @@ function useChatStorage(options) {
15240
15733
  resumable = false,
15241
15734
  onCancelResult,
15242
15735
  onStreamMeta,
15736
+ onToolSelection,
15243
15737
  piiRedaction,
15244
15738
  onPiiRedacted,
15245
15739
  nerDetector,
@@ -15454,12 +15948,24 @@ function useChatStorage(options) {
15454
15948
  if (!autoEmbedMessages || !getToken) return;
15455
15949
  if (message.content.length < minContentLength) return;
15456
15950
  try {
15457
- const embedding = await generateEmbedding(mask(message.content), {
15458
- getToken,
15459
- baseUrl,
15460
- model: embeddingModel
15461
- });
15462
- await updateMessageEmbeddingOp(storageCtx, message.uniqueId, embedding, embeddingModel);
15951
+ const opts = { getToken, baseUrl, model: embeddingModel };
15952
+ if (shouldChunkMessage(message.content, DEFAULT_CHUNK_SIZE)) {
15953
+ const textChunks = chunkText(message.content);
15954
+ const embeddings = await generateEmbeddings(
15955
+ textChunks.map((c) => mask(c.text)),
15956
+ opts
15957
+ );
15958
+ const messageChunks = textChunks.map((chunk, i) => ({
15959
+ text: chunk.text,
15960
+ vector: embeddings[i],
15961
+ startOffset: chunk.startOffset,
15962
+ endOffset: chunk.endOffset
15963
+ }));
15964
+ await updateMessageChunksOp(storageCtx, message.uniqueId, messageChunks, embeddingModel);
15965
+ } else {
15966
+ const embedding = await generateEmbedding(mask(message.content), opts);
15967
+ await updateMessageEmbeddingOp(storageCtx, message.uniqueId, embedding, embeddingModel);
15968
+ }
15463
15969
  } catch (err) {
15464
15970
  getLogger().warn("[useChatStorage] Failed to embed message:", err);
15465
15971
  }
@@ -15809,6 +16315,10 @@ function useChatStorage(options) {
15809
16315
  }
15810
16316
  throw new Error("No conversation ID provided and autoCreateConversation is disabled");
15811
16317
  }, [currentConversationId, getConversation, autoCreateConversation, createConversation]);
16318
+ const activeToolSetsRef = (0, import_react4.useRef)(activeToolSets);
16319
+ activeToolSetsRef.current = activeToolSets;
16320
+ const getTokenRef = (0, import_react4.useRef)(getToken);
16321
+ getTokenRef.current = getToken;
15812
16322
  const sendMessage = (0, import_react4.useCallback)(
15813
16323
  async (args) => {
15814
16324
  const {
@@ -15835,6 +16345,7 @@ function useChatStorage(options) {
15835
16345
  maxOutputTokens,
15836
16346
  clientTools,
15837
16347
  serverTools: serverToolsFilter,
16348
+ clientToolsFilter,
15838
16349
  toolChoice,
15839
16350
  reasoning,
15840
16351
  thinking,
@@ -15861,6 +16372,13 @@ function useChatStorage(options) {
15861
16372
  };
15862
16373
  pendingResumeRef.current = null;
15863
16374
  const effectiveAssistantUniqueId = assistantUniqueId ?? (resumable ? `msg_${(0, import_uuid5.v7)()}` : void 0);
16375
+ const embedToolText = (text12, mask, token) => {
16376
+ const opts = { getToken: token, baseUrl, model: embeddingModel };
16377
+ return shouldChunkMessage(text12, DEFAULT_CHUNK_SIZE) ? generateEmbeddings(
16378
+ chunkText(text12).map((c) => mask(c.text)),
16379
+ opts
16380
+ ) : generateEmbedding(mask(text12), opts);
16381
+ };
15864
16382
  if (walletAddress && signMessage && !hasEncryptionKey(walletAddress)) {
15865
16383
  try {
15866
16384
  await requestEncryptionKey(walletAddress, signMessage, embeddedWalletSigner);
@@ -15871,40 +16389,95 @@ function useChatStorage(options) {
15871
16389
  const effectiveApiType2 = resolveApiType(requestApiType ?? apiType ?? "auto", model);
15872
16390
  const { callPiiRedaction: callPiiRedaction2, maskForCall: maskForCall2 } = resolvePiiForCall(currentConversationId);
15873
16391
  let mergedTools2 = void 0;
15874
- let filteredServerTools = [];
16392
+ let filteredServerTools2 = [];
15875
16393
  const isServerToolsFunction2 = typeof serverToolsFilter === "function";
15876
- if (getToken && effectiveApiType2 === "responses" && !(Array.isArray(serverToolsFilter) && serverToolsFilter.length === 0)) {
16394
+ const extracted2 = extractUserMessageFromMessages(messages);
16395
+ const messageContent = resolveStoredUserContent(
16396
+ storedUserContent,
16397
+ extracted2?.content ?? ""
16398
+ );
16399
+ let skipUserEmbedding;
16400
+ let skipEmbeddingFailed = false;
16401
+ if (getTokenRef.current && effectiveApiType2 === "responses" && !(Array.isArray(serverToolsFilter) && serverToolsFilter.length === 0)) {
15877
16402
  try {
15878
16403
  const allServerTools = await getServerTools({
15879
16404
  baseUrl,
15880
16405
  cacheExpirationMs: serverToolsConfig?.cacheExpirationMs,
15881
- getToken
16406
+ getToken: getTokenRef.current,
16407
+ cache: serverToolsConfig?.cache
15882
16408
  });
15883
- if (isServerToolsFunction2) {
15884
- const extracted2 = extractUserMessageFromMessages(messages);
15885
- const messageContent = resolveStoredUserContent(
15886
- storedUserContent,
15887
- extracted2?.content ?? ""
15888
- );
15889
- if (messageContent.length >= minContentLength) {
15890
- const embedding = await generateEmbedding(maskForCall2(messageContent), {
15891
- getToken,
15892
- baseUrl,
15893
- model: embeddingModel
15894
- });
15895
- const toolNames = serverToolsFilter(embedding, allServerTools);
15896
- filteredServerTools = filterServerTools(allServerTools, toolNames);
15897
- } else {
15898
- filteredServerTools = allServerTools;
16409
+ if (serverToolsConfig?.deferLoading?.enabled) {
16410
+ filteredServerTools2 = allServerTools;
16411
+ } else if (isServerToolsFunction2) {
16412
+ if (messageContent.length >= MIN_CONTENT_LENGTH_FOR_TOOLS) {
16413
+ skipUserEmbedding = await embedToolText(
16414
+ messageContent,
16415
+ maskForCall2,
16416
+ getTokenRef.current
16417
+ );
16418
+ const toolNames = serverToolsFilter(skipUserEmbedding, allServerTools);
16419
+ filteredServerTools2 = filterServerTools(allServerTools, toolNames);
15899
16420
  }
15900
16421
  } else {
15901
- filteredServerTools = filterServerTools(allServerTools, serverToolsFilter);
16422
+ filteredServerTools2 = filterServerTools(allServerTools, serverToolsFilter);
15902
16423
  }
15903
16424
  } catch {
15904
16425
  }
15905
16426
  }
15906
- if (filteredServerTools.length > 0 || clientTools && clientTools.length > 0) {
15907
- mergedTools2 = mergeTools(filteredServerTools, clientTools, effectiveApiType2);
16427
+ let narrowedClientTools2 = clientTools;
16428
+ let clientActivatedSetNames2;
16429
+ if (clientTools?.length) {
16430
+ try {
16431
+ if (!skipUserEmbedding && getTokenRef.current && messageContent.length >= MIN_CONTENT_LENGTH_FOR_TOOLS) {
16432
+ try {
16433
+ skipUserEmbedding = await embedToolText(
16434
+ messageContent,
16435
+ maskForCall2,
16436
+ getTokenRef.current
16437
+ );
16438
+ } catch {
16439
+ skipEmbeddingFailed = true;
16440
+ }
16441
+ }
16442
+ if (typeof clientToolsFilter === "function") {
16443
+ if (!skipEmbeddingFailed) {
16444
+ const keep = new Set(clientToolsFilter(skipUserEmbedding ?? null, clientTools));
16445
+ narrowedClientTools2 = clientTools.filter((t) => keep.has(getToolName2(t)));
16446
+ }
16447
+ } else if (getTokenRef.current) {
16448
+ const { tools: autoTools, activatedSetNames } = await autoFilterClientTools(
16449
+ clientTools,
16450
+ skipUserEmbedding ?? null,
16451
+ clientToolFilterCache,
16452
+ { getToken: getTokenRef.current, baseUrl, model: embeddingModel },
16453
+ extraToolSets ?? [],
16454
+ activeToolSetsRef.current ?? [],
16455
+ skipEmbeddingFailed ? "error" : "short-prompt"
16456
+ );
16457
+ narrowedClientTools2 = autoTools;
16458
+ clientActivatedSetNames2 = activatedSetNames;
16459
+ }
16460
+ } catch (error) {
16461
+ getLogger().warn("[useChatStorage] client tool filtering failed (skipStorage):", error);
16462
+ }
16463
+ }
16464
+ if (filteredServerTools2.length > 0 || narrowedClientTools2 && narrowedClientTools2.length > 0) {
16465
+ mergedTools2 = mergeTools(
16466
+ filteredServerTools2,
16467
+ narrowedClientTools2,
16468
+ effectiveApiType2,
16469
+ serverToolsConfig?.deferLoading
16470
+ );
16471
+ }
16472
+ if (onToolSelection) {
16473
+ try {
16474
+ onToolSelection({
16475
+ prompt: messageContent,
16476
+ clientToolNames: (narrowedClientTools2 ?? []).map(getToolName2).filter(Boolean),
16477
+ serverToolNames: filteredServerTools2.map((t) => t.name)
16478
+ });
16479
+ } catch {
16480
+ }
15908
16481
  }
15909
16482
  const result2 = await baseSendMessage({
15910
16483
  messages,
@@ -15914,6 +16487,12 @@ function useChatStorage(options) {
15914
16487
  memoryContext,
15915
16488
  searchContext,
15916
16489
  fileContext,
16490
+ toolGuidance: computeToolGuidance(
16491
+ filteredServerTools2,
16492
+ narrowedClientTools2,
16493
+ extraToolSets ?? [],
16494
+ clientActivatedSetNames2
16495
+ ),
15917
16496
  temperature,
15918
16497
  maxOutputTokens,
15919
16498
  tools: mergedTools2,
@@ -15941,6 +16520,24 @@ function useChatStorage(options) {
15941
16520
  error: result2.error || "Unknown error"
15942
16521
  };
15943
16522
  }
16523
+ const skipRefreshGetToken = getTokenRef.current;
16524
+ const skipRefreshData = result2.data;
16525
+ if (skipRefreshGetToken) {
16526
+ Promise.resolve().then(
16527
+ () => shouldRefreshTools(getToolsChecksum(skipRefreshData), serverToolsConfig?.cache)
16528
+ ).then((refresh) => {
16529
+ if (refresh) {
16530
+ return getServerTools({
16531
+ baseUrl,
16532
+ getToken: skipRefreshGetToken,
16533
+ forceRefresh: true,
16534
+ cache: serverToolsConfig?.cache
16535
+ });
16536
+ }
16537
+ }).catch((err) => {
16538
+ getLogger().warn("[useChatStorage] Failed to refresh server tools cache:", err);
16539
+ });
16540
+ }
15944
16541
  return {
15945
16542
  data: result2.data,
15946
16543
  error: null,
@@ -15979,12 +16576,12 @@ function useChatStorage(options) {
15979
16576
  if (includeHistory) {
15980
16577
  const validMessages = storedMessages.filter((msg) => !msg.error);
15981
16578
  const limitedMessages = validMessages.slice(-maxHistoryMessages);
15982
- if (summarizeHistory && !getToken) {
16579
+ if (summarizeHistory && !getTokenRef.current) {
15983
16580
  getLogger().warn(
15984
16581
  "[summarize] summarizeHistory is enabled but getToken is not provided \u2014 summarization will be skipped"
15985
16582
  );
15986
16583
  }
15987
- const summaryToken = summarizeHistory && getToken ? await getToken() : null;
16584
+ const summaryToken = summarizeHistory && getTokenRef.current ? await getTokenRef.current() : null;
15988
16585
  const { messagesToConvert, summarySystemMessage } = await maybeSummarizeHistory({
15989
16586
  database,
15990
16587
  conversationId: convId,
@@ -16043,50 +16640,131 @@ function useChatStorage(options) {
16043
16640
  const effectiveApiType = resolveApiType(requestApiType ?? apiType ?? "auto", model);
16044
16641
  let mergedTools = clientTools;
16045
16642
  let userMessageEmbedding;
16643
+ let userMessageEmbeddingFailed = false;
16644
+ let filteredServerTools = [];
16046
16645
  const isServerToolsFunction = typeof serverToolsFilter === "function";
16047
- if (getToken && !(Array.isArray(serverToolsFilter) && serverToolsFilter.length === 0)) {
16646
+ if (getTokenRef.current && !(Array.isArray(serverToolsFilter) && serverToolsFilter.length === 0)) {
16048
16647
  try {
16049
16648
  const allServerTools = await getServerTools({
16050
16649
  baseUrl,
16051
16650
  cacheExpirationMs: serverToolsConfig?.cacheExpirationMs,
16052
- getToken
16651
+ getToken: getTokenRef.current,
16652
+ cache: serverToolsConfig?.cache
16053
16653
  });
16054
- let filteredServerTools;
16055
- if (isServerToolsFunction) {
16056
- if (contentForStorage.length >= minContentLength) {
16057
- userMessageEmbedding = await generateEmbedding(maskForCall(contentForStorage), {
16058
- getToken,
16059
- baseUrl,
16060
- model: embeddingModel
16061
- });
16654
+ if (serverToolsConfig?.deferLoading?.enabled && effectiveApiType === "responses") {
16655
+ filteredServerTools = allServerTools;
16656
+ } else if (isServerToolsFunction) {
16657
+ if (contentForStorage.length >= MIN_CONTENT_LENGTH_FOR_TOOLS) {
16658
+ userMessageEmbedding = await embedToolText(
16659
+ contentForStorage,
16660
+ maskForCall,
16661
+ getTokenRef.current
16662
+ );
16062
16663
  const toolNames = serverToolsFilter(userMessageEmbedding, allServerTools);
16063
16664
  filteredServerTools = filterServerTools(allServerTools, toolNames);
16064
- } else {
16065
- filteredServerTools = allServerTools;
16066
16665
  }
16067
16666
  } else {
16068
16667
  filteredServerTools = filterServerTools(allServerTools, serverToolsFilter);
16069
16668
  }
16070
16669
  if (filteredServerTools.length > 0) {
16071
- mergedTools = mergeTools(filteredServerTools, clientTools, effectiveApiType);
16670
+ mergedTools = mergeTools(
16671
+ filteredServerTools,
16672
+ clientTools,
16673
+ effectiveApiType,
16674
+ serverToolsConfig?.deferLoading
16675
+ );
16072
16676
  }
16073
16677
  } catch (error) {
16074
16678
  getLogger().warn("[useChatStorage] Failed to fetch server tools:", error);
16075
16679
  }
16076
16680
  }
16681
+ let narrowedClientTools = clientTools;
16682
+ let clientActivatedSetNames;
16683
+ if (clientTools?.length) {
16684
+ try {
16685
+ if (!userMessageEmbedding && getTokenRef.current && contentForStorage.length >= MIN_CONTENT_LENGTH_FOR_TOOLS) {
16686
+ try {
16687
+ userMessageEmbedding = await embedToolText(
16688
+ contentForStorage,
16689
+ maskForCall,
16690
+ getTokenRef.current
16691
+ );
16692
+ } catch {
16693
+ userMessageEmbeddingFailed = true;
16694
+ }
16695
+ }
16696
+ if (typeof clientToolsFilter === "function") {
16697
+ if (!userMessageEmbeddingFailed) {
16698
+ const keep = new Set(clientToolsFilter(userMessageEmbedding ?? null, clientTools));
16699
+ narrowedClientTools = clientTools.filter((t) => keep.has(getToolName2(t)));
16700
+ }
16701
+ } else if (getTokenRef.current) {
16702
+ const { tools: autoTools, activatedSetNames } = await autoFilterClientTools(
16703
+ clientTools,
16704
+ userMessageEmbedding ?? null,
16705
+ clientToolFilterCache,
16706
+ { getToken: getTokenRef.current, baseUrl, model: embeddingModel },
16707
+ extraToolSets ?? [],
16708
+ activeToolSetsRef.current ?? [],
16709
+ userMessageEmbeddingFailed ? "error" : "short-prompt"
16710
+ );
16711
+ narrowedClientTools = autoTools;
16712
+ clientActivatedSetNames = activatedSetNames;
16713
+ }
16714
+ mergedTools = filteredServerTools.length > 0 || (narrowedClientTools?.length ?? 0) > 0 ? mergeTools(
16715
+ filteredServerTools,
16716
+ narrowedClientTools,
16717
+ effectiveApiType,
16718
+ serverToolsConfig?.deferLoading
16719
+ ) : void 0;
16720
+ } catch (error) {
16721
+ getLogger().warn("[useChatStorage] client tool filtering failed:", error);
16722
+ }
16723
+ }
16077
16724
  if (!userMsgQueueId) {
16078
16725
  if (userMessageEmbedding && autoEmbedMessages) {
16079
- updateMessageEmbeddingOp(
16080
- storageCtx,
16081
- storedUserMessage.uniqueId,
16082
- userMessageEmbedding,
16083
- embeddingModel
16084
- ).catch(() => {
16085
- });
16726
+ if (Array.isArray(userMessageEmbedding[0])) {
16727
+ const textChunks = chunkText(contentForStorage);
16728
+ const messageChunks = textChunks.map((chunk, i) => ({
16729
+ text: chunk.text,
16730
+ vector: userMessageEmbedding[i],
16731
+ startOffset: chunk.startOffset,
16732
+ endOffset: chunk.endOffset
16733
+ }));
16734
+ updateMessageChunksOp(
16735
+ storageCtx,
16736
+ storedUserMessage.uniqueId,
16737
+ messageChunks,
16738
+ embeddingModel
16739
+ ).catch((err) => {
16740
+ getLogger().warn(
16741
+ "[useChatStorage] Failed to persist chunked embeddings for user message:",
16742
+ err
16743
+ );
16744
+ });
16745
+ } else {
16746
+ updateMessageEmbeddingOp(
16747
+ storageCtx,
16748
+ storedUserMessage.uniqueId,
16749
+ userMessageEmbedding,
16750
+ embeddingModel
16751
+ ).catch(() => {
16752
+ });
16753
+ }
16086
16754
  } else {
16087
16755
  void embedMessageAsync(storedUserMessage, maskForCall);
16088
16756
  }
16089
16757
  }
16758
+ if (onToolSelection) {
16759
+ try {
16760
+ onToolSelection({
16761
+ prompt: contentForStorage,
16762
+ clientToolNames: (narrowedClientTools ?? []).map(getToolName2).filter(Boolean),
16763
+ serverToolNames: filteredServerTools.map((t) => t.name)
16764
+ });
16765
+ } catch {
16766
+ }
16767
+ }
16090
16768
  const result = await baseSendMessage({
16091
16769
  messages: messagesToSend,
16092
16770
  model,
@@ -16095,6 +16773,12 @@ function useChatStorage(options) {
16095
16773
  memoryContext,
16096
16774
  searchContext,
16097
16775
  fileContext,
16776
+ toolGuidance: computeToolGuidance(
16777
+ filteredServerTools,
16778
+ narrowedClientTools,
16779
+ extraToolSets ?? [],
16780
+ clientActivatedSetNames
16781
+ ),
16098
16782
  apiType: requestApiType,
16099
16783
  // Responses API options
16100
16784
  temperature,
@@ -16296,6 +16980,21 @@ function useChatStorage(options) {
16296
16980
  userMessage: storedUserMessage
16297
16981
  };
16298
16982
  }
16983
+ const refreshGetToken = getTokenRef.current;
16984
+ if (refreshGetToken) {
16985
+ Promise.resolve().then(() => shouldRefreshTools(getToolsChecksum(responseData), serverToolsConfig?.cache)).then((refresh) => {
16986
+ if (refresh) {
16987
+ return getServerTools({
16988
+ baseUrl,
16989
+ getToken: refreshGetToken,
16990
+ forceRefresh: true,
16991
+ cache: serverToolsConfig?.cache
16992
+ });
16993
+ }
16994
+ }).catch((err) => {
16995
+ getLogger().warn("[useChatStorage] Failed to refresh server tools cache:", err);
16996
+ });
16997
+ }
16299
16998
  return {
16300
16999
  data: responseData,
16301
17000
  error: null,
@@ -19019,6 +19718,7 @@ function createNotionTools(getAccessToken, requestNotionAccess) {
19019
19718
  getConversationMemoriesOp,
19020
19719
  getConversationsByProjectLazyOp,
19021
19720
  getConversationsLazyOp,
19721
+ getConversationsPageOp,
19022
19722
  getLogger,
19023
19723
  getMemoriesNeedingTopicExtractionOp,
19024
19724
  getServerTools,