@mux/ai 0.61.0 → 0.62.0-canary.97

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.
@@ -1,4 +1,4 @@
1
- export { am as ASK_QUESTIONS_DEFAULT_MAX_ANSWER_OPTION_LENGTH, an as ASK_QUESTIONS_DEFAULT_MAX_FREE_FORM_ANSWER_LENGTH, ao as ASK_QUESTIONS_MAX_QUESTIONS_PER_CALL, ap as ASK_QUESTIONS_MAX_QUESTION_LENGTH, aq as AskQuestionsOptions, ar as AskQuestionsResult, as as AskQuestionsType, at as AudioTranslationOptions, au as AudioTranslationResult, av as AutoCensorProfanityOptions, aw as BurnedInCaptionsAnalysis, ax as BurnedInCaptionsOptions, ay as BurnedInCaptionsPromptOverrides, az as BurnedInCaptionsPromptSections, aA as BurnedInCaptionsResult, aB as CaptionReplacement, aC as CensorMode, aD as Chapter, aE as ChapterSystemPromptSections, aF as ChaptersOptions, aG as ChaptersPromptOverrides, aH as ChaptersPromptSections, aI as ChaptersResult, aJ as ChaptersType, aK as DEFAULT_TRANSCRIPT_WINDOWING, aL as DubbedCaptionsOutcome, aM as EditCaptionsOptions, aN as EditCaptionsResult, aO as EmbeddingsOptions, aP as EmbeddingsResult, aQ as EngagementInsightsOptions, aR as EngagementInsightsResult, aS as GENERATE_TEXT_CALLS_TO_ACTION, aT as GENERATE_TEXT_CHANNELS, aU as GENERATE_TEXT_CHANNEL_CEILINGS, aV as GENERATE_TEXT_FORMATS, aW as GENERATE_TEXT_LENGTH_BOUNDS, aX as GENERATE_TEXT_MAX_ARTIFACTS, aY as GENERATE_TEXT_MAX_AUDIENCE_CHARS, aZ as GENERATE_TEXT_MAX_BRAND_TERMS, a_ as GENERATE_TEXT_MAX_BRAND_TERMS_TOTAL_CHARS, a$ as GENERATE_TEXT_MAX_BRAND_TERM_CHARS, b0 as GENERATE_TEXT_MAX_CONCURRENT_GENERATIONS, b1 as GENERATE_TEXT_MAX_INSTRUCTIONS_CHARS, b2 as GENERATE_TEXT_MAX_SHOT_FRAMES, b3 as GENERATE_TEXT_MAX_VARIANTS, b4 as GENERATE_TEXT_VOICES, b5 as GOOGLE_VISION_LIKELIHOOD_TO_SCORE, b6 as GenerateTextArtifact, b7 as GenerateTextCallToAction, b8 as GenerateTextChannel, b9 as GenerateTextFormat, ba as GenerateTextKeyedItem, bb as GenerateTextLengthLimit, bc as GenerateTextOptions, bd as GenerateTextResult, be as GenerateTextVariant, bf as GenerateTextVoice, bg as GeneratedTextArtifact, bh as GeneratedTextVariant, bi as HIVE_SEXUAL_CATEGORIES, bj as HIVE_VIOLENCE_CATEGORIES, bk as HiveModerationOutput, bl as HiveModerationSource, bm as ModerationOptions, bn as ModerationProvider, bo as ModerationResult, bp as ModerationSurfaceStatus, bq as MomentInsight, br as OverallInsight, bs as ProfanityDetectionPayload, bt as Question, bu as QuestionAnswer, bv as QuestionAnswerType, bw as RepairAttempt, bx as RepairCall, by as RepairOptions, bz as RepairPlan, bA as RepairResult, bB as RepairSpan, bC as ReplacementRecord, bD as SpeakerReplacement, bE as StaticRenditionCleanupOutcome, bF as SummarizationOptions, bG as SummarizationPromptOverrides, bH as SummarizationPromptSections, bI as SummaryAndTagsResult, bJ as SummaryType, bK as TextLengthLimit, bL as TextRepairModelOptions, bM as ThumbnailModerationScore, bN as ThumbnailModerationSkipReason, bO as ThumbnailModerationStatus, bP as TranscriptModerationScore, bQ as TranscriptModerationSkipReason, bR as TranscriptModerationStatus, bS as TranslationChunkingOptions, bT as TranslationOptions, bU as TranslationPayload, bV as TranslationResult, bW as aggregateTokenUsage, bX as applyOverrideLists, bY as applyReplacements, bZ as applySpeakerReplacements, b_ as applyTextRepair, b$ as askQuestions, c0 as buildReplacementRegex, c1 as buildTranscriptWindows, c2 as burnedInCaptionsSchema, c3 as censorVttContent, c4 as chapterSchema, c5 as chaptersSchema, c6 as createReplacer, c7 as createTextRepairGenerator, c8 as editCaptions, c9 as extractTranscriptSegmentsForHotspots, ca as findGenerateTextLengthViolation, cb as generateChapters, cc as generateEmbeddings, cd as generateEngagementInsights, ce as generateText, cf as generateVideoEmbeddings, cg as getModerationScores, ch as getSummaryAndTags, ci as hasBurnedInCaptions, cj as mapShotsToHotspots, ck as measureGenerateTextLength, cl as normalizeTranslatedVtt, cm as planTextRepair, cn as profanityDetectionSchema, co as questionAnswerSchema, cp as repairJsonSchema, cq as repairText, cr as resolveGenerateTextLengthLimit, cs as resolveGenerateTextLengthLimits, ct as resolveGenerateTextOptions, cu as runTextRepairLoop, cv as selectGenerateTextShotFrames, cw as shouldSplitChunkTranslationError, cx as summarySchema, cy as transformCueText, cz as translateAudio, cA as translateCaptions, cB as translationSchema, cC as validateNeverTranslateTerms, cD as verifyNeverTranslateTerms } from '../index-CnI9D5S0.js';
1
+ export { am as ASK_QUESTIONS_DEFAULT_MAX_ANSWER_OPTION_LENGTH, an as ASK_QUESTIONS_DEFAULT_MAX_FREE_FORM_ANSWER_LENGTH, ao as ASK_QUESTIONS_MAX_QUESTIONS_PER_CALL, ap as ASK_QUESTIONS_MAX_QUESTION_LENGTH, aq as AskQuestionsOptions, ar as AskQuestionsResult, as as AskQuestionsType, at as AudioTranslationOptions, au as AudioTranslationResult, av as AutoCensorProfanityOptions, aw as BurnedInCaptionsAnalysis, ax as BurnedInCaptionsOptions, ay as BurnedInCaptionsPromptOverrides, az as BurnedInCaptionsPromptSections, aA as BurnedInCaptionsResult, aB as CaptionReplacement, aC as CensorMode, aD as Chapter, aE as ChapterSystemPromptSections, aF as ChaptersOptions, aG as ChaptersPromptOverrides, aH as ChaptersPromptSections, aI as ChaptersResult, aJ as ChaptersType, aK as DEFAULT_TRANSCRIPT_WINDOWING, aL as DubbedCaptionsOutcome, aM as EditCaptionsOptions, aN as EditCaptionsResult, aO as EmbeddingsOptions, aP as EmbeddingsResult, aQ as EngagementInsightsOptions, aR as EngagementInsightsResult, aS as GENERATE_TEXT_CALLS_TO_ACTION, aT as GENERATE_TEXT_CHANNELS, aU as GENERATE_TEXT_CHANNEL_CEILINGS, aV as GENERATE_TEXT_FORMATS, aW as GENERATE_TEXT_LENGTH_BOUNDS, aX as GENERATE_TEXT_MAX_ARTIFACTS, aY as GENERATE_TEXT_MAX_AUDIENCE_CHARS, aZ as GENERATE_TEXT_MAX_BRAND_TERMS, a_ as GENERATE_TEXT_MAX_BRAND_TERMS_TOTAL_CHARS, a$ as GENERATE_TEXT_MAX_BRAND_TERM_CHARS, b0 as GENERATE_TEXT_MAX_CONCURRENT_GENERATIONS, b1 as GENERATE_TEXT_MAX_INSTRUCTIONS_CHARS, b2 as GENERATE_TEXT_MAX_SHOT_FRAMES, b3 as GENERATE_TEXT_MAX_VARIANTS, b4 as GENERATE_TEXT_VOICES, b5 as GOOGLE_VISION_LIKELIHOOD_TO_SCORE, b6 as GenerateTextArtifact, b7 as GenerateTextCallToAction, b8 as GenerateTextChannel, b9 as GenerateTextFormat, ba as GenerateTextKeyedItem, bb as GenerateTextLengthLimit, bc as GenerateTextOptions, bd as GenerateTextResult, be as GenerateTextVariant, bf as GenerateTextVoice, bg as GeneratedTextArtifact, bh as GeneratedTextVariant, bi as HIVE_SEXUAL_CATEGORIES, bj as HIVE_VIOLENCE_CATEGORIES, bk as HiveModerationOutput, bl as HiveModerationSource, bm as ModerationOptions, bn as ModerationProvider, bo as ModerationResult, bp as ModerationSurfaceStatus, bq as MomentInsight, br as OverallInsight, bs as ProfanityDetectionPayload, bt as Question, bu as QuestionAnswer, bv as QuestionAnswerType, bw as RepairAttempt, bx as RepairCall, by as RepairOptions, bz as RepairPlan, bA as RepairResult, bB as RepairSpan, bC as ReplacementRecord, bD as SpeakerReplacement, bE as StaticRenditionCleanupOutcome, bF as SummarizationOptions, bG as SummarizationPromptOverrides, bH as SummarizationPromptSections, bI as SummaryAndTagsResult, bJ as SummaryType, bK as TextLengthLimit, bL as TextRepairModelOptions, bM as ThumbnailModerationScore, bN as ThumbnailModerationSkipReason, bO as ThumbnailModerationStatus, bP as TranscriptModerationScore, bQ as TranscriptModerationSkipReason, bR as TranscriptModerationStatus, bS as TranslationChunkingOptions, bT as TranslationOptions, bU as TranslationPayload, bV as TranslationResult, bW as aggregateTokenUsage, bX as applyOverrideLists, bY as applyReplacements, bZ as applySpeakerReplacements, b_ as applyTextRepair, b$ as askQuestions, c0 as buildReplacementRegex, c1 as buildTranscriptWindows, c2 as burnedInCaptionsSchema, c3 as censorVttContent, c4 as chapterSchema, c5 as chaptersSchema, c6 as createReplacer, c7 as createTextRepairGenerator, c8 as editCaptions, c9 as extractTranscriptSegmentsForHotspots, ca as findGenerateTextLengthViolation, cb as generateChapters, cc as generateEmbeddings, cd as generateEngagementInsights, ce as generateText, cf as generateVideoEmbeddings, cg as getModerationScores, ch as getSummaryAndTags, ci as hasBurnedInCaptions, cj as mapShotsToHotspots, ck as measureGenerateTextLength, cl as normalizeTranslatedVtt, cm as planTextRepair, cn as profanityDetectionSchema, co as questionAnswerSchema, cp as repairJsonSchema, cq as repairText, cr as resolveGenerateTextLengthLimit, cs as resolveGenerateTextLengthLimits, ct as resolveGenerateTextOptions, cu as runTextRepairLoop, cv as selectGenerateTextShotFrames, cw as shouldSplitChunkTranslationError, cx as summarySchema, cy as transformCueText, cz as translateAudio, cA as translateCaptions, cB as translationSchema, cC as validateNeverTranslateTerms, cD as verifyNeverTranslateTerms } from '../index-BN5yOn9o.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
4
  import '../transcripts-DuNI058z.js';
