modality-ai 0.8.1 → 0.8.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -17221,7 +17221,7 @@ function slugify2(input) {
17221
17221
  function isObject2(data) {
17222
17222
  return typeof data === "object" && data !== null && !Array.isArray(data);
17223
17223
  }
17224
- function isPlainObject2(o) {
17224
+ function isPlainObject3(o) {
17225
17225
  if (isObject2(o) === false)
17226
17226
  return false;
17227
17227
  const ctor = o.constructor;
@@ -17238,7 +17238,7 @@ function isPlainObject2(o) {
17238
17238
  return true;
17239
17239
  }
17240
17240
  function shallowClone2(o) {
17241
- if (isPlainObject2(o))
17241
+ if (isPlainObject3(o))
17242
17242
  return { ...o };
17243
17243
  if (Array.isArray(o))
17244
17244
  return [...o];
@@ -17378,7 +17378,7 @@ function omit2(schema, mask) {
17378
17378
  return clone2(schema, def);
17379
17379
  }
17380
17380
  function extend2(schema, shape) {
17381
- if (!isPlainObject2(shape)) {
17381
+ if (!isPlainObject3(shape)) {
17382
17382
  throw new Error("Invalid input to extend: expected a plain object");
17383
17383
  }
17384
17384
  const checks3 = schema._zod.def.checks;
@@ -17401,7 +17401,7 @@ function extend2(schema, shape) {
17401
17401
  return clone2(schema, def);
17402
17402
  }
17403
17403
  function safeExtend2(schema, shape) {
17404
- if (!isPlainObject2(shape)) {
17404
+ if (!isPlainObject3(shape)) {
17405
17405
  throw new Error("Invalid input to safeExtend: expected a plain object");
17406
17406
  }
17407
17407
  const def = mergeDefs2(schema._zod.def, {
@@ -18002,7 +18002,7 @@ function mergeValues3(a, b) {
18002
18002
  if (a instanceof Date && b instanceof Date && +a === +b) {
18003
18003
  return { valid: true, data: a };
18004
18004
  }
18005
- if (isPlainObject2(a) && isPlainObject2(b)) {
18005
+ if (isPlainObject3(a) && isPlainObject3(b)) {
18006
18006
  const bKeys = Object.keys(b);
18007
18007
  const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1);
18008
18008
  const newObj = { ...a, ...b };
@@ -19834,12 +19834,12 @@ function toJSONSchema2(input, params) {
19834
19834
  process22(schema, ctx2);
19835
19835
  }
19836
19836
  const schemas3 = {};
19837
- const external4 = {
19837
+ const external3 = {
19838
19838
  registry: registry22,
19839
19839
  uri: params?.uri,
19840
19840
  defs
19841
19841
  };
19842
- ctx2.external = external4;
19842
+ ctx2.external = external3;
19843
19843
  for (const entry of registry22._idmap.entries()) {
19844
19844
  const [key, schema] = entry;
19845
19845
  extractDefs2(ctx2, schema);
@@ -28977,7 +28977,7 @@ var init_dist = __esm(() => {
28977
28977
  jsonStringifyReplacer: () => jsonStringifyReplacer2,
28978
28978
  joinValues: () => joinValues2,
28979
28979
  issue: () => issue2,
28980
- isPlainObject: () => isPlainObject2,
28980
+ isPlainObject: () => isPlainObject3,
28981
28981
  isObject: () => isObject2,
28982
28982
  hexToUint8Array: () => hexToUint8Array2,
28983
28983
  getSizableOrigin: () => getSizableOrigin2,
@@ -30750,7 +30750,7 @@ var init_dist = __esm(() => {
30750
30750
  $ZodType2.init(inst, def);
30751
30751
  inst._zod.parse = (payload, ctx) => {
30752
30752
  const input = payload.value;
30753
- if (!isPlainObject2(input)) {
30753
+ if (!isPlainObject3(input)) {
30754
30754
  payload.issues.push({
30755
30755
  expected: "record",
30756
30756
  code: "invalid_type",
@@ -33259,7 +33259,7 @@ __export(exports_Predicate, {
33259
33259
  isTruthy: () => isTruthy,
33260
33260
  isTagged: () => isTagged,
33261
33261
  isSymbol: () => isSymbol,
33262
- isString: () => isString,
33262
+ isString: () => isString2,
33263
33263
  isSet: () => isSet,
33264
33264
  isRegExp: () => isRegExp,
33265
33265
  isRecordOrArray: () => isRecordOrArray,
@@ -33269,7 +33269,7 @@ __export(exports_Predicate, {
33269
33269
  isPromiseLike: () => isPromiseLike,
33270
33270
  isPromise: () => isPromise,
33271
33271
  isObject: () => isObject3,
33272
- isNumber: () => isNumber,
33272
+ isNumber: () => isNumber2,
33273
33273
  isNullable: () => isNullable,
33274
33274
  isNull: () => isNull,
33275
33275
  isNotUndefined: () => isNotUndefined,
@@ -33291,7 +33291,7 @@ __export(exports_Predicate, {
33291
33291
  and: () => and,
33292
33292
  all: () => all2
33293
33293
  });
33294
- var mapInput2, isTupleOf, isTupleOfAtLeast, isTruthy = (input) => !!input, isSet = (input) => input instanceof Set, isMap = (input) => input instanceof Map, isString = (input) => typeof input === "string", isNumber = (input) => typeof input === "number", isBoolean = (input) => typeof input === "boolean", isBigInt = (input) => typeof input === "bigint", isSymbol = (input) => typeof input === "symbol", isPropertyKey = (u) => isString(u) || isNumber(u) || isSymbol(u), isFunction2, isUndefined = (input) => input === undefined, isNotUndefined = (input) => input !== undefined, isNull = (input) => input === null, isNotNull = (input) => input !== null, isNever = (_) => false, isUnknown = (_) => true, isRecordOrArray = (input) => typeof input === "object" && input !== null, isObject3 = (input) => isRecordOrArray(input) || isFunction2(input), hasProperty, isTagged, isNullable = (input) => input === null || input === undefined, isNotNullable = (input) => input !== null && input !== undefined, isError = (input) => input instanceof Error, isUint8Array = (input) => input instanceof Uint8Array, isDate = (input) => input instanceof Date, isIterable = (input) => typeof input === "string" || hasProperty(input, Symbol.iterator), isRecord2 = (input) => isRecordOrArray(input) && !Array.isArray(input), isReadonlyRecord, isPromise = (input) => hasProperty(input, "then") && ("catch" in input) && isFunction2(input.then) && isFunction2(input.catch), isPromiseLike = (input) => hasProperty(input, "then") && isFunction2(input.then), isRegExp = (input) => input instanceof RegExp, compose2, product2 = (self, that) => ([a, b]) => self(a) && that(b), all2 = (collection) => {
33294
+ var mapInput2, isTupleOf, isTupleOfAtLeast, isTruthy = (input) => !!input, isSet = (input) => input instanceof Set, isMap = (input) => input instanceof Map, isString2 = (input) => typeof input === "string", isNumber2 = (input) => typeof input === "number", isBoolean = (input) => typeof input === "boolean", isBigInt = (input) => typeof input === "bigint", isSymbol = (input) => typeof input === "symbol", isPropertyKey = (u) => isString2(u) || isNumber2(u) || isSymbol(u), isFunction2, isUndefined = (input) => input === undefined, isNotUndefined = (input) => input !== undefined, isNull = (input) => input === null, isNotNull = (input) => input !== null, isNever = (_) => false, isUnknown = (_) => true, isRecordOrArray = (input) => typeof input === "object" && input !== null, isObject3 = (input) => isRecordOrArray(input) || isFunction2(input), hasProperty, isTagged, isNullable = (input) => input === null || input === undefined, isNotNullable = (input) => input !== null && input !== undefined, isError = (input) => input instanceof Error, isUint8Array = (input) => input instanceof Uint8Array, isDate = (input) => input instanceof Date, isIterable = (input) => typeof input === "string" || hasProperty(input, Symbol.iterator), isRecord2 = (input) => isRecordOrArray(input) && !Array.isArray(input), isReadonlyRecord, isPromise = (input) => hasProperty(input, "then") && ("catch" in input) && isFunction2(input.then) && isFunction2(input.catch), isPromiseLike = (input) => hasProperty(input, "then") && isFunction2(input.then), isRegExp = (input) => input instanceof RegExp, compose2, product2 = (self, that) => ([a, b]) => self(a) && that(b), all2 = (collection) => {
33295
33295
  return (as) => {
33296
33296
  let collectionIndex = 0;
33297
33297
  for (const p of collection) {
@@ -33794,12 +33794,12 @@ function safeToString(input) {
33794
33794
  }
33795
33795
  }
33796
33796
  function formatPropertyKey(name24) {
33797
- return isString(name24) ? JSON.stringify(name24) : String(name24);
33797
+ return isString2(name24) ? JSON.stringify(name24) : String(name24);
33798
33798
  }
33799
33799
  function formatUnknown(input, options) {
33800
33800
  const space = options?.space ?? 0;
33801
33801
  const seen = new WeakSet;
33802
- const gap = !space ? "" : isNumber(space) ? " ".repeat(space) : space;
33802
+ const gap = !space ? "" : isNumber2(space) ? " ".repeat(space) : space;
33803
33803
  const ind = (d) => gap.repeat(d);
33804
33804
  const wrap = (v, body) => {
33805
33805
  const ctor = v?.constructor;
@@ -33834,9 +33834,9 @@ ${ind(d)}]`;
33834
33834
  }
33835
33835
  return s;
33836
33836
  }
33837
- if (isString(v))
33837
+ if (isString2(v))
33838
33838
  return JSON.stringify(v);
33839
- if (isNumber(v) || v == null || isBoolean(v) || isSymbol(v))
33839
+ if (isNumber2(v) || v == null || isBoolean(v) || isSymbol(v))
33840
33840
  return String(v);
33841
33841
  if (isBigInt(v))
33842
33842
  return String(v) + "n";
@@ -47834,7 +47834,7 @@ __export(exports_Number, {
47834
47834
  max: () => max3,
47835
47835
  lessThanOrEqualTo: () => lessThanOrEqualTo2,
47836
47836
  lessThan: () => lessThan2,
47837
- isNumber: () => isNumber2,
47837
+ isNumber: () => isNumber3,
47838
47838
  increment: () => increment,
47839
47839
  greaterThanOrEqualTo: () => greaterThanOrEqualTo2,
47840
47840
  greaterThan: () => greaterThan2,
@@ -47845,7 +47845,7 @@ __export(exports_Number, {
47845
47845
  Order: () => Order,
47846
47846
  Equivalence: () => Equivalence
47847
47847
  });
47848
- var isNumber2, negate = (n) => multiply(n, -1), sum, sumAll = (collection) => reduce(collection, 0, sum), subtract, multiply, multiplyAll = (collection) => {
47848
+ var isNumber3, negate = (n) => multiply(n, -1), sum, sumAll = (collection) => reduce(collection, 0, sum), subtract, multiply, multiplyAll = (collection) => {
47849
47849
  let out = 1;
47850
47850
  for (const n of collection) {
47851
47851
  if (n === 0) {
@@ -47880,7 +47880,7 @@ var init_Number = __esm(() => {
47880
47880
  init_Iterable();
47881
47881
  init_Order();
47882
47882
  init_Predicate();
47883
- isNumber2 = isNumber;
47883
+ isNumber3 = isNumber2;
47884
47884
  sum = /* @__PURE__ */ dual(2, (self, that) => self + that);
47885
47885
  subtract = /* @__PURE__ */ dual(2, (minuend, subtrahend) => minuend - subtrahend);
47886
47886
  multiply = /* @__PURE__ */ dual(2, (multiplier, multiplicand) => multiplier * multiplicand);
@@ -48975,7 +48975,7 @@ var TypeConstructorAnnotationId, BrandAnnotationId, SchemaIdAnnotationId, Messag
48975
48975
  if (isSome2(ops)) {
48976
48976
  return ops.value;
48977
48977
  }
48978
- if (isString(name24)) {
48978
+ if (isString2(name24)) {
48979
48979
  let out = undefined;
48980
48980
  for (const is of ast.indexSignatures) {
48981
48981
  const encodedParameter = getEncodedParameter(is.parameter);
@@ -49060,7 +49060,7 @@ var TypeConstructorAnnotationId, BrandAnnotationId, SchemaIdAnnotationId, Messag
49060
49060
  indexSignatures.push(new IndexSignature(key2, value, true));
49061
49061
  break;
49062
49062
  case "Literal":
49063
- if (isString(key2.literal) || isNumber(key2.literal)) {
49063
+ if (isString2(key2.literal) || isNumber2(key2.literal)) {
49064
49064
  propertySignatures.push(new PropertySignature(key2.literal, value, false, true));
49065
49065
  } else {
49066
49066
  throw new Error(getASTUnsupportedLiteralErrorMessage(key2.literal));
@@ -49589,9 +49589,9 @@ var init_SchemaAST = __esm(() => {
49589
49589
  isTemplateLiteral = /* @__PURE__ */ createASTGuard("TemplateLiteral");
49590
49590
  OptionalType = class OptionalType extends Type {
49591
49591
  isOptional;
49592
- constructor(type, isOptional, annotations = {}) {
49592
+ constructor(type, isOptional2, annotations = {}) {
49593
49593
  super(type, annotations);
49594
- this.isOptional = isOptional;
49594
+ this.isOptional = isOptional2;
49595
49595
  }
49596
49596
  toJSON() {
49597
49597
  return {
@@ -49608,8 +49608,8 @@ var init_SchemaAST = __esm(() => {
49608
49608
  PropertySignature = class PropertySignature extends OptionalType {
49609
49609
  name;
49610
49610
  isReadonly;
49611
- constructor(name24, type, isOptional, isReadonly, annotations) {
49612
- super(type, isOptional, annotations);
49611
+ constructor(name24, type, isOptional2, isReadonly, annotations) {
49612
+ super(type, isOptional2, annotations);
49613
49613
  this.name = name24;
49614
49614
  this.isReadonly = isReadonly;
49615
49615
  }
@@ -49812,13 +49812,13 @@ var makeLazy2 = (schema) => {
49812
49812
  _tag: "StringConstraints",
49813
49813
  constraints: {}
49814
49814
  };
49815
- if (isNumber(options.minLength)) {
49815
+ if (isNumber2(options.minLength)) {
49816
49816
  out.constraints.minLength = options.minLength;
49817
49817
  }
49818
- if (isNumber(options.maxLength)) {
49818
+ if (isNumber2(options.maxLength)) {
49819
49819
  out.constraints.maxLength = options.maxLength;
49820
49820
  }
49821
- if (isString(options.pattern)) {
49821
+ if (isString2(options.pattern)) {
49822
49822
  out.pattern = options.pattern;
49823
49823
  }
49824
49824
  return out;
@@ -49828,13 +49828,13 @@ var makeLazy2 = (schema) => {
49828
49828
  constraints: {},
49829
49829
  isInteger: options.isInteger ?? false
49830
49830
  };
49831
- if (isNumber(options.min)) {
49831
+ if (isNumber2(options.min)) {
49832
49832
  out.constraints.min = Math.fround(options.min);
49833
49833
  }
49834
49834
  if (isBoolean(options.minExcluded)) {
49835
49835
  out.constraints.minExcluded = options.minExcluded;
49836
49836
  }
49837
- if (isNumber(options.max)) {
49837
+ if (isNumber2(options.max)) {
49838
49838
  out.constraints.max = Math.fround(options.max);
49839
49839
  }
49840
49840
  if (isBoolean(options.maxExcluded)) {
@@ -49864,10 +49864,10 @@ var makeLazy2 = (schema) => {
49864
49864
  _tag: "ArrayConstraints",
49865
49865
  constraints: {}
49866
49866
  };
49867
- if (isNumber(options.minLength)) {
49867
+ if (isNumber2(options.minLength)) {
49868
49868
  out.constraints.minLength = options.minLength;
49869
49869
  }
49870
- if (isNumber(options.maxLength)) {
49870
+ if (isNumber2(options.maxLength)) {
49871
49871
  out.constraints.maxLength = options.maxLength;
49872
49872
  }
49873
49873
  return out;
@@ -51955,11 +51955,11 @@ __export(exports_Duration, {
51955
51955
  var TypeId8, bigint03, bigint24, bigint60, bigint1e3, bigint1e6, bigint1e9, DURATION_REGEX, decode4 = (input) => {
51956
51956
  if (isDuration(input)) {
51957
51957
  return input;
51958
- } else if (isNumber(input)) {
51958
+ } else if (isNumber2(input)) {
51959
51959
  return millis(input);
51960
51960
  } else if (isBigInt(input)) {
51961
51961
  return nanos(input);
51962
- } else if (Array.isArray(input) && input.length === 2 && input.every(isNumber)) {
51962
+ } else if (Array.isArray(input) && input.length === 2 && input.every(isNumber2)) {
51963
51963
  if (input[0] === -Infinity || input[1] === -Infinity || Number.isNaN(input[0]) || Number.isNaN(input[1])) {
51964
51964
  return zero2;
51965
51965
  }
@@ -51967,7 +51967,7 @@ var TypeId8, bigint03, bigint24, bigint60, bigint1e3, bigint1e6, bigint1e9, DURA
51967
51967
  return infinity;
51968
51968
  }
51969
51969
  return nanos(BigInt(Math.round(input[0] * 1e9)) + BigInt(Math.round(input[1])));
51970
- } else if (isString(input)) {
51970
+ } else if (isString2(input)) {
51971
51971
  const match5 = DURATION_REGEX.exec(input);
51972
51972
  if (match5) {
51973
51973
  const [_, valueStr, unit] = match5;
@@ -52003,7 +52003,7 @@ var TypeId8, bigint03, bigint24, bigint60, bigint1e3, bigint1e6, bigint1e9, DURA
52003
52003
  throw new Error("Invalid DurationInput");
52004
52004
  }, decodeUnknown, zeroValue, infinityValue, DurationProto, make10 = (input) => {
52005
52005
  const duration4 = Object.create(DurationProto);
52006
- if (isNumber(input)) {
52006
+ if (isNumber2(input)) {
52007
52007
  if (isNaN(input) || input <= 0) {
52008
52008
  duration4.value = zeroValue;
52009
52009
  } else if (!Number.isFinite(input)) {
@@ -59880,7 +59880,7 @@ var init_core_effect = __esm(() => {
59880
59880
  let keys5;
59881
59881
  return catchIf(self, (e) => {
59882
59882
  keys5 ??= Object.keys(cases);
59883
- return hasProperty(e, "_tag") && isString(e["_tag"]) && keys5.includes(e["_tag"]);
59883
+ return hasProperty(e, "_tag") && isString2(e["_tag"]) && keys5.includes(e["_tag"]);
59884
59884
  }, (e) => cases[e["_tag"]](e));
59885
59885
  });
59886
59886
  clockWith3 = clockWith2;
@@ -69540,7 +69540,7 @@ __export(exports_String, {
69540
69540
  length: () => length4,
69541
69541
  lastIndexOf: () => lastIndexOf,
69542
69542
  kebabToSnake: () => kebabToSnake,
69543
- isString: () => isString2,
69543
+ isString: () => isString3,
69544
69544
  isNonEmpty: () => isNonEmpty7,
69545
69545
  isEmpty: () => isEmpty14,
69546
69546
  indexOf: () => indexOf,
@@ -69557,7 +69557,7 @@ __export(exports_String, {
69557
69557
  Order: () => Order10,
69558
69558
  Equivalence: () => Equivalence7
69559
69559
  });
69560
- var isString2, Equivalence7, Order10, empty41 = "", concat2, toUpperCase = (self) => self.toUpperCase(), toLowerCase = (self) => self.toLowerCase(), capitalize = (self) => {
69560
+ var isString3, Equivalence7, Order10, empty41 = "", concat2, toUpperCase = (self) => self.toUpperCase(), toLowerCase = (self) => self.toLowerCase(), capitalize = (self) => {
69561
69561
  if (self.length === 0)
69562
69562
  return self;
69563
69563
  return toUpperCase(self[0]) + self.slice(1);
@@ -69588,7 +69588,7 @@ var init_String = __esm(() => {
69588
69588
  init_Option();
69589
69589
  init_Order();
69590
69590
  init_Predicate();
69591
- isString2 = isString;
69591
+ isString3 = isString2;
69592
69592
  Equivalence7 = string5;
69593
69593
  Order10 = string7;
69594
69594
  concat2 = /* @__PURE__ */ dual(2, (self, that) => self + that);
@@ -79451,8 +79451,8 @@ var StreamSymbolKey = "effect/Stream", StreamTypeId3, streamVariance, StreamImpl
79451
79451
  }, Do7, bind9, bindTo9, let_9, channelToStream = (self) => {
79452
79452
  return new StreamImpl(self);
79453
79453
  }, decodeText, encodeText = (self) => suspend10(() => {
79454
- const encoder2 = new TextEncoder;
79455
- return map35(self, (s) => encoder2.encode(s));
79454
+ const encoder3 = new TextEncoder;
79455
+ return map35(self, (s) => encoder3.encode(s));
79456
79456
  }), fromEventListener = (target, type, options) => asyncPush((emit2) => acquireRelease3(sync8(() => target.addEventListener(type, emit2.single, options)), () => sync8(() => target.removeEventListener(type, emit2.single, options))), {
79457
79457
  bufferSize: typeof options === "object" ? options.bufferSize : undefined
79458
79458
  });
@@ -82473,7 +82473,7 @@ var DecodeExceptionTypeId, DecodeException = (input, message) => {
82473
82473
  [DecodeExceptionTypeId]: DecodeExceptionTypeId,
82474
82474
  input
82475
82475
  };
82476
- if (isString(message)) {
82476
+ if (isString2(message)) {
82477
82477
  out.message = message;
82478
82478
  }
82479
82479
  return out;
@@ -82483,16 +82483,16 @@ var DecodeExceptionTypeId, DecodeException = (input, message) => {
82483
82483
  [EncodeExceptionTypeId]: EncodeExceptionTypeId,
82484
82484
  input
82485
82485
  };
82486
- if (isString(message)) {
82486
+ if (isString2(message)) {
82487
82487
  out.message = message;
82488
82488
  }
82489
82489
  return out;
82490
- }, isEncodeException = (u) => hasProperty(u, EncodeExceptionTypeId), encoder2, decoder;
82490
+ }, isEncodeException = (u) => hasProperty(u, EncodeExceptionTypeId), encoder3, decoder;
82491
82491
  var init_common = __esm(() => {
82492
82492
  init_Predicate();
82493
82493
  DecodeExceptionTypeId = /* @__PURE__ */ Symbol.for("effect/Encoding/errors/Decode");
82494
82494
  EncodeExceptionTypeId = /* @__PURE__ */ Symbol.for("effect/Encoding/errors/Encode");
82495
- encoder2 = /* @__PURE__ */ new TextEncoder;
82495
+ encoder3 = /* @__PURE__ */ new TextEncoder;
82496
82496
  decoder = /* @__PURE__ */ new TextDecoder;
82497
82497
  });
82498
82498
 
@@ -82643,7 +82643,7 @@ __export(exports_Encoding, {
82643
82643
  DecodeExceptionTypeId: () => DecodeExceptionTypeId2,
82644
82644
  DecodeException: () => DecodeException2
82645
82645
  });
82646
- var encodeBase64 = (input) => typeof input === "string" ? encode4(encoder2.encode(input)) : encode4(input), decodeBase64 = (str) => decode5(str), decodeBase64String = (str) => map3(decodeBase64(str), (_) => decoder.decode(_)), encodeBase64Url = (input) => typeof input === "string" ? encode5(encoder2.encode(input)) : encode5(input), decodeBase64Url = (str) => decode6(str), decodeBase64UrlString = (str) => map3(decodeBase64Url(str), (_) => decoder.decode(_)), encodeHex = (input) => typeof input === "string" ? encode6(encoder2.encode(input)) : encode6(input), decodeHex = (str) => decode7(str), decodeHexString = (str) => map3(decodeHex(str), (_) => decoder.decode(_)), encodeUriComponent = (str) => try_({
82646
+ var encodeBase64 = (input) => typeof input === "string" ? encode4(encoder3.encode(input)) : encode4(input), decodeBase64 = (str) => decode5(str), decodeBase64String = (str) => map3(decodeBase64(str), (_) => decoder.decode(_)), encodeBase64Url = (input) => typeof input === "string" ? encode5(encoder3.encode(input)) : encode5(input), decodeBase64Url = (str) => decode6(str), decodeBase64UrlString = (str) => map3(decodeBase64Url(str), (_) => decoder.decode(_)), encodeHex = (input) => typeof input === "string" ? encode6(encoder3.encode(input)) : encode6(input), decodeHex = (str) => decode7(str), decodeHexString = (str) => map3(decodeHex(str), (_) => decoder.decode(_)), encodeUriComponent = (str) => try_({
82647
82647
  try: () => encodeURIComponent(str),
82648
82648
  catch: (e) => EncodeException2(str, e instanceof Error ? e.message : "Invalid input")
82649
82649
  }), decodeUriComponent = (str) => try_({
@@ -85339,7 +85339,7 @@ var ParseErrorTypeId2, isParseError2 = (u) => hasProperty(u, ParseErrorTypeId2),
85339
85339
  return self;
85340
85340
  }
85341
85341
  }, mapBoth10, orElse18, mergeInternalOptions = (options, overrideOptions) => {
85342
- if (overrideOptions === undefined || isNumber(overrideOptions)) {
85342
+ if (overrideOptions === undefined || isNumber2(overrideOptions)) {
85343
85343
  return options;
85344
85344
  }
85345
85345
  if (options === undefined) {
@@ -85455,9 +85455,9 @@ var ParseErrorTypeId2, isParseError2 = (u) => hasProperty(u, ParseErrorTypeId2),
85455
85455
  case "VoidKeyword":
85456
85456
  return right2;
85457
85457
  case "StringKeyword":
85458
- return fromRefinement(ast, isString);
85458
+ return fromRefinement(ast, isString2);
85459
85459
  case "NumberKeyword":
85460
- return fromRefinement(ast, isNumber);
85460
+ return fromRefinement(ast, isNumber2);
85461
85461
  case "BooleanKeyword":
85462
85462
  return fromRefinement(ast, isBoolean);
85463
85463
  case "BigIntKeyword":
@@ -85470,7 +85470,7 @@ var ParseErrorTypeId2, isParseError2 = (u) => hasProperty(u, ParseErrorTypeId2),
85470
85470
  return fromRefinement(ast, (u) => ast.enums.some(([_, value5]) => value5 === u));
85471
85471
  case "TemplateLiteral": {
85472
85472
  const regex = getTemplateLiteralRegExp(ast);
85473
- return fromRefinement(ast, (u) => isString(u) && regex.test(u));
85473
+ return fromRefinement(ast, (u) => isString2(u) && regex.test(u));
85474
85474
  }
85475
85475
  case "TupleType": {
85476
85476
  const elements = ast.elements.map((e) => goMemo(e.type, isDecoding));
@@ -86137,7 +86137,7 @@ var ParseErrorTypeId2, isParseError2 = (u) => hasProperty(u, ParseErrorTypeId2),
86137
86137
  onNone: () => Either_void,
86138
86138
  onSome: (messageAnnotation) => {
86139
86139
  const union17 = messageAnnotation(issue3);
86140
- if (isString(union17)) {
86140
+ if (isString2(union17)) {
86141
86141
  return right2({
86142
86142
  message: union17,
86143
86143
  override: false
@@ -86149,7 +86149,7 @@ var ParseErrorTypeId2, isParseError2 = (u) => hasProperty(u, ParseErrorTypeId2),
86149
86149
  override: false
86150
86150
  }));
86151
86151
  }
86152
- if (isString(union17.message)) {
86152
+ if (isString2(union17.message)) {
86153
86153
  return right2({
86154
86154
  message: union17.message,
86155
86155
  override: union17.override
@@ -86170,7 +86170,7 @@ var ParseErrorTypeId2, isParseError2 = (u) => hasProperty(u, ParseErrorTypeId2),
86170
86170
  const missingMessageAnnotation = getMissingMessageAnnotation(issue3.ast);
86171
86171
  if (isSome2(missingMessageAnnotation)) {
86172
86172
  const annotation = missingMessageAnnotation.value();
86173
- return isString(annotation) ? right2(annotation) : annotation;
86173
+ return isString2(annotation) ? right2(annotation) : annotation;
86174
86174
  }
86175
86175
  return right2(issue3.message ?? "is missing");
86176
86176
  }, formatTree = (issue3) => {
@@ -86621,12 +86621,12 @@ function go3(ast, $defs, identifier2, path, options, annotation, errors5) {
86621
86621
  return addASTAnnotations({
86622
86622
  type: "null"
86623
86623
  }, ast);
86624
- } else if (isString(literal5)) {
86624
+ } else if (isString2(literal5)) {
86625
86625
  return addASTAnnotations({
86626
86626
  type: "string",
86627
86627
  enum: [literal5]
86628
86628
  }, ast);
86629
- } else if (isNumber(literal5)) {
86629
+ } else if (isNumber2(literal5)) {
86630
86630
  return addASTAnnotations({
86631
86631
  type: "number",
86632
86632
  enum: [literal5]
@@ -86643,7 +86643,7 @@ function go3(ast, $defs, identifier2, path, options, annotation, errors5) {
86643
86643
  }
86644
86644
  case "Enums": {
86645
86645
  const anyOf = ast.enums.map((e) => {
86646
- const type = isNumber(e[1]) ? "number" : "string";
86646
+ const type = isNumber2(e[1]) ? "number" : "string";
86647
86647
  return {
86648
86648
  type,
86649
86649
  title: e[0],
@@ -86751,7 +86751,7 @@ function go3(ast, $defs, identifier2, path, options, annotation, errors5) {
86751
86751
  for (let i = 0;i < ast.propertySignatures.length; i++) {
86752
86752
  const ps = ast.propertySignatures[i];
86753
86753
  const name24 = ps.name;
86754
- if (isString(name24)) {
86754
+ if (isString2(name24)) {
86755
86755
  const pruned = pruneUndefined3(ps.type);
86756
86756
  const type = pruned ?? ps.type;
86757
86757
  output.properties[name24] = mergeJsonSchemaAnnotations(go3(type, $defs, "handle-identifier", path.concat(ps.name), options, "handle-annotation", errors5), getContextJsonSchemaAnnotations(type, ps));
@@ -86818,15 +86818,15 @@ function go3(ast, $defs, identifier2, path, options, annotation, errors5) {
86818
86818
  for (const t of ast.transformation.propertySignatureTransformations) {
86819
86819
  const toKey = t.to;
86820
86820
  const fromKey = t.from;
86821
- if (isString(toKey) && isString(fromKey)) {
86821
+ if (isString2(toKey) && isString2(fromKey)) {
86822
86822
  const toProperty2 = to.properties[toKey];
86823
86823
  if (isRecord2(toProperty2)) {
86824
86824
  const fromProperty = from.properties[fromKey];
86825
86825
  if (isRecord2(fromProperty)) {
86826
86826
  const annotations2 = {};
86827
- if (isString(toProperty2.title))
86827
+ if (isString2(toProperty2.title))
86828
86828
  annotations2.title = toProperty2.title;
86829
- if (isString(toProperty2.description))
86829
+ if (isString2(toProperty2.description))
86830
86830
  annotations2.description = toProperty2.description;
86831
86831
  if (Array.isArray(toProperty2.examples))
86832
86832
  annotations2.examples = toProperty2.examples;
@@ -88703,8 +88703,8 @@ var init_Match = __esm(() => {
88703
88703
  not4 = not3;
88704
88704
  nonEmptyString4 = nonEmptyString3;
88705
88705
  is3 = is2;
88706
- string11 = isString;
88707
- number10 = isNumber;
88706
+ string11 = isString2;
88707
+ number10 = isNumber2;
88708
88708
  any4 = any3;
88709
88709
  defined2 = defined;
88710
88710
  boolean10 = isBoolean;
@@ -90723,7 +90723,7 @@ function getTemplateLiteralParserCoercedElement(encoded, schema) {
90723
90723
  switch (ast._tag) {
90724
90724
  case "Literal": {
90725
90725
  const literal5 = ast.literal;
90726
- if (!isString(literal5)) {
90726
+ if (!isString2(literal5)) {
90727
90727
  const s = String(literal5);
90728
90728
  return transform5(Literal2(s), schema, {
90729
90729
  strict: true,
@@ -91314,11 +91314,11 @@ var TypeId42, variance11, makeStandardResult = (exit4) => isSuccess(exit4) ? exi
91314
91314
  constructor
91315
91315
  },
91316
91316
  ...annotations2
91317
- }), Undefined, Void, Null, Never, Unknown, Any, BigIntFromSelf, SymbolFromSelf, String$, Number$, Boolean$, Object$, getDefaultUnionAST = (members) => Union.make(members.map((m) => m.ast)), NullOr = (self) => Union2(self, Null), UndefinedOr = (self) => Union2(self, Undefined), NullishOr = (self) => Union2(self, Null, Undefined), keyof4 = (self) => make115(keyof3(self.ast)), element = (self) => new ElementImpl(new OptionalType(self.ast, false), self), optionalElement = (self) => new ElementImpl(new OptionalType(self.ast, true), self), ElementImpl, getDefaultTupleTypeAST = (elements, rest) => new TupleType(elements.map((el) => isSchema2(el) ? new OptionalType(el.ast, false) : el.ast), rest.map((el) => isSchema2(el) ? new Type(el.ast) : el.ast), true), Array$ = (value9) => makeArrayClass(value9), NonEmptyArray = (value9) => makeNonEmptyArrayClass(value9), formatPropertySignatureToken = (isOptional) => isOptional ? '"?:"' : '":"', PropertySignatureDeclaration, FromPropertySignature, ToPropertySignature, formatPropertyKey2 = (p) => {
91317
+ }), Undefined, Void, Null, Never, Unknown, Any, BigIntFromSelf, SymbolFromSelf, String$, Number$, Boolean$, Object$, getDefaultUnionAST = (members) => Union.make(members.map((m) => m.ast)), NullOr = (self) => Union2(self, Null), UndefinedOr = (self) => Union2(self, Undefined), NullishOr = (self) => Union2(self, Null, Undefined), keyof4 = (self) => make115(keyof3(self.ast)), element = (self) => new ElementImpl(new OptionalType(self.ast, false), self), optionalElement = (self) => new ElementImpl(new OptionalType(self.ast, true), self), ElementImpl, getDefaultTupleTypeAST = (elements, rest) => new TupleType(elements.map((el) => isSchema2(el) ? new OptionalType(el.ast, false) : el.ast), rest.map((el) => isSchema2(el) ? new Type(el.ast) : el.ast), true), Array$ = (value9) => makeArrayClass(value9), NonEmptyArray = (value9) => makeNonEmptyArrayClass(value9), formatPropertySignatureToken = (isOptional2) => isOptional2 ? '"?:"' : '":"', PropertySignatureDeclaration, FromPropertySignature, ToPropertySignature, formatPropertyKey2 = (p) => {
91318
91318
  if (p === undefined) {
91319
91319
  return "never";
91320
91320
  }
91321
- if (isString(p)) {
91321
+ if (isString2(p)) {
91322
91322
  return JSON.stringify(p);
91323
91323
  }
91324
91324
  return String(p);
@@ -91454,11 +91454,11 @@ var TypeId42, variance11, makeStandardResult = (exit4) => isSuccess(exit4) ? exi
91454
91454
  switch (ast._tag) {
91455
91455
  case "PropertySignatureDeclaration": {
91456
91456
  const type3 = ast.type;
91457
- const isOptional = ast.isOptional;
91457
+ const isOptional2 = ast.isOptional;
91458
91458
  const toAnnotations = ast.annotations;
91459
- from.push(new PropertySignature(key, type3, isOptional, true, preserveMissingMessageAnnotation(ast)));
91460
- to.push(new PropertySignature(key, typeAST(type3), isOptional, true, toAnnotations));
91461
- pss.push(new PropertySignature(key, type3, isOptional, true, toAnnotations));
91459
+ from.push(new PropertySignature(key, type3, isOptional2, true, preserveMissingMessageAnnotation(ast)));
91460
+ to.push(new PropertySignature(key, typeAST(type3), isOptional2, true, toAnnotations));
91461
+ pss.push(new PropertySignature(key, type3, isOptional2, true, toAnnotations));
91462
91462
  break;
91463
91463
  }
91464
91464
  case "PropertySignatureTransformation": {
@@ -91545,10 +91545,10 @@ var TypeId42, variance11, makeStandardResult = (exit4) => isSuccess(exit4) ? exi
91545
91545
  propertySignatures.push(ps);
91546
91546
  } else {
91547
91547
  const {
91548
- isOptional,
91548
+ isOptional: isOptional2,
91549
91549
  type: type3
91550
91550
  } = propertySignatures[i];
91551
- propertySignatures[i] = new PropertySignature(name24, extendAST(type3, ps.type, path.concat(name24)), isOptional, true);
91551
+ propertySignatures[i] = new PropertySignature(name24, extendAST(type3, ps.type, path.concat(name24)), isOptional2, true);
91552
91552
  }
91553
91553
  }
91554
91554
  return new TypeLiteral(propertySignatures, x.indexSignatures.concat(y.indexSignatures));
@@ -91557,14 +91557,14 @@ var TypeId42, variance11, makeStandardResult = (exit4) => isSuccess(exit4) ? exi
91557
91557
  }, preserveRefinementAnnotations, addRefinementToMembers = (refinement, asts) => asts.map((ast) => new Refinement(ast, refinement.filter, preserveRefinementAnnotations(refinement))), extendAST = (x, y, path) => Union.make(intersectUnionMembers([x], [y], path)), getTypes = (ast) => isUnion(ast) ? ast.types : [ast], intersectUnionMembers = (xs, ys, path) => flatMap4(xs, (x) => flatMap4(ys, (y) => {
91558
91558
  switch (y._tag) {
91559
91559
  case "Literal": {
91560
- if (isString(y.literal) && isStringKeyword(x) || isNumber(y.literal) && isNumberKeyword(x) || isBoolean(y.literal) && isBooleanKeyword(x)) {
91560
+ if (isString2(y.literal) && isStringKeyword(x) || isNumber2(y.literal) && isNumberKeyword(x) || isBoolean(y.literal) && isBooleanKeyword(x)) {
91561
91561
  return [y];
91562
91562
  }
91563
91563
  break;
91564
91564
  }
91565
91565
  case "StringKeyword": {
91566
91566
  if (y === stringKeyword) {
91567
- if (isStringKeyword(x) || isLiteral(x) && isString(x.literal)) {
91567
+ if (isStringKeyword(x) || isLiteral(x) && isString2(x.literal)) {
91568
91568
  return [x];
91569
91569
  } else if (isRefinement(x)) {
91570
91570
  return addRefinementToMembers(x, intersectUnionMembers(getTypes(x.from), [y], path));
@@ -91576,7 +91576,7 @@ var TypeId42, variance11, makeStandardResult = (exit4) => isSuccess(exit4) ? exi
91576
91576
  }
91577
91577
  case "NumberKeyword": {
91578
91578
  if (y === numberKeyword) {
91579
- if (isNumberKeyword(x) || isLiteral(x) && isNumber(x.literal)) {
91579
+ if (isNumberKeyword(x) || isLiteral(x) && isNumber2(x.literal)) {
91580
91580
  return [x];
91581
91581
  } else if (isRefinement(x)) {
91582
91582
  return addRefinementToMembers(x, intersectUnionMembers(getTypes(x.from), [y], path));
@@ -91652,7 +91652,7 @@ var TypeId42, variance11, makeStandardResult = (exit4) => isSuccess(exit4) ? exi
91652
91652
  if (isBoolean(item)) {
91653
91653
  return item ? none2() : some3(new Type2(ast, input));
91654
91654
  }
91655
- if (isString(item)) {
91655
+ if (isString2(item)) {
91656
91656
  return some3(new Type2(ast, input, item));
91657
91657
  }
91658
91658
  if (item !== undefined) {
@@ -93381,8 +93381,8 @@ var init_Schema = __esm(() => {
93381
93381
  isReadonly;
93382
93382
  defaultValue;
93383
93383
  _tag = "PropertySignatureDeclaration";
93384
- constructor(type3, isOptional, isReadonly, annotations2, defaultValue) {
93385
- super(type3, isOptional, annotations2);
93384
+ constructor(type3, isOptional2, isReadonly, annotations2, defaultValue) {
93385
+ super(type3, isOptional2, annotations2);
93386
93386
  this.isReadonly = isReadonly;
93387
93387
  this.defaultValue = defaultValue;
93388
93388
  }
@@ -93395,8 +93395,8 @@ var init_Schema = __esm(() => {
93395
93395
  FromPropertySignature = class FromPropertySignature extends OptionalType {
93396
93396
  isReadonly;
93397
93397
  fromKey;
93398
- constructor(type3, isOptional, isReadonly, annotations2, fromKey) {
93399
- super(type3, isOptional, annotations2);
93398
+ constructor(type3, isOptional2, isReadonly, annotations2, fromKey) {
93399
+ super(type3, isOptional2, annotations2);
93400
93400
  this.isReadonly = isReadonly;
93401
93401
  this.fromKey = fromKey;
93402
93402
  }
@@ -93404,8 +93404,8 @@ var init_Schema = __esm(() => {
93404
93404
  ToPropertySignature = class ToPropertySignature extends OptionalType {
93405
93405
  isReadonly;
93406
93406
  defaultValue;
93407
- constructor(type3, isOptional, isReadonly, annotations2, defaultValue) {
93408
- super(type3, isOptional, annotations2);
93407
+ constructor(type3, isOptional2, isReadonly, annotations2, defaultValue) {
93408
+ super(type3, isOptional2, annotations2);
93409
93409
  this.isReadonly = isReadonly;
93410
93410
  this.defaultValue = defaultValue;
93411
93411
  }
@@ -99388,7 +99388,7 @@ var require_Sury_res = __commonJS((exports) => {
99388
99388
  var itemSymbol = Symbol(vendor + ":item");
99389
99389
  var $$Error = /* @__PURE__ */ create("Sury.Error");
99390
99390
  var isLiteral2 = (s2) => ("const" in s2);
99391
- function isOptional(schema2) {
99391
+ function isOptional2(schema2) {
99392
99392
  var match43 = schema2.type;
99393
99393
  switch (match43) {
99394
99394
  case "undefined":
@@ -101089,7 +101089,7 @@ var require_Sury_res = __commonJS((exports) => {
101089
101089
  var anyOf = reversed3.anyOf;
101090
101090
  if (anyOf !== undefined) {
101091
101091
  return factory(anyOf.filter(function(s2) {
101092
- return !isOptional(s2);
101092
+ return !isOptional2(s2);
101093
101093
  }));
101094
101094
  } else {
101095
101095
  return reversed3;
@@ -103044,7 +103044,7 @@ var require_Sury_res = __commonJS((exports) => {
103044
103044
  var required5 = [];
103045
103045
  schema2.items.forEach(function(item2) {
103046
103046
  var fieldSchema = internalToJSONSchema(item2.schema);
103047
- if (!isOptional(item2.schema)) {
103047
+ if (!isOptional2(item2.schema)) {
103048
103048
  required5.push(item2.location);
103049
103049
  }
103050
103050
  properties[item2.location] = fieldSchema;
@@ -108855,33 +108855,8 @@ function combineHeaders(...headers) {
108855
108855
  ...currentHeaders != null ? currentHeaders : {}
108856
108856
  }), {});
108857
108857
  }
108858
- var { btoa: btoa2, atob: atob2 } = globalThis;
108859
- function convertBase64ToUint8Array(base64String) {
108860
- const base64Url = base64String.replace(/-/g, "+").replace(/_/g, "/");
108861
- const latin1string = atob2(base64Url);
108862
- return Uint8Array.from(latin1string, (byte) => byte.codePointAt(0));
108863
- }
108864
- function convertUint8ArrayToBase64(array2) {
108865
- let latin1string = "";
108866
- for (let i = 0;i < array2.length; i++) {
108867
- latin1string += String.fromCodePoint(array2[i]);
108868
- }
108869
- return btoa2(latin1string);
108870
- }
108871
- function convertToBase64(value) {
108872
- return value instanceof Uint8Array ? convertUint8ArrayToBase64(value) : value;
108873
- }
108874
- function convertInlineFileDataToUint8Array(data) {
108875
- if (data.type === "text") {
108876
- return new TextEncoder().encode(data.text);
108877
- }
108878
- if (data.data instanceof Uint8Array) {
108879
- return data.data;
108880
- }
108881
- if (data.data instanceof ArrayBuffer) {
108882
- return new Uint8Array(data.data);
108883
- }
108884
- return convertBase64ToUint8Array(data.data);
108858
+ function removeUndefinedEntries(record2) {
108859
+ return Object.fromEntries(Object.entries(record2).filter(([_key, value]) => value != null));
108885
108860
  }
108886
108861
  async function delay(delayInMs, options) {
108887
108862
  if (delayInMs == null) {
@@ -108911,6 +108886,134 @@ async function delay(delayInMs, options) {
108911
108886
  function createAbortError() {
108912
108887
  return new DOMException("Delay was aborted", "AbortError");
108913
108888
  }
108889
+ function getWebSocketConstructor(webSocket) {
108890
+ const WebSocketConstructor = webSocket != null ? webSocket : globalThis.WebSocket;
108891
+ if (WebSocketConstructor == null) {
108892
+ throw new Error("No WebSocket implementation available.");
108893
+ }
108894
+ return WebSocketConstructor;
108895
+ }
108896
+ var textDecoder = new TextDecoder;
108897
+ async function readWebSocketMessageText(data) {
108898
+ if (typeof data === "string")
108899
+ return data;
108900
+ if (data instanceof ArrayBuffer)
108901
+ return textDecoder.decode(data);
108902
+ if (ArrayBuffer.isView(data)) {
108903
+ return textDecoder.decode(data);
108904
+ }
108905
+ if (typeof Blob !== "undefined" && data instanceof Blob) {
108906
+ return data.text();
108907
+ }
108908
+ return String(data);
108909
+ }
108910
+ var WEBSOCKET_OPEN_STATE = 1;
108911
+ async function waitForWebSocketBufferDrain(socket, {
108912
+ highWaterMark = 1024 * 1024,
108913
+ pollIntervalMs = 20,
108914
+ abortSignal
108915
+ } = {}) {
108916
+ var _a22;
108917
+ while (socket.readyState === WEBSOCKET_OPEN_STATE && ((_a22 = socket.bufferedAmount) != null ? _a22 : 0) > highWaterMark) {
108918
+ if ((abortSignal == null ? undefined : abortSignal.aborted) === true) {
108919
+ return;
108920
+ }
108921
+ await delay(pollIntervalMs);
108922
+ }
108923
+ }
108924
+ function connectToWebSocket({
108925
+ url: url2,
108926
+ protocols,
108927
+ headers,
108928
+ webSocket,
108929
+ abortSignal,
108930
+ onOpen,
108931
+ onMessageText,
108932
+ onProcessingError,
108933
+ onSocketError,
108934
+ onClose,
108935
+ onAbort
108936
+ }) {
108937
+ var _a22;
108938
+ let socket;
108939
+ let abortListener;
108940
+ const close = (code) => {
108941
+ if (abortListener != null) {
108942
+ abortSignal == null || abortSignal.removeEventListener("abort", abortListener);
108943
+ abortListener = undefined;
108944
+ }
108945
+ try {
108946
+ socket == null || socket.close(code);
108947
+ } catch (e) {}
108948
+ };
108949
+ if (abortSignal == null ? undefined : abortSignal.aborted) {
108950
+ onAbort == null || onAbort((_a22 = abortSignal.reason) != null ? _a22 : new Error("Aborted"));
108951
+ return { socket: undefined, close };
108952
+ }
108953
+ try {
108954
+ const WebSocketConstructor = getWebSocketConstructor(webSocket);
108955
+ socket = new WebSocketConstructor(url2, protocols, {
108956
+ headers: removeUndefinedEntries(headers != null ? headers : {})
108957
+ });
108958
+ } catch (error51) {
108959
+ onProcessingError(error51);
108960
+ return { socket: undefined, close };
108961
+ }
108962
+ if (abortSignal != null && onAbort != null) {
108963
+ abortListener = () => {
108964
+ var _a32;
108965
+ return onAbort((_a32 = abortSignal.reason) != null ? _a32 : new Error("Aborted"));
108966
+ };
108967
+ abortSignal.addEventListener("abort", abortListener, { once: true });
108968
+ }
108969
+ const openedSocket = socket;
108970
+ socket.onopen = () => {
108971
+ try {
108972
+ onOpen == null || onOpen(openedSocket);
108973
+ } catch (error51) {
108974
+ onProcessingError(error51);
108975
+ }
108976
+ };
108977
+ let tail = Promise.resolve();
108978
+ socket.onmessage = (event) => {
108979
+ tail = tail.then(() => readWebSocketMessageText(event.data)).then((text) => onMessageText(text)).catch(onProcessingError);
108980
+ };
108981
+ socket.onerror = () => {
108982
+ tail = tail.then(() => onSocketError == null ? undefined : onSocketError()).catch(onProcessingError);
108983
+ };
108984
+ socket.onclose = () => {
108985
+ tail = tail.then(() => onClose == null ? undefined : onClose()).catch(onProcessingError);
108986
+ };
108987
+ return { socket, close };
108988
+ }
108989
+ var { btoa: btoa2, atob: atob2 } = globalThis;
108990
+ function convertBase64ToUint8Array(base64String) {
108991
+ const base64Url = base64String.replace(/-/g, "+").replace(/_/g, "/");
108992
+ const latin1string = atob2(base64Url);
108993
+ return Uint8Array.from(latin1string, (byte) => byte.codePointAt(0));
108994
+ }
108995
+ function convertUint8ArrayToBase64(array2) {
108996
+ let latin1string = "";
108997
+ for (let i = 0;i < array2.length; i++) {
108998
+ latin1string += String.fromCodePoint(array2[i]);
108999
+ }
109000
+ return btoa2(latin1string);
109001
+ }
109002
+ function convertToBase64(value) {
109003
+ return value instanceof Uint8Array ? convertUint8ArrayToBase64(value) : value;
109004
+ }
109005
+ function convertInlineFileDataToUint8Array(data) {
109006
+ if (data.type === "text") {
109007
+ return new TextEncoder().encode(data.text);
109008
+ }
109009
+ if (data.data instanceof Uint8Array) {
109010
+ return data.data;
109011
+ }
109012
+ if (data.data instanceof ArrayBuffer) {
109013
+ return new Uint8Array(data.data);
109014
+ }
109015
+ return convertBase64ToUint8Array(data.data);
109016
+ }
108914
109017
  var imageMediaTypeSignatures = [
108915
109018
  {
108916
109019
  mediaType: "image/gif",
@@ -108994,7 +109097,7 @@ var documentMediaTypeSignatures = [
108994
109097
  bytesPrefix: [37, 80, 68, 70]
108995
109098
  }
108996
109099
  ];
108997
- var audioMediaTypeSignatures = [
109100
+ var audioMediaTypeSignaturesWithoutMp4 = [
108998
109101
  {
108999
109102
  mediaType: "audio/mpeg",
109000
109103
  bytesPrefix: [255, 251]
@@ -109048,15 +109151,27 @@ var audioMediaTypeSignatures = [
109048
109151
  mediaType: "audio/aac",
109049
109152
  bytesPrefix: [64, 21, 0, 0]
109050
109153
  },
109051
- {
109052
- mediaType: "audio/mp4",
109053
- bytesPrefix: [102, 116, 121, 112]
109054
- },
109055
109154
  {
109056
109155
  mediaType: "audio/webm",
109057
109156
  bytesPrefix: [26, 69, 223, 163]
109058
109157
  }
109059
109158
  ];
109159
+ var audioMediaTypeSignatures = [
109160
+ ...audioMediaTypeSignaturesWithoutMp4,
109161
+ {
109162
+ mediaType: "audio/mp4",
109163
+ bytesPrefix: [
109164
+ 0,
109165
+ 0,
109166
+ 0,
109167
+ null,
109168
+ 102,
109169
+ 116,
109170
+ 121,
109171
+ 112
109172
+ ]
109173
+ }
109174
+ ];
109060
109175
  var videoMediaTypeSignatures = [
109061
109176
  {
109062
109177
  mediaType: "video/mp4",
@@ -109095,21 +109210,33 @@ var videoMediaTypeSignatures = [
109095
109210
  bytesPrefix: [82, 73, 70, 70]
109096
109211
  }
109097
109212
  ];
109098
- var stripID3 = (data) => {
109099
- const bytes = typeof data === "string" ? convertBase64ToUint8Array(data) : data;
109213
+ var DEFAULT_SNIFF_BYTES = 18;
109214
+ var MAX_SIGNATURE_BYTES = 12;
109215
+ var MAX_ID3_TAG_BYTES = 128 * 1024;
109216
+ var ID3_SCAN_BYTES = MAX_ID3_TAG_BYTES + MAX_SIGNATURE_BYTES;
109217
+ function decodePrefix(data, maxBytes) {
109218
+ if (typeof data !== "string") {
109219
+ return data.length > maxBytes ? data.subarray(0, maxBytes) : data;
109220
+ }
109221
+ const maxChars = Math.ceil(maxBytes / 3) * 4;
109222
+ const bytes = convertBase64ToUint8Array(data.substring(0, Math.min(data.length, maxChars)));
109223
+ return bytes.length > maxBytes ? bytes.subarray(0, maxBytes) : bytes;
109224
+ }
109225
+ function hasID3(bytes) {
109226
+ return bytes.length > 10 && bytes[0] === 73 && bytes[1] === 68 && bytes[2] === 51;
109227
+ }
109228
+ var stripID3 = (bytes) => {
109100
109229
  const id3Size = (bytes[6] & 127) << 21 | (bytes[7] & 127) << 14 | (bytes[8] & 127) << 7 | bytes[9] & 127;
109101
- return bytes.slice(id3Size + 10);
109230
+ return bytes.subarray(id3Size + 10);
109102
109231
  };
109103
- function stripID3TagsIfPresent(data) {
109104
- const hasId3 = typeof data === "string" && data.startsWith("SUQz") || typeof data !== "string" && data.length > 10 && data[0] === 73 && data[1] === 68 && data[2] === 51;
109105
- return hasId3 ? stripID3(data) : data;
109106
- }
109107
109232
  function detectMediaTypeBySignatures({
109108
109233
  data,
109109
109234
  signatures
109110
109235
  }) {
109111
- const processedData = stripID3TagsIfPresent(data);
109112
- const bytes = typeof processedData === "string" ? convertBase64ToUint8Array(processedData.substring(0, Math.min(processedData.length, 24))) : processedData;
109236
+ let bytes = decodePrefix(data, DEFAULT_SNIFF_BYTES);
109237
+ if (hasID3(bytes)) {
109238
+ bytes = stripID3(decodePrefix(data, ID3_SCAN_BYTES));
109239
+ }
109113
109240
  for (const signature of signatures) {
109114
109241
  if (bytes.length >= signature.bytesPrefix.length && signature.bytesPrefix.every((byte, index) => byte === null || bytes[index] === byte)) {
109115
109242
  return signature.mediaType;
@@ -109133,7 +109260,7 @@ function detectMediaType({
109133
109260
  signatures: [
109134
109261
  ...imageMediaTypeSignatures,
109135
109262
  ...documentMediaTypeSignatures,
109136
- ...audioMediaTypeSignatures,
109263
+ ...audioMediaTypeSignaturesWithoutMp4,
109137
109264
  ...videoMediaTypeSignatures
109138
109265
  ]
109139
109266
  });
@@ -109188,6 +109315,42 @@ var DownloadError = class extends (_b16 = AISDKError, _a19 = symbol18, _b16) {
109188
109315
  function isBrowserRuntime(globalThisAny = globalThis) {
109189
109316
  return globalThisAny.window != null;
109190
109317
  }
109318
+ function isSameOrigin(url2, baseUrl) {
109319
+ try {
109320
+ return new URL(url2).origin === new URL(baseUrl).origin;
109321
+ } catch (e) {
109322
+ return false;
109323
+ }
109324
+ }
109325
+ var BLOCKED_REQUEST_HEADERS = [
109326
+ "connection",
109327
+ "keep-alive",
109328
+ "te",
109329
+ "trailer",
109330
+ "transfer-encoding",
109331
+ "upgrade",
109332
+ "host",
109333
+ "forwarded",
109334
+ "proxy-authorization",
109335
+ "via",
109336
+ "x-forwarded-for",
109337
+ "x-forwarded-host",
109338
+ "x-forwarded-proto",
109339
+ "x-real-ip",
109340
+ "metadata",
109341
+ "metadata-flavor",
109342
+ "x-aws-ec2-metadata-token",
109343
+ "x-metadata-token",
109344
+ "cookie",
109345
+ "set-cookie"
109346
+ ];
109347
+ function sanitizeRequestHeaders(input) {
109348
+ const headers = new Headers(input);
109349
+ for (const name22 of BLOCKED_REQUEST_HEADERS) {
109350
+ headers.delete(name22);
109351
+ }
109352
+ return headers;
109353
+ }
109191
109354
  function validateDownloadUrl(url2) {
109192
109355
  let parsed;
109193
109356
  try {
@@ -109266,11 +109429,17 @@ function isPrivateIPv4(ip) {
109266
109429
  return true;
109267
109430
  if (a === 192 && b === 0 && c === 0)
109268
109431
  return true;
109432
+ if (a === 192 && b === 0 && c === 2)
109433
+ return true;
109269
109434
  if (a === 192 && b === 168)
109270
109435
  return true;
109271
109436
  if (a === 198 && (b === 18 || b === 19))
109272
109437
  return true;
109273
- if (a >= 240)
109438
+ if (a === 198 && b === 51 && c === 100)
109439
+ return true;
109440
+ if (a === 203 && b === 0 && c === 113)
109441
+ return true;
109442
+ if (a >= 224)
109274
109443
  return true;
109275
109444
  return false;
109276
109445
  }
@@ -109332,6 +109501,10 @@ function isPrivateIPv6(ip) {
109332
109501
  return true;
109333
109502
  if ((groups[0] & 65280) === 65280)
109334
109503
  return true;
109504
+ if (groups[0] === 8193 && groups[1] === 3512)
109505
+ return true;
109506
+ if (groups[0] === 16383 && (groups[1] & 61440) === 0)
109507
+ return true;
109335
109508
  const embedsIPv4 = topZero(6) || topZero(5) && groups[5] === 65535 || topZero(4) && groups[4] === 65535 && groups[5] === 0 || groups[0] === 100 && groups[1] === 65435 && groups[2] === 0 && groups[3] === 0 && groups[4] === 0 && groups[5] === 0 || groups[0] === 100 && groups[1] === 65435 && groups[2] === 1;
109336
109509
  if (embedsIPv4) {
109337
109510
  const a = groups[6] >> 8 & 255;
@@ -109343,23 +109516,29 @@ function isPrivateIPv6(ip) {
109343
109516
  return false;
109344
109517
  }
109345
109518
  var MAX_DOWNLOAD_REDIRECTS = 10;
109519
+ var REDIRECT_STATUS_CODES = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]);
109346
109520
  async function fetchWithValidatedRedirects({
109347
109521
  url: url2,
109348
109522
  headers,
109349
109523
  abortSignal,
109350
- maxRedirects = MAX_DOWNLOAD_REDIRECTS
109524
+ maxRedirects = MAX_DOWNLOAD_REDIRECTS,
109525
+ fetch: fetch2 = globalThis.fetch,
109526
+ trustedOrigin
109351
109527
  }) {
109352
- const baseInit = { signal: abortSignal };
109353
- if (headers !== undefined) {
109354
- baseInit.headers = headers;
109355
- }
109528
+ let currentHeaders = headers === undefined ? undefined : sanitizeRequestHeaders(headers);
109529
+ const perHopInit = (redirect) => {
109530
+ const init = { signal: abortSignal, redirect };
109531
+ if (currentHeaders !== undefined) {
109532
+ init.headers = new Headers(currentHeaders);
109533
+ }
109534
+ return init;
109535
+ };
109356
109536
  let currentUrl = url2;
109357
109537
  for (let redirectCount = 0;redirectCount <= maxRedirects; redirectCount++) {
109358
- validateDownloadUrl(currentUrl);
109359
- const response = await fetch(currentUrl, {
109360
- ...baseInit,
109361
- redirect: "manual"
109362
- });
109538
+ if (trustedOrigin === undefined || !isSameOrigin(currentUrl, trustedOrigin)) {
109539
+ validateDownloadUrl(currentUrl);
109540
+ }
109541
+ const response = await fetch2(currentUrl, perHopInit("manual"));
109363
109542
  if (response.type === "opaqueredirect") {
109364
109543
  if (!isBrowserRuntime()) {
109365
109544
  throw new DownloadError({
@@ -109367,12 +109546,17 @@ async function fetchWithValidatedRedirects({
109367
109546
  message: `Redirect from ${currentUrl} could not be validated and was blocked`
109368
109547
  });
109369
109548
  }
109370
- return await fetch(currentUrl, { ...baseInit, redirect: "follow" });
109549
+ return await fetch2(currentUrl, perHopInit("follow"));
109371
109550
  }
109372
109551
  const location = response.headers.get("location");
109373
- if (response.status >= 300 && response.status < 400 && location) {
109552
+ if (REDIRECT_STATUS_CODES.has(response.status) && location) {
109374
109553
  await cancelResponseBody(response);
109375
- currentUrl = new URL(location, currentUrl).toString();
109554
+ const nextUrl = new URL(location, currentUrl).toString();
109555
+ if (currentHeaders !== undefined && !isSameOrigin(nextUrl, currentUrl)) {
109556
+ const userAgent = currentHeaders.get("user-agent");
109557
+ currentHeaders = new Headers(userAgent == null ? undefined : { "user-agent": userAgent });
109558
+ }
109559
+ currentUrl = nextUrl;
109376
109560
  continue;
109377
109561
  }
109378
109562
  return response;
@@ -109565,7 +109749,7 @@ function withUserAgentSuffix(headers, ...userAgentSuffixParts) {
109565
109749
  normalizedHeaders.set("user-agent", [currentUserAgentHeader, ...userAgentSuffixParts].filter(Boolean).join(" "));
109566
109750
  return Object.fromEntries(normalizedHeaders.entries());
109567
109751
  }
109568
- var VERSION = "5.0.6";
109752
+ var VERSION = "5.0.12";
109569
109753
  var getOriginalFetch = () => globalThis.fetch;
109570
109754
  var getFromApi = async ({
109571
109755
  url: url2,
@@ -109573,12 +109757,23 @@ var getFromApi = async ({
109573
109757
  successfulResponseHandler,
109574
109758
  failedResponseHandler,
109575
109759
  abortSignal,
109576
- fetch: fetch2 = getOriginalFetch()
109760
+ fetch: fetch2 = getOriginalFetch(),
109761
+ validateUrl,
109762
+ credentialedOrigin,
109763
+ trustedOrigin
109577
109764
  }) => {
109578
109765
  try {
109579
- const response = await fetch2(url2, {
109766
+ const outgoingHeaders = credentialedOrigin !== undefined && !isSameOrigin(url2, credentialedOrigin) ? {} : headers;
109767
+ const requestHeaders = withUserAgentSuffix(outgoingHeaders, `ai-sdk/provider-utils/${VERSION}`, getRuntimeEnvironmentUserAgent());
109768
+ const response = validateUrl ? await fetchWithValidatedRedirects({
109769
+ url: url2,
109770
+ headers: requestHeaders,
109771
+ abortSignal,
109772
+ fetch: fetch2,
109773
+ trustedOrigin
109774
+ }) : await fetch2(url2, {
109580
109775
  method: "GET",
109581
- headers: withUserAgentSuffix(headers, `ai-sdk/provider-utils/${VERSION}`, getRuntimeEnvironmentUserAgent()),
109776
+ headers: requestHeaders,
109582
109777
  signal: abortSignal
109583
109778
  });
109584
109779
  const responseHeaders = extractResponseHeaders(response);
@@ -109634,13 +109829,6 @@ function isBuffer(value) {
109634
109829
  var _a22, _b22;
109635
109830
  return (_b22 = (_a22 = globalThis.Buffer) == null ? undefined : _a22.isBuffer(value)) != null ? _b22 : false;
109636
109831
  }
109637
- function isSameOrigin(url2, baseUrl) {
109638
- try {
109639
- return new URL(url2).origin === new URL(baseUrl).origin;
109640
- } catch (e) {
109641
- return false;
109642
- }
109643
- }
109644
109832
  function isProviderReference(data) {
109645
109833
  return typeof data === "object" && data !== null && !(data instanceof Uint8Array) && !(data instanceof URL) && !(data instanceof ArrayBuffer) && !isBuffer(data) && !("type" in data);
109646
109834
  }
@@ -110876,9 +111064,14 @@ function asSchema(schema) {
110876
111064
  }) : isSchema(schema) ? schema : ("~standard" in schema) ? schema["~standard"].vendor === "zod" ? zodSchema(schema) : standardSchema(schema) : schema();
110877
111065
  }
110878
111066
  function standardSchema(standardSchema2) {
110879
- return jsonSchema(() => addAdditionalPropertiesToJsonSchema(standardSchema2["~standard"].jsonSchema.input({
110880
- target: "draft-07"
110881
- })), {
111067
+ return jsonSchema(() => {
111068
+ if (!hasStandardJsonSchema(standardSchema2)) {
111069
+ throw new Error(`Standard schema vendor '${standardSchema2["~standard"].vendor}' does not support JSON Schema conversion.`);
111070
+ }
111071
+ return addAdditionalPropertiesToJsonSchema(standardSchema2["~standard"].jsonSchema.input({
111072
+ target: "draft-07"
111073
+ }));
111074
+ }, {
110882
111075
  validate: async (value) => {
110883
111076
  const result = await standardSchema2["~standard"].validate(value);
110884
111077
  return "value" in result ? { success: true, value: result.value } : {
@@ -110891,6 +111084,9 @@ function standardSchema(standardSchema2) {
110891
111084
  }
110892
111085
  });
110893
111086
  }
111087
+ function hasStandardJsonSchema(schema) {
111088
+ return schema["~standard"].jsonSchema != null;
111089
+ }
110894
111090
  function zod3Schema(zodSchema2, options) {
110895
111091
  var _a22;
110896
111092
  const useReferences = (_a22 = options == null ? undefined : options.useReferences) != null ? _a22 : false;
@@ -111261,12 +111457,12 @@ async function retryWithExponentialBackoffInternal(f, {
111261
111457
  });
111262
111458
  }
111263
111459
  }
111264
- var textDecoder = new TextDecoder;
111460
+ var textDecoder2 = new TextDecoder;
111265
111461
  async function readResponseBodyAsText({
111266
111462
  response,
111267
111463
  url: url2
111268
111464
  }) {
111269
- return textDecoder.decode(await readResponseWithSizeLimit({
111465
+ return textDecoder2.decode(await readResponseWithSizeLimit({
111270
111466
  response,
111271
111467
  url: url2
111272
111468
  }));
@@ -111402,7 +111598,70 @@ function resolveSync(value) {
111402
111598
  }
111403
111599
  return next;
111404
111600
  }
111405
- var textDecoder2 = new TextDecoder;
111601
+ var TRANSCRIPTION_STREAM_START_FRAME_TYPE = "transcription-stream.start";
111602
+ var TRANSCRIPTION_STREAM_AUDIO_DONE_FRAME_TYPE = "transcription-stream.audio-done";
111603
+ function parseTranscriptionStreamPart(text) {
111604
+ let value;
111605
+ try {
111606
+ value = secureJsonParse(text);
111607
+ } catch (e) {
111608
+ return;
111609
+ }
111610
+ if (value == null || typeof value !== "object" || Array.isArray(value)) {
111611
+ return;
111612
+ }
111613
+ const part = value;
111614
+ switch (part.type) {
111615
+ case "stream-start":
111616
+ return Array.isArray(part.warnings) && part.warnings.every(isWarning) ? part : undefined;
111617
+ case "transcript-delta":
111618
+ return isString(part.delta) && isOptional(part.id, isString) && isOptional(part.providerMetadata, isPlainObject2) ? part : undefined;
111619
+ case "transcript-partial":
111620
+ return isString(part.text) && isOptional(part.id, isString) && isOptional(part.startSecond, isNumber) && isOptional(part.durationInSeconds, isNumber) && isOptional(part.channelIndex, isNumber) && isOptional(part.providerMetadata, isPlainObject2) ? part : undefined;
111621
+ case "transcript-final":
111622
+ return isString(part.text) && isOptional(part.id, isString) && isOptional(part.startSecond, isNumber) && isOptional(part.endSecond, isNumber) && isOptional(part.channelIndex, isNumber) && isOptional(part.providerMetadata, isPlainObject2) ? part : undefined;
111623
+ case "finish":
111624
+ return isString(part.text) && Array.isArray(part.segments) && part.segments.every(isSegment) && isOptional(part.language, isString) && isOptional(part.durationInSeconds, isNumber) && isOptional(part.providerMetadata, isPlainObject2) ? part : undefined;
111625
+ case "response-metadata": {
111626
+ if (!(isOptional(part.modelId, isString) && isOptional(part.headers, isPlainObject2))) {
111627
+ return;
111628
+ }
111629
+ const timestamp = part.timestamp;
111630
+ if (timestamp == null) {
111631
+ return { ...part, timestamp: undefined };
111632
+ }
111633
+ if (typeof timestamp !== "string") {
111634
+ return;
111635
+ }
111636
+ const revived = new Date(timestamp);
111637
+ return Number.isNaN(revived.getTime()) ? undefined : { ...part, timestamp: revived };
111638
+ }
111639
+ case "raw":
111640
+ return "rawValue" in part ? part : undefined;
111641
+ case "error":
111642
+ return "error" in part ? part : undefined;
111643
+ default:
111644
+ return;
111645
+ }
111646
+ }
111647
+ function isString(value) {
111648
+ return typeof value === "string";
111649
+ }
111650
+ function isNumber(value) {
111651
+ return typeof value === "number";
111652
+ }
111653
+ function isOptional(value, check2) {
111654
+ return value === undefined || check2(value);
111655
+ }
111656
+ function isPlainObject2(value) {
111657
+ return typeof value === "object" && value != null && !Array.isArray(value);
111658
+ }
111659
+ function isWarning(value) {
111660
+ return isPlainObject2(value) && isString(value.type);
111661
+ }
111662
+ function isSegment(value) {
111663
+ return isPlainObject2(value) && isString(value.text) && isNumber(value.startSecond) && isNumber(value.endSecond);
111664
+ }
111406
111665
  function withoutTrailingSlash(url2) {
111407
111666
  return url2 == null ? undefined : url2.replace(/\/$/, "");
111408
111667
  }
@@ -111431,7 +111690,7 @@ async function* executeTool({
111431
111690
  }
111432
111691
 
111433
111692
  // node_modules/@ai-sdk/google/dist/index.js
111434
- var VERSION2 = "4.0.10";
111693
+ var VERSION2 = "4.0.24";
111435
111694
  var googleErrorDataSchema = lazySchema(() => zodSchema(exports_external.object({
111436
111695
  error: exports_external.object({
111437
111696
  code: exports_external.number().nullable(),
@@ -111748,7 +112007,7 @@ function convertUrlToolResultPart(url2) {
111748
112007
  }
111749
112008
  };
111750
112009
  }
111751
- function appendToolResultParts(parts, toolName, outputValue, toolCallId) {
112010
+ function appendToolResultParts(parts, toolName, outputValue, toolCallId, includeFunctionCallIds = true) {
111752
112011
  const functionResponseParts = [];
111753
112012
  const responseTextParts = [];
111754
112013
  for (const contentPart of outputValue) {
@@ -111785,7 +112044,7 @@ function appendToolResultParts(parts, toolName, outputValue, toolCallId) {
111785
112044
  }
111786
112045
  parts.push({
111787
112046
  functionResponse: {
111788
- ...toolCallId != null ? { id: toolCallId } : {},
112047
+ ...includeFunctionCallIds && toolCallId != null ? { id: toolCallId } : {},
111789
112048
  name: toolName,
111790
112049
  response: {
111791
112050
  name: toolName,
@@ -111796,13 +112055,13 @@ function appendToolResultParts(parts, toolName, outputValue, toolCallId) {
111796
112055
  }
111797
112056
  });
111798
112057
  }
111799
- function appendLegacyToolResultParts(parts, toolName, outputValue, toolCallId) {
112058
+ function appendLegacyToolResultParts(parts, toolName, outputValue, toolCallId, includeFunctionCallIds = true) {
111800
112059
  for (const contentPart of outputValue) {
111801
112060
  switch (contentPart.type) {
111802
112061
  case "text":
111803
112062
  parts.push({
111804
112063
  functionResponse: {
111805
- ...toolCallId != null ? { id: toolCallId } : {},
112064
+ ...includeFunctionCallIds && toolCallId != null ? { id: toolCallId } : {},
111806
112065
  name: toolName,
111807
112066
  response: {
111808
112067
  name: toolName,
@@ -111812,14 +112071,15 @@ function appendLegacyToolResultParts(parts, toolName, outputValue, toolCallId) {
111812
112071
  });
111813
112072
  break;
111814
112073
  case "file": {
111815
- if (contentPart.data.type === "data" && getTopLevelMediaType(contentPart.mediaType) === "image") {
112074
+ if (contentPart.data.type === "data") {
112075
+ const topLevelMediaType = getTopLevelMediaType(contentPart.mediaType);
111816
112076
  parts.push({
111817
112077
  inlineData: {
111818
112078
  mimeType: resolveFullMediaType({ part: contentPart }),
111819
112079
  data: convertToBase64(contentPart.data.data)
111820
112080
  }
111821
112081
  }, {
111822
- text: "Tool executed successfully and returned this image as a response"
112082
+ text: `Tool executed successfully and returned this ${topLevelMediaType === "image" ? "image" : "file"} as a response`
111823
112083
  });
111824
112084
  } else {
111825
112085
  parts.push({ text: JSON.stringify(contentPart) });
@@ -111833,16 +112093,17 @@ function appendLegacyToolResultParts(parts, toolName, outputValue, toolCallId) {
111833
112093
  }
111834
112094
  }
111835
112095
  function convertToGoogleMessages(prompt, options) {
111836
- var _a17, _b17, _c, _d, _e;
112096
+ var _a17, _b17, _c, _d, _e, _f;
111837
112097
  const systemInstructionParts = [];
111838
112098
  const contents = [];
111839
112099
  let systemMessagesAllowed = true;
111840
112100
  const isGemmaModel = (_a17 = options == null ? undefined : options.isGemmaModel) != null ? _a17 : false;
111841
- const isGemini3Model2 = (_b17 = options == null ? undefined : options.isGemini3Model) != null ? _b17 : false;
112101
+ const isGemini3Model = (_b17 = options == null ? undefined : options.isGemini3Model) != null ? _b17 : false;
111842
112102
  const onWarning = options == null ? undefined : options.onWarning;
111843
112103
  const providerOptionsNames = (_c = options == null ? undefined : options.providerOptionsNames) != null ? _c : ["google"];
111844
112104
  const isVertexLike = !providerOptionsNames.includes("google");
111845
112105
  const supportsFunctionResponseParts = (_d = options == null ? undefined : options.supportsFunctionResponseParts) != null ? _d : true;
112106
+ const includeFunctionCallIds = (_e = options == null ? undefined : options.includeFunctionCallIds) != null ? _e : true;
111846
112107
  let sentinelInjected = false;
111847
112108
  const missingSignatureToolNames = [];
111848
112109
  const injectSkipSignature = (toolName) => {
@@ -111938,6 +112199,7 @@ function convertToGoogleMessages(prompt, options) {
111938
112199
  }
111939
112200
  case "assistant": {
111940
112201
  systemMessagesAllowed = false;
112202
+ let modelResponseHasSignedFunctionCall = false;
111941
112203
  contents.push({
111942
112204
  role: "model",
111943
112205
  parts: content.map((part) => {
@@ -112028,8 +112290,13 @@ function convertToGoogleMessages(prompt, options) {
112028
112290
  case "tool-call": {
112029
112291
  const serverToolCallId = (providerOpts == null ? undefined : providerOpts.serverToolCallId) != null ? String(providerOpts.serverToolCallId) : undefined;
112030
112292
  const serverToolType = (providerOpts == null ? undefined : providerOpts.serverToolType) != null ? String(providerOpts.serverToolType) : undefined;
112031
- const effectiveThoughtSignature = thoughtSignature != null ? thoughtSignature : isGemini3Model2 ? injectSkipSignature(part.toolName) : undefined;
112032
- if (serverToolCallId && serverToolType) {
112293
+ const isServerToolCall = serverToolCallId != null && serverToolType != null;
112294
+ const shouldSkipMissingSignatureMitigation = !isServerToolCall && thoughtSignature == null && modelResponseHasSignedFunctionCall;
112295
+ const effectiveThoughtSignature = thoughtSignature != null ? thoughtSignature : isGemini3Model && !shouldSkipMissingSignatureMitigation ? injectSkipSignature(part.toolName) : undefined;
112296
+ if (!isServerToolCall && thoughtSignature != null) {
112297
+ modelResponseHasSignedFunctionCall = true;
112298
+ }
112299
+ if (isServerToolCall) {
112033
112300
  return {
112034
112301
  toolCall: {
112035
112302
  toolType: serverToolType,
@@ -112041,7 +112308,7 @@ function convertToGoogleMessages(prompt, options) {
112041
112308
  }
112042
112309
  return {
112043
112310
  functionCall: {
112044
- ...part.toolCallId != null ? { id: part.toolCallId } : {},
112311
+ ...includeFunctionCallIds && part.toolCallId != null ? { id: part.toolCallId } : {},
112045
112312
  name: part.toolName,
112046
112313
  args: part.input
112047
112314
  },
@@ -112098,18 +112365,18 @@ function convertToGoogleMessages(prompt, options) {
112098
112365
  const output = part.output;
112099
112366
  if (output.type === "content") {
112100
112367
  if (supportsFunctionResponseParts) {
112101
- appendToolResultParts(parts, part.toolName, output.value, part.toolCallId);
112368
+ appendToolResultParts(parts, part.toolName, output.value, part.toolCallId, includeFunctionCallIds);
112102
112369
  } else {
112103
- appendLegacyToolResultParts(parts, part.toolName, output.value, part.toolCallId);
112370
+ appendLegacyToolResultParts(parts, part.toolName, output.value, part.toolCallId, includeFunctionCallIds);
112104
112371
  }
112105
112372
  } else {
112106
112373
  parts.push({
112107
112374
  functionResponse: {
112108
- ...part.toolCallId != null ? { id: part.toolCallId } : {},
112375
+ ...includeFunctionCallIds && part.toolCallId != null ? { id: part.toolCallId } : {},
112109
112376
  name: part.toolName,
112110
112377
  response: {
112111
112378
  name: part.toolName,
112112
- content: output.type === "execution-denied" ? (_e = output.reason) != null ? _e : "Tool call execution denied." : output.value
112379
+ content: output.type === "execution-denied" ? (_f = output.reason) != null ? _f : "Tool call execution denied." : output.value
112113
112380
  }
112114
112381
  }
112115
112382
  });
@@ -112206,7 +112473,22 @@ var googleLanguageModelOptions = lazySchema(() => zodSchema(exports_external.obj
112206
112473
  "1:4",
112207
112474
  "4:1"
112208
112475
  ]).optional(),
112209
- imageSize: exports_external.enum(["1K", "2K", "4K", "512"]).optional()
112476
+ imageSize: exports_external.enum(["1K", "2K", "4K", "512"]).optional(),
112477
+ personGeneration: exports_external.enum([
112478
+ "PERSON_GENERATION_UNSPECIFIED",
112479
+ "ALLOW_ALL",
112480
+ "ALLOW_ADULT",
112481
+ "ALLOW_NONE"
112482
+ ]).optional(),
112483
+ prominentPeople: exports_external.enum([
112484
+ "PROMINENT_PEOPLE_UNSPECIFIED",
112485
+ "ALLOW_PROMINENT_PEOPLE",
112486
+ "BLOCK_PROMINENT_PEOPLE"
112487
+ ]).optional(),
112488
+ imageOutputOptions: exports_external.object({
112489
+ mimeType: exports_external.enum(["image/jpeg", "image/png"]).optional(),
112490
+ compressionQuality: exports_external.number().optional()
112491
+ }).optional()
112210
112492
  }).optional(),
112211
112493
  retrievalConfig: exports_external.object({
112212
112494
  latLng: exports_external.object({
@@ -112219,6 +112501,25 @@ var googleLanguageModelOptions = lazySchema(() => zodSchema(exports_external.obj
112219
112501
  sharedRequestType: exports_external.enum(["priority", "flex", "standard"]).optional(),
112220
112502
  requestType: exports_external.enum(["shared"]).optional()
112221
112503
  })));
112504
+ var gemini1ModelPattern = /(^|\/)gemini-1(?:[.-]|$)/i;
112505
+ var gemini2ModelPattern = /(^|\/)gemini-2(?:[.-]|$)/i;
112506
+ var gemini25ModelPattern = /(^|\/)gemini-2\.5(?:[.-]|$)/i;
112507
+ var geminiModelPattern = /(^|\/)gemini-/i;
112508
+ function isKnownPreGemini2Model(modelId) {
112509
+ return gemini1ModelPattern.test(modelId) || /(^|\/)gemini-pro(?:-vision)?$/i.test(modelId) || /(^|\/)gemini-robotics-er-1\.5(?:[.-]|$)/i.test(modelId);
112510
+ }
112511
+ function getGoogleModelCapabilities(modelId) {
112512
+ const isGeminiModel2 = geminiModelPattern.test(modelId);
112513
+ const isGemini2Model = gemini2ModelPattern.test(modelId);
112514
+ const isKnownPreGemini2 = isKnownPreGemini2Model(modelId);
112515
+ const isKnownOlderModel = isKnownPreGemini2 || isGemini2Model;
112516
+ const usesGemini3Features = isGeminiModel2 && !isKnownOlderModel;
112517
+ return {
112518
+ supportsGemini2Tools: isGeminiModel2 && !isKnownPreGemini2 || modelId.toLowerCase().includes("nano-banana"),
112519
+ supportsFileSearch: gemini25ModelPattern.test(modelId) || usesGemini3Features,
112520
+ usesGemini3Features
112521
+ };
112522
+ }
112222
112523
  function prepareTools({
112223
112524
  tools,
112224
112525
  toolChoice,
@@ -112228,20 +112529,13 @@ function prepareTools({
112228
112529
  var _a17, _b17;
112229
112530
  tools = (tools == null ? undefined : tools.length) ? tools : undefined;
112230
112531
  const toolWarnings = [];
112231
- const isLatest = [
112232
- "gemini-flash-latest",
112233
- "gemini-flash-lite-latest",
112234
- "gemini-pro-latest"
112235
- ].some((id) => id === modelId);
112236
- const isGemini2orNewer = modelId.includes("gemini-2") || modelId.includes("gemini-3") || modelId.includes("nano-banana") || isLatest;
112237
- const isGemini3orNewer = modelId.includes("gemini-3");
112238
- const supportsFileSearch = modelId.includes("gemini-2.5") || modelId.includes("gemini-3");
112532
+ const { supportsGemini2Tools, supportsFileSearch, usesGemini3Features } = getGoogleModelCapabilities(modelId);
112239
112533
  if (tools == null) {
112240
112534
  return { tools: undefined, toolConfig: undefined, toolWarnings };
112241
112535
  }
112242
112536
  const hasFunctionTools = tools.some((tool2) => tool2.type === "function");
112243
112537
  const hasProviderTools = tools.some((tool2) => tool2.type === "provider");
112244
- if (hasFunctionTools && hasProviderTools && !isGemini3orNewer) {
112538
+ if (hasFunctionTools && hasProviderTools && !usesGemini3Features) {
112245
112539
  toolWarnings.push({
112246
112540
  type: "unsupported",
112247
112541
  feature: `combination of function and provider-defined tools`
@@ -112253,7 +112547,7 @@ function prepareTools({
112253
112547
  ProviderTools.forEach((tool2) => {
112254
112548
  switch (tool2.id) {
112255
112549
  case "google.google_search":
112256
- if (isGemini2orNewer) {
112550
+ if (supportsGemini2Tools) {
112257
112551
  googleTools2.push({ googleSearch: { ...tool2.args } });
112258
112552
  } else {
112259
112553
  toolWarnings.push({
@@ -112264,7 +112558,7 @@ function prepareTools({
112264
112558
  }
112265
112559
  break;
112266
112560
  case "google.enterprise_web_search":
112267
- if (isGemini2orNewer) {
112561
+ if (supportsGemini2Tools) {
112268
112562
  googleTools2.push({ enterpriseWebSearch: {} });
112269
112563
  } else {
112270
112564
  toolWarnings.push({
@@ -112275,7 +112569,7 @@ function prepareTools({
112275
112569
  }
112276
112570
  break;
112277
112571
  case "google.url_context":
112278
- if (isGemini2orNewer) {
112572
+ if (supportsGemini2Tools) {
112279
112573
  googleTools2.push({ urlContext: {} });
112280
112574
  } else {
112281
112575
  toolWarnings.push({
@@ -112286,7 +112580,7 @@ function prepareTools({
112286
112580
  }
112287
112581
  break;
112288
112582
  case "google.code_execution":
112289
- if (isGemini2orNewer) {
112583
+ if (supportsGemini2Tools) {
112290
112584
  googleTools2.push({ codeExecution: {} });
112291
112585
  } else {
112292
112586
  toolWarnings.push({
@@ -112308,7 +112602,7 @@ function prepareTools({
112308
112602
  }
112309
112603
  break;
112310
112604
  case "google.vertex_rag_store":
112311
- if (isGemini2orNewer) {
112605
+ if (supportsGemini2Tools) {
112312
112606
  googleTools2.push({
112313
112607
  retrieval: {
112314
112608
  vertex_rag_store: {
@@ -112328,7 +112622,7 @@ function prepareTools({
112328
112622
  }
112329
112623
  break;
112330
112624
  case "google.google_maps":
112331
- if (isGemini2orNewer) {
112625
+ if (supportsGemini2Tools) {
112332
112626
  googleTools2.push({ googleMaps: {} });
112333
112627
  } else {
112334
112628
  toolWarnings.push({
@@ -112346,7 +112640,7 @@ function prepareTools({
112346
112640
  break;
112347
112641
  }
112348
112642
  });
112349
- if (hasFunctionTools && isGemini3orNewer && googleTools2.length > 0) {
112643
+ if (hasFunctionTools && usesGemini3Features && googleTools2.length > 0) {
112350
112644
  const functionDeclarations2 = [];
112351
112645
  for (const tool2 of tools) {
112352
112646
  if (tool2.type === "function") {
@@ -112674,6 +112968,12 @@ function mapGoogleFinishReason({
112674
112968
  return "other";
112675
112969
  }
112676
112970
  }
112971
+ var configurableSafetySettingCategories = [
112972
+ "HARM_CATEGORY_HATE_SPEECH",
112973
+ "HARM_CATEGORY_DANGEROUS_CONTENT",
112974
+ "HARM_CATEGORY_HARASSMENT",
112975
+ "HARM_CATEGORY_SEXUALLY_EXPLICIT"
112976
+ ];
112677
112977
  var GoogleLanguageModel = class _GoogleLanguageModel {
112678
112978
  constructor(modelId, config2) {
112679
112979
  this.specificationVersion = "v4";
@@ -112714,7 +113014,7 @@ var GoogleLanguageModel = class _GoogleLanguageModel {
112714
113014
  reasoning,
112715
113015
  providerOptions
112716
113016
  }, { isStreaming = false } = {}) {
112717
- var _a17, _b17;
113017
+ var _a17, _b17, _c;
112718
113018
  const warnings = [];
112719
113019
  const providerOptionsNames = this.config.provider.includes("vertex") ? ["googleVertex", "vertex"] : ["google"];
112720
113020
  let googleOptions;
@@ -112768,15 +113068,36 @@ var GoogleLanguageModel = class _GoogleLanguageModel {
112768
113068
  }
112769
113069
  } : undefined;
112770
113070
  const bodyServiceTier = isVertexProvider ? undefined : googleOptions == null ? undefined : googleOptions.serviceTier;
113071
+ let imageConfig = googleOptions == null ? undefined : googleOptions.imageConfig;
113072
+ if (imageConfig != null && !isVertexProvider) {
113073
+ const {
113074
+ personGeneration,
113075
+ prominentPeople,
113076
+ imageOutputOptions,
113077
+ ...geminiApiImageConfig
113078
+ } = imageConfig;
113079
+ const droppedImageConfigFields = Object.entries({
113080
+ personGeneration,
113081
+ prominentPeople,
113082
+ imageOutputOptions
113083
+ }).filter(([, value]) => value != null).map(([key]) => `'imageConfig.${key}'`);
113084
+ if (droppedImageConfigFields.length > 0) {
113085
+ warnings.push({
113086
+ type: "other",
113087
+ message: `${droppedImageConfigFields.join(", ")} ${droppedImageConfigFields.length === 1 ? "is a Vertex AI option and is" : "are Vertex AI options and are"} ignored with the current Google provider (${this.config.provider}).`
113088
+ });
113089
+ imageConfig = geminiApiImageConfig;
113090
+ }
113091
+ }
112771
113092
  const isGemmaModel = this.modelId.toLowerCase().startsWith("gemma-");
112772
- const isGemini3Model2 = /^gemini-3[.-]/.test(this.modelId);
112773
- const supportsFunctionResponseParts = isGemini3Model2;
113093
+ const { usesGemini3Features } = getGoogleModelCapabilities(this.modelId);
112774
113094
  const { contents, systemInstruction } = convertToGoogleMessages(prompt, {
112775
113095
  isGemmaModel,
112776
- isGemini3Model: isGemini3Model2,
113096
+ isGemini3Model: usesGemini3Features,
112777
113097
  onWarning: (warning) => warnings.push(warning),
112778
113098
  providerOptionsNames,
112779
- supportsFunctionResponseParts
113099
+ supportsFunctionResponseParts: usesGemini3Features,
113100
+ includeFunctionCallIds: !isVertexProvider
112780
113101
  });
112781
113102
  const {
112782
113103
  tools: googleTools2,
@@ -112795,6 +113116,11 @@ var GoogleLanguageModel = class _GoogleLanguageModel {
112795
113116
  });
112796
113117
  const thinkingConfig = (googleOptions == null ? undefined : googleOptions.thinkingConfig) || resolvedThinking ? { ...resolvedThinking, ...googleOptions == null ? undefined : googleOptions.thinkingConfig } : undefined;
112797
113118
  const streamFunctionCallArguments = isStreaming && isVertexProvider ? (_a17 = googleOptions == null ? undefined : googleOptions.streamFunctionCallArguments) != null ? _a17 : false : undefined;
113119
+ const safetyThreshold = googleOptions == null ? undefined : googleOptions.threshold;
113120
+ const safetySettings = (_b17 = googleOptions == null ? undefined : googleOptions.safetySettings) != null ? _b17 : safetyThreshold != null ? configurableSafetySettingCategories.map((category) => ({
113121
+ category,
113122
+ threshold: safetyThreshold
113123
+ })) : undefined;
112798
113124
  const toolConfig = googleToolConfig || streamFunctionCallArguments || (googleOptions == null ? undefined : googleOptions.retrievalConfig) ? {
112799
113125
  ...googleToolConfig,
112800
113126
  ...streamFunctionCallArguments && {
@@ -112819,7 +113145,7 @@ var GoogleLanguageModel = class _GoogleLanguageModel {
112819
113145
  stopSequences,
112820
113146
  seed,
112821
113147
  responseMimeType: (responseFormat == null ? undefined : responseFormat.type) === "json" ? "application/json" : undefined,
112822
- responseSchema: (responseFormat == null ? undefined : responseFormat.type) === "json" && responseFormat.schema != null && ((_b17 = googleOptions == null ? undefined : googleOptions.structuredOutputs) != null ? _b17 : true) ? convertJSONSchemaToOpenAPISchema(responseFormat.schema) : undefined,
113148
+ responseSchema: (responseFormat == null ? undefined : responseFormat.type) === "json" && responseFormat.schema != null && ((_c = googleOptions == null ? undefined : googleOptions.structuredOutputs) != null ? _c : true) ? convertJSONSchemaToOpenAPISchema(responseFormat.schema) : undefined,
112823
113149
  ...(googleOptions == null ? undefined : googleOptions.audioTimestamp) && {
112824
113150
  audioTimestamp: googleOptions.audioTimestamp
112825
113151
  },
@@ -112828,13 +113154,11 @@ var GoogleLanguageModel = class _GoogleLanguageModel {
112828
113154
  ...(googleOptions == null ? undefined : googleOptions.mediaResolution) && {
112829
113155
  mediaResolution: googleOptions.mediaResolution
112830
113156
  },
112831
- ...(googleOptions == null ? undefined : googleOptions.imageConfig) && {
112832
- imageConfig: googleOptions.imageConfig
112833
- }
113157
+ ...imageConfig && { imageConfig }
112834
113158
  },
112835
113159
  contents,
112836
113160
  systemInstruction: isGemmaModel ? undefined : systemInstruction,
112837
- safetySettings: googleOptions == null ? undefined : googleOptions.safetySettings,
113161
+ safetySettings,
112838
113162
  tools: googleTools2,
112839
113163
  toolConfig,
112840
113164
  cachedContent: googleOptions == null ? undefined : googleOptions.cachedContent,
@@ -112847,7 +113171,7 @@ var GoogleLanguageModel = class _GoogleLanguageModel {
112847
113171
  };
112848
113172
  }
112849
113173
  async doGenerate(options) {
112850
- var _a17, _b17, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r;
113174
+ var _a17, _b17, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s;
112851
113175
  const { args, warnings, providerOptionsNames, extraHeaders } = await this.getArgs(options);
112852
113176
  const wrapProviderMetadata = (payload) => Object.fromEntries(providerOptionsNames.map((name16) => [name16, payload]));
112853
113177
  const mergedHeaders = combineHeaders(this.config.headers ? await resolve(this.config.headers) : undefined, options.headers, extraHeaders);
@@ -112891,7 +113215,6 @@ var GoogleLanguageModel = class _GoogleLanguageModel {
112891
113215
  output: (_d = part.codeExecutionResult.output) != null ? _d : ""
112892
113216
  }
112893
113217
  });
112894
- lastCodeExecutionToolCallId = undefined;
112895
113218
  } else if ("text" in part && part.text != null) {
112896
113219
  const thoughtSignatureMetadata = part.thoughtSignature ? wrapProviderMetadata({
112897
113220
  thoughtSignature: part.thoughtSignature
@@ -112996,6 +113319,7 @@ var GoogleLanguageModel = class _GoogleLanguageModel {
112996
113319
  }),
112997
113320
  request: { body: args },
112998
113321
  response: {
113322
+ id: (_s = response.responseId) != null ? _s : undefined,
112999
113323
  headers: responseHeaders,
113000
113324
  body: rawResponse
113001
113325
  }
@@ -113024,6 +113348,7 @@ var GoogleLanguageModel = class _GoogleLanguageModel {
113024
113348
  let lastUrlContextMetadata = null;
113025
113349
  const generateId3 = this.config.generateId;
113026
113350
  let hasToolCalls = false;
113351
+ let hasEmittedResponseMetadata = false;
113027
113352
  let currentTextBlockId = null;
113028
113353
  let currentReasoningBlockId = null;
113029
113354
  let blockCounter = 0;
@@ -113074,6 +113399,13 @@ var GoogleLanguageModel = class _GoogleLanguageModel {
113074
113399
  return;
113075
113400
  }
113076
113401
  const value = chunk.value;
113402
+ if (!hasEmittedResponseMetadata && value.responseId != null) {
113403
+ hasEmittedResponseMetadata = true;
113404
+ controller.enqueue({
113405
+ type: "response-metadata",
113406
+ id: value.responseId
113407
+ });
113408
+ }
113077
113409
  const usageMetadata = value.usageMetadata;
113078
113410
  if (usageMetadata != null) {
113079
113411
  usage = usageMetadata;
@@ -113126,7 +113458,6 @@ var GoogleLanguageModel = class _GoogleLanguageModel {
113126
113458
  output: (_d = part.codeExecutionResult.output) != null ? _d : ""
113127
113459
  }
113128
113460
  });
113129
- lastCodeExecutionToolCallId = undefined;
113130
113461
  }
113131
113462
  } else if ("text" in part && part.text != null) {
113132
113463
  const thoughtSignatureMetadata = part.thoughtSignature ? wrapProviderMetadata({
@@ -113404,9 +113735,6 @@ var GoogleLanguageModel = class _GoogleLanguageModel {
113404
113735
  };
113405
113736
  }
113406
113737
  };
113407
- function isGemini3Model(modelId) {
113408
- return /gemini-3[\.\-]/i.test(modelId) || /gemini-3$/i.test(modelId);
113409
- }
113410
113738
  function getMaxOutputTokensForGemini25Model() {
113411
113739
  return 65536;
113412
113740
  }
@@ -113425,7 +113753,7 @@ function resolveThinkingConfig({
113425
113753
  if (!isCustomReasoning(reasoning)) {
113426
113754
  return;
113427
113755
  }
113428
- if (isGemini3Model(modelId) && !modelId.includes("gemini-3-pro-image")) {
113756
+ if (getGoogleModelCapabilities(modelId).usesGemini3Features && !modelId.includes("gemini-3-pro-image")) {
113429
113757
  return resolveGemini3ThinkingConfig({ reasoning, warnings });
113430
113758
  }
113431
113759
  return resolveGemini25ThinkingConfig({ reasoning, modelId, warnings });
@@ -113699,6 +114027,7 @@ var getUrlContextMetadataSchema = () => exports_external.object({
113699
114027
  })).nullish()
113700
114028
  });
113701
114029
  var responseSchema = lazySchema(() => zodSchema(exports_external.object({
114030
+ responseId: exports_external.string().nullish(),
113702
114031
  candidates: exports_external.array(exports_external.object({
113703
114032
  content: getContentSchema().nullish().or(exports_external.object({}).strict()),
113704
114033
  finishReason: exports_external.string().nullish(),
@@ -113714,6 +114043,7 @@ var responseSchema = lazySchema(() => zodSchema(exports_external.object({
113714
114043
  }).nullish()
113715
114044
  })));
113716
114045
  var chunkSchema = lazySchema(() => zodSchema(exports_external.object({
114046
+ responseId: exports_external.string().nullish(),
113717
114047
  candidates: exports_external.array(exports_external.object({
113718
114048
  content: getContentSchema().nullish(),
113719
114049
  finishReason: exports_external.string().nullish(),
@@ -114131,6 +114461,7 @@ var GoogleFiles = class {
114131
114461
  await delay(pollIntervalMs);
114132
114462
  const { value: fileStatus } = await getFromApi({
114133
114463
  url: `${this.config.baseURL}/${file2.name}`,
114464
+ validateUrl: false,
114134
114465
  headers: combineHeaders(resolvedHeaders),
114135
114466
  successfulResponseHandler: createJsonResponseHandler(googleFileResponseSchema),
114136
114467
  failedResponseHandler: googleFailedResponseHandler,
@@ -114227,24 +114558,27 @@ function convertFileToGoogleImage(file2, warnings) {
114227
114558
  }
114228
114559
  const base64Data = typeof file2.data === "string" ? file2.data : convertUint8ArrayToBase64(file2.data);
114229
114560
  return {
114230
- inlineData: {
114231
- mimeType: file2.mediaType || "image/png",
114232
- data: base64Data
114233
- }
114561
+ bytesBase64Encoded: base64Data,
114562
+ mimeType: file2.mediaType || "image/png"
114234
114563
  };
114235
114564
  }
114236
114565
  function convertProviderReferenceImage(refImg) {
114237
114566
  if (refImg.bytesBase64Encoded) {
114238
114567
  return {
114239
- inlineData: {
114240
- mimeType: "image/png",
114241
- data: refImg.bytesBase64Encoded
114242
- }
114568
+ image: {
114569
+ bytesBase64Encoded: refImg.bytesBase64Encoded,
114570
+ mimeType: "image/png"
114571
+ },
114572
+ referenceType: "asset"
114243
114573
  };
114244
114574
  }
114245
114575
  if (refImg.gcsUri) {
114246
114576
  return {
114247
- gcsUri: refImg.gcsUri
114577
+ image: {
114578
+ gcsUri: refImg.gcsUri,
114579
+ mimeType: "image/png"
114580
+ },
114581
+ referenceType: "asset"
114248
114582
  };
114249
114583
  }
114250
114584
  return refImg;
@@ -114382,6 +114716,7 @@ var GoogleVideoModel = class {
114382
114716
  }
114383
114717
  const { value: statusOperation, responseHeaders: pollHeaders } = await getFromApi({
114384
114718
  url: `${this.config.baseURL}/${operationName}`,
114719
+ validateUrl: false,
114385
114720
  headers: combineHeaders(await resolve(this.config.headers), options.headers),
114386
114721
  successfulResponseHandler: createJsonResponseHandler(googleOperationSchema),
114387
114722
  failedResponseHandler: googleFailedResponseHandler,
@@ -115607,6 +115942,7 @@ function convertFilePartToContent({
115607
115942
  kind = "video";
115608
115943
  break;
115609
115944
  case "application":
115945
+ case "text":
115610
115946
  kind = "document";
115611
115947
  break;
115612
115948
  default:
@@ -116499,6 +116835,7 @@ async function pollGoogleInteractionUntilTerminal({
116499
116835
  responseHeaders
116500
116836
  } = await getFromApi({
116501
116837
  url: url2,
116838
+ validateUrl: false,
116502
116839
  headers,
116503
116840
  failedResponseHandler: googleFailedResponseHandler,
116504
116841
  successfulResponseHandler: createJsonResponseHandler(googleInteractionsResponseSchema),
@@ -116711,6 +117048,7 @@ function streamGoogleInteractionEvents({
116711
117048
  async function openReader() {
116712
117049
  const { value: stream } = await getFromApi({
116713
117050
  url: buildUrl(),
117051
+ validateUrl: false,
116714
117052
  headers: eventSourceHeaders,
116715
117053
  failedResponseHandler: googleFailedResponseHandler,
116716
117054
  successfulResponseHandler: createEventSourceResponseHandler(googleInteractionsEventSchema),
@@ -117012,12 +117350,7 @@ var GoogleInteractionsLanguageModel = class _GoogleInteractionsLanguageModel {
117012
117350
  const hasTools = options.tools != null && options.tools.length > 0;
117013
117351
  let toolsForBody;
117014
117352
  let toolChoiceForBody;
117015
- if (hasTools && isAgent) {
117016
- warnings.push({
117017
- type: "other",
117018
- message: "google.interactions: tools are not supported when an agent is set; tools will be omitted from the request body."
117019
- });
117020
- } else if (hasTools) {
117353
+ if (hasTools) {
117021
117354
  const prepared = prepareGoogleInteractionsTools({
117022
117355
  tools: options.tools,
117023
117356
  toolChoice: options.toolChoice
@@ -117474,6 +117807,20 @@ var GoogleRealtimeEventMapper = class {
117474
117807
  raw
117475
117808
  };
117476
117809
  }
117810
+ if (data.goAway != null) {
117811
+ return {
117812
+ type: "custom",
117813
+ rawType: "goAway",
117814
+ raw
117815
+ };
117816
+ }
117817
+ if (data.sessionResumptionUpdate != null) {
117818
+ return {
117819
+ type: "custom",
117820
+ rawType: "sessionResumptionUpdate",
117821
+ raw
117822
+ };
117823
+ }
117477
117824
  if (data.serverContent != null) {
117478
117825
  return this.parseServerContent(data.serverContent, raw);
117479
117826
  }
@@ -117539,6 +117886,13 @@ var GoogleRealtimeEventMapper = class {
117539
117886
  raw
117540
117887
  });
117541
117888
  }
117889
+ if (serverContent.generationComplete) {
117890
+ events.push({
117891
+ type: "custom",
117892
+ rawType: "generationComplete",
117893
+ raw
117894
+ });
117895
+ }
117542
117896
  if (serverContent.turnComplete) {
117543
117897
  if (this.hasAudio) {
117544
117898
  events.push({
@@ -117930,17 +118284,22 @@ function createGoogle(options = {}) {
117930
118284
  return provider;
117931
118285
  }
117932
118286
  var google = createGoogle();
118287
+
117933
118288
  // node_modules/@ai-sdk/gateway/dist/index.js
117934
118289
  var import_oidc = __toESM(require_dist(), 1);
117935
118290
  var import_oidc2 = __toESM(require_dist(), 1);
117936
118291
  var GATEWAY_REALTIME_SUBPROTOCOL = "ai-gateway-realtime.v1";
118292
+ var GATEWAY_TRANSCRIPTION_SUBPROTOCOL = "ai-gateway-transcription.v1";
117937
118293
  var GATEWAY_AUTH_SUBPROTOCOL_PREFIX = "ai-gateway-auth.";
117938
118294
  var GATEWAY_TEAM_SUBPROTOCOL_PREFIX = "ai-gateway-team.";
117939
118295
  function getGatewayRealtimeProtocols(token, options) {
117940
- const protocols = [
117941
- GATEWAY_REALTIME_SUBPROTOCOL,
117942
- `${GATEWAY_AUTH_SUBPROTOCOL_PREFIX}${token}`
117943
- ];
118296
+ return buildGatewayProtocols(GATEWAY_REALTIME_SUBPROTOCOL, token, options);
118297
+ }
118298
+ function getGatewayTranscriptionProtocols(token, options) {
118299
+ return buildGatewayProtocols(GATEWAY_TRANSCRIPTION_SUBPROTOCOL, token, options);
118300
+ }
118301
+ function buildGatewayProtocols(marker112, token, options) {
118302
+ const protocols = [marker112, `${GATEWAY_AUTH_SUBPROTOCOL_PREFIX}${token}`];
117944
118303
  if (options == null ? undefined : options.teamIdOrSlug) {
117945
118304
  protocols.push(`${GATEWAY_TEAM_SUBPROTOCOL_PREFIX}${encodeSubprotocolValue(options.teamIdOrSlug)}`);
117946
118305
  }
@@ -118155,6 +118514,9 @@ var GatewayFailedDependencyError = class extends (_b72 = GatewayError, _a72 = sy
118155
118514
  var name72 = "GatewayForbiddenError";
118156
118515
  var marker82 = `vercel.ai.gateway.error.${name72}`;
118157
118516
  var symbol82 = Symbol.for(marker82);
118517
+ var forbiddenParamSchema = lazySchema(() => zodSchema(exports_external.object({
118518
+ ruleId: exports_external.string()
118519
+ })));
118158
118520
  var _a82;
118159
118521
  var _b82;
118160
118522
  var GatewayForbiddenError = class extends (_b82 = GatewayError, _a82 = symbol82, _b82) {
@@ -118162,12 +118524,14 @@ var GatewayForbiddenError = class extends (_b82 = GatewayError, _a82 = symbol82,
118162
118524
  message = "Forbidden",
118163
118525
  statusCode = 403,
118164
118526
  cause,
118165
- generationId
118527
+ generationId,
118528
+ ruleId
118166
118529
  } = {}) {
118167
118530
  super({ message, statusCode, cause, generationId });
118168
118531
  this[_a82] = true;
118169
118532
  this.name = name72;
118170
118533
  this.type = "forbidden";
118534
+ this.ruleId = ruleId;
118171
118535
  }
118172
118536
  static isInstance(error51) {
118173
118537
  return GatewayError.hasMarker(error51) && symbol82 in error51;
@@ -118275,13 +118639,19 @@ async function createGatewayErrorFromResponse({
118275
118639
  cause,
118276
118640
  generationId
118277
118641
  });
118278
- case "forbidden":
118642
+ case "forbidden": {
118643
+ const ruleResult = await safeValidateTypes({
118644
+ value: validatedResponse.error.param,
118645
+ schema: forbiddenParamSchema
118646
+ });
118279
118647
  return new GatewayForbiddenError({
118280
118648
  message,
118281
118649
  statusCode,
118282
118650
  cause,
118283
- generationId
118651
+ generationId,
118652
+ ruleId: ruleResult.success ? ruleResult.value.ruleId : undefined
118284
118653
  });
118654
+ }
118285
118655
  default:
118286
118656
  return new GatewayInternalServerError({
118287
118657
  message,
@@ -118427,6 +118797,7 @@ var GatewayFetchMetadata = class {
118427
118797
  try {
118428
118798
  const { value } = await getFromApi({
118429
118799
  url: `${this.config.baseURL}/config`,
118800
+ validateUrl: false,
118430
118801
  headers: this.config.headers ? await resolve(this.config.headers) : undefined,
118431
118802
  successfulResponseHandler: createJsonResponseHandler(gatewayAvailableModelsResponseSchema),
118432
118803
  failedResponseHandler: createJsonErrorResponseHandler({
@@ -118445,6 +118816,7 @@ var GatewayFetchMetadata = class {
118445
118816
  const baseUrl = new URL(this.config.baseURL);
118446
118817
  const { value } = await getFromApi({
118447
118818
  url: `${baseUrl.origin}/v1/credits`,
118819
+ validateUrl: false,
118448
118820
  headers: this.config.headers ? await resolve(this.config.headers) : undefined,
118449
118821
  successfulResponseHandler: createJsonResponseHandler(gatewayCreditsResponseSchema),
118450
118822
  failedResponseHandler: createJsonErrorResponseHandler({
@@ -118523,6 +118895,7 @@ var GatewaySpendReport = class {
118523
118895
  }
118524
118896
  const { value } = await getFromApi({
118525
118897
  url: `${baseUrl.origin}/v1/report?${searchParams.toString()}`,
118898
+ validateUrl: false,
118526
118899
  headers: this.config.headers ? await resolve(this.config.headers) : undefined,
118527
118900
  successfulResponseHandler: createJsonResponseHandler(gatewaySpendReportResponseSchema),
118528
118901
  failedResponseHandler: createJsonErrorResponseHandler({
@@ -118587,6 +118960,7 @@ var GatewayGenerationInfoFetcher = class {
118587
118960
  const baseUrl = new URL(this.config.baseURL);
118588
118961
  const { value } = await getFromApi({
118589
118962
  url: `${baseUrl.origin}/v1/generation?id=${encodeURIComponent(params.id)}`,
118963
+ validateUrl: false,
118590
118964
  headers: this.config.headers ? await resolve(this.config.headers) : undefined,
118591
118965
  successfulResponseHandler: createJsonResponseHandler(gatewayGenerationInfoResponseSchema),
118592
118966
  failedResponseHandler: createJsonErrorResponseHandler({
@@ -119477,6 +119851,36 @@ var GatewayTranscriptionModel = class {
119477
119851
  throw await asGatewayError(error51, await parseAuthMethod(resolvedHeaders != null ? resolvedHeaders : {}));
119478
119852
  }
119479
119853
  }
119854
+ async doStream(options) {
119855
+ var _a112, _b112, _c, _d, _e;
119856
+ const currentDate = (_c = (_b112 = (_a112 = this.config._internal) == null ? undefined : _a112.currentDate) == null ? undefined : _b112.call(_a112)) != null ? _c : /* @__PURE__ */ new Date;
119857
+ const headers = combineHeaders(await resolve((_d = this.config.headers) != null ? _d : {}), (_e = options.headers) != null ? _e : {}, this.getModelConfigHeaders(), await resolve(this.config.o11yHeaders));
119858
+ const authMethod = await parseAuthMethod(headers);
119859
+ const startFrame = {
119860
+ type: TRANSCRIPTION_STREAM_START_FRAME_TYPE,
119861
+ inputAudioFormat: options.inputAudioFormat,
119862
+ ...options.providerOptions != null && {
119863
+ providerOptions: options.providerOptions
119864
+ },
119865
+ ...options.includeRawChunks != null && {
119866
+ includeRawChunks: options.includeRawChunks
119867
+ }
119868
+ };
119869
+ return {
119870
+ stream: createGatewayTranscriptionStream({
119871
+ webSocket: this.config.webSocket,
119872
+ url: toGatewayTranscriptionUrl(this.config.baseURL, this.modelId),
119873
+ protocols: getProtocolsFromHeaders(headers),
119874
+ headers,
119875
+ startFrame,
119876
+ audio: options.audio,
119877
+ abortSignal: options.abortSignal,
119878
+ authMethod
119879
+ }),
119880
+ request: { body: startFrame },
119881
+ response: { timestamp: currentDate, modelId: this.modelId }
119882
+ };
119883
+ }
119480
119884
  getUrl() {
119481
119885
  return `${this.config.baseURL}/transcription-model`;
119482
119886
  }
@@ -119487,6 +119891,151 @@ var GatewayTranscriptionModel = class {
119487
119891
  };
119488
119892
  }
119489
119893
  };
119894
+ function toGatewayTranscriptionUrl(baseURL, modelId) {
119895
+ const url2 = new URL(`${baseURL.replace(/^http/, "ws")}/transcription-model`);
119896
+ url2.searchParams.set("ai-model-id", modelId);
119897
+ return url2.toString();
119898
+ }
119899
+ function getProtocolsFromHeaders(headers) {
119900
+ const normalizedHeaders = normalizeHeaders(headers);
119901
+ const authorization = normalizedHeaders.authorization;
119902
+ const token = (authorization == null ? undefined : authorization.startsWith("Bearer ")) ? authorization.slice("Bearer ".length) : undefined;
119903
+ return token == null ? [GATEWAY_TRANSCRIPTION_SUBPROTOCOL] : getGatewayTranscriptionProtocols(token, {
119904
+ teamIdOrSlug: normalizedHeaders[VERCEL_AI_GATEWAY_TEAM_HEADER]
119905
+ });
119906
+ }
119907
+ var MAX_AUDIO_FRAME_BYTES = 64 * 1024;
119908
+ function createGatewayTranscriptionStream({
119909
+ webSocket,
119910
+ url: url2,
119911
+ protocols,
119912
+ headers,
119913
+ startFrame,
119914
+ audio,
119915
+ abortSignal,
119916
+ authMethod
119917
+ }) {
119918
+ let finished = false;
119919
+ let cleanup = () => {};
119920
+ return new ReadableStream({
119921
+ start: (controller) => {
119922
+ let audioReader;
119923
+ let hasServerErrorPart = false;
119924
+ let lastServerError;
119925
+ let audioStopped = false;
119926
+ let connection;
119927
+ cleanup = (closeCode) => {
119928
+ if (audioReader != null) {
119929
+ audioReader.cancel().catch(() => {});
119930
+ } else {
119931
+ audio.cancel().catch(() => {});
119932
+ }
119933
+ connection == null || connection.close(closeCode);
119934
+ };
119935
+ const stopAudio = () => {
119936
+ audioStopped = true;
119937
+ if (audioReader != null) {
119938
+ audioReader.cancel().catch(() => {});
119939
+ audioReader = undefined;
119940
+ } else {
119941
+ audio.cancel().catch(() => {});
119942
+ }
119943
+ };
119944
+ const finishWithError = (error51) => {
119945
+ if (finished)
119946
+ return;
119947
+ finished = true;
119948
+ cleanup();
119949
+ errorControllerWithGatewayError(controller, error51, authMethod);
119950
+ };
119951
+ const sendAudio = async (socket) => {
119952
+ const reader = audio.getReader();
119953
+ audioReader = reader;
119954
+ try {
119955
+ while (true) {
119956
+ const { done, value } = await reader.read();
119957
+ if (done || finished)
119958
+ break;
119959
+ const bytes = typeof value === "string" ? convertBase64ToUint8Array(value) : value;
119960
+ for (let offset = 0;offset < bytes.length; offset += MAX_AUDIO_FRAME_BYTES) {
119961
+ if (finished)
119962
+ break;
119963
+ socket.send(bytes.subarray(offset, offset + MAX_AUDIO_FRAME_BYTES));
119964
+ await waitForWebSocketBufferDrain(socket);
119965
+ }
119966
+ }
119967
+ } finally {
119968
+ reader.releaseLock();
119969
+ if (audioReader === reader) {
119970
+ audioReader = undefined;
119971
+ }
119972
+ }
119973
+ if (!finished && !audioStopped) {
119974
+ socket.send(JSON.stringify({
119975
+ type: TRANSCRIPTION_STREAM_AUDIO_DONE_FRAME_TYPE
119976
+ }));
119977
+ }
119978
+ };
119979
+ connection = connectToWebSocket({
119980
+ url: url2,
119981
+ protocols,
119982
+ headers,
119983
+ webSocket,
119984
+ abortSignal,
119985
+ onAbort: (reason) => {
119986
+ if (finished)
119987
+ return;
119988
+ finished = true;
119989
+ cleanup();
119990
+ controller.error(reason);
119991
+ },
119992
+ onProcessingError: finishWithError,
119993
+ onOpen: (socket) => {
119994
+ socket.send(JSON.stringify(startFrame));
119995
+ sendAudio(socket).catch(finishWithError);
119996
+ },
119997
+ onMessageText: (text) => {
119998
+ if (finished)
119999
+ return;
120000
+ const part = parseTranscriptionStreamPart(text);
120001
+ if (part == null)
120002
+ return;
120003
+ if (part.type === "finish") {
120004
+ finished = true;
120005
+ controller.enqueue(part);
120006
+ controller.close();
120007
+ cleanup(1000);
120008
+ return;
120009
+ }
120010
+ if (part.type === "error") {
120011
+ hasServerErrorPart = true;
120012
+ lastServerError = part.error;
120013
+ stopAudio();
120014
+ }
120015
+ controller.enqueue(part);
120016
+ },
120017
+ onSocketError: () => {
120018
+ finishWithError(new Error("Connection error on AI Gateway transcription stream"));
120019
+ },
120020
+ onClose: () => {
120021
+ if (hasServerErrorPart) {
120022
+ if (finished)
120023
+ return;
120024
+ createErrorFromServerErrorPart(lastServerError, authMethod).then(finishWithError);
120025
+ return;
120026
+ }
120027
+ finishWithError(new Error("AI Gateway transcription stream closed before a finish part was received"));
120028
+ }
120029
+ });
120030
+ },
120031
+ cancel: () => {
120032
+ if (finished)
120033
+ return;
120034
+ finished = true;
120035
+ cleanup();
120036
+ }
120037
+ });
120038
+ }
119490
120039
  var providerMetadataEntrySchema4 = exports_external.object({}).catchall(exports_external.unknown());
119491
120040
  var gatewayTranscriptionWarningSchema = exports_external.discriminatedUnion("type", [
119492
120041
  exports_external.object({
@@ -119521,6 +120070,34 @@ var gatewayTranscriptionResponseSchema = exports_external.object({
119521
120070
  warnings: exports_external.array(gatewayTranscriptionWarningSchema).optional(),
119522
120071
  providerMetadata: exports_external.record(exports_external.string(), providerMetadataEntrySchema4).optional()
119523
120072
  });
120073
+ async function errorControllerWithGatewayError(controller, error51, authMethod) {
120074
+ controller.error(await asGatewayError(error51, authMethod));
120075
+ }
120076
+ function getServerErrorMessage(error51) {
120077
+ if (error51 != null && typeof error51 === "object" && "message" in error51 && typeof error51.message === "string") {
120078
+ return error51.message;
120079
+ }
120080
+ return getErrorMessage(error51);
120081
+ }
120082
+ var SERVER_ERROR_STATUS_CODES = {
120083
+ authentication_error: 401,
120084
+ failed_dependency: 424,
120085
+ forbidden: 403,
120086
+ internal_server_error: 500,
120087
+ invalid_request_error: 400,
120088
+ model_not_found: 404,
120089
+ rate_limit_exceeded: 429
120090
+ };
120091
+ async function createErrorFromServerErrorPart(error51, authMethod) {
120092
+ if (typeof error51 === "object" && error51 != null && "message" in error51 && typeof error51.message === "string" && "type" in error51 && typeof error51.type === "string" && error51.type in SERVER_ERROR_STATUS_CODES) {
120093
+ return createGatewayErrorFromResponse({
120094
+ response: { error: { message: error51.message, type: error51.type } },
120095
+ statusCode: SERVER_ERROR_STATUS_CODES[error51.type],
120096
+ authMethod
120097
+ });
120098
+ }
120099
+ return new Error(`AI Gateway transcription stream failed: ${getServerErrorMessage(error51)}`);
120100
+ }
119524
120101
  var GatewayRealtimeModel = class {
119525
120102
  constructor(modelId, config2) {
119526
120103
  this.specificationVersion = "v4";
@@ -119650,7 +120227,7 @@ var exaSearchOutputSchema = lazySchema(() => zodSchema(exports_external.union([
119650
120227
  })),
119651
120228
  costDollars: exports_external.object({
119652
120229
  total: exports_external.number().optional(),
119653
- search: exports_external.record(exports_external.number()).optional()
120230
+ search: exports_external.record(exports_external.string(), exports_external.number()).optional()
119654
120231
  }).optional()
119655
120232
  }),
119656
120233
  exports_external.object({
@@ -119773,7 +120350,7 @@ async function getVercelRequestId() {
119773
120350
  var _a112;
119774
120351
  return (_a112 = import_oidc.getContext().headers) == null ? undefined : _a112["x-vercel-id"];
119775
120352
  }
119776
- var VERSION3 = "4.0.14";
120353
+ var VERSION3 = "4.0.28";
119777
120354
  var AI_GATEWAY_PROTOCOL_VERSION = "0.0.1";
119778
120355
  var gatewayClientSecretResponseSchema = exports_external.object({
119779
120356
  token: exports_external.string(),
@@ -119817,8 +120394,8 @@ function createGateway(options = {}) {
119817
120394
  });
119818
120395
  }
119819
120396
  };
119820
- const mintRealtimeClientSecret = async (params) => {
119821
- assertGatewayRealtimeServerEnvironment();
120397
+ const mintClientSecret = async (params) => {
120398
+ assertGatewayClientSecretServerEnvironment();
119822
120399
  const auth = await getRealtimeAuthToken();
119823
120400
  const headers = createAuthHeaders(auth);
119824
120401
  const url2 = new URL("/v1/realtime/client-secrets", baseURL).toString();
@@ -119828,6 +120405,7 @@ function createGateway(options = {}) {
119828
120405
  headers,
119829
120406
  body: {
119830
120407
  model: params.modelId,
120408
+ ...params.routeKind != null && { routeKind: params.routeKind },
119831
120409
  ...params.expiresAfterSeconds != null && {
119832
120410
  expiresIn: params.expiresAfterSeconds
119833
120411
  }
@@ -119998,16 +120576,33 @@ function createGateway(options = {}) {
119998
120576
  baseURL,
119999
120577
  headers: getHeaders,
120000
120578
  fetch: options.fetch,
120001
- o11yHeaders: createO11yHeaders()
120579
+ o11yHeaders: createO11yHeaders(),
120580
+ webSocket: options.webSocket
120002
120581
  });
120003
120582
  };
120004
120583
  provider.transcriptionModel = createTranscriptionModel;
120005
120584
  provider.transcription = createTranscriptionModel;
120585
+ provider.experimental_transcription = Object.assign((modelId) => createTranscriptionModel(modelId), {
120586
+ getToken: async (tokenOptions) => {
120587
+ const secret = await mintClientSecret({
120588
+ modelId: tokenOptions.model,
120589
+ routeKind: "transcription",
120590
+ ...tokenOptions.expiresAfterSeconds != null && {
120591
+ expiresAfterSeconds: tokenOptions.expiresAfterSeconds
120592
+ }
120593
+ });
120594
+ return {
120595
+ token: secret.token,
120596
+ url: toGatewayTranscriptionUrl(baseURL, tokenOptions.model),
120597
+ ...secret.expiresAt != null && { expiresAt: secret.expiresAt }
120598
+ };
120599
+ }
120600
+ });
120006
120601
  const createRealtimeModel = (modelId) => new GatewayRealtimeModel(modelId, {
120007
120602
  provider: "gateway.realtime",
120008
120603
  baseURL,
120009
120604
  teamIdOrSlug: options.teamIdOrSlug,
120010
- createClientSecret: mintRealtimeClientSecret
120605
+ createClientSecret: mintClientSecret
120011
120606
  });
120012
120607
  provider.experimental_realtime = Object.assign((modelId) => createRealtimeModel(modelId), {
120013
120608
  getToken: async (tokenOptions) => {
@@ -120046,9 +120641,9 @@ async function getGatewayAuthToken(options) {
120046
120641
  authMethod: "oidc"
120047
120642
  };
120048
120643
  }
120049
- function assertGatewayRealtimeServerEnvironment() {
120644
+ function assertGatewayClientSecretServerEnvironment() {
120050
120645
  if (typeof globalThis.window !== "undefined") {
120051
- throw new Error("AI Gateway realtime client secrets must be minted server-side: minting needs your Gateway credential, which must never reach the browser. Call gateway.experimental_realtime.getToken() from your server and pass the returned token to the client.");
120646
+ throw new Error("AI Gateway client secrets must be minted server-side: minting needs your Gateway credential, which must never reach the browser. Call gateway.experimental_realtime.getToken() or gateway.experimental_transcription.getToken() from your server and pass the returned token to the client.");
120052
120647
  }
120053
120648
  }
120054
120649
 
@@ -120753,7 +121348,7 @@ function cloneValue(value) {
120753
121348
  }
120754
121349
  return value;
120755
121350
  }
120756
- var VERSION4 = "7.0.18";
121351
+ var VERSION4 = "7.0.37";
120757
121352
  var download = async ({
120758
121353
  url: url2,
120759
121354
  maxBytes,
@@ -120793,6 +121388,37 @@ var download = async ({
120793
121388
  }
120794
121389
  };
120795
121390
  var createDefaultDownloadFunction = (download2 = download) => (requestedDownloads) => Promise.all(requestedDownloads.map(async (requestedDownload) => requestedDownload.isUrlSupportedByModel ? null : await download2(requestedDownload)));
121391
+ function mergeObjects(base, overrides) {
121392
+ if (base === undefined && overrides === undefined) {
121393
+ return;
121394
+ }
121395
+ if (base === undefined) {
121396
+ return overrides;
121397
+ }
121398
+ if (overrides === undefined) {
121399
+ return base;
121400
+ }
121401
+ const result = { ...base };
121402
+ for (const key in overrides) {
121403
+ if (key === "__proto__" || key === "constructor" || key === "prototype") {
121404
+ continue;
121405
+ }
121406
+ if (Object.prototype.hasOwnProperty.call(overrides, key)) {
121407
+ const overridesValue = overrides[key];
121408
+ if (overridesValue === undefined)
121409
+ continue;
121410
+ const baseValue = key in base ? base[key] : undefined;
121411
+ const isSourceObject = overridesValue !== null && typeof overridesValue === "object" && !Array.isArray(overridesValue) && !(overridesValue instanceof Date) && !(overridesValue instanceof RegExp);
121412
+ const isTargetObject = baseValue !== null && baseValue !== undefined && typeof baseValue === "object" && !Array.isArray(baseValue) && !(baseValue instanceof Date) && !(baseValue instanceof RegExp);
121413
+ if (isSourceObject && isTargetObject) {
121414
+ result[key] = mergeObjects(baseValue, overridesValue);
121415
+ } else {
121416
+ result[key] = overridesValue;
121417
+ }
121418
+ }
121419
+ }
121420
+ return result;
121421
+ }
120796
121422
  function splitDataUrl(dataUrl) {
120797
121423
  try {
120798
121424
  const [header, base64Content] = dataUrl.split(",");
@@ -120936,7 +121562,12 @@ async function convertToLanguageModelPrompt({
120936
121562
  }
120937
121563
  const lastCombinedMessage = combinedMessages.at(-1);
120938
121564
  if ((lastCombinedMessage == null ? undefined : lastCombinedMessage.role) === "tool") {
121565
+ const lastContentPart = lastCombinedMessage.content.at(-1);
121566
+ if (lastContentPart != null && lastCombinedMessage.providerOptions != null) {
121567
+ lastContentPart.providerOptions = mergeObjects(lastCombinedMessage.providerOptions, lastContentPart.providerOptions);
121568
+ }
120939
121569
  lastCombinedMessage.content.push(...message.content);
121570
+ lastCombinedMessage.providerOptions = message.providerOptions;
120940
121571
  } else {
120941
121572
  combinedMessages.push(message);
120942
121573
  }
@@ -122036,41 +122667,13 @@ function addLanguageModelUsage(usage1, usage2) {
122036
122667
  function addTokenCounts(tokenCount1, tokenCount2) {
122037
122668
  return tokenCount1 == null && tokenCount2 == null ? undefined : (tokenCount1 != null ? tokenCount1 : 0) + (tokenCount2 != null ? tokenCount2 : 0);
122038
122669
  }
122670
+ function getOwn(obj, key) {
122671
+ return obj != null && Object.hasOwn(obj, key) ? obj[key] : undefined;
122672
+ }
122039
122673
  function mergeAbortSignals(...signals) {
122040
122674
  const validSignals = filterNullable(...signals).map((signal) => signal instanceof AbortSignal ? signal : AbortSignal.timeout(signal));
122041
122675
  return validSignals.length === 0 ? undefined : validSignals.length === 1 ? validSignals[0] : AbortSignal.any(validSignals);
122042
122676
  }
122043
- function mergeObjects(base, overrides) {
122044
- if (base === undefined && overrides === undefined) {
122045
- return;
122046
- }
122047
- if (base === undefined) {
122048
- return overrides;
122049
- }
122050
- if (overrides === undefined) {
122051
- return base;
122052
- }
122053
- const result = { ...base };
122054
- for (const key in overrides) {
122055
- if (key === "__proto__" || key === "constructor" || key === "prototype") {
122056
- continue;
122057
- }
122058
- if (Object.prototype.hasOwnProperty.call(overrides, key)) {
122059
- const overridesValue = overrides[key];
122060
- if (overridesValue === undefined)
122061
- continue;
122062
- const baseValue = key in base ? base[key] : undefined;
122063
- const isSourceObject = overridesValue !== null && typeof overridesValue === "object" && !Array.isArray(overridesValue) && !(overridesValue instanceof Date) && !(overridesValue instanceof RegExp);
122064
- const isTargetObject = baseValue !== null && baseValue !== undefined && typeof baseValue === "object" && !Array.isArray(baseValue) && !(baseValue instanceof Date) && !(baseValue instanceof RegExp);
122065
- if (isSourceObject && isTargetObject) {
122066
- result[key] = mergeObjects(baseValue, overridesValue);
122067
- } else {
122068
- result[key] = overridesValue;
122069
- }
122070
- }
122071
- }
122072
- return result;
122073
- }
122074
122677
  function now() {
122075
122678
  var _a222, _b17;
122076
122679
  return (_b17 = (_a222 = globalThis == null ? undefined : globalThis.performance) == null ? undefined : _a222.now()) != null ? _b17 : Date.now();
@@ -122184,7 +122787,7 @@ function collectToolApprovals({
122184
122787
  deniedToolApprovals: []
122185
122788
  };
122186
122789
  }
122187
- const toolCallsByToolCallId = {};
122790
+ const toolCallsByToolCallId = /* @__PURE__ */ Object.create(null);
122188
122791
  for (const message of messages) {
122189
122792
  if (message.role === "assistant" && typeof message.content !== "string") {
122190
122793
  const content = message.content;
@@ -122195,7 +122798,7 @@ function collectToolApprovals({
122195
122798
  }
122196
122799
  }
122197
122800
  }
122198
- const toolApprovalRequestsByApprovalId = {};
122801
+ const toolApprovalRequestsByApprovalId = /* @__PURE__ */ Object.create(null);
122199
122802
  for (const message of messages) {
122200
122803
  if (message.role === "assistant" && typeof message.content !== "string") {
122201
122804
  const content = message.content;
@@ -122206,7 +122809,7 @@ function collectToolApprovals({
122206
122809
  }
122207
122810
  }
122208
122811
  }
122209
- const toolResults = {};
122812
+ const toolResults = /* @__PURE__ */ Object.create(null);
122210
122813
  for (const part of lastMessage.content) {
122211
122814
  if (part.type === "tool-result") {
122212
122815
  toolResults[part.toolCallId] = part;
@@ -122222,7 +122825,8 @@ function collectToolApprovals({
122222
122825
  approvalId: approvalResponse.approvalId
122223
122826
  });
122224
122827
  }
122225
- if (toolResults[approvalRequest.toolCallId] != null) {
122828
+ const existingToolResult = toolResults[approvalRequest.toolCallId];
122829
+ if (existingToolResult != null && (approvalResponse.approved || existingToolResult.output.type !== "execution-denied")) {
122226
122830
  continue;
122227
122831
  }
122228
122832
  const toolCall = toolCallsByToolCallId[approvalRequest.toolCallId];
@@ -122235,7 +122839,8 @@ function collectToolApprovals({
122235
122839
  const approval = {
122236
122840
  approvalRequest,
122237
122841
  approvalResponse,
122238
- toolCall
122842
+ toolCall,
122843
+ ...existingToolResult != null ? { existingToolResult } : {}
122239
122844
  };
122240
122845
  if (approvalResponse.approved) {
122241
122846
  approvedToolApprovals.push(approval);
@@ -122278,13 +122883,13 @@ async function executeToolCall({
122278
122883
  runInTracingChannelSpan = async ({ execute }) => await execute()
122279
122884
  }) {
122280
122885
  const { toolName, toolCallId, input } = toolCall;
122281
- const tool2 = tools == null ? undefined : tools[toolName];
122886
+ const tool2 = getOwn(tools, toolName);
122282
122887
  if (!isExecutableTool(tool2)) {
122283
122888
  return;
122284
122889
  }
122285
122890
  const context = await validateToolContext({
122286
122891
  toolName,
122287
- context: toolsContext == null ? undefined : toolsContext[toolName],
122892
+ context: getOwn(toolsContext, toolName),
122288
122893
  contextSchema: tool2.contextSchema
122289
122894
  });
122290
122895
  const toolExecutionContext = {
@@ -123122,7 +123727,8 @@ async function parseToolCall({
123122
123727
  toolCall,
123123
123728
  tools,
123124
123729
  inputSchema: async ({ toolName }) => {
123125
- const { inputSchema } = tools[toolName];
123730
+ var _a222;
123731
+ const inputSchema = (_a222 = getOwn(tools, toolName)) == null ? undefined : _a222.inputSchema;
123126
123732
  return await asSchema(inputSchema).jsonSchema;
123127
123733
  },
123128
123734
  instructions,
@@ -123147,7 +123753,7 @@ async function parseToolCall({
123147
123753
  } catch (error51) {
123148
123754
  const parsedInput = await safeParseJSON({ text: toolCall.input });
123149
123755
  const input = parsedInput.success ? parsedInput.value : toolCall.input;
123150
- const tool2 = tools == null ? undefined : tools[toolCall.toolName];
123756
+ const tool2 = getOwn(tools, toolCall.toolName);
123151
123757
  return {
123152
123758
  type: "tool-call",
123153
123759
  toolCallId: toolCall.toolCallId,
@@ -123167,7 +123773,7 @@ async function refineParsedToolCallInput({
123167
123773
  toolCall,
123168
123774
  refineToolInput
123169
123775
  }) {
123170
- const refine2 = refineToolInput == null ? undefined : refineToolInput[toolCall.toolName];
123776
+ const refine2 = getOwn(refineToolInput, toolCall.toolName);
123171
123777
  if (refine2 == null) {
123172
123778
  return toolCall;
123173
123779
  }
@@ -123200,7 +123806,7 @@ async function doParseToolCall({
123200
123806
  tools
123201
123807
  }) {
123202
123808
  const toolName = toolCall.toolName;
123203
- const tool2 = tools[toolName];
123809
+ const tool2 = getOwn(tools, toolName);
123204
123810
  if (tool2 == null) {
123205
123811
  if (toolCall.providerExecuted && toolCall.dynamic) {
123206
123812
  return await parseProviderExecutedDynamicToolCall(toolCall);
@@ -123302,16 +123908,16 @@ async function resolveToolApproval({
123302
123908
  }));
123303
123909
  }
123304
123910
  const toolName = toolCall.toolName;
123305
- const tool2 = tools == null ? undefined : tools[toolName];
123911
+ const tool2 = getOwn(tools, toolName);
123306
123912
  const input = toolCall.input;
123307
- const userDefinedToolApprovalStatus = toolApproval == null ? undefined : toolApproval[toolName];
123913
+ const userDefinedToolApprovalStatus = getOwn(toolApproval, toolName);
123308
123914
  if (userDefinedToolApprovalStatus != null) {
123309
123915
  const approvalStatus = typeof userDefinedToolApprovalStatus === "function" ? await userDefinedToolApprovalStatus(input, {
123310
123916
  toolCallId: toolCall.toolCallId,
123311
123917
  messages,
123312
123918
  toolContext: await validateToolContext({
123313
123919
  toolName,
123314
- context: toolsContext == null ? undefined : toolsContext[toolName],
123920
+ context: getOwn(toolsContext, toolName),
123315
123921
  contextSchema: tool2 == null ? undefined : tool2.contextSchema
123316
123922
  }),
123317
123923
  runtimeContext
@@ -123326,7 +123932,7 @@ async function resolveToolApproval({
123326
123932
  messages,
123327
123933
  context: await validateToolContext({
123328
123934
  toolName,
123329
- context: toolsContext == null ? undefined : toolsContext[toolName],
123935
+ context: getOwn(toolsContext, toolName),
123330
123936
  contextSchema: tool2 == null ? undefined : tool2.contextSchema
123331
123937
  })
123332
123938
  }) : tool2.needsApproval;
@@ -123881,7 +124487,7 @@ async function toResponseMessages({
123881
124487
  const output = await createToolModelOutput({
123882
124488
  toolCallId: part.toolCallId,
123883
124489
  input: part.input,
123884
- tool: tools == null ? undefined : tools[part.toolName],
124490
+ tool: getOwn(tools, part.toolName),
123885
124491
  output: part.output,
123886
124492
  errorMode: "none"
123887
124493
  });
@@ -123898,7 +124504,7 @@ async function toResponseMessages({
123898
124504
  const output = await createToolModelOutput({
123899
124505
  toolCallId: part.toolCallId,
123900
124506
  input: part.input,
123901
- tool: tools == null ? undefined : tools[part.toolName],
124507
+ tool: getOwn(tools, part.toolName),
123902
124508
  output: part.error,
123903
124509
  errorMode: "json"
123904
124510
  });
@@ -123960,7 +124566,7 @@ async function toResponseMessages({
123960
124566
  const output = await createToolModelOutput({
123961
124567
  toolCallId: part.toolCallId,
123962
124568
  input: part.input,
123963
- tool: tools == null ? undefined : tools[part.toolName],
124569
+ tool: getOwn(tools, part.toolName),
123964
124570
  output: part.type === "tool-result" ? part.output : part.error,
123965
124571
  errorMode: part.type === "tool-error" ? "text" : "none"
123966
124572
  });
@@ -124022,20 +124628,29 @@ function canonicalJSON(value) {
124022
124628
  function toBase64url(bytes) {
124023
124629
  return convertUint8ArrayToBase64(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
124024
124630
  }
124631
+ async function hashCanonical(value) {
124632
+ const digest = await crypto.subtle.digest("SHA-256", encoder.encode(canonicalJSON(value)));
124633
+ return toBase64url(new Uint8Array(digest));
124634
+ }
124635
+ var encoder2 = new TextEncoder;
124025
124636
  function fromBase64url(str) {
124026
124637
  return convertBase64ToUint8Array(str);
124027
124638
  }
124028
124639
  async function importKey(secret) {
124029
- const keyData = typeof secret === "string" ? encoder.encode(secret) : secret;
124640
+ const keyData = typeof secret === "string" ? encoder2.encode(secret) : secret;
124030
124641
  return crypto.subtle.importKey("raw", keyData, { name: "HMAC", hash: "SHA-256" }, false, ["sign", "verify"]);
124031
124642
  }
124032
- async function hashInput(input) {
124033
- const canonical = canonicalJSON(input);
124034
- const digest = await crypto.subtle.digest("SHA-256", encoder.encode(canonical));
124035
- return toBase64url(new Uint8Array(digest));
124036
- }
124037
124643
  function buildPayload(approvalId, toolCallId, toolName, inputDigest) {
124038
- return encoder.encode(`${approvalId}
124644
+ return encoder2.encode(JSON.stringify([
124645
+ "ai-sdk-tool-approval-v1",
124646
+ approvalId,
124647
+ toolCallId,
124648
+ toolName,
124649
+ inputDigest
124650
+ ]));
124651
+ }
124652
+ function buildLegacyPayload(approvalId, toolCallId, toolName, inputDigest) {
124653
+ return encoder2.encode(`${approvalId}
124039
124654
  ${toolCallId}
124040
124655
  ${toolName}
124041
124656
  ${inputDigest}`);
@@ -124048,7 +124663,7 @@ async function signToolApproval({
124048
124663
  input
124049
124664
  }) {
124050
124665
  const key = await importKey(secret);
124051
- const inputDigest = await hashInput(input);
124666
+ const inputDigest = await hashCanonical(input);
124052
124667
  const payload = buildPayload(approvalId, toolCallId, toolName, inputDigest);
124053
124668
  const sig = await crypto.subtle.sign("HMAC", key, payload);
124054
124669
  return toBase64url(new Uint8Array(sig));
@@ -124062,10 +124677,20 @@ async function verifyToolApprovalSignature({
124062
124677
  input
124063
124678
  }) {
124064
124679
  const key = await importKey(secret);
124065
- const inputDigest = await hashInput(input);
124066
- const payload = buildPayload(approvalId, toolCallId, toolName, inputDigest);
124680
+ const inputDigest = await hashCanonical(input);
124067
124681
  const sigBytes = fromBase64url(signature);
124068
- return crypto.subtle.verify("HMAC", key, sigBytes, payload);
124682
+ const payload = buildPayload(approvalId, toolCallId, toolName, inputDigest);
124683
+ if (await crypto.subtle.verify("HMAC", key, sigBytes, payload)) {
124684
+ return true;
124685
+ }
124686
+ if (!approvalId.includes(`
124687
+ `) && !toolCallId.includes(`
124688
+ `) && !toolName.includes(`
124689
+ `)) {
124690
+ const legacyPayload = buildLegacyPayload(approvalId, toolCallId, toolName, inputDigest);
124691
+ return crypto.subtle.verify("HMAC", key, sigBytes, legacyPayload);
124692
+ }
124693
+ return false;
124069
124694
  }
124070
124695
  async function maybeSignApproval({
124071
124696
  secret,
@@ -124092,7 +124717,7 @@ async function validateApprovedToolApprovals({
124092
124717
  const denied = [];
124093
124718
  for (const approval of approvedToolApprovals) {
124094
124719
  const { toolCall, approvalRequest } = approval;
124095
- const tool2 = tools == null ? undefined : tools[toolCall.toolName];
124720
+ const tool2 = getOwn(tools, toolCall.toolName);
124096
124721
  if (toolApprovalSecret != null) {
124097
124722
  if (approvalRequest.signature == null) {
124098
124723
  throw new InvalidToolApprovalSignatureError({
@@ -124185,7 +124810,8 @@ async function generateText({
124185
124810
  activeTools,
124186
124811
  toolOrder,
124187
124812
  prepareStep,
124188
- experimental_repairToolCall: repairToolCall,
124813
+ experimental_repairToolCall,
124814
+ repairToolCall = experimental_repairToolCall,
124189
124815
  experimental_refineToolInput: refineToolInput,
124190
124816
  experimental_download: download2,
124191
124817
  runtimeContext = {},
@@ -124311,7 +124937,8 @@ async function generateText({
124311
124937
  ...collectedDeniedToolApprovals,
124312
124938
  ...revalidationDeniedToolApprovals
124313
124939
  ];
124314
- if (deniedToolApprovals.length > 0 || localApprovedToolApprovals.length > 0) {
124940
+ const deniedToolApprovalsWithoutResults = deniedToolApprovals.filter((toolApproval2) => toolApproval2.existingToolResult == null);
124941
+ if (deniedToolApprovalsWithoutResults.length > 0 || localApprovedToolApprovals.length > 0) {
124315
124942
  const toolResults2 = await executeTools({
124316
124943
  toolCalls: localApprovedToolApprovals.map((toolApproval2) => toolApproval2.toolCall),
124317
124944
  tools,
@@ -124344,7 +124971,7 @@ async function generateText({
124344
124971
  const modelOutput = await createToolModelOutput({
124345
124972
  toolCallId: output2.toolCallId,
124346
124973
  input: output2.input,
124347
- tool: tools == null ? undefined : tools[output2.toolName],
124974
+ tool: getOwn(tools, output2.toolName),
124348
124975
  output: output2.type === "tool-result" ? output2.output : output2.error,
124349
124976
  errorMode: output2.type === "tool-error" ? "text" : "none"
124350
124977
  });
@@ -124355,7 +124982,7 @@ async function generateText({
124355
124982
  output: modelOutput
124356
124983
  });
124357
124984
  }
124358
- for (const toolApproval2 of deniedToolApprovals) {
124985
+ for (const toolApproval2 of deniedToolApprovalsWithoutResults) {
124359
124986
  toolContent.push({
124360
124987
  type: "tool-result",
124361
124988
  toolCallId: toolApproval2.toolCall.toolCallId,
@@ -124392,6 +125019,9 @@ async function generateText({
124392
125019
  ];
124393
125020
  const pendingDeferredToolCalls = /* @__PURE__ */ new Map;
124394
125021
  do {
125022
+ if (steps.length > 0) {
125023
+ mergedAbortSignal == null || mergedAbortSignal.throwIfAborted();
125024
+ }
124395
125025
  const stepTimeoutId = setAbortTimeout({
124396
125026
  abortController: stepAbortController,
124397
125027
  label: "Step",
@@ -124577,10 +125207,18 @@ async function generateText({
124577
125207
  if (toolCall.invalid) {
124578
125208
  continue;
124579
125209
  }
124580
- const tool2 = tools == null ? undefined : tools[toolCall.toolName];
125210
+ const tool2 = getOwn(tools, toolCall.toolName);
124581
125211
  if (tool2 == null) {
124582
125212
  continue;
124583
125213
  }
125214
+ if (tool2.onInputStart != null) {
125215
+ await tool2.onInputStart({
125216
+ toolCallId: toolCall.toolCallId,
125217
+ messages: stepMessages,
125218
+ abortSignal: mergedAbortSignal,
125219
+ context: runtimeContext
125220
+ });
125221
+ }
124584
125222
  if ((tool2 == null ? undefined : tool2.onInputAvailable) != null) {
124585
125223
  await tool2.onInputAvailable({
124586
125224
  input: toolCall.input,
@@ -124727,7 +125365,7 @@ async function generateText({
124727
125365
  for (const toolCall of stepToolCalls) {
124728
125366
  if (!toolCall.providerExecuted)
124729
125367
  continue;
124730
- const tool2 = tools == null ? undefined : tools[toolCall.toolName];
125368
+ const tool2 = getOwn(tools, toolCall.toolName);
124731
125369
  if ((tool2 == null ? undefined : tool2.type) === "provider" && tool2.supportsDeferredResults) {
124732
125370
  const hasResultInResponse = currentModelResponse.content.some((part) => part.type === "tool-result" && part.toolCallId === toolCall.toolCallId);
124733
125371
  if (!hasResultInResponse) {
@@ -125046,7 +125684,7 @@ function asContent({
125046
125684
  case "tool-result": {
125047
125685
  const toolCall = toolCalls.find((toolCall2) => toolCall2.toolCallId === part.toolCallId);
125048
125686
  if (toolCall == null) {
125049
- const tool2 = tools == null ? undefined : tools[part.toolName];
125687
+ const tool2 = getOwn(tools, part.toolName);
125050
125688
  const supportsDeferredResults = (tool2 == null ? undefined : tool2.type) === "provider" && tool2.supportsDeferredResults;
125051
125689
  if (!supportsDeferredResults) {
125052
125690
  throw new Error(`Tool call ${part.toolCallId} not found.`);
@@ -125155,27 +125793,27 @@ var JsonToSseTransformStream = class extends TransformStream {
125155
125793
  };
125156
125794
  var toolMetadataSchema = exports_external.record(exports_external.string(), jsonValueSchema.optional());
125157
125795
  var uiMessageChunkSchema = lazySchema(() => zodSchema(exports_external.union([
125158
- exports_external.strictObject({
125796
+ exports_external.looseObject({
125159
125797
  type: exports_external.literal("text-start"),
125160
125798
  id: exports_external.string(),
125161
125799
  providerMetadata: providerMetadataSchema.optional()
125162
125800
  }),
125163
- exports_external.strictObject({
125801
+ exports_external.looseObject({
125164
125802
  type: exports_external.literal("text-delta"),
125165
125803
  id: exports_external.string(),
125166
125804
  delta: exports_external.string(),
125167
125805
  providerMetadata: providerMetadataSchema.optional()
125168
125806
  }),
125169
- exports_external.strictObject({
125807
+ exports_external.looseObject({
125170
125808
  type: exports_external.literal("text-end"),
125171
125809
  id: exports_external.string(),
125172
125810
  providerMetadata: providerMetadataSchema.optional()
125173
125811
  }),
125174
- exports_external.strictObject({
125812
+ exports_external.looseObject({
125175
125813
  type: exports_external.literal("error"),
125176
125814
  errorText: exports_external.string()
125177
125815
  }),
125178
- exports_external.strictObject({
125816
+ exports_external.looseObject({
125179
125817
  type: exports_external.literal("tool-input-start"),
125180
125818
  toolCallId: exports_external.string(),
125181
125819
  toolName: exports_external.string(),
@@ -125185,12 +125823,12 @@ var uiMessageChunkSchema = lazySchema(() => zodSchema(exports_external.union([
125185
125823
  dynamic: exports_external.boolean().optional(),
125186
125824
  title: exports_external.string().optional()
125187
125825
  }),
125188
- exports_external.strictObject({
125826
+ exports_external.looseObject({
125189
125827
  type: exports_external.literal("tool-input-delta"),
125190
125828
  toolCallId: exports_external.string(),
125191
125829
  inputTextDelta: exports_external.string()
125192
125830
  }),
125193
- exports_external.strictObject({
125831
+ exports_external.looseObject({
125194
125832
  type: exports_external.literal("tool-input-available"),
125195
125833
  toolCallId: exports_external.string(),
125196
125834
  toolName: exports_external.string(),
@@ -125201,7 +125839,7 @@ var uiMessageChunkSchema = lazySchema(() => zodSchema(exports_external.union([
125201
125839
  dynamic: exports_external.boolean().optional(),
125202
125840
  title: exports_external.string().optional()
125203
125841
  }),
125204
- exports_external.strictObject({
125842
+ exports_external.looseObject({
125205
125843
  type: exports_external.literal("tool-input-error"),
125206
125844
  toolCallId: exports_external.string(),
125207
125845
  toolName: exports_external.string(),
@@ -125213,14 +125851,14 @@ var uiMessageChunkSchema = lazySchema(() => zodSchema(exports_external.union([
125213
125851
  errorText: exports_external.string(),
125214
125852
  title: exports_external.string().optional()
125215
125853
  }),
125216
- exports_external.strictObject({
125854
+ exports_external.looseObject({
125217
125855
  type: exports_external.literal("tool-approval-request"),
125218
125856
  approvalId: exports_external.string(),
125219
125857
  toolCallId: exports_external.string(),
125220
125858
  isAutomatic: exports_external.boolean().optional(),
125221
125859
  signature: exports_external.string().optional()
125222
125860
  }),
125223
- exports_external.strictObject({
125861
+ exports_external.looseObject({
125224
125862
  type: exports_external.literal("tool-approval-response"),
125225
125863
  approvalId: exports_external.string(),
125226
125864
  approved: exports_external.boolean(),
@@ -125228,7 +125866,7 @@ var uiMessageChunkSchema = lazySchema(() => zodSchema(exports_external.union([
125228
125866
  providerExecuted: exports_external.boolean().optional(),
125229
125867
  providerMetadata: providerMetadataSchema.optional()
125230
125868
  }),
125231
- exports_external.strictObject({
125869
+ exports_external.looseObject({
125232
125870
  type: exports_external.literal("tool-output-available"),
125233
125871
  toolCallId: exports_external.string(),
125234
125872
  output: exports_external.unknown(),
@@ -125238,7 +125876,7 @@ var uiMessageChunkSchema = lazySchema(() => zodSchema(exports_external.union([
125238
125876
  dynamic: exports_external.boolean().optional(),
125239
125877
  preliminary: exports_external.boolean().optional()
125240
125878
  }),
125241
- exports_external.strictObject({
125879
+ exports_external.looseObject({
125242
125880
  type: exports_external.literal("tool-output-error"),
125243
125881
  toolCallId: exports_external.string(),
125244
125882
  errorText: exports_external.string(),
@@ -125247,39 +125885,39 @@ var uiMessageChunkSchema = lazySchema(() => zodSchema(exports_external.union([
125247
125885
  toolMetadata: toolMetadataSchema.optional(),
125248
125886
  dynamic: exports_external.boolean().optional()
125249
125887
  }),
125250
- exports_external.strictObject({
125888
+ exports_external.looseObject({
125251
125889
  type: exports_external.literal("tool-output-denied"),
125252
125890
  toolCallId: exports_external.string()
125253
125891
  }),
125254
- exports_external.strictObject({
125892
+ exports_external.looseObject({
125255
125893
  type: exports_external.literal("reasoning-start"),
125256
125894
  id: exports_external.string(),
125257
125895
  providerMetadata: providerMetadataSchema.optional()
125258
125896
  }),
125259
- exports_external.strictObject({
125897
+ exports_external.looseObject({
125260
125898
  type: exports_external.literal("reasoning-delta"),
125261
125899
  id: exports_external.string(),
125262
125900
  delta: exports_external.string(),
125263
125901
  providerMetadata: providerMetadataSchema.optional()
125264
125902
  }),
125265
- exports_external.strictObject({
125903
+ exports_external.looseObject({
125266
125904
  type: exports_external.literal("reasoning-end"),
125267
125905
  id: exports_external.string(),
125268
125906
  providerMetadata: providerMetadataSchema.optional()
125269
125907
  }),
125270
- exports_external.strictObject({
125908
+ exports_external.looseObject({
125271
125909
  type: exports_external.literal("custom"),
125272
125910
  kind: exports_external.string().transform((value) => value),
125273
125911
  providerMetadata: providerMetadataSchema.optional()
125274
125912
  }),
125275
- exports_external.strictObject({
125913
+ exports_external.looseObject({
125276
125914
  type: exports_external.literal("source-url"),
125277
125915
  sourceId: exports_external.string(),
125278
125916
  url: exports_external.string(),
125279
125917
  title: exports_external.string().optional(),
125280
125918
  providerMetadata: providerMetadataSchema.optional()
125281
125919
  }),
125282
- exports_external.strictObject({
125920
+ exports_external.looseObject({
125283
125921
  type: exports_external.literal("source-document"),
125284
125922
  sourceId: exports_external.string(),
125285
125923
  mediaType: exports_external.string(),
@@ -125287,36 +125925,36 @@ var uiMessageChunkSchema = lazySchema(() => zodSchema(exports_external.union([
125287
125925
  filename: exports_external.string().optional(),
125288
125926
  providerMetadata: providerMetadataSchema.optional()
125289
125927
  }),
125290
- exports_external.strictObject({
125928
+ exports_external.looseObject({
125291
125929
  type: exports_external.literal("file"),
125292
125930
  url: exports_external.string(),
125293
125931
  mediaType: exports_external.string(),
125294
125932
  providerMetadata: providerMetadataSchema.optional()
125295
125933
  }),
125296
- exports_external.strictObject({
125934
+ exports_external.looseObject({
125297
125935
  type: exports_external.literal("reasoning-file"),
125298
125936
  url: exports_external.string(),
125299
125937
  mediaType: exports_external.string(),
125300
125938
  providerMetadata: providerMetadataSchema.optional()
125301
125939
  }),
125302
- exports_external.strictObject({
125940
+ exports_external.looseObject({
125303
125941
  type: exports_external.custom((value) => typeof value === "string" && value.startsWith("data-"), { message: 'Type must start with "data-"' }),
125304
125942
  id: exports_external.string().optional(),
125305
125943
  data: exports_external.unknown(),
125306
125944
  transient: exports_external.boolean().optional()
125307
125945
  }),
125308
- exports_external.strictObject({
125946
+ exports_external.looseObject({
125309
125947
  type: exports_external.literal("start-step")
125310
125948
  }),
125311
- exports_external.strictObject({
125949
+ exports_external.looseObject({
125312
125950
  type: exports_external.literal("finish-step")
125313
125951
  }),
125314
- exports_external.strictObject({
125952
+ exports_external.looseObject({
125315
125953
  type: exports_external.literal("start"),
125316
125954
  messageId: exports_external.string().optional(),
125317
125955
  messageMetadata: exports_external.unknown().optional()
125318
125956
  }),
125319
- exports_external.strictObject({
125957
+ exports_external.looseObject({
125320
125958
  type: exports_external.literal("finish"),
125321
125959
  finishReason: exports_external.enum([
125322
125960
  "stop",
@@ -125328,11 +125966,11 @@ var uiMessageChunkSchema = lazySchema(() => zodSchema(exports_external.union([
125328
125966
  ]).optional(),
125329
125967
  messageMetadata: exports_external.unknown().optional()
125330
125968
  }),
125331
- exports_external.strictObject({
125969
+ exports_external.looseObject({
125332
125970
  type: exports_external.literal("abort"),
125333
125971
  reason: exports_external.string().optional()
125334
125972
  }),
125335
- exports_external.strictObject({
125973
+ exports_external.looseObject({
125336
125974
  type: exports_external.literal("message-metadata"),
125337
125975
  messageMetadata: exports_external.unknown()
125338
125976
  })
@@ -125657,7 +126295,19 @@ var uiMessagesSchema = lazySchema(() => zodSchema(exports_external.array(exports
125657
126295
  signature: exports_external.string().optional()
125658
126296
  })
125659
126297
  })
125660
- ])).nonempty("Message must contain at least one part")
126298
+ ]))
126299
+ }).superRefine((message, context) => {
126300
+ if (message.role !== "assistant" && message.parts.length === 0) {
126301
+ context.addIssue({
126302
+ origin: "array",
126303
+ code: "too_small",
126304
+ minimum: 1,
126305
+ inclusive: true,
126306
+ input: message.parts,
126307
+ path: ["parts"],
126308
+ message: "Message must contain at least one part"
126309
+ });
126310
+ }
125661
126311
  })).nonempty("Messages array must not be empty")));
125662
126312
  var originalGenerateCallId4 = createIdGenerator({
125663
126313
  prefix: "call",
@@ -128801,7 +129451,7 @@ class McpSessionManager {
128801
129451
  }
128802
129452
 
128803
129453
  // node_modules/modality-mcp-kit/dist/types/mcp-result-types.js
128804
- function isString3(value10) {
129454
+ function isString4(value10) {
128805
129455
  return typeof value10 === "string";
128806
129456
  }
128807
129457
  function looksLikeCallToolResult(value10) {
@@ -128818,7 +129468,7 @@ function isCallToolResult(value10) {
128818
129468
  const obj = value10;
128819
129469
  return Array.isArray(obj.content) && obj.content.length > 0 && (typeof obj.isError === "undefined" || typeof obj.isError === "boolean") && (typeof obj.structuredContent === "undefined" || typeof obj.structuredContent === "object");
128820
129470
  }
128821
- function isPlainObject3(value10) {
129471
+ function isPlainObject4(value10) {
128822
129472
  return typeof value10 === "object" && value10 !== null && !Array.isArray(value10) && !isCallToolResult(value10);
128823
129473
  }
128824
129474
  function isNullOrUndefined(value10) {
@@ -128987,7 +129637,7 @@ function generateJsonSummary(obj) {
128987
129637
  }
128988
129638
  }
128989
129639
  function normalizeToolResult(result) {
128990
- if (isString3(result)) {
129640
+ if (isString4(result)) {
128991
129641
  return createSimpleResult(result);
128992
129642
  }
128993
129643
  if (isNullOrUndefined(result)) {
@@ -129003,7 +129653,7 @@ function normalizeToolResult(result) {
129003
129653
  }
129004
129654
  return result;
129005
129655
  }
129006
- if (isPlainObject3(result)) {
129656
+ if (isPlainObject4(result)) {
129007
129657
  const summary11 = generateJsonSummary(result);
129008
129658
  return {
129009
129659
  content: [createTextContent(`Result:
@@ -129357,6 +130007,13 @@ function createJsonRpcManager(middleware, sessionId) {
129357
130007
  }
129358
130008
  // node_modules/modality-mcp-kit/dist/util_mcp_proxy.js
129359
130009
  init_dist();
130010
+
130011
+ // node_modules/modality-mcp-kit/dist/utils/oauth-token-store.js
130012
+ import { homedir } from "node:os";
130013
+ import { join as join9 } from "node:path";
130014
+ var DEFAULT_OAUTH_CACHE_DIR = join9(homedir(), ".cache", "counter");
130015
+
130016
+ // node_modules/modality-mcp-kit/dist/util_mcp_proxy.js
129360
130017
  var DEFAULT_TTL_MS = 5 * 60 * 1000;
129361
130018
  var METHOD_TTL_MS = {
129362
130019
  initialize: 30 * 60 * 1000,
@@ -129460,8 +130117,11 @@ var setupStdioToHttpTools = async (client, mcpServer) => {
129460
130117
  // src/mcp-oauth-provider.ts
129461
130118
  import { createHash, randomBytes } from "node:crypto";
129462
130119
  import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
129463
- import { homedir } from "node:os";
129464
- import { join as join9 } from "node:path";
130120
+ import { homedir as homedir2 } from "node:os";
130121
+ import { join as join10 } from "node:path";
130122
+ import { Client as Client2 } from "@modelcontextprotocol/sdk/client/index.js";
130123
+ import { StreamableHTTPClientTransport as StreamableHTTPClientTransport3 } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
130124
+ import { UnauthorizedError } from "@modelcontextprotocol/sdk/client/auth.js";
129465
130125
  var SERVER_IDENTITY_WHITELIST = {
129466
130126
  "figma.com": {
129467
130127
  client_name: "Claude Code",
@@ -129500,9 +130160,9 @@ class CLIBrowserOAuthProvider {
129500
130160
  this._cachePath = null;
129501
130161
  } else {
129502
130162
  const key = options.serverUrl ? urlStorageKey(options.serverUrl) : "default";
129503
- const dir3 = join9(homedir(), ".cache", "counter");
130163
+ const dir3 = join10(homedir2(), ".cache", "counter");
129504
130164
  mkdirSync(dir3, { recursive: true });
129505
- this._cachePath = join9(dir3, `${key}.json`);
130165
+ this._cachePath = join10(dir3, `${key}.json`);
129506
130166
  }
129507
130167
  const saved = this._loadCache();
129508
130168
  this._clientInfo = saved.clientInfo;
@@ -129798,10 +130458,66 @@ function resolveServerIdentity(serverUrl) {
129798
130458
  }
129799
130459
  return null;
129800
130460
  }
130461
+ function createHostedOAuth(options) {
130462
+ const { callbackPath, getPort, host = "127.0.0.1", clientName: clientName2 = "mcp-cli" } = options;
130463
+ const pending6 = new Map;
130464
+ function handleCallback(input2) {
130465
+ const req = input2 instanceof Request ? input2 : input2.req.raw;
130466
+ const state = new URL(req.url).searchParams.get("state");
130467
+ const provider = state ? pending6.get(state) : undefined;
130468
+ if (!provider) {
130469
+ return new Response("No matching OAuth session (state missing or expired).", { status: 400 });
130470
+ }
130471
+ return provider.handleCallback(req);
130472
+ }
130473
+ async function allowAccess(serverUrl, mcpName) {
130474
+ const port3 = await getPort();
130475
+ const provider = new CLIBrowserOAuthProvider({
130476
+ clientName: clientName2,
130477
+ serverUrl,
130478
+ externalCallback: { port: port3, path: callbackPath, host },
130479
+ onAuthorizationUrl: (url5) => {
130480
+ const state = url5.searchParams.get("state");
130481
+ if (state)
130482
+ pending6.set(state, provider);
130483
+ }
130484
+ });
130485
+ try {
130486
+ if (provider.tokens()) {
130487
+ return { status: "already_authorized", message: `${mcpName} already authorized` };
130488
+ }
130489
+ const transport = new StreamableHTTPClientTransport3(new URL(serverUrl), {
130490
+ authProvider: provider
130491
+ });
130492
+ const client = new Client2({ name: clientName2, version: "1.0" }, { capabilities: {} });
130493
+ try {
130494
+ await client.connect(transport);
130495
+ await client.close();
130496
+ return { status: "authorized", message: `${mcpName} connected successfully` };
130497
+ } catch (err) {
130498
+ if (!(err instanceof UnauthorizedError))
130499
+ throw err;
130500
+ const code = await provider.waitForCode();
130501
+ await transport.finishAuth(code);
130502
+ const transport2 = new StreamableHTTPClientTransport3(new URL(serverUrl), {
130503
+ authProvider: provider
130504
+ });
130505
+ await client.connect(transport2);
130506
+ await client.close();
130507
+ return { status: "authorized", message: `${mcpName} OAuth completed` };
130508
+ }
130509
+ } finally {
130510
+ pending6.delete(provider.oauthState);
130511
+ provider.stop();
130512
+ }
130513
+ }
130514
+ return { handleCallback, allowAccess };
130515
+ }
129801
130516
  export {
129802
130517
  setupStdioToHttpTools,
129803
130518
  mergeToolCallsAndResults,
129804
130519
  createStdioClient,
130520
+ createHostedOAuth,
129805
130521
  createAIChat,
129806
130522
  OllamaProvider,
129807
130523
  ModalityClient,