@mux/ai 0.62.0 → 0.63.0-canary.99

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,10 +1,10 @@
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';
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-CA8sRSVJ.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-DuNI058z.js';
4
+ import '../transcripts-So1KIXSI.js';
5
+ import '@workflow/serde';
5
6
  import '@mux/ts';
6
7
  import 'zod';
7
8
  import '@ai-sdk/anthropic';
8
9
  import '@ai-sdk/google';
9
10
  import '@ai-sdk/openai';
10
- import '@workflow/serde';
@@ -573,7 +573,7 @@ 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`) 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. */
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",
@@ -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
+ /** The asset's ready caption track has no id, so its transcript can't be fetched. Facts: `assetId`, `languageCode`. */
609
+ CAPTION_TRACK_ID_MISSING: "caption_track_id_missing",
608
610
  /** The asset snapshot the service running the SDK passed in is for a different asset than the one requested. Facts: `assetId`, `snapshotAssetId`. */
609
611
  ASSET_SNAPSHOT_MISMATCH: "asset_snapshot_mismatch",
610
612
  /** Mux answered an asset fetch with a different asset than the one requested. Facts: `assetId`, `returnedAssetId`. */
@@ -665,6 +667,7 @@ var MUX_AI_ERROR_CATALOG = {
665
667
  [MUX_AI_ERROR_CODES.CAPTION_TRACK_LANGUAGE_MISSING]: { type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR, source: MUX_AI_ERROR_SOURCES.ASSET },
666
668
  // The track may exist, so a step retry could duplicate it; the job stays retryable.
667
669
  [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
+ [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 },
668
671
  [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 },
669
672
  // Model calls.
670
673
  [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 },
@@ -2911,35 +2914,60 @@ function createLanguageSection(languageName) {
2911
2914
  function hasWorkflowScopeBoundaries(scope) {
2912
2915
  return scope?.startTime !== void 0 || scope?.endTime !== void 0;
2913
2916
  }
2914
- function resolveWorkflowScope(scope, assetDurationSeconds) {
2917
+ function invalidScopeError(message, facts, inputs) {
2918
+ return new MuxAiError(message, {
2919
+ code: MUX_AI_ERROR_CODES.INVALID_SCOPE,
2920
+ type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR,
2921
+ source: MUX_AI_ERROR_SOURCES.REQUEST,
2922
+ facts: { ...facts, inputs }
2923
+ });
2924
+ }
2925
+ function boundFact(value) {
2926
+ return Number.isFinite(value) ? value : String(value);
2927
+ }
2928
+ function resolveWorkflowScope(scope, assetDurationSeconds, options = {}) {
2929
+ const classified = options.classifiedErrors === true;
2915
2930
  if (assetDurationSeconds === void 0 || !Number.isFinite(assetDurationSeconds) || assetDurationSeconds <= 0) {
2931
+ if (classified) {
2932
+ throw new MuxAiError("Asset has no valid duration.", {
2933
+ code: MUX_AI_ERROR_CODES.ASSET_DURATION_UNAVAILABLE,
2934
+ type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR,
2935
+ source: MUX_AI_ERROR_SOURCES.ASSET,
2936
+ facts: { ...options.assetId && { assetId: options.assetId } }
2937
+ });
2938
+ }
2916
2939
  throw new LegacyMuxAiError("Asset has no valid duration.", { type: "validation_error" });
2917
2940
  }
2918
2941
  const startTime = scope?.startTime ?? 0;
2919
2942
  const endTime = scope?.endTime ?? assetDurationSeconds;
2920
2943
  if (!Number.isFinite(startTime) || startTime < 0) {
2921
- throw new LegacyMuxAiError(
2922
- `scope.startTime must be a finite, non-negative number (received ${startTime}).`,
2923
- { type: "validation_error" }
2924
- );
2944
+ const message = `scope.startTime must be a finite, non-negative number (received ${startTime}).`;
2945
+ if (classified) {
2946
+ throw invalidScopeError(message, { reason: "invalid_start_time", received: boundFact(startTime) }, ["scope.startTime"]);
2947
+ }
2948
+ throw new LegacyMuxAiError(message, { type: "validation_error" });
2925
2949
  }
2926
2950
  if (!Number.isFinite(endTime) || endTime < 0) {
2927
- throw new LegacyMuxAiError(
2928
- `scope.endTime must be a finite, non-negative number (received ${endTime}).`,
2929
- { type: "validation_error" }
2930
- );
2951
+ const message = `scope.endTime must be a finite, non-negative number (received ${endTime}).`;
2952
+ if (classified) {
2953
+ throw invalidScopeError(message, { reason: "invalid_end_time", received: boundFact(endTime) }, ["scope.endTime"]);
2954
+ }
2955
+ throw new LegacyMuxAiError(message, { type: "validation_error" });
2931
2956
  }
2932
2957
  if (endTime > assetDurationSeconds) {
2933
- throw new LegacyMuxAiError(
2934
- `scope.endTime (${endTime}) cannot exceed the asset duration (${assetDurationSeconds}).`,
2935
- { type: "validation_error" }
2936
- );
2958
+ const message = `scope.endTime (${endTime}) cannot exceed the asset duration (${assetDurationSeconds}).`;
2959
+ if (classified) {
2960
+ throw invalidScopeError(message, { reason: "exceeds_duration", endTime, assetDurationSeconds }, ["scope.endTime"]);
2961
+ }
2962
+ throw new LegacyMuxAiError(message, { type: "validation_error" });
2937
2963
  }
2938
2964
  if (startTime >= endTime) {
2939
- throw new LegacyMuxAiError(
2940
- `scope.startTime (${startTime}) must be less than scope.endTime (${endTime}).`,
2941
- { type: "validation_error" }
2942
- );
2965
+ const message = `scope.startTime (${startTime}) must be less than scope.endTime (${endTime}).`;
2966
+ if (classified) {
2967
+ const inputs = scope?.endTime === void 0 ? ["scope.startTime"] : ["scope.startTime", "scope.endTime"];
2968
+ throw invalidScopeError(message, { reason: "empty_range", startTime, endTime }, inputs);
2969
+ }
2970
+ throw new LegacyMuxAiError(message, { type: "validation_error" });
2943
2971
  }
2944
2972
  return { startTime, endTime };
2945
2973
  }
@@ -3692,11 +3720,7 @@ async function fetchTranscriptDataForUrl(transcriptUrl, options = {}) {
3692
3720
  "use step";
3693
3721
  const { cleanTranscript = true, scope } = options;
3694
3722
  try {
3695
- const response = await fetch(transcriptUrl);
3696
- if (!response.ok) {
3697
- throw new Error(`Failed to fetch transcript (HTTP ${response.status})`);
3698
- }
3699
- const rawVtt = await response.text();
3723
+ const rawVtt = options.classifiedErrors ? await fetchTranscriptVtt(transcriptUrl) : await fetchTranscriptVttLegacy(transcriptUrl);
3700
3724
  const effectiveScope = hasWorkflowScopeBoundaries(scope) ? scope : void 0;
3701
3725
  const scopedVtt = filterVttByScope(rawVtt, effectiveScope);
3702
3726
  const transcriptText = cleanTranscript ? extractTextFromVTT(scopedVtt) : scopedVtt;
@@ -3709,24 +3733,69 @@ async function fetchTranscriptDataForUrl(transcriptUrl, options = {}) {
3709
3733
  }
3710
3734
  return { transcriptText };
3711
3735
  } catch (error) {
3736
+ if (options.classifiedErrors) {
3737
+ wrapError(error, "Failed to fetch transcript");
3738
+ }
3712
3739
  legacyWrapError(error, "Failed to fetch transcript");
3713
3740
  }
3714
3741
  }
3742
+ async function fetchTranscriptVttLegacy(transcriptUrl) {
3743
+ const response = await fetch(transcriptUrl);
3744
+ if (!response.ok) {
3745
+ throw new Error(`Failed to fetch transcript (HTTP ${response.status})`);
3746
+ }
3747
+ return response.text();
3748
+ }
3749
+ async function fetchTranscriptVtt(transcriptUrl) {
3750
+ let response;
3751
+ try {
3752
+ response = await fetch(transcriptUrl);
3753
+ } catch (error) {
3754
+ throw muxVideoError("Failed to fetch transcript from Mux", { call: "fetch_transcript", cause: error });
3755
+ }
3756
+ if (!response.ok) {
3757
+ throw muxVideoError(`Failed to fetch transcript from Mux (HTTP ${response.status})`, {
3758
+ call: "fetch_transcript",
3759
+ status: response.status,
3760
+ requestId: requestIdOf(response.headers)
3761
+ });
3762
+ }
3763
+ try {
3764
+ return await response.text();
3765
+ } catch (error) {
3766
+ throw muxVideoError("Failed to read transcript from Mux", { call: "fetch_transcript", cause: error });
3767
+ }
3768
+ }
3715
3769
  async function fetchTranscriptForAsset(asset, playbackId, options = {}) {
3716
- const { required = false, languageCode, cleanTranscript, scope, shouldSign, credentials } = options;
3770
+ const { required = false, languageCode, cleanTranscript, scope, shouldSign, credentials, classifiedErrors } = options;
3717
3771
  const track = findCaptionTrack(asset, languageCode);
3718
3772
  if (!track) {
3719
3773
  if (required) {
3720
- const availableLanguages = getReadyTextTracks(asset).map((t) => t.language_code).filter(Boolean).join(", ");
3721
- throw new LegacyMuxAiError(
3722
- `No caption track found${languageCode ? ` for language ${languageCode}` : ""}. Available languages: ${availableLanguages || "none"}.`,
3723
- { type: "validation_error" }
3724
- );
3774
+ const availableLanguages = getReadyTextTracks(asset).map((t) => t.language_code).filter((code) => !!code);
3775
+ const message = `No caption track found${languageCode ? ` for language ${languageCode}` : ""}. Available languages: ${availableLanguages.join(", ") || "none"}.`;
3776
+ if (classifiedErrors) {
3777
+ throw new MuxAiError(message, {
3778
+ code: MUX_AI_ERROR_CODES.CAPTION_TRACK_NOT_FOUND,
3779
+ type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR,
3780
+ source: MUX_AI_ERROR_SOURCES.ASSET,
3781
+ facts: { assetId: asset.id, ...languageCode && { languageCode }, availableLanguages }
3782
+ });
3783
+ }
3784
+ throw new LegacyMuxAiError(message, { type: "validation_error" });
3725
3785
  }
3726
3786
  return { transcriptText: "" };
3727
3787
  }
3728
3788
  if (!track.id) {
3729
3789
  if (required) {
3790
+ if (classifiedErrors) {
3791
+ throw new MuxAiError("Transcript track is missing an id.", {
3792
+ code: MUX_AI_ERROR_CODES.CAPTION_TRACK_ID_MISSING,
3793
+ type: MUX_AI_ERROR_TYPES.PROCESSING_ERROR,
3794
+ source: MUX_AI_ERROR_SOURCES.UPSTREAM,
3795
+ dependency: MUX_AI_ERROR_DEPENDENCIES.MUX_VIDEO,
3796
+ facts: { assetId: asset.id, ...track.language_code && { languageCode: track.language_code } }
3797
+ });
3798
+ }
3730
3799
  throw new LegacyMuxAiError("Transcript track is missing an id.", { type: "validation_error" });
3731
3800
  }
3732
3801
  return { transcriptText: "", track };
@@ -3734,7 +3803,7 @@ async function fetchTranscriptForAsset(asset, playbackId, options = {}) {
3734
3803
  const transcriptUrl = await buildTranscriptUrl(playbackId, track.id, shouldSign, credentials);
3735
3804
  let result;
3736
3805
  try {
3737
- result = await fetchTranscriptDataForUrl(transcriptUrl, { cleanTranscript, scope });
3806
+ result = await fetchTranscriptDataForUrl(transcriptUrl, { cleanTranscript, scope, classifiedErrors });
3738
3807
  } catch (error) {
3739
3808
  if (required) {
3740
3809
  throw error;
@@ -3747,8 +3816,23 @@ async function fetchTranscriptForAsset(asset, playbackId, options = {}) {
3747
3816
  }
3748
3817
  switch (result.emptyReason) {
3749
3818
  case "no_scoped_cues":
3819
+ if (classifiedErrors) {
3820
+ throw invalidScopeError(
3821
+ "Transcript has no cues in the requested scope.",
3822
+ { reason: "no_transcript", trackId: track.id, ...scope?.startTime !== void 0 && { startTime: scope.startTime }, ...scope?.endTime !== void 0 && { endTime: scope.endTime } },
3823
+ ["scope"]
3824
+ );
3825
+ }
3750
3826
  throw new LegacyMuxAiError("Transcript has no cues in the requested scope.", { type: "validation_error" });
3751
3827
  case "empty_body":
3828
+ if (classifiedErrors) {
3829
+ throw new MuxAiError("Transcript is empty.", {
3830
+ code: MUX_AI_ERROR_CODES.TRANSCRIPT_EMPTY,
3831
+ type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR,
3832
+ source: MUX_AI_ERROR_SOURCES.ASSET,
3833
+ facts: { assetId: asset.id, trackId: track.id }
3834
+ });
3835
+ }
3752
3836
  throw new LegacyMuxAiError("Transcript is empty.", { type: "validation_error" });
3753
3837
  }
3754
3838
  }
@@ -4739,6 +4823,7 @@ async function generateChaptersWithAI({
4739
4823
  }) {
4740
4824
  "use step";
4741
4825
  const model = await createLanguageModelFromConfig(provider, modelId, credentials);
4826
+ const context = { call: "generate_chapters", provider, model: modelId };
4742
4827
  const response = await withContentPolicyAwareRetry(() => generateText4({
4743
4828
  model,
4744
4829
  maxRetries: 0,
@@ -4750,8 +4835,10 @@ async function generateChaptersWithAI({
4750
4835
  content: userPrompt
4751
4836
  }
4752
4837
  ]
4753
- }));
4754
- const output = getGeneratedOutputWithContentPolicyHandling(response);
4838
+ }), void 0, context).catch((error) => {
4839
+ throw modelStepError(error, "Chapter generation model call failed", { ...context });
4840
+ });
4841
+ const output = getGeneratedOutputWithContentPolicyHandling(response, context);
4755
4842
  const unexpectedRootKeys = detectUnexpectedKeysFromRawText(
4756
4843
  response.text,
4757
4844
  chaptersSchema.keyof().options
@@ -4966,48 +5053,46 @@ async function generateChaptersInternal(assetId, options, collectedUsage) {
4966
5053
  model,
4967
5054
  provider
4968
5055
  });
4969
- const { asset: assetData, playbackId, policy } = await getPlaybackIdForAsset(assetId, credentials, options.assetSnapshot);
5056
+ const { asset: assetData, playbackId, policy } = await getPlaybackIdForAsset(assetId, credentials, options.assetSnapshot, { classifiedErrors: true });
4970
5057
  const assetDurationSeconds = getAssetDurationSecondsFromAsset(assetData);
4971
5058
  const effectiveScope = hasWorkflowScopeBoundaries(scope) ? scope : void 0;
4972
- const resolvedScope = effectiveScope ? resolveWorkflowScope(effectiveScope, assetDurationSeconds) : void 0;
5059
+ const resolvedScope = effectiveScope ? resolveWorkflowScope(effectiveScope, assetDurationSeconds, { classifiedErrors: true, assetId }) : void 0;
4973
5060
  const isAudioOnly = isAudioOnlyAsset(assetData);
4974
5061
  const signingContext = await resolveMuxSigningContext(credentials);
4975
5062
  if (policy === "signed" && !signingContext) {
4976
- throw new LegacyMuxAiError(
4977
- "Signed playback ID requires signing credentials. Set MUX_SIGNING_KEY and MUX_PRIVATE_KEY environment variables.",
4978
- { type: "validation_error" }
4979
- );
5063
+ throw signingCredentialsMissingError();
4980
5064
  }
4981
- const readyTextTracks = getReadyTextTracks(assetData);
4982
5065
  const transcriptResult = await fetchTranscriptForAsset(assetData, playbackId, {
4983
5066
  languageCode,
4984
5067
  cleanTranscript: false,
4985
5068
  // keep timestamps for chapter segmentation
4986
5069
  shouldSign: policy === "signed",
4987
5070
  credentials,
4988
- scope: effectiveScope
5071
+ scope: effectiveScope,
5072
+ required: true,
5073
+ classifiedErrors: true
4989
5074
  });
4990
- if (!transcriptResult.track || !transcriptResult.transcriptText) {
4991
- const availableLanguages = readyTextTracks.map((t) => t.language_code).filter(Boolean).join(", ");
4992
- throw new LegacyMuxAiError(
4993
- `No caption track found${languageCode ? ` for language ${languageCode}` : ""}. Available languages: ${availableLanguages || "none"}.`,
4994
- { type: "validation_error" }
4995
- );
4996
- }
5075
+ const transcriptTrack = transcriptResult.track;
4997
5076
  const timestampedTranscript = extractTimestampedTranscript(transcriptResult.transcriptText);
4998
5077
  if (!timestampedTranscript) {
4999
5078
  const contentLabel = isAudioOnly ? "transcript" : "caption track";
5000
- throw new LegacyMuxAiError(`No usable content found in ${contentLabel}.`, { type: "validation_error" });
5079
+ throw new MuxAiError(`No usable content found in ${contentLabel}.`, {
5080
+ code: MUX_AI_ERROR_CODES.TRANSCRIPT_EMPTY,
5081
+ type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR,
5082
+ source: MUX_AI_ERROR_SOURCES.ASSET,
5083
+ facts: { assetId, ...transcriptTrack.id && { trackId: transcriptTrack.id } }
5084
+ });
5001
5085
  }
5002
- const resolvedLanguageCode = outputLanguageCode && outputLanguageCode !== "auto" ? outputLanguageCode : getReliableLanguageCode(transcriptResult.track) ?? languageCode;
5086
+ const resolvedLanguageCode = outputLanguageCode && outputLanguageCode !== "auto" ? outputLanguageCode : getReliableLanguageCode(transcriptTrack) ?? languageCode;
5003
5087
  const languageName = resolvedLanguageCode ? getLanguageName(resolvedLanguageCode) : void 0;
5004
5088
  const sceneBoundarySeconds = getSceneBoundarySeconds(sceneContext).filter(
5005
5089
  (boundary) => resolvedScope ? boundary >= resolvedScope.startTime && boundary < resolvedScope.endTime : true
5006
5090
  );
5007
5091
  if (sceneContext?.length && sceneBoundarySeconds.length === 0) {
5008
- throw new LegacyMuxAiError(
5092
+ throw invalidScopeError(
5009
5093
  "Scene context has no chapter boundaries within the requested scope.",
5010
- { type: "validation_error" }
5094
+ { reason: "no_scenes", ...resolvedScope && { startTime: resolvedScope.startTime, endTime: resolvedScope.endTime } },
5095
+ ["scope", "sceneContext"]
5011
5096
  );
5012
5097
  }
5013
5098
  const userPrompt = buildUserPrompt3({
@@ -5019,29 +5104,20 @@ async function generateChaptersInternal(assetId, options, collectedUsage) {
5019
5104
  languageName,
5020
5105
  scope: resolvedScope
5021
5106
  });
5022
- let chaptersData = null;
5023
- try {
5024
- const systemPromptOverrides = {
5025
- ...isAudioOnly ? AUDIO_ONLY_SYSTEM_PROMPT_OVERRIDES : {},
5026
- ...sceneContext?.length ? SCENE_CONTEXT_SYSTEM_PROMPT_OVERRIDES : {}
5027
- };
5028
- const systemPrompt = chapterSystemPromptBuilder.build(systemPromptOverrides);
5029
- chaptersData = await generateChaptersWithAI({
5030
- provider: modelConfig.provider,
5031
- modelId: modelConfig.modelId,
5032
- userPrompt,
5033
- systemPrompt,
5034
- credentials
5035
- });
5036
- } catch (error) {
5037
- legacyWrapError(error, `Failed to generate chapters with ${provider}`);
5038
- }
5039
- if (chaptersData) {
5040
- collectedUsage.push(chaptersData.usage);
5041
- }
5042
- if (!chaptersData || !chaptersData.chapters) {
5043
- throw new LegacyMuxAiError(`Failed to generate chapters for asset ${assetId}.`);
5044
- }
5107
+ const modelFacts = { call: "generate_chapters", provider: modelConfig.provider, model: modelConfig.modelId, assetId };
5108
+ const systemPromptOverrides = {
5109
+ ...isAudioOnly ? AUDIO_ONLY_SYSTEM_PROMPT_OVERRIDES : {},
5110
+ ...sceneContext?.length ? SCENE_CONTEXT_SYSTEM_PROMPT_OVERRIDES : {}
5111
+ };
5112
+ const systemPrompt = chapterSystemPromptBuilder.build(systemPromptOverrides);
5113
+ const chaptersData = await generateChaptersWithAI({
5114
+ provider: modelConfig.provider,
5115
+ modelId: modelConfig.modelId,
5116
+ userPrompt,
5117
+ systemPrompt,
5118
+ credentials
5119
+ }).catch((error) => wrapError(error, `Failed to generate chapters with ${modelConfig.provider}`, modelFacts));
5120
+ collectedUsage.push(chaptersData.usage);
5045
5121
  const { chapters: chaptersPayload, usage } = chaptersData;
5046
5122
  const scopedChapters = chaptersPayload.chapters.filter((chapter) => typeof chapter.startTime === "number" && typeof chapter.title === "string").filter(
5047
5123
  (chapter) => resolvedScope ? chapter.startTime >= resolvedScope.startTime && chapter.startTime < resolvedScope.endTime : true
@@ -5051,7 +5127,13 @@ async function generateChaptersInternal(assetId, options, collectedUsage) {
5051
5127
  sceneBoundarySeconds
5052
5128
  );
5053
5129
  if (validChapters.length === 0) {
5054
- throw new LegacyMuxAiError(`Failed to generate valid chapters for asset ${assetId}.`);
5130
+ throw new MuxAiError(`Failed to generate valid chapters for asset ${assetId}.`, {
5131
+ code: MUX_AI_ERROR_CODES.MODEL_OUTPUT_INVALID,
5132
+ type: MUX_AI_ERROR_TYPES.PROCESSING_ERROR,
5133
+ source: MUX_AI_ERROR_SOURCES.UPSTREAM,
5134
+ dependency: MUX_AI_ERROR_DEPENDENCIES.AI_PROVIDER,
5135
+ facts: { ...modelFacts, returnedChapterCount: chaptersPayload.chapters.length, ...resolvedScope && { scopeStartTime: resolvedScope.startTime, scopeEndTime: resolvedScope.endTime } }
5136
+ });
5055
5137
  }
5056
5138
  const safety = createSafetyReporter();
5057
5139
  for (const key of chaptersData.unexpectedRootKeys) {
@@ -5073,7 +5155,13 @@ async function generateChaptersInternal(assetId, options, collectedUsage) {
5073
5155
  return !scrub.leaked;
5074
5156
  });
5075
5157
  if (scrubbedChapters.length === 0) {
5076
- throw new LegacyMuxAiError(`Failed to generate valid chapters for asset ${assetId}.`);
5158
+ throw new MuxAiError(`Failed to generate valid chapters for asset ${assetId}: every chapter title was withheld by the output safety filter.`, {
5159
+ code: MUX_AI_ERROR_CODES.MODEL_OUTPUT_SUPPRESSED,
5160
+ type: MUX_AI_ERROR_TYPES.PROCESSING_ERROR,
5161
+ source: MUX_AI_ERROR_SOURCES.UPSTREAM,
5162
+ dependency: MUX_AI_ERROR_DEPENDENCIES.AI_PROVIDER,
5163
+ facts: { ...modelFacts, suppressedChapterCount: validChapters.length }
5164
+ });
5077
5165
  }
5078
5166
  if (sceneBoundarySeconds.length === 0) {
5079
5167
  const firstChapterStartTime = resolvedScope?.startTime ?? 0;
@@ -5090,7 +5178,7 @@ async function generateChaptersInternal(assetId, options, collectedUsage) {
5090
5178
  };
5091
5179
  return {
5092
5180
  assetId,
5093
- languageCode: languageCode ?? getReliableLanguageCode(transcriptResult.track) ?? "en",
5181
+ languageCode: languageCode ?? getReliableLanguageCode(transcriptTrack) ?? "en",
5094
5182
  chapters: scrubbedChapters,
5095
5183
  usage: usageWithMetadata,
5096
5184
  safety: safety.report()