@mux/ai 0.64.0 → 0.65.0-canary.105

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.
@@ -400,7 +400,7 @@ declare const MUX_AI_ERROR_CODES: {
400
400
  readonly INVALID_SCOPE: "invalid_scope";
401
401
  /** 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. */
402
402
  readonly TRACK_REPLACEMENT_BLOCKED: "track_replacement_blocked";
403
- /** 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`, `audio_only`) 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). */
403
+ /** 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`, `audio_only`, `not_positive`) 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). */
404
404
  readonly INVALID_PARAMETER: "invalid_parameter";
405
405
  /** 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. */
406
406
  readonly PARAMETER_OUT_OF_RANGE: "parameter_out_of_range";
@@ -1,7 +1,7 @@
1
- export { P as ASK_QUESTIONS_DEFAULT_MAX_ANSWER_OPTION_LENGTH, Q as ASK_QUESTIONS_DEFAULT_MAX_FREE_FORM_ANSWER_LENGTH, U as ASK_QUESTIONS_MAX_QUESTIONS_PER_CALL, V as ASK_QUESTIONS_MAX_QUESTION_LENGTH, W as AskQuestionsOptions, X as AskQuestionsResult, Y as AskQuestionsType, Z as AudioTranslationOptions, _ as AudioTranslationResult, $ as AutoCensorProfanityOptions, a0 as BurnedInCaptionsAnalysis, a1 as BurnedInCaptionsOptions, a2 as BurnedInCaptionsPromptOverrides, a3 as BurnedInCaptionsPromptSections, a4 as BurnedInCaptionsResult, a5 as CaptionReplacement, a6 as CensorMode, a7 as Chapter, a8 as ChapterSystemPromptSections, a9 as ChaptersOptions, aa as ChaptersPromptOverrides, ab as ChaptersPromptSections, ac as ChaptersResult, ad as ChaptersType, ae as DEFAULT_TRANSCRIPT_WINDOWING, af as DubbedCaptionsOutcome, ag as EditCaptionsOptions, ah as EditCaptionsResult, ai as EmbeddingsOptions, aj as EmbeddingsResult, ak as EngagementInsightsOptions, al as EngagementInsightsResult, am as GENERATE_TEXT_CALLS_TO_ACTION, an as GENERATE_TEXT_CHANNELS, ao as GENERATE_TEXT_CHANNEL_CEILINGS, ap as GENERATE_TEXT_FORMATS, aq as GENERATE_TEXT_LENGTH_BOUNDS, ar as GENERATE_TEXT_MAX_ARTIFACTS, as as GENERATE_TEXT_MAX_AUDIENCE_CHARS, at as GENERATE_TEXT_MAX_BRAND_TERMS, au as GENERATE_TEXT_MAX_BRAND_TERMS_TOTAL_CHARS, av as GENERATE_TEXT_MAX_BRAND_TERM_CHARS, aw as GENERATE_TEXT_MAX_CONCURRENT_GENERATIONS, ax as GENERATE_TEXT_MAX_INSTRUCTIONS_CHARS, ay as GENERATE_TEXT_MAX_SHOT_FRAMES, az as GENERATE_TEXT_MAX_VARIANTS, aA as GENERATE_TEXT_VOICES, aB as GOOGLE_VISION_LIKELIHOOD_TO_SCORE, aC as GenerateTextArtifact, aD as GenerateTextCallToAction, aE as GenerateTextChannel, aF as GenerateTextFormat, aG as GenerateTextKeyedItem, aH as GenerateTextLengthLimit, aI as GenerateTextOptions, aJ as GenerateTextResult, aK as GenerateTextVariant, aL as GenerateTextVoice, aM as GeneratedTextArtifact, aN as GeneratedTextVariant, aO as HIVE_SEXUAL_CATEGORIES, aP as HIVE_VIOLENCE_CATEGORIES, aQ as HiveModerationOutput, aR as HiveModerationSource, aS as ModerationOptions, aT as ModerationProvider, aU as ModerationResult, aV as ModerationSurfaceStatus, aW as MomentInsight, aX as OverallInsight, aY as ProfanityDetectionPayload, aZ as Question, a_ as QuestionAnswer, a$ as QuestionAnswerType, b0 as RepairAttempt, b1 as RepairCall, b2 as RepairOptions, b3 as RepairPlan, b4 as RepairResult, b5 as RepairSpan, b6 as ReplacementRecord, b7 as SpeakerReplacement, b8 as StaticRenditionCleanupOutcome, b9 as SummarizationOptions, ba as SummarizationPromptOverrides, bb as SummarizationPromptSections, bc as SummaryAndTagsResult, bd as SummaryType, be as TextLengthLimit, bf as TextRepairModelOptions, bg as ThumbnailModerationScore, bh as ThumbnailModerationSkipReason, bi as ThumbnailModerationStatus, bj as TranscriptModerationScore, bk as TranscriptModerationSkipReason, bl as TranscriptModerationStatus, bm as TranslationChunkingOptions, bn as TranslationOptions, bo as TranslationPayload, bp as TranslationResult, bq as aggregateTokenUsage, br as applyOverrideLists, bs as applyReplacements, bt as applySpeakerReplacements, bu as applyTextRepair, bv as askQuestions, bw as buildReplacementRegex, bx as buildTranscriptWindows, by as burnedInCaptionsSchema, bz as censorVttContent, bA as chapterSchema, bB as chaptersSchema, bC as createReplacer, bD as createTextRepairGenerator, bE as editCaptions, bF as extractTranscriptSegmentsForHotspots, bG as findGenerateTextLengthViolation, bH as generateChapters, bI as generateEmbeddings, bJ as generateEngagementInsights, bK as generateText, bL as generateVideoEmbeddings, bM as getModerationScores, bN as getSummaryAndTags, bO as hasBurnedInCaptions, bP as mapShotsToHotspots, bQ as measureGenerateTextLength, bR as normalizeTranslatedVtt, bS as planTextRepair, bT as profanityDetectionSchema, bU as questionAnswerSchema, bV as repairJsonSchema, bW as repairText, bX as resolveGenerateTextLengthLimit, bY as resolveGenerateTextLengthLimits, bZ as resolveGenerateTextOptions, b_ as runTextRepairLoop, b$ as selectGenerateTextShotFrames, c0 as shouldSplitChunkTranslationError, c1 as summarySchema, c2 as transformCueText, c3 as translateAudio, c4 as translateCaptions, c5 as translationSchema, c6 as validateNeverTranslateTerms, c7 as verifyNeverTranslateTerms } from '../index-DxCv-w74.js';
1
+ export { P as ASK_QUESTIONS_DEFAULT_MAX_ANSWER_OPTION_LENGTH, Q as ASK_QUESTIONS_DEFAULT_MAX_FREE_FORM_ANSWER_LENGTH, U as ASK_QUESTIONS_MAX_QUESTIONS_PER_CALL, V as ASK_QUESTIONS_MAX_QUESTION_LENGTH, W as AskQuestionsOptions, X as AskQuestionsResult, Y as AskQuestionsType, Z as AudioTranslationOptions, _ as AudioTranslationResult, $ as AutoCensorProfanityOptions, a0 as BurnedInCaptionsAnalysis, a1 as BurnedInCaptionsOptions, a2 as BurnedInCaptionsPromptOverrides, a3 as BurnedInCaptionsPromptSections, a4 as BurnedInCaptionsResult, a5 as CaptionReplacement, a6 as CensorMode, a7 as Chapter, a8 as ChapterSystemPromptSections, a9 as ChaptersOptions, aa as ChaptersPromptOverrides, ab as ChaptersPromptSections, ac as ChaptersResult, ad as ChaptersType, ae as DEFAULT_TRANSCRIPT_WINDOWING, af as DubbedCaptionsOutcome, ag as EditCaptionsOptions, ah as EditCaptionsResult, ai as EmbeddingsOptions, aj as EmbeddingsResult, ak as EngagementInsightsOptions, al as EngagementInsightsResult, am as GENERATE_TEXT_CALLS_TO_ACTION, an as GENERATE_TEXT_CHANNELS, ao as GENERATE_TEXT_CHANNEL_CEILINGS, ap as GENERATE_TEXT_FORMATS, aq as GENERATE_TEXT_LENGTH_BOUNDS, ar as GENERATE_TEXT_MAX_ARTIFACTS, as as GENERATE_TEXT_MAX_AUDIENCE_CHARS, at as GENERATE_TEXT_MAX_BRAND_TERMS, au as GENERATE_TEXT_MAX_BRAND_TERMS_TOTAL_CHARS, av as GENERATE_TEXT_MAX_BRAND_TERM_CHARS, aw as GENERATE_TEXT_MAX_CONCURRENT_GENERATIONS, ax as GENERATE_TEXT_MAX_INSTRUCTIONS_CHARS, ay as GENERATE_TEXT_MAX_SHOT_FRAMES, az as GENERATE_TEXT_MAX_VARIANTS, aA as GENERATE_TEXT_VOICES, aB as GOOGLE_VISION_LIKELIHOOD_TO_SCORE, aC as GenerateTextArtifact, aD as GenerateTextCallToAction, aE as GenerateTextChannel, aF as GenerateTextFormat, aG as GenerateTextKeyedItem, aH as GenerateTextLengthLimit, aI as GenerateTextOptions, aJ as GenerateTextResult, aK as GenerateTextVariant, aL as GenerateTextVoice, aM as GeneratedTextArtifact, aN as GeneratedTextVariant, aO as HIVE_SEXUAL_CATEGORIES, aP as HIVE_VIOLENCE_CATEGORIES, aQ as HiveModerationOutput, aR as HiveModerationSource, aS as ModerationOptions, aT as ModerationProvider, aU as ModerationResult, aV as ModerationSurfaceStatus, aW as MomentInsight, aX as OverallInsight, aY as ProfanityDetectionPayload, aZ as Question, a_ as QuestionAnswer, a$ as QuestionAnswerType, b0 as RepairAttempt, b1 as RepairCall, b2 as RepairOptions, b3 as RepairPlan, b4 as RepairResult, b5 as RepairSpan, b6 as ReplacementRecord, b7 as SpeakerReplacement, b8 as StaticRenditionCleanupOutcome, b9 as SummarizationOptions, ba as SummarizationPromptOverrides, bb as SummarizationPromptSections, bc as SummaryAndTagsResult, bd as SummaryType, be as TextLengthLimit, bf as TextRepairModelOptions, bg as ThumbnailModerationScore, bh as ThumbnailModerationSkipReason, bi as ThumbnailModerationStatus, bj as TranscriptModerationScore, bk as TranscriptModerationSkipReason, bl as TranscriptModerationStatus, bm as TranslationChunkingOptions, bn as TranslationOptions, bo as TranslationPayload, bp as TranslationResult, bq as aggregateTokenUsage, br as applyOverrideLists, bs as applyReplacements, bt as applySpeakerReplacements, bu as applyTextRepair, bv as askQuestions, bw as buildReplacementRegex, bx as buildTranscriptWindows, by as burnedInCaptionsSchema, bz as censorVttContent, bA as chapterSchema, bB as chaptersSchema, bC as createReplacer, bD as createTextRepairGenerator, bE as editCaptions, bF as extractTranscriptSegmentsForHotspots, bG as findGenerateTextLengthViolation, bH as generateChapters, bI as generateEmbeddings, bJ as generateEngagementInsights, bK as generateText, bL as generateVideoEmbeddings, bM as getModerationScores, bN as getSummaryAndTags, bO as hasBurnedInCaptions, bP as mapShotsToHotspots, bQ as measureGenerateTextLength, bR as normalizeTranslatedVtt, bS as planTextRepair, bT as profanityDetectionSchema, bU as questionAnswerSchema, bV as repairJsonSchema, bW as repairText, bX as resolveGenerateTextLengthLimit, bY as resolveGenerateTextLengthLimits, bZ as resolveGenerateTextOptions, b_ as runTextRepairLoop, b$ as selectGenerateTextShotFrames, c0 as shouldSplitChunkTranslationError, c1 as summarySchema, c2 as transformCueText, c3 as translateAudio, c4 as translateCaptions, c5 as translationSchema, c6 as validateNeverTranslateTerms, c7 as verifyNeverTranslateTerms } from '../index-BUM1MVpR.js';
2
2
  export { D as DEFAULT_DESCRIPTION_LENGTH, a as DEFAULT_SUMMARY_KEYWORD_LIMIT, b as DEFAULT_TITLE_LENGTH } from '../summarization-BFmhXeAu.js';
3
3
  import 'ai';
4
- import '../transcripts-CGRjxn_g.js';
4
+ import '../transcripts-qZm-RokR.js';
5
5
  import '@workflow/serde';
6
6
  import '@mux/ts';
7
7
  import 'zod';
@@ -577,7 +577,7 @@ var MUX_AI_ERROR_CODES = {
577
577
  INVALID_SCOPE: "invalid_scope",
578
578
  /** Existing tracks block writing the output track under the chosen replacement policy. Facts: `reason` (`policy_fail`, `not_generated`, `name_collision`, `primary_audio`), `conflictingTracks` and the target track, plus `sourceRestored` and `restoredTrackId` when a source track was deleted first. */
579
579
  TRACK_REPLACEMENT_BLOCKED: "track_replacement_blocked",
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`, `audio_only`) 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
+ /** 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`, `audio_only`, `not_positive`) 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",
@@ -2976,6 +2976,43 @@ function createLanguageSection(languageName) {
2976
2976
  };
2977
2977
  }
