@mux/ai 0.66.0 → 0.67.0-canary.110

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.
@@ -3,7 +3,7 @@ import { generateText, jsonSchema, NoObjectGeneratedError as NoObjectGeneratedEr
3
3
 
4
4
  // src/lib/content-policy-error.ts
5
5
  import { APICallError as APICallError2, NoObjectGeneratedError, NoOutputGeneratedError as NoOutputGeneratedError2, RetryError, TypeValidationError } from "ai";
6
- import { z as z3 } from "zod";
6
+ import { z as z4 } from "zod";
7
7
 
8
8
  // src/lib/google-errors.ts
9
9
  import { z as z2 } from "zod";
@@ -657,6 +657,8 @@ var MUX_AI_ERROR_CODES = {
657
657
  PROVIDER_UNAVAILABLE: "provider_unavailable",
658
658
  /** The provider can't process the asset's audio. The site names the dependency. Facts: `call`, `status`, `providerCode`, `reason` (`corrupt`, `unsupported_format`, `too_long`, `too_short`). */
659
659
  AUDIO_UNPROCESSABLE: "audio_unprocessable",
660
+ /** The provider says it can't process an image taken from the asset (invalid or unreadable). The site names the dependency. Facts: `call`, `providerCode`. */
661
+ IMAGE_UNPROCESSABLE: "image_unprocessable",
660
662
  /** Mux rejected the caller's access token (401), or the token lacks permission for this call (403), e.g. Mux Data access. Facts: `call`, `status`, `inputs` (`credentials`). */
661
663
  ACCOUNT_CREDENTIALS_REJECTED: "account_credentials_rejected",
662
664
  /** Mux answered 404 for something belonging to the asset (a track, a rendition, an image, its engagement data): gone, or not ready yet. A missing asset itself is `asset_not_found`. Facts: `call`, `status`. */
@@ -753,6 +755,7 @@ var MUX_AI_ERROR_CATALOG = {
753
755
  [MUX_AI_ERROR_CODES.PROVIDER_RATE_LIMITED]: { type: MUX_AI_ERROR_TYPES.CAPACITY_ERROR, source: MUX_AI_ERROR_SOURCES.UPSTREAM, siteDependency: true, transient: true, retryable: true },
754
756
  [MUX_AI_ERROR_CODES.PROVIDER_UNAVAILABLE]: { type: MUX_AI_ERROR_TYPES.CAPACITY_ERROR, source: MUX_AI_ERROR_SOURCES.UPSTREAM, siteDependency: true, transient: true, retryable: true },
755
757
  [MUX_AI_ERROR_CODES.AUDIO_UNPROCESSABLE]: { type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR, source: MUX_AI_ERROR_SOURCES.ASSET, siteDependency: true },
758
+ [MUX_AI_ERROR_CODES.IMAGE_UNPROCESSABLE]: { type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR, source: MUX_AI_ERROR_SOURCES.ASSET, siteDependency: true },
756
759
  // Mux's own responses, where the call says whose they are (see mux-video-errors.ts).
757
760
  // The access token is the caller's: only its permissions decide what Mux allows.
758
761
  [MUX_AI_ERROR_CODES.ACCOUNT_CREDENTIALS_REJECTED]: { type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR, source: MUX_AI_ERROR_SOURCES.ACCOUNT, siteDependency: true },
@@ -997,6 +1000,9 @@ function internalError(message, facts, cause) {
997
1000
  cause
998
1001
  });
999
1002
  }
1003
+ function assertNever(value, what = "value") {
1004
+ throw internalError(`Unexpected ${what}: ${String(value)}`);
1005
+ }
1000
1006
 
1001
1007
  // src/lib/dependency-error.ts
1002
1008
  function classifyDependencyFailure(init) {
@@ -1234,6 +1240,77 @@ function legacyWrapError(error, message) {
1234
1240
  throw wrapped;
1235
1241
  }
1236
1242
 
1243
+ // src/lib/openai-errors.ts
1244
+ import { z as z3 } from "zod";
1245
+ var OpenAITokenSchema = z3.string().regex(/^[\w.-]{1,64}$/);
1246
+ var OpenAIErrorBodySchema = z3.object({
1247
+ error: z3.object({
1248
+ code: OpenAITokenSchema.nullish(),
1249
+ type: OpenAITokenSchema.nullish()
1250
+ })
1251
+ });
1252
+ function parseOpenAIErrorBody(responseBody) {
1253
+ if (!responseBody) {
1254
+ return {};
1255
+ }
1256
+ let body;
1257
+ try {
1258
+ body = JSON.parse(responseBody);
1259
+ } catch {
1260
+ return {};
1261
+ }
1262
+ const parsed = OpenAIErrorBodySchema.safeParse(body);
1263
+ if (!parsed.success) {
1264
+ return {};
1265
+ }
1266
+ const { code, type } = parsed.data.error;
1267
+ return { ...code && { code }, ...type && { type } };
1268
+ }
1269
+ var OPENAI_QUOTA_CODES = /* @__PURE__ */ new Set(["credit_balance_exhausted", "organization_spend_limit_exceeded", "project_spend_limit_exceeded", "organization_usage_limit_exceeded", "insufficient_quota"]);
1270
+ var OPENAI_RATE_LIMIT_CODES = /* @__PURE__ */ new Set(["slow_down", "rate_limit_exceeded"]);
1271
+ var OPENAI_UNAVAILABLE_CODES = /* @__PURE__ */ new Set(["server_is_overloaded", "service_unavailable_error"]);
1272
+ function openAIErrorRule(status, { code, type }) {
1273
+ if (code && OPENAI_QUOTA_CODES.has(code) || !code && type === "insufficient_quota") {
1274
+ return MUX_AI_ERROR_CODES.PROVIDER_QUOTA_EXHAUSTED;
1275
+ }
1276
+ if (code && OPENAI_RATE_LIMIT_CODES.has(code)) {
1277
+ return MUX_AI_ERROR_CODES.PROVIDER_RATE_LIMITED;
1278
+ }
1279
+ if (code && OPENAI_UNAVAILABLE_CODES.has(code)) {
1280
+ return MUX_AI_ERROR_CODES.PROVIDER_UNAVAILABLE;
1281
+ }
1282
+ return status === 401 ? MUX_AI_ERROR_CODES.PROVIDER_CREDENTIALS_REJECTED : void 0;
1283
+ }
1284
+ function openAICallError(apiError, message, init) {
1285
+ const body = parseOpenAIErrorBody(apiError.responseBody);
1286
+ const providerCode = body.code ?? body.type;
1287
+ const code = openAIErrorRule(apiError.statusCode, body);
1288
+ return dependencyError(message, {
1289
+ dependency: MUX_AI_ERROR_DEPENDENCIES.AI_PROVIDER,
1290
+ call: init.call,
1291
+ status: apiError.statusCode,
1292
+ requestId: requestIdOf(apiError.responseHeaders),
1293
+ facts: { ...init.facts, ...providerCode && { providerCode } },
1294
+ ...code && { code },
1295
+ cause: init.cause ?? apiError
1296
+ });
1297
+ }
1298
+ function openAIFetchError(message, init) {
1299
+ const body = parseOpenAIErrorBody(init.body);
1300
+ const providerCode = body.code ?? body.type;
1301
+ const code = init.status === void 0 ? void 0 : openAIErrorRule(init.status, body);
1302
+ return dependencyError(message, {
1303
+ dependency: MUX_AI_ERROR_DEPENDENCIES.AI_PROVIDER,
1304
+ call: init.call,
1305
+ status: init.status,
1306
+ requestId: init.requestId,
1307
+ timedOut: init.timedOut,
1308
+ facts: { ...init.facts, ...providerCode && { providerCode } },
1309
+ ...code && { code },
1310
+ cause: init.cause
1311
+ });
1312
+ }
1313
+
1237
1314
  // src/lib/retry.ts
1238
1315
  import { APICallError, DownloadError, NoOutputGeneratedError } from "ai";
1239
1316
  var DEFAULT_RETRY_OPTIONS = {
@@ -1298,50 +1375,50 @@ async function withRetry(fn, {
1298
1375
  }
1299
1376
 
1300
1377
  // src/lib/content-policy-error.ts
1301
- var PolicyTokenSchema = z3.string().trim().min(1).max(64).regex(/^[A-Z0-9_]+$/);
1302
- var SafetyRatingSchema = z3.object({
1378
+ var PolicyTokenSchema = z4.string().trim().min(1).max(64).regex(/^[A-Z0-9_]+$/);
1379
+ var SafetyRatingSchema = z4.object({
1303
1380
  category: PolicyTokenSchema.nullish(),
1304
- blocked: z3.boolean().nullish()
1381
+ blocked: z4.boolean().nullish()
1305
1382
  });
1306
- var ContentPolicyResponseSchema = z3.object({
1307
- promptFeedback: z3.object({
1383
+ var ContentPolicyResponseSchema = z4.object({
1384
+ promptFeedback: z4.object({
1308
1385
  blockReason: PolicyTokenSchema.nullish(),
1309
- safetyRatings: z3.array(SafetyRatingSchema).max(32).nullish()
1386
+ safetyRatings: z4.array(SafetyRatingSchema).max(32).nullish()
1310
1387
  }).nullish(),
1311
- candidates: z3.array(z3.object({
1388
+ candidates: z4.array(z4.object({
1312
1389
  finishReason: PolicyTokenSchema.nullish(),
1313
- safetyRatings: z3.array(SafetyRatingSchema).max(32).nullish()
1390
+ safetyRatings: z4.array(SafetyRatingSchema).max(32).nullish()
1314
1391
  })).max(8).nullish()
1315
1392
  });
1316
- var ContentPolicyUsageResponseSchema = z3.object({
1317
- usageMetadata: z3.object({
1318
- promptTokenCount: z3.number().finite().nonnegative().nullish(),
1319
- candidatesTokenCount: z3.number().finite().nonnegative().nullish(),
1320
- totalTokenCount: z3.number().finite().nonnegative().nullish(),
1321
- cachedContentTokenCount: z3.number().finite().nonnegative().nullish(),
1322
- thoughtsTokenCount: z3.number().finite().nonnegative().nullish()
1393
+ var ContentPolicyUsageResponseSchema = z4.object({
1394
+ usageMetadata: z4.object({
1395
+ promptTokenCount: z4.number().finite().nonnegative().nullish(),
1396
+ candidatesTokenCount: z4.number().finite().nonnegative().nullish(),
1397
+ totalTokenCount: z4.number().finite().nonnegative().nullish(),
1398
+ cachedContentTokenCount: z4.number().finite().nonnegative().nullish(),
1399
+ thoughtsTokenCount: z4.number().finite().nonnegative().nullish()
1323
1400
  }).nullish()
1324
1401
  });
1325
- var OpenAIRefusalResponseSchema = z3.object({
1326
- output: z3.array(z3.object({
1327
- type: z3.string(),
1328
- content: z3.array(z3.object({ type: z3.string() })).max(32).nullish()
1402
+ var OpenAIRefusalResponseSchema = z4.object({
1403
+ output: z4.array(z4.object({
1404
+ type: z4.string(),
1405
+ content: z4.array(z4.object({ type: z4.string() })).max(32).nullish()
1329
1406
  })).max(8)
1330
1407
  });
1331
- var OpenAIUsageResponseSchema = z3.object({
1332
- usage: z3.object({
1333
- input_tokens: z3.number().finite().nonnegative(),
1334
- output_tokens: z3.number().finite().nonnegative(),
1335
- total_tokens: z3.number().finite().nonnegative().optional(),
1336
- input_tokens_details: z3.object({
1337
- cached_tokens: z3.number().finite().nonnegative().nullish(),
1338
- cache_write_tokens: z3.number().finite().nonnegative().nullish()
1408
+ var OpenAIUsageResponseSchema = z4.object({
1409
+ usage: z4.object({
1410
+ input_tokens: z4.number().finite().nonnegative(),
1411
+ output_tokens: z4.number().finite().nonnegative(),
1412
+ total_tokens: z4.number().finite().nonnegative().optional(),
1413
+ input_tokens_details: z4.object({
1414
+ cached_tokens: z4.number().finite().nonnegative().nullish(),
1415
+ cache_write_tokens: z4.number().finite().nonnegative().nullish()
1339
1416
  }).nullish(),
1340
- output_tokens_details: z3.object({ reasoning_tokens: z3.number().finite().nonnegative().nullish() }).nullish()
1417
+ output_tokens_details: z4.object({ reasoning_tokens: z4.number().finite().nonnegative().nullish() }).nullish()
1341
1418
  })
1342
1419
  });
1343
- var OpenAIPolicyErrorSchema = z3.object({
1344
- error: z3.object({ code: z3.enum(["content_policy_violation", "content_filter"]) })
1420
+ var OpenAIPolicyErrorSchema = z4.object({
1421
+ error: z4.object({ code: z4.enum(["content_policy_violation", "content_filter"]) })
1345
1422
  });
1346
1423
  var OPENAI_PROMPT_FLAG = /invalid prompt:.*flagged as potentially violating/i;
1347
1424
  var OPENAI_PROMPT_FLAGGED = "PROMPT_FLAGGED";
@@ -1518,6 +1595,8 @@ function classifyModelCallError(error, context) {
1518
1595
  switch (context.provider) {
1519
1596
  case "google":
1520
1597
  return withUsage(googleCallError(apiError, message, { call: context.call, facts: modelCallFacts(context), cause: error }), getErrorTokenUsage(error));
1598
+ case "openai":
1599
+ return withUsage(openAICallError(apiError, message, { call: context.call, facts: modelCallFacts(context), cause: error }), getErrorTokenUsage(error));
1521
1600
  default:
1522
1601
  return void 0;
1523
1602
  }
@@ -2008,17 +2087,17 @@ function repairText(options) {
2008
2087
  // src/workflows/ask-questions.ts
2009
2088
  import { generateText as generateText2, Output as Output2 } from "ai";
2010
2089
  import dedent2 from "dedent";
2011
- import { z as z5 } from "zod";
2090
+ import { z as z6 } from "zod";
2012
2091
 
2013
2092
  // src/lib/image-download.ts
2014
2093
  import pRetry, { AbortError } from "p-retry";
2015
2094
 
2016
2095
  // src/lib/mux-video-errors.ts
2017
- import { z as z4 } from "zod";
2018
- var MuxTokenSchema = z4.string().regex(/^[\w.-]{1,64}$/);
2019
- var MuxApiErrorSchema = z4.object({
2020
- error: z4.object({
2021
- error: z4.object({ type: MuxTokenSchema })
2096
+ import { z as z5 } from "zod";
2097
+ var MuxTokenSchema = z5.string().regex(/^[\w.-]{1,64}$/);
2098
+ var MuxApiErrorSchema = z5.object({
2099
+ error: z5.object({
2100
+ error: z5.object({ type: MuxTokenSchema })
2022
2101
  })
2023
2102
  });
2024
2103
  function muxVideoErrorFacts(error) {
@@ -2216,12 +2295,12 @@ function imageDownloadError(failure, call, cause) {
2216
2295
  { call, cause, timedOut: failure?.timedOut }
2217
2296
  );
2218
2297
  }
2219
- async function downloadImagesAsBase64(urls, options = {}, maxConcurrent = 5) {
2298
+ async function downloadImagesAsBase64(urls, options = {}, maxConcurrent = 5, errorOptions = {}) {
2220
2299
  "use step";
2221
2300
  const results = [];
2222
2301
  for (let i = 0; i < urls.length; i += maxConcurrent) {
2223
2302
  const batch = urls.slice(i, i + maxConcurrent);
2224
- const batchPromises = batch.map((url) => downloadImageAsBase64(url, options));
2303
+ const batchPromises = batch.map((url) => downloadImageAsBase64(url, options, errorOptions));
2225
2304
  const batchResults = await Promise.all(batchPromises);
2226
2305
  results.push(...batchResults);
2227
2306
  }
@@ -4067,17 +4146,17 @@ var ASK_QUESTIONS_MAX_QUESTION_LENGTH = 600;
4067
4146
  var ASK_QUESTIONS_MAX_QUESTIONS_PER_CALL = 50;
4068
4147
  var ASK_QUESTIONS_DEFAULT_MAX_ANSWER_OPTION_LENGTH = 150;
4069
4148
  var ASK_QUESTIONS_DEFAULT_MAX_FREE_FORM_ANSWER_LENGTH = 500;
4070
- var questionAnswerSchema = z5.object({
4071
- question: z5.string().describe("The full text of the original question"),
4072
- answer: z5.string().nullable(),
4073
- confidence: z5.number(),
4074
- reasoning: z5.string().max(1e3),
4075
- skipped: z5.boolean()
4149
+ var questionAnswerSchema = z6.object({
4150
+ question: z6.string().describe("The full text of the original question"),
4151
+ answer: z6.string().nullable(),
4152
+ confidence: z6.number(),
4153
+ reasoning: z6.string().max(1e3),
4154
+ skipped: z6.boolean()
4076
4155
  });
4077
4156
  var SKIP_SENTINEL = "__SKIPPED__";
4078
4157
  function createAskQuestionsSchema(answerSchema) {
4079
- return z5.object({
4080
- answers: z5.array(
4158
+ return z6.object({
4159
+ answers: z6.array(
4081
4160
  questionAnswerSchema.extend({
4082
4161
  answer: answerSchema
4083
4162
  })
@@ -4452,12 +4531,12 @@ function buildResponseSchemaForQuestions(normalizedQuestions, maxFreeFormAnswerL
4452
4531
  SKIP_SENTINEL.length,
4453
4532
  longestConstrained
4454
4533
  );
4455
- return createAskQuestionsSchema(z5.string().min(1).max(schemaMax));
4534
+ return createAskQuestionsSchema(z6.string().min(1).max(schemaMax));
4456
4535
  }
4457
4536
  const allowed = Array.from(
4458
4537
  new Set(normalizedQuestions.flatMap(allowedAnswersForQuestion))
4459
4538
  );
4460
- return createAskQuestionsSchema(z5.enum([...allowed, SKIP_SENTINEL]));
4539
+ return createAskQuestionsSchema(z6.enum([...allowed, SKIP_SENTINEL]));
4461
4540
  }
4462
4541
  async function analyzeQuestions({
4463
4542
  provider,
@@ -4759,11 +4838,11 @@ async function askQuestionsInternal(assetId, questions, options, collectedUsage)
4759
4838
  // src/workflows/burned-in-captions.ts
4760
4839
  import { generateText as generateText3, Output as Output3 } from "ai";
4761
4840
  import dedent3 from "dedent";
4762
- import { z as z6 } from "zod";
4763
- var burnedInCaptionsSchema = z6.object({
4764
- hasBurnedInCaptions: z6.boolean(),
4765
- confidence: z6.number(),
4766
- detectedLanguage: z6.string().max(100).nullable()
4841
+ import { z as z7 } from "zod";
4842
+ var burnedInCaptionsSchema = z7.object({
4843
+ hasBurnedInCaptions: z7.boolean(),
4844
+ confidence: z7.number(),
4845
+ detectedLanguage: z7.string().max(100).nullable()
4767
4846
  });
4768
4847
  var SYSTEM_PROMPT2 = promptDedent`
4769
4848
  <role>
@@ -4860,7 +4939,7 @@ function buildUserPrompt2(promptOverrides) {
4860
4939
  var DEFAULT_PROVIDER = "openai";
4861
4940
  async function fetchImageAsBase642(imageUrl, imageDownloadOptions) {
4862
4941
  "use step";
4863
- const downloadResult = await downloadImageAsBase64(imageUrl, imageDownloadOptions);
4942
+ const downloadResult = await downloadImageAsBase64(imageUrl, imageDownloadOptions, { classifiedErrors: true, call: "fetch_storyboard" });
4864
4943
  return downloadResult.base64Data;
4865
4944
  }
4866
4945
  async function analyzeStoryboard({
@@ -4873,6 +4952,7 @@ async function analyzeStoryboard({
4873
4952
  }) {
4874
4953
  "use step";
4875
4954
  const model = await createLanguageModelFromConfig(provider, modelId, credentials);
4955
+ const context = { call: "detect_burned_in_captions", provider, model: modelId };
4876
4956
  const response = await withContentPolicyAwareRetry(() => generateText3({
4877
4957
  model,
4878
4958
  maxRetries: 0,
@@ -4888,8 +4968,10 @@ async function analyzeStoryboard({
4888
4968
  ]
4889
4969
  }
4890
4970
  ]
4891
- }));
4892
- const output = getGeneratedOutputWithContentPolicyHandling(response);
4971
+ }), void 0, context).catch((error) => {
4972
+ throw modelStepError(error, "Burned-in captions model call failed", { ...context });
4973
+ });
4974
+ const output = getGeneratedOutputWithContentPolicyHandling(response, context);
4893
4975
  const unexpectedKeys = detectUnexpectedKeysFromRawText(
4894
4976
  response.text,
4895
4977
  burnedInCaptionsSchema.keyof().options
@@ -4936,12 +5018,13 @@ async function hasBurnedInCaptionsInternal(assetId, options, collectedUsage) {
4936
5018
  model,
4937
5019
  provider
4938
5020
  });
4939
- const { asset: assetData, playbackId, policy } = await getPlaybackIdForAsset(assetId, credentials, options.assetSnapshot);
5021
+ const { asset: assetData, playbackId, policy } = await getPlaybackIdForAsset(assetId, credentials, options.assetSnapshot, { classifiedErrors: true });
4940
5022
  const assetDurationSeconds = getAssetDurationSecondsFromAsset(assetData);
4941
5023
  const storyboardScope = resolveRenderableVideoScope(
4942
5024
  scope,
4943
5025
  assetDurationSeconds,
4944
- getVideoTrackDurationSecondsFromAsset(assetData)
5026
+ getVideoTrackDurationSecondsFromAsset(assetData),
5027
+ { classifiedErrors: true, assetId }
4945
5028
  );
4946
5029
  const imageUrl = await getStoryboardUrl(
4947
5030
  playbackId,
@@ -4950,31 +5033,17 @@ async function hasBurnedInCaptionsInternal(assetId, options, collectedUsage) {
4950
5033
  credentials,
4951
5034
  storyboardScope
4952
5035
  );
4953
- let analysisResponse;
4954
- if (imageSubmissionMode === "base64") {
4955
- const base64Data = await fetchImageAsBase642(imageUrl, imageDownloadOptions);
4956
- analysisResponse = await analyzeStoryboard({
4957
- imageDataUrl: base64Data,
4958
- provider: modelConfig.provider,
4959
- modelId: modelConfig.modelId,
4960
- userPrompt,
4961
- systemPrompt: SYSTEM_PROMPT2,
4962
- credentials
4963
- });
4964
- } else {
4965
- analysisResponse = await analyzeStoryboard({
4966
- imageDataUrl: imageUrl,
4967
- provider: modelConfig.provider,
4968
- modelId: modelConfig.modelId,
4969
- userPrompt,
4970
- systemPrompt: SYSTEM_PROMPT2,
4971
- credentials
4972
- });
4973
- }
5036
+ const imageDataUrl = imageSubmissionMode === "base64" ? await fetchImageAsBase642(imageUrl, imageDownloadOptions) : imageUrl;
5037
+ const modelFacts = { call: "detect_burned_in_captions", provider: modelConfig.provider, model: modelConfig.modelId, assetId };
5038
+ const analysisResponse = await analyzeStoryboard({
5039
+ imageDataUrl,
5040
+ provider: modelConfig.provider,
5041
+ modelId: modelConfig.modelId,
5042
+ userPrompt,
5043
+ systemPrompt: SYSTEM_PROMPT2,
5044
+ credentials
5045
+ }).catch((error) => wrapError(error, `Failed to analyze storyboard with ${modelConfig.provider}`, modelFacts));
4974
5046
  collectedUsage.push(analysisResponse.usage);
4975
- if (!analysisResponse.result) {
4976
- throw new Error("No analysis result received from AI provider");
4977
- }
4978
5047
  const safety = createSafetyReporter();
4979
5048
  if (analysisResponse.unexpectedKeys.length > 0) {
4980
5049
  console.warn(
@@ -5003,7 +5072,7 @@ async function hasBurnedInCaptionsInternal(assetId, options, collectedUsage) {
5003
5072
  // src/workflows/chapters.ts
5004
5073
  import { generateText as generateText4, Output as Output4 } from "ai";
5005
5074
  import dedent5 from "dedent";
5006
- import { z as z7 } from "zod";
5075
+ import { z as z8 } from "zod";
5007
5076
 
5008
5077
  // src/prompts/chapters.ts
5009
5078
  import dedent4 from "dedent";
@@ -5028,12 +5097,12 @@ function createChapterGuidance({
5028
5097
  }
5029
5098
 
5030
5099
  // src/workflows/chapters.ts
5031
- var chapterSchema = z7.object({
5032
- startTime: z7.number(),
5033
- title: z7.string().max(300)
5100
+ var chapterSchema = z8.object({
5101
+ startTime: z8.number(),
5102
+ title: z8.string().max(300)
5034
5103
  });
5035
- var chaptersSchema = z7.object({
5036
- chapters: z7.array(chapterSchema)
5104
+ var chaptersSchema = z8.object({
5105
+ chapters: z8.array(chapterSchema)
5037
5106
  });
5038
5107
  async function generateChaptersWithAI({
5039
5108
  provider,
@@ -5408,7 +5477,7 @@ async function generateChaptersInternal(assetId, options, collectedUsage) {
5408
5477
 
5409
5478
  // src/workflows/edit-captions.ts
5410
5479
  import { generateText as generateText5, Output as Output5 } from "ai";
5411
- import { z as z8 } from "zod";
5480
+ import { z as z9 } from "zod";
5412
5481
 
5413
5482
  // src/lib/mux-tracks.ts
5414
5483
  function trackWriteFailure(outcome) {
@@ -6097,8 +6166,8 @@ async function createPresignedGetUrlWithStorageAdapter(input, adapter) {
6097
6166
  }
6098
6167
 
6099
6168
  // src/workflows/edit-captions.ts
6100
- var profanityDetectionSchema = z8.object({
6101
- profanity: z8.array(z8.string().max(100)).describe(
6169
+ var profanityDetectionSchema = z9.object({
6170
+ profanity: z9.array(z9.string().max(100)).describe(
6102
6171
  "Unique profane words or short phrases exactly as they appear in the transcript text. Include each distinct form only once (e.g., if 'fuck' and 'fucking' both appear, list both)."
6103
6172
  )
6104
6173
  });
@@ -7171,7 +7240,7 @@ async function generateVideoEmbeddings(assetId, options = {}) {
7171
7240
  // src/workflows/engagement-insights.ts
7172
7241
  import { generateText as generateText6, Output as Output6 } from "ai";
7173
7242
  import dedent6 from "dedent";
7174
- import { z as z9 } from "zod";
7243
+ import { z as z10 } from "zod";
7175
7244
 
7176
7245
  // src/primitives/heatmap.ts
7177
7246
  async function getHeatmapForAsset(assetId, options = {}) {
@@ -7313,20 +7382,20 @@ async function getShotsForAsset(assetId, options = {}) {
7313
7382
  }
7314
7383
 
7315
7384
  // src/workflows/engagement-insights.ts
7316
- var aiMomentInsightSchema = z9.object({
7317
- hotspotIndex: z9.number(),
7318
- startMs: z9.number(),
7319
- endMs: z9.number(),
7320
- timestamp: z9.string(),
7321
- engagementScore: z9.number(),
7322
- insight: z9.string().max(1e3)
7385
+ var aiMomentInsightSchema = z10.object({
7386
+ hotspotIndex: z10.number(),
7387
+ startMs: z10.number(),
7388
+ endMs: z10.number(),
7389
+ timestamp: z10.string(),
7390
+ engagementScore: z10.number(),
7391
+ insight: z10.string().max(1e3)
7323
7392
  });
7324
- var aiOverallInsightSchema = z9.object({
7325
- summary: z9.string().max(2e3),
7326
- trends: z9.array(z9.string().max(500))
7393
+ var aiOverallInsightSchema = z10.object({
7394
+ summary: z10.string().max(2e3),
7395
+ trends: z10.array(z10.string().max(500))
7327
7396
  });
7328
- var engagementInsightsSchema = z9.object({
7329
- momentInsights: z9.array(aiMomentInsightSchema),
7397
+ var engagementInsightsSchema = z10.object({
7398
+ momentInsights: z10.array(aiMomentInsightSchema),
7330
7399
  overallInsight: aiOverallInsightSchema
7331
7400
  });
7332
7401
  var SYSTEM_PROMPT4 = promptDedent`
@@ -7890,7 +7959,7 @@ async function generateEngagementInsightsInternal(assetId, options, collectedUsa
7890
7959
 
7891
7960
  // src/workflows/generate-text.ts
7892
7961
  import { APICallError as APICallError4, generateText as generateTextWithModel, Output as Output7 } from "ai";
7893
- import { z as z10 } from "zod";
7962
+ import { z as z11 } from "zod";
7894
7963
  var GENERATE_TEXT_MAX_VARIANTS = 5;
7895
7964
  var GENERATE_TEXT_MAX_ARTIFACTS = 5;
7896
7965
  var GENERATE_TEXT_MAX_INSTRUCTIONS_CHARS = 500;
@@ -8065,14 +8134,14 @@ async function getCompletedShots(assetId, credentials) {
8065
8134
  }
8066
8135
  return void 0;
8067
8136
  }
8068
- var briefSchema = z10.object({
8069
- centralIdea: z10.string().max(500),
8070
- readerValue: z10.string().max(500),
8071
- keyPoints: z10.array(z10.string().max(500)),
8072
- sourceSpecifics: z10.array(z10.string().max(500)),
8073
- visualContext: z10.array(z10.string().max(500)),
8074
- voiceSignals: z10.array(z10.string().max(300)),
8075
- claimsToQualify: z10.array(z10.string().max(500))
8137
+ var briefSchema = z11.object({
8138
+ centralIdea: z11.string().max(500),
8139
+ readerValue: z11.string().max(500),
8140
+ keyPoints: z11.array(z11.string().max(500)),
8141
+ sourceSpecifics: z11.array(z11.string().max(500)),
8142
+ visualContext: z11.array(z11.string().max(500)),
8143
+ voiceSignals: z11.array(z11.string().max(300)),
8144
+ claimsToQualify: z11.array(z11.string().max(500))
8076
8145
  });
8077
8146
  var BRIEF_LIST_LIMITS = {
8078
8147
  keyPoints: 8,
@@ -8333,7 +8402,7 @@ async function extractBriefWithModel(args) {
8333
8402
  };
8334
8403
  });
8335
8404
  }
8336
- var artifactSchema = z10.object({ content: z10.string() });
8405
+ var artifactSchema = z11.object({ content: z11.string() });
8337
8406
  async function generateArtifactWithModel(args) {
8338
8407
  "use step";
8339
8408
  const diagnostics = { phase: "draft", provider: args.provider, modelId: args.modelId };
@@ -8594,7 +8663,71 @@ async function generateTextInternal(assetId, rawOptions, collectedUsage) {
8594
8663
  }
8595
8664
 
8596
8665
  // src/workflows/moderation.ts
8597
- import { z as z11 } from "zod";
8666
+ import { z as z12 } from "zod";
8667
+
8668
+ // src/lib/google-vision-errors.ts
8669
+ var GOOGLE_RPC_INVALID_ARGUMENT = "3";
8670
+ var GOOGLE_RPC_RESOURCE_EXHAUSTED = "8";
8671
+ var GOOGLE_RPC_UNAVAILABLE = "14";
8672
+ function googleVisionImageErrorRule(rpcCode, { inline }) {
8673
+ switch (rpcCode) {
8674
+ // Per image, not per request. With the image sent inline, it's that image that can't be
8675
+ // used. With a URL, Vision fetches the image itself and reports a failed fetch with the
8676
+ // same code ("The URL does not appear to be accessible by us"), which says nothing about
8677
+ // the image, so it stays `dependency_response_failed`.
8678
+ case GOOGLE_RPC_INVALID_ARGUMENT:
8679
+ return inline ? { code: MUX_AI_ERROR_CODES.IMAGE_UNPROCESSABLE } : void 0;
8680
+ case GOOGLE_RPC_UNAVAILABLE:
8681
+ return { code: MUX_AI_ERROR_CODES.PROVIDER_UNAVAILABLE };
8682
+ // A rate limit or a spent quota, which Google can't tell apart here: "generally don't retry".
8683
+ case GOOGLE_RPC_RESOURCE_EXHAUSTED:
8684
+ return { retryable: false };
8685
+ default:
8686
+ return void 0;
8687
+ }
8688
+ }
8689
+ function googleVisionCallError(message, init) {
8690
+ const answered = init.answered === true;
8691
+ const rule = answered ? googleVisionImageErrorRule(init.rpcCode, { inline: init.inline === true }) : void 0;
8692
+ return dependencyError(message, {
8693
+ dependency: MUX_AI_ERROR_DEPENDENCIES.AI_PROVIDER,
8694
+ call: init.call,
8695
+ status: init.status,
8696
+ requestId: init.requestId,
8697
+ timedOut: init.timedOut,
8698
+ facts: { provider: "google-vision-api", ...init.facts, ...init.rpcCode && { providerCode: init.rpcCode } },
8699
+ ...answered && { code: rule?.code ?? MUX_AI_ERROR_CODES.DEPENDENCY_RESPONSE_FAILED },
8700
+ ...rule?.retryable !== void 0 && { retryable: rule.retryable },
8701
+ cause: init.cause
8702
+ });
8703
+ }
8704
+
8705
+ // src/lib/hive-errors.ts
8706
+ function hiveErrorRule(status) {
8707
+ switch (status) {
8708
+ case 405:
8709
+ return MUX_AI_ERROR_CODES.PROVIDER_QUOTA_EXHAUSTED;
8710
+ case 403:
8711
+ return MUX_AI_ERROR_CODES.PROVIDER_CREDENTIALS_REJECTED;
8712
+ case 429:
8713
+ return MUX_AI_ERROR_CODES.PROVIDER_RATE_LIMITED;
8714
+ default:
8715
+ return void 0;
8716
+ }
8717
+ }
8718
+ function hiveCallError(message, init) {
8719
+ const code = init.answered ? MUX_AI_ERROR_CODES.DEPENDENCY_RESPONSE_FAILED : hiveErrorRule(init.status);
8720
+ return dependencyError(message, {
8721
+ dependency: MUX_AI_ERROR_DEPENDENCIES.AI_PROVIDER,
8722
+ call: init.call,
8723
+ status: init.status,
8724
+ requestId: init.requestId,
8725
+ timedOut: init.timedOut,
8726
+ facts: { provider: "hive", ...init.facts, ...init.returnCode && { providerCode: init.returnCode } },
8727
+ ...code && { code },
8728
+ cause: init.cause
8729
+ });
8730
+ }
8598
8731
 
8599
8732
  // src/lib/sampling-plan.ts
8600
8733
  var DEFAULT_FPS = 30;
@@ -8703,7 +8836,6 @@ var DEFAULT_THRESHOLDS = {
8703
8836
  violence: 0.8
8704
8837
  };
8705
8838
  var DEFAULT_PROVIDER2 = "openai";
8706
- var OPENAI_MODERATION_RETRIABLE_STATUS_CODES = /* @__PURE__ */ new Set([408, 429, 500, 502, 503, 504]);
8707
8839
  var OPENAI_MODERATION_MAX_RETRIES = 2;
8708
8840
  var OPENAI_MODERATION_BASE_DELAY_MS = 750;
8709
8841
  var OPENAI_MODERATION_MAX_DELAY_MS = 3e3;
@@ -8748,19 +8880,23 @@ var HIVE_VIOLENCE_CATEGORIES = [
8748
8880
  "yes_self_harm",
8749
8881
  "garm_death_injury_or_military_conflict"
8750
8882
  ];
8751
- var OpenAIModerationRequestError = class extends Error {
8752
- constructor(message, {
8753
- status,
8754
- retriable
8755
- }) {
8756
- super(message);
8757
- this.name = "OpenAIModerationRequestError";
8758
- this.status = status;
8759
- this.retriable = retriable;
8760
- }
8761
- };
8762
- function isRetriableOpenAIModerationStatus(status) {
8763
- return OPENAI_MODERATION_RETRIABLE_STATUS_CODES.has(status);
8883
+ function unusableResponseError(message, call, provider) {
8884
+ return new MuxAiError(message, {
8885
+ code: MUX_AI_ERROR_CODES.MODEL_OUTPUT_INVALID,
8886
+ type: MUX_AI_ERROR_TYPES.PROCESSING_ERROR,
8887
+ source: MUX_AI_ERROR_SOURCES.UPSTREAM,
8888
+ dependency: MUX_AI_ERROR_DEPENDENCIES.AI_PROVIDER,
8889
+ facts: { call, provider }
8890
+ });
8891
+ }
8892
+ var RETRIED_WITHIN_CALL = /* @__PURE__ */ new WeakSet();
8893
+ function sampleFailureOf(error) {
8894
+ return MuxAiError.is(error) ? error : void 0;
8895
+ }
8896
+ var ProviderCodeSchema = z12.string().regex(/^[\w.-]{1,64}$/);
8897
+ function providerCodeOf(value) {
8898
+ const parsed = ProviderCodeSchema.safeParse(typeof value === "number" ? String(value) : value);
8899
+ return parsed.success ? parsed.data : void 0;
8764
8900
  }
8765
8901
  function compactBodySnippet(body, maxLength = 180) {
8766
8902
  const compact = body.replace(/\s+/g, " ").trim();
@@ -8769,34 +8905,45 @@ function compactBodySnippet(body, maxLength = 180) {
8769
8905
  }
8770
8906
  return compact.length > maxLength ? `${compact.slice(0, maxLength)}...` : compact;
8771
8907
  }
8772
- function parseOpenAIModerationResponse(bodyText, status, statusText) {
8908
+ function unreadableOpenAIResponseError(message, res, call, { retryWithinCall }) {
8909
+ if (!res.ok) {
8910
+ return openAIFetchError(message, { call, status: res.status, requestId: requestIdOf(res.headers), facts: { provider: "openai" } });
8911
+ }
8912
+ const error = unusableResponseError(message, call, "openai");
8913
+ if (retryWithinCall) {
8914
+ RETRIED_WITHIN_CALL.add(error);
8915
+ }
8916
+ return error;
8917
+ }
8918
+ function parseOpenAIModerationResponse(bodyText, res, call) {
8919
+ const { status, statusText } = res;
8773
8920
  if (!bodyText.trim()) {
8774
- throw new OpenAIModerationRequestError(
8775
- `OpenAI moderation returned an empty response (${status} ${statusText}).`,
8776
- { status, retriable: isRetriableOpenAIModerationStatus(status) }
8777
- );
8921
+ throw unreadableOpenAIResponseError(`OpenAI moderation returned an empty response (${status} ${statusText}).`, res, call, { retryWithinCall: false });
8778
8922
  }
8779
8923
  try {
8780
8924
  return JSON.parse(bodyText);
8781
8925
  } catch {
8782
- throw new OpenAIModerationRequestError(
8926
+ throw unreadableOpenAIResponseError(
8783
8927
  `OpenAI moderation returned non-JSON response (${status} ${statusText}): ${compactBodySnippet(bodyText)}`,
8784
- { status, retriable: true }
8928
+ res,
8929
+ call,
8930
+ { retryWithinCall: true }
8785
8931
  );
8786
8932
  }
8787
8933
  }
8788
- var OpenAIModerationResponseSchema = z11.object({
8789
- results: z11.array(z11.object({
8790
- category_scores: z11.object({
8791
- sexual: z11.number().finite().nullish(),
8792
- violence: z11.number().finite().nullish()
8934
+ var OpenAIModerationResponseSchema = z12.object({
8935
+ results: z12.array(z12.object({
8936
+ category_scores: z12.object({
8937
+ sexual: z12.number().finite().nullish(),
8938
+ violence: z12.number().finite().nullish()
8793
8939
  })
8794
8940
  }))
8795
8941
  });
8796
8942
  async function callOpenAIModerationApi({
8797
8943
  model,
8798
8944
  input,
8799
- credentials
8945
+ credentials,
8946
+ call
8800
8947
  }) {
8801
8948
  "use step";
8802
8949
  const apiKey = await getApiKeyFromEnv("openai", credentials);
@@ -8816,35 +8963,34 @@ async function callOpenAIModerationApi({
8816
8963
  })
8817
8964
  });
8818
8965
  } catch (error) {
8819
- throw new OpenAIModerationRequestError(
8966
+ throw openAIFetchError(
8820
8967
  `OpenAI moderation request failed: ${error instanceof Error ? error.message : String(error)}`,
8821
- { retriable: true }
8968
+ { call, facts: { provider: "openai" }, cause: error }
8822
8969
  );
8823
8970
  }
8824
- const bodyText = await res.text();
8825
- const json = parseOpenAIModerationResponse(bodyText, res.status, res.statusText);
8971
+ let bodyText;
8972
+ try {
8973
+ bodyText = await res.text();
8974
+ } catch (error) {
8975
+ throw openAIFetchError(
8976
+ `OpenAI moderation response could not be read: ${error instanceof Error ? error.message : String(error)}`,
8977
+ { call, requestId: requestIdOf(res.headers), facts: { provider: "openai" }, cause: error }
8978
+ );
8979
+ }
8980
+ const json = parseOpenAIModerationResponse(bodyText, res, call);
8826
8981
  if (!res.ok) {
8827
- throw new OpenAIModerationRequestError(
8982
+ throw openAIFetchError(
8828
8983
  `OpenAI moderation error: ${res.status} ${res.statusText} - ${JSON.stringify(json)}`,
8829
- {
8830
- status: res.status,
8831
- retriable: isRetriableOpenAIModerationStatus(res.status)
8832
- }
8984
+ { call, status: res.status, requestId: requestIdOf(res.headers), body: bodyText, facts: { provider: "openai" } }
8833
8985
  );
8834
8986
  }
8835
8987
  const parsed = OpenAIModerationResponseSchema.safeParse(json);
8836
8988
  if (!parsed.success) {
8837
- throw new OpenAIModerationRequestError(
8838
- `OpenAI moderation returned an unexpected response shape: ${compactBodySnippet(bodyText)}`,
8839
- { status: res.status, retriable: false }
8840
- );
8989
+ throw unusableResponseError(`OpenAI moderation returned an unexpected response shape: ${compactBodySnippet(bodyText)}`, call, "openai");
8841
8990
  }
8842
8991
  const expectedResultCount = Array.isArray(input) ? input.length : 1;
8843
8992
  if (parsed.data.results.length !== expectedResultCount) {
8844
- throw new OpenAIModerationRequestError(
8845
- `OpenAI moderation returned ${parsed.data.results.length} result(s) for ${expectedResultCount} input(s).`,
8846
- { status: res.status, retriable: false }
8847
- );
8993
+ throw unusableResponseError(`OpenAI moderation returned ${parsed.data.results.length} result(s) for ${expectedResultCount} input(s).`, call, "openai");
8848
8994
  }
8849
8995
  return parsed.data;
8850
8996
  },
@@ -8852,10 +8998,27 @@ async function callOpenAIModerationApi({
8852
8998
  maxRetries: OPENAI_MODERATION_MAX_RETRIES,
8853
8999
  baseDelay: OPENAI_MODERATION_BASE_DELAY_MS,
8854
9000
  maxDelay: OPENAI_MODERATION_MAX_DELAY_MS,
8855
- shouldRetry: (error) => error instanceof OpenAIModerationRequestError ? error.retriable : true
9001
+ // The classification decides: no response, 408/429/5xx and an accepted call's
9002
+ // unreadable body are transient; a spent quota and other rejections aren't.
9003
+ shouldRetry: (error) => MuxAiError.is(error) ? error.transient || RETRIED_WITHIN_CALL.has(error) : true
8856
9004
  }
8857
9005
  );
8858
9006
  }
9007
+ function withoutFailure({ failure: _failure, ...score }) {
9008
+ return score;
9009
+ }
9010
+ function thumbnailErrorSample(entry, error) {
9011
+ const failure = sampleFailureOf(error);
9012
+ return {
9013
+ url: entry.url,
9014
+ time: entry.time,
9015
+ sexual: 0,
9016
+ violence: 0,
9017
+ error: true,
9018
+ errorMessage: error instanceof Error ? error.message : String(error),
9019
+ ...failure && { failure }
9020
+ };
9021
+ }
8859
9022
  async function processConcurrently(items, processor, maxConcurrent = 5) {
8860
9023
  "use step";
8861
9024
  const results = [];
@@ -8871,6 +9034,7 @@ async function moderateImageWithOpenAI(entry) {
8871
9034
  "use step";
8872
9035
  try {
8873
9036
  const { results } = await callOpenAIModerationApi({
9037
+ call: "moderate_thumbnails",
8874
9038
  model: entry.model,
8875
9039
  input: [
8876
9040
  {
@@ -8892,21 +9056,15 @@ async function moderateImageWithOpenAI(entry) {
8892
9056
  };
8893
9057
  } catch (error) {
8894
9058
  console.error("OpenAI moderation failed:", error);
8895
- return {
8896
- url: entry.url,
8897
- time: entry.time,
8898
- sexual: 0,
8899
- violence: 0,
8900
- error: true,
8901
- errorMessage: error instanceof Error ? error.message : String(error)
8902
- };
9059
+ return thumbnailErrorSample(entry, error);
8903
9060
  }
8904
9061
  }
9062
+ var THUMBNAIL_DOWNLOAD_ERRORS = { classifiedErrors: true, call: "fetch_thumbnail" };
8905
9063
  async function requestOpenAIModeration(images, model, maxConcurrent = 5, submissionMode = "url", downloadOptions, credentials) {
8906
9064
  "use step";
8907
9065
  const imageUrls = images.map((img) => img.url);
8908
9066
  const timeByUrl = new Map(images.map((img) => [img.url, img.time]));
8909
- const targetUrls = submissionMode === "base64" ? (await downloadImagesAsBase64(imageUrls, downloadOptions, maxConcurrent)).map(
9067
+ const targetUrls = submissionMode === "base64" ? (await downloadImagesAsBase64(imageUrls, downloadOptions, maxConcurrent, THUMBNAIL_DOWNLOAD_ERRORS)).map(
8910
9068
  (img) => ({ url: img.url, time: timeByUrl.get(img.url), image: img.base64Data, model, credentials })
8911
9069
  ) : images.map((img) => ({ url: img.url, time: img.time, image: img.url, model, credentials }));
8912
9070
  return processConcurrently(targetUrls, moderateImageWithOpenAI, maxConcurrent);
@@ -9032,13 +9190,15 @@ function packWindowsIntoBatches(windows) {
9032
9190
  return batches;
9033
9191
  }
9034
9192
  function transcriptErrorScore(window, error) {
9193
+ const failure = sampleFailureOf(error);
9035
9194
  return {
9036
9195
  startTime: window.startTime,
9037
9196
  endTime: window.endTime,
9038
9197
  sexual: 0,
9039
9198
  violence: 0,
9040
9199
  error: true,
9041
- errorMessage: error instanceof Error ? error.message : String(error)
9200
+ errorMessage: error instanceof Error ? error.message : String(error),
9201
+ ...failure && { failure }
9042
9202
  };
9043
9203
  }
9044
9204
  async function moderateTranscriptBatchWithOpenAI(batch) {
@@ -9049,6 +9209,7 @@ async function moderateTranscriptBatchWithOpenAI(batch) {
9049
9209
  }
9050
9210
  try {
9051
9211
  const { results } = await callOpenAIModerationApi({
9212
+ call: "moderate_transcript",
9052
9213
  model,
9053
9214
  input: windows.map((window) => window.text),
9054
9215
  credentials
@@ -9064,7 +9225,7 @@ async function moderateTranscriptBatchWithOpenAI(batch) {
9064
9225
  };
9065
9226
  });
9066
9227
  } catch (error) {
9067
- const status = error instanceof OpenAIModerationRequestError ? error.status : void 0;
9228
+ const status = MuxAiError.is(error) ? error.facts.status : void 0;
9068
9229
  if (status === 400 && windows.length > 1) {
9069
9230
  const mid = Math.ceil(windows.length / 2);
9070
9231
  const [left, right] = await Promise.all([
@@ -9108,8 +9269,8 @@ function getHiveCategoryScores(classes, categoryNames) {
9108
9269
  }
9109
9270
  async function moderateImageWithHive(entry) {
9110
9271
  "use step";
9111
- const apiKey = await getApiKeyFromEnv("hive", entry.credentials);
9112
9272
  try {
9273
+ const apiKey = await getApiKeyFromEnv("hive", entry.credentials);
9113
9274
  const formData = new FormData();
9114
9275
  if (entry.source.kind === "url") {
9115
9276
  formData.append("url", entry.source.value);
@@ -9135,28 +9296,28 @@ async function moderateImageWithHive(entry) {
9135
9296
  });
9136
9297
  } catch (err) {
9137
9298
  if (err?.name === "AbortError") {
9138
- throw new Error("Hive request timed out after 15s");
9299
+ throw hiveCallError("Hive request timed out after 15s", { call: "moderate_thumbnails", timedOut: true, cause: err });
9139
9300
  }
9140
- throw err;
9301
+ throw hiveCallError(err instanceof Error ? err.message : String(err), { call: "moderate_thumbnails", cause: err });
9141
9302
  } finally {
9142
9303
  clearTimeout(timeout);
9143
9304
  }
9144
9305
  const json = await res.json().catch(() => void 0);
9145
9306
  if (!res.ok) {
9146
- throw new Error(
9147
- `Hive moderation error: ${res.status} ${res.statusText} - ${JSON.stringify(json)}`
9307
+ throw hiveCallError(
9308
+ `Hive moderation error: ${res.status} ${res.statusText} - ${JSON.stringify(json)}`,
9309
+ { call: "moderate_thumbnails", status: res.status, requestId: requestIdOf(res.headers) }
9148
9310
  );
9149
9311
  }
9150
9312
  if (json?.return_code != null && json.return_code !== 0) {
9151
- throw new Error(
9152
- `Hive API error (return_code ${json.return_code}): ${json.message || "Unknown error"}`
9313
+ throw hiveCallError(
9314
+ `Hive API error (return_code ${json.return_code}): ${json.message || "Unknown error"}`,
9315
+ { call: "moderate_thumbnails", answered: true, returnCode: providerCodeOf(json.return_code) }
9153
9316
  );
9154
9317
  }
9155
9318
  const classes = json?.status?.[0]?.response?.output?.[0]?.classes;
9156
9319
  if (!Array.isArray(classes)) {
9157
- throw new TypeError(
9158
- `Unexpected Hive response structure: ${JSON.stringify(json)}`
9159
- );
9320
+ throw unusableResponseError(`Unexpected Hive response structure: ${JSON.stringify(json)}`, "moderate_thumbnails", "hive");
9160
9321
  }
9161
9322
  const sexual = getHiveCategoryScores(classes, HIVE_SEXUAL_CATEGORIES);
9162
9323
  const violence = getHiveCategoryScores(classes, HIVE_VIOLENCE_CATEGORIES);
@@ -9168,21 +9329,14 @@ async function moderateImageWithHive(entry) {
9168
9329
  error: false
9169
9330
  };
9170
9331
  } catch (error) {
9171
- return {
9172
- url: entry.url,
9173
- time: entry.time,
9174
- sexual: 0,
9175
- violence: 0,
9176
- error: true,
9177
- errorMessage: error instanceof Error ? error.message : String(error)
9178
- };
9332
+ return thumbnailErrorSample(entry, error);
9179
9333
  }
9180
9334
  }
9181
9335
  async function requestHiveModeration(images, maxConcurrent = 5, submissionMode = "url", downloadOptions, credentials) {
9182
9336
  "use step";
9183
9337
  const imageUrls = images.map((img) => img.url);
9184
9338
  const timeByUrl = new Map(images.map((img) => [img.url, img.time]));
9185
- const targets = submissionMode === "base64" ? (await downloadImagesAsBase64(imageUrls, downloadOptions, maxConcurrent)).map((img) => ({
9339
+ const targets = submissionMode === "base64" ? (await downloadImagesAsBase64(imageUrls, downloadOptions, maxConcurrent, THUMBNAIL_DOWNLOAD_ERRORS)).map((img) => ({
9186
9340
  url: img.url,
9187
9341
  time: timeByUrl.get(img.url),
9188
9342
  source: {
@@ -9227,27 +9381,29 @@ async function moderateImageWithGoogleVision(entry) {
9227
9381
  });
9228
9382
  } catch (err) {
9229
9383
  if (err?.name === "AbortError") {
9230
- throw new Error("Google Vision request timed out after 15s");
9384
+ throw googleVisionCallError("Google Vision request timed out after 15s", { call: "moderate_thumbnails", timedOut: true, cause: err });
9231
9385
  }
9232
- throw err;
9386
+ throw googleVisionCallError(err instanceof Error ? err.message : String(err), { call: "moderate_thumbnails", cause: err });
9233
9387
  } finally {
9234
9388
  clearTimeout(timeout);
9235
9389
  }
9236
9390
  const json = await res.json().catch(() => void 0);
9237
9391
  if (!res.ok) {
9238
- throw new Error(
9239
- `Google Vision moderation error: ${res.status} ${res.statusText} - ${JSON.stringify(json)}`
9392
+ throw googleVisionCallError(
9393
+ `Google Vision moderation error: ${res.status} ${res.statusText} - ${JSON.stringify(json)}`,
9394
+ { call: "moderate_thumbnails", status: res.status, requestId: requestIdOf(res.headers) }
9240
9395
  );
9241
9396
  }
9242
9397
  const perImage = json?.responses?.[0];
9243
9398
  if (perImage?.error) {
9244
- throw new Error(
9245
- `Google Vision per-image error: ${perImage.error.code} ${perImage.error.message || "Unknown error"}`
9399
+ throw googleVisionCallError(
9400
+ `Google Vision per-image error: ${perImage.error.code} ${perImage.error.message || "Unknown error"}`,
9401
+ { call: "moderate_thumbnails", answered: true, rpcCode: providerCodeOf(perImage.error.code), inline: entry.isBase64 }
9246
9402
  );
9247
9403
  }
9248
9404
  const annotation = perImage?.safeSearchAnnotation;
9249
9405
  if (!annotation) {
9250
- throw new Error(`Google Vision response missing safeSearchAnnotation: ${JSON.stringify(json)}`);
9406
+ throw unusableResponseError(`Google Vision response missing safeSearchAnnotation: ${JSON.stringify(json)}`, "moderate_thumbnails", "google-vision-api");
9251
9407
  }
9252
9408
  const adultLikelihood = typeof annotation.adult === "string" ? annotation.adult : "UNKNOWN";
9253
9409
  const violenceLikelihood = typeof annotation.violence === "string" ? annotation.violence : "UNKNOWN";
@@ -9261,21 +9417,14 @@ async function moderateImageWithGoogleVision(entry) {
9261
9417
  error: false
9262
9418
  };
9263
9419
  } catch (error) {
9264
- return {
9265
- url: entry.url,
9266
- time: entry.time,
9267
- sexual: 0,
9268
- violence: 0,
9269
- error: true,
9270
- errorMessage: error instanceof Error ? error.message : String(error)
9271
- };
9420
+ return thumbnailErrorSample(entry, error);
9272
9421
  }
9273
9422
  }
9274
9423
  async function requestGoogleVisionModeration(images, maxConcurrent = 5, submissionMode = "url", downloadOptions, credentials) {
9275
9424
  "use step";
9276
9425
  const imageUrls = images.map((img) => img.url);
9277
9426
  const timeByUrl = new Map(images.map((img) => [img.url, img.time]));
9278
- const targets = submissionMode === "base64" ? (await downloadImagesAsBase64(imageUrls, downloadOptions, maxConcurrent)).map((img) => ({
9427
+ const targets = submissionMode === "base64" ? (await downloadImagesAsBase64(imageUrls, downloadOptions, maxConcurrent, THUMBNAIL_DOWNLOAD_ERRORS)).map((img) => ({
9279
9428
  url: img.url,
9280
9429
  time: timeByUrl.get(img.url),
9281
9430
  // Vision REST wants raw base64; downloadImagesAsBase64 returns a data URI.
@@ -9330,12 +9479,99 @@ async function requestThumbnailModeration(provider, thumbnailUrls, options) {
9330
9479
  return requestHiveModeration(thumbnailUrls, maxConcurrent, imageSubmissionMode, imageDownloadOptions, credentials);
9331
9480
  case "google-vision-api":
9332
9481
  return requestGoogleVisionModeration(thumbnailUrls, maxConcurrent, imageSubmissionMode, imageDownloadOptions, credentials);
9333
- default: {
9334
- const exhaustiveCheck = provider;
9335
- throw new Error(`Unsupported moderation provider: ${exhaustiveCheck}`);
9482
+ default:
9483
+ return assertNever(provider, "moderation provider");
9484
+ }
9485
+ }
9486
+ var MODERATION_PROVIDERS = ["openai", "hive", "google-vision-api"];
9487
+ function nothingToModerateError(message, context) {
9488
+ const { assetId, thumbnailModeration, transcriptModeration } = context;
9489
+ const skips = {
9490
+ assetId,
9491
+ ...thumbnailModeration.skipReason && { thumbnailSkipReason: thumbnailModeration.skipReason },
9492
+ ...transcriptModeration.skipReason && { transcriptSkipReason: transcriptModeration.skipReason }
9493
+ };
9494
+ if (thumbnailModeration.skipReason === "no_video_in_scope" && context.resolvedScope) {
9495
+ return invalidScopeError(message, {
9496
+ reason: "no_video",
9497
+ startTime: context.resolvedScope.startTime,
9498
+ endTime: context.resolvedScope.endTime,
9499
+ videoEndTime: context.videoEndTime,
9500
+ ...skips
9501
+ }, ["scope"]);
9502
+ }
9503
+ switch (transcriptModeration.skipReason) {
9504
+ case "unsupported_provider":
9505
+ return new MuxAiError(message, {
9506
+ code: MUX_AI_ERROR_CODES.INVALID_PARAMETER,
9507
+ type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR,
9508
+ source: MUX_AI_ERROR_SOURCES.REQUEST,
9509
+ facts: { parameter: "provider", reason: "not_allowed", allowed: ["openai"], value: context.provider, ...skips, inputs: ["provider"] }
9510
+ });
9511
+ case "disabled":
9512
+ return new MuxAiError(message, {
9513
+ code: MUX_AI_ERROR_CODES.INVALID_PARAMETER,
9514
+ type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR,
9515
+ source: MUX_AI_ERROR_SOURCES.REQUEST,
9516
+ facts: { parameter: "includeTranscript", reason: "audio_only", allowed: [true], value: false, ...skips, inputs: ["includeTranscript"] }
9517
+ });
9518
+ case "no_ready_text_track": {
9519
+ const availableLanguages = getReadyTextTracks(context.asset).map((track) => track.language_code).filter((code) => !!code);
9520
+ return new MuxAiError(message, {
9521
+ code: MUX_AI_ERROR_CODES.CAPTION_TRACK_NOT_FOUND,
9522
+ type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR,
9523
+ source: MUX_AI_ERROR_SOURCES.ASSET,
9524
+ facts: { ...context.languageCode && { languageCode: context.languageCode }, availableLanguages, ...skips }
9525
+ });
9336
9526
  }
9527
+ case "no_cues":
9528
+ if (context.transcriptEmptyCause === "no_scoped_cues") {
9529
+ return invalidScopeError(message, {
9530
+ reason: "no_transcript",
9531
+ ...context.captionTrackId && { trackId: context.captionTrackId },
9532
+ ...context.scope?.startTime !== void 0 && { startTime: context.scope.startTime },
9533
+ ...context.scope?.endTime !== void 0 && { endTime: context.scope.endTime },
9534
+ ...skips
9535
+ }, ["scope"]);
9536
+ }
9537
+ return new MuxAiError(message, {
9538
+ code: MUX_AI_ERROR_CODES.TRANSCRIPT_EMPTY,
9539
+ type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR,
9540
+ source: MUX_AI_ERROR_SOURCES.ASSET,
9541
+ facts: { ...context.captionTrackId && { trackId: context.captionTrackId }, ...context.transcriptEmptyCause && { reason: context.transcriptEmptyCause }, ...skips }
9542
+ });
9543
+ case void 0:
9544
+ return internalError(message, skips);
9545
+ default:
9546
+ return assertNever(transcriptModeration.skipReason, "transcript skip reason");
9337
9547
  }
9338
9548
  }
9549
+ var SAMPLE_SPECIFIC_CODES = /* @__PURE__ */ new Set([
9550
+ MUX_AI_ERROR_CODES.IMAGE_UNPROCESSABLE,
9551
+ MUX_AI_ERROR_CODES.MODEL_OUTPUT_INVALID,
9552
+ MUX_AI_ERROR_CODES.DEPENDENCY_RESPONSE_FAILED
9553
+ ]);
9554
+ function isSampleSpecific(error) {
9555
+ return error.source === MUX_AI_ERROR_SOURCES.ASSET || error.code !== void 0 && SAMPLE_SPECIFIC_CODES.has(error.code);
9556
+ }
9557
+ function allSamplesFailedError(message, failures, facts) {
9558
+ const errors = failures.map(({ call, failure }) => failure ?? internalError(message, { ...facts, call }));
9559
+ const callWide = errors.filter((error) => !isSampleSpecific(error));
9560
+ const representative = callWide.find((error) => !error.transient) ?? callWide[0] ?? errors.find((error) => !error.transient) ?? errors[0];
9561
+ if (!representative) {
9562
+ return internalError(message, facts);
9563
+ }
9564
+ return new MuxAiError(message, {
9565
+ ...representative.code && { code: representative.code },
9566
+ type: representative.type,
9567
+ source: representative.source,
9568
+ ...representative.dependency && { dependency: representative.dependency },
9569
+ facts: { ...facts, ...representative.facts },
9570
+ transient: representative.transient,
9571
+ retryable: representative.retryable,
9572
+ cause: representative
9573
+ });
9574
+ }
9339
9575
  async function getModerationScores(assetId, options = {}) {
9340
9576
  "use workflow";
9341
9577
  const {
@@ -9354,7 +9590,23 @@ async function getModerationScores(assetId, options = {}) {
9354
9590
  scope
9355
9591
  } = options;
9356
9592
  const credentials = providedCredentials;
9357
- const { asset, playbackId, policy } = await getPlaybackIdForAsset(assetId, credentials, options.assetSnapshot);
9593
+ if (!MODERATION_PROVIDERS.includes(provider)) {
9594
+ throw new MuxAiError(`Unsupported moderation provider: ${String(provider)}`, {
9595
+ code: MUX_AI_ERROR_CODES.INVALID_PARAMETER,
9596
+ type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR,
9597
+ source: MUX_AI_ERROR_SOURCES.REQUEST,
9598
+ facts: { parameter: "provider", reason: "not_allowed", allowed: [...MODERATION_PROVIDERS], value: String(provider).slice(0, 100), inputs: ["provider"] }
9599
+ });
9600
+ }
9601
+ if (maxSamples !== void 0 && !(maxSamples > 0)) {
9602
+ throw new MuxAiError(`maxSamples must be a positive number (received ${String(maxSamples)}).`, {
9603
+ code: MUX_AI_ERROR_CODES.INVALID_PARAMETER,
9604
+ type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR,
9605
+ source: MUX_AI_ERROR_SOURCES.REQUEST,
9606
+ facts: { parameter: "maxSamples", reason: "not_positive", ...typeof maxSamples === "number" && Number.isFinite(maxSamples) && { value: maxSamples }, inputs: ["maxSamples"] }
9607
+ });
9608
+ }
9609
+ const { asset, playbackId, policy } = await getPlaybackIdForAsset(assetId, credentials, options.assetSnapshot, { classifiedErrors: true });
9358
9610
  const videoTrackDurationSeconds = getVideoTrackDurationSecondsFromAsset(asset);
9359
9611
  const videoTrackFps = getVideoTrackMaxFrameRateFromAsset(asset);
9360
9612
  const assetDurationSeconds = getAssetDurationSecondsFromAsset(asset);
@@ -9363,7 +9615,7 @@ async function getModerationScores(assetId, options = {}) {
9363
9615
  );
9364
9616
  const duration = candidateDurations.length > 0 ? Math.min(...candidateDurations) : 0;
9365
9617
  const effectiveScope = hasWorkflowScopeBoundaries(scope) ? scope : void 0;
9366
- const resolvedScope = effectiveScope ? resolveWorkflowScope(effectiveScope, assetDurationSeconds) : void 0;
9618
+ const resolvedScope = effectiveScope ? resolveWorkflowScope(effectiveScope, assetDurationSeconds, { classifiedErrors: true, assetId }) : void 0;
9367
9619
  const isAudioOnly = isAudioOnlyAsset(asset);
9368
9620
  const renderableScope = resolvedScope ? {
9369
9621
  startTime: Math.min(resolvedScope.startTime, duration),
@@ -9371,19 +9623,20 @@ async function getModerationScores(assetId, options = {}) {
9371
9623
  } : void 0;
9372
9624
  const signingContext = await resolveMuxSigningContext(credentials);
9373
9625
  if (policy === "signed" && !signingContext) {
9374
- throw new Error(
9375
- "Signed playback ID requires signing credentials. Set MUX_SIGNING_KEY and MUX_PRIVATE_KEY environment variables."
9376
- );
9626
+ throw signingCredentialsMissingError();
9377
9627
  }
9378
9628
  let thumbnailModeration = { status: "completed" };
9379
9629
  let thumbnailUrls = [];
9380
9630
  let shouldRunThumbnails = false;
9631
+ let thumbnailsUnsampled = false;
9381
9632
  if (isAudioOnly) {
9382
9633
  thumbnailModeration = {
9383
9634
  status: "skipped",
9384
9635
  skipReason: "no_video_track",
9385
9636
  skipMessage: "Asset has no video track, so there are no thumbnails to moderate."
9386
9637
  };
9638
+ } else if (duration <= 0) {
9639
+ thumbnailsUnsampled = true;
9387
9640
  } else if (renderableScope && renderableScope.startTime >= renderableScope.endTime) {
9388
9641
  thumbnailModeration = {
9389
9642
  status: "skipped",
@@ -9398,7 +9651,7 @@ async function getModerationScores(assetId, options = {}) {
9398
9651
  filterTimestampsWithinExclusiveScope(
9399
9652
  planSamplingTimestamps({
9400
9653
  duration_sec: duration,
9401
- max_candidates: maxSamples,
9654
+ max_candidates: Math.max(1, Math.floor(maxSamples)),
9402
9655
  trim_start_sec: renderableScope?.startTime ?? (duration > 2 ? Math.min(5, Math.max(1, duration / 6)) : 0),
9403
9656
  trim_end_sec: renderableScope ? duration - renderableScope.endTime : duration > 2 ? Math.min(5, Math.max(1, duration / 6)) : 0,
9404
9657
  fps: videoTrackFps,
@@ -9418,9 +9671,18 @@ async function getModerationScores(assetId, options = {}) {
9418
9671
  credentials,
9419
9672
  scope: renderableScope
9420
9673
  });
9421
- shouldRunThumbnails = true;
9674
+ if (thumbnailUrls.length > 0) {
9675
+ shouldRunThumbnails = true;
9676
+ } else {
9677
+ thumbnailModeration = {
9678
+ status: "skipped",
9679
+ skipReason: "no_video_in_scope",
9680
+ skipMessage: "The requested scope does not include any renderable video, so there are no thumbnails to moderate."
9681
+ };
9682
+ }
9422
9683
  }
9423
9684
  let transcriptModeration = { status: "completed" };
9685
+ let transcriptEmptyCause;
9424
9686
  let transcriptCues = [];
9425
9687
  let shouldRunTranscript = false;
9426
9688
  const transcriptEnabled = includeTranscript || isAudioOnly;
@@ -9445,14 +9707,22 @@ async function getModerationScores(assetId, options = {}) {
9445
9707
  };
9446
9708
  } else {
9447
9709
  if (!captionTrack.id) {
9448
- throw new LegacyMuxAiError("Transcript track is missing an id.", { type: "validation_error" });
9710
+ throw new MuxAiError("Transcript track is missing an id.", {
9711
+ code: MUX_AI_ERROR_CODES.CAPTION_TRACK_ID_MISSING,
9712
+ type: MUX_AI_ERROR_TYPES.PROCESSING_ERROR,
9713
+ source: MUX_AI_ERROR_SOURCES.UPSTREAM,
9714
+ dependency: MUX_AI_ERROR_DEPENDENCIES.MUX_VIDEO,
9715
+ facts: { assetId, ...captionTrack.language_code && { languageCode: captionTrack.language_code } }
9716
+ });
9449
9717
  }
9450
9718
  const transcriptUrl = await buildTranscriptUrl(playbackId, captionTrack.id, policy === "signed", credentials);
9451
9719
  const { transcriptText, emptyReason } = await fetchTranscriptDataForUrl(transcriptUrl, {
9452
9720
  cleanTranscript: false,
9453
- scope: effectiveScope
9721
+ scope: effectiveScope,
9722
+ classifiedErrors: true
9454
9723
  });
9455
9724
  if (emptyReason) {
9725
+ transcriptEmptyCause = emptyReason;
9456
9726
  transcriptModeration = {
9457
9727
  status: "skipped",
9458
9728
  skipReason: "no_cues",
@@ -9462,6 +9732,7 @@ async function getModerationScores(assetId, options = {}) {
9462
9732
  transcriptCues = parseVTTCues(transcriptText, { capCueText: false });
9463
9733
  const windows = transcriptCues.length === 0 ? [] : buildTranscriptWindows(transcriptCues, duration);
9464
9734
  if (windows.length === 0) {
9735
+ transcriptEmptyCause = "no_parseable_cues";
9465
9736
  transcriptModeration = {
9466
9737
  status: "skipped",
9467
9738
  skipReason: "no_cues",
@@ -9472,10 +9743,30 @@ async function getModerationScores(assetId, options = {}) {
9472
9743
  }
9473
9744
  }
9474
9745
  }
9746
+ if (thumbnailsUnsampled && !shouldRunTranscript) {
9747
+ throw new MuxAiError(`Nothing to moderate: asset ${assetId} has no valid duration to sample thumbnails from, and the transcript was skipped: ${transcriptModeration.skipMessage}`, {
9748
+ code: MUX_AI_ERROR_CODES.ASSET_DURATION_UNAVAILABLE,
9749
+ type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR,
9750
+ source: MUX_AI_ERROR_SOURCES.ASSET,
9751
+ facts: { assetId, ...transcriptModeration.skipReason && { transcriptSkipReason: transcriptModeration.skipReason } }
9752
+ });
9753
+ }
9475
9754
  if (!shouldRunThumbnails && !shouldRunTranscript) {
9476
- throw new LegacyMuxAiError(
9755
+ throw nothingToModerateError(
9477
9756
  `Nothing to moderate. Thumbnails skipped: ${thumbnailModeration.skipMessage} Transcript skipped: ${transcriptModeration.skipMessage}`,
9478
- { type: "validation_error" }
9757
+ {
9758
+ assetId,
9759
+ asset,
9760
+ provider,
9761
+ languageCode,
9762
+ thumbnailModeration,
9763
+ transcriptModeration,
9764
+ transcriptEmptyCause,
9765
+ captionTrackId: captionTrack?.id,
9766
+ scope: effectiveScope,
9767
+ resolvedScope,
9768
+ videoEndTime: duration
9769
+ }
9479
9770
  );
9480
9771
  }
9481
9772
  const [thumbnailScores, transcriptScores] = await Promise.all([
@@ -9497,15 +9788,17 @@ async function getModerationScores(assetId, options = {}) {
9497
9788
  const mode = shouldRunThumbnails && shouldRunTranscript ? "combined" : shouldRunTranscript ? "transcript" : "thumbnails";
9498
9789
  const thumbnailCount = shouldRunThumbnails ? thumbnailUrls.length : void 0;
9499
9790
  const allScores = [
9500
- ...thumbnailScores.map((s) => ({ ...s, label: s.url })),
9501
- ...transcriptScores.map((s) => ({ ...s, error: s.error ?? false, label: `transcript window ${s.startTime}-${s.endTime}s` }))
9791
+ ...thumbnailScores.map((s) => ({ ...s, label: s.time === void 0 ? "thumbnail" : `thumbnail at ${s.time}s`, call: "moderate_thumbnails" })),
9792
+ ...transcriptScores.map((s) => ({ ...s, error: s.error ?? false, label: `transcript window ${s.startTime}-${s.endTime}s`, call: "moderate_transcript" }))
9502
9793
  ];
9503
9794
  const failed = allScores.filter((s) => s.error);
9504
9795
  const successful = allScores.filter((s) => !s.error);
9505
9796
  if (successful.length === 0) {
9506
9797
  const details = failed.map((s) => `${s.label}: ${s.errorMessage || "Unknown error"}`).join("; ");
9507
- throw new Error(
9508
- `Moderation failed for all ${allScores.length} sample(s): ${details}`
9798
+ throw allSamplesFailedError(
9799
+ `Moderation failed for all ${allScores.length} sample(s): ${details}`,
9800
+ failed,
9801
+ { provider, ...model && { model }, assetId, sampleCount: allScores.length }
9509
9802
  );
9510
9803
  }
9511
9804
  if (failed.length > 0) {
@@ -9550,8 +9843,8 @@ async function getModerationScores(assetId, options = {}) {
9550
9843
  assetId,
9551
9844
  mode,
9552
9845
  isAudioOnly,
9553
- thumbnailScores,
9554
- transcriptScores,
9846
+ thumbnailScores: thumbnailScores.map(withoutFailure),
9847
+ transcriptScores: transcriptScores.map(withoutFailure),
9555
9848
  thumbnailModeration,
9556
9849
  transcriptModeration,
9557
9850
  coverage: {
@@ -9579,7 +9872,7 @@ async function getModerationScores(assetId, options = {}) {
9579
9872
 
9580
9873
  // src/workflows/summarization.ts
9581
9874
  import { generateText as generateText8, Output as Output8 } from "ai";
9582
- import { z as z12 } from "zod";
9875
+ import { z as z13 } from "zod";
9583
9876
 
9584
9877
  // src/lib/markdown-normalization.ts
9585
9878
  var ESCAPED_LINE_BREAK_REGEX = /\\r\\n|\\n|\\r/g;
@@ -9724,17 +10017,17 @@ function createSummarizationGuidance({
9724
10017
  }
9725
10018
 
9726
10019
  // src/workflows/summarization.ts
9727
- var summarySchema = z12.object({
9728
- keywords: z12.array(z12.string().max(200)),
9729
- title: z12.string().max(500),
9730
- description: z12.string().max(1e4)
10020
+ var summarySchema = z13.object({
10021
+ keywords: z13.array(z13.string().max(200)),
10022
+ title: z13.string().max(500),
10023
+ description: z13.string().max(1e4)
9731
10024
  });
9732
10025
  function buildSummarySchema(descriptionLength) {
9733
10026
  const descriptionMaxChars = Math.max(2e3, descriptionLength * 15);
9734
- return z12.object({
9735
- keywords: z12.array(z12.string().max(200)),
9736
- title: z12.string().max(500),
9737
- description: z12.string().max(descriptionMaxChars)
10027
+ return z13.object({
10028
+ keywords: z13.array(z13.string().max(200)),
10029
+ title: z13.string().max(500),
10030
+ description: z13.string().max(descriptionMaxChars)
9738
10031
  });
9739
10032
  }
9740
10033
  var VALID_TONES = ["neutral", "playful", "professional"];
@@ -11266,9 +11559,9 @@ async function translateAudio(assetId, toLanguageCode, options = {}) {
11266
11559
 
11267
11560
  // src/workflows/translate-captions.ts
11268
11561
  import { generateText as generateText9, Output as Output9 } from "ai";
11269
- import { z as z13 } from "zod";
11270
- var translationSchema = z13.object({
11271
- translation: z13.string()
11562
+ import { z as z14 } from "zod";
11563
+ var translationSchema = z14.object({
11564
+ translation: z14.string()
11272
11565
  });
11273
11566
  var SYSTEM_PROMPT5 = promptDedent`
11274
11567
  You are a subtitle translation expert. Translate VTT subtitle files to the target language specified by the user.
@@ -11632,8 +11925,8 @@ async function translateCueChunkWithAI({
11632
11925
  }) {
11633
11926
  "use step";
11634
11927
  const model = await createLanguageModelFromConfig(provider, modelId, credentials);
11635
- const schema = z13.object({
11636
- translations: z13.array(z13.string().min(1).max(2e3)).length(cues.length)
11928
+ const schema = z14.object({
11929
+ translations: z14.array(z14.string().min(1).max(2e3)).length(cues.length)
11637
11930
  });
11638
11931
  const cuePayload = cues.map((cue, index) => ({
11639
11932
  index,