ai 7.0.172 → 7.0.174

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 (55) hide show
  1. package/CHANGELOG.md +41 -0
  2. package/dist/index.d.ts +68 -21
  3. package/dist/index.d.ts.map +1 -1
  4. package/dist/index.js +325 -100
  5. package/dist/index.js.map +1 -1
  6. package/dist/internal/index.d.ts +109 -9
  7. package/dist/internal/index.d.ts.map +1 -1
  8. package/dist/internal/index.js +68 -18
  9. package/dist/internal/index.js.map +1 -1
  10. package/docs/02-foundations/02-providers-and-models.mdx +1 -0
  11. package/docs/02-foundations/03-prompts.mdx +1 -1
  12. package/docs/03-agents/04-loop-control.mdx +1 -1
  13. package/docs/03-agents/06-memory.mdx +28 -1
  14. package/docs/03-agents/06-tool-approvals.mdx +1 -1
  15. package/docs/03-agents/07-workflow-agent.mdx +87 -34
  16. package/docs/03-ai-sdk-core/05-generating-text.mdx +7 -2
  17. package/docs/03-ai-sdk-core/10-generating-structured-data.mdx +4 -0
  18. package/docs/03-ai-sdk-core/16-mcp-tools.mdx +3 -0
  19. package/docs/03-ai-sdk-core/26-reasoning.mdx +3 -3
  20. package/docs/03-ai-sdk-core/32-decisions.mdx +4 -0
  21. package/docs/03-ai-sdk-core/33-extractions.mdx +59 -2
  22. package/docs/03-ai-sdk-core/35-image-generation.mdx +2 -0
  23. package/docs/03-ai-sdk-core/36-transcription.mdx +3 -0
  24. package/docs/03-ai-sdk-core/37-speech.mdx +3 -0
  25. package/docs/03-ai-sdk-core/42-batch.mdx +54 -0
  26. package/docs/03-ai-sdk-core/45-provider-management.mdx +8 -0
  27. package/docs/07-reference/01-ai-sdk-core/14-extract.mdx +13 -13
  28. package/docs/07-reference/01-ai-sdk-core/20-start-batch.mdx +7 -0
  29. package/docs/07-reference/01-ai-sdk-core/22-get-batch-results.mdx +7 -0
  30. package/docs/07-reference/01-ai-sdk-core/32-validate-ui-messages.mdx +6 -0
  31. package/docs/07-reference/01-ai-sdk-core/33-safe-validate-ui-messages.mdx +3 -0
  32. package/docs/07-reference/01-ai-sdk-core/40-provider-registry.mdx +14 -0
  33. package/docs/07-reference/01-ai-sdk-core/42-custom-provider.mdx +13 -0
  34. package/docs/07-reference/04-ai-sdk-workflow/01-workflow-agent.mdx +62 -5
  35. package/docs/07-reference/05-ai-sdk-errors/ai-no-such-model-error.mdx +3 -0
  36. package/docs/07-reference/05-ai-sdk-errors/ai-no-such-provider-error.mdx +3 -0
  37. package/package.json +12 -12
  38. package/src/agent/default-stop-condition.ts +28 -13
  39. package/src/batch/batch-types.ts +70 -18
  40. package/src/batch/batch.ts +93 -7
  41. package/src/extract/extract.ts +23 -4
  42. package/src/extract/extraction-provider.ts +5 -0
  43. package/src/extract/extraction-result.ts +1 -1
  44. package/src/generate-text/stream-text.ts +1 -1
  45. package/src/generate-text/validate-tool-approvals.ts +23 -19
  46. package/src/global.ts +1 -0
  47. package/src/model/resolve-model.ts +25 -0
  48. package/src/registry/custom-provider.ts +37 -0
  49. package/src/registry/index.ts +1 -0
  50. package/src/registry/no-such-provider-error.ts +1 -0
  51. package/src/registry/provider-registry.ts +59 -5
  52. package/src/telemetry/redact-telemetry-credentials.ts +22 -4
  53. package/src/types/citation.ts +41 -25
  54. package/src/ui/validate-ui-messages.ts +46 -91
  55. package/src/util/normalize-json-value.ts +182 -0
package/dist/index.js CHANGED
@@ -1176,6 +1176,20 @@ function resolveDecisionModel(model) {
1176
1176
  };
1177
1177
  }
