@openrouter/ai-sdk-provider 2.7.0 → 2.8.1

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
@@ -71,7 +71,7 @@ __export(index_exports, {
71
71
  });
72
72
  module.exports = __toCommonJS(index_exports);
73
73
 
74
- // node_modules/.pnpm/@ai-sdk+provider@3.0.0/node_modules/@ai-sdk/provider/dist/index.mjs
74
+ // node_modules/.pnpm/@ai-sdk+provider@3.0.8/node_modules/@ai-sdk/provider/dist/index.mjs
75
75
  var marker = "vercel.ai.error";
76
76
  var symbol = Symbol.for(marker);
77
77
  var _a;
@@ -341,34 +341,61 @@ var symbol13 = Symbol.for(marker13);
341
341
  var _a13;
342
342
  var _b13;
343
343
  var TypeValidationError = class _TypeValidationError extends (_b13 = AISDKError, _a13 = symbol13, _b13) {
344
- constructor({ value, cause }) {
344
+ constructor({
345
+ value,
346
+ cause,
347
+ context
348
+ }) {
349
+ let contextPrefix = "Type validation failed";
350
+ if (context == null ? void 0 : context.field) {
351
+ contextPrefix += ` for ${context.field}`;
352
+ }
353
+ if ((context == null ? void 0 : context.entityName) || (context == null ? void 0 : context.entityId)) {
354
+ contextPrefix += " (";
355
+ const parts = [];
356
+ if (context.entityName) {
357
+ parts.push(context.entityName);
358
+ }
359
+ if (context.entityId) {
360
+ parts.push(`id: "${context.entityId}"`);
361
+ }
362
+ contextPrefix += parts.join(", ");
363
+ contextPrefix += ")";
364
+ }
345
365
  super({
346
366
  name: name12,
347
- message: `Type validation failed: Value: ${JSON.stringify(value)}.
367
+ message: `${contextPrefix}: Value: ${JSON.stringify(value)}.
348
368
  Error message: ${getErrorMessage(cause)}`,
349
369
  cause
350
370
  });
351
371
  this[_a13] = true;
352
372
  this.value = value;
373
+ this.context = context;
353
374
  }
354
375
  static isInstance(error) {
355
376
  return AISDKError.hasMarker(error, marker13);
356
377
  }
357
378
  /**
358
379
  * Wraps an error into a TypeValidationError.
359
- * If the cause is already a TypeValidationError with the same value, it returns the cause.
380
+ * If the cause is already a TypeValidationError with the same value and context, it returns the cause.
360
381
  * Otherwise, it creates a new TypeValidationError.
361
382
  *
362
383
  * @param {Object} params - The parameters for wrapping the error.
363
384
  * @param {unknown} params.value - The value that failed validation.
364
385
  * @param {unknown} params.cause - The original error or cause of the validation failure.
386
+ * @param {TypeValidationContext} params.context - Optional context about what is being validated.
365
387
  * @returns {TypeValidationError} A TypeValidationError instance.
366
388
  */
367
389
  static wrap({
368
390
  value,
369
- cause
391
+ cause,
392
+ context
370
393
  }) {
371
- return _TypeValidationError.isInstance(cause) && cause.value === value ? cause : new _TypeValidationError({ value, cause });
394
+ var _a152, _b152, _c;
395
+ if (_TypeValidationError.isInstance(cause) && cause.value === value && ((_a152 = cause.context) == null ? void 0 : _a152.field) === (context == null ? void 0 : context.field) && ((_b152 = cause.context) == null ? void 0 : _b152.entityName) === (context == null ? void 0 : context.entityName) && ((_c = cause.context) == null ? void 0 : _c.entityId) === (context == null ? void 0 : context.entityId)) {
396
+ return cause;
397
+ }
398
+ return new _TypeValidationError({ value, cause, context });
372
399
  }
373
400
  };
374
401
  var name13 = "AI_UnsupportedFunctionalityError";
@@ -390,7 +417,7 @@ var UnsupportedFunctionalityError = class extends (_b14 = AISDKError, _a14 = sym
390
417
  }
391
418
  };
392
419
 
393
- // node_modules/.pnpm/@ai-sdk+provider-utils@4.0.1_zod@4.3.5/node_modules/@ai-sdk/provider-utils/dist/index.mjs
420
+ // node_modules/.pnpm/@ai-sdk+provider-utils@4.0.23_zod@4.3.5/node_modules/@ai-sdk/provider-utils/dist/index.mjs
394
421
  var z4 = __toESM(require("zod/v4"), 1);
395
422
  var import_v3 = require("zod/v3");
396
423
  var import_v32 = require("zod/v3");
@@ -523,13 +550,41 @@ var EventSourceParserStream = class extends TransformStream {
523
550
  }
524
551
  };
525
552
 
526
- // node_modules/.pnpm/@ai-sdk+provider-utils@4.0.1_zod@4.3.5/node_modules/@ai-sdk/provider-utils/dist/index.mjs
553
+ // node_modules/.pnpm/@ai-sdk+provider-utils@4.0.23_zod@4.3.5/node_modules/@ai-sdk/provider-utils/dist/index.mjs
527
554
  function combineHeaders(...headers) {
528
555
  return headers.reduce(
529
556
  (combinedHeaders, currentHeaders) => __spreadValues(__spreadValues({}, combinedHeaders), currentHeaders != null ? currentHeaders : {}),
530
557
  {}
531
558
  );
532
559
  }
560
+ async function delay(delayInMs, options) {
561
+ if (delayInMs == null) {
562
+ return Promise.resolve();
563
+ }
564
+ const signal = options == null ? void 0 : options.abortSignal;
565
+ return new Promise((resolve2, reject) => {
566
+ if (signal == null ? void 0 : signal.aborted) {
567
+ reject(createAbortError());
568
+ return;
569
+ }
570
+ const timeoutId = setTimeout(() => {
571
+ cleanup();
572
+ resolve2();
573
+ }, delayInMs);
574
+ const cleanup = () => {
575
+ clearTimeout(timeoutId);
576
+ signal == null ? void 0 : signal.removeEventListener("abort", onAbort);
577
+ };
578
+ const onAbort = () => {
579
+ cleanup();
580
+ reject(createAbortError());
581
+ };
582
+ signal == null ? void 0 : signal.addEventListener("abort", onAbort);
583
+ });
584
+ }
585
+ function createAbortError() {
586
+ return new DOMException("Delay was aborted", "AbortError");
587
+ }
533
588
  function extractResponseHeaders(response) {
534
589
  return Object.fromEntries([...response.headers]);
535
590
  }
@@ -564,6 +619,7 @@ var DownloadError = class extends (_b15 = AISDKError, _a15 = symbol15, _b15) {
564
619
  return AISDKError.hasMarker(error, marker15);
565
620
  }
566
621
  };
622
+ var DEFAULT_MAX_DOWNLOAD_SIZE = 2 * 1024 * 1024 * 1024;
567
623
  var createIdGenerator = ({
568
624
  prefix,
569
625
  size = 16,
@@ -595,6 +651,25 @@ function isAbortError(error) {
595
651
  error.name === "TimeoutError");
596
652
  }
597
653
  var FETCH_FAILED_ERROR_MESSAGES = ["fetch failed", "failed to fetch"];
654
+ var BUN_ERROR_CODES = [
655
+ "ConnectionRefused",
656
+ "ConnectionClosed",
657
+ "FailedToOpenSocket",
658
+ "ECONNRESET",
659
+ "ECONNREFUSED",
660
+ "ETIMEDOUT",
661
+ "EPIPE"
662
+ ];
663
+ function isBunNetworkError(error) {
664
+ if (!(error instanceof Error)) {
665
+ return false;
666
+ }
667
+ const code = error.code;
668
+ if (typeof code === "string" && BUN_ERROR_CODES.includes(code)) {
669
+ return true;
670
+ }
671
+ return false;
672
+ }
598
673
  function handleFetchError({
599
674
  error,
600
675
  url,
@@ -616,6 +691,15 @@ function handleFetchError({
616
691
  });
617
692
  }
618
693
  }
694
+ if (isBunNetworkError(error)) {
695
+ return new APICallError({
696
+ message: `Cannot connect to API: ${error.message}`,
697
+ cause: error,
698
+ url,
699
+ requestBodyValues,
700
+ isRetryable: true
701
+ });
702
+ }
619
703
  return error;
620
704
  }
621
705
  function getRuntimeEnvironmentUserAgent(globalThisAny = globalThis) {
@@ -664,7 +748,75 @@ function withUserAgentSuffix(headers, ...userAgentSuffixParts) {
664
748
  );
665
749
  return Object.fromEntries(normalizedHeaders.entries());
666
750
  }
667
- var VERSION = true ? "4.0.1" : "0.0.0-test";
751
+ var VERSION = true ? "4.0.23" : "0.0.0-test";
752
+ var getOriginalFetch = () => globalThis.fetch;
753
+ var getFromApi = async ({
754
+ url,
755
+ headers = {},
756
+ successfulResponseHandler,
757
+ failedResponseHandler,
758
+ abortSignal,
759
+ fetch: fetch2 = getOriginalFetch()
760
+ }) => {
761
+ try {
762
+ const response = await fetch2(url, {
763
+ method: "GET",
764
+ headers: withUserAgentSuffix(
765
+ headers,
766
+ `ai-sdk/provider-utils/${VERSION}`,
767
+ getRuntimeEnvironmentUserAgent()
768
+ ),
769
+ signal: abortSignal
770
+ });
771
+ const responseHeaders = extractResponseHeaders(response);
772
+ if (!response.ok) {
773
+ let errorInformation;
774
+ try {
775
+ errorInformation = await failedResponseHandler({
776
+ response,
777
+ url,
778
+ requestBodyValues: {}
779
+ });
780
+ } catch (error) {
781
+ if (isAbortError(error) || APICallError.isInstance(error)) {
782
+ throw error;
783
+ }
784
+ throw new APICallError({
785
+ message: "Failed to process error response",
786
+ cause: error,
787
+ statusCode: response.status,
788
+ url,
789
+ responseHeaders,
790
+ requestBodyValues: {}
791
+ });
792
+ }
793
+ throw errorInformation.value;
794
+ }
795
+ try {
796
+ return await successfulResponseHandler({
797
+ response,
798
+ url,
799
+ requestBodyValues: {}
800
+ });
801
+ } catch (error) {
802
+ if (error instanceof Error) {
803
+ if (isAbortError(error) || APICallError.isInstance(error)) {
804
+ throw error;
805
+ }
806
+ }
807
+ throw new APICallError({
808
+ message: "Failed to process successful response",
809
+ cause: error,
810
+ statusCode: response.status,
811
+ url,
812
+ responseHeaders,
813
+ requestBodyValues: {}
814
+ });
815
+ }
816
+ } catch (error) {
817
+ throw handleFetchError({ error, url, requestBodyValues: {} });
818
+ }
819
+ };
668
820
  function loadApiKey({
669
821
  apiKey,
670
822
  environmentVariableName,
@@ -681,7 +833,7 @@ function loadApiKey({
681
833
  }
682
834
  if (typeof process === "undefined") {
683
835
  throw new LoadAPIKeyError({
684
- message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter. Environment variables is not supported in this environment.`
836
+ message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter. Environment variables are not supported in this environment.`
685
837
  });
686
838
  }
687
839
  apiKey = process.env[environmentVariableName];
@@ -697,8 +849,8 @@ function loadApiKey({
697
849
  }
698
850
  return apiKey;
699
851
  }
700
- var suspectProtoRx = /"__proto__"\s*:/;
701
- var suspectConstructorRx = /"constructor"\s*:/;
852
+ var suspectProtoRx = /"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/;
853
+ var suspectConstructorRx = /"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;
702
854
  function _parse(text) {
703
855
  const obj = JSON.parse(text);
704
856
  if (obj === null || typeof obj !== "object") {
@@ -718,7 +870,7 @@ function filter(obj) {
718
870
  if (Object.prototype.hasOwnProperty.call(node, "__proto__")) {
719
871
  throw new SyntaxError("Object contains forbidden prototype property");
720
872
  }
721
- if (Object.prototype.hasOwnProperty.call(node, "constructor") && Object.prototype.hasOwnProperty.call(node.constructor, "prototype")) {
873
+ if (Object.prototype.hasOwnProperty.call(node, "constructor") && node.constructor !== null && typeof node.constructor === "object" && Object.prototype.hasOwnProperty.call(node.constructor, "prototype")) {
722
874
  throw new SyntaxError("Object contains forbidden prototype property");
723
875
  }
724
876
  for (const key in node) {
@@ -745,31 +897,40 @@ function secureJsonParse(text) {
745
897
  }
746
898
  }
747
899
  function addAdditionalPropertiesToJsonSchema(jsonSchema2) {
748
- if (jsonSchema2.type === "object") {
900
+ if (jsonSchema2.type === "object" || Array.isArray(jsonSchema2.type) && jsonSchema2.type.includes("object")) {
749
901
  jsonSchema2.additionalProperties = false;
750
- const properties = jsonSchema2.properties;
902
+ const { properties } = jsonSchema2;
751
903
  if (properties != null) {
752
- for (const property in properties) {
753
- properties[property] = addAdditionalPropertiesToJsonSchema(
754
- properties[property]
755
- );
904
+ for (const key of Object.keys(properties)) {
905
+ properties[key] = visit(properties[key]);
756
906
  }
757
907
  }
758
908
  }
759
- if (jsonSchema2.type === "array" && jsonSchema2.items != null) {
760
- if (Array.isArray(jsonSchema2.items)) {
761
- jsonSchema2.items = jsonSchema2.items.map(
762
- (item) => addAdditionalPropertiesToJsonSchema(item)
763
- );
764
- } else {
765
- jsonSchema2.items = addAdditionalPropertiesToJsonSchema(
766
- jsonSchema2.items
767
- );
909
+ if (jsonSchema2.items != null) {
910
+ jsonSchema2.items = Array.isArray(jsonSchema2.items) ? jsonSchema2.items.map(visit) : visit(jsonSchema2.items);
911
+ }
912
+ if (jsonSchema2.anyOf != null) {
913
+ jsonSchema2.anyOf = jsonSchema2.anyOf.map(visit);
914
+ }
915
+ if (jsonSchema2.allOf != null) {
916
+ jsonSchema2.allOf = jsonSchema2.allOf.map(visit);
917
+ }
918
+ if (jsonSchema2.oneOf != null) {
919
+ jsonSchema2.oneOf = jsonSchema2.oneOf.map(visit);
920
+ }
921
+ const { definitions } = jsonSchema2;
922
+ if (definitions != null) {
923
+ for (const key of Object.keys(definitions)) {
924
+ definitions[key] = visit(definitions[key]);
768
925
  }
769
926
  }
770
927
  return jsonSchema2;
771
928
  }
772
- var ignoreOverride = Symbol(
929
+ function visit(def) {
930
+ if (typeof def === "boolean") return def;
931
+ return addAdditionalPropertiesToJsonSchema(def);
932
+ }
933
+ var ignoreOverride = /* @__PURE__ */ Symbol(
773
934
  "Let zodToJsonSchema decide on which parser to use"
774
935
  );
775
936
  var defaultOptions = {
@@ -1835,7 +1996,7 @@ var zod3ToJsonSchema = (schema, options) => {
1835
1996
  combined.$schema = "http://json-schema.org/draft-07/schema#";
1836
1997
  return combined;
1837
1998
  };
1838
- var schemaSymbol = Symbol.for("vercel.ai.schema");
1999
+ var schemaSymbol = /* @__PURE__ */ Symbol.for("vercel.ai.schema");
1839
2000
  function jsonSchema(jsonSchema2, {
1840
2001
  validate
1841
2002
  } = {}) {
@@ -1860,9 +2021,11 @@ function asSchema(schema) {
1860
2021
  }
1861
2022
  function standardSchema(standardSchema2) {
1862
2023
  return jsonSchema(
1863
- () => standardSchema2["~standard"].jsonSchema.input({
1864
- target: "draft-07"
1865
- }),
2024
+ () => addAdditionalPropertiesToJsonSchema(
2025
+ standardSchema2["~standard"].jsonSchema.input({
2026
+ target: "draft-07"
2027
+ })
2028
+ ),
1866
2029
  {
1867
2030
  validate: async (value) => {
1868
2031
  const result = await standardSchema2["~standard"].validate(value);
@@ -1925,17 +2088,19 @@ function zodSchema(zodSchema2, options) {
1925
2088
  }
1926
2089
  async function validateTypes({
1927
2090
  value,
1928
- schema
2091
+ schema,
2092
+ context
1929
2093
  }) {
1930
- const result = await safeValidateTypes({ value, schema });
2094
+ const result = await safeValidateTypes({ value, schema, context });
1931
2095
  if (!result.success) {
1932
- throw TypeValidationError.wrap({ value, cause: result.error });
2096
+ throw TypeValidationError.wrap({ value, cause: result.error, context });
1933
2097
  }
1934
2098
  return result.value;
1935
2099
  }
1936
2100
  async function safeValidateTypes({
1937
2101
  value,
1938
- schema
2102
+ schema,
2103
+ context
1939
2104
  }) {
1940
2105
  const actualSchema = asSchema(schema);
1941
2106
  try {
@@ -1948,13 +2113,13 @@ async function safeValidateTypes({
1948
2113
  }
1949
2114
  return {
1950
2115
  success: false,
1951
- error: TypeValidationError.wrap({ value, cause: result.error }),
2116
+ error: TypeValidationError.wrap({ value, cause: result.error, context }),
1952
2117
  rawValue: value
1953
2118
  };
1954
2119
  } catch (error) {
1955
2120
  return {
1956
2121
  success: false,
1957
- error: TypeValidationError.wrap({ value, cause: error }),
2122
+ error: TypeValidationError.wrap({ value, cause: error, context }),
1958
2123
  rawValue: value
1959
2124
  };
1960
2125
  }
@@ -2888,9 +3053,9 @@ function convertToOpenRouterChatMessages(prompt) {
2888
3053
  const parsedProviderOptions = OpenRouterProviderOptionsSchema.safeParse(providerOptions);
2889
3054
  const messageReasoningDetails = parsedProviderOptions.success ? (_e = (_d = parsedProviderOptions.data) == null ? void 0 : _d.openrouter) == null ? void 0 : _e.reasoning_details : void 0;
2890
3055
  const messageAnnotations = parsedProviderOptions.success ? (_g = (_f = parsedProviderOptions.data) == null ? void 0 : _f.openrouter) == null ? void 0 : _g.annotations : void 0;
2891
- const candidateReasoningDetails = messageReasoningDetails && Array.isArray(messageReasoningDetails) && messageReasoningDetails.length > 0 ? messageReasoningDetails : findFirstReasoningDetails(content);
3056
+ const candidateReasoningDetails = messageReasoningDetails && Array.isArray(messageReasoningDetails) ? messageReasoningDetails : findFirstReasoningDetails(content);
2892
3057
  let finalReasoningDetails;
2893
- if (candidateReasoningDetails && candidateReasoningDetails.length > 0) {
3058
+ if (candidateReasoningDetails) {
2894
3059
  const validDetails = candidateReasoningDetails.filter((detail) => {
2895
3060
  var _a17;
2896
3061
  if (detail.type !== "reasoning.text" /* Text */) {
@@ -2916,9 +3081,9 @@ function convertToOpenRouterChatMessages(prompt) {
2916
3081
  uniqueDetails.push(detail);
2917
3082
  }
2918
3083
  }
2919
- finalReasoningDetails = uniqueDetails.length > 0 ? uniqueDetails : void 0;
3084
+ finalReasoningDetails = uniqueDetails;
2920
3085
  }
2921
- const effectiveReasoning = reasoning && finalReasoningDetails ? reasoning : void 0;
3086
+ const effectiveReasoning = reasoning && finalReasoningDetails && finalReasoningDetails.length > 0 ? reasoning : void 0;
2922
3087
  messages.push({
2923
3088
  role: "assistant",
2924
3089
  content: text,
@@ -3845,15 +4010,17 @@ var OpenRouterChatLanguageModel = class {
3845
4010
  controller.enqueue({
3846
4011
  type: "reasoning-end",
3847
4012
  id: reasoningId || generateId(),
3848
- // Include accumulated reasoning_details so the AI SDK can update
3849
- // the reasoning part's providerMetadata with the correct signature.
3850
- // The signature typically arrives in the last reasoning delta,
4013
+ // Always include accumulated reasoning_details so the AI SDK can
4014
+ // update the reasoning part's providerMetadata with the correct
4015
+ // signature. The signature typically arrives in the last delta,
3851
4016
  // but reasoning-start only carries the first delta's metadata.
3852
- providerMetadata: accumulatedReasoningDetails.length > 0 ? {
4017
+ // An empty array is intentional — it signals the provider produced
4018
+ // no reasoning tokens this turn (e.g. DeepSeek V4).
4019
+ providerMetadata: {
3853
4020
  openrouter: {
3854
4021
  reasoning_details: accumulatedReasoningDetails
3855
4022
  }
3856
- } : void 0
4023
+ }
3857
4024
  });
3858
4025
  reasoningStarted = false;
3859
4026
  }
@@ -4088,13 +4255,14 @@ var OpenRouterChatLanguageModel = class {
4088
4255
  controller.enqueue({
4089
4256
  type: "reasoning-end",
4090
4257
  id: reasoningId || generateId(),
4091
- // Include accumulated reasoning_details so the AI SDK can update
4092
- // the reasoning part's providerMetadata with the correct signature.
4093
- providerMetadata: accumulatedReasoningDetails.length > 0 ? {
4258
+ // Always include accumulated reasoning_details so the AI SDK can
4259
+ // update the reasoning part's providerMetadata. An empty array is
4260
+ // intentional it signals the provider produced no reasoning tokens.
4261
+ providerMetadata: {
4094
4262
  openrouter: {
4095
4263
  reasoning_details: accumulatedReasoningDetails
4096
4264
  }
4097
- } : void 0
4265
+ }
4098
4266
  });
4099
4267
  }
4100
4268
  if (textStarted) {
@@ -4109,9 +4277,7 @@ var OpenRouterChatLanguageModel = class {
4109
4277
  if (provider !== void 0) {
4110
4278
  openrouterMetadata.provider = provider;
4111
4279
  }
4112
- if (accumulatedReasoningDetails.length > 0) {
4113
- openrouterMetadata.reasoning_details = accumulatedReasoningDetails;
4114
- }
4280
+ openrouterMetadata.reasoning_details = accumulatedReasoningDetails;
4115
4281
  if (accumulatedFileAnnotations.length > 0) {
4116
4282
  openrouterMetadata.annotations = accumulatedFileAnnotations;
4117
4283
  }
@@ -4935,7 +5101,199 @@ function withUserAgentSuffix2(headers, ...userAgentSuffixParts) {
4935
5101
  }
4936
5102
 
4937
5103
  // src/version.ts
4938
- var VERSION2 = false ? "0.0.0-test" : "2.7.0";
5104
+ var VERSION2 = false ? "0.0.0-test" : "2.8.1";
5105
+
5106
+ // src/video/schemas.ts
5107
+ var import_v411 = require("zod/v4");
5108
+ var VideoGenerationSubmitResponseSchema = import_v411.z.object({
5109
+ id: import_v411.z.string(),
5110
+ generation_id: import_v411.z.string().optional(),
5111
+ polling_url: import_v411.z.string(),
5112
+ status: import_v411.z.string()
5113
+ }).passthrough();
5114
+ var VideoGenerationPollResponseSchema = import_v411.z.object({
5115
+ id: import_v411.z.string(),
5116
+ generation_id: import_v411.z.string().optional(),
5117
+ polling_url: import_v411.z.string(),
5118
+ status: import_v411.z.string(),
5119
+ unsigned_urls: import_v411.z.array(import_v411.z.string()).optional(),
5120
+ usage: import_v411.z.object({
5121
+ cost: import_v411.z.number().optional(),
5122
+ is_byok: import_v411.z.boolean().optional()
5123
+ }).passthrough().optional(),
5124
+ error: import_v411.z.string().optional()
5125
+ }).passthrough();
5126
+
5127
+ // src/video/index.ts
5128
+ var DEFAULT_POLL_INTERVAL_MS = 2e3;
5129
+ var DEFAULT_MAX_POLL_TIME_MS = 6e5;
5130
+ var OpenRouterVideoModel = class {
5131
+ constructor(modelId, settings, config) {
5132
+ this.specificationVersion = "v3";
5133
+ this.provider = "openrouter";
5134
+ this.maxVideosPerCall = 1;
5135
+ this.modelId = modelId;
5136
+ this.settings = settings;
5137
+ this.config = config;
5138
+ }
5139
+ async doGenerate(options) {
5140
+ var _a16, _b16, _c, _d, _e;
5141
+ const {
5142
+ prompt,
5143
+ n,
5144
+ aspectRatio,
5145
+ resolution,
5146
+ duration,
5147
+ seed,
5148
+ image,
5149
+ abortSignal,
5150
+ headers,
5151
+ providerOptions
5152
+ } = options;
5153
+ const warnings = [];
5154
+ if (n > 1) {
5155
+ warnings.push({
5156
+ type: "unsupported",
5157
+ feature: "n > 1",
5158
+ details: `OpenRouter video generation returns 1 video per call. Requested ${n} videos.`
5159
+ });
5160
+ }
5161
+ const body = __spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues({
5162
+ model: this.modelId,
5163
+ prompt: prompt != null ? prompt : ""
5164
+ }, aspectRatio !== void 0 && { aspect_ratio: aspectRatio }), resolution !== void 0 && { size: resolution }), duration !== void 0 && { duration }), seed !== void 0 && { seed }), this.settings.generateAudio !== void 0 && {
5165
+ generate_audio: this.settings.generateAudio
5166
+ }), image !== void 0 && {
5167
+ frame_images: [convertImageToFrameImage(image)]
5168
+ }), this.config.extraBody), this.settings.extraBody), providerOptions.openrouter);
5169
+ const mergedHeaders = combineHeaders(this.config.headers(), headers);
5170
+ const { value: submitResponse, responseHeaders } = await postJsonToApi({
5171
+ url: this.config.url({
5172
+ path: "/videos",
5173
+ modelId: this.modelId
5174
+ }),
5175
+ headers: mergedHeaders,
5176
+ body,
5177
+ failedResponseHandler: openrouterFailedResponseHandler,
5178
+ successfulResponseHandler: createJsonResponseHandler(
5179
+ VideoGenerationSubmitResponseSchema
5180
+ ),
5181
+ abortSignal,
5182
+ fetch: this.config.fetch
5183
+ });
5184
+ const pollIntervalMs = (_a16 = this.settings.pollIntervalMs) != null ? _a16 : DEFAULT_POLL_INTERVAL_MS;
5185
+ const maxPollTimeMs = (_b16 = this.settings.maxPollTimeMs) != null ? _b16 : DEFAULT_MAX_POLL_TIME_MS;
5186
+ const pollResult = await this.pollUntilComplete({
5187
+ jobId: submitResponse.id,
5188
+ headers: mergedHeaders,
5189
+ abortSignal,
5190
+ pollIntervalMs,
5191
+ maxPollTimeMs
5192
+ });
5193
+ const videos = [];
5194
+ if (pollResult.unsigned_urls) {
5195
+ for (const url of pollResult.unsigned_urls) {
5196
+ videos.push({
5197
+ type: "url",
5198
+ url,
5199
+ mediaType: "video/mp4"
5200
+ });
5201
+ }
5202
+ }
5203
+ const providerMetadata = {
5204
+ openrouter: {
5205
+ generationId: (_c = pollResult.generation_id) != null ? _c : null,
5206
+ cost: (_e = (_d = pollResult.usage) == null ? void 0 : _d.cost) != null ? _e : null
5207
+ }
5208
+ };
5209
+ return {
5210
+ videos,
5211
+ warnings,
5212
+ providerMetadata,
5213
+ response: {
5214
+ timestamp: /* @__PURE__ */ new Date(),
5215
+ modelId: this.modelId,
5216
+ headers: responseHeaders
5217
+ }
5218
+ };
5219
+ }
5220
+ async pollUntilComplete({
5221
+ jobId,
5222
+ headers,
5223
+ abortSignal,
5224
+ pollIntervalMs,
5225
+ maxPollTimeMs
5226
+ }) {
5227
+ var _a16;
5228
+ const startTime = Date.now();
5229
+ while (Date.now() - startTime < maxPollTimeMs) {
5230
+ abortSignal == null ? void 0 : abortSignal.throwIfAborted();
5231
+ await delay(pollIntervalMs);
5232
+ abortSignal == null ? void 0 : abortSignal.throwIfAborted();
5233
+ const { value: pollResponse } = await getFromApi({
5234
+ url: this.config.url({
5235
+ path: `/videos/${jobId}`,
5236
+ modelId: this.modelId
5237
+ }),
5238
+ headers,
5239
+ failedResponseHandler: openrouterFailedResponseHandler,
5240
+ successfulResponseHandler: createJsonResponseHandler(
5241
+ VideoGenerationPollResponseSchema
5242
+ ),
5243
+ abortSignal,
5244
+ fetch: this.config.fetch
5245
+ });
5246
+ if (pollResponse.status === "completed") {
5247
+ return {
5248
+ generation_id: pollResponse.generation_id,
5249
+ unsigned_urls: pollResponse.unsigned_urls,
5250
+ usage: pollResponse.usage
5251
+ };
5252
+ }
5253
+ if (pollResponse.status === "failed" || pollResponse.status === "dead" || pollResponse.status === "cancelled" || pollResponse.status === "expired") {
5254
+ throw new APICallError({
5255
+ message: (_a16 = pollResponse.error) != null ? _a16 : `Video generation failed with status: ${pollResponse.status}`,
5256
+ url: this.config.url({
5257
+ path: `/videos/${jobId}`,
5258
+ modelId: this.modelId
5259
+ }),
5260
+ requestBodyValues: {},
5261
+ statusCode: 500,
5262
+ isRetryable: false
5263
+ });
5264
+ }
5265
+ }
5266
+ throw new APICallError({
5267
+ message: `Video generation timed out after ${maxPollTimeMs}ms`,
5268
+ url: this.config.url({
5269
+ path: `/videos/${jobId}`,
5270
+ modelId: this.modelId
5271
+ }),
5272
+ requestBodyValues: {},
5273
+ statusCode: 408,
5274
+ isRetryable: true
5275
+ });
5276
+ }
5277
+ };
5278
+ function convertImageToFrameImage(file) {
5279
+ if (file.type === "url") {
5280
+ return {
5281
+ type: "image_url",
5282
+ image_url: { url: file.url },
5283
+ frame_type: "first_frame"
5284
+ };
5285
+ }
5286
+ const url = buildFileDataUrl({
5287
+ data: file.data,
5288
+ mediaType: file.mediaType,
5289
+ defaultMediaType: "image/png"
5290
+ });
5291
+ return {
5292
+ type: "image_url",
5293
+ image_url: { url },
5294
+ frame_type: "first_frame"
5295
+ };
5296
+ }
4939
5297
 
4940
5298
  // src/provider.ts
4941
5299
  function createOpenRouter(options = {}) {
@@ -4984,6 +5342,13 @@ function createOpenRouter(options = {}) {
4984
5342
  fetch: options.fetch,
4985
5343
  extraBody: options.extraBody
4986
5344
  });
5345
+ const createVideoModel = (modelId, settings = {}) => new OpenRouterVideoModel(modelId, settings, {
5346
+ provider: "openrouter.video",
5347
+ url: ({ path }) => `${baseURL}${path}`,
5348
+ headers: getHeaders,
5349
+ fetch: options.fetch,
5350
+ extraBody: options.extraBody
5351
+ });
4987
5352
  const createLanguageModel = (modelId, settings) => {
4988
5353
  if (new.target) {
4989
5354
  throw new Error(
@@ -5005,6 +5370,7 @@ function createOpenRouter(options = {}) {
5005
5370
  provider.textEmbeddingModel = createEmbeddingModel;
5006
5371
  provider.embedding = createEmbeddingModel;
5007
5372
  provider.imageModel = createImageModel;
5373
+ provider.videoModel = createVideoModel;
5008
5374
  provider.tools = {
5009
5375
  webSearch
5010
5376
  };