@mux/ai 0.58.0 → 0.59.1-canary.90

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.
@@ -530,29 +530,244 @@ function rethrowWithTokenUsage(error, collectedUsage) {
530
530
  }
531
531
 
532
532
  // src/lib/mux-ai-error.ts
533
- var MuxAiError = class _MuxAiError extends Error {
534
- constructor(message, opts) {
535
- super(message);
536
- /** Structural brand for duck-type identification. */
537
- this.__robots_error = true;
538
- if (opts?.cause !== void 0) {
539
- Object.defineProperty(this, "cause", { value: opts.cause, writable: true, configurable: true });
533
+ var MUX_AI_ERROR_TYPES = {
534
+ /** The request, the asset or the account can't be used as it is. */
535
+ VALIDATION_ERROR: "validation_error",
536
+ /** The work was attempted and failed. */
537
+ PROCESSING_ERROR: "processing_error",
538
+ /** The work didn't finish in time. */
539
+ TIMEOUT_ERROR: "timeout_error",
540
+ /** Content was refused by a content policy. */
541
+ CONTENT_POLICY_ERROR: "content_policy_error",
542
+ /** A service is rate limiting or over capacity. */
543
+ CAPACITY_ERROR: "capacity_error",
544
+ /** A fault in this code or its configuration. */
545
+ SERVER_ERROR: "server_error"
546
+ };
547
+ var MUX_AI_ERROR_TYPE_VALUES = Object.values(MUX_AI_ERROR_TYPES);
548
+ var MUX_AI_ERROR_SOURCES = {
549
+ /** The caller's input, e.g. a scope past the end of the asset. */
550
+ REQUEST: "request",
551
+ /** The Mux asset's state, e.g. no caption track in the requested language. */
552
+ ASSET: "asset",
553
+ /** The Mux account or environment, e.g. missing permissions. */
554
+ ACCOUNT: "account",
555
+ /** A remote service failed, e.g. the dubbing provider reported a failed dub. */
556
+ UPSTREAM: "upstream",
557
+ /** This code, or the configuration of the service running it, e.g. missing signing keys. */
558
+ INTERNAL: "internal"
559
+ };
560
+ var MUX_AI_ERROR_SOURCE_VALUES = Object.values(MUX_AI_ERROR_SOURCES);
561
+ var MUX_AI_ERROR_DEPENDENCIES = {
562
+ /** Mux Video: the API, stream and image delivery, and its static renditions and tracks. */
563
+ MUX_VIDEO: "mux_video",
564
+ /** Mux Data: its API, e.g. engagement data (heatmaps and hotspots). */
565
+ MUX_DATA: "mux_data",
566
+ /** A model or AI service provider, e.g. a language model API or the dubbing provider. */
567
+ AI_PROVIDER: "ai_provider",
568
+ /** Object storage the SDK writes to or reads from, e.g. an S3-compatible bucket. */
569
+ STORAGE: "storage"
570
+ };
571
+ var MUX_AI_ERROR_DEPENDENCY_VALUES = Object.values(MUX_AI_ERROR_DEPENDENCIES);
572
+ var MUX_AI_ERROR_CODES = {
573
+ /** 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. */
574
+ INVALID_SCOPE: "invalid_scope",
575
+ /** 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. */
576
+ TRACK_REPLACEMENT_BLOCKED: "track_replacement_blocked",
577
+ /** 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. */
578
+ PARAMETER_OUT_OF_RANGE: "parameter_out_of_range",
579
+ /** No ready caption track matches the requested track or language. Facts: `trackId` or `languageCode`, and what is available. */
580
+ CAPTION_TRACK_NOT_FOUND: "caption_track_not_found",
581
+ /** The asset has no public or signed playback ID (DRM-only assets included). */
582
+ PLAYBACK_ID_NOT_FOUND: "playback_id_not_found",
583
+ /** The transcript has no usable content. */
584
+ TRANSCRIPT_EMPTY: "transcript_empty",
585
+ /** The asset has no valid duration, so work that depends on it can't run. Facts: `assetId`. */
586
+ ASSET_DURATION_UNAVAILABLE: "asset_duration_unavailable",
587
+ /** Mux won't add an audio track to this asset. Facts: `reason` (`clip`, `live_stream`, `audio_only`). */
588
+ AUDIO_TRACK_UNSUPPORTED: "audio_track_unsupported",
589
+ /** The asset's existing static rendition can't be used as a source. Facts: `reason` (`unusable`, `too_large`) and the rendition's details. */
590
+ STATIC_RENDITION_UNSUPPORTED: "static_rendition_unsupported",
591
+ /** Signed playback needs signing keys the service running the SDK didn't provide. */
592
+ SIGNING_CREDENTIALS_MISSING: "signing_credentials_missing",
593
+ /** Storage is needed but the service running the SDK didn't configure it. */
594
+ STORAGE_NOT_CONFIGURED: "storage_not_configured",
595
+ /** The model provider refused the content. Facts: `reason` and `category`. */
596
+ CONTENT_POLICY_BLOCKED: "content_policy_blocked",
597
+ /** The model returned no output, or a required field was empty. Facts: `call`, `provider`, `model`, and `assetId` when there is one. */
598
+ MODEL_OUTPUT_MISSING: "model_output_missing",
599
+ /** The model's output breaks the expected shape or constraints (counts, allowed values, limits). Facts: `call`, `provider`, `model`, and `assetId` when there is one. */
600
+ MODEL_OUTPUT_INVALID: "model_output_invalid",
601
+ /** The model's output was withheld by the SDK's output safety filter (a suspected prompt leak). */
602
+ MODEL_OUTPUT_SUPPRESSED: "model_output_suppressed",
603
+ /** The model stopped early for a reason other than the length limit. */
604
+ MODEL_OUTPUT_INCOMPLETE: "model_output_incomplete",
605
+ /** The model hit the output length limit. */
606
+ MODEL_OUTPUT_TRUNCATED: "model_output_truncated",
607
+ /** Mux reported the static rendition a workflow needs as errored. */
608
+ STATIC_RENDITION_FAILED: "static_rendition_failed",
609
+ /** The dubbing provider doesn't support the requested language. Facts: `language` and `which` (`target` or `source`). */
610
+ DUBBING_LANGUAGE_UNSUPPORTED: "dubbing_language_unsupported",
611
+ /** The dubbing provider ran the dub and reported it failed. Facts: `providerError`, the provider's display text, when it gave one. */
612
+ DUBBING_FAILED: "dubbing_failed"
613
+ };
614
+ var MUX_AI_ERROR_CODE_VALUES = Object.values(MUX_AI_ERROR_CODES);
615
+ var MUX_AI_ERROR_CATALOG = {
616
+ // The caller's input.
617
+ [MUX_AI_ERROR_CODES.INVALID_SCOPE]: { type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR, source: MUX_AI_ERROR_SOURCES.REQUEST },
618
+ [MUX_AI_ERROR_CODES.TRACK_REPLACEMENT_BLOCKED]: { type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR, source: MUX_AI_ERROR_SOURCES.REQUEST },
619
+ [MUX_AI_ERROR_CODES.PARAMETER_OUT_OF_RANGE]: { type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR, source: MUX_AI_ERROR_SOURCES.REQUEST },
620
+ // The asset's state.
621
+ [MUX_AI_ERROR_CODES.CAPTION_TRACK_NOT_FOUND]: { type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR, source: MUX_AI_ERROR_SOURCES.ASSET },
622
+ [MUX_AI_ERROR_CODES.PLAYBACK_ID_NOT_FOUND]: { type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR, source: MUX_AI_ERROR_SOURCES.ASSET },
623
+ [MUX_AI_ERROR_CODES.ASSET_DURATION_UNAVAILABLE]: { type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR, source: MUX_AI_ERROR_SOURCES.ASSET },
624
+ [MUX_AI_ERROR_CODES.TRANSCRIPT_EMPTY]: { type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR, source: MUX_AI_ERROR_SOURCES.ASSET },
625
+ [MUX_AI_ERROR_CODES.AUDIO_TRACK_UNSUPPORTED]: { type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR, source: MUX_AI_ERROR_SOURCES.ASSET },
626
+ [MUX_AI_ERROR_CODES.STATIC_RENDITION_UNSUPPORTED]: { type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR, source: MUX_AI_ERROR_SOURCES.ASSET },
627
+ // The configuration of the service running the SDK.
628
+ [MUX_AI_ERROR_CODES.SIGNING_CREDENTIALS_MISSING]: { type: MUX_AI_ERROR_TYPES.SERVER_ERROR, source: MUX_AI_ERROR_SOURCES.INTERNAL },
629
+ [MUX_AI_ERROR_CODES.STORAGE_NOT_CONFIGURED]: { type: MUX_AI_ERROR_TYPES.SERVER_ERROR, source: MUX_AI_ERROR_SOURCES.INTERNAL },
630
+ // Model calls.
631
+ [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 },
632
+ // The model-output policies below keep what these failures did before classification
633
+ // (fatal, not resubmittable); sites that differed keep their old values explicitly.
634
+ // Whether they should be retried is an open follow-up, not decided here.
635
+ [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 },
636
+ [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 },
637
+ [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 },
638
+ // Not transient: a step retry would repeat a full generation; the job can be resubmitted.
639
+ [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 },
640
+ [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 },
641
+ // Mux Video.
642
+ // Reported by Mux: a step retry would find the same errored rendition, and resubmitting the same asset errors again.
643
+ [MUX_AI_ERROR_CODES.STATIC_RENDITION_FAILED]: { type: MUX_AI_ERROR_TYPES.PROCESSING_ERROR, source: MUX_AI_ERROR_SOURCES.UPSTREAM, dependency: MUX_AI_ERROR_DEPENDENCIES.MUX_VIDEO, transient: false, retryable: false },
644
+ // Audio dubbing.
645
+ [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 },
646
+ // Reported by the dubbing provider: a step retry would find the same failed dub.
647
+ [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 }
648
+ };
649
+ function isTransientStatus(status) {
650
+ return status === void 0 || status === 408 || status === 425 || status === 429 || status >= 500;
651
+ }
652
+ function defaultTransient(source, facts = {}) {
653
+ return source === MUX_AI_ERROR_SOURCES.UPSTREAM && typeof facts.status === "number" && isTransientStatus(facts.status);
654
+ }
655
+ function defaultRetryable(type, source, transient) {
656
+ if (transient || type === MUX_AI_ERROR_TYPES.TIMEOUT_ERROR || type === MUX_AI_ERROR_TYPES.CAPACITY_ERROR) {
657
+ return true;
658
+ }
659
+ if (type === MUX_AI_ERROR_TYPES.VALIDATION_ERROR || type === MUX_AI_ERROR_TYPES.CONTENT_POLICY_ERROR) {
660
+ return false;
661
+ }
662
+ return source === MUX_AI_ERROR_SOURCES.UPSTREAM;
663
+ }
664
+ var MAX_CAUSE_DEPTH = 3;
665
+ var MAX_CAUSE_MESSAGE_LENGTH = 500;
666
+ function statusOf(value) {
667
+ if (typeof value !== "object" || value === null) {
668
+ return void 0;
669
+ }
670
+ const { status, statusCode } = value;
671
+ const candidate = typeof status === "number" ? status : statusCode;
672
+ return typeof candidate === "number" && candidate >= 100 && candidate < 600 ? candidate : void 0;
673
+ }
674
+ function summarizeCauses(cause) {
675
+ const causes = [];
676
+ let current = cause;
677
+ while (current !== void 0 && current !== null && causes.length < MAX_CAUSE_DEPTH) {
678
+ if (ClassifiedError.isClassified(current)) {
679
+ causes.push(...current.causes.slice(0, MAX_CAUSE_DEPTH - causes.length));
680
+ break;
540
681
  }
541
- this.name = "FatalError";
542
- this.publicType = opts?.type ?? "processing_error";
543
- this.publicMessage = message;
544
- this.retryable = opts?.retryable ?? false;
682
+ const status = statusOf(current);
683
+ causes.push({
684
+ // Duck-typed: an error from another realm (e.g. a Workflow step VM) fails instanceof.
685
+ name: typeof current.name === "string" ? current.name : typeof current,
686
+ message: scrubDetail(extractErrorDetail(current)).slice(0, MAX_CAUSE_MESSAGE_LENGTH),
687
+ ...status !== void 0 && { status }
688
+ });
689
+ current = typeof current === "object" ? current.cause : void 0;
690
+ }
691
+ return causes;
692
+ }
693
+ var ClassifiedError = class extends Error {
694
+ constructor(message, init, catalog) {
695
+ super(message);
696
+ /** Structural brand shared by every classified error, for duck-type identification across realms. */
697
+ this.__classified_error = true;
698
+ const entry = init.code ? catalog[init.code] : void 0;
699
+ this.type = entry?.type ?? init.type;
700
+ this.source = entry?.source ?? init.source;
701
+ const dependency = init.dependency ?? entry?.dependency;
702
+ if (dependency) {
703
+ this.dependency = dependency;
704
+ }
705
+ if (init.code) {
706
+ this.code = init.code;
707
+ }
708
+ this.facts = init.facts ?? {};
709
+ this.transient = init.transient ?? entry?.transient ?? defaultTransient(this.source, this.facts);
710
+ this.retryable = this.transient || (init.retryable ?? entry?.retryable ?? defaultRetryable(this.type, this.source, false));
711
+ this.name = this.transient ? "Error" : "FatalError";
712
+ if (init.cause !== void 0) {
713
+ Object.defineProperty(this, "cause", { value: init.cause, writable: true, configurable: true });
714
+ }
715
+ Object.defineProperty(this, "causes", { value: summarizeCauses(init.cause), writable: true, configurable: true });
716
+ }
717
+ /** Whether `value` is any classified error, from this copy of the SDK or another. */
718
+ static isClassified(value) {
719
+ return typeof value === "object" && value !== null && "__classified_error" in value && value.__classified_error === true;
720
+ }
721
+ };
722
+ function serializeClassification(error) {
723
+ return {
724
+ message: error.message,
725
+ type: error.type,
726
+ source: error.source,
727
+ ...error.dependency && { dependency: error.dependency },
728
+ ...error.code && { code: error.code },
729
+ facts: error.facts,
730
+ retryable: error.retryable,
731
+ transient: error.transient,
732
+ causes: error.causes,
733
+ stack: error.stack
734
+ };
735
+ }
736
+ function classificationInit(record) {
737
+ return {
738
+ type: record.type,
739
+ source: record.source,
740
+ dependency: record.dependency,
741
+ facts: record.facts,
742
+ retryable: record.retryable,
743
+ transient: record.transient
744
+ };
745
+ }
746
+ function restoreClassification(error, record) {
747
+ if (record.code) {
748
+ Object.assign(error, { code: record.code });
749
+ }
750
+ Object.defineProperty(error, "causes", { value: record.causes, writable: true, configurable: true });
751
+ if (record.stack !== void 0) {
752
+ error.stack = record.stack;
753
+ }
754
+ return error;
755
+ }
756
+ var MuxAiError = class _MuxAiError extends ClassifiedError {
757
+ constructor(message, init) {
758
+ super(message, init, MUX_AI_ERROR_CATALOG);
759
+ /** Structural brand for duck-type identification across copies of the SDK. */
760
+ this.__mux_ai_error = true;
545
761
  }
546
762
  static is(value) {
547
- return typeof value === "object" && value !== null && "__robots_error" in value && value.__robots_error === true;
763
+ return typeof value === "object" && value !== null && "__mux_ai_error" in value && value.__mux_ai_error === true;
548
764
  }
765
+ // Subclasses with their own codec (LegacyMuxAiError) write their own shape.
549
766
  static [WORKFLOW_SERIALIZE](instance) {
550
767
  const incomplete = instance;
551
768
  return {
552
- message: instance.publicMessage,
553
- publicType: instance.publicType,
554
- retryable: instance.retryable,
555
- stack: instance.stack,
769
+ v: 2,
770
+ ...serializeClassification(instance),
556
771
  usage: getErrorTokenUsage(instance),
557
772
  finishReason: incomplete.finishReason,
558
773
  rawFinishReason: incomplete.rawFinishReason,
@@ -560,16 +775,13 @@ var MuxAiError = class _MuxAiError extends Error {
560
775
  };
561
776
  }
562
777
  static [WORKFLOW_DESERIALIZE](value) {
563
- const error = new _MuxAiError(value.message, { type: value.publicType, retryable: value.retryable });
778
+ const error = restoreClassification(new _MuxAiError(value.message, classificationInit(value)), value);
564
779
  Object.assign(error, {
565
780
  usage: value.usage,
566
781
  diagnostics: value.diagnostics,
567
782
  ...value.finishReason !== void 0 && { finishReason: value.finishReason },
568
783
  ...value.rawFinishReason !== void 0 && { rawFinishReason: value.rawFinishReason }
569
784
  });
570
- if (value.stack !== void 0) {
571
- error.stack = value.stack;
572
- }
573
785
  return error;
574
786
  }
575
787
  };
@@ -588,8 +800,105 @@ function extractErrorDetail(error) {
588
800
  }
589
801
  return "Unknown error";
590
802
  }
591
- function wrapError(error, message) {
803
+ var URL_IN_TEXT = /https?:\/\/[^\s"'<>]+/g;
804
+ var URL_QUERY = /^([^?#]+)[?#].*$/s;
805
+ function stripUrlQueries(text) {
806
+ return text.replace(URL_IN_TEXT, (match) => {
807
+ let url;
808
+ try {
809
+ url = new URL(match);
810
+ } catch {
811
+ return match.replace(URL_QUERY, "$1?\u2026");
812
+ }
813
+ if (!url.username && !url.password && !url.search && !url.hash) {
814
+ return match;
815
+ }
816
+ return `${url.origin}${url.pathname}${url.search || url.hash ? "?\u2026" : ""}`;
817
+ });
818
+ }
819
+ function scrubDetail(detail, context) {
820
+ const leakReason = detectLeakReason(detail);
821
+ if (leakReason !== "canary" && leakReason !== "prompt_tag") {
822
+ return stripUrlQueries(detail);
823
+ }
824
+ console.warn(`[@mux/ai] Suppressed suspected prompt leak in error detail${context ? ` (context: ${context})` : ""} (reason: ${leakReason}).`);
825
+ return "Upstream error details suppressed by safety filter";
826
+ }
827
+ function wrapError(error, message, facts) {
592
828
  if (MuxAiError.is(error)) {
829
+ if (facts) {
830
+ Object.assign(error, { facts: { ...facts, ...error.facts } });
831
+ }
832
+ throw error;
833
+ }
834
+ const wrapped = new MuxAiError(`${message}: ${scrubDetail(extractErrorDetail(error), message)}`, {
835
+ type: MUX_AI_ERROR_TYPES.SERVER_ERROR,
836
+ source: MUX_AI_ERROR_SOURCES.INTERNAL,
837
+ facts,
838
+ cause: error
839
+ });
840
+ const usage = getErrorTokenUsage(error);
841
+ if (usage) {
842
+ wrapped.usage = usage;
843
+ }
844
+ throw wrapped;
845
+ }
846
+
847
+ // src/lib/legacy-mux-ai-error.ts
848
+ function legacySource(type) {
849
+ switch (type) {
850
+ case MUX_AI_ERROR_TYPES.VALIDATION_ERROR:
851
+ return MUX_AI_ERROR_SOURCES.REQUEST;
852
+ case MUX_AI_ERROR_TYPES.CONTENT_POLICY_ERROR:
853
+ return MUX_AI_ERROR_SOURCES.ASSET;
854
+ default:
855
+ return MUX_AI_ERROR_SOURCES.INTERNAL;
856
+ }
857
+ }
858
+ var LegacyMuxAiError = class _LegacyMuxAiError extends MuxAiError {
859
+ constructor(message, opts) {
860
+ const type = opts?.type ?? MUX_AI_ERROR_TYPES.PROCESSING_ERROR;
861
+ super(message, { type, source: legacySource(type), retryable: opts?.retryable ?? false, transient: false, cause: opts?.cause });
862
+ this.__robots_error = true;
863
+ this.publicType = type;
864
+ this.publicMessage = message;
865
+ }
866
+ // Its own codec, so a legacy error crosses step boundaries in its previous shape and
867
+ // revives as a legacy error (subclasses such as IncompleteGenerationError inherit it).
868
+ static [WORKFLOW_SERIALIZE](instance) {
869
+ const incomplete = instance;
870
+ return {
871
+ message: instance.publicMessage,
872
+ publicType: instance.publicType,
873
+ retryable: instance.retryable,
874
+ stack: instance.stack,
875
+ usage: getErrorTokenUsage(instance),
876
+ finishReason: incomplete.finishReason,
877
+ rawFinishReason: incomplete.rawFinishReason,
878
+ diagnostics: instance.diagnostics
879
+ };
880
+ }
881
+ // Typed to match the base codec; this codec only ever reads the legacy shape it writes.
882
+ static [WORKFLOW_DESERIALIZE](record) {
883
+ const value = record;
884
+ const error = new _LegacyMuxAiError(value.message, { type: value.publicType, retryable: value.retryable });
885
+ Object.assign(error, {
886
+ usage: value.usage,
887
+ diagnostics: value.diagnostics,
888
+ ...value.finishReason !== void 0 && { finishReason: value.finishReason },
889
+ ...value.rawFinishReason !== void 0 && { rawFinishReason: value.rawFinishReason }
890
+ });
891
+ if (value.stack !== void 0) {
892
+ error.stack = value.stack;
893
+ }
894
+ return error;
895
+ }
896
+ };
897
+ function isLegacyMuxAiError(value) {
898
+ return typeof value === "object" && value !== null && "__robots_error" in value && value.__robots_error === true && typeof value.publicMessage === "string";
899
+ }
900
+ function legacyWrapError(error, message) {
901
+ if (MuxAiError.is(error) || isLegacyMuxAiError(error)) {
593
902
  throw error;
594
903
  }
595
904
  const rawDetail = extractErrorDetail(error);
@@ -729,7 +1038,7 @@ var CONTENT_POLICY_REASONS = /* @__PURE__ */ new Set([
729
1038
  "SAFETY",
730
1039
  "SPII"
731
1040
  ]);
732
- var IncompleteGenerationError = class extends MuxAiError {
1041
+ var IncompleteGenerationError = class extends LegacyMuxAiError {
733
1042
  constructor(finishReason, rawFinishReason, usage) {
734
1043
  const reason = rawFinishReason ?? finishReason;
735
1044
  const message = finishReason === "length" ? `The model reached its output limit before producing a complete response (finish reason: ${reason}).` : `The model stopped before producing a complete response (finish reason: ${reason}).`;
@@ -827,7 +1136,7 @@ function getGeneratedOutputWithContentPolicyHandling(response) {
827
1136
  }
828
1137
  function throwContentPolicyError(block, usage) {
829
1138
  const category = block.category ? `; category: ${block.category}` : "";
830
- const contentPolicyError = new MuxAiError(
1139
+ const contentPolicyError = new LegacyMuxAiError(
831
1140
  `The supplied content was blocked by a content policy (reason: ${block.reason}${category}).`,
832
1141
  {
833
1142
  type: "content_policy_error",
@@ -2019,7 +2328,7 @@ function getPlaybackId(asset) {
2019
2328
  if (signedPlaybackId?.id) {
2020
2329
  return { id: signedPlaybackId.id, policy: "signed" };
2021
2330
  }
2022
- throw new MuxAiError(
2331
+ throw new LegacyMuxAiError(
2023
2332
  "No public or signed playback ID found for this asset. DRM playback IDs are not currently supported.",
2024
2333
  { type: "validation_error" }
2025
2334
  );
@@ -2042,7 +2351,7 @@ async function getPlaybackIdForAsset(assetId, credentials, assetSnapshot) {
2042
2351
  "use step";
2043
2352
  const asset = assetSnapshot ?? await getMuxAsset(assetId, credentials);
2044
2353
  if (asset.id !== assetId) {
2045
- throw new MuxAiError("Asset snapshot does not match the requested asset ID.", { type: "validation_error" });
2354
+ throw new LegacyMuxAiError("Asset snapshot does not match the requested asset ID.", { type: "validation_error" });
2046
2355
  }
2047
2356
  return toPlaybackAsset(asset);
2048
2357
  }
@@ -2153,30 +2462,30 @@ function hasWorkflowScopeBoundaries(scope) {
2153
2462
  }
2154
2463
  function resolveWorkflowScope(scope, assetDurationSeconds) {
2155
2464
  if (assetDurationSeconds === void 0 || !Number.isFinite(assetDurationSeconds) || assetDurationSeconds <= 0) {
2156
- throw new MuxAiError("Asset has no valid duration.", { type: "validation_error" });
2465
+ throw new LegacyMuxAiError("Asset has no valid duration.", { type: "validation_error" });
2157
2466
  }
2158
2467
  const startTime = scope?.startTime ?? 0;
2159
2468
  const endTime = scope?.endTime ?? assetDurationSeconds;
2160
2469
  if (!Number.isFinite(startTime) || startTime < 0) {
2161
- throw new MuxAiError(
2470
+ throw new LegacyMuxAiError(
2162
2471
  `scope.startTime must be a finite, non-negative number (received ${startTime}).`,
2163
2472
  { type: "validation_error" }
2164
2473
  );
2165
2474
  }
2166
2475
  if (!Number.isFinite(endTime) || endTime < 0) {
2167
- throw new MuxAiError(
2476
+ throw new LegacyMuxAiError(
2168
2477
  `scope.endTime must be a finite, non-negative number (received ${endTime}).`,
2169
2478
  { type: "validation_error" }
2170
2479
  );
2171
2480
  }
2172
2481
  if (endTime > assetDurationSeconds) {
2173
- throw new MuxAiError(
2482
+ throw new LegacyMuxAiError(
2174
2483
  `scope.endTime (${endTime}) cannot exceed the asset duration (${assetDurationSeconds}).`,
2175
2484
  { type: "validation_error" }
2176
2485
  );
2177
2486
  }
2178
2487
  if (startTime >= endTime) {
2179
- throw new MuxAiError(
2488
+ throw new LegacyMuxAiError(
2180
2489
  `scope.startTime (${startTime}) must be less than scope.endTime (${endTime}).`,
2181
2490
  { type: "validation_error" }
2182
2491
  );
@@ -2197,7 +2506,7 @@ function resolveRenderableVideoScope(scope, assetDurationSeconds, videoTrackDura
2197
2506
  endTime: renderableEndTime
2198
2507
  };
2199
2508
  if (renderableScope.startTime >= renderableScope.endTime) {
2200
- throw new MuxAiError("The requested scope does not include any renderable video.", {
2509
+ throw new LegacyMuxAiError("The requested scope does not include any renderable video.", {
2201
2510
  type: "validation_error"
2202
2511
  });
2203
2512
  }
@@ -2306,14 +2615,18 @@ async function signUrl(url, playbackId, type = "video", params, credentials) {
2306
2615
  "use step";
2307
2616
  const resolvedContext = await resolveMuxSigningContext(credentials);
2308
2617
  if (!resolvedContext) {
2309
- throw new Error(
2310
- "Signed playback ID requires signing credentials. Provide muxSigningKey and muxPrivateKey via workflow credentials or set MUX_SIGNING_KEY and MUX_PRIVATE_KEY environment variables."
2311
- );
2618
+ throw signingCredentialsMissingError();
2312
2619
  }
2313
2620
  const token = await signPlaybackId(playbackId, resolvedContext, type, params);
2314
2621
  const separator = url.includes("?") ? "&" : "?";
2315
2622
  return `${url}${separator}token=${token}`;
2316
2623
  }
2624
+ function signingCredentialsMissingError() {
2625
+ return new MuxAiError(
2626
+ "Signed playback ID requires signing credentials. Provide muxSigningKey and muxPrivateKey via workflow credentials or set MUX_SIGNING_KEY and MUX_PRIVATE_KEY environment variables.",
2627
+ { code: MUX_AI_ERROR_CODES.SIGNING_CREDENTIALS_MISSING, type: MUX_AI_ERROR_TYPES.SERVER_ERROR, source: MUX_AI_ERROR_SOURCES.INTERNAL }
2628
+ );
2629
+ }
2317
2630
 
2318
2631
  // src/primitives/storyboards.ts
2319
2632
  var DEFAULT_STORYBOARD_WIDTH = 640;
@@ -2945,7 +3258,7 @@ async function fetchTranscriptDataForUrl(transcriptUrl, options = {}) {
2945
3258
  }
2946
3259
  return { transcriptText };
2947
3260
  } catch (error) {
2948
- wrapError(error, "Failed to fetch transcript");
3261
+ legacyWrapError(error, "Failed to fetch transcript");
2949
3262
  }
2950
3263
  }
2951
3264
  async function fetchTranscriptForAsset(asset, playbackId, options = {}) {
@@ -2954,7 +3267,7 @@ async function fetchTranscriptForAsset(asset, playbackId, options = {}) {
2954
3267
  if (!track) {
2955
3268
  if (required) {
2956
3269
  const availableLanguages = getReadyTextTracks(asset).map((t) => t.language_code).filter(Boolean).join(", ");
2957
- throw new MuxAiError(
3270
+ throw new LegacyMuxAiError(
2958
3271
  `No caption track found${languageCode ? ` for language ${languageCode}` : ""}. Available languages: ${availableLanguages || "none"}.`,
2959
3272
  { type: "validation_error" }
2960
3273
  );
@@ -2963,7 +3276,7 @@ async function fetchTranscriptForAsset(asset, playbackId, options = {}) {
2963
3276
  }
2964
3277
  if (!track.id) {
2965
3278
  if (required) {
2966
- throw new MuxAiError("Transcript track is missing an id.", { type: "validation_error" });
3279
+ throw new LegacyMuxAiError("Transcript track is missing an id.", { type: "validation_error" });
2967
3280
  }
2968
3281
  return { transcriptText: "", track };
2969
3282
  }
@@ -2983,9 +3296,9 @@ async function fetchTranscriptForAsset(asset, playbackId, options = {}) {
2983
3296
  }
2984
3297
  switch (result.emptyReason) {
2985
3298
  case "no_scoped_cues":
2986
- throw new MuxAiError("Transcript has no cues in the requested scope.", { type: "validation_error" });
3299
+ throw new LegacyMuxAiError("Transcript has no cues in the requested scope.", { type: "validation_error" });
2987
3300
  case "empty_body":
2988
- throw new MuxAiError("Transcript is empty.", { type: "validation_error" });
3301
+ throw new LegacyMuxAiError("Transcript is empty.", { type: "validation_error" });
2989
3302
  }
2990
3303
  }
2991
3304
 
@@ -3263,7 +3576,7 @@ function normalizeQuestion(q, idx) {
3263
3576
  const hasOptions = Array.isArray(q.answerOptions);
3264
3577
  const isFreeForm = q.freeFormReply === true;
3265
3578
  if (hasOptions && isFreeForm) {
3266
- throw new MuxAiError(
3579
+ throw new LegacyMuxAiError(
3267
3580
  `Question at index ${idx} sets both answerOptions and freeFormReply: true. These are mutually exclusive \u2014 pick one.`,
3268
3581
  { type: "validation_error" }
3269
3582
  );
@@ -3278,7 +3591,7 @@ function normalizeQuestion(q, idx) {
3278
3591
  )
3279
3592
  );
3280
3593
  if (!options.length) {
3281
- throw new MuxAiError(
3594
+ throw new LegacyMuxAiError(
3282
3595
  `Question at index ${idx} has invalid answerOptions: must include at least one non-empty value.`,
3283
3596
  { type: "validation_error" }
3284
3597
  );
@@ -3449,23 +3762,23 @@ async function askQuestions(assetId, questions, options) {
3449
3762
  }
3450
3763
  async function askQuestionsInternal(assetId, questions, options, collectedUsage) {
3451
3764
  if (!questions || questions.length === 0) {
3452
- throw new MuxAiError("At least one question must be provided.", { type: "validation_error" });
3765
+ throw new LegacyMuxAiError("At least one question must be provided.", { type: "validation_error" });
3453
3766
  }
3454
3767
  if (questions.length > ASK_QUESTIONS_MAX_QUESTIONS_PER_CALL) {
3455
- throw new MuxAiError(
3768
+ throw new LegacyMuxAiError(
3456
3769
  `Too many questions: received ${questions.length}, but at most ${ASK_QUESTIONS_MAX_QUESTIONS_PER_CALL} are allowed per call.`,
3457
3770
  { type: "validation_error" }
3458
3771
  );
3459
3772
  }
3460
3773
  questions.forEach((q, idx) => {
3461
3774
  if (!q.question || typeof q.question !== "string" || !q.question.trim()) {
3462
- throw new MuxAiError(
3775
+ throw new LegacyMuxAiError(
3463
3776
  `Question at index ${idx} is invalid: must have a non-empty question field.`,
3464
3777
  { type: "validation_error" }
3465
3778
  );
3466
3779
  }
3467
3780
  if (q.question.length > ASK_QUESTIONS_MAX_QUESTION_LENGTH) {
3468
- throw new MuxAiError(
3781
+ throw new LegacyMuxAiError(
3469
3782
  `Question at index ${idx} exceeds the ${ASK_QUESTIONS_MAX_QUESTION_LENGTH}-character limit (received ${q.question.length}).`,
3470
3783
  { type: "validation_error" }
3471
3784
  );
@@ -3473,7 +3786,7 @@ async function askQuestionsInternal(assetId, questions, options, collectedUsage)
3473
3786
  });
3474
3787
  const maxAnswerOptionLength = options?.maxAnswerOptionLength ?? ASK_QUESTIONS_DEFAULT_MAX_ANSWER_OPTION_LENGTH;
3475
3788
  if (!Number.isFinite(maxAnswerOptionLength) || maxAnswerOptionLength <= 0) {
3476
- throw new MuxAiError(
3789
+ throw new LegacyMuxAiError(
3477
3790
  `maxAnswerOptionLength must be a positive number (received ${maxAnswerOptionLength}).`,
3478
3791
  { type: "validation_error" }
3479
3792
  );
@@ -3483,7 +3796,7 @@ async function askQuestionsInternal(assetId, questions, options, collectedUsage)
3483
3796
  return;
3484
3797
  for (const opt of q.answerOptions ?? []) {
3485
3798
  if (typeof opt === "string" && opt.length > maxAnswerOptionLength) {
3486
- throw new MuxAiError(
3799
+ throw new LegacyMuxAiError(
3487
3800
  `Question at index ${idx} has an answerOption exceeding the ${maxAnswerOptionLength}-character limit (received ${opt.length}). Answer options should be short labels, not sentences.`,
3488
3801
  { type: "validation_error" }
3489
3802
  );
@@ -3492,7 +3805,7 @@ async function askQuestionsInternal(assetId, questions, options, collectedUsage)
3492
3805
  });
3493
3806
  const maxFreeFormAnswerLength = options?.maxFreeFormAnswerLength ?? ASK_QUESTIONS_DEFAULT_MAX_FREE_FORM_ANSWER_LENGTH;
3494
3807
  if (!Number.isFinite(maxFreeFormAnswerLength) || maxFreeFormAnswerLength <= 0) {
3495
- throw new MuxAiError(
3808
+ throw new LegacyMuxAiError(
3496
3809
  `maxFreeFormAnswerLength must be a positive number (received ${maxFreeFormAnswerLength}).`,
3497
3810
  { type: "validation_error" }
3498
3811
  );
@@ -3529,14 +3842,14 @@ async function askQuestionsInternal(assetId, questions, options, collectedUsage)
3529
3842
  resolveWorkflowScope(effectiveScope, assetDurationSeconds);
3530
3843
  }
3531
3844
  if (isAudioOnly && !includeTranscript) {
3532
- throw new MuxAiError(
3845
+ throw new LegacyMuxAiError(
3533
3846
  "Audio-only assets require a transcript. Set includeTranscript: true and ensure the asset has a ready text track (captions/subtitles).",
3534
3847
  { type: "validation_error" }
3535
3848
  );
3536
3849
  }
3537
3850
  const signingContext = await resolveMuxSigningContext(credentials);
3538
3851
  if (policy === "signed" && !signingContext) {
3539
- throw new MuxAiError(
3852
+ throw new LegacyMuxAiError(
3540
3853
  "Signed playback ID requires signing credentials. Set MUX_SIGNING_KEY and MUX_PRIVATE_KEY environment variables.",
3541
3854
  { type: "validation_error" }
3542
3855
  );
@@ -3607,14 +3920,14 @@ async function askQuestionsInternal(assetId, questions, options, collectedUsage)
3607
3920
  }
3608
3921
  } catch (error) {
3609
3922
  const contentType = isAudioOnly ? "audio" : "video";
3610
- wrapError(error, `Failed to analyze ${contentType} questions with ${provider}`);
3923
+ legacyWrapError(error, `Failed to analyze ${contentType} questions with ${provider}`);
3611
3924
  }
3612
3925
  collectedUsage.push(analysisResponse.usage);
3613
3926
  if (!analysisResponse.result?.answers) {
3614
- throw new MuxAiError(`Failed to generate answers for asset ${assetId}.`);
3927
+ throw new LegacyMuxAiError(`Failed to generate answers for asset ${assetId}.`);
3615
3928
  }
3616
3929
  if (analysisResponse.result.answers.length !== questions.length) {
3617
- throw new MuxAiError(
3930
+ throw new LegacyMuxAiError(
3618
3931
  `Failed to generate answers for all questions for asset ${assetId}.`
3619
3932
  );
3620
3933
  }
@@ -3649,7 +3962,7 @@ async function askQuestionsInternal(assetId, questions, options, collectedUsage)
3649
3962
  if (!isSkipped && !isFreeForm) {
3650
3963
  const allowed = allowedAnswersForQuestion(question);
3651
3964
  if (!allowed.includes(raw.answer)) {
3652
- throw new MuxAiError(
3965
+ throw new LegacyMuxAiError(
3653
3966
  `Answer "${raw.answer}" for question ${idx} is not in allowed options: ${allowed.join(", ")}`
3654
3967
  );
3655
3968
  }
@@ -4209,7 +4522,7 @@ async function generateChaptersInternal(assetId, options, collectedUsage) {
4209
4522
  const isAudioOnly = isAudioOnlyAsset(assetData);
4210
4523
  const signingContext = await resolveMuxSigningContext(credentials);
4211
4524
  if (policy === "signed" && !signingContext) {
4212
- throw new MuxAiError(
4525
+ throw new LegacyMuxAiError(
4213
4526
  "Signed playback ID requires signing credentials. Set MUX_SIGNING_KEY and MUX_PRIVATE_KEY environment variables.",
4214
4527
  { type: "validation_error" }
4215
4528
  );
@@ -4225,7 +4538,7 @@ async function generateChaptersInternal(assetId, options, collectedUsage) {
4225
4538
  });
4226
4539
  if (!transcriptResult.track || !transcriptResult.transcriptText) {
4227
4540
  const availableLanguages = readyTextTracks.map((t) => t.language_code).filter(Boolean).join(", ");
4228
- throw new MuxAiError(
4541
+ throw new LegacyMuxAiError(
4229
4542
  `No caption track found${languageCode ? ` for language ${languageCode}` : ""}. Available languages: ${availableLanguages || "none"}.`,
4230
4543
  { type: "validation_error" }
4231
4544
  );
@@ -4233,7 +4546,7 @@ async function generateChaptersInternal(assetId, options, collectedUsage) {
4233
4546
  const timestampedTranscript = extractTimestampedTranscript(transcriptResult.transcriptText);
4234
4547
  if (!timestampedTranscript) {
4235
4548
  const contentLabel = isAudioOnly ? "transcript" : "caption track";
4236
- throw new MuxAiError(`No usable content found in ${contentLabel}.`, { type: "validation_error" });
4549
+ throw new LegacyMuxAiError(`No usable content found in ${contentLabel}.`, { type: "validation_error" });
4237
4550
  }
4238
4551
  const resolvedLanguageCode = outputLanguageCode && outputLanguageCode !== "auto" ? outputLanguageCode : getReliableLanguageCode(transcriptResult.track) ?? languageCode;
4239
4552
  const languageName = resolvedLanguageCode ? getLanguageName(resolvedLanguageCode) : void 0;
@@ -4241,7 +4554,7 @@ async function generateChaptersInternal(assetId, options, collectedUsage) {
4241
4554
  (boundary) => resolvedScope ? boundary >= resolvedScope.startTime && boundary < resolvedScope.endTime : true
4242
4555
  );
4243
4556
  if (sceneContext?.length && sceneBoundarySeconds.length === 0) {
4244
- throw new MuxAiError(
4557
+ throw new LegacyMuxAiError(
4245
4558
  "Scene context has no chapter boundaries within the requested scope.",
4246
4559
  { type: "validation_error" }
4247
4560
  );
@@ -4270,13 +4583,13 @@ async function generateChaptersInternal(assetId, options, collectedUsage) {
4270
4583
  credentials
4271
4584
  });
4272
4585
  } catch (error) {
4273
- wrapError(error, `Failed to generate chapters with ${provider}`);
4586
+ legacyWrapError(error, `Failed to generate chapters with ${provider}`);
4274
4587
  }
4275
4588
  if (chaptersData) {
4276
4589
  collectedUsage.push(chaptersData.usage);
4277
4590
  }
4278
4591
  if (!chaptersData || !chaptersData.chapters) {
4279
- throw new MuxAiError(`Failed to generate chapters for asset ${assetId}.`);
4592
+ throw new LegacyMuxAiError(`Failed to generate chapters for asset ${assetId}.`);
4280
4593
  }
4281
4594
  const { chapters: chaptersPayload, usage } = chaptersData;
4282
4595
  const scopedChapters = chaptersPayload.chapters.filter((chapter) => typeof chapter.startTime === "number" && typeof chapter.title === "string").filter(
@@ -4287,7 +4600,7 @@ async function generateChaptersInternal(assetId, options, collectedUsage) {
4287
4600
  sceneBoundarySeconds
4288
4601
  );
4289
4602
  if (validChapters.length === 0) {
4290
- throw new MuxAiError(`Failed to generate valid chapters for asset ${assetId}.`);
4603
+ throw new LegacyMuxAiError(`Failed to generate valid chapters for asset ${assetId}.`);
4291
4604
  }
4292
4605
  const safety = createSafetyReporter();
4293
4606
  for (const key of chaptersData.unexpectedRootKeys) {
@@ -4309,7 +4622,7 @@ async function generateChaptersInternal(assetId, options, collectedUsage) {
4309
4622
  return !scrub.leaked;
4310
4623
  });
4311
4624
  if (scrubbedChapters.length === 0) {
4312
- throw new MuxAiError(`Failed to generate valid chapters for asset ${assetId}.`);
4625
+ throw new LegacyMuxAiError(`Failed to generate valid chapters for asset ${assetId}.`);
4313
4626
  }
4314
4627
  if (sceneBoundarySeconds.length === 0) {
4315
4628
  const firstChapterStartTime = resolvedScope?.startTime ?? 0;
@@ -4402,41 +4715,53 @@ function itOrThem(tracks) {
4402
4715
  return tracks.length === 1 ? "it" : "them";
4403
4716
  }
4404
4717
  function describeTracks(tracks) {
4405
- return tracks.map((track) => `${track.name ?? "(unnamed)"} [${track.language_code ?? "?"}, ${track.type === "audio" ? track.primary ? "primary audio" : "audio" : track.text_source ?? "unknown source"}, ${track.status ?? "ready"}]`).join("; ");
4718
+ return describeTrackSummaries(tracks.map(summarizeTextTrack));
4719
+ }
4720
+ function describeTrackSummaries(tracks) {
4721
+ return tracks.map((track) => `${track.name ?? "(unnamed)"} [${track.languageCode ?? "?"}, ${track.type === "audio" ? track.primary ? "primary audio" : "audio" : track.textSource ?? "unknown source"}, ${track.status ?? "ready"}]`).join("; ");
4406
4722
  }
4407
4723
  function planTextTrackReplacement(asset, target, policy) {
4408
4724
  const label = targetType(target) === "audio" ? "Audio" : "Text";
4725
+ const sameLanguage = findSameLanguageTextTracks(asset, target);
4726
+ const sameLanguageIds = new Set(sameLanguage.map((track) => track.id));
4409
4727
  const conflicts = /* @__PURE__ */ new Map();
4410
- for (const track of [...findSameLanguageTextTracks(asset, target), ...findNameCollisionTextTracks(asset, target)]) {
4728
+ for (const track of [...sameLanguage, ...findNameCollisionTextTracks(asset, target)]) {
4411
4729
  conflicts.set(track.id, track);
4412
4730
  }
4413
4731
  const conflicting = [...conflicts.values()];
4414
4732
  if (conflicting.length === 0) {
4415
4733
  return { kind: "clear" };
4416
4734
  }
4735
+ const blocked = (code, reason, tracks) => ({
4736
+ kind: "blocked",
4737
+ reason,
4738
+ code,
4739
+ tracks: tracks.map(summarizeTextTrack),
4740
+ conflictsOnLanguage: tracks.some((track) => sameLanguageIds.has(track.id))
4741
+ });
4417
4742
  if (policy === "fail") {
4418
- return {
4419
- kind: "blocked",
4420
- reason: `${countTracks(conflicting, label, "already exists", "already exist")} for language '${target.languageCode}' or name '${target.name}': ${describeTracks(conflicting)}. Set replaceExistingTracks to replace ${itOrThem(conflicting)}.`,
4421
- tracks: conflicting.map(summarizeTextTrack)
4422
- };
4743
+ return blocked(
4744
+ "policy_fail",
4745
+ `${countTracks(conflicting, label, "already exists", "already exist")} for language '${target.languageCode}' or name '${target.name}': ${describeTracks(conflicting)}. Set replaceExistingTracks to replace ${itOrThem(conflicting)}.`,
4746
+ conflicting
4747
+ );
4423
4748
  }
4424
4749
  const primary = conflicting.filter((track) => track.type === "audio" && track.primary === true);
4425
4750
  if (primary.length > 0) {
4426
- return {
4427
- kind: "blocked",
4428
- reason: `The asset's primary audio track is in the way for language '${target.languageCode}' or name '${target.name}': ${describeTracks(primary)}. Primary audio cannot be replaced; choose a different trackName.`,
4429
- tracks: primary.map(summarizeTextTrack)
4430
- };
4751
+ return blocked(
4752
+ "primary_audio",
4753
+ `The asset's primary audio track is in the way for language '${target.languageCode}' or name '${target.name}': ${describeTracks(primary)}. Primary audio cannot be replaced; choose a different trackName.`,
4754
+ primary
4755
+ );
4431
4756
  }
4432
4757
  if (policy === "replace_generated") {
4433
4758
  const notGenerated = conflicting.filter((track) => track.type !== "text" || !isMuxGeneratedTextTrack(track));
4434
4759
  if (notGenerated.length > 0) {
4435
- return {
4436
- kind: "blocked",
4437
- reason: `${countTracks(notGenerated, label, "that is not Mux-generated exists", "that are not Mux-generated exist")} for language '${target.languageCode}' or name '${target.name}': ${describeTracks(notGenerated)}. Use replaceExistingTracks: "replace_all" to replace ${itOrThem(notGenerated)}.`,
4438
- tracks: notGenerated.map(summarizeTextTrack)
4439
- };
4760
+ return blocked(
4761
+ "not_generated",
4762
+ `${countTracks(notGenerated, label, "that is not Mux-generated exists", "that are not Mux-generated exist")} for language '${target.languageCode}' or name '${target.name}': ${describeTracks(notGenerated)}. Use replaceExistingTracks: "replace_all" to replace ${itOrThem(notGenerated)}.`,
4763
+ notGenerated
4764
+ );
4440
4765
  }
4441
4766
  }
4442
4767
  return { kind: "replace", toDelete: conflicting.map(summarizeTextTrack) };
@@ -4447,8 +4772,10 @@ function planSourceTrackReplacement(asset, sourceTrackId, target, policy) {
4447
4772
  if (blocking.length > 0) {
4448
4773
  return {
4449
4774
  kind: "blocked",
4775
+ code: "name_collision",
4450
4776
  reason: `${countTracks(blocking, "Text", "already has", "already have")} the name '${target.name}': ${describeTracks(blocking)}. Choose a different trackName.`,
4451
- tracks: blocking.map(summarizeTextTrack)
4777
+ tracks: blocking.map(summarizeTextTrack),
4778
+ conflictsOnLanguage: false
4452
4779
  };
4453
4780
  }
4454
4781
  const source = policy === "replace" ? listTracks(asset, targetType(target)).find((track) => track.id === sourceTrackId) : void 0;
@@ -4474,7 +4801,7 @@ function buildMuxAiTrackPassthrough(workflow) {
4474
4801
  }
4475
4802
  function validateTrackPassthrough(passthrough) {
4476
4803
  if (passthrough !== void 0 && passthrough.length > MUX_TRACK_PASSTHROUGH_MAX_CHARS) {
4477
- throw new MuxAiError(
4804
+ throw new LegacyMuxAiError(
4478
4805
  `Track passthrough must be at most ${MUX_TRACK_PASSTHROUGH_MAX_CHARS} characters (received ${passthrough.length}).`,
4479
4806
  { type: "validation_error" }
4480
4807
  );
@@ -5153,27 +5480,27 @@ async function editCaptionsInternal(assetId, trackId, options, collectedUsage) {
5153
5480
  const hasReplacements = !!replacementsOption && replacementsOption.length > 0;
5154
5481
  const hasSpeakerReplacements = !!speakerReplacementsOption && speakerReplacementsOption.length > 0;
5155
5482
  if (!hasAutoCensor && !hasReplacements && !hasSpeakerReplacements) {
5156
- throw new MuxAiError("At least one of autoCensorProfanity, replacements, or speakerReplacements must be provided.", { type: "validation_error" });
5483
+ throw new LegacyMuxAiError("At least one of autoCensorProfanity, replacements, or speakerReplacements must be provided.", { type: "validation_error" });
5157
5484
  }
5158
5485
  if (autoCensorOption && !provider) {
5159
- throw new MuxAiError("provider is required when using autoCensorProfanity.", { type: "validation_error" });
5486
+ throw new LegacyMuxAiError("provider is required when using autoCensorProfanity.", { type: "validation_error" });
5160
5487
  }
5161
5488
  const legacyTrackNaming = deleteOriginalTrack !== void 0 || trackNameSuffix !== void 0;
5162
5489
  if (legacyTrackNaming && (replaceExistingTracksOption !== void 0 || providedTrackName !== void 0)) {
5163
- throw new MuxAiError(
5490
+ throw new LegacyMuxAiError(
5164
5491
  "deleteOriginalTrack and trackNameSuffix are deprecated and cannot be combined with replaceExistingTracks or trackName.",
5165
5492
  { type: "validation_error" }
5166
5493
  );
5167
5494
  }
5168
5495
  if (replaceExistingTracksOption !== void 0 && replaceExistingTracksOption !== "replace" && replaceExistingTracksOption !== "fail") {
5169
- throw new MuxAiError(
5496
+ throw new LegacyMuxAiError(
5170
5497
  `replaceExistingTracks must be "replace" or "fail" for editCaptions (received "${String(replaceExistingTracksOption)}").`,
5171
5498
  { type: "validation_error" }
5172
5499
  );
5173
5500
  }
5174
5501
  const replaceExistingTracks = replaceExistingTracksOption ?? "replace";
5175
5502
  if (!legacyTrackNaming && replaceExistingTracks === "fail" && !providedTrackName) {
5176
- throw new MuxAiError(
5503
+ throw new LegacyMuxAiError(
5177
5504
  `trackName is required when replaceExistingTracks is "fail": the edited track cannot reuse the source track's name while the source is kept.`,
5178
5505
  { type: "validation_error" }
5179
5506
  );
@@ -5186,7 +5513,7 @@ async function editCaptionsInternal(assetId, trackId, options, collectedUsage) {
5186
5513
  const hasInvalidFindCharacter = replacement.find.includes("[") || replacement.find.includes("]") || /[\r\n]/.test(replacement.find);
5187
5514
  const hasInvalidReplaceCharacter = replacement.replace.includes("[") || replacement.replace.includes("]") || /[\r\n]/.test(replacement.replace);
5188
5515
  if (!replacement.find || !replacement.replace || hasInvalidFindCharacter || hasInvalidReplaceCharacter) {
5189
- throw new MuxAiError(
5516
+ throw new LegacyMuxAiError(
5190
5517
  "Speaker replacement labels must be non-empty and must not contain square brackets or newlines.",
5191
5518
  { type: "validation_error" }
5192
5519
  );
@@ -5198,7 +5525,7 @@ async function editCaptionsInternal(assetId, trackId, options, collectedUsage) {
5198
5525
  const s3AccessKeyId = env_default.S3_ACCESS_KEY_ID;
5199
5526
  const s3SecretAccessKey = env_default.S3_SECRET_ACCESS_KEY;
5200
5527
  if (uploadToS3 && (!s3Endpoint || !s3Bucket || !storageAdapter && (!s3AccessKeyId || !s3SecretAccessKey))) {
5201
- throw new MuxAiError(
5528
+ throw new LegacyMuxAiError(
5202
5529
  "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.",
5203
5530
  { type: "validation_error" }
5204
5531
  );
@@ -5207,7 +5534,7 @@ async function editCaptionsInternal(assetId, trackId, options, collectedUsage) {
5207
5534
  const assetDurationSeconds = getAssetDurationSecondsFromAsset(assetData);
5208
5535
  const signingContext = await resolveMuxSigningContext(credentials);
5209
5536
  if (policy === "signed" && !signingContext) {
5210
- throw new MuxAiError(
5537
+ throw new LegacyMuxAiError(
5211
5538
  "Signed playback ID requires signing credentials. Set MUX_SIGNING_KEY and MUX_PRIVATE_KEY environment variables.",
5212
5539
  { type: "validation_error" }
5213
5540
  );
@@ -5216,7 +5543,7 @@ async function editCaptionsInternal(assetId, trackId, options, collectedUsage) {
5216
5543
  const sourceTrack = readyTextTracks.find((t) => t.id === trackId);
5217
5544
  if (!sourceTrack) {
5218
5545
  const availableTrackIds = readyTextTracks.map((t) => t.id).filter(Boolean).join(", ");
5219
- throw new MuxAiError(
5546
+ throw new LegacyMuxAiError(
5220
5547
  `Track ${trackId} not found or not ready on asset ${assetId}. Available track IDs: ${availableTrackIds || "none"}.`,
5221
5548
  { type: "validation_error" }
5222
5549
  );
@@ -5228,7 +5555,7 @@ async function editCaptionsInternal(assetId, trackId, options, collectedUsage) {
5228
5555
  name: providedTrackName ?? sourceName
5229
5556
  };
5230
5557
  if (replaceExistingTracks === "fail" && normalizeTrackName(outputTrack.name) === normalizeTrackName(sourceName)) {
5231
- throw new MuxAiError(
5558
+ throw new LegacyMuxAiError(
5232
5559
  `trackName "${outputTrack.name}" matches the source track's name. Mux track names must be unique; choose a different trackName or use replaceExistingTracks: "replace" to replace the source.`,
5233
5560
  { type: "validation_error" }
5234
5561
  );
@@ -5236,7 +5563,7 @@ async function editCaptionsInternal(assetId, trackId, options, collectedUsage) {
5236
5563
  if (uploadToMux && !legacyTrackNaming) {
5237
5564
  const plan = planSourceTrackReplacement(assetData, trackId, outputTrack, replaceExistingTracks);
5238
5565
  if (plan.kind === "blocked") {
5239
- throw new MuxAiError(plan.reason, { type: "validation_error" });
5566
+ throw new LegacyMuxAiError(plan.reason, { type: "validation_error" });
5240
5567
  }
5241
5568
  }
5242
5569
  const vttUrl = await buildTranscriptUrl(playbackId, trackId, policy === "signed", credentials);
@@ -5244,7 +5571,7 @@ async function editCaptionsInternal(assetId, trackId, options, collectedUsage) {
5244
5571
  try {
5245
5572
  vttContent = await fetchVttFromMux(vttUrl);
5246
5573
  } catch (error) {
5247
- wrapError(error, "Failed to fetch VTT content");
5574
+ legacyWrapError(error, "Failed to fetch VTT content");
5248
5575
  }
5249
5576
  let editedVtt = vttContent;
5250
5577
  let totalReplacementCount = 0;
@@ -5255,7 +5582,7 @@ async function editCaptionsInternal(assetId, trackId, options, collectedUsage) {
5255
5582
  const { mode = "blank", alwaysCensor = [], neverCensor = [] } = autoCensorOption;
5256
5583
  const plainText = extractTextFromVTT(vttContent);
5257
5584
  if (!plainText.trim()) {
5258
- throw new MuxAiError("Track transcript is empty; nothing to censor.", { type: "validation_error" });
5585
+ throw new LegacyMuxAiError("Track transcript is empty; nothing to censor.", { type: "validation_error" });
5259
5586
  }
5260
5587
  const modelConfig = resolveLanguageModelConfig({
5261
5588
  ...options,
@@ -5282,7 +5609,7 @@ async function editCaptionsInternal(assetId, trackId, options, collectedUsage) {
5282
5609
  }
5283
5610
  }
5284
5611
  } catch (error) {
5285
- wrapError(error, `Failed to detect profanity with ${modelConfig.provider}`);
5612
+ legacyWrapError(error, `Failed to detect profanity with ${modelConfig.provider}`);
5286
5613
  }
5287
5614
  const scrubbedProfanity = detectedProfanity.map((word, i) => safety.scrubDetailed(word, `profanity[${i}]`)).filter((result) => !result.leaked).map((result) => result.text);
5288
5615
  const finalProfanity = applyOverrideLists(scrubbedProfanity, alwaysCensor, neverCensor);
@@ -5330,7 +5657,7 @@ async function editCaptionsInternal(assetId, trackId, options, collectedUsage) {
5330
5657
  try {
5331
5658
  presignedUrl = await uploadEditedVttToS3({ editedVtt, ...s3Config });
5332
5659
  } catch (error) {
5333
- wrapError(error, "Failed to upload VTT to S3");
5660
+ legacyWrapError(error, "Failed to upload VTT to S3");
5334
5661
  }
5335
5662
  if (uploadToMux && legacyTrackNaming) {
5336
5663
  try {
@@ -5344,13 +5671,13 @@ async function editCaptionsInternal(assetId, trackId, options, collectedUsage) {
5344
5671
  { closedCaptions: sourceTrack.closed_captions, passthrough: trackPassthrough }
5345
5672
  );
5346
5673
  } catch (error) {
5347
- wrapError(error, "Failed to add edited track to Mux asset");
5674
+ legacyWrapError(error, "Failed to add edited track to Mux asset");
5348
5675
  }
5349
5676
  if (deleteOriginal && uploadedTrackId) {
5350
5677
  try {
5351
5678
  await deleteTrackOnMux(assetId, trackId, credentials);
5352
5679
  } catch (error) {
5353
- wrapError(error, "Failed to delete original track");
5680
+ legacyWrapError(error, "Failed to delete original track");
5354
5681
  }
5355
5682
  }
5356
5683
  } else if (uploadToMux) {
@@ -5367,7 +5694,7 @@ async function editCaptionsInternal(assetId, trackId, options, collectedUsage) {
5367
5694
  credentials
5368
5695
  });
5369
5696
  } catch (error) {
5370
- wrapError(error, "Failed to add edited track to Mux asset");
5697
+ legacyWrapError(error, "Failed to add edited track to Mux asset");
5371
5698
  }
5372
5699
  if (outcome.kind !== "created") {
5373
5700
  const sourceWasDeleted = outcome.deleted.some((track) => track.id === trackId);
@@ -5389,7 +5716,7 @@ async function editCaptionsInternal(assetId, trackId, options, collectedUsage) {
5389
5716
  }
5390
5717
  }
5391
5718
  if (outcome.kind === "blocked") {
5392
- throw new MuxAiError(`${outcome.reason}${restoreNote}`, { type: "validation_error" });
5719
+ throw new LegacyMuxAiError(`${outcome.reason}${restoreNote}`, { type: "validation_error" });
5393
5720
  }
5394
5721
  throw new Error(`Failed to add edited track to Mux asset: ${outcome.reason}.${restoreNote}`);
5395
5722
  }
@@ -5829,6 +6156,74 @@ import { generateText as generateText6, Output as Output6 } from "ai";
5829
6156
  import dedent6 from "dedent";
5830
6157
  import { z as z7 } from "zod";
5831
6158
 
6159
+ // src/lib/dependency-error.ts
6160
+ function classifyDependencyFailure(init) {
6161
+ const { call, status, requestId, facts, timedOut } = init;
6162
+ const transient = timedOut === true || isTransientStatus(status);
6163
+ let source;
6164
+ let type;
6165
+ if (transient) {
6166
+ source = MUX_AI_ERROR_SOURCES.UPSTREAM;
6167
+ type = timedOut || status === 408 ? MUX_AI_ERROR_TYPES.TIMEOUT_ERROR : status === 429 ? MUX_AI_ERROR_TYPES.CAPACITY_ERROR : MUX_AI_ERROR_TYPES.PROCESSING_ERROR;
6168
+ } else {
6169
+ source = status === 404 ? init.notFoundSource ?? MUX_AI_ERROR_SOURCES.INTERNAL : status === 401 || status === 403 ? init.authSource ?? MUX_AI_ERROR_SOURCES.INTERNAL : MUX_AI_ERROR_SOURCES.INTERNAL;
6170
+ type = source === MUX_AI_ERROR_SOURCES.INTERNAL ? MUX_AI_ERROR_TYPES.SERVER_ERROR : MUX_AI_ERROR_TYPES.VALIDATION_ERROR;
6171
+ }
6172
+ return {
6173
+ type,
6174
+ source,
6175
+ facts: {
6176
+ call,
6177
+ ...status !== void 0 && { status },
6178
+ ...requestId && { requestId },
6179
+ ...facts
6180
+ },
6181
+ // Set here, not left to the default: only the call site knows a missing status
6182
+ // means no response (transient), rather than a failure the dependency reported.
6183
+ // A non-idempotent call may have taken effect only with no response or a 5xx;
6184
+ // a 408, 425 or 429 means it wasn't processed, so retrying stays safe.
6185
+ transient: init.transient ?? (init.idempotent === false && (status === void 0 || status >= 500) ? false : transient),
6186
+ ...init.retryable !== void 0 && { retryable: init.retryable }
6187
+ };
6188
+ }
6189
+ function dependencyError(message, init) {
6190
+ const { source, ...classification } = classifyDependencyFailure(init);
6191
+ const where = { source, dependency: init.dependency };
6192
+ return new MuxAiError(message, { ...classification, ...where, cause: init.cause });
6193
+ }
6194
+ function httpStatusOf(error) {
6195
+ if (typeof error !== "object" || error === null) {
6196
+ return void 0;
6197
+ }
6198
+ const { status, statusCode } = error;
6199
+ const candidate = typeof status === "number" ? status : statusCode;
6200
+ return typeof candidate === "number" && candidate >= 100 && candidate < 600 ? candidate : void 0;
6201
+ }
6202
+ function requestIdOf(headers) {
6203
+ if (!headers || typeof headers !== "object") {
6204
+ return void 0;
6205
+ }
6206
+ const names = ["x-request-id", "x-amz-request-id", "request-id"];
6207
+ for (const name of names) {
6208
+ const value = typeof headers.get === "function" ? headers.get(name) : headers[name];
6209
+ if (typeof value === "string" && value) {
6210
+ return value;
6211
+ }
6212
+ }
6213
+ return void 0;
6214
+ }
6215
+ function dependencyErrorFrom(error, message, init) {
6216
+ if (MuxAiError.is(error)) {
6217
+ return error;
6218
+ }
6219
+ return dependencyError(message, {
6220
+ ...init,
6221
+ status: httpStatusOf(error),
6222
+ requestId: requestIdOf(error?.headers),
6223
+ cause: error
6224
+ });
6225
+ }
6226
+
5832
6227
  // src/primitives/heatmap.ts
5833
6228
  async function getHeatmapForAsset(assetId, options = {}) {
5834
6229
  "use step";
@@ -6213,6 +6608,15 @@ async function getThumbnailUrlsForHotspots(playbackId, hotspots, options = {}) {
6213
6608
  });
6214
6609
  return Promise.all(urlPromises);
6215
6610
  }
6611
+ function engagementDataError(error, call, assetId, timeframe) {
6612
+ return dependencyErrorFrom(error, `Failed to fetch engagement data for asset ${assetId}.`, {
6613
+ dependency: MUX_AI_ERROR_DEPENDENCIES.MUX_DATA,
6614
+ call,
6615
+ facts: { assetId, timeframe },
6616
+ notFoundSource: MUX_AI_ERROR_SOURCES.ASSET,
6617
+ authSource: MUX_AI_ERROR_SOURCES.ACCOUNT
6618
+ });
6619
+ }
6216
6620
  async function fetchEngagementData(assetId, options) {
6217
6621
  "use step";
6218
6622
  const { hotspotLimit, timeframe, credentials } = options;
@@ -6222,16 +6626,22 @@ async function fetchEngagementData(assetId, options) {
6222
6626
  orderDirection: "desc",
6223
6627
  timeframe,
6224
6628
  credentials
6629
+ }).catch((error) => {
6630
+ throw engagementDataError(error, "get_hotspots", assetId, timeframe);
6225
6631
  }),
6226
6632
  getHotspotsForAsset(assetId, {
6227
6633
  limit: hotspotLimit,
6228
6634
  orderDirection: "asc",
6229
6635
  timeframe,
6230
6636
  credentials
6637
+ }).catch((error) => {
6638
+ throw engagementDataError(error, "get_hotspots", assetId, timeframe);
6231
6639
  }),
6232
6640
  getHeatmapForAsset(assetId, {
6233
6641
  timeframe,
6234
6642
  credentials
6643
+ }).catch((error) => {
6644
+ throw engagementDataError(error, "get_heatmap", assetId, timeframe);
6235
6645
  })
6236
6646
  ]);
6237
6647
  const allHotspots = [...peaks, ...valleys].sort((a, b) => a.startMs - b.startMs);
@@ -6261,7 +6671,13 @@ async function generateInsightsWithAI(provider, modelId, systemPrompt, userPromp
6261
6671
  }));
6262
6672
  const output = getGeneratedOutputWithContentPolicyHandling(response);
6263
6673
  if (!output) {
6264
- throw new Error("AI returned empty or unparseable response");
6674
+ throw new MuxAiError("AI returned empty or unparseable response", {
6675
+ code: MUX_AI_ERROR_CODES.MODEL_OUTPUT_MISSING,
6676
+ type: MUX_AI_ERROR_TYPES.PROCESSING_ERROR,
6677
+ source: MUX_AI_ERROR_SOURCES.UPSTREAM,
6678
+ dependency: MUX_AI_ERROR_DEPENDENCIES.AI_PROVIDER,
6679
+ facts: { call: "generate_engagement_insights", provider, model: modelId }
6680
+ });
6265
6681
  }
6266
6682
  const unexpectedRootKeys = detectUnexpectedKeysFromRawText(
6267
6683
  response.text,
@@ -6316,7 +6732,12 @@ async function generateEngagementInsightsInternal(assetId, options, collectedUsa
6316
6732
  skipShots = false
6317
6733
  } = options;
6318
6734
  if (!Number.isInteger(hotspotLimit) || hotspotLimit < 1 || hotspotLimit > 10) {
6319
- throw new MuxAiError("hotspotLimit must be an integer between 1 and 10.", { type: "validation_error" });
6735
+ throw new MuxAiError("hotspotLimit must be an integer between 1 and 10.", {
6736
+ code: MUX_AI_ERROR_CODES.PARAMETER_OUT_OF_RANGE,
6737
+ type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR,
6738
+ source: MUX_AI_ERROR_SOURCES.REQUEST,
6739
+ facts: { parameter: "hotspotLimit", value: hotspotLimit, min: 1, max: 10, integer: true }
6740
+ });
6320
6741
  }
6321
6742
  const modelConfig = resolveLanguageModelConfig({
6322
6743
  ...options,
@@ -6326,15 +6747,17 @@ async function generateEngagementInsightsInternal(assetId, options, collectedUsa
6326
6747
  const { asset, playbackId, policy } = await getPlaybackIdForAsset(assetId, credentials, options.assetSnapshot);
6327
6748
  const assetDurationSeconds = getAssetDurationSecondsFromAsset(asset);
6328
6749
  if (!assetDurationSeconds) {
6329
- throw new MuxAiError(`Asset ${assetId} has no valid duration.`, { type: "validation_error" });
6750
+ throw new MuxAiError(`Asset ${assetId} has no valid duration.`, {
6751
+ code: MUX_AI_ERROR_CODES.ASSET_DURATION_UNAVAILABLE,
6752
+ type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR,
6753
+ source: MUX_AI_ERROR_SOURCES.ASSET,
6754
+ facts: { assetId }
6755
+ });
6330
6756
  }
6331
6757
  const audioOnly = isAudioOnlyAsset(asset);
6332
6758
  const signingContext = await resolveMuxSigningContext(credentials);
6333
6759
  if (policy === "signed" && !signingContext) {
6334
- throw new MuxAiError(
6335
- "Signed playback ID requires signing credentials. Set MUX_SIGNING_KEY and MUX_PRIVATE_KEY environment variables.",
6336
- { type: "validation_error" }
6337
- );
6760
+ throw signingCredentialsMissingError();
6338
6761
  }
6339
6762
  const shouldSign = policy === "signed";
6340
6763
  const shouldFetchShots = !skipShots && !audioOnly;
@@ -6361,9 +6784,7 @@ async function generateEngagementInsightsInternal(assetId, options, collectedUsa
6361
6784
  storyboardPromise
6362
6785
  ]);
6363
6786
  if (engagementResult.status === "rejected") {
6364
- throw new Error(
6365
- `Failed to fetch engagement data for asset ${assetId}: ${engagementResult.reason}`
6366
- );
6787
+ wrapError(engagementResult.reason, `Failed to fetch engagement data for asset ${assetId}`, { assetId, timeframe });
6367
6788
  }
6368
6789
  const { hotspots, heatmap } = engagementResult.value;
6369
6790
  if (hotspots.length === 0) {
@@ -6434,8 +6855,20 @@ async function generateEngagementInsightsInternal(assetId, options, collectedUsa
6434
6855
  );
6435
6856
  const { result: aiInsights, usage } = aiStepResult;
6436
6857
  collectedUsage.push(usage);
6858
+ const modelOutputFacts = {
6859
+ call: "generate_engagement_insights",
6860
+ provider: modelConfig.provider,
6861
+ model: modelConfig.modelId,
6862
+ assetId
6863
+ };
6437
6864
  if (!aiInsights.momentInsights || aiInsights.momentInsights.length === 0) {
6438
- throw new MuxAiError(`Failed to generate insights for asset ${assetId}.`);
6865
+ throw new MuxAiError(`Failed to generate insights for asset ${assetId}.`, {
6866
+ code: MUX_AI_ERROR_CODES.MODEL_OUTPUT_MISSING,
6867
+ type: MUX_AI_ERROR_TYPES.PROCESSING_ERROR,
6868
+ source: MUX_AI_ERROR_SOURCES.UPSTREAM,
6869
+ dependency: MUX_AI_ERROR_DEPENDENCIES.AI_PROVIDER,
6870
+ facts: modelOutputFacts
6871
+ });
6439
6872
  }
6440
6873
  const safety = createSafetyReporter();
6441
6874
  for (const key of aiStepResult.unexpectedRootKeys) {
@@ -6475,7 +6908,14 @@ async function generateEngagementInsightsInternal(assetId, options, collectedUsa
6475
6908
  }
6476
6909
  if (momentInsights.length === 0) {
6477
6910
  throw new MuxAiError(
6478
- `Failed to generate valid insights for asset ${assetId}.`
6911
+ `Failed to generate valid insights for asset ${assetId}.`,
6912
+ {
6913
+ code: MUX_AI_ERROR_CODES.MODEL_OUTPUT_INVALID,
6914
+ type: MUX_AI_ERROR_TYPES.PROCESSING_ERROR,
6915
+ source: MUX_AI_ERROR_SOURCES.UPSTREAM,
6916
+ dependency: MUX_AI_ERROR_DEPENDENCIES.AI_PROVIDER,
6917
+ facts: { ...modelOutputFacts, returnedCount: aiInsights.momentInsights.length }
6918
+ }
6479
6919
  );
6480
6920
  }
6481
6921
  const summaryScrub = safety.scrubDetailed(aiInsights.overallInsight.summary, "overallInsight.summary");
@@ -6526,7 +6966,7 @@ var KEY_PATTERN = /^[a-z][a-z0-9_]{0,63}$/;
6526
6966
  var LANGUAGE_TAG_PATTERN = /^[a-z]{2,3}(?:-[a-z0-9]{2,8})*$/i;
6527
6967
  var LENGTH_UNITS = ["characters", "words"];
6528
6968
  function validationError(message) {
6529
- return new MuxAiError(message, { type: "validation_error" });
6969
+ return new LegacyMuxAiError(message, { type: "validation_error" });
6530
6970
  }
6531
6971
  function assertOneOf(value, allowed, label) {
6532
6972
  if (!allowed.includes(value)) {
@@ -6710,7 +7150,7 @@ function scrubBrief(brief, safety) {
6710
7150
  const centralIdea = safety.scrubDetailed(brief.centralIdea, "editorial_brief.centralIdea");
6711
7151
  const readerValue = safety.scrubDetailed(brief.readerValue, "editorial_brief.readerValue");
6712
7152
  if (centralIdea.leaked || readerValue.leaked || !centralIdea.text.trim()) {
6713
- throw new MuxAiError(
7153
+ throw new LegacyMuxAiError(
6714
7154
  "The editorial brief was suppressed by the output safety filter.",
6715
7155
  { type: "processing_error", retryable: true }
6716
7156
  );
@@ -7013,11 +7453,11 @@ ${renderSection({ tag: "revision_request", content: "The previous draft was empt
7013
7453
  let failure;
7014
7454
  if (isIncompleteGenerationError(cause)) {
7015
7455
  failure = new IncompleteGenerationError(cause.finishReason, cause.rawFinishReason);
7016
- } else if (MuxAiError.is(cause)) {
7017
- failure = new MuxAiError(cause.publicMessage, { type: cause.publicType, retryable: cause.retryable });
7456
+ } else if (isLegacyMuxAiError(cause)) {
7457
+ failure = new LegacyMuxAiError(cause.publicMessage, { type: cause.publicType, retryable: cause.retryable });
7018
7458
  } else {
7019
7459
  const apiError = APICallError4.isInstance(cause) ? cause : void 0;
7020
- failure = new MuxAiError("Unable to complete text generation.", {
7460
+ failure = new LegacyMuxAiError("Unable to complete text generation.", {
7021
7461
  type: "processing_error",
7022
7462
  retryable: apiError?.isRetryable ?? true,
7023
7463
  cause
@@ -7061,7 +7501,7 @@ async function generateArtifactsInBatches(requests, collectedUsage, provider) {
7061
7501
  collectedUsage.push(usage);
7062
7502
  }
7063
7503
  }
7064
- wrapError(failures[0], `Failed to generate text with ${provider}`);
7504
+ legacyWrapError(failures[0], `Failed to generate text with ${provider}`);
7065
7505
  }
7066
7506
  }
7067
7507
  return results;
@@ -7099,14 +7539,14 @@ async function generateTextInternal(assetId, rawOptions, collectedUsage) {
7099
7539
  getVideoTrackDurationSecondsFromAsset(asset)
7100
7540
  );
7101
7541
  if (useShots && isAudioOnly) {
7102
- throw new MuxAiError("useShots is not supported for audio-only assets.", { type: "validation_error" });
7542
+ throw new LegacyMuxAiError("useShots is not supported for audio-only assets.", { type: "validation_error" });
7103
7543
  }
7104
7544
  if (useShots && assetDurationSeconds === void 0) {
7105
- throw new MuxAiError("Asset has no valid duration.", { type: "validation_error" });
7545
+ throw new LegacyMuxAiError("Asset has no valid duration.", { type: "validation_error" });
7106
7546
  }
7107
7547
  const signingContext = await resolveMuxSigningContext(credentials);
7108
7548
  if (policy === "signed" && !signingContext) {
7109
- throw new MuxAiError(
7549
+ throw new LegacyMuxAiError(
7110
7550
  "Signed playback ID requires signing credentials. Set MUX_SIGNING_KEY and MUX_PRIVATE_KEY environment variables.",
7111
7551
  { type: "validation_error" }
7112
7552
  );
@@ -7126,7 +7566,7 @@ async function generateTextInternal(assetId, rawOptions, collectedUsage) {
7126
7566
  ]);
7127
7567
  const transcriptText = transcriptResult.transcriptText.trim();
7128
7568
  if (!transcriptText) {
7129
- throw new MuxAiError(
7569
+ throw new LegacyMuxAiError(
7130
7570
  effectiveScope ? "Transcript has no usable content in the requested scope." : "Transcript has no usable content.",
7131
7571
  { type: "validation_error" }
7132
7572
  );
@@ -7146,7 +7586,7 @@ async function generateTextInternal(assetId, rawOptions, collectedUsage) {
7146
7586
  userPrompt: buildBriefUserPrompt({ transcriptText, imageCount: imageUrls.length, audience, languageName }),
7147
7587
  imageUrls,
7148
7588
  credentials
7149
- }).catch((error) => wrapError(error, `Failed to extract editorial brief with ${provider}`));
7589
+ }).catch((error) => legacyWrapError(error, `Failed to extract editorial brief with ${provider}`));
7150
7590
  collectedUsage.push(briefStep.usage);
7151
7591
  for (const key of briefStep.unexpectedKeys) {
7152
7592
  safety.record(`editorial_brief.${key}`, "unexpected_key");
@@ -7175,10 +7615,10 @@ async function generateTextInternal(assetId, rawOptions, collectedUsage) {
7175
7615
  safety.record(`${field}.${key}`, "unexpected_key");
7176
7616
  }
7177
7617
  if (item.violation === "empty") {
7178
- throw new MuxAiError(`Generated text for ${field} was empty after a retry.`, { type: "processing_error", retryable: true });
7618
+ throw new LegacyMuxAiError(`Generated text for ${field} was empty after a retry.`, { type: "processing_error", retryable: true });
7179
7619
  }
7180
7620
  if (item.violation) {
7181
- throw new MuxAiError(
7621
+ throw new LegacyMuxAiError(
7182
7622
  `Generated text for ${field} exceeded the ${item.violation.limit.value} ${item.violation.limit.unit} limit after a retry (${item.violation.actual} returned).`,
7183
7623
  { type: "processing_error", retryable: true }
7184
7624
  );
@@ -8056,7 +8496,7 @@ async function getModerationScores(assetId, options = {}) {
8056
8496
  };
8057
8497
  } else {
8058
8498
  if (!captionTrack.id) {
8059
- throw new MuxAiError("Transcript track is missing an id.", { type: "validation_error" });
8499
+ throw new LegacyMuxAiError("Transcript track is missing an id.", { type: "validation_error" });
8060
8500
  }
8061
8501
  const transcriptUrl = await buildTranscriptUrl(playbackId, captionTrack.id, policy === "signed", credentials);
8062
8502
  const { transcriptText, emptyReason } = await fetchTranscriptDataForUrl(transcriptUrl, {
@@ -8084,7 +8524,7 @@ async function getModerationScores(assetId, options = {}) {
8084
8524
  }
8085
8525
  }
8086
8526
  if (!shouldRunThumbnails && !shouldRunTranscript) {
8087
- throw new MuxAiError(
8527
+ throw new LegacyMuxAiError(
8088
8528
  `Nothing to moderate. Thumbnails skipped: ${thumbnailModeration.skipMessage} Transcript skipped: ${transcriptModeration.skipMessage}`,
8089
8529
  { type: "validation_error" }
8090
8530
  );
@@ -8687,7 +9127,7 @@ async function getSummaryAndTagsInternal(assetId, options, collectedUsage) {
8687
9127
  scope
8688
9128
  } = options ?? {};
8689
9129
  if (!VALID_TONES.includes(tone)) {
8690
- throw new MuxAiError(
9130
+ throw new LegacyMuxAiError(
8691
9131
  `Invalid tone "${tone}". Valid tones are: ${VALID_TONES.join(", ")}.`,
8692
9132
  { type: "validation_error" }
8693
9133
  );
@@ -8712,7 +9152,7 @@ async function getSummaryAndTagsInternal(assetId, options, collectedUsage) {
8712
9152
  resolveWorkflowScope(effectiveScope, assetDurationSeconds);
8713
9153
  }
8714
9154
  if (isAudioOnly && !includeTranscript) {
8715
- throw new MuxAiError(
9155
+ throw new LegacyMuxAiError(
8716
9156
  "Audio-only assets require a transcript. Set includeTranscript: true and ensure the asset has a ready text track (captions/subtitles).",
8717
9157
  { type: "validation_error" }
8718
9158
  );
@@ -8720,7 +9160,7 @@ async function getSummaryAndTagsInternal(assetId, options, collectedUsage) {
8720
9160
  const signingContext = await resolveMuxSigningContext(workflowCredentials);
8721
9161
  const requiresSignedPlaybackAccess = includeTranscript || !isAudioOnly;
8722
9162
  if (policy === "signed" && requiresSignedPlaybackAccess && !signingContext) {
8723
- throw new MuxAiError(
9163
+ throw new LegacyMuxAiError(
8724
9164
  "Signed playback ID requires signing credentials. Set MUX_SIGNING_KEY and MUX_PRIVATE_KEY environment variables.",
8725
9165
  { type: "validation_error" }
8726
9166
  );
@@ -8799,18 +9239,18 @@ async function getSummaryAndTagsInternal(assetId, options, collectedUsage) {
8799
9239
  }
8800
9240
  } catch (error) {
8801
9241
  const contentType = isAudioOnly ? "audio" : "video";
8802
- wrapError(error, `Failed to analyze ${contentType} content with ${provider}`);
9242
+ legacyWrapError(error, `Failed to analyze ${contentType} content with ${provider}`);
8803
9243
  }
8804
9244
  collectedUsage.push(analysisResponse.usage);
8805
9245
  if (!analysisResponse.result) {
8806
9246
  const contentType = isAudioOnly ? "audio" : "video";
8807
- throw new MuxAiError(`Failed to analyze ${contentType} content for asset ${assetId}.`);
9247
+ throw new LegacyMuxAiError(`Failed to analyze ${contentType} content for asset ${assetId}.`);
8808
9248
  }
8809
9249
  if (!analysisResponse.result.title) {
8810
- throw new MuxAiError(`Failed to generate title for asset ${assetId}.`);
9250
+ throw new LegacyMuxAiError(`Failed to generate title for asset ${assetId}.`);
8811
9251
  }
8812
9252
  if (!analysisResponse.result.description) {
8813
- throw new MuxAiError(`Failed to generate description for asset ${assetId}.`);
9253
+ throw new LegacyMuxAiError(`Failed to generate description for asset ${assetId}.`);
8814
9254
  }
8815
9255
  const safety = createSafetyReporter();
8816
9256
  if (analysisResponse.unexpectedKeys.length > 0) {
@@ -8942,10 +9382,7 @@ function resolveLegacyMp4SupportRendition(asset) {
8942
9382
  return { kind: "preparing" };
8943
9383
  }
8944
9384
  if (status !== "ready") {
8945
- return {
8946
- kind: "unusable",
8947
- reason: `This asset uses the deprecated mp4_support setting, and its static renditions are ${status}. Move the asset to the Static Renditions API (${STATIC_RENDITIONS_GUIDE_URL}) and add an audio-only static rendition, then retry.`
8948
- };
9385
+ return { kind: "unusable", reason: legacyMp4SupportUnusableMessage({ status }), mp4Support: asset.mp4_support, status };
8949
9386
  }
8950
9387
  const files = asset.static_renditions?.files ?? [];
8951
9388
  for (const name of LEGACY_MP4_SUPPORT_FILE_PREFERENCE[asset.mp4_support] ?? []) {
@@ -8954,10 +9391,14 @@ function resolveLegacyMp4SupportRendition(asset) {
8954
9391
  return { kind: "ready", name, filesizeBytes: parseFilesizeBytes(file.filesize) };
8955
9392
  }
8956
9393
  }
8957
- return {
8958
- kind: "unusable",
8959
- reason: `This asset uses the deprecated mp4_support setting ("${asset.mp4_support}"), and none of its static renditions can be used by this workflow. Move the asset to the Static Renditions API (${STATIC_RENDITIONS_GUIDE_URL}) and add an audio-only static rendition, then retry.`
8960
- };
9394
+ return { kind: "unusable", reason: legacyMp4SupportUnusableMessage({ mp4Support: asset.mp4_support }), mp4Support: asset.mp4_support };
9395
+ }
9396
+ var MOVE_TO_STATIC_RENDITIONS = `Move the asset to the Static Renditions API (${STATIC_RENDITIONS_GUIDE_URL}) and add an audio-only static rendition, then retry.`;
9397
+ function legacyMp4SupportUnusableMessage({ status, mp4Support }) {
9398
+ return status ? `This asset uses the deprecated mp4_support setting, and its static renditions are ${status}. ${MOVE_TO_STATIC_RENDITIONS}` : `This asset uses the deprecated mp4_support setting${mp4Support ? ` ("${mp4Support}")` : ""}, and none of its static renditions can be used by this workflow. ${MOVE_TO_STATIC_RENDITIONS}`;
9399
+ }
9400
+ function legacyMp4SupportTooLargeMessage({ name, filesizeBytes, maxBytes }) {
9401
+ return `This asset uses the deprecated mp4_support setting, and its ${name} static rendition (${formatGigabytes(filesizeBytes)}) is larger than the ${formatGigabytes(maxBytes)} this workflow can process. ${MOVE_TO_STATIC_RENDITIONS}`;
8961
9402
  }
8962
9403
  function formatGigabytes(bytes) {
8963
9404
  return `${Math.round(bytes / BYTES_PER_GB * 100) / 100} GB`;
@@ -8966,7 +9407,7 @@ function getLegacyMp4SupportRenditionSizeError(rendition, maxBytes) {
8966
9407
  if (rendition.filesizeBytes === void 0 || rendition.filesizeBytes <= maxBytes) {
8967
9408
  return void 0;
8968
9409
  }
8969
- return `This asset uses the deprecated mp4_support setting, and its ${rendition.name} static rendition (${formatGigabytes(rendition.filesizeBytes)}) is larger than the ${formatGigabytes(maxBytes)} this workflow can process. Move the asset to the Static Renditions API (${STATIC_RENDITIONS_GUIDE_URL}) and add an audio-only static rendition, then retry.`;
9410
+ return legacyMp4SupportTooLargeMessage({ name: rendition.name, filesizeBytes: rendition.filesizeBytes, maxBytes });
8970
9411
  }
8971
9412
 
8972
9413
  // src/workflows/translate-audio.ts
@@ -9018,7 +9459,7 @@ async function requestStaticRenditionCreation(assetId, credentials) {
9018
9459
  if (statusCode === 409 || alreadyDefined) {
9019
9460
  return void 0;
9020
9461
  }
9021
- wrapError(error, "Failed to request static rendition from Mux");
9462
+ legacyWrapError(error, "Failed to request static rendition from Mux");
9022
9463
  }
9023
9464
  }
9024
9465
  async function deleteCreatedStaticRendition(assetId, staticRenditionId, credentials) {
@@ -9068,12 +9509,12 @@ async function waitForAudioStaticRendition({
9068
9509
  `\u231B Waiting for static rendition (attempt ${attempt}/${STATIC_RENDITION_MAX_ATTEMPTS}) \u2192 ${currentStatus}`
9069
9510
  );
9070
9511
  if (currentStatus === "errored") {
9071
- throw new MuxAiError(
9512
+ throw new LegacyMuxAiError(
9072
9513
  "Mux failed to create the static rendition for this asset. Please check the asset in the Mux dashboard."
9073
9514
  );
9074
9515
  }
9075
9516
  }
9076
- throw new MuxAiError(
9517
+ throw new LegacyMuxAiError(
9077
9518
  "Timed out waiting for the static rendition to become ready. Please try again in a moment.",
9078
9519
  { type: "timeout_error", retryable: true }
9079
9520
  );
@@ -9092,23 +9533,23 @@ async function waitForLegacyMp4SupportRendition({
9092
9533
  rendition = resolveLegacyMp4SupportRendition(await retrieveAsset(assetId, credentials));
9093
9534
  }
9094
9535
  if (!rendition) {
9095
- throw new MuxAiError(
9536
+ throw new LegacyMuxAiError(
9096
9537
  "The asset's static rendition settings changed while waiting for them. Please try again.",
9097
9538
  { type: "processing_error", retryable: true }
9098
9539
  );
9099
9540
  }
9100
9541
  if (rendition.kind === "preparing") {
9101
- throw new MuxAiError(
9542
+ throw new LegacyMuxAiError(
9102
9543
  "Timed out waiting for the static rendition to become ready. Please try again in a moment.",
9103
9544
  { type: "timeout_error", retryable: true }
9104
9545
  );
9105
9546
  }
9106
9547
  if (rendition.kind === "unusable") {
9107
- throw new MuxAiError(rendition.reason, { type: "validation_error" });
9548
+ throw new LegacyMuxAiError(rendition.reason, { type: "validation_error" });
9108
9549
  }
9109
9550
  const sizeError = getLegacyMp4SupportRenditionSizeError(rendition, MAX_DUBBING_SOURCE_BYTES);
9110
9551
  if (sizeError) {
9111
- throw new MuxAiError(sizeError, { type: "validation_error" });
9552
+ throw new LegacyMuxAiError(sizeError, { type: "validation_error" });
9112
9553
  }
9113
9554
  return rendition.name;
9114
9555
  }
@@ -9130,19 +9571,19 @@ function audioTrackUnsupportedReason(asset) {
9130
9571
  }
9131
9572
  function dubbingProviderError(message, failure) {
9132
9573
  if (failure.reason === "timeout") {
9133
- return new MuxAiError(`${message} The dubbing service timed out. Please try again.`, { type: "timeout_error", retryable: true });
9574
+ return new LegacyMuxAiError(`${message} The dubbing service timed out. Please try again.`, { type: "timeout_error", retryable: true });
9134
9575
  }
9135
9576
  if (failure.retryable) {
9136
- return new MuxAiError(`${message} The dubbing service is temporarily unavailable. Please try again.`, { type: "processing_error", retryable: true });
9577
+ return new LegacyMuxAiError(`${message} The dubbing service is temporarily unavailable. Please try again.`, { type: "processing_error", retryable: true });
9137
9578
  }
9138
- return new MuxAiError(message, { type: "processing_error" });
9579
+ return new LegacyMuxAiError(message, { type: "processing_error" });
9139
9580
  }
9140
9581
  function dubbingStartError(failure, languages) {
9141
9582
  if (failure.reason === "unsupported_target_language") {
9142
- return new MuxAiError(`Audio dubbing does not support the target language "${languages.target}".`, { type: "validation_error" });
9583
+ return new LegacyMuxAiError(`Audio dubbing does not support the target language "${languages.target}".`, { type: "validation_error" });
9143
9584
  }
9144
9585
  if (failure.reason === "unsupported_source_language" && languages.source) {
9145
- return new MuxAiError(`Audio dubbing does not support the source language "${languages.source}".`, { type: "validation_error" });
9586
+ return new LegacyMuxAiError(`Audio dubbing does not support the source language "${languages.source}".`, { type: "validation_error" });
9146
9587
  }
9147
9588
  return dubbingProviderError("Audio dubbing could not be started.", failure);
9148
9589
  }
@@ -9377,11 +9818,11 @@ async function translateAudio(assetId, toLanguageCode, options = {}) {
9377
9818
  trackPassthrough: providedTrackPassthrough
9378
9819
  } = options;
9379
9820
  if (provider !== "elevenlabs") {
9380
- throw new MuxAiError("Only ElevenLabs provider is currently supported for audio translation.", { type: "validation_error" });
9821
+ throw new LegacyMuxAiError("Only ElevenLabs provider is currently supported for audio translation.", { type: "validation_error" });
9381
9822
  }
9382
9823
  const targetLanguageCode = toISO639_1(toLanguageCode);
9383
9824
  if (numSpeakers !== 0) {
9384
- throw new MuxAiError("The ElevenLabs project API does not support numSpeakers overrides. Omit it or use 0 for auto-detection.", { type: "validation_error" });
9825
+ throw new LegacyMuxAiError("The ElevenLabs project API does not support numSpeakers overrides. Omit it or use 0 for auto-detection.", { type: "validation_error" });
9385
9826
  }
9386
9827
  const credentials = providedCredentials;
9387
9828
  const effectiveStorageAdapter = storageAdapter;
@@ -9398,21 +9839,21 @@ async function translateAudio(assetId, toLanguageCode, options = {}) {
9398
9839
  const s3AccessKeyId = env_default.S3_ACCESS_KEY_ID;
9399
9840
  const s3SecretAccessKey = env_default.S3_SECRET_ACCESS_KEY;
9400
9841
  if (uploadToS3 && (!s3Endpoint || !s3Bucket || !effectiveStorageAdapter && (!s3AccessKeyId || !s3SecretAccessKey))) {
9401
- throw new MuxAiError("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" });
9842
+ 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" });
9402
9843
  }
9403
9844
  const { asset: initialAsset, playbackId, policy } = await getPlaybackIdForAsset(assetId, credentials, options.assetSnapshot);
9404
9845
  const assetDurationSeconds = getAssetDurationSecondsFromAsset(initialAsset);
9405
9846
  if (isVideoOnlyAsset(initialAsset)) {
9406
- throw new MuxAiError(`Asset ${assetId} has no audio track, so there is no audio to dub.`, { type: "validation_error" });
9847
+ throw new LegacyMuxAiError(`Asset ${assetId} has no audio track, so there is no audio to dub.`, { type: "validation_error" });
9407
9848
  }
9408
9849
  const audioTrackUnsupported = uploadToMux ? audioTrackUnsupportedReason(initialAsset) : void 0;
9409
9850
  if (audioTrackUnsupported) {
9410
- throw new MuxAiError(`Asset ${assetId} ${audioTrackUnsupported}`, { type: "validation_error" });
9851
+ throw new LegacyMuxAiError(`Asset ${assetId} ${audioTrackUnsupported}`, { type: "validation_error" });
9411
9852
  }
9412
9853
  if (uploadToMux) {
9413
9854
  const plan = planTextTrackReplacement(initialAsset, audioTrackTarget, replaceExistingTracks);
9414
9855
  if (plan.kind === "blocked") {
9415
- throw new MuxAiError(plan.reason, { type: "validation_error" });
9856
+ throw new LegacyMuxAiError(plan.reason, { type: "validation_error" });
9416
9857
  }
9417
9858
  }
9418
9859
  let currentAsset = initialAsset;
@@ -9454,7 +9895,7 @@ async function translateAudio(assetId, toLanguageCode, options = {}) {
9454
9895
  }
9455
9896
  const audioRendition = getReadyAudioStaticRendition(currentAsset);
9456
9897
  if (!audioRendition) {
9457
- throw new MuxAiError(
9898
+ throw new LegacyMuxAiError(
9458
9899
  "Unable to obtain an audio-only static rendition for this asset. Please verify static renditions are enabled in Mux.",
9459
9900
  { type: "validation_error" }
9460
9901
  );
@@ -9481,7 +9922,7 @@ async function translateAudio(assetId, toLanguageCode, options = {}) {
9481
9922
  credentials
9482
9923
  });
9483
9924
  } catch (error) {
9484
- wrapError(error, "Failed to create ElevenLabs dubbing job");
9925
+ legacyWrapError(error, "Failed to create ElevenLabs dubbing job");
9485
9926
  }
9486
9927
  if (created.kind === "failed") {
9487
9928
  const { failure } = created;
@@ -9512,7 +9953,7 @@ async function translateAudio(assetId, toLanguageCode, options = {}) {
9512
9953
  credentials
9513
9954
  });
9514
9955
  } catch (error) {
9515
- wrapError(error, "Failed to check dubbing status");
9956
+ legacyWrapError(error, "Failed to check dubbing status");
9516
9957
  }
9517
9958
  if (statusResult.kind === "failed") {
9518
9959
  const { failure } = statusResult;
@@ -9529,16 +9970,16 @@ async function translateAudio(assetId, toLanguageCode, options = {}) {
9529
9970
  if (dubbingStatus === "failed") {
9530
9971
  console.warn(`\u274C ElevenLabs dubbing project ${dubbingId} (language ${languageId}) failed: ${dubbingError ? `${dubbingError.code}: ${dubbingError.message}` : "no error reported"}`);
9531
9972
  if (!dubbingError) {
9532
- throw new MuxAiError("Audio dubbing failed.", { type: "processing_error" });
9973
+ throw new LegacyMuxAiError("Audio dubbing failed.", { type: "processing_error" });
9533
9974
  }
9534
- throw new MuxAiError(
9975
+ throw new LegacyMuxAiError(
9535
9976
  `Audio dubbing failed: ${dubbingError.message}${dubbingError.retryable ? " Please try again." : ""}`,
9536
9977
  { type: "processing_error", retryable: dubbingError.retryable }
9537
9978
  );
9538
9979
  }
9539
9980
  }
9540
9981
  if (dubbingStatus !== "completed") {
9541
- throw new MuxAiError("Audio translation timed out or failed. Please try again.", { type: "timeout_error", retryable: true });
9982
+ throw new LegacyMuxAiError("Audio translation timed out or failed. Please try again.", { type: "timeout_error", retryable: true });
9542
9983
  }
9543
9984
  console.warn("\u2705 Dubbing completed successfully!");
9544
9985
  if (uploadToS3) {
@@ -9559,7 +10000,7 @@ async function translateAudio(assetId, toLanguageCode, options = {}) {
9559
10000
  credentials
9560
10001
  });
9561
10002
  } catch (error) {
9562
- wrapError(error, "Failed to download and upload dubbed audio");
10003
+ legacyWrapError(error, "Failed to download and upload dubbed audio");
9563
10004
  }
9564
10005
  if (staged.kind === "staged") {
9565
10006
  presignedUrl = staged.presignedUrl;
@@ -9586,10 +10027,10 @@ async function translateAudio(assetId, toLanguageCode, options = {}) {
9586
10027
  credentials
9587
10028
  });
9588
10029
  } catch (error) {
9589
- wrapError(error, `Failed to add dubbed audio track to Mux asset (dubbed audio is staged at: ${presignedUrl})`);
10030
+ legacyWrapError(error, `Failed to add dubbed audio track to Mux asset (dubbed audio is staged at: ${presignedUrl})`);
9590
10031
  }
9591
10032
  if (outcome.kind === "blocked") {
9592
- throw new MuxAiError(`${outcome.reason} Dubbed audio is staged at: ${presignedUrl}`, { type: "validation_error" });
10033
+ throw new LegacyMuxAiError(`${outcome.reason} Dubbed audio is staged at: ${presignedUrl}`, { type: "validation_error" });
9593
10034
  }
9594
10035
  if (outcome.kind === "create_failed") {
9595
10036
  throw new Error(`Failed to add dubbed audio track to Mux asset: ${outcome.reason}. Dubbed audio is staged at: ${presignedUrl}`);
@@ -9751,7 +10192,7 @@ var MAX_NEVER_TRANSLATE_TERMS = 100;
9751
10192
  var MAX_NEVER_TRANSLATE_TERM_CHARS = 100;
9752
10193
  function validateNeverTranslateTerms(terms) {
9753
10194
  if (terms.length > MAX_NEVER_TRANSLATE_TERMS) {
9754
- throw new MuxAiError(
10195
+ throw new LegacyMuxAiError(
9755
10196
  `neverTranslate accepts at most ${MAX_NEVER_TRANSLATE_TERMS} terms (received ${terms.length}).`,
9756
10197
  { type: "validation_error" }
9757
10198
  );
@@ -9761,25 +10202,25 @@ function validateNeverTranslateTerms(terms) {
9761
10202
  for (const term of terms) {
9762
10203
  const trimmed = term.trim();
9763
10204
  if (trimmed.length === 0) {
9764
- throw new MuxAiError(
10205
+ throw new LegacyMuxAiError(
9765
10206
  "neverTranslate terms must be non-empty.",
9766
10207
  { type: "validation_error" }
9767
10208
  );
9768
10209
  }
9769
10210
  if (trimmed.length > MAX_NEVER_TRANSLATE_TERM_CHARS) {
9770
- throw new MuxAiError(
10211
+ throw new LegacyMuxAiError(
9771
10212
  `neverTranslate terms must be at most ${MAX_NEVER_TRANSLATE_TERM_CHARS} characters (received ${trimmed.length}).`,
9772
10213
  { type: "validation_error" }
9773
10214
  );
9774
10215
  }
9775
10216
  if (trimmed.includes("<") || trimmed.includes(">")) {
9776
- throw new MuxAiError(
10217
+ throw new LegacyMuxAiError(
9777
10218
  "neverTranslate terms must not contain '<' or '>'.",
9778
10219
  { type: "validation_error" }
9779
10220
  );
9780
10221
  }
9781
10222
  if (sanitizeUntrustedText(trimmed) !== trimmed) {
9782
- throw new MuxAiError(
10223
+ throw new LegacyMuxAiError(
9783
10224
  "neverTranslate terms must not contain invisible characters or characters altered by Unicode NFKC normalization.",
9784
10225
  { type: "validation_error" }
9785
10226
  );
@@ -10181,7 +10622,7 @@ async function translateChunkWithFallback({
10181
10622
  };
10182
10623
  } catch (error) {
10183
10624
  if (!shouldSplitChunkTranslationError(error) || chunk.cueCount <= 1) {
10184
- wrapError(error, `Chunk ${chunk.id} failed for ${Math.round(chunk.startTime)}s-${Math.round(chunk.endTime)}s`);
10625
+ legacyWrapError(error, `Chunk ${chunk.id} failed for ${Math.round(chunk.startTime)}s-${Math.round(chunk.endTime)}s`);
10185
10626
  }
10186
10627
  const [leftChunk, rightChunk] = splitTranslationChunkAtMidpoint(chunk);
10187
10628
  const failedAttemptUsage = getErrorTokenUsage(error);
@@ -10362,13 +10803,13 @@ async function translateCaptionsInternal(assetId, trackId, toLanguageCode, optio
10362
10803
  provider
10363
10804
  });
10364
10805
  if (uploadToS3 && (!s3Endpoint || !s3Bucket || !effectiveStorageAdapter && (!s3AccessKeyId || !s3SecretAccessKey))) {
10365
- throw new MuxAiError("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" });
10806
+ 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" });
10366
10807
  }
10367
10808
  const { asset: assetData, playbackId, policy } = await getPlaybackIdForAsset(assetId, credentials, options.assetSnapshot);
10368
10809
  const assetDurationSeconds = getAssetDurationSecondsFromAsset(assetData);
10369
10810
  const signingContext = await resolveMuxSigningContext(credentials);
10370
10811
  if (policy === "signed" && !signingContext) {
10371
- throw new MuxAiError(
10812
+ throw new LegacyMuxAiError(
10372
10813
  "Signed playback ID requires signing credentials. Set MUX_SIGNING_KEY and MUX_PRIVATE_KEY environment variables.",
10373
10814
  { type: "validation_error" }
10374
10815
  );
@@ -10377,14 +10818,14 @@ async function translateCaptionsInternal(assetId, trackId, toLanguageCode, optio
10377
10818
  const sourceTextTrack = readyTextTracks.find((t) => t.id === trackId);
10378
10819
  if (!sourceTextTrack) {
10379
10820
  const availableTrackIds = readyTextTracks.map((t) => t.id).filter(Boolean).join(", ");
10380
- throw new MuxAiError(
10821
+ throw new LegacyMuxAiError(
10381
10822
  `Track ${trackId} not found or not ready on asset ${assetId}. Available track IDs: ${availableTrackIds || "none"}.`,
10382
10823
  { type: "validation_error" }
10383
10824
  );
10384
10825
  }
10385
10826
  const fromLanguageCode = sourceTextTrack.language_code;
10386
10827
  if (!fromLanguageCode) {
10387
- throw new MuxAiError(
10828
+ throw new LegacyMuxAiError(
10388
10829
  `Track ${trackId} is missing language metadata. Cannot determine source language for translation.`,
10389
10830
  { type: "validation_error" }
10390
10831
  );
@@ -10396,7 +10837,7 @@ async function translateCaptionsInternal(assetId, trackId, toLanguageCode, optio
10396
10837
  if (uploadToMux) {
10397
10838
  const plan = planTextTrackReplacement(assetData, outputTrack, replaceExistingTracks);
10398
10839
  if (plan.kind === "blocked") {
10399
- throw new MuxAiError(plan.reason, { type: "validation_error" });
10840
+ throw new LegacyMuxAiError(plan.reason, { type: "validation_error" });
10400
10841
  }
10401
10842
  }
10402
10843
  const vttUrl = await buildTranscriptUrl(playbackId, trackId, policy === "signed", credentials);
@@ -10404,7 +10845,7 @@ async function translateCaptionsInternal(assetId, trackId, toLanguageCode, optio
10404
10845
  try {
10405
10846
  vttContent = await fetchVttFromMux(vttUrl);
10406
10847
  } catch (error) {
10407
- wrapError(error, "Failed to fetch VTT content");
10848
+ legacyWrapError(error, "Failed to fetch VTT content");
10408
10849
  }
10409
10850
  let translatedVtt;
10410
10851
  let usage;
@@ -10428,7 +10869,7 @@ async function translateCaptionsInternal(assetId, trackId, toLanguageCode, optio
10428
10869
  scrubbedCueCounts = result.scrubbedCueCounts;
10429
10870
  unexpectedKeyCount = result.unexpectedKeyCount;
10430
10871
  } catch (error) {
10431
- wrapError(error, `Failed to translate VTT with ${modelConfig.provider}`);
10872
+ legacyWrapError(error, `Failed to translate VTT with ${modelConfig.provider}`);
10432
10873
  }
10433
10874
  const scrubbedFields = [];
10434
10875
  for (const [reason, count] of Object.entries(scrubbedCueCounts)) {
@@ -10481,7 +10922,7 @@ async function translateCaptionsInternal(assetId, trackId, toLanguageCode, optio
10481
10922
  s3SignedUrlExpirySeconds: options.s3SignedUrlExpirySeconds
10482
10923
  });
10483
10924
  } catch (error) {
10484
- wrapError(error, "Failed to upload VTT to S3");
10925
+ legacyWrapError(error, "Failed to upload VTT to S3");
10485
10926
  }
10486
10927
  if (uploadToMux) {
10487
10928
  let outcome;
@@ -10495,12 +10936,12 @@ async function translateCaptionsInternal(assetId, trackId, toLanguageCode, optio
10495
10936
  credentials
10496
10937
  });
10497
10938
  } catch (error) {
10498
- wrapError(error, "Failed to add translated track to Mux asset");
10939
+ legacyWrapError(error, "Failed to add translated track to Mux asset");
10499
10940
  }
10500
10941
  if (outcome.kind !== "created") {
10501
10942
  const deletedNote = outcome.deleted.length > 0 ? ` Tracks already deleted before the failure: ${outcome.deleted.map((track) => `${track.name ?? track.id} (${track.id})`).join(", ")}.` : "";
10502
10943
  if (outcome.kind === "blocked") {
10503
- throw new MuxAiError(`${outcome.reason}${deletedNote}`, { type: "validation_error" });
10944
+ throw new LegacyMuxAiError(`${outcome.reason}${deletedNote}`, { type: "validation_error" });
10504
10945
  }
10505
10946
  throw new Error(`Failed to add translated track to Mux asset: ${outcome.reason}.${deletedNote}`);
10506
10947
  }