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/dist/index.js CHANGED
@@ -1,8 +1,9 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.js";
2
2
  import { GatewayAuthenticationError, GatewayError, createGateway, gateway, gateway as gateway$1 } from "@ai-sdk/gateway";
3
- import { DEFAULT_MAX_DOWNLOAD_SIZE, DelayedPromise, DownloadError, DownloadError as DownloadError$1, EXPERIMENTAL_EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL, EXPERIMENTAL_EMBEDDING_MODEL_PROVIDER_OPTIONS_TRANSFORMER, asArray, asSchema, asSchema as asSchema$1, cancelResponseBody, convertAsyncIteratorToReadableStream, convertBase64ToUint8Array, convertUint8ArrayToBase64, createIdGenerator, createIdGenerator as createIdGenerator$1, delay, detectMediaType, dynamicTool, executeTool, experimental_getToolCaller, experimental_toolCaller, fetchUntrustedUrl, filterNullable, generateId, generateId as generateId$1, getErrorMessage, getRuntimeEnvironmentUserAgent, getTopLevelMediaType, getWebSocketConstructor, isAbortError, isArrayBuffer, isBuffer, isExecutableTool, isFullMediaType, isNonNullable, isProviderReference, isProviderStreamError, isUint8Array, isUrlSupported, jsonSchema, jsonSchema as jsonSchema$1, lazySchema, normalizeHeaders, parseJsonEventStream, parseJsonEventStream as parseJsonEventStream$1, readResponseWithSizeLimit, readWebSocketMessageText, resolve, retryWithExponentialBackoff, safeParseJSON, safeValidateTypes, toWebSocketUrl, tool, tool as tool$1, validateTypes, waitForWebSocketBufferDrain, withUserAgentSuffix, zodSchema, zodSchema as zodSchema$1 } from "@ai-sdk/provider-utils";
3
+ import { DEFAULT_MAX_DOWNLOAD_SIZE, DelayedPromise, DownloadError, DownloadError as DownloadError$1, EXPERIMENTAL_EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL, EXPERIMENTAL_EMBEDDING_MODEL_PROVIDER_OPTIONS_TRANSFORMER, asArray, asSchema, asSchema as asSchema$1, cancelResponseBody, convertAsyncIteratorToReadableStream, convertBase64ToUint8Array, convertUint8ArrayToBase64, createIdGenerator, createIdGenerator as createIdGenerator$1, delay, detectMediaType, dynamicTool, executeTool, experimental_getToolCaller, experimental_toolCaller, fetchUntrustedUrl, filterNullable, generateId, generateId as generateId$1, getErrorMessage, getRuntimeEnvironmentUserAgent, getTopLevelMediaType, getWebSocketConstructor, isAbortError, isArrayBuffer, isBuffer, isExecutableTool, isFullMediaType, isNonNullable, isProviderReference, isProviderStreamError, isUint8Array, isUrlSupported, jsonSchema, jsonSchema as jsonSchema$1, lazySchema, normalizeHeaders, parseJsonEventStream, parseJsonEventStream as parseJsonEventStream$1, readResponseWithSizeLimit, readWebSocketMessageText, redactTelemetryValue, resolve, retryWithExponentialBackoff, safeParseJSON, safeValidateTypes, toWebSocketUrl, tool, tool as tool$1, validateTypes, waitForWebSocketBufferDrain, withUserAgentSuffix, zodSchema, zodSchema as zodSchema$1 } from "@ai-sdk/provider-utils";
4
4
  import { AISDKError, AISDKError as AISDKError$1, APICallError, APICallError as APICallError$1, EmptyResponseBodyError, EmptyResponseBodyError as EmptyResponseBodyError$1, Experimental_DecisionRefusalError, Experimental_DecisionRefusalError as Experimental_DecisionRefusalError$1, Experimental_DecisionUnsupportedQuestionTypeError, Experimental_DecisionUnsupportedQuestionTypeError as Experimental_DecisionUnsupportedQuestionTypeError$1, InvalidPromptError, InvalidPromptError as InvalidPromptError$1, InvalidResponseDataError, InvalidResponseDataError as InvalidResponseDataError$1, JSONParseError, JSONParseError as JSONParseError$1, LoadAPIKeyError, LoadSettingError, NoContentGeneratedError, NoSuchModelError, NoSuchModelError as NoSuchModelError$1, NoSuchProviderReferenceError, TooManyEmbeddingValuesForCallError, TypeValidationError, TypeValidationError as TypeValidationError$1, UnsupportedFunctionalityError, UnsupportedFunctionalityError as UnsupportedFunctionalityError$1, getErrorMessage as getErrorMessage$1, isJSONArray, isJSONObject } from "@ai-sdk/provider";
5
- import { array, boolean, custom, discriminatedUnion, enum as enum$1, instanceof as instanceof$1, lazy, literal, looseObject, never, null as null$1, number, object, record, string, union, unknown } from "zod/v4";
5
+ import { array, boolean, custom, discriminatedUnion, enum as enum$1, extend, int, literal, looseObject, maximum, minLength, never, nonnegative, number, object, optional, pipe, positive, record, refine, startsWith, string, transform, union, unknown } from "zod/v4/mini";
6
+ import { array as array$1, boolean as boolean$1, custom as custom$1, discriminatedUnion as discriminatedUnion$1, instanceof as instanceof$1, lazy, literal as literal$1, null as null$1, number as number$1, object as object$1, record as record$1, string as string$1, union as union$1, unknown as unknown$1 } from "zod/v4";
6
7
  //#region src/telemetry/get-request-origin.ts
7
8
  /** Remove credentials, paths, queries, and fragments before emitting telemetry. */
8
9
  function getRequestOrigin(url) {
@@ -1241,7 +1242,7 @@ function cloneValue(value, seen) {
1241
1242
  }
1242
1243
  //#endregion
1243
1244
  //#region src/version.ts
1244
- const VERSION = "7.0.166";
1245
+ const VERSION = "7.0.169";
1245
1246
  //#endregion
1246
1247
  //#region src/util/download/download.ts
1247
1248
  /**
@@ -3469,10 +3470,10 @@ async function parsePartialJson(jsonText) {
3469
3470
  //#endregion
3470
3471
  //#region src/generate-text/output.ts
3471
3472
  var output_exports = /* @__PURE__ */ __exportAll({
3472
- array: () => array$1,
3473
+ array: () => array$2,
3473
3474
  choice: () => choice,
3474
3475
  json: () => json,
3475
- object: () => object$1,
3476
+ object: () => object$2,
3476
3477
  text: () => text
3477
3478
  });
3478
3479
  /**
@@ -3492,7 +3493,7 @@ const text = () => ({
3492
3493
  },
3493
3494
  createElementStreamTransform() {}
3494
3495
  });
3495
- function object$1({ schema: inputSchema, name, description }) {
3496
+ function object$2({ schema: inputSchema, name, description }) {
3496
3497
  const schema = asSchema$1(inputSchema);
3497
3498
  return {
3498
3499
  name: "object",
@@ -3538,7 +3539,7 @@ function object$1({ schema: inputSchema, name, description }) {
3538
3539
  createElementStreamTransform() {}
3539
3540
  };
3540
3541
  }
3541
- function array$1({ element: inputElementSchema, minItems, maxItems, name, description }) {
3542
+ function array$2({ element: inputElementSchema, minItems, maxItems, name, description }) {
3542
3543
  validateArrayBound({
3543
3544
  name: "minItems",
3544
3545
  value: minItems
@@ -4103,6 +4104,65 @@ function isNodeRuntime() {
4103
4104
  return globalThis.process?.release?.name === "node";
4104
4105
  }
4105
4106
  //#endregion
4107
+ //#region src/telemetry/redact-telemetry-credentials.ts
4108
+ /**
4109
+ * Apply provider-owned credential redaction on telemetry-only copies. Only visit SDK
4110
+ * metadata containers, never arbitrary prompts, tool outputs, or user context.
4111
+ */
4112
+ function redactTelemetryCredentials(value) {
4113
+ return replaceProperties(value, {
4114
+ args: redactTelemetryValue,
4115
+ tools: redactTools,
4116
+ stepTools: redactTools,
4117
+ request: redactMetadata,
4118
+ response: redactMetadata,
4119
+ steps: (steps) => mapArray(steps, redactTelemetryCredentials),
4120
+ finalStep: redactTelemetryCredentials,
4121
+ error: redactTelemetryCredentials,
4122
+ cause: redactTelemetryCredentials,
4123
+ errors: (errors) => mapArray(errors, redactTelemetryCredentials),
4124
+ lastError: redactTelemetryCredentials,
4125
+ requestBodyValues: redactBody
4126
+ });
4127
+ }
4128
+ function redactMetadata(value) {
4129
+ return Array.isArray(value) ? mapArray(value, redactMetadata) : replaceProperties(value, { body: redactBody });
4130
+ }
4131
+ function redactBody(value) {
4132
+ return replaceProperties(redactTelemetryValue(value), { tools: redactTools });
4133
+ }
4134
+ function redactTools(value) {
4135
+ if (Array.isArray(value)) return mapArray(value, redactTelemetryCredentials);
4136
+ if (!isRecord$2(value)) return value;
4137
+ return replaceProperties(value, Object.fromEntries(Object.keys(value).map((key) => [key, redactTelemetryCredentials])));
4138
+ }
4139
+ function isRecord$2(value) {
4140
+ return value != null && typeof value === "object" && !Array.isArray(value);
4141
+ }
4142
+ function mapArray(value, redact) {
4143
+ if (!Array.isArray(value)) return value;
4144
+ const copy = value.map(redact);
4145
+ return copy.some((entry, index) => entry !== value[index]) ? copy : value;
4146
+ }
4147
+ /** Preserve result getters, streams, and property descriptors without mutation. */
4148
+ function replaceProperties(value, redactors) {
4149
+ if (!isRecord$2(value)) return value;
4150
+ let descriptors;
4151
+ for (const [key, redact] of Object.entries(redactors)) {
4152
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
4153
+ if (descriptor == null || !("value" in descriptor)) continue;
4154
+ const redacted = redact(descriptor.value);
4155
+ if (redacted !== descriptor.value) {
4156
+ descriptors ??= Object.getOwnPropertyDescriptors(value);
4157
+ descriptors[key] = {
4158
+ ...descriptor,
4159
+ value: redacted
4160
+ };
4161
+ }
4162
+ }
4163
+ return descriptors == null ? value : Object.create(Object.getPrototypeOf(value), descriptors);
4164
+ }
4165
+ //#endregion
4106
4166
  //#region src/telemetry/tracing-channel-publisher.ts
4107
4167
  let diagnosticsChannelPromise;
4108
4168
  /**
@@ -4156,7 +4216,9 @@ async function runWithTracingChannelSpan(message, execute, recordResult = true)
4156
4216
  hasExecutionError = true;
4157
4217
  throw error;
4158
4218
  });
4159
- return recordResult ? executePromise : executePromise.then(() => void 0, () => {
4219
+ return recordResult ? executePromise.then(redactTelemetryCredentials, (error) => {
4220
+ throw redactTelemetryCredentials(error);
4221
+ }) : executePromise.then(() => void 0, () => {
4160
4222
  throw new Error("AI SDK operation failed");
4161
4223
  });
4162
4224
  };
@@ -4198,10 +4260,10 @@ function openTelemetryChannelSpanContext({ message, completion, recordResult = t
4198
4260
  if (asyncEndPublished) return;
4199
4261
  asyncEndPublished = true;
4200
4262
  if (error !== void 0) {
4201
- context.error = recordResult ? error : /* @__PURE__ */ new Error("AI SDK operation failed");
4263
+ context.error = recordResult ? redactTelemetryCredentials(error) : /* @__PURE__ */ new Error("AI SDK operation failed");
4202
4264
  safePublish(() => tracingChannel.error.publish(context));
4203
4265
  }
