ai 7.0.55 → 7.0.57

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/CHANGELOG.md CHANGED
@@ -1,5 +1,34 @@
1
1
  # ai
2
2
 
3
+ ## 7.0.57
4
+
5
+ ### Patch Changes
6
+
7
+ - Updated dependencies [1937bef]
8
+ - @ai-sdk/provider-utils@5.0.24
9
+ - @ai-sdk/gateway@4.0.45
10
+
11
+ ## 7.0.56
12
+
13
+ ### Patch Changes
14
+
15
+ - 25c9120: Expose provider metadata on language-model-call end callbacks and telemetry spans.
16
+ - 89080c8: fix (ai/gateway): make retried `doStart` calls idempotent
17
+
18
+ `generateVideo` retries `doStart`, which creates a billable generation, so a
19
+ retry after a lost response could start a second one. It now mints one
20
+ idempotency token per logical start — outside the retry closure — and forwards it
21
+ as an `idempotency-key` header, so a provider that deduplicates (the Vercel AI
22
+ Gateway does) sees the same key on every attempt. `GatewayVideoModel` simply
23
+ forwards the caller's headers rather than inferring retry identity from an
24
+ options object, which would collide across unrelated calls.
25
+
26
+ - 79d6195: Stop pending and active resumed chat streams after cancellation, and prevent
27
+ overlapping resumptions from applying stale updates.
28
+ - Updated dependencies [89080c8]
29
+ - Updated dependencies [89080c8]
30
+ - @ai-sdk/gateway@4.0.44
31
+
3
32
  ## 7.0.55
4
33
 
5
34
  ### Patch Changes
