@librechat/agents 4.2.13 → 4.2.14

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 (121) hide show
  1. package/dist/cjs/graphs/Graph.cjs +45 -3
  2. package/dist/cjs/graphs/Graph.cjs.map +1 -1
  3. package/dist/cjs/harness/providerText.cjs +1 -0
  4. package/dist/cjs/harness/providerText.cjs.map +1 -1
  5. package/dist/cjs/llm/google/utils/signatures.cjs +22 -14
  6. package/dist/cjs/llm/google/utils/signatures.cjs.map +1 -1
  7. package/dist/cjs/llm/invoke.cjs +122 -13
  8. package/dist/cjs/llm/invoke.cjs.map +1 -1
  9. package/dist/cjs/llm/openai/index.cjs +8 -2
  10. package/dist/cjs/llm/openai/index.cjs.map +1 -1
  11. package/dist/cjs/llm/openai/typedContent.cjs +94 -0
  12. package/dist/cjs/llm/openai/typedContent.cjs.map +1 -0
  13. package/dist/cjs/llm/prepareProviderRequest.cjs +80 -3
  14. package/dist/cjs/llm/prepareProviderRequest.cjs.map +1 -1
  15. package/dist/cjs/llm/providerTextBatch.cjs +128 -0
  16. package/dist/cjs/llm/providerTextBatch.cjs.map +1 -0
  17. package/dist/cjs/llm/providerTextBoundary.cjs +81 -12
  18. package/dist/cjs/llm/providerTextBoundary.cjs.map +1 -1
  19. package/dist/cjs/main.cjs +2 -0
  20. package/dist/cjs/protection/providerText.cjs +56 -6
  21. package/dist/cjs/protection/providerText.cjs.map +1 -1
  22. package/dist/cjs/protection/providerTextAdmission.cjs +5 -0
  23. package/dist/cjs/protection/providerTextAdmission.cjs.map +1 -1
  24. package/dist/cjs/run.cjs +7 -2
  25. package/dist/cjs/run.cjs.map +1 -1
  26. package/dist/cjs/runtime/client.cjs +2 -0
  27. package/dist/cjs/runtime/client.cjs.map +1 -1
  28. package/dist/cjs/stream.cjs +9 -2
  29. package/dist/cjs/stream.cjs.map +1 -1
  30. package/dist/cjs/tools/handlers.cjs +47 -1
  31. package/dist/cjs/tools/handlers.cjs.map +1 -1
  32. package/dist/cjs/tools/search/citations.cjs +194 -0
  33. package/dist/cjs/tools/search/citations.cjs.map +1 -0
  34. package/dist/cjs/tools/search/firecrawl.cjs +4 -9
  35. package/dist/cjs/tools/search/firecrawl.cjs.map +1 -1
  36. package/dist/cjs/tools/search/google.cjs +68 -0
  37. package/dist/cjs/tools/search/google.cjs.map +1 -0
  38. package/dist/cjs/tools/search/openai.cjs +80 -0
  39. package/dist/cjs/tools/search/openai.cjs.map +1 -0
  40. package/dist/cjs/utils/tokens.cjs +5 -0
  41. package/dist/cjs/utils/tokens.cjs.map +1 -1
  42. package/dist/esm/graphs/Graph.mjs +46 -4
  43. package/dist/esm/graphs/Graph.mjs.map +1 -1
  44. package/dist/esm/harness/providerText.mjs +1 -0
  45. package/dist/esm/harness/providerText.mjs.map +1 -1
  46. package/dist/esm/llm/google/utils/signatures.mjs +22 -14
  47. package/dist/esm/llm/google/utils/signatures.mjs.map +1 -1
  48. package/dist/esm/llm/invoke.mjs +124 -15
  49. package/dist/esm/llm/invoke.mjs.map +1 -1
  50. package/dist/esm/llm/openai/index.mjs +8 -2
  51. package/dist/esm/llm/openai/index.mjs.map +1 -1
  52. package/dist/esm/llm/openai/typedContent.mjs +93 -0
  53. package/dist/esm/llm/openai/typedContent.mjs.map +1 -0
  54. package/dist/esm/llm/prepareProviderRequest.mjs +80 -3
  55. package/dist/esm/llm/prepareProviderRequest.mjs.map +1 -1
  56. package/dist/esm/llm/providerTextBatch.mjs +128 -0
  57. package/dist/esm/llm/providerTextBatch.mjs.map +1 -0
  58. package/dist/esm/llm/providerTextBoundary.mjs +81 -12
  59. package/dist/esm/llm/providerTextBoundary.mjs.map +1 -1
  60. package/dist/esm/main.mjs +3 -3
  61. package/dist/esm/protection/providerText.mjs +55 -7
  62. package/dist/esm/protection/providerText.mjs.map +1 -1
  63. package/dist/esm/protection/providerTextAdmission.mjs +5 -0
  64. package/dist/esm/protection/providerTextAdmission.mjs.map +1 -1
  65. package/dist/esm/run.mjs +7 -2
  66. package/dist/esm/run.mjs.map +1 -1
  67. package/dist/esm/runtime/client.mjs +2 -0
  68. package/dist/esm/runtime/client.mjs.map +1 -1
  69. package/dist/esm/stream.mjs +9 -2
  70. package/dist/esm/stream.mjs.map +1 -1
  71. package/dist/esm/tools/handlers.mjs +47 -2
  72. package/dist/esm/tools/handlers.mjs.map +1 -1
  73. package/dist/esm/tools/search/citations.mjs +190 -0
  74. package/dist/esm/tools/search/citations.mjs.map +1 -0
  75. package/dist/esm/tools/search/firecrawl.mjs +4 -9
  76. package/dist/esm/tools/search/firecrawl.mjs.map +1 -1
  77. package/dist/esm/tools/search/google.mjs +67 -0
  78. package/dist/esm/tools/search/google.mjs.map +1 -0
  79. package/dist/esm/tools/search/openai.mjs +80 -0
  80. package/dist/esm/tools/search/openai.mjs.map +1 -0
  81. package/dist/esm/utils/tokens.mjs +5 -0
  82. package/dist/esm/utils/tokens.mjs.map +1 -1
  83. package/dist/types/graphs/Graph.d.ts +14 -0
  84. package/dist/types/index.d.ts +2 -2
  85. package/dist/types/llm/openai/typedContent.d.ts +14 -0
  86. package/dist/types/llm/providerTextBatch.d.ts +26 -0
  87. package/dist/types/llm/providerTextBoundary.d.ts +7 -1
  88. package/dist/types/protection/providerText.d.ts +29 -1
  89. package/dist/types/protection/providerTextAdmission.d.ts +1 -0
  90. package/dist/types/tools/handlers.d.ts +13 -0
  91. package/dist/types/tools/search/citations.d.ts +88 -0
  92. package/dist/types/tools/search/firecrawl.d.ts +3 -1
  93. package/dist/types/tools/search/google.d.ts +11 -0
  94. package/dist/types/tools/search/openai.d.ts +3 -0
  95. package/dist/types/tools/search/types.d.ts +24 -0
  96. package/dist/types/types/stream.d.ts +12 -0
  97. package/dist/types/utils/tokens.d.ts +1 -0
  98. package/package.json +1 -1
  99. package/src/graphs/Graph.ts +103 -3
  100. package/src/harness/providerText.ts +1 -0
  101. package/src/index.ts +2 -0
  102. package/src/llm/google/utils/signatures.ts +52 -36
  103. package/src/llm/invoke.ts +160 -16
  104. package/src/llm/openai/index.ts +18 -5
  105. package/src/llm/openai/typedContent.ts +110 -0
  106. package/src/llm/prepareProviderRequest.ts +154 -4
  107. package/src/llm/providerTextBatch.ts +158 -0
  108. package/src/llm/providerTextBoundary.ts +119 -13
  109. package/src/protection/providerText.ts +95 -6
  110. package/src/protection/providerTextAdmission.ts +6 -0
  111. package/src/run.ts +22 -1
  112. package/src/runtime/client.ts +3 -0
  113. package/src/stream.ts +18 -2
  114. package/src/tools/handlers.ts +110 -5
  115. package/src/tools/search/citations.ts +375 -0
  116. package/src/tools/search/firecrawl.ts +13 -16
  117. package/src/tools/search/google.ts +122 -0
  118. package/src/tools/search/openai.ts +118 -0
  119. package/src/tools/search/types.ts +21 -0
  120. package/src/types/stream.ts +9 -0
  121. package/src/utils/tokens.ts +9 -0
