ai 7.0.166 → 7.0.169

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 (33) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/dist/index.d.ts +51 -7
  3. package/dist/index.d.ts.map +1 -1
  4. package/dist/index.js +747 -513
  5. package/dist/index.js.map +1 -1
  6. package/dist/internal/index.d.ts +1 -0
  7. package/dist/internal/index.d.ts.map +1 -1
  8. package/dist/internal/index.js +90 -10
  9. package/dist/internal/index.js.map +1 -1
  10. package/docs/02-foundations/02-providers-and-models.mdx +2 -0
  11. package/docs/03-ai-sdk-core/16-mcp-tools.mdx +13 -0
  12. package/docs/03-ai-sdk-core/60-telemetry.mdx +9 -0
  13. package/docs/03-ai-sdk-harnesses/02-harness-agent.mdx +4 -0
  14. package/docs/03-ai-sdk-harnesses/06-workflow-utilities.mdx +5 -0
  15. package/docs/04-ai-sdk-ui/02-chatbot.mdx +58 -0
  16. package/docs/06-advanced/11-secure-url-fetching.mdx +12 -0
  17. package/docs/07-reference/02-ai-sdk-ui/01-use-chat.mdx +24 -0
  18. package/package.json +12 -12
  19. package/src/prompt/content-part.ts +1 -1
  20. package/src/prompt/message.ts +1 -1
  21. package/src/realtime/validate-realtime-setup.ts +23 -19
  22. package/src/telemetry/create-telemetry-dispatcher.ts +30 -3
  23. package/src/telemetry/redact-telemetry-credentials.ts +80 -0
  24. package/src/telemetry/tracing-channel-publisher.ts +7 -4
  25. package/src/types/citation.ts +7 -7
  26. package/src/types/json-value.ts +1 -1
  27. package/src/types/provider-metadata.ts +1 -1
  28. package/src/ui/chat.ts +313 -7
  29. package/src/ui/validate-ui-messages.ts +157 -155
  30. package/src/ui-message-stream/to-ui-message-stream.ts +27 -10
  31. package/src/ui-message-stream/ui-message-chunks.ts +66 -63
  32. package/src/util/classic-zod.ts +37 -0
  33. package/src/util/zod.ts +25 -10
package/src/ui/chat.ts CHANGED
@@ -159,6 +159,13 @@ export interface ChatState<UI_MESSAGE extends UIMessage> {
159
159
  popMessage: () => void;
160
160
  replaceMessage: (index: number, message: UI_MESSAGE) => void;
161
161
 
162
+ /**
163
+ * Experimental. Messages that are waiting to be sent when
164
+ * `experimental_queue` is enabled. States that don't implement it keep the
165
+ * queue in the chat, without change notifications.
166
+ */
167
+ experimental_queuedMessages?: UI_MESSAGE[];
168
+
162
169
  snapshot: <T>(thing: T) => T;
163
170
  }
164
171
 
@@ -246,6 +253,17 @@ export interface ChatInit<UI_MESSAGE extends UIMessage> {
246
253
  sendAutomaticallyWhen?: (options: {
247
254
  messages: UI_MESSAGE[];
248
255
  }) => boolean | PromiseLike<boolean>;
256
+
257
+ /**
258
+ * Experimental. Queue messages that are sent while a response is in progress
259
+ * or while the assistant waits for a tool result or approval, and send them
260
+ * one at a time after each response finishes. Stopping, an error or an
261
+ * interrupted response pauses the queue until the next message is sent.
262
+ * Editing a message or regenerating clears the queue.
263
+ *
264
+ * @default false
265
+ */
266
+ experimental_queue?: boolean;
249
267
  }
250
268
 
