@mux/ai 0.60.0 → 0.61.0-canary.95

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.
@@ -2,7 +2,7 @@
2
2
  import { generateText, jsonSchema, NoObjectGeneratedError as NoObjectGeneratedError2, Output } from "ai";
3
3
 
4
4
  // src/lib/content-policy-error.ts
5
- import { APICallError as APICallError2, NoObjectGeneratedError, NoOutputGeneratedError as NoOutputGeneratedError2, RetryError } from "ai";
5
+ import { APICallError as APICallError2, NoObjectGeneratedError, NoOutputGeneratedError as NoOutputGeneratedError2, RetryError, TypeValidationError } from "ai";
6
6
  import { z as z3 } from "zod";
7
7
 
8
8
  // src/lib/google-errors.ts
@@ -575,14 +575,16 @@ var MUX_AI_ERROR_DEPENDENCY_VALUES = Object.values(MUX_AI_ERROR_DEPENDENCIES);
575
575
  var MUX_AI_ERROR_CODES = {
576
576
  /** The requested time range is invalid, or has nothing to work with. Facts: `reason` (`invalid_start_time`, `invalid_end_time`, `exceeds_duration`, `empty_range`, `no_video`, `no_transcript`) and the bounds involved. */
577
577
  INVALID_SCOPE: "invalid_scope",
578
- /** Existing tracks block writing the output track under the chosen replacement policy. Facts: `reason` (`policy_fail`, `not_generated`, `name_collision`, `primary_audio`), `conflictingTracks` and the target track. */
578
+ /** Existing tracks block writing the output track under the chosen replacement policy. Facts: `reason` (`policy_fail`, `not_generated`, `name_collision`, `primary_audio`), `conflictingTracks` and the target track, plus `sourceRestored` and `restoredTrackId` when a source track was deleted first. */
579
579
  TRACK_REPLACEMENT_BLOCKED: "track_replacement_blocked",
580
- /** An option's value can't be used. Facts: `parameter` (the caller's option name), `reason` (`too_many`, `empty`, `too_long`, `disallowed_characters`, `not_normalized`) and the values the reason names: `count` and `max`, `index` (0-based entry), `length` and `maxLength`, `characters`. */
580
+ /** An option's value can't be used. Facts: `parameter` (the caller's option name), `reason` (`too_many`, `empty`, `too_long`, `disallowed_characters`, `not_normalized`, `multiline`, `required_with`, `conflicts_with`, `not_allowed`, `one_of_required`) and the values the reason names: `count` and `max`, `index` (0-based entry), `length` and `maxLength`, `characters`, `with` and `withValue` (the other option), `allowed` and `value`, `parameters` (the options to choose from). */
581
581
  INVALID_PARAMETER: "invalid_parameter",
582
582
  /** A numeric option is outside its allowed range. Facts: `parameter` (the caller's option name), `value`, `min`, `max`, and `integer` when it must be a whole number. */
583
583
  PARAMETER_OUT_OF_RANGE: "parameter_out_of_range",
584
584
  /** No ready caption track matches the requested track or language. Facts: `trackId` or `languageCode`, and what is available. */
585
585
  CAPTION_TRACK_NOT_FOUND: "caption_track_not_found",
586
+ /** The caption track has no language, so its source language can't be determined. Facts: `trackId`. */
587
+ CAPTION_TRACK_LANGUAGE_MISSING: "caption_track_language_missing",
586
588
  /** The asset has no public or signed playback ID (DRM-only assets included). */
587
589
  PLAYBACK_ID_NOT_FOUND: "playback_id_not_found",
588
590
  /** Mux has no asset with the requested ID in this environment. Facts: `assetId`. */
@@ -599,6 +601,16 @@ var MUX_AI_ERROR_CODES = {
599
601
  SIGNING_CREDENTIALS_MISSING: "signing_credentials_missing",
600
602
  /** Storage is needed but the service running the SDK didn't configure it. */
601
603
  STORAGE_NOT_CONFIGURED: "storage_not_configured",
604
+ /** A track write failed, but the opted-in result carried no classified error: a bug in the SDK's track-write path. Facts: `reason`, the raw failure's message. */
605
+ TRACK_WRITE_UNCLASSIFIED: "track_write_unclassified",
606
+ /** Mux answered a track create without a track id. The track may exist, so it isn't step-retried. Facts: `call`, `assetId`. */
607
+ TRACK_ID_MISSING: "track_id_missing",
608
+ /** The asset snapshot the service running the SDK passed in is for a different asset than the one requested. Facts: `assetId`, `snapshotAssetId`. */
609
+ ASSET_SNAPSHOT_MISMATCH: "asset_snapshot_mismatch",
610
+ /** Mux answered an asset fetch with a different asset than the one requested. Facts: `assetId`, `returnedAssetId`. */
611
+ ASSET_ID_MISMATCH: "asset_id_mismatch",
612
+ /** Translation needed to split a chunk of fewer than two cues: a bug in the SDK's chunking. Facts: `chunkId`, `cueCount`. */
613
+ TRANSLATION_CHUNK_UNSPLITTABLE: "translation_chunk_unsplittable",
602
614
  /** The model provider refused the content. Facts: `reason` and `category`. */
603
615
  CONTENT_POLICY_BLOCKED: "content_policy_blocked",
604
616
  /** The model returned no output, or a required field was empty. Facts: `call`, `provider`, `model`, and `assetId` when there is one. */
@@ -636,6 +648,14 @@ var MUX_AI_ERROR_CATALOG = {
636
648
  // The configuration of the service running the SDK.
637
649
  [MUX_AI_ERROR_CODES.SIGNING_CREDENTIALS_MISSING]: { type: MUX_AI_ERROR_TYPES.SERVER_ERROR, source: MUX_AI_ERROR_SOURCES.INTERNAL },
638
650
  [MUX_AI_ERROR_CODES.STORAGE_NOT_CONFIGURED]: { type: MUX_AI_ERROR_TYPES.SERVER_ERROR, source: MUX_AI_ERROR_SOURCES.INTERNAL },
651
+ [MUX_AI_ERROR_CODES.ASSET_SNAPSHOT_MISMATCH]: { type: MUX_AI_ERROR_TYPES.SERVER_ERROR, source: MUX_AI_ERROR_SOURCES.INTERNAL },
652
+ // The SDK's own bug: never expected.
653
+ [MUX_AI_ERROR_CODES.TRACK_WRITE_UNCLASSIFIED]: { type: MUX_AI_ERROR_TYPES.SERVER_ERROR, source: MUX_AI_ERROR_SOURCES.INTERNAL },
654
+ [MUX_AI_ERROR_CODES.TRANSLATION_CHUNK_UNSPLITTABLE]: { type: MUX_AI_ERROR_TYPES.SERVER_ERROR, source: MUX_AI_ERROR_SOURCES.INTERNAL },
655
+ [MUX_AI_ERROR_CODES.CAPTION_TRACK_LANGUAGE_MISSING]: { type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR, source: MUX_AI_ERROR_SOURCES.ASSET },
656
+ // The track may exist, so a step retry could duplicate it; the job stays retryable.
657
+ [MUX_AI_ERROR_CODES.TRACK_ID_MISSING]: { type: MUX_AI_ERROR_TYPES.PROCESSING_ERROR, source: MUX_AI_ERROR_SOURCES.UPSTREAM, dependency: MUX_AI_ERROR_DEPENDENCIES.MUX_VIDEO },
658
+ [MUX_AI_ERROR_CODES.ASSET_ID_MISMATCH]: { type: MUX_AI_ERROR_TYPES.PROCESSING_ERROR, source: MUX_AI_ERROR_SOURCES.UPSTREAM, dependency: MUX_AI_ERROR_DEPENDENCIES.MUX_VIDEO },
639
659
  // Model calls.
640
660
  [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 },
641
661
  // The model-output policies below keep what these failures did before classification
@@ -825,6 +845,9 @@ function stripUrlQueries(text) {
825
845
  return `${url.origin}${url.pathname}${url.search || url.hash ? "?\u2026" : ""}`;
826
846
  });
827
847
  }
848
+ function errorDetailFact(text, maxLength = 500) {
849
+ return scrubDetail(text).slice(0, maxLength);
850
+ }
828
851
  function scrubDetail(detail, context) {
829
852
  const leakReason = detectLeakReason(detail);
830
853
  if (leakReason !== "canary" && leakReason !== "prompt_tag") {
@@ -1491,6 +1514,67 @@ function getContentPolicyTokenUsage(error) {
1491
1514
  function findBlockedCategory(ratings) {
1492
1515
  return ratings?.find((rating) => rating.blocked === true)?.category ?? void 0;
1493
1516
  }
1517
+ function findProviderServiceError(error) {
1518
+ if (!error) {
1519
+ return void 0;
1520
+ }
1521
+ if (RetryError.isInstance(error)) {
1522
+ return findProviderServiceError(error.lastError);
1523
+ }
1524
+ if (APICallError2.isInstance(error)) {
1525
+ return error;
1526
+ }
1527
+ if (error instanceof Error && "cause" in error) {
1528
+ return findProviderServiceError(error.cause);
1529
+ }
1530
+ return void 0;
1531
+ }
1532
+ function isUnusableOutputError(error) {
1533
+ return NoObjectGeneratedError.isInstance(error) || NoOutputGeneratedError2.isInstance(error) || TypeValidationError.isInstance(error);
1534
+ }
1535
+ function modelStepError(error, message, facts) {
1536
+ if (MuxAiError.is(error)) {
1537
+ Object.assign(error, { facts: { ...facts, ...error.facts } });
1538
+ return error;
1539
+ }
1540
+ const context = { call: String(facts.call), provider: String(facts.provider), ...facts.model !== void 0 && { model: String(facts.model) } };
1541
+ let classified = classifyModelCallError(error, context);
1542
+ if (classified) {
1543
+ Object.assign(classified, { facts: { ...facts, ...classified.facts } });
1544
+ return classified;
1545
+ }
1546
+ if (isUnusableOutputError(error)) {
1547
+ classified = new MuxAiError(message, {
1548
+ code: MUX_AI_ERROR_CODES.MODEL_OUTPUT_INVALID,
1549
+ type: MUX_AI_ERROR_TYPES.PROCESSING_ERROR,
1550
+ source: MUX_AI_ERROR_SOURCES.UPSTREAM,
1551
+ dependency: MUX_AI_ERROR_DEPENDENCIES.AI_PROVIDER,
1552
+ facts,
1553
+ // As before: the raw error was retried by the step runner. See the model-output follow-up.
1554
+ transient: true,
1555
+ cause: error
1556
+ });
1557
+ } else {
1558
+ const providerError = findProviderServiceError(error);
1559
+ classified = providerError ? (
1560
+ // A provider without its own classifier: not classified, but kept retryable by the
1561
+ // step runner when the AI SDK judges it retryable (no response, 408, 409, 429, 5xx),
1562
+ // as the raw error was before.
1563
+ new MuxAiError(message, {
1564
+ type: MUX_AI_ERROR_TYPES.SERVER_ERROR,
1565
+ source: MUX_AI_ERROR_SOURCES.INTERNAL,
1566
+ facts,
1567
+ transient: providerError.isRetryable,
1568
+ cause: error
1569
+ })
1570
+ ) : internalError(message, facts, error);
1571
+ }
1572
+ const usage = getErrorTokenUsage(error);
1573
+ if (usage) {
1574
+ classified.usage = usage;
1575
+ }
1576
+ return classified;
1577
+ }
1494
1578
 
1495
1579
  // src/lib/model-call-diagnostics.ts
1496
1580
  import { APICallError as APICallError3 } from "ai";
@@ -2617,6 +2701,7 @@ function muxAssetFetchError(assetId, error) {
2617
2701
  }
2618
2702
  function missingTrackIdError(message, facts) {
2619
2703
  return new MuxAiError(message, {
2704
+ code: MUX_AI_ERROR_CODES.TRACK_ID_MISSING,
2620
2705
  type: MUX_AI_ERROR_TYPES.PROCESSING_ERROR,
2621
2706
  source: MUX_AI_ERROR_SOURCES.UPSTREAM,
2622
2707
  dependency: MUX_AI_ERROR_DEPENDENCIES.MUX_VIDEO,
@@ -2684,10 +2769,20 @@ async function getPlaybackIdForAsset(assetId, credentials, assetSnapshot, option
2684
2769
  }
2685
2770
  }
2686
2771
  if (asset.id !== assetId) {
2687
- throw new MuxAiError("Asset snapshot does not match the requested asset ID.", {
2688
- type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR,
2689
- source: MUX_AI_ERROR_SOURCES.REQUEST,
2690
- facts: { assetId, snapshotAssetId: asset.id, inputs: ["assetId", "assetSnapshot"] }
2772
+ if (assetSnapshot) {
2773
+ throw new MuxAiError("Asset snapshot does not match the requested asset ID.", {
2774
+ code: MUX_AI_ERROR_CODES.ASSET_SNAPSHOT_MISMATCH,
2775
+ type: MUX_AI_ERROR_TYPES.SERVER_ERROR,
2776
+ source: MUX_AI_ERROR_SOURCES.INTERNAL,
2777
+ facts: { assetId, snapshotAssetId: asset.id }
2778
+ });
2779
+ }
2780
+ throw new MuxAiError("Mux returned a different asset than the one requested.", {
2781
+ code: MUX_AI_ERROR_CODES.ASSET_ID_MISMATCH,
2782
+ type: MUX_AI_ERROR_TYPES.PROCESSING_ERROR,
2783
+ source: MUX_AI_ERROR_SOURCES.UPSTREAM,
2784
+ dependency: MUX_AI_ERROR_DEPENDENCIES.MUX_VIDEO,
2785
+ facts: { assetId, returnedAssetId: asset.id }
2691
2786
  });
2692
2787
  }
2693
2788
  return toPlaybackAsset(asset, options);
@@ -4988,6 +5083,14 @@ import { generateText as generateText5, Output as Output5 } from "ai";
4988
5083
  import { z as z8 } from "zod";
4989
5084
 
4990
5085
  // src/lib/mux-tracks.ts
5086
+ function trackWriteFailure(outcome) {
5087
+ return outcome.error ?? new MuxAiError(`Track write failed without a classified error: ${outcome.reason}`, {
5088
+ code: MUX_AI_ERROR_CODES.TRACK_WRITE_UNCLASSIFIED,
5089
+ type: MUX_AI_ERROR_TYPES.SERVER_ERROR,
5090
+ source: MUX_AI_ERROR_SOURCES.INTERNAL,
5091
+ facts: { reason: errorDetailFact(outcome.reason) }
5092
+ });
5093
+ }
4991
5094
  var MUX_TRACK_PASSTHROUGH_MAX_CHARS = 255;
4992
5095
  function normalizeTrackLanguageCode(code) {
4993
5096
  if (!code) {
@@ -5227,17 +5330,22 @@ async function createTextTrackOnMux(assetId, languageCode, trackName, presignedU
5227
5330
  "use step";
5228
5331
  const muxClient = await resolveMuxClient(credentials);
5229
5332
  const mux = await muxClient.createClient();
5230
- const trackResponse = await mux.video.assets.createTrack(assetId, {
5231
- type: "text",
5232
- text_type: "subtitles",
5233
- language_code: languageCode,
5234
- name: trackName,
5235
- url: presignedUrl,
5236
- closed_captions: options.closedCaptions,
5237
- passthrough: options.passthrough
5238
- });
5333
+ let trackResponse;
5334
+ try {
5335
+ trackResponse = await mux.video.assets.createTrack(assetId, {
5336
+ type: "text",
5337
+ text_type: "subtitles",
5338
+ language_code: languageCode,
5339
+ name: trackName,
5340
+ url: presignedUrl,
5341
+ closed_captions: options.closedCaptions,
5342
+ passthrough: options.passthrough
5343
+ });
5344
+ } catch (error) {
5345
+ throw muxVideoCallError("Failed to create the text track on Mux", "create_track", error, { assetId });
5346
+ }
5239
5347
  if (!trackResponse.id) {
5240
- throw new Error("Failed to create text track: no track ID returned from Mux");
5348
+ throw missingTrackIdError("Failed to create text track: no track ID returned from Mux", { assetId });
5241
5349
  }
5242
5350
  return trackResponse.id;
5243
5351
  }
@@ -5809,6 +5917,7 @@ async function identifyProfanityWithAI({
5809
5917
  tag: "transcript",
5810
5918
  content: plainText
5811
5919
  });
5920
+ const context = { call: "detect_profanity", provider, model: modelId };
5812
5921
  const response = await withContentPolicyAwareRetry(() => generateText5({
5813
5922
  model,
5814
5923
  maxRetries: 0,
@@ -5822,8 +5931,10 @@ async function identifyProfanityWithAI({
5822
5931
  ${transcriptSection}`
5823
5932
  }
5824
5933
  ]
5825
- }));
5826
- const output = getGeneratedOutputWithContentPolicyHandling(response);
5934
+ }), void 0, context).catch((error) => {
5935
+ throw modelStepError(error, "Profanity detection model call failed", { ...context });
5936
+ });
5937
+ const output = getGeneratedOutputWithContentPolicyHandling(response, context);
5827
5938
  const unexpectedKeys = detectUnexpectedKeysFromRawText(
5828
5939
  response.text,
5829
5940
  profanityDetectionSchema.keyof().options
@@ -5880,7 +5991,49 @@ async function deleteTrackOnMux(assetId, trackId, credentials) {
5880
5991
  "use step";
5881
5992
  const muxClient = await resolveMuxClient(credentials);
5882
5993
  const mux = await muxClient.createClient();
5883
- await mux.video.assets.deleteTrack(assetId, trackId);
5994
+ try {
5995
+ await mux.video.assets.deleteTrack(assetId, trackId);
5996
+ } catch (error) {
5997
+ if (httpStatusOf(error) === 404) {
5998
+ return;
5999
+ }
6000
+ throw muxVideoCallError("Failed to delete the original track on Mux", "delete_track", error, { assetId, trackId });
6001
+ }
6002
+ }
6003
+ function restoreFailureFacts(error) {
6004
+ if (!MuxAiError.is(error)) {
6005
+ return { restoreError: errorDetailFact(extractErrorDetail(error)) };
6006
+ }
6007
+ const cause = error.causes?.[0]?.message;
6008
+ return {
6009
+ restoreError: errorDetailFact(cause ? `${error.message}: ${cause}` : error.message),
6010
+ restoreFailure: error.facts
6011
+ };
6012
+ }
6013
+ function invalidOptionError(message, facts, inputs) {
6014
+ return new MuxAiError(message, {
6015
+ code: MUX_AI_ERROR_CODES.INVALID_PARAMETER,
6016
+ type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR,
6017
+ source: MUX_AI_ERROR_SOURCES.REQUEST,
6018
+ facts: { ...facts, inputs }
6019
+ });
6020
+ }
6021
+ function speakerLabelProblem(label) {
6022
+ if (!label) {
6023
+ return "empty";
6024
+ }
6025
+ if (label.includes("[") || label.includes("]")) {
6026
+ return "disallowed_characters";
6027
+ }
6028
+ return /[\r\n]/.test(label) ? "multiline" : void 0;
6029
+ }
6030
+ function missingStorageSettings(config) {
6031
+ return [
6032
+ ...config.s3Endpoint ? [] : ["s3Endpoint"],
6033
+ ...config.s3Bucket ? [] : ["s3Bucket"],
6034
+ ...config.storageAdapter || config.s3AccessKeyId ? [] : ["S3_ACCESS_KEY_ID"],
6035
+ ...config.storageAdapter || config.s3SecretAccessKey ? [] : ["S3_SECRET_ACCESS_KEY"]
6036
+ ];
5884
6037
  }
5885
6038
  async function editCaptions(assetId, trackId, options) {
5886
6039
  "use workflow";
@@ -5915,42 +6068,64 @@ async function editCaptionsInternal(assetId, trackId, options, collectedUsage) {
5915
6068
  const hasReplacements = !!replacementsOption && replacementsOption.length > 0;
5916
6069
  const hasSpeakerReplacements = !!speakerReplacementsOption && speakerReplacementsOption.length > 0;
5917
6070
  if (!hasAutoCensor && !hasReplacements && !hasSpeakerReplacements) {
5918
- throw new LegacyMuxAiError("At least one of autoCensorProfanity, replacements, or speakerReplacements must be provided.", { type: "validation_error" });
6071
+ const parameters = ["autoCensorProfanity", "replacements", "speakerReplacements"];
6072
+ throw invalidOptionError(
6073
+ "At least one of autoCensorProfanity, replacements, or speakerReplacements must be provided.",
6074
+ { reason: "one_of_required", parameters },
6075
+ parameters
6076
+ );
5919
6077
  }
5920
6078
  if (autoCensorOption && !provider) {
5921
- throw new LegacyMuxAiError("provider is required when using autoCensorProfanity.", { type: "validation_error" });
6079
+ throw invalidOptionError(
6080
+ "provider is required when using autoCensorProfanity.",
6081
+ { parameter: "provider", reason: "required_with", with: "autoCensorProfanity" },
6082
+ ["provider", "autoCensorProfanity"]
6083
+ );
5922
6084
  }
5923
6085
  const legacyTrackNaming = deleteOriginalTrack !== void 0 || trackNameSuffix !== void 0;
5924
6086
  if (legacyTrackNaming && (replaceExistingTracksOption !== void 0 || providedTrackName !== void 0)) {
5925
- throw new LegacyMuxAiError(
6087
+ const legacy = deleteOriginalTrack !== void 0 ? "deleteOriginalTrack" : "trackNameSuffix";
6088
+ const conflicting = [
6089
+ ...replaceExistingTracksOption !== void 0 ? ["replaceExistingTracks"] : [],
6090
+ ...providedTrackName !== void 0 ? ["trackName"] : []
6091
+ ];
6092
+ throw invalidOptionError(
5926
6093
  "deleteOriginalTrack and trackNameSuffix are deprecated and cannot be combined with replaceExistingTracks or trackName.",
5927
- { type: "validation_error" }
6094
+ { parameter: legacy, reason: "conflicts_with", with: conflicting },
6095
+ [legacy, ...conflicting]
5928
6096
  );
5929
6097
  }
5930
6098
  if (replaceExistingTracksOption !== void 0 && replaceExistingTracksOption !== "replace" && replaceExistingTracksOption !== "fail") {
5931
- throw new LegacyMuxAiError(
6099
+ throw invalidOptionError(
5932
6100
  `replaceExistingTracks must be "replace" or "fail" for editCaptions (received "${String(replaceExistingTracksOption)}").`,
5933
- { type: "validation_error" }
6101
+ {
6102
+ parameter: "replaceExistingTracks",
6103
+ reason: "not_allowed",
6104
+ allowed: ["replace", "fail"],
6105
+ value: String(replaceExistingTracksOption).slice(0, 100)
6106
+ },
6107
+ ["replaceExistingTracks"]
5934
6108
  );
5935
6109
  }
5936
6110
  const replaceExistingTracks = replaceExistingTracksOption ?? "replace";
5937
6111
  if (!legacyTrackNaming && replaceExistingTracks === "fail" && !providedTrackName) {
5938
- throw new LegacyMuxAiError(
6112
+ throw invalidOptionError(
5939
6113
  `trackName is required when replaceExistingTracks is "fail": the edited track cannot reuse the source track's name while the source is kept.`,
5940
- { type: "validation_error" }
6114
+ { parameter: "trackName", reason: "required_with", with: "replaceExistingTracks", withValue: "fail" },
6115
+ ["trackName", "replaceExistingTracks"]
5941
6116
  );
5942
6117
  }
5943
- const trackPassthrough = validateTrackPassthrough(providedTrackPassthrough) ?? buildMuxAiTrackPassthrough("edit-captions");
6118
+ const trackPassthrough = validateTrackPassthrough(providedTrackPassthrough, { classifiedErrors: true }) ?? buildMuxAiTrackPassthrough("edit-captions");
5944
6119
  const deleteOriginal = deleteOriginalTrack !== false;
5945
6120
  const uploadToMux = uploadToMuxOption !== false;
5946
6121
  const uploadToS3 = uploadToS3Option || uploadToMux;
5947
- for (const replacement of speakerReplacementsOption ?? []) {
5948
- const hasInvalidFindCharacter = replacement.find.includes("[") || replacement.find.includes("]") || /[\r\n]/.test(replacement.find);
5949
- const hasInvalidReplaceCharacter = replacement.replace.includes("[") || replacement.replace.includes("]") || /[\r\n]/.test(replacement.replace);
5950
- if (!replacement.find || !replacement.replace || hasInvalidFindCharacter || hasInvalidReplaceCharacter) {
5951
- throw new LegacyMuxAiError(
6122
+ for (const [index, replacement] of (speakerReplacementsOption ?? []).entries()) {
6123
+ const reason = speakerLabelProblem(replacement.find) ?? speakerLabelProblem(replacement.replace);
6124
+ if (reason) {
6125
+ throw invalidOptionError(
5952
6126
  "Speaker replacement labels must be non-empty and must not contain square brackets or newlines.",
5953
- { type: "validation_error" }
6127
+ { parameter: "speakerReplacements", reason, index, ...reason === "disallowed_characters" && { characters: ["[", "]"] } },
6128
+ ["speakerReplacements"]
5954
6129
  );
5955
6130
  }
5956
6131
  }
@@ -5959,28 +6134,30 @@ async function editCaptionsInternal(assetId, trackId, options, collectedUsage) {
5959
6134
  const s3Bucket = providedS3Bucket ?? env_default.S3_BUCKET;
5960
6135
  const s3AccessKeyId = env_default.S3_ACCESS_KEY_ID;
5961
6136
  const s3SecretAccessKey = env_default.S3_SECRET_ACCESS_KEY;
5962
- if (uploadToS3 && (!s3Endpoint || !s3Bucket || !storageAdapter && (!s3AccessKeyId || !s3SecretAccessKey))) {
5963
- throw new LegacyMuxAiError(
5964
- "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.",
5965
- { type: "validation_error" }
5966
- );
6137
+ if (uploadToS3) {
6138
+ const missing = missingStorageSettings({ s3Endpoint, s3Bucket, storageAdapter, s3AccessKeyId, s3SecretAccessKey });
6139
+ if (missing.length > 0) {
6140
+ throw storageNotConfiguredError(missing);
6141
+ }
5967
6142
  }
5968
- const { asset: assetData, playbackId, policy } = await getPlaybackIdForAsset(assetId, credentials, options.assetSnapshot);
6143
+ const { asset: assetData, playbackId, policy } = await getPlaybackIdForAsset(assetId, credentials, options.assetSnapshot, { classifiedErrors: true });
5969
6144
  const assetDurationSeconds = getAssetDurationSecondsFromAsset(assetData);
5970
6145
  const signingContext = await resolveMuxSigningContext(credentials);
5971
6146
  if (policy === "signed" && !signingContext) {
5972
- throw new LegacyMuxAiError(
5973
- "Signed playback ID requires signing credentials. Set MUX_SIGNING_KEY and MUX_PRIVATE_KEY environment variables.",
5974
- { type: "validation_error" }
5975
- );
6147
+ throw signingCredentialsMissingError();
5976
6148
  }
5977
6149
  const readyTextTracks = getReadyTextTracks(assetData);
5978
6150
  const sourceTrack = readyTextTracks.find((t) => t.id === trackId);
5979
6151
  if (!sourceTrack) {
5980
- const availableTrackIds = readyTextTracks.map((t) => t.id).filter(Boolean).join(", ");
5981
- throw new LegacyMuxAiError(
5982
- `Track ${trackId} not found or not ready on asset ${assetId}. Available track IDs: ${availableTrackIds || "none"}.`,
5983
- { type: "validation_error" }
6152
+ const availableTrackIds = readyTextTracks.map((t) => t.id).filter((id) => !!id);
6153
+ throw new MuxAiError(
6154
+ `Track ${trackId} not found or not ready on asset ${assetId}. Available track IDs: ${availableTrackIds.join(", ") || "none"}.`,
6155
+ {
6156
+ code: MUX_AI_ERROR_CODES.CAPTION_TRACK_NOT_FOUND,
6157
+ type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR,
6158
+ source: MUX_AI_ERROR_SOURCES.ASSET,
6159
+ facts: { assetId, trackId, availableTrackIds }
6160
+ }
5984
6161
  );
5985
6162
  }
5986
6163
  const sourceLanguageCode = sourceTrack.language_code || "en";
@@ -5990,23 +6167,25 @@ async function editCaptionsInternal(assetId, trackId, options, collectedUsage) {
5990
6167
  name: providedTrackName ?? sourceName
5991
6168
  };
5992
6169
  if (replaceExistingTracks === "fail" && normalizeTrackName(outputTrack.name) === normalizeTrackName(sourceName)) {
5993
- throw new LegacyMuxAiError(
5994
- `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.`,
5995
- { type: "validation_error" }
5996
- );
6170
+ throw trackReplacementBlockedError({
6171
+ reason: `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.`,
6172
+ code: "name_collision",
6173
+ tracks: [summarizeTextTrack(sourceTrack)],
6174
+ conflictsOnLanguage: false
6175
+ }, { facts: { ...trackTargetFacts(outputTrack), assetId, policy: replaceExistingTracks } });
5997
6176
  }
5998
6177
  if (uploadToMux && !legacyTrackNaming) {
5999
6178
  const plan = planSourceTrackReplacement(assetData, trackId, outputTrack, replaceExistingTracks);
6000
6179
  if (plan.kind === "blocked") {
6001
- throw new LegacyMuxAiError(plan.reason, { type: "validation_error" });
6180
+ throw trackReplacementBlockedError(plan, { facts: { ...trackTargetFacts(outputTrack), assetId, policy: replaceExistingTracks } });
6002
6181
  }
6003
6182
  }
6004
6183
  const vttUrl = await buildTranscriptUrl(playbackId, trackId, policy === "signed", credentials);
6005
6184
  let vttContent;
6006
6185
  try {
6007
- vttContent = await fetchVttFromMux(vttUrl);
6186
+ vttContent = await fetchVttFromMux(vttUrl, { classifiedErrors: true });
6008
6187
  } catch (error) {
6009
- legacyWrapError(error, "Failed to fetch VTT content");
6188
+ wrapError(error, "Failed to fetch VTT content", { assetId, trackId });
6010
6189
  }
6011
6190
  let editedVtt = vttContent;
6012
6191
  let totalReplacementCount = 0;
@@ -6017,36 +6196,45 @@ async function editCaptionsInternal(assetId, trackId, options, collectedUsage) {
6017
6196
  const { mode = "blank", alwaysCensor = [], neverCensor = [] } = autoCensorOption;
6018
6197
  const plainText = extractTextFromVTT(vttContent);
6019
6198
  if (!plainText.trim()) {
6020
- throw new LegacyMuxAiError("Track transcript is empty; nothing to censor.", { type: "validation_error" });
6199
+ throw new MuxAiError("Track transcript is empty; nothing to censor.", {
6200
+ code: MUX_AI_ERROR_CODES.TRANSCRIPT_EMPTY,
6201
+ type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR,
6202
+ source: MUX_AI_ERROR_SOURCES.ASSET,
6203
+ facts: { assetId, trackId }
6204
+ });
6021
6205
  }
6022
6206
  const modelConfig = resolveLanguageModelConfig({
6023
6207
  ...options,
6024
6208
  provider,
6025
6209
  model
6026
6210
  });
6027
- let detectedProfanity;
6211
+ let result;
6028
6212
  try {
6029
- const result = await identifyProfanityWithAI({
6213
+ result = await identifyProfanityWithAI({
6030
6214
  plainText,
6031
6215
  provider: modelConfig.provider,
6032
6216
  modelId: modelConfig.modelId,
6033
6217
  credentials
6034
6218
  });
6035
- detectedProfanity = result.profanity;
6036
- usage = result.usage;
6037
- collectedUsage.push(result.usage);
6038
- if (result.unexpectedKeys.length > 0) {
6039
- console.warn(
6040
- `[@mux/ai] Model emitted unexpected keys in profanity detection (stripped): ${result.unexpectedKeys.join(", ")}.`
6041
- );
6042
- for (const key of result.unexpectedKeys) {
6043
- safety.record(`profanity_detection.${key}`, "unexpected_key");
6044
- }
6045
- }
6046
6219
  } catch (error) {
6047
- legacyWrapError(error, `Failed to detect profanity with ${modelConfig.provider}`);
6220
+ wrapError(error, `Failed to detect profanity with ${modelConfig.provider}`, {
6221
+ call: "detect_profanity",
6222
+ provider: modelConfig.provider,
6223
+ model: modelConfig.modelId
6224
+ });
6225
+ }
6226
+ const detectedProfanity = result.profanity;
6227
+ usage = result.usage;
6228
+ collectedUsage.push(result.usage);
6229
+ if (result.unexpectedKeys.length > 0) {
6230
+ console.warn(
6231
+ `[@mux/ai] Model emitted unexpected keys in profanity detection (stripped): ${result.unexpectedKeys.join(", ")}.`
6232
+ );
6233
+ for (const key of result.unexpectedKeys) {
6234
+ safety.record(`profanity_detection.${key}`, "unexpected_key");
6235
+ }
6048
6236
  }
6049
- const scrubbedProfanity = detectedProfanity.map((word, i) => safety.scrubDetailed(word, `profanity[${i}]`)).filter((result) => !result.leaked).map((result) => result.text);
6237
+ const scrubbedProfanity = detectedProfanity.map((word, i) => safety.scrubDetailed(word, `profanity[${i}]`)).filter((result2) => !result2.leaked).map((result2) => result2.text);
6050
6238
  const finalProfanity = applyOverrideLists(scrubbedProfanity, alwaysCensor, neverCensor);
6051
6239
  const { censoredVtt, replacements: censorReplacements } = censorVttContent(editedVtt, finalProfanity, mode);
6052
6240
  editedVtt = censoredVtt;
@@ -6092,11 +6280,11 @@ async function editCaptionsInternal(assetId, trackId, options, collectedUsage) {
6092
6280
  try {
6093
6281
  presignedUrl = await uploadEditedVttToS3({ editedVtt, ...s3Config });
6094
6282
  } catch (error) {
6095
- legacyWrapError(error, "Failed to upload VTT to S3");
6283
+ wrapError(error, "Failed to upload VTT to S3", { call: "put_object", bucket: s3Bucket });
6096
6284
  }
6097
6285
  if (uploadToMux && legacyTrackNaming) {
6286
+ const trackName = `${sourceName} (${trackNameSuffix ?? "edited"})`;
6098
6287
  try {
6099
- const trackName = `${sourceName} (${trackNameSuffix ?? "edited"})`;
6100
6288
  uploadedTrackId = await createTextTrackOnMux(
6101
6289
  assetId,
6102
6290
  sourceLanguageCode,
@@ -6106,13 +6294,13 @@ async function editCaptionsInternal(assetId, trackId, options, collectedUsage) {
6106
6294
  { closedCaptions: sourceTrack.closed_captions, passthrough: trackPassthrough }
6107
6295
  );
6108
6296
  } catch (error) {
6109
- legacyWrapError(error, "Failed to add edited track to Mux asset");
6297
+ wrapError(error, "Failed to add edited track to Mux asset", { assetId, languageCode: sourceLanguageCode });
6110
6298
  }
6111
6299
  if (deleteOriginal && uploadedTrackId) {
6112
6300
  try {
6113
6301
  await deleteTrackOnMux(assetId, trackId, credentials);
6114
6302
  } catch (error) {
6115
- legacyWrapError(error, "Failed to delete original track");
6303
+ wrapError(error, "Failed to delete original track", { assetId, trackId });
6116
6304
  }
6117
6305
  }
6118
6306
  } else if (uploadToMux) {
@@ -6126,14 +6314,16 @@ async function editCaptionsInternal(assetId, trackId, options, collectedUsage) {
6126
6314
  presignedUrl,
6127
6315
  closedCaptions: sourceTrack.closed_captions,
6128
6316
  passthrough: trackPassthrough,
6129
- credentials
6317
+ credentials,
6318
+ classifiedErrors: true
6130
6319
  });
6131
6320
  } catch (error) {
6132
- legacyWrapError(error, "Failed to add edited track to Mux asset");
6321
+ wrapError(error, "Failed to fetch the asset before adding the edited track", { assetId });
6133
6322
  }
6134
6323
  if (outcome.kind !== "created") {
6135
6324
  const sourceWasDeleted = outcome.deleted.some((track) => track.id === trackId);
6136
6325
  let restoreNote = "";
6326
+ let restoreFacts = {};
6137
6327
  if (sourceWasDeleted) {
6138
6328
  try {
6139
6329
  const originalUrl = await uploadEditedVttToS3({ editedVtt: vttContent, variant: "original", ...s3Config });
@@ -6146,14 +6336,27 @@ async function editCaptionsInternal(assetId, trackId, options, collectedUsage) {
6146
6336
  { closedCaptions: sourceTrack.closed_captions, passthrough: sourceTrack.passthrough }
6147
6337
  );
6148
6338
  restoreNote = ` The source track was restored as ${restoredTrackId}.`;
6339
+ restoreFacts = { sourceRestored: true, restoredTrackId };
6149
6340
  } catch (restoreError) {
6150
- restoreNote = ` Restoring the source track also failed: ${restoreError instanceof Error ? restoreError.message : String(restoreError)}.`;
6341
+ restoreNote = " Restoring the source track also failed.";
6342
+ restoreFacts = { sourceRestored: false, ...restoreFailureFacts(restoreError) };
6151
6343
  }
6152
6344
  }
6345
+ const facts = {
6346
+ assetId,
6347
+ trackId,
6348
+ languageCode: sourceLanguageCode,
6349
+ trackName: outputTrack.name,
6350
+ ...outcome.deleted.length > 0 && { deletedTracks: trackSummaryFacts(outcome.deleted) },
6351
+ ...restoreFacts
6352
+ };
6153
6353
  if (outcome.kind === "blocked") {
6154
- throw new LegacyMuxAiError(`${outcome.reason}${restoreNote}`, { type: "validation_error" });
6354
+ throw trackReplacementBlockedError(outcome, { message: `${outcome.reason}${restoreNote}`, facts: { ...trackTargetFacts(outputTrack), ...facts } });
6155
6355
  }
6156
- throw new Error(`Failed to add edited track to Mux asset: ${outcome.reason}.${restoreNote}`);
6356
+ const failure = trackWriteFailure(outcome);
6357
+ Object.assign(failure, { facts: { ...facts, ...failure.facts } });
6358
+ failure.message = `Failed to add edited track to Mux asset: ${failure.message}.${restoreNote}`;
6359
+ throw failure;
6157
6360
  }
6158
6361
  uploadedTrackId = outcome.trackId;
6159
6362
  replacedTracks = outcome.deleted;
@@ -10492,15 +10695,7 @@ async function translateAudio(assetId, toLanguageCode, options = {}) {
10492
10695
  }
10493
10696
 
10494
10697
  // src/workflows/translate-captions.ts
10495
- import {
10496
- APICallError as APICallError5,
10497
- generateText as generateText9,
10498
- NoObjectGeneratedError as NoObjectGeneratedError3,
10499
- NoOutputGeneratedError as NoOutputGeneratedError3,
10500
- Output as Output9,
10501
- RetryError as RetryError2,
10502
- TypeValidationError
10503
- } from "ai";
10698
+ import { generateText as generateText9, Output as Output9 } from "ai";
10504
10699
  import { z as z13 } from "zod";
10505
10700
  var translationSchema = z13.object({
10506
10701
  translation: z13.string()
@@ -10637,24 +10832,6 @@ var DEFAULT_TRANSLATION_CHUNKING = {
10637
10832
  maxCuesPerChunk: 80,
10638
10833
  maxCueTextTokensPerChunk: 2e3
10639
10834
  };
10640
- function findProviderServiceError(error) {
10641
- if (!error) {
10642
- return void 0;
10643
- }
10644
- if (RetryError2.isInstance(error)) {
10645
- return findProviderServiceError(error.lastError);
10646
- }
10647
- if (APICallError5.isInstance(error)) {
10648
- return error;
10649
- }
10650
- if (error instanceof Error && "cause" in error) {
10651
- return findProviderServiceError(error.cause);
10652
- }
10653
- return void 0;
10654
- }
10655
- function isUnusableOutputError(error) {
10656
- return NoObjectGeneratedError3.isInstance(error) || NoOutputGeneratedError3.isInstance(error) || TypeValidationError.isInstance(error);
10657
- }
10658
10835
  function shouldSplitChunkTranslationError(error) {
10659
10836
  if (findProviderServiceError(error)) {
10660
10837
  return false;
@@ -10662,49 +10839,6 @@ function shouldSplitChunkTranslationError(error) {
10662
10839
  return isUnusableOutputError(error) || isIncompleteGenerationError(error) || // Missing or invalid output, including a wrong cue count.
10663
10840
  MuxAiError.is(error) && (error.code === MUX_AI_ERROR_CODES.MODEL_OUTPUT_MISSING || error.code === MUX_AI_ERROR_CODES.MODEL_OUTPUT_INVALID);
10664
10841
  }
10665
- function translationStepError(error, message, facts) {
10666
- if (MuxAiError.is(error)) {
10667
- Object.assign(error, { facts: { ...facts, ...error.facts } });
10668
- return error;
10669
- }
10670
- const context = { call: String(facts.call), provider: String(facts.provider), ...facts.model !== void 0 && { model: String(facts.model) } };
10671
- let classified = classifyModelCallError(error, context);
10672
- if (classified) {
10673
- Object.assign(classified, { facts: { ...facts, ...classified.facts } });
10674
- return classified;
10675
- }
10676
- if (isUnusableOutputError(error)) {
10677
- classified = new MuxAiError(message, {
10678
- code: MUX_AI_ERROR_CODES.MODEL_OUTPUT_INVALID,
10679
- type: MUX_AI_ERROR_TYPES.PROCESSING_ERROR,
10680
- source: MUX_AI_ERROR_SOURCES.UPSTREAM,
10681
- dependency: MUX_AI_ERROR_DEPENDENCIES.AI_PROVIDER,
10682
- facts,
10683
- // As before: the raw error was retried by the step runner. See the model-output follow-up.
10684
- transient: true,
10685
- cause: error
10686
- });
10687
- } else {
10688
- const providerError = findProviderServiceError(error);
10689
- classified = providerError ? (
10690
- // A provider without its own classifier: not classified, but kept retryable by the
10691
- // step runner when the AI SDK judges it retryable (no response, 408, 409, 429, 5xx),
10692
- // as the raw error was before.
10693
- new MuxAiError(message, {
10694
- type: MUX_AI_ERROR_TYPES.SERVER_ERROR,
10695
- source: MUX_AI_ERROR_SOURCES.INTERNAL,
10696
- facts,
10697
- transient: providerError.isRetryable,
10698
- cause: error
10699
- })
10700
- ) : internalError(message, facts, error);
10701
- }
10702
- const usage = getErrorTokenUsage(error);
10703
- if (usage) {
10704
- classified.usage = usage;
10705
- }
10706
- return classified;
10707
- }
10708
10842
  function resolveTranslationChunkingOptions(options) {
10709
10843
  const targetChunkDurationSeconds = Math.max(
10710
10844
  1,
@@ -10884,7 +11018,7 @@ ${sanitisedVttContent}`
10884
11018
  }
10885
11019
  ]
10886
11020
  }), void 0, context).catch((error) => {
10887
- throw translationStepError(error, "Caption translation model call failed", { ...context });
11021
+ throw modelStepError(error, "Caption translation model call failed", { ...context });
10888
11022
  });
10889
11023
  const output = getGeneratedOutputWithContentPolicyHandling(response, context);
10890
11024
  const translated = normalizeTranslatedVtt(output.translation);
@@ -10979,7 +11113,12 @@ ${JSON.stringify(cuePayload, null, 2)}`
10979
11113
  function splitTranslationChunkAtMidpoint(chunk) {
10980
11114
  const midpoint = Math.floor(chunk.cueCount / 2);
10981
11115
  if (midpoint <= 0 || midpoint >= chunk.cueCount) {
10982
- throw internalError("Cannot split a translation chunk with fewer than two cues", { chunkId: chunk.id, cueCount: chunk.cueCount });
11116
+ throw new MuxAiError("Cannot split a translation chunk with fewer than two cues", {
11117
+ code: MUX_AI_ERROR_CODES.TRANSLATION_CHUNK_UNSPLITTABLE,
11118
+ type: MUX_AI_ERROR_TYPES.SERVER_ERROR,
11119
+ source: MUX_AI_ERROR_SOURCES.INTERNAL,
11120
+ facts: { chunkId: chunk.id, cueCount: chunk.cueCount }
11121
+ });
10983
11122
  }
10984
11123
  return [
10985
11124
  createTranslationChunkRequest(
@@ -11056,7 +11195,7 @@ async function translateChunkWithFallback({
11056
11195
  };
11057
11196
  } catch (error) {
11058
11197
  if (!shouldSplitChunkTranslationError(error) || chunk.cueCount <= 1) {
11059
- throw translationStepError(error, "Failed to translate a caption chunk", chunkFacts);
11198
+ throw modelStepError(error, "Failed to translate a caption chunk", chunkFacts);
11060
11199
  }
11061
11200
  const [leftChunk, rightChunk] = splitTranslationChunkAtMidpoint(chunk);
11062
11201
  const failedAttemptUsage = getErrorTokenUsage(error);
@@ -11271,7 +11410,12 @@ async function translateCaptionsInternal(assetId, trackId, toLanguageCode, optio
11271
11410
  if (!fromLanguageCode) {
11272
11411
  throw new MuxAiError(
11273
11412
  `Track ${trackId} is missing language metadata. Cannot determine source language for translation.`,
11274
- { type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR, source: MUX_AI_ERROR_SOURCES.ASSET, facts: { assetId, trackId } }
11413
+ {
11414
+ code: MUX_AI_ERROR_CODES.CAPTION_TRACK_LANGUAGE_MISSING,
11415
+ type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR,
11416
+ source: MUX_AI_ERROR_SOURCES.ASSET,
11417
+ facts: { assetId, trackId }
11418
+ }
11275
11419
  );
11276
11420
  }
11277
11421
  const outputTrack = {
@@ -11399,7 +11543,7 @@ async function translateCaptionsInternal(assetId, trackId, toLanguageCode, optio
11399
11543
  if (outcome.kind === "blocked") {
11400
11544
  throw trackReplacementBlockedError(outcome, { message: `${outcome.reason}${deletedNote}`, facts: { ...trackTargetFacts(outputTrack), ...facts } });
11401
11545
  }
11402
- const failure = outcome.error ?? internalError(`Track write failed without a classified error: ${outcome.reason}`);
11546
+ const failure = trackWriteFailure(outcome);
11403
11547
  Object.assign(failure, { facts: { ...facts, ...failure.facts } });
11404
11548
  failure.message = `Failed to add translated track to Mux asset: ${failure.message}.${deletedNote}`;
11405
11549
  throw failure;