@mux/ai 0.68.0 → 0.69.0-canary.116

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.
@@ -965,13 +965,26 @@ declare class ClassifiedError<TType extends string = string, TCode extends strin
965
965
  }
966
966
  /** The classification of `error`, for a subclass's `WORKFLOW_SERIALIZE` hook. */
967
967
  declare function serializeClassification<TType extends string, TCode extends string, TDependency extends string>(error: ClassifiedError<TType, TCode, TDependency>): SerializedClassification<TType, TCode, TDependency>;
968
+ /**
969
+ * A stored classification, read so that rebuilding it can't throw. A record written by this
970
+ * codec reads as it was written, whatever its version; a field that is missing or malformed
971
+ * (an unknown future shape, a corrupted or hand-edited record, or no record at all) gets a
972
+ * fallback instead: the type `server_error` and source `internal`, no code or dependency, empty
973
+ * facts and causes, not retryable or transient, and the message "Unknown error". A deserializer
974
+ * that throws would make Workflow DevKit hand the workflow an unclassified error in its place.
975
+ */
976
+ declare function readSerializedClassification(record: unknown): SerializedClassification;
968
977
  /**
969
978
  * The constructor options that rebuild a serialized classification, for a
970
979
  * subclass's `WORKFLOW_DESERIALIZE` hook; follow with {@link restoreClassification}.
971
- * The stored classification wins over the catalog's current mapping for a code.
980
+ * The stored classification wins over the catalog's current mapping for a code. Reads the
981
+ * record with {@link readSerializedClassification}, so a malformed one can't make it throw.
972
982
  */
973
983
  declare function classificationInit<TType extends string, TCode extends string, TDependency extends string>(record: SerializedClassification<TType, TCode, TDependency>): ClassifiedErrorInit<TType, TCode, TDependency>;
974
- /** Restores what the constructor can't take back: the code, the cause summaries and the stack. */
984
+ /**
985
+ * Restores what the constructor can't take back: the code, the cause summaries and the stack.
986
+ * Reads the record with {@link readSerializedClassification}, so a malformed one can't make it throw.
987
+ */
975
988
  declare function restoreClassification<T extends ClassifiedError>(error: T, record: SerializedClassification): T;
976
989
  /**
977
990
  * A classified @mux/ai failure, built on {@link ClassifiedError} with the SDK's
@@ -1005,7 +1018,8 @@ declare function errorDetailFact(text: string, maxLength?: number): string;
1005
1018
  * unclassified is this code's own failure.
1006
1019
  *
1007
1020
  * Use this in catch blocks that re-throw, so a classified error from a callee
1008
- * keeps its classification. Token usage carries over either way.
1021
+ * keeps its classification, including one a step threw after Workflow DevKit wrapped it
1022
+ * (see {@link classifiedErrorOf}). Token usage carries over either way.
1009
1023
  */
1010
1024
  declare function wrapError(error: unknown, message: string, facts?: MuxAiErrorFacts): never;
