@librechat/agents 2.4.22 → 2.4.31

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.
Files changed (90) hide show
  1. package/dist/cjs/common/enum.cjs +1 -0
  2. package/dist/cjs/common/enum.cjs.map +1 -1
  3. package/dist/cjs/llm/anthropic/index.cjs +1 -1
  4. package/dist/cjs/llm/anthropic/index.cjs.map +1 -1
  5. package/dist/cjs/llm/anthropic/types.cjs +50 -0
  6. package/dist/cjs/llm/anthropic/types.cjs.map +1 -0
  7. package/dist/cjs/llm/anthropic/utils/message_inputs.cjs +227 -21
  8. package/dist/cjs/llm/anthropic/utils/message_inputs.cjs.map +1 -1
  9. package/dist/cjs/llm/anthropic/utils/message_outputs.cjs +1 -0
  10. package/dist/cjs/llm/anthropic/utils/message_outputs.cjs.map +1 -1
  11. package/dist/cjs/llm/openai/index.cjs.map +1 -1
  12. package/dist/cjs/main.cjs +2 -0
  13. package/dist/cjs/main.cjs.map +1 -1
  14. package/dist/cjs/run.cjs.map +1 -1
  15. package/dist/cjs/tools/search/firecrawl.cjs +149 -0
  16. package/dist/cjs/tools/search/firecrawl.cjs.map +1 -0
  17. package/dist/cjs/tools/search/format.cjs +116 -0
  18. package/dist/cjs/tools/search/format.cjs.map +1 -0
  19. package/dist/cjs/tools/search/highlights.cjs +193 -0
  20. package/dist/cjs/tools/search/highlights.cjs.map +1 -0
  21. package/dist/cjs/tools/search/rerankers.cjs +187 -0
  22. package/dist/cjs/tools/search/rerankers.cjs.map +1 -0
  23. package/dist/cjs/tools/search/search.cjs +410 -0
  24. package/dist/cjs/tools/search/search.cjs.map +1 -0
  25. package/dist/cjs/tools/search/tool.cjs +103 -0
  26. package/dist/cjs/tools/search/tool.cjs.map +1 -0
  27. package/dist/esm/common/enum.mjs +1 -0
  28. package/dist/esm/common/enum.mjs.map +1 -1
  29. package/dist/esm/llm/anthropic/index.mjs +1 -1
  30. package/dist/esm/llm/anthropic/index.mjs.map +1 -1
  31. package/dist/esm/llm/anthropic/types.mjs +48 -0
  32. package/dist/esm/llm/anthropic/types.mjs.map +1 -0
  33. package/dist/esm/llm/anthropic/utils/message_inputs.mjs +228 -22
  34. package/dist/esm/llm/anthropic/utils/message_inputs.mjs.map +1 -1
  35. package/dist/esm/llm/anthropic/utils/message_outputs.mjs +1 -0
  36. package/dist/esm/llm/anthropic/utils/message_outputs.mjs.map +1 -1
  37. package/dist/esm/llm/openai/index.mjs.map +1 -1
  38. package/dist/esm/main.mjs +1 -0
  39. package/dist/esm/main.mjs.map +1 -1
  40. package/dist/esm/run.mjs.map +1 -1
  41. package/dist/esm/tools/search/firecrawl.mjs +145 -0
  42. package/dist/esm/tools/search/firecrawl.mjs.map +1 -0
  43. package/dist/esm/tools/search/format.mjs +114 -0
  44. package/dist/esm/tools/search/format.mjs.map +1 -0
  45. package/dist/esm/tools/search/highlights.mjs +191 -0
  46. package/dist/esm/tools/search/highlights.mjs.map +1 -0
  47. package/dist/esm/tools/search/rerankers.mjs +181 -0
  48. package/dist/esm/tools/search/rerankers.mjs.map +1 -0
  49. package/dist/esm/tools/search/search.mjs +407 -0
  50. package/dist/esm/tools/search/search.mjs.map +1 -0
  51. package/dist/esm/tools/search/tool.mjs +101 -0
  52. package/dist/esm/tools/search/tool.mjs.map +1 -0
  53. package/dist/types/common/enum.d.ts +1 -0
  54. package/dist/types/index.d.ts +1 -0
  55. package/dist/types/llm/anthropic/index.d.ts +3 -4
  56. package/dist/types/llm/anthropic/types.d.ts +4 -35
  57. package/dist/types/llm/anthropic/utils/message_inputs.d.ts +2 -2
  58. package/dist/types/llm/anthropic/utils/message_outputs.d.ts +1 -3
  59. package/dist/types/llm/anthropic/utils/output_parsers.d.ts +22 -0
  60. package/dist/types/llm/openai/index.d.ts +3 -2
  61. package/dist/types/scripts/search.d.ts +1 -0
  62. package/dist/types/tools/example.d.ts +21 -3
  63. package/dist/types/tools/search/firecrawl.d.ts +117 -0
  64. package/dist/types/tools/search/format.d.ts +2 -0
  65. package/dist/types/tools/search/highlights.d.ts +13 -0
  66. package/dist/types/tools/search/index.d.ts +2 -0
  67. package/dist/types/tools/search/rerankers.d.ts +32 -0
  68. package/dist/types/tools/search/search.d.ts +9 -0
  69. package/dist/types/tools/search/tool.d.ts +12 -0
  70. package/dist/types/tools/search/types.d.ts +150 -0
  71. package/package.json +10 -9
  72. package/src/common/enum.ts +1 -0
  73. package/src/index.ts +1 -0
  74. package/src/llm/anthropic/index.ts +6 -5
  75. package/src/llm/anthropic/llm.spec.ts +176 -179
  76. package/src/llm/anthropic/types.ts +64 -39
  77. package/src/llm/anthropic/utils/message_inputs.ts +275 -37
  78. package/src/llm/anthropic/utils/message_outputs.ts +4 -21
  79. package/src/llm/anthropic/utils/output_parsers.ts +114 -0
  80. package/src/llm/openai/index.ts +7 -6
  81. package/src/run.ts +1 -1
  82. package/src/scripts/search.ts +141 -0
  83. package/src/tools/search/firecrawl.ts +270 -0
  84. package/src/tools/search/format.ts +121 -0
  85. package/src/tools/search/highlights.ts +237 -0
  86. package/src/tools/search/index.ts +2 -0
  87. package/src/tools/search/rerankers.ts +248 -0
  88. package/src/tools/search/search.ts +567 -0
  89. package/src/tools/search/tool.ts +151 -0
  90. package/src/tools/search/types.ts +179 -0
