@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.
@@ -36,7 +36,7 @@ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot
36
36
  var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
37
37
  var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
38
38
 
39
- // node_modules/.pnpm/@ai-sdk+provider@3.0.0/node_modules/@ai-sdk/provider/dist/index.mjs
39
+ // node_modules/.pnpm/@ai-sdk+provider@3.0.8/node_modules/@ai-sdk/provider/dist/index.mjs
40
40
  var marker = "vercel.ai.error";
41
41
  var symbol = Symbol.for(marker);
42
42
  var _a;
@@ -306,34 +306,61 @@ var symbol13 = Symbol.for(marker13);
306
306
  var _a13;
307
307
  var _b13;
308
308
  var TypeValidationError = class _TypeValidationError extends (_b13 = AISDKError, _a13 = symbol13, _b13) {
309
- constructor({ value, cause }) {
309
+ constructor({
310
+ value,
311
+ cause,
312
+ context
313
+ }) {
314
+ let contextPrefix = "Type validation failed";
315
+ if (context == null ? void 0 : context.field) {
316
+ contextPrefix += ` for ${context.field}`;
317
+ }
318
+ if ((context == null ? void 0 : context.entityName) || (context == null ? void 0 : context.entityId)) {
319
+ contextPrefix += " (";
320
+ const parts = [];
321
+ if (context.entityName) {
322
+ parts.push(context.entityName);
323
+ }
324
+ if (context.entityId) {
325
+ parts.push(`id: "${context.entityId}"`);
326
+ }
327
+ contextPrefix += parts.join(", ");
328
+ contextPrefix += ")";
329
+ }
310
330
  super({
311
331
  name: name12,
312
- message: `Type validation failed: Value: ${JSON.stringify(value)}.
332
+ message: `${contextPrefix}: Value: ${JSON.stringify(value)}.
313
333
  Error message: ${getErrorMessage(cause)}`,
314
334
  cause
315
335
  });
316
336
  this[_a13] = true;
317
337
  this.value = value;
338
+ this.context = context;
318
339
  }
319
340
  static isInstance(error) {
320
341
  return AISDKError.hasMarker(error, marker13);
321
342
  }
322
343
  /**
323
344
  * Wraps an error into a TypeValidationError.
324
- * If the cause is already a TypeValidationError with the same value, it returns the cause.
345
+ * If the cause is already a TypeValidationError with the same value and context, it returns the cause.
325
346
  * Otherwise, it creates a new TypeValidationError.
326
347
  *
327
348
  * @param {Object} params - The parameters for wrapping the error.
328
349
  * @param {unknown} params.value - The value that failed validation.
329
350
  * @param {unknown} params.cause - The original error or cause of the validation failure.
351
+ * @param {TypeValidationContext} params.context - Optional context about what is being validated.
330
352
  * @returns {TypeValidationError} A TypeValidationError instance.
331
353
  */
332
354
  static wrap({
333
355
  value,
334
- cause
356
+ cause,
357
+ context
335
358
  }) {
336
- return _TypeValidationError.isInstance(cause) && cause.value === value ? cause : new _TypeValidationError({ value, cause });
359
+ var _a152, _b152, _c;
360
+ 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)) {
361
+ return cause;
362
+ }
363
+ return new _TypeValidationError({ value, cause, context });
337
364
  }
338
365
  };
339
366
  var name13 = "AI_UnsupportedFunctionalityError";
@@ -355,7 +382,7 @@ var UnsupportedFunctionalityError = class extends (_b14 = AISDKError, _a14 = sym
355
382
  }
356
383
  };
357
384
 
358
- // node_modules/.pnpm/@ai-sdk+provider-utils@4.0.1_zod@4.3.5/node_modules/@ai-sdk/provider-utils/dist/index.mjs
385
+ // node_modules/.pnpm/@ai-sdk+provider-utils@4.0.23_zod@4.3.5/node_modules/@ai-sdk/provider-utils/dist/index.mjs
359
386
  import * as z4 from "zod/v4";
360
387
  import { ZodFirstPartyTypeKind as ZodFirstPartyTypeKind3 } from "zod/v3";
361
388
  import { ZodFirstPartyTypeKind } from "zod/v3";
@@ -490,13 +517,41 @@ var EventSourceParserStream = class extends TransformStream {
490
517
  }
491
518
  };
492
519
 
493
- // node_modules/.pnpm/@ai-sdk+provider-utils@4.0.1_zod@4.3.5/node_modules/@ai-sdk/provider-utils/dist/index.mjs
520
+ // node_modules/.pnpm/@ai-sdk+provider-utils@4.0.23_zod@4.3.5/node_modules/@ai-sdk/provider-utils/dist/index.mjs
494
521
  function combineHeaders(...headers) {
495
522
  return headers.reduce(
496
523
  (combinedHeaders, currentHeaders) => __spreadValues(__spreadValues({}, combinedHeaders), currentHeaders != null ? currentHeaders : {}),
497
524
  {}
498
525
  );
499
526
  }
527
+ async function delay(delayInMs, options) {
528
+ if (delayInMs == null) {
529
+ return Promise.resolve();
530
+ }
531
+ const signal = options == null ? void 0 : options.abortSignal;
532
+ return new Promise((resolve2, reject) => {
533
+ if (signal == null ? void 0 : signal.aborted) {
534
+ reject(createAbortError());
535
+ return;
536
+ }
537
+ const timeoutId = setTimeout(() => {
538
+ cleanup();
539
+ resolve2();
540
+ }, delayInMs);
541
+ const cleanup = () => {
542
+ clearTimeout(timeoutId);
543
+ signal == null ? void 0 : signal.removeEventListener("abort", onAbort);
544
+ };
545
+ const onAbort = () => {
546
+ cleanup();
547
+ reject(createAbortError());
548
+ };
549
+ signal == null ? void 0 : signal.addEventListener("abort", onAbort);
550
+ });
551
+ }
552
+ function createAbortError() {
553
+ return new DOMException("Delay was aborted", "AbortError");
554
+ }
500
555
  function extractResponseHeaders(response) {
501
556
  return Object.fromEntries([...response.headers]);
502
557
  }
@@ -531,6 +586,7 @@ var DownloadError = class extends (_b15 = AISDKError, _a15 = symbol15, _b15) {
531
586
  return AISDKError.hasMarker(error, marker15);
532
587
  }
533
588
  };
589
+ var DEFAULT_MAX_DOWNLOAD_SIZE = 2 * 1024 * 1024 * 1024;
534
590
  var createIdGenerator = ({
535
591
  prefix,
536
592
  size = 16,
@@ -562,6 +618,25 @@ function isAbortError(error) {
562
618
  error.name === "TimeoutError");
563
619
  }
564
620
  var FETCH_FAILED_ERROR_MESSAGES = ["fetch failed", "failed to fetch"];
621
+ var BUN_ERROR_CODES = [
622
+ "ConnectionRefused",
623
+ "ConnectionClosed",
624
+ "FailedToOpenSocket",
625
+ "ECONNRESET",
626
+ "ECONNREFUSED",
627
+ "ETIMEDOUT",
628
+ "EPIPE"
629
+ ];
630
+ function isBunNetworkError(error) {
631
+ if (!(error instanceof Error)) {
632
+ return false;
633
+ }
634
+ const code = error.code;
635
+ if (typeof code === "string" && BUN_ERROR_CODES.includes(code)) {
636
+ return true;
637
+ }
638
+ return false;
639
+ }
565
640
  function handleFetchError({
566
641
  error,
567
642
  url,
@@ -583,6 +658,15 @@ function handleFetchError({
583
658
  });
584
659
  }
585
660
  }
661
+ if (isBunNetworkError(error)) {
662
+ return new APICallError({
663
+ message: `Cannot connect to API: ${error.message}`,
664
+ cause: error,
665
+ url,
666
+ requestBodyValues,
667
+ isRetryable: true
668
+ });
669
+ }
586
670
  return error;
587
671
  }
588
672
  function getRuntimeEnvironmentUserAgent(globalThisAny = globalThis) {
@@ -631,9 +715,77 @@ function withUserAgentSuffix(headers, ...userAgentSuffixParts) {
631
715
  );
632
716
  return Object.fromEntries(normalizedHeaders.entries());
633
717
  }
634
- var VERSION = true ? "4.0.1" : "0.0.0-test";
635
- var suspectProtoRx = /"__proto__"\s*:/;
636
- var suspectConstructorRx = /"constructor"\s*:/;
718
+ var VERSION = true ? "4.0.23" : "0.0.0-test";
719
+ var getOriginalFetch = () => globalThis.fetch;
720
+ var getFromApi = async ({
721
+ url,
722
+ headers = {},
723
+ successfulResponseHandler,
724
+ failedResponseHandler,
725
+ abortSignal,
726
+ fetch: fetch2 = getOriginalFetch()
727
+ }) => {
728
+ try {
729
+ const response = await fetch2(url, {
730
+ method: "GET",
731
+ headers: withUserAgentSuffix(
732
+ headers,
733
+ `ai-sdk/provider-utils/${VERSION}`,
734
+ getRuntimeEnvironmentUserAgent()
735
+ ),
736
+ signal: abortSignal
737
+ });
738
+ const responseHeaders = extractResponseHeaders(response);
739
+ if (!response.ok) {
740
+ let errorInformation;
741
+ try {
742
+ errorInformation = await failedResponseHandler({
743
+ response,
744
+ url,
745
+ requestBodyValues: {}
746
+ });
747
+ } catch (error) {
748
+ if (isAbortError(error) || APICallError.isInstance(error)) {
749
+ throw error;
750
+ }
751
+ throw new APICallError({
752
+ message: "Failed to process error response",
753
+ cause: error,
754
+ statusCode: response.status,
755
+ url,
756
+ responseHeaders,
757
+ requestBodyValues: {}
758
+ });
759
+ }
760
+ throw errorInformation.value;
761
+ }
762
+ try {
763
+ return await successfulResponseHandler({
764
+ response,
765
+ url,
766
+ requestBodyValues: {}
767
+ });
768
+ } catch (error) {
769
+ if (error instanceof Error) {
770
+ if (isAbortError(error) || APICallError.isInstance(error)) {
771
+ throw error;
772
+ }
773
+ }
774
+ throw new APICallError({
775
+ message: "Failed to process successful response",
776
+ cause: error,
777
+ statusCode: response.status,
778
+ url,
779
+ responseHeaders,
780
+ requestBodyValues: {}
781
+ });
782
+ }
783
+ } catch (error) {
784
+ throw handleFetchError({ error, url, requestBodyValues: {} });
785
+ }
786
+ };
787
+ var suspectProtoRx = /"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/;
788
+ 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*:/;
637
789
  function _parse(text) {
638
790
  const obj = JSON.parse(text);
639
791
  if (obj === null || typeof obj !== "object") {
@@ -653,7 +805,7 @@ function filter(obj) {
653
805
  if (Object.prototype.hasOwnProperty.call(node, "__proto__")) {
654
806
  throw new SyntaxError("Object contains forbidden prototype property");
655
807
  }
656
- if (Object.prototype.hasOwnProperty.call(node, "constructor") && Object.prototype.hasOwnProperty.call(node.constructor, "prototype")) {
808
+ if (Object.prototype.hasOwnProperty.call(node, "constructor") && node.constructor !== null && typeof node.constructor === "object" && Object.prototype.hasOwnProperty.call(node.constructor, "prototype")) {
657
809
  throw new SyntaxError("Object contains forbidden prototype property");
658
810
  }
659
811
  for (const key in node) {
@@ -680,31 +832,40 @@ function secureJsonParse(text) {
680
832
  }
681
833
  }
682
834
  function addAdditionalPropertiesToJsonSchema(jsonSchema2) {
683
- if (jsonSchema2.type === "object") {
835
+ if (jsonSchema2.type === "object" || Array.isArray(jsonSchema2.type) && jsonSchema2.type.includes("object")) {
684
836
  jsonSchema2.additionalProperties = false;
685
- const properties = jsonSchema2.properties;
837
+ const { properties } = jsonSchema2;
686
838
  if (properties != null) {
687
- for (const property in properties) {
688
- properties[property] = addAdditionalPropertiesToJsonSchema(
689
- properties[property]
690
- );
839
+ for (const key of Object.keys(properties)) {
840
+ properties[key] = visit(properties[key]);
691
841
  }
692
842
  }
693
843
  }
694
- if (jsonSchema2.type === "array" && jsonSchema2.items != null) {
695
- if (Array.isArray(jsonSchema2.items)) {
696
- jsonSchema2.items = jsonSchema2.items.map(
697
- (item) => addAdditionalPropertiesToJsonSchema(item)
698
- );
699
- } else {
700
- jsonSchema2.items = addAdditionalPropertiesToJsonSchema(
701
- jsonSchema2.items
702
- );
844
+ if (jsonSchema2.items != null) {
845
+ jsonSchema2.items = Array.isArray(jsonSchema2.items) ? jsonSchema2.items.map(visit) : visit(jsonSchema2.items);
846
+ }
847
+ if (jsonSchema2.anyOf != null) {
848
+ jsonSchema2.anyOf = jsonSchema2.anyOf.map(visit);
849
+ }
850
+ if (jsonSchema2.allOf != null) {
851
+ jsonSchema2.allOf = jsonSchema2.allOf.map(visit);
852
+ }
853
+ if (jsonSchema2.oneOf != null) {
854
+ jsonSchema2.oneOf = jsonSchema2.oneOf.map(visit);
855
+ }
856
+ const { definitions } = jsonSchema2;
857
+ if (definitions != null) {
858
+ for (const key of Object.keys(definitions)) {
859
+ definitions[key] = visit(definitions[key]);
703
860
  }
704
861
  }
705
862
  return jsonSchema2;
706
863
  }
707
- var ignoreOverride = Symbol(
864
+ function visit(def) {
865
+ if (typeof def === "boolean") return def;
866
+ return addAdditionalPropertiesToJsonSchema(def);
867
+ }
868
+ var ignoreOverride = /* @__PURE__ */ Symbol(
708
869
  "Let zodToJsonSchema decide on which parser to use"
709
870
  );
710
871
  var defaultOptions = {
@@ -1770,7 +1931,7 @@ var zod3ToJsonSchema = (schema, options) => {
1770
1931
  combined.$schema = "http://json-schema.org/draft-07/schema#";
1771
1932
  return combined;
1772
1933
  };
1773
- var schemaSymbol = Symbol.for("vercel.ai.schema");
1934
+ var schemaSymbol = /* @__PURE__ */ Symbol.for("vercel.ai.schema");
1774
1935
  function jsonSchema(jsonSchema2, {
1775
1936
  validate
1776
1937
  } = {}) {
@@ -1795,9 +1956,11 @@ function asSchema(schema) {
1795
1956
  }
1796
1957
  function standardSchema(standardSchema2) {
1797
1958
  return jsonSchema(
1798
- () => standardSchema2["~standard"].jsonSchema.input({
1799
- target: "draft-07"
1800
- }),
1959
+ () => addAdditionalPropertiesToJsonSchema(
1960
+ standardSchema2["~standard"].jsonSchema.input({
1961
+ target: "draft-07"
1962
+ })
1963
+ ),
1801
1964
  {
1802
1965
  validate: async (value) => {
1803
1966
  const result = await standardSchema2["~standard"].validate(value);
@@ -1860,17 +2023,19 @@ function zodSchema(zodSchema2, options) {
1860
2023
  }
1861
2024
  async function validateTypes({
1862
2025
  value,
1863
- schema
2026
+ schema,
2027
+ context
1864
2028
  }) {
1865
- const result = await safeValidateTypes({ value, schema });
2029
+ const result = await safeValidateTypes({ value, schema, context });
1866
2030
  if (!result.success) {
1867
- throw TypeValidationError.wrap({ value, cause: result.error });
2031
+ throw TypeValidationError.wrap({ value, cause: result.error, context });
1868
2032
  }
1869
2033
  return result.value;
1870
2034
  }
1871
2035
  async function safeValidateTypes({
1872
2036
  value,
1873
- schema
2037
+ schema,
2038
+ context
1874
2039
  }) {
1875
2040
  const actualSchema = asSchema(schema);
1876
2041
  try {
@@ -1883,13 +2048,13 @@ async function safeValidateTypes({
1883
2048
  }
1884
2049
  return {
1885
2050
  success: false,
1886
- error: TypeValidationError.wrap({ value, cause: result.error }),
2051
+ error: TypeValidationError.wrap({ value, cause: result.error, context }),
1887
2052
  rawValue: value
1888
2053
  };
1889
2054
  } catch (error) {
1890
2055
  return {
1891
2056
  success: false,
1892
- error: TypeValidationError.wrap({ value, cause: error }),
2057
+ error: TypeValidationError.wrap({ value, cause: error, context }),
1893
2058
  rawValue: value
1894
2059
  };
1895
2060
  }
@@ -2780,9 +2945,9 @@ function convertToOpenRouterChatMessages(prompt) {
2780
2945
  const parsedProviderOptions = OpenRouterProviderOptionsSchema.safeParse(providerOptions);
2781
2946
  const messageReasoningDetails = parsedProviderOptions.success ? (_e = (_d = parsedProviderOptions.data) == null ? void 0 : _d.openrouter) == null ? void 0 : _e.reasoning_details : void 0;
2782
2947
  const messageAnnotations = parsedProviderOptions.success ? (_g = (_f = parsedProviderOptions.data) == null ? void 0 : _f.openrouter) == null ? void 0 : _g.annotations : void 0;
2783
- const candidateReasoningDetails = messageReasoningDetails && Array.isArray(messageReasoningDetails) && messageReasoningDetails.length > 0 ? messageReasoningDetails : findFirstReasoningDetails(content);
2948
+ const candidateReasoningDetails = messageReasoningDetails && Array.isArray(messageReasoningDetails) ? messageReasoningDetails : findFirstReasoningDetails(content);
2784
2949
  let finalReasoningDetails;
2785
- if (candidateReasoningDetails && candidateReasoningDetails.length > 0) {
2950
+ if (candidateReasoningDetails) {
2786
2951
  const validDetails = candidateReasoningDetails.filter((detail) => {
2787
2952
  var _a17;
2788
2953
  if (detail.type !== "reasoning.text" /* Text */) {
@@ -2808,9 +2973,9 @@ function convertToOpenRouterChatMessages(prompt) {
2808
2973
  uniqueDetails.push(detail);
2809
2974
  }
2810
2975
  }
2811
- finalReasoningDetails = uniqueDetails.length > 0 ? uniqueDetails : void 0;
2976
+ finalReasoningDetails = uniqueDetails;
2812
2977
  }
2813
- const effectiveReasoning = reasoning && finalReasoningDetails ? reasoning : void 0;
2978
+ const effectiveReasoning = reasoning && finalReasoningDetails && finalReasoningDetails.length > 0 ? reasoning : void 0;
2814
2979
  messages.push({
2815
2980
  role: "assistant",
2816
2981
  content: text,
@@ -3737,15 +3902,17 @@ var OpenRouterChatLanguageModel = class {
3737
3902
  controller.enqueue({
3738
3903
  type: "reasoning-end",
3739
3904
  id: reasoningId || generateId(),
3740
- // Include accumulated reasoning_details so the AI SDK can update
3741
- // the reasoning part's providerMetadata with the correct signature.
3742
- // The signature typically arrives in the last reasoning delta,
3905
+ // Always include accumulated reasoning_details so the AI SDK can
3906
+ // update the reasoning part's providerMetadata with the correct
3907
+ // signature. The signature typically arrives in the last delta,
3743
3908
  // but reasoning-start only carries the first delta's metadata.
3744
- providerMetadata: accumulatedReasoningDetails.length > 0 ? {
3909
+ // An empty array is intentional — it signals the provider produced
3910
+ // no reasoning tokens this turn (e.g. DeepSeek V4).
3911
+ providerMetadata: {
3745
3912
  openrouter: {
3746
3913
  reasoning_details: accumulatedReasoningDetails
3747
3914
  }
3748
- } : void 0
3915
+ }
3749
3916
  });
3750
3917
  reasoningStarted = false;
3751
3918
  }
@@ -3980,13 +4147,14 @@ var OpenRouterChatLanguageModel = class {
3980
4147
  controller.enqueue({
3981
4148
  type: "reasoning-end",
3982
4149
  id: reasoningId || generateId(),
3983
- // Include accumulated reasoning_details so the AI SDK can update
3984
- // the reasoning part's providerMetadata with the correct signature.
3985
- providerMetadata: accumulatedReasoningDetails.length > 0 ? {
4150
+ // Always include accumulated reasoning_details so the AI SDK can
4151
+ // update the reasoning part's providerMetadata. An empty array is
4152
+ // intentional it signals the provider produced no reasoning tokens.
4153
+ providerMetadata: {
3986
4154
  openrouter: {
3987
4155
  reasoning_details: accumulatedReasoningDetails
3988
4156
  }
3989
- } : void 0
4157
+ }
3990
4158
  });
3991
4159
  }
3992
4160
  if (textStarted) {
@@ -4001,9 +4169,7 @@ var OpenRouterChatLanguageModel = class {
4001
4169
  if (provider !== void 0) {
4002
4170
  openrouterMetadata.provider = provider;
4003
4171
  }
4004
- if (accumulatedReasoningDetails.length > 0) {
4005
- openrouterMetadata.reasoning_details = accumulatedReasoningDetails;
4006
- }
4172
+ openrouterMetadata.reasoning_details = accumulatedReasoningDetails;
4007
4173
  if (accumulatedFileAnnotations.length > 0) {
4008
4174
  openrouterMetadata.annotations = accumulatedFileAnnotations;
4009
4175
  }
@@ -4715,10 +4881,203 @@ function convertImageFileToContentPart(file) {
4715
4881
  image_url: { url }
4716
4882
  };
4717
4883
  }
4884
+
4885
+ // src/video/schemas.ts
4886
+ import { z as z11 } from "zod/v4";
4887
+ var VideoGenerationSubmitResponseSchema = z11.object({
4888
+ id: z11.string(),
4889
+ generation_id: z11.string().optional(),
4890
+ polling_url: z11.string(),
4891
+ status: z11.string()
4892
+ }).passthrough();
4893
+ var VideoGenerationPollResponseSchema = z11.object({
4894
+ id: z11.string(),
4895
+ generation_id: z11.string().optional(),
4896
+ polling_url: z11.string(),
4897
+ status: z11.string(),
4898
+ unsigned_urls: z11.array(z11.string()).optional(),
4899
+ usage: z11.object({
4900
+ cost: z11.number().optional(),
4901
+ is_byok: z11.boolean().optional()
4902
+ }).passthrough().optional(),
4903
+ error: z11.string().optional()
4904
+ }).passthrough();
4905
+
4906
+ // src/video/index.ts
4907
+ var DEFAULT_POLL_INTERVAL_MS = 2e3;
4908
+ var DEFAULT_MAX_POLL_TIME_MS = 6e5;
4909
+ var OpenRouterVideoModel = class {
4910
+ constructor(modelId, settings, config) {
4911
+ this.specificationVersion = "v3";
4912
+ this.provider = "openrouter";
4913
+ this.maxVideosPerCall = 1;
4914
+ this.modelId = modelId;
4915
+ this.settings = settings;
4916
+ this.config = config;
4917
+ }
4918
+ async doGenerate(options) {
4919
+ var _a16, _b16, _c, _d, _e;
4920
+ const {
4921
+ prompt,
4922
+ n,
4923
+ aspectRatio,
4924
+ resolution,
4925
+ duration,
4926
+ seed,
4927
+ image,
4928
+ abortSignal,
4929
+ headers,
4930
+ providerOptions
4931
+ } = options;
4932
+ const warnings = [];
4933
+ if (n > 1) {
4934
+ warnings.push({
4935
+ type: "unsupported",
4936
+ feature: "n > 1",
4937
+ details: `OpenRouter video generation returns 1 video per call. Requested ${n} videos.`
4938
+ });
4939
+ }
4940
+ const body = __spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues({
4941
+ model: this.modelId,
4942
+ prompt: prompt != null ? prompt : ""
4943
+ }, aspectRatio !== void 0 && { aspect_ratio: aspectRatio }), resolution !== void 0 && { size: resolution }), duration !== void 0 && { duration }), seed !== void 0 && { seed }), this.settings.generateAudio !== void 0 && {
4944
+ generate_audio: this.settings.generateAudio
4945
+ }), image !== void 0 && {
4946
+ frame_images: [convertImageToFrameImage(image)]
4947
+ }), this.config.extraBody), this.settings.extraBody), providerOptions.openrouter);
4948
+ const mergedHeaders = combineHeaders(this.config.headers(), headers);
4949
+ const { value: submitResponse, responseHeaders } = await postJsonToApi({
4950
+ url: this.config.url({
4951
+ path: "/videos",
4952
+ modelId: this.modelId
4953
+ }),
4954
+ headers: mergedHeaders,
4955
+ body,
4956
+ failedResponseHandler: openrouterFailedResponseHandler,
4957
+ successfulResponseHandler: createJsonResponseHandler(
4958
+ VideoGenerationSubmitResponseSchema
4959
+ ),
4960
+ abortSignal,
4961
+ fetch: this.config.fetch
4962
+ });
4963
+ const pollIntervalMs = (_a16 = this.settings.pollIntervalMs) != null ? _a16 : DEFAULT_POLL_INTERVAL_MS;
4964
+ const maxPollTimeMs = (_b16 = this.settings.maxPollTimeMs) != null ? _b16 : DEFAULT_MAX_POLL_TIME_MS;
4965
+ const pollResult = await this.pollUntilComplete({
4966
+ jobId: submitResponse.id,
4967
+ headers: mergedHeaders,
4968
+ abortSignal,
4969
+ pollIntervalMs,
4970
+ maxPollTimeMs
4971
+ });
4972
+ const videos = [];
4973
+ if (pollResult.unsigned_urls) {
4974
+ for (const url of pollResult.unsigned_urls) {
4975
+ videos.push({
4976
+ type: "url",
4977
+ url,
4978
+ mediaType: "video/mp4"
4979
+ });
4980
+ }
4981
+ }
4982
+ const providerMetadata = {
4983
+ openrouter: {
4984
+ generationId: (_c = pollResult.generation_id) != null ? _c : null,
4985
+ cost: (_e = (_d = pollResult.usage) == null ? void 0 : _d.cost) != null ? _e : null
4986
+ }
4987
+ };
4988
+ return {
4989
+ videos,
4990
+ warnings,
4991
+ providerMetadata,
4992
+ response: {
4993
+ timestamp: /* @__PURE__ */ new Date(),
4994
+ modelId: this.modelId,
4995
+ headers: responseHeaders
4996
+ }
4997
+ };
4998
+ }
4999
+ async pollUntilComplete({
5000
+ jobId,
5001
+ headers,
5002
+ abortSignal,
5003
+ pollIntervalMs,
5004
+ maxPollTimeMs
5005
+ }) {
5006
+ var _a16;
5007
+ const startTime = Date.now();
5008
+ while (Date.now() - startTime < maxPollTimeMs) {
5009
+ abortSignal == null ? void 0 : abortSignal.throwIfAborted();
5010
+ await delay(pollIntervalMs);
5011
+ abortSignal == null ? void 0 : abortSignal.throwIfAborted();
5012
+ const { value: pollResponse } = await getFromApi({
5013
+ url: this.config.url({
5014
+ path: `/videos/${jobId}`,
5015
+ modelId: this.modelId
5016
+ }),
5017
+ headers,
5018
+ failedResponseHandler: openrouterFailedResponseHandler,
5019
+ successfulResponseHandler: createJsonResponseHandler(
5020
+ VideoGenerationPollResponseSchema
5021
+ ),
5022
+ abortSignal,
5023
+ fetch: this.config.fetch
5024
+ });
5025
+ if (pollResponse.status === "completed") {
5026
+ return {
5027
+ generation_id: pollResponse.generation_id,
5028
+ unsigned_urls: pollResponse.unsigned_urls,
5029
+ usage: pollResponse.usage
5030
+ };
5031
+ }
5032
+ if (pollResponse.status === "failed" || pollResponse.status === "dead" || pollResponse.status === "cancelled" || pollResponse.status === "expired") {
5033
+ throw new APICallError({
5034
+ message: (_a16 = pollResponse.error) != null ? _a16 : `Video generation failed with status: ${pollResponse.status}`,
5035
+ url: this.config.url({
5036
+ path: `/videos/${jobId}`,
5037
+ modelId: this.modelId
5038
+ }),
5039
+ requestBodyValues: {},
5040
+ statusCode: 500,
5041
+ isRetryable: false
5042
+ });
5043
+ }
5044
+ }
5045
+ throw new APICallError({
5046
+ message: `Video generation timed out after ${maxPollTimeMs}ms`,
5047
+ url: this.config.url({
5048
+ path: `/videos/${jobId}`,
5049
+ modelId: this.modelId
5050
+ }),
5051
+ requestBodyValues: {},
5052
+ statusCode: 408,
5053
+ isRetryable: true
5054
+ });
5055
+ }
5056
+ };
5057
+ function convertImageToFrameImage(file) {
5058
+ if (file.type === "url") {
5059
+ return {
5060
+ type: "image_url",
5061
+ image_url: { url: file.url },
5062
+ frame_type: "first_frame"
5063
+ };
5064
+ }
5065
+ const url = buildFileDataUrl({
5066
+ data: file.data,
5067
+ mediaType: file.mediaType,
5068
+ defaultMediaType: "image/png"
5069
+ });
5070
+ return {
5071
+ type: "image_url",
5072
+ image_url: { url },
5073
+ frame_type: "first_frame"
5074
+ };
5075
+ }
4718
5076
  export {
4719
5077
  OpenRouterChatLanguageModel,
4720
5078
  OpenRouterCompletionLanguageModel,
4721
5079
  OpenRouterEmbeddingModel,
4722
- OpenRouterImageModel
5080
+ OpenRouterImageModel,
5081
+ OpenRouterVideoModel
4723
5082
  };
4724
5083
  //# sourceMappingURL=index.mjs.map