@@ -628,7 +628,17 @@ var MUX_AI_ERROR_CODES = {
628
628
  /** The dubbing provider doesn't support the requested language. Facts: `language` and `which` (`target` or `source`). */
629
629
  DUBBING_LANGUAGE_UNSUPPORTED: "dubbing_language_unsupported",
630
630
  /** The dubbing provider ran the dub and reported it failed. Facts: `providerError`, the provider's display text, when it gave one. */
631
- DUBBING_FAILED: "dubbing_failed"
631
+ DUBBING_FAILED: "dubbing_failed",
632
+ /** The dubbing provider didn't finish the dub within the polling budget. Facts: `dubbingId`, `timeoutSeconds`, `lastStatus`. */
633
+ DUBBING_TIMEOUT: "dubbing_timeout",
634
+ /** The asset has no audio track, so there is no audio to work with. Facts: `assetId`. */
635
+ AUDIO_TRACK_MISSING: "audio_track_missing",
636
+ /** Writing an audio track would replace the asset's primary audio track, which can't be replaced. Facts: `languageCode`, `conflictingTracks`. */
637
+ PRIMARY_AUDIO_TRACK_CONFLICT: "primary_audio_track_conflict",
638
+ /** The asset's static rendition settings changed while waiting for its rendition. A new job uses the new settings. Facts: `assetId`. */
639
+ STATIC_RENDITION_CHANGED: "static_rendition_changed",
640
+ /** Mux didn't finish the static rendition within the polling budget. Facts: `assetId`, `attempts`, `pollIntervalMs`, `lastStatus`. */
641
+ STATIC_RENDITION_TIMEOUT: "static_rendition_timeout"
632
642
  };
633
643
  var MUX_AI_ERROR_CODE_VALUES = Object.values(MUX_AI_ERROR_CODES);
