@mux/ai 0.66.0 → 0.67.0-canary.109

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>
@@ -5003,7 +5082,7 @@ async function hasBurnedInCaptionsInternal(assetId, options, collectedUsage) {
5003
5082
  // src/workflows/chapters.ts
5004
5083
  import { generateText as generateText4, Output as Output4 } from "ai";
5005
5084
  import dedent5 from "dedent";
5006
- import { z as z7 } from "zod";
5085
+ import { z as z8 } from "zod";
5007
5086
 
5008
5087
  // src/prompts/chapters.ts
5009
5088
  import dedent4 from "dedent";
@@ -5028,12 +5107,12 @@ function createChapterGuidance({
5028
5107
  }
5029
5108
 
5030
5109
  // src/workflows/chapters.ts
5031
- var chapterSchema = z7.object({
5032
- startTime: z7.number(),
5033
- title: z7.string().max(300)
5110
+ var chapterSchema = z8.object({
5111
+ startTime: z8.number(),
5112
+ title: z8.string().max(300)
5034
5113
  });
5035
- var chaptersSchema = z7.object({
5036
- chapters: z7.array(chapterSchema)
5114
+ var chaptersSchema = z8.object({
5115
+ chapters: z8.array(chapterSchema)
5037
5116
  });
5038
5117
  async function generateChaptersWithAI({
5039
5118
  provider,
@@ -5408,7 +5487,7 @@ async function generateChaptersInternal(assetId, options, collectedUsage) {
5408
5487
 
5409
5488
  // src/workflows/edit-captions.ts
5410
5489
  import { generateText as generateText5, Output as Output5 } from "ai";
5411
- import { z as z8 } from "zod";
5490
+ import { z as z9 } from "zod";
5412
5491
 
5413
5492
  // src/lib/mux-tracks.ts
5414
5493
  function trackWriteFailure(outcome) {
@@ -6097,8 +6176,8 @@ async function createPresignedGetUrlWithStorageAdapter(input, adapter) {
6097
6176
  }
6098
6177
 
6099
6178
  // src/workflows/edit-captions.ts
6100
- var profanityDetectionSchema = z8.object({
6101
- profanity: z8.array(z8.string().max(100)).describe(
6179
+ var profanityDetectionSchema = z9.object({
6180
+ profanity: z9.array(z9.string().max(100)).describe(
6102
6181
  "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
6182
  )
6104
6183
  });
@@ -7171,7 +7250,7 @@ async function generateVideoEmbeddings(assetId, options = {}) {
7171
7250
  // src/workflows/engagement-insights.ts
7172
7251
  import { generateText as generateText6, Output as Output6 } from "ai";
7173
7252
  import dedent6 from "dedent";
7174
- import { z as z9 } from "zod";
7253
+ import { z as z10 } from "zod";
7175
7254
 
7176
7255
  // src/primitives/heatmap.ts
7177
7256
  async function getHeatmapForAsset(assetId, options = {}) {
@@ -7313,20 +7392,20 @@ async function getShotsForAsset(assetId, options = {}) {
7313
7392
  }
7314
7393
 
7315
7394
  // 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)
7395
+ var aiMomentInsightSchema = z10.object({
7396
+ hotspotIndex: z10.number(),
7397
+ startMs: z10.number(),
7398
+ endMs: z10.number(),
7399
+ timestamp: z10.string(),
7400
+ engagementScore: z10.number(),
7401
+ insight: z10.string().max(1e3)
7323
7402
  });
7324
- var aiOverallInsightSchema = z9.object({
7325
- summary: z9.string().max(2e3),
7326
- trends: z9.array(z9.string().max(500))
7403
+ var aiOverallInsightSchema = z10.object({
7404
+ summary: z10.string().max(2e3),
7405
+ trends: z10.array(z10.string().max(500))
7327
7406
  });
7328
- var engagementInsightsSchema = z9.object({
7329
- momentInsights: z9.array(aiMomentInsightSchema),
7407
+ var engagementInsightsSchema = z10.object({
7408
+ momentInsights: z10.array(aiMomentInsightSchema),
7330
7409
  overallInsight: aiOverallInsightSchema
7331
7410
  });
7332
7411
  var SYSTEM_PROMPT4 = promptDedent`
@@ -7890,7 +7969,7 @@ async function generateEngagementInsightsInternal(assetId, options, collectedUsa
7890
7969
 
7891
7970
  // src/workflows/generate-text.ts
7892
7971
  import { APICallError as APICallError4, generateText as generateTextWithModel, Output as Output7 } from "ai";
7893
- import { z as z10 } from "zod";
7972
+ import { z as z11 } from "zod";
7894
7973
  var GENERATE_TEXT_MAX_VARIANTS = 5;
7895
7974
  var GENERATE_TEXT_MAX_ARTIFACTS = 5;
7896
7975
  var GENERATE_TEXT_MAX_INSTRUCTIONS_CHARS = 500;
@@ -8065,14 +8144,14 @@ async function getCompletedShots(assetId, credentials) {
8065
8144
  }
8066
8145
  return void 0;
8067
8146
  }
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))
8147
+ var briefSchema = z11.object({
8148
+ centralIdea: z11.string().max(500),
8149
+ readerValue: z11.string().max(500),
8150
+ keyPoints: z11.array(z11.string().max(500)),
8151
+ sourceSpecifics: z11.array(z11.string().max(500)),
8152
+ visualContext: z11.array(z11.string().max(500)),
8153
+ voiceSignals: z11.array(z11.string().max(300)),
8154
+ claimsToQualify: z11.array(z11.string().max(500))
8076
8155
  });
8077
8156
  var BRIEF_LIST_LIMITS = {
8078
8157
  keyPoints: 8,
@@ -8333,7 +8412,7 @@ async function extractBriefWithModel(args) {
8333
8412
  };
8334
8413
  });
8335
8414
  }
8336
- var artifactSchema = z10.object({ content: z10.string() });
8415
+ var artifactSchema = z11.object({ content: z11.string() });
8337
8416
  async function generateArtifactWithModel(args) {
8338
8417
  "use step";
8339
8418
  const diagnostics = { phase: "draft", provider: args.provider, modelId: args.modelId };
@@ -8594,7 +8673,71 @@ async function generateTextInternal(assetId, rawOptions, collectedUsage) {
8594
8673
  }
8595
8674
 
8596
8675
  // src/workflows/moderation.ts
8597
- import { z as z11 } from "zod";
8676
+ import { z as z12 } from "zod";
8677
+
8678
+ // src/lib/google-vision-errors.ts
8679
+ var GOOGLE_RPC_INVALID_ARGUMENT = "3";
8680
+ var GOOGLE_RPC_RESOURCE_EXHAUSTED = "8";
8681
+ var GOOGLE_RPC_UNAVAILABLE = "14";
8682
+ function googleVisionImageErrorRule(rpcCode, { inline }) {
8683
+ switch (rpcCode) {
8684
+ // Per image, not per request. With the image sent inline, it's that image that can't be
8685
+ // used. With a URL, Vision fetches the image itself and reports a failed fetch with the
8686
+ // same code ("The URL does not appear to be accessible by us"), which says nothing about
8687
+ // the image, so it stays `dependency_response_failed`.
8688
+ case GOOGLE_RPC_INVALID_ARGUMENT:
8689
+ return inline ? { code: MUX_AI_ERROR_CODES.IMAGE_UNPROCESSABLE } : void 0;
8690
+ case GOOGLE_RPC_UNAVAILABLE:
8691
+ return { code: MUX_AI_ERROR_CODES.PROVIDER_UNAVAILABLE };
8692
+ // A rate limit or a spent quota, which Google can't tell apart here: "generally don't retry".
8693
+ case GOOGLE_RPC_RESOURCE_EXHAUSTED:
8694
+ return { retryable: false };
8695
+ default:
8696
+ return void 0;
8697
+ }
8698
+ }
8699
+ function googleVisionCallError(message, init) {
8700
+ const answered = init.answered === true;
8701
+ const rule = answered ? googleVisionImageErrorRule(init.rpcCode, { inline: init.inline === true }) : void 0;
8702
+ return dependencyError(message, {
8703
+ dependency: MUX_AI_ERROR_DEPENDENCIES.AI_PROVIDER,
8704
+ call: init.call,
8705
+ status: init.status,
8706
+ requestId: init.requestId,
8707
+ timedOut: init.timedOut,
8708
+ facts: { provider: "google-vision-api", ...init.facts, ...init.rpcCode && { providerCode: init.rpcCode } },
8709
+ ...answered && { code: rule?.code ?? MUX_AI_ERROR_CODES.DEPENDENCY_RESPONSE_FAILED },
8710
+ ...rule?.retryable !== void 0 && { retryable: rule.retryable },
8711
+ cause: init.cause
8712
+ });
8713
+ }
8714
+
8715
+ // src/lib/hive-errors.ts
8716
+ function hiveErrorRule(status) {
8717
+ switch (status) {
8718
+ case 405:
8719
+ return MUX_AI_ERROR_CODES.PROVIDER_QUOTA_EXHAUSTED;
8720
+ case 403:
8721
+ return MUX_AI_ERROR_CODES.PROVIDER_CREDENTIALS_REJECTED;
8722
+ case 429:
8723
+ return MUX_AI_ERROR_CODES.PROVIDER_RATE_LIMITED;
8724
+ default:
8725
+ return void 0;
8726
+ }
8727
+ }
8728
+ function hiveCallError(message, init) {
8729
+ const code = init.answered ? MUX_AI_ERROR_CODES.DEPENDENCY_RESPONSE_FAILED : hiveErrorRule(init.status);
8730
+ return dependencyError(message, {
8731
+ dependency: MUX_AI_ERROR_DEPENDENCIES.AI_PROVIDER,
8732
+ call: init.call,
8733
+ status: init.status,
8734
+ requestId: init.requestId,
8735
+ timedOut: init.timedOut,
8736
+ facts: { provider: "hive", ...init.facts, ...init.returnCode && { providerCode: init.returnCode } },
8737
+ ...code && { code },
8738
+ cause: init.cause
8739
+ });
8740
+ }
8598
8741
 
8599
8742
  // src/lib/sampling-plan.ts
8600
8743
  var DEFAULT_FPS = 30;
@@ -8703,7 +8846,6 @@ var DEFAULT_THRESHOLDS = {
8703
8846
  violence: 0.8
8704
8847
  };
8705
8848
  var DEFAULT_PROVIDER2 = "openai";
8706
- var OPENAI_MODERATION_RETRIABLE_STATUS_CODES = /* @__PURE__ */ new Set([408, 429, 500, 502, 503, 504]);
8707
8849
  var OPENAI_MODERATION_MAX_RETRIES = 2;
8708
8850
  var OPENAI_MODERATION_BASE_DELAY_MS = 750;
8709
8851
  var OPENAI_MODERATION_MAX_DELAY_MS = 3e3;
@@ -8748,19 +8890,23 @@ var HIVE_VIOLENCE_CATEGORIES = [
8748
8890
  "yes_self_harm",
8749
8891
  "garm_death_injury_or_military_conflict"
8750
8892
  ];
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);
8893
+ function unusableResponseError(message, call, provider) {
8894
+ return new MuxAiError(message, {
8895
+ code: MUX_AI_ERROR_CODES.MODEL_OUTPUT_INVALID,
8896
+ type: MUX_AI_ERROR_TYPES.PROCESSING_ERROR,
8897
+ source: MUX_AI_ERROR_SOURCES.UPSTREAM,
8898
+ dependency: MUX_AI_ERROR_DEPENDENCIES.AI_PROVIDER,
8899
+ facts: { call, provider }
8900
+ });
8901
+ }
8902
+ var RETRIED_WITHIN_CALL = /* @__PURE__ */ new WeakSet();
8903
+ function sampleFailureOf(error) {
8904
+ return MuxAiError.is(error) ? error : void 0;
8905
+ }
8906
+ var ProviderCodeSchema = z12.string().regex(/^[\w.-]{1,64}$/);
8907
+ function providerCodeOf(value) {
8908
+ const parsed = ProviderCodeSchema.safeParse(typeof value === "number" ? String(value) : value);
8909
+ return parsed.success ? parsed.data : void 0;
8764
8910
  }
8765
8911
  function compactBodySnippet(body, maxLength = 180) {
8766
8912
  const compact = body.replace(/\s+/g, " ").trim();
@@ -8769,34 +8915,45 @@ function compactBodySnippet(body, maxLength = 180) {
8769
8915
  }
8770
8916
  return compact.length > maxLength ? `${compact.slice(0, maxLength)}...` : compact;
8771
8917
  }
8772
- function parseOpenAIModerationResponse(bodyText, status, statusText) {
8918
+ function unreadableOpenAIResponseError(message, res, call, { retryWithinCall }) {
8919
+ if (!res.ok) {
8920
+ return openAIFetchError(message, { call, status: res.status, requestId: requestIdOf(res.headers), facts: { provider: "openai" } });
8921
+ }
8922
+ const error = unusableResponseError(message, call, "openai");
8923
+ if (retryWithinCall) {
8924
+ RETRIED_WITHIN_CALL.add(error);
8925
+ }
8926
+ return error;
8927
+ }
8928
+ function parseOpenAIModerationResponse(bodyText, res, call) {
8929
+ const { status, statusText } = res;
8773
8930
  if (!bodyText.trim()) {
8774
- throw new OpenAIModerationRequestError(
8775
- `OpenAI moderation returned an empty response (${status} ${statusText}).`,
8776
- { status, retriable: isRetriableOpenAIModerationStatus(status) }
8777
- );
8931
+ throw unreadableOpenAIResponseError(`OpenAI moderation returned an empty response (${status} ${statusText}).`, res, call, { retryWithinCall: false });
8778
8932
  }
8779
8933
  try {
8780
8934
  return JSON.parse(bodyText);
8781
8935
  } catch {
8782
- throw new OpenAIModerationRequestError(
8936
+ throw unreadableOpenAIResponseError(
8783
8937
  `OpenAI moderation returned non-JSON response (${status} ${statusText}): ${compactBodySnippet(bodyText)}`,
8784
- { status, retriable: true }
8938
+ res,
8939
+ call,
8940
+ { retryWithinCall: true }
8785
8941
  );
8786
8942
  }
8787
8943
  }
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()
8944
+ var OpenAIModerationResponseSchema = z12.object({
8945
+ results: z12.array(z12.object({
8946
+ category_scores: z12.object({
8947
+ sexual: z12.number().finite().nullish(),
8948
+ violence: z12.number().finite().nullish()
8793
8949
  })
8794
8950
  }))
8795
8951
  });
8796
8952
  async function callOpenAIModerationApi({
8797
8953
  model,
8798
8954
  input,
8799
- credentials
8955
+ credentials,
8956
+ call
8800
8957
  }) {
8801
8958
  "use step";
8802
8959
  const apiKey = await getApiKeyFromEnv("openai", credentials);
@@ -8816,35 +8973,34 @@ async function callOpenAIModerationApi({
8816
8973
  })
8817
8974
  });
8818
8975
  } catch (error) {
8819
- throw new OpenAIModerationRequestError(
8976
+ throw openAIFetchError(
8820
8977
  `OpenAI moderation request failed: ${error instanceof Error ? error.message : String(error)}`,
8821
- { retriable: true }
8978
+ { call, facts: { provider: "openai" }, cause: error }
8822
8979
  );
8823
8980
  }
8824
- const bodyText = await res.text();
8825
- const json = parseOpenAIModerationResponse(bodyText, res.status, res.statusText);
8981
+ let bodyText;
8982
+ try {
8983
+ bodyText = await res.text();
8984
+ } catch (error) {
8985
+ throw openAIFetchError(
8986
+ `OpenAI moderation response could not be read: ${error instanceof Error ? error.message : String(error)}`,
8987
+ { call, requestId: requestIdOf(res.headers), facts: { provider: "openai" }, cause: error }
8988
+ );
8989
+ }
8990
+ const json = parseOpenAIModerationResponse(bodyText, res, call);
8826
8991
  if (!res.ok) {
8827
- throw new OpenAIModerationRequestError(
8992
+ throw openAIFetchError(
8828
8993
  `OpenAI moderation error: ${res.status} ${res.statusText} - ${JSON.stringify(json)}`,
8829
- {
8830
- status: res.status,
8831
- retriable: isRetriableOpenAIModerationStatus(res.status)
8832
- }
8994
+ { call, status: res.status, requestId: requestIdOf(res.headers), body: bodyText, facts: { provider: "openai" } }
8833
8995
  );
8834
8996
  }
8835
8997
  const parsed = OpenAIModerationResponseSchema.safeParse(json);
8836
8998
  if (!parsed.success) {
8837
- throw new OpenAIModerationRequestError(
8838
- `OpenAI moderation returned an unexpected response shape: ${compactBodySnippet(bodyText)}`,
8839
- { status: res.status, retriable: false }
8840
- );
8999
+ throw unusableResponseError(`OpenAI moderation returned an unexpected response shape: ${compactBodySnippet(bodyText)}`, call, "openai");
8841
9000
  }
8842
9001
  const expectedResultCount = Array.isArray(input) ? input.length : 1;
8843
9002
  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
- );
9003
+ throw unusableResponseError(`OpenAI moderation returned ${parsed.data.results.length} result(s) for ${expectedResultCount} input(s).`, call, "openai");
8848
9004
  }
8849
9005
  return parsed.data;
8850
9006
  },
@@ -8852,10 +9008,27 @@ async function callOpenAIModerationApi({
8852
9008
  maxRetries: OPENAI_MODERATION_MAX_RETRIES,
8853
9009
  baseDelay: OPENAI_MODERATION_BASE_DELAY_MS,
8854
9010
  maxDelay: OPENAI_MODERATION_MAX_DELAY_MS,
8855
- shouldRetry: (error) => error instanceof OpenAIModerationRequestError ? error.retriable : true
9011
+ // The classification decides: no response, 408/429/5xx and an accepted call's
9012
+ // unreadable body are transient; a spent quota and other rejections aren't.
9013
+ shouldRetry: (error) => MuxAiError.is(error) ? error.transient || RETRIED_WITHIN_CALL.has(error) : true
8856
9014
  }
8857
9015
  );
8858
9016
  }
9017
+ function withoutFailure({ failure: _failure, ...score }) {
9018
+ return score;
9019
+ }
9020
+ function thumbnailErrorSample(entry, error) {
9021
+ const failure = sampleFailureOf(error);
9022
+ return {
9023
+ url: entry.url,
9024
+ time: entry.time,
9025
+ sexual: 0,
9026
+ violence: 0,
9027
+ error: true,
9028
+ errorMessage: error instanceof Error ? error.message : String(error),
9029
+ ...failure && { failure }
9030
+ };
9031
+ }
8859
9032
  async function processConcurrently(items, processor, maxConcurrent = 5) {
8860
9033
  "use step";
8861
9034
  const results = [];
@@ -8871,6 +9044,7 @@ async function moderateImageWithOpenAI(entry) {
8871
9044
  "use step";
8872
9045
  try {
8873
9046
  const { results } = await callOpenAIModerationApi({
9047
+ call: "moderate_thumbnails",
8874
9048
  model: entry.model,
8875
9049
  input: [
8876
9050
  {
@@ -8892,21 +9066,15 @@ async function moderateImageWithOpenAI(entry) {
8892
9066
  };
8893
9067
  } catch (error) {
8894
9068
  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
- };
9069
+ return thumbnailErrorSample(entry, error);
8903
9070
  }
8904
9071
  }
9072
+ var THUMBNAIL_DOWNLOAD_ERRORS = { classifiedErrors: true, call: "fetch_thumbnail" };
8905
9073
  async function requestOpenAIModeration(images, model, maxConcurrent = 5, submissionMode = "url", downloadOptions, credentials) {
8906
9074
  "use step";
8907
9075
  const imageUrls = images.map((img) => img.url);
8908
9076
  const timeByUrl = new Map(images.map((img) => [img.url, img.time]));
8909
- const targetUrls = submissionMode === "base64" ? (await downloadImagesAsBase64(imageUrls, downloadOptions, maxConcurrent)).map(
9077
+ const targetUrls = submissionMode === "base64" ? (await downloadImagesAsBase64(imageUrls, downloadOptions, maxConcurrent, THUMBNAIL_DOWNLOAD_ERRORS)).map(
8910
9078
  (img) => ({ url: img.url, time: timeByUrl.get(img.url), image: img.base64Data, model, credentials })
8911
9079
  ) : images.map((img) => ({ url: img.url, time: img.time, image: img.url, model, credentials }));
8912
9080
  return processConcurrently(targetUrls, moderateImageWithOpenAI, maxConcurrent);
@@ -9032,13 +9200,15 @@ function packWindowsIntoBatches(windows) {
9032
9200
  return batches;
9033
9201
  }
9034
9202
  function transcriptErrorScore(window, error) {
9203
+ const failure = sampleFailureOf(error);
9035
9204
  return {
9036
9205
  startTime: window.startTime,
9037
9206
  endTime: window.endTime,
9038
9207
  sexual: 0,
9039
9208
  violence: 0,
9040
9209
  error: true,
9041
- errorMessage: error instanceof Error ? error.message : String(error)
9210
+ errorMessage: error instanceof Error ? error.message : String(error),
9211
+ ...failure && { failure }
9042
9212
  };
9043
9213
  }
9044
9214
  async function moderateTranscriptBatchWithOpenAI(batch) {
@@ -9049,6 +9219,7 @@ async function moderateTranscriptBatchWithOpenAI(batch) {
9049
9219
  }
9050
9220
  try {
9051
9221
  const { results } = await callOpenAIModerationApi({
9222
+ call: "moderate_transcript",
9052
9223
  model,
9053
9224
  input: windows.map((window) => window.text),
9054
9225
  credentials
@@ -9064,7 +9235,7 @@ async function moderateTranscriptBatchWithOpenAI(batch) {
9064
9235
  };
9065
9236
  });
9066
9237
  } catch (error) {
9067
- const status = error instanceof OpenAIModerationRequestError ? error.status : void 0;
9238
+ const status = MuxAiError.is(error) ? error.facts.status : void 0;
9068
9239
  if (status === 400 && windows.length > 1) {
9069
9240
  const mid = Math.ceil(windows.length / 2);
9070
9241
  const [left, right] = await Promise.all([
@@ -9108,8 +9279,8 @@ function getHiveCategoryScores(classes, categoryNames) {
9108
9279
  }
9109
9280
  async function moderateImageWithHive(entry) {
9110
9281
  "use step";
9111
- const apiKey = await getApiKeyFromEnv("hive", entry.credentials);
9112
9282
  try {
9283
+ const apiKey = await getApiKeyFromEnv("hive", entry.credentials);
9113
9284
  const formData = new FormData();
9114
9285
  if (entry.source.kind === "url") {
9115
9286
  formData.append("url", entry.source.value);
@@ -9135,28 +9306,28 @@ async function moderateImageWithHive(entry) {
9135
9306
  });
9136
9307
  } catch (err) {
9137
9308
  if (err?.name === "AbortError") {
9138
- throw new Error("Hive request timed out after 15s");
9309
+ throw hiveCallError("Hive request timed out after 15s", { call: "moderate_thumbnails", timedOut: true, cause: err });
9139
9310
  }
9140
- throw err;
9311
+ throw hiveCallError(err instanceof Error ? err.message : String(err), { call: "moderate_thumbnails", cause: err });
9141
9312
  } finally {
9142
9313
  clearTimeout(timeout);
9143
9314
  }
9144
9315
  const json = await res.json().catch(() => void 0);
9145
9316
  if (!res.ok) {
9146
- throw new Error(
9147
- `Hive moderation error: ${res.status} ${res.statusText} - ${JSON.stringify(json)}`
9317
+ throw hiveCallError(
9318
+ `Hive moderation error: ${res.status} ${res.statusText} - ${JSON.stringify(json)}`,
9319
+ { call: "moderate_thumbnails", status: res.status, requestId: requestIdOf(res.headers) }
9148
9320
  );
9149
9321
  }
9150
9322
  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"}`
9323
+ throw hiveCallError(
9324
+ `Hive API error (return_code ${json.return_code}): ${json.message || "Unknown error"}`,
9325
+ { call: "moderate_thumbnails", answered: true, returnCode: providerCodeOf(json.return_code) }
9153
9326
  );
9154
9327
  }
9155
9328
  const classes = json?.status?.[0]?.response?.output?.[0]?.classes;
9156
9329
  if (!Array.isArray(classes)) {
9157
- throw new TypeError(
9158
- `Unexpected Hive response structure: ${JSON.stringify(json)}`
9159
- );
9330
+ throw unusableResponseError(`Unexpected Hive response structure: ${JSON.stringify(json)}`, "moderate_thumbnails", "hive");
9160
9331
  }
9161
9332
  const sexual = getHiveCategoryScores(classes, HIVE_SEXUAL_CATEGORIES);
9162
9333
  const violence = getHiveCategoryScores(classes, HIVE_VIOLENCE_CATEGORIES);
@@ -9168,21 +9339,14 @@ async function moderateImageWithHive(entry) {
9168
9339
  error: false
9169
9340
  };
9170
9341
  } 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
- };
9342
+ return thumbnailErrorSample(entry, error);
9179
9343
  }
9180
9344
  }
9181
9345
  async function requestHiveModeration(images, maxConcurrent = 5, submissionMode = "url", downloadOptions, credentials) {
9182
9346
  "use step";
9183
9347
  const imageUrls = images.map((img) => img.url);
9184
9348
  const timeByUrl = new Map(images.map((img) => [img.url, img.time]));
9185
- const targets = submissionMode === "base64" ? (await downloadImagesAsBase64(imageUrls, downloadOptions, maxConcurrent)).map((img) => ({
9349
+ const targets = submissionMode === "base64" ? (await downloadImagesAsBase64(imageUrls, downloadOptions, maxConcurrent, THUMBNAIL_DOWNLOAD_ERRORS)).map((img) => ({
9186
9350
  url: img.url,
9187
9351
  time: timeByUrl.get(img.url),
9188
9352
  source: {
@@ -9227,27 +9391,29 @@ async function moderateImageWithGoogleVision(entry) {
9227
9391
  });
9228
9392
  } catch (err) {
9229
9393
  if (err?.name === "AbortError") {
9230
- throw new Error("Google Vision request timed out after 15s");
9394
+ throw googleVisionCallError("Google Vision request timed out after 15s", { call: "moderate_thumbnails", timedOut: true, cause: err });
9231
9395
  }
9232
- throw err;
9396
+ throw googleVisionCallError(err instanceof Error ? err.message : String(err), { call: "moderate_thumbnails", cause: err });
9233
9397
  } finally {
9234
9398
  clearTimeout(timeout);
9235
9399
  }
9236
9400
  const json = await res.json().catch(() => void 0);
9237
9401
  if (!res.ok) {
9238
- throw new Error(
9239
- `Google Vision moderation error: ${res.status} ${res.statusText} - ${JSON.stringify(json)}`
9402
+ throw googleVisionCallError(
9403
+ `Google Vision moderation error: ${res.status} ${res.statusText} - ${JSON.stringify(json)}`,
9404
+ { call: "moderate_thumbnails", status: res.status, requestId: requestIdOf(res.headers) }
9240
9405
  );
9241
9406
  }
9242
9407
  const perImage = json?.responses?.[0];
9243
9408
  if (perImage?.error) {
9244
- throw new Error(
9245
- `Google Vision per-image error: ${perImage.error.code} ${perImage.error.message || "Unknown error"}`
9409
+ throw googleVisionCallError(
9410
+ `Google Vision per-image error: ${perImage.error.code} ${perImage.error.message || "Unknown error"}`,
9411
+ { call: "moderate_thumbnails", answered: true, rpcCode: providerCodeOf(perImage.error.code), inline: entry.isBase64 }
9246
9412
  );
9247
9413
  }
9248
9414
  const annotation = perImage?.safeSearchAnnotation;
9249
9415
  if (!annotation) {
9250
- throw new Error(`Google Vision response missing safeSearchAnnotation: ${JSON.stringify(json)}`);
9416
+ throw unusableResponseError(`Google Vision response missing safeSearchAnnotation: ${JSON.stringify(json)}`, "moderate_thumbnails", "google-vision-api");
9251
9417
  }
9252
9418
  const adultLikelihood = typeof annotation.adult === "string" ? annotation.adult : "UNKNOWN";
9253
9419
  const violenceLikelihood = typeof annotation.violence === "string" ? annotation.violence : "UNKNOWN";
@@ -9261,21 +9427,14 @@ async function moderateImageWithGoogleVision(entry) {
9261
9427
  error: false
9262
9428
  };
9263
9429
  } 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
- };
9430
+ return thumbnailErrorSample(entry, error);
9272
9431
  }
9273
9432
  }
9274
9433
  async function requestGoogleVisionModeration(images, maxConcurrent = 5, submissionMode = "url", downloadOptions, credentials) {
9275
9434
  "use step";
9276
9435
  const imageUrls = images.map((img) => img.url);
9277
9436
  const timeByUrl = new Map(images.map((img) => [img.url, img.time]));
9278
- const targets = submissionMode === "base64" ? (await downloadImagesAsBase64(imageUrls, downloadOptions, maxConcurrent)).map((img) => ({
9437
+ const targets = submissionMode === "base64" ? (await downloadImagesAsBase64(imageUrls, downloadOptions, maxConcurrent, THUMBNAIL_DOWNLOAD_ERRORS)).map((img) => ({
9279
9438
  url: img.url,
9280
9439
  time: timeByUrl.get(img.url),
9281
9440
  // Vision REST wants raw base64; downloadImagesAsBase64 returns a data URI.
@@ -9330,12 +9489,99 @@ async function requestThumbnailModeration(provider, thumbnailUrls, options) {
9330
9489
  return requestHiveModeration(thumbnailUrls, maxConcurrent, imageSubmissionMode, imageDownloadOptions, credentials);
9331
9490
  case "google-vision-api":
9332
9491
  return requestGoogleVisionModeration(thumbnailUrls, maxConcurrent, imageSubmissionMode, imageDownloadOptions, credentials);
9333
- default: {
9334
- const exhaustiveCheck = provider;
9335
- throw new Error(`Unsupported moderation provider: ${exhaustiveCheck}`);
9492
+ default:
9493
+ return assertNever(provider, "moderation provider");
9494
+ }
9495
+ }
9496
+ var MODERATION_PROVIDERS = ["openai", "hive", "google-vision-api"];
9497
+ function nothingToModerateError(message, context) {
9498
+ const { assetId, thumbnailModeration, transcriptModeration } = context;
9499
+ const skips = {
9500
+ assetId,
9501
+ ...thumbnailModeration.skipReason && { thumbnailSkipReason: thumbnailModeration.skipReason },
9502
+ ...transcriptModeration.skipReason && { transcriptSkipReason: transcriptModeration.skipReason }
9503
+ };
9504
+ if (thumbnailModeration.skipReason === "no_video_in_scope" && context.resolvedScope) {
9505
+ return invalidScopeError(message, {
9506
+ reason: "no_video",
9507
+ startTime: context.resolvedScope.startTime,
9508
+ endTime: context.resolvedScope.endTime,
9509
+ videoEndTime: context.videoEndTime,
9510
+ ...skips
9511
+ }, ["scope"]);
9512
+ }
9513
+ switch (transcriptModeration.skipReason) {
9514
+ case "unsupported_provider":
9515
+ return new MuxAiError(message, {
9516
+ code: MUX_AI_ERROR_CODES.INVALID_PARAMETER,
9517
+ type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR,
9518
+ source: MUX_AI_ERROR_SOURCES.REQUEST,
9519
+ facts: { parameter: "provider", reason: "not_allowed", allowed: ["openai"], value: context.provider, ...skips, inputs: ["provider"] }
9520
+ });
9521
+ case "disabled":
9522
+ return new MuxAiError(message, {
9523
+ code: MUX_AI_ERROR_CODES.INVALID_PARAMETER,
9524
+ type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR,
9525
+ source: MUX_AI_ERROR_SOURCES.REQUEST,
9526
+ facts: { parameter: "includeTranscript", reason: "audio_only", allowed: [true], value: false, ...skips, inputs: ["includeTranscript"] }
9527
+ });
9528
+ case "no_ready_text_track": {
9529
+ const availableLanguages = getReadyTextTracks(context.asset).map((track) => track.language_code).filter((code) => !!code);
9530
+ return new MuxAiError(message, {
9531
+ code: MUX_AI_ERROR_CODES.CAPTION_TRACK_NOT_FOUND,
9532
+ type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR,
9533
+ source: MUX_AI_ERROR_SOURCES.ASSET,
9534
+ facts: { ...context.languageCode && { languageCode: context.languageCode }, availableLanguages, ...skips }
9535
+ });
9336
9536
  }
9537
+ case "no_cues":
9538
+ if (context.transcriptEmptyCause === "no_scoped_cues") {
9539
+ return invalidScopeError(message, {
9540
+ reason: "no_transcript",
9541
+ ...context.captionTrackId && { trackId: context.captionTrackId },
9542
+ ...context.scope?.startTime !== void 0 && { startTime: context.scope.startTime },
9543
+ ...context.scope?.endTime !== void 0 && { endTime: context.scope.endTime },
9544
+ ...skips
9545
+ }, ["scope"]);
9546
+ }
9547
+ return new MuxAiError(message, {
9548
+ code: MUX_AI_ERROR_CODES.TRANSCRIPT_EMPTY,
9549
+ type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR,
9550
+ source: MUX_AI_ERROR_SOURCES.ASSET,
9551
+ facts: { ...context.captionTrackId && { trackId: context.captionTrackId }, ...context.transcriptEmptyCause && { reason: context.transcriptEmptyCause }, ...skips }
9552
+ });
9553
+ case void 0:
9554
+ return internalError(message, skips);
9555
+ default:
9556
+ return assertNever(transcriptModeration.skipReason, "transcript skip reason");
9337
9557
  }
9338
9558
  }
9559
+ var SAMPLE_SPECIFIC_CODES = /* @__PURE__ */ new Set([
9560
+ MUX_AI_ERROR_CODES.IMAGE_UNPROCESSABLE,
9561
+ MUX_AI_ERROR_CODES.MODEL_OUTPUT_INVALID,
9562
+ MUX_AI_ERROR_CODES.DEPENDENCY_RESPONSE_FAILED
9563
+ ]);
9564
+ function isSampleSpecific(error) {
9565
+ return error.source === MUX_AI_ERROR_SOURCES.ASSET || error.code !== void 0 && SAMPLE_SPECIFIC_CODES.has(error.code);
9566
+ }
9567
+ function allSamplesFailedError(message, failures, facts) {
9568
+ const errors = failures.map(({ call, failure }) => failure ?? internalError(message, { ...facts, call }));
9569
+ const callWide = errors.filter((error) => !isSampleSpecific(error));
9570
+ const representative = callWide.find((error) => !error.transient) ?? callWide[0] ?? errors.find((error) => !error.transient) ?? errors[0];
9571
+ if (!representative) {
9572
+ return internalError(message, facts);
9573
+ }
9574
+ return new MuxAiError(message, {
9575
+ ...representative.code && { code: representative.code },
9576
+ type: representative.type,
9577
+ source: representative.source,
9578
+ ...representative.dependency && { dependency: representative.dependency },
9579
+ facts: { ...facts, ...representative.facts },
9580
+ transient: representative.transient,
9581
+ retryable: representative.retryable,
9582
+ cause: representative
9583
+ });
9584
+ }
9339
9585
  async function getModerationScores(assetId, options = {}) {
9340
9586
  "use workflow";
9341
9587
  const {
@@ -9354,7 +9600,23 @@ async function getModerationScores(assetId, options = {}) {
9354
9600
  scope
9355
9601
  } = options;
9356
9602
  const credentials = providedCredentials;
9357
- const { asset, playbackId, policy } = await getPlaybackIdForAsset(assetId, credentials, options.assetSnapshot);
9603
+ if (!MODERATION_PROVIDERS.includes(provider)) {
9604
+ throw new MuxAiError(`Unsupported moderation provider: ${String(provider)}`, {
9605
+ code: MUX_AI_ERROR_CODES.INVALID_PARAMETER,
9606
+ type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR,
9607
+ source: MUX_AI_ERROR_SOURCES.REQUEST,
9608
+ facts: { parameter: "provider", reason: "not_allowed", allowed: [...MODERATION_PROVIDERS], value: String(provider).slice(0, 100), inputs: ["provider"] }
9609
+ });
9610
+ }
9611
+ if (maxSamples !== void 0 && !(maxSamples > 0)) {
9612
+ throw new MuxAiError(`maxSamples must be a positive number (received ${String(maxSamples)}).`, {
9613
+ code: MUX_AI_ERROR_CODES.INVALID_PARAMETER,
9614
+ type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR,
9615
+ source: MUX_AI_ERROR_SOURCES.REQUEST,
9616
+ facts: { parameter: "maxSamples", reason: "not_positive", ...typeof maxSamples === "number" && Number.isFinite(maxSamples) && { value: maxSamples }, inputs: ["maxSamples"] }
9617
+ });
9618
+ }
9619
+ const { asset, playbackId, policy } = await getPlaybackIdForAsset(assetId, credentials, options.assetSnapshot, { classifiedErrors: true });
9358
9620
  const videoTrackDurationSeconds = getVideoTrackDurationSecondsFromAsset(asset);
9359
9621
  const videoTrackFps = getVideoTrackMaxFrameRateFromAsset(asset);
9360
9622
  const assetDurationSeconds = getAssetDurationSecondsFromAsset(asset);
@@ -9363,7 +9625,7 @@ async function getModerationScores(assetId, options = {}) {
9363
9625
  );
9364
9626
  const duration = candidateDurations.length > 0 ? Math.min(...candidateDurations) : 0;
9365
9627
  const effectiveScope = hasWorkflowScopeBoundaries(scope) ? scope : void 0;
9366
- const resolvedScope = effectiveScope ? resolveWorkflowScope(effectiveScope, assetDurationSeconds) : void 0;
9628
+ const resolvedScope = effectiveScope ? resolveWorkflowScope(effectiveScope, assetDurationSeconds, { classifiedErrors: true, assetId }) : void 0;
9367
9629
  const isAudioOnly = isAudioOnlyAsset(asset);
9368
9630
  const renderableScope = resolvedScope ? {
9369
9631
  startTime: Math.min(resolvedScope.startTime, duration),
@@ -9371,19 +9633,20 @@ async function getModerationScores(assetId, options = {}) {
9371
9633
  } : void 0;
9372
9634
  const signingContext = await resolveMuxSigningContext(credentials);
9373
9635
  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
- );
9636
+ throw signingCredentialsMissingError();
9377
9637
  }
9378
9638
  let thumbnailModeration = { status: "completed" };
9379
9639
  let thumbnailUrls = [];
9380
9640
  let shouldRunThumbnails = false;
9641
+ let thumbnailsUnsampled = false;
9381
9642
  if (isAudioOnly) {
9382
9643
  thumbnailModeration = {
9383
9644
  status: "skipped",
9384
9645
  skipReason: "no_video_track",
9385
9646
  skipMessage: "Asset has no video track, so there are no thumbnails to moderate."
9386
9647
  };
9648
+ } else if (duration <= 0) {
9649
+ thumbnailsUnsampled = true;
9387
9650
  } else if (renderableScope && renderableScope.startTime >= renderableScope.endTime) {
9388
9651
  thumbnailModeration = {
9389
9652
  status: "skipped",
@@ -9398,7 +9661,7 @@ async function getModerationScores(assetId, options = {}) {
9398
9661
  filterTimestampsWithinExclusiveScope(
9399
9662
  planSamplingTimestamps({
9400
9663
  duration_sec: duration,
9401
- max_candidates: maxSamples,
9664
+ max_candidates: Math.max(1, Math.floor(maxSamples)),
9402
9665
  trim_start_sec: renderableScope?.startTime ?? (duration > 2 ? Math.min(5, Math.max(1, duration / 6)) : 0),
9403
9666
  trim_end_sec: renderableScope ? duration - renderableScope.endTime : duration > 2 ? Math.min(5, Math.max(1, duration / 6)) : 0,
9404
9667
  fps: videoTrackFps,
@@ -9418,9 +9681,18 @@ async function getModerationScores(assetId, options = {}) {
9418
9681
  credentials,
9419
9682
  scope: renderableScope
9420
9683
  });
9421
- shouldRunThumbnails = true;
9684
+ if (thumbnailUrls.length > 0) {
9685
+ shouldRunThumbnails = true;
9686
+ } else {
9687
+ thumbnailModeration = {
9688
+ status: "skipped",
9689
+ skipReason: "no_video_in_scope",
9690
+ skipMessage: "The requested scope does not include any renderable video, so there are no thumbnails to moderate."
9691
+ };
9692
+ }
9422
9693
  }
9423
9694
  let transcriptModeration = { status: "completed" };
9695
+ let transcriptEmptyCause;
9424
9696
  let transcriptCues = [];
9425
9697
  let shouldRunTranscript = false;
9426
9698
  const transcriptEnabled = includeTranscript || isAudioOnly;
@@ -9445,14 +9717,22 @@ async function getModerationScores(assetId, options = {}) {
9445
9717
  };
9446
9718
  } else {
9447
9719
  if (!captionTrack.id) {
9448
- throw new LegacyMuxAiError("Transcript track is missing an id.", { type: "validation_error" });
9720
+ throw new MuxAiError("Transcript track is missing an id.", {
9721
+ code: MUX_AI_ERROR_CODES.CAPTION_TRACK_ID_MISSING,
9722
+ type: MUX_AI_ERROR_TYPES.PROCESSING_ERROR,
9723
+ source: MUX_AI_ERROR_SOURCES.UPSTREAM,
9724
+ dependency: MUX_AI_ERROR_DEPENDENCIES.MUX_VIDEO,
9725
+ facts: { assetId, ...captionTrack.language_code && { languageCode: captionTrack.language_code } }
9726
+ });
9449
9727
  }
9450
9728
  const transcriptUrl = await buildTranscriptUrl(playbackId, captionTrack.id, policy === "signed", credentials);
9451
9729
  const { transcriptText, emptyReason } = await fetchTranscriptDataForUrl(transcriptUrl, {
9452
9730
  cleanTranscript: false,
9453
- scope: effectiveScope
9731
+ scope: effectiveScope,
9732
+ classifiedErrors: true
9454
9733
  });
9455
9734
  if (emptyReason) {
9735
+ transcriptEmptyCause = emptyReason;
9456
9736
  transcriptModeration = {
9457
9737
  status: "skipped",
9458
9738
  skipReason: "no_cues",
@@ -9462,6 +9742,7 @@ async function getModerationScores(assetId, options = {}) {
9462
9742
  transcriptCues = parseVTTCues(transcriptText, { capCueText: false });
9463
9743
  const windows = transcriptCues.length === 0 ? [] : buildTranscriptWindows(transcriptCues, duration);
9464
9744
  if (windows.length === 0) {
9745
+ transcriptEmptyCause = "no_parseable_cues";
9465
9746
  transcriptModeration = {
9466
9747
  status: "skipped",
9467
9748
  skipReason: "no_cues",
@@ -9472,10 +9753,30 @@ async function getModerationScores(assetId, options = {}) {
9472
9753
  }
9473
9754
  }
9474
9755
  }
9756
+ if (thumbnailsUnsampled && !shouldRunTranscript) {
9757
+ throw new MuxAiError(`Nothing to moderate: asset ${assetId} has no valid duration to sample thumbnails from, and the transcript was skipped: ${transcriptModeration.skipMessage}`, {
9758
+ code: MUX_AI_ERROR_CODES.ASSET_DURATION_UNAVAILABLE,
9759
+ type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR,
9760
+ source: MUX_AI_ERROR_SOURCES.ASSET,
9761
+ facts: { assetId, ...transcriptModeration.skipReason && { transcriptSkipReason: transcriptModeration.skipReason } }
9762
+ });
9763
+ }
9475
9764
  if (!shouldRunThumbnails && !shouldRunTranscript) {
9476
- throw new LegacyMuxAiError(
9765
+ throw nothingToModerateError(
9477
9766
  `Nothing to moderate. Thumbnails skipped: ${thumbnailModeration.skipMessage} Transcript skipped: ${transcriptModeration.skipMessage}`,
9478
- { type: "validation_error" }
9767
+ {
9768
+ assetId,
9769
+ asset,
9770
+ provider,
9771
+ languageCode,
9772
+ thumbnailModeration,
9773
+ transcriptModeration,
9774
+ transcriptEmptyCause,
9775
+ captionTrackId: captionTrack?.id,
9776
+ scope: effectiveScope,
9777
+ resolvedScope,
9778
+ videoEndTime: duration
9779
+ }
9479
9780
  );
9480
9781
  }
9481
9782
  const [thumbnailScores, transcriptScores] = await Promise.all([
@@ -9497,15 +9798,17 @@ async function getModerationScores(assetId, options = {}) {
9497
9798
  const mode = shouldRunThumbnails && shouldRunTranscript ? "combined" : shouldRunTranscript ? "transcript" : "thumbnails";
9498
9799
  const thumbnailCount = shouldRunThumbnails ? thumbnailUrls.length : void 0;
9499
9800
  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` }))
9801
+ ...thumbnailScores.map((s) => ({ ...s, label: s.time === void 0 ? "thumbnail" : `thumbnail at ${s.time}s`, call: "moderate_thumbnails" })),
9802
+ ...transcriptScores.map((s) => ({ ...s, error: s.error ?? false, label: `transcript window ${s.startTime}-${s.endTime}s`, call: "moderate_transcript" }))
9502
9803
  ];
9503
9804
  const failed = allScores.filter((s) => s.error);
9504
9805
  const successful = allScores.filter((s) => !s.error);
9505
9806
  if (successful.length === 0) {
9506
9807
  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}`
9808
+ throw allSamplesFailedError(
9809
+ `Moderation failed for all ${allScores.length} sample(s): ${details}`,
9810
+ failed,
9811
+ { provider, ...model && { model }, assetId, sampleCount: allScores.length }
9509
9812
  );
9510
9813
  }
9511
9814
  if (failed.length > 0) {
@@ -9550,8 +9853,8 @@ async function getModerationScores(assetId, options = {}) {
9550
9853
  assetId,
9551
9854
  mode,
9552
9855
  isAudioOnly,
9553
- thumbnailScores,
9554
- transcriptScores,
9856
+ thumbnailScores: thumbnailScores.map(withoutFailure),
9857
+ transcriptScores: transcriptScores.map(withoutFailure),
9555
9858
  thumbnailModeration,
9556
9859
  transcriptModeration,
9557
9860
  coverage: {
@@ -9579,7 +9882,7 @@ async function getModerationScores(assetId, options = {}) {
9579
9882
 
9580
9883
  // src/workflows/summarization.ts
9581
9884
  import { generateText as generateText8, Output as Output8 } from "ai";
9582
- import { z as z12 } from "zod";
9885
+ import { z as z13 } from "zod";
9583
9886
 
9584
9887
  // src/lib/markdown-normalization.ts
9585
9888
  var ESCAPED_LINE_BREAK_REGEX = /\\r\\n|\\n|\\r/g;
@@ -9724,17 +10027,17 @@ function createSummarizationGuidance({
9724
10027
  }
9725
10028
 
9726
10029
  // 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)
10030
+ var summarySchema = z13.object({
10031
+ keywords: z13.array(z13.string().max(200)),
10032
+ title: z13.string().max(500),
10033
+ description: z13.string().max(1e4)
9731
10034
  });
9732
10035
  function buildSummarySchema(descriptionLength) {
9733
10036
  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)
10037
+ return z13.object({
10038
+ keywords: z13.array(z13.string().max(200)),
10039
+ title: z13.string().max(500),
10040
+ description: z13.string().max(descriptionMaxChars)
9738
10041
  });
9739
10042
  }
9740
10043
  var VALID_TONES = ["neutral", "playful", "professional"];
@@ -11266,9 +11569,9 @@ async function translateAudio(assetId, toLanguageCode, options = {}) {
11266
11569
 
11267
11570
  // src/workflows/translate-captions.ts
11268
11571
  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()
11572
+ import { z as z14 } from "zod";
11573
+ var translationSchema = z14.object({
11574
+ translation: z14.string()
11272
11575
  });
11273
11576
  var SYSTEM_PROMPT5 = promptDedent`
11274
11577
  You are a subtitle translation expert. Translate VTT subtitle files to the target language specified by the user.
@@ -11632,8 +11935,8 @@ async function translateCueChunkWithAI({
11632
11935
  }) {
11633
11936
  "use step";
11634
11937
  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)
11938
+ const schema = z14.object({
11939
+ translations: z14.array(z14.string().min(1).max(2e3)).length(cues.length)
11637
11940
  });
11638
11941
  const cuePayload = cues.map((cue, index) => ({
11639
11942
  index,