@librechat/agents 4.2.13 → 4.2.15

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 (147) hide show
  1. package/dist/cjs/agents/AgentContext.cjs +75 -19
  2. package/dist/cjs/agents/AgentContext.cjs.map +1 -1
  3. package/dist/cjs/graphs/Graph.cjs +52 -6
  4. package/dist/cjs/graphs/Graph.cjs.map +1 -1
  5. package/dist/cjs/harness/providerText.cjs +1 -0
  6. package/dist/cjs/harness/providerText.cjs.map +1 -1
  7. package/dist/cjs/llm/google/utils/signatures.cjs +22 -14
  8. package/dist/cjs/llm/google/utils/signatures.cjs.map +1 -1
  9. package/dist/cjs/llm/invoke.cjs +122 -13
  10. package/dist/cjs/llm/invoke.cjs.map +1 -1
  11. package/dist/cjs/llm/openai/index.cjs +8 -2
  12. package/dist/cjs/llm/openai/index.cjs.map +1 -1
  13. package/dist/cjs/llm/openai/typedContent.cjs +94 -0
  14. package/dist/cjs/llm/openai/typedContent.cjs.map +1 -0
  15. package/dist/cjs/llm/prepareProviderRequest.cjs +102 -7
  16. package/dist/cjs/llm/prepareProviderRequest.cjs.map +1 -1
  17. package/dist/cjs/llm/providerTextBatch.cjs +128 -0
  18. package/dist/cjs/llm/providerTextBatch.cjs.map +1 -0
  19. package/dist/cjs/llm/providerTextBoundary.cjs +81 -12
  20. package/dist/cjs/llm/providerTextBoundary.cjs.map +1 -1
  21. package/dist/cjs/main.cjs +3 -0
  22. package/dist/cjs/messages/content.cjs +3 -3
  23. package/dist/cjs/messages/content.cjs.map +1 -1
  24. package/dist/cjs/messages/vision.cjs +77 -0
  25. package/dist/cjs/messages/vision.cjs.map +1 -0
  26. package/dist/cjs/protection/providerText.cjs +56 -6
  27. package/dist/cjs/protection/providerText.cjs.map +1 -1
  28. package/dist/cjs/protection/providerTextAdmission.cjs +5 -0
  29. package/dist/cjs/protection/providerTextAdmission.cjs.map +1 -1
  30. package/dist/cjs/run.cjs +7 -2
  31. package/dist/cjs/run.cjs.map +1 -1
  32. package/dist/cjs/runtime/client.cjs +2 -0
  33. package/dist/cjs/runtime/client.cjs.map +1 -1
  34. package/dist/cjs/stream.cjs +9 -2
  35. package/dist/cjs/stream.cjs.map +1 -1
  36. package/dist/cjs/summarization/node.cjs +6 -2
  37. package/dist/cjs/summarization/node.cjs.map +1 -1
  38. package/dist/cjs/tools/handlers.cjs +47 -1
  39. package/dist/cjs/tools/handlers.cjs.map +1 -1
  40. package/dist/cjs/tools/search/citations.cjs +194 -0
  41. package/dist/cjs/tools/search/citations.cjs.map +1 -0
  42. package/dist/cjs/tools/search/firecrawl.cjs +4 -9
  43. package/dist/cjs/tools/search/firecrawl.cjs.map +1 -1
  44. package/dist/cjs/tools/search/google.cjs +68 -0
  45. package/dist/cjs/tools/search/google.cjs.map +1 -0
  46. package/dist/cjs/tools/search/openai.cjs +80 -0
  47. package/dist/cjs/tools/search/openai.cjs.map +1 -0
  48. package/dist/cjs/utils/tokens.cjs +6 -0
  49. package/dist/cjs/utils/tokens.cjs.map +1 -1
  50. package/dist/esm/agents/AgentContext.mjs +76 -20
  51. package/dist/esm/agents/AgentContext.mjs.map +1 -1
  52. package/dist/esm/graphs/Graph.mjs +53 -7
  53. package/dist/esm/graphs/Graph.mjs.map +1 -1
  54. package/dist/esm/harness/providerText.mjs +1 -0
  55. package/dist/esm/harness/providerText.mjs.map +1 -1
  56. package/dist/esm/llm/google/utils/signatures.mjs +22 -14
  57. package/dist/esm/llm/google/utils/signatures.mjs.map +1 -1
  58. package/dist/esm/llm/invoke.mjs +124 -15
  59. package/dist/esm/llm/invoke.mjs.map +1 -1
  60. package/dist/esm/llm/openai/index.mjs +8 -2
  61. package/dist/esm/llm/openai/index.mjs.map +1 -1
  62. package/dist/esm/llm/openai/typedContent.mjs +93 -0
  63. package/dist/esm/llm/openai/typedContent.mjs.map +1 -0
  64. package/dist/esm/llm/prepareProviderRequest.mjs +102 -7
  65. package/dist/esm/llm/prepareProviderRequest.mjs.map +1 -1
  66. package/dist/esm/llm/providerTextBatch.mjs +128 -0
  67. package/dist/esm/llm/providerTextBatch.mjs.map +1 -0
  68. package/dist/esm/llm/providerTextBoundary.mjs +81 -12
  69. package/dist/esm/llm/providerTextBoundary.mjs.map +1 -1
  70. package/dist/esm/main.mjs +4 -4
  71. package/dist/esm/messages/content.mjs +3 -3
  72. package/dist/esm/messages/content.mjs.map +1 -1
  73. package/dist/esm/messages/vision.mjs +73 -0
  74. package/dist/esm/messages/vision.mjs.map +1 -0
  75. package/dist/esm/protection/providerText.mjs +55 -7
  76. package/dist/esm/protection/providerText.mjs.map +1 -1
  77. package/dist/esm/protection/providerTextAdmission.mjs +5 -0
  78. package/dist/esm/protection/providerTextAdmission.mjs.map +1 -1
  79. package/dist/esm/run.mjs +7 -2
  80. package/dist/esm/run.mjs.map +1 -1
  81. package/dist/esm/runtime/client.mjs +2 -0
  82. package/dist/esm/runtime/client.mjs.map +1 -1
  83. package/dist/esm/stream.mjs +9 -2
  84. package/dist/esm/stream.mjs.map +1 -1
  85. package/dist/esm/summarization/node.mjs +6 -2
  86. package/dist/esm/summarization/node.mjs.map +1 -1
  87. package/dist/esm/tools/handlers.mjs +47 -2
  88. package/dist/esm/tools/handlers.mjs.map +1 -1
  89. package/dist/esm/tools/search/citations.mjs +190 -0
  90. package/dist/esm/tools/search/citations.mjs.map +1 -0
  91. package/dist/esm/tools/search/firecrawl.mjs +4 -9
  92. package/dist/esm/tools/search/firecrawl.mjs.map +1 -1
  93. package/dist/esm/tools/search/google.mjs +67 -0
  94. package/dist/esm/tools/search/google.mjs.map +1 -0
  95. package/dist/esm/tools/search/openai.mjs +80 -0
  96. package/dist/esm/tools/search/openai.mjs.map +1 -0
  97. package/dist/esm/utils/tokens.mjs +6 -1
  98. package/dist/esm/utils/tokens.mjs.map +1 -1
  99. package/dist/types/agents/AgentContext.d.ts +20 -1
  100. package/dist/types/graphs/Graph.d.ts +14 -0
  101. package/dist/types/index.d.ts +2 -2
  102. package/dist/types/llm/openai/typedContent.d.ts +14 -0
  103. package/dist/types/llm/prepareProviderRequest.d.ts +7 -1
  104. package/dist/types/llm/providerTextBatch.d.ts +26 -0
  105. package/dist/types/llm/providerTextBoundary.d.ts +7 -1
  106. package/dist/types/messages/content.d.ts +2 -1
  107. package/dist/types/messages/vision.d.ts +20 -0
  108. package/dist/types/protection/providerText.d.ts +29 -1
  109. package/dist/types/protection/providerTextAdmission.d.ts +1 -0
  110. package/dist/types/tools/handlers.d.ts +13 -0
  111. package/dist/types/tools/search/citations.d.ts +88 -0
  112. package/dist/types/tools/search/firecrawl.d.ts +3 -1
  113. package/dist/types/tools/search/google.d.ts +11 -0
  114. package/dist/types/tools/search/openai.d.ts +3 -0
  115. package/dist/types/tools/search/types.d.ts +24 -0
  116. package/dist/types/types/graph.d.ts +8 -0
  117. package/dist/types/types/stream.d.ts +12 -0
  118. package/dist/types/utils/tokens.d.ts +3 -0
  119. package/package.json +1 -1
  120. package/src/agents/AgentContext.ts +188 -78
  121. package/src/graphs/Graph.ts +117 -8
  122. package/src/harness/providerText.ts +1 -0
  123. package/src/index.ts +2 -0
  124. package/src/llm/google/utils/signatures.ts +52 -36
  125. package/src/llm/invoke.ts +160 -16
  126. package/src/llm/openai/index.ts +18 -5
  127. package/src/llm/openai/typedContent.ts +110 -0
  128. package/src/llm/prepareProviderRequest.ts +206 -7
  129. package/src/llm/providerTextBatch.ts +158 -0
  130. package/src/llm/providerTextBoundary.ts +119 -13
  131. package/src/messages/content.ts +10 -4
  132. package/src/messages/vision.ts +109 -0
  133. package/src/protection/providerText.ts +95 -6
  134. package/src/protection/providerTextAdmission.ts +6 -0
  135. package/src/run.ts +22 -1
  136. package/src/runtime/client.ts +3 -0
  137. package/src/stream.ts +18 -2
  138. package/src/summarization/node.ts +4 -0
  139. package/src/tools/handlers.ts +110 -5
  140. package/src/tools/search/citations.ts +375 -0
  141. package/src/tools/search/firecrawl.ts +13 -16
  142. package/src/tools/search/google.ts +122 -0
  143. package/src/tools/search/openai.ts +118 -0
  144. package/src/tools/search/types.ts +21 -0
  145. package/src/types/graph.ts +8 -0
  146. package/src/types/stream.ts +9 -0
  147. package/src/utils/tokens.ts +13 -1
