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.js CHANGED
@@ -1335,7 +1335,7 @@ function detectMediaType({
1335
1335
  var import_provider_utils3 = require("@ai-sdk/provider-utils");
1336
1336
 
1337
1337
  // src/version.ts
1338
- var VERSION = true ? "6.0.302" : "0.0.0-test";
1338
+ var VERSION = true ? "6.0.304" : "0.0.0-test";
1339
1339
 
1340
1340
  // src/util/download/download.ts
1341
1341
  var download = async ({
@@ -1535,32 +1535,6 @@ async function convertToLanguageModelPrompt({
1535
1535
  download2 != null ? download2 : createDefaultDownloadFunction(void 0, abortSignal),
1536
1536
  supportedUrls
1537
1537
  );
1538
- const approvalIdToToolCallId = /* @__PURE__ */ new Map();
1539
- for (const message of prompt.messages) {
1540
- if (message.role === "assistant" && Array.isArray(message.content)) {
1541
- for (const part of message.content) {
1542
- if (part.type === "tool-approval-request" && "approvalId" in part && "toolCallId" in part) {
1543
- approvalIdToToolCallId.set(
1544
- part.approvalId,
1545
- part.toolCallId
1546
- );
1547
- }
1548
- }
1549
- }
1550
- }
1551
- const approvedToolCallIds = /* @__PURE__ */ new Set();
1552
- for (const message of prompt.messages) {
1553
- if (message.role === "tool") {
1554
- for (const part of message.content) {
1555
- if (part.type === "tool-approval-response") {
1556
- const toolCallId = approvalIdToToolCallId.get(part.approvalId);
1557
- if (toolCallId) {
1558
- approvedToolCallIds.add(toolCallId);
1559
- }
1560
- }
1561
- }
1562
- }
1563
- }
1564
1538
  const messages = [
1565
1539
  ...prompt.system != null ? typeof prompt.system === "string" ? [{ role: "system", content: prompt.system }] : asArray(prompt.system).map((message) => ({
1566
1540
  role: "system",
@@ -1613,9 +1587,6 @@ async function convertToLanguageModelPrompt({
1613
1587
  }
1614
1588
  case "user":
1615
1589
  case "system":
1616
- for (const id of approvedToolCallIds) {
1617
- toolCallIds.delete(id);
1618
- }
1619
1590
  if (toolCallIds.size > 0) {
1620
1591
  throw new MissingToolResultsError({
1621
1592
  toolCallIds: Array.from(toolCallIds)
@@ -1624,9 +1595,6 @@ async function convertToLanguageModelPrompt({
1624
1595
  break;
1625
1596
  }
1626
1597
  }
1627
- for (const id of approvedToolCallIds) {
1628
- toolCallIds.delete(id);
1629
- }
1630
1598
  if (toolCallIds.size > 0) {
1631
1599
  throw new MissingToolResultsError({ toolCallIds: Array.from(toolCallIds) });
1632
1600
  }
@@ -6124,13 +6092,16 @@ function processUIMessageStream({
6124
6092
  runUpdateMessageJob,
6125
6093
  onError,
6126
6094
  onToolCall,
6127
- onData
6095
+ onData,
6096
+ resetStateOnMessageIdChange = false,
6097
+ resetStateOnFirstMessageStart = false
6128
6098
  }) {
6099
+ let isFirstMessageStart = true;
6129
6100
  return stream.pipeThrough(
6130
6101
  new TransformStream({
6131
6102
  async transform(chunk, controller) {
6132
6103
  await runUpdateMessageJob(async ({ state, write }) => {
6133
- var _a23, _b, _c, _d, _e, _f, _g, _h;
6104
+ var _a23, _b, _c, _d, _e, _f, _g, _h, _i;
6134
6105
  function getCurrentStepParts() {
6135
6106
  const parts = state.message.parts;
6136
6107
  let currentStepStartIndex = parts.length - 1;
@@ -6637,11 +6608,23 @@ function processUIMessageStream({
6637
6608
  break;
6638
6609
  }
6639
6610
  case "start": {
6611
+ const shouldReset = resetStateOnFirstMessageStart && isFirstMessageStart || resetStateOnMessageIdChange && chunk.messageId != null && chunk.messageId !== state.message.id;
6612
+ isFirstMessageStart = false;
6613
+ if (shouldReset) {
6614
+ Object.assign(
6615
+ state,
6616
+ createStreamingUIMessageState({
6617
+ lastMessage: void 0,
6618
+ messageId: (_i = chunk.messageId) != null ? _i : state.message.id
6619
+ }),
6620
+ { finishReason: void 0 }
6621
+ );
6622
+ }
6640
6623
  if (chunk.messageId != null) {
6641
6624
  state.message.id = chunk.messageId;
6642
6625
  }
6643
6626
  await updateMessageMetadata(chunk.messageMetadata);
6644
- if (chunk.messageId != null || chunk.messageMetadata != null) {
6627
+ if (shouldReset || chunk.messageId != null || chunk.messageMetadata != null) {
6645
6628
  write({ updateStatus: false });
6646
6629
  }
6647
6630
  break;
@@ -9691,6 +9674,7 @@ function readUIMessageStream({
9691
9674
  consumeStream({
9692
9675
  stream: processUIMessageStream({
9693
9676
  stream,
9677
+ resetStateOnMessageIdChange: true,
9694
9678
  runUpdateMessageJob(job) {
9695
9679
  return job({
9696
9680
  state,
@@ -11997,17 +11981,24 @@ var SerialJobExecutor = class {
11997
11981
  constructor() {
11998
11982
  this.queue = [];
11999
11983
  this.isProcessing = false;
11984
+ this.idleWaiters = [];
12000
11985
  }
12001
11986
  async processQueue() {
12002
11987
  if (this.isProcessing) {
12003
11988
  return;
12004
11989
  }
12005
11990
  this.isProcessing = true;
12006
- while (this.queue.length > 0) {
12007
- await this.queue[0]();
12008
- this.queue.shift();
11991
+ try {
11992
+ while (this.queue.length > 0) {
11993
+ await this.queue[0]();
11994
+ this.queue.shift();
11995
+ }
11996
+ } finally {
11997
+ this.isProcessing = false;
11998
+ for (const resolve3 of this.idleWaiters.splice(0)) {
11999
+ resolve3();
12000
+ }
12009
12001
  }
12010
- this.isProcessing = false;
12011
12002
  }
12012
12003
  async run(job) {
12013
12004
  return new Promise((resolve3, reject) => {
@@ -12022,6 +12013,14 @@ var SerialJobExecutor = class {
12022
12013
  void this.processQueue();
12023
12014
  });
12024
12015
  }
12016
+ async waitForIdle() {
12017
+ if (!this.isProcessing && this.queue.length === 0) {
12018
+ return;
12019
+ }
12020
+ await new Promise((resolve3) => {
12021
+ this.idleWaiters.push(resolve3);
12022
+ });
12023
+ }
12025
12024
  };
12026
12025
 
12027
12026
  // src/util/simulate-readable-stream.ts
@@ -14618,8 +14617,12 @@ var HttpChatTransport = class {
14618
14617
 
14619
14618
  // src/ui/default-chat-transport.ts
14620
14619
  var DefaultChatTransport = class extends HttpChatTransport {
14621
- constructor(options = {}) {
14620
+ constructor({
14621
+ resumeStreamIsReplay = true,
14622
+ ...options
14623
+ } = {}) {
14622
14624
  super(options);
14625
+ this.resumeStreamIsReplay = resumeStreamIsReplay;
14623
14626
  }
14624
14627
  processResponseStream(stream) {
14625
14628
  return (0, import_provider_utils42.parseJsonEventStream)({
@@ -14657,6 +14660,8 @@ var AbstractChat = class {
14657
14660
  this.activeResumeRequest = void 0;
14658
14661
  this.resumableStreamState = void 0;
14659
14662
  this.jobExecutor = new SerialJobExecutor();
14663
+ this.activeStopCount = 0;
14664
+ this.stopGeneration = 0;
14660
14665
  /**
14661
14666
  * Appends or replaces a user message to the chat list. This triggers the API call to fetch
14662
14667
  * the assistant's response.
@@ -14762,6 +14767,27 @@ var AbstractChat = class {
14762
14767
  this.resumeStream = async (options = {}) => {
14763
14768
  await this.makeRequest({ trigger: "resume-stream", ...options });
14764
14769
  };
14770
+ /**
14771
+ * Resume the stream if the latest response ended with a resumable network
14772
+ * disconnect. If a response is still active, wait for it to settle first so
14773
+ * disconnects reported shortly after the caller's trigger are handled.
14774
+ *
14775
+ * @internal
14776
+ */
14777
+ this["~resumeStreamIfDisconnected"] = async ({
14778
+ shouldResume = () => true
14779
+ } = {}) => {
14780
+ const activeResponse = this.activeResponse;
14781
+ if (this.resumableStreamState == null && activeResponse != null) {
14782
+ await activeResponse.completionPromise;
14783
+ if (this.resumableStreamState !== activeResponse.state) {
14784
+ return;
14785
+ }
14786
+ }
14787
+ if (this.resumableStreamState != null && shouldResume()) {
14788
+ await this.resumeStream();
14789
+ }
14790
+ };
14765
14791
  /**
14766
14792
  * Clear the error state and set the status to ready if the chat is in an error state.
14767
14793
  */
@@ -14800,17 +14826,18 @@ var AbstractChat = class {
14800
14826
  this.activeResponse.state.message.parts = this.activeResponse.state.message.parts.map(updatePart);
14801
14827
  }
14802
14828
  if (this.status !== "streaming" && this.status !== "submitted" && this.sendAutomaticallyWhen) {
14803
- this.shouldSendAutomatically().then((shouldSend) => {
14804
- var _a23;
14805
- if (shouldSend) {
14829
+ const shouldSend = await this.shouldSendAutomatically();
14830
+ if (shouldSend) {
14831
+ void this.runAutomaticRequest(() => {
14832
+ var _a23;
14806
14833
  const messageId = messageIndex === -1 ? (_a23 = this.lastMessage) == null ? void 0 : _a23.id : messages[messageIndex].id;
14807
- this.makeRequestForToolApproval({
14834
+ return this.makeRequestForToolApproval({
14808
14835
  messageId,
14809
14836
  messageIndex,
14810
14837
  ...options
14811
14838
  });
14812
- }
14813
- });
14839
+ }, shouldSend);
14840
+ }
14814
14841
  }
14815
14842
  });
14816
14843
  this.addToolOutput = async ({
@@ -14821,37 +14848,58 @@ var AbstractChat = class {
14821
14848
  options
14822
14849
  }) => this.jobExecutor.run(async () => {
14823
14850
  const messages = this.state.messages;
14824
- const lastMessage = messages[messages.length - 1];
14825
14851
  const updatePart = (part) => isToolUIPart(part) && part.toolCallId === toolCallId ? { ...part, state, output, errorText } : part;
14826
- this.state.replaceMessage(messages.length - 1, {
14827
- ...lastMessage,
14828
- parts: lastMessage.parts.map(updatePart)
14829
- });
14852
+ const messageIndex = messages.findIndex(
14853
+ (message) => message.parts.some(
14854
+ (part) => isToolUIPart(part) && part.toolCallId === toolCallId
14855
+ )
14856
+ );
14857
+ if (messageIndex !== -1) {
14858
+ const message = messages[messageIndex];
14859
+ this.state.replaceMessage(messageIndex, {
14860
+ ...message,
14861
+ parts: message.parts.map(updatePart)
14862
+ });
14863
+ }
14830
14864
  if (this.activeResponse) {
14831
14865
  this.activeResponse.state.message.parts = this.activeResponse.state.message.parts.map(updatePart);
14832
14866
  }
14833
- if (this.status !== "streaming" && this.status !== "submitted" && this.sendAutomaticallyWhen) {
14834
- this.shouldSendAutomatically().then((shouldSend) => {
14835
- var _a23;
14836
- if (shouldSend) {
14837
- this.makeRequest({
14867
+ if (messageIndex !== -1 && this.status !== "streaming" && this.status !== "submitted" && this.sendAutomaticallyWhen) {
14868
+ const shouldSend = await this.shouldSendAutomatically();
14869
+ if (shouldSend) {
14870
+ void this.runAutomaticRequest(
14871
+ () => this.makeRequest({
14838
14872
  trigger: "submit-message",
14839
- messageId: (_a23 = this.lastMessage) == null ? void 0 : _a23.id,
14873
+ messageId: messages[messageIndex].id,
14840
14874
  ...options
14841
- });
14842
- }
14843
- });
14875
+ }),
14876
+ shouldSend
14877
+ );
14878
+ }
14844
14879
  }
14845
14880
  });
14846
14881
  /** @deprecated Use addToolOutput */
14847
14882
  this.addToolResult = this.addToolOutput;
14848
14883
  /**
14849
- * Abort the current request immediately, keep the generated tokens if any.
14884
+ * Abort the current request, keep the generated tokens if any, and wait for
14885
+ * the request pipeline to finish.
14850
14886
  */
14851
14887
  this.stop = async () => {
14852
- var _a23, _b;
14853
- (_a23 = this.activeResumeRequest) == null ? void 0 : _a23.abortController.abort();
14854
- (_b = this.activeResponse) == null ? void 0 : _b.abortController.abort();
14888
+ this.activeStopCount++;
14889
+ this.stopGeneration++;
14890
+ try {
14891
+ const activeResumeRequest = this.activeResumeRequest;
14892
+ const activeResponse = this.activeResponse;
14893
+ activeResumeRequest == null ? void 0 : activeResumeRequest.abortController.abort();
14894
+ activeResponse == null ? void 0 : activeResponse.abortController.abort();
14895
+ await Promise.all([
14896
+ activeResumeRequest == null ? void 0 : activeResumeRequest.completionPromise,
14897
+ activeResponse == null ? void 0 : activeResponse.completionPromise
14898
+ ]);
14899
+ await this.jobExecutor.waitForIdle();
14900
+ } finally {
14901
+ this.activeStopCount--;
14902
+ }
14855
14903
  };
14856
14904
  this.id = id;
14857
14905
  this.transport = transport;
@@ -14912,6 +14960,17 @@ var AbstractChat = class {
14912
14960
  }
14913
14961
  return result;
14914
14962
  }
14963
+ async runAutomaticRequest(request, shouldSend) {
14964
+ const stopGeneration = this.stopGeneration;
14965
+ const startedWhileStopping = this.activeStopCount > 0;
14966
+ if (!(shouldSend != null ? shouldSend : await this.shouldSendAutomatically())) {
14967
+ return;
14968
+ }
14969
+ if (startedWhileStopping || stopGeneration !== this.stopGeneration || this.activeStopCount > 0) {
14970
+ return;
14971
+ }
14972
+ await request();
14973
+ }
14915
14974
  async makeRequestForToolApproval({
14916
14975
  messageId,
14917
14976
  messageIndex,
@@ -14931,19 +14990,31 @@ var AbstractChat = class {
14931
14990
  this.pendingApprovalMessageId = (_b = (_a23 = this.state.messages[messageIndex]) == null ? void 0 : _a23.id) != null ? _b : messageId;
14932
14991
  }
14933
14992
  }
14934
- async makeRequest({
14993
+ async makeRequest(options) {
14994
+ const completion = createResolvablePromise();
14995
+ try {
14996
+ await this.makeRequestImpl({
14997
+ ...options,
14998
+ completionPromise: completion.promise
14999
+ });
15000
+ } finally {
15001
+ completion.resolve();
15002
+ }
15003
+ }
15004
+ async makeRequestImpl({
14935
15005
  trigger,
14936
15006
  metadata,
14937
15007
  headers,
14938
15008
  body,
14939
- messageId
15009
+ messageId,
15010
+ completionPromise
14940
15011
  }) {
14941
- var _a23, _b, _c;
15012
+ var _a23, _b;
14942
15013
  if (trigger !== "resume-stream") {
14943
15014
  this.resumableStreamState = void 0;
14944
15015
  }
14945
15016
  const abortController = new AbortController();
14946
- const activeResumeRequest = trigger === "resume-stream" ? { abortController } : void 0;
15017
+ const activeResumeRequest = trigger === "resume-stream" ? { abortController, completionPromise } : void 0;
14947
15018
  if (activeResumeRequest) {
14948
15019
  (_a23 = this.activeResumeRequest) == null ? void 0 : _a23.abortController.abort();
14949
15020
  this.activeResumeRequest = activeResumeRequest;
@@ -15005,6 +15076,7 @@ var AbstractChat = class {
15005
15076
  const lastMessage = this.lastMessage;
15006
15077
  const responseMessageIndex = trigger === "submit-message" && messageId != null ? this.state.messages.findIndex((message) => message.id === messageId) : this.state.messages.length - 1;
15007
15078
  const responseMessage = responseMessageIndex === -1 ? lastMessage : this.state.messages[responseMessageIndex];
15079
+ const originalResponseMessageId = responseMessage == null ? void 0 : responseMessage.id;
15008
15080
  const resumableResponseMessage = trigger === "resume-stream" && (responseMessage == null ? void 0 : responseMessage.role) === "assistant" && responseMessage.parts.some(
15009
15081
  (part) => isToolUIPart(part) && part.state === "input-streaming"
15010
15082
  ) ? this.state.snapshot(responseMessage) : void 0;
@@ -15019,7 +15091,8 @@ var AbstractChat = class {
15019
15091
  lastMessage: trigger === "resume-stream" ? resumableResponseMessage : trigger === "regenerate-message" ? void 0 : this.state.snapshot(responseMessage),
15020
15092
  messageId: this.generateId()
15021
15093
  }),
15022
- abortController
15094
+ abortController,
15095
+ completionPromise
15023
15096
  };
15024
15097
  activeResponse = response;
15025
15098
  response.abortController.signal.addEventListener("abort", () => {
@@ -15050,23 +15123,32 @@ var AbstractChat = class {
15050
15123
  return job({
15051
15124
  state: response.state,
15052
15125
  write: ({ updateStatus = true } = {}) => {
15053
- var _a24;
15054
15126
  if (response.abortController.signal.aborted) {
15055
15127
  return;
15056
15128
  }
15057
15129
  if (updateStatus) {
15058
15130
  this.setStatus({ status: "streaming" });
15059
15131
  }
15060
- if (usesEarlierAssistantMessage) {
15132
+ const existingMessageIndex = this.state.messages.findLastIndex(
15133
+ (message) => message.id === response.state.message.id
15134
+ );
15135
+ if (existingMessageIndex !== -1) {
15061
15136
  this.state.replaceMessage(
15062
- responseMessageIndex,
15137
+ existingMessageIndex,
15063
15138
  response.state.message
15064
15139
  );
15065
- } else if (response.state.message.id === ((_a24 = this.lastMessage) == null ? void 0 : _a24.id)) {
15066
- this.state.replaceMessage(
15067
- this.state.messages.length - 1,
15068
- response.state.message
15140
+ } else if (usesEarlierAssistantMessage) {
15141
+ const originalMessageIndex = this.state.messages.findLastIndex(
15142
+ (message) => message.id === originalResponseMessageId
15069
15143
  );
15144
+ if (originalMessageIndex !== -1) {
15145
+ this.state.replaceMessage(
15146
+ originalMessageIndex,
15147
+ response.state.message
15148
+ );
15149
+ } else {
15150
+ this.state.pushMessage(response.state.message);
15151
+ }
15070
15152
  } else {
15071
15153
  this.state.pushMessage(response.state.message);
15072
15154
  }
@@ -15077,6 +15159,8 @@ var AbstractChat = class {
15077
15159
  await consumeStream({
15078
15160
  stream: processUIMessageStream({
15079
15161
  stream,
15162
+ resetStateOnMessageIdChange: trigger === "resume-stream",
15163
+ resetStateOnFirstMessageStart: trigger === "resume-stream" && this.transport.resumeStreamIsReplay,
15080
15164
  onToolCall: this.onToolCall,
15081
15165
  onData: this.onData,
15082
15166
  messageMetadataSchema: this.messageMetadataSchema,
@@ -15152,14 +15236,19 @@ var AbstractChat = class {
15152
15236
  clearActiveResumeRequest();
15153
15237
  }
15154
15238
  }
15155
- if (!isError && await this.shouldSendAutomatically()) {
15156
- await this.makeRequest({
15157
- trigger: "submit-message",
15158
- messageId: (_c = this.lastMessage) == null ? void 0 : _c.id,
15159
- metadata,
15160
- headers,
15161
- body
15162
- });
15239
+ if (!isAbort && !isError) {
15240
+ await this.runAutomaticRequest(
15241
+ () => {
15242
+ var _a24;
15243
+ return this.makeRequest({
15244
+ trigger: "submit-message",
15245
+ messageId: (_a24 = this.lastMessage) == null ? void 0 : _a24.id,
15246
+ metadata,
15247
+ headers,
15248
+ body
15249
+ });
15250
+ }
15251
+ );
15163
15252
  }
15164
15253
  }
15165
15254
  };