1178
1178
  function resolveExtractionModel(model) {
1179
+ if (typeof model === "string") {
1180
+ const provider = globalThis.AI_SDK_DEFAULT_PROVIDER ?? gateway$1;
1181
+ if (typeof provider.extractionModel !== "function") throw new NoSuchModelError$1({
1182
+ modelId: model,
1183
+ modelType: "extractionModel",
1184
+ message: "The default provider does not support extraction models. Pass an extraction model instance or configure AI_SDK_DEFAULT_PROVIDER with an extractionModel method."
1185
+ });
1186
+ const resolvedModel = provider.extractionModel(model);
1187
+ if (resolvedModel == null) throw new NoSuchModelError$1({
1188
+ modelId: model,
1189
+ modelType: "extractionModel"
1190
+ });
1191
+ model = resolvedModel;
1192
+ }
1179
1193
  const version = model.specificationVersion;
1180
1194
  if (version !== "v4") throw new UnsupportedModelVersionError({
1181
1195
  version,
@@ -1251,7 +1265,7 @@ function cloneValue(value, seen) {
1251
1265
  }
1252
1266
  //#endregion
1253
1267
  //#region src/version.ts
1254
- const VERSION = "7.0.172";
1268
+ const VERSION = "7.0.174";
1255
1269
  //#endregion
1256
1270
  //#region src/util/download/download.ts
1257
1271
  /**
@@ -4248,7 +4262,7 @@ function mapArray(value, redact) {
4248
4262
  const copy = value.map(redact);
4249
4263
  return copy.some((entry, index) => entry !== value[index]) ? copy : value;
4250
4264
  }
4251
- /** Preserve result getters, streams, and property descriptors without mutation. */
4265
+ /** Preserve result getters and property descriptors without mutation. */
4252
4266
  function replaceProperties(value, redactors) {
4253
4267
  if (!isRecord$2(value)) return value;
4254
4268
  let descriptors;
@@ -4264,7 +4278,20 @@ function replaceProperties(value, redactors) {
4264
4278
  };
4265
4279
  }
4266
4280
  }
4267
- return descriptors == null ? value : Object.create(Object.getPrototypeOf(value), descriptors);
4281
+ if (descriptors == null) return value;
4282
+ const streamDescriptor = descriptors.stream;
4283
+ if (streamDescriptor?.writable && streamDescriptor.value instanceof ReadableStream) {
4284
+ const original = value;
4285
+ descriptors.stream = {
4286
+ configurable: streamDescriptor.configurable,
4287
+ enumerable: streamDescriptor.enumerable,
4288
+ get: () => original.stream,
4289
+ set: (stream) => {
4290
+ original.stream = stream;
4291
+ }
4292
+ };
4293
+ }
4294
+ return Object.create(Object.getPrototypeOf(value), descriptors);
4268
4295
  }
4269
4296
  //#endregion
4270
4297
  //#region src/telemetry/tracing-channel-publisher.ts
@@ -5379,22 +5406,25 @@ async function validateApprovedToolApprovals({ approvedToolApprovals, tools, too
5379
5406
  });
5380
5407
  }