1011
1025
  /**
@@ -1360,4 +1374,4 @@ interface TranscriptFetchStepResult {
1360
1374
  declare function fetchTranscriptDataForUrl(transcriptUrl: string, options?: Pick<TranscriptFetchOptions, "cleanTranscript" | "scope" | "classifiedErrors">): Promise<TranscriptFetchStepResult>;
1361
1375
  declare function fetchTranscriptForAsset(asset: MuxAsset, playbackId: string, options?: TranscriptFetchOptions): Promise<TranscriptResult>;
1362
1376
 
1363
- export { type WorkflowScope as $, type AssetTextTrack as A, MUX_AI_ERROR_SOURCE_VALUES as B, ClassifiedError as C, MUX_AI_ERROR_TYPES as D, type Encrypted as E, MUX_AI_ERROR_TYPE_VALUES as F, type MuxAIOptions as G, type MuxAiErrorInit as H, type ImageSubmissionMode as I, type PlaybackPolicy as J, type ScopedMuxAIOptions as K, type SerializedClassification as L, type MuxAiErrorDependency as M, type SourceAndDependency as N, type StorageAdapter as O, type PlaybackAsset as P, type TokenChunkingConfig as Q, type TokenUsage as R, type StoragePutObjectInput as S, type TextChunk as T, type ToneType as U, type UsageMetadata as V, type WorkflowCredentials as W, type VTTChunkingConfig as X, type VideoEmbeddingsResult as Y, type WorkflowCredentialsInput as Z, type WorkflowMuxClient as _, type MuxAiErrorFacts as a, assertNever as a0, classificationInit as a1, decryptFromWorkflow as a2, encryptForWorkflow as a3, errorDetailFact as a4, internalError as a5, isTransientStatus as a6, restoreClassification as a7, serializeClassification as a8, wrapError as a9, fetchTranscriptDataForUrl as aA, fetchTranscriptForAsset as aB, filterVttByScope as aC, findCaptionTrack as aD, getHotspotsForAsset as aE, getHotspotsForPlaybackId as aF, getHotspotsForVideo as aG, getReadyTextTracks as aH, getReliableLanguageCode as aI, getShotsForAsset as aJ, parseVTTCues as aK, replaceCueText as aL, requestShotsForAsset as aM, sanitizeUntrustedText as aN, secondsToTimestamp as aO, splitVttPreambleAndCueBlocks as aP, stripVttMetadataBlocks as aQ, vttTimestampToSeconds as aR, waitForShotsForAsset as aS, type VTTCue as aa, type CompletedShotsResult as ab, type DeletedShotsResult as ac, type ErroredShotsResult as ad, type Hotspot as ae, type HotspotOptions as af, type HotspotResponse as ag, LOW_CONFIDENCE_THRESHOLD as ah, MAX_CUE_TEXT_CHARS as ai, type ParseVTTCuesOptions as aj, type PendingShotsResult as ak, type Shot as al, type ShotRequestOptions as am, type ShotsResult as an, type SkippedShotsResult as ao, type TranscriptEmptyReason as ap, type TranscriptFetchOptions as aq, type TranscriptFetchStepResult as ar, type TranscriptResult as as, type WaitForShotsOptions as at, buildTranscriptUrl as au, buildVttFromCueBlocks as av, buildVttFromTranslatedCueBlocks as aw, concatenateVttSegments as ax, extractTextFromVTT as ay, extractTimestampedTranscript as az, MUX_AI_ERROR_SOURCES as b, type MuxAiErrorSource as c, type MuxAiSiteDependencyCode as d, type MuxAiErrorType as e, MuxAiError as f, type MuxAiDependencyStatusCode as g, type MuxAsset as h, type MuxAiErrorFactValue as i, type MuxAiErrorCode as j, type ClassifiedErrorsOption as k, type StoragePresignGetObjectInput as l, type ChunkEmbedding as m, type ChunkingStrategy as n, type ClassifiedErrorInit as o, type CodedClassification as p, type EncryptedPayload as q, type ErrorCatalogEntry as r, type ErrorCauseSummary as s, MUX_AI_DEPENDENCY_STATUS_CODES as t, MUX_AI_DEPENDENCY_STATUS_CODE_VALUES as u, MUX_AI_ERROR_CATALOG as v, MUX_AI_ERROR_CODES as w, MUX_AI_ERROR_CODE_VALUES as x, MUX_AI_ERROR_DEPENDENCIES as y, MUX_AI_ERROR_DEPENDENCY_VALUES as z };
1377
+ export { type WorkflowScope as $, type AssetTextTrack as A, MUX_AI_ERROR_SOURCE_VALUES as B, ClassifiedError as C, MUX_AI_ERROR_TYPES as D, type Encrypted as E, MUX_AI_ERROR_TYPE_VALUES as F, type MuxAIOptions as G, type MuxAiErrorInit as H, type ImageSubmissionMode as I, type PlaybackPolicy as J, type ScopedMuxAIOptions as K, type SerializedClassification as L, type MuxAiErrorDependency as M, type SourceAndDependency as N, type StorageAdapter as O, type PlaybackAsset as P, type TokenChunkingConfig as Q, type TokenUsage as R, type StoragePutObjectInput as S, type TextChunk as T, type ToneType as U, type UsageMetadata as V, type WorkflowCredentials as W, type VTTChunkingConfig as X, type VideoEmbeddingsResult as Y, type WorkflowCredentialsInput as Z, type WorkflowMuxClient as _, type MuxAiErrorFacts as a, assertNever as a0, classificationInit as a1, decryptFromWorkflow as a2, encryptForWorkflow as a3, errorDetailFact as a4, internalError as a5, isTransientStatus as a6, readSerializedClassification as a7, restoreClassification as a8, serializeClassification as a9, extractTimestampedTranscript as aA, fetchTranscriptDataForUrl as aB, fetchTranscriptForAsset as aC, filterVttByScope as aD, findCaptionTrack as aE, getHotspotsForAsset as aF, getHotspotsForPlaybackId as aG, getHotspotsForVideo as aH, getReadyTextTracks as aI, getReliableLanguageCode as aJ, getShotsForAsset as aK, parseVTTCues as aL, replaceCueText as aM, requestShotsForAsset as aN, sanitizeUntrustedText as aO, secondsToTimestamp as aP, splitVttPreambleAndCueBlocks as aQ, stripVttMetadataBlocks as aR, vttTimestampToSeconds as aS, waitForShotsForAsset as aT, wrapError as aa, type VTTCue as ab, type CompletedShotsResult as ac, type DeletedShotsResult as ad, type ErroredShotsResult as ae, type Hotspot as af, type HotspotOptions as ag, type HotspotResponse as ah, LOW_CONFIDENCE_THRESHOLD as ai, MAX_CUE_TEXT_CHARS as aj, type ParseVTTCuesOptions as ak, type PendingShotsResult as al, type Shot as am, type ShotRequestOptions as an, type ShotsResult as ao, type SkippedShotsResult as ap, type TranscriptEmptyReason as aq, type TranscriptFetchOptions as ar, type TranscriptFetchStepResult as as, type TranscriptResult as at, type WaitForShotsOptions as au, buildTranscriptUrl as av, buildVttFromCueBlocks as aw, buildVttFromTranslatedCueBlocks as ax, concatenateVttSegments as ay, extractTextFromVTT as az, MUX_AI_ERROR_SOURCES as b, type MuxAiErrorSource as c, type MuxAiSiteDependencyCode as d, type MuxAiErrorType as e, MuxAiError as f, type MuxAiDependencyStatusCode as g, type MuxAsset as h, type MuxAiErrorFactValue as i, type MuxAiErrorCode as j, type ClassifiedErrorsOption as k, type StoragePresignGetObjectInput as l, type ChunkEmbedding as m, type ChunkingStrategy as n, type ClassifiedErrorInit as o, type CodedClassification as p, type EncryptedPayload as q, type ErrorCatalogEntry as r, type ErrorCauseSummary as s, MUX_AI_DEPENDENCY_STATUS_CODES as t, MUX_AI_DEPENDENCY_STATUS_CODE_VALUES as u, MUX_AI_ERROR_CATALOG as v, MUX_AI_ERROR_CODES as w, MUX_AI_ERROR_CODE_VALUES as x, MUX_AI_ERROR_DEPENDENCIES as y, MUX_AI_ERROR_DEPENDENCY_VALUES as z };
@@ -1,7 +1,7 @@
1
- export { U as ASK_QUESTIONS_DEFAULT_MAX_ANSWER_OPTION_LENGTH, V as ASK_QUESTIONS_DEFAULT_MAX_FREE_FORM_ANSWER_LENGTH, W as ASK_QUESTIONS_MAX_QUESTIONS_PER_CALL, X as ASK_QUESTIONS_MAX_QUESTION_LENGTH, Y as AskQuestionsOptions, Z as AskQuestionsResult, _ as AskQuestionsType, $ as AudioTranslationOptions, a0 as AudioTranslationResult, a1 as AutoCensorProfanityOptions, a2 as BurnedInCaptionsAnalysis, a3 as BurnedInCaptionsOptions, a4 as BurnedInCaptionsPromptOverrides, a5 as BurnedInCaptionsPromptSections, a6 as BurnedInCaptionsResult, a7 as CaptionReplacement, a8 as CensorMode, a9 as Chapter, aa as ChapterSystemPromptSections, ab as ChaptersOptions, ac as ChaptersPromptOverrides, ad as ChaptersPromptSections, ae as ChaptersResult, af as ChaptersType, ag as DEFAULT_TRANSCRIPT_WINDOWING, ah as DubbedCaptionsOutcome, ai as EditCaptionsOptions, aj as EditCaptionsResult, ak as EmbeddingsOptions, al as EmbeddingsResult, am as EngagementInsightsOptions, an as EngagementInsightsResult, ao as GENERATE_TEXT_CALLS_TO_ACTION, ap as GENERATE_TEXT_CHANNELS, aq as GENERATE_TEXT_CHANNEL_CEILINGS, ar as GENERATE_TEXT_FORMATS, as as GENERATE_TEXT_LENGTH_BOUNDS, at as GENERATE_TEXT_MAX_ARTIFACTS, au as GENERATE_TEXT_MAX_AUDIENCE_CHARS, av as GENERATE_TEXT_MAX_BRAND_TERMS, aw as GENERATE_TEXT_MAX_BRAND_TERMS_TOTAL_CHARS, ax as GENERATE_TEXT_MAX_BRAND_TERM_CHARS, ay as GENERATE_TEXT_MAX_CONCURRENT_GENERATIONS, az as GENERATE_TEXT_MAX_INSTRUCTIONS_CHARS, aA as GENERATE_TEXT_MAX_SHOT_FRAMES, aB as GENERATE_TEXT_MAX_VARIANTS, aC as GENERATE_TEXT_VOICES, aD as GOOGLE_VISION_LIKELIHOOD_TO_SCORE, aE as GenerateTextArtifact, aF as GenerateTextCallToAction, aG as GenerateTextChannel, aH as GenerateTextFormat, aI as GenerateTextKeyedItem, aJ as GenerateTextLengthLimit, aK as GenerateTextOptions, aL as GenerateTextResult, aM as GenerateTextVariant, aN as GenerateTextVoice, aO as GeneratedTextArtifact, aP as GeneratedTextVariant, aQ as HIVE_SEXUAL_CATEGORIES, aR as HIVE_VIOLENCE_CATEGORIES, aS as HiveModerationOutput, aT as HiveModerationSource, aU as ModerationOptions, aV as ModerationProvider, aW as ModerationResult, aX as ModerationSurfaceStatus, aY as MomentInsight, aZ as OverallInsight, a_ as ProfanityDetectionPayload, a$ as Question, b0 as QuestionAnswer, b1 as QuestionAnswerType, b2 as RepairAttempt, b3 as RepairCall, b4 as RepairFailureOutcome, b5 as RepairOptions, b6 as RepairPlan, b7 as RepairRejectionCode, b8 as RepairResult, b9 as RepairSpan, ba as ReplacementRecord, bb as SpeakerReplacement, bc as StaticRenditionCleanupOutcome, bd as SummarizationOptions, be as SummarizationPromptOverrides, bf as SummarizationPromptSections, bg as SummaryAndTagsResult, bh as SummaryType, bi as TextLengthLimit, bj as TextRepairModelOptions, bk as ThumbnailModerationScore, bl as ThumbnailModerationSkipReason, bm as ThumbnailModerationStatus, bn as TranscriptModerationScore, bo as TranscriptModerationSkipReason, bp as TranscriptModerationStatus, bq as TranslationChunkingOptions, br as TranslationOptions, bs as TranslationPayload, bt as TranslationResult, bu as aggregateTokenUsage, bv as applyOverrideLists, bw as applyReplacements, bx as applySpeakerReplacements, by as applyTextRepair, bz as askQuestions, bA as buildReplacementRegex, bB as buildTranscriptWindows, bC as burnedInCaptionsSchema, bD as censorVttContent, bE as chapterSchema, bF as chaptersSchema, bG as createReplacer, bH as createTextRepairGenerator, bI as editCaptions, bJ as extractTranscriptSegmentsForHotspots, bK as findGenerateTextLengthViolation, bL as generateChapters, bM as generateEmbeddings, bN as generateEngagementInsights, bO as generateText, bP as generateVideoEmbeddings, bQ as getModerationScores, bR as getSummaryAndTags, bS as hasBurnedInCaptions, bT as mapShotsToHotspots, bU as measureGenerateTextLength, bV as normalizeTranslatedVtt, bW as planTextRepair, bX as profanityDetectionSchema, bY as questionAnswerSchema, bZ as repairJsonSchema, b_ as repairText, b$ as resolveGenerateTextLengthLimit, c0 as resolveGenerateTextLengthLimits, c1 as resolveGenerateTextOptions, c2 as runTextRepairLoop, c3 as selectGenerateTextShotFrames, c4 as shouldSplitChunkTranslationError, c5 as summarySchema, c6 as transformCueText, c7 as translateAudio, c8 as translateCaptions, c9 as translationSchema, ca as validateNeverTranslateTerms, cb as verifyNeverTranslateTerms } from '../index-CxDX1bX1.js';
1
+ export { U as ASK_QUESTIONS_DEFAULT_MAX_ANSWER_OPTION_LENGTH, V as ASK_QUESTIONS_DEFAULT_MAX_FREE_FORM_ANSWER_LENGTH, W as ASK_QUESTIONS_MAX_QUESTIONS_PER_CALL, X as ASK_QUESTIONS_MAX_QUESTION_LENGTH, Y as AskQuestionsOptions, Z as AskQuestionsResult, _ as AskQuestionsType, $ as AudioTranslationOptions, a0 as AudioTranslationResult, a1 as AutoCensorProfanityOptions, a2 as BurnedInCaptionsAnalysis, a3 as BurnedInCaptionsOptions, a4 as BurnedInCaptionsPromptOverrides, a5 as BurnedInCaptionsPromptSections, a6 as BurnedInCaptionsResult, a7 as CaptionReplacement, a8 as CensorMode, a9 as Chapter, aa as ChapterSystemPromptSections, ab as ChaptersOptions, ac as ChaptersPromptOverrides, ad as ChaptersPromptSections, ae as ChaptersResult, af as ChaptersType, ag as DEFAULT_TRANSCRIPT_WINDOWING, ah as DubbedCaptionsOutcome, ai as EditCaptionsOptions, aj as EditCaptionsResult, ak as EmbeddingsOptions, al as EmbeddingsResult, am as EngagementInsightsOptions, an as EngagementInsightsResult, ao as GENERATE_TEXT_CALLS_TO_ACTION, ap as GENERATE_TEXT_CHANNELS, aq as GENERATE_TEXT_CHANNEL_CEILINGS, ar as GENERATE_TEXT_FORMATS, as as GENERATE_TEXT_LENGTH_BOUNDS, at as GENERATE_TEXT_MAX_ARTIFACTS, au as GENERATE_TEXT_MAX_AUDIENCE_CHARS, av as GENERATE_TEXT_MAX_BRAND_TERMS, aw as GENERATE_TEXT_MAX_BRAND_TERMS_TOTAL_CHARS, ax as GENERATE_TEXT_MAX_BRAND_TERM_CHARS, ay as GENERATE_TEXT_MAX_CONCURRENT_GENERATIONS, az as GENERATE_TEXT_MAX_INSTRUCTIONS_CHARS, aA as GENERATE_TEXT_MAX_SHOT_FRAMES, aB as GENERATE_TEXT_MAX_VARIANTS, aC as GENERATE_TEXT_VOICES, aD as GOOGLE_VISION_LIKELIHOOD_TO_SCORE, aE as GenerateTextArtifact, aF as GenerateTextCallToAction, aG as GenerateTextChannel, aH as GenerateTextFormat, aI as GenerateTextKeyedItem, aJ as GenerateTextLengthLimit, aK as GenerateTextOptions, aL as GenerateTextResult, aM as GenerateTextVariant, aN as GenerateTextVoice, aO as GeneratedTextArtifact, aP as GeneratedTextVariant, aQ as HIVE_SEXUAL_CATEGORIES, aR as HIVE_VIOLENCE_CATEGORIES, aS as HiveModerationOutput, aT as HiveModerationSource, aU as ModerationOptions, aV as ModerationProvider, aW as ModerationResult, aX as ModerationSurfaceStatus, aY as MomentInsight, aZ as OverallInsight, a_ as ProfanityDetectionPayload, a$ as Question, b0 as QuestionAnswer, b1 as QuestionAnswerType, b2 as RepairAttempt, b3 as RepairCall, b4 as RepairFailureOutcome, b5 as RepairOptions, b6 as RepairPlan, b7 as RepairRejectionCode, b8 as RepairResult, b9 as RepairSpan, ba as ReplacementRecord, bb as SpeakerReplacement, bc as StaticRenditionCleanupOutcome, bd as SummarizationOptions, be as SummarizationPromptOverrides, bf as SummarizationPromptSections, bg as SummaryAndTagsResult, bh as SummaryType, bi as TextLengthLimit, bj as TextRepairModelOptions, bk as ThumbnailModerationScore, bl as ThumbnailModerationSkipReason, bm as ThumbnailModerationStatus, bn as TranscriptModerationScore, bo as TranscriptModerationSkipReason, bp as TranscriptModerationStatus, bq as TranslationChunkingOptions, br as TranslationOptions, bs as TranslationPayload, bt as TranslationResult, bu as aggregateTokenUsage, bv as applyOverrideLists, bw as applyReplacements, bx as applySpeakerReplacements, by as applyTextRepair, bz as askQuestions, bA as buildReplacementRegex, bB as buildTranscriptWindows, bC as burnedInCaptionsSchema, bD as censorVttContent, bE as chapterSchema, bF as chaptersSchema, bG as createReplacer, bH as createTextRepairGenerator, bI as editCaptions, bJ as extractTranscriptSegmentsForHotspots, bK as findGenerateTextLengthViolation, bL as generateChapters, bM as generateContextualText, bN as generateEmbeddings, bO as generateEngagementInsights, bM as generateText, bP as generateVideoEmbeddings, bQ as getModerationScores, bR as getSummaryAndTags, bS as hasBurnedInCaptions, bT as mapShotsToHotspots, bU as measureGenerateTextLength, bQ as moderate, bV as normalizeTranslatedVtt, bW as planTextRepair, bX as profanityDetectionSchema, bY as questionAnswerSchema, bZ as repairJsonSchema, b_ as repairText, b$ as resolveGenerateTextLengthLimit, c0 as resolveGenerateTextLengthLimits, c1 as resolveGenerateTextOptions, c2 as runTextRepairLoop, c3 as selectGenerateTextShotFrames, c4 as shouldSplitChunkTranslationError, bR as summarize, c5 as summarySchema, c6 as transformCueText, c7 as translateAudio, c8 as translateCaptions, c9 as translationSchema, ca as validateNeverTranslateTerms, cb as verifyNeverTranslateTerms } from '../index-D9gsq_-m.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-Cs-n8X_l.js';
4
+ import '../transcripts-S4CdWuUq.js';
5
5
  import '@workflow/serde';
6
6
  import '@mux/ts';
7
7
  import 'zod';
@@ -9,6 +9,38 @@ import { z as z4 } from "zod";
9
9
  var WORKFLOW_SERIALIZE = /* @__PURE__ */ Symbol.for("workflow-serialize");