251
269
  export abstract class AbstractChat<UI_MESSAGE extends UIMessage> {
@@ -271,6 +289,16 @@ export abstract class AbstractChat<UI_MESSAGE extends UIMessage> {
271
289
  private onFinish?: ChatInit<UI_MESSAGE>['onFinish'];
272
290
  private onData?: ChatInit<UI_MESSAGE>['onData'];
273
291
  private sendAutomaticallyWhen?: ChatInit<UI_MESSAGE>['sendAutomaticallyWhen'];
292
+ private queueEnabled: boolean;
293
+ private queuedMessagesFallback: UI_MESSAGE[] = [];
294
+ private queuedMessageOptions = new Map<string, ChatRequestOptions>();
295
+ // a stop or an error pauses the queue. a paused response is not waiting for
296
+ // the user, so resuming the queue skips that check:
297
+ private isQueuePaused = false;
298
+ private pendingAutomaticDecisions: number[] = [];
299
+ // a user send that has to wait to send an answered approval first, with the
300
+ // request options of that send:
301
+ private deferredApprovalSend: { options?: ChatRequestOptions } | undefined;
274
302
 
275
303
  private pendingMessagePreparations = new Set<AbortController>();
276
304
  private pendingApprovalMessageId: string | undefined;
@@ -298,6 +326,7 @@ export abstract class AbstractChat<UI_MESSAGE extends UIMessage> {
298
326
  onFinish,
299
327
  onData,
300
328
  sendAutomaticallyWhen,
329
+ experimental_queue = false,
301
330
  }: Omit<ChatInit<UI_MESSAGE>, 'messages'> & {
302
331
  state: ChatState<UI_MESSAGE>;
303
332
  }) {
@@ -312,6 +341,7 @@ export abstract class AbstractChat<UI_MESSAGE extends UIMessage> {
312
341
  this.onFinish = onFinish;
313
342
  this.onData = onData;
314
343
  this.sendAutomaticallyWhen = sendAutomaticallyWhen;
344
+ this.queueEnabled = experimental_queue;
315
345
  }
316
346
 
317
347
  /**
@@ -356,6 +386,196 @@ export abstract class AbstractChat<UI_MESSAGE extends UIMessage> {
356
386
  return this.state.messages[this.state.messages.length - 1];
357
387
  }
358
388
 
389
+ /**
390
+ * Experimental. Messages that wait to be sent when `experimental_queue` is
391
+ * enabled, in the order they will be sent.
392
+ */
393
+ get experimental_queuedMessages(): UI_MESSAGE[] {
394
+ return (
395
+ this.state.experimental_queuedMessages ?? this.queuedMessagesFallback
396
+ );
397
+ }
398
+
399
+ private setQueuedMessages(experimental_queuedMessages: UI_MESSAGE[]) {
400
+ if ('experimental_queuedMessages' in this.state) {
401
+ this.state.experimental_queuedMessages = experimental_queuedMessages;
402
+ } else {
403
+ this.queuedMessagesFallback = experimental_queuedMessages;
404
+ }
405
+ }
406
+
407
+ /**
408
+ * Experimental. Removes a queued message so it is not sent.
409
+ */
410
+ experimental_removeQueuedMessage = (id: string): void => {
411
+ this.queuedMessageOptions.delete(id);
412
+ this.setQueuedMessages(
413
+ this.experimental_queuedMessages.filter(message => message.id !== id),
414
+ );
415
+ };
416
+
417
+ /**
418
+ * Experimental. Stops the response in progress and sends the queued message
419
+ * with the given id next. The rest of the queue is sent after it.
420
+ */
421
+ experimental_sendQueuedMessageNow = async (id: string): Promise<void> => {
422
+ const message = this.experimental_queuedMessages.find(
423
+ message => message.id === id,
424
+ );
425
+
426
+ if (message == null) {
427
+ return;
428
+ }
429
+
430
+ this.setQueuedMessages([
431
+ message,
432
+ ...this.experimental_queuedMessages.filter(queued => queued.id !== id),
433
+ ]);
434
+
435
+ await this.stop();
436
+ await this.resumeQueue({
437
+ skipWaitForUser: true,
438
+ options: this.queuedMessageOptions.get(id),
439
+ });
440
+ };
441
+
442
+ // the user sending a message resumes a paused queue (after a stop, an error
443
+ // or an interruption). an answered approval that was not sent yet goes
444
+ // first, the queue continues when its response finishes:
445
+ private async resumeQueue({
446
+ skipWaitForUser,
447
+ options,
448
+ }: {
449
+ skipWaitForUser: boolean;
450
+ options?: ChatRequestOptions;
451
+ }): Promise<void> {
452
+ this.isQueuePaused = false;
453
+
454
+ if (this.hasUnsentApprovalResponse()) {
455
+ if (!this.isRequestInProgress()) {
456
+ await this.sendMessage(undefined, options);
457
+ return;
458
+ }
459
+
460
+ // a pending sendAutomaticallyWhen decision can still send the approval.
461
+ // if it does not, the queue sends it first when it settles:
462
+ this.deferredApprovalSend = { options };
463
+ }
464
+
465
+ await this.settleQueue({ skipWaitForUser });
466
+ }
467
+
468
+ // editing a message or regenerating rewrites the history that the queued
469
+ // messages were sent after, so they are dropped together with the response
470
+ // in progress:
471
+ private async clearQueueForHistoryChange(): Promise<void> {
472
+ if (!this.queueEnabled) {
473
+ return;
474
+ }
475
+
476
+ this.queuedMessageOptions.clear();
477
+ this.setQueuedMessages([]);
478
+ this.deferredApprovalSend = undefined;
479
+
480
+ if (this.isRequestInProgress()) {
481
+ await this.stop();
482
+ }
483
+ }
484
+
485
+ // a pending sendAutomaticallyWhen decision can still start a request, so the
486
+ // queue waits for it like for a response in progress. a stop invalidates the
487
+ // decisions that were pending, so they no longer hold the queue:
488
+ private isRequestInProgress(): boolean {
489
+ return (
490
+ this.pendingAutomaticDecisions.includes(this.stopGeneration) ||
491
+ this.activeResponse != null ||
492
+ this.status === 'submitted' ||
493
+ this.status === 'streaming'
494
+ );
495
+ }
496
+
497
+ // the assistant waits for the user when the last message has a tool call
498
+ // without a result or an approval that has not been sent yet:
499
+ private isWaitingForUser(): boolean {
500
+ const lastMessage = this.lastMessage;
501
+
502
+ return (
503
+ lastMessage?.role === 'assistant' &&
504
+ lastMessage.parts.some(
505
+ part =>
506
+ isToolUIPart(part) &&
507
+ (part.state === 'approval-requested' ||
508
+ part.state === 'approval-responded' ||
509
+ (!part.providerExecuted &&
510
+ (part.state === 'input-streaming' ||
511
+ part.state === 'input-available'))),
512
+ )
513
+ );
514
+ }
515
+
516
+ // an answered approval has to reach the model before the next user message,
517
+ // otherwise its tool call is left without a result:
518
+ private hasUnsentApprovalResponse(): boolean {
519
+ const lastMessage = this.lastMessage;
520
+
521
+ return (
522
+ lastMessage?.role === 'assistant' &&
523
+ lastMessage.parts.some(
524
+ part => isToolUIPart(part) && part.state === 'approval-responded',
525
+ ) &&
526
+ !lastMessage.parts.some(
527
+ part =>
528
+ isToolUIPart(part) &&
529
+ (part.state === 'approval-requested' ||
530
+ (!part.providerExecuted &&
531
+ (part.state === 'input-streaming' ||
532
+ part.state === 'input-available'))),
533
+ )
534
+ );
535
+ }
536
+
537
+ // every path that can leave the chat idle ends here. the queue then either
538
+ // sends its next message, stays paused until the user sends again, or waits
539
+ // for the user to answer a tool call. a stop that happened after the caller
540
+ // captured `stopGeneration` cancels the send:
541
+ private async settleQueue({
542
+ stopGeneration = this.stopGeneration,
543
+ skipWaitForUser = false,
544
+ }: {
545
+ stopGeneration?: number;
546
+ skipWaitForUser?: boolean;
547
+ } = {}): Promise<void> {
548
+ if (
549
+ this.isQueuePaused ||
550
+ this.isRequestInProgress() ||
551
+ this.activeStopCount > 0 ||
552
+ stopGeneration !== this.stopGeneration
553
+ ) {
554
+ return;
555
+ }
556
+
557
+ const deferredApprovalSend = this.deferredApprovalSend;
558
+ this.deferredApprovalSend = undefined;
559
+ if (deferredApprovalSend != null && this.hasUnsentApprovalResponse()) {
560
+ await this.sendMessage(undefined, deferredApprovalSend.options);
561
+ return;
562
+ }
563
+
564
+ const [message, ...rest] = this.experimental_queuedMessages;
565
+
566
+ if (message == null || (!skipWaitForUser && this.isWaitingForUser())) {
567
+ return;
568
+ }
569
+
570
+ const options = this.queuedMessageOptions.get(message.id);
571
+ this.queuedMessageOptions.delete(message.id);
572
+ this.setQueuedMessages(rest);
573
+
574
+ this.state.pushMessage(message);
575
+
576
+ await this.makeRequest({ trigger: 'submit-message', ...options });
577
+ }
578
+
359
579
  set messages(messages: UI_MESSAGE[]) {
360
580
  this.state.messages = messages;
361
581
  }
@@ -456,7 +676,40 @@ export abstract class AbstractChat<UI_MESSAGE extends UIMessage> {
456
676
  uiMessage = message;
457
677
  }
458
678
 
679
+ if (
680
+ this.queueEnabled &&
681
+ message.messageId == null &&
682
+ (this.isRequestInProgress() ||
683
+ this.isWaitingForUser() ||
684
+ this.experimental_queuedMessages.length > 0)
685
+ ) {
686
+ const queuedMessage = {
687
+ ...uiMessage,
688
+ id: uiMessage.id ?? this.generateId(),
689
+ role: uiMessage.role ?? 'user',
690
+ metadata: message.metadata,
691
+ } as UI_MESSAGE;
692
+
693
+ if (options != null) {
694
+ this.queuedMessageOptions.set(queuedMessage.id, options);
695
+ }
696
+ this.setQueuedMessages([
697
+ ...this.experimental_queuedMessages,
698
+ queuedMessage,
699
+ ]);
700
+
701
+ // a stopped response is not waiting for the user anymore, so resuming a
702
+ // paused queue skips that check:
703
+ await this.resumeQueue({
704
+ skipWaitForUser: this.isQueuePaused,
705
+ options,
706
+ });
707
+ return;
708
+ }
709
+
459
710
  if (message.messageId != null) {
711
+ await this.clearQueueForHistoryChange();
712
+
460
713
  const messageIndex = this.state.messages.findIndex(
461
714
  m => m.id === message.messageId,
462
715
  );
@@ -496,6 +749,9 @@ export abstract class AbstractChat<UI_MESSAGE extends UIMessage> {
496
749
  } as UI_MESSAGE);
497
750
  }
498
751
 
752
+ // sending a new message is the user taking over after a stop or an error:
753
+ this.isQueuePaused = false;
754
+
499
755
  await this.makeRequest({
500
756
  trigger: 'submit-message',
501
757
  messageId: message.messageId,
@@ -513,6 +769,8 @@ export abstract class AbstractChat<UI_MESSAGE extends UIMessage> {
513
769
  }: {
514
770
  messageId?: string;
515
771
  } & ChatRequestOptions = {}): Promise<void> => {
772
+ await this.clearQueueForHistoryChange();
773
+
516
774
  const messageIndex =
517
775
  messageId == null
518
776
  ? this.state.messages.length - 1
@@ -593,6 +851,7 @@ export abstract class AbstractChat<UI_MESSAGE extends UIMessage> {
593
851
  options,
594
852
  }) =>
595
853
  this.jobExecutor.run(async () => {
854
+ const stopGeneration = this.stopGeneration;
596
855
  const messages = this.state.messages;
597
856
 
598
857
  const updatePart = (
@@ -659,8 +918,12 @@ export abstract class AbstractChat<UI_MESSAGE extends UIMessage> {
659
918
  ...options,
660
919
  });
661
920
  }, shouldSend);
921
+ return;
662
922
  }
663
923
  }
