@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,110 @@
1
+ import type { OpenAIClient } from '@langchain/openai';
2
+
3
+ type Chunk = OpenAIClient.Chat.Completions.ChatCompletionChunk;
4
+ type Completion = OpenAIClient.Chat.Completions.ChatCompletion;
5
+ type Choice = Chunk['choices'][number];
6
+ type Delta = Choice['delta'] & { reasoning_content?: string };
7
+ /** Usage-only chunks carry no choice, Azure content-filter chunks no delta. */
8
+ type StreamChoice = Omit<Choice, 'delta'> & { delta?: Delta };
9
+ type Message = Completion['choices'][number]['message'] & {
10
+ reasoning_content?: string;
11
+ };
12
+ type TextPart = { type: 'text'; text?: string };
13
+ /**
14
+ * Mistral reasoning models send Chat Completions `content` as a list of typed
15
+ * parts instead of a string: `thinking` parts, each holding a list of `text`
16
+ * parts, carry the reasoning, and `text` parts carry the answer. Other part
17
+ * types are read as neither.
18
+ */
19
+ type ContentPart = TextPart | { type: 'thinking'; thinking?: TextPart[] };
20
+ type TypedText = { text: string; reasoning: string };
21
+
22
+ function readTypedContent(content: ContentPart[]): TypedText {
23
+ let text = '';
24
+ let reasoning = '';
25
+ for (const part of content) {
26
+ if (part.type === 'text' && typeof part.text === 'string') {
27
+ text += part.text;
28
+ continue;
29
+ }
30
+ if (part.type !== 'thinking' || !Array.isArray(part.thinking)) {
31
+ continue;
32
+ }
33
+ for (const thought of part.thinking) {
34
+ if (typeof thought.text === 'string') {
35
+ reasoning += thought.text;
36
+ }
37
+ }
38
+ }
39
+ return { text, reasoning };
40
+ }
41
+
42
+ /**
43
+ * Rewrites a streamed chunk whose `delta.content` is a typed list as string
44
+ * content with the reasoning in `reasoning_content`, or returns `undefined`
45
+ * when the content is not a list. The chunk that closes the reasoning also
46
+ * opens the answer or a tool call, so it splits in two: the reasoning first,
47
+ * then the rest of the delta.
48
+ */
49
+ export function splitTypedDeltaContent(chunk: Chunk): Chunk[] | undefined {
50
+ const choice = chunk.choices[0] as StreamChoice | undefined;
51
+ const delta = choice?.delta;
52
+ const content: unknown = delta?.content;
53
+ if (choice == null || delta == null || !Array.isArray(content)) {
54
+ return undefined;
55
+ }
56
+ const { text, reasoning } = readTypedContent(content);
57
+ const rest: Delta = { ...delta, content: text };
58
+ const others = chunk.choices.slice(1);
59
+ const continues = text !== '' || (rest.tool_calls?.length ?? 0) > 0;
60
+ if (reasoning === '' || !continues) {
61
+ if (reasoning !== '') {
62
+ rest.reasoning_content = reasoning;
63
+ }
64
+ return [{ ...chunk, choices: [{ ...choice, delta: rest }, ...others] }];
65
+ }
66
+ const thought: Delta = { content: '', reasoning_content: reasoning };
67
+ if (rest.role != null) {
68
+ thought.role = rest.role;
69
+ }
70
+ return [
71
+ {
72
+ ...chunk,
73
+ choices: [
74
+ { ...choice, delta: thought, finish_reason: null, logprobs: null },
75
+ ],
76
+ },
77
+ { ...chunk, choices: [{ ...choice, delta: rest }, ...others] },
78
+ ];
79
+ }
80
+
81
+ function flattenMessage(message: Message | undefined): Message | undefined {
82
+ const content: unknown = message?.content;
83
+ if (message == null || !Array.isArray(content)) {
84
+ return undefined;
85
+ }
86
+ const { text, reasoning } = readTypedContent(content);
87
+ const flat: Message = { ...message, content: text };
88
+ if (reasoning !== '') {
89
+ flat.reasoning_content = reasoning;
90
+ }
91
+ return flat;
92
+ }
93
+
94
+ /** Rewrites the typed `message.content` lists of a non-streamed completion. */
95
+ export function flattenTypedMessageContent(completion: Completion): Completion {
96
+ if (!Array.isArray(completion.choices)) {
97
+ return completion;
98
+ }
99
+ let choices: Completion['choices'] | undefined;
100
+ for (let i = 0; i < completion.choices.length; i++) {
101
+ const choice = completion.choices[i];
102
+ const message = flattenMessage(choice.message);
103
+ if (message == null) {
104
+ continue;
105
+ }
106
+ choices ??= [...completion.choices];
107
+ choices[i] = { ...choice, message };
108
+ }
109
+ return choices == null ? completion : { ...completion, choices };
110
+ }
@@ -331,6 +331,134 @@ function canProjectBedrockDocument(
331
331
  return false;
332
332
  }