package/dist/index.d.ts CHANGED
@@ -1544,6 +1544,8 @@ type LanguageModelCallEndEvent<TOOLS extends ToolSet = ToolSet> = ModelInfo & {
1544
1544
  readonly content: ReadonlyArray<ContentPart<TOOLS>>;
1545
1545
  /** The provider-returned response id for this model call. */
1546
1546
  readonly responseId: string;
1547
+ /** Optional provider-specific metadata for this model call. */
1548
+ readonly providerMetadata?: ProviderMetadata;
1547
1549
  /** Performance metrics for the model call. */
1548
1550
  readonly performance: {
1549
1551
  /** Time spent waiting for the language model response in milliseconds. */
@@ -5314,6 +5316,7 @@ interface ChatTransport<UI_MESSAGE extends UIMessage> {
5314
5316
  *
5315
5317
  * @param options - Configuration object containing:
5316
5318
  * @param options.chatId - Unique identifier for the chat session to reconnect to
5319
+ * @param options.abortSignal - Signal to abort the reconnection request if needed
5317
5320
  * @param options.headers - Additional HTTP headers to include in the reconnection request
5318
5321
  * @param options.body - Additional JSON properties to include in the request body
5319
5322
  * @param options.metadata - Custom metadata to attach to the request
@@ -5327,6 +5330,8 @@ interface ChatTransport<UI_MESSAGE extends UIMessage> {
5327
5330
  reconnectToStream: (options: {
5328
5331
  /** Unique identifier for the chat session to reconnect to */
5329
5332
  chatId: string;
5333
+ /** Signal to abort the reconnection request if needed */
5334
+ abortSignal?: AbortSignal;
5330
5335
  } & ChatRequestOptions) => Promise<ReadableStream<UIMessageChunk> | null>;
5331
5336
  }
5332
5337
 
@@ -5487,6 +5492,7 @@ declare abstract class AbstractChat<UI_MESSAGE extends UIMessage> {
5487
5492
  private onData?;
5488
5493
  private sendAutomaticallyWhen?;
5489
5494
  private activeResponse;
5495
+ private activeResumeRequest;
5490
5496
  private jobExecutor;
5491
5497
  constructor({ generateId, id, transport, messageMetadataSchema, dataPartSchemas, state, onError, onToolCall, onFinish, onData, sendAutomaticallyWhen, }: Omit<ChatInit<UI_MESSAGE>, 'messages'> & {
5492
5498
  state: ChatState<UI_MESSAGE>;
@@ -7431,9 +7437,10 @@ declare function generateObject<SCHEMA extends FlexibleSchema<unknown> = Flexibl
7431
7437
  * @param options.onError - Optional callback to handle errors that occur during consumption.
7432
7438
  * @returns A promise that resolves when the stream is fully consumed.
7433
7439
  */
7434
- declare function consumeStream({ stream, onError, }: {
7440
+ declare function consumeStream({ stream, onError, abortSignal, }: {
7435
7441
  stream: ReadableStream;
7436
7442
  onError?: (error: unknown) => void;
7443
+ abortSignal?: AbortSignal;
7437
7444
  }): Promise<void>;
7438
7445
 
7439
7446
  /**
package/dist/index.js CHANGED
@@ -11,7 +11,7 @@ import {
11
11
  createIdGenerator as createIdGenerator9,
12
12
  dynamicTool,
13
13
  experimental_toolCaller,
14
- generateId,
14
+ generateId as generateId2,
15
15
  jsonSchema,
16
16
  parseJsonEventStream as parseJsonEventStream3,
17
17
  tool,
@@ -1143,7 +1143,7 @@ import {
1143
1143
  } from "@ai-sdk/provider-utils";
1144
1144
 
1145
1145
  // src/version.ts
1146
- var VERSION = true ? "7.0.55" : "0.0.0-test";
1146
+ var VERSION = true ? "7.0.57" : "0.0.0-test";
1147
1147
 
1148
1148
  // src/util/download/download.ts
1149
1149
  var download = async ({
@@ -5227,7 +5227,7 @@ async function generateText({
5227
5227
  experimental_include,
5228
5228
  include = experimental_include,
5229
5229
  _internal: {
5230
- generateId: generateId2 = originalGenerateId,
5230
+ generateId: generateId3 = originalGenerateId,
5231
5231
  generateCallId = originalGenerateCallId,
5232
5232
  now: now2 = now
5233
5233
  } = {},
@@ -5612,7 +5612,7 @@ async function generateText({
5612
5612
  }
5613
5613
  );
5614
5614
  const responseData = {
5615
- id: (_b3 = (_a26 = result.response) == null ? void 0 : _a26.id) != null ? _b3 : generateId2(),
5615
+ id: (_b3 = (_a26 = result.response) == null ? void 0 : _a26.id) != null ? _b3 : generateId3(),
5616
5616
  timestamp: (_d3 = (_c3 = result.response) == null ? void 0 : _c3.timestamp) != null ? _d3 : /* @__PURE__ */ new Date(),
5617
5617
  modelId: (_f2 = (_e2 = result.response) == null ? void 0 : _e2.modelId) != null ? _f2 : stepModel.modelId,
5618
5618
  headers: (_g2 = result.response) == null ? void 0 : _g2.headers,
@@ -5658,6 +5658,9 @@ async function generateText({
5658
5658
  usage: stepUsage,
5659
5659
  content: modelCallContent,
5660
5660
  responseId: currentModelResponse.response.id,
5661
+ ...currentModelResponse.providerMetadata != null ? {
5662
+ providerMetadata: currentModelResponse.providerMetadata
5663
+ } : {},
5661
5664
  performance: {
5662
5665
  responseTimeMs,
5663
5666
  effectiveOutputTokensPerSecond: calculateTokensPerSecond({
@@ -5717,7 +5720,7 @@ async function generateText({
5717
5720
  if (toolApprovalStatus.type === "not-applicable") {
5718
5721
  continue;
5719
5722
  }
5720
- const approvalId = generateId2();
5723
+ const approvalId = generateId3();
5721
5724
  const signature = await maybeSignApproval({
5722
5725
  secret: experimental_toolApprovalSecret,
5723
5726
  approvalId,
@@ -7886,9 +7889,19 @@ function asAsyncIterableStream(stream) {
7886
7889
  // src/util/consume-stream.ts
7887
7890
  async function consumeStream({
7888
7891
  stream,
7889
- onError
7892
+ onError,
7893
+ abortSignal
7890
7894
  }) {
7891
7895
  const reader = stream.getReader();
7896
+ const cancelOnAbort = () => {
7897
+ reader.cancel().catch(() => {
7898
+ });
7899
+ };
7900
+ if (abortSignal == null ? void 0 : abortSignal.aborted) {
7901
+ cancelOnAbort();
7902
+ } else {
7903
+ abortSignal == null ? void 0 : abortSignal.addEventListener("abort", cancelOnAbort, { once: true });
7904
+ }
7892
7905
  try {
7893
7906
  while (true) {
7894
7907
  const { done } = await reader.read();
@@ -7898,6 +7911,7 @@ async function consumeStream({
7898
7911
  } catch (error) {
7899
7912
  onError == null ? void 0 : onError(error);
7900
7913
  } finally {
7914
+ abortSignal == null ? void 0 : abortSignal.removeEventListener("abort", cancelOnAbort);
7901
7915
  reader.releaseLock();
7902
7916
  }
7903
7917
  }
@@ -8021,7 +8035,7 @@ function executeToolsFromStream({
8021
8035
  toolApproval,
8022
8036
  runtimeContext,
8023
8037
  toolApprovalSecret,
8024
- generateId: generateId2,
8038
+ generateId: generateId3,
8025
8039
  onToolExecutionStart,
8026
8040
  onToolExecutionEnd,
8027
8041
  executeToolInTelemetryContext,
@@ -8056,7 +8070,7 @@ function executeToolsFromStream({
8056
8070
  }
8057
8071
  return;
8058
8072
  }
8059
- const approvalId = generateId2();
8073
+ const approvalId = generateId3();
8060
8074
  const signature = await maybeSignApproval({
8061
8075
  secret: toolApprovalSecret,
8062
8076
  approvalId,
@@ -8262,7 +8276,7 @@ async function streamLanguageModelCall({
8262
8276
  toolsContext,
8263
8277
  experimental_sandbox: sandbox,
8264
8278
  _internal: {
8265
- generateId: generateId2 = originalGenerateId2,
8279
+ generateId: generateId3 = originalGenerateId2,
8266
8280
  generateCallId = originalGenerateCallId2,
8267
8281
  now: now2 = now
8268
8282
  } = {},
@@ -8347,7 +8361,7 @@ async function streamLanguageModelCall({
8347
8361
  callId: effectiveCallId,
8348
8362
  provider: resolvedModel.provider,
8349
8363
  modelId: resolvedModel.modelId,
8350
- generateId: generateId2,
8364
+ generateId: generateId3,
8351
8365
  now: now2,
8352
8366
  callStartTimestampMs,
8353
8367
  onLanguageModelCallEnd
@@ -8368,7 +8382,7 @@ function createLanguageModelV4StreamPartToLanguageModelStreamPartTransform({
8368
8382
  callId,
8369
8383
  provider,
8370
8384
  modelId,
8371
- generateId: generateId2,
8385
+ generateId: generateId3,
8372
8386
  now: now2,
8373
8387
  callStartTimestampMs,
8374
8388
  onLanguageModelCallEnd
@@ -8377,7 +8391,7 @@ function createLanguageModelV4StreamPartToLanguageModelStreamPartTransform({
8377
8391
  const modelCallContent = [];
8378
8392
  const textPartIndexes = /* @__PURE__ */ new Map();
8379
8393
  const reasoningPartIndexes = /* @__PURE__ */ new Map();
8380
- let responseId = generateId2();
8394
+ let responseId = generateId3();
8381
8395
  let responseModelId = modelId;
8382
8396
  let timeToFirstOutputMs;
8383
8397
  let previousOutputChunkTimestampMs;
@@ -8522,6 +8536,7 @@ function createLanguageModelV4StreamPartToLanguageModelStreamPartTransform({
8522
8536
  usage,
8523
8537
  content: modelCallContent,
8524
8538
  responseId,
8539
+ ...chunk.providerMetadata != null ? { providerMetadata: chunk.providerMetadata } : {},
8525
8540
  performance
8526
8541
  },
8527
8542
  callbacks: onLanguageModelCallEnd
@@ -8811,7 +8826,7 @@ function streamText({
8811
8826
  include = experimental_include,
8812
8827
  _internal: {
8813
8828
  now: now2 = now,
8814
- generateId: generateId2 = originalGenerateId3,
8829
+ generateId: generateId3 = originalGenerateId3,
8815
8830
  generateCallId = originalGenerateCallId3
8816
8831
  } = {},
8817
8832
  ...settings
@@ -8885,7 +8900,7 @@ function streamText({
8885
8900
  onToolExecutionStart: resolvedOnToolExecutionStart,
8886
8901
  onToolExecutionEnd: resolvedOnToolExecutionEnd,
8887
8902
  now: now2,
8888
- generateId: generateId2,
8903
+ generateId: generateId3,
8889
8904
  generateCallId,
8890
8905
  download: download2,
8891
8906
  // assign default values to include:
@@ -9003,7 +9018,7 @@ var DefaultStreamTextResult = class {
9003
9018
  providerOptions,
9004
9019
  prepareStep,
9005
9020
  now: now2,
9006
- generateId: generateId2,
9021
+ generateId: generateId3,
9007
9022
  generateCallId,
9008
9023
  timeout,
9009
9024
  onChunk,
@@ -9771,7 +9786,7 @@ var DefaultStreamTextResult = class {
9771
9786
  toolApproval,
9772
9787
  runtimeContext,
9773
9788
  toolApprovalSecret: experimental_toolApprovalSecret,
9774
- generateId: generateId2,
9789
+ generateId: generateId3,
9775
9790
  // the callbacks need to be passed down and handled by executeToolCall
9776
9791
  // to guarantee that the onToolExecutionStart callback is invoked before the tool execute function
9777
9792
  onToolExecutionStart: filterNullable2(
@@ -9813,7 +9828,7 @@ var DefaultStreamTextResult = class {
9813
9828
  };
9814
9829
  const toolExecutionMs = {};
9815
9830
  let stepResponse = {
9816
- id: generateId2(),
9831
+ id: generateId3(),
9817
9832
  timestamp: /* @__PURE__ */ new Date(),
9818
9833
  modelId: model.modelId
9819
9834
  };
@@ -10577,7 +10592,7 @@ function createUIMessageStream({
10577
10592
  onStepFinish,
10578
10593
  onEnd,
10579
10594
  onFinish,
10580
- generateId: generateId2 = generateIdFunc
10595
+ generateId: generateId3 = generateIdFunc
10581
10596
  }) {
10582
10597
  let controller;
10583
10598
  const ongoingStreamPromises = [];
@@ -10649,7 +10664,7 @@ function createUIMessageStream({
10649
10664
  });
10650
10665
  return handleUIMessageStreamFinish({
10651
10666
  stream,
10652
- messageId: generateId2(),
10667
+ messageId: generateId3(),
10653
10668
  originalMessages,
10654
10669
  onStepEnd: onStepEnd != null ? onStepEnd : onStepFinish,
10655
10670
  onEnd: onEnd != null ? onEnd : onFinish,
@@ -12925,7 +12940,7 @@ async function generateObject(options) {
12925
12940
  onStepFinish,
12926
12941
  onFinish,
12927
12942
  _internal: {
12928
- generateId: generateId2 = originalGenerateId4,
12943
+ generateId: generateId3 = originalGenerateId4,
12929
12944
  currentDate = () => /* @__PURE__ */ new Date()
12930
12945
  } = {},
12931
12946
  ...settings
@@ -12965,7 +12980,7 @@ async function generateObject(options) {
12965
12980
  const resolvedOnStepStart = onStepStart != null ? onStepStart : experimental_onStepStart;
12966
12981
  const resolvedOnStepEnd = onStepEnd != null ? onStepEnd : onStepFinish;
12967
12982
  const jsonSchema2 = await outputStrategy.jsonSchema();
12968
- const callId = generateId2();
12983
+ const callId = generateId3();
12969
12984
  await notify({
12970
12985
  event: {
12971
12986
  callId,
@@ -13034,7 +13049,7 @@ async function generateObject(options) {
13034
13049
  })
13035
13050
  );
13036
13051
  const responseData = {
13037
- id: (_b = (_a23 = generateResult.response) == null ? void 0 : _a23.id) != null ? _b : generateId2(),
13052
+ id: (_b = (_a23 = generateResult.response) == null ? void 0 : _a23.id) != null ? _b : generateId3(),
13038
13053
  timestamp: (_d = (_c = generateResult.response) == null ? void 0 : _c.timestamp) != null ? _d : currentDate(),
13039
13054
  modelId: (_f = (_e = generateResult.response) == null ? void 0 : _e.modelId) != null ? _f : model.modelId,
13040
13055
  headers: (_g = generateResult.response) == null ? void 0 : _g.headers,
@@ -13314,7 +13329,7 @@ function streamObject(options) {
13314
13329
  },
13315
13330
  onFinish,
13316
13331
  _internal: {
13317
- generateId: generateId2 = originalGenerateId5,
13332
+ generateId: generateId3 = originalGenerateId5,
13318
13333
  currentDate = () => /* @__PURE__ */ new Date(),
13319
13334
  now: now2 = now
13320
13335
  } = {},
@@ -13361,7 +13376,7 @@ function streamObject(options) {
13361
13376
  onError,
13362
13377
  onFinish,
13363
13378
  download: download2,
13364
- generateId: generateId2,
13379
+ generateId: generateId3,
13365
13380
  currentDate,
13366
13381
  now: now2
13367
13382
  });
@@ -13390,7 +13405,7 @@ var DefaultStreamObjectResult = class {
13390
13405
  onError,
13391
13406
  onFinish,
13392
13407
  download: download2,
13393
- generateId: generateId2,
13408
+ generateId: generateId3,
13394
13409
  currentDate,
13395
13410
  now: now2
13396
13411
  }) {
@@ -13421,7 +13436,7 @@ var DefaultStreamObjectResult = class {
13421
13436
  }
13422
13437
  });
13423
13438
  this.baseStream = stitchableStream.stream.pipeThrough(eventProcessor);
13424
- const callId = generateId2();
13439
+ const callId = generateId3();
13425
13440
  (async () => {
13426
13441
  const jsonSchema2 = await outputStrategy.jsonSchema();
13427
13442
  await notify({
@@ -13518,7 +13533,7 @@ var DefaultStreamObjectResult = class {
13518
13533
  let accumulatedText = "";
13519
13534
  let textDelta = "";
13520
13535
  let fullResponse = {
13521
- id: generateId2(),
13536
+ id: generateId3(),
13522
13537
  timestamp: currentDate(),
13523
13538
  modelId: model.modelId
13524
13539
  };
@@ -14136,6 +14151,7 @@ function detectToolDrift(current, baseline) {
14136
14151
  import {
14137
14152
  convertBase64ToUint8Array as convertBase64ToUint8Array5,
14138
14153
  delay as defaultDelay,
14154
+ generateId,
14139
14155
  withUserAgentSuffix as withUserAgentSuffix10,
14140
14156
  detectMediaType as detectMediaType4
14141
14157
  } from "@ai-sdk/provider-utils";
@@ -14337,7 +14353,7 @@ async function executeStartStatusFlow({
14337
14353
  webhook: webhookFactory,
14338
14354
  retry
14339
14355
  }) {
14340
- var _a23, _b, _c;
14356
+ var _a23, _b, _c, _d;
14341
14357
  const earlyWarnings = [];
14342
14358
  let webhookUrl;
14343
14359
  let webhookReceived;
@@ -14356,17 +14372,23 @@ async function executeStartStatusFlow({
14356
14372
  });
14357
14373
  }
14358
14374
  }
14359
- const startResult = await retry(
14360
- () => model.doStart({
14361
- ...callOptions,
14362
- webhookUrl
14363
- })
14375
+ const callerIdempotencyKey = Object.entries((_a23 = callOptions.headers) != null ? _a23 : {}).find(
14376
+ ([key, value]) => key.toLowerCase() === "idempotency-key" && value !== void 0
14364
14377
  );
14378
+ const startCallOptions = {
14379
+ ...callOptions,
14380
+ headers: {
14381
+ ...callOptions.headers,
14382
+ ...callerIdempotencyKey ? {} : { "idempotency-key": `aisdk_vid_${generateId()}` }
14383
+ },
14384
+ webhookUrl
14385
+ };
14386
+ const startResult = await retry(() => model.doStart(startCallOptions));
14365
14387
  const allWarnings = [...earlyWarnings, ...startResult.warnings];
14366
14388
  let operationProviderMetadata = startResult.providerMetadata == null ? void 0 : { ...startResult.providerMetadata };
14367
- const intervalMs = (_a23 = pollConfig == null ? void 0 : pollConfig.intervalMs) != null ? _a23 : 5e3;
14368
- const timeoutMs = (_b = pollConfig == null ? void 0 : pollConfig.timeoutMs) != null ? _b : 6e5;
14369
- const delay = (_c = pollConfig == null ? void 0 : pollConfig.delay) != null ? _c : defaultDelay;
14389
+ const intervalMs = (_b = pollConfig == null ? void 0 : pollConfig.intervalMs) != null ? _b : 5e3;
14390
+ const timeoutMs = (_c = pollConfig == null ? void 0 : pollConfig.timeoutMs) != null ? _c : 6e5;
14391
+ const delay = (_d = pollConfig == null ? void 0 : pollConfig.delay) != null ? _d : defaultDelay;
14370
14392
  const startTime = Date.now();
14371
14393
  if (webhookReceived != null) {
14372
14394
  await waitForWebhook({
@@ -17473,7 +17495,8 @@ var HttpChatTransport = class {
17473
17495
  const response = await fetch2(api, {
17474
17496
  method: "GET",
17475
17497
  headers,
17476
- credentials
17498
+ credentials,
17499
+ signal: options.abortSignal
17477
17500
  });
17478
17501
  if (response.status === 204) {
17479
17502
  return null;
@@ -17515,8 +17538,8 @@ var DefaultChatTransport = class extends HttpChatTransport {
17515
17538
  // src/ui/chat.ts
17516
17539
  var AbstractChat = class {
17517
17540
  constructor({
17518
- generateId: generateId2 = generateIdFunc2,
17519
- id = generateId2(),
17541
+ generateId: generateId3 = generateIdFunc2,
17542
+ id = generateId3(),
17520
17543
  transport = new DefaultChatTransport(),
17521
17544
  messageMetadataSchema,
17522
17545
  dataPartSchemas,
@@ -17528,6 +17551,7 @@ var AbstractChat = class {
17528
17551
  sendAutomaticallyWhen
17529
17552
  }) {
17530
17553
  this.activeResponse = void 0;
17554
+ this.activeResumeRequest = void 0;
17531
17555
  this.jobExecutor = new SerialJobExecutor();
17532
17556
  /**
17533
17557
  * Appends or replaces a user message to the chat list. This triggers the API call to fetch
@@ -17697,16 +17721,13 @@ var AbstractChat = class {
17697
17721
  * Abort the current request immediately, keep the generated tokens if any.
17698
17722
  */
17699
17723
  this.stop = async () => {
17700
- var _a23;
17701
- if (this.status !== "streaming" && this.status !== "submitted")
17702
- return;
17703
- if ((_a23 = this.activeResponse) == null ? void 0 : _a23.abortController) {
17704
- this.activeResponse.abortController.abort();
17705
- }
17724
+ var _a23, _b;
17725
+ (_a23 = this.activeResumeRequest) == null ? void 0 : _a23.abortController.abort();
17726
+ (_b = this.activeResponse) == null ? void 0 : _b.abortController.abort();
17706
17727
  };
17707
17728
  this.id = id;
17708
17729
  this.transport = transport;
17709
- this.generateId = generateId2;
17730
+ this.generateId = generateId3;
17710
17731
  this.messageMetadataSchema = messageMetadataSchema;
17711
17732
  this.dataPartSchemas = dataPartSchemas;
17712
17733
  this.state = state;
@@ -17766,25 +17787,60 @@ var AbstractChat = class {
17766
17787
  body,
17767
17788
  messageId
17768
17789
  }) {
17769
- var _a23, _b;
17790
+ var _a23, _b, _c;
17791
+ const abortController = new AbortController();
17792
+ const activeResumeRequest = trigger === "resume-stream" ? { abortController } : void 0;
17793
+ if (activeResumeRequest) {
17794
+ (_a23 = this.activeResumeRequest) == null ? void 0 : _a23.abortController.abort();
17795
+ this.activeResumeRequest = activeResumeRequest;
17796
+ }
17797
+ const isCurrentRequest = () => activeResumeRequest == null || this.activeResumeRequest === activeResumeRequest;
17798
+ const clearActiveResumeRequest = () => {
17799
+ if (this.activeResumeRequest === activeResumeRequest) {
17800
+ this.activeResumeRequest = void 0;
17801
+ }
17802
+ };
17770
17803
  let resumeStream;
17771
17804
  if (trigger === "resume-stream") {
17772
17805
  try {
17773
17806
  const reconnect = await this.transport.reconnectToStream({
17774
17807
  chatId: this.id,
17808
+ abortSignal: abortController.signal,
17775
17809
  metadata,
17776
17810
  headers,
17777
17811
  body
17778
17812
  });
17813
+ if (abortController.signal.aborted || !isCurrentRequest()) {
17814
+ await (reconnect == null ? void 0 : reconnect.cancel().catch(() => {
17815
+ }));
17816
+ if (isCurrentRequest()) {
17817
+ this.setStatus({ status: "ready" });
17818
+ }
17819
+ clearActiveResumeRequest();
17820
+ return;
17821
+ }
17779
17822
  if (reconnect == null) {
17823
+ this.setStatus({ status: "ready" });
17824
+ clearActiveResumeRequest();
17780
17825
  return;
17781
17826
  }
17782
17827
  resumeStream = reconnect;
17783
17828
  } catch (err) {
17829
+ if (abortController.signal.aborted || err.name === "AbortError") {
17830
+ if (isCurrentRequest()) {
17831
+ this.setStatus({ status: "ready" });
17832
+ }
17833
+ clearActiveResumeRequest();
17834
+ return;
17835
+ }
17836
+ if (!isCurrentRequest()) {
17837
+ return;
17838
+ }
17784
17839
  if (this.onError && err instanceof Error) {
17785
17840
  this.onError(err);
17786
17841
  }
17787
17842
  this.setStatus({ status: "error", error: err });
17843
+ clearActiveResumeRequest();
17788
17844
  return;
17789
17845
  }
17790
17846
  }
@@ -17800,7 +17856,7 @@ var AbstractChat = class {
17800
17856
  lastMessage: trigger === "regenerate-message" ? void 0 : this.state.snapshot(lastMessage),
17801
17857
  messageId: this.generateId()
17802
17858
  }),
17803
- abortController: new AbortController()
17859
+ abortController
17804
17860
  };
17805
17861
  activeResponse = response;
17806
17862
  response.abortController.signal.addEventListener("abort", () => {
@@ -17824,11 +17880,17 @@ var AbstractChat = class {
17824
17880
  }
17825
17881
  const runUpdateMessageJob = (job) => (
17826
17882
  // serialize the job execution to avoid race conditions:
17827
- this.jobExecutor.run(
17828
- () => job({
17883
+ this.jobExecutor.run(() => {
17884
+ if (response.abortController.signal.aborted) {
17885
+ return Promise.resolve();
17886
+ }
17887
+ return job({
17829
17888
  state: response.state,
17830
17889
  write: () => {
17831
17890
  var _a24;
17891
+ if (response.abortController.signal.aborted) {
17892
+ return;
17893
+ }
17832
17894
  this.setStatus({ status: "streaming" });
17833
17895
  const replaceLastMessage = response.state.message.id === ((_a24 = this.lastMessage) == null ? void 0 : _a24.id);
17834
17896
  if (replaceLastMessage) {
@@ -17840,8 +17902,8 @@ var AbstractChat = class {
17840
17902
  this.state.pushMessage(response.state.message);
17841
17903
  }
17842
17904
  }
17843
- })
17844
- )
17905
+ });
17906
+ })
17845
17907
  );
17846
17908
  await consumeStream({
17847
17909
  stream: processUIMessageStream({
@@ -17855,15 +17917,29 @@ var AbstractChat = class {
17855
17917
  throw error;
17856
17918
  }
17857
17919
  }),
17920
+ abortSignal: response.abortController.signal,
17858
17921
  onError: (error) => {
17859
17922
  throw error;
17860
17923
  }
17861
17924
  });
17862
- this.setStatus({ status: "ready" });
17925
+ if (isAbort) {
17926
+ if (isCurrentRequest()) {
17927
+ this.setStatus({ status: "ready" });
17928
+ }
17929
+ return null;
17930
+ }
17931
+ if (isCurrentRequest()) {
17932
+ this.setStatus({ status: "ready" });
17933
+ }
17863
17934
  } catch (err) {
17864
17935
  if (isAbort || err.name === "AbortError") {
17865
17936
  isAbort = true;
17866
- this.setStatus({ status: "ready" });
17937
+ if (isCurrentRequest()) {
17938
+ this.setStatus({ status: "ready" });
17939
+ }
17940
+ return null;
17941
+ }
17942
+ if (!isCurrentRequest()) {
17867
17943
  return null;
17868
17944
  }
17869
17945
  isError = true;
@@ -17877,7 +17953,7 @@ var AbstractChat = class {
17877
17953
  } finally {
17878
17954
  try {
17879
17955
  if (activeResponse) {
17880
- (_a23 = this.onFinish) == null ? void 0 : _a23.call(this, {
17956
+ (_b = this.onFinish) == null ? void 0 : _b.call(this, {
17881
17957
  message: activeResponse.state.message,
17882
17958
  messages: this.state.messages,
17883
17959
  isAbort,
@@ -17892,11 +17968,12 @@ var AbstractChat = class {
17892
17968
  if (this.activeResponse === activeResponse) {
17893
17969
  this.activeResponse = void 0;
17894
17970
  }
17971
+ clearActiveResumeRequest();
17895
17972
  }
17896
17973
  if (!isError && await this.shouldSendAutomatically()) {
17897
17974
  await this.makeRequest({
17898
17975
  trigger: "submit-message",
17899
- messageId: (_b = this.lastMessage) == null ? void 0 : _b.id,
17976
+ messageId: (_c = this.lastMessage) == null ? void 0 : _c.id,
17900
17977
  metadata,
17901
17978
  headers,
17902
17979
  body
@@ -18213,7 +18290,7 @@ export {
18213
18290
  extractReasoningMiddleware,
18214
18291
  fingerprintTools,
18215
18292
  gateway2 as gateway,
18216
- generateId,
18293
+ generateId2 as generateId,
18217
18294
  generateImage,
18218
18295
  generateObject,
18219
18296
  generateSpeech,