ai 6.0.302 → 6.0.304

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.
package/dist/index.mjs CHANGED
@@ -1225,7 +1225,7 @@ import {
1225
1225
  } from "@ai-sdk/provider-utils";
1226
1226
 
1227
1227
  // src/version.ts
1228
- var VERSION = true ? "6.0.302" : "0.0.0-test";
1228
+ var VERSION = true ? "6.0.304" : "0.0.0-test";
1229
1229
 
1230
1230
  // src/util/download/download.ts
1231
1231
  var download = async ({
@@ -1428,32 +1428,6 @@ async function convertToLanguageModelPrompt({
1428
1428
  download2 != null ? download2 : createDefaultDownloadFunction(void 0, abortSignal),
1429
1429
  supportedUrls
1430
1430
  );
1431
- const approvalIdToToolCallId = /* @__PURE__ */ new Map();
1432
- for (const message of prompt.messages) {
1433
- if (message.role === "assistant" && Array.isArray(message.content)) {
1434
- for (const part of message.content) {
1435
- if (part.type === "tool-approval-request" && "approvalId" in part && "toolCallId" in part) {
1436
- approvalIdToToolCallId.set(
1437
- part.approvalId,
1438
- part.toolCallId
1439
- );
1440
- }
1441
- }
1442
- }
1443
- }
1444
- const approvedToolCallIds = /* @__PURE__ */ new Set();
1445
- for (const message of prompt.messages) {
1446
- if (message.role === "tool") {
1447
- for (const part of message.content) {
1448
- if (part.type === "tool-approval-response") {
1449
- const toolCallId = approvalIdToToolCallId.get(part.approvalId);
1450
- if (toolCallId) {
1451
- approvedToolCallIds.add(toolCallId);
1452
- }
1453
- }
1454
- }
1455
- }
1456
- }
1457
1431
  const messages = [
1458
1432
  ...prompt.system != null ? typeof prompt.system === "string" ? [{ role: "system", content: prompt.system }] : asArray(prompt.system).map((message) => ({
1459
1433
  role: "system",
@@ -1506,9 +1480,6 @@ async function convertToLanguageModelPrompt({
1506
1480
  }
1507
1481
  case "user":
1508
1482
  case "system":
1509
- for (const id of approvedToolCallIds) {
1510
- toolCallIds.delete(id);
1511
- }
1512
1483
  if (toolCallIds.size > 0) {
1513
1484
  throw new MissingToolResultsError({
1514
1485
  toolCallIds: Array.from(toolCallIds)
@@ -1517,9 +1488,6 @@ async function convertToLanguageModelPrompt({
1517
1488
  break;
1518
1489
  }
1519
1490
  }
1520
- for (const id of approvedToolCallIds) {
1521
- toolCallIds.delete(id);
1522
- }
1523
1491
  if (toolCallIds.size > 0) {
1524
1492
  throw new MissingToolResultsError({ toolCallIds: Array.from(toolCallIds) });
1525
1493
  }
@@ -6051,13 +6019,16 @@ function processUIMessageStream({
6051
6019
  runUpdateMessageJob,
6052
6020
  onError,
6053
6021
  onToolCall,
6054
- onData
6022
+ onData,
6023
+ resetStateOnMessageIdChange = false,
6024
+ resetStateOnFirstMessageStart = false
6055
6025
  }) {
6026
+ let isFirstMessageStart = true;
6056
6027
  return stream.pipeThrough(
6057
6028
  new TransformStream({
6058
6029
  async transform(chunk, controller) {
6059
6030
  await runUpdateMessageJob(async ({ state, write }) => {
6060
- var _a23, _b, _c, _d, _e, _f, _g, _h;
6031
+ var _a23, _b, _c, _d, _e, _f, _g, _h, _i;
6061
6032
  function getCurrentStepParts() {
6062
6033
  const parts = state.message.parts;
6063
6034
  let currentStepStartIndex = parts.length - 1;
@@ -6564,11 +6535,23 @@ function processUIMessageStream({
6564
6535
  break;
6565
6536
  }
6566
6537
  case "start": {
6538
+ const shouldReset = resetStateOnFirstMessageStart && isFirstMessageStart || resetStateOnMessageIdChange && chunk.messageId != null && chunk.messageId !== state.message.id;
6539
+ isFirstMessageStart = false;
6540
+ if (shouldReset) {
6541
+ Object.assign(
6542
+ state,
6543
+ createStreamingUIMessageState({
6544
+ lastMessage: void 0,
6545
+ messageId: (_i = chunk.messageId) != null ? _i : state.message.id
6546
+ }),
6547
+ { finishReason: void 0 }
6548
+ );
6549
+ }
6567
6550
  if (chunk.messageId != null) {
6568
6551
  state.message.id = chunk.messageId;
6569
6552
  }
6570
6553
  await updateMessageMetadata(chunk.messageMetadata);
6571
- if (chunk.messageId != null || chunk.messageMetadata != null) {
6554
+ if (shouldReset || chunk.messageId != null || chunk.messageMetadata != null) {
6572
6555
  write({ updateStatus: false });
6573
6556
  }
6574
6557
  break;
@@ -9622,6 +9605,7 @@ function readUIMessageStream({
9622
9605
  consumeStream({
9623
9606
  stream: processUIMessageStream({
9624
9607
  stream,
9608
+ resetStateOnMessageIdChange: true,
9625
9609
  runUpdateMessageJob(job) {
9626
9610
  return job({
9627
9611
  state,
@@ -11960,17 +11944,24 @@ var SerialJobExecutor = class {
11960
11944
  constructor() {
11961
11945
  this.queue = [];
11962
11946
  this.isProcessing = false;
11947
+ this.idleWaiters = [];
11963
11948
  }
11964
11949
  async processQueue() {
11965
11950
  if (this.isProcessing) {
11966
11951
  return;
11967
11952
  }
11968
11953
  this.isProcessing = true;
11969
- while (this.queue.length > 0) {
11970
- await this.queue[0]();
11971
- this.queue.shift();
11954
+ try {
11955
+ while (this.queue.length > 0) {
11956
+ await this.queue[0]();
11957
+ this.queue.shift();
11958
+ }
11959
+ } finally {
11960
+ this.isProcessing = false;
11961
+ for (const resolve3 of this.idleWaiters.splice(0)) {
11962
+ resolve3();
11963
+ }
11972
11964
  }
11973
- this.isProcessing = false;
11974
11965
  }
11975
11966
  async run(job) {
11976
11967
  return new Promise((resolve3, reject) => {
@@ -11985,6 +11976,14 @@ var SerialJobExecutor = class {
11985
11976
  void this.processQueue();
11986
11977
  });
11987
11978
  }
11979
+ async waitForIdle() {
11980
+ if (!this.isProcessing && this.queue.length === 0) {
11981
+ return;
11982
+ }
11983
+ await new Promise((resolve3) => {
11984
+ this.idleWaiters.push(resolve3);
11985
+ });
11986
+ }
11988
11987
  };
11989
11988
 
11990
11989
  // src/util/simulate-readable-stream.ts
@@ -14608,8 +14607,12 @@ var HttpChatTransport = class {
14608
14607
 
14609
14608
  // src/ui/default-chat-transport.ts
14610
14609
  var DefaultChatTransport = class extends HttpChatTransport {
14611
- constructor(options = {}) {
14610
+ constructor({
14611
+ resumeStreamIsReplay = true,
14612
+ ...options
14613
+ } = {}) {
14612
14614
  super(options);
14615
+ this.resumeStreamIsReplay = resumeStreamIsReplay;
14613
14616
  }
14614
14617
  processResponseStream(stream) {
14615
14618
  return parseJsonEventStream2({
@@ -14647,6 +14650,8 @@ var AbstractChat = class {
14647
14650
  this.activeResumeRequest = void 0;
14648
14651
  this.resumableStreamState = void 0;
14649
14652
  this.jobExecutor = new SerialJobExecutor();
14653
+ this.activeStopCount = 0;
14654
+ this.stopGeneration = 0;
14650
14655
  /**
14651
14656
  * Appends or replaces a user message to the chat list. This triggers the API call to fetch
14652
14657
  * the assistant's response.
@@ -14752,6 +14757,27 @@ var AbstractChat = class {
14752
14757
  this.resumeStream = async (options = {}) => {
14753
14758
  await this.makeRequest({ trigger: "resume-stream", ...options });
14754
14759
  };
14760
+ /**
14761
+ * Resume the stream if the latest response ended with a resumable network
14762
+ * disconnect. If a response is still active, wait for it to settle first so
14763
+ * disconnects reported shortly after the caller's trigger are handled.
14764
+ *
14765
+ * @internal
14766
+ */
14767
+ this["~resumeStreamIfDisconnected"] = async ({
14768
+ shouldResume = () => true
14769
+ } = {}) => {
14770
+ const activeResponse = this.activeResponse;
14771
+ if (this.resumableStreamState == null && activeResponse != null) {
14772
+ await activeResponse.completionPromise;
14773
+ if (this.resumableStreamState !== activeResponse.state) {
14774
+ return;
14775
+ }
14776
+ }
14777
+ if (this.resumableStreamState != null && shouldResume()) {
14778
+ await this.resumeStream();
14779
+ }
14780
+ };
14755
14781
  /**
14756
14782
  * Clear the error state and set the status to ready if the chat is in an error state.
14757
14783
  */
@@ -14790,17 +14816,18 @@ var AbstractChat = class {
14790
14816
  this.activeResponse.state.message.parts = this.activeResponse.state.message.parts.map(updatePart);
14791
14817
  }
14792
14818
  if (this.status !== "streaming" && this.status !== "submitted" && this.sendAutomaticallyWhen) {
14793
- this.shouldSendAutomatically().then((shouldSend) => {
14794
- var _a23;
14795
- if (shouldSend) {
14819
+ const shouldSend = await this.shouldSendAutomatically();
14820
+ if (shouldSend) {
14821
+ void this.runAutomaticRequest(() => {
14822
+ var _a23;
14796
14823
  const messageId = messageIndex === -1 ? (_a23 = this.lastMessage) == null ? void 0 : _a23.id : messages[messageIndex].id;
14797
- this.makeRequestForToolApproval({
14824
+ return this.makeRequestForToolApproval({
14798
14825
  messageId,
14799
14826
  messageIndex,
14800
14827
  ...options
14801
14828
  });
14802
- }
14803
- });
14829
+ }, shouldSend);
14830
+ }
14804
14831
  }
14805
14832
  });
14806
14833
  this.addToolOutput = async ({
@@ -14811,37 +14838,58 @@ var AbstractChat = class {
14811
14838
  options
14812
14839
  }) => this.jobExecutor.run(async () => {
14813
14840
  const messages = this.state.messages;
14814
- const lastMessage = messages[messages.length - 1];
14815
14841
  const updatePart = (part) => isToolUIPart(part) && part.toolCallId === toolCallId ? { ...part, state, output, errorText } : part;
14816
- this.state.replaceMessage(messages.length - 1, {
14817
- ...lastMessage,
14818
- parts: lastMessage.parts.map(updatePart)
14819
- });
14842
+ const messageIndex = messages.findIndex(
14843
+ (message) => message.parts.some(
14844
+ (part) => isToolUIPart(part) && part.toolCallId === toolCallId
14845
+ )
14846
+ );
14847
+ if (messageIndex !== -1) {
14848
+ const message = messages[messageIndex];
14849
+ this.state.replaceMessage(messageIndex, {
14850
+ ...message,
14851
+ parts: message.parts.map(updatePart)
14852
+ });
14853
+ }
14820
14854
  if (this.activeResponse) {
14821
14855
  this.activeResponse.state.message.parts = this.activeResponse.state.message.parts.map(updatePart);
14822
14856
  }
14823
- if (this.status !== "streaming" && this.status !== "submitted" && this.sendAutomaticallyWhen) {
14824
- this.shouldSendAutomatically().then((shouldSend) => {
14825
- var _a23;
14826
- if (shouldSend) {
14827
- this.makeRequest({
14857
+ if (messageIndex !== -1 && this.status !== "streaming" && this.status !== "submitted" && this.sendAutomaticallyWhen) {
14858
+ const shouldSend = await this.shouldSendAutomatically();
14859
+ if (shouldSend) {
14860
+ void this.runAutomaticRequest(
14861
+ () => this.makeRequest({
14828
14862
  trigger: "submit-message",
14829
- messageId: (_a23 = this.lastMessage) == null ? void 0 : _a23.id,
14863
+ messageId: messages[messageIndex].id,
14830
14864
  ...options
14831
- });
14832
- }
14833
- });
14865
+ }),
14866
+ shouldSend
14867
+ );
14868
+ }
14834
14869
  }
14835
14870
  });
14836
14871
  /** @deprecated Use addToolOutput */
14837
14872
  this.addToolResult = this.addToolOutput;
14838
14873
  /**
14839
- * Abort the current request immediately, keep the generated tokens if any.
14874
+ * Abort the current request, keep the generated tokens if any, and wait for
14875
+ * the request pipeline to finish.
14840
14876
  */
14841
14877
  this.stop = async () => {
14842
- var _a23, _b;
14843
- (_a23 = this.activeResumeRequest) == null ? void 0 : _a23.abortController.abort();
14844
- (_b = this.activeResponse) == null ? void 0 : _b.abortController.abort();
14878
+ this.activeStopCount++;
14879
+ this.stopGeneration++;
14880
+ try {
14881
+ const activeResumeRequest = this.activeResumeRequest;
14882
+ const activeResponse = this.activeResponse;
14883
+ activeResumeRequest == null ? void 0 : activeResumeRequest.abortController.abort();
14884
+ activeResponse == null ? void 0 : activeResponse.abortController.abort();
14885
+ await Promise.all([
14886
+ activeResumeRequest == null ? void 0 : activeResumeRequest.completionPromise,
14887
+ activeResponse == null ? void 0 : activeResponse.completionPromise
14888
+ ]);
14889
+ await this.jobExecutor.waitForIdle();
14890
+ } finally {
14891
+ this.activeStopCount--;
14892
+ }
14845
14893
  };
14846
14894
  this.id = id;
14847
14895
  this.transport = transport;
@@ -14902,6 +14950,17 @@ var AbstractChat = class {
14902
14950
  }
14903
14951
  return result;
14904
14952
  }
14953
+ async runAutomaticRequest(request, shouldSend) {
14954
+ const stopGeneration = this.stopGeneration;
14955
+ const startedWhileStopping = this.activeStopCount > 0;
14956
+ if (!(shouldSend != null ? shouldSend : await this.shouldSendAutomatically())) {
14957
+ return;
14958
+ }
14959
+ if (startedWhileStopping || stopGeneration !== this.stopGeneration || this.activeStopCount > 0) {
14960
+ return;
14961
+ }
14962
+ await request();
14963
+ }
14905
14964
  async makeRequestForToolApproval({
14906
14965
  messageId,
14907
14966
  messageIndex,
@@ -14921,19 +14980,31 @@ var AbstractChat = class {
14921
14980
  this.pendingApprovalMessageId = (_b = (_a23 = this.state.messages[messageIndex]) == null ? void 0 : _a23.id) != null ? _b : messageId;
14922
14981
  }
14923
14982
  }
14924
- async makeRequest({
14983
+ async makeRequest(options) {
14984
+ const completion = createResolvablePromise();
14985
+ try {
14986
+ await this.makeRequestImpl({
14987
+ ...options,
14988
+ completionPromise: completion.promise
14989
+ });
14990
+ } finally {
14991
+ completion.resolve();
14992
+ }
14993
+ }
14994
+ async makeRequestImpl({
14925
14995
  trigger,
14926
14996
  metadata,
14927
14997
  headers,
14928
14998
  body,
14929
- messageId
14999
+ messageId,
15000
+ completionPromise
14930
15001
  }) {
14931
- var _a23, _b, _c;
15002
+ var _a23, _b;
14932
15003
  if (trigger !== "resume-stream") {
14933
15004
  this.resumableStreamState = void 0;
14934
15005
  }
14935
15006
  const abortController = new AbortController();
14936
- const activeResumeRequest = trigger === "resume-stream" ? { abortController } : void 0;
15007
+ const activeResumeRequest = trigger === "resume-stream" ? { abortController, completionPromise } : void 0;
14937
15008
  if (activeResumeRequest) {
14938
15009
  (_a23 = this.activeResumeRequest) == null ? void 0 : _a23.abortController.abort();
14939
15010
  this.activeResumeRequest = activeResumeRequest;
@@ -14995,6 +15066,7 @@ var AbstractChat = class {
14995
15066
  const lastMessage = this.lastMessage;
14996
15067
  const responseMessageIndex = trigger === "submit-message" && messageId != null ? this.state.messages.findIndex((message) => message.id === messageId) : this.state.messages.length - 1;
14997
15068
  const responseMessage = responseMessageIndex === -1 ? lastMessage : this.state.messages[responseMessageIndex];
15069
+ const originalResponseMessageId = responseMessage == null ? void 0 : responseMessage.id;
14998
15070
  const resumableResponseMessage = trigger === "resume-stream" && (responseMessage == null ? void 0 : responseMessage.role) === "assistant" && responseMessage.parts.some(
14999
15071
  (part) => isToolUIPart(part) && part.state === "input-streaming"
15000
15072
  ) ? this.state.snapshot(responseMessage) : void 0;
@@ -15009,7 +15081,8 @@ var AbstractChat = class {
15009
15081
  lastMessage: trigger === "resume-stream" ? resumableResponseMessage : trigger === "regenerate-message" ? void 0 : this.state.snapshot(responseMessage),
15010
15082
  messageId: this.generateId()
15011
15083
  }),
15012
- abortController
15084
+ abortController,
15085
+ completionPromise
15013
15086
  };
15014
15087
  activeResponse = response;
15015
15088
  response.abortController.signal.addEventListener("abort", () => {
@@ -15040,23 +15113,32 @@ var AbstractChat = class {
15040
15113
  return job({
15041
15114
  state: response.state,
15042
15115
  write: ({ updateStatus = true } = {}) => {
15043
- var _a24;
15044
15116
  if (response.abortController.signal.aborted) {
15045
15117
  return;
15046
15118
  }
15047
15119
  if (updateStatus) {
15048
15120
  this.setStatus({ status: "streaming" });
15049
15121
  }
15050
- if (usesEarlierAssistantMessage) {
15122
+ const existingMessageIndex = this.state.messages.findLastIndex(
15123
+ (message) => message.id === response.state.message.id
15124
+ );
15125
+ if (existingMessageIndex !== -1) {
15051
15126
  this.state.replaceMessage(
15052
- responseMessageIndex,
15127
+ existingMessageIndex,
15053
15128
  response.state.message
15054
15129
  );
15055
- } else if (response.state.message.id === ((_a24 = this.lastMessage) == null ? void 0 : _a24.id)) {
15056
- this.state.replaceMessage(
15057
- this.state.messages.length - 1,
15058
- response.state.message
15130
+ } else if (usesEarlierAssistantMessage) {
15131
+ const originalMessageIndex = this.state.messages.findLastIndex(
15132
+ (message) => message.id === originalResponseMessageId
15059
15133
  );
15134
+ if (originalMessageIndex !== -1) {
15135
+ this.state.replaceMessage(
15136
+ originalMessageIndex,
15137
+ response.state.message
15138
+ );
15139
+ } else {
15140
+ this.state.pushMessage(response.state.message);
15141
+ }
15060
15142
  } else {
15061
15143
  this.state.pushMessage(response.state.message);
15062
15144
  }
@@ -15067,6 +15149,8 @@ var AbstractChat = class {
15067
15149
  await consumeStream({
15068
15150
  stream: processUIMessageStream({
15069
15151
  stream,
15152
+ resetStateOnMessageIdChange: trigger === "resume-stream",
15153
+ resetStateOnFirstMessageStart: trigger === "resume-stream" && this.transport.resumeStreamIsReplay,
15070
15154
  onToolCall: this.onToolCall,
15071
15155
  onData: this.onData,
15072
15156
  messageMetadataSchema: this.messageMetadataSchema,
@@ -15142,14 +15226,19 @@ var AbstractChat = class {
15142
15226
  clearActiveResumeRequest();
15143
15227
  }
15144
15228
  }
15145
- if (!isError && await this.shouldSendAutomatically()) {
15146
- await this.makeRequest({
15147
- trigger: "submit-message",
15148
- messageId: (_c = this.lastMessage) == null ? void 0 : _c.id,
15149
- metadata,
15150
- headers,
15151
- body
15152
- });
15229
+ if (!isAbort && !isError) {
15230
+ await this.runAutomaticRequest(
15231
+ () => {
15232
+ var _a24;
15233
+ return this.makeRequest({
15234
+ trigger: "submit-message",
15235
+ messageId: (_a24 = this.lastMessage) == null ? void 0 : _a24.id,
15236
+ metadata,
15237
+ headers,
15238
+ body
15239
+ });
15240
+ }
15241
+ );
15153
15242
  }
15154
15243
  }
15155
15244
  };