333
333
 
334
+ /** How one provider request takes audio and video. */
335
+ type TimedMediaInput = 'gemini' | 'openai' | 'none';
336
+
337
+ /**
338
+ * Gemini and Vertex read audio and video as `media` parts. OpenAI-compatible
339
+ * Chat Completions endpoints read `input_audio` and `video_url` parts, where
340
+ * the endpoint and model accept them, which only the host can tell. Claude,
341
+ * Bedrock's Converse converter and the Responses API read none of them.
342
+ */
343
+ function getTimedMediaInput(
344
+ provider: t.ProviderName,
345
+ projectionMode: ProviderMessageProjectionMode
346
+ ): TimedMediaInput {
347
+ if (isGoogleLike(provider)) {
348
+ return 'gemini';
349
+ }
350
+ const family = getProviderFamily(provider);
351
+ if (
352
+ projectionMode === 'openai-responses' ||
353
+ provider === Providers.ANTHROPIC ||
354
+ family === 'anthropic' ||
355
+ provider === Providers.BEDROCK ||
356
+ family === 'bedrock'
357
+ ) {
358
+ return 'none';
359
+ }
360
+ return 'openai';
361
+ }
362
+
363
+ /** The audio or video MIME type a block names, normalized; `undefined` for anything else. */
364
+ function getTimedMediaMimeType(mimeType: unknown): string | undefined {
365
+ if (typeof mimeType !== 'string') {
366
+ return undefined;
367
+ }
368
+ const normalized = mimeType.split(';', 1)[0].trim().toLowerCase();
369
+ return normalized.startsWith('audio/') || normalized.startsWith('video/')
370
+ ? normalized
371
+ : undefined;
372
+ }
373
+
374
+ /** Gemini's MIME type for each `input_audio` format it plays; raw PCM names no sample rate. */
375
+ const GEMINI_AUDIO_MIME_TYPES: Readonly<Partial<Record<string, string>>> = {
376
+ aac: 'audio/aac',
377
+ aiff: 'audio/aiff',
378
+ flac: 'audio/flac',
379
+ m4a: 'audio/mp4',
380
+ mp3: 'audio/mp3',
381
+ ogg: 'audio/ogg',
382
+ wav: 'audio/wav',
383
+ webm: 'audio/webm',
384
+ };
385
+
386
+ /** The MIME type and payload of a base64 `data:` URL. */
387
+ function parseDataUrl(
388
+ url: string
389
+ ): { mimeType: string; data: string } | undefined {
390
+ const comma = url.indexOf(',');
391
+ if (!url.startsWith('data:') || comma < 0) {
392
+ return undefined;
393
+ }
394
+ const [mimeType, ...parameters] = url.slice(5, comma).split(';');
395
+ if (parameters.at(-1)?.trim().toLowerCase() !== 'base64') {
396
+ return undefined;
397
+ }
398
+ const data = url.slice(comma + 1);
399
+ return data === '' ? undefined : { mimeType, data };
400
+ }
401
+
402
+ /** An OpenAI-compatible audio or video part as Gemini inline media, when it carries its bytes. */
403
+ function toGeminiMedia(
404
+ block: ProviderContentBlock
405
+ ): ProviderContentBlock | null {
406
+ if (block.type === 'input_audio') {
407
+ const audio = (
408
+ block as { input_audio?: { data?: unknown; format?: unknown } }
409
+ ).input_audio;
410
+ const mimeType =
411
+ typeof audio?.format === 'string'
412
+ ? GEMINI_AUDIO_MIME_TYPES[audio.format.toLowerCase()]
413
+ : undefined;
414
+ return mimeType != null &&
415
+ typeof audio?.data === 'string' &&
416
+ audio.data !== ''
417
+ ? { type: 'media', mimeType, data: audio.data }
418
+ : null;
419
+ }
420
+ const video = (block as { video_url?: string | { url?: unknown } | null })
421
+ .video_url;
422
+ const url = typeof video === 'string' ? video : video?.url;
423
+ const parsed = typeof url === 'string' ? parseDataUrl(url) : undefined;
424
+ const mimeType = getTimedMediaMimeType(parsed?.mimeType);
425
+ return parsed != null && mimeType != null
426
+ ? { type: 'media', mimeType, data: parsed.data }
427
+ : null;
428
+ }
429
+
430
+ /**
431
+ * The part a request that takes `input` gets for an audio or video part: the
432
+ * part itself when its provider reads it, Gemini inline media rewritten from
433
+ * an OpenAI-compatible part, or `null` to leave it out. `undefined` for any
434
+ * other block.
435
+ */
436
+ function projectTimedMedia(
437
+ block: ProviderContentBlock,
438
+ input: TimedMediaInput
439
+ ): ProviderContentBlock | null | undefined {
440
+ if (block.type === 'media') {
441
+ const media = block as { mimeType?: unknown; mime_type?: unknown };
442
+ if (getTimedMediaMimeType(media.mimeType ?? media.mime_type) == null) {
443
+ return undefined;
444
+ }
445
+ return input === 'gemini' ? block : null;
446
+ }
447
+ if (block.type === 'input_audio' || block.type === 'video_url') {
448
+ if (input === 'openai') {
449
+ return block;
450
+ }
451
+ return input === 'gemini' ? toGeminiMedia(block) : null;
452
+ }
453
+ if (
454
+ isStandardFileBlock(block) &&
455
+ getTimedMediaMimeType(block.mime_type) != null
456
+ ) {
457
+ return input === 'gemini' ? block : null;
458
+ }
459
+ return undefined;
460
+ }
461
+
334
462
  function isBlankTextBlock(block: ProviderContentBlock): boolean {
335
463
  return (
336
464
  block.type === 'text' &&
@@ -369,24 +497,26 @@ function anchorCacheControl(
369
497
 
370
498
  /**
371
499
  * Resolves referenced attachments and reprojects persisted provider-native
372
- * ones, in one pass and without changing history.
500
+ * ones, in one pass and without changing history. Audio and video reach each
501
+ * provider in the part it reads, or not at all (`projectTimedMedia`); tool
502
+ * results keep their own tool-output projection.
373
503
  */
374
504
  function projectAttachmentsForProvider(
375
505
  messages: BaseMessage[],
376
506
  provider: t.ProviderName,
507
+ projectionMode: ProviderMessageProjectionMode,
377
508
  resolve?: ResolveReference
378
509
  ): BaseMessage[] {
379
510
  const native =
380
511
  provider === Providers.BEDROCK || getProviderFamily(provider) === 'bedrock';
381
- if (native && resolve == null) {
382
- return messages;
383
- }
512
+ const timedMediaInput = getTimedMediaInput(provider, projectionMode);
384
513
  let projected: BaseMessage[] | undefined;
385
514
  for (let messageIndex = 0; messageIndex < messages.length; messageIndex++) {
386
515
  const message = messages[messageIndex];
387
516
  if (!Array.isArray(message.content)) {
388
517
  continue;
389
518
  }
519
+ const projectsTimedMedia = message.getType() !== 'tool';
390
520
  const sourceContent = message.content as ProviderContentBlock[];
391
521
  let content: ProviderContentBlock[] | undefined;
392
522
  let displaced: ReturnType<typeof getCacheControl>;
@@ -406,6 +536,25 @@ function projectAttachmentsForProvider(
406
536
  }
407
537
  continue;
408
538
  }
539
+ const media = projectsTimedMedia
540
+ ? projectTimedMedia(block, timedMediaInput)
541
+ : undefined;
542
+ if (media === block) {
543
+ content?.push(block);
544
+ continue;
545
+ }
546
+ if (media !== undefined) {
547
+ content ??= copyUsableContentPrefix(sourceContent, blockIndex);
548
+ const marker = getCacheControl(block);
549
+ if (media === null) {
550
+ displaced = marker ?? displaced;
551
+ } else {
552
+ content.push(
553
+ marker == null ? media : withCacheControl(media, marker)
554
+ );
555
+ }
556
+ continue;
557
+ }
409
558
  if (native) {
410
559
  if (content != null && !isBlankTextBlock(block)) {
411
560
  content.push(block);
@@ -475,6 +624,7 @@ function projectMessagesForProviderMode(
475
624
  toolHistory
476
625
  ),
477
626
  provider,
627
+ projectionMode,
478
628
  resolve
479
629
  );
480
630
  if (nativeOpenAIResponses) {
@@ -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
+ }
@@ -21,6 +21,7 @@ import {
21
21
  import { isProviderTextInput } from '@/protection/providerTextInput';
22
22
  import { createProviderTextChunk } from '@/llm/providerTextChunk';
23
23
  import { preserveModelInvocationContext } from '@/llm/invocation';
24
+ import { ProviderTextBatch } from '@/llm/providerTextBatch';
24
25
  import { getChatModelClass } from '@/llm/providers';
25
26
  import { Providers } from '@/common';
26
27
 
@@ -136,6 +137,52 @@ function validateMetadata(metadata: AIMessageChunk['response_metadata'], google
136
137
  }
137
138
  }
138
139
 
140
+ /** The staged frame may contain provider controls as well as raw prose. */
141
+ function batchControls(generation: ChatGenerationChunk): number {
142
+ const message = generation.message as AIMessageChunk;
143
+ if (
144
+ (message.tool_calls?.length ?? 0) > 0 ||
145
+ (message.tool_call_chunks?.length ?? 0) > 0 ||
146
+ (message.invalid_tool_calls?.length ?? 0) > 0 ||
147
+ Object.hasOwn(message.response_metadata, 'output') ||
148
+ generation.text !== message.content
149
+ ) throw new ProviderTextProtectionError('unsupported');
150
+
151
+ for (const key of Object.keys(message.additional_kwargs)) {
152
+ if (!Object.hasOwn(additionalControls, key) || additionalControls[key]?.(message.additional_kwargs[key]) !== true) {
153
+ throw new ProviderTextProtectionError('unsupported');
154
+ }
155
+ }
156
+ validateMetadata(message.response_metadata);
157
+ validateMetadata(generation.generationInfo ?? {});
158
+ if (!numericMetadata(message.usage_metadata)) throw new ProviderTextProtectionError('unsupported');
159
+
160
+ let bytes = 256 + ((message.id?.length ?? 0) + (message.name?.length ?? 0)) * 2;
161
+ for (const record of [message.additional_kwargs, message.response_metadata, generation.generationInfo]) {
162
+ if (record == null) continue;
163
+ for (const [key, value] of Object.entries(record)) {
164
+ bytes += key.length * 2 + metadataBytes(value);
165
+ }
166
+ }
167
+ return bytes + metadataBytes(message.usage_metadata);
168
+ }
169
+
170
+ /** Called only for already validated scalar or bounded numeric metadata. */
171
+ function metadataBytes(value: unknown): number {
172
+ if (typeof value === 'string') return value.length * 2 + 16;
173
+ if (typeof value !== 'object' || value == null) return 16;
174
+ let bytes = 64;
175
+ for (const [key, entry] of Object.entries(value)) bytes += key.length * 2 + metadataBytes(entry);
176
+ return bytes;
177
+ }
178
+
179
+ function batchChunk(text: string): ChatGenerationChunk | undefined {
180
+ return text === '' ? undefined : new ChatGenerationChunk({
181
+ text,
182
+ message: new AIMessageChunk({ content: text }),
183
+ });
184
+ }
185
+
139
186
  class Candidate {
140
187
  private block?: TextBlock;
141
188
  private stringContent = false;
@@ -144,10 +191,23 @@ class Candidate {
144
191
 
145
192
  constructor(private readonly attempt: ProviderTextAttempt, private readonly provider?: ProviderName) { this.responses = new ResponsesTextProjection(attempt); }
146
193
 
147
- strip(generation: ChatGenerationChunk): ChatGenerationChunk {
194
+ strip(generation: ChatGenerationChunk): ChatGenerationChunk;
195
+ strip(generation: ChatGenerationChunk, batch: ProviderTextBatch | undefined): ChatGenerationChunk | undefined;
196
+ strip(generation: ChatGenerationChunk, batch?: ProviderTextBatch): ChatGenerationChunk | undefined {
148
197
  const message = generation.message;
149
198
  if (!(message instanceof AIMessageChunk))
150
199
  throw new ProviderTextProtectionError('unsupported');
200
+ if (batch != null) {
201
+ if (typeof message.content !== 'string') throw new ProviderTextProtectionError('unsupported');
202
+ batch.append(message.content);
203
+ if (message.id == null && message.name == null && message.usage_metadata == null &&
204
+ Object.keys(message.additional_kwargs).length === 0 &&
205
+ Object.keys(message.response_metadata).length === 0 &&
206
+ Object.keys(generation.generationInfo ?? {}).length === 0) return undefined;
207
+ return new ChatGenerationChunk({
208
+ text: '', message: copyMessage(message, ''), generationInfo: generation.generationInfo,
209
+ });
210
+ }
151
211
  this.attempt.observeChunk();
152
212
  for (const key of Object.keys(message.additional_kwargs)) {
153
213
  if (additionalKeys.has(key)) continue;
@@ -303,17 +363,25 @@ function usesInternalStreaming(
303
363
  return false;
304
364
  }
305
365
 
366
+ interface BatchInvocation {
367
+ getAttempt: (signal?: AbortSignal) => ProviderTextAttempt;
368
+ dispatchStart?: (attempt: ProviderTextAttempt) => void | Promise<void>;
369
+ }
370
+
306
371
  /** Clone only known runnable shells. Never mutate a shared provider or its callback configuration. */
307
372
  export function withProviderTextBoundary(
308
373
  model: ChatModel,
309
374
  policy: ProviderTextProtection,
310
- provider?: ProviderName
375
+ provider?: ProviderName,
376
+ batchInvocation?: BatchInvocation
311
377
  ): ChatModel {
312
378
  const protectedModel = clone(model);
313
379
  if (model instanceof RunnableBinding) {
314
380
  assertBindingShell(model);
315
381
  Object.defineProperty(protectedModel, 'bound', {
316
- value: withProviderTextBoundary(model.bound as ChatModel, policy, provider),
382
+ value: withProviderTextBoundary(
383
+ model.bound as ChatModel, policy, provider, batchInvocation
384
+ ),
317
385
  });
318
386
  return protectedModel;
319
387
  }
@@ -330,7 +398,8 @@ export function withProviderTextBoundary(
330
398
  value: withProviderTextBoundary(
331
399
  steps[steps.length - 1] as ChatModel,
332
400
  policy,
333
- provider
401
+ provider,
402
+ batchInvocation
334
403
  ),
335
404
  });
336
405
  return protectedModel;
@@ -354,16 +423,27 @@ export function withProviderTextBoundary(
354
423
  if (model.disableStreaming && usesInternalStreaming(model)) {
355
424
  throw new ProviderTextProtectionError('unsupported');
356
425
  }
426
+ if (policy.batching != null && provider !== Providers.OPENAI) {
427
+ throw new ProviderTextProtectionError('unsupported');
428
+ }
357
429
  const protectedChat = clone(model);
358
430
  protectedChat._streamResponseChunks = async function* (
359
431
  messages,
360
432
  options,
361
433
  runManager
362
434
  ): AsyncGenerator<ChatGenerationChunk> {
363
- const attempt = new ProviderTextAttempt(policy, options.signal);
435
+ const attempt =
436
+ batchInvocation?.getAttempt(options.signal) ??
437
+ new ProviderTextAttempt(policy, options.signal);
364
438
  const candidate = new Candidate(attempt, provider);
439
+ const batch = policy.batching == null ? undefined : new ProviderTextBatch(attempt, policy.batching, batchControls);
440
+ let completed = false;
365
441
  let source: AsyncGenerator<ChatGenerationChunk> | undefined;
366
442
  try {
443
+ if (batch != null) {
444
+ const ready = batchInvocation?.dispatchStart?.(attempt);
445
+ if (ready != null) await ready;
446
+ }
367
447
  source = model._streamResponseChunks(
368
448
  messages,
369
449
  preserveModelInvocationContext(
@@ -374,26 +454,35 @@ export function withProviderTextBoundary(
374
454
  undefined
375
455
  );
376
456
  for (;;) {
377
- const next = await attempt.wait(source.next());
457
+ const next = batch == null ? await attempt.wait(source.next()) : await batch.read(source);
458
+ attempt.check();
459
+ if (next !== 'flush' && next.done === true) break;
460
+ const chunk = next === 'flush'
461
+ ? batchChunk(await batch!.flush(false))
462
+ : candidate.strip(next.value, batch);
463
+ if (chunk == null) continue;
378
464
  attempt.check();
379
- if (next.done === true) break;
380
- const chunk = candidate.strip(next.value);
465
+ if (batch != null && chunk.text !== '') attempt.markTextPublished();
381
466
  yield chunk;
382
- await runManager?.handleLLMNewToken(
383
- '',
467
+ if (batch != null) attempt.check();
468
+ const notification = runManager?.handleLLMNewToken(
469
+ chunk.text,
384
470
  undefined,
385
471
  undefined,
386
472
  undefined,
387
473
  undefined,
388
474
  { chunk }
389
475
  );
476
+ if (batch != null && notification != null) await attempt.wait(notification, false);
477
+ else await notification;
390
478
  }
391
- const canonical = await candidate.canonical();
479
+ const canonical = batch == null ? await candidate.canonical() : batchChunk(await batch.flush(true));
392
480
  attempt.check();
393
481
  if (canonical != null) {
482
+ if (batch != null) attempt.markTextPublished();
394
483
  yield canonical;
395
484
  attempt.check();
396
- await runManager?.handleLLMNewToken(
485
+ const notification = runManager?.handleLLMNewToken(
397
486
  canonical.text,
398
487
  undefined,
399
488
  undefined,
@@ -401,8 +490,23 @@ export function withProviderTextBoundary(
401
490
  undefined,
402
491
  { chunk: canonical }
403
492
  );
493
+ if (batch != null && notification != null) await attempt.wait(notification, false);
494
+ else await notification;
404
495
  }
496
+ completed = true;
497
+ } catch (error) {
498
+ if (batch == null) throw error;
499
+ attempt.check();
500
+ const safe = error instanceof ProviderTextProtectionError
501
+ ? error
502
+ : new ProviderTextProtectionError('unavailable');
503
+ attempt.stop(safe);
504
+ throw safe;
405
505
  } finally {
506
+ if (batch != null) {
507
+ batch.close();
508
+ if (!completed) attempt.stop(new ProviderTextProtectionError('cancelled'));
509
+ }
406
510
  try {
407
511
  if (source != null) void attempt.wait(source.return(undefined)).catch(() => {});
408
512
  } finally {
@@ -413,7 +517,9 @@ export function withProviderTextBoundary(
413
517
  protectedChat._streamChatModelEvents =
414
518
  BaseChatModel.prototype._streamChatModelEvents;
415
519
  protectedChat._generate = async function (messages, options, runManager): Promise<ChatResult> {
416
- if (usesInternalStreaming(model, options)) throw new ProviderTextProtectionError('unsupported');
520
+ if (policy.batching != null || usesInternalStreaming(model, options)) {
521
+ throw new ProviderTextProtectionError('unsupported');
522
+ }
417
523
  const attempt = new ProviderTextAttempt(policy, options.signal);
418
524
  try {
419
525
  const result = await attempt.wait(