634
644
  var MUX_AI_ERROR_CATALOG = {
@@ -664,8 +674,8 @@ var MUX_AI_ERROR_CATALOG = {
664
674
  [MUX_AI_ERROR_CODES.MODEL_OUTPUT_MISSING]: { type: MUX_AI_ERROR_TYPES.PROCESSING_ERROR, source: MUX_AI_ERROR_SOURCES.UPSTREAM, dependency: MUX_AI_ERROR_DEPENDENCIES.AI_PROVIDER, transient: false, retryable: false },
665
675
  [MUX_AI_ERROR_CODES.MODEL_OUTPUT_INVALID]: { type: MUX_AI_ERROR_TYPES.PROCESSING_ERROR, source: MUX_AI_ERROR_SOURCES.UPSTREAM, dependency: MUX_AI_ERROR_DEPENDENCIES.AI_PROVIDER, transient: false, retryable: false },
666
676
  [MUX_AI_ERROR_CODES.MODEL_OUTPUT_SUPPRESSED]: { type: MUX_AI_ERROR_TYPES.PROCESSING_ERROR, source: MUX_AI_ERROR_SOURCES.UPSTREAM, dependency: MUX_AI_ERROR_DEPENDENCIES.AI_PROVIDER, transient: false, retryable: false },
667
- // Not transient: a step retry would repeat a full generation; the job can be resubmitted.
668
- [MUX_AI_ERROR_CODES.MODEL_OUTPUT_INCOMPLETE]: { type: MUX_AI_ERROR_TYPES.PROCESSING_ERROR, source: MUX_AI_ERROR_SOURCES.UPSTREAM, dependency: MUX_AI_ERROR_DEPENDENCIES.AI_PROVIDER, transient: false },
677
+ // Not transient: a step retry would repeat a full generation. Retryable: the job can be resubmitted.
678
+ [MUX_AI_ERROR_CODES.MODEL_OUTPUT_INCOMPLETE]: { type: MUX_AI_ERROR_TYPES.PROCESSING_ERROR, source: MUX_AI_ERROR_SOURCES.UPSTREAM, dependency: MUX_AI_ERROR_DEPENDENCIES.AI_PROVIDER, transient: false, retryable: true },
669
679
  [MUX_AI_ERROR_CODES.MODEL_OUTPUT_TRUNCATED]: { type: MUX_AI_ERROR_TYPES.PROCESSING_ERROR, source: MUX_AI_ERROR_SOURCES.INTERNAL, dependency: MUX_AI_ERROR_DEPENDENCIES.AI_PROVIDER },
670
680
  // Mux Video.
671
681
  // Reported by Mux: a step retry would find the same errored rendition, and resubmitting the same asset errors again.
@@ -673,7 +683,16 @@ var MUX_AI_ERROR_CATALOG = {
673
683
  // Audio dubbing.
674
684
  [MUX_AI_ERROR_CODES.DUBBING_LANGUAGE_UNSUPPORTED]: { type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR, source: MUX_AI_ERROR_SOURCES.REQUEST, dependency: MUX_AI_ERROR_DEPENDENCIES.AI_PROVIDER },
675
685
  // Reported by the dubbing provider: a step retry would find the same failed dub.
676
- [MUX_AI_ERROR_CODES.DUBBING_FAILED]: { type: MUX_AI_ERROR_TYPES.PROCESSING_ERROR, source: MUX_AI_ERROR_SOURCES.UPSTREAM, dependency: MUX_AI_ERROR_DEPENDENCIES.AI_PROVIDER, transient: false }
686
+ // Retryable by default; each failure sets it from the provider's report.
687
+ [MUX_AI_ERROR_CODES.DUBBING_FAILED]: { type: MUX_AI_ERROR_TYPES.PROCESSING_ERROR, source: MUX_AI_ERROR_SOURCES.UPSTREAM, dependency: MUX_AI_ERROR_DEPENDENCIES.AI_PROVIDER, transient: false, retryable: true },
688
+ // Polling timeouts: not transient, since the whole polling budget was already spent,
689
+ // but retryable, since a later attempt may finish in time.
690
+ [MUX_AI_ERROR_CODES.DUBBING_TIMEOUT]: { type: MUX_AI_ERROR_TYPES.TIMEOUT_ERROR, source: MUX_AI_ERROR_SOURCES.UPSTREAM, dependency: MUX_AI_ERROR_DEPENDENCIES.AI_PROVIDER, transient: false, retryable: true },
691
+ [MUX_AI_ERROR_CODES.STATIC_RENDITION_TIMEOUT]: { type: MUX_AI_ERROR_TYPES.TIMEOUT_ERROR, source: MUX_AI_ERROR_SOURCES.UPSTREAM, dependency: MUX_AI_ERROR_DEPENDENCIES.MUX_VIDEO, transient: false, retryable: true },
692
+ [MUX_AI_ERROR_CODES.AUDIO_TRACK_MISSING]: { type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR, source: MUX_AI_ERROR_SOURCES.ASSET },
693
+ [MUX_AI_ERROR_CODES.PRIMARY_AUDIO_TRACK_CONFLICT]: { type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR, source: MUX_AI_ERROR_SOURCES.ASSET },
694
+ // Retryable although asset-sourced: the asset changed mid-run, and a new job uses the new settings.
695
+ [MUX_AI_ERROR_CODES.STATIC_RENDITION_CHANGED]: { type: MUX_AI_ERROR_TYPES.PROCESSING_ERROR, source: MUX_AI_ERROR_SOURCES.ASSET, retryable: true }
677
696
  };
678
697
  function isTransientStatus(status) {
679
698
  return status === void 0 || status === 408 || status === 425 || status === 429 || status >= 500;
@@ -5179,13 +5198,6 @@ function planTextTrackReplacement(asset, target, policy) {
5179
5198
  tracks: tracks.map(summarizeTextTrack),
5180
5199
  conflictsOnLanguage: tracks.some((track) => sameLanguageIds.has(track.id))
5181
5200
  });
5182
- if (policy === "fail") {
5183
- return blocked(
5184
- "policy_fail",
5185
- `${countTracks(conflicting, label, "already exists", "already exist")} for language '${target.languageCode}' or name '${target.name}': ${describeTracks(conflicting)}. Set replaceExistingTracks to replace ${itOrThem(conflicting)}.`,
5186
- conflicting
5187
- );
5188
- }
5189
5201
  const primary = conflicting.filter((track) => track.type === "audio" && track.primary === true);
5190
5202
  if (primary.length > 0) {
5191
5203
  return blocked(
@@ -5194,6 +5206,13 @@ function planTextTrackReplacement(asset, target, policy) {
5194
5206
  primary
5195
5207
  );
5196
5208
  }
5209
+ if (policy === "fail") {
5210
+ return blocked(
5211
+ "policy_fail",
5212
+ `${countTracks(conflicting, label, "already exists", "already exist")} for language '${target.languageCode}' or name '${target.name}': ${describeTracks(conflicting)}. Set replaceExistingTracks to replace ${itOrThem(conflicting)}.`,
5213
+ conflicting
5214
+ );
5215
+ }
5197
5216
  if (policy === "replace_generated") {
5198
5217
  const notGenerated = conflicting.filter((track) => track.type !== "text" || !isMuxGeneratedTextTrack(track));
5199
5218
  if (notGenerated.length > 0) {
@@ -5268,6 +5287,7 @@ function trackReplacementBlockedError(blocked, options = {}) {
5268
5287
  };
5269
5288
  if (blocked.code === "primary_audio" && blocked.conflictsOnLanguage) {
5270
5289
  return new MuxAiError(message, {
5290
+ code: MUX_AI_ERROR_CODES.PRIMARY_AUDIO_TRACK_CONFLICT,
5271
5291
  type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR,
5272
5292
  source: MUX_AI_ERROR_SOURCES.ASSET,
5273
5293
  facts
@@ -9859,17 +9879,34 @@ import { sleep } from "workflow";
9859
9879
  // src/lib/elevenlabs-errors.ts
9860
9880
  var MAX_ERROR_BODY_CHARS = 500;
9861
9881
  function isRetryableElevenLabsStatus(status) {
9862
- return status === 408 || status === 425 || status === 429 || status >= 500;
9882
+ return isTransientStatus(status);
9883
+ }
9884
+ function elevenLabsFailureError(message, call, failure, facts) {
9885
+ return dependencyError(message, {
9886
+ dependency: MUX_AI_ERROR_DEPENDENCIES.AI_PROVIDER,
9887
+ call,
9888
+ status: failure.httpStatus,
9889
+ requestId: failure.requestId,
9890
+ timedOut: failure.reason === "timeout",
9891
+ facts: {
9892
+ provider: "elevenlabs",
9893
+ ...failure.reason && { providerCode: failure.reason },
9894
+ ...failure.detail && { detail: errorDetailFact(failure.detail) },
9895
+ ...facts
9896
+ },
9897
+ transient: false,
9898
+ retryable: failure.retryable
9899
+ });
9863
9900
  }
9864
9901
  async function elevenLabsResponseFailure(response) {
9865
9902
  const body = await response.text().catch(() => "");
9866
- return httpFailure(response.status, response.statusText, body);
9903
+ return httpFailure(response.status, response.statusText, body, response.headers);
9867
9904
  }
9868
9905
  function elevenLabsSdkFailure(error) {
9869
9906
  const failure = error;
9870
9907
  if (typeof failure?.statusCode === "number") {
9871
9908
  const body = typeof failure.body === "string" ? failure.body : JSON.stringify(failure.body ?? "");
9872
- return httpFailure(failure.statusCode, failure.rawResponse?.statusText, body);
9909
+ return httpFailure(failure.statusCode, failure.rawResponse?.statusText, body, failure.rawResponse?.headers);
9873
9910
  }
9874
9911
  const message = failure?.message ?? String(error);
9875
9912
  switch (failure?.name) {
@@ -9886,12 +9923,14 @@ function elevenLabsSdkFailure(error) {
9886
9923
  return { retryable: false, detail: message };
9887
9924
  }
9888
9925
  }
9889
- function httpFailure(status, statusText, body) {
9926
+ function httpFailure(status, statusText, body, headers) {
9890
9927
  const statusLine = [status, statusText].filter(Boolean).join(" ");
9891
- const { reason, detail } = parseElevenLabsErrorBody(body);
9928
+ const { reason, detail, requestId } = parseElevenLabsErrorBody(body);
9929
+ const responseRequestId = requestId ?? requestIdOf(headers);
9892
9930
  return {
9893
9931
  httpStatus: status,
9894
9932
  reason,
9933
+ ...responseRequestId && { requestId: responseRequestId },
9895
9934
  retryable: isRetryableElevenLabsStatus(status),
9896
9935
  detail: detail ? `${statusLine}: ${detail}` : statusLine
9897
9936
  };
@@ -9921,7 +9960,11 @@ function parseElevenLabsErrorBody(body) {
9921
9960
  const reasonText = [reasonCode, message].filter(Boolean).join(": ");
9922
9961
  const context = [param && `param: ${param}`, requestId && `request_id: ${requestId}`].filter(Boolean).join(", ");
9923
9962
  if (reasonText) {
9924
- return { reason: reasonCode, detail: context ? `${reasonText} (${context})` : reasonText };
9963
+ return {
9964
+ reason: reasonCode,
9965
+ detail: context ? `${reasonText} (${context})` : reasonText,
9966
+ ...typeof requestId === "string" && requestId && { requestId }
9967
+ };
9925
9968
  }
9926
9969
  }
9927
9970
  return { detail: trimmed.slice(0, MAX_ERROR_BODY_CHARS) };
@@ -10029,7 +10072,7 @@ async function requestStaticRenditionCreation(assetId, credentials) {
10029
10072
  if (statusCode === 409 || alreadyDefined) {
10030
10073
  return void 0;
10031
10074
  }
10032
- legacyWrapError(error, "Failed to request static rendition from Mux");
10075
+ throw muxVideoCallError("Failed to request static rendition from Mux", "create_static_rendition", error, { assetId });
10033
10076
  }
10034
10077
  }
10035
10078
  async function deleteCreatedStaticRendition(assetId, staticRenditionId, credentials) {
@@ -10057,7 +10100,11 @@ async function retrieveAsset(assetId, credentials) {
10057
10100
  "use step";
10058
10101
  const muxClient = await resolveMuxClient(credentials);
10059
10102
  const mux = await muxClient.createClient();
10060
- return mux.video.assets.retrieve(assetId);
10103
+ try {
10104
+ return await mux.video.assets.retrieve(assetId);
10105
+ } catch (error) {
10106
+ throw muxVideoCallError("Failed to fetch the asset from Mux", "get_asset", error, { assetId });
10107
+ }
10061
10108
  }
10062
10109
  async function waitForAudioStaticRendition({
10063
10110
  assetId,
@@ -10079,14 +10126,36 @@ async function waitForAudioStaticRendition({
10079
10126
  `\u231B Waiting for static rendition (attempt ${attempt}/${STATIC_RENDITION_MAX_ATTEMPTS}) \u2192 ${currentStatus}`
10080
10127
  );
10081
10128
  if (currentStatus === "errored") {
10082
- throw new LegacyMuxAiError(
10083
- "Mux failed to create the static rendition for this asset. Please check the asset in the Mux dashboard."
10129
+ throw new MuxAiError(
10130
+ "Mux failed to create the static rendition for this asset. Please check the asset in the Mux dashboard.",
10131
+ {
10132
+ code: MUX_AI_ERROR_CODES.STATIC_RENDITION_FAILED,
10133
+ type: MUX_AI_ERROR_TYPES.PROCESSING_ERROR,
10134
+ source: MUX_AI_ERROR_SOURCES.UPSTREAM,
10135
+ dependency: MUX_AI_ERROR_DEPENDENCIES.MUX_VIDEO,
10136
+ facts: { call: "get_asset", assetId, renditionStatus: currentStatus }
10137
+ }
10084
10138
  );
10085
10139
  }
10086
10140
  }
10087
- throw new LegacyMuxAiError(
10141
+ throw new MuxAiError(
10088
10142
  "Timed out waiting for the static rendition to become ready. Please try again in a moment.",
10089
- { type: "timeout_error", retryable: true }
10143
+ {
10144
+ // Mux didn't finish the rendition in time; the asset itself is fine.
10145
+ code: MUX_AI_ERROR_CODES.STATIC_RENDITION_TIMEOUT,
10146
+ type: MUX_AI_ERROR_TYPES.TIMEOUT_ERROR,
10147
+ source: MUX_AI_ERROR_SOURCES.UPSTREAM,
10148
+ dependency: MUX_AI_ERROR_DEPENDENCIES.MUX_VIDEO,
10149
+ facts: {
10150
+ call: "get_asset",
10151
+ assetId,
10152
+ attempts: STATIC_RENDITION_MAX_ATTEMPTS,
10153
+ pollIntervalMs: STATIC_RENDITION_POLL_INTERVAL_MS,
10154
+ lastStatus: getAudioStaticRenditionStatus(currentAsset)
10155
+ },
10156
+ // Not transient: this already polled for the whole budget.
10157
+ transient: false
10158
+ }
10090
10159
  );
10091
10160
  }
10092
10161
  async function waitForLegacyMp4SupportRendition({
@@ -10103,23 +10172,48 @@ async function waitForLegacyMp4SupportRendition({
10103
10172
  rendition = resolveLegacyMp4SupportRendition(await retrieveAsset(assetId, credentials));
10104
10173
  }
10105
10174
  if (!rendition) {
10106
- throw new LegacyMuxAiError(
10175
+ throw new MuxAiError(
10107
10176
  "The asset's static rendition settings changed while waiting for them. Please try again.",
10108
- { type: "processing_error", retryable: true }
10177
+ {
10178
+ code: MUX_AI_ERROR_CODES.STATIC_RENDITION_CHANGED,
10179
+ type: MUX_AI_ERROR_TYPES.PROCESSING_ERROR,
10180
+ source: MUX_AI_ERROR_SOURCES.ASSET,
10181
+ facts: { assetId },
10182
+ // Retryable although asset-sourced: the asset changed mid-run, and a new job uses the new settings.
10183
+ retryable: true
10184
+ }
10109
10185
  );
10110
10186
  }
10111
10187
  if (rendition.kind === "preparing") {
10112
- throw new LegacyMuxAiError(
10188
+ throw new MuxAiError(
10113
10189
  "Timed out waiting for the static rendition to become ready. Please try again in a moment.",
10114
- { type: "timeout_error", retryable: true }
10190
+ {
10191
+ code: MUX_AI_ERROR_CODES.STATIC_RENDITION_TIMEOUT,
10192
+ type: MUX_AI_ERROR_TYPES.TIMEOUT_ERROR,
10193
+ source: MUX_AI_ERROR_SOURCES.UPSTREAM,
10194
+ dependency: MUX_AI_ERROR_DEPENDENCIES.MUX_VIDEO,
10195
+ facts: { call: "get_asset", assetId, attempts: STATIC_RENDITION_MAX_ATTEMPTS, pollIntervalMs: STATIC_RENDITION_POLL_INTERVAL_MS },
10196
+ // Not transient: this already polled for the whole budget.
10197
+ transient: false
10198
+ }
10115
10199
  );
10116
10200
  }
10117
10201
  if (rendition.kind === "unusable") {
10118
- throw new LegacyMuxAiError(rendition.reason, { type: "validation_error" });
10202
+ throw new MuxAiError(rendition.reason, {
10203
+ code: MUX_AI_ERROR_CODES.STATIC_RENDITION_UNSUPPORTED,
10204
+ type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR,
10205
+ source: MUX_AI_ERROR_SOURCES.ASSET,
10206
+ facts: { reason: "unusable", assetId, mp4Support: rendition.mp4Support, ...rendition.status && { renditionStatus: rendition.status } }
10207
+ });
10119
10208
  }
10120
10209
  const sizeError = getLegacyMp4SupportRenditionSizeError(rendition, MAX_DUBBING_SOURCE_BYTES);
10121
10210
  if (sizeError) {
10122
- throw new LegacyMuxAiError(sizeError, { type: "validation_error" });
10211
+ throw new MuxAiError(sizeError, {
10212
+ code: MUX_AI_ERROR_CODES.STATIC_RENDITION_UNSUPPORTED,
10213
+ type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR,
10214
+ source: MUX_AI_ERROR_SOURCES.ASSET,
10215
+ facts: { reason: "too_large", assetId, renditionName: rendition.name, sizeBytes: rendition.filesizeBytes, maxBytes: MAX_DUBBING_SOURCE_BYTES }
10216
+ });
10123
10217
  }
10124
10218
  return rendition.name;
10125
10219
  }
@@ -10129,33 +10223,49 @@ function toBaseLanguageCode(code) {
10129
10223
  function audioTrackUnsupportedReason(asset) {
10130
10224
  const useDubbedFile = "skip uploading to Mux and use the dubbed audio file directly.";
10131
10225
  if (asset.ingest_type === "on_demand_clip" || asset.source_asset_id) {
10132
- return `is a clip, and Mux does not support adding audio tracks to clipped assets. Dub the source asset instead, or ${useDubbedFile}`;
10226
+ return { reason: "clip", message: `is a clip, and Mux does not support adding audio tracks to clipped assets. Dub the source asset instead, or ${useDubbedFile}` };
10133
10227
  }
10134
10228
  if (asset.is_live || asset.live_stream_id) {
10135
- return `comes from a live stream, and Mux does not support adding audio tracks to live stream assets. Instead, ${useDubbedFile}`;
10229
+ return { reason: "live_stream", message: `comes from a live stream, and Mux does not support adding audio tracks to live stream assets. Instead, ${useDubbedFile}` };
10136
10230
  }
10137
10231
  if (isAudioOnlyAsset(asset)) {
10138
- return `is audio-only, and Mux does not support adding audio tracks to audio-only assets. Instead, ${useDubbedFile}`;
10232
+ return { reason: "audio_only", message: `is audio-only, and Mux does not support adding audio tracks to audio-only assets. Instead, ${useDubbedFile}` };
10139
10233
  }
10140
10234
  return void 0;
10141
10235
  }
10142
- function dubbingProviderError(message, failure) {
10143
- if (failure.reason === "timeout") {
10144
- return new LegacyMuxAiError(`${message} The dubbing service timed out. Please try again.`, { type: "timeout_error", retryable: true });
10145
- }
10146
- if (failure.retryable) {
10147
- return new LegacyMuxAiError(`${message} The dubbing service is temporarily unavailable. Please try again.`, { type: "processing_error", retryable: true });
10148
- }
10149
- return new LegacyMuxAiError(message, { type: "processing_error" });
10236
+ function dubbingProviderError(message, call, failure, facts) {
10237
+ const detailed = failure.reason === "timeout" ? `${message} The dubbing service timed out. Please try again.` : failure.retryable ? `${message} The dubbing service is temporarily unavailable. Please try again.` : message;
10238
+ return elevenLabsFailureError(detailed, call, failure, facts);
10150
10239
  }
10151
- function dubbingStartError(failure, languages) {
10152
- if (failure.reason === "unsupported_target_language") {
10153
- return new LegacyMuxAiError(`Audio dubbing does not support the target language "${languages.target}".`, { type: "validation_error" });
10154
- }
10155
- if (failure.reason === "unsupported_source_language" && languages.source) {
10156
- return new LegacyMuxAiError(`Audio dubbing does not support the source language "${languages.source}".`, { type: "validation_error" });
10240
+ function dubbingStartError(failure, languages, facts) {
10241
+ const call = "elevenlabs_create_dubbing_project";
10242
+ const unsupported = failure.reason === "unsupported_target_language" ? { language: languages.target, which: "target" } : failure.reason === "unsupported_source_language" && languages.source ? { language: languages.source, which: "source" } : void 0;
10243
+ if (unsupported) {
10244
+ return new MuxAiError(`Audio dubbing does not support the ${unsupported.which} language "${unsupported.language}".`, {
10245
+ code: MUX_AI_ERROR_CODES.DUBBING_LANGUAGE_UNSUPPORTED,
10246
+ type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR,
10247
+ source: MUX_AI_ERROR_SOURCES.REQUEST,
10248
+ dependency: MUX_AI_ERROR_DEPENDENCIES.AI_PROVIDER,
10249
+ facts: {
10250
+ language: unsupported.language,
10251
+ which: unsupported.which,
10252
+ call,
10253
+ provider: "elevenlabs",
10254
+ ...failure.httpStatus !== void 0 && { status: failure.httpStatus },
10255
+ ...failure.requestId && { requestId: failure.requestId },
10256
+ providerCode: failure.reason,
10257
+ ...facts
10258
+ }
10259
+ });
10157
10260
  }
10158
- return dubbingProviderError("Audio dubbing could not be started.", failure);
10261
+ return dubbingProviderError("Audio dubbing could not be started.", call, failure, facts);
10262
+ }
10263
+ function stagedAudioFacts(presignedUrl, bucket) {
10264
+ const key = presignedUrl?.split("?")[0].match(/audio-translations\/[^?#]+$/)?.[0];
10265
+ return {
10266
+ ...bucket && { stagedAudioBucket: bucket },
10267
+ ...key && { stagedAudioKey: key }
10268
+ };
10159
10269
  }
10160
10270
  async function createElevenLabsDubbingJob({
10161
10271
  sourceUrl,
@@ -10388,15 +10498,25 @@ async function translateAudio(assetId, toLanguageCode, options = {}) {
10388
10498
  trackPassthrough: providedTrackPassthrough
10389
10499
  } = options;
10390
10500
  if (provider !== "elevenlabs") {
10391
- throw new LegacyMuxAiError("Only ElevenLabs provider is currently supported for audio translation.", { type: "validation_error" });
10501
+ throw new MuxAiError("Only ElevenLabs provider is currently supported for audio translation.", {
10502
+ code: MUX_AI_ERROR_CODES.INVALID_PARAMETER,
10503
+ type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR,
10504
+ source: MUX_AI_ERROR_SOURCES.REQUEST,
10505
+ facts: { parameter: "provider", reason: "not_allowed", allowed: ["elevenlabs"], value: String(provider).slice(0, 100), inputs: ["provider"] }
10506
+ });
10392
10507
  }
10393
10508
  const targetLanguageCode = toISO639_1(toLanguageCode);
10394
10509
  if (numSpeakers !== 0) {
10395
- throw new LegacyMuxAiError("The ElevenLabs project API does not support numSpeakers overrides. Omit it or use 0 for auto-detection.", { type: "validation_error" });
10510
+ throw new MuxAiError("The ElevenLabs project API does not support numSpeakers overrides. Omit it or use 0 for auto-detection.", {
10511
+ code: MUX_AI_ERROR_CODES.INVALID_PARAMETER,
10512
+ type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR,
10513
+ source: MUX_AI_ERROR_SOURCES.REQUEST,
10514
+ facts: { parameter: "numSpeakers", reason: "not_allowed", allowed: [0], value: numSpeakers, inputs: ["numSpeakers"] }
10515
+ });
10396
10516
  }
10397
10517
  const credentials = providedCredentials;
10398
10518
  const effectiveStorageAdapter = storageAdapter;
10399
- const trackPassthrough = validateTrackPassthrough(providedTrackPassthrough) ?? buildMuxAiTrackPassthrough("translate-audio");
10519
+ const trackPassthrough = validateTrackPassthrough(providedTrackPassthrough, { classifiedErrors: true }) ?? buildMuxAiTrackPassthrough("translate-audio");
10400
10520
  const uploadToMux = uploadToMuxOption !== false;
10401
10521
  const uploadToS3 = uploadToS3Option || uploadToMux || uploadCaptionsToMux;
10402
10522
  const muxLangCode = targetLanguageCode;
@@ -10408,22 +10528,40 @@ async function translateAudio(assetId, toLanguageCode, options = {}) {
10408
10528
  const s3Bucket = options.s3Bucket ?? env_default.S3_BUCKET;
10409
10529
  const s3AccessKeyId = env_default.S3_ACCESS_KEY_ID;
10410
10530
  const s3SecretAccessKey = env_default.S3_SECRET_ACCESS_KEY;
10411
- if (uploadToS3 && (!s3Endpoint || !s3Bucket || !effectiveStorageAdapter && (!s3AccessKeyId || !s3SecretAccessKey))) {
10412
- throw new LegacyMuxAiError("Storage configuration is required for uploading. Provide s3Endpoint and s3Bucket. If no storageAdapter is supplied, also provide s3AccessKeyId and s3SecretAccessKey in options or set S3_ENDPOINT, S3_BUCKET, S3_ACCESS_KEY_ID, and S3_SECRET_ACCESS_KEY environment variables.", { type: "validation_error" });
10531
+ if (uploadToS3) {
10532
+ const missing = [
10533
+ ...s3Endpoint ? [] : ["s3Endpoint"],
10534
+ ...s3Bucket ? [] : ["s3Bucket"],
10535
+ ...effectiveStorageAdapter || s3AccessKeyId ? [] : ["S3_ACCESS_KEY_ID"],
10536
+ ...effectiveStorageAdapter || s3SecretAccessKey ? [] : ["S3_SECRET_ACCESS_KEY"]
10537
+ ];
10538
+ if (missing.length > 0) {
10539
+ throw storageNotConfiguredError(missing);
10540
+ }
10413
10541
  }
10414
- const { asset: initialAsset, playbackId, policy } = await getPlaybackIdForAsset(assetId, credentials, options.assetSnapshot);
10542
+ const { asset: initialAsset, playbackId, policy } = await getPlaybackIdForAsset(assetId, credentials, options.assetSnapshot, { classifiedErrors: true });
10415
10543
  const assetDurationSeconds = getAssetDurationSecondsFromAsset(initialAsset);
10416
10544
  if (isVideoOnlyAsset(initialAsset)) {
10417
- throw new LegacyMuxAiError(`Asset ${assetId} has no audio track, so there is no audio to dub.`, { type: "validation_error" });
10545
+ throw new MuxAiError(`Asset ${assetId} has no audio track, so there is no audio to dub.`, {
10546
+ code: MUX_AI_ERROR_CODES.AUDIO_TRACK_MISSING,
10547
+ type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR,
10548
+ source: MUX_AI_ERROR_SOURCES.ASSET,
10549
+ facts: { assetId }
10550
+ });
10418
10551
  }
10419
10552
  const audioTrackUnsupported = uploadToMux ? audioTrackUnsupportedReason(initialAsset) : void 0;
10420
10553
  if (audioTrackUnsupported) {
10421
- throw new LegacyMuxAiError(`Asset ${assetId} ${audioTrackUnsupported}`, { type: "validation_error" });
10554
+ throw new MuxAiError(`Asset ${assetId} ${audioTrackUnsupported.message}`, {
10555
+ code: MUX_AI_ERROR_CODES.AUDIO_TRACK_UNSUPPORTED,
10556
+ type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR,
10557
+ source: MUX_AI_ERROR_SOURCES.ASSET,
10558
+ facts: { assetId, reason: audioTrackUnsupported.reason }
10559
+ });
10422
10560
  }
10423
10561
  if (uploadToMux) {
10424
10562
  const plan = planTextTrackReplacement(initialAsset, audioTrackTarget, replaceExistingTracks);
10425
10563
  if (plan.kind === "blocked") {
10426
- throw new LegacyMuxAiError(plan.reason, { type: "validation_error" });
10564
+ throw trackReplacementBlockedError(plan, { facts: { ...trackTargetFacts(audioTrackTarget), assetId, policy: replaceExistingTracks } });
10427
10565
  }
10428
10566
  }
10429
10567
  let currentAsset = initialAsset;
@@ -10463,13 +10601,6 @@ async function translateAudio(assetId, toLanguageCode, options = {}) {
10463
10601
  credentials
10464
10602
  });
10465
10603
  }
10466
- const audioRendition = getReadyAudioStaticRendition(currentAsset);
10467
- if (!audioRendition) {
10468
- throw new LegacyMuxAiError(
10469
- "Unable to obtain an audio-only static rendition for this asset. Please verify static renditions are enabled in Mux.",
10470
- { type: "validation_error" }
10471
- );
10472
- }
10473
10604
  }
10474
10605
  let audioUrl = `${await getMuxStreamOrigin(credentials)}/${playbackId}/${sourceRenditionName}`;
10475
10606
  if (policy === "signed") {
@@ -10492,7 +10623,7 @@ async function translateAudio(assetId, toLanguageCode, options = {}) {
10492
10623
  credentials
10493
10624
  });
10494
10625
  } catch (error) {
10495
- legacyWrapError(error, "Failed to create ElevenLabs dubbing job");
10626
+ wrapError(error, "Failed to create ElevenLabs dubbing job", { provider: "elevenlabs", assetId });
10496
10627
  }
10497
10628
  if (created.kind === "failed") {
10498
10629
  const { failure } = created;
@@ -10500,7 +10631,7 @@ async function translateAudio(assetId, toLanguageCode, options = {}) {
10500
10631
  console.warn(
10501
10632
  `Failed to create ElevenLabs dubbing project for asset ${assetId}: ${failure.detail}${mayHaveCreated ? " The project may have been created; check ElevenLabs before retrying." : ""}`
10502
10633
  );
10503
- throw dubbingStartError(failure, { target: elevenLabsLangCode, source: elevenLabsSourceLangCode });
10634
+ throw dubbingStartError(failure, { target: elevenLabsLangCode, source: elevenLabsSourceLangCode }, { assetId, ...mayHaveCreated && { mayHaveCreated } });
10504
10635
  }
10505
10636
  dubbingId = created.projectId;
10506
10637
  languageId = created.languageId;
@@ -10523,14 +10654,17 @@ async function translateAudio(assetId, toLanguageCode, options = {}) {
10523
10654
  credentials
10524
10655
  });
10525
10656
  } catch (error) {
10526
- legacyWrapError(error, "Failed to check dubbing status");
10657
+ wrapError(error, "Failed to check dubbing status", { provider: "elevenlabs", dubbingId });
10527
10658
  }
10528
10659
  if (statusResult.kind === "failed") {
10529
10660
  const { failure } = statusResult;
10530
10661
  consecutiveStatusCheckFailures++;
10531
10662
  console.warn(`Status check for ElevenLabs dubbing project ${dubbingId} failed: ${failure.detail}`);
10532
10663
  if (!failure.retryable || consecutiveStatusCheckFailures >= MAX_CONSECUTIVE_STATUS_CHECK_FAILURES) {
10533
- throw dubbingProviderError("Could not check audio dubbing progress.", failure);
10664
+ throw dubbingProviderError("Could not check audio dubbing progress.", "elevenlabs_get_dubbing_project", failure, {
10665
+ dubbingId,
10666
+ consecutiveFailures: consecutiveStatusCheckFailures
10667
+ });
10534
10668
  }
10535
10669
  continue;
10536
10670
  }
@@ -10539,17 +10673,51 @@ async function translateAudio(assetId, toLanguageCode, options = {}) {
10539
10673
  dubbingError = statusResult.error;
10540
10674
  if (dubbingStatus === "failed") {
10541
10675
  console.warn(`\u274C ElevenLabs dubbing project ${dubbingId} (language ${languageId}) failed: ${dubbingError ? `${dubbingError.code}: ${dubbingError.message}` : "no error reported"}`);
10676
+ const facts = { call: "elevenlabs_get_dubbing_project", provider: "elevenlabs", dubbingId, languageId };
10542
10677
  if (!dubbingError) {
10543
- throw new LegacyMuxAiError("Audio dubbing failed.", { type: "processing_error" });
10678
+ throw new MuxAiError("Audio dubbing failed.", {
10679
+ code: MUX_AI_ERROR_CODES.DUBBING_FAILED,
10680
+ type: MUX_AI_ERROR_TYPES.PROCESSING_ERROR,
10681
+ source: MUX_AI_ERROR_SOURCES.UPSTREAM,
10682
+ dependency: MUX_AI_ERROR_DEPENDENCIES.AI_PROVIDER,
10683
+ facts,
10684
+ // No reason was given, so a resubmit isn't known to help.
10685
+ retryable: false
10686
+ });
10544
10687
  }
10545
- throw new LegacyMuxAiError(
10688
+ throw new MuxAiError(
10546
10689
  `Audio dubbing failed: ${dubbingError.message}${dubbingError.retryable ? " Please try again." : ""}`,
10547
- { type: "processing_error", retryable: dubbingError.retryable }
10690
+ {
10691
+ code: MUX_AI_ERROR_CODES.DUBBING_FAILED,
10692
+ type: MUX_AI_ERROR_TYPES.PROCESSING_ERROR,
10693
+ source: MUX_AI_ERROR_SOURCES.UPSTREAM,
10694
+ dependency: MUX_AI_ERROR_DEPENDENCIES.AI_PROVIDER,
10695
+ // ElevenLabs documents `message` as display text.
10696
+ facts: { ...facts, providerCode: dubbingError.code, providerError: errorDetailFact(dubbingError.message) },
10697
+ // ElevenLabs says whether a new attempt may succeed.
10698
+ retryable: dubbingError.retryable
10699
+ }
10548
10700
  );
10549
10701
  }
10550
10702
  }
10551
10703
  if (dubbingStatus !== "completed") {
10552
- throw new LegacyMuxAiError("Audio translation timed out or failed. Please try again.", { type: "timeout_error", retryable: true });
10704
+ throw new MuxAiError("Audio translation timed out. Please try again.", {
10705
+ code: MUX_AI_ERROR_CODES.DUBBING_TIMEOUT,
10706
+ type: MUX_AI_ERROR_TYPES.TIMEOUT_ERROR,
10707
+ source: MUX_AI_ERROR_SOURCES.UPSTREAM,
10708
+ dependency: MUX_AI_ERROR_DEPENDENCIES.AI_PROVIDER,
10709
+ facts: {
10710
+ call: "elevenlabs_get_dubbing_project",
10711
+ provider: "elevenlabs",
10712
+ dubbingId,
10713
+ languageId,
10714
+ pollAttempts,
10715
+ timeoutSeconds: dubbingPollTimeoutSeconds,
10716
+ lastStatus: dubbingStatus
10717
+ },
10718
+ // Not transient: this already polled for the whole budget.
10719
+ transient: false
10720
+ });
10553
10721
  }
10554
10722
  console.warn("\u2705 Dubbing completed successfully!");
10555
10723
  if (uploadToS3) {
@@ -10570,7 +10738,7 @@ async function translateAudio(assetId, toLanguageCode, options = {}) {
10570
10738
  credentials
10571
10739
  });
10572
10740
  } catch (error) {
10573
- legacyWrapError(error, "Failed to download and upload dubbed audio");
10741
+ wrapError(error, "Failed to download and upload dubbed audio", { dubbingId, languageId });
10574
10742
  }
10575
10743
  if (staged.kind === "staged") {
10576
10744
  presignedUrl = staged.presignedUrl;
@@ -10579,7 +10747,7 @@ async function translateAudio(assetId, toLanguageCode, options = {}) {
10579
10747
  const { failure } = staged;
10580
10748
  console.warn(`Downloading dubbed audio for ElevenLabs dubbing project ${dubbingId} failed (attempt ${attempt}): ${failure.detail}`);
10581
10749
  if (!failure.retryable || attempt >= DUBBED_AUDIO_DOWNLOAD_ATTEMPTS) {
10582
- throw dubbingProviderError("Could not download the dubbed audio.", failure);
10750
+ throw dubbingProviderError("Could not download the dubbed audio.", "elevenlabs_get_dubbed_audio", failure, { dubbingId, languageId, attempts: attempt });
10583
10751
  }
10584
10752
  await sleep(DUBBED_AUDIO_DOWNLOAD_RETRY_DELAY_MS);
10585
10753
  }
@@ -10594,16 +10762,32 @@ async function translateAudio(assetId, toLanguageCode, options = {}) {
10594
10762
  policy: replaceExistingTracks,
10595
10763
  presignedUrl,
10596
10764
  passthrough: trackPassthrough,
10597
- credentials
10765
+ credentials,
10766
+ classifiedErrors: true
10598
10767
  });
10599
10768
  } catch (error) {
10600
- legacyWrapError(error, `Failed to add dubbed audio track to Mux asset (dubbed audio is staged at: ${presignedUrl})`);
10601
- }
10602
- if (outcome.kind === "blocked") {
10603
- throw new LegacyMuxAiError(`${outcome.reason} Dubbed audio is staged at: ${presignedUrl}`, { type: "validation_error" });
10769
+ wrapError(error, "Failed to fetch the asset before adding the dubbed audio track", {
10770
+ assetId,
10771
+ ...stagedAudioFacts(presignedUrl, s3Bucket)
10772
+ });
10604
10773
  }
10605
- if (outcome.kind === "create_failed") {
10606
- throw new Error(`Failed to add dubbed audio track to Mux asset: ${outcome.reason}. Dubbed audio is staged at: ${presignedUrl}`);
10774
+ if (outcome.kind !== "created") {
10775
+ const facts = {
10776
+ assetId,
10777
+ trackType: "audio",
10778
+ languageCode: muxLangCode,
10779
+ trackName,
10780
+ dubbingId,
10781
+ ...outcome.deleted.length > 0 && { deletedTracks: trackSummaryFacts(outcome.deleted) },
10782
+ ...stagedAudioFacts(presignedUrl, s3Bucket)
10783
+ };
10784
+ if (outcome.kind === "blocked") {
10785
+ throw trackReplacementBlockedError(outcome, { message: `${outcome.reason} The dubbed audio is still staged in storage.`, facts });
10786
+ }
10787
+ const failure = trackWriteFailure(outcome);
10788
+ Object.assign(failure, { facts: { ...facts, ...failure.facts } });
10789
+ failure.message = `Failed to add dubbed audio track to Mux asset: ${failure.message}. The dubbed audio is still staged in storage.`;
10790
+ throw failure;
10607
10791
  }
10608
10792
  uploadedTrackId = outcome.trackId;
10609
10793
  replacedTracks = outcome.deleted;