@@ -33,10 +33,17 @@ import {
33
33
  appendInstructionlessHandoffCue,
34
34
  removePredecessorHandoffCue,
35
35
  } from '@/messages';
36
+ import {
37
+ omitImageBlock,
38
+ isImageContentBlock,
39
+ toOmittedImageBlock,
40
+ } from '@/messages/vision';
36
41
  import { createToolHistoryPreparation } from '@/messages/toolHistoryProjection';
42
+ import { flattenLegacyContent, isLegacyConvertible } from '@/messages/content';
37
43
  import { isAnthropicLike, isGoogleLike, isOpenAILike } from '@/utils/llm';
38
44
  import { annotateMessagesForLLM } from '@/tools/toolOutputReferences';
39
45
  import { providerRequiresStrictAlternation } from '@/llm/providers';
46
+ import { hasComputerCallOutputMarker } from '@/utils/toolContent';
40
47
  import { getProviderFamily } from '@/llm/providerRegistry';
41
48
  import { Providers } from '@/common';
42
49
 
@@ -132,6 +139,10 @@ export interface PrepareProviderRequestParams {
132
139
  maxToolResultChars?: number;
133
140
  measure?: (messages: BaseMessage[]) => ProviderPayloadMeasurement;
134
141
  toolHistory?: ToolHistoryPreparation;
142
+ /** `false` replaces images with a text marker for a model without image input. */
143
+ vision?: boolean;
144
+ /** Flattens messages the image replacement leaves text-only, as `formatContentStrings` does. */
145
+ useLegacyContent?: boolean;
135
146
  }