2978
2978
 
2979
+ // src/lib/url-signing.ts
2980
+ async function createSigningClient(context) {
2981
+ const { default: MuxClient } = await import("@mux/ts");
2982
+ return new MuxClient({
2983
+ jwtSigningKey: context.keyId,
2984
+ jwtPrivateKey: context.keySecret
2985
+ });
2986
+ }
2987
+ async function signPlaybackId(playbackId, context, type = "video", params) {
2988
+ "use step";
2989
+ const client = await createSigningClient(context);
2990
+ const stringParams = params ? Object.fromEntries(
2991
+ Object.entries(params).map(([key, value]) => [key, String(value)])
2992
+ ) : void 0;
2993
+ return client.jwt.signPlaybackId(playbackId, {
2994
+ type,
2995
+ expiration: context.expiration || "1h",
2996
+ params: stringParams
2997
+ });
2998
+ }
2999
+ async function signUrl(url, playbackId, type = "video", params, credentials) {
3000
+ "use step";
3001
+ const resolvedContext = await resolveMuxSigningContext(credentials);
3002
+ if (!resolvedContext) {
3003
+ throw signingCredentialsMissingError();
3004
+ }
3005
+ const token = await signPlaybackId(playbackId, resolvedContext, type, params);
3006
+ const separator = url.includes("?") ? "&" : "?";
3007
+ return `${url}${separator}token=${token}`;
3008
+ }
3009
+ function signingCredentialsMissingError() {
3010
+ return new MuxAiError(
3011
+ "Signed playback ID requires signing credentials. Provide muxSigningKey and muxPrivateKey via workflow credentials or set MUX_SIGNING_KEY and MUX_PRIVATE_KEY environment variables.",
3012
+ { code: MUX_AI_ERROR_CODES.SIGNING_CREDENTIALS_MISSING, type: MUX_AI_ERROR_TYPES.SERVER_ERROR, source: MUX_AI_ERROR_SOURCES.INTERNAL }
3013
+ );
3014
+ }
3015
+
2979
3016
  // src/lib/workflow-scope.ts