924
+
925
+ // no await to avoid deadlocking
926
+ void this.settleQueue({ stopGeneration });
664
927
  });
665
928
 
666
929
  addToolOutput: ChatAddToolOutputFunction<UI_MESSAGE> = async ({
@@ -671,6 +934,7 @@ export abstract class AbstractChat<UI_MESSAGE extends UIMessage> {
671
934
  options,
672
935
  }) =>
673
936
  this.jobExecutor.run(async () => {
937
+ const stopGeneration = this.stopGeneration;
674
938
  const messages = this.state.messages;
675
939
 
676
940
  const updatePart = (
@@ -755,8 +1019,13 @@ export abstract class AbstractChat<UI_MESSAGE extends UIMessage> {
755
1019
  }),
756
1020
  shouldSend,
757
1021
  );
1022
+ return;
758
1023
  }
759
1024
  }
1025
+
1026
+ // the tool result can be what the queue was waiting for. no await to
1027
+ // avoid deadlocking:
1028
+ void this.settleQueue({ stopGeneration });
760
1029
  });
761
1030
 
762
1031
  /** @deprecated Use addToolOutput */
@@ -769,6 +1038,7 @@ export abstract class AbstractChat<UI_MESSAGE extends UIMessage> {
769
1038
  stop = async () => {
770
1039
  this.activeStopCount++;
771
1040
  this.stopGeneration++;
1041
+ this.deferredApprovalSend = undefined;
772
1042
 
773
1043
  try {
774
1044
  const activeResumeRequest = this.activeResumeRequest;
@@ -788,6 +1058,10 @@ export abstract class AbstractChat<UI_MESSAGE extends UIMessage> {
788
1058
  // Stream cancellation can complete while a processing job is still
789
1059
  // blocked in onToolCall. Drain that job and any message update it queued.
790
1060
  await this.jobExecutor.waitForIdle();
1061
+
1062
+ // a stop pauses the queue even when no response was running, e.g. while
1063
+ // the assistant waits for a tool approval:
1064
+ this.isQueuePaused = true;
791
1065
  } finally {
792
1066
  this.activeStopCount--;
793
1067
  }
@@ -815,9 +1089,19 @@ export abstract class AbstractChat<UI_MESSAGE extends UIMessage> {
815
1089
  return false;
816
1090
  }
817
1091
 
818
- const result = await this.sendAutomaticallyWhen({
819
- messages: this.state.messages,
820
- });
1092
+ const stopGeneration = this.stopGeneration;
1093
+ this.pendingAutomaticDecisions.push(stopGeneration);
1094
+ let result: boolean;
1095
+ try {
1096
+ result = await this.sendAutomaticallyWhen({
1097
+ messages: this.state.messages,
1098
+ });
1099
+ } finally {
1100
+ this.pendingAutomaticDecisions.splice(
1101
+ this.pendingAutomaticDecisions.indexOf(stopGeneration),
1102
+ 1,
1103
+ );
1104
+ }
821
1105
 
822
1106
  return (
823
1107
  result &&
@@ -829,12 +1113,12 @@ export abstract class AbstractChat<UI_MESSAGE extends UIMessage> {
829
1113
  private async runAutomaticRequest(
830
1114
  request: () => Promise<void>,
831
1115
  shouldSend?: boolean,
832
- ): Promise<void> {
1116
+ ): Promise<boolean> {
833
1117
  const stopGeneration = this.stopGeneration;
834
1118
  const startedWhileStopping = this.activeStopCount > 0;
835
1119
 
836
1120
  if (!(shouldSend ?? (await this.shouldSendAutomatically()))) {
837
- return;
1121
+ return false;
838
1122
  }
839
1123
 
840
1124
  // A stop invalidates automatic requests that were pending when it started,
@@ -844,10 +1128,11 @@ export abstract class AbstractChat<UI_MESSAGE extends UIMessage> {
844
1128
  stopGeneration !== this.stopGeneration ||
845
1129
  this.activeStopCount > 0
846
1130
  ) {
847
- return;
1131
+ return false;
848
1132
  }
849
1133
 
850
1134
  await request();
1135
+ return true;
851
1136
  }
852
1137
 
853
1138
  private async makeRequestForToolApproval({
@@ -858,6 +1143,8 @@ export abstract class AbstractChat<UI_MESSAGE extends UIMessage> {
858
1143
  messageId?: string;
859
1144
  messageIndex: number;
860
1145
  } & ChatRequestOptions) {
1146
+ this.deferredApprovalSend = undefined;
1147
+
861
1148
  const consumesPendingApproval =
862
1149
  messageId != null && messageId === this.pendingApprovalMessageId;
863
1150
  if (consumesPendingApproval) {
@@ -1216,6 +1503,17 @@ export abstract class AbstractChat<UI_MESSAGE extends UIMessage> {
1216
1503
  });
1217
1504
  }
1218
1505
  } finally {
1506
+ // a response that did not finish (stopped, failed or interrupted)
1507
+ // pauses the queue until the user sends again. a response that finishes
1508
+ // on its own (e.g. an automatic resume) never clears the pause:
1509
+ if (
1510
+ isAbort ||
1511
+ isError ||
1512
+ activeResponse?.state.finishReason === 'interrupted'
1513
+ ) {
1514
+ this.isQueuePaused = true;
1515
+ }
1516
+
1219
1517
  if (this.activeResponse === activeResponse) {
1220
1518
  this.activeResponse = undefined;
1221
1519
  }
@@ -1230,7 +1528,8 @@ export abstract class AbstractChat<UI_MESSAGE extends UIMessage> {
1230
1528
  !isError &&
1231
1529
  activeResponse?.state.finishReason !== 'interrupted'
1232
1530
  ) {
1233
- await this.runAutomaticRequest(() =>
1531
+ const stopGeneration = this.stopGeneration;
1532
+ const sentAutomatically = await this.runAutomaticRequest(() =>
1234
1533
  this.makeRequest({
1235
1534
  trigger: 'submit-message',
1236
1535
  messageId: this.lastMessage?.id,
@@ -1239,6 +1538,13 @@ export abstract class AbstractChat<UI_MESSAGE extends UIMessage> {
1239
1538
  body,
1240
1539
  }),
1241
1540
  );
1541
+
1542
+ // the automatic request settles the queue when it finishes. a stop while
1543
+ // sendAutomaticallyWhen was pending cancels the send too, so a stopped or
1544
+ // replaced chat never sends queued messages on its own:
1545
+ if (!sentAutomatically) {
1546
+ await this.settleQueue({ stopGeneration });
1547
+ }
1242
1548
  }
1243
1549
  }
1244
1550
  }