10
10
  var WORKFLOW_DESERIALIZE = /* @__PURE__ */ Symbol.for("workflow-deserialize");
11
11
 
12
+ // src/lib/error-guards.ts
13
+ function isClassifiedError(value) {
14
+ return typeof value === "object" && value !== null && "__classified_error" in value && value.__classified_error === true;
15
+ }
16
+ function isLegacyMuxAiError(value) {
17
+ return typeof value === "object" && value !== null && "__robots_error" in value && value.__robots_error === true && typeof value.publicMessage === "string";
18
+ }
19
+ var MAX_CAUSE_DEPTH = 5;
20
+ function classifiedErrorOf(error) {
21
+ const seen = /* @__PURE__ */ new Set();
22
+ let current = error;
23
+ for (let depth = 0; depth < MAX_CAUSE_DEPTH && typeof current === "object" && current !== null && !seen.has(current); depth += 1) {
24
+ if (isLegacyMuxAiError(current)) {
25
+ return isClassifiedError(current) ? current : void 0;
26
+ }
27
+ if (isClassifiedError(current)) {
28
+ return current;
29
+ }
30
+ seen.add(current);
31
+ current = current.cause;
32
+ }
33
+ return void 0;
34
+ }
35
+ var WORKFLOW_CONTROL_FLOW_ERROR_NAMES = /* @__PURE__ */ new Set(["ReplayDivergenceError", "WorkflowSuspension"]);
36
+ function isWorkflowControlFlowError(value) {
37
+ if (typeof value !== "object" || value === null) {
38
+ return false;
39
+ }
40
+ const { name } = value;
41
+ return typeof name === "string" && WORKFLOW_CONTROL_FLOW_ERROR_NAMES.has(name);
42
+ }
43
+
12
44
  // src/lib/prompt-fragments.ts