@@ -0,0 +1,116 @@
1
+ 'use strict';
2
+
3
+ function formatResultsForLLM(results) {
4
+ let output = '';
5
+ const addSection = (title) => {
6
+ output += `\n=== ${title} ===\n`;
7
+ };
8
+ // Organic (web) results
9
+ const organic = results.organic ?? [];
10
+ if (organic.length) {
11
+ addSection('Web Results');
12
+ organic.forEach((r, i) => {
13
+ output += [
14
+ `Source ${i + 1}: ${r.title ?? '(no title)'}`,
15
+ `Citation Anchor: \\ue202turn0search${i + 1}`,
16
+ `URL: ${r.link}`,
17
+ r.snippet != null ? `Summary: ${r.snippet}` : '',
18
+ r.date != null ? `Date: ${r.date}` : '',
19
+ r.attribution != null ? `Source: ${r.attribution}` : '',
20
+ '',
21
+ '--- Content Highlights ---',
22
+ ...(r.highlights ?? [])
23
+ .filter((h) => h.text.trim().length > 0)
24
+ .map((h) => `[Relevance: ${h.score.toFixed(2)}]\n${h.text.trim()}`),
25
+ '',
26
+ ]
27
+ .filter(Boolean)
28
+ .join('\n');
29
+ });
30
+ }
31
+ // Ignoring these sections for now
32
+ // // Top stories (news)
33
+ // const topStores = results.topStories ?? [];
34
+ // if (topStores.length) {
35
+ // addSection('News Results');
36
+ // topStores.forEach((r, i) => {
37
+ // output += [
38
+ // `Anchor: \ue202turn0news${i + 1}`,
39
+ // `Title: ${r.title ?? '(no title)'}`,
40
+ // `URL: ${r.link}`,
41
+ // r.snippet != null ? `Snippet: ${r.snippet}` : '',
42
+ // r.date != null ? `Date: ${r.date}` : '',
43
+ // r.attribution != null ? `Source: ${r.attribution}` : '',
44
+ // ''
45
+ // ].filter(Boolean).join('\n');
46
+ // });
47
+ // }
48
+ // // Images
49
+ // const images = results.images ?? [];
50
+ // if (images.length) {
51
+ // addSection('Image Results');
52
+ // images.forEach((img, i) => {
53
+ // output += [
54
+ // `Anchor: \ue202turn0image${i + 1}`,
55
+ // `Title: ${img.title ?? '(no title)'}`,
56
+ // `Image URL: ${img.imageUrl}`,
57
+ // ''
58
+ // ].join('\n');
59
+ // });
60
+ // }
61
+ // Knowledge Graph
62
+ if (results.knowledgeGraph != null) {
63
+ addSection('Knowledge Graph');
64
+ output += [
65
+ `Title: ${results.knowledgeGraph.title ?? '(no title)'}`,
66
+ results.knowledgeGraph.description != null
67
+ ? `Description: ${results.knowledgeGraph.description}`
68
+ : '',
69
+ results.knowledgeGraph.type != null
70
+ ? `Type: ${results.knowledgeGraph.type}`
71
+ : '',
72
+ results.knowledgeGraph.imageUrl != null
73
+ ? `Image URL: ${results.knowledgeGraph.imageUrl}`
74
+ : '',
75
+ results.knowledgeGraph.attributes != null
76
+ ? `Attributes: ${JSON.stringify(results.knowledgeGraph.attributes, null, 2)}`
77
+ : '',
78
+ '',
79
+ ]
80
+ .filter(Boolean)
81
+ .join('\n');
82
+ }
83
+ // Answer Box
84
+ if (results.answerBox != null) {
85
+ addSection('Answer Box');
86
+ output += [
87
+ results.answerBox.title != null
88
+ ? `Title: ${results.answerBox.title}`
89
+ : '',
90
+ results.answerBox.answer != null
91
+ ? `Answer: ${results.answerBox.answer}`
92
+ : '',
93
+ results.answerBox.snippet != null
94
+ ? `Snippet: ${results.answerBox.snippet}`
95
+ : '',
96
+ results.answerBox.date != null ? `Date: ${results.answerBox.date}` : '',
97
+ '',
98
+ ]
99
+ .filter(Boolean)
100
+ .join('\n');
101
+ }
102
+ // People also ask
103
+ const peopleAlsoAsk = results.peopleAlsoAsk ?? [];
104
+ if (peopleAlsoAsk.length) {
105
+ addSection('People Also Ask');
106
+ peopleAlsoAsk.forEach((p, _i) => {
107
+ output += [`Q: ${p.question}`, `A: ${p.answer}`, '']
108
+ .filter(Boolean)
109
+ .join('\n');
110
+ });
111
+ }
112
+ return output.trim();
113
+ }
114
+
115
+ exports.formatResultsForLLM = formatResultsForLLM;
116
+ //# sourceMappingURL=format.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"format.cjs","sources":["../../../../src/tools/search/format.ts"],"sourcesContent":["import type * as t from './types';\n\nexport function formatResultsForLLM(results: t.SearchResultData): string {\n let output = '';\n\n const addSection = (title: string): void => {\n output += `\\n=== ${title} ===\\n`;\n };\n\n // Organic (web) results\n const organic = results.organic ?? [];\n if (organic.length) {\n addSection('Web Results');\n organic.forEach((r, i) => {\n output += [\n `Source ${i + 1}: ${r.title ?? '(no title)'}`,\n `Citation Anchor: \\\\ue202turn0search${i + 1}`,\n `URL: ${r.link}`,\n r.snippet != null ? `Summary: ${r.snippet}` : '',\n r.date != null ? `Date: ${r.date}` : '',\n r.attribution != null ? `Source: ${r.attribution}` : '',\n '',\n '--- Content Highlights ---',\n ...(r.highlights ?? [])\n .filter((h) => h.text.trim().length > 0)\n .map((h) => `[Relevance: ${h.score.toFixed(2)}]\\n${h.text.trim()}`),\n '',\n ]\n .filter(Boolean)\n .join('\\n');\n });\n }\n\n // Ignoring these sections for now\n // // Top stories (news)\n // const topStores = results.topStories ?? [];\n // if (topStores.length) {\n // addSection('News Results');\n // topStores.forEach((r, i) => {\n // output += [\n // `Anchor: \\ue202turn0news${i + 1}`,\n // `Title: ${r.title ?? '(no title)'}`,\n // `URL: ${r.link}`,\n // r.snippet != null ? `Snippet: ${r.snippet}` : '',\n // r.date != null ? `Date: ${r.date}` : '',\n // r.attribution != null ? `Source: ${r.attribution}` : '',\n // ''\n // ].filter(Boolean).join('\\n');\n // });\n // }\n\n // // Images\n // const images = results.images ?? [];\n // if (images.length) {\n // addSection('Image Results');\n // images.forEach((img, i) => {\n // output += [\n // `Anchor: \\ue202turn0image${i + 1}`,\n // `Title: ${img.title ?? '(no title)'}`,\n // `Image URL: ${img.imageUrl}`,\n // ''\n // ].join('\\n');\n // });\n // }\n\n // Knowledge Graph\n if (results.knowledgeGraph != null) {\n addSection('Knowledge Graph');\n output += [\n `Title: ${results.knowledgeGraph.title ?? '(no title)'}`,\n results.knowledgeGraph.description != null\n ? `Description: ${results.knowledgeGraph.description}`\n : '',\n results.knowledgeGraph.type != null\n ? `Type: ${results.knowledgeGraph.type}`\n : '',\n results.knowledgeGraph.imageUrl != null\n ? `Image URL: ${results.knowledgeGraph.imageUrl}`\n : '',\n results.knowledgeGraph.attributes != null\n ? `Attributes: ${JSON.stringify(results.knowledgeGraph.attributes, null, 2)}`\n : '',\n '',\n ]\n .filter(Boolean)\n .join('\\n');\n }\n\n // Answer Box\n if (results.answerBox != null) {\n addSection('Answer Box');\n output += [\n results.answerBox.title != null\n ? `Title: ${results.answerBox.title}`\n : '',\n results.answerBox.answer != null\n ? `Answer: ${results.answerBox.answer}`\n : '',\n results.answerBox.snippet != null\n ? `Snippet: ${results.answerBox.snippet}`\n : '',\n results.answerBox.date != null ? `Date: ${results.answerBox.date}` : '',\n '',\n ]\n .filter(Boolean)\n .join('\\n');\n }\n\n // People also ask\n const peopleAlsoAsk = results.peopleAlsoAsk ?? [];\n if (peopleAlsoAsk.length) {\n addSection('People Also Ask');\n peopleAlsoAsk.forEach((p, _i) => {\n output += [`Q: ${p.question}`, `A: ${p.answer}`, '']\n .filter(Boolean)\n .join('\\n');\n });\n }\n\n return output.trim();\n}\n"],"names":[],"mappings":";;AAEM,SAAU,mBAAmB,CAAC,OAA2B,EAAA;IAC7D,IAAI,MAAM,GAAG,EAAE;AAEf,IAAA,MAAM,UAAU,GAAG,CAAC,KAAa,KAAU;AACzC,QAAA,MAAM,IAAI,CAAA,MAAA,EAAS,KAAK,CAAA,MAAA,CAAQ;AAClC,KAAC;;AAGD,IAAA,MAAM,OAAO,GAAG,OAAO,CAAC,OAAO,IAAI,EAAE;AACrC,IAAA,IAAI,OAAO,CAAC,MAAM,EAAE;QAClB,UAAU,CAAC,aAAa,CAAC;QACzB,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,CAAC,KAAI;AACvB,YAAA,MAAM,IAAI;gBACR,CAAU,OAAA,EAAA,CAAC,GAAG,CAAC,CAAA,EAAA,EAAK,CAAC,CAAC,KAAK,IAAI,YAAY,CAAE,CAAA;gBAC7C,CAAsC,mCAAA,EAAA,CAAC,GAAG,CAAC,CAAE,CAAA;gBAC7C,CAAQ,KAAA,EAAA,CAAC,CAAC,IAAI,CAAE,CAAA;AAChB,gBAAA,CAAC,CAAC,OAAO,IAAI,IAAI,GAAG,CAAY,SAAA,EAAA,CAAC,CAAC,OAAO,CAAA,CAAE,GAAG,EAAE;AAChD,gBAAA,CAAC,CAAC,IAAI,IAAI,IAAI,GAAG,CAAS,MAAA,EAAA,CAAC,CAAC,IAAI,CAAA,CAAE,GAAG,EAAE;AACvC,gBAAA,CAAC,CAAC,WAAW,IAAI,IAAI,GAAG,CAAW,QAAA,EAAA,CAAC,CAAC,WAAW,CAAA,CAAE,GAAG,EAAE;gBACvD,EAAE;gBACF,4BAA4B;AAC5B,gBAAA,GAAG,CAAC,CAAC,CAAC,UAAU,IAAI,EA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+ 'use strict';
2
+
3
+ // 2. Pre-compile all regular expressions (only do this once)
4
+ // Group patterns by priority for early returns
5
+ const priorityPatterns = [
6
+ // High priority patterns (structural)
7
+ [
8
+ { regex: /\n\n/g }, // Double newline (paragraph break)
9
+ { regex: /\n/g }, // Single newline
10
+ { regex: /={3,}\s*\n|-{3,}\s*\n/g }, // Section separators
11
+ ],
12
+ // Medium priority (semantic)
13
+ [
14
+ { regex: /[.!?][")\]]?\s/g }, // End of sentence
15
+ { regex: /;\s/g }, // Semicolon
16
+ { regex: /:\s/g }, // Colon
17
+ ],
18
+ // Low priority (any breaks)
19
+ [
20
+ { regex: /,\s/g }, // Comma
21
+ { regex: /\s-\s/g }, // Dash surrounded by spaces
22
+ { regex: /\s/g }, // Any space
23
+ ],
24
+ ];
25
+ function findFirstMatch(text, regex) {
26
+ // Reset regex
27
+ regex.lastIndex = 0;
28
+ // For very long texts, try chunking
29
+ if (text.length > 10000) {
30
+ const chunkSize = 2000;
31
+ let position = 0;
32
+ while (position < text.length) {
33
+ const chunk = text.substring(position, position + chunkSize);
34
+ regex.lastIndex = 0;
35
+ const match = regex.exec(chunk);
36
+ if (match) {
37
+ return position + match.index;
38
+ }
39
+ // Move to next chunk with some overlap
40
+ position += chunkSize - 100;
41
+ if (position >= text.length)
42
+ break;
43
+ }
44
+ return -1;
45
+ }
46
+ // For shorter texts, normal regex search
47
+ const match = regex.exec(text);
48
+ return match ? match.index : -1;
49
+ }
50
+ // 3. Optimized boundary finding functions
51
+ function findLastMatch(text, regex) {
52
+ // Reset regex state
53
+ regex.lastIndex = 0;
54
+ let lastIndex = -1;
55
+ let lastLength = 0;
56
+ let match;
57
+ // For very long texts, use a different approach to avoid regex engine slowdowns
58
+ if (text.length > 10000) {
59
+ // Try dividing the text into chunks for faster processing
60
+ const chunkSize = 2000;
61
+ let startPosition = Math.max(0, text.length - chunkSize);
62
+ while (startPosition >= 0) {
63
+ const chunk = text.substring(startPosition, startPosition + chunkSize);
64
+ regex.lastIndex = 0;
65
+ let chunkLastIndex = -1;
66
+ let chunkLastLength = 0;
67
+ while ((match = regex.exec(chunk)) !== null) {
68
+ chunkLastIndex = match.index;
69
+ chunkLastLength = match[0].length;
70
+ }
71
+ if (chunkLastIndex !== -1) {
72
+ return startPosition + chunkLastIndex + chunkLastLength;
73
+ }
74
+ // Move to previous chunk with some overlap
75
+ startPosition = Math.max(0, startPosition - chunkSize + 100) - 1;
76
+ if (startPosition <= 0)
77
+ break;
78
+ }
79
+ return -1;
80
+ }
81
+ // For shorter texts, normal regex search
82
+ while ((match = regex.exec(text)) !== null) {
83
+ lastIndex = match.index;
84
+ lastLength = match[0].length;
85
+ }
86
+ return lastIndex === -1 ? -1 : lastIndex + lastLength;
87
+ }
88
+ // 4. Find the best boundary with priority groups
89
+ function findBestBoundary(text, direction = 'backward') {
90
+ if (!text || text.length === 0)
91
+ return 0;
92
+ // Try each priority group
93
+ for (const patternGroup of priorityPatterns) {
94
+ for (const pattern of patternGroup) {
95
+ const position = direction === 'backward'
96
+ ? findLastMatch(text, pattern.regex)
97
+ : findFirstMatch(text, pattern.regex);
98
+ if (position !== -1) {
99
+ return position;
100
+ }
101
+ }
102
+ }
103
+ // No match found, use character boundary
104
+ return direction === 'backward' ? text.length : 0;
105
+ }
106
+ /**
107
+ * Expand highlights in search results using smart boundary detection.
108
+ *
109
+ * This implementation finds natural text boundaries like paragraphs, sentences,
110
+ * and phrases to provide context while maintaining readability.
111
+ *
112
+ * @param searchResults - Search results object
113
+ * @param mainExpandBy - Primary expansion size on each side (default: 300)
114
+ * @param separatorExpandBy - Additional range to look for separators (default: 150)
115
+ * @returns Copy of search results with expanded highlights
116
+ */
117
+ function expandHighlights(searchResults, mainExpandBy = 300, separatorExpandBy = 150) {
118
+ // 1. Avoid full deep copy - only copy what we modify
119
+ const resultCopy = { ...searchResults };
120
+ // Only deep copy the relevant arrays
121
+ if (resultCopy.organic) {
122
+ resultCopy.organic = [...resultCopy.organic];
123
+ }
124
+ if (resultCopy.topStories) {
125
+ resultCopy.topStories = [...resultCopy.topStories];
126
+ }
127
+ // 5. Process the results efficiently
128
+ const processResultTypes = ['organic', 'topStories'];
129
+ for (const resultType of processResultTypes) {
130
+ if (!resultCopy[resultType])
131
+ continue;
132
+ // Map results to new array with modified highlights
133
+ resultCopy[resultType] = resultCopy[resultType]?.map((result) => {
134
+ if (result.content == null ||
135
+ result.content === '' ||
136
+ !result.highlights ||
137
+ result.highlights.length === 0) {
138
+ return result; // No modification needed
139
+ }
140
+ // Create a shallow copy with expanded highlights
141
+ const resultCopy = { ...result };
142
+ const content = result.content;
143
+ const highlights = [];
144
+ // Process each highlight
145
+ for (const highlight of result.highlights) {
146
+ const highlightText = highlight.text;
147
+ let startPos = content.indexOf(highlightText);
148
+ let highlightLen = highlightText.length;
149
+ if (startPos === -1) {
150
+ // Try with stripped whitespace
151
+ const strippedHighlight = highlightText.trim();
152
+ startPos = content.indexOf(strippedHighlight);
153
+ if (startPos === -1) {
154
+ highlights.push({
155
+ text: highlight.text,
156
+ score: highlight.score,
157
+ });
158
+ continue;
159
+ }
160
+ highlightLen = strippedHighlight.length;
161
+ }
162
+ // Calculate boundaries
163
+ const mainStart = Math.max(0, startPos - mainExpandBy);
164
+ const mainEnd = Math.min(content.length, startPos + highlightLen + mainExpandBy);
165
+ const separatorStart = Math.max(0, mainStart - separatorExpandBy);
166
+ const separatorEnd = Math.min(content.length, mainEnd + separatorExpandBy);
167
+ // Extract text segments
168
+ const headText = content.substring(separatorStart, mainStart);
169
+ const tailText = content.substring(mainEnd, separatorEnd);
170
+ // Find natural boundaries
171
+ const bestHeadBoundary = findBestBoundary(headText, 'backward');
172
+ const bestTailBoundary = findBestBoundary(tailText, 'forward');
173
+ // Calculate final positions
174
+ const finalStart = separatorStart + bestHeadBoundary;
175
+ const finalEnd = mainEnd + bestTailBoundary;
176
+ // Extract the expanded highlight
177
+ const expandedHighlightText = content
178
+ .substring(finalStart, finalEnd)
179
+ .trim();
180
+ highlights.push({
181
+ text: expandedHighlightText,
182
+ score: highlight.score,
183
+ });
184
+ }
185
+ resultCopy.highlights = highlights;
186
+ return resultCopy;
187
+ });
188
+ }
189
+ return resultCopy;
190
+ }
191
+
192
+ exports.expandHighlights = expandHighlights;
193
+ //# sourceMappingURL=highlights.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"highlights.cjs","sources":["../../../../src/tools/search/highlights.ts"],"sourcesContent":["import type * as t from './types';\n\n// 2. Pre-compile all regular expressions (only do this once)\n// Group patterns by priority for early returns\nconst priorityPatterns = [\n // High priority patterns (structural)\n [\n { regex: /\\n\\n/g }, // Double newline (paragraph break)\n { regex: /\\n/g }, // Single newline\n { regex: /={3,}\\s*\\n|-{3,}\\s*\\n/g }, // Section separators\n ],\n // Medium priority (semantic)\n [\n { regex: /[.!?][\")\\]]?\\s/g }, // End of sentence\n { regex: /;\\s/g }, // Semicolon\n { regex: /:\\s/g }, // Colon\n ],\n // Low priority (any breaks)\n [\n { regex: /,\\s/g }, // Comma\n { regex: /\\s-\\s/g }, // Dash surrounded by spaces\n { regex: /\\s/g }, // Any space\n ],\n];\n\nfunction findFirstMatch(text: string, regex: RegExp): number {\n // Reset regex\n regex.lastIndex = 0;\n\n // For very long texts, try chunking\n if (text.length > 10000) {\n const chunkSize = 2000;\n let position = 0;\n\n while (position < text.length) {\n const chunk = text.substring(position, position + chunkSize);\n regex.lastIndex = 0;\n\n const match = regex.exec(chunk);\n if (match) {\n return position + match.index;\n }\n\n // Move to next chunk with some overlap\n position += chunkSize - 100;\n if (position >= text.length) break;\n }\n return -1;\n }\n\n // For shorter texts, normal regex search\n const match = regex.exec(text);\n return match ? match.index : -1;\n}\n\n// 3. Optimized boundary finding functions\nfunction findLastMatch(text: string, regex: RegExp): number {\n // Reset regex state\n regex.lastIndex = 0;\n\n let lastIndex = -1;\n let lastLength = 0;\n let match;\n\n // For very long texts, use a different approach to avoid regex engine slowdowns\n if (text.length > 10000) {\n // Try dividing the text into chunks for faster processing\n const chunkSize = 2000;\n let startPosition = Math.max(0, text.length - chunkSize);\n\n while (startPosition >= 0) {\n const chunk = text.substring(startPosition, startPosition + chunkSize);\n regex.lastIndex = 0;\n\n let chunkLastIndex = -1;\n let chunkLastLength = 0;\n\n while ((match = regex.exec(chunk)) !== null) {\n chunkLastIndex = match.index;\n chunkLastLength = match[0].length;\n }\n\n if (chunkLastIndex !== -1) {\n return startPosition + chunkLastIndex + chunkLastLength;\n }\n\n // Move to previous chunk with some overlap\n startPosition = Math.max(0, startPosition - chunkSize + 100) - 1;\n if (startPosition <= 0) break;\n }\n return -1;\n }\n\n // For shorter texts, normal regex search\n while ((match = regex.exec(text)) !== null) {\n lastIndex = match.index;\n lastLength = match[0].length;\n }\n\n return lastIndex === -1 ? -1 : lastIndex + lastLength;\n}\n\n// 4. Find the best boundary with priority groups\nfunction findBestBoundary(text: string, direction = 'backward'): number {\n if (!text || text.length === 0) return 0;\n\n // Try each priority group\n for (const patternGroup of priorityPatterns) {\n for (const pattern of patternGroup) {\n const position =\n direction === 'backward'\n ? findLastMatch(text, pattern.regex)\n : findFirstMatch(text, pattern.regex);\n\n if (position !== -1) {\n return position;\n }\n }\n }\n\n // No match found, use character boundary\n return direction === 'backward' ? text.length : 0;\n}\n\n/**\n * Expand highlights in search results using smart boundary detection.\n *\n * This implementation finds natural text boundaries like paragraphs, sentences,\n * and phrases to provide context while maintaining readability.\n *\n * @param searchResults - Search results object\n * @param mainExpandBy - Primary expansion size on each side (default: 300)\n * @param separatorExpandBy - Additional range to look for separators (default: 150)\n * @returns Copy of search results with expanded highlights\n */\nexport function expandHighlights(\n searchResults: t.SearchResultData,\n mainExpandBy = 300,\n separatorExpandBy = 150\n): t.SearchResultData {\n // 1. Avoid full deep copy - only copy what we modify\n const resultCopy = { ...searchResults };\n\n // Only deep copy the relevant arrays\n if (resultCopy.organic) {\n resultCopy.organic = [...resultCopy.organic];\n }\n if (resultCopy.topStories) {\n resultCopy.topStories = [...resultCopy.topStories];\n }\n\n // 5. Process the results efficiently\n const processResultTypes = ['organic', 'topStories'] as const;\n\n for (const resultType of processResultTypes) {\n if (!resultCopy[resultType as 'organic' | 'topStories']) continue;\n\n // Map results to new array with modified highlights\n resultCopy[resultType] = resultCopy[resultType]?.map((result) => {\n if (\n result.content == null ||\n result.content === '' ||\n !result.highlights ||\n result.highlights.length === 0\n ) {\n return result; // No modification needed\n }\n\n // Create a shallow copy with expanded highlights\n const resultCopy = { ...result };\n const content = result.content;\n const highlights = [];\n\n // Process each highlight\n for (const highlight of result.highlights) {\n const highlightText = highlight.text;\n\n let startPos = content.indexOf(highlightText);\n let highlightLen = highlightText.length;\n\n if (startPos === -1) {\n // Try with stripped whitespace\n const strippedHighlight = highlightText.trim();\n startPos = content.indexOf(strippedHighlight);\n\n if (startPos === -1) {\n highlights.push({\n text: highlight.text,\n score: highlight.score,\n });\n continue;\n }\n highlightLen = strippedHighlight.length;\n }\n\n // Calculate boundaries\n const mainStart = Math.max(0, startPos - mainExpandBy);\n const mainEnd = Math.min(\n content.length,\n startPos + highlightLen + mainExpandBy\n );\n\n const separatorStart = Math.max(0, mainStart - separatorExpandBy);\n const separatorEnd = Math.min(\n content.length,\n mainEnd + separatorExpandBy\n );\n\n // Extract text segments\n const headText = content.substring(separatorStart, mainStart);\n const tailText = content.substring(mainEnd, separatorEnd);\n\n // Find natural boundaries\n const bestHeadBoundary = findBestBoundary(headText, 'backward');\n const bestTailBoundary = findBestBoundary(tailText, 'forward');\n\n // Calculate final positions\n const finalStart = separatorStart + bestHeadBoundary;\n const finalEnd = mainEnd + bestTailBoundary;\n\n // Extract the expanded highlight\n const expandedHighlightText = content\n .substring(finalStart, finalEnd)\n .trim();\n highlights.push({\n text: expandedHighlightText,\n score: highlight.score,\n });\n }\n\n resultCopy.highlights = highlights;\n return resultCopy;\n });\n }\n\n return resultCopy;\n}\n"],"names":[],"mappings":";;AAEA;AACA;AACA,MAAM,gBAAgB,GAAG;;AAEvB,IAAA;AACE,QAAA,EAAE,KAAK,EAAE,OAAO,EA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EACd,QAAQ,GAAG,YAAY,GAAG,YAAY,CACvC;AAED,gBAAA,MAAM,cAAc,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,SAAS,GAAG,iBAAiB,CAAC;AACjE,gBAAA,MAAM,YAAY,GAAG,IAAI,CAAC,GAAG,CAC3B,OAAO,CAAC,MAAM,EACd,OAAO,GAAG,iBAAiB,CAC5B;;gBAGD,MAAM,QAAQ,GAAG,OAAO,CAAC,SAAS,CAAC,cAAc,EAAE,SAAS,CAAC;gBAC7D,MAAM,QAAQ,GAAG,OAAO,CAAC,SAAS,CAAC,OAAO,EAAE,YAAY,CAAC;;gBAGzD,MAAM,gBAAgB,GAAG,gBAAgB,CAAC,QAAQ,EAAE,UAAU,CAAC;gBAC/D,MAAM,gBAAgB,GAAG,gBAAgB,CAAC,QAAQ,EAAE,SAAS,CAAC;;AAG9D,gBAAA,MAAM,UAAU,GAAG,cAAc,GAAG,gBAAgB;AACpD,gBAAA,MAAM,QAAQ,GAAG,OAAO,GAAG,gBAAgB;;gBAG3C,MAAM,qBAAqB,GAAG;AAC3B,qBAAA,SAAS,CAAC,UAAU,EAAE,QAAQ;AAC9B,qBAAA,IAAI,EAAE;gBACT,UAAU,CAAC,IAAI,CAAC;AACd,oBAAA,IAAI,EAAE,qBAAqB;oBAC3B,KAAK,EAAE,SAAS,CAAC,KAAK;AACvB,iBAAA,CAAC;;AAGJ,YAAA,UAAU,CAAC,UAAU,GAAG,UAAU;AAClC,YAAA,OAAO,UAAU;AACnB,SAAC,CAAC;;AAGJ,IAAA,OAAO,UAAU;AACnB;;;;"}
@@ -0,0 +1,187 @@
1
+ 'use strict';
2
+
3
+ var axios = require('axios');
4
+
5
+ /* eslint-disable no-console */
6
+ class BaseReranker {
7
+ apiKey;
8
+ constructor() {
9
+ // Each specific reranker will set its API key
10
+ }
11
+ getDefaultRanking(documents, topK) {
12
+ return documents
13
+ .slice(0, Math.min(topK, documents.length))
14
+ .map((doc) => ({ text: doc, score: 0 }));
15
+ }
16
+ logDocumentSamples(documents) {
17
+ console.log('Sample documents being sent to API:');
18
+ for (let i = 0; i < Math.min(3, documents.length); i++) {
19
+ console.log(`Document ${i}: ${documents[i].substring(0, 100)}...`);
20
+ }
21
+ }
22
+ }
23
+ class JinaReranker extends BaseReranker {
24
+ constructor({ apiKey = process.env.JINA_API_KEY }) {
25
+ super();
26
+ this.apiKey = apiKey;
27
+ }
28
+ async rerank(query, documents, topK = 5) {
29
+ console.log(`Reranking ${documents.length} documents with Jina`);
30
+ try {
31
+ if (this.apiKey == null || this.apiKey === '') {
32
+ console.warn('JINA_API_KEY is not set. Using default ranking.');
33
+ return this.getDefaultRanking(documents, topK);
34
+ }
35
+ this.logDocumentSamples(documents);
36
+ const requestData = {
37
+ model: 'jina-reranker-v2-base-multilingual',
38
+ query: query,
39
+ top_n: topK,
40
+ documents: documents,
41
+ return_documents: true,
42
+ };
43
+ const response = await axios.post('https://api.jina.ai/v1/rerank', requestData, {
44
+ headers: {
45
+ 'Content-Type': 'application/json',
46
+ Authorization: `Bearer ${this.apiKey}`,
47
+ },
48
+ });
49
+ // Log the response data structure
50
+ console.log('Jina API response structure:');
51
+ console.log('Model:', response.data?.model);
52
+ console.log('Usage:', response.data?.usage);
53
+ console.log('Results count:', response.data?.results.length);
54
+ // Log a sample of the results
55
+ if ((response.data?.results.length ?? 0) > 0) {
56
+ console.log('Sample result:', JSON.stringify(response.data?.results[0], null, 2));
57
+ }
58
+ if (response.data && response.data.results.length) {
59
+ return response.data.results.map((result) => {
60
+ const docIndex = result.index;
61
+ const score = result.relevance_score;
62
+ let text = '';
63
+ // If return_documents is true, the document field will be present
64
+ if (result.document != null) {
65
+ const doc = result.document;
66
+ if (typeof doc === 'object' && 'text' in doc) {
67
+ text = doc.text;
68
+ }
69
+ else if (typeof doc === 'string') {
70
+ text = doc;
71
+ }
72
+ }
73
+ else {
74
+ // Otherwise, use the index to get the document
75
+ text = documents[docIndex];
76
+ }
77
+ return { text, score };
78
+ });
79
+ }
80
+ else {
81
+ console.warn('Unexpected response format from Jina API. Using default ranking.');
82
+ return this.getDefaultRanking(documents, topK);
83
+ }
84
+ }
85
+ catch (error) {
86
+ console.error('Error using Jina reranker:', error);
87
+ // Fallback to default ranking on error
88
+ return this.getDefaultRanking(documents, topK);
89
+ }
90
+ }
91
+ }
92
+ class CohereReranker extends BaseReranker {
93
+ constructor({ apiKey = process.env.COHERE_API_KEY }) {
94
+ super();
95
+ this.apiKey = apiKey;
96
+ }
97
+ async rerank(query, documents, topK = 5) {
98
+ console.log(`Reranking ${documents.length} documents with Cohere`);
99
+ try {
100
+ if (this.apiKey == null || this.apiKey === '') {
101
+ console.warn('COHERE_API_KEY is not set. Using default ranking.');
102
+ return this.getDefaultRanking(documents, topK);
103
+ }
104
+ this.logDocumentSamples(documents);
105
+ const requestData = {
106
+ model: 'rerank-v3.5',
107
+ query: query,
108
+ top_n: topK,
109
+ documents: documents,
110
+ };
111
+ const response = await axios.post('https://api.cohere.com/v2/rerank', requestData, {
112
+ headers: {
113
+ 'Content-Type': 'application/json',
114
+ Authorization: `Bearer ${this.apiKey}`,
115
+ },
116
+ });
117
+ // Log the response data structure
118
+ console.log('Cohere API response structure:');
119
+ console.log('ID:', response.data?.id);
120
+ console.log('Meta:', response.data?.meta);
121
+ console.log('Results count:', response.data?.results.length);
122
+ // Log a sample of the results
123
+ if ((response.data?.results.length ?? 0) > 0) {
124
+ console.log('Sample result:', JSON.stringify(response.data?.results[0], null, 2));
125
+ }
126
+ if (response.data && response.data.results.length) {
127
+ return response.data.results.map((result) => {
128
+ const docIndex = result.index;
129
+ const score = result.relevance_score;
130
+ const text = documents[docIndex];
131
+ return { text, score };
132
+ });
133
+ }
134
+ else {
135
+ console.warn('Unexpected response format from Cohere API. Using default ranking.');
136
+ return this.getDefaultRanking(documents, topK);
137
+ }
138
+ }
139
+ catch (error) {
140
+ console.error('Error using Cohere reranker:', error);
141
+ // Fallback to default ranking on error
142
+ return this.getDefaultRanking(documents, topK);
143
+ }
144
+ }
145
+ }
146
+ class InfinityReranker extends BaseReranker {
147
+ constructor() {
148
+ super();
149
+ // No API key needed for the placeholder implementation
150
+ }
151
+ async rerank(query, documents, topK = 5) {
152
+ console.log(`Reranking ${documents.length} documents with Infinity (placeholder)`);
153
+ // This would be replaced with actual Infinity reranker implementation
154
+ return this.getDefaultRanking(documents, topK);
155
+ }
156
+ }
157
+ /**
158
+ * Creates the appropriate reranker based on type and configuration
159
+ */
160
+ const createReranker = (config) => {
161
+ const { rerankerType, jinaApiKey, cohereApiKey } = config;
162
+ switch (rerankerType.toLowerCase()) {
163
+ case 'jina':
164
+ return new JinaReranker({ apiKey: jinaApiKey });
165
+ case 'cohere':
166
+ return new CohereReranker({ apiKey: cohereApiKey });
167
+ case 'infinity':
168
+ return new InfinityReranker();
169
+ case 'none':
170
+ console.log('Skipping reranking as reranker is set to "none"');
171
+ return undefined;
172
+ default:
173
+ console.warn(`Unknown reranker type: ${rerankerType}. Defaulting to InfinityReranker.`);
174
+ return new JinaReranker({ apiKey: jinaApiKey });
175
+ }
176
+ };
177
+ // Example usage:
178
+ // const jinaReranker = new JinaReranker();
179
+ // const cohereReranker = new CohereReranker();
180
+ // const infinityReranker = new InfinityReranker();
181
+
182
+ exports.BaseReranker = BaseReranker;
183
+ exports.CohereReranker = CohereReranker;
184
+ exports.InfinityReranker = InfinityReranker;
185
+ exports.JinaReranker = JinaReranker;
186
+ exports.createReranker = createReranker;
187
+ //# sourceMappingURL=rerankers.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rerankers.cjs","sources":["../../../../src/tools/search/rerankers.ts"],"sourcesContent":["/* eslint-disable no-console */\nimport axios from 'axios';\nimport type * as t from './types';\n\nexport abstract class BaseReranker {\n protected apiKey: string | undefined;\n\n constructor() {\n // Each specific reranker will set its API key\n }\n\n abstract rerank(\n query: string,\n documents: string[],\n topK?: number\n ): Promise<t.Highlight[]>;\n\n protected getDefaultRanking(\n documents: string[],\n topK: number\n ): t.Highlight[] {\n return documents\n .slice(0, Math.min(topK, documents.length))\n .map((doc) => ({ text: doc, score: 0 }));\n }\n\n protected logDocumentSamples(documents: string[]): void {\n console.log('Sample documents being sent to API:');\n for (let i = 0; i < Math.min(3, documents.length); i++) {\n console.log(`Document ${i}: ${documents[i].substring(0, 100)}...`);\n }\n }\n}\n\nexport class JinaReranker extends BaseReranker {\n constructor({ apiKey = process.env.JINA_API_KEY }: { apiKey?: string }) {\n super();\n this.apiKey = apiKey;\n }\n\n async rerank(\n query: string,\n documents: string[],\n topK: number = 5\n ): Promise<t.Highlight[]> {\n console.log(`Reranking ${documents.length} documents with Jina`);\n\n try {\n if (this.apiKey == null || this.apiKey === '') {\n console.warn('JINA_API_KEY is not set. Using default ranking.');\n return this.getDefaultRanking(documents, topK);\n }\n\n this.logDocumentSamples(documents);\n\n const requestData = {\n model: 'jina-reranker-v2-base-multilingual',\n query: query,\n top_n: topK,\n documents: documents,\n return_documents: true,\n };\n\n const response = await axios.post<t.JinaRerankerResponse | undefined>(\n 'https://api.jina.ai/v1/rerank',\n requestData,\n {\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${this.apiKey}`,\n },\n }\n );\n\n // Log the response data structure\n console.log('Jina API response structure:');\n console.log('Model:', response.data?.model);\n console.log('Usage:', response.data?.usage);\n console.log('Results count:', response.data?.results.length);\n\n // Log a sample of the results\n if ((response.data?.results.length ?? 0) > 0) {\n console.log(\n 'Sample result:',\n JSON.stringify(response.data?.results[0], null, 2)\n );\n }\n\n if (response.data && response.data.results.length) {\n return response.data.results.map((result) => {\n const docIndex = result.index;\n const score = result.relevance_score;\n let text = '';\n\n // If return_documents is true, the document field will be present\n if (result.document != null) {\n const doc = result.document;\n if (typeof doc === 'object' && 'text' in doc) {\n text = doc.text;\n } else if (typeof doc === 'string') {\n text = doc;\n }\n } else {\n // Otherwise, use the index to get the document\n text = documents[docIndex];\n }\n\n return { text, score };\n });\n } else {\n console.warn(\n 'Unexpected response format from Jina API. Using default ranking.'\n );\n return this.getDefaultRanking(documents, topK);\n }\n } catch (error) {\n console.error('Error using Jina reranker:', error);\n // Fallback to default ranking on error\n return this.getDefaultRanking(documents, topK);\n }\n }\n}\n\nexport class CohereReranker extends BaseReranker {\n constructor({ apiKey = process.env.COHERE_API_KEY }: { apiKey?: string }) {\n super();\n this.apiKey = apiKey;\n }\n\n async rerank(\n query: string,\n documents: string[],\n topK: number = 5\n ): Promise<t.Highlight[]> {\n console.log(`Reranking ${documents.length} documents with Cohere`);\n\n try {\n if (this.apiKey == null || this.apiKey === '') {\n console.warn('COHERE_API_KEY is not set. Using default ranking.');\n return this.getDefaultRanking(documents, topK);\n }\n\n this.logDocumentSamples(documents);\n\n const requestData = {\n model: 'rerank-v3.5',\n query: query,\n top_n: topK,\n documents: documents,\n };\n\n const response = await axios.post<t.CohereRerankerResponse | undefined>(\n 'https://api.cohere.com/v2/rerank',\n requestData,\n {\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${this.apiKey}`,\n },\n }\n );\n\n // Log the response data structure\n console.log('Cohere API response structure:');\n console.log('ID:', response.data?.id);\n console.log('Meta:', response.data?.meta);\n console.log('Results count:', response.data?.results.length);\n\n // Log a sample of the results\n if ((response.data?.results.length ?? 0) > 0) {\n console.log(\n 'Sample result:',\n JSON.stringify(response.data?.results[0], null, 2)\n );\n }\n\n if (response.data && response.data.results.length) {\n return response.data.results.map((result) => {\n const docIndex = result.index;\n const score = result.relevance_score;\n const text = documents[docIndex];\n return { text, score };\n });\n } else {\n console.warn(\n 'Unexpected response format from Cohere API. Using default ranking.'\n );\n return this.getDefaultRanking(documents, topK);\n }\n } catch (error) {\n console.error('Error using Cohere reranker:', error);\n // Fallback to default ranking on error\n return this.getDefaultRanking(documents, topK);\n }\n }\n}\n\nexport class InfinityReranker extends BaseReranker {\n constructor() {\n super();\n // No API key needed for the placeholder implementation\n }\n\n async rerank(\n query: string,\n documents: string[],\n topK: number = 5\n ): Promise<t.Highlight[]> {\n console.log(\n `Reranking ${documents.length} documents with Infinity (placeholder)`\n );\n // This would be replaced with actual Infinity reranker implementation\n return this.getDefaultRanking(documents, topK);\n }\n}\n\n/**\n * Creates the appropriate reranker based on type and configuration\n */\nexport const createReranker = (config: {\n rerankerType: t.RerankerType;\n jinaApiKey?: string;\n cohereApiKey?: string;\n}): BaseReranker | undefined => {\n const { rerankerType, jinaApiKey, cohereApiKey } = config;\n\n switch (rerankerType.toLowerCase()) {\n case 'jina':\n return new JinaReranker({ apiKey: jinaApiKey });\n case 'cohere':\n return new CohereReranker({ apiKey: cohereApiKey });\n case 'infinity':\n return new InfinityReranker();\n case 'none':\n console.log('Skipping reranking as reranker is set to \"none\"');\n return undefined;\n default:\n console.warn(\n `Unknown reranker type: ${rerankerType}. Defaulting to InfinityReranker.`\n );\n return new JinaReranker({ apiKey: jinaApiKey });\n }\n};\n\n// Example usage:\n// const jinaReranker = new JinaReranker();\n// const cohereReranker = new CohereReranker();\n// const infinityReranker = new InfinityReranker();\n"],"names":[],"mappings":";;;;AAAA;MAIsB,YAAY,CAAA;AACtB,IAAA,MAAM;AAEhB,IAAA,WAAA,GAAA;;;IAUU,iBAAiB,CACzB,SAAmB,EACnB,IAAY,EAAA;AAEZ,QAAA,OAAO;AACJ,aAAA,KAAK,CAAC,CAAC,EAAE,IAAI,CAAC,GAAG,CAAC,IAAI,EAAE,SAAS,CAAC,MAAM,CAAC;AACzC,aAAA,GAAG,CAAC,CAAC,GAAG,MAAM,EAAE,IAAI,EAAE,GAAG,EAAE,KAAK,EAAE,CAAC,EAAE,CAAC,CAAC;;AAGlC,IAAA,kBAAkB,CAAC,SAAmB,EAAA;AAC9C,QAAA,OAAO,CAAC,GAAG,CAAC,qCAAqC,CAAC;QAClD,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,SAAS,CAAC,MAAM,CAAC,EAAE,CAAC,EAAE,EAAE;AACtD,YAAA,OAAO,CAAC,GAAG,CAAC,YA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