5381
5408
  if (isExecutableTool(tool) && tool.inputSchema != null) {
5382
- const hasInputSchemaInput = Object.prototype.hasOwnProperty.call(approvalRequest, "inputSchemaInput");
5383
- const validation = await safeValidateTypes({
5384
- value: hasInputSchemaInput ? approvalRequest.inputSchemaInput : toolCall.input,
5385
- schema: asSchema$1(tool.inputSchema)
5386
- });
5387
5409
  let validationError;
5388
- if (!validation.success) validationError = validation.error;
5389
- else try {
5390
- const revalidatedToolCall = await refineParsedToolCallInput({
5391
- toolCall: {
5392
- ...toolCall,
5393
- input: validation.value
5394
- },
5395
- refineToolInput
5410
+ try {
5411
+ const approvedInput = structuredClone(toolCall.input);
5412
+ const hasInputSchemaInput = Object.prototype.hasOwnProperty.call(approvalRequest, "inputSchemaInput");
5413
+ const validation = await safeValidateTypes({
5414
+ value: structuredClone(hasInputSchemaInput ? approvalRequest.inputSchemaInput : toolCall.input),
5415
+ schema: asSchema$1(tool.inputSchema)
5396
5416
  });
5397
- if (!isDeepEqualData(structuredClone(revalidatedToolCall.input), structuredClone(toolCall.input))) validationError = /* @__PURE__ */ new Error("Approved tool input does not match the validated schema output.");
5417
+ if (!validation.success) validationError = validation.error;
5418
+ else {
5419
+ const revalidatedToolCall = await refineParsedToolCallInput({
5420
+ toolCall: {
5421
+ ...toolCall,
5422
+ input: validation.value
5423
+ },
5424
+ refineToolInput
5425
+ });
5426
+ if (!isDeepEqualData(structuredClone(revalidatedToolCall.input), approvedInput)) validationError = /* @__PURE__ */ new Error("Approved tool input does not match the validated schema output.");
5427
+ }
5398
5428
  } catch (error) {
5399
5429
  validationError = error;
5400
5430
  }
@@ -6672,43 +6702,50 @@ const z = {
6672
6702
  };
6673
6703
  //#endregion
6674
6704
  //#region src/types/json-value.ts
6675
- const jsonValueSchema = z.lazy(() => z.union([
6705
+ const jsonValueSchema$1 = z.lazy(() => z.union([
6676
6706
  z.null(),
6677
6707
  z.string(),
6678
6708
  z.number(),
6679
6709
  z.boolean(),
6680
- z.record(z.string(), jsonValueSchema.optional()),
6681
- z.array(jsonValueSchema)
6710
+ z.record(z.string(), jsonValueSchema$1.optional()),
6711
+ z.array(jsonValueSchema$1)
6682
6712
  ]));
6683
6713
  //#endregion
6684
6714
  //#region src/types/provider-metadata.ts
6685
- const providerMetadataSchema$1 = z.record(z.string(), z.record(z.string(), jsonValueSchema.optional()));
6715
+ const providerMetadataSchema$1 = z.record(z.string(), z.record(z.string(), jsonValueSchema$1.optional()));
6686
6716
  //#endregion
6687
6717
  //#region src/types/citation.ts
6688
- const citationSchema = z$1.object({
6689
- source: z$1.discriminatedUnion("sourceType", [z$1.object({
6690
- type: z$1.literal("source"),
6691
- sourceType: z$1.literal("url"),
6692
- id: z$1.string(),
6693
- url: z$1.string(),
6694
- title: z$1.optional(z$1.string()),
6695
- providerMetadata: z$1.optional(providerMetadataSchema$1)
6696
- }), z$1.object({
6697
- type: z$1.literal("source"),
6698
- sourceType: z$1.literal("document"),
6699
- id: z$1.string(),
6700
- mediaType: z$1.string(),
6701
- title: z$1.string(),
6702
- filename: z$1.optional(z$1.string()),
6703
- providerMetadata: z$1.optional(providerMetadataSchema$1)
6704
- })]),
6705
- startIndex: z$1.optional(z$1.number().check(z$1.int()).check(z$1.nonnegative())),
6706
- endIndex: z$1.optional(z$1.number().check(z$1.int()).check(z$1.nonnegative())),
6707
- citedText: z$1.optional(z$1.string())
6708
- });
6718
+ /**
6719
+ * Creates a citation schema that validates the provider metadata of the
6720
+ * source with the given schema.
6721
+ */
6722
+ function createCitationSchema(providerMetadataSchema) {
6723
+ return z$1.object({
6724
+ source: z$1.discriminatedUnion("sourceType", [z$1.object({
6725
+ type: z$1.literal("source"),
6726
+ sourceType: z$1.literal("url"),
6727
+ id: z$1.string(),
6728
+ url: z$1.string(),
6729
+ title: z$1.optional(z$1.string()),
6730
+ providerMetadata: z$1.optional(providerMetadataSchema)
6731
+ }), z$1.object({
6732
+ type: z$1.literal("source"),
6733
+ sourceType: z$1.literal("document"),
6734
+ id: z$1.string(),
6735
+ mediaType: z$1.string(),
6736
+ title: z$1.string(),
6737
+ filename: z$1.optional(z$1.string()),
6738
+ providerMetadata: z$1.optional(providerMetadataSchema)
6739
+ })]),
6740
+ startIndex: z$1.optional(z$1.number().check(z$1.int()).check(z$1.nonnegative())),
6741
+ endIndex: z$1.optional(z$1.number().check(z$1.int()).check(z$1.nonnegative())),
6742
+ citedText: z$1.optional(z$1.string())
6743
+ });
6744
+ }
6745
+ const citationSchema = createCitationSchema(providerMetadataSchema$1);
6709
6746
  //#endregion
6710
6747
  //#region src/ui-message-stream/ui-message-chunks.ts
6711
- const toolMetadataSchema$1 = z$1.record(z$1.string(), z$1.optional(jsonValueSchema));
6748
+ const toolMetadataSchema$1 = z$1.record(z$1.string(), z$1.optional(jsonValueSchema$1));
6712
6749
  const uiMessageChunkSchema = lazySchema(() => zodSchema$1(z$1.union([
6713
6750
  z$1.looseObject({
6714
6751
  type: z$1.literal("text-start"),
@@ -10053,7 +10090,7 @@ var DefaultStreamTextResult = class {
10053
10090
  stream = applyStreamTextTransforms({
10054
10091
  stream,
10055
10092
  transforms,
10056
- tools,
10093
+ tools: tools ?? {},
10057
10094
  stopStream() {
10058
10095
  stitchableStream.terminate();
10059
10096
  isRunning = false;
@@ -11171,6 +11208,19 @@ function isCausedByAbort(error) {
11171
11208
  //#endregion
11172
11209
  //#region src/agent/default-stop-condition.ts
11173
11210
  /**
11211
+ * Logs the warning for the default stopWhen condition.
11212
+ */
11213
+ function logDefaultStopConditionWarning({ stepCount, provider, modelId }) {
11214
+ logWarnings({
11215
+ provider,
11216
+ model: modelId,
11217
+ warnings: [{
11218
+ type: "other",
11219
+ message: `The tool loop stopped because it reached the default stopWhen condition, isStepCount(${stepCount}). To allow more steps, set stopWhen to isStepCount(...) with a higher limit or provide a custom stop condition. Learn more: https://ai-sdk.dev/docs/agents/loop-control`
11220
+ }]
11221
+ });
11222
+ }
11223
+ /**
11174
11224
  * Stop conditions are only evaluated when the tool loop can otherwise continue,
11175
11225
  * so logging here avoids warning when a call finishes naturally at the limit.
11176
11226
  */
@@ -11178,13 +11228,10 @@ function createDefaultStopCondition(stepCount) {
11178
11228
  return ({ steps }) => {
11179
11229
  if (steps.length !== stepCount) return false;
11180
11230
  const { provider, modelId } = steps[steps.length - 1].model;
11181
- logWarnings({
11231
+ logDefaultStopConditionWarning({
11232
+ stepCount,
11182
11233
  provider,
11183
- model: modelId,
11184
- warnings: [{
11185
- type: "other",
11186
- message: `The tool loop stopped because it reached the default stopWhen condition, isStepCount(${stepCount}). To allow more steps, set stopWhen to isStepCount(...) with a higher limit or provide a custom stop condition. Learn more: https://ai-sdk.dev/docs/agents/loop-control`
11187
- }]
11234
+ modelId
11188
11235
  });
11189
11236
  return true;
11190
11237
  };
@@ -11807,60 +11854,159 @@ function convertUserContentUIPart(part) {
11807
11854
  };
11808
11855
  }
11809
11856
  //#endregion
11810
- //#region src/ui/validate-ui-messages.ts
11857
+ //#region src/util/normalize-json-value.ts
11858
+ const invalid = Symbol("invalid");
11859
+ /**
11860
+ * Validates that a value is a JSON value: `null`, a string, a finite number, a
11861
+ * boolean, an array of JSON values, or a plain object with JSON values.
11862
+ *
11863
+ * The value is validated in a single pass that does not allocate memory for
11864
+ * its valid parts, so that validating untrusted input costs little more than
11865
+ * the input itself. A recursive union schema tries (and reports the issues of)
11866
+ * every alternative for every nested value and returns a copy of the value.
11867
+ *
11868
+ * It accepts the same values as a record schema of JSON values, except that a
11869
+ * JSON value cannot contain itself:
11870
+ *
11871
+ * - Object properties can be `undefined`. Array elements cannot.
11872
+ * - Objects must be plain objects without enumerable symbol keys.
11873
+ * - Own `__proto__` keys are removed. Only the objects with such a key and the
11874
+ * arrays and objects that contain them are copied. Everything else is
11875
+ * returned as is.
11876
+ *
11877
+ * @returns The JSON value, or the path to the first invalid value.
11878
+ */
11879
+ function normalizeJsonValue(value) {
11880
+ const path = [];
11881
+ const normalized = normalize(value, path, /* @__PURE__ */ new Set());
11882
+ return normalized === invalid ? {
11883
+ success: false,
11884
+ path
11885
+ } : {
11886
+ success: true,
11887
+ value: normalized
11888
+ };
11889
+ }
11811
11890
  /**
11812
- * Returns the path to the first value that can never be part of a JSON value
11813
- * (a non-finite number, bigint, symbol, or function), if there is one.
11891
+ * Returns the normalized value, or `invalid` with the path to the invalid
11892
+ * value in `path`.
11893
+ *
11894
+ * @param ancestors - The arrays and objects that contain `value`. Tracking
11895
+ * them instead of all visited values detects cycles with memory proportional
11896
+ * to the nesting depth.
11814
11897
  */
11815
- function findInvalidJsonValuePath(value, path = [], visited = /* @__PURE__ */ new WeakSet()) {
11898
+ function normalize(value, path, ancestors) {
11816
11899
  switch (typeof value) {
11817
- case "number": return Number.isFinite(value) ? void 0 : [...path];
11818
- case "bigint":
11819
- case "symbol":
11820
- case "function": return [...path];
11900
+ case "string":
11901
+ case "boolean": return value;
11902
+ case "number": return Number.isFinite(value) ? value : invalid;
11821
11903
  case "object": {
11822
- if (value === null || visited.has(value)) return;
11823
- visited.add(value);
11824
- const keys = Array.isArray(value) ? value.keys() : Object.keys(value);
11825
- for (const key of keys) {
11826
- if (key === "__proto__") continue;
11827
- path.push(key);
11828
- const invalidPath = findInvalidJsonValuePath(value[key], path, visited);
11829
- if (invalidPath != null) return invalidPath;
11830
- path.pop();
11831
- }
11832
- return;
11904
+ if (value === null) return value;
11905
+ if (ancestors.has(value)) return invalid;
11906
+ ancestors.add(value);
11907
+ const normalized = Array.isArray(value) ? normalizeArray(value, path, ancestors) : normalizeObject(value, path, ancestors);
11908
+ ancestors.delete(value);
11909
+ return normalized;
11910
+ }
11911
+ default: return invalid;
11912
+ }
11913
+ }
11914
+ function normalizeArray(array, path, ancestors) {
11915
+ let copy;
11916
+ for (let index = 0; index < array.length; index++) {
11917
+ const element = array[index];
11918
+ path.push(index);
11919
+ const normalized = normalize(element, path, ancestors);
11920
+ if (normalized === invalid) return invalid;
11921
+ path.pop();
11922
+ if (copy != null) copy.push(normalized);
11923
+ else if (normalized !== element) {
11924
+ copy = array.slice(0, index);
11925
+ copy.push(normalized);
11926
+ }
11927
+ }
11928
+ return copy ?? array;
11929
+ }
11930
+ function normalizeObject(object, path, ancestors) {
11931
+ if (!isPlainObject(object) || hasEnumerableSymbolKey(object)) return invalid;
11932
+ const keys = Object.keys(object);
11933
+ let copy;
11934
+ for (let index = 0; index < keys.length; index++) {
11935
+ const key = keys[index];
11936
+ if (key === "__proto__") {
11937
+ copy ??= copyProperties(object, keys, index);
11938
+ continue;
11939
+ }
11940
+ const property = object[key];
11941
+ let normalized = property;
11942
+ if (property !== void 0) {
11943
+ path.push(key);
11944
+ normalized = normalize(property, path, ancestors);
11945
+ if (normalized === invalid) return invalid;
11946
+ path.pop();
11947
+ }
11948
+ if (copy != null) copy[key] = normalized;
11949
+ else if (normalized !== property) {
11950
+ copy = copyProperties(object, keys, index);
11951
+ copy[key] = normalized;
11833
11952
  }
11834
- default: return;
11835
11953
  }
11954
+ return copy ?? object;
11836
11955
  }
11837
11956
  /**
11838
- * Rejects values that contain an invalid JSON value with a single issue before
11839
- * `schema` validates them.
11840
- *
11841
- * The JSON value schema is a recursive union. It reports the issues of every
11842
- * alternative at every nesting level around an invalid value, so the size of a
11843
- * validation error would grow much faster than the (untrusted) input.
11957
+ * Copies the properties of the first `count` keys, which are known to be valid.
11958
+ */
11959
+ function copyProperties(object, keys, count) {
11960
+ const copy = {};
11961
+ for (let index = 0; index < count; index++) copy[keys[index]] = object[keys[index]];
11962
+ return copy;
11963
+ }
11964
+ /**
11965
+ * Same check as record schemas, which accepts plain objects from other realms
11966
+ * and objects without a prototype.
11967
+ */
11968
+ function isPlainObject(object) {
11969
+ const constructor = object.constructor;
11970
+ if (typeof constructor !== "function") return true;
11971
+ const prototype = constructor.prototype;
11972
+ return prototype !== null && typeof prototype === "object" && Object.prototype.hasOwnProperty.call(prototype, "isPrototypeOf");
11973
+ }
11974
+ function hasEnumerableSymbolKey(object) {
11975
+ const symbols = Object.getOwnPropertySymbols(object);
11976
+ for (let index = 0; index < symbols.length; index++) if (Object.prototype.propertyIsEnumerable.call(object, symbols[index])) return true;
11977
+ return false;
11978
+ }
11979
+ //#endregion
11980
+ //#region src/ui/validate-ui-messages.ts
11981
+ /**
11982
+ * Validates a JSON value in a single pass and reports an invalid JSON value
11983
+ * with a single issue.
11844
11984
  *
11845
- * @param jsonValuePath - Path from the validated value to the JSON value.
11985
+ * UI messages are untrusted input. The recursive JSON value schema tries
11986
+ * every alternative for every nested value and returns a copy of the value,
11987
+ * so accepting a value would need several times the memory of the value. It
11988
+ * also reports the issues of every alternative at every nesting level around
11989
+ * an invalid value, so the size of a validation error would grow much faster
11990
+ * than the input.
11846
11991
  */
11847
- function withJsonValueCheck(schema, jsonValuePath = []) {
11848
- return z$1.pipe(z$1.unknown().check((context) => {
11849
- let jsonValue = context.value;
11850
- for (const key of jsonValuePath) jsonValue = jsonValue != null && typeof jsonValue === "object" ? jsonValue[key] : void 0;
11851
- const invalidPath = findInvalidJsonValuePath(jsonValue);
11852
- if (invalidPath != null) context.issues.push({
11992
+ const jsonValueSchema = z$1.pipe(z$1.unknown(), z$1.transform((value, context) => {
11993
+ const result = normalizeJsonValue(value);
11994
+ if (!result.success) {
11995
+ context.issues.push({
11853
11996
  code: "custom",
11854
11997
  message: "Invalid JSON value. Expected null, a string, a finite number, a boolean, an array, or an object.",
11855
- input: context.value,
11856
- path: [...jsonValuePath, ...invalidPath]
11998
+ input: value,
11999
+ path: result.path
11857
12000
  });
11858
- }), schema);
11859
- }
11860
- const toolMetadataSchema = withJsonValueCheck(z$1.record(z$1.string(), z$1.optional(jsonValueSchema)));
11861
- const providerMetadataSchema = withJsonValueCheck(providerMetadataSchema$1);
12001
+ return z$1.NEVER;
12002
+ }
12003
+ return result.value;
12004
+ }));
12005
+ const validatedJsonValueSchema = z$1.custom();
12006
+ const toolMetadataSchema = z$1.pipe(jsonValueSchema, z$1.record(z$1.string(), validatedJsonValueSchema));
12007
+ const providerMetadataSchema = z$1.pipe(jsonValueSchema, z$1.record(z$1.string(), z$1.record(z$1.string(), validatedJsonValueSchema)));
11862
12008
  const providerReferenceSchema$1 = z$1.record(z$1.string(), z$1.string());
11863
- const uiCitationSchema = withJsonValueCheck(citationSchema, ["source", "providerMetadata"]);
12009
+ const uiCitationSchema = createCitationSchema(providerMetadataSchema);
11864
12010
  function isEmptyObject(value) {
11865
12011
  return value != null && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === 0;
11866
12012
  }
@@ -12819,12 +12965,13 @@ async function listBatches({ provider, providerOptions, limit, cursor, maxRetrie
12819
12965
  /**
12820
12966
  * Starts a batch.
12821
12967
  */
12822
- async function startBatch({ provider, requests, providerOptions, webhookUrl, abortSignal, headers, timeout }) {
12968
+ async function startBatch({ provider, requests, providerOptions, output, webhookUrl, abortSignal, headers, timeout }) {
12823
12969
  validateRequests(requests);
12824
12970
  const batchApi = resolveBatchApi(provider);
12825
12971
  const operationAbortSignal = mergeAbortSignals(abortSignal, getTotalTimeoutMs(timeout));
12826
12972
  const supportedUrls = await batchApi.supportedUrls;
12827
12973
  operationAbortSignal?.throwIfAborted();
12974
+ const responseFormat = await output?.responseFormat;
12828
12975
  const normalizedRequests = [];
12829
12976
  const toolsByName = /* @__PURE__ */ new Map();
12830
12977
  for (const request of requests) {
@@ -12848,6 +12995,7 @@ async function startBatch({ provider, requests, providerOptions, webhookUrl, abo
12848
12995
  modelId: request.model,
12849
12996
  options: {
12850
12997
  ...prepareLanguageModelCallOptions(request),
12998
+ responseFormat,
12851
12999
  prompt: await convertToLanguageModelPrompt({
12852
13000
  prompt: standardizedPrompt,
12853
13001
  supportedUrls,
@@ -12957,7 +13105,7 @@ async function getBatchStatus({ provider, batch, providerOptions, maxRetries, ab
12957
13105
  /**
12958
13106
  * Streams complete terminal results for the requests in a batch.
12959
13107
  */
12960
- function getBatchResults({ provider, batch, tools, providerOptions, maxRetries, abortSignal, headers, timeout }) {
13108
+ function getBatchResults({ provider, batch, tools, output, providerOptions, maxRetries, abortSignal, headers, timeout }) {
12961
13109
  const batchApi = resolveBatchApi(provider);
12962
13110
  validateBatchReference({
12963
13111
  batchApi,
@@ -12974,6 +13122,7 @@ function getBatchResults({ provider, batch, tools, providerOptions, maxRetries,
12974
13122
  controller.enqueue(await convertBatchItemResult({
12975
13123
  item,
12976
13124
  tools,
13125
+ output,
12977
13126
  abortSignal: operationAbortSignal
12978
13127
  }));
12979
13128
  },
@@ -13039,7 +13188,7 @@ function validateBatchReference({ batchApi, batch }) {
13039
13188
  message: `provider ${batchApi.provider} is not compatible with batch provider ${batch.provider}`
13040
13189
  });
13041
13190
  }
13042
- async function convertBatchItemResult({ item, tools, abortSignal }) {
13191
+ async function convertBatchItemResult({ item, tools, output, abortSignal }) {
13043
13192
  switch (item.type) {
13044
13193
  case "text": switch (item.status) {
13045
13194
  case "succeeded": return {
@@ -13050,7 +13199,11 @@ async function convertBatchItemResult({ item, tools, abortSignal }) {
13050
13199
  result: item.result,
13051
13200
  tools,
13052
13201
  abortSignal
13053
- })
13202
+ }),
13203
+ ...output != null ? await parseBatchOutput({
13204
+ result: item.result,
13205
+ output
13206
+ }) : {}
13054
13207
  };
13055
13208
  case "failed": return {
13056
13209
  type: item.type,
@@ -13113,6 +13266,42 @@ function convertImageResult(result) {
13113
13266
  usage: result.usage
13114
13267
  };
13115
13268
  }
13269
+ /**
13270
+ * Parses the structured output of a successful text item. Failures are
13271
+ * reported as `outputError` so that one malformed item does not affect the
13272
+ * rest of the batch or discard the item's text and usage.
13273
+ */
13274
+ async function parseBatchOutput({ result, output }) {
13275
+ const generatedText = result.content.filter((part) => {
13276
+ return part.type === "text";
13277
+ }).map((part) => part.text).join("");
13278
+ const finishReason = result.finishReason.unified;
13279
+ if (!(finishReason === "stop" || finishReason !== "tool-calls" && generatedText.length > 0)) {
13280
+ const error = new NoOutputGeneratedError();
13281
+ return { outputError: {
13282
+ message: error.message,
13283
+ type: error.name
13284
+ } };
13285
+ }
13286
+ const textForOutput = (await output.responseFormat)?.type === "json" ? result.structuredOutputText ?? generatedText : generatedText;
13287
+ try {
13288
+ return { output: await output.parseCompleteOutput({ text: textForOutput }, {
13289
+ response: {
13290
+ id: result.response?.id ?? "",
13291
+ timestamp: result.response?.timestamp ?? /* @__PURE__ */ new Date(0),
13292
+ modelId: result.response?.modelId ?? "",
13293
+ headers: result.response?.headers
13294
+ },
13295
+ usage: asLanguageModelUsage(result.usage),
13296
+ finishReason
13297
+ }) };
13298
+ } catch (error) {
13299
+ return { outputError: {
13300
+ message: error instanceof Error ? error.message : String(error),
13301
+ type: error instanceof Error ? error.name : "Error"
13302
+ } };
13303
+ }
13304
+ }
13116
13305
  async function convertGenerateResult({ result, tools, abortSignal }) {
13117
13306
  const toolCalls = await Promise.all(result.content.filter((part) => part.type === "tool-call").map((toolCall) => parseToolCall({
13118
13307
  toolCall,
@@ -14139,12 +14328,24 @@ async function extract({ model: modelArg, state, fields, referenceDate, maxOutpu
14139
14328
  });
14140
14329
  });
14141
14330
  abortSignal?.throwIfAborted();
14331
+ const answers = isRecord$1(result.answers) ? Object.fromEntries(Object.entries(result.answers).map(([id, answer]) => {
14332
+ if (!isRecord$1(answer) || answer.type === "refusal") return [id, answer];
14333
+ if (answer.value === "" || Array.isArray(answer.value) && answer.value.length === 0) {
14334
+ const normalized = {
14335
+ ...answer,
14336
+ value: null
14337
+ };
14338
+ if (normalized.type === "list") delete normalized.items;
14339
+ return [id, normalized];
14340
+ }
14341
+ return [id, answer];
14342
+ })) : result.answers;
14142
14343
  validateExtractionAnswers({
14143
14344
  fields,
14144
14345
  state: preparedState,
14145
- answers: result.answers
14346
+ answers
14146
14347
  });
14147
- const refusedFieldIds = Object.keys(fields).filter((id) => result.answers[id]?.type === "refusal");
14348
+ const refusedFieldIds = Object.keys(fields).filter((id) => answers[id]?.type === "refusal");
14148
14349
  if (refusedFieldIds.length > 0) throw new Experimental_ExtractionRefusalError$1({
14149
14350
  fieldIds: refusedFieldIds,
14150
14351
  provider: model.provider,
@@ -14158,7 +14359,7 @@ async function extract({ model: modelArg, state, fields, referenceDate, maxOutpu
14158
14359
  const inputTokens = result.usage?.inputTokens;
14159
14360
  const outputTokens = result.usage?.outputTokens;
14160
14361
  return {
14161
- answers: result.answers,
14362
+ answers,
14162
14363
  usage: {
14163
14364
  inputTokens,
14164
14365
  outputTokens,
@@ -17583,7 +17784,7 @@ const outputSchema = z.discriminatedUnion("type", [
17583
17784
  }),
17584
17785
  z.object({
17585
17786
  type: z.literal("json"),
17586
- value: jsonValueSchema,
17787
+ value: jsonValueSchema$1,
17587
17788
  providerOptions: providerMetadataSchema$1.optional()
17588
17789
  }),
17589
17790
  z.object({
@@ -17598,7 +17799,7 @@ const outputSchema = z.discriminatedUnion("type", [
17598
17799
  }),
17599
17800
  z.object({
17600
17801
  type: z.literal("error-json"),
17601
- value: jsonValueSchema,
17802
+ value: jsonValueSchema$1,
17602
17803
  providerOptions: providerMetadataSchema$1.optional()
17603
17804
  }),
17604
17805
  z.object({
@@ -20117,6 +20318,7 @@ var AbstractRealtimeSession = class {
20117
20318
  * @param {Record<string, RerankingModel>} [options.rerankingModels] - A record of reranking models, where keys are model IDs and values are reranking model instances.
20118
20319
  * @param {Record<string, VideoModel>} [options.videoModels] - A record of video models, where keys are model IDs and values are video model instances.
20119
20320
  * @param {Record<string, DecisionModel>} [options.decisionModels] - Experimental decision models or default-provider model IDs, keyed by alias.
20321
+ * @param {Record<string, ExtractionModel>} [options.extractionModels] - Experimental extraction models or default-provider model IDs, keyed by alias.
20120
20322
  * @param {FilesV4} [options.files] - A files interface for uploading files.
20121
20323
  * @param {SkillsV4} [options.skills] - A skills interface for uploading skills.
20122
20324
  * @param {ProviderV2 | ProviderV3 | ProviderV4} [options.fallbackProvider] - An optional fallback provider to use when a requested model is not found in the custom provider.
@@ -20124,7 +20326,7 @@ var AbstractRealtimeSession = class {
20124
20326
  *
20125
20327
  * @throws {NoSuchModelError} Throws when a requested model is not found and no fallback provider is available.
20126
20328
  */
20127
- function customProvider({ languageModels, embeddingModels, imageModels, transcriptionModels, speechModels, rerankingModels, videoModels, decisionModels: decisionModelsArg, evaluationModels, files, skills, fallbackProvider: fallbackProviderArg }) {
20329
+ function customProvider({ languageModels, embeddingModels, imageModels, transcriptionModels, speechModels, rerankingModels, videoModels, decisionModels: decisionModelsArg, evaluationModels, extractionModels, files, skills, fallbackProvider: fallbackProviderArg }) {
20128
20330
  const decisionModels = decisionModelsArg ?? evaluationModels;
20129
20331
  const fallbackProvider = fallbackProviderArg == null ? void 0 : asProviderV4(fallbackProviderArg);
20130
20332
  const baseProvider = {
@@ -20199,6 +20401,18 @@ function customProvider({ languageModels, embeddingModels, imageModels, transcri
20199
20401
  evaluationModel(modelId) {
20200
20402
  return asEvaluationModel(this.decisionModel(modelId));
20201
20403
  },
20404
+ extractionModel(modelId) {
20405
+ if (extractionModels != null && Object.hasOwn(extractionModels, modelId)) return resolveExtractionModel(extractionModels[modelId]);
20406
+ const provider = fallbackProviderArg;
20407
+ if (typeof provider?.extractionModel === "function") {
20408
+ const model = provider.extractionModel(modelId);
20409
+ if (model != null) return resolveExtractionModel(model);
20410
+ }
20411
+ throw new NoSuchModelError$1({
20412
+ modelId,
20413
+ modelType: "extractionModel"
20414
+ });
20415
+ },
20202
20416
  videoModel(modelId) {
20203
20417
  if (videoModels != null && modelId in videoModels) return resolveVideoModel(videoModels[modelId]);
20204
20418
  const provider = fallbackProviderArg;
@@ -20283,11 +20497,13 @@ var DefaultProviderRegistry = class {
20283
20497
  const videoModel = provider.videoModel?.bind(provider);
20284
20498
  const decisionProvider = provider;
20285
20499
  const decisionModel = (decisionProvider.decisionModel ?? decisionProvider.evaluationModel)?.bind(provider);
20500
+ const extractionModel = provider.extractionModel?.bind(provider);
20286
20501
  const registeredProvider = videoModel == null ? providerV4 : Object.assign(Object.create(Object.getPrototypeOf(providerV4)), {
20287
20502
  ...providerV4,
20288
20503
  videoModel: (modelId) => asVideoModelV4(videoModel(modelId))
20289
20504
  });
20290
20505
  if (registeredProvider !== provider && decisionModel != null) Object.assign(registeredProvider, { decisionModel });
20506
+ if (registeredProvider !== provider && extractionModel != null) Object.assign(registeredProvider, { extractionModel });
20291
20507
  this.providers[id] = registeredProvider;
20292
20508
  }
20293
20509
  getProvider(id, modelType) {
@@ -20394,6 +20610,15 @@ var DefaultProviderRegistry = class {
20394
20610
  evaluationModel(id) {
20395
20611
  return asEvaluationModel(this.decisionModel(id));
20396
20612
  }
20613
+ extractionModel(id) {
20614
+ const [providerId, modelId] = this.splitId(id, "extractionModel");
20615
+ const model = this.getProvider(providerId, "extractionModel").extractionModel?.(modelId);
20616
+ if (model == null) throw new NoSuchModelError$1({
20617
+ modelId: id,
20618
+ modelType: "extractionModel"
20619
+ });
20620
+ return resolveExtractionModel(model);
20621
+ }
20397
20622
  files(id) {
20398
20623
  const files = this.getProvider(id, "languageModel").files?.();
20399
20624
  if (files == null) throw new Error(`The provider "${id}" does not support file uploads. Make sure it exposes a files() method.`);