@mux/ai 0.63.1 → 0.64.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import { O as WorkflowCredentialsInput, R as WorkflowScope, T as TextChunk, j as ChunkingStrategy, a5 as VTTCue, a6 as CompletedShotsResult, a7 as DeletedShotsResult, a8 as ErroredShotsResult, a9 as Hotspot, aa as HotspotOptions, ab as HotspotResponse, ac as LOW_CONFIDENCE_THRESHOLD, ad as MAX_CUE_TEXT_CHARS, ae as ParseVTTCuesOptions, af as PendingShotsResult, ag as Shot, ah as ShotRequestOptions, ai as ShotsResult, aj as SkippedShotsResult, ak as TranscriptEmptyReason, al as TranscriptFetchOptions, am as TranscriptFetchStepResult, an as TranscriptResult, ao as WaitForShotsOptions, ap as buildTranscriptUrl, aq as buildVttFromCueBlocks, ar as buildVttFromTranslatedCueBlocks, as as concatenateVttSegments, at as extractTextFromVTT, au as extractTimestampedTranscript, av as fetchTranscriptDataForUrl, aw as fetchTranscriptForAsset, ax as filterVttByScope, ay as findCaptionTrack, az as getHotspotsForAsset, aA as getHotspotsForPlaybackId, aB as getHotspotsForVideo, aC as getReadyTextTracks, aD as getReliableLanguageCode, aE as getShotsForAsset, aF as parseVTTCues, aG as replaceCueText, aH as requestShotsForAsset, aI as sanitizeUntrustedText, aJ as secondsToTimestamp, aK as splitVttPreambleAndCueBlocks, aL as stripVttMetadataBlocks, aM as vttTimestampToSeconds, aN as waitForShotsForAsset } from './transcripts-CFZM111v.js';
1
+ import { O as WorkflowCredentialsInput, R as WorkflowScope, T as TextChunk, j as ChunkingStrategy, a5 as VTTCue, a6 as CompletedShotsResult, a7 as DeletedShotsResult, a8 as ErroredShotsResult, a9 as Hotspot, aa as HotspotOptions, ab as HotspotResponse, ac as LOW_CONFIDENCE_THRESHOLD, ad as MAX_CUE_TEXT_CHARS, ae as ParseVTTCuesOptions, af as PendingShotsResult, ag as Shot, ah as ShotRequestOptions, ai as ShotsResult, aj as SkippedShotsResult, ak as TranscriptEmptyReason, al as TranscriptFetchOptions, am as TranscriptFetchStepResult, an as TranscriptResult, ao as WaitForShotsOptions, ap as buildTranscriptUrl, aq as buildVttFromCueBlocks, ar as buildVttFromTranslatedCueBlocks, as as concatenateVttSegments, at as extractTextFromVTT, au as extractTimestampedTranscript, av as fetchTranscriptDataForUrl, aw as fetchTranscriptForAsset, ax as filterVttByScope, ay as findCaptionTrack, az as getHotspotsForAsset, aA as getHotspotsForPlaybackId, aB as getHotspotsForVideo, aC as getReadyTextTracks, aD as getReliableLanguageCode, aE as getShotsForAsset, aF as parseVTTCues, aG as replaceCueText, aH as requestShotsForAsset, aI as sanitizeUntrustedText, aJ as secondsToTimestamp, aK as splitVttPreambleAndCueBlocks, aL as stripVttMetadataBlocks, aM as vttTimestampToSeconds, aN as waitForShotsForAsset } from './transcripts-CGRjxn_g.js';
2
2
 
