@mux/ai 0.63.1 → 0.64.0

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.
@@ -396,11 +396,11 @@ type ErrorCatalogEntry<TType extends string = string, TDependency extends string
396
396
  * them. Codes name the condition, never the vendor.
397
397
  */
398
398
  declare const MUX_AI_ERROR_CODES: {
399
- /** The requested time range is invalid, or has nothing to work with. Facts: `reason` (`invalid_start_time`, `invalid_end_time`, `exceeds_duration`, `empty_range`, `no_video`, `no_transcript`, `no_scenes`) and the bounds involved. */
399
+ /** The requested time range is invalid, or has nothing to work with. Facts: `reason` (`invalid_start_time`, `invalid_end_time`, `exceeds_duration`, `empty_range`, `no_video`, `no_transcript`, `no_scenes`) and the bounds involved (`videoEndTime` for `no_video`). */
400
400
  readonly INVALID_SCOPE: "invalid_scope";
401
401
  /** Existing tracks block writing the output track under the chosen replacement policy. Facts: `reason` (`policy_fail`, `not_generated`, `name_collision`, `primary_audio`), `conflictingTracks` and the target track, plus `sourceRestored` and `restoredTrackId` when a source track was deleted first. */
402
402
  readonly TRACK_REPLACEMENT_BLOCKED: "track_replacement_blocked";
403
- /** An option's value can't be used. Facts: `parameter` (the caller's option name), `reason` (`too_many`, `empty`, `too_long`, `disallowed_characters`, `not_normalized`, `multiline`, `required_with`, `conflicts_with`, `not_allowed`, `one_of_required`) and the values the reason names: `count` and `max`, `index` (0-based entry), `length` and `maxLength`, `characters`, `with` and `withValue` (the other option), `allowed` and `value`, `parameters` (the options to choose from). */
403
+ /** An option's value can't be used. Facts: `parameter` (the caller's option name), `reason` (`too_many`, `empty`, `too_long`, `disallowed_characters`, `not_normalized`, `multiline`, `required_with`, `conflicts_with`, `not_allowed`, `one_of_required`, `audio_only`) and the values the reason names: `count` and `max`, `index` (0-based entry), `length` and `maxLength`, `characters`, `with` and `withValue` (the other option), `allowed` and `value`, `parameters` (the options to choose from). */
404
404
  readonly INVALID_PARAMETER: "invalid_parameter";
405
405
  /** A numeric option is outside its allowed range. Facts: `parameter` (the caller's option name), `value`, `min`, `max`, and `integer` when it must be a whole number. */
406
406
  readonly PARAMETER_OUT_OF_RANGE: "parameter_out_of_range";
@@ -428,6 +428,8 @@ declare const MUX_AI_ERROR_CODES: {
428
428
  readonly TRACK_WRITE_UNCLASSIFIED: "track_write_unclassified";
429
429
  /** Mux answered a track create without a track id. The track may exist, so it isn't step-retried. Facts: `call`, `assetId`. */
430
430
  readonly TRACK_ID_MISSING: "track_id_missing";
431
+ /** Mux answered an image download with something other than a non-empty image. Facts: `call`, `reason` (`not_image`, `empty`), `contentType`. */
432
+ readonly IMAGE_RESPONSE_INVALID: "image_response_invalid";
431
433
  /** The asset's ready caption track has no id, so its transcript can't be fetched. Facts: `assetId`, `languageCode`. */
432
434
  readonly CAPTION_TRACK_ID_MISSING: "caption_track_id_missing";
433
435
  /** The asset snapshot the service running the SDK passed in is for a different asset than the one requested. Facts: `assetId`, `snapshotAssetId`. */
@@ -548,6 +550,13 @@ declare const MUX_AI_ERROR_CATALOG: {
548
550
  readonly source: "upstream";
549
551
  readonly dependency: "mux_video";
550
552
  };
553
+ readonly image_response_invalid: {
554
+ readonly type: "processing_error";
555
+ readonly source: "upstream";
556
+ readonly dependency: "mux_video";
557
+ readonly transient: true;
558
+ readonly retryable: true;
559
+ };
551
560
  readonly asset_id_mismatch: {
552
561
  readonly type: "processing_error";
553
562
  readonly source: "upstream";
@@ -1,7 +1,7 @@
1
- export { P as ASK_QUESTIONS_DEFAULT_MAX_ANSWER_OPTION_LENGTH, Q as ASK_QUESTIONS_DEFAULT_MAX_FREE_FORM_ANSWER_LENGTH, U as ASK_QUESTIONS_MAX_QUESTIONS_PER_CALL, V as ASK_QUESTIONS_MAX_QUESTION_LENGTH, W as AskQuestionsOptions, X as AskQuestionsResult, Y as AskQuestionsType, Z as AudioTranslationOptions, _ as AudioTranslationResult, $ as AutoCensorProfanityOptions, a0 as BurnedInCaptionsAnalysis, a1 as BurnedInCaptionsOptions, a2 as BurnedInCaptionsPromptOverrides, a3 as BurnedInCaptionsPromptSections, a4 as BurnedInCaptionsResult, a5 as CaptionReplacement, a6 as CensorMode, a7 as Chapter, a8 as ChapterSystemPromptSections, a9 as ChaptersOptions, aa as ChaptersPromptOverrides, ab as ChaptersPromptSections, ac as ChaptersResult, ad as ChaptersType, ae as DEFAULT_TRANSCRIPT_WINDOWING, af as DubbedCaptionsOutcome, ag as EditCaptionsOptions, ah as EditCaptionsResult, ai as EmbeddingsOptions, aj as EmbeddingsResult, ak as EngagementInsightsOptions, al as EngagementInsightsResult, am as GENERATE_TEXT_CALLS_TO_ACTION, an as GENERATE_TEXT_CHANNELS, ao as GENERATE_TEXT_CHANNEL_CEILINGS, ap as GENERATE_TEXT_FORMATS, aq as GENERATE_TEXT_LENGTH_BOUNDS, ar as GENERATE_TEXT_MAX_ARTIFACTS, as as GENERATE_TEXT_MAX_AUDIENCE_CHARS, at as GENERATE_TEXT_MAX_BRAND_TERMS, au as GENERATE_TEXT_MAX_BRAND_TERMS_TOTAL_CHARS, av as GENERATE_TEXT_MAX_BRAND_TERM_CHARS, aw as GENERATE_TEXT_MAX_CONCURRENT_GENERATIONS, ax as GENERATE_TEXT_MAX_INSTRUCTIONS_CHARS, ay as GENERATE_TEXT_MAX_SHOT_FRAMES, az as GENERATE_TEXT_MAX_VARIANTS, aA as GENERATE_TEXT_VOICES, aB as GOOGLE_VISION_LIKELIHOOD_TO_SCORE, aC as GenerateTextArtifact, aD as GenerateTextCallToAction, aE as GenerateTextChannel, aF as GenerateTextFormat, aG as GenerateTextKeyedItem, aH as GenerateTextLengthLimit, aI as GenerateTextOptions, aJ as GenerateTextResult, aK as GenerateTextVariant, aL as GenerateTextVoice, aM as GeneratedTextArtifact, aN as GeneratedTextVariant, aO as HIVE_SEXUAL_CATEGORIES, aP as HIVE_VIOLENCE_CATEGORIES, aQ as HiveModerationOutput, aR as HiveModerationSource, aS as ModerationOptions, aT as ModerationProvider, aU as ModerationResult, aV as ModerationSurfaceStatus, aW as MomentInsight, aX as OverallInsight, aY as ProfanityDetectionPayload, aZ as Question, a_ as QuestionAnswer, a$ as QuestionAnswerType, b0 as RepairAttempt, b1 as RepairCall, b2 as RepairOptions, b3 as RepairPlan, b4 as RepairResult, b5 as RepairSpan, b6 as ReplacementRecord, b7 as SpeakerReplacement, b8 as StaticRenditionCleanupOutcome, b9 as SummarizationOptions, ba as SummarizationPromptOverrides, bb as SummarizationPromptSections, bc as SummaryAndTagsResult, bd as SummaryType, be as TextLengthLimit, bf as TextRepairModelOptions, bg as ThumbnailModerationScore, bh as ThumbnailModerationSkipReason, bi as ThumbnailModerationStatus, bj as TranscriptModerationScore, bk as TranscriptModerationSkipReason, bl as TranscriptModerationStatus, bm as TranslationChunkingOptions, bn as TranslationOptions, bo as TranslationPayload, bp as TranslationResult, bq as aggregateTokenUsage, br as applyOverrideLists, bs as applyReplacements, bt as applySpeakerReplacements, bu as applyTextRepair, bv as askQuestions, bw as buildReplacementRegex, bx as buildTranscriptWindows, by as burnedInCaptionsSchema, bz as censorVttContent, bA as chapterSchema, bB as chaptersSchema, bC as createReplacer, bD as createTextRepairGenerator, bE as editCaptions, bF as extractTranscriptSegmentsForHotspots, bG as findGenerateTextLengthViolation, bH as generateChapters, bI as generateEmbeddings, bJ as generateEngagementInsights, bK as generateText, bL as generateVideoEmbeddings, bM as getModerationScores, bN as getSummaryAndTags, bO as hasBurnedInCaptions, bP as mapShotsToHotspots, bQ as measureGenerateTextLength, bR as normalizeTranslatedVtt, bS as planTextRepair, bT as profanityDetectionSchema, bU as questionAnswerSchema, bV as repairJsonSchema, bW as repairText, bX as resolveGenerateTextLengthLimit, bY as resolveGenerateTextLengthLimits, bZ as resolveGenerateTextOptions, b_ as runTextRepairLoop, b$ as selectGenerateTextShotFrames, c0 as shouldSplitChunkTranslationError, c1 as summarySchema, c2 as transformCueText, c3 as translateAudio, c4 as translateCaptions, c5 as translationSchema, c6 as validateNeverTranslateTerms, c7 as verifyNeverTranslateTerms } from '../index-DJ6j4-nM.js';
1
+ export { P as ASK_QUESTIONS_DEFAULT_MAX_ANSWER_OPTION_LENGTH, Q as ASK_QUESTIONS_DEFAULT_MAX_FREE_FORM_ANSWER_LENGTH, U as ASK_QUESTIONS_MAX_QUESTIONS_PER_CALL, V as ASK_QUESTIONS_MAX_QUESTION_LENGTH, W as AskQuestionsOptions, X as AskQuestionsResult, Y as AskQuestionsType, Z as AudioTranslationOptions, _ as AudioTranslationResult, $ as AutoCensorProfanityOptions, a0 as BurnedInCaptionsAnalysis, a1 as BurnedInCaptionsOptions, a2 as BurnedInCaptionsPromptOverrides, a3 as BurnedInCaptionsPromptSections, a4 as BurnedInCaptionsResult, a5 as CaptionReplacement, a6 as CensorMode, a7 as Chapter, a8 as ChapterSystemPromptSections, a9 as ChaptersOptions, aa as ChaptersPromptOverrides, ab as ChaptersPromptSections, ac as ChaptersResult, ad as ChaptersType, ae as DEFAULT_TRANSCRIPT_WINDOWING, af as DubbedCaptionsOutcome, ag as EditCaptionsOptions, ah as EditCaptionsResult, ai as EmbeddingsOptions, aj as EmbeddingsResult, ak as EngagementInsightsOptions, al as EngagementInsightsResult, am as GENERATE_TEXT_CALLS_TO_ACTION, an as GENERATE_TEXT_CHANNELS, ao as GENERATE_TEXT_CHANNEL_CEILINGS, ap as GENERATE_TEXT_FORMATS, aq as GENERATE_TEXT_LENGTH_BOUNDS, ar as GENERATE_TEXT_MAX_ARTIFACTS, as as GENERATE_TEXT_MAX_AUDIENCE_CHARS, at as GENERATE_TEXT_MAX_BRAND_TERMS, au as GENERATE_TEXT_MAX_BRAND_TERMS_TOTAL_CHARS, av as GENERATE_TEXT_MAX_BRAND_TERM_CHARS, aw as GENERATE_TEXT_MAX_CONCURRENT_GENERATIONS, ax as GENERATE_TEXT_MAX_INSTRUCTIONS_CHARS, ay as GENERATE_TEXT_MAX_SHOT_FRAMES, az as GENERATE_TEXT_MAX_VARIANTS, aA as GENERATE_TEXT_VOICES, aB as GOOGLE_VISION_LIKELIHOOD_TO_SCORE, aC as GenerateTextArtifact, aD as GenerateTextCallToAction, aE as GenerateTextChannel, aF as GenerateTextFormat, aG as GenerateTextKeyedItem, aH as GenerateTextLengthLimit, aI as GenerateTextOptions, aJ as GenerateTextResult, aK as GenerateTextVariant, aL as GenerateTextVoice, aM as GeneratedTextArtifact, aN as GeneratedTextVariant, aO as HIVE_SEXUAL_CATEGORIES, aP as HIVE_VIOLENCE_CATEGORIES, aQ as HiveModerationOutput, aR as HiveModerationSource, aS as ModerationOptions, aT as ModerationProvider, aU as ModerationResult, aV as ModerationSurfaceStatus, aW as MomentInsight, aX as OverallInsight, aY as ProfanityDetectionPayload, aZ as Question, a_ as QuestionAnswer, a$ as QuestionAnswerType, b0 as RepairAttempt, b1 as RepairCall, b2 as RepairOptions, b3 as RepairPlan, b4 as RepairResult, b5 as RepairSpan, b6 as ReplacementRecord, b7 as SpeakerReplacement, b8 as StaticRenditionCleanupOutcome, b9 as SummarizationOptions, ba as SummarizationPromptOverrides, bb as SummarizationPromptSections, bc as SummaryAndTagsResult, bd as SummaryType, be as TextLengthLimit, bf as TextRepairModelOptions, bg as ThumbnailModerationScore, bh as ThumbnailModerationSkipReason, bi as ThumbnailModerationStatus, bj as TranscriptModerationScore, bk as TranscriptModerationSkipReason, bl as TranscriptModerationStatus, bm as TranslationChunkingOptions, bn as TranslationOptions, bo as TranslationPayload, bp as TranslationResult, bq as aggregateTokenUsage, br as applyOverrideLists, bs as applyReplacements, bt as applySpeakerReplacements, bu as applyTextRepair, bv as askQuestions, bw as buildReplacementRegex, bx as buildTranscriptWindows, by as burnedInCaptionsSchema, bz as censorVttContent, bA as chapterSchema, bB as chaptersSchema, bC as createReplacer, bD as createTextRepairGenerator, bE as editCaptions, bF as extractTranscriptSegmentsForHotspots, bG as findGenerateTextLengthViolation, bH as generateChapters, bI as generateEmbeddings, bJ as generateEngagementInsights, bK as generateText, bL as generateVideoEmbeddings, bM as getModerationScores, bN as getSummaryAndTags, bO as hasBurnedInCaptions, bP as mapShotsToHotspots, bQ as measureGenerateTextLength, bR as normalizeTranslatedVtt, bS as planTextRepair, bT as profanityDetectionSchema, bU as questionAnswerSchema, bV as repairJsonSchema, bW as repairText, bX as resolveGenerateTextLengthLimit, bY as resolveGenerateTextLengthLimits, bZ as resolveGenerateTextOptions, b_ as runTextRepairLoop, b$ as selectGenerateTextShotFrames, c0 as shouldSplitChunkTranslationError, c1 as summarySchema, c2 as transformCueText, c3 as translateAudio, c4 as translateCaptions, c5 as translationSchema, c6 as validateNeverTranslateTerms, c7 as verifyNeverTranslateTerms } from '../index-DxCv-w74.js';
2
2
  export { D as DEFAULT_DESCRIPTION_LENGTH, a as DEFAULT_SUMMARY_KEYWORD_LIMIT, b as DEFAULT_TITLE_LENGTH } from '../summarization-BFmhXeAu.js';
3
3
  import 'ai';
4
- import '../transcripts-CFZM111v.js';
4
+ import '../transcripts-CGRjxn_g.js';
5
5
  import '@workflow/serde';
6
6
  import '@mux/ts';
7
7
  import 'zod';
@@ -573,11 +573,11 @@ var MUX_AI_ERROR_DEPENDENCIES = {
573
573
  };
574
574
  var MUX_AI_ERROR_DEPENDENCY_VALUES = Object.values(MUX_AI_ERROR_DEPENDENCIES);
575
575
  var MUX_AI_ERROR_CODES = {
576
- /** The requested time range is invalid, or has nothing to work with. Facts: `reason` (`invalid_start_time`, `invalid_end_time`, `exceeds_duration`, `empty_range`, `no_video`, `no_transcript`, `no_scenes`) and the bounds involved. */
576
+ /** The requested time range is invalid, or has nothing to work with. Facts: `reason` (`invalid_start_time`, `invalid_end_time`, `exceeds_duration`, `empty_range`, `no_video`, `no_transcript`, `no_scenes`) and the bounds involved (`videoEndTime` for `no_video`). */
577
577
  INVALID_SCOPE: "invalid_scope",
578
578
  /** Existing tracks block writing the output track under the chosen replacement policy. Facts: `reason` (`policy_fail`, `not_generated`, `name_collision`, `primary_audio`), `conflictingTracks` and the target track, plus `sourceRestored` and `restoredTrackId` when a source track was deleted first. */
579
579
  TRACK_REPLACEMENT_BLOCKED: "track_replacement_blocked",
580
- /** An option's value can't be used. Facts: `parameter` (the caller's option name), `reason` (`too_many`, `empty`, `too_long`, `disallowed_characters`, `not_normalized`, `multiline`, `required_with`, `conflicts_with`, `not_allowed`, `one_of_required`) and the values the reason names: `count` and `max`, `index` (0-based entry), `length` and `maxLength`, `characters`, `with` and `withValue` (the other option), `allowed` and `value`, `parameters` (the options to choose from). */
580
+ /** An option's value can't be used. Facts: `parameter` (the caller's option name), `reason` (`too_many`, `empty`, `too_long`, `disallowed_characters`, `not_normalized`, `multiline`, `required_with`, `conflicts_with`, `not_allowed`, `one_of_required`, `audio_only`) and the values the reason names: `count` and `max`, `index` (0-based entry), `length` and `maxLength`, `characters`, `with` and `withValue` (the other option), `allowed` and `value`, `parameters` (the options to choose from). */
581
581
  INVALID_PARAMETER: "invalid_parameter",
582
582
  /** A numeric option is outside its allowed range. Facts: `parameter` (the caller's option name), `value`, `min`, `max`, and `integer` when it must be a whole number. */
583
583
  PARAMETER_OUT_OF_RANGE: "parameter_out_of_range",
@@ -605,6 +605,8 @@ var MUX_AI_ERROR_CODES = {
605
605
  TRACK_WRITE_UNCLASSIFIED: "track_write_unclassified",
606
606
  /** Mux answered a track create without a track id. The track may exist, so it isn't step-retried. Facts: `call`, `assetId`. */
607
607
  TRACK_ID_MISSING: "track_id_missing",
608
+ /** Mux answered an image download with something other than a non-empty image. Facts: `call`, `reason` (`not_image`, `empty`), `contentType`. */
609
+ IMAGE_RESPONSE_INVALID: "image_response_invalid",
608
610
  /** The asset's ready caption track has no id, so its transcript can't be fetched. Facts: `assetId`, `languageCode`. */
609
611
  CAPTION_TRACK_ID_MISSING: "caption_track_id_missing",
610
612
  /** The asset snapshot the service running the SDK passed in is for a different asset than the one requested. Facts: `assetId`, `snapshotAssetId`. */
@@ -668,6 +670,9 @@ var MUX_AI_ERROR_CATALOG = {
668
670
  // The track may exist, so a step retry could duplicate it; the job stays retryable.
669
671
  [MUX_AI_ERROR_CODES.TRACK_ID_MISSING]: { type: MUX_AI_ERROR_TYPES.PROCESSING_ERROR, source: MUX_AI_ERROR_SOURCES.UPSTREAM, dependency: MUX_AI_ERROR_DEPENDENCIES.MUX_VIDEO },
670
672
  [MUX_AI_ERROR_CODES.CAPTION_TRACK_ID_MISSING]: { type: MUX_AI_ERROR_TYPES.PROCESSING_ERROR, source: MUX_AI_ERROR_SOURCES.UPSTREAM, dependency: MUX_AI_ERROR_DEPENDENCIES.MUX_VIDEO },
673
+ // Transient (so retryable): the download doesn't retry a reply that isn't a non-empty image
674
+ // itself, so the step runner does, as it did before classification.
675
+ [MUX_AI_ERROR_CODES.IMAGE_RESPONSE_INVALID]: { type: MUX_AI_ERROR_TYPES.PROCESSING_ERROR, source: MUX_AI_ERROR_SOURCES.UPSTREAM, dependency: MUX_AI_ERROR_DEPENDENCIES.MUX_VIDEO, transient: true, retryable: true },
671
676
  [MUX_AI_ERROR_CODES.ASSET_ID_MISMATCH]: { type: MUX_AI_ERROR_TYPES.PROCESSING_ERROR, source: MUX_AI_ERROR_SOURCES.UPSTREAM, dependency: MUX_AI_ERROR_DEPENDENCIES.MUX_VIDEO },
672
677
  // Model calls.
673
678
  [MUX_AI_ERROR_CODES.CONTENT_POLICY_BLOCKED]: { type: MUX_AI_ERROR_TYPES.CONTENT_POLICY_ERROR, source: MUX_AI_ERROR_SOURCES.ASSET, dependency: MUX_AI_ERROR_DEPENDENCIES.AI_PROVIDER },
@@ -1867,6 +1872,69 @@ import { z as z5 } from "zod";
1867
1872
 
1868
1873
  // src/lib/image-download.ts
1869
1874
  import pRetry, { AbortError } from "p-retry";
1875
+
1876
+ // src/lib/mux-video-errors.ts
1877
+ import { z as z4 } from "zod";
1878
+ var MuxTokenSchema = z4.string().regex(/^[\w.-]{1,64}$/);
1879
+ var MuxApiErrorSchema = z4.object({
1880
+ error: z4.object({
1881
+ error: z4.object({ type: MuxTokenSchema })
1882
+ })
1883
+ });
1884
+ function muxVideoErrorFacts(error) {
1885
+ const parsed = MuxApiErrorSchema.safeParse(error);
1886
+ return parsed.success ? { muxErrorType: parsed.data.error.error.type } : {};
1887
+ }
1888
+ function muxVideoError(message, init) {
1889
+ return dependencyError(message, {
1890
+ ...init,
1891
+ dependency: MUX_AI_ERROR_DEPENDENCIES.MUX_VIDEO,
1892
+ notFoundSource: MUX_AI_ERROR_SOURCES.ASSET,
1893
+ authSource: MUX_AI_ERROR_SOURCES.ACCOUNT,
1894
+ authInputs: ["credentials"],
1895
+ // A create may have taken effect despite the failure; retrying could duplicate the track.
1896
+ idempotent: init.call !== "create_track"
1897
+ });
1898
+ }
1899
+ function muxVideoCallError(message, call, error, facts) {
1900
+ if (MuxAiError.is(error)) {
1901
+ if (facts) {
1902
+ Object.assign(error, { facts: { ...facts, ...error.facts } });
1903
+ }
1904
+ return error;
1905
+ }
1906
+ return muxVideoError(message, {
1907
+ call,
1908
+ status: httpStatusOf(error),
1909
+ requestId: requestIdOf(error?.headers),
1910
+ facts: { ...facts, ...muxVideoErrorFacts(error) },
1911
+ cause: error
1912
+ });
1913
+ }
1914
+ function muxAssetFetchError(assetId, error) {
1915
+ if (!MuxAiError.is(error) && httpStatusOf(error) === 404) {
1916
+ return new MuxAiError(`Mux asset ${assetId} not found`, {
1917
+ code: MUX_AI_ERROR_CODES.ASSET_NOT_FOUND,
1918
+ type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR,
1919
+ source: MUX_AI_ERROR_SOURCES.REQUEST,
1920
+ dependency: MUX_AI_ERROR_DEPENDENCIES.MUX_VIDEO,
1921
+ facts: { call: "get_asset", status: 404, assetId, inputs: ["assetId"], ...muxVideoErrorFacts(error) },
1922
+ cause: error
1923
+ });
1924
+ }
1925
+ return muxVideoCallError("Failed to fetch the asset from Mux", "get_asset", error, { assetId });
1926
+ }
1927
+ function missingTrackIdError(message, facts) {
1928
+ return new MuxAiError(message, {
1929
+ code: MUX_AI_ERROR_CODES.TRACK_ID_MISSING,
1930
+ type: MUX_AI_ERROR_TYPES.PROCESSING_ERROR,
1931
+ source: MUX_AI_ERROR_SOURCES.UPSTREAM,
1932
+ dependency: MUX_AI_ERROR_DEPENDENCIES.MUX_VIDEO,
1933
+ facts: { call: "create_track", ...facts }
1934
+ });
1935
+ }
1936
+
1937
+ // src/lib/image-download.ts
1870
1938
  var BASE64_CHUNK_SIZE = 32768;
1871
1939
  function bytesToBase64(bytes) {
1872
1940
  if (bytes.length === 0) {
@@ -1889,13 +1957,15 @@ var DEFAULT_OPTIONS = {
1889
1957
  maxRetryDelay: 1e4,
1890
1958
  exponentialBackoff: true
1891
1959
  };
1892
- async function downloadImageAsBase64(url, options = {}) {
1960
+ async function downloadImageAsBase64(url, options = {}, errorOptions = {}) {
1893
1961
  "use step";
1894
1962
  const opts = { ...DEFAULT_OPTIONS, ...options };
1895
1963
  let attemptCount = 0;
1964
+ let failure;
1896
1965
  return pRetry(
1897
1966
  async () => {
1898
1967
  attemptCount++;
1968
+ failure = void 0;
1899
1969
  const controller = new AbortController();
1900
1970
  const timeoutId = setTimeout(() => controller.abort(), opts.timeout);
1901
1971
  try {
@@ -1907,6 +1977,7 @@ async function downloadImageAsBase64(url, options = {}) {
1907
1977
  });
1908
1978
  clearTimeout(timeoutId);
1909
1979
  if (!response.ok) {
1980
+ failure = { kind: "status", status: response.status, requestId: requestIdOf(response.headers) };
1910
1981
  if (response.status >= 400 && response.status < 500 && response.status !== 429) {
1911
1982
  throw new AbortError(`HTTP ${response.status}: ${response.statusText}`);
1912
1983
  }
@@ -1914,11 +1985,13 @@ async function downloadImageAsBase64(url, options = {}) {
1914
1985
  }
1915
1986
  const contentType = response.headers.get("content-type");
1916
1987
  if (!contentType?.startsWith("image/")) {
1988
+ failure = { kind: "invalid", reason: "not_image", ...contentType && { contentType: contentType.slice(0, 100) } };
1917
1989
  throw new AbortError(`Invalid content type: ${contentType}. Expected image/*`);
1918
1990
  }
1919
1991
  const arrayBuffer = await response.arrayBuffer();
1920
1992
  const buffer = new Uint8Array(arrayBuffer);
1921
1993
  if (buffer.length === 0) {
1994
+ failure = { kind: "invalid", reason: "empty" };
1922
1995
  throw new AbortError("Downloaded image is empty");
1923
1996
  }
1924
1997
  const base64Data = `data:${contentType};base64,${bytesToBase64(buffer)}`;
@@ -1935,6 +2008,7 @@ async function downloadImageAsBase64(url, options = {}) {
1935
2008
  if (error instanceof AbortError) {
1936
2009
  throw error;
1937
2010
  }
2011
+ failure ?? (failure = { kind: "no_response", timedOut: error instanceof Error && error.name === "AbortError" });
1938
2012
  if (error instanceof Error) {
1939
2013
  if (error.name === "AbortError") {
1940
2014
  throw new Error(`Request timeout after ${opts.timeout}ms`);
@@ -1958,6 +2032,36 @@ async function downloadImageAsBase64(url, options = {}) {
1958
2032
  }
1959
2033
  }
1960
2034
  }
2035
+ ).catch((error) => {
2036
+ if (!errorOptions.classifiedErrors) {
2037
+ throw error;
2038
+ }
2039
+ throw imageDownloadError(failure, errorOptions.call ?? "fetch_image", error);
2040
+ });
2041
+ }
2042
+ function imageDownloadError(failure, call, cause) {
2043
+ if (failure?.kind === "status") {
2044
+ return muxVideoError(`Failed to download image from Mux (HTTP ${failure.status})`, {
2045
+ call,
2046
+ status: failure.status,
2047
+ requestId: failure.requestId
2048
+ });
2049
+ }
2050
+ if (failure?.kind === "invalid") {
2051
+ return new MuxAiError(
2052
+ failure.reason === "empty" ? "Mux returned an empty image." : `Mux returned ${failure.contentType ?? "no content type"} instead of an image.`,
2053
+ {
2054
+ code: MUX_AI_ERROR_CODES.IMAGE_RESPONSE_INVALID,
2055
+ type: MUX_AI_ERROR_TYPES.PROCESSING_ERROR,
2056
+ source: MUX_AI_ERROR_SOURCES.UPSTREAM,
2057
+ dependency: MUX_AI_ERROR_DEPENDENCIES.MUX_VIDEO,
2058
+ facts: { call, reason: failure.reason, ...failure.contentType && { contentType: failure.contentType } }
2059
+ }
2060
+ );
2061
+ }
2062
+ return muxVideoError(
2063
+ failure?.timedOut ? "Image download from Mux timed out" : "Failed to download image from Mux",
2064
+ { call, cause, timedOut: failure?.timedOut }
1961
2065
  );
1962
2066
  }
1963
2067
  async function downloadImagesAsBase64(urls, options = {}, maxConcurrent = 5) {
@@ -2693,67 +2797,6 @@ async function getApiKeyFromEnv(provider, credentials) {
2693
2797
  return resolveProviderApiKey(provider, credentials);
2694
2798
  }
2695
2799
 
2696
- // src/lib/mux-video-errors.ts
2697
- import { z as z4 } from "zod";
2698
- var MuxTokenSchema = z4.string().regex(/^[\w.-]{1,64}$/);
2699
- var MuxApiErrorSchema = z4.object({
2700
- error: z4.object({
2701
- error: z4.object({ type: MuxTokenSchema })
2702
- })
2703
- });
2704
- function muxVideoErrorFacts(error) {
2705
- const parsed = MuxApiErrorSchema.safeParse(error);
2706
- return parsed.success ? { muxErrorType: parsed.data.error.error.type } : {};
2707
- }
2708
- function muxVideoError(message, init) {
2709
- return dependencyError(message, {
2710
- ...init,
2711
- dependency: MUX_AI_ERROR_DEPENDENCIES.MUX_VIDEO,
2712
- notFoundSource: MUX_AI_ERROR_SOURCES.ASSET,
2713
- authSource: MUX_AI_ERROR_SOURCES.ACCOUNT,
2714
- authInputs: ["credentials"],
2715
- // A create may have taken effect despite the failure; retrying could duplicate the track.
2716
- idempotent: init.call !== "create_track"
2717
- });
2718
- }
2719
- function muxVideoCallError(message, call, error, facts) {
2720
- if (MuxAiError.is(error)) {
2721
- if (facts) {
2722
- Object.assign(error, { facts: { ...facts, ...error.facts } });
2723
- }
2724
- return error;
2725
- }
2726
- return muxVideoError(message, {
2727
- call,
2728
- status: httpStatusOf(error),
2729
- requestId: requestIdOf(error?.headers),
2730
- facts: { ...facts, ...muxVideoErrorFacts(error) },
2731
- cause: error
2732
- });
2733
- }
2734
- function muxAssetFetchError(assetId, error) {
2735
- if (!MuxAiError.is(error) && httpStatusOf(error) === 404) {
2736
- return new MuxAiError(`Mux asset ${assetId} not found`, {
2737
- code: MUX_AI_ERROR_CODES.ASSET_NOT_FOUND,
2738
- type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR,
2739
- source: MUX_AI_ERROR_SOURCES.REQUEST,
2740
- dependency: MUX_AI_ERROR_DEPENDENCIES.MUX_VIDEO,
2741
- facts: { call: "get_asset", status: 404, assetId, inputs: ["assetId"], ...muxVideoErrorFacts(error) },
2742
- cause: error
2743
- });
2744
- }
2745
- return muxVideoCallError("Failed to fetch the asset from Mux", "get_asset", error, { assetId });
2746
- }
2747
- function missingTrackIdError(message, facts) {
2748
- return new MuxAiError(message, {
2749
- code: MUX_AI_ERROR_CODES.TRACK_ID_MISSING,
2750
- type: MUX_AI_ERROR_TYPES.PROCESSING_ERROR,
2751
- source: MUX_AI_ERROR_SOURCES.UPSTREAM,
2752
- dependency: MUX_AI_ERROR_DEPENDENCIES.MUX_VIDEO,
2753
- facts: { call: "create_track", ...facts }
2754
- });
2755
- }
2756
-
2757
2800
  // src/lib/mux-assets.ts
2758
2801
  function getPlaybackId(asset, options = {}) {
2759
2802
  const playbackIds = asset.playback_ids || [];
@@ -2994,11 +3037,11 @@ function resolveWorkflowScope(scope, assetDurationSeconds, options = {}) {
2994
3037
  }
2995
3038
  return { startTime, endTime };
2996
3039
  }
2997
- function resolveRenderableVideoScope(scope, assetDurationSeconds, videoTrackDurationSeconds) {
3040
+ function resolveRenderableVideoScope(scope, assetDurationSeconds, videoTrackDurationSeconds, options = {}) {
2998
3041
  if (!hasWorkflowScopeBoundaries(scope)) {
2999
3042
  return void 0;
3000
3043
  }
3001
- const resolvedScope = resolveWorkflowScope(scope, assetDurationSeconds);
3044
+ const resolvedScope = resolveWorkflowScope(scope, assetDurationSeconds, options);
3002
3045
  let renderableEndTime = resolvedScope.endTime;
3003
3046
  if (videoTrackDurationSeconds !== void 0 && Number.isFinite(videoTrackDurationSeconds) && videoTrackDurationSeconds >= 0) {
3004
3047
  renderableEndTime = Math.min(videoTrackDurationSeconds, resolvedScope.endTime);
@@ -3008,6 +3051,13 @@ function resolveRenderableVideoScope(scope, assetDurationSeconds, videoTrackDura
3008
3051
  endTime: renderableEndTime
3009
3052
  };
3010
3053
  if (renderableScope.startTime >= renderableScope.endTime) {
3054
+ if (options.classifiedErrors) {
3055
+ throw invalidScopeError(
3056
+ "The requested scope does not include any renderable video.",
3057
+ { reason: "no_video", startTime: resolvedScope.startTime, endTime: resolvedScope.endTime, videoEndTime: renderableEndTime },
3058
+ ["scope"]
3059
+ );
3060
+ }
3011
3061
  throw new LegacyMuxAiError("The requested scope does not include any renderable video.", {
3012
3062
  type: "validation_error"
3013
3063
  });
@@ -9693,6 +9743,7 @@ async function analyzeVideo(imageDataUrl, provider, modelId, userPrompt, systemP
9693
9743
  "use step";
9694
9744
  const model = await createLanguageModelFromConfig(provider, modelId, credentials);
9695
9745
  const schema = buildSummarySchema(descriptionLength);
9746
+ const context = { call: "generate_summary", provider, model: modelId };
9696
9747
  const response = await withContentPolicyAwareRetry(() => generateText8({
9697
9748
  model,
9698
9749
  maxRetries: 0,
@@ -9711,11 +9762,10 @@ async function analyzeVideo(imageDataUrl, provider, modelId, userPrompt, systemP
9711
9762
  ] : userPrompt
9712
9763
  }
9713
9764
  ]
9714
- }));
9715
- const output = getGeneratedOutputWithContentPolicyHandling(response);
9716
- if (!output) {
9717
- throw new Error("Summarization output missing");
9718
- }
9765
+ }), void 0, context).catch((error) => {
9766
+ throw modelStepError(error, "Summary generation model call failed", { ...context });
9767
+ });
9768
+ const output = getGeneratedOutputWithContentPolicyHandling(response, context);
9719
9769
  const parsed = schema.parse(output);
9720
9770
  const unexpectedKeys = detectUnexpectedKeysFromRawText(
9721
9771
  response.text,
@@ -9738,6 +9788,7 @@ async function analyzeAudioOnly(provider, modelId, userPrompt, systemPrompt, des
9738
9788
  "use step";
9739
9789
  const model = await createLanguageModelFromConfig(provider, modelId, credentials);
9740
9790
  const schema = buildSummarySchema(descriptionLength);
9791
+ const context = { call: "generate_summary", provider, model: modelId };
9741
9792
  const response = await withContentPolicyAwareRetry(() => generateText8({
9742
9793
  model,
9743
9794
  maxRetries: 0,
@@ -9753,11 +9804,10 @@ async function analyzeAudioOnly(provider, modelId, userPrompt, systemPrompt, des
9753
9804
  content: userPrompt
9754
9805
  }
9755
9806
  ]
9756
- }));
9757
- const output = getGeneratedOutputWithContentPolicyHandling(response);
9758
- if (!output) {
9759
- throw new Error("Summarization output missing");
9760
- }
9807
+ }), void 0, context).catch((error) => {
9808
+ throw modelStepError(error, "Summary generation model call failed", { ...context });
9809
+ });
9810
+ const output = getGeneratedOutputWithContentPolicyHandling(response, context);
9761
9811
  const parsed = schema.parse(output);
9762
9812
  const unexpectedKeys = detectUnexpectedKeysFromRawText(
9763
9813
  response.text,
@@ -9828,10 +9878,12 @@ async function getSummaryAndTagsInternal(assetId, options, collectedUsage) {
9828
9878
  scope
9829
9879
  } = options ?? {};
9830
9880
  if (!VALID_TONES.includes(tone)) {
9831
- throw new LegacyMuxAiError(
9832
- `Invalid tone "${tone}". Valid tones are: ${VALID_TONES.join(", ")}.`,
9833
- { type: "validation_error" }
9834
- );
9881
+ throw new MuxAiError(`Invalid tone "${tone}". Valid tones are: ${VALID_TONES.join(", ")}.`, {
9882
+ code: MUX_AI_ERROR_CODES.INVALID_PARAMETER,
9883
+ type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR,
9884
+ source: MUX_AI_ERROR_SOURCES.REQUEST,
9885
+ facts: { parameter: "tone", reason: "not_allowed", allowed: [...VALID_TONES], value: String(tone).slice(0, 100), inputs: ["tone"] }
9886
+ });
9835
9887
  }
9836
9888
  const modelConfig = resolveLanguageModelConfig({
9837
9889
  ...options,
@@ -9839,7 +9891,7 @@ async function getSummaryAndTagsInternal(assetId, options, collectedUsage) {
9839
9891
  provider
9840
9892
  });
9841
9893
  const workflowCredentials = credentials;
9842
- const { asset: assetData, playbackId, policy } = await getPlaybackIdForAsset(assetId, workflowCredentials, options?.assetSnapshot);
9894
+ const { asset: assetData, playbackId, policy } = await getPlaybackIdForAsset(assetId, workflowCredentials, options?.assetSnapshot, { classifiedErrors: true });
9843
9895
  const assetDurationSeconds = getAssetDurationSecondsFromAsset(assetData);
9844
9896
  const isAudioOnly = isAudioOnlyAsset(assetData);
9845
9897
  const hasSceneContext = !isAudioOnly && Boolean(sceneContext?.length);
@@ -9847,24 +9899,27 @@ async function getSummaryAndTagsInternal(assetId, options, collectedUsage) {
9847
9899
  const storyboardScope = isAudioOnly ? void 0 : resolveRenderableVideoScope(
9848
9900
  effectiveScope,
9849
9901
  assetDurationSeconds,
9850
- getVideoTrackDurationSecondsFromAsset(assetData)
9902
+ getVideoTrackDurationSecondsFromAsset(assetData),
9903
+ { classifiedErrors: true, assetId }
9851
9904
  );
9852
9905
  if (isAudioOnly && effectiveScope) {
9853
- resolveWorkflowScope(effectiveScope, assetDurationSeconds);
9906
+ resolveWorkflowScope(effectiveScope, assetDurationSeconds, { classifiedErrors: true, assetId });
9854
9907
  }
9855
9908
  if (isAudioOnly && !includeTranscript) {
9856
- throw new LegacyMuxAiError(
9909
+ throw new MuxAiError(
9857
9910
  "Audio-only assets require a transcript. Set includeTranscript: true and ensure the asset has a ready text track (captions/subtitles).",
9858
- { type: "validation_error" }
9911
+ {
9912
+ code: MUX_AI_ERROR_CODES.INVALID_PARAMETER,
9913
+ type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR,
9914
+ source: MUX_AI_ERROR_SOURCES.REQUEST,
9915
+ facts: { parameter: "includeTranscript", reason: "audio_only", allowed: [true], value: false, assetId, inputs: ["includeTranscript"] }
9916
+ }
9859
9917
  );
9860
9918
  }
9861
9919
  const signingContext = await resolveMuxSigningContext(workflowCredentials);
9862
9920
  const requiresSignedPlaybackAccess = includeTranscript || !isAudioOnly;
9863
9921
  if (policy === "signed" && requiresSignedPlaybackAccess && !signingContext) {
9864
- throw new LegacyMuxAiError(
9865
- "Signed playback ID requires signing credentials. Set MUX_SIGNING_KEY and MUX_PRIVATE_KEY environment variables.",
9866
- { type: "validation_error" }
9867
- );
9922
+ throw signingCredentialsMissingError();
9868
9923
  }
9869
9924
  const transcriptResult = includeTranscript ? await fetchTranscriptForAsset(assetData, playbackId, {
9870
9925
  languageCode,
@@ -9872,7 +9927,8 @@ async function getSummaryAndTagsInternal(assetId, options, collectedUsage) {
9872
9927
  shouldSign: policy === "signed",
9873
9928
  credentials: workflowCredentials,
9874
9929
  required: isAudioOnly,
9875
- scope: effectiveScope
9930
+ scope: effectiveScope,
9931
+ classifiedErrors: true
9876
9932
  }) : void 0;
9877
9933
  const transcriptText = transcriptResult?.transcriptText ?? "";
9878
9934
  const resolvedLanguageCode = outputLanguageCode && outputLanguageCode !== "auto" ? outputLanguageCode : getReliableLanguageCode(transcriptResult?.track) ?? getReliableLanguageCode(getReadyTextTracks(assetData)[0]);
@@ -9889,69 +9945,51 @@ async function getSummaryAndTagsInternal(assetId, options, collectedUsage) {
9889
9945
  languageName,
9890
9946
  sceneContext: hasSceneContext ? sceneContext : void 0
9891
9947
  });
9892
- let analysisResponse;
9893
- let imageUrl;
9894
9948
  let systemPrompt = AUDIO_ONLY_SYSTEM_PROMPT3;
9895
9949
  if (!isAudioOnly) {
9896
9950
  systemPrompt = createVideoSystemPrompt(hasSceneContext);
9897
9951
  }
9898
9952
  const effectiveDescriptionLength = descriptionLength ?? DEFAULT_DESCRIPTION_LENGTH;
9899
- try {
9900
- if (isAudioOnly) {
9901
- analysisResponse = await analyzeAudioOnly(
9902
- modelConfig.provider,
9903
- modelConfig.modelId,
9904
- userPrompt,
9905
- systemPrompt,
9906
- effectiveDescriptionLength,
9907
- workflowCredentials
9908
- );
9909
- } else {
9910
- const storyboardUrl = await getStoryboardUrl(
9911
- playbackId,
9912
- 640,
9913
- policy === "signed",
9914
- workflowCredentials,
9915
- storyboardScope
9916
- );
9917
- imageUrl = storyboardUrl;
9918
- if (imageSubmissionMode === "base64") {
9919
- const downloadResult = await downloadImageAsBase64(storyboardUrl, imageDownloadOptions);
9920
- analysisResponse = await analyzeVideo(
9921
- downloadResult.base64Data,
9922
- modelConfig.provider,
9923
- modelConfig.modelId,
9924
- userPrompt,
9925
- systemPrompt,
9926
- effectiveDescriptionLength,
9927
- workflowCredentials
9928
- );
9929
- } else {
9930
- analysisResponse = await analyzeVideo(
9931
- storyboardUrl,
9932
- modelConfig.provider,
9933
- modelConfig.modelId,
9934
- userPrompt,
9935
- systemPrompt,
9936
- effectiveDescriptionLength,
9937
- workflowCredentials
9938
- );
9939
- }
9940
- }
9941
- } catch (error) {
9942
- const contentType = isAudioOnly ? "audio" : "video";
9943
- legacyWrapError(error, `Failed to analyze ${contentType} content with ${provider}`);
9953
+ let imageUrl;
9954
+ let imageInput;
9955
+ if (!isAudioOnly) {
9956
+ imageUrl = await getStoryboardUrl(
9957
+ playbackId,
9958
+ 640,
9959
+ policy === "signed",
9960
+ workflowCredentials,
9961
+ storyboardScope
9962
+ );
9963
+ imageInput = imageSubmissionMode === "base64" ? (await downloadImageAsBase64(imageUrl, imageDownloadOptions, { classifiedErrors: true, call: "fetch_storyboard" })).base64Data : imageUrl;
9944
9964
  }
9965
+ const modelFacts = { call: "generate_summary", provider: modelConfig.provider, model: modelConfig.modelId, assetId };
9966
+ const analysisResponse = await (isAudioOnly ? analyzeAudioOnly(
9967
+ modelConfig.provider,
9968
+ modelConfig.modelId,
9969
+ userPrompt,
9970
+ systemPrompt,
9971
+ effectiveDescriptionLength,
9972
+ workflowCredentials
9973
+ ) : analyzeVideo(
9974
+ imageInput,
9975
+ modelConfig.provider,
9976
+ modelConfig.modelId,
9977
+ userPrompt,
9978
+ systemPrompt,
9979
+ effectiveDescriptionLength,
9980
+ workflowCredentials
9981
+ )).catch((error) => wrapError(error, `Failed to analyze ${isAudioOnly ? "audio" : "video"} content with ${modelConfig.provider}`, modelFacts));
9945
9982
  collectedUsage.push(analysisResponse.usage);
9946
- if (!analysisResponse.result) {
9947
- const contentType = isAudioOnly ? "audio" : "video";
9948
- throw new LegacyMuxAiError(`Failed to analyze ${contentType} content for asset ${assetId}.`);
9949
- }
9950
- if (!analysisResponse.result.title) {
9951
- throw new LegacyMuxAiError(`Failed to generate title for asset ${assetId}.`);
9952
- }
9953
- if (!analysisResponse.result.description) {
9954
- throw new LegacyMuxAiError(`Failed to generate description for asset ${assetId}.`);
9983
+ for (const field of ["title", "description"]) {
9984
+ if (!analysisResponse.result[field]) {
9985
+ throw new MuxAiError(`Failed to generate ${field} for asset ${assetId}.`, {
9986
+ code: MUX_AI_ERROR_CODES.MODEL_OUTPUT_MISSING,
9987
+ type: MUX_AI_ERROR_TYPES.PROCESSING_ERROR,
9988
+ source: MUX_AI_ERROR_SOURCES.UPSTREAM,
9989
+ dependency: MUX_AI_ERROR_DEPENDENCIES.AI_PROVIDER,
9990
+ facts: { ...modelFacts, field }
9991
+ });
9992
+ }
9955
9993
  }
9956
9994
  const safety = createSafetyReporter();
9957
9995
  if (analysisResponse.unexpectedKeys.length > 0) {