@@ -0,0 +1,375 @@
1
+ import type {
2
+ GoogleGroundingMetadata,
3
+ SearchResultData,
4
+ ProcessedOrganic,
5
+ } from './types';
6
+ import type * as t from '@/types';
7
+ import { ContentTypes } from '@/common/enum';
8
+
9
+ /**
10
+ * LibreChat's citation markers. They are private-use code points, while a
11
+ * model following the web search prompt writes the escaped `\ue202` text, so
12
+ * markers in these forms were inserted here.
13
+ */
14
+ const ANCHOR = '\ue202';
15
+ const GROUP_START = '\ue200';
16
+ const GROUP_END = '\ue201';
17
+ const INSERTED_MARKERS = /\ue200|\ue201|\ue202turn\d+search\d+/g;
18
+
19
+ export type SearchRef = { turn: number; index: number };
20
+
21
+ /** A span of a model call's text that cites `sources` (organic indices). */
22
+ export type CitationSpan = { start: number; end: number; sources: number[] };
23
+
24
+ export type NativeSearchResults = {
25
+ organic: ProcessedOrganic[];
26
+ spans: CitationSpan[];
27
+ queries?: string[];
28
+ };
29
+
30
+ export type UrlCitation = {
31
+ block?: number;
32
+ url: string;
33
+ title?: string;
34
+ start?: number;
35
+ end?: number;
36
+ };
37
+
38
+ export type NativeSearchCall = {
39
+ text: string;
40
+ /** Where each step's text starts, in `text` and in the step's content part. */
41
+ steps: { id: string; start: number; base: number }[];
42
+ /** Offset in `text` where each provider text block starts. */
43
+ blocks: Map<number, number>;
44
+ citations: UrlCitation[];
45
+ grounding?: GoogleGroundingMetadata;
46
+ metadata?: Record<string, unknown>;
47
+ };
48
+
49
+ type PendingAnchors = {
50
+ block?: number;
51
+ refs: SearchRef[];
52
+ metadata?: Record<string, unknown>;
53
+ };
54
+
55
+ type CitedPart = {
56
+ type?: string;
57
+ text?: unknown;
58
+ index?: unknown;
59
+ citations?: unknown;
60
+ annotations?: unknown;
61
+ };
62
+
63
+ export function formatSearchAnchors(refs: readonly SearchRef[]): string {
64
+ const anchors = refs
65
+ .map(({ turn, index }) => `${ANCHOR}turn${turn}search${index}`)
66
+ .join('');
67
+ return refs.length > 1 ? `${GROUP_START}${anchors}${GROUP_END}` : anchors;
68
+ }
69
+
70
+ /** Removes the markers {@link formatSearchAnchors} writes, so replayed text matches what the provider sent. */
71
+ export function stripSearchAnchors(text: string): string {
72
+ return text.replace(INSERTED_MARKERS, '');
73
+ }
74
+
75
+ /** Applies non-overlapping edits by position; an edit outside the text or over an earlier one is skipped. */
76
+ export function applyTextEdits(
77
+ text: string,
78
+ edits: readonly t.TextEdit[]
79
+ ): string {
80
+ const valid = edits
81
+ .filter(
82
+ ({ start, end }) =>
83
+ Number.isSafeInteger(start) &&
84
+ Number.isSafeInteger(end) &&
85
+ start >= 0 &&
86
+ start <= end &&
87
+ end <= text.length
88
+ )
89
+ .sort((a, b) => a.start - b.start || a.end - b.end);
90
+ let result = '';
91
+ let cursor = 0;
92
+ for (const edit of valid) {
93
+ if (edit.start < cursor) {
94
+ continue;
95
+ }
96
+ result += text.slice(cursor, edit.start) + edit.text;
97
+ cursor = edit.end;
98
+ }
99
+ return result + text.slice(cursor);
100
+ }
101
+
102
+ function getUtf8Length(code: number): number {
103
+ if (code < 0x80) {
104
+ return 1;
105
+ }
106
+ if (code < 0x800) {
107
+ return 2;
108
+ }
109
+ return code < 0x10000 ? 3 : 4;
110
+ }
111
+
112
+ /** Converts a UTF-8 byte offset into a UTF-16 index of `text`; undefined when it falls inside a character. */
113
+ export function byteToCharOffset(
114
+ text: string,
115
+ bytes: number
116
+ ): number | undefined {
117
+ let consumed = 0;
118
+ let index = 0;
119
+ while (consumed < bytes && index < text.length) {
120
+ const code = text.codePointAt(index) ?? 0;
121
+ consumed += getUtf8Length(code);
122
+ index += code > 0xffff ? 2 : 1;
123
+ }
124
+ return consumed === bytes ? index : undefined;
125
+ }
126
+
127
+ function getUrlCitations(part: CitedPart): UrlCitation[] {
128
+ if (!Array.isArray(part.annotations)) {
129
+ return [];
130
+ }
131
+ const block = typeof part.index === 'number' ? part.index : undefined;
132
+ const citations: UrlCitation[] = [];
133
+ for (const annotation of part.annotations as Record<string, unknown>[]) {
134
+ const isUrlCitation =
135
+ annotation.source === 'url_citation' ||
136
+ annotation.type === 'url_citation';
137
+ if (!isUrlCitation || typeof annotation.url !== 'string') {
138
+ continue;
139
+ }
140
+ const start = annotation.startIndex ?? annotation.start_index;
141
+ const end = annotation.endIndex ?? annotation.end_index;
142
+ citations.push({
143
+ block,
144
+ url: annotation.url,
145
+ title:
146
+ typeof annotation.title === 'string' ? annotation.title : undefined,
147
+ start: typeof start === 'number' ? start : undefined,
148
+ end: typeof end === 'number' ? end : undefined,
149
+ });
150
+ }
151
+ return citations;
152
+ }
153
+
154
+ /**
155
+ * Run-scoped state that turns provider-native web search citations into the
156
+ * `turnNsearchM` anchors hosts already render for the SDK's own search tool.
157
+ */
158
+ export class SearchCitations {
159
+ /** Organic results by link, so a cited URL resolves to its turn and index. */
160
+ private sources = new Map<string, SearchRef>();
161
+ /** Anchors for a cited block, written once the block ends. */
162
+ private pending = new Map<string, PendingAnchors>();
163
+ /** Text and citation data of a model call still streaming, by agent lane. */
164
+ private calls = new Map<string, NativeSearchCall>();
165
+ /** Text length dispatched to each tracked step, to place late edits. */
166
+ private lengths = new Map<string, number>();
167
+ /** Turns claimed by searches that never produce a tool call id. */
168
+ private claimed = 0;
169
+
170
+ register(data: SearchResultData): void {
171
+ const turn = data.turn ?? 0;
172
+ data.organic?.forEach((result, index) => {
173
+ if (result.link) {
174
+ this.sources.set(result.link, { turn, index });
175
+ }
176
+ });
177
+ }
178
+
179
+ /** The turn for a search identified by a tool call id that joins `invokedToolIds`. */
180
+ turn(invoked: number): number {
181
+ return invoked + this.claimed;
182
+ }
183
+
184
+ /** Claims a turn for a search with no tool call id of its own. */
185
+ claimTurn(invoked: number): number {
186
+ const turn = this.turn(invoked);
187
+ this.claimed += 1;
188
+ return turn;
189
+ }
190
+
191
+ /**
192
+ * Adds the anchors of a cited block before the first delta of the next
193
+ * block. Anthropic sends a block's citations before or after its text, and
194
+ * the anchor belongs after the text, so it waits for the block to end.
195
+ * Returns undefined when the content needs no change.
196
+ */
197
+ anchor(
198
+ stepId: string,
199
+ content: t.MessageContentComplex[],
200
+ metadata?: Record<string, unknown>
201
+ ): t.MessageContentComplex[] | undefined {
202
+ let result: t.MessageContentComplex[] | undefined;
203
+ for (let i = 0; i < content.length; i++) {
204
+ const part = content[i] as CitedPart;
205
+ const pending = this.pending.get(stepId);
206
+ if (
207
+ pending != null &&
208
+ part.type === ContentTypes.TEXT &&
209
+ part.index !== pending.block
210
+ ) {
211
+ result ??= content.slice(0, i);
212
+ result.push({
213
+ type: ContentTypes.TEXT,
214
+ text: formatSearchAnchors(pending.refs),
215
+ });
216
+ this.pending.delete(stepId);
217
+ }
218
+ result?.push(content[i]);
219
+ const refs = this.resolve(part);
220
+ if (refs.length === 0) {
221
+ continue;
222
+ }
223
+ const current = this.pending.get(stepId) ?? {
224
+ block: typeof part.index === 'number' ? part.index : undefined,
225
+ refs: [],
226
+ metadata,
227
+ };
228
+ for (const ref of refs) {
229
+ if (
230
+ !current.refs.some(
231
+ ({ turn, index }) => turn === ref.turn && index === ref.index
232
+ )
233
+ ) {
234
+ current.refs.push(ref);
235
+ }
236
+ }
237
+ this.pending.set(stepId, current);
238
+ }
239
+ return result;
240
+ }
241
+
242
+ /** Anchors still waiting on a step that is closing. */
243
+ release(
244
+ stepId: string
245
+ ): { text: string; metadata?: Record<string, unknown> } | undefined {
246
+ const pending = this.pending.get(stepId);
247
+ if (pending == null) {
248
+ return undefined;
249
+ }
250
+ this.pending.delete(stepId);
251
+ return {
252
+ text: formatSearchAnchors(pending.refs),
253
+ metadata: pending.metadata,
254
+ };
255
+ }
256
+
257
+ /** Records a step's streamed text and url citations for edits made when the model call ends. */
258
+ track(
259
+ lane: string,
260
+ stepId: string,
261
+ content: t.MessageContentComplex[],
262
+ metadata?: Record<string, unknown>
263
+ ): void {
264
+ for (const item of content) {
265
+ const part = item as CitedPart;
266
+ if (part.type !== ContentTypes.TEXT) {
267
+ continue;
268
+ }
269
+ const text = typeof part.text === 'string' ? part.text : '';
270
+ const citations = getUrlCitations(part);
271
+ if (text === '' && citations.length === 0) {
272
+ continue;
273
+ }
274
+ const call = this.open(lane, metadata);
275
+ call.citations.push(...citations);
276
+ if (text === '') {
277
+ continue;
278
+ }
279
+ const base = this.lengths.get(stepId) ?? 0;
280
+ if (call.steps.at(-1)?.id !== stepId) {
281
+ call.steps.push({ id: stepId, start: call.text.length, base });
282
+ }
283
+ if (typeof part.index === 'number' && !call.blocks.has(part.index)) {
284
+ call.blocks.set(part.index, call.text.length);
285
+ }
286
+ call.text += text;
287
+ this.lengths.set(stepId, base + text.length);
288
+ }
289
+ }
290
+
291
+ /** Keeps the latest grounding payload of a model call. */
292
+ ground(
293
+ lane: string,
294
+ grounding: GoogleGroundingMetadata,
295
+ metadata?: Record<string, unknown>
296
+ ): void {
297
+ this.open(lane, metadata).grounding = grounding;
298
+ }
299
+
300
+ /** Hands over the finished model call of a lane. */
301
+ take(lane: string): NativeSearchCall | undefined {
302
+ const call = this.calls.get(lane);
303
+ this.calls.delete(lane);
304
+ return call;
305
+ }
306
+
307
+ /** Splits call-relative edits by the step that holds their text, in that step's offsets. */
308
+ locate(
309
+ call: NativeSearchCall,
310
+ edits: readonly t.TextEdit[]
311
+ ): Map<string, t.TextEdit[]> {
312
+ const byStep = new Map<string, t.TextEdit[]>();
313
+ for (const edit of edits) {
314
+ const step = call.steps.findLast(
315
+ ({ start }) => start < edit.end || (start === 0 && edit.end === 0)
316
+ );
317
+ if (step == null || edit.start < step.start) {
318
+ continue;
319
+ }
320
+ const offset = step.base - step.start;
321
+ const stepEdits = byStep.get(step.id) ?? [];
322
+ stepEdits.push({
323
+ start: edit.start + offset,
324
+ end: edit.end + offset,
325
+ text: edit.text,
326
+ });
327
+ byStep.set(step.id, stepEdits);
328
+ this.lengths.set(
329
+ step.id,
330
+ (this.lengths.get(step.id) ?? 0) +
331
+ edit.text.length -
332
+ (edit.end - edit.start)
333
+ );
334
+ }
335
+ return byStep;
336
+ }
337
+
338
+ private open(
339
+ lane: string,
340
+ metadata?: Record<string, unknown>
341
+ ): NativeSearchCall {
342
+ let call = this.calls.get(lane);
343
+ if (call == null) {
344
+ call = {
345
+ text: '',
346
+ steps: [],
347
+ blocks: new Map(),
348
+ citations: [],
349
+ metadata,
350
+ };
351
+ this.calls.set(lane, call);
352
+ }
353
+ return call;
354
+ }
355
+
356
+ private resolve(part: CitedPart): SearchRef[] {
357
+ if (part.type !== ContentTypes.TEXT || !Array.isArray(part.citations)) {
358
+ return [];
359
+ }
360
+ const refs: SearchRef[] = [];
361
+ for (const citation of part.citations as Record<string, unknown>[]) {
362
+ if (
363
+ citation.type !== 'web_search_result_location' ||
364
+ typeof citation.url !== 'string'
365
+ ) {
366
+ continue;
367
+ }
368
+ const ref = this.sources.get(citation.url);
369
+ if (ref != null) {
370
+ refs.push(ref);
371
+ }
372
+ }
373
+ return refs;
374
+ }
375
+ }
@@ -5,7 +5,9 @@ import { processContent } from './content';
5
5
 