4204
- if (recordResult && result !== void 0) context.result = result;
4266
+ if (recordResult && result !== void 0) context.result = redactTelemetryCredentials(result);
4205
4267
  safePublish(() => tracingChannel.asyncEnd.publish(context));
4206
4268
  };
4207
4269
  safePublish(() => {
@@ -4360,7 +4422,7 @@ function augmentEvent(event, telemetry, filterContext = false) {
4360
4422
  includeToolsContext: telemetry.includeToolsContext
4361
4423
  });
4362
4424
  }
4363
- return filterTelemetryEvent(augmentedEvent, telemetry);
4425
+ return redactTelemetryCredentials(filterTelemetryEvent(augmentedEvent, telemetry));
4364
4426
  }
4365
4427
  /**
4366
4428
  * Creates a telemetry dispatcher that sends telemetry events
@@ -4447,10 +4509,29 @@ function createTelemetryDispatcher({ telemetry }) {
4447
4509
  let wrappedExecute = execute;
4448
4510
  for (const executeWrapper of executeLanguageModelCallWrappers) {
4449
4511
  const innerExecute = wrappedExecute;
4450
- wrappedExecute = () => executeWrapper({
4451
- ...augmentedEvent,
4452
- execute: innerExecute
4453
- });
4512
+ wrappedExecute = async () => {
4513
+ const originals = /* @__PURE__ */ new Map();
4514
+ const redact = (original) => {
4515
+ const redacted = redactTelemetryCredentials(original);
4516
+ if (redacted !== original) originals.set(redacted, original);
4517
+ return redacted;
4518
+ };
4519
+ const restore = (value) => originals.has(value) ? originals.get(value) : value;
4520
+ try {
4521
+ return restore(await executeWrapper({
4522
+ ...augmentedEvent,
4523
+ execute: async () => {
4524
+ try {
4525
+ return redact(await innerExecute());
4526
+ } catch (error) {
4527
+ throw redact(error);
4528
+ }
4529
+ }
4530
+ }));
4531
+ } catch (error) {
4532
+ throw restore(error);
4533
+ }
4534
+ };
4454
4535
  }