3
3
  interface HeatmapOptions {
4
4
  /** Time window for results, e.g., '7:days' (default: '7:days') */
@@ -1,5 +1,5 @@
1
1
  import { LanguageModel, generateText as generateText$1 } from 'ai';
2
- import { aO as ClassifiedErrorsOption, O as WorkflowCredentialsInput, d as MuxAiError, e as MuxAsset, A as AssetTextTrack, a as MuxAiErrorFacts, K as TokenUsage, D as ScopedMuxAIOptions, I as ImageSubmissionMode, y as MuxAIOptions, j as ChunkingStrategy, N as VideoEmbeddingsResult, a9 as Hotspot, ag as Shot, a5 as VTTCue, L as ToneType, H as StorageAdapter } from './transcripts-CFZM111v.js';
2
+ import { aO as ClassifiedErrorsOption, O as WorkflowCredentialsInput, d as MuxAiError, e as MuxAsset, A as AssetTextTrack, a as MuxAiErrorFacts, K as TokenUsage, D as ScopedMuxAIOptions, I as ImageSubmissionMode, y as MuxAIOptions, j as ChunkingStrategy, N as VideoEmbeddingsResult, a9 as Hotspot, ag as Shot, a5 as VTTCue, L as ToneType, H as StorageAdapter } from './transcripts-CGRjxn_g.js';
3
3
  import { z } from 'zod';
4
4
  import { S as SafetyReport, e as PromptOverrides, h as SceneContextItemV1, D as DEFAULT_DESCRIPTION_LENGTH, a as DEFAULT_SUMMARY_KEYWORD_LIMIT, b as DEFAULT_TITLE_LENGTH } from './summarization-BFmhXeAu.js';
5
5
  import { createAnthropic } from '@ai-sdk/anthropic';
package/dist/index.d.ts CHANGED
@@ -1,8 +1,8 @@
1
- import { M as MuxAiErrorDependency, a as MuxAiErrorFacts, b as MuxAiErrorSource, c as MuxAiErrorType, d as MuxAiError, e as MuxAsset, f as MuxAiErrorFactValue, g as MuxAiErrorCode, C as ClassifiedError, W as WorkflowCredentials, S as StoragePutObjectInput, h as StoragePresignGetObjectInput } from './transcripts-CFZM111v.js';
2
- export { A as AssetTextTrack, i as ChunkEmbedding, j as ChunkingStrategy, k as ClassifiedErrorInit, l as CodedClassification, E as Encrypted, m as EncryptedPayload, n as ErrorCatalogEntry, o as ErrorCauseSummary, I as ImageSubmissionMode, p as MUX_AI_ERROR_CATALOG, q as MUX_AI_ERROR_CODES, r as MUX_AI_ERROR_CODE_VALUES, s as MUX_AI_ERROR_DEPENDENCIES, t as MUX_AI_ERROR_DEPENDENCY_VALUES, u as MUX_AI_ERROR_SOURCES, v as MUX_AI_ERROR_SOURCE_VALUES, w as MUX_AI_ERROR_TYPES, x as MUX_AI_ERROR_TYPE_VALUES, y as MuxAIOptions, z as MuxAiErrorInit, P as PlaybackAsset, B as PlaybackPolicy, D as ScopedMuxAIOptions, F as SerializedClassification, G as SourceAndDependency, H as StorageAdapter, T as TextChunk, J as TokenChunkingConfig, K as TokenUsage, L as ToneType, U as UsageMetadata, V as VTTChunkingConfig, N as VideoEmbeddingsResult, O as WorkflowCredentialsInput, Q as WorkflowMuxClient, R as WorkflowScope, X as assertNever, Y as classificationInit, Z as decryptFromWorkflow, _ as encryptForWorkflow, $ as errorDetailFact, a0 as internalError, a1 as isTransientStatus, a2 as restoreClassification, a3 as serializeClassification, a4 as wrapError } from './transcripts-CFZM111v.js';
3
- export { I as ISO639_1, a as ISO639_3, L as LanguageCodePair, M as MUX_TRACK_PASSTHROUGH_MAX_CHARS, R as ReplaceAndCreateTextTrackInput, b as ReplaceAndCreateTextTrackResult, c as ReplaceAndCreateTrackInput, d as ReplaceExistingTracksPolicy, e as ReplaceSourceTrackInput, f as ReplaceableTrackType, S as SourceTrackReplacementPolicy, g as SupportedISO639_1, h as SupportedISO639_3, T as TextTrackReplacementPlan, i as TextTrackSummary, j as TextTrackTarget, k as TrackReplacementBlocked, l as TrackReplacementBlockedReason, m as TrackSummary, n as TrackTarget, o as buildMuxAiTrackPassthrough, p as findNameCollisionTextTracks, q as findSameLanguageTextTracks, r as getLanguageCodePair, s as getLanguageName, t as isDuplicateTrackNameError, u as isMuxGeneratedTextTrack, v as isUndeterminedLanguageCode, w as isValidISO639_1, x as isValidISO639_3, y as normalizeTrackLanguageCode, z as normalizeTrackName, A as planSourceTrackReplacement, B as planTextTrackReplacement, C as replaceAndCreateTextTrack, D as replaceAndCreateTrack, E as replaceSourceTrack, F as summarizeTextTrack, G as toISO639_1, H as toISO639_3, J as trackReplacementBlockedError, K as trackTargetFacts, N as validateTrackPassthrough, O as workflows } from './index-DJ6j4-nM.js';
1
+ import { M as MuxAiErrorDependency, a as MuxAiErrorFacts, b as MuxAiErrorSource, c as MuxAiErrorType, d as MuxAiError, e as MuxAsset, f as MuxAiErrorFactValue, g as MuxAiErrorCode, C as ClassifiedError, W as WorkflowCredentials, S as StoragePutObjectInput, h as StoragePresignGetObjectInput } from './transcripts-CGRjxn_g.js';
2
+ export { A as AssetTextTrack, i as ChunkEmbedding, j as ChunkingStrategy, k as ClassifiedErrorInit, l as CodedClassification, E as Encrypted, m as EncryptedPayload, n as ErrorCatalogEntry, o as ErrorCauseSummary, I as ImageSubmissionMode, p as MUX_AI_ERROR_CATALOG, q as MUX_AI_ERROR_CODES, r as MUX_AI_ERROR_CODE_VALUES, s as MUX_AI_ERROR_DEPENDENCIES, t as MUX_AI_ERROR_DEPENDENCY_VALUES, u as MUX_AI_ERROR_SOURCES, v as MUX_AI_ERROR_SOURCE_VALUES, w as MUX_AI_ERROR_TYPES, x as MUX_AI_ERROR_TYPE_VALUES, y as MuxAIOptions, z as MuxAiErrorInit, P as PlaybackAsset, B as PlaybackPolicy, D as ScopedMuxAIOptions, F as SerializedClassification, G as SourceAndDependency, H as StorageAdapter, T as TextChunk, J as TokenChunkingConfig, K as TokenUsage, L as ToneType, U as UsageMetadata, V as VTTChunkingConfig, N as VideoEmbeddingsResult, O as WorkflowCredentialsInput, Q as WorkflowMuxClient, R as WorkflowScope, X as assertNever, Y as classificationInit, Z as decryptFromWorkflow, _ as encryptForWorkflow, $ as errorDetailFact, a0 as internalError, a1 as isTransientStatus, a2 as restoreClassification, a3 as serializeClassification, a4 as wrapError } from './transcripts-CGRjxn_g.js';
3
+ export { I as ISO639_1, a as ISO639_3, L as LanguageCodePair, M as MUX_TRACK_PASSTHROUGH_MAX_CHARS, R as ReplaceAndCreateTextTrackInput, b as ReplaceAndCreateTextTrackResult, c as ReplaceAndCreateTrackInput, d as ReplaceExistingTracksPolicy, e as ReplaceSourceTrackInput, f as ReplaceableTrackType, S as SourceTrackReplacementPolicy, g as SupportedISO639_1, h as SupportedISO639_3, T as TextTrackReplacementPlan, i as TextTrackSummary, j as TextTrackTarget, k as TrackReplacementBlocked, l as TrackReplacementBlockedReason, m as TrackSummary, n as TrackTarget, o as buildMuxAiTrackPassthrough, p as findNameCollisionTextTracks, q as findSameLanguageTextTracks, r as getLanguageCodePair, s as getLanguageName, t as isDuplicateTrackNameError, u as isMuxGeneratedTextTrack, v as isUndeterminedLanguageCode, w as isValidISO639_1, x as isValidISO639_3, y as normalizeTrackLanguageCode, z as normalizeTrackName, A as planSourceTrackReplacement, B as planTextTrackReplacement, C as replaceAndCreateTextTrack, D as replaceAndCreateTrack, E as replaceSourceTrack, F as summarizeTextTrack, G as toISO639_1, H as toISO639_3, J as trackReplacementBlockedError, K as trackTargetFacts, N as validateTrackPassthrough, O as workflows } from './index-DxCv-w74.js';
4
4
  import { WORKFLOW_SERIALIZE, WORKFLOW_DESERIALIZE } from '@workflow/serde';
5
- export { i as primitives } from './index-CntSHp7Q.js';
5
+ export { i as primitives } from './index-C0BdM1ob.js';
6
6
  import '@mux/ts';
7
7
  import 'ai';
8
8
  import 'zod';
@@ -11,7 +11,7 @@ import '@ai-sdk/anthropic';
11
11
  import '@ai-sdk/google';
12
12
  import '@ai-sdk/openai';
13
13
 
14
- var version = "0.63.1";
14
+ var version = "0.64.0";
15
15
 
16
16
  interface DependencyErrorInit {
17
17
  dependency: MuxAiErrorDependency;
@@ -174,7 +174,7 @@ declare function invalidParameterMessage(facts: MuxAiErrorFacts): string;
174
174
  */
175
175
  declare const MUX_AI_ERROR_PUBLIC_MAPPINGS: {
176
176
  readonly invalid_scope: {
177
- readonly facts: readonly ["reason", "received", "startTime", "endTime", "assetDurationSeconds"];
177
+ readonly facts: readonly ["reason", "received", "startTime", "endTime", "assetDurationSeconds", "videoEndTime"];
178
178
  readonly message: typeof scopeMessage;
179
179
  };
180
180
  readonly track_replacement_blocked: {
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.63.1";
8
+ var version = "0.64.0";
9
9
 
10
10
  // node_modules/@workflow/serde/dist/index.js
11
11
  var WORKFLOW_SERIALIZE = /* @__PURE__ */ Symbol.for("workflow-serialize");
@@ -572,11 +572,11 @@ var MUX_AI_ERROR_DEPENDENCIES = {
572
572
  };
573
573
  var MUX_AI_ERROR_DEPENDENCY_VALUES = Object.values(MUX_AI_ERROR_DEPENDENCIES);
574
574
  var MUX_AI_ERROR_CODES = {
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`, `no_scenes`) and the bounds involved. */
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`, `no_scenes`) and the bounds involved (`videoEndTime` for `no_video`). */
576
576
  INVALID_SCOPE: "invalid_scope",
577
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`, `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). */
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`, `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
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",
@@ -604,6 +604,8 @@ var MUX_AI_ERROR_CODES = {
604
604
  TRACK_WRITE_UNCLASSIFIED: "track_write_unclassified",
605
605
  /** Mux answered a track create without a track id. The track may exist, so it isn't step-retried. Facts: `call`, `assetId`. */
606
606
  TRACK_ID_MISSING: "track_id_missing",
607
+ /** Mux answered an image download with something other than a non-empty image. Facts: `call`, `reason` (`not_image`, `empty`), `contentType`. */
608
+ IMAGE_RESPONSE_INVALID: "image_response_invalid",
607
609
  /** The asset's ready caption track has no id, so its transcript can't be fetched. Facts: `assetId`, `languageCode`. */
608
610
  CAPTION_TRACK_ID_MISSING: "caption_track_id_missing",
609
611
  /** The asset snapshot the service running the SDK passed in is for a different asset than the one requested. Facts: `assetId`, `snapshotAssetId`. */
@@ -667,6 +669,9 @@ var MUX_AI_ERROR_CATALOG = {
667
669
  // The track may exist, so a step retry could duplicate it; the job stays retryable.
668
670
  [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 },
669
671
  [MUX_AI_ERROR_CODES.CAPTION_TRACK_ID_MISSING]: { type: MUX_AI_ERROR_TYPES.PROCESSING_ERROR, source: MUX_AI_ERROR_SOURCES.UPSTREAM, dependency: MUX_AI_ERROR_DEPENDENCIES.MUX_VIDEO },
672
+ // Transient (so retryable): the download doesn't retry a reply that isn't a non-empty image
673
+ // itself, so the step runner does, as it did before classification.
674
+ [MUX_AI_ERROR_CODES.IMAGE_RESPONSE_INVALID]: { type: MUX_AI_ERROR_TYPES.PROCESSING_ERROR, source: MUX_AI_ERROR_SOURCES.UPSTREAM, dependency: MUX_AI_ERROR_DEPENDENCIES.MUX_VIDEO, transient: true, retryable: true },
670
675
  [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 },
671
676
  // Model calls.
672
677
  [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 },
@@ -2265,7 +2270,7 @@ function scopeMessage(facts) {
2265
2270
  case "empty_range":
2266
2271
  return `The requested start time (${text(facts.startTime)}s) must be before the end time (${text(facts.endTime)}s).`;
2267
2272
  case "no_video":
2268
- return "The requested time range doesn't include any video.";
2273
+ return facts.videoEndTime === void 0 ? "The requested time range doesn't include any video." : `The requested time range starts at ${text(facts.startTime)}s, at or after the end of the asset's video (${text(facts.videoEndTime)}s).`;
2269
2274
  case "no_transcript":
2270
2275
  return "The transcript has no content in the requested time range.";
2271
2276
  case "no_scenes":
@@ -2306,6 +2311,8 @@ function invalidParameterMessage(facts) {
2306
2311
  return `${parameter} must be ${quotedList(facts.allowed)}${facts.value === void 0 ? "" : ` (received '${text(facts.value)}')`}.`;
2307
2312
  case "one_of_required":
2308
2313
  return `Provide at least one of ${names(facts.parameters)}.`;
2314
+ case "audio_only":
2315
+ return `${parameter} must be ${quotedList(facts.allowed)} for an audio-only asset, which is processed from its transcript and needs a ready caption or subtitle track.`;
2309
2316
  default:
2310
2317
  return `${parameter} has a value that can't be used.`;
2311
2318
  }
@@ -2317,7 +2324,7 @@ var AUDIO_TRACK_UNSUPPORTED_MESSAGES = {
2317
2324
  };
2318
2325
  var MUX_AI_ERROR_PUBLIC_MAPPINGS = {
2319
2326
  [MUX_AI_ERROR_CODES.INVALID_SCOPE]: {
2320
- facts: ["reason", "received", "startTime", "endTime", "assetDurationSeconds"],
2327
+ facts: ["reason", "received", "startTime", "endTime", "assetDurationSeconds", "videoEndTime"],
2321
2328
  message: scopeMessage
2322
2329
  },
2323
2330
  [MUX_AI_ERROR_CODES.TRACK_REPLACEMENT_BLOCKED]: {
@@ -3748,11 +3755,11 @@ function resolveWorkflowScope(scope, assetDurationSeconds, options = {}) {
3748
3755
  }
3749
3756
  return { startTime, endTime };
3750
3757
  }
3751
- function resolveRenderableVideoScope(scope, assetDurationSeconds, videoTrackDurationSeconds) {
3758
+ function resolveRenderableVideoScope(scope, assetDurationSeconds, videoTrackDurationSeconds, options = {}) {
3752
3759
  if (!hasWorkflowScopeBoundaries(scope)) {
3753
3760
  return void 0;
3754
3761
  }
3755
- const resolvedScope = resolveWorkflowScope(scope, assetDurationSeconds);
3762
+ const resolvedScope = resolveWorkflowScope(scope, assetDurationSeconds, options);
3756
3763
  let renderableEndTime = resolvedScope.endTime;
3757
3764
  if (videoTrackDurationSeconds !== void 0 && Number.isFinite(videoTrackDurationSeconds) && videoTrackDurationSeconds >= 0) {
3758
3765
  renderableEndTime = Math.min(videoTrackDurationSeconds, resolvedScope.endTime);
@@ -3762,6 +3769,13 @@ function resolveRenderableVideoScope(scope, assetDurationSeconds, videoTrackDura
3762
3769
  endTime: renderableEndTime
3763
3770
  };
3764
3771
  if (renderableScope.startTime >= renderableScope.endTime) {
3772
+ if (options.classifiedErrors) {
3773
+ throw invalidScopeError(
3774
+ "The requested scope does not include any renderable video.",
3775
+ { reason: "no_video", startTime: resolvedScope.startTime, endTime: resolvedScope.endTime, videoEndTime: renderableEndTime },
3776
+ ["scope"]
3777
+ );
3778
+ }
3765
3779
  throw new LegacyMuxAiError("The requested scope does not include any renderable video.", {
3766
3780
  type: "validation_error"
3767
3781
  });
@@ -5355,13 +5369,15 @@ var DEFAULT_OPTIONS = {
5355
5369
  maxRetryDelay: 1e4,
5356
5370
  exponentialBackoff: true
5357
5371
  };
5358
- async function downloadImageAsBase64(url, options = {}) {
5372
+ async function downloadImageAsBase64(url, options = {}, errorOptions = {}) {
5359
5373
  "use step";
5360
5374
  const opts = { ...DEFAULT_OPTIONS, ...options };
5361
5375
  let attemptCount = 0;
5376
+ let failure;
5362
5377
  return pRetry(
5363
5378
  async () => {
5364
5379
  attemptCount++;
5380
+ failure = void 0;
5365
5381
  const controller = new AbortController();
5366
5382
  const timeoutId = setTimeout(() => controller.abort(), opts.timeout);
5367
5383
  try {
@@ -5373,6 +5389,7 @@ async function downloadImageAsBase64(url, options = {}) {
5373
5389
  });
5374
5390
  clearTimeout(timeoutId);
5375
5391
  if (!response.ok) {
5392
+ failure = { kind: "status", status: response.status, requestId: requestIdOf(response.headers) };
5376
5393
  if (response.status >= 400 && response.status < 500 && response.status !== 429) {
5377
5394
  throw new AbortError(`HTTP ${response.status}: ${response.statusText}`);
5378
5395
  }
@@ -5380,11 +5397,13 @@ async function downloadImageAsBase64(url, options = {}) {
5380
5397
  }
5381
5398
  const contentType = response.headers.get("content-type");
5382
5399
  if (!contentType?.startsWith("image/")) {
5400
+ failure = { kind: "invalid", reason: "not_image", ...contentType && { contentType: contentType.slice(0, 100) } };
5383
5401
  throw new AbortError(`Invalid content type: ${contentType}. Expected image/*`);
5384
5402
  }
5385
5403
  const arrayBuffer = await response.arrayBuffer();
5386
5404
  const buffer = new Uint8Array(arrayBuffer);
5387
5405
  if (buffer.length === 0) {
5406
+ failure = { kind: "invalid", reason: "empty" };
5388
5407
  throw new AbortError("Downloaded image is empty");
5389
5408
  }
5390
5409
  const base64Data = `data:${contentType};base64,${bytesToBase642(buffer)}`;
@@ -5401,6 +5420,7 @@ async function downloadImageAsBase64(url, options = {}) {
5401
5420
  if (error instanceof AbortError) {
5402
5421
  throw error;
5403
5422
  }
5423
+ failure ?? (failure = { kind: "no_response", timedOut: error instanceof Error && error.name === "AbortError" });
5404
5424
  if (error instanceof Error) {
5405
5425
  if (error.name === "AbortError") {
5406
5426
  throw new Error(`Request timeout after ${opts.timeout}ms`);
@@ -5424,6 +5444,36 @@ async function downloadImageAsBase64(url, options = {}) {
5424
5444
  }
5425
5445
  }
5426
5446
  }
5447
+ ).catch((error) => {
5448
+ if (!errorOptions.classifiedErrors) {
5449
+ throw error;
5450
+ }
5451
+ throw imageDownloadError(failure, errorOptions.call ?? "fetch_image", error);
5452
+ });
5453
+ }
5454
+ function imageDownloadError(failure, call, cause) {
5455
+ if (failure?.kind === "status") {
5456
+ return muxVideoError(`Failed to download image from Mux (HTTP ${failure.status})`, {
5457
+ call,
5458
+ status: failure.status,
5459
+ requestId: failure.requestId
5460
+ });
5461
+ }
5462
+ if (failure?.kind === "invalid") {
5463
+ return new MuxAiError(
5464
+ failure.reason === "empty" ? "Mux returned an empty image." : `Mux returned ${failure.contentType ?? "no content type"} instead of an image.`,
5465
+ {
5466
+ code: MUX_AI_ERROR_CODES.IMAGE_RESPONSE_INVALID,
5467
+ type: MUX_AI_ERROR_TYPES.PROCESSING_ERROR,
5468
+ source: MUX_AI_ERROR_SOURCES.UPSTREAM,
5469
+ dependency: MUX_AI_ERROR_DEPENDENCIES.MUX_VIDEO,
5470
+ facts: { call, reason: failure.reason, ...failure.contentType && { contentType: failure.contentType } }
5471
+ }
5472
+ );
5473
+ }
5474
+ return muxVideoError(
5475
+ failure?.timedOut ? "Image download from Mux timed out" : "Failed to download image from Mux",
5476
+ { call, cause, timedOut: failure?.timedOut }
5427
5477
  );
5428
5478
  }
5429
5479
  async function downloadImagesAsBase64(urls, options = {}, maxConcurrent = 5) {
@@ -10346,6 +10396,7 @@ async function analyzeVideo(imageDataUrl, provider, modelId, userPrompt, systemP
10346
10396
  "use step";
10347
10397
  const model = await createLanguageModelFromConfig(provider, modelId, credentials);
10348
10398
  const schema = buildSummarySchema(descriptionLength);
10399
+ const context = { call: "generate_summary", provider, model: modelId };
10349
10400
  const response = await withContentPolicyAwareRetry(() => generateText8({
10350
10401
  model,
10351
10402
  maxRetries: 0,
@@ -10364,11 +10415,10 @@ async function analyzeVideo(imageDataUrl, provider, modelId, userPrompt, systemP
10364
10415
  ] : userPrompt
10365
10416
  }
10366
10417
  ]
10367
- }));
10368
- const output = getGeneratedOutputWithContentPolicyHandling(response);
10369
- if (!output) {
10370
- throw new Error("Summarization output missing");
10371
- }
10418
+ }), void 0, context).catch((error) => {
10419
+ throw modelStepError(error, "Summary generation model call failed", { ...context });
10420
+ });
10421
+ const output = getGeneratedOutputWithContentPolicyHandling(response, context);
10372
10422
  const parsed = schema.parse(output);
10373
10423
  const unexpectedKeys = detectUnexpectedKeysFromRawText(
10374
10424
  response.text,
@@ -10391,6 +10441,7 @@ async function analyzeAudioOnly(provider, modelId, userPrompt, systemPrompt, des
10391
10441
  "use step";
10392
10442
  const model = await createLanguageModelFromConfig(provider, modelId, credentials);
10393
10443
  const schema = buildSummarySchema(descriptionLength);
10444
+ const context = { call: "generate_summary", provider, model: modelId };
10394
10445
  const response = await withContentPolicyAwareRetry(() => generateText8({
10395
10446
  model,
10396
10447
  maxRetries: 0,
@@ -10406,11 +10457,10 @@ async function analyzeAudioOnly(provider, modelId, userPrompt, systemPrompt, des
10406
10457
  content: userPrompt
10407
10458
  }
10408
10459
  ]
10409
- }));
10410
- const output = getGeneratedOutputWithContentPolicyHandling(response);
10411
- if (!output) {
10412
- throw new Error("Summarization output missing");
10413
- }
10460
+ }), void 0, context).catch((error) => {
10461
+ throw modelStepError(error, "Summary generation model call failed", { ...context });
10462
+ });
10463
+ const output = getGeneratedOutputWithContentPolicyHandling(response, context);
10414
10464
  const parsed = schema.parse(output);
10415
10465
  const unexpectedKeys = detectUnexpectedKeysFromRawText(
10416
10466
  response.text,
@@ -10481,10 +10531,12 @@ async function getSummaryAndTagsInternal(assetId, options, collectedUsage) {
10481
10531
  scope
10482
10532
  } = options ?? {};
10483
10533
  if (!VALID_TONES.includes(tone)) {
10484
- throw new LegacyMuxAiError(
10485
- `Invalid tone "${tone}". Valid tones are: ${VALID_TONES.join(", ")}.`,
10486
- { type: "validation_error" }
10487
- );
10534
+ throw new MuxAiError(`Invalid tone "${tone}". Valid tones are: ${VALID_TONES.join(", ")}.`, {
10535
+ code: MUX_AI_ERROR_CODES.INVALID_PARAMETER,
10536
+ type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR,
10537
+ source: MUX_AI_ERROR_SOURCES.REQUEST,
10538
+ facts: { parameter: "tone", reason: "not_allowed", allowed: [...VALID_TONES], value: String(tone).slice(0, 100), inputs: ["tone"] }
10539
+ });
10488
10540
  }
10489
10541
  const modelConfig = resolveLanguageModelConfig({
10490
10542
  ...options,
@@ -10492,7 +10544,7 @@ async function getSummaryAndTagsInternal(assetId, options, collectedUsage) {
10492
10544
  provider
10493
10545
  });
10494
10546
  const workflowCredentials = credentials;
10495
- const { asset: assetData, playbackId, policy } = await getPlaybackIdForAsset(assetId, workflowCredentials, options?.assetSnapshot);
10547
+ const { asset: assetData, playbackId, policy } = await getPlaybackIdForAsset(assetId, workflowCredentials, options?.assetSnapshot, { classifiedErrors: true });
10496
10548
  const assetDurationSeconds = getAssetDurationSecondsFromAsset(assetData);
10497
10549
  const isAudioOnly = isAudioOnlyAsset(assetData);
10498
10550
  const hasSceneContext = !isAudioOnly && Boolean(sceneContext?.length);
@@ -10500,24 +10552,27 @@ async function getSummaryAndTagsInternal(assetId, options, collectedUsage) {
10500
10552
  const storyboardScope = isAudioOnly ? void 0 : resolveRenderableVideoScope(
10501
10553
  effectiveScope,
10502
10554
  assetDurationSeconds,
10503
- getVideoTrackDurationSecondsFromAsset(assetData)
10555
+ getVideoTrackDurationSecondsFromAsset(assetData),
10556
+ { classifiedErrors: true, assetId }
10504
10557
  );
10505
10558
  if (isAudioOnly && effectiveScope) {
10506
- resolveWorkflowScope(effectiveScope, assetDurationSeconds);
10559
+ resolveWorkflowScope(effectiveScope, assetDurationSeconds, { classifiedErrors: true, assetId });
10507
10560
  }
10508
10561
  if (isAudioOnly && !includeTranscript) {
10509
- throw new LegacyMuxAiError(
10562
+ throw new MuxAiError(
10510
10563
  "Audio-only assets require a transcript. Set includeTranscript: true and ensure the asset has a ready text track (captions/subtitles).",
10511
- { type: "validation_error" }
10564
+ {
10565
+ code: MUX_AI_ERROR_CODES.INVALID_PARAMETER,
10566
+ type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR,
10567
+ source: MUX_AI_ERROR_SOURCES.REQUEST,
10568
+ facts: { parameter: "includeTranscript", reason: "audio_only", allowed: [true], value: false, assetId, inputs: ["includeTranscript"] }
10569
+ }
10512
10570
  );
10513
10571
  }
10514
10572
  const signingContext = await resolveMuxSigningContext(workflowCredentials);
10515
10573
  const requiresSignedPlaybackAccess = includeTranscript || !isAudioOnly;
10516
10574
  if (policy === "signed" && requiresSignedPlaybackAccess && !signingContext) {
10517
- throw new LegacyMuxAiError(
10518
- "Signed playback ID requires signing credentials. Set MUX_SIGNING_KEY and MUX_PRIVATE_KEY environment variables.",
10519
- { type: "validation_error" }
10520
- );
10575
+ throw signingCredentialsMissingError();
10521
10576
  }
10522
10577
  const transcriptResult = includeTranscript ? await fetchTranscriptForAsset(assetData, playbackId, {
10523
10578
  languageCode,
@@ -10525,7 +10580,8 @@ async function getSummaryAndTagsInternal(assetId, options, collectedUsage) {
10525
10580
  shouldSign: policy === "signed",
10526
10581
  credentials: workflowCredentials,
10527
10582
  required: isAudioOnly,
10528
- scope: effectiveScope
10583
+ scope: effectiveScope,
10584
+ classifiedErrors: true
10529
10585
  }) : void 0;
10530
10586
  const transcriptText = transcriptResult?.transcriptText ?? "";
10531
10587
  const resolvedLanguageCode = outputLanguageCode && outputLanguageCode !== "auto" ? outputLanguageCode : getReliableLanguageCode(transcriptResult?.track) ?? getReliableLanguageCode(getReadyTextTracks(assetData)[0]);
@@ -10542,69 +10598,51 @@ async function getSummaryAndTagsInternal(assetId, options, collectedUsage) {
10542
10598
  languageName,
10543
10599
  sceneContext: hasSceneContext ? sceneContext : void 0
10544
10600
  });
10545
- let analysisResponse;
10546
- let imageUrl;
10547
10601
  let systemPrompt = AUDIO_ONLY_SYSTEM_PROMPT3;
10548
10602
  if (!isAudioOnly) {
10549
10603
  systemPrompt = createVideoSystemPrompt(hasSceneContext);
10550
10604
  }
10551
10605
  const effectiveDescriptionLength = descriptionLength ?? DEFAULT_DESCRIPTION_LENGTH;
10552
- try {
10553
- if (isAudioOnly) {
10554
- analysisResponse = await analyzeAudioOnly(
10555
- modelConfig.provider,
10556
- modelConfig.modelId,
10557
- userPrompt,
10558
- systemPrompt,
10559
- effectiveDescriptionLength,
10560
- workflowCredentials
10561
- );
10562
- } else {
10563
- const storyboardUrl = await getStoryboardUrl(
10564
- playbackId,
10565
- 640,
10566
- policy === "signed",
10567
- workflowCredentials,
10568
- storyboardScope
10569
- );
10570
- imageUrl = storyboardUrl;
10571
- if (imageSubmissionMode === "base64") {
10572
- const downloadResult = await downloadImageAsBase64(storyboardUrl, imageDownloadOptions);
10573
- analysisResponse = await analyzeVideo(
10574
- downloadResult.base64Data,
10575
- modelConfig.provider,
10576
- modelConfig.modelId,
10577
- userPrompt,
10578
- systemPrompt,
10579
- effectiveDescriptionLength,
10580
- workflowCredentials
10581
- );
10582
- } else {
10583
- analysisResponse = await analyzeVideo(
10584
- storyboardUrl,
10585
- modelConfig.provider,
10586
- modelConfig.modelId,
10587
- userPrompt,
10588
- systemPrompt,
10589
- effectiveDescriptionLength,
10590
- workflowCredentials
10591
- );
10592
- }
10593
- }
10594
- } catch (error) {
10595
- const contentType = isAudioOnly ? "audio" : "video";
10596
- legacyWrapError(error, `Failed to analyze ${contentType} content with ${provider}`);
10606
+ let imageUrl;
10607
+ let imageInput;
10608
+ if (!isAudioOnly) {
10609
+ imageUrl = await getStoryboardUrl(
10610
+ playbackId,
10611
+ 640,
10612
+ policy === "signed",
10613
+ workflowCredentials,
10614
+ storyboardScope
10615
+ );
10616
+ imageInput = imageSubmissionMode === "base64" ? (await downloadImageAsBase64(imageUrl, imageDownloadOptions, { classifiedErrors: true, call: "fetch_storyboard" })).base64Data : imageUrl;
10597
10617
  }
10618
+ const modelFacts = { call: "generate_summary", provider: modelConfig.provider, model: modelConfig.modelId, assetId };
10619
+ const analysisResponse = await (isAudioOnly ? analyzeAudioOnly(
10620
+ modelConfig.provider,
10621
+ modelConfig.modelId,
10622
+ userPrompt,
10623
+ systemPrompt,
10624
+ effectiveDescriptionLength,
10625
+ workflowCredentials
10626
+ ) : analyzeVideo(
10627
+ imageInput,
10628
+ modelConfig.provider,
10629
+ modelConfig.modelId,
10630
+ userPrompt,
10631
+ systemPrompt,
10632
+ effectiveDescriptionLength,
10633
+ workflowCredentials
10634
+ )).catch((error) => wrapError(error, `Failed to analyze ${isAudioOnly ? "audio" : "video"} content with ${modelConfig.provider}`, modelFacts));
10598
10635
  collectedUsage.push(analysisResponse.usage);
10599
- if (!analysisResponse.result) {
10600
- const contentType = isAudioOnly ? "audio" : "video";
10601
- throw new LegacyMuxAiError(`Failed to analyze ${contentType} content for asset ${assetId}.`);
10602
- }
10603
- if (!analysisResponse.result.title) {
10604
- throw new LegacyMuxAiError(`Failed to generate title for asset ${assetId}.`);
10605
- }
10606
- if (!analysisResponse.result.description) {
10607
- throw new LegacyMuxAiError(`Failed to generate description for asset ${assetId}.`);
10636
+ for (const field of ["title", "description"]) {
10637
+ if (!analysisResponse.result[field]) {
10638
+ throw new MuxAiError(`Failed to generate ${field} for asset ${assetId}.`, {
10639
+ code: MUX_AI_ERROR_CODES.MODEL_OUTPUT_MISSING,
10640
+ type: MUX_AI_ERROR_TYPES.PROCESSING_ERROR,
10641
+ source: MUX_AI_ERROR_SOURCES.UPSTREAM,
10642
+ dependency: MUX_AI_ERROR_DEPENDENCIES.AI_PROVIDER,
10643
+ facts: { ...modelFacts, field }
10644
+ });
10645
+ }
10608
10646
  }
10609
10647
  const safety = createSafetyReporter();
10610
10648
  if (analysisResponse.unexpectedKeys.length > 0) {