136
147
 
137
148
  export function usesNativeOpenAIResponses(
@@ -211,6 +222,12 @@ function resolveProviderMessageProjectionMode(
211
222
  : 'chat-messages';
212
223
  }
213
224
 
225
+ /** How a request for a model without image input treats images. */
226
+ interface ImageOmission {
227
+ /** Flattens a turn left with only text, as `formatContentStrings` does. */
228
+ legacyContent: boolean;
229
+ }
230
+
214
231
  interface ProjectMessagesForProviderParams {
215
232
  model: t.ChatModel;
216
233
  messages: BaseMessage[];
@@ -219,6 +236,8 @@ interface ProjectMessagesForProviderParams {
219
236
  callOptions?: unknown;
220
237
  toolHistory?: ToolHistoryPreparation;
221
238
  resolve?: ResolveReference;
239
+ vision?: boolean;
240
+ useLegacyContent?: boolean;
222
241
  }
223
242
 
224
243
  function isSerializedBuffer(value: object): value is SerializedBuffer {
@@ -331,6 +350,134 @@ function canProjectBedrockDocument(
331
350
  return false;
332
351
  }
333
352
 
353
+ /** How one provider request takes audio and video. */
354
+ type TimedMediaInput = 'gemini' | 'openai' | 'none';
355
+
356
+ /**
357
+ * Gemini and Vertex read audio and video as `media` parts. OpenAI-compatible
358
+ * Chat Completions endpoints read `input_audio` and `video_url` parts, where
359
+ * the endpoint and model accept them, which only the host can tell. Claude,
360
+ * Bedrock's Converse converter and the Responses API read none of them.
361
+ */
362
+ function getTimedMediaInput(
363
+ provider: t.ProviderName,
364
+ projectionMode: ProviderMessageProjectionMode
365
+ ): TimedMediaInput {
366
+ if (isGoogleLike(provider)) {
367
+ return 'gemini';
368
+ }
369
+ const family = getProviderFamily(provider);
370
+ if (
371
+ projectionMode === 'openai-responses' ||
372
+ provider === Providers.ANTHROPIC ||
373
+ family === 'anthropic' ||
374
+ provider === Providers.BEDROCK ||
375
+ family === 'bedrock'
376
+ ) {
377
+ return 'none';
378
+ }
379
+ return 'openai';
380
+ }
381
+
382
+ /** The audio or video MIME type a block names, normalized; `undefined` for anything else. */
383
+ function getTimedMediaMimeType(mimeType: unknown): string | undefined {
384
+ if (typeof mimeType !== 'string') {
385
+ return undefined;
386
+ }
387
+ const normalized = mimeType.split(';', 1)[0].trim().toLowerCase();
388
+ return normalized.startsWith('audio/') || normalized.startsWith('video/')
389
+ ? normalized
390
+ : undefined;
391
+ }
392
+
393
+ /** Gemini's MIME type for each `input_audio` format it plays; raw PCM names no sample rate. */
394
+ const GEMINI_AUDIO_MIME_TYPES: Readonly<Partial<Record<string, string>>> = {
395
+ aac: 'audio/aac',
396
+ aiff: 'audio/aiff',
397
+ flac: 'audio/flac',
398
+ m4a: 'audio/mp4',
399
+ mp3: 'audio/mp3',
400
+ ogg: 'audio/ogg',
401
+ wav: 'audio/wav',
402
+ webm: 'audio/webm',
403
+ };
404
+
405
+ /** The MIME type and payload of a base64 `data:` URL. */
406
+ function parseDataUrl(
407
+ url: string
408
+ ): { mimeType: string; data: string } | undefined {
409
+ const comma = url.indexOf(',');
410
+ if (!url.startsWith('data:') || comma < 0) {
411
+ return undefined;
412
+ }
413
+ const [mimeType, ...parameters] = url.slice(5, comma).split(';');
414
+ if (parameters.at(-1)?.trim().toLowerCase() !== 'base64') {
415
+ return undefined;
416
+ }
417
+ const data = url.slice(comma + 1);
418
+ return data === '' ? undefined : { mimeType, data };
419
+ }
420
+
421
+ /** An OpenAI-compatible audio or video part as Gemini inline media, when it carries its bytes. */
422
+ function toGeminiMedia(
423
+ block: ProviderContentBlock
424
+ ): ProviderContentBlock | null {
425
+ if (block.type === 'input_audio') {
426
+ const audio = (
427
+ block as { input_audio?: { data?: unknown; format?: unknown } }
428
+ ).input_audio;
429
+ const mimeType =
430
+ typeof audio?.format === 'string'
431
+ ? GEMINI_AUDIO_MIME_TYPES[audio.format.toLowerCase()]
432
+ : undefined;
433
+ return mimeType != null &&
434
+ typeof audio?.data === 'string' &&
435
+ audio.data !== ''
436
+ ? { type: 'media', mimeType, data: audio.data }
437
+ : null;
438
+ }
439
+ const video = (block as { video_url?: string | { url?: unknown } | null })
440
+ .video_url;
441
+ const url = typeof video === 'string' ? video : video?.url;
442
+ const parsed = typeof url === 'string' ? parseDataUrl(url) : undefined;
443
+ const mimeType = getTimedMediaMimeType(parsed?.mimeType);
444
+ return parsed != null && mimeType != null
445
+ ? { type: 'media', mimeType, data: parsed.data }
446
+ : null;
447
+ }
448
+
449
+ /**
450
+ * The part a request that takes `input` gets for an audio or video part: the
451
+ * part itself when its provider reads it, Gemini inline media rewritten from
452
+ * an OpenAI-compatible part, or `null` to leave it out. `undefined` for any
453
+ * other block.
454
+ */
455
+ function projectTimedMedia(
456
+ block: ProviderContentBlock,
457
+ input: TimedMediaInput
458
+ ): ProviderContentBlock | null | undefined {
459
+ if (block.type === 'media') {
460
+ const media = block as { mimeType?: unknown; mime_type?: unknown };
461
+ if (getTimedMediaMimeType(media.mimeType ?? media.mime_type) == null) {
462
+ return undefined;
463
+ }
464
+ return input === 'gemini' ? block : null;
465
+ }
466
+ if (block.type === 'input_audio' || block.type === 'video_url') {
467
+ if (input === 'openai') {
468
+ return block;
469
+ }
470
+ return input === 'gemini' ? toGeminiMedia(block) : null;
471
+ }
472
+ if (
473
+ isStandardFileBlock(block) &&
474
+ getTimedMediaMimeType(block.mime_type) != null
475
+ ) {
476
+ return input === 'gemini' ? block : null;
477
+ }
478
+ return undefined;
479
+ }
480
+
334
481
  function isBlankTextBlock(block: ProviderContentBlock): boolean {
335
482
  return (
336
483
  block.type === 'text' &&
@@ -369,29 +516,45 @@ function anchorCacheControl(
369
516
 
370
517
  /**
371
518
  * Resolves referenced attachments and reprojects persisted provider-native
372
- * ones, in one pass and without changing history.
519
+ * ones, in one pass and without changing history. Audio and video reach each
520
+ * provider in the part it reads, or not at all (`projectTimedMedia`); tool
521
+ * results keep their own tool-output projection.
373
522
  */
374
523
  function projectAttachmentsForProvider(
375
524
  messages: BaseMessage[],
376
525
  provider: t.ProviderName,
377
- resolve?: ResolveReference
526
+ projectionMode: ProviderMessageProjectionMode,
527
+ resolve?: ResolveReference,
528
+ imageOmission?: ImageOmission
378
529
  ): BaseMessage[] {
379
530
  const native =
380
531
  provider === Providers.BEDROCK || getProviderFamily(provider) === 'bedrock';
381
- if (native && resolve == null) {
382
- return messages;
383
- }
532
+ const timedMediaInput = getTimedMediaInput(provider, projectionMode);
384
533
  let projected: BaseMessage[] | undefined;
385
534
  for (let messageIndex = 0; messageIndex < messages.length; messageIndex++) {
386
535
  const message = messages[messageIndex];
387
536
  if (!Array.isArray(message.content)) {
388
537
  continue;
389
538
  }
539
+ const projectsTimedMedia = message.getType() !== 'tool';
540
+ /** A native computer-call output keeps its screenshot: the Responses API takes no other output. */
541
+ const omitsImages =
542
+ imageOmission != null && !hasComputerCallOutputMarker(message);
390
543
  const sourceContent = message.content as ProviderContentBlock[];
391
544
  let content: ProviderContentBlock[] | undefined;
392
545
  let displaced: ReturnType<typeof getCacheControl>;
546
+ let omittedImage = false;
393
547
  for (let blockIndex = 0; blockIndex < sourceContent.length; blockIndex++) {
394
548
  const block = sourceContent[blockIndex];
549
+ const omitted = omitsImages
550
+ ? omitImageBlock(block as MessageContentComplex)
551
+ : undefined;
552
+ if (omitted != null && omitted !== block) {
553
+ content ??= copyUsableContentPrefix(sourceContent, blockIndex);
554
+ content.push(omitted);
555
+ omittedImage = true;
556
+ continue;
557
+ }
395
558
  const resolved =
396
559
  resolve != null && isIDContentBlock(block) ? resolve(block) : undefined;
397
560
  if (resolved !== undefined) {
@@ -399,6 +562,9 @@ function projectAttachmentsForProvider(
399
562
  const marker = getCacheControl(block);
400
563
  if (resolved === null) {
401
564
  displaced = marker ?? displaced;
565
+ } else if (omitsImages && isImageContentBlock(resolved)) {
566
+ content.push(toOmittedImageBlock(block as MessageContentComplex));
567
+ omittedImage = true;
402
568
  } else {
403
569
  content.push(
404
570
  marker == null ? resolved : withCacheControl(resolved, marker)
@@ -406,6 +572,25 @@ function projectAttachmentsForProvider(
406
572
  }
407
573
  continue;
408
574
  }
575
+ const media = projectsTimedMedia
576
+ ? projectTimedMedia(block, timedMediaInput)
577
+ : undefined;
578
+ if (media === block) {
579
+ content?.push(block);
580
+ continue;
581
+ }
582
+ if (media !== undefined) {
583
+ content ??= copyUsableContentPrefix(sourceContent, blockIndex);
584
+ const marker = getCacheControl(block);
585
+ if (media === null) {
586
+ displaced = marker ?? displaced;
587
+ } else {
588
+ content.push(
589
+ marker == null ? media : withCacheControl(media, marker)
590
+ );
591
+ }
592
+ continue;
593
+ }
409
594
  if (native) {
410
595
  if (content != null && !isBlankTextBlock(block)) {
411
596
  content.push(block);
@@ -446,10 +631,15 @@ function projectAttachmentsForProvider(
446
631
  if (displaced != null) {
447
632
  anchorCacheControl(content as MessageContentComplex[], displaced);
448
633
  }
634
+ const projectedContent = content as MessageContentComplex[];
449
635
  projected ??= [...messages];
450
636
  projected[messageIndex] = cloneMessage(
451
637
  message,
452
- content as MessageContentComplex[]
638
+ omittedImage &&
639
+ imageOmission?.legacyContent === true &&
640
+ isLegacyConvertible(message, projectedContent)
641
+ ? flattenLegacyContent(projectedContent)
642
+ : projectedContent
453
643
  );
454
644
  }
455
645
  return projected ?? messages;
@@ -462,11 +652,14 @@ function projectMessagesForProviderMode(
462
652
  maxToolResultChars,
463
653
  toolHistory,
464
654
  resolve,
655
+ vision,
656
+ useLegacyContent,
465
657
  }: ProjectMessagesForProviderParams,
466
658
  projectionMode: ProviderMessageProjectionMode
467
659
  ): BaseMessage[] {
468
660
  const providerFamily = getProviderFamily(provider);
469
661
  const nativeOpenAIResponses = projectionMode === 'openai-responses';
662
+ /** Images go before tool results are serialized, so none lands in them as base64 text. */
470
663
  const providerInputMessages = projectAttachmentsForProvider(
471
664
  projectToolStreamContentForProvider(
472
665
  messages,
@@ -475,7 +668,9 @@ function projectMessagesForProviderMode(
475
668
  toolHistory
476
669
  ),
477
670
  provider,
478
- resolve
671
+ projectionMode,
672
+ resolve,
673
+ vision === false ? { legacyContent: useLegacyContent === true } : undefined
479
674
  );
480
675
  if (nativeOpenAIResponses) {
481
676
  return projectOpenAIResponsesToolMessageContent(
@@ -586,6 +781,8 @@ export function prepareProviderRequest({
586
781
  maxToolResultChars,
587
782
  measure,
588
783
  toolHistory = createToolHistoryPreparation(),
784
+ vision,
785
+ useLegacyContent,
589
786
  }: PrepareProviderRequestParams): PreparedProviderRequest {
590
787
  const projectionMode = resolveProviderMessageProjectionMode(
591
788
  model,
@@ -602,6 +799,8 @@ export function prepareProviderRequest({
602
799
  maxToolResultChars,
603
800
  callOptions: config,
604
801
  toolHistory,
802
+ vision,
803
+ useLegacyContent,
605
804
  resolve:
606
805
  resolveAttachment == null
607
806
  ? undefined
@@ -0,0 +1,158 @@
1
+ import { Buffer } from 'node:buffer';
2
+ import { performance } from 'node:perf_hooks';
3
+ import { AIMessageChunk } from '@langchain/core/messages';
4
+ import type { ChatGenerationChunk } from '@langchain/core/outputs';
5
+ import type {
6
+ ProviderTextAttempt,
7
+ ProviderTextBatching,
8
+ } from '@/protection/providerText';
9
+ import { ProviderTextProtectionError } from '@/protection/providerText';
10
+
11
+ /** A single provider read can overlap inspection or downstream publication. */
12
+ export class ProviderTextBatch {
13
+ private parts: string[] = [];
14
+ private freshBytes = 0;
15
+ private bytes = 0;
16
+ private stagedText = 0;
17
+ private stagedControl = 0;
18
+ private reading = false;
19
+ private next?: IteratorResult<ChatGenerationChunk>;
20
+ private timer?: ReturnType<typeof setTimeout>;
21
+ private deadline = Infinity;
22
+ private wake?: () => void;
23
+ private closed = false;
24
+
25
+ constructor(
26
+ private readonly attempt: ProviderTextAttempt,
27
+ private readonly options: ProviderTextBatching,
28
+ private readonly admit: (chunk: ChatGenerationChunk) => number
29
+ ) {}
30
+
31
+ private prefetch(source: AsyncGenerator<ChatGenerationChunk>): void {
32
+ if (this.reading || this.next != null) return;
33
+ this.reading = true;
34
+ void this.attempt
35
+ .wait(source.next())
36
+ .then((next) => {
37
+ this.reading = false;
38
+ if (this.closed) return;
39
+ this.attempt.check();
40
+ if (next.done !== true) {
41
+ const { content } = next.value.message;
42
+ if (
43
+ typeof content !== 'string' ||
44
+ !(next.value.message instanceof AIMessageChunk)
45
+ ) {
46
+ throw new ProviderTextProtectionError('unsupported');
47
+ }
48
+ this.stagedControl = this.admit(next.value);
49
+ // Raw fragments, their joined copy, and detached prefix/tail during a split.
50
+ this.stagedText = content === '' ? 0 : content.length * 8 + 256;
51
+ this.attempt.retain(this.stagedText + this.stagedControl);
52
+ }
53
+ this.next = next;
54
+ this.wake?.();
55
+ })
56
+ .catch((error: unknown) => {
57
+ if (this.closed) return;
58
+ this.attempt.stop(
59
+ error instanceof ProviderTextProtectionError
60
+ ? error
61
+ : new ProviderTextProtectionError('unavailable')
62
+ );
63
+ this.wake?.();
64
+ });
65
+ }
66
+
67
+ async read(
68
+ source: AsyncGenerator<ChatGenerationChunk>
69
+ ): Promise<IteratorResult<ChatGenerationChunk> | 'flush'> {
70
+ this.attempt.check();
71
+ this.prefetch(source);
72
+ for (;;) {
73
+ this.attempt.check();
74
+ if (
75
+ this.freshBytes >= this.options.batchBytes ||
76
+ performance.now() >= this.deadline
77
+ )
78
+ return 'flush';
79
+ if (this.next != null) {
80
+ const next = this.next;
81
+ this.next = undefined;
82
+ return next;
83
+ }
84
+ // Only one waiter, so a timer shared across a batch does not accumulate race listeners.
85
+ const signal = this.attempt.signal;
86
+ const ready = Promise.withResolvers<void>();
87
+ this.wake = (): void => ready.resolve();
88
+ signal.addEventListener('abort', this.wake, { once: true });
89
+ try {
90
+ if (!signal.aborted) await ready.promise;
91
+ } finally {
92
+ signal.removeEventListener('abort', this.wake);
93
+ this.wake = undefined;
94
+ }
95
+ }
96
+ }
97
+
98
+ append(text: string): void {
99
+ const bytes = this.stagedText;
100
+ this.stagedText = 0;
101
+ this.attempt.releaseWindow(this.stagedControl);
102
+ this.stagedControl = 0;
103
+ if (text === '') return;
104
+ this.parts.push(text);
105
+ this.freshBytes += text.length * 2;
106
+ this.bytes += bytes;
107
+ if (this.timer == null) {
108
+ this.deadline = performance.now() + this.options.flushMs;
109
+ this.timer = setTimeout(() => {
110
+ this.deadline = 0;
111
+ this.wake?.();
112
+ }, this.options.flushMs);
113
+ this.timer.unref();
114
+ }
115
+ }
116
+
117
+ async flush(final: boolean): Promise<string> {
118
+ this.resetTimer();
119
+ this.freshBytes = 0;
120
+ const text = this.parts.length === 1 ? this.parts[0] : this.parts.join('');
121
+ if (text === '') return '';
122
+ const approved = await this.attempt.inspect(text);
123
+ if (approved !== text)
124
+ throw new ProviderTextProtectionError('incompatible');
125
+ if (final) return text;
126
+ let end = Math.max(0, text.length - (this.options.maxMatchChars - 1));
127
+ if (end > 0) {
128
+ const previous = text.charCodeAt(end - 1);
129
+ if (previous >= 0xd800 && previous <= 0xdbff) end--;
130
+ }
131
+ if (end === 0) return '';
132
+ const tail = end === text.length ? '' : detach(text.slice(end));
133
+ const prefix = tail === '' ? text : detach(text.slice(0, end));
134
+ const retained = tail === '' ? 0 : tail.length * 8 + 256;
135
+ this.parts = tail === '' ? [] : [tail];
136
+ this.attempt.releaseWindow(this.bytes - retained);
137
+ this.bytes = retained;
138
+ return prefix;
139
+ }
140
+
141
+ private resetTimer(): void {
142
+ clearTimeout(this.timer);
143
+ this.timer = undefined;
144
+ this.deadline = Infinity;
145
+ }
146
+
147
+ close(): void {
148
+ this.closed = true;
149
+ this.resetTimer();
150
+ this.parts = [];
151
+ this.next = undefined;
152
+ }
153
+ }
154
+
155
+ /** Avoid keeping an unchecked suffix alive through a sliced, published prefix. */
156
+ function detach(text: string): string {
157
+ return Buffer.from(text, 'utf16le').toString('utf16le');
158
+ }