4455
4536
  return await runWithTracingChannelSpan({
4456
4537
  type: "languageModelCall",
@@ -6421,26 +6502,52 @@ function getResponseUIMessageId({ originalMessages, responseMessageId }) {
6421
6502
  }
6422
6503
  //#endregion
6423
6504
  //#region src/util/zod.ts
6424
- const z = {
6505
+ const z$1 = {
6425
6506
  array,
6426
6507
  boolean,
6427
6508
  custom,
6428
6509
  discriminatedUnion,
6429
6510
  enum: enum$1,
6430
- instanceof: instanceof$1,
6431
- lazy,
6511
+ extend,
6512
+ int,
6432
6513
  literal,
6433
6514
  looseObject,
6515
+ maximum,
6516
+ minLength,
6434
6517
  never,
6435
- null: null$1,
6518
+ nonnegative,
6436
6519
  number,
6437
6520
  object,
6521
+ optional,
6522
+ pipe,
6523
+ positive,
6438
6524
  record,
6525
+ refine,
6526
+ startsWith,
6439
6527
  string,
6528
+ transform,
6440
6529
  union,
6441
6530
  unknown
6442
6531
  };
6443
6532
  //#endregion
6533
+ //#region src/util/classic-zod.ts
6534
+ const z = {
6535
+ array: array$1,
6536
+ boolean: boolean$1,
6537
+ custom: custom$1,
6538
+ discriminatedUnion: discriminatedUnion$1,
6539
+ instanceof: instanceof$1,
6540
+ lazy,
6541
+ literal: literal$1,
6542
+ null: null$1,
6543
+ number: number$1,
6544
+ object: object$1,
6545
+ record: record$1,
6546
+ string: string$1,
6547
+ union: union$1,
6548
+ unknown: unknown$1
6549
+ };
6550
+ //#endregion
6444
6551
  //#region src/types/json-value.ts
6445
6552
  const jsonValueSchema = z.lazy(() => z.union([
6446
6553
  z.null(),
@@ -6455,213 +6562,213 @@ const jsonValueSchema = z.lazy(() => z.union([
6455
6562
  const providerMetadataSchema = z.record(z.string(), z.record(z.string(), jsonValueSchema.optional()));
6456
6563
  //#endregion
6457
6564
  //#region src/types/citation.ts
6458
- const citationSchema = z.object({
6459
- source: z.discriminatedUnion("sourceType", [z.object({
6460
- type: z.literal("source"),
6461
- sourceType: z.literal("url"),
6462
- id: z.string(),
6463
- url: z.string(),
6464
- title: z.string().optional(),
6465
- providerMetadata: providerMetadataSchema.optional()
6466
- }), z.object({
6467
- type: z.literal("source"),
6468
- sourceType: z.literal("document"),
6469
- id: z.string(),
6470
- mediaType: z.string(),
6471
- title: z.string(),
6472
- filename: z.string().optional(),
6473
- providerMetadata: providerMetadataSchema.optional()
6565
+ const citationSchema = z$1.object({
6566
+ source: z$1.discriminatedUnion("sourceType", [z$1.object({
6567
+ type: z$1.literal("source"),
6568
+ sourceType: z$1.literal("url"),
6569
+ id: z$1.string(),
6570
+ url: z$1.string(),
6571
+ title: z$1.optional(z$1.string()),
6572
+ providerMetadata: z$1.optional(providerMetadataSchema)
6573
+ }), z$1.object({
6574
+ type: z$1.literal("source"),
6575
+ sourceType: z$1.literal("document"),
6576
+ id: z$1.string(),
6577
+ mediaType: z$1.string(),
6578
+ title: z$1.string(),
6579
+ filename: z$1.optional(z$1.string()),
6580
+ providerMetadata: z$1.optional(providerMetadataSchema)
6474
6581
  })]),
6475
- startIndex: z.number().int().nonnegative().optional(),
6476
- endIndex: z.number().int().nonnegative().optional(),
6477
- citedText: z.string().optional()
6582
+ startIndex: z$1.optional(z$1.number().check(z$1.int()).check(z$1.nonnegative())),
6583
+ endIndex: z$1.optional(z$1.number().check(z$1.int()).check(z$1.nonnegative())),
6584
+ citedText: z$1.optional(z$1.string())
6478
6585
  });
6479
6586
  //#endregion
6480
6587
  //#region src/ui-message-stream/ui-message-chunks.ts
6481
- const toolMetadataSchema$1 = z.record(z.string(), jsonValueSchema.optional());
6482
- const uiMessageChunkSchema = lazySchema(() => zodSchema$1(z.union([
6483
- z.looseObject({
6484
- type: z.literal("text-start"),
6485
- id: z.string(),
6486
- providerMetadata: providerMetadataSchema.optional()
6588
+ const toolMetadataSchema$1 = z$1.record(z$1.string(), z$1.optional(jsonValueSchema));
6589
+ const uiMessageChunkSchema = lazySchema(() => zodSchema$1(z$1.union([
6590
+ z$1.looseObject({
6591
+ type: z$1.literal("text-start"),
6592
+ id: z$1.string(),
6593
+ providerMetadata: z$1.optional(providerMetadataSchema)
6487
6594
  }),
6488
- z.looseObject({
6489
- type: z.literal("text-delta"),
6490
- id: z.string(),
6491
- delta: z.string(),
6492
- providerMetadata: providerMetadataSchema.optional()
6595
+ z$1.looseObject({
6596
+ type: z$1.literal("text-delta"),
6597
+ id: z$1.string(),
6598
+ delta: z$1.string(),
6599
+ providerMetadata: z$1.optional(providerMetadataSchema)
6493
6600
  }),
6494
- z.looseObject({
6495
- type: z.literal("text-end"),
6496
- id: z.string(),
6497
- citations: z.array(citationSchema).optional(),
6498
- providerMetadata: providerMetadataSchema.optional()
6601
+ z$1.looseObject({
6602
+ type: z$1.literal("text-end"),
6603
+ id: z$1.string(),
6604
+ citations: z$1.optional(z$1.array(citationSchema)),
6605
+ providerMetadata: z$1.optional(providerMetadataSchema)
6499
6606
  }),
6500
- z.looseObject({
6501
- type: z.literal("error"),
6502
- errorText: z.string()
6607
+ z$1.looseObject({
6608
+ type: z$1.literal("error"),
6609
+ errorText: z$1.string()
6503
6610
  }),
6504
- z.looseObject({
6505
- type: z.literal("tool-input-start"),
6506
- toolCallId: z.string(),
6507
- toolName: z.string(),
6508
- inputEncoding: z.enum(["json", "text"]).optional(),
6509
- providerExecuted: z.boolean().optional(),
6510
- providerMetadata: providerMetadataSchema.optional(),
6511
- toolMetadata: toolMetadataSchema$1.optional(),
6512
- dynamic: z.boolean().optional(),
6513
- title: z.string().optional()
6611
+ z$1.looseObject({
6612
+ type: z$1.literal("tool-input-start"),
6613
+ toolCallId: z$1.string(),
6614
+ toolName: z$1.string(),
6615
+ inputEncoding: z$1.optional(z$1.enum(["json", "text"])),
6616
+ providerExecuted: z$1.optional(z$1.boolean()),
6617
+ providerMetadata: z$1.optional(providerMetadataSchema),
6618
+ toolMetadata: z$1.optional(toolMetadataSchema$1),
6619
+ dynamic: z$1.optional(z$1.boolean()),
6620
+ title: z$1.optional(z$1.string())
6514
6621
  }),
6515
- z.looseObject({
6516
- type: z.literal("tool-input-delta"),
6517
- toolCallId: z.string(),
6518
- inputTextDelta: z.string()
6622
+ z$1.looseObject({
6623
+ type: z$1.literal("tool-input-delta"),
6624
+ toolCallId: z$1.string(),
6625
+ inputTextDelta: z$1.string()
6519
6626
  }),
6520
- z.looseObject({
6521
- type: z.literal("tool-input-available"),
6522
- toolCallId: z.string(),
6523
- toolName: z.string(),
6524
- input: z.unknown(),
6525
- providerExecuted: z.boolean().optional(),
6526
- providerMetadata: providerMetadataSchema.optional(),
6527
- toolMetadata: toolMetadataSchema$1.optional(),
6528
- dynamic: z.boolean().optional(),
6529
- title: z.string().optional()
6627
+ z$1.looseObject({
6628
+ type: z$1.literal("tool-input-available"),
6629
+ toolCallId: z$1.string(),
6630
+ toolName: z$1.string(),
6631
+ input: z$1.unknown(),
6632
+ providerExecuted: z$1.optional(z$1.boolean()),
6633
+ providerMetadata: z$1.optional(providerMetadataSchema),
6634
+ toolMetadata: z$1.optional(toolMetadataSchema$1),
6635
+ dynamic: z$1.optional(z$1.boolean()),
6636
+ title: z$1.optional(z$1.string())
6530
6637
  }),
6531
- z.looseObject({
6532
- type: z.literal("tool-input-error"),
6533
- toolCallId: z.string(),
6534
- toolName: z.string(),
6535
- input: z.unknown(),
6536
- providerExecuted: z.boolean().optional(),
6537
- providerMetadata: providerMetadataSchema.optional(),
6538
- toolMetadata: toolMetadataSchema$1.optional(),
6539
- dynamic: z.boolean().optional(),
6540
- errorText: z.string(),
6541
- title: z.string().optional()
6638
+ z$1.looseObject({
6639
+ type: z$1.literal("tool-input-error"),
6640
+ toolCallId: z$1.string(),
6641
+ toolName: z$1.string(),
6642
+ input: z$1.unknown(),
6643
+ providerExecuted: z$1.optional(z$1.boolean()),
6644
+ providerMetadata: z$1.optional(providerMetadataSchema),
6645
+ toolMetadata: z$1.optional(toolMetadataSchema$1),
6646
+ dynamic: z$1.optional(z$1.boolean()),
6647
+ errorText: z$1.string(),
6648
+ title: z$1.optional(z$1.string())
6542
6649
  }),
6543
- z.looseObject({
6544
- type: z.literal("tool-approval-request"),
6545
- approvalId: z.string(),
6546
- toolCallId: z.string(),
6547
- approvalDescriptor: z.unknown().optional(),
6548
- inputSchemaInput: z.unknown().optional(),
6549
- reason: z.string().optional(),
6550
- isAutomatic: z.boolean().optional(),
6551
- signature: z.string().optional()
6650
+ z$1.looseObject({
6651
+ type: z$1.literal("tool-approval-request"),
6652
+ approvalId: z$1.string(),
6653
+ toolCallId: z$1.string(),
6654
+ approvalDescriptor: z$1.optional(z$1.unknown()),
6655
+ inputSchemaInput: z$1.optional(z$1.unknown()),
6656
+ reason: z$1.optional(z$1.string()),
6657
+ isAutomatic: z$1.optional(z$1.boolean()),
6658
+ signature: z$1.optional(z$1.string())
6552
6659
  }),
6553
- z.looseObject({
6554
- type: z.literal("tool-approval-response"),
6555
- approvalId: z.string(),
6556
- approved: z.boolean(),
6557
- reason: z.string().optional(),
6558
- providerExecuted: z.boolean().optional(),
6559
- providerMetadata: providerMetadataSchema.optional()
6660
+ z$1.looseObject({
6661
+ type: z$1.literal("tool-approval-response"),
6662
+ approvalId: z$1.string(),
6663
+ approved: z$1.boolean(),
6664
+ reason: z$1.optional(z$1.string()),
6665
+ providerExecuted: z$1.optional(z$1.boolean()),
6666
+ providerMetadata: z$1.optional(providerMetadataSchema)
6560
6667
  }),
6561
- z.looseObject({
6562
- type: z.literal("tool-output-available"),
6563
- toolCallId: z.string(),
6564
- output: z.unknown(),
6565
- providerExecuted: z.boolean().optional(),
6566
- providerMetadata: providerMetadataSchema.optional(),
6567
- toolMetadata: toolMetadataSchema$1.optional(),
6568
- dynamic: z.boolean().optional(),
6569
- preliminary: z.boolean().optional()
6668
+ z$1.looseObject({
6669
+ type: z$1.literal("tool-output-available"),
6670
+ toolCallId: z$1.string(),
6671
+ output: z$1.unknown(),
6672
+ providerExecuted: z$1.optional(z$1.boolean()),
6673
+ providerMetadata: z$1.optional(providerMetadataSchema),
6674
+ toolMetadata: z$1.optional(toolMetadataSchema$1),
6675
+ dynamic: z$1.optional(z$1.boolean()),
6676
+ preliminary: z$1.optional(z$1.boolean())
6570
6677
  }),
6571
- z.looseObject({
6572
- type: z.literal("tool-output-error"),
6573
- toolCallId: z.string(),
6574
- errorText: z.string(),
6575
- providerExecuted: z.boolean().optional(),
6576
- providerMetadata: providerMetadataSchema.optional(),
6577
- toolMetadata: toolMetadataSchema$1.optional(),
6578
- dynamic: z.boolean().optional()
6678
+ z$1.looseObject({
6679
+ type: z$1.literal("tool-output-error"),
6680
+ toolCallId: z$1.string(),
6681
+ errorText: z$1.string(),
6682
+ providerExecuted: z$1.optional(z$1.boolean()),
6683
+ providerMetadata: z$1.optional(providerMetadataSchema),
6684
+ toolMetadata: z$1.optional(toolMetadataSchema$1),
6685
+ dynamic: z$1.optional(z$1.boolean())
6579
6686
  }),
6580
- z.looseObject({
6581
- type: z.literal("tool-output-denied"),
6582
- toolCallId: z.string()
6687
+ z$1.looseObject({
6688
+ type: z$1.literal("tool-output-denied"),
6689
+ toolCallId: z$1.string()
6583
6690
  }),
6584
- z.looseObject({
6585
- type: z.literal("reasoning-start"),
6586
- id: z.string(),
6587
- providerMetadata: providerMetadataSchema.optional()
6691
+ z$1.looseObject({
6692
+ type: z$1.literal("reasoning-start"),
6693
+ id: z$1.string(),
6694
+ providerMetadata: z$1.optional(providerMetadataSchema)
6588
6695
  }),
6589
- z.looseObject({
6590
- type: z.literal("reasoning-delta"),
6591
- id: z.string(),
6592
- delta: z.string(),
6593
- providerMetadata: providerMetadataSchema.optional()
6696
+ z$1.looseObject({
6697
+ type: z$1.literal("reasoning-delta"),
6698
+ id: z$1.string(),
6699
+ delta: z$1.string(),
6700
+ providerMetadata: z$1.optional(providerMetadataSchema)
6594
6701
  }),
6595
- z.looseObject({
6596
- type: z.literal("reasoning-end"),
6597
- id: z.string(),
6598
- providerMetadata: providerMetadataSchema.optional()
6702
+ z$1.looseObject({
6703
+ type: z$1.literal("reasoning-end"),
6704
+ id: z$1.string(),
6705
+ providerMetadata: z$1.optional(providerMetadataSchema)
6599
6706
  }),
6600
- z.looseObject({
6601
- type: z.literal("custom"),
6602
- kind: z.string().transform((value) => value),
6603
- providerMetadata: providerMetadataSchema.optional()
6707
+ z$1.looseObject({
6708
+ type: z$1.literal("custom"),
6709
+ kind: z$1.pipe(z$1.string(), z$1.transform((value) => value)),
6710
+ providerMetadata: z$1.optional(providerMetadataSchema)
6604
6711
  }),
6605
- z.looseObject({
6606
- type: z.literal("source-url"),
6607
- sourceId: z.string(),
6608
- url: z.string(),
6609
- title: z.string().optional(),
6610
- providerMetadata: providerMetadataSchema.optional()
6712
+ z$1.looseObject({
6713
+ type: z$1.literal("source-url"),
6714
+ sourceId: z$1.string(),
6715
+ url: z$1.string(),
6716
+ title: z$1.optional(z$1.string()),
6717
+ providerMetadata: z$1.optional(providerMetadataSchema)
6611
6718
  }),
6612
- z.looseObject({
6613
- type: z.literal("source-document"),
6614
- sourceId: z.string(),
6615
- mediaType: z.string(),
6616
- title: z.string(),
6617
- filename: z.string().optional(),
6618
- providerMetadata: providerMetadataSchema.optional()
6719
+ z$1.looseObject({
6720
+ type: z$1.literal("source-document"),
6721
+ sourceId: z$1.string(),
6722
+ mediaType: z$1.string(),
6723
+ title: z$1.string(),
6724
+ filename: z$1.optional(z$1.string()),
6725
+ providerMetadata: z$1.optional(providerMetadataSchema)
6619
6726
  }),
6620
- z.looseObject({
6621
- type: z.literal("file"),
6622
- url: z.string(),
6623
- mediaType: z.string(),
6624
- providerMetadata: providerMetadataSchema.optional()
6727
+ z$1.looseObject({
6728
+ type: z$1.literal("file"),
6729
+ url: z$1.string(),
6730
+ mediaType: z$1.string(),
6731
+ providerMetadata: z$1.optional(providerMetadataSchema)
6625
6732
  }),
6626
- z.looseObject({
6627
- type: z.literal("reasoning-file"),
6628
- url: z.string(),
6629
- mediaType: z.string(),
6630
- providerMetadata: providerMetadataSchema.optional()
6733
+ z$1.looseObject({
6734
+ type: z$1.literal("reasoning-file"),
6735
+ url: z$1.string(),
6736
+ mediaType: z$1.string(),
6737
+ providerMetadata: z$1.optional(providerMetadataSchema)
6631
6738
  }),
6632
- z.looseObject({
6633
- type: z.literal("steering-message"),
6634
- id: z.string(),
6635
- parts: z.array(z.union([z.looseObject({
6636
- type: z.literal("text"),
6637
- text: z.string(),
6638
- providerMetadata: providerMetadataSchema.optional()
6639
- }), z.looseObject({
6640
- type: z.literal("file"),
6641
- mediaType: z.string(),
6642
- url: z.string(),
6643
- filename: z.string().optional(),
6644
- providerReference: z.record(z.string(), z.string()).optional(),
6645
- providerMetadata: providerMetadataSchema.optional()
6739
+ z$1.looseObject({
6740
+ type: z$1.literal("steering-message"),
6741
+ id: z$1.string(),
6742
+ parts: z$1.array(z$1.union([z$1.looseObject({
6743
+ type: z$1.literal("text"),
6744
+ text: z$1.string(),
6745
+ providerMetadata: z$1.optional(providerMetadataSchema)
6746
+ }), z$1.looseObject({
6747
+ type: z$1.literal("file"),
6748
+ mediaType: z$1.string(),
6749
+ url: z$1.string(),
6750
+ filename: z$1.optional(z$1.string()),
6751
+ providerReference: z$1.optional(z$1.record(z$1.string(), z$1.string())),
6752
+ providerMetadata: z$1.optional(providerMetadataSchema)
6646
6753
  })]))
6647
6754
  }),
6648
- z.looseObject({
6649
- type: z.custom((value) => typeof value === "string" && value.startsWith("data-"), { message: "Type must start with \"data-\"" }),
6650
- id: z.string().optional(),
6651
- data: z.unknown(),
6652
- transient: z.boolean().optional()
6755
+ z$1.looseObject({
6756
+ type: z$1.custom((value) => typeof value === "string" && value.startsWith("data-"), { message: "Type must start with \"data-\"" }),
6757
+ id: z$1.optional(z$1.string()),
6758
+ data: z$1.unknown(),
6759
+ transient: z$1.optional(z$1.boolean())
6653
6760
  }),
6654
- z.looseObject({ type: z.literal("start-step") }),
6655
- z.looseObject({ type: z.literal("finish-step") }),
6656
- z.looseObject({ type: z.literal("reset-step") }),
6657
- z.looseObject({
6658
- type: z.literal("start"),
6659
- messageId: z.string().optional(),
6660
- messageMetadata: z.unknown().optional()
6761
+ z$1.looseObject({ type: z$1.literal("start-step") }),
6762
+ z$1.looseObject({ type: z$1.literal("finish-step") }),
6763
+ z$1.looseObject({ type: z$1.literal("reset-step") }),
6764
+ z$1.looseObject({
6765
+ type: z$1.literal("start"),
6766
+ messageId: z$1.optional(z$1.string()),
6767
+ messageMetadata: z$1.optional(z$1.unknown())
6661
6768
  }),
6662
- z.looseObject({
6663
- type: z.literal("finish"),
6664
- finishReason: z.enum([
6769
+ z$1.looseObject({
6770
+ type: z$1.literal("finish"),
6771
+ finishReason: z$1.optional(z$1.enum([
6665
6772
  "stop",
6666
6773
  "length",
6667
6774
  "content-filter",
@@ -6669,16 +6776,16 @@ const uiMessageChunkSchema = lazySchema(() => zodSchema$1(z.union([
6669
6776
  "error",
6670
6777
  "interrupted",
6671
6778
  "other"
6672
- ]).optional(),
6673
- messageMetadata: z.unknown().optional()
6779
+ ])),
6780
+ messageMetadata: z$1.optional(z$1.unknown())
6674
6781
  }),
6675
- z.looseObject({
6676
- type: z.literal("abort"),
6677
- reason: z.string().optional()
6782
+ z$1.looseObject({
6783
+ type: z$1.literal("abort"),
6784
+ reason: z$1.optional(z$1.string())
6678
6785
  }),
6679
- z.looseObject({
6680
- type: z.literal("message-metadata"),
6681
- messageMetadata: z.unknown()
6786
+ z$1.looseObject({
6787
+ type: z$1.literal("message-metadata"),
6788
+ messageMetadata: z$1.unknown()
6682
6789
  })
6683
6790
  ])));
6684
6791
  function isDataUIMessageChunk(chunk) {
@@ -7724,6 +7831,7 @@ function convertUserMessageToUIParts(message) {
7724
7831
  function toUIMessageStream({ stream, tools, sendReasoning = true, sendSources = false, sendStart = true, sendFinish = true, onError = () => "An error occurred.", messageMetadata, originalMessages, generateMessageId, onStepEnd, onStepFinish, onEnd, onFinish }) {
7725
7832
  let outcome = { status: "unknown" };
7726
7833
  let hasFatalFailure = false;
7834
+ const invalidToolCallIds = /* @__PURE__ */ new Set();
7727
7835
  const setSourceOutcome = (newOutcome) => {
7728
7836
  if (!hasFatalFailure && outcome.status !== "completed" && outcome.status !== "aborted" && newOutcome.status !== "unknown" && (outcome.status === "unknown" || newOutcome.status !== "failed")) outcome = newOutcome;
7729
7837
  };
@@ -7775,8 +7883,10 @@ function toUIMessageStream({ stream, tools, sendReasoning = true, sendSources =
7775
7883
  }
7776
7884
  }).pipeThrough(new TransformStream({ transform: async (part, controller) => {
7777
7885
  try {
7886
+ if (part.type === "tool-call" && part.invalid) invalidToolCallIds.add(part.toolCallId);
7887
+ const isInvalidToolCallError = part.type === "tool-error" && !part.providerExecuted && invalidToolCallIds.delete(part.toolCallId);
7778
7888
  const messageMetadataValue = messageMetadata?.({ part });
7779
- const uiMessageChunk = toUIMessageChunk(part, {
7889
+ const uiMessageChunk = isInvalidToolCallError ? void 0 : toUIMessageChunk(part, {
7780
7890
  tools,
7781
7891
  sendReasoning,
7782
7892
  sendSources,
@@ -11528,8 +11638,8 @@ function convertUserContentUIPart(part) {
11528
11638
  }
11529
11639
  //#endregion
11530
11640
  //#region src/ui/validate-ui-messages.ts
11531
- const toolMetadataSchema = z.record(z.string(), jsonValueSchema.optional());
11532
- const providerReferenceSchema$1 = z.record(z.string(), z.string());
11641
+ const toolMetadataSchema = z$1.record(z$1.string(), z$1.optional(jsonValueSchema));
11642
+ const providerReferenceSchema$1 = z$1.record(z$1.string(), z$1.string());
11533
11643
  function isEmptyObject(value) {
11534
11644
  return value != null && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === 0;
11535
11645
  }
@@ -11545,312 +11655,314 @@ function getToolPartInputSchemaInput(toolPart) {
11545
11655
  return toolPart.approval != null && Object.prototype.hasOwnProperty.call(toolPart.approval, "inputSchemaInput") ? { value: toolPart.approval.inputSchemaInput } : void 0;
11546
11656
  }
11547
11657
  const uiMessagesSchema = lazySchema(() => {
11548
- const approvalRequestedSchema = z.object({
11549
- id: z.string(),
11550
- approved: z.never().optional(),
11551
- descriptor: z.unknown().optional(),
11552
- requestReason: z.string().optional(),
11553
- reason: z.never().optional(),
11554
- isAutomatic: z.boolean().optional(),
11555
- signature: z.string().optional(),
11556
- inputSchemaInput: z.unknown().optional()
11658
+ const approvalRequestedSchema = z$1.object({
11659
+ id: z$1.string(),
11660
+ approved: z$1.optional(z$1.never()),
11661
+ descriptor: z$1.optional(z$1.unknown()),
11662
+ requestReason: z$1.optional(z$1.string()),
11663
+ reason: z$1.optional(z$1.never()),
11664
+ isAutomatic: z$1.optional(z$1.boolean()),
11665
+ signature: z$1.optional(z$1.string()),
11666
+ inputSchemaInput: z$1.optional(z$1.unknown())
11557
11667
  });
11558
- const approvalRespondedSchema = approvalRequestedSchema.extend({
11559
- approved: z.boolean(),
11560
- reason: z.string().optional()
11668
+ const approvalRespondedSchema = z$1.extend(approvalRequestedSchema, {
11669
+ approved: z$1.boolean(),
11670
+ reason: z$1.optional(z$1.string())
11561
11671
  });
11562
- const approvalGrantedSchema = approvalRespondedSchema.extend({ approved: z.literal(true) });
11563
- const approvalDeniedSchema = approvalRespondedSchema.extend({ approved: z.literal(false) });
11564
- return zodSchema$1(z.array(z.object({
11565
- id: z.string(),
11566
- role: z.enum([
11672
+ const approvalGrantedSchema = z$1.extend(approvalRespondedSchema, { approved: z$1.literal(true) });
11673
+ const approvalDeniedSchema = z$1.extend(approvalRespondedSchema, { approved: z$1.literal(false) });
11674
+ return zodSchema$1(z$1.array(z$1.object({
11675
+ id: z$1.string(),
11676
+ role: z$1.enum([
11567
11677
  "system",
11568
11678
  "user",
11569
11679
  "assistant"
11570
11680
  ]),
11571
- metadata: z.unknown().optional(),
11572
- parts: z.array(z.union([
11573
- z.object({
11574
- type: z.literal("text"),
11575
- text: z.string(),
11576
- citations: z.array(citationSchema).optional(),
11577
- state: z.enum(["streaming", "done"]).optional(),
11578
- providerMetadata: providerMetadataSchema.optional()
11681
+ metadata: z$1.optional(z$1.unknown()),
11682
+ parts: z$1.array(z$1.union([
11683
+ z$1.object({
11684
+ type: z$1.literal("text"),
11685
+ text: z$1.string(),
11686
+ citations: z$1.optional(z$1.array(citationSchema)),
11687
+ state: z$1.optional(z$1.enum(["streaming", "done"])),
11688
+ providerMetadata: z$1.optional(providerMetadataSchema)
11579
11689
  }),
11580
- z.object({
11581
- type: z.literal("reasoning"),
11582
- id: z.string().optional(),
11583
- text: z.string(),
11584
- state: z.enum(["streaming", "done"]).optional(),
11585
- providerMetadata: providerMetadataSchema.optional()
11690
+ z$1.object({
11691
+ type: z$1.literal("reasoning"),
11692
+ id: z$1.optional(z$1.string()),
11693
+ text: z$1.string(),
11694
+ state: z$1.optional(z$1.enum(["streaming", "done"])),
11695
+ providerMetadata: z$1.optional(providerMetadataSchema)
11586
11696
  }),
11587
- z.object({
11588
- type: z.literal("custom"),
11589
- kind: z.string(),
11590
- providerMetadata: providerMetadataSchema.optional()
11697
+ z$1.object({
11698
+ type: z$1.literal("custom"),
11699
+ kind: z$1.string(),
11700
+ providerMetadata: z$1.optional(providerMetadataSchema)
11591
11701
  }),
11592
- z.object({
11593
- type: z.literal("source-url"),
11594
- sourceId: z.string(),
11595
- url: z.string(),
11596
- title: z.string().optional(),
11597
- providerMetadata: providerMetadataSchema.optional()
11702
+ z$1.object({
11703
+ type: z$1.literal("source-url"),
11704
+ sourceId: z$1.string(),
11705
+ url: z$1.string(),
11706
+ title: z$1.optional(z$1.string()),
11707
+ providerMetadata: z$1.optional(providerMetadataSchema)
11598
11708
  }),
11599
- z.object({
11600
- type: z.literal("source-document"),
11601
- sourceId: z.string(),
11602
- mediaType: z.string(),
11603
- title: z.string(),
11604
- filename: z.string().optional(),
11605
- providerMetadata: providerMetadataSchema.optional()
11709
+ z$1.object({
11710
+ type: z$1.literal("source-document"),
11711
+ sourceId: z$1.string(),
11712
+ mediaType: z$1.string(),
11713
+ title: z$1.string(),
11714
+ filename: z$1.optional(z$1.string()),
11715
+ providerMetadata: z$1.optional(providerMetadataSchema)
11606
11716
  }),
11607
- z.object({
11608
- type: z.literal("file"),
11609
- mediaType: z.string(),
11610
- filename: z.string().optional(),
11611
- url: z.string(),
11612
- providerReference: providerReferenceSchema$1.optional(),
11613
- providerMetadata: providerMetadataSchema.optional()
11717
+ z$1.object({
11718
+ type: z$1.literal("file"),
11719
+ mediaType: z$1.string(),
11720
+ filename: z$1.optional(z$1.string()),
11721
+ url: z$1.string(),
11722
+ providerReference: z$1.optional(providerReferenceSchema$1),
11723
+ providerMetadata: z$1.optional(providerMetadataSchema)
11614
11724
  }),
11615
- z.object({
11616
- type: z.literal("reasoning-file"),
11617
- mediaType: z.string(),
11618
- url: z.string(),
11619
- providerMetadata: providerMetadataSchema.optional()
11725
+ z$1.object({
11726
+ type: z$1.literal("reasoning-file"),
11727
+ mediaType: z$1.string(),
11728
+ url: z$1.string(),
11729
+ providerMetadata: z$1.optional(providerMetadataSchema)
11620
11730
  }),
11621
- z.object({
11622
- type: z.literal("steering-message"),
11623
- id: z.string(),
11624
- parts: z.array(z.union([z.object({
11625
- type: z.literal("text"),
11626
- text: z.string(),
11627
- providerMetadata: providerMetadataSchema.optional()
11628
- }), z.object({
11629
- type: z.literal("file"),
11630
- mediaType: z.string(),
11631
- filename: z.string().optional(),
11632
- url: z.string(),
11633
- providerReference: providerReferenceSchema$1.optional(),
11634
- providerMetadata: providerMetadataSchema.optional()
11731
+ z$1.object({
11732
+ type: z$1.literal("steering-message"),
11733
+ id: z$1.string(),
11734
+ parts: z$1.array(z$1.union([z$1.object({
11735
+ type: z$1.literal("text"),
11736
+ text: z$1.string(),
11737
+ providerMetadata: z$1.optional(providerMetadataSchema)
11738
+ }), z$1.object({
11739
+ type: z$1.literal("file"),
11740
+ mediaType: z$1.string(),
11741
+ filename: z$1.optional(z$1.string()),
11742
+ url: z$1.string(),
11743
+ providerReference: z$1.optional(providerReferenceSchema$1),
11744
+ providerMetadata: z$1.optional(providerMetadataSchema)
11635
11745
  })]))
11636
11746
  }),
11637
- z.object({ type: z.literal("step-start") }),
11638
- z.object({
11639
- type: z.string().startsWith("data-"),
11640
- id: z.string().optional(),
11641
- data: z.unknown()
11747
+ z$1.object({ type: z$1.literal("step-start") }),
11748
+ z$1.object({
11749
+ type: z$1.string().check(z$1.startsWith("data-")),
11750
+ id: z$1.optional(z$1.string()),
11751
+ data: z$1.unknown()
11642
11752
  }),
11643
- z.object({
11644
- type: z.literal("dynamic-tool"),
11645
- dynamic: z.literal(false).optional(),
11646
- toolName: z.string(),
11647
- toolCallId: z.string(),
11648
- title: z.string().optional(),
11649
- toolMetadata: toolMetadataSchema.optional(),
11650
- state: z.literal("input-streaming"),
11651
- input: z.unknown().optional(),
11652
- rawInput: z.string().optional(),
11653
- inputEncoding: z.enum(["json", "text"]).optional(),
11654
- providerExecuted: z.boolean().optional(),
11655
- callProviderMetadata: providerMetadataSchema.optional(),
11656
- output: z.never().optional(),
11657
- errorText: z.never().optional(),
11658
- approval: z.never().optional()
11753
+ z$1.object({
11754
+ type: z$1.literal("dynamic-tool"),
11755
+ dynamic: z$1.optional(z$1.literal(false)),
11756
+ toolName: z$1.string(),
11757
+ toolCallId: z$1.string(),
11758
+ title: z$1.optional(z$1.string()),
11759
+ toolMetadata: z$1.optional(toolMetadataSchema),
11760
+ state: z$1.literal("input-streaming"),
11761
+ input: z$1.optional(z$1.unknown()),
11762
+ rawInput: z$1.optional(z$1.string()),
11763
+ inputEncoding: z$1.optional(z$1.enum(["json", "text"])),
11764
+ providerExecuted: z$1.optional(z$1.boolean()),
11765
+ callProviderMetadata: z$1.optional(providerMetadataSchema),
11766
+ output: z$1.optional(z$1.never()),
11767
+ errorText: z$1.optional(z$1.never()),
11768
+ approval: z$1.optional(z$1.never())
11659
11769
  }),
11660
- z.object({
11661
- type: z.literal("dynamic-tool"),
11662
- dynamic: z.literal(false).optional(),
11663
- toolName: z.string(),
11664
- toolCallId: z.string(),
11665
- title: z.string().optional(),
11666
- toolMetadata: toolMetadataSchema.optional(),
11667
- state: z.literal("input-available"),
11668
- input: z.unknown(),
11669
- providerExecuted: z.boolean().optional(),
11670
- output: z.never().optional(),
11671
- errorText: z.never().optional(),
11672
- callProviderMetadata: providerMetadataSchema.optional(),
11673
- approval: z.never().optional()
11770
+ z$1.object({
11771
+ type: z$1.literal("dynamic-tool"),
11772
+ dynamic: z$1.optional(z$1.literal(false)),
11773
+ toolName: z$1.string(),
11774
+ toolCallId: z$1.string(),
11775
+ title: z$1.optional(z$1.string()),
11776
+ toolMetadata: z$1.optional(toolMetadataSchema),
11777
+ state: z$1.literal("input-available"),
11778
+ input: z$1.unknown(),
11779
+ providerExecuted: z$1.optional(z$1.boolean()),
11780
+ output: z$1.optional(z$1.never()),
11781
+ errorText: z$1.optional(z$1.never()),
11782
+ callProviderMetadata: z$1.optional(providerMetadataSchema),
11783
+ approval: z$1.optional(z$1.never())
11674
11784
  }),
11675
- z.object({
11676
- type: z.literal("dynamic-tool"),
11677
- dynamic: z.literal(false).optional(),
11678
- toolName: z.string(),
11679
- toolCallId: z.string(),
11680
- title: z.string().optional(),
11681
- toolMetadata: toolMetadataSchema.optional(),
11682
- state: z.literal("approval-requested"),
11683
- input: z.unknown(),
11684
- providerExecuted: z.boolean().optional(),
11685
- output: z.never().optional(),
11686
- errorText: z.never().optional(),
11687
- callProviderMetadata: providerMetadataSchema.optional(),
11785
+ z$1.object({
11786
+ type: z$1.literal("dynamic-tool"),
11787
+ dynamic: z$1.optional(z$1.literal(false)),
11788
+ toolName: z$1.string(),
11789
+ toolCallId: z$1.string(),
11790
+ title: z$1.optional(z$1.string()),
11791
+ toolMetadata: z$1.optional(toolMetadataSchema),
11792
+ state: z$1.literal("approval-requested"),
11793
+ input: z$1.unknown(),
11794
+ providerExecuted: z$1.optional(z$1.boolean()),
11795
+ output: z$1.optional(z$1.never()),
11796
+ errorText: z$1.optional(z$1.never()),
11797
+ callProviderMetadata: z$1.optional(providerMetadataSchema),
11688
11798
  approval: approvalRequestedSchema
11689
11799
  }),
11690
- z.object({
11691
- type: z.literal("dynamic-tool"),
11692
- dynamic: z.literal(false).optional(),
11693
- toolName: z.string(),
11694
- toolCallId: z.string(),
11695
- title: z.string().optional(),
11696
- toolMetadata: toolMetadataSchema.optional(),
11697
- state: z.literal("approval-responded"),
11698
- input: z.unknown(),
11699
- providerExecuted: z.boolean().optional(),
11700
- output: z.never().optional(),
11701
- errorText: z.never().optional(),
11702
- callProviderMetadata: providerMetadataSchema.optional(),
11800
+ z$1.object({
11801
+ type: z$1.literal("dynamic-tool"),
11802
+ dynamic: z$1.optional(z$1.literal(false)),
11803
+ toolName: z$1.string(),
11804
+ toolCallId: z$1.string(),
11805
+ title: z$1.optional(z$1.string()),
11806
+ toolMetadata: z$1.optional(toolMetadataSchema),
11807
+ state: z$1.literal("approval-responded"),
11808
+ input: z$1.unknown(),
11809
+ providerExecuted: z$1.optional(z$1.boolean()),
11810
+ output: z$1.optional(z$1.never()),
11811
+ errorText: z$1.optional(z$1.never()),
11812
+ callProviderMetadata: z$1.optional(providerMetadataSchema),
11703
11813
  approval: approvalRespondedSchema
11704
11814
  }),
11705
- z.object({
11706
- type: z.literal("dynamic-tool"),
11707
- dynamic: z.literal(false).optional(),
11708
- toolName: z.string(),
11709
- toolCallId: z.string(),
11710
- title: z.string().optional(),
11711
- toolMetadata: toolMetadataSchema.optional(),
11712
- state: z.literal("output-available"),
11713
- input: z.unknown(),
11714
- providerExecuted: z.boolean().optional(),
11715
- output: z.unknown(),
11716
- errorText: z.never().optional(),
11717
- callProviderMetadata: providerMetadataSchema.optional(),
11718
- resultProviderMetadata: providerMetadataSchema.optional(),
11719
- preliminary: z.boolean().optional(),
11720
- approval: approvalGrantedSchema.optional()
11815
+ z$1.object({
11816
+ type: z$1.literal("dynamic-tool"),
11817
+ dynamic: z$1.optional(z$1.literal(false)),
11818
+ toolName: z$1.string(),
11819
+ toolCallId: z$1.string(),
11820
+ title: z$1.optional(z$1.string()),
11821
+ toolMetadata: z$1.optional(toolMetadataSchema),
11822
+ state: z$1.literal("output-available"),
11823
+ input: z$1.unknown(),
11824
+ providerExecuted: z$1.optional(z$1.boolean()),
11825
+ output: z$1.unknown(),
11826
+ errorText: z$1.optional(z$1.never()),
11827
+ callProviderMetadata: z$1.optional(providerMetadataSchema),
11828
+ resultProviderMetadata: z$1.optional(providerMetadataSchema),
11829
+ preliminary: z$1.optional(z$1.boolean()),
11830
+ approval: z$1.optional(approvalGrantedSchema)
11721
11831
  }),
11722
- z.object({
11723
- type: z.literal("dynamic-tool"),
11724
- dynamic: z.literal(false).optional(),
11725
- toolName: z.string(),
11726
- toolCallId: z.string(),
11727
- title: z.string().optional(),
11728
- toolMetadata: toolMetadataSchema.optional(),
11729
- state: z.literal("output-error"),
11730
- input: z.unknown().optional(),
11731
- rawInput: z.unknown().optional(),
11732
- providerExecuted: z.boolean().optional(),
11733
- output: z.never().optional(),
11734
- errorText: z.string(),
11735
- callProviderMetadata: providerMetadataSchema.optional(),
11736
- resultProviderMetadata: providerMetadataSchema.optional(),
11737
- approval: approvalGrantedSchema.optional()
11832
+ z$1.object({
11833
+ type: z$1.literal("dynamic-tool"),
11834
+ dynamic: z$1.optional(z$1.literal(false)),
11835
+ toolName: z$1.string(),
11836
+ toolCallId: z$1.string(),
11837
+ title: z$1.optional(z$1.string()),
11838
+ toolMetadata: z$1.optional(toolMetadataSchema),
11839
+ state: z$1.literal("output-error"),
11840
+ input: z$1.optional(z$1.unknown()),
11841
+ rawInput: z$1.optional(z$1.unknown()),
11842
+ providerExecuted: z$1.optional(z$1.boolean()),
11843
+ output: z$1.optional(z$1.never()),
11844
+ errorText: z$1.string(),
11845
+ callProviderMetadata: z$1.optional(providerMetadataSchema),
11846
+ resultProviderMetadata: z$1.optional(providerMetadataSchema),
11847
+ approval: z$1.optional(approvalGrantedSchema)
11738
11848
  }),
11739
- z.object({
11740
- type: z.literal("dynamic-tool"),
11741
- dynamic: z.literal(false).optional(),
11742
- toolName: z.string(),
11743
- toolCallId: z.string(),
11744
- title: z.string().optional(),
11745
- toolMetadata: toolMetadataSchema.optional(),
11746
- state: z.literal("output-denied"),
11747
- input: z.unknown(),
11748
- providerExecuted: z.boolean().optional(),
11749
- output: z.never().optional(),
11750
- errorText: z.never().optional(),
11751
- callProviderMetadata: providerMetadataSchema.optional(),
11849
+ z$1.object({
11850
+ type: z$1.literal("dynamic-tool"),
11851
+ dynamic: z$1.optional(z$1.literal(false)),
11852
+ toolName: z$1.string(),
11853
+ toolCallId: z$1.string(),
11854
+ title: z$1.optional(z$1.string()),
11855
+ toolMetadata: z$1.optional(toolMetadataSchema),
11856
+ state: z$1.literal("output-denied"),
11857
+ input: z$1.unknown(),
11858
+ providerExecuted: z$1.optional(z$1.boolean()),
11859
+ output: z$1.optional(z$1.never()),
11860
+ errorText: z$1.optional(z$1.never()),
11861
+ callProviderMetadata: z$1.optional(providerMetadataSchema),
11752
11862
  approval: approvalDeniedSchema
11753
11863
  }),
11754
- z.object({
11755
- type: z.string().startsWith("tool-"),
11756
- toolCallId: z.string(),
11757
- title: z.string().optional(),
11758
- toolMetadata: toolMetadataSchema.optional(),
11759
- state: z.literal("input-streaming"),
11760
- providerExecuted: z.boolean().optional(),
11761
- callProviderMetadata: providerMetadataSchema.optional(),
11762
- input: z.unknown().optional(),
11763
- rawInput: z.string().optional(),
11764
- inputEncoding: z.enum(["json", "text"]).optional(),
11765
- output: z.never().optional(),
11766
- errorText: z.never().optional(),
11767
- approval: z.never().optional()
11864
+ z$1.object({
11865
+ type: z$1.string().check(z$1.startsWith("tool-")),
11866
+ toolCallId: z$1.string(),
11867
+ title: z$1.optional(z$1.string()),
11868
+ toolMetadata: z$1.optional(toolMetadataSchema),
11869
+ state: z$1.literal("input-streaming"),
11870
+ providerExecuted: z$1.optional(z$1.boolean()),
11871
+ callProviderMetadata: z$1.optional(providerMetadataSchema),
11872
+ input: z$1.optional(z$1.unknown()),
11873
+ rawInput: z$1.optional(z$1.string()),
11874
+ inputEncoding: z$1.optional(z$1.enum(["json", "text"])),
11875
+ output: z$1.optional(z$1.never()),
11876
+ errorText: z$1.optional(z$1.never()),
11877
+ approval: z$1.optional(z$1.never())
11768
11878
  }),
11769
- z.object({
11770
- type: z.string().startsWith("tool-"),
11771
- toolCallId: z.string(),
11772
- title: z.string().optional(),
11773
- toolMetadata: toolMetadataSchema.optional(),
11774
- state: z.literal("input-available"),
11775
- providerExecuted: z.boolean().optional(),
11776
- input: z.unknown(),
11777
- output: z.never().optional(),
11778
- errorText: z.never().optional(),
11779
- callProviderMetadata: providerMetadataSchema.optional(),
11780
- approval: z.never().optional()
11879
+ z$1.object({
11880
+ type: z$1.string().check(z$1.startsWith("tool-")),
11881
+ toolCallId: z$1.string(),
11882
+ title: z$1.optional(z$1.string()),
11883
+ toolMetadata: z$1.optional(toolMetadataSchema),
11884
+ state: z$1.literal("input-available"),
11885
+ providerExecuted: z$1.optional(z$1.boolean()),
11886
+ input: z$1.unknown(),
11887
+ output: z$1.optional(z$1.never()),
11888
+ errorText: z$1.optional(z$1.never()),
11889
+ callProviderMetadata: z$1.optional(providerMetadataSchema),
11890
+ approval: z$1.optional(z$1.never())
11781
11891
  }),
11782
- z.object({
11783
- type: z.string().startsWith("tool-"),
11784
- toolCallId: z.string(),
11785
- title: z.string().optional(),
11786
- toolMetadata: toolMetadataSchema.optional(),
11787
- state: z.literal("approval-requested"),
11788
- input: z.unknown(),
11789
- providerExecuted: z.boolean().optional(),
11790
- output: z.never().optional(),
11791
- errorText: z.never().optional(),
11792
- callProviderMetadata: providerMetadataSchema.optional(),
11892
+ z$1.object({
11893
+ type: z$1.string().check(z$1.startsWith("tool-")),
11894
+ toolCallId: z$1.string(),
11895
+ title: z$1.optional(z$1.string()),
11896
+ toolMetadata: z$1.optional(toolMetadataSchema),
11897
+ state: z$1.literal("approval-requested"),
11898
+ input: z$1.unknown(),
11899
+ providerExecuted: z$1.optional(z$1.boolean()),
11900
+ output: z$1.optional(z$1.never()),
11901
+ errorText: z$1.optional(z$1.never()),
11902
+ callProviderMetadata: z$1.optional(providerMetadataSchema),
11793
11903
  approval: approvalRequestedSchema
11794
11904
  }),
11795
- z.object({
11796
- type: z.string().startsWith("tool-"),
11797
- toolCallId: z.string(),
11798
- title: z.string().optional(),
11799
- toolMetadata: toolMetadataSchema.optional(),
11800
- state: z.literal("approval-responded"),
11801
- input: z.unknown(),
11802
- providerExecuted: z.boolean().optional(),
11803
- output: z.never().optional(),
11804
- errorText: z.never().optional(),
11805
- callProviderMetadata: providerMetadataSchema.optional(),
11905
+ z$1.object({
11906
+ type: z$1.string().check(z$1.startsWith("tool-")),
11907
+ toolCallId: z$1.string(),
11908
+ title: z$1.optional(z$1.string()),
11909
+ toolMetadata: z$1.optional(toolMetadataSchema),
11910
+ state: z$1.literal("approval-responded"),
11911
+ input: z$1.unknown(),
11912
+ providerExecuted: z$1.optional(z$1.boolean()),
11913
+ output: z$1.optional(z$1.never()),
11914
+ errorText: z$1.optional(z$1.never()),
11915
+ callProviderMetadata: z$1.optional(providerMetadataSchema),
11806
11916
  approval: approvalRespondedSchema
11807
11917
  }),
11808
- z.object({
11809
- type: z.string().startsWith("tool-"),
11810
- toolCallId: z.string(),
11811
- title: z.string().optional(),
11812
- toolMetadata: toolMetadataSchema.optional(),
11813
- state: z.literal("output-available"),
11814
- providerExecuted: z.boolean().optional(),
11815
- input: z.unknown(),
11816
- output: z.unknown(),
11817
- errorText: z.never().optional(),
11818
- callProviderMetadata: providerMetadataSchema.optional(),
11819
- resultProviderMetadata: providerMetadataSchema.optional(),
11820
- preliminary: z.boolean().optional(),
11821
- approval: approvalGrantedSchema.optional()
11918
+ z$1.object({
11919
+ type: z$1.string().check(z$1.startsWith("tool-")),
11920
+ toolCallId: z$1.string(),
11921
+ title: z$1.optional(z$1.string()),
11922
+ toolMetadata: z$1.optional(toolMetadataSchema),
11923
+ state: z$1.literal("output-available"),
11924
+ providerExecuted: z$1.optional(z$1.boolean()),
11925
+ input: z$1.unknown(),
11926
+ output: z$1.unknown(),
11927
+ errorText: z$1.optional(z$1.never()),
11928
+ callProviderMetadata: z$1.optional(providerMetadataSchema),
11929
+ resultProviderMetadata: z$1.optional(providerMetadataSchema),
11930
+ preliminary: z$1.optional(z$1.boolean()),
11931
+ approval: z$1.optional(approvalGrantedSchema)
11822
11932
  }),
11823
- z.object({
11824
- type: z.string().startsWith("tool-"),
11825
- toolCallId: z.string(),
11826
- title: z.string().optional(),
11827
- toolMetadata: toolMetadataSchema.optional(),
11828
- state: z.literal("output-error"),
11829
- providerExecuted: z.boolean().optional(),
11830
- input: z.unknown().optional(),
11831
- rawInput: z.unknown().optional(),
11832
- output: z.never().optional(),
11833
- errorText: z.string(),
11834
- callProviderMetadata: providerMetadataSchema.optional(),
11835
- resultProviderMetadata: providerMetadataSchema.optional(),
11836
- approval: approvalGrantedSchema.optional()
11933
+ z$1.object({
11934
+ type: z$1.string().check(z$1.startsWith("tool-")),
11935
+ toolCallId: z$1.string(),
11936
+ title: z$1.optional(z$1.string()),
11937
+ toolMetadata: z$1.optional(toolMetadataSchema),
11938
+ state: z$1.literal("output-error"),
11939
+ providerExecuted: z$1.optional(z$1.boolean()),
11940
+ input: z$1.optional(z$1.unknown()),
11941
+ rawInput: z$1.optional(z$1.unknown()),
11942
+ output: z$1.optional(z$1.never()),
11943
+ errorText: z$1.string(),
11944
+ callProviderMetadata: z$1.optional(providerMetadataSchema),
11945
+ resultProviderMetadata: z$1.optional(providerMetadataSchema),
11946
+ approval: z$1.optional(approvalGrantedSchema)
11837
11947
  }),
11838
- z.object({
11839
- type: z.string().startsWith("tool-"),
11840
- toolCallId: z.string(),
11841
- title: z.string().optional(),
11842
- toolMetadata: toolMetadataSchema.optional(),
11843
- state: z.literal("output-denied"),
11844
- providerExecuted: z.boolean().optional(),
11845
- input: z.unknown(),
11846
- output: z.never().optional(),
11847
- errorText: z.never().optional(),
11848
- callProviderMetadata: providerMetadataSchema.optional(),
11948
+ z$1.object({
11949
+ type: z$1.string().check(z$1.startsWith("tool-")),
11950
+ toolCallId: z$1.string(),
11951
+ title: z$1.optional(z$1.string()),
11952
+ toolMetadata: z$1.optional(toolMetadataSchema),
11953
+ state: z$1.literal("output-denied"),
11954
+ providerExecuted: z$1.optional(z$1.boolean()),
11955
+ input: z$1.unknown(),
11956
+ output: z$1.optional(z$1.never()),
11957
+ errorText: z$1.optional(z$1.never()),
11958
+ callProviderMetadata: z$1.optional(providerMetadataSchema),
11849
11959
  approval: approvalDeniedSchema
11850
11960
  })
11851
11961
  ]))
11852
- }).superRefine((message, context) => {
11853
- if (message.role !== "assistant" && message.parts.length === 0) context.addIssue({
11962
+ }).check((context) => {
11963
+ const message = context.value;
11964
+ if (message.role !== "assistant" && message.parts.length === 0) context.issues.push({
11965
+ continue: true,
11854
11966
  origin: "array",
11855
11967
  code: "too_small",
11856
11968
  minimum: 1,
@@ -11859,7 +11971,7 @@ const uiMessagesSchema = lazySchema(() => {
11859
11971
  path: ["parts"],
11860
11972
  message: "Message must contain at least one part"
11861
11973
  });
11862
- })).nonempty("Messages array must not be empty"));
11974
+ })).check(z$1.minLength(1, "Messages array must not be empty")));
11863
11975
  });
11864
11976
  async function safeValidateUIMessagesInternal({ messages, metadataSchema, dataSchemas, tools, experimental_refineToolInput }, { convertMissingTerminalToolsToDynamic }) {
11865
11977
  try {
@@ -18461,23 +18573,23 @@ var RealtimeCommandTracker = class {
18461
18573
  };
18462
18574
  //#endregion
18463
18575
  //#region src/realtime/validate-realtime-setup.ts
18464
- const setupSchema = z.object({
18465
- token: z.string().refine((value) => value.trim().length > 0),
18466
- url: z.string().refine((value) => {
18576
+ const setupSchema = z$1.object({
18577
+ token: z$1.string().check(z$1.refine((value) => value.trim().length > 0)),
18578
+ url: z$1.string().check(z$1.refine((value) => {
18467
18579
  try {
18468
18580
  const url = new URL(value);
18469
18581
  return (url.protocol === "ws:" || url.protocol === "wss:") && url.hostname !== "";
18470
18582
  } catch {
18471
18583
  return false;
18472
18584
  }
18473
- }),
18474
- expiresAt: z.number().positive().max(Number.MAX_SAFE_INTEGER).optional(),
18475
- tools: z.array(z.object({
18476
- type: z.literal("function"),
18477
- name: z.string().min(1),
18478
- description: z.string().optional(),
18479
- parameters: z.record(z.string(), z.unknown())
18480
- })).optional()
18585
+ })),
18586
+ expiresAt: z$1.optional(z$1.number().check(z$1.positive()).check(z$1.maximum(Number.MAX_SAFE_INTEGER))),
18587
+ tools: z$1.optional(z$1.array(z$1.object({
18588
+ type: z$1.literal("function"),
18589
+ name: z$1.string().check(z$1.minLength(1)),
18590
+ description: z$1.optional(z$1.string()),
18591
+ parameters: z$1.record(z$1.string(), z$1.unknown())
18592
+ })))
18481
18593
  });
18482
18594
  function validateRealtimeSetup(payload) {
18483
18595
  const result = setupSchema.safeParse(payload);
@@ -21014,7 +21126,11 @@ var AbstractChat = class {
21014
21126
  get id() {
21015
21127
  return this._id ??= this.generateId();
21016
21128
  }
21017
- constructor({ generateId = generateId$1, id, transport = new DefaultChatTransport(), messageMetadataSchema, dataPartSchemas, state, onError, onToolCall, onFinish, onData, sendAutomaticallyWhen }) {
21129
+ constructor({ generateId = generateId$1, id, transport = new DefaultChatTransport(), messageMetadataSchema, dataPartSchemas, state, onError, onToolCall, onFinish, onData, sendAutomaticallyWhen, experimental_queue = false }) {
21130
+ this.queuedMessagesFallback = [];
21131
+ this.queuedMessageOptions = /* @__PURE__ */ new Map();
21132
+ this.isQueuePaused = false;
21133
+ this.pendingAutomaticDecisions = [];
21018
21134
  this.pendingMessagePreparations = /* @__PURE__ */ new Set();
21019
21135
  this.interruptedMessageIds = /* @__PURE__ */ new Set();
21020
21136
  this.activeResponse = void 0;
@@ -21023,6 +21139,20 @@ var AbstractChat = class {
21023
21139
  this.jobExecutor = new SerialJobExecutor();
21024
21140
  this.activeStopCount = 0;
21025
21141
  this.stopGeneration = 0;
21142
+ this.experimental_removeQueuedMessage = (id) => {
21143
+ this.queuedMessageOptions.delete(id);
21144
+ this.setQueuedMessages(this.experimental_queuedMessages.filter((message) => message.id !== id));
21145
+ };
21146
+ this.experimental_sendQueuedMessageNow = async (id) => {
21147
+ const message = this.experimental_queuedMessages.find((message) => message.id === id);
21148
+ if (message == null) return;
21149
+ this.setQueuedMessages([message, ...this.experimental_queuedMessages.filter((queued) => queued.id !== id)]);
21150
+ await this.stop();
21151
+ await this.resumeQueue({
21152
+ skipWaitForUser: true,
21153
+ options: this.queuedMessageOptions.get(id)
21154
+ });
21155
+ };
21026
21156
  this.sendMessage = async (message, options) => {
21027
21157
  if (message == null) {
21028
21158
  let messageId = this.pendingApprovalMessageId;
@@ -21060,7 +21190,23 @@ var AbstractChat = class {
21060
21190
  text: message.text
21061
21191
  }] : []] };
21062
21192
  } else uiMessage = message;
21193
+ if (this.queueEnabled && message.messageId == null && (this.isRequestInProgress() || this.isWaitingForUser() || this.experimental_queuedMessages.length > 0)) {
21194
+ const queuedMessage = {
21195
+ ...uiMessage,
21196
+ id: uiMessage.id ?? this.generateId(),
21197
+ role: uiMessage.role ?? "user",
21198
+ metadata: message.metadata
21199
+ };
21200
+ if (options != null) this.queuedMessageOptions.set(queuedMessage.id, options);
21201
+ this.setQueuedMessages([...this.experimental_queuedMessages, queuedMessage]);
21202
+ await this.resumeQueue({
21203
+ skipWaitForUser: this.isQueuePaused,
21204
+ options
21205
+ });
21206
+ return;
21207
+ }
21063
21208
  if (message.messageId != null) {
21209
+ await this.clearQueueForHistoryChange();
21064
21210
  const messageIndex = this.state.messages.findIndex((m) => m.id === message.messageId);
21065
21211
  if (messageIndex === -1) throw new InvalidArgumentError({
21066
21212
  parameter: "message.messageId",
@@ -21085,6 +21231,7 @@ var AbstractChat = class {
21085
21231
  role: uiMessage.role ?? "user",
21086
21232
  metadata: message.metadata
21087
21233
  });
21234
+ this.isQueuePaused = false;
21088
21235
  await this.makeRequest({
21089
21236
  trigger: "submit-message",
21090
21237
  messageId: message.messageId,
@@ -21092,6 +21239,7 @@ var AbstractChat = class {
21092
21239
  });
21093
21240
  };
21094
21241
  this.regenerate = async ({ messageId, ...options } = {}) => {
21242
+ await this.clearQueueForHistoryChange();
21095
21243
  const messageIndex = messageId == null ? this.state.messages.length - 1 : this.state.messages.findIndex((message) => message.id === messageId);
21096
21244
  if (messageIndex === -1) throw new InvalidArgumentError({
21097
21245
  parameter: "messageId",
@@ -21126,6 +21274,7 @@ var AbstractChat = class {
21126
21274
  }
21127
21275
  };
21128
21276
  this.addToolApprovalResponse = async ({ id, approved, reason, options }) => this.jobExecutor.run(async () => {
21277
+ const stopGeneration = this.stopGeneration;
21129
21278
  const messages = this.state.messages;
21130
21279
  const updatePart = (part) => isToolUIPart(part) && part.state === "approval-requested" && part.approval.id === id ? {
21131
21280
  ...part,
@@ -21149,17 +21298,22 @@ var AbstractChat = class {
21149
21298
  if (this.activeResponse) this.activeResponse.state.message.parts = this.activeResponse.state.message.parts.map(updatePart);
21150
21299
  if (messageIndex !== -1 && this.status !== "streaming" && this.status !== "submitted" && this.sendAutomaticallyWhen) {
21151
21300
  const shouldSend = await this.shouldSendAutomatically(messages[messageIndex].id);
21152
- if (shouldSend) this.runAutomaticRequest(() => {
21153
- const messageId = messageIndex === -1 ? this.lastMessage?.id : messages[messageIndex].id;
21154
- return this.makeRequestForToolApproval({
21155
- messageId,
21156
- messageIndex,
21157
- ...options
21158
- });
21159
- }, shouldSend);
21301
+ if (shouldSend) {
21302
+ this.runAutomaticRequest(() => {
21303
+ const messageId = messageIndex === -1 ? this.lastMessage?.id : messages[messageIndex].id;
21304
+ return this.makeRequestForToolApproval({
21305
+ messageId,
21306
+ messageIndex,
21307
+ ...options
21308
+ });
21309
+ }, shouldSend);
21310
+ return;
21311
+ }
21160
21312
  }
21313
+ this.settleQueue({ stopGeneration });
21161
21314
  });
21162
21315
  this.addToolOutput = async ({ state, toolCallId, output, errorText, options }) => this.jobExecutor.run(async () => {
21316
+ const stopGeneration = this.stopGeneration;
21163
21317
  const messages = this.state.messages;
21164
21318
  const updatePart = (part) => {
21165
21319
  if (!isToolUIPart(part) || part.toolCallId !== toolCallId) return part;
@@ -21195,17 +21349,22 @@ var AbstractChat = class {
21195
21349
  if (this.activeResponse) this.activeResponse.state.message.parts = this.activeResponse.state.message.parts.map(updatePart);
21196
21350
  if (messageIndex !== -1 && this.status !== "streaming" && this.status !== "submitted" && this.sendAutomaticallyWhen) {
21197
21351
  const shouldSend = await this.shouldSendAutomatically(messages[messageIndex].id);
21198
- if (shouldSend) this.runAutomaticRequest(() => this.makeRequest({
21199
- trigger: "submit-message",
21200
- messageId: messages[messageIndex].id,
21201
- ...options
21202
- }), shouldSend);
21352
+ if (shouldSend) {
21353
+ this.runAutomaticRequest(() => this.makeRequest({
21354
+ trigger: "submit-message",
21355
+ messageId: messages[messageIndex].id,
21356
+ ...options
21357
+ }), shouldSend);
21358
+ return;
21359
+ }
21203
21360
  }
21361
+ this.settleQueue({ stopGeneration });
21204
21362
  });
21205
21363
  this.addToolResult = this.addToolOutput;
21206
21364
  this.stop = async () => {
21207
21365
  this.activeStopCount++;
21208
21366
  this.stopGeneration++;
21367
+ this.deferredApprovalSend = void 0;
21209
21368
  try {
21210
21369
  const activeResumeRequest = this.activeResumeRequest;
21211
21370
  const activeResponse = this.activeResponse;
@@ -21214,6 +21373,7 @@ var AbstractChat = class {
21214
21373
  activeResponse?.abortController.abort();
21215
21374
  await Promise.all([activeResumeRequest?.completionPromise, activeResponse?.completionPromise]);
21216
21375
  await this.jobExecutor.waitForIdle();
21376
+ this.isQueuePaused = true;
21217
21377
  } finally {
21218
21378
  this.activeStopCount--;
21219
21379
  }
@@ -21233,6 +21393,7 @@ var AbstractChat = class {
21233
21393
  this.onFinish = onFinish;
21234
21394
  this.onData = onData;
21235
21395
  this.sendAutomaticallyWhen = sendAutomaticallyWhen;
21396
+ this.queueEnabled = experimental_queue;
21236
21397
  }
21237
21398
  /**
21238
21399
  * Hook status:
@@ -21262,22 +21423,91 @@ var AbstractChat = class {
21262
21423
  get lastMessage() {
21263
21424
  return this.state.messages[this.state.messages.length - 1];
21264
21425
  }
21426
+ /**
21427
+ * Experimental. Messages that wait to be sent when `experimental_queue` is
21428
+ * enabled, in the order they will be sent.
21429
+ */
21430
+ get experimental_queuedMessages() {
21431
+ return this.state.experimental_queuedMessages ?? this.queuedMessagesFallback;
21432
+ }
21433
+ setQueuedMessages(experimental_queuedMessages) {
21434
+ if ("experimental_queuedMessages" in this.state) this.state.experimental_queuedMessages = experimental_queuedMessages;
21435
+ else this.queuedMessagesFallback = experimental_queuedMessages;
21436
+ }
21437
+ async resumeQueue({ skipWaitForUser, options }) {
21438
+ this.isQueuePaused = false;
21439
+ if (this.hasUnsentApprovalResponse()) {
21440
+ if (!this.isRequestInProgress()) {
21441
+ await this.sendMessage(void 0, options);
21442
+ return;
21443
+ }
21444
+ this.deferredApprovalSend = { options };
21445
+ }
21446
+ await this.settleQueue({ skipWaitForUser });
21447
+ }
21448
+ async clearQueueForHistoryChange() {
21449
+ if (!this.queueEnabled) return;
21450
+ this.queuedMessageOptions.clear();
21451
+ this.setQueuedMessages([]);
21452
+ this.deferredApprovalSend = void 0;
21453
+ if (this.isRequestInProgress()) await this.stop();
21454
+ }
21455
+ isRequestInProgress() {
21456
+ return this.pendingAutomaticDecisions.includes(this.stopGeneration) || this.activeResponse != null || this.status === "submitted" || this.status === "streaming";
21457
+ }
21458
+ isWaitingForUser() {
21459
+ const lastMessage = this.lastMessage;
21460
+ return lastMessage?.role === "assistant" && lastMessage.parts.some((part) => isToolUIPart(part) && (part.state === "approval-requested" || part.state === "approval-responded" || !part.providerExecuted && (part.state === "input-streaming" || part.state === "input-available")));
21461
+ }
21462
+ hasUnsentApprovalResponse() {
21463
+ const lastMessage = this.lastMessage;
21464
+ return lastMessage?.role === "assistant" && lastMessage.parts.some((part) => isToolUIPart(part) && part.state === "approval-responded") && !lastMessage.parts.some((part) => isToolUIPart(part) && (part.state === "approval-requested" || !part.providerExecuted && (part.state === "input-streaming" || part.state === "input-available")));
21465
+ }
21466
+ async settleQueue({ stopGeneration = this.stopGeneration, skipWaitForUser = false } = {}) {
21467
+ if (this.isQueuePaused || this.isRequestInProgress() || this.activeStopCount > 0 || stopGeneration !== this.stopGeneration) return;
21468
+ const deferredApprovalSend = this.deferredApprovalSend;
21469
+ this.deferredApprovalSend = void 0;
21470
+ if (deferredApprovalSend != null && this.hasUnsentApprovalResponse()) {
21471
+ await this.sendMessage(void 0, deferredApprovalSend.options);
21472
+ return;
21473
+ }
21474
+ const [message, ...rest] = this.experimental_queuedMessages;
21475
+ if (message == null || !skipWaitForUser && this.isWaitingForUser()) return;
21476
+ const options = this.queuedMessageOptions.get(message.id);
21477
+ this.queuedMessageOptions.delete(message.id);
21478
+ this.setQueuedMessages(rest);
21479
+ this.state.pushMessage(message);
21480
+ await this.makeRequest({
21481
+ trigger: "submit-message",
21482
+ ...options
21483
+ });
21484
+ }
21265
21485
  set messages(messages) {
21266
21486
  this.state.messages = messages;
21267
21487
  }
21268
21488
  async shouldSendAutomatically(messageId = this.lastMessage?.id) {
21269
21489
  const isInterrupted = (id) => id != null && this.interruptedMessageIds.has(id);
21270
21490
  if (!this.sendAutomaticallyWhen || isInterrupted(messageId) || isInterrupted(this.lastMessage?.id)) return false;
21271
- return await this.sendAutomaticallyWhen({ messages: this.state.messages }) && !isInterrupted(messageId) && !isInterrupted(this.lastMessage?.id);
21491
+ const stopGeneration = this.stopGeneration;
21492
+ this.pendingAutomaticDecisions.push(stopGeneration);
21493
+ let result;
21494
+ try {
21495
+ result = await this.sendAutomaticallyWhen({ messages: this.state.messages });
21496
+ } finally {
21497
+ this.pendingAutomaticDecisions.splice(this.pendingAutomaticDecisions.indexOf(stopGeneration), 1);
21498
+ }
21499
+ return result && !isInterrupted(messageId) && !isInterrupted(this.lastMessage?.id);
21272
21500
  }
21273
21501
  async runAutomaticRequest(request, shouldSend) {
21274
21502
  const stopGeneration = this.stopGeneration;
21275
21503
  const startedWhileStopping = this.activeStopCount > 0;
21276
- if (!(shouldSend ?? await this.shouldSendAutomatically())) return;
21277
- if (startedWhileStopping || stopGeneration !== this.stopGeneration || this.activeStopCount > 0) return;
21504
+ if (!(shouldSend ?? await this.shouldSendAutomatically())) return false;
21505
+ if (startedWhileStopping || stopGeneration !== this.stopGeneration || this.activeStopCount > 0) return false;
21278
21506
  await request();
21507
+ return true;
21279
21508
  }
21280
21509
  async makeRequestForToolApproval({ messageId, messageIndex, ...options }) {
21510
+ this.deferredApprovalSend = void 0;
21281
21511
  const consumesPendingApproval = messageId != null && messageId === this.pendingApprovalMessageId;
21282
21512
  if (consumesPendingApproval) this.pendingApprovalMessageId = void 0;
21283
21513
  await this.makeRequest({
@@ -21481,17 +21711,21 @@ var AbstractChat = class {
21481
21711
  });
21482
21712
  }
21483
21713
  } finally {
21714
+ if (isAbort || isError || activeResponse?.state.finishReason === "interrupted") this.isQueuePaused = true;
21484
21715
  if (this.activeResponse === activeResponse) this.activeResponse = void 0;
21485
21716
  clearActiveResumeRequest();
21486
21717
  }
21487
21718
  }
21488
- if (!isAbort && !isError && activeResponse?.state.finishReason !== "interrupted") await this.runAutomaticRequest(() => this.makeRequest({
21489
- trigger: "submit-message",
21490
- messageId: this.lastMessage?.id,
21491
- metadata,
21492
- headers,
21493
- body
21494
- }));
21719
+ if (!isAbort && !isError && activeResponse?.state.finishReason !== "interrupted") {
21720
+ const stopGeneration = this.stopGeneration;
21721
+ if (!await this.runAutomaticRequest(() => this.makeRequest({
21722
+ trigger: "submit-message",
21723
+ messageId: this.lastMessage?.id,
21724
+ metadata,
21725
+ headers,
21726
+ body
21727
+ }))) await this.settleQueue({ stopGeneration });
21728
+ }
21495
21729
  }
21496
21730
  };
21497
21731
  //#endregion