@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.
package/dist/index.js CHANGED
@@ -5,7 +5,7 @@ var __export = (target, all) => {
5
5
  };
6
6
 
7
7
  // package.json
8
- var version = "0.60.0";
8
+ var version = "0.61.0-canary.95";
9
9
 
10
10
  // node_modules/@workflow/serde/dist/index.js
11
11
  var WORKFLOW_SERIALIZE = /* @__PURE__ */ Symbol.for("workflow-serialize");
@@ -574,14 +574,16 @@ var MUX_AI_ERROR_DEPENDENCY_VALUES = Object.values(MUX_AI_ERROR_DEPENDENCIES);
574
574
  var MUX_AI_ERROR_CODES = {
575
575
  /** The requested time range is invalid, or has nothing to work with. Facts: `reason` (`invalid_start_time`, `invalid_end_time`, `exceeds_duration`, `empty_range`, `no_video`, `no_transcript`) and the bounds involved. */
576
576
  INVALID_SCOPE: "invalid_scope",
577
- /** 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. */
577
+ /** 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. */
578
578
  TRACK_REPLACEMENT_BLOCKED: "track_replacement_blocked",
579
- /** 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`. */
579
+ /** An option's value can't be used. Facts: `parameter` (the caller's option name), `reason` (`too_many`, `empty`, `too_long`, `disallowed_characters`, `not_normalized`, `multiline`, `required_with`, `conflicts_with`, `not_allowed`, `one_of_required`) and the values the reason names: `count` and `max`, `index` (0-based entry), `length` and `maxLength`, `characters`, `with` and `withValue` (the other option), `allowed` and `value`, `parameters` (the options to choose from). */
580
580
  INVALID_PARAMETER: "invalid_parameter",
581
581
  /** 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. */
582
582
  PARAMETER_OUT_OF_RANGE: "parameter_out_of_range",
583
583
  /** No ready caption track matches the requested track or language. Facts: `trackId` or `languageCode`, and what is available. */
584
584
  CAPTION_TRACK_NOT_FOUND: "caption_track_not_found",
585
+ /** The caption track has no language, so its source language can't be determined. Facts: `trackId`. */
586
+ CAPTION_TRACK_LANGUAGE_MISSING: "caption_track_language_missing",
585
587
  /** The asset has no public or signed playback ID (DRM-only assets included). */
586
588
  PLAYBACK_ID_NOT_FOUND: "playback_id_not_found",
587
589
  /** Mux has no asset with the requested ID in this environment. Facts: `assetId`. */
@@ -598,6 +600,16 @@ var MUX_AI_ERROR_CODES = {
598
600
  SIGNING_CREDENTIALS_MISSING: "signing_credentials_missing",
599
601
  /** Storage is needed but the service running the SDK didn't configure it. */
600
602
  STORAGE_NOT_CONFIGURED: "storage_not_configured",
603
+ /** 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. */
604
+ TRACK_WRITE_UNCLASSIFIED: "track_write_unclassified",
605
+ /** Mux answered a track create without a track id. The track may exist, so it isn't step-retried. Facts: `call`, `assetId`. */
606
+ TRACK_ID_MISSING: "track_id_missing",
607
+ /** The asset snapshot the service running the SDK passed in is for a different asset than the one requested. Facts: `assetId`, `snapshotAssetId`. */
608
+ ASSET_SNAPSHOT_MISMATCH: "asset_snapshot_mismatch",
609
+ /** Mux answered an asset fetch with a different asset than the one requested. Facts: `assetId`, `returnedAssetId`. */
610
+ ASSET_ID_MISMATCH: "asset_id_mismatch",
611
+ /** Translation needed to split a chunk of fewer than two cues: a bug in the SDK's chunking. Facts: `chunkId`, `cueCount`. */
612
+ TRANSLATION_CHUNK_UNSPLITTABLE: "translation_chunk_unsplittable",
601
613
  /** The model provider refused the content. Facts: `reason` and `category`. */
602
614
  CONTENT_POLICY_BLOCKED: "content_policy_blocked",
603
615
  /** The model returned no output, or a required field was empty. Facts: `call`, `provider`, `model`, and `assetId` when there is one. */
@@ -635,6 +647,14 @@ var MUX_AI_ERROR_CATALOG = {
635
647
  // The configuration of the service running the SDK.
636
648
  [MUX_AI_ERROR_CODES.SIGNING_CREDENTIALS_MISSING]: { type: MUX_AI_ERROR_TYPES.SERVER_ERROR, source: MUX_AI_ERROR_SOURCES.INTERNAL },
637
649
  [MUX_AI_ERROR_CODES.STORAGE_NOT_CONFIGURED]: { type: MUX_AI_ERROR_TYPES.SERVER_ERROR, source: MUX_AI_ERROR_SOURCES.INTERNAL },
650
+ [MUX_AI_ERROR_CODES.ASSET_SNAPSHOT_MISMATCH]: { type: MUX_AI_ERROR_TYPES.SERVER_ERROR, source: MUX_AI_ERROR_SOURCES.INTERNAL },
651
+ // The SDK's own bug: never expected.
652
+ [MUX_AI_ERROR_CODES.TRACK_WRITE_UNCLASSIFIED]: { type: MUX_AI_ERROR_TYPES.SERVER_ERROR, source: MUX_AI_ERROR_SOURCES.INTERNAL },
653
+ [MUX_AI_ERROR_CODES.TRANSLATION_CHUNK_UNSPLITTABLE]: { type: MUX_AI_ERROR_TYPES.SERVER_ERROR, source: MUX_AI_ERROR_SOURCES.INTERNAL },
654
+ [MUX_AI_ERROR_CODES.CAPTION_TRACK_LANGUAGE_MISSING]: { type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR, source: MUX_AI_ERROR_SOURCES.ASSET },
655
+ // The track may exist, so a step retry could duplicate it; the job stays retryable.
656
+ [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 },
657
+ [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 },
638
658
  // Model calls.
639
659
  [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 },
640
660
  // The model-output policies below keep what these failures did before classification
@@ -915,8 +935,8 @@ function requestIdOf(headers) {
915
935
  if (!headers || typeof headers !== "object") {
916
936
  return void 0;
917
937
  }
918
- const names = ["x-request-id", "x-amz-request-id", "request-id"];
919
- for (const name of names) {
938
+ const names2 = ["x-request-id", "x-amz-request-id", "request-id"];
939
+ for (const name of names2) {
920
940
  const value = typeof headers.get === "function" ? headers.get(name) : headers[name];
921
941
  if (typeof value === "string" && value) {
922
942
  return value;
@@ -1315,6 +1335,7 @@ function muxAssetFetchError(assetId, error) {
1315
1335
  }
1316
1336
  function missingTrackIdError(message, facts) {
1317
1337
  return new MuxAiError(message, {
1338
+ code: MUX_AI_ERROR_CODES.TRACK_ID_MISSING,
1318
1339
  type: MUX_AI_ERROR_TYPES.PROCESSING_ERROR,
1319
1340
  source: MUX_AI_ERROR_SOURCES.UPSTREAM,
1320
1341
  dependency: MUX_AI_ERROR_DEPENDENCIES.MUX_VIDEO,
@@ -1717,6 +1738,14 @@ async function resolveMuxSigningContext(credentials) {
1717
1738
  }
1718
1739
 
1719
1740
  // src/lib/mux-tracks.ts
1741
+ function trackWriteFailure(outcome) {
1742
+ return outcome.error ?? new MuxAiError(`Track write failed without a classified error: ${outcome.reason}`, {
1743
+ code: MUX_AI_ERROR_CODES.TRACK_WRITE_UNCLASSIFIED,
1744
+ type: MUX_AI_ERROR_TYPES.SERVER_ERROR,
1745
+ source: MUX_AI_ERROR_SOURCES.INTERNAL,
1746
+ facts: { reason: errorDetailFact(outcome.reason) }
1747
+ });
1748
+ }
1720
1749
  var MUX_TRACK_PASSTHROUGH_MAX_CHARS = 255;
1721
1750
  function normalizeTrackLanguageCode(code) {
1722
1751
  if (!code) {
@@ -1956,17 +1985,22 @@ async function createTextTrackOnMux(assetId, languageCode, trackName, presignedU
1956
1985
  "use step";
1957
1986
  const muxClient = await resolveMuxClient(credentials);
1958
1987
  const mux = await muxClient.createClient();
1959
- const trackResponse = await mux.video.assets.createTrack(assetId, {
1960
- type: "text",
1961
- text_type: "subtitles",
1962
- language_code: languageCode,
1963
- name: trackName,
1964
- url: presignedUrl,
1965
- closed_captions: options.closedCaptions,
1966
- passthrough: options.passthrough
1967
- });
1988
+ let trackResponse;
1989
+ try {
1990
+ trackResponse = await mux.video.assets.createTrack(assetId, {
1991
+ type: "text",
1992
+ text_type: "subtitles",
1993
+ language_code: languageCode,
1994
+ name: trackName,
1995
+ url: presignedUrl,
1996
+ closed_captions: options.closedCaptions,
1997
+ passthrough: options.passthrough
1998
+ });
1999
+ } catch (error) {
2000
+ throw muxVideoCallError("Failed to create the text track on Mux", "create_track", error, { assetId });
2001
+ }
1968
2002
  if (!trackResponse.id) {
1969
- throw new Error("Failed to create text track: no track ID returned from Mux");
2003
+ throw missingTrackIdError("Failed to create text track: no track ID returned from Mux", { assetId });
1970
2004
  }
1971
2005
  return trackResponse.id;
1972
2006
  }
@@ -2171,7 +2205,16 @@ function trackTarget(facts) {
2171
2205
  const parts = [facts.languageCode && `language '${text(facts.languageCode)}'`, facts.trackName && `name '${text(facts.trackName)}'`].filter(Boolean);
2172
2206
  return parts.length > 0 ? ` for ${parts.join(" or ")}` : "";
2173
2207
  }
2208
+ function restoredSourceNote(facts) {
2209
+ if (facts.sourceRestored === true && facts.restoredTrackId) {
2210
+ return ` The source track was restored as ${text(facts.restoredTrackId)}.`;
2211
+ }
2212
+ return facts.sourceRestored === false ? " Restoring the source track also failed." : "";
2213
+ }
2174
2214
  function blockedTrackMessage(facts) {
2215
+ return blockedTrackReason(facts) + restoredSourceNote(facts);
2216
+ }
2217
+ function blockedTrackReason(facts) {
2175
2218
  const tracks = Array.isArray(facts.conflictingTracks) ? facts.conflictingTracks : [];
2176
2219
  const kind = facts.trackType === "audio" ? "audio" : "text";
2177
2220
  const subject = tracks.length > 1 ? `${tracks.length} ${kind} tracks` : `${kind === "audio" ? "An" : "A"} ${kind} track`;
@@ -2206,6 +2249,10 @@ function scopeMessage(facts) {
2206
2249
  return "The requested time range can't be used for this asset.";
2207
2250
  }
2208
2251
  }
2252
+ function names(value) {
2253
+ const items = (Array.isArray(value) ? value : [value]).filter((item) => item !== void 0 && item !== null).map(text);
2254
+ return items.length > 1 ? `${items.slice(0, -1).join(", ")} or ${items.at(-1)}` : items[0] ?? "another option";
2255
+ }
2209
2256
  function quotedList(value) {
2210
2257
  return Array.isArray(value) && value.length > 0 ? value.map((item) => `'${text(item)}'`).join(" or ") : "certain characters";
2211
2258
  }
@@ -2224,6 +2271,16 @@ function invalidParameterMessage(facts) {
2224
2271
  return `${subject} must not contain ${quotedList(facts.characters)}${entry}.`;
2225
2272
  case "not_normalized":
2226
2273
  return `${subject} must not contain invisible characters or characters altered by Unicode NFKC normalization${entry}.`;
2274
+ case "multiline":
2275
+ return `${subject} must be a single line${entry}.`;
2276
+ case "required_with":
2277
+ return `${parameter} is required when ${text(facts.with)} is set${facts.withValue === void 0 ? "" : ` to '${text(facts.withValue)}'`}.`;
2278
+ case "conflicts_with":
2279
+ return `${parameter} can't be combined with ${names(facts.with)}.`;
2280
+ case "not_allowed":
2281
+ return `${parameter} must be ${quotedList(facts.allowed)}${facts.value === void 0 ? "" : ` (received '${text(facts.value)}')`}.`;
2282
+ case "one_of_required":
2283
+ return `Provide at least one of ${names(facts.parameters)}.`;
2227
2284
  default:
2228
2285
  return `${parameter} has a value that can't be used.`;
2229
2286
  }
@@ -2239,13 +2296,17 @@ var MUX_AI_ERROR_PUBLIC_MAPPINGS = {
2239
2296
  message: scopeMessage
2240
2297
  },
2241
2298
  [MUX_AI_ERROR_CODES.TRACK_REPLACEMENT_BLOCKED]: {
2242
- facts: ["reason", "trackType", "languageCode", "trackName", "conflictingTracks"],
2299
+ facts: ["reason", "trackType", "languageCode", "trackName", "conflictingTracks", "sourceRestored", "restoredTrackId"],
2243
2300
  message: blockedTrackMessage
2244
2301
  },
2245
2302
  [MUX_AI_ERROR_CODES.CAPTION_TRACK_NOT_FOUND]: {
2246
2303
  facts: ["trackId", "availableTrackIds", "languageCode", "availableLanguages"],
2247
2304
  message: (facts) => facts.trackId ? `Track ${text(facts.trackId)} was not found or is not ready. Available track IDs: ${list(facts.availableTrackIds)}.` : `No ready caption track was found${facts.languageCode ? ` for language ${text(facts.languageCode)}` : ""}. Available languages: ${list(facts.availableLanguages)}.`
2248
2305
  },
2306
+ [MUX_AI_ERROR_CODES.CAPTION_TRACK_LANGUAGE_MISSING]: {
2307
+ facts: ["trackId"],
2308
+ message: (facts) => `${facts.trackId ? `Track ${text(facts.trackId)}` : "The caption track"} has no language set, so its source language can't be determined.`
2309
+ },
2249
2310
  [MUX_AI_ERROR_CODES.ASSET_NOT_FOUND]: {
2250
2311
  facts: ["assetId"],
2251
2312
  message: (facts) => facts.assetId ? `Asset ${text(facts.assetId)} could not be found.` : "The asset could not be found."
@@ -2258,7 +2319,7 @@ var MUX_AI_ERROR_PUBLIC_MAPPINGS = {
2258
2319
  },
2259
2320
  // Names the caller's own option; a consumer that exposes different names overrides the wording.
2260
2321
  [MUX_AI_ERROR_CODES.INVALID_PARAMETER]: {
2261
- facts: ["parameter", "reason", "count", "max", "index", "length", "maxLength", "characters"],
2322
+ facts: ["parameter", "reason", "count", "max", "index", "length", "maxLength", "characters", "with", "withValue", "allowed", "value", "parameters"],
2262
2323
  message: invalidParameterMessage
2263
2324
  },
2264
2325
  [MUX_AI_ERROR_CODES.PARAMETER_OUT_OF_RANGE]: {
@@ -3747,10 +3808,20 @@ async function getPlaybackIdForAsset(assetId, credentials, assetSnapshot, option
3747
3808
  }
3748
3809
  }
3749
3810
  if (asset.id !== assetId) {
3750
- throw new MuxAiError("Asset snapshot does not match the requested asset ID.", {
3751
- type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR,
3752
- source: MUX_AI_ERROR_SOURCES.REQUEST,
3753
- facts: { assetId, snapshotAssetId: asset.id, inputs: ["assetId", "assetSnapshot"] }
3811
+ if (assetSnapshot) {
3812
+ throw new MuxAiError("Asset snapshot does not match the requested asset ID.", {
3813
+ code: MUX_AI_ERROR_CODES.ASSET_SNAPSHOT_MISMATCH,
3814
+ type: MUX_AI_ERROR_TYPES.SERVER_ERROR,
3815
+ source: MUX_AI_ERROR_SOURCES.INTERNAL,
3816
+ facts: { assetId, snapshotAssetId: asset.id }
3817
+ });
3818
+ }
3819
+ throw new MuxAiError("Mux returned a different asset than the one requested.", {
3820
+ code: MUX_AI_ERROR_CODES.ASSET_ID_MISMATCH,
3821
+ type: MUX_AI_ERROR_TYPES.PROCESSING_ERROR,
3822
+ source: MUX_AI_ERROR_SOURCES.UPSTREAM,
3823
+ dependency: MUX_AI_ERROR_DEPENDENCIES.MUX_VIDEO,
3824
+ facts: { assetId, returnedAssetId: asset.id }
3754
3825
  });
3755
3826
  }
3756
3827
  return toPlaybackAsset(asset, options);
@@ -4316,7 +4387,7 @@ __export(workflows_exports, {
4316
4387
  import { generateText, jsonSchema, NoObjectGeneratedError as NoObjectGeneratedError2, Output } from "ai";
4317
4388
 
4318
4389
  // src/lib/content-policy-error.ts
4319
- import { APICallError as APICallError2, NoObjectGeneratedError, NoOutputGeneratedError as NoOutputGeneratedError2, RetryError } from "ai";
4390
+ import { APICallError as APICallError2, NoObjectGeneratedError, NoOutputGeneratedError as NoOutputGeneratedError2, RetryError, TypeValidationError } from "ai";
4320
4391
  import { z as z4 } from "zod";
4321
4392
 
4322
4393
  // src/lib/google-errors.ts
@@ -4808,6 +4879,67 @@ function getContentPolicyTokenUsage(error) {
4808
4879
  function findBlockedCategory(ratings) {
4809
4880
  return ratings?.find((rating) => rating.blocked === true)?.category ?? void 0;
4810
4881
  }
4882
+ function findProviderServiceError(error) {
4883
+ if (!error) {
4884
+ return void 0;
4885
+ }
4886
+ if (RetryError.isInstance(error)) {
4887
+ return findProviderServiceError(error.lastError);
4888
+ }
4889
+ if (APICallError2.isInstance(error)) {
4890
+ return error;
4891
+ }
4892
+ if (error instanceof Error && "cause" in error) {
4893
+ return findProviderServiceError(error.cause);
4894
+ }
4895
+ return void 0;
4896
+ }
4897
+ function isUnusableOutputError(error) {
4898
+ return NoObjectGeneratedError.isInstance(error) || NoOutputGeneratedError2.isInstance(error) || TypeValidationError.isInstance(error);
4899
+ }
4900
+ function modelStepError(error, message, facts) {
4901
+ if (MuxAiError.is(error)) {
4902
+ Object.assign(error, { facts: { ...facts, ...error.facts } });
4903
+ return error;
4904
+ }
4905
+ const context = { call: String(facts.call), provider: String(facts.provider), ...facts.model !== void 0 && { model: String(facts.model) } };
4906
+ let classified = classifyModelCallError(error, context);
4907
+ if (classified) {
4908
+ Object.assign(classified, { facts: { ...facts, ...classified.facts } });
4909
+ return classified;
4910
+ }
4911
+ if (isUnusableOutputError(error)) {
4912
+ classified = new MuxAiError(message, {
4913
+ code: MUX_AI_ERROR_CODES.MODEL_OUTPUT_INVALID,
4914
+ type: MUX_AI_ERROR_TYPES.PROCESSING_ERROR,
4915
+ source: MUX_AI_ERROR_SOURCES.UPSTREAM,
4916
+ dependency: MUX_AI_ERROR_DEPENDENCIES.AI_PROVIDER,
4917
+ facts,
4918
+ // As before: the raw error was retried by the step runner. See the model-output follow-up.
4919
+ transient: true,
4920
+ cause: error
4921
+ });
4922
+ } else {
4923
+ const providerError = findProviderServiceError(error);
4924
+ classified = providerError ? (
4925
+ // A provider without its own classifier: not classified, but kept retryable by the
4926
+ // step runner when the AI SDK judges it retryable (no response, 408, 409, 429, 5xx),
4927
+ // as the raw error was before.
4928
+ new MuxAiError(message, {
4929
+ type: MUX_AI_ERROR_TYPES.SERVER_ERROR,
4930
+ source: MUX_AI_ERROR_SOURCES.INTERNAL,
4931
+ facts,
4932
+ transient: providerError.isRetryable,
4933
+ cause: error
4934
+ })
4935
+ ) : internalError(message, facts, error);
4936
+ }
4937
+ const usage = getErrorTokenUsage(error);
4938
+ if (usage) {
4939
+ classified.usage = usage;
4940
+ }
4941
+ return classified;
4942
+ }
4811
4943
 
4812
4944
  // src/lib/model-call-diagnostics.ts
4813
4945
  import { APICallError as APICallError3 } from "ai";
@@ -6841,6 +6973,7 @@ async function identifyProfanityWithAI({
6841
6973
  tag: "transcript",
6842
6974
  content: plainText
6843
6975
  });
6976
+ const context = { call: "detect_profanity", provider, model: modelId };
6844
6977
  const response = await withContentPolicyAwareRetry(() => generateText5({
6845
6978
  model,
6846
6979
  maxRetries: 0,
@@ -6854,8 +6987,10 @@ async function identifyProfanityWithAI({
6854
6987
  ${transcriptSection}`
6855
6988
  }
6856
6989
  ]
6857
- }));
6858
- const output = getGeneratedOutputWithContentPolicyHandling(response);
6990
+ }), void 0, context).catch((error) => {
6991
+ throw modelStepError(error, "Profanity detection model call failed", { ...context });
6992
+ });
6993
+ const output = getGeneratedOutputWithContentPolicyHandling(response, context);
6859
6994
  const unexpectedKeys = detectUnexpectedKeysFromRawText(
6860
6995
  response.text,
6861
6996
  profanityDetectionSchema.keyof().options
@@ -6912,7 +7047,49 @@ async function deleteTrackOnMux(assetId, trackId, credentials) {
6912
7047
  "use step";
6913
7048
  const muxClient = await resolveMuxClient(credentials);
6914
7049
  const mux = await muxClient.createClient();
6915
- await mux.video.assets.deleteTrack(assetId, trackId);
7050
+ try {
7051
+ await mux.video.assets.deleteTrack(assetId, trackId);
7052
+ } catch (error) {
7053
+ if (httpStatusOf(error) === 404) {
7054
+ return;
7055
+ }
7056
+ throw muxVideoCallError("Failed to delete the original track on Mux", "delete_track", error, { assetId, trackId });
7057
+ }
7058
+ }
7059
+ function restoreFailureFacts(error) {
7060
+ if (!MuxAiError.is(error)) {
7061
+ return { restoreError: errorDetailFact(extractErrorDetail(error)) };
7062
+ }
7063
+ const cause = error.causes?.[0]?.message;
7064
+ return {
7065
+ restoreError: errorDetailFact(cause ? `${error.message}: ${cause}` : error.message),
7066
+ restoreFailure: error.facts
7067
+ };
7068
+ }
7069
+ function invalidOptionError(message, facts, inputs) {
7070
+ return new MuxAiError(message, {
7071
+ code: MUX_AI_ERROR_CODES.INVALID_PARAMETER,
7072
+ type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR,
7073
+ source: MUX_AI_ERROR_SOURCES.REQUEST,
7074
+ facts: { ...facts, inputs }
7075
+ });
7076
+ }
7077
+ function speakerLabelProblem(label) {
7078
+ if (!label) {
7079
+ return "empty";
7080
+ }
7081
+ if (label.includes("[") || label.includes("]")) {
7082
+ return "disallowed_characters";
7083
+ }
7084
+ return /[\r\n]/.test(label) ? "multiline" : void 0;
7085
+ }
7086
+ function missingStorageSettings(config) {
7087
+ return [
7088
+ ...config.s3Endpoint ? [] : ["s3Endpoint"],
7089
+ ...config.s3Bucket ? [] : ["s3Bucket"],
7090
+ ...config.storageAdapter || config.s3AccessKeyId ? [] : ["S3_ACCESS_KEY_ID"],
7091
+ ...config.storageAdapter || config.s3SecretAccessKey ? [] : ["S3_SECRET_ACCESS_KEY"]
7092
+ ];
6916
7093
  }
6917
7094
  async function editCaptions(assetId, trackId, options) {
6918
7095
  "use workflow";
@@ -6947,42 +7124,64 @@ async function editCaptionsInternal(assetId, trackId, options, collectedUsage) {
6947
7124
  const hasReplacements = !!replacementsOption && replacementsOption.length > 0;
6948
7125
  const hasSpeakerReplacements = !!speakerReplacementsOption && speakerReplacementsOption.length > 0;
6949
7126
  if (!hasAutoCensor && !hasReplacements && !hasSpeakerReplacements) {
6950
- throw new LegacyMuxAiError("At least one of autoCensorProfanity, replacements, or speakerReplacements must be provided.", { type: "validation_error" });
7127
+ const parameters = ["autoCensorProfanity", "replacements", "speakerReplacements"];
7128
+ throw invalidOptionError(
7129
+ "At least one of autoCensorProfanity, replacements, or speakerReplacements must be provided.",
7130
+ { reason: "one_of_required", parameters },
7131
+ parameters
7132
+ );
6951
7133
  }
6952
7134
  if (autoCensorOption && !provider) {
6953
- throw new LegacyMuxAiError("provider is required when using autoCensorProfanity.", { type: "validation_error" });
7135
+ throw invalidOptionError(
7136
+ "provider is required when using autoCensorProfanity.",
7137
+ { parameter: "provider", reason: "required_with", with: "autoCensorProfanity" },
7138
+ ["provider", "autoCensorProfanity"]
7139
+ );
6954
7140
  }
6955
7141
  const legacyTrackNaming = deleteOriginalTrack !== void 0 || trackNameSuffix !== void 0;
6956
7142
  if (legacyTrackNaming && (replaceExistingTracksOption !== void 0 || providedTrackName !== void 0)) {
6957
- throw new LegacyMuxAiError(
7143
+ const legacy = deleteOriginalTrack !== void 0 ? "deleteOriginalTrack" : "trackNameSuffix";
7144
+ const conflicting = [
7145
+ ...replaceExistingTracksOption !== void 0 ? ["replaceExistingTracks"] : [],
7146
+ ...providedTrackName !== void 0 ? ["trackName"] : []
7147
+ ];
7148
+ throw invalidOptionError(
6958
7149
  "deleteOriginalTrack and trackNameSuffix are deprecated and cannot be combined with replaceExistingTracks or trackName.",
6959
- { type: "validation_error" }
7150
+ { parameter: legacy, reason: "conflicts_with", with: conflicting },
7151
+ [legacy, ...conflicting]
6960
7152
  );
6961
7153
  }
6962
7154
  if (replaceExistingTracksOption !== void 0 && replaceExistingTracksOption !== "replace" && replaceExistingTracksOption !== "fail") {
6963
- throw new LegacyMuxAiError(
7155
+ throw invalidOptionError(
6964
7156
  `replaceExistingTracks must be "replace" or "fail" for editCaptions (received "${String(replaceExistingTracksOption)}").`,
6965
- { type: "validation_error" }
7157
+ {
7158
+ parameter: "replaceExistingTracks",
7159
+ reason: "not_allowed",
7160
+ allowed: ["replace", "fail"],
7161
+ value: String(replaceExistingTracksOption).slice(0, 100)
7162
+ },
7163
+ ["replaceExistingTracks"]
6966
7164
  );
6967
7165
  }
6968
7166
  const replaceExistingTracks = replaceExistingTracksOption ?? "replace";
6969
7167
  if (!legacyTrackNaming && replaceExistingTracks === "fail" && !providedTrackName) {
6970
- throw new LegacyMuxAiError(
7168
+ throw invalidOptionError(
6971
7169
  `trackName is required when replaceExistingTracks is "fail": the edited track cannot reuse the source track's name while the source is kept.`,
6972
- { type: "validation_error" }
7170
+ { parameter: "trackName", reason: "required_with", with: "replaceExistingTracks", withValue: "fail" },
7171
+ ["trackName", "replaceExistingTracks"]
6973
7172
  );
6974
7173
  }
6975
- const trackPassthrough = validateTrackPassthrough(providedTrackPassthrough) ?? buildMuxAiTrackPassthrough("edit-captions");
7174
+ const trackPassthrough = validateTrackPassthrough(providedTrackPassthrough, { classifiedErrors: true }) ?? buildMuxAiTrackPassthrough("edit-captions");
6976
7175
  const deleteOriginal = deleteOriginalTrack !== false;
6977
7176
  const uploadToMux = uploadToMuxOption !== false;
6978
7177
  const uploadToS3 = uploadToS3Option || uploadToMux;
6979
- for (const replacement of speakerReplacementsOption ?? []) {
6980
- const hasInvalidFindCharacter = replacement.find.includes("[") || replacement.find.includes("]") || /[\r\n]/.test(replacement.find);
6981
- const hasInvalidReplaceCharacter = replacement.replace.includes("[") || replacement.replace.includes("]") || /[\r\n]/.test(replacement.replace);
6982
- if (!replacement.find || !replacement.replace || hasInvalidFindCharacter || hasInvalidReplaceCharacter) {
6983
- throw new LegacyMuxAiError(
7178
+ for (const [index, replacement] of (speakerReplacementsOption ?? []).entries()) {
7179
+ const reason = speakerLabelProblem(replacement.find) ?? speakerLabelProblem(replacement.replace);
7180
+ if (reason) {
7181
+ throw invalidOptionError(
6984
7182
  "Speaker replacement labels must be non-empty and must not contain square brackets or newlines.",
6985
- { type: "validation_error" }
7183
+ { parameter: "speakerReplacements", reason, index, ...reason === "disallowed_characters" && { characters: ["[", "]"] } },
7184
+ ["speakerReplacements"]
6986
7185
  );
6987
7186
  }
6988
7187
  }
@@ -6991,28 +7190,30 @@ async function editCaptionsInternal(assetId, trackId, options, collectedUsage) {
6991
7190
  const s3Bucket = providedS3Bucket ?? env_default.S3_BUCKET;
6992
7191
  const s3AccessKeyId = env_default.S3_ACCESS_KEY_ID;
6993
7192
  const s3SecretAccessKey = env_default.S3_SECRET_ACCESS_KEY;
6994
- if (uploadToS3 && (!s3Endpoint || !s3Bucket || !storageAdapter && (!s3AccessKeyId || !s3SecretAccessKey))) {
6995
- throw new LegacyMuxAiError(
6996
- "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.",
6997
- { type: "validation_error" }
6998
- );
7193
+ if (uploadToS3) {
7194
+ const missing = missingStorageSettings({ s3Endpoint, s3Bucket, storageAdapter, s3AccessKeyId, s3SecretAccessKey });
7195
+ if (missing.length > 0) {
7196
+ throw storageNotConfiguredError(missing);
7197
+ }
6999
7198
  }
7000
- const { asset: assetData, playbackId, policy } = await getPlaybackIdForAsset(assetId, credentials, options.assetSnapshot);
7199
+ const { asset: assetData, playbackId, policy } = await getPlaybackIdForAsset(assetId, credentials, options.assetSnapshot, { classifiedErrors: true });
7001
7200
  const assetDurationSeconds = getAssetDurationSecondsFromAsset(assetData);
7002
7201
  const signingContext = await resolveMuxSigningContext(credentials);
7003
7202
  if (policy === "signed" && !signingContext) {
7004
- throw new LegacyMuxAiError(
7005
- "Signed playback ID requires signing credentials. Set MUX_SIGNING_KEY and MUX_PRIVATE_KEY environment variables.",
7006
- { type: "validation_error" }
7007
- );
7203
+ throw signingCredentialsMissingError();
7008
7204
  }
7009
7205
  const readyTextTracks = getReadyTextTracks(assetData);
7010
7206
  const sourceTrack = readyTextTracks.find((t) => t.id === trackId);
7011
7207
  if (!sourceTrack) {
7012
- const availableTrackIds = readyTextTracks.map((t) => t.id).filter(Boolean).join(", ");
7013
- throw new LegacyMuxAiError(
7014
- `Track ${trackId} not found or not ready on asset ${assetId}. Available track IDs: ${availableTrackIds || "none"}.`,
7015
- { type: "validation_error" }
7208
+ const availableTrackIds = readyTextTracks.map((t) => t.id).filter((id) => !!id);
7209
+ throw new MuxAiError(
7210
+ `Track ${trackId} not found or not ready on asset ${assetId}. Available track IDs: ${availableTrackIds.join(", ") || "none"}.`,
7211
+ {
7212
+ code: MUX_AI_ERROR_CODES.CAPTION_TRACK_NOT_FOUND,
7213
+ type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR,
7214
+ source: MUX_AI_ERROR_SOURCES.ASSET,
7215
+ facts: { assetId, trackId, availableTrackIds }
7216
+ }
7016
7217
  );
7017
7218
  }
7018
7219
  const sourceLanguageCode = sourceTrack.language_code || "en";
@@ -7022,23 +7223,25 @@ async function editCaptionsInternal(assetId, trackId, options, collectedUsage) {
7022
7223
  name: providedTrackName ?? sourceName
7023
7224
  };
7024
7225
  if (replaceExistingTracks === "fail" && normalizeTrackName(outputTrack.name) === normalizeTrackName(sourceName)) {
7025
- throw new LegacyMuxAiError(
7026
- `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.`,
7027
- { type: "validation_error" }
7028
- );
7226
+ throw trackReplacementBlockedError({
7227
+ 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.`,
7228
+ code: "name_collision",
7229
+ tracks: [summarizeTextTrack(sourceTrack)],
7230
+ conflictsOnLanguage: false
7231
+ }, { facts: { ...trackTargetFacts(outputTrack), assetId, policy: replaceExistingTracks } });
7029
7232
  }
7030
7233
  if (uploadToMux && !legacyTrackNaming) {
7031
7234
  const plan = planSourceTrackReplacement(assetData, trackId, outputTrack, replaceExistingTracks);
7032
7235
  if (plan.kind === "blocked") {
7033
- throw new LegacyMuxAiError(plan.reason, { type: "validation_error" });
7236
+ throw trackReplacementBlockedError(plan, { facts: { ...trackTargetFacts(outputTrack), assetId, policy: replaceExistingTracks } });
7034
7237
  }
7035
7238
  }
7036
7239
  const vttUrl = await buildTranscriptUrl(playbackId, trackId, policy === "signed", credentials);
7037
7240
  let vttContent;
7038
7241
  try {
7039
- vttContent = await fetchVttFromMux(vttUrl);
7242
+ vttContent = await fetchVttFromMux(vttUrl, { classifiedErrors: true });
7040
7243
  } catch (error) {
7041
- legacyWrapError(error, "Failed to fetch VTT content");
7244
+ wrapError(error, "Failed to fetch VTT content", { assetId, trackId });
7042
7245
  }
7043
7246
  let editedVtt = vttContent;
7044
7247
  let totalReplacementCount = 0;
@@ -7049,36 +7252,45 @@ async function editCaptionsInternal(assetId, trackId, options, collectedUsage) {
7049
7252
  const { mode = "blank", alwaysCensor = [], neverCensor = [] } = autoCensorOption;
7050
7253
  const plainText = extractTextFromVTT(vttContent);
7051
7254
  if (!plainText.trim()) {
7052
- throw new LegacyMuxAiError("Track transcript is empty; nothing to censor.", { type: "validation_error" });
7255
+ throw new MuxAiError("Track transcript is empty; nothing to censor.", {
7256
+ code: MUX_AI_ERROR_CODES.TRANSCRIPT_EMPTY,
7257
+ type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR,
7258
+ source: MUX_AI_ERROR_SOURCES.ASSET,
7259
+ facts: { assetId, trackId }
7260
+ });
7053
7261
  }
7054
7262
  const modelConfig = resolveLanguageModelConfig({
7055
7263
  ...options,
7056
7264
  provider,
7057
7265
  model
7058
7266
  });
7059
- let detectedProfanity;
7267
+ let result;
7060
7268
  try {
7061
- const result = await identifyProfanityWithAI({
7269
+ result = await identifyProfanityWithAI({
7062
7270
  plainText,
7063
7271
  provider: modelConfig.provider,
7064
7272
  modelId: modelConfig.modelId,
7065
7273
  credentials
7066
7274
  });
7067
- detectedProfanity = result.profanity;
7068
- usage = result.usage;
7069
- collectedUsage.push(result.usage);
7070
- if (result.unexpectedKeys.length > 0) {
7071
- console.warn(
7072
- `[@mux/ai] Model emitted unexpected keys in profanity detection (stripped): ${result.unexpectedKeys.join(", ")}.`
7073
- );
7074
- for (const key of result.unexpectedKeys) {
7075
- safety.record(`profanity_detection.${key}`, "unexpected_key");
7076
- }
7077
- }
7078
7275
  } catch (error) {
7079
- legacyWrapError(error, `Failed to detect profanity with ${modelConfig.provider}`);
7276
+ wrapError(error, `Failed to detect profanity with ${modelConfig.provider}`, {
7277
+ call: "detect_profanity",
7278
+ provider: modelConfig.provider,
7279
+ model: modelConfig.modelId
7280
+ });
7281
+ }
7282
+ const detectedProfanity = result.profanity;
7283
+ usage = result.usage;
7284
+ collectedUsage.push(result.usage);
7285
+ if (result.unexpectedKeys.length > 0) {
7286
+ console.warn(
7287
+ `[@mux/ai] Model emitted unexpected keys in profanity detection (stripped): ${result.unexpectedKeys.join(", ")}.`
7288
+ );
7289
+ for (const key of result.unexpectedKeys) {
7290
+ safety.record(`profanity_detection.${key}`, "unexpected_key");
7291
+ }
7080
7292
  }
7081
- const scrubbedProfanity = detectedProfanity.map((word, i) => safety.scrubDetailed(word, `profanity[${i}]`)).filter((result) => !result.leaked).map((result) => result.text);
7293
+ const scrubbedProfanity = detectedProfanity.map((word, i) => safety.scrubDetailed(word, `profanity[${i}]`)).filter((result2) => !result2.leaked).map((result2) => result2.text);
7082
7294
  const finalProfanity = applyOverrideLists(scrubbedProfanity, alwaysCensor, neverCensor);
7083
7295
  const { censoredVtt, replacements: censorReplacements } = censorVttContent(editedVtt, finalProfanity, mode);
7084
7296
  editedVtt = censoredVtt;
@@ -7124,11 +7336,11 @@ async function editCaptionsInternal(assetId, trackId, options, collectedUsage) {
7124
7336
  try {
7125
7337
  presignedUrl = await uploadEditedVttToS3({ editedVtt, ...s3Config });
7126
7338
  } catch (error) {
7127
- legacyWrapError(error, "Failed to upload VTT to S3");
7339
+ wrapError(error, "Failed to upload VTT to S3", { call: "put_object", bucket: s3Bucket });
7128
7340
  }
7129
7341
  if (uploadToMux && legacyTrackNaming) {
7342
+ const trackName = `${sourceName} (${trackNameSuffix ?? "edited"})`;
7130
7343
  try {
7131
- const trackName = `${sourceName} (${trackNameSuffix ?? "edited"})`;
7132
7344
  uploadedTrackId = await createTextTrackOnMux(
7133
7345
  assetId,
7134
7346
  sourceLanguageCode,
@@ -7138,13 +7350,13 @@ async function editCaptionsInternal(assetId, trackId, options, collectedUsage) {
7138
7350
  { closedCaptions: sourceTrack.closed_captions, passthrough: trackPassthrough }
7139
7351
  );
7140
7352
  } catch (error) {
7141
- legacyWrapError(error, "Failed to add edited track to Mux asset");
7353
+ wrapError(error, "Failed to add edited track to Mux asset", { assetId, languageCode: sourceLanguageCode });
7142
7354
  }
7143
7355
  if (deleteOriginal && uploadedTrackId) {
7144
7356
  try {
7145
7357
  await deleteTrackOnMux(assetId, trackId, credentials);
7146
7358
  } catch (error) {
7147
- legacyWrapError(error, "Failed to delete original track");
7359
+ wrapError(error, "Failed to delete original track", { assetId, trackId });
7148
7360
  }
7149
7361
  }
7150
7362
  } else if (uploadToMux) {
@@ -7158,14 +7370,16 @@ async function editCaptionsInternal(assetId, trackId, options, collectedUsage) {
7158
7370
  presignedUrl,
7159
7371
  closedCaptions: sourceTrack.closed_captions,
7160
7372
  passthrough: trackPassthrough,
7161
- credentials
7373
+ credentials,
7374
+ classifiedErrors: true
7162
7375
  });
7163
7376
  } catch (error) {
7164
- legacyWrapError(error, "Failed to add edited track to Mux asset");
7377
+ wrapError(error, "Failed to fetch the asset before adding the edited track", { assetId });
7165
7378
  }
7166
7379
  if (outcome.kind !== "created") {
7167
7380
  const sourceWasDeleted = outcome.deleted.some((track) => track.id === trackId);
7168
7381
  let restoreNote = "";
7382
+ let restoreFacts = {};
7169
7383
  if (sourceWasDeleted) {
7170
7384
  try {
7171
7385
  const originalUrl = await uploadEditedVttToS3({ editedVtt: vttContent, variant: "original", ...s3Config });
@@ -7178,14 +7392,27 @@ async function editCaptionsInternal(assetId, trackId, options, collectedUsage) {
7178
7392
  { closedCaptions: sourceTrack.closed_captions, passthrough: sourceTrack.passthrough }
7179
7393
  );
7180
7394
  restoreNote = ` The source track was restored as ${restoredTrackId}.`;
7395
+ restoreFacts = { sourceRestored: true, restoredTrackId };
7181
7396
  } catch (restoreError) {
7182
- restoreNote = ` Restoring the source track also failed: ${restoreError instanceof Error ? restoreError.message : String(restoreError)}.`;
7397
+ restoreNote = " Restoring the source track also failed.";
7398
+ restoreFacts = { sourceRestored: false, ...restoreFailureFacts(restoreError) };
7183
7399
  }
7184
7400
  }
7401
+ const facts = {
7402
+ assetId,
7403
+ trackId,
7404
+ languageCode: sourceLanguageCode,
7405
+ trackName: outputTrack.name,
7406
+ ...outcome.deleted.length > 0 && { deletedTracks: trackSummaryFacts(outcome.deleted) },
7407
+ ...restoreFacts
7408
+ };
7185
7409
  if (outcome.kind === "blocked") {
7186
- throw new LegacyMuxAiError(`${outcome.reason}${restoreNote}`, { type: "validation_error" });
7410
+ throw trackReplacementBlockedError(outcome, { message: `${outcome.reason}${restoreNote}`, facts: { ...trackTargetFacts(outputTrack), ...facts } });
7187
7411
  }
7188
- throw new Error(`Failed to add edited track to Mux asset: ${outcome.reason}.${restoreNote}`);
7412
+ const failure = trackWriteFailure(outcome);
7413
+ Object.assign(failure, { facts: { ...facts, ...failure.facts } });
7414
+ failure.message = `Failed to add edited track to Mux asset: ${failure.message}.${restoreNote}`;
7415
+ throw failure;
7189
7416
  }
7190
7417
  uploadedTrackId = outcome.trackId;
7191
7418
  replacedTracks = outcome.deleted;
@@ -11049,15 +11276,7 @@ async function translateAudio(assetId, toLanguageCode, options = {}) {
11049
11276
  }
11050
11277
 
11051
11278
  // src/workflows/translate-captions.ts
11052
- import {
11053
- APICallError as APICallError5,
11054
- generateText as generateText9,
11055
- NoObjectGeneratedError as NoObjectGeneratedError3,
11056
- NoOutputGeneratedError as NoOutputGeneratedError3,
11057
- Output as Output9,
11058
- RetryError as RetryError2,
11059
- TypeValidationError
11060
- } from "ai";
11279
+ import { generateText as generateText9, Output as Output9 } from "ai";
11061
11280
  import { z as z13 } from "zod";
11062
11281
  var translationSchema = z13.object({
11063
11282
  translation: z13.string()
@@ -11194,24 +11413,6 @@ var DEFAULT_TRANSLATION_CHUNKING = {
11194
11413
  maxCuesPerChunk: 80,
11195
11414
  maxCueTextTokensPerChunk: 2e3
11196
11415
  };
11197
- function findProviderServiceError(error) {
11198
- if (!error) {
11199
- return void 0;
11200
- }
11201
- if (RetryError2.isInstance(error)) {
11202
- return findProviderServiceError(error.lastError);
11203
- }
11204
- if (APICallError5.isInstance(error)) {
11205
- return error;
11206
- }
11207
- if (error instanceof Error && "cause" in error) {
11208
- return findProviderServiceError(error.cause);
11209
- }
11210
- return void 0;
11211
- }
11212
- function isUnusableOutputError(error) {
11213
- return NoObjectGeneratedError3.isInstance(error) || NoOutputGeneratedError3.isInstance(error) || TypeValidationError.isInstance(error);
11214
- }
11215
11416
  function shouldSplitChunkTranslationError(error) {
11216
11417
  if (findProviderServiceError(error)) {
11217
11418
  return false;
@@ -11219,49 +11420,6 @@ function shouldSplitChunkTranslationError(error) {
11219
11420
  return isUnusableOutputError(error) || isIncompleteGenerationError(error) || // Missing or invalid output, including a wrong cue count.
11220
11421
  MuxAiError.is(error) && (error.code === MUX_AI_ERROR_CODES.MODEL_OUTPUT_MISSING || error.code === MUX_AI_ERROR_CODES.MODEL_OUTPUT_INVALID);
11221
11422
  }
11222
- function translationStepError(error, message, facts) {
11223
- if (MuxAiError.is(error)) {
11224
- Object.assign(error, { facts: { ...facts, ...error.facts } });
11225
- return error;
11226
- }
11227
- const context = { call: String(facts.call), provider: String(facts.provider), ...facts.model !== void 0 && { model: String(facts.model) } };
11228
- let classified = classifyModelCallError(error, context);
11229
- if (classified) {
11230
- Object.assign(classified, { facts: { ...facts, ...classified.facts } });
11231
- return classified;
11232
- }
11233
- if (isUnusableOutputError(error)) {
11234
- classified = new MuxAiError(message, {
11235
- code: MUX_AI_ERROR_CODES.MODEL_OUTPUT_INVALID,
11236
- type: MUX_AI_ERROR_TYPES.PROCESSING_ERROR,
11237
- source: MUX_AI_ERROR_SOURCES.UPSTREAM,
11238
- dependency: MUX_AI_ERROR_DEPENDENCIES.AI_PROVIDER,
11239
- facts,
11240
- // As before: the raw error was retried by the step runner. See the model-output follow-up.
11241
- transient: true,
11242
- cause: error
11243
- });
11244
- } else {
11245
- const providerError = findProviderServiceError(error);
11246
- classified = providerError ? (
11247
- // A provider without its own classifier: not classified, but kept retryable by the
11248
- // step runner when the AI SDK judges it retryable (no response, 408, 409, 429, 5xx),
11249
- // as the raw error was before.
11250
- new MuxAiError(message, {
11251
- type: MUX_AI_ERROR_TYPES.SERVER_ERROR,
11252
- source: MUX_AI_ERROR_SOURCES.INTERNAL,
11253
- facts,
11254
- transient: providerError.isRetryable,
11255
- cause: error
11256
- })
11257
- ) : internalError(message, facts, error);
11258
- }
11259
- const usage = getErrorTokenUsage(error);
11260
- if (usage) {
11261
- classified.usage = usage;
11262
- }
11263
- return classified;
11264
- }
11265
11423
  function resolveTranslationChunkingOptions(options) {
11266
11424
  const targetChunkDurationSeconds = Math.max(
11267
11425
  1,
@@ -11441,7 +11599,7 @@ ${sanitisedVttContent}`
11441
11599
  }
11442
11600
  ]
11443
11601
  }), void 0, context).catch((error) => {
11444
- throw translationStepError(error, "Caption translation model call failed", { ...context });
11602
+ throw modelStepError(error, "Caption translation model call failed", { ...context });
11445
11603
  });
11446
11604
  const output = getGeneratedOutputWithContentPolicyHandling(response, context);
11447
11605
  const translated = normalizeTranslatedVtt(output.translation);
@@ -11536,7 +11694,12 @@ ${JSON.stringify(cuePayload, null, 2)}`
11536
11694
  function splitTranslationChunkAtMidpoint(chunk) {
11537
11695
  const midpoint = Math.floor(chunk.cueCount / 2);
11538
11696
  if (midpoint <= 0 || midpoint >= chunk.cueCount) {
11539
- throw internalError("Cannot split a translation chunk with fewer than two cues", { chunkId: chunk.id, cueCount: chunk.cueCount });
11697
+ throw new MuxAiError("Cannot split a translation chunk with fewer than two cues", {
11698
+ code: MUX_AI_ERROR_CODES.TRANSLATION_CHUNK_UNSPLITTABLE,
11699
+ type: MUX_AI_ERROR_TYPES.SERVER_ERROR,
11700
+ source: MUX_AI_ERROR_SOURCES.INTERNAL,
11701
+ facts: { chunkId: chunk.id, cueCount: chunk.cueCount }
11702
+ });
11540
11703
  }
11541
11704
  return [
11542
11705
  createTranslationChunkRequest(
@@ -11613,7 +11776,7 @@ async function translateChunkWithFallback({
11613
11776
  };
11614
11777
  } catch (error) {
11615
11778
  if (!shouldSplitChunkTranslationError(error) || chunk.cueCount <= 1) {
11616
- throw translationStepError(error, "Failed to translate a caption chunk", chunkFacts);
11779
+ throw modelStepError(error, "Failed to translate a caption chunk", chunkFacts);
11617
11780
  }
11618
11781
  const [leftChunk, rightChunk] = splitTranslationChunkAtMidpoint(chunk);
11619
11782
  const failedAttemptUsage = getErrorTokenUsage(error);
@@ -11828,7 +11991,12 @@ async function translateCaptionsInternal(assetId, trackId, toLanguageCode, optio
11828
11991
  if (!fromLanguageCode) {
11829
11992
  throw new MuxAiError(
11830
11993
  `Track ${trackId} is missing language metadata. Cannot determine source language for translation.`,
11831
- { type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR, source: MUX_AI_ERROR_SOURCES.ASSET, facts: { assetId, trackId } }
11994
+ {
11995
+ code: MUX_AI_ERROR_CODES.CAPTION_TRACK_LANGUAGE_MISSING,
11996
+ type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR,
11997
+ source: MUX_AI_ERROR_SOURCES.ASSET,
11998
+ facts: { assetId, trackId }
11999
+ }
11832
12000
  );
11833
12001
  }
11834
12002
  const outputTrack = {
@@ -11956,7 +12124,7 @@ async function translateCaptionsInternal(assetId, trackId, toLanguageCode, optio
11956
12124
  if (outcome.kind === "blocked") {
11957
12125
  throw trackReplacementBlockedError(outcome, { message: `${outcome.reason}${deletedNote}`, facts: { ...trackTargetFacts(outputTrack), ...facts } });
11958
12126
  }
11959
- const failure = outcome.error ?? internalError(`Track write failed without a classified error: ${outcome.reason}`);
12127
+ const failure = trackWriteFailure(outcome);
11960
12128
  Object.assign(failure, { facts: { ...facts, ...failure.facts } });
11961
12129
  failure.message = `Failed to add translated track to Mux asset: ${failure.message}.${deletedNote}`;
11962
12130
  throw failure;