13
45
  import dedent from "dedent";
14
46
 
@@ -487,7 +519,8 @@ function getErrorTokenUsage(error) {
487
519
  }
488
520
  const usage = error.usage;
489
521
  if (typeof usage !== "object" || usage === null) {
490
- return void 0;
522
+ const classified = classifiedErrorOf(error);
523
+ return classified && classified !== error ? getErrorTokenUsage(classified) : void 0;
491
524
  }
492
525
  const source = usage;
493
526
  const extracted = {};
@@ -518,8 +551,12 @@ function getErrorTokenUsage(error) {
518
551
  return Object.keys(extracted).length > 0 ? extracted : void 0;
519
552
  }
520
553
  function rethrowWithTokenUsage(error, collectedUsage) {
521
- const usages = [...collectedUsage];
554
+ if (isWorkflowControlFlowError(error)) {
555
+ throw error;
556
+ }
522
557
  const errorUsage = getErrorTokenUsage(error);
558
+ error = classifiedErrorOf(error) ?? error;
559
+ const usages = [...collectedUsage];
523
560
  if (errorUsage) {
524
561
  usages.push(errorUsage);
525
562
  }
@@ -805,7 +842,7 @@ var MUX_AI_DEPENDENCY_STATUS_CODES = {
805
842
  RESPONSE_FAILED: MUX_AI_ERROR_CODES.DEPENDENCY_RESPONSE_FAILED
806
843
  };
807
844
  var MUX_AI_DEPENDENCY_STATUS_CODE_VALUES = Object.values(MUX_AI_DEPENDENCY_STATUS_CODES);
808
- var MAX_CAUSE_DEPTH = 3;
845
+ var MAX_CAUSE_DEPTH2 = 3;
809
846
  var MAX_CAUSE_MESSAGE_LENGTH = 500;
810
847
  function statusOf(value) {
811
848
  if (typeof value !== "object" || value === null) {
@@ -818,9 +855,9 @@ function statusOf(value) {
818
855
  function summarizeCauses(cause) {
819
856
  const causes = [];
820
857
  let current = cause;
821
- while (current !== void 0 && current !== null && causes.length < MAX_CAUSE_DEPTH) {
858
+ while (current !== void 0 && current !== null && causes.length < MAX_CAUSE_DEPTH2) {
822
859
  if (ClassifiedError.isClassified(current)) {
823
- causes.push(...current.causes.slice(0, MAX_CAUSE_DEPTH - causes.length));
860
+ causes.push(...current.causes.slice(0, MAX_CAUSE_DEPTH2 - causes.length));
824
861
  break;
825
862
  }
826
863
  const status = statusOf(current);
@@ -860,7 +897,7 @@ var ClassifiedError = class extends Error {
860
897
  }
861
898
  /** Whether `value` is any classified error, from this copy of the SDK or another. */
862
899
  static isClassified(value) {
863
- return typeof value === "object" && value !== null && "__classified_error" in value && value.__classified_error === true;
900
+ return isClassifiedError(value);
864
901
  }
865
902
  };
866
903
  function serializeClassification(error) {
@@ -870,6 +907,8 @@ function serializeClassification(error) {
870
907
  source: error.source,
871
908
  ...error.dependency && { dependency: error.dependency },
872
909
  ...error.code && { code: error.code },
910
+ // JSON-safe by type, but not checked at runtime: a value Workflow DevKit can't serialize
911
+ // would stop the step's failure from being recorded at all.
873
912
  facts: error.facts,
874
913
  retryable: error.retryable,
875
914
  transient: error.transient,
@@ -877,7 +916,41 @@ function serializeClassification(error) {
877
916
  stack: error.stack
878
917
  };
879
918
  }
919
+ function readString(value) {
920
+ return typeof value === "string" && value.length > 0 ? value : void 0;
921
+ }
922
+ function readPlainRecord(value) {
923
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
924
+ }
925
+ function readSerializedClassification(record) {
926
+ const value = readPlainRecord(record) ?? {};
927
+ const dependency = readString(value.dependency);
928
+ const code = readString(value.code);
929
+ const stack = readString(value.stack);
930
+ const causes = Array.isArray(value.causes) ? value.causes.flatMap((cause) => {
931
+ const entry = readPlainRecord(cause);
932
+ const name = readString(entry?.name);
933
+ const message = typeof entry?.message === "string" ? entry.message : void 0;
934
+ if (!name || message === void 0) {
935
+ return [];
936
+ }
937
+ return [{ name, message, ...typeof entry?.status === "number" && { status: entry.status } }];
938
+ }) : [];
939
+ return {
940
+ message: typeof value.message === "string" ? value.message : "Unknown error",
941
+ type: readString(value.type) ?? MUX_AI_ERROR_TYPES.SERVER_ERROR,
942
+ source: readString(value.source) ?? MUX_AI_ERROR_SOURCES.INTERNAL,
943
+ ...dependency && { dependency },
944
+ ...code && { code },
945
+ facts: readPlainRecord(value.facts) ?? {},
946
+ retryable: value.retryable === true,
947
+ transient: value.transient === true,
948
+ causes,
949
+ ...stack && { stack }
950
+ };
951
+ }
880
952
  function classificationInit(record) {
953
+ record = readSerializedClassification(record);
881
954
  return {
882
955
  type: record.type,
883
956
  source: record.source,
@@ -888,6 +961,7 @@ function classificationInit(record) {
888
961
  };
889
962
  }
890
963
  function restoreClassification(error, record) {
964
+ record = readSerializedClassification(record);
891
965
  if (record.code) {
892
966
  Object.assign(error, { code: record.code });
893
967
  }
@@ -919,14 +993,20 @@ var MuxAiError = class _MuxAiError extends ClassifiedError {
919
993
  };
920
994
  }
921
995
  static [WORKFLOW_DESERIALIZE](value) {
922
- const error = restoreClassification(new _MuxAiError(value.message, classificationInit(value)), value);
923
- Object.assign(error, {
924
- usage: value.usage,
925
- diagnostics: value.diagnostics,
926
- ...value.finishReason !== void 0 && { finishReason: value.finishReason },
927
- ...value.rawFinishReason !== void 0 && { rawFinishReason: value.rawFinishReason }
928
- });
929
- return error;
996
+ try {
997
+ const record = readSerializedClassification(value);
998
+ const fields = readPlainRecord(value) ?? {};
999
+ const error = restoreClassification(new _MuxAiError(record.message, classificationInit(record)), record);
1000
+ Object.assign(error, {
1001
+ usage: readPlainRecord(fields.usage),
1002
+ diagnostics: readPlainRecord(fields.diagnostics),
1003
+ ...typeof fields.finishReason === "string" && { finishReason: fields.finishReason },
1004
+ ...typeof fields.rawFinishReason === "string" && { rawFinishReason: fields.rawFinishReason }
1005
+ });
1006
+ return error;
1007
+ } catch {
1008
+ return new _MuxAiError("Unknown error", { type: MUX_AI_ERROR_TYPES.SERVER_ERROR, source: MUX_AI_ERROR_SOURCES.INTERNAL });
1009
+ }
930
1010
  }
931
1011
  };
932
1012
  function extractErrorDetail(error) {
@@ -972,10 +1052,18 @@ function scrubDetail(detail, context) {
972
1052
  return "Upstream error details suppressed by safety filter";
973
1053
  }
974
1054
  function wrapError(error, message, facts) {
1055
+ if (isWorkflowControlFlowError(error)) {
1056
+ throw error;
1057
+ }
1058
+ const usage = getErrorTokenUsage(error);
1059
+ error = classifiedErrorOf(error) ?? error;
975
1060
  if (MuxAiError.is(error)) {
976
1061
  if (facts) {
977
1062
  Object.assign(error, { facts: { ...facts, ...error.facts } });
978
1063
  }
1064
+ if (usage) {
1065
+ error.usage = usage;
1066
+ }
979
1067
  throw error;
980
1068
  }
981
1069
  const wrapped = new MuxAiError(`${message}: ${scrubDetail(extractErrorDetail(error), message)}`, {
@@ -984,7 +1072,6 @@ function wrapError(error, message, facts) {
984
1072
  facts,
985
1073
  cause: error
986
1074
  });
987
- const usage = getErrorTokenUsage(error);
988
1075
  if (usage) {
989
1076
  wrapped.usage = usage;
990
1077
  }
@@ -1256,9 +1343,6 @@ var LegacyMuxAiError = class _LegacyMuxAiError extends MuxAiError {
1256
1343
  return error;
1257
1344
  }
1258
1345
  };
1259
- function isLegacyMuxAiError(value) {
1260
- return typeof value === "object" && value !== null && "__robots_error" in value && value.__robots_error === true && typeof value.publicMessage === "string";
1261
- }
1262
1346
  function legacyWrapError(error, message) {
1263
1347
  if (MuxAiError.is(error) || isLegacyMuxAiError(error)) {
1264
1348
  throw error;
@@ -2594,16 +2678,16 @@ async function resolveWorkflowCredentials(credentials) {
2594
2678
  }
2595
2679
  return { ...resolved, ...credentials };
2596
2680
  }
2597
- function readString(record, key) {
2681
+ function readString2(record, key) {
2598
2682
  const value = record?.[key];
2599
2683
  return typeof value === "string" && value.length > 0 ? value : void 0;
2600
2684
  }
2601
2685
  function resolveDirectMuxCredentials(record) {
2602
- const tokenId = readString(record, "muxTokenId");
2603
- const tokenSecret = readString(record, "muxTokenSecret");
2604
- const authorizationToken = readString(record, "muxAuthorizationToken");
2605
- const signingKey = readString(record, "muxSigningKey");
2606
- const privateKey = readString(record, "muxPrivateKey");
2686
+ const tokenId = readString2(record, "muxTokenId");
2687
+ const tokenSecret = readString2(record, "muxTokenSecret");
2688
+ const authorizationToken = readString2(record, "muxAuthorizationToken");
2689
+ const signingKey = readString2(record, "muxSigningKey");
2690
+ const privateKey = readString2(record, "muxPrivateKey");
2607
2691
  if (!tokenId && !tokenSecret && !authorizationToken && !signingKey && !privateKey) {
2608
2692
  return void 0;
2609
2693
  }
@@ -2661,13 +2745,13 @@ async function resolveMuxClient(credentials) {
2661
2745
  }
2662
2746
  function resolveProviderApiKeyFromCredentials(provider, resolved) {
2663
2747
  const record = resolved;
2664
- const openaiApiKey = readString(record, "openaiApiKey");
2665
- const basetenApiKey = readString(record, "basetenApiKey");
2666
- const anthropicApiKey = readString(record, "anthropicApiKey");
2667
- const googleApiKey = readString(record, "googleApiKey");
2668
- const googleVisionApiKey = readString(record, "googleVisionApiKey");
2669
- const hiveApiKey = readString(record, "hiveApiKey");
2670
- const elevenLabsApiKey = readString(record, "elevenLabsApiKey");
2748
+ const openaiApiKey = readString2(record, "openaiApiKey");
2749
+ const basetenApiKey = readString2(record, "basetenApiKey");
2750
+ const anthropicApiKey = readString2(record, "anthropicApiKey");
2751
+ const googleApiKey = readString2(record, "googleApiKey");
2752
+ const googleVisionApiKey = readString2(record, "googleVisionApiKey");
2753
+ const hiveApiKey = readString2(record, "hiveApiKey");
2754
+ const elevenLabsApiKey = readString2(record, "elevenLabsApiKey");
2671
2755
  const apiKeyMap = {
2672
2756
  "openai": openaiApiKey ?? env_default.OPENAI_API_KEY,
2673
2757
  "baseten": basetenApiKey ?? env_default.BASETEN_API_KEY,
@@ -2701,8 +2785,8 @@ async function resolveProviderApiKey(provider, credentials) {
2701
2785
  async function resolveMuxSigningContext(credentials) {
2702
2786
  const resolved = await resolveWorkflowCredentials(credentials);
2703
2787
  const resolvedRecord = resolved;
2704
- const keyId = readString(resolvedRecord, "muxSigningKey") ?? env_default.MUX_SIGNING_KEY;
2705
- const keySecret = readString(resolvedRecord, "muxPrivateKey") ?? env_default.MUX_PRIVATE_KEY;
2788
+ const keyId = readString2(resolvedRecord, "muxSigningKey") ?? env_default.MUX_SIGNING_KEY;
2789
+ const keySecret = readString2(resolvedRecord, "muxPrivateKey") ?? env_default.MUX_PRIVATE_KEY;
2706
2790
  if (!keyId || !keySecret) {
2707
2791
  return void 0;
2708
2792
  }
@@ -4173,7 +4257,7 @@ async function fetchTranscriptForAsset(asset, playbackId, options = {}) {
4173
4257
  try {
4174
4258
  result = await fetchTranscriptDataForUrl(transcriptUrl, { cleanTranscript, scope, classifiedErrors });
4175
4259
  } catch (error) {
4176
- if (required) {
4260
+ if (required || isWorkflowControlFlowError(error)) {
4177
4261
  throw error;
4178
4262
  }
4179
4263
  console.warn("Failed to fetch transcript:", error);
@@ -6513,6 +6597,7 @@ async function deleteTrackOnMux(assetId, trackId, credentials) {
6513
6597
  }
6514
6598
  }
6515
6599
  function restoreFailureFacts(error) {
6600
+ error = classifiedErrorOf(error) ?? error;
6516
6601
  if (!MuxAiError.is(error)) {
6517
6602
  return { restoreError: errorDetailFact(extractErrorDetail(error)) };
6518
6603
  }
@@ -6850,6 +6935,9 @@ async function editCaptionsInternal(assetId, trackId, options, collectedUsage) {
6850
6935
  restoreNote = ` The source track was restored as ${restoredTrackId}.`;
6851
6936
  restoreFacts = { sourceRestored: true, restoredTrackId };
6852
6937
  } catch (restoreError) {
6938
+ if (isWorkflowControlFlowError(restoreError)) {
6939
+ throw restoreError;
6940
+ }
6853
6941
  restoreNote = " Restoring the source track also failed.";
6854
6942
  restoreFacts = { sourceRestored: false, ...restoreFailureFacts(restoreError) };
6855
6943
  }
@@ -7865,6 +7953,11 @@ async function generateEngagementInsightsInternal(assetId, options, collectedUsa
7865
7953
  }),
7866
7954
  storyboardPromise
7867
7955
  ]);
7956
+ for (const result of [engagementResult, shotsResult, transcriptResult, storyboardResult]) {
7957
+ if (result.status === "rejected" && isWorkflowControlFlowError(result.reason)) {
7958
+ throw result.reason;
7959
+ }
7960
+ }
7868
7961
  if (engagementResult.status === "rejected") {
7869
7962
  wrapError(engagementResult.reason, `Failed to fetch engagement data for asset ${assetId}`, { assetId, timeframe });
7870
7963
  }
@@ -8248,7 +8341,10 @@ async function getCompletedShots(assetId, credentials) {
8248
8341
  return result;
8249
8342
  }
8250
8343
  console.warn(`[@mux/ai] Shots are not ready for asset ${assetId} (status: ${result.status}). Using the storyboard only.`);
8251
- } catch {
8344
+ } catch (error) {
8345
+ if (isWorkflowControlFlowError(error)) {
8346
+ throw error;
8347
+ }
8252
8348
  console.warn(`[@mux/ai] Shots lookup failed for asset ${assetId}. Using the storyboard only.`);
8253
8349
  }
8254
8350
  return void 0;
@@ -8684,6 +8780,10 @@ async function generateArtifactsInBatches(requests, collectedUsage, provider, mo
8684
8780
  }
8685
8781
  }
8686
8782
  if (failures.length > 0) {
8783
+ const controlFlow = failures.find(isWorkflowControlFlowError);
8784
+ if (controlFlow) {
8785
+ throw controlFlow;
8786
+ }
8687
8787
  for (const failure of failures.slice(1)) {
8688
8788
  const usage = getErrorTokenUsage(failure);
8689
8789
  if (usage) {
@@ -9781,6 +9881,13 @@ function allSamplesFailedError(message, failures, facts) {
9781
9881
  }
9782
9882
  async function getModerationScores(assetId, options = {}) {
9783
9883
  "use workflow";
9884
+ try {
9885
+ return await getModerationScoresInternal(assetId, options);
9886
+ } catch (error) {
9887
+ rethrowWithTokenUsage(error, []);
9888
+ }
9889
+ }
9890
+ async function getModerationScoresInternal(assetId, options) {
9784
9891
  const {
9785
9892
  provider = DEFAULT_PROVIDER2,
9786
9893
  model = provider === "openai" ? "omni-moderation-latest" : void 0,
@@ -11367,6 +11474,13 @@ async function attachDubbedCaptions(input) {
11367
11474
  }
11368
11475
  async function translateAudio(assetId, toLanguageCode, options = {}) {
11369
11476
  "use workflow";
11477
+ try {
11478
+ return await translateAudioInternal(assetId, toLanguageCode, options);
11479
+ } catch (error) {
11480
+ rethrowWithTokenUsage(error, []);
11481
+ }
11482
+ }
11483
+ async function translateAudioInternal(assetId, toLanguageCode, options) {
11370
11484
  const {
11371
11485
  provider = "elevenlabs",
11372
11486
  fromLanguageCode,
@@ -11722,6 +11836,9 @@ async function translateAudio(assetId, toLanguageCode, options = {}) {
11722
11836
  }
11723
11837
  }
11724
11838
  } catch (error) {
11839
+ if (isWorkflowControlFlowError(error)) {
11840
+ throw error;
11841
+ }
11725
11842
  captionsOutcome = captionsPresignedUrl ? { status: "failed", message: CAPTIONS_ATTACHMENT_FAILED_MESSAGE, retryable: true, replacedTracks: [] } : { status: "unavailable", message: CAPTIONS_UNAVAILABLE_MESSAGE, retryable: true };
11726
11843
  console.warn(`\u26A0\uFE0F Failed to attach dubbed captions: ${extractErrorDetail(error)}`);
11727
11844
  if (captionsPresignedUrl) {
@@ -12684,6 +12801,7 @@ export {
12684
12801
  extractTranscriptSegmentsForHotspots,
12685
12802
  findGenerateTextLengthViolation,
12686
12803
  generateChapters,
12804
+ generateText7 as generateContextualText,
12687
12805
  generateEmbeddings,
12688
12806
  generateEngagementInsights,
12689
12807
  generateText7 as generateText,
@@ -12693,6 +12811,7 @@ export {
12693
12811
  hasBurnedInCaptions,
12694
12812
  mapShotsToHotspots,
12695
12813
  measureGenerateTextLength,
12814
+ getModerationScores as moderate,
12696
12815
  normalizeTranslatedVtt,
12697
12816
  planTextRepair,
12698
12817
  profanityDetectionSchema,
@@ -12705,6 +12824,7 @@ export {
12705
12824
  runTextRepairLoop,
12706
12825
  selectGenerateTextShotFrames,
12707
12826
  shouldSplitChunkTranslationError,
12827
+ getSummaryAndTags as summarize,
12708
12828
  summarySchema,
12709
12829
  transformCueText,
12710
12830
  translateAudio,