@reverbia/sdk 1.0.0-next.20251120124145 → 1.0.0-next.20251124100226

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.
@@ -45,6 +45,11 @@ function useChat(options) {
45
45
  setIsLoading(false);
46
46
  return { data: null, error };
47
47
  }
48
+ if (typeof completion.data === "string") {
49
+ const error = "API returned a string response instead of a completion object.";
50
+ setIsLoading(false);
51
+ return { data: null, error };
52
+ }
48
53
  setIsLoading(false);
49
54
  return { data: completion.data, error: null };
50
55
  } catch (err) {
@@ -60,6 +65,1428 @@ function useChat(options) {
60
65
  sendMessage
61
66
  };
62
67
  }
68
+
69
+ // src/react/useMemory.ts
70
+ import { useCallback as useCallback2, useRef } from "react";
71
+ import { postApiV1ChatCompletions as postApiV1ChatCompletions2 } from "@reverbia/sdk";
72
+
73
+ // src/lib/memory/service.ts
74
+ var FACT_EXTRACTION_PROMPT = `You are a memory extraction system. Extract durable user memories from chat messages.
75
+
76
+ CRITICAL: You MUST respond with ONLY valid JSON. No explanations, no markdown, no code blocks, just pure JSON.
77
+
78
+ Only extract facts that will be useful in future conversations, such as identity, stable preferences, ongoing projects, skills, and constraints.
79
+
80
+ Do not extract sensitive attributes, temporary things, or single-use instructions.
81
+
82
+ If there are no memories to extract, return: {"items": []}
83
+
84
+ Response format (JSON only, no other text):
85
+
86
+ {
87
+ "items": [
88
+ {
89
+ "type": "identity",
90
+ "namespace": "identity",
91
+ "key": "name",
92
+ "value": "Charlie",
93
+ "rawEvidence": "I'm Charlie",
94
+ "confidence": 0.98,
95
+ "pii": true
96
+ },
97
+ {
98
+ "type": "identity",
99
+ "namespace": "work",
100
+ "key": "company",
101
+ "value": "ZetaChain",
102
+ "rawEvidence": "called ZetaChain",
103
+ "confidence": 0.99,
104
+ "pii": false
105
+ },
106
+ {
107
+ "type": "preference",
108
+ "namespace": "answer_style",
109
+ "key": "verbosity",
110
+ "value": "concise_direct",
111
+ "rawEvidence": "I prefer concise, direct answers",
112
+ "confidence": 0.96,
113
+ "pii": false
114
+ },
115
+ {
116
+ "type": "identity",
117
+ "namespace": "timezone",
118
+ "key": "tz",
119
+ "value": "America/Los_Angeles",
120
+ "rawEvidence": "I'm in PST",
121
+ "confidence": 0.9,
122
+ "pii": false
123
+ }
124
+ ]
125
+ }`;
126
+ var preprocessMemories = (items, minConfidence = 0.6) => {
127
+ if (!items || !Array.isArray(items)) {
128
+ return [];
129
+ }
130
+ const validItems = items.filter((item) => {
131
+ if (item.namespace == null || item.key == null || item.value == null) {
132
+ console.warn(
133
+ "Dropping memory item with null/undefined namespace, key, or value:",
134
+ item
135
+ );
136
+ return false;
137
+ }
138
+ const namespace = String(item.namespace).trim();
139
+ const key = String(item.key).trim();
140
+ const value = String(item.value).trim();
141
+ if (namespace === "" || key === "" || value === "") {
142
+ console.warn(
143
+ "Dropping memory item with empty namespace, key, or value after trimming:",
144
+ item
145
+ );
146
+ return false;
147
+ }
148
+ if (typeof item.confidence !== "number" || item.confidence < minConfidence) {
149
+ console.warn(
150
+ `Dropping memory item with confidence ${item.confidence} below threshold ${minConfidence}:`,
151
+ item
152
+ );
153
+ return false;
154
+ }
155
+ return true;
156
+ });
157
+ const deduplicatedMap = /* @__PURE__ */ new Map();
158
+ for (const item of validItems) {
159
+ const uniqueKey = `${item.namespace}:${item.key}:${item.value}`;
160
+ const existing = deduplicatedMap.get(uniqueKey);
161
+ if (!existing || item.confidence > existing.confidence) {
162
+ deduplicatedMap.set(uniqueKey, item);
163
+ } else {
164
+ console.debug(
165
+ `Deduplicating memory item: keeping entry with higher confidence (${existing.confidence} > ${item.confidence})`,
166
+ { namespace: item.namespace, key: item.key, value: item.value }
167
+ );
168
+ }
169
+ }
170
+ return Array.from(deduplicatedMap.values());
171
+ };
172
+
173
+ // src/lib/memory/db.ts
174
+ import Dexie from "dexie";
175
+ var MemoryDatabase = class extends Dexie {
176
+ constructor() {
177
+ super("MemoryDatabase");
178
+ this.version(2).stores({
179
+ memories: "++id, uniqueKey, compositeKey, namespace, key, type, createdAt, updatedAt"
180
+ });
181
+ this.version(3).stores({
182
+ memories: "++id, uniqueKey, compositeKey, namespace, key, type, createdAt, updatedAt"
183
+ });
184
+ }
185
+ };
186
+ var memoryDb = new MemoryDatabase();
187
+ var saveMemory = async (memory) => {
188
+ const compositeKey = `${memory.namespace}:${memory.key}`;
189
+ const uniqueKey = `${memory.namespace}:${memory.key}:${memory.value}`;
190
+ const now = Date.now();
191
+ const existing = await memoryDb.memories.where("uniqueKey").equals(uniqueKey).first();
192
+ if (existing) {
193
+ const shouldPreserveEmbedding = existing.value === memory.value && existing.rawEvidence === memory.rawEvidence && existing.type === memory.type && existing.namespace === memory.namespace && existing.key === memory.key && existing.embedding !== void 0 && existing.embedding.length > 0;
194
+ const updateData = {
195
+ ...memory,
196
+ compositeKey,
197
+ uniqueKey,
198
+ updatedAt: now,
199
+ createdAt: existing.createdAt
200
+ };
201
+ if (shouldPreserveEmbedding) {
202
+ updateData.embedding = existing.embedding;
203
+ updateData.embeddingModel = existing.embeddingModel;
204
+ } else {
205
+ updateData.embedding = [];
206
+ updateData.embeddingModel = void 0;
207
+ }
208
+ await memoryDb.memories.update(existing.id, updateData);
209
+ } else {
210
+ await memoryDb.memories.add({
211
+ ...memory,
212
+ compositeKey,
213
+ uniqueKey,
214
+ createdAt: now,
215
+ updatedAt: now
216
+ });
217
+ }
218
+ };
219
+ var saveMemories = async (memories) => {
220
+ await Promise.all(memories.map((memory) => saveMemory(memory)));
221
+ };
222
+ var getAllMemories = async () => {
223
+ return memoryDb.memories.toArray();
224
+ };
225
+ var cosineSimilarity = (a, b) => {
226
+ if (a.length !== b.length) {
227
+ throw new Error("Vectors must have the same length");
228
+ }
229
+ let dotProduct = 0;
230
+ let normA = 0;
231
+ let normB = 0;
232
+ for (let i = 0; i < a.length; i++) {
233
+ dotProduct += a[i] * b[i];
234
+ normA += a[i] * a[i];
235
+ normB += b[i] * b[i];
236
+ }
237
+ const denominator = Math.sqrt(normA) * Math.sqrt(normB);
238
+ if (denominator === 0) {
239
+ return 0;
240
+ }
241
+ return dotProduct / denominator;
242
+ };
243
+ var searchSimilarMemories = async (queryEmbedding, limit = 10, minSimilarity = 0.6) => {
244
+ const allMemories = await getAllMemories();
245
+ const memoriesWithEmbeddings = allMemories.filter(
246
+ (m) => m.embedding && m.embedding.length > 0
247
+ );
248
+ console.log(
249
+ `[Memory Search] Total memories: ${allMemories.length}, memories with embeddings: ${memoriesWithEmbeddings.length}`
250
+ );
251
+ if (memoriesWithEmbeddings.length === 0) {
252
+ console.warn(
253
+ "[Memory Search] No memories with embeddings found. Memories may need embeddings generated. Use generateAndStoreEmbeddings() to generate embeddings for existing memories."
254
+ );
255
+ return [];
256
+ }
257
+ const allResults = memoriesWithEmbeddings.map((memory) => {
258
+ const similarity = cosineSimilarity(queryEmbedding, memory.embedding);
259
+ return {
260
+ ...memory,
261
+ similarity
262
+ };
263
+ }).sort((a, b) => b.similarity - a.similarity);
264
+ console.log(
265
+ `[Memory Search] All similarity scores:`,
266
+ allResults.map((r) => ({
267
+ key: `${r.namespace}:${r.key}`,
268
+ value: r.value,
269
+ similarity: r.similarity.toFixed(4)
270
+ }))
271
+ );
272
+ const results = allResults.filter((result) => result.similarity >= minSimilarity).slice(0, limit);
273
+ if (results.length === 0 && allResults.length > 0) {
274
+ const topSimilarity = allResults[0].similarity;
275
+ const suggestedThreshold = Math.max(0.3, topSimilarity - 0.1);
276
+ console.warn(
277
+ `[Memory Search] No memories above threshold ${minSimilarity}. Highest similarity was ${topSimilarity.toFixed(4)}. Consider lowering the threshold to ${suggestedThreshold.toFixed(2)}`
278
+ );
279
+ } else {
280
+ console.log(
281
+ `[Memory Search] Found ${results.length} memories above similarity threshold ${minSimilarity}. Top similarity: ${results[0]?.similarity.toFixed(4) || "N/A"}`
282
+ );
283
+ }
284
+ return results;
285
+ };
286
+
287
+ // src/client/core/bodySerializer.gen.ts
288
+ var jsonBodySerializer = {
289
+ bodySerializer: (body) => JSON.stringify(
290
+ body,
291
+ (_key, value) => typeof value === "bigint" ? value.toString() : value
292
+ )
293
+ };
294
+
295
+ // src/client/core/params.gen.ts
296
+ var extraPrefixesMap = {
297
+ $body_: "body",
298
+ $headers_: "headers",
299
+ $path_: "path",
300
+ $query_: "query"
301
+ };
302
+ var extraPrefixes = Object.entries(extraPrefixesMap);
303
+
304
+ // src/client/core/serverSentEvents.gen.ts
305
+ var createSseClient = ({
306
+ onRequest,
307
+ onSseError,
308
+ onSseEvent,
309
+ responseTransformer,
310
+ responseValidator,
311
+ sseDefaultRetryDelay,
312
+ sseMaxRetryAttempts,
313
+ sseMaxRetryDelay,
314
+ sseSleepFn,
315
+ url,
316
+ ...options
317
+ }) => {
318
+ let lastEventId;
319
+ const sleep = sseSleepFn ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
320
+ const createStream = async function* () {
321
+ let retryDelay = sseDefaultRetryDelay ?? 3e3;
322
+ let attempt = 0;
323
+ const signal = options.signal ?? new AbortController().signal;
324
+ while (true) {
325
+ if (signal.aborted) break;
326
+ attempt++;
327
+ const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers);
328
+ if (lastEventId !== void 0) {
329
+ headers.set("Last-Event-ID", lastEventId);
330
+ }
331
+ try {
332
+ const requestInit = {
333
+ redirect: "follow",
334
+ ...options,
335
+ body: options.serializedBody,
336
+ headers,
337
+ signal
338
+ };
339
+ let request = new Request(url, requestInit);
340
+ if (onRequest) {
341
+ request = await onRequest(url, requestInit);
342
+ }
343
+ const _fetch = options.fetch ?? globalThis.fetch;
344
+ const response = await _fetch(request);
345
+ if (!response.ok)
346
+ throw new Error(
347
+ `SSE failed: ${response.status} ${response.statusText}`
348
+ );
349
+ if (!response.body) throw new Error("No body in SSE response");
350
+ const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
351
+ let buffer = "";
352
+ const abortHandler = () => {
353
+ try {
354
+ reader.cancel();
355
+ } catch {
356
+ }
357
+ };
358
+ signal.addEventListener("abort", abortHandler);
359
+ try {
360
+ while (true) {
361
+ const { done, value } = await reader.read();
362
+ if (done) break;
363
+ buffer += value;
364
+ const chunks = buffer.split("\n\n");
365
+ buffer = chunks.pop() ?? "";
366
+ for (const chunk of chunks) {
367
+ const lines = chunk.split("\n");
368
+ const dataLines = [];
369
+ let eventName;
370
+ for (const line of lines) {
371
+ if (line.startsWith("data:")) {
372
+ dataLines.push(line.replace(/^data:\s*/, ""));
373
+ } else if (line.startsWith("event:")) {
374
+ eventName = line.replace(/^event:\s*/, "");
375
+ } else if (line.startsWith("id:")) {
376
+ lastEventId = line.replace(/^id:\s*/, "");
377
+ } else if (line.startsWith("retry:")) {
378
+ const parsed = Number.parseInt(
379
+ line.replace(/^retry:\s*/, ""),
380
+ 10
381
+ );
382
+ if (!Number.isNaN(parsed)) {
383
+ retryDelay = parsed;
384
+ }
385
+ }
386
+ }
387
+ let data;
388
+ let parsedJson = false;
389
+ if (dataLines.length) {
390
+ const rawData = dataLines.join("\n");
391
+ try {
392
+ data = JSON.parse(rawData);
393
+ parsedJson = true;
394
+ } catch {
395
+ data = rawData;
396
+ }
397
+ }
398
+ if (parsedJson) {
399
+ if (responseValidator) {
400
+ await responseValidator(data);
401
+ }
402
+ if (responseTransformer) {
403
+ data = await responseTransformer(data);
404
+ }
405
+ }
406
+ onSseEvent?.({
407
+ data,
408
+ event: eventName,
409
+ id: lastEventId,
410
+ retry: retryDelay
411
+ });
412
+ if (dataLines.length) {
413
+ yield data;
414
+ }
415
+ }
416
+ }
417
+ } finally {
418
+ signal.removeEventListener("abort", abortHandler);
419
+ reader.releaseLock();
420
+ }
421
+ break;
422
+ } catch (error) {
423
+ onSseError?.(error);
424
+ if (sseMaxRetryAttempts !== void 0 && attempt >= sseMaxRetryAttempts) {
425
+ break;
426
+ }
427
+ const backoff = Math.min(
428
+ retryDelay * 2 ** (attempt - 1),
429
+ sseMaxRetryDelay ?? 3e4
430
+ );
431
+ await sleep(backoff);
432
+ }
433
+ }
434
+ };
435
+ const stream = createStream();
436
+ return { stream };
437
+ };
438
+
439
+ // src/client/core/pathSerializer.gen.ts
440
+ var separatorArrayExplode = (style) => {
441
+ switch (style) {
442
+ case "label":
443
+ return ".";
444
+ case "matrix":
445
+ return ";";
446
+ case "simple":
447
+ return ",";
448
+ default:
449
+ return "&";
450
+ }
451
+ };
452
+ var separatorArrayNoExplode = (style) => {
453
+ switch (style) {
454
+ case "form":
455
+ return ",";
456
+ case "pipeDelimited":
457
+ return "|";
458
+ case "spaceDelimited":
459
+ return "%20";
460
+ default:
461
+ return ",";
462
+ }
463
+ };
464
+ var separatorObjectExplode = (style) => {
465
+ switch (style) {
466
+ case "label":
467
+ return ".";
468
+ case "matrix":
469
+ return ";";
470
+ case "simple":
471
+ return ",";
472
+ default:
473
+ return "&";
474
+ }
475
+ };
476
+ var serializeArrayParam = ({
477
+ allowReserved,
478
+ explode,
479
+ name,
480
+ style,
481
+ value
482
+ }) => {
483
+ if (!explode) {
484
+ const joinedValues2 = (allowReserved ? value : value.map((v) => encodeURIComponent(v))).join(separatorArrayNoExplode(style));
485
+ switch (style) {
486
+ case "label":
487
+ return `.${joinedValues2}`;
488
+ case "matrix":
489
+ return `;${name}=${joinedValues2}`;
490
+ case "simple":
491
+ return joinedValues2;
492
+ default:
493
+ return `${name}=${joinedValues2}`;
494
+ }
495
+ }
496
+ const separator = separatorArrayExplode(style);
497
+ const joinedValues = value.map((v) => {
498
+ if (style === "label" || style === "simple") {
499
+ return allowReserved ? v : encodeURIComponent(v);
500
+ }
501
+ return serializePrimitiveParam({
502
+ allowReserved,
503
+ name,
504
+ value: v
505
+ });
506
+ }).join(separator);
507
+ return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues;
508
+ };
509
+ var serializePrimitiveParam = ({
510
+ allowReserved,
511
+ name,
512
+ value
513
+ }) => {
514
+ if (value === void 0 || value === null) {
515
+ return "";
516
+ }
517
+ if (typeof value === "object") {
518
+ throw new Error(
519
+ "Deeply-nested arrays/objects aren\u2019t supported. Provide your own `querySerializer()` to handle these."
520
+ );
521
+ }
522
+ return `${name}=${allowReserved ? value : encodeURIComponent(value)}`;
523
+ };
524
+ var serializeObjectParam = ({
525
+ allowReserved,
526
+ explode,
527
+ name,
528
+ style,
529
+ value,
530
+ valueOnly
531
+ }) => {
532
+ if (value instanceof Date) {
533
+ return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`;
534
+ }
535
+ if (style !== "deepObject" && !explode) {
536
+ let values = [];
537
+ Object.entries(value).forEach(([key, v]) => {
538
+ values = [
539
+ ...values,
540
+ key,
541
+ allowReserved ? v : encodeURIComponent(v)
542
+ ];
543
+ });
544
+ const joinedValues2 = values.join(",");
545
+ switch (style) {
546
+ case "form":
547
+ return `${name}=${joinedValues2}`;
548
+ case "label":
549
+ return `.${joinedValues2}`;
550
+ case "matrix":
551
+ return `;${name}=${joinedValues2}`;
552
+ default:
553
+ return joinedValues2;
554
+ }
555
+ }
556
+ const separator = separatorObjectExplode(style);
557
+ const joinedValues = Object.entries(value).map(
558
+ ([key, v]) => serializePrimitiveParam({
559
+ allowReserved,
560
+ name: style === "deepObject" ? `${name}[${key}]` : key,
561
+ value: v
562
+ })
563
+ ).join(separator);
564
+ return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues;
565
+ };
566
+
567
+ // src/client/core/utils.gen.ts
568
+ function getValidRequestBody(options) {
569
+ const hasBody = options.body !== void 0;
570
+ const isSerializedBody = hasBody && options.bodySerializer;
571
+ if (isSerializedBody) {
572
+ if ("serializedBody" in options) {
573
+ const hasSerializedBody = options.serializedBody !== void 0 && options.serializedBody !== "";
574
+ return hasSerializedBody ? options.serializedBody : null;
575
+ }
576
+ return options.body !== "" ? options.body : null;
577
+ }
578
+ if (hasBody) {
579
+ return options.body;
580
+ }
581
+ return void 0;
582
+ }
583
+
584
+ // src/client/core/auth.gen.ts
585
+ var getAuthToken = async (auth, callback) => {
586
+ const token = typeof callback === "function" ? await callback(auth) : callback;
587
+ if (!token) {
588
+ return;
589
+ }
590
+ if (auth.scheme === "bearer") {
591
+ return `Bearer ${token}`;
592
+ }
593
+ if (auth.scheme === "basic") {
594
+ return `Basic ${btoa(token)}`;
595
+ }
596
+ return token;
597
+ };
598
+
599
+ // src/client/client/utils.gen.ts
600
+ var PATH_PARAM_RE = /\{[^{}]+\}/g;
601
+ var defaultPathSerializer = ({ path, url: _url }) => {
602
+ let url = _url;
603
+ const matches = _url.match(PATH_PARAM_RE);
604
+ if (matches) {
605
+ for (const match of matches) {
606
+ let explode = false;
607
+ let name = match.substring(1, match.length - 1);
608
+ let style = "simple";
609
+ if (name.endsWith("*")) {
610
+ explode = true;
611
+ name = name.substring(0, name.length - 1);
612
+ }
613
+ if (name.startsWith(".")) {
614
+ name = name.substring(1);
615
+ style = "label";
616
+ } else if (name.startsWith(";")) {
617
+ name = name.substring(1);
618
+ style = "matrix";
619
+ }
620
+ const value = path[name];
621
+ if (value === void 0 || value === null) {
622
+ continue;
623
+ }
624
+ if (Array.isArray(value)) {
625
+ url = url.replace(
626
+ match,
627
+ serializeArrayParam({ explode, name, style, value })
628
+ );
629
+ continue;
630
+ }
631
+ if (typeof value === "object") {
632
+ url = url.replace(
633
+ match,
634
+ serializeObjectParam({
635
+ explode,
636
+ name,
637
+ style,
638
+ value,
639
+ valueOnly: true
640
+ })
641
+ );
642
+ continue;
643
+ }
644
+ if (style === "matrix") {
645
+ url = url.replace(
646
+ match,
647
+ `;${serializePrimitiveParam({
648
+ name,
649
+ value
650
+ })}`
651
+ );
652
+ continue;
653
+ }
654
+ const replaceValue = encodeURIComponent(
655
+ style === "label" ? `.${value}` : value
656
+ );
657
+ url = url.replace(match, replaceValue);
658
+ }
659
+ }
660
+ return url;
661
+ };
662
+ var createQuerySerializer = ({
663
+ parameters = {},
664
+ ...args
665
+ } = {}) => {
666
+ const querySerializer = (queryParams) => {
667
+ const search = [];
668
+ if (queryParams && typeof queryParams === "object") {
669
+ for (const name in queryParams) {
670
+ const value = queryParams[name];
671
+ if (value === void 0 || value === null) {
672
+ continue;
673
+ }
674
+ const options = parameters[name] || args;
675
+ if (Array.isArray(value)) {
676
+ const serializedArray = serializeArrayParam({
677
+ allowReserved: options.allowReserved,
678
+ explode: true,
679
+ name,
680
+ style: "form",
681
+ value,
682
+ ...options.array
683
+ });
684
+ if (serializedArray) search.push(serializedArray);
685
+ } else if (typeof value === "object") {
686
+ const serializedObject = serializeObjectParam({
687
+ allowReserved: options.allowReserved,
688
+ explode: true,
689
+ name,
690
+ style: "deepObject",
691
+ value,
692
+ ...options.object
693
+ });
694
+ if (serializedObject) search.push(serializedObject);
695
+ } else {
696
+ const serializedPrimitive = serializePrimitiveParam({
697
+ allowReserved: options.allowReserved,
698
+ name,
699
+ value
700
+ });
701
+ if (serializedPrimitive) search.push(serializedPrimitive);
702
+ }
703
+ }
704
+ }
705
+ return search.join("&");
706
+ };
707
+ return querySerializer;
708
+ };
709
+ var getParseAs = (contentType) => {
710
+ if (!contentType) {
711
+ return "stream";
712
+ }
713
+ const cleanContent = contentType.split(";")[0]?.trim();
714
+ if (!cleanContent) {
715
+ return;
716
+ }
717
+ if (cleanContent.startsWith("application/json") || cleanContent.endsWith("+json")) {
718
+ return "json";
719
+ }
720
+ if (cleanContent === "multipart/form-data") {
721
+ return "formData";
722
+ }
723
+ if (["application/", "audio/", "image/", "video/"].some(
724
+ (type) => cleanContent.startsWith(type)
725
+ )) {
726
+ return "blob";
727
+ }
728
+ if (cleanContent.startsWith("text/")) {
729
+ return "text";
730
+ }
731
+ return;
732
+ };
733
+ var checkForExistence = (options, name) => {
734
+ if (!name) {
735
+ return false;
736
+ }
737
+ if (options.headers.has(name) || options.query?.[name] || options.headers.get("Cookie")?.includes(`${name}=`)) {
738
+ return true;
739
+ }
740
+ return false;
741
+ };
742
+ var setAuthParams = async ({
743
+ security,
744
+ ...options
745
+ }) => {
746
+ for (const auth of security) {
747
+ if (checkForExistence(options, auth.name)) {
748
+ continue;
749
+ }
750
+ const token = await getAuthToken(auth, options.auth);
751
+ if (!token) {
752
+ continue;
753
+ }
754
+ const name = auth.name ?? "Authorization";
755
+ switch (auth.in) {
756
+ case "query":
757
+ if (!options.query) {
758
+ options.query = {};
759
+ }
760
+ options.query[name] = token;
761
+ break;
762
+ case "cookie":
763
+ options.headers.append("Cookie", `${name}=${token}`);
764
+ break;
765
+ case "header":
766
+ default:
767
+ options.headers.set(name, token);
768
+ break;
769
+ }
770
+ }
771
+ };
772
+ var buildUrl = (options) => {
773
+ const url = getUrl({
774
+ baseUrl: options.baseUrl,
775
+ path: options.path,
776
+ query: options.query,
777
+ querySerializer: typeof options.querySerializer === "function" ? options.querySerializer : createQuerySerializer(options.querySerializer),
778
+ url: options.url
779
+ });
780
+ return url;
781
+ };
782
+ var getUrl = ({
783
+ baseUrl,
784
+ path,
785
+ query,
786
+ querySerializer,
787
+ url: _url
788
+ }) => {
789
+ const pathUrl = _url.startsWith("/") ? _url : `/${_url}`;
790
+ let url = (baseUrl ?? "") + pathUrl;
791
+ if (path) {
792
+ url = defaultPathSerializer({ path, url });
793
+ }
794
+ let search = query ? querySerializer(query) : "";
795
+ if (search.startsWith("?")) {
796
+ search = search.substring(1);
797
+ }
798
+ if (search) {
799
+ url += `?${search}`;
800
+ }
801
+ return url;
802
+ };
803
+ var mergeConfigs = (a, b) => {
804
+ const config = { ...a, ...b };
805
+ if (config.baseUrl?.endsWith("/")) {
806
+ config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1);
807
+ }
808
+ config.headers = mergeHeaders(a.headers, b.headers);
809
+ return config;
810
+ };
811
+ var headersEntries = (headers) => {
812
+ const entries = [];
813
+ headers.forEach((value, key) => {
814
+ entries.push([key, value]);
815
+ });
816
+ return entries;
817
+ };
818
+ var mergeHeaders = (...headers) => {
819
+ const mergedHeaders = new Headers();
820
+ for (const header of headers) {
821
+ if (!header || typeof header !== "object") {
822
+ continue;
823
+ }
824
+ const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header);
825
+ for (const [key, value] of iterator) {
826
+ if (value === null) {
827
+ mergedHeaders.delete(key);
828
+ } else if (Array.isArray(value)) {
829
+ for (const v of value) {
830
+ mergedHeaders.append(key, v);
831
+ }
832
+ } else if (value !== void 0) {
833
+ mergedHeaders.set(
834
+ key,
835
+ typeof value === "object" ? JSON.stringify(value) : value
836
+ );
837
+ }
838
+ }
839
+ }
840
+ return mergedHeaders;
841
+ };
842
+ var Interceptors = class {
843
+ constructor() {
844
+ this.fns = [];
845
+ }
846
+ clear() {
847
+ this.fns = [];
848
+ }
849
+ eject(id) {
850
+ const index = this.getInterceptorIndex(id);
851
+ if (this.fns[index]) {
852
+ this.fns[index] = null;
853
+ }
854
+ }
855
+ exists(id) {
856
+ const index = this.getInterceptorIndex(id);
857
+ return Boolean(this.fns[index]);
858
+ }
859
+ getInterceptorIndex(id) {
860
+ if (typeof id === "number") {
861
+ return this.fns[id] ? id : -1;
862
+ }
863
+ return this.fns.indexOf(id);
864
+ }
865
+ update(id, fn) {
866
+ const index = this.getInterceptorIndex(id);
867
+ if (this.fns[index]) {
868
+ this.fns[index] = fn;
869
+ return id;
870
+ }
871
+ return false;
872
+ }
873
+ use(fn) {
874
+ this.fns.push(fn);
875
+ return this.fns.length - 1;
876
+ }
877
+ };
878
+ var createInterceptors = () => ({
879
+ error: new Interceptors(),
880
+ request: new Interceptors(),
881
+ response: new Interceptors()
882
+ });
883
+ var defaultQuerySerializer = createQuerySerializer({
884
+ allowReserved: false,
885
+ array: {
886
+ explode: true,
887
+ style: "form"
888
+ },
889
+ object: {
890
+ explode: true,
891
+ style: "deepObject"
892
+ }
893
+ });
894
+ var defaultHeaders = {
895
+ "Content-Type": "application/json"
896
+ };
897
+ var createConfig = (override = {}) => ({
898
+ ...jsonBodySerializer,
899
+ headers: defaultHeaders,
900
+ parseAs: "auto",
901
+ querySerializer: defaultQuerySerializer,
902
+ ...override
903
+ });
904
+
905
+ // src/client/client/client.gen.ts
906
+ var createClient = (config = {}) => {
907
+ let _config = mergeConfigs(createConfig(), config);
908
+ const getConfig = () => ({ ..._config });
909
+ const setConfig = (config2) => {
910
+ _config = mergeConfigs(_config, config2);
911
+ return getConfig();
912
+ };
913
+ const interceptors = createInterceptors();
914
+ const beforeRequest = async (options) => {
915
+ const opts = {
916
+ ..._config,
917
+ ...options,
918
+ fetch: options.fetch ?? _config.fetch ?? globalThis.fetch,
919
+ headers: mergeHeaders(_config.headers, options.headers),
920
+ serializedBody: void 0
921
+ };
922
+ if (opts.security) {
923
+ await setAuthParams({
924
+ ...opts,
925
+ security: opts.security
926
+ });
927
+ }
928
+ if (opts.requestValidator) {
929
+ await opts.requestValidator(opts);
930
+ }
931
+ if (opts.body !== void 0 && opts.bodySerializer) {
932
+ opts.serializedBody = opts.bodySerializer(opts.body);
933
+ }
934
+ if (opts.body === void 0 || opts.serializedBody === "") {
935
+ opts.headers.delete("Content-Type");
936
+ }
937
+ const url = buildUrl(opts);
938
+ return { opts, url };
939
+ };
940
+ const request = async (options) => {
941
+ const { opts, url } = await beforeRequest(options);
942
+ for (const fn of interceptors.request.fns) {
943
+ if (fn) {
944
+ await fn(opts);
945
+ }
946
+ }
947
+ const _fetch = opts.fetch;
948
+ const requestInit = {
949
+ ...opts,
950
+ body: getValidRequestBody(opts)
951
+ };
952
+ let response = await _fetch(url, requestInit);
953
+ for (const fn of interceptors.response.fns) {
954
+ if (fn) {
955
+ response = await fn(response, opts);
956
+ }
957
+ }
958
+ const result = {
959
+ response
960
+ };
961
+ if (response.ok) {
962
+ const parseAs = (opts.parseAs === "auto" ? getParseAs(response.headers.get("Content-Type")) : opts.parseAs) ?? "json";
963
+ if (response.status === 204 || response.headers.get("Content-Length") === "0") {
964
+ let emptyData;
965
+ switch (parseAs) {
966
+ case "arrayBuffer":
967
+ case "blob":
968
+ case "text":
969
+ emptyData = await response[parseAs]();
970
+ break;
971
+ case "formData":
972
+ emptyData = new FormData();
973
+ break;
974
+ case "stream":
975
+ emptyData = response.body;
976
+ break;
977
+ case "json":
978
+ default:
979
+ emptyData = {};
980
+ break;
981
+ }
982
+ return {
983
+ data: emptyData,
984
+ ...result
985
+ };
986
+ }
987
+ let data;
988
+ switch (parseAs) {
989
+ case "arrayBuffer":
990
+ case "blob":
991
+ case "formData":
992
+ case "json":
993
+ case "text":
994
+ data = await response[parseAs]();
995
+ break;
996
+ case "stream":
997
+ return {
998
+ data: response.body,
999
+ ...result
1000
+ };
1001
+ }
1002
+ if (parseAs === "json") {
1003
+ if (opts.responseValidator) {
1004
+ await opts.responseValidator(data);
1005
+ }
1006
+ if (opts.responseTransformer) {
1007
+ data = await opts.responseTransformer(data);
1008
+ }
1009
+ }
1010
+ return {
1011
+ data,
1012
+ ...result
1013
+ };
1014
+ }
1015
+ const textError = await response.text();
1016
+ let jsonError;
1017
+ try {
1018
+ jsonError = JSON.parse(textError);
1019
+ } catch {
1020
+ }
1021
+ const error = jsonError ?? textError;
1022
+ let finalError = error;
1023
+ for (const fn of interceptors.error.fns) {
1024
+ if (fn) {
1025
+ finalError = await fn(error, response, opts);
1026
+ }
1027
+ }
1028
+ finalError = finalError || {};
1029
+ if (opts.throwOnError) {
1030
+ throw finalError;
1031
+ }
1032
+ return {
1033
+ error: finalError,
1034
+ ...result
1035
+ };
1036
+ };
1037
+ const makeMethodFn = (method) => (options) => request({ ...options, method });
1038
+ const makeSseFn = (method) => async (options) => {
1039
+ const { opts, url } = await beforeRequest(options);
1040
+ return createSseClient({
1041
+ ...opts,
1042
+ body: opts.body,
1043
+ headers: opts.headers,
1044
+ method,
1045
+ onRequest: async (url2, init) => {
1046
+ let request2 = new Request(url2, init);
1047
+ const requestInit = {
1048
+ ...init,
1049
+ method: init.method,
1050
+ url: url2
1051
+ };
1052
+ for (const fn of interceptors.request.fns) {
1053
+ if (fn) {
1054
+ await fn(requestInit);
1055
+ request2 = new Request(requestInit.url, requestInit);
1056
+ }
1057
+ }
1058
+ return request2;
1059
+ },
1060
+ url
1061
+ });
1062
+ };
1063
+ return {
1064
+ buildUrl,
1065
+ connect: makeMethodFn("CONNECT"),
1066
+ delete: makeMethodFn("DELETE"),
1067
+ get: makeMethodFn("GET"),
1068
+ getConfig,
1069
+ head: makeMethodFn("HEAD"),
1070
+ interceptors,
1071
+ options: makeMethodFn("OPTIONS"),
1072
+ patch: makeMethodFn("PATCH"),
1073
+ post: makeMethodFn("POST"),
1074
+ put: makeMethodFn("PUT"),
1075
+ request,
1076
+ setConfig,
1077
+ sse: {
1078
+ connect: makeSseFn("CONNECT"),
1079
+ delete: makeSseFn("DELETE"),
1080
+ get: makeSseFn("GET"),
1081
+ head: makeSseFn("HEAD"),
1082
+ options: makeSseFn("OPTIONS"),
1083
+ patch: makeSseFn("PATCH"),
1084
+ post: makeSseFn("POST"),
1085
+ put: makeSseFn("PUT"),
1086
+ trace: makeSseFn("TRACE")
1087
+ },
1088
+ trace: makeMethodFn("TRACE")
1089
+ };
1090
+ };
1091
+
1092
+ // src/clientConfig.ts
1093
+ var createClientConfig = (config) => ({
1094
+ ...config,
1095
+ baseUrl: "https://ai-portal-dev.zetachain.com"
1096
+ });
1097
+
1098
+ // src/client/client.gen.ts
1099
+ var client = createClient(createClientConfig(createConfig()));
1100
+
1101
+ // src/client/sdk.gen.ts
1102
+ var postApiV1Embeddings = (options) => {
1103
+ return (options.client ?? client).post({
1104
+ url: "/api/v1/embeddings",
1105
+ ...options,
1106
+ headers: {
1107
+ "Content-Type": "application/json",
1108
+ ...options.headers
1109
+ }
1110
+ });
1111
+ };
1112
+
1113
+ // src/lib/memory/embeddings.ts
1114
+ var generateEmbeddingForText = async (text, options = {}) => {
1115
+ const { model = "openai/text-embedding-3-small", getToken } = options;
1116
+ try {
1117
+ const token = getToken ? await getToken() : null;
1118
+ const headers = {};
1119
+ if (token) {
1120
+ headers.Authorization = `Bearer ${token}`;
1121
+ }
1122
+ const response = await postApiV1Embeddings({
1123
+ body: {
1124
+ input: text,
1125
+ model
1126
+ },
1127
+ headers
1128
+ });
1129
+ if (!response.data || !response.data.data || response.data.data.length === 0) {
1130
+ throw new Error(
1131
+ `Failed to generate embedding: ${response.error?.error ?? "No data returned"}`
1132
+ );
1133
+ }
1134
+ const embedding = response.data.data[0]?.embedding;
1135
+ if (!embedding || !Array.isArray(embedding)) {
1136
+ throw new Error("Invalid embedding format returned from API");
1137
+ }
1138
+ return embedding;
1139
+ } catch (error) {
1140
+ console.error("Failed to generate embedding:", error);
1141
+ throw error;
1142
+ }
1143
+ };
1144
+ var generateEmbeddingForMemory = async (memory, options = {}) => {
1145
+ const text = [
1146
+ memory.rawEvidence,
1147
+ memory.type,
1148
+ memory.namespace,
1149
+ memory.key,
1150
+ memory.value
1151
+ ].filter(Boolean).join(" ");
1152
+ return generateEmbeddingForText(text, options);
1153
+ };
1154
+ var generateEmbeddingsForMemories = async (memories, options = {}) => {
1155
+ const { model = "openai/text-embedding-3-small", getToken } = options;
1156
+ const embeddings = /* @__PURE__ */ new Map();
1157
+ for (const memory of memories) {
1158
+ const uniqueKey = `${memory.namespace}:${memory.key}:${memory.value}`;
1159
+ try {
1160
+ const embedding = await generateEmbeddingForMemory(memory, {
1161
+ model,
1162
+ getToken
1163
+ });
1164
+ embeddings.set(uniqueKey, embedding);
1165
+ } catch (error) {
1166
+ console.error(
1167
+ `Failed to generate embedding for memory ${uniqueKey}:`,
1168
+ error
1169
+ );
1170
+ }
1171
+ }
1172
+ return embeddings;
1173
+ };
1174
+ var updateMemoriesWithEmbeddings = async (embeddings, embeddingModel) => {
1175
+ const updates = Array.from(embeddings.entries()).map(
1176
+ async ([uniqueKey, embedding]) => {
1177
+ const existing = await memoryDb.memories.where("uniqueKey").equals(uniqueKey).first();
1178
+ if (existing?.id) {
1179
+ await memoryDb.memories.update(existing.id, {
1180
+ embedding,
1181
+ embeddingModel,
1182
+ updatedAt: Date.now(),
1183
+ createdAt: existing.createdAt
1184
+ });
1185
+ } else {
1186
+ console.warn(
1187
+ `[Embeddings] Memory with uniqueKey ${uniqueKey} not found. It may have been updated or deleted before embedding was generated.`
1188
+ );
1189
+ }
1190
+ }
1191
+ );
1192
+ await Promise.all(updates);
1193
+ };
1194
+ var generateAndStoreEmbeddings = async (memories, options = {}) => {
1195
+ const { model = "openai/text-embedding-3-small" } = options;
1196
+ if (memories.length === 0) {
1197
+ return;
1198
+ }
1199
+ console.log(`Generating embeddings for ${memories.length} memories...`);
1200
+ const embeddings = await generateEmbeddingsForMemories(memories, options);
1201
+ await updateMemoriesWithEmbeddings(embeddings, model);
1202
+ console.log(`Generated and stored ${embeddings.size} embeddings`);
1203
+ };
1204
+ var generateQueryEmbedding = async (query, options = {}) => {
1205
+ return generateEmbeddingForText(query, options);
1206
+ };
1207
+
1208
+ // src/react/useMemory.ts
1209
+ function useMemory(options = {}) {
1210
+ const {
1211
+ memoryModel = "openai/gpt-4o",
1212
+ embeddingModel = "openai/text-embedding-3-small",
1213
+ generateEmbeddings = true,
1214
+ onFactsExtracted,
1215
+ getToken
1216
+ } = options;
1217
+ const extractionInProgressRef = useRef(false);
1218
+ const extractMemoriesFromMessage = useCallback2(
1219
+ async (options2) => {
1220
+ const { messages, model } = options2;
1221
+ if (!getToken || extractionInProgressRef.current) {
1222
+ return null;
1223
+ }
1224
+ extractionInProgressRef.current = true;
1225
+ try {
1226
+ const token = await getToken();
1227
+ if (!token) {
1228
+ console.error("No access token available for memory extraction");
1229
+ return null;
1230
+ }
1231
+ const completion = await postApiV1ChatCompletions2({
1232
+ body: {
1233
+ messages: [
1234
+ {
1235
+ role: "system",
1236
+ content: FACT_EXTRACTION_PROMPT
1237
+ },
1238
+ ...messages
1239
+ ],
1240
+ model: model || memoryModel
1241
+ },
1242
+ headers: {
1243
+ Authorization: `Bearer ${token}`
1244
+ }
1245
+ });
1246
+ if (!completion.data) {
1247
+ console.error(
1248
+ "Memory extraction failed:",
1249
+ completion.error?.error ?? "API did not return a response"
1250
+ );
1251
+ return null;
1252
+ }
1253
+ if (typeof completion.data === "string") {
1254
+ console.error(
1255
+ "Memory extraction failed: API returned a string response instead of a completion object"
1256
+ );
1257
+ return null;
1258
+ }
1259
+ const content = completion.data.choices?.[0]?.message?.content?.trim() || "";
1260
+ if (!content) {
1261
+ console.error("No content in memory extraction response");
1262
+ return null;
1263
+ }
1264
+ let jsonContent = content;
1265
+ jsonContent = jsonContent.replace(/^data:\s*/gm, "").trim();
1266
+ if (jsonContent.startsWith("{")) {
1267
+ let braceCount = 0;
1268
+ let jsonStart = -1;
1269
+ let jsonEnd = -1;
1270
+ for (let i = 0; i < jsonContent.length; i++) {
1271
+ if (jsonContent[i] === "{") {
1272
+ if (jsonStart === -1) jsonStart = i;
1273
+ braceCount++;
1274
+ } else if (jsonContent[i] === "}") {
1275
+ braceCount--;
1276
+ if (braceCount === 0 && jsonStart !== -1) {
1277
+ jsonEnd = i + 1;
1278
+ break;
1279
+ }
1280
+ }
1281
+ }
1282
+ if (jsonStart !== -1 && jsonEnd !== -1) {
1283
+ jsonContent = jsonContent.substring(jsonStart, jsonEnd);
1284
+ }
1285
+ } else {
1286
+ const jsonMatch = jsonContent.match(
1287
+ /```(?:json)?\s*(\{[\s\S]*?\})\s*```/
1288
+ );
1289
+ if (jsonMatch && jsonMatch[1]) {
1290
+ jsonContent = jsonMatch[1].trim();
1291
+ } else {
1292
+ const jsonObjectMatch = jsonContent.match(/\{[\s\S]*\}/);
1293
+ if (jsonObjectMatch && jsonObjectMatch[0]) {
1294
+ jsonContent = jsonObjectMatch[0];
1295
+ } else {
1296
+ console.warn(
1297
+ "Memory extraction returned non-JSON response. The model may not have found any memories to extract, or it returned natural language instead of JSON.",
1298
+ "\nFirst 200 chars of response:",
1299
+ content.substring(0, 200)
1300
+ );
1301
+ return { items: [] };
1302
+ }
1303
+ }
1304
+ }
1305
+ const trimmedJson = jsonContent.trim();
1306
+ if (!trimmedJson.startsWith("{") || !trimmedJson.includes("items")) {
1307
+ console.warn(
1308
+ "Memory extraction response doesn't appear to be valid JSON. The model may not have found any memories to extract, or returned natural language instead of JSON.",
1309
+ "\nResponse preview:",
1310
+ content.substring(0, 200)
1311
+ );
1312
+ return { items: [] };
1313
+ }
1314
+ let result;
1315
+ try {
1316
+ result = JSON.parse(jsonContent);
1317
+ if (!result || typeof result !== "object") {
1318
+ throw new Error("Invalid JSON structure: not an object");
1319
+ }
1320
+ if (!Array.isArray(result.items)) {
1321
+ console.warn(
1322
+ "Memory extraction result missing 'items' array. Result:",
1323
+ result
1324
+ );
1325
+ return { items: [] };
1326
+ }
1327
+ } catch (parseError) {
1328
+ console.error(
1329
+ "Failed to parse memory extraction JSON:",
1330
+ parseError instanceof Error ? parseError.message : parseError
1331
+ );
1332
+ console.error("Attempted to parse:", jsonContent.substring(0, 200));
1333
+ console.error("Full raw content:", content.substring(0, 500));
1334
+ return { items: [] };
1335
+ }
1336
+ if (result.items && Array.isArray(result.items)) {
1337
+ const originalCount = result.items.length;
1338
+ result.items = preprocessMemories(result.items);
1339
+ const filteredCount = result.items.length;
1340
+ if (originalCount !== filteredCount) {
1341
+ console.log(
1342
+ `Preprocessed memories: ${originalCount} -> ${filteredCount} (dropped ${originalCount - filteredCount} entries)`
1343
+ );
1344
+ }
1345
+ }
1346
+ console.log("Extracted memories:", JSON.stringify(result, null, 2));
1347
+ if (result.items && result.items.length > 0) {
1348
+ try {
1349
+ await saveMemories(result.items);
1350
+ console.log(`Saved ${result.items.length} memories to IndexedDB`);
1351
+ if (generateEmbeddings && embeddingModel) {
1352
+ try {
1353
+ await generateAndStoreEmbeddings(result.items, {
1354
+ model: embeddingModel,
1355
+ getToken: getToken || void 0
1356
+ });
1357
+ console.log(
1358
+ `Generated embeddings for ${result.items.length} memories`
1359
+ );
1360
+ } catch (error) {
1361
+ console.error("Failed to generate embeddings:", error);
1362
+ }
1363
+ }
1364
+ } catch (error) {
1365
+ console.error("Failed to save memories to IndexedDB:", error);
1366
+ }
1367
+ }
1368
+ if (onFactsExtracted) {
1369
+ onFactsExtracted(result);
1370
+ }
1371
+ return result;
1372
+ } catch (error) {
1373
+ console.error("Failed to extract facts:", error);
1374
+ return null;
1375
+ } finally {
1376
+ extractionInProgressRef.current = false;
1377
+ }
1378
+ },
1379
+ [
1380
+ memoryModel,
1381
+ embeddingModel,
1382
+ generateEmbeddings,
1383
+ getToken,
1384
+ onFactsExtracted
1385
+ ]
1386
+ );
1387
+ const searchMemories = useCallback2(
1388
+ async (query, limit = 10, minSimilarity = 0.6) => {
1389
+ if (!getToken || !embeddingModel) {
1390
+ console.warn(
1391
+ "Cannot search memories: getToken or embeddingModel not provided"
1392
+ );
1393
+ return [];
1394
+ }
1395
+ try {
1396
+ console.log(`[Memory Search] Searching for: "${query}"`);
1397
+ const queryEmbedding = await generateQueryEmbedding(query, {
1398
+ model: embeddingModel,
1399
+ getToken
1400
+ });
1401
+ console.log(
1402
+ `[Memory Search] Generated query embedding (${queryEmbedding.length} dimensions)`
1403
+ );
1404
+ const results = await searchSimilarMemories(
1405
+ queryEmbedding,
1406
+ limit,
1407
+ minSimilarity
1408
+ );
1409
+ if (results.length === 0) {
1410
+ console.warn(
1411
+ `[Memory Search] No memories found above similarity threshold ${minSimilarity}. Try lowering the threshold or ensure memories have embeddings generated.`
1412
+ );
1413
+ } else {
1414
+ console.log(
1415
+ `[Memory Search] Found ${results.length} memories. Similarity scores: ${results.map((r) => r.similarity.toFixed(3)).join(", ")}`
1416
+ );
1417
+ }
1418
+ return results;
1419
+ } catch (error) {
1420
+ console.error("Failed to search memories:", error);
1421
+ return [];
1422
+ }
1423
+ },
1424
+ [embeddingModel, getToken]
1425
+ );
1426
+ return {
1427
+ extractMemoriesFromMessage,
1428
+ searchMemories
1429
+ };
1430
+ }
1431
+
1432
+ // src/lib/memory/chat.ts
1433
+ var formatMemoriesForChat = (memories, format = "compact") => {
1434
+ if (memories.length === 0) {
1435
+ return "";
1436
+ }
1437
+ const sections = [];
1438
+ const byNamespace = /* @__PURE__ */ new Map();
1439
+ for (const memory of memories) {
1440
+ if (!byNamespace.has(memory.namespace)) {
1441
+ byNamespace.set(memory.namespace, []);
1442
+ }
1443
+ byNamespace.get(memory.namespace).push(memory);
1444
+ }
1445
+ for (const [namespace, namespaceMemories] of byNamespace) {
1446
+ const items = [];
1447
+ for (const memory of namespaceMemories) {
1448
+ if (format === "detailed") {
1449
+ items.push(
1450
+ `- ${memory.key}: ${memory.value} (${memory.type}, confidence: ${memory.confidence.toFixed(2)}${memory.similarity ? `, relevance: ${memory.similarity.toFixed(2)}` : ""})`
1451
+ );
1452
+ if (memory.rawEvidence) {
1453
+ items.push(` Evidence: "${memory.rawEvidence}"`);
1454
+ }
1455
+ } else {
1456
+ items.push(`${memory.key}: ${memory.value}`);
1457
+ }
1458
+ }
1459
+ if (items.length > 0) {
1460
+ sections.push(`[${namespace}]
1461
+ ${items.join("\n")}`);
1462
+ }
1463
+ }
1464
+ return sections.join("\n\n");
1465
+ };
1466
+ var createMemoryContextSystemMessage = (memories, baseSystemPrompt) => {
1467
+ const memoryContext = formatMemoriesForChat(memories, "compact");
1468
+ if (!memoryContext) {
1469
+ return baseSystemPrompt || "";
1470
+ }
1471
+ const memorySection = `## User Context
1472
+ ${memoryContext}
1473
+
1474
+ Use this information to provide personalized and relevant responses.`;
1475
+ if (baseSystemPrompt) {
1476
+ return `${baseSystemPrompt}
1477
+
1478
+ ${memorySection}`;
1479
+ }
1480
+ return memorySection;
1481
+ };
1482
+ var extractConversationContext = (messages, maxMessages = 3) => {
1483
+ const userMessages = messages.filter((msg) => msg.role === "user").slice(-maxMessages).map((msg) => msg.content).join(" ");
1484
+ return userMessages.trim();
1485
+ };
63
1486
  export {
64
- useChat
1487
+ createMemoryContextSystemMessage,
1488
+ extractConversationContext,
1489
+ formatMemoriesForChat,
1490
+ useChat,
1491
+ useMemory
65
1492
  };