6
6
  /**
7
7
  * Firecrawl scraper implementation
8
- * Uses the Firecrawl API to scrape web pages
8
+ * Uses the Firecrawl API to scrape web pages. Without an API key, requests go
9
+ * out with no Authorization header, which a self-hosted instance running
10
+ * without authentication accepts.
9
11
  */
10
12
  export class FirecrawlScraper implements t.BaseScraper {
11
13
  private apiKey: string;
@@ -67,7 +69,9 @@ export class FirecrawlScraper implements t.BaseScraper {
67
69
  this.httpsAgent = config.httpsAgent;
68
70
 
69
71
  if (!this.apiKey) {
70
- this.logger.warn('FIRECRAWL_API_KEY is not set. Scraping will not work.');
72
+ this.logger.debug(
73
+ 'FIRECRAWL_API_KEY is not set; Firecrawl requests are sent without an API key'
74
+ );
71
75
  }
72
76
 
73
77
  this.logger.debug(
@@ -85,16 +89,6 @@ export class FirecrawlScraper implements t.BaseScraper {
85
89
  url: string,
86
90
  options: t.FirecrawlScrapeOptions = {}
87
91
  ): Promise<[string, t.FirecrawlScrapeResponse]> {
88
- if (!this.apiKey) {
89
- return [
90
- url,
91
- {
92
- success: false,
93
- error: 'FIRECRAWL_API_KEY is not set',
94
- },
95
- ];
96
- }
97
-
98
92
  try {
99
93
  const payload = omitUndefined({
100
94
  url,
@@ -119,11 +113,14 @@ export class FirecrawlScraper implements t.BaseScraper {
119
113
  changeTrackingOptions:
120
114
  options.changeTrackingOptions ?? this.changeTrackingOptions,
121
115
  });
116
+ const headers: Record<string, string> = {
117
+ 'Content-Type': 'application/json',
118
+ };
119
+ if (this.apiKey) {
120
+ headers.Authorization = `Bearer ${this.apiKey}`;
121
+ }
122
122
  const response = await axios.post(this.apiUrl, payload, {
123
- headers: {
124
- 'Content-Type': 'application/json',
125
- Authorization: `Bearer ${this.apiKey}`,
126
- },
123
+ headers,
127
124
  timeout: this.timeout,
128
125
  httpAgent: this.httpAgent,
129
126
  httpsAgent: this.httpsAgent,
@@ -0,0 +1,122 @@
1
+ import type { GoogleGroundingMetadata, ProcessedOrganic } from './types';
2
+ import type { NativeSearchResults, CitationSpan } from './citations';
3
+ import { byteToCharOffset } from './citations';
4
+ import { getAttribution } from './utils';
5
+
6
+ type GroundedChunk = {
7
+ additional_kwargs?: Record<string, unknown>;
8
+ response_metadata?: Record<string, unknown>;
9
+ };
10
+
11
+ function isGroundingMetadata(value: unknown): value is GoogleGroundingMetadata {
12
+ return (
13
+ value != null &&
14
+ typeof value === 'object' &&
15
+ Array.isArray((value as GoogleGroundingMetadata).groundingChunks)
16
+ );
17
+ }
18
+
19
+ /** Gemini API chunks carry it in `additional_kwargs`, Vertex AI chunks in `response_metadata`. */
20
+ export function getGoogleGroundingMetadata(
21
+ chunk: GroundedChunk
22
+ ): GoogleGroundingMetadata | undefined {
23
+ const candidates = [
24
+ chunk.additional_kwargs?.groundingMetadata,
25
+ chunk.response_metadata?.groundingMetadata,
26
+ chunk.response_metadata?.grounding_metadata,
27
+ ];
28
+ return candidates.find(isGroundingMetadata);
29
+ }
30
+
31
+ /**
32
+ * Finds where a grounded segment ends in the call text. The API measures
33
+ * offsets in UTF-8 bytes of one response part, and streamed text carries no
34
+ * part boundaries, so the byte offset is trusted only for the first part and
35
+ * when the segment text sits right before it. A first-part segment is
36
+ * otherwise searched from the previous segment's end; a later part's segment
37
+ * is placed only when its text occurs once, never at a guessed occurrence.
38
+ */
39
+ function locateSegmentEnd(
40
+ text: string,
41
+ segment: { partIndex?: number; endIndex?: number; text?: string },
42
+ cursor: number
43
+ ): number | undefined {
44
+ const value = segment.text;
45
+ const firstPart = (segment.partIndex ?? 0) === 0;
46
+ const end =
47
+ firstPart && typeof segment.endIndex === 'number'
48
+ ? byteToCharOffset(text, segment.endIndex)
49
+ : undefined;
50
+ if (value == null || value === '') {
51
+ return end;
52
+ }
53
+ if (end != null && text.slice(end - value.length, end) === value) {
54
+ return end;
55
+ }
56
+ if (!firstPart) {
57
+ const index = text.indexOf(value);
58
+ return index !== -1 && text.indexOf(value, index + 1) === -1
59
+ ? index + value.length
60
+ : undefined;
61
+ }
62
+ let index = text.indexOf(value, cursor);
63
+ if (index === -1) {
64
+ index = text.indexOf(value);
65
+ }
66
+ return index === -1 ? undefined : index + value.length;
67
+ }
68
+
69
+ /** Turns Gemini grounding into organic results and the spans each support cites. */
70
+ export function coerceGoogleGroundingResults(
71
+ grounding: GoogleGroundingMetadata,
72
+ text: string
73
+ ): NativeSearchResults | undefined {
74
+ const organic: ProcessedOrganic[] = [];
75
+ const sourceByChunk = new Map<number, number>();
76
+ grounding.groundingChunks?.forEach((chunk, index) => {
77
+ const link = chunk.web?.uri;
78
+ if (link == null || link === '') {
79
+ return;
80
+ }
81
+ sourceByChunk.set(index, organic.length);
82
+ organic.push({
83
+ link,
84
+ position: organic.length + 1,
85
+ title: chunk.web?.title,
86
+ attribution:
87
+ chunk.web?.domain ?? chunk.web?.title ?? getAttribution(link),
88
+ });
89
+ });
90
+ if (organic.length === 0) {
91
+ return undefined;
92
+ }
93
+
94
+ const sourcesByEnd = new Map<number, number[]>();
95
+ let cursor = 0;
96
+ for (const support of grounding.groundingSupports ?? []) {
97
+ const sources = [
98
+ ...new Set(
99
+ (support.groundingChunkIndices ?? []).flatMap(
100
+ (index) => sourceByChunk.get(index) ?? []
101
+ )
102
+ ),
103
+ ];
104
+ if (sources.length === 0 || support.segment == null) {
105
+ continue;
106
+ }
107
+ const end = locateSegmentEnd(text, support.segment, cursor);
108
+ if (end == null) {
109
+ continue;
110
+ }
111
+ cursor = end;
112
+ const cited = sourcesByEnd.get(end) ?? [];
113
+ sourcesByEnd.set(end, [...new Set([...cited, ...sources])]);
114
+ }
115
+
116
+ const spans: CitationSpan[] = [...sourcesByEnd].map(([end, sources]) => ({
117
+ start: end,
118
+ end,
119
+ sources,
120
+ }));
121
+ return { organic, spans, queries: grounding.webSearchQueries };
122
+ }
@@ -0,0 +1,118 @@
1
+ import type {
2
+ NativeSearchResults,
3
+ CitationSpan,
4
+ UrlCitation,
5
+ } from './citations';
6
+ import type { ProcessedOrganic } from './types';
7
+ import { getAttribution, getDomainName } from './utils';
8
+
9
+ /** A markdown link, optionally wrapped in the parentheses OpenAI puts around citations. */
10
+ const MARKDOWN_LINK = /^\(?\[[^\]\n]+\]\((https?:\/\/\S+?)\)\)?$/;
11
+
12
+ function linksTo(span: string, url: string): boolean {
13
+ const target = MARKDOWN_LINK.exec(span)?.[1];
14
+ if (target == null) {
15
+ return false;
16
+ }
17
+ return target === url || getDomainName(target) === getDomainName(url);
18
+ }
19
+
20
+ function matchLink(
21
+ text: string,
22
+ start: number,
23
+ end: number,
24
+ url: string
25
+ ): { start: number; end: number } | undefined {
26
+ for (const close of [end, end + 1]) {
27
+ if (!linksTo(text.slice(start, close), url)) {
28
+ continue;
29
+ }
30
+ const wrapped = text[start - 1] === '(' && text[close] === ')';
31
+ return wrapped
32
+ ? { start: start - 1, end: close + 1 }
33
+ : { start, end: close };
34
+ }
35
+ return undefined;
36
+ }
37
+
38
+ /** UTF-16 index of every code point from `from` to the end of `text`, then the end itself. */
39
+ function getCodePointOffsets(text: string, from: number): number[] {
40
+ const offsets: number[] = [];
41
+ let index = from;
42
+ while (index < text.length) {
43
+ offsets.push(index);
44
+ index += (text.codePointAt(index) ?? 0) > 0xffff ? 2 : 1;
45
+ }
46
+ offsets.push(index);
47
+ return offsets;
48
+ }
49
+
50
+ /**
51
+ * Finds the inline markdown link a `url_citation` covers. Its indices count
52
+ * characters of one output text block; they are read as UTF-16 first, then as
53
+ * code points, and the end is tried as exclusive and inclusive. A span that is
54
+ * not a link to the cited host is left alone.
55
+ */
56
+ function locateLink(
57
+ text: string,
58
+ blockStart: number,
59
+ citation: UrlCitation,
60
+ getOffsets: () => number[]
61
+ ): { start: number; end: number } | undefined {
62
+ const { start, end, url } = citation;
63
+ if (start == null || end == null) {
64
+ return undefined;
65
+ }
66
+ const direct = matchLink(text, blockStart + start, blockStart + end, url);
67
+ if (direct != null) {
68
+ return direct;
69
+ }
70
+ const offsets = getOffsets();
71
+ const from = offsets.at(start);
72
+ const to = offsets.at(end);
73
+ return from == null || to == null
74
+ ? undefined
75
+ : matchLink(text, from, to, url);
76
+ }
77
+
78
+ /** Turns OpenAI `url_citation` annotations into organic results and the links they replace. */
79
+ export function coerceOpenAICitationResults(
80
+ citations: readonly UrlCitation[],
81
+ text: string,
82
+ blocks: ReadonlyMap<number, number>
83
+ ): NativeSearchResults | undefined {
84
+ const organic: ProcessedOrganic[] = [];
85
+ const sourceByUrl = new Map<string, number>();
86
+ const offsetsByBlock = new Map<number, number[]>();
87
+ const spans: CitationSpan[] = [];
88
+ for (const citation of citations) {
89
+ let source = sourceByUrl.get(citation.url);
90
+ if (source == null) {
91
+ source = organic.length;
92
+ sourceByUrl.set(citation.url, source);
93
+ organic.push({
94
+ link: citation.url,
95
+ position: source + 1,
96
+ title: citation.title,
97
+ attribution: getAttribution(citation.url),
98
+ });
99
+ }
100
+ const blockStart =
101
+ citation.block == null ? undefined : blocks.get(citation.block);
102
+ const span =
103
+ blockStart == null
104
+ ? undefined
105
+ : locateLink(text, blockStart, citation, () => {
106
+ let offsets = offsetsByBlock.get(blockStart);
107
+ if (offsets == null) {
108
+ offsets = getCodePointOffsets(text, blockStart);
109
+ offsetsByBlock.set(blockStart, offsets);
110
+ }
111
+ return offsets;
112
+ });
113
+ if (span != null) {
114
+ spans.push({ ...span, sources: [source] });
115
+ }
116
+ }
117
+ return organic.length > 0 ? { organic, spans } : undefined;
118
+ }
@@ -75,6 +75,27 @@ export interface SearchResultData {
75
75
  error?: string;
76
76
  }
77
77
 
78
+ /**
79
+ * Gemini's `groundingMetadata` as the API returns it. The
80
+ * `@google/generative-ai` declarations type `segment` as a string and
81
+ * misspell `groundingChunkIndices`, so they cannot describe it.
82
+ */
83
+ export type GoogleGroundingMetadata = {
84
+ webSearchQueries?: string[];
85
+ groundingChunks?: {
86
+ web?: { uri?: string; title?: string; domain?: string };
87
+ }[];
88
+ groundingSupports?: {
89
+ segment?: {
90
+ partIndex?: number;
91
+ startIndex?: number;
92
+ endIndex?: number;
93
+ text?: string;
94
+ };
95
+ groundingChunkIndices?: number[];
96
+ }[];
97
+ };
98
+
78
99
  export interface SearchResult {
79
100
  data?: SearchResultData;
80
101
  error?: string;