2980
3017
  function hasWorkflowScopeBoundaries(scope) {
2981
3018
  return scope?.startTime !== void 0 || scope?.endTime !== void 0;
@@ -3143,43 +3180,6 @@ async function getMuxThumbnailBaseUrl(playbackId, credentials) {
3143
3180
  return getMuxImageBaseUrl(playbackId, "thumbnail", credentials);
3144
3181
  }
3145
3182
 
3146
- // src/lib/url-signing.ts
3147
- async function createSigningClient(context) {
3148
- const { default: MuxClient } = await import("@mux/ts");
3149
- return new MuxClient({
3150
- jwtSigningKey: context.keyId,
3151
- jwtPrivateKey: context.keySecret
3152
- });
3153
- }
3154
- async function signPlaybackId(playbackId, context, type = "video", params) {
3155
- "use step";
3156
- const client = await createSigningClient(context);
3157
- const stringParams = params ? Object.fromEntries(
3158
- Object.entries(params).map(([key, value]) => [key, String(value)])
3159
- ) : void 0;
3160
- return client.jwt.signPlaybackId(playbackId, {
3161
- type,
3162
- expiration: context.expiration || "1h",
3163
- params: stringParams
3164
- });
3165
- }
3166
- async function signUrl(url, playbackId, type = "video", params, credentials) {
3167
- "use step";
3168
- const resolvedContext = await resolveMuxSigningContext(credentials);
3169
- if (!resolvedContext) {
3170
- throw signingCredentialsMissingError();
3171
- }
3172
- const token = await signPlaybackId(playbackId, resolvedContext, type, params);
3173
- const separator = url.includes("?") ? "&" : "?";
3174
- return `${url}${separator}token=${token}`;
3175
- }
3176
- function signingCredentialsMissingError() {
3177
- return new MuxAiError(
3178
- "Signed playback ID requires signing credentials. Provide muxSigningKey and muxPrivateKey via workflow credentials or set MUX_SIGNING_KEY and MUX_PRIVATE_KEY environment variables.",
3179
- { code: MUX_AI_ERROR_CODES.SIGNING_CREDENTIALS_MISSING, type: MUX_AI_ERROR_TYPES.SERVER_ERROR, source: MUX_AI_ERROR_SOURCES.INTERNAL }
3180
- );
3181
- }
3182
-
3183
3183
  // src/primitives/storyboards.ts
3184
3184
  var DEFAULT_STORYBOARD_WIDTH = 640;
3185
3185
  async function getStoryboardUrl(playbackId, width = DEFAULT_STORYBOARD_WIDTH, shouldSign = false, credentials, scope) {
@@ -4180,13 +4180,25 @@ function allowedAnswersForQuestion(q) {
4180
4180
  return [];
4181
4181
  }
4182
4182
  }
4183
+ function numberFact(value) {
4184
+ return Number.isFinite(value) ? value : String(value);
4185
+ }
4186
+ function invalidOptionError(message, facts, inputs) {
4187
+ return new MuxAiError(message, {
4188
+ code: MUX_AI_ERROR_CODES.INVALID_PARAMETER,
4189
+ type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR,
4190
+ source: MUX_AI_ERROR_SOURCES.REQUEST,
4191
+ facts: { ...facts, inputs }
4192
+ });
4193
+ }
4183
4194
  function normalizeQuestion(q, idx) {
4184
4195
  const hasOptions = Array.isArray(q.answerOptions);
4185
4196
  const isFreeForm = q.freeFormReply === true;
4186
4197
  if (hasOptions && isFreeForm) {
4187
- throw new LegacyMuxAiError(
4198
+ throw invalidOptionError(
4188
4199
  `Question at index ${idx} sets both answerOptions and freeFormReply: true. These are mutually exclusive \u2014 pick one.`,
4189
- { type: "validation_error" }
4200
+ { parameter: `questions[${idx}].answerOptions`, reason: "conflicts_with", with: `questions[${idx}].freeFormReply` },
4201
+ ["questions"]
4190
4202
  );
4191
4203
  }
4192
4204
  if (isFreeForm) {
@@ -4199,9 +4211,10 @@ function normalizeQuestion(q, idx) {
4199
4211
  )
4200
4212
  );
4201
4213
  if (!options.length) {
4202
- throw new LegacyMuxAiError(
4214
+ throw invalidOptionError(
4203
4215
  `Question at index ${idx} has invalid answerOptions: must include at least one non-empty value.`,
4204
- { type: "validation_error" }
4216
+ { parameter: `questions[${idx}].answerOptions`, reason: "empty" },
4217
+ ["questions"]
4205
4218
  );
4206
4219
  }
4207
4220
  return {
@@ -4272,7 +4285,7 @@ ${questionBlocks}
4272
4285
  }
4273
4286
  async function fetchImageAsBase64(imageUrl, imageDownloadOptions) {
4274
4287
  "use step";
4275
- const downloadResult = await downloadImageAsBase64(imageUrl, imageDownloadOptions);
4288
+ const downloadResult = await downloadImageAsBase64(imageUrl, imageDownloadOptions, { classifiedErrors: true, call: "fetch_storyboard" });
4276
4289
  return downloadResult.base64Data;
4277
4290
  }
4278
4291
  function buildResponseSchemaForQuestions(normalizedQuestions, maxFreeFormAnswerLength) {
@@ -4310,6 +4323,7 @@ async function analyzeQuestions({
4310
4323
  normalizedQuestions,
4311
4324
  maxFreeFormAnswerLength
4312
4325
  );
4326
+ const context = { call: "answer_questions", provider, model: modelId };
4313
4327
  const response = await withContentPolicyAwareRetry(() => generateText2({
4314
4328
  model,
4315
4329
  maxRetries: 0,
@@ -4325,11 +4339,10 @@ async function analyzeQuestions({
4325
4339
  ] : userPrompt
4326
4340
  }
4327
4341
  ]
4328
- }));
4329
- const output = getGeneratedOutputWithContentPolicyHandling(response);
4330
- if (!output) {
4331
- throw new Error("Ask-questions output missing");
4332
- }
4342
+ }), void 0, context).catch((error) => {
4343
+ throw modelStepError(error, "Ask-questions model call failed", { ...context });
4344
+ });
4345
+ const output = getGeneratedOutputWithContentPolicyHandling(response, context);
4333
4346
  const parsed = responseSchema.parse(output);
4334
4347
  const unexpectedRootKeys = detectUnexpectedKeysFromRawText(
4335
4348
  response.text,
@@ -4370,33 +4383,37 @@ async function askQuestions(assetId, questions, options) {
4370
4383
  }
4371
4384
  async function askQuestionsInternal(assetId, questions, options, collectedUsage) {
4372
4385
  if (!questions || questions.length === 0) {
4373
- throw new LegacyMuxAiError("At least one question must be provided.", { type: "validation_error" });
4386
+ throw invalidOptionError("At least one question must be provided.", { parameter: "questions", reason: "empty" }, ["questions"]);
4374
4387
  }
4375
4388
  if (questions.length > ASK_QUESTIONS_MAX_QUESTIONS_PER_CALL) {
4376
- throw new LegacyMuxAiError(
4389
+ throw invalidOptionError(
4377
4390
  `Too many questions: received ${questions.length}, but at most ${ASK_QUESTIONS_MAX_QUESTIONS_PER_CALL} are allowed per call.`,
4378
- { type: "validation_error" }
4391
+ { parameter: "questions", reason: "too_many", count: questions.length, max: ASK_QUESTIONS_MAX_QUESTIONS_PER_CALL },
4392
+ ["questions"]
4379
4393
  );
4380
4394
  }
4381
4395
  questions.forEach((q, idx) => {
4382
4396
  if (!q.question || typeof q.question !== "string" || !q.question.trim()) {
4383
- throw new LegacyMuxAiError(
4397
+ throw invalidOptionError(
4384
4398
  `Question at index ${idx} is invalid: must have a non-empty question field.`,
4385
- { type: "validation_error" }
4399
+ { parameter: `questions[${idx}].question`, reason: "empty" },
4400
+ ["questions"]
4386
4401
  );
4387
4402
  }
4388
4403
  if (q.question.length > ASK_QUESTIONS_MAX_QUESTION_LENGTH) {
4389
- throw new LegacyMuxAiError(
4404
+ throw invalidOptionError(
4390
4405
  `Question at index ${idx} exceeds the ${ASK_QUESTIONS_MAX_QUESTION_LENGTH}-character limit (received ${q.question.length}).`,
4391
- { type: "validation_error" }
4406
+ { parameter: `questions[${idx}].question`, reason: "too_long", length: q.question.length, maxLength: ASK_QUESTIONS_MAX_QUESTION_LENGTH },
4407
+ ["questions"]
4392
4408
  );
4393
4409
  }
4394
4410
  });
4395
4411
  const maxAnswerOptionLength = options?.maxAnswerOptionLength ?? ASK_QUESTIONS_DEFAULT_MAX_ANSWER_OPTION_LENGTH;
4396
4412
  if (!Number.isFinite(maxAnswerOptionLength) || maxAnswerOptionLength <= 0) {
4397
- throw new LegacyMuxAiError(
4413
+ throw invalidOptionError(
4398
4414
  `maxAnswerOptionLength must be a positive number (received ${maxAnswerOptionLength}).`,
4399
- { type: "validation_error" }
4415
+ { parameter: "maxAnswerOptionLength", reason: "not_positive", value: numberFact(maxAnswerOptionLength) },
4416
+ ["maxAnswerOptionLength"]
4400
4417
  );
4401
4418
  }
4402
4419
  questions.forEach((q, idx) => {
@@ -4404,18 +4421,20 @@ async function askQuestionsInternal(assetId, questions, options, collectedUsage)
4404
4421
  return;
4405
4422
  for (const opt of q.answerOptions ?? []) {
4406
4423
  if (typeof opt === "string" && opt.length > maxAnswerOptionLength) {
4407
- throw new LegacyMuxAiError(
4424
+ throw invalidOptionError(
4408
4425
  `Question at index ${idx} has an answerOption exceeding the ${maxAnswerOptionLength}-character limit (received ${opt.length}). Answer options should be short labels, not sentences.`,
4409
- { type: "validation_error" }
4426
+ { parameter: `questions[${idx}].answerOptions`, reason: "too_long", length: opt.length, maxLength: maxAnswerOptionLength },
4427
+ ["questions", "maxAnswerOptionLength"]
4410
4428
  );
4411
4429
  }
4412
4430
  }
4413
4431
  });
4414
4432
  const maxFreeFormAnswerLength = options?.maxFreeFormAnswerLength ?? ASK_QUESTIONS_DEFAULT_MAX_FREE_FORM_ANSWER_LENGTH;
4415
4433
  if (!Number.isFinite(maxFreeFormAnswerLength) || maxFreeFormAnswerLength <= 0) {
4416
- throw new LegacyMuxAiError(
4434
+ throw invalidOptionError(
4417
4435
  `maxFreeFormAnswerLength must be a positive number (received ${maxFreeFormAnswerLength}).`,
4418
- { type: "validation_error" }
4436
+ { parameter: "maxFreeFormAnswerLength", reason: "not_positive", value: numberFact(maxFreeFormAnswerLength) },
4437
+ ["maxFreeFormAnswerLength"]
4419
4438
  );
4420
4439
  }
4421
4440
  const {
@@ -4437,30 +4456,29 @@ async function askQuestionsInternal(assetId, questions, options, collectedUsage)
4437
4456
  model,
4438
4457
  provider
4439
4458
  });
4440
- const { asset: assetData, playbackId, policy } = await getPlaybackIdForAsset(assetId, credentials, options?.assetSnapshot);
4459
+ const { asset: assetData, playbackId, policy } = await getPlaybackIdForAsset(assetId, credentials, options?.assetSnapshot, { classifiedErrors: true });
4441
4460
  const assetDurationSeconds = getAssetDurationSecondsFromAsset(assetData);
4442
4461
  const isAudioOnly = isAudioOnlyAsset(assetData);
4443
4462
  const effectiveScope = hasWorkflowScopeBoundaries(scope) ? scope : void 0;
4444
4463
  const storyboardScope = isAudioOnly ? void 0 : resolveRenderableVideoScope(
4445
4464
  effectiveScope,
4446
4465
  assetDurationSeconds,
4447
- getVideoTrackDurationSecondsFromAsset(assetData)
4466
+ getVideoTrackDurationSecondsFromAsset(assetData),
4467
+ { classifiedErrors: true, assetId }
4448
4468
  );
4449
4469
  if (isAudioOnly && effectiveScope) {
4450
- resolveWorkflowScope(effectiveScope, assetDurationSeconds);
4470
+ resolveWorkflowScope(effectiveScope, assetDurationSeconds, { classifiedErrors: true, assetId });
4451
4471
  }
4452
4472
  if (isAudioOnly && !includeTranscript) {
4453
- throw new LegacyMuxAiError(
4473
+ throw invalidOptionError(
4454
4474
  "Audio-only assets require a transcript. Set includeTranscript: true and ensure the asset has a ready text track (captions/subtitles).",
4455
- { type: "validation_error" }
4475
+ { parameter: "includeTranscript", reason: "audio_only", allowed: [true], value: false, assetId },
4476
+ ["includeTranscript"]
4456
4477
  );
4457
4478
  }
4458
4479
  const signingContext = await resolveMuxSigningContext(credentials);
4459
4480
  if (policy === "signed" && !signingContext) {
4460
- throw new LegacyMuxAiError(
4461
- "Signed playback ID requires signing credentials. Set MUX_SIGNING_KEY and MUX_PRIVATE_KEY environment variables.",
4462
- { type: "validation_error" }
4463
- );
4481
+ throw signingCredentialsMissingError();
4464
4482
  }
4465
4483
  const transcriptResult = includeTranscript ? await fetchTranscriptForAsset(assetData, playbackId, {
4466
4484
  languageCode,
@@ -4468,7 +4486,8 @@ async function askQuestionsInternal(assetId, questions, options, collectedUsage)
4468
4486
  shouldSign: policy === "signed",
4469
4487
  credentials,
4470
4488
  required: isAudioOnly,
4471
- scope: effectiveScope
4489
+ scope: effectiveScope,
4490
+ classifiedErrors: true
4472
4491
  }) : void 0;
4473
4492
  const transcriptText = transcriptResult?.transcriptText ?? "";
4474
4493
  const userPrompt = buildUserPrompt({
@@ -4479,65 +4498,38 @@ async function askQuestionsInternal(assetId, questions, options, collectedUsage)
4479
4498
  maxFreeFormAnswerLength
4480
4499
  });
4481
4500
  const systemPrompt = buildSystemPrompt(isAudioOnly, hasFreeForm, maxFreeFormAnswerLength);
4482
- let analysisResponse;
4483
4501
  let imageUrl;
4484
- try {
4485
- if (isAudioOnly) {
4486
- analysisResponse = await analyzeQuestions({
4487
- provider: modelConfig.provider,
4488
- modelId: modelConfig.modelId,
4489
- userPrompt,
4490
- systemPrompt,
4491
- normalizedQuestions,
4492
- maxFreeFormAnswerLength,
4493
- credentials
4494
- });
4495
- } else {
4496
- const storyboardUrl = await getStoryboardUrl(
4497
- playbackId,
4498
- storyboardWidth,
4499
- policy === "signed",
4500
- credentials,
4501
- storyboardScope
4502
- );
4503
- imageUrl = storyboardUrl;
4504
- if (imageSubmissionMode === "base64") {
4505
- const base64Data = await fetchImageAsBase64(storyboardUrl, imageDownloadOptions);
4506
- analysisResponse = await analyzeQuestions({
4507
- provider: modelConfig.provider,
4508
- modelId: modelConfig.modelId,
4509
- userPrompt,
4510
- systemPrompt,
4511
- normalizedQuestions,
4512
- maxFreeFormAnswerLength,
4513
- imageDataUrl: base64Data,
4514
- credentials
4515
- });
4516
- } else {
4517
- analysisResponse = await analyzeQuestions({
4518
- provider: modelConfig.provider,
4519
- modelId: modelConfig.modelId,
4520
- userPrompt,
4521
- systemPrompt,
4522
- normalizedQuestions,
4523
- maxFreeFormAnswerLength,
4524
- imageDataUrl: storyboardUrl,
4525
- credentials
4526
- });
4527
- }
4528
- }
4529
- } catch (error) {
4530
- const contentType = isAudioOnly ? "audio" : "video";
4531
- legacyWrapError(error, `Failed to analyze ${contentType} questions with ${provider}`);
4502
+ let imageDataUrl;
4503
+ if (!isAudioOnly) {
4504
+ imageUrl = await getStoryboardUrl(
4505
+ playbackId,
4506
+ storyboardWidth,
4507
+ policy === "signed",
4508
+ credentials,
4509
+ storyboardScope
4510
+ );
4511
+ imageDataUrl = imageSubmissionMode === "base64" ? await fetchImageAsBase64(imageUrl, imageDownloadOptions) : imageUrl;
4532
4512
  }
4513
+ const modelFacts = { call: "answer_questions", provider: modelConfig.provider, model: modelConfig.modelId, assetId };
4514
+ const analysisResponse = await analyzeQuestions({
4515
+ provider: modelConfig.provider,
4516
+ modelId: modelConfig.modelId,
4517
+ userPrompt,
4518
+ systemPrompt,
4519
+ normalizedQuestions,
4520
+ maxFreeFormAnswerLength,
4521
+ imageDataUrl,
4522
+ credentials
4523
+ }).catch((error) => wrapError(error, `Failed to analyze ${isAudioOnly ? "audio" : "video"} questions with ${modelConfig.provider}`, modelFacts));
4533
4524
  collectedUsage.push(analysisResponse.usage);
4534
- if (!analysisResponse.result?.answers) {
4535
- throw new LegacyMuxAiError(`Failed to generate answers for asset ${assetId}.`);
4536
- }
4537
4525
  if (analysisResponse.result.answers.length !== questions.length) {
4538
- throw new LegacyMuxAiError(
4539
- `Failed to generate answers for all questions for asset ${assetId}.`
4540
- );
4526
+ throw new MuxAiError(`Failed to generate answers for all questions for asset ${assetId}.`, {
4527
+ code: MUX_AI_ERROR_CODES.MODEL_OUTPUT_INVALID,
4528
+ type: MUX_AI_ERROR_TYPES.PROCESSING_ERROR,
4529
+ source: MUX_AI_ERROR_SOURCES.UPSTREAM,
4530
+ dependency: MUX_AI_ERROR_DEPENDENCIES.AI_PROVIDER,
4531
+ facts: { ...modelFacts, questionCount: questions.length, returnedAnswerCount: analysisResponse.result.answers.length }
4532
+ });
4541
4533
  }
4542
4534
  const safety = createSafetyReporter();
4543
4535
  for (const key of analysisResponse.unexpectedRootKeys) {
@@ -4570,9 +4562,13 @@ async function askQuestionsInternal(assetId, questions, options, collectedUsage)
4570
4562
  if (!isSkipped && !isFreeForm) {
4571
4563
  const allowed = allowedAnswersForQuestion(question);
4572
4564
  if (!allowed.includes(raw.answer)) {
4573
- throw new LegacyMuxAiError(
4574
- `Answer "${raw.answer}" for question ${idx} is not in allowed options: ${allowed.join(", ")}`
4575
- );
4565
+ throw new MuxAiError(`Answer "${raw.answer}" for question ${idx} is not in allowed options: ${allowed.join(", ")}`, {
4566
+ code: MUX_AI_ERROR_CODES.MODEL_OUTPUT_INVALID,
4567
+ type: MUX_AI_ERROR_TYPES.PROCESSING_ERROR,
4568
+ source: MUX_AI_ERROR_SOURCES.UPSTREAM,
4569
+ dependency: MUX_AI_ERROR_DEPENDENCIES.AI_PROVIDER,
4570
+ facts: { ...modelFacts, questionIndex: idx }
4571
+ });
4576
4572
  }
4577
4573
  }
4578
4574
  let finalAnswer;
@@ -6191,7 +6187,7 @@ function restoreFailureFacts(error) {
6191
6187
  restoreFailure: error.facts
6192
6188
  };
6193
6189
  }
6194
- function invalidOptionError(message, facts, inputs) {
6190
+ function invalidOptionError2(message, facts, inputs) {
6195
6191
  return new MuxAiError(message, {
6196
6192
  code: MUX_AI_ERROR_CODES.INVALID_PARAMETER,
6197
6193
  type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR,
@@ -6250,14 +6246,14 @@ async function editCaptionsInternal(assetId, trackId, options, collectedUsage) {
6250
6246
  const hasSpeakerReplacements = !!speakerReplacementsOption && speakerReplacementsOption.length > 0;
6251
6247
  if (!hasAutoCensor && !hasReplacements && !hasSpeakerReplacements) {
6252
6248
  const parameters = ["autoCensorProfanity", "replacements", "speakerReplacements"];
6253
- throw invalidOptionError(
6249
+ throw invalidOptionError2(
6254
6250
  "At least one of autoCensorProfanity, replacements, or speakerReplacements must be provided.",
6255
6251
  { reason: "one_of_required", parameters },
6256
6252
  parameters
6257
6253
  );
6258
6254
  }
6259
6255
  if (autoCensorOption && !provider) {
6260
- throw invalidOptionError(
6256
+ throw invalidOptionError2(
6261
6257
  "provider is required when using autoCensorProfanity.",
6262
6258
  { parameter: "provider", reason: "required_with", with: "autoCensorProfanity" },
6263
6259
  ["provider", "autoCensorProfanity"]
@@ -6270,14 +6266,14 @@ async function editCaptionsInternal(assetId, trackId, options, collectedUsage) {
6270
6266
  ...replaceExistingTracksOption !== void 0 ? ["replaceExistingTracks"] : [],
6271
6267
  ...providedTrackName !== void 0 ? ["trackName"] : []
6272
6268
  ];
6273
- throw invalidOptionError(
6269
+ throw invalidOptionError2(
6274
6270
  "deleteOriginalTrack and trackNameSuffix are deprecated and cannot be combined with replaceExistingTracks or trackName.",
6275
6271
  { parameter: legacy, reason: "conflicts_with", with: conflicting },
6276
6272
  [legacy, ...conflicting]
6277
6273
  );
6278
6274
  }
6279
6275
  if (replaceExistingTracksOption !== void 0 && replaceExistingTracksOption !== "replace" && replaceExistingTracksOption !== "fail") {
6280
- throw invalidOptionError(
6276
+ throw invalidOptionError2(
6281
6277
  `replaceExistingTracks must be "replace" or "fail" for editCaptions (received "${String(replaceExistingTracksOption)}").`,
6282
6278
  {
6283
6279
  parameter: "replaceExistingTracks",
@@ -6290,7 +6286,7 @@ async function editCaptionsInternal(assetId, trackId, options, collectedUsage) {
6290
6286
  }
6291
6287
  const replaceExistingTracks = replaceExistingTracksOption ?? "replace";
6292
6288
  if (!legacyTrackNaming && replaceExistingTracks === "fail" && !providedTrackName) {
6293
- throw invalidOptionError(
6289
+ throw invalidOptionError2(
6294
6290
  `trackName is required when replaceExistingTracks is "fail": the edited track cannot reuse the source track's name while the source is kept.`,
6295
6291
  { parameter: "trackName", reason: "required_with", with: "replaceExistingTracks", withValue: "fail" },
6296
6292
  ["trackName", "replaceExistingTracks"]
@@ -6303,7 +6299,7 @@ async function editCaptionsInternal(assetId, trackId, options, collectedUsage) {
6303
6299
  for (const [index, replacement] of (speakerReplacementsOption ?? []).entries()) {
6304
6300
  const reason = speakerLabelProblem(replacement.find) ?? speakerLabelProblem(replacement.replace);
6305
6301
  if (reason) {
6306
- throw invalidOptionError(
6302
+ throw invalidOptionError2(
6307
6303
  "Speaker replacement labels must be non-empty and must not contain square brackets or newlines.",
6308
6304
  { parameter: "speakerReplacements", reason, index, ...reason === "disallowed_characters" && { characters: ["[", "]"] } },
6309
6305
  ["speakerReplacements"]