@mux/ai 0.67.0 → 0.68.0-canary.112

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.
@@ -5,9 +5,6 @@ import { generateText, jsonSchema, NoObjectGeneratedError as NoObjectGeneratedEr
5
5
  import { APICallError as APICallError2, NoObjectGeneratedError, NoOutputGeneratedError as NoOutputGeneratedError2, RetryError, TypeValidationError } from "ai";
6
6
  import { z as z4 } from "zod";
7
7
 
8
- // src/lib/google-errors.ts
9
- import { z as z2 } from "zod";
10
-
11
8
  // node_modules/@workflow/serde/dist/index.js
12
9
  var WORKFLOW_SERIALIZE = /* @__PURE__ */ Symbol.for("workflow-serialize");
13
10
  var WORKFLOW_DESERIALIZE = /* @__PURE__ */ Symbol.for("workflow-deserialize");
@@ -577,9 +574,9 @@ var MUX_AI_ERROR_CODES = {
577
574
  INVALID_SCOPE: "invalid_scope",
578
575
  /** Existing tracks block writing the output track under the chosen replacement policy. Facts: `reason` (`policy_fail`, `not_generated`, `name_collision`, `primary_audio`), `conflictingTracks` and the target track, plus `sourceRestored` and `restoredTrackId` when a source track was deleted first. */
579
576
  TRACK_REPLACEMENT_BLOCKED: "track_replacement_blocked",
580
- /** An option's value can't be used. Facts: `parameter` (the caller's option name), `reason` (`too_many`, `empty`, `too_long`, `disallowed_characters`, `not_normalized`, `multiline`, `required_with`, `conflicts_with`, `not_allowed`, `one_of_required`, `audio_only`, `not_positive`) and the values the reason names: `count` and `max`, `index` (0-based entry), `length` and `maxLength`, `characters`, `with` and `withValue` (the other option), `allowed` and `value`, `parameters` (the options to choose from). */
577
+ /** An option's value can't be used. Facts: `parameter` (the caller's option name), `reason` (`too_many`, `empty`, `too_long`, `disallowed_characters`, `not_normalized`, `multiline`, `required_with`, `conflicts_with`, `not_allowed`, `one_of_required`, `audio_only`, `not_positive`, `invalid_format`, `duplicate`) and the values the reason names: `count` and `max`, `index` (0-based entry), `length` and `maxLength`, `characters`, `with` and `withValue` (the other option), `allowed` and `value`, `parameters` (the options to choose from), `format` (what the value must look like). `duplicate` is a list of keyed entries that repeats a key (`value`). */
581
578
  INVALID_PARAMETER: "invalid_parameter",
582
- /** A numeric option is outside its allowed range. Facts: `parameter` (the caller's option name), `value`, `min`, `max`, and `integer` when it must be a whole number. */
579
+ /** A numeric option is outside its allowed range. Facts: `parameter` (the caller's option name), `value`, `min`, `max`, `integer` when it must be a whole number, and `unit` when the bounds have one. The public wording names the bound that was crossed. */
583
580
  PARAMETER_OUT_OF_RANGE: "parameter_out_of_range",
584
581
  /** No ready caption track matches the requested track or language. Facts: `trackId` or `languageCode`, and what is available. */
585
582
  CAPTION_TRACK_NOT_FOUND: "caption_track_not_found",
@@ -1128,6 +1125,7 @@ function dependencyErrorFrom(error, message, init) {
1128
1125
  }
1129
1126
 
1130
1127
  // src/lib/google-errors.ts
1128
+ import { z as z2 } from "zod";
1131
1129
  var GoogleTokenSchema = z2.string().regex(/^[\w.-]{1,128}$/);
1132
1130
  var GoogleErrorBodySchema = z2.object({
1133
1131
  error: z2.object({
@@ -1587,6 +1585,15 @@ function classifyModelCallError(error, context) {
1587
1585
  if (unusable) {
1588
1586
  return unusable;
1589
1587
  }
1588
+ if (isClientTimeout(last)) {
1589
+ return withUsage(dependencyError(`${context.call} timed out`, {
1590
+ dependency: MUX_AI_ERROR_DEPENDENCIES.AI_PROVIDER,
1591
+ call: context.call,
1592
+ timedOut: true,
1593
+ facts: modelCallFacts(context),
1594
+ cause: error
1595
+ }), getErrorTokenUsage(error));
1596
+ }
1590
1597
  const apiError = findProviderCallError(error);
1591
1598
  if (!apiError) {
1592
1599
  return void 0;
@@ -1601,6 +1608,9 @@ function classifyModelCallError(error, context) {
1601
1608
  return void 0;
1602
1609
  }
1603
1610
  }
1611
+ function isClientTimeout(error) {
1612
+ return typeof error === "object" && error !== null && error.name === "TimeoutError";
1613
+ }
1604
1614
  function classifyUnusableOutput(last, error, context) {
1605
1615
  const parse = NoObjectGeneratedError.isInstance(last);
1606
1616
  if (!parse && !NoOutputGeneratedError2.isInstance(last)) {
@@ -1846,7 +1856,6 @@ function modelStepError(error, message, facts) {
1846
1856
  }
1847
1857
 
1848
1858
  // src/lib/model-call-diagnostics.ts
1849
- import { APICallError as APICallError3 } from "ai";
1850
1859
  function recordModelCallFailure(error, diagnostics, observedUsage = getErrorTokenUsage(error)) {
1851
1860
  if (typeof error !== "object" || error === null) {
1852
1861
  return;
@@ -1856,12 +1865,14 @@ function recordModelCallFailure(error, diagnostics, observedUsage = getErrorToke
1856
1865
  return;
1857
1866
  }
1858
1867
  failure.diagnostics = { ...diagnostics };
1868
+ const providerError = findProviderServiceError(error);
1869
+ const reported = providerError ?? error;
1859
1870
  console.warn("[@mux/ai] Model call failed.", {
1860
1871
  ...diagnostics,
1861
1872
  finishReason: failure.finishReason,
1862
- statusCode: failure.statusCode,
1863
- errorName: error instanceof Error ? error.name : void 0,
1864
- requestId: APICallError3.isInstance(error) ? error.responseHeaders?.["x-request-id"] ?? error.responseHeaders?.["request-id"] : void 0,
1873
+ statusCode: providerError?.statusCode ?? failure.statusCode,
1874
+ errorName: reported instanceof Error ? reported.name : void 0,
1875
+ requestId: providerError?.responseHeaders?.["x-request-id"] ?? providerError?.responseHeaders?.["request-id"],
1865
1876
  usage: observedUsage
1866
1877
  });
1867
1878
  }
@@ -1977,25 +1988,32 @@ function repairJsonSchema(plan) {
1977
1988
  properties: Object.fromEntries(plan.spans.map((span) => [span.id, { type: "string" }]))
1978
1989
  };
1979
1990
  }
1991
+ function rejected(code, reason) {
1992
+ return { accepted: false, code, reason };
1993
+ }
1980
1994
  function applyTextRepair(content, plan, replacements) {
1981
1995
  if (!replacements || typeof replacements !== "object" || Array.isArray(replacements))
1982
- return { accepted: false, reason: "Invalid replacement object" };
1996
+ return rejected("invalid_object", "Invalid replacement object");
1983
1997
  const values = replacements;
1984
1998
  if (Object.keys(values).length !== plan.spans.length || Object.keys(values).some((key) => !plan.spans.some((span) => span.id === key)))
1985
- return { accepted: false, reason: "Unexpected or missing span IDs" };
1999
+ return rejected("span_ids", "Unexpected or missing span IDs");
1986
2000
  const parts = split(content);
1987
2001
  for (const span of plan.spans) {
1988
2002
  const index = Number(span.id.slice(2));
1989
2003
  const replacement = values[span.id];
1990
2004
  if (parts[index] !== span.text)
1991
- return { accepted: false, reason: "Stale repair plan" };
1992
- if (typeof replacement !== "string" || !replacement.trim() || INVALID_REPLACEMENT.test(replacement) || introducesLiteralEscapes(span.text, replacement))
1993
- return { accepted: false, reason: "Empty or incompatible paragraph replacement" };
2005
+ return rejected("stale_plan", "Stale repair plan");
2006
+ if (typeof replacement !== "string" || !replacement.trim())
2007
+ return rejected("empty_replacement", "Empty or incompatible paragraph replacement");
2008
+ if (INVALID_REPLACEMENT.test(replacement))
2009
+ return rejected("split_paragraph", "Empty or incompatible paragraph replacement");
2010
+ if (introducesLiteralEscapes(span.text, replacement))
2011
+ return rejected("literal_escapes", "Empty or incompatible paragraph replacement");
1994
2012
  parts[index] = replacement;
1995
2013
  }
1996
2014
  const editedText = plan.spans.map((span) => values[span.id]).join("\n\n");
1997
2015
  if (plan.protectedTerms.some((term) => !editedText.includes(term)))
1998
- return { accepted: false, reason: "Protected term removed from edited spans" };
2016
+ return rejected("protected_term", "Protected term removed from edited spans");
1999
2017
  return { accepted: true, content: parts.join("") };
2000
2018
  }
2001
2019
  function introducesLiteralEscapes(source, replacement) {
@@ -2010,24 +2028,30 @@ async function runTextRepairLoop(options) {
2010
2028
  let content = options.content;
2011
2029
  const attempts = [];
2012
2030
  if (!content.trim())
2013
- return { status: "failed", attempts, reason: "Empty draft has no substance to preserve" };
2031
+ return { status: "failed", attempts, reason: "Empty draft has no substance to preserve", outcome: "empty_draft" };
2014
2032
  for (let index = 0; index < maxAttempts; index++) {
2015
2033
  if (!findGenerateTextLengthViolation(content, options.limits))
2016
2034
  return { status: "valid", content, attempts };
2017
2035
  const plan = planTextRepair(content, options.limits, options.protectedTerms);
2018
2036
  if (!plan)
2019
- return { status: "failed", attempts, reason: "No feasible span budget" };
2037
+ return { status: "failed", attempts, reason: "No feasible span budget", outcome: "no_plan" };
2020
2038
  const call = await options.generate(plan);
2021
2039
  const applied = applyTextRepair(content, plan, call.replacements);
2022
- attempts.push({ plan, call, rejection: applied.accepted ? void 0 : applied.reason });
2040
+ const overLimit = applied.accepted ? findGenerateTextLengthViolation(applied.content, options.limits) : void 0;
2041
+ attempts.push({
2042
+ plan,
2043
+ call,
2044
+ ...!applied.accepted && { rejection: applied.reason, rejectionCode: applied.code },
2045
+ ...overLimit && { overLimit }
2046
+ });
2023
2047
  if (call.error)
2024
- return { status: "failed", attempts, reason: call.error };
2025
- if (applied.accepted && !findGenerateTextLengthViolation(applied.content, options.limits))
2048
+ return { status: "failed", attempts, reason: call.error, outcome: "call_failed" };
2049
+ if (applied.accepted && !overLimit)
2026
2050
  return { status: "valid", content: applied.content, attempts };
2027
2051
  if (applied.accepted && options.limits.every((limit) => measureGenerateTextLength(applied.content, limit.unit) <= measureGenerateTextLength(content, limit.unit)))
2028
2052
  content = applied.content;
2029
2053
  }
2030
- return !findGenerateTextLengthViolation(content, options.limits) ? { status: "valid", content, attempts } : { status: "failed", attempts, reason: "Repair budget exhausted without a valid output" };
2054
+ return !findGenerateTextLengthViolation(content, options.limits) ? { status: "valid", content, attempts } : { status: "failed", attempts, reason: "Repair budget exhausted without a valid output", outcome: "exhausted" };
2031
2055
  }
2032
2056
 
2033
2057
  // src/lib/text-repair-model.ts
@@ -2061,15 +2085,15 @@ function createTextRepairGenerator(options) {
2061
2085
  onStepFinish: (step) => {
2062
2086
  usage = getErrorTokenUsage(step);
2063
2087
  }
2064
- }));
2088
+ }), options.context);
2065
2089
  usage = getErrorTokenUsage(response);
2066
- const output = getGeneratedOutputWithContentPolicyHandling(response);
2090
+ const output = getGeneratedOutputWithContentPolicyHandling(response, options.context);
2067
2091
  if (!output) {
2068
2092
  return { usage, elapsedMs: Date.now() - started, error: "Repair output missing" };
2069
2093
  }
2070
2094
  return { replacements: output, usage, elapsedMs: Date.now() - started };
2071
2095
  } catch (error) {
2072
- const cause = NoObjectGeneratedError2.isInstance(error) && error.finishReason && error.finishReason !== "stop" ? new IncompleteGenerationError(error.finishReason, void 0, getErrorTokenUsage(error)) : error;
2096
+ const cause = NoObjectGeneratedError2.isInstance(error) && error.finishReason && error.finishReason !== "stop" ? options.context ? incompleteGenerationError(error.finishReason, void 0, getErrorTokenUsage(error), options.context) : new IncompleteGenerationError(error.finishReason, void 0, getErrorTokenUsage(error)) : error;
2073
2097
  recordModelCallFailure(cause, {
2074
2098
  phase: "length_repair",
2075
2099
  provider: typeof options.model === "object" ? options.model.provider : "gateway",
@@ -7958,7 +7982,7 @@ async function generateEngagementInsightsInternal(assetId, options, collectedUsa
7958
7982
  }
7959
7983
 
7960
7984
  // src/workflows/generate-text.ts
7961
- import { APICallError as APICallError4, generateText as generateTextWithModel, Output as Output7 } from "ai";
7985
+ import { generateText as generateTextWithModel, Output as Output7 } from "ai";
7962
7986
  import { z as z11 } from "zod";
7963
7987
  var GENERATE_TEXT_MAX_VARIANTS = 5;
7964
7988
  var GENERATE_TEXT_MAX_ARTIFACTS = 5;
@@ -7981,96 +8005,151 @@ var GENERATE_TEXT_CHANNEL_CEILINGS = {
7981
8005
  x: { unit: "characters", value: 280 }
7982
8006
  };
7983
8007
  var KEY_PATTERN = /^[a-z][a-z0-9_]{0,63}$/;
8008
+ var KEY_FORMAT = "lowercase snake_case beginning with a letter, up to 64 characters";
7984
8009
  var LANGUAGE_TAG_PATTERN = /^[a-z]{2,3}(?:-[a-z0-9]{2,8})*$/i;
8010
+ var LANGUAGE_TAG_FORMAT = "a BCP 47 language tag such as 'en' or 'pt-BR'";
7985
8011
  var LENGTH_UNITS = ["characters", "words"];
7986
- function validationError(message) {
7987
- return new LegacyMuxAiError(message, { type: "validation_error" });
8012
+ function invalidOptionError3(message, facts, inputs) {
8013
+ return new MuxAiError(message, {
8014
+ code: MUX_AI_ERROR_CODES.INVALID_PARAMETER,
8015
+ type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR,
8016
+ source: MUX_AI_ERROR_SOURCES.REQUEST,
8017
+ facts: { ...facts, inputs }
8018
+ });
8019
+ }
8020
+ function outOfRangeError(message, facts, inputs) {
8021
+ return new MuxAiError(message, {
8022
+ code: MUX_AI_ERROR_CODES.PARAMETER_OUT_OF_RANGE,
8023
+ type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR,
8024
+ source: MUX_AI_ERROR_SOURCES.REQUEST,
8025
+ facts: { ...facts, inputs }
8026
+ });
8027
+ }
8028
+ var ECHOABLE_VALUE = /^[\w.-]{1,40}$/;
8029
+ function echoableValue(value) {
8030
+ return typeof value === "string" && ECHOABLE_VALUE.test(value) ? { value } : {};
7988
8031
  }
7989
- function assertOneOf(value, allowed, label) {
8032
+ function assertOneOf(value, allowed, label, parameter, input) {
7990
8033
  if (!allowed.includes(value)) {
7991
- throw validationError(`Invalid ${label} "${value}". Valid values are: ${allowed.join(", ")}.`);
8034
+ throw invalidOptionError3(
8035
+ `Invalid ${label} "${value}". Valid values are: ${allowed.join(", ")}.`,
8036
+ { parameter, reason: "not_allowed", allowed: [...allowed], ...echoableValue(value) },
8037
+ [input]
8038
+ );
7992
8039
  }
7993
8040
  }
7994
- function assertBoundedText(value, max, label) {
8041
+ function assertBoundedText(value, max, label, parameter, input) {
7995
8042
  const length = value.trim().length;
7996
8043
  if (length === 0 || length > max) {
7997
- throw validationError(`${label} must be 1-${max} characters.`);
8044
+ throw invalidOptionError3(
8045
+ `${label} must be 1-${max} characters.`,
8046
+ length === 0 ? { parameter, reason: "empty" } : { parameter, reason: "too_long", length, maxLength: max },
8047
+ [input]
8048
+ );
7998
8049
  }
7999
8050
  return length;
8000
8051
  }
8001
- function assertKeyedItems(items, noun, max) {
8052
+ function assertKeyedItems(items, noun, parameter, max) {
8002
8053
  if (items.length === 0) {
8003
- throw validationError(`At least one ${noun} is required.`);
8054
+ throw invalidOptionError3(`At least one ${noun} is required.`, { parameter, reason: "empty" }, [parameter]);
8004
8055
  }
8005
8056
  if (items.length > max) {
8006
- throw validationError(`At most ${max} ${noun}s are supported (received ${items.length}).`);
8057
+ throw invalidOptionError3(
8058
+ `At most ${max} ${noun}s are supported (received ${items.length}).`,
8059
+ { parameter, reason: "too_many", count: items.length, max },
8060
+ [parameter]
8061
+ );
8007
8062
  }
8008
8063
  const seen = /* @__PURE__ */ new Set();
8009
- for (const { key, instructions } of items) {
8064
+ items.forEach(({ key, instructions }, index) => {
8010
8065
  if (!KEY_PATTERN.test(key ?? "")) {
8011
- throw validationError(`${noun} key "${key}" must be lowercase snake_case beginning with a letter, up to 64 characters.`);
8066
+ throw invalidOptionError3(
8067
+ `${noun} key "${key}" must be lowercase snake_case beginning with a letter, up to 64 characters.`,
8068
+ { parameter: `${parameter}[${index}].key`, reason: "invalid_format", format: KEY_FORMAT },
8069
+ [parameter]
8070
+ );
8012
8071
  }
8013
8072
  if (seen.has(key)) {
8014
- throw validationError(`Duplicate ${noun} key "${key}".`);
8073
+ throw invalidOptionError3(`Duplicate ${noun} key "${key}".`, { parameter, reason: "duplicate", value: key, index }, [parameter]);
8015
8074
  }
8016
8075
  seen.add(key);
8017
8076
  if (instructions !== void 0) {
8018
- assertBoundedText(instructions, GENERATE_TEXT_MAX_INSTRUCTIONS_CHARS, `${noun} "${key}" instructions`);
8077
+ assertBoundedText(instructions, GENERATE_TEXT_MAX_INSTRUCTIONS_CHARS, `${noun} "${key}" instructions`, `${parameter}[${index}].instructions`, parameter);
8019
8078
  }
8020
- }
8079
+ });
8021
8080
  }
8022
- function assertArtifact(artifact) {
8081
+ function assertArtifact(artifact, index) {
8082
+ const parameter = `artifacts[${index}]`;
8023
8083
  if (artifact.channel !== void 0) {
8024
- assertOneOf(artifact.channel, GENERATE_TEXT_CHANNELS, `artifact "${artifact.key}" channel`);
8084
+ assertOneOf(artifact.channel, GENERATE_TEXT_CHANNELS, `artifact "${artifact.key}" channel`, `${parameter}.channel`, "artifacts");
8025
8085
  }
8026
8086
  if (artifact.format !== void 0) {
8027
- assertOneOf(artifact.format, GENERATE_TEXT_FORMATS, `artifact "${artifact.key}" format`);
8087
+ assertOneOf(artifact.format, GENERATE_TEXT_FORMATS, `artifact "${artifact.key}" format`, `${parameter}.format`, "artifacts");
8028
8088
  }
8029
8089
  if (artifact.maxLength === void 0) {
8030
8090
  return;
8031
8091
  }
8032
8092
  const { unit, value } = artifact.maxLength;
8033
- assertOneOf(unit, LENGTH_UNITS, `artifact "${artifact.key}" maxLength.unit`);
8093
+ assertOneOf(unit, LENGTH_UNITS, `artifact "${artifact.key}" maxLength.unit`, `${parameter}.maxLength.unit`, "artifacts");
8034
8094
  const bounds = GENERATE_TEXT_LENGTH_BOUNDS[unit];
8035
8095
  if (!Number.isInteger(value) || value < bounds.min || value > bounds.max) {
8036
- throw validationError(`Artifact "${artifact.key}" maxLength.value must be an integer between ${bounds.min} and ${bounds.max} (received ${value}).`);
8096
+ throw outOfRangeError(
8097
+ `Artifact "${artifact.key}" maxLength.value must be an integer between ${bounds.min} and ${bounds.max} ${unit} (received ${value}).`,
8098
+ { parameter: `${parameter}.maxLength.value`, ...typeof value === "number" ? { value: Number.isFinite(value) ? value : String(value) } : echoableValue(value), min: bounds.min, max: bounds.max, integer: true, unit },
8099
+ ["artifacts"]
8100
+ );
8037
8101
  }
8038
8102
  const ceiling = artifact.channel ? GENERATE_TEXT_CHANNEL_CEILINGS[artifact.channel] : void 0;
8039
8103
  if (ceiling && ceiling.unit === unit && value > ceiling.value) {
8040
- throw validationError(`Artifact "${artifact.key}" targets ${artifact.channel} and supports at most ${ceiling.value} ${ceiling.unit}.`);
8104
+ throw outOfRangeError(
8105
+ `Artifact "${artifact.key}" targets ${artifact.channel} and supports at most ${ceiling.value} ${ceiling.unit}.`,
8106
+ { parameter: `${parameter}.maxLength.value`, value, min: bounds.min, max: ceiling.value, integer: true, unit, channel: artifact.channel },
8107
+ ["artifacts"]
8108
+ );
8041
8109
  }
8042
8110
  }
8043
- function assertLanguageTag(value, label) {
8111
+ function assertLanguageTag(value, parameter) {
8044
8112
  if (value.length > 35 || !LANGUAGE_TAG_PATTERN.test(value)) {
8045
- throw validationError(`${label} must be a BCP 47 language tag such as "en" or "pt-BR".`);
8113
+ throw invalidOptionError3(
8114
+ `${parameter} must be a BCP 47 language tag such as "en" or "pt-BR".`,
8115
+ { parameter, reason: "invalid_format", format: LANGUAGE_TAG_FORMAT },
8116
+ [parameter]
8117
+ );
8046
8118
  }
8047
8119
  }
8048
8120
  function resolveGenerateTextOptions(options) {
8049
8121
  const variants = options.variants ?? [{ key: "default" }];
8050
- assertKeyedItems(variants, "variant", GENERATE_TEXT_MAX_VARIANTS);
8051
- assertKeyedItems(options.artifacts, "artifact", GENERATE_TEXT_MAX_ARTIFACTS);
8052
- for (const artifact of options.artifacts) {
8053
- assertArtifact(artifact);
8054
- }
8122
+ assertKeyedItems(variants, "variant", "variants", GENERATE_TEXT_MAX_VARIANTS);
8123
+ assertKeyedItems(options.artifacts, "artifact", "artifacts", GENERATE_TEXT_MAX_ARTIFACTS);
8124
+ options.artifacts.forEach(assertArtifact);
8055
8125
  if (options.audience !== void 0) {
8056
- assertBoundedText(options.audience, GENERATE_TEXT_MAX_AUDIENCE_CHARS, "audience");
8126
+ assertBoundedText(options.audience, GENERATE_TEXT_MAX_AUDIENCE_CHARS, "audience", "audience", "audience");
8057
8127
  }
8058
8128
  if (options.voice !== void 0) {
8059
- assertOneOf(options.voice, GENERATE_TEXT_VOICES, "voice");
8129
+ assertOneOf(options.voice, GENERATE_TEXT_VOICES, "voice", "voice", "voice");
8060
8130
  }
8061
8131
  if (options.callToAction !== void 0) {
8062
- assertOneOf(options.callToAction, GENERATE_TEXT_CALLS_TO_ACTION, "callToAction");
8132
+ assertOneOf(options.callToAction, GENERATE_TEXT_CALLS_TO_ACTION, "callToAction", "callToAction", "callToAction");
8063
8133
  }
8064
8134
  if (options.brandTerms !== void 0) {
8065
- if (options.brandTerms.length === 0 || options.brandTerms.length > GENERATE_TEXT_MAX_BRAND_TERMS) {
8066
- throw validationError(`brandTerms must contain 1-${GENERATE_TEXT_MAX_BRAND_TERMS} terms.`);
8135
+ const count = options.brandTerms.length;
8136
+ if (count === 0 || count > GENERATE_TEXT_MAX_BRAND_TERMS) {
8137
+ throw invalidOptionError3(
8138
+ `brandTerms must contain 1-${GENERATE_TEXT_MAX_BRAND_TERMS} terms.`,
8139
+ count === 0 ? { parameter: "brandTerms", reason: "empty" } : { parameter: "brandTerms", reason: "too_many", count, max: GENERATE_TEXT_MAX_BRAND_TERMS },
8140
+ ["brandTerms"]
8141
+ );
8067
8142
  }
8068
8143
  const total = options.brandTerms.reduce(
8069
- (sum, term) => sum + assertBoundedText(term, GENERATE_TEXT_MAX_BRAND_TERM_CHARS, "Each brand term"),
8144
+ (sum, term, index) => sum + assertBoundedText(term, GENERATE_TEXT_MAX_BRAND_TERM_CHARS, "Each brand term", `brandTerms[${index}]`, "brandTerms"),
8070
8145
  0
8071
8146
  );
8072
8147
  if (total > GENERATE_TEXT_MAX_BRAND_TERMS_TOTAL_CHARS) {
8073
- throw validationError(`Combined brandTerms must be ${GENERATE_TEXT_MAX_BRAND_TERMS_TOTAL_CHARS} characters or fewer.`);
8148
+ throw invalidOptionError3(
8149
+ `Combined brandTerms must be ${GENERATE_TEXT_MAX_BRAND_TERMS_TOTAL_CHARS} characters or fewer.`,
8150
+ { parameter: "brandTerms", reason: "too_long", length: total, maxLength: GENERATE_TEXT_MAX_BRAND_TERMS_TOTAL_CHARS },
8151
+ ["brandTerms"]
8152
+ );
8074
8153
  }
8075
8154
  }
8076
8155
  if (options.languageCode !== void 0) {
@@ -8164,14 +8243,20 @@ function clampBriefArrays(brief) {
8164
8243
  }
8165
8244
  return clamped;
8166
8245
  }
8167
- function scrubBrief(brief, safety) {
8246
+ function scrubBrief(brief, safety, facts) {
8168
8247
  const centralIdea = safety.scrubDetailed(brief.centralIdea, "editorial_brief.centralIdea");
8169
8248
  const readerValue = safety.scrubDetailed(brief.readerValue, "editorial_brief.readerValue");
8170
8249
  if (centralIdea.leaked || readerValue.leaked || !centralIdea.text.trim()) {
8171
- throw new LegacyMuxAiError(
8172
- "The editorial brief was suppressed by the output safety filter.",
8173
- { type: "processing_error", retryable: true }
8174
- );
8250
+ throw new MuxAiError("The editorial brief was suppressed by the output safety filter.", {
8251
+ code: MUX_AI_ERROR_CODES.MODEL_OUTPUT_SUPPRESSED,
8252
+ type: MUX_AI_ERROR_TYPES.PROCESSING_ERROR,
8253
+ source: MUX_AI_ERROR_SOURCES.UPSTREAM,
8254
+ dependency: MUX_AI_ERROR_DEPENDENCIES.AI_PROVIDER,
8255
+ facts,
8256
+ // Resubmittable, as before classification: a new brief may not trip the filter.
8257
+ transient: false,
8258
+ retryable: true
8259
+ });
8175
8260
  }
8176
8261
  const scrubbed = { ...brief, centralIdea: centralIdea.text, readerValue: readerValue.text };
8177
8262
  for (const field of Object.keys(BRIEF_LIST_LIMITS)) {
@@ -8368,10 +8453,65 @@ function describeLengthRevision({ limit, actual }) {
8368
8453
  function readUsage(response) {
8369
8454
  return getErrorTokenUsage(response) ?? {};
8370
8455
  }
8456
+ function invalidModelOutputError(context, cause) {
8457
+ return new MuxAiError(`${context.call} returned output that doesn't match its schema`, {
8458
+ code: MUX_AI_ERROR_CODES.MODEL_OUTPUT_INVALID,
8459
+ type: MUX_AI_ERROR_TYPES.PROCESSING_ERROR,
8460
+ source: MUX_AI_ERROR_SOURCES.UPSTREAM,
8461
+ dependency: MUX_AI_ERROR_DEPENDENCIES.AI_PROVIDER,
8462
+ facts: { call: context.call, provider: context.provider, ...context.model && { model: context.model } },
8463
+ transient: true,
8464
+ cause
8465
+ });
8466
+ }
8467
+ function lengthRepairError(repaired, context, draft) {
8468
+ const cause = repaired.attempts.at(-1)?.call.errorCause;
8469
+ const facts = { call: context.call, provider: context.provider, ...context.model && { model: context.model } };
8470
+ if (cause === void 0) {
8471
+ return new MuxAiError("Unable to bring the generated text within its length limit.", {
8472
+ code: MUX_AI_ERROR_CODES.MODEL_OUTPUT_INVALID,
8473
+ type: MUX_AI_ERROR_TYPES.PROCESSING_ERROR,
8474
+ source: MUX_AI_ERROR_SOURCES.UPSTREAM,
8475
+ dependency: MUX_AI_ERROR_DEPENDENCIES.AI_PROVIDER,
8476
+ // The draft's own length, then why the repair stopped (no feasible plan, or its calls
8477
+ // used up) and what each call produced: rejected replacements, or text still over a limit.
8478
+ facts: {
8479
+ ...facts,
8480
+ reason: "over_length",
8481
+ limitUnit: draft.limit.unit,
8482
+ limit: draft.limit.value,
8483
+ actual: draft.actual,
8484
+ ...repaired.outcome && { repairOutcome: repaired.outcome },
8485
+ repairAttempts: repaired.attempts.map((attempt) => attempt.rejectionCode ? { rejection: attempt.rejectionCode } : attempt.overLimit ? { limitUnit: attempt.overLimit.limit.unit, limit: attempt.overLimit.limit.value, actual: attempt.overLimit.actual } : {})
8486
+ },
8487
+ transient: false,
8488
+ retryable: true
8489
+ });
8490
+ }
8491
+ const classified = MuxAiError.is(cause) ? cause : modelStepError(cause, "Unable to complete text generation.", { ...context });
8492
+ const retryable = classified.dependency ? classified.retryable : findProviderServiceError(cause)?.isRetryable ?? true;
8493
+ const failure = classified.transient || classified.retryable !== retryable ? new MuxAiError(classified.message, {
8494
+ ...classified.code && { code: classified.code },
8495
+ type: classified.type,
8496
+ source: classified.source,
8497
+ ...classified.dependency && { dependency: classified.dependency },
8498
+ facts: classified.facts,
8499
+ transient: false,
8500
+ retryable,
8501
+ // The raw failure, so the cause chain stays the provider's own error, not a second wrapper of it.
8502
+ cause: MuxAiError.is(cause) ? classified.cause ?? classified : cause
8503
+ }) : classified;
8504
+ delete failure.usage;
8505
+ if (typeof cause === "object" && cause !== null && "diagnostics" in cause) {
8506
+ failure.diagnostics = cause.diagnostics;
8507
+ }
8508
+ return failure;
8509
+ }
8371
8510
  async function extractBriefWithModel(args) {
8372
8511
  "use step";
8373
8512
  return withModelCallDiagnostics({ phase: "brief", provider: args.provider, modelId: args.modelId }, async () => {
8374
8513
  const model = await createLanguageModelFromConfig(args.provider, args.modelId, args.credentials);
8514
+ const context = { call: "extract_brief", provider: args.provider, model: args.modelId };
8375
8515
  const response = await withContentPolicyAwareRetry(() => generateTextWithModel({
8376
8516
  model,
8377
8517
  maxRetries: 0,
@@ -8390,13 +8530,16 @@ async function extractBriefWithModel(args) {
8390
8530
  ]
8391
8531
  }
8392
8532
  ]
8393
- }));
8394
- const output = getGeneratedOutputWithContentPolicyHandling(response);
8395
- if (!output) {
8396
- throw new Error("Editorial brief output missing");
8533
+ }), void 0, context).catch((error) => {
8534
+ throw modelStepError(error, "Editorial brief model call failed", { ...context });
8535
+ });
8536
+ const output = getGeneratedOutputWithContentPolicyHandling(response, context);
8537
+ const parsed = briefSchema.safeParse(output);
8538
+ if (!parsed.success) {
8539
+ throw invalidModelOutputError(context, parsed.error);
8397
8540
  }
8398
8541
  return {
8399
- brief: clampBriefArrays(briefSchema.parse(output)),
8542
+ brief: clampBriefArrays(parsed.data),
8400
8543
  usage: readUsage(response),
8401
8544
  unexpectedKeys: detectUnexpectedKeysFromRawText(response.text, briefSchema.keyof().options)
8402
8545
  };
@@ -8408,6 +8551,7 @@ async function generateArtifactWithModel(args) {
8408
8551
  const diagnostics = { phase: "draft", provider: args.provider, modelId: args.modelId };
8409
8552
  return withModelCallDiagnostics(diagnostics, async () => {
8410
8553
  const model = await createLanguageModelFromConfig(args.provider, args.modelId, args.credentials);
8554
+ const context = { call: "generate_artifact", provider: args.provider, model: args.modelId };
8411
8555
  const attempt = async (messages) => {
8412
8556
  const response = await withContentPolicyAwareRetry(() => generateTextWithModel({
8413
8557
  model,
@@ -8419,13 +8563,16 @@ async function generateArtifactWithModel(args) {
8419
8563
  }),
8420
8564
  system: args.systemPrompt,
8421
8565
  messages
8422
- }));
8423
- const output = getGeneratedOutputWithContentPolicyHandling(response);
8424
- if (!output) {
8425
- throw new Error("Generated text output missing");
8566
+ }), void 0, context).catch((error) => {
8567
+ throw modelStepError(error, "Text generation model call failed", { ...context });
8568
+ });
8569
+ const output = getGeneratedOutputWithContentPolicyHandling(response, context);
8570
+ const parsed = artifactSchema.safeParse(output);
8571
+ if (!parsed.success) {
8572
+ throw invalidModelOutputError(context, parsed.error);
8426
8573
  }
8427
8574
  return {
8428
- content: artifactSchema.parse(output).content.trim(),
8575
+ content: parsed.data.content.trim(),
8429
8576
  usage: readUsage(response),
8430
8577
  unexpectedKeys: detectUnexpectedKeysFromRawText(response.text, artifactSchema.keyof().options)
8431
8578
  };
@@ -8463,28 +8610,12 @@ ${renderSection({ tag: "revision_request", content: "The previous draft was empt
8463
8610
  content: candidate.content,
8464
8611
  limits: args.limits,
8465
8612
  protectedTerms: args.protectedTerms,
8466
- model
8613
+ model,
8614
+ context
8467
8615
  });
8468
8616
  usages.push(...repaired.attempts.flatMap((item) => item.call.usage ? [item.call.usage] : []));
8469
8617
  if (repaired.status !== "valid") {
8470
- const cause = repaired.attempts.at(-1)?.call.errorCause;
8471
- let failure;
8472
- if (isIncompleteGenerationError(cause)) {
8473
- failure = new IncompleteGenerationError(cause.finishReason, cause.rawFinishReason);
8474
- } else if (isLegacyMuxAiError(cause)) {
8475
- failure = new LegacyMuxAiError(cause.publicMessage, { type: cause.publicType, retryable: cause.retryable });
8476
- } else {
8477
- const apiError = APICallError4.isInstance(cause) ? cause : void 0;
8478
- failure = new LegacyMuxAiError("Unable to complete text generation.", {
8479
- type: "processing_error",
8480
- retryable: apiError?.isRetryable ?? true,
8481
- cause
8482
- });
8483
- }
8484
- if (typeof cause === "object" && cause !== null && "diagnostics" in cause) {
8485
- failure.diagnostics = cause.diagnostics;
8486
- }
8487
- rethrowWithTokenUsage(failure, usages);
8618
+ rethrowWithTokenUsage(lengthRepairError(repaired, context, violation), usages);
8488
8619
  }
8489
8620
  return { content: repaired.content, usages, unexpectedKeys };
8490
8621
  });
@@ -8498,7 +8629,7 @@ async function generateText7(assetId, options) {
8498
8629
  rethrowWithTokenUsage(error, collectedUsage);
8499
8630
  }
8500
8631
  }
8501
- async function generateArtifactsInBatches(requests, collectedUsage, provider) {
8632
+ async function generateArtifactsInBatches(requests, collectedUsage, provider, model, assetId) {
8502
8633
  const results = [];
8503
8634
  for (let start = 0; start < requests.length; start += GENERATE_TEXT_MAX_CONCURRENT_GENERATIONS) {
8504
8635
  const batch = requests.slice(start, start + GENERATE_TEXT_MAX_CONCURRENT_GENERATIONS);
@@ -8519,7 +8650,7 @@ async function generateArtifactsInBatches(requests, collectedUsage, provider) {
8519
8650
  collectedUsage.push(usage);
8520
8651
  }
8521
8652
  }
8522
- legacyWrapError(failures[0], `Failed to generate text with ${provider}`);
8653
+ wrapError(failures[0], `Failed to generate text with ${provider}`, { call: "generate_artifact", provider, model, assetId });
8523
8654
  }
8524
8655
  }
8525
8656
  return results;
@@ -8546,28 +8677,35 @@ async function generateTextInternal(assetId, rawOptions, collectedUsage) {
8546
8677
  model,
8547
8678
  provider
8548
8679
  });
8549
- const { asset, playbackId, policy } = await getPlaybackIdForAsset(assetId, credentials, options.assetSnapshot);
8680
+ const { asset, playbackId, policy } = await getPlaybackIdForAsset(assetId, credentials, options.assetSnapshot, { classifiedErrors: true });
8550
8681
  const assetDurationSeconds = getAssetDurationSecondsFromAsset(asset);
8551
8682
  const isAudioOnly = isAudioOnlyAsset(asset);
8552
8683
  const effectiveScope = hasWorkflowScopeBoundaries(scope) ? scope : void 0;
8553
- const resolvedScope = effectiveScope ? resolveWorkflowScope(effectiveScope, assetDurationSeconds) : void 0;
8684
+ const resolvedScope = effectiveScope ? resolveWorkflowScope(effectiveScope, assetDurationSeconds, { classifiedErrors: true, assetId }) : void 0;
8554
8685
  const storyboardScope = isAudioOnly ? void 0 : resolveRenderableVideoScope(
8555
8686
  effectiveScope,
8556
8687
  assetDurationSeconds,
8557
- getVideoTrackDurationSecondsFromAsset(asset)
8688
+ getVideoTrackDurationSecondsFromAsset(asset),
8689
+ { classifiedErrors: true, assetId }
8558
8690
  );
8559
8691
  if (useShots && isAudioOnly) {
8560
- throw new LegacyMuxAiError("useShots is not supported for audio-only assets.", { type: "validation_error" });
8692
+ throw invalidOptionError3(
8693
+ "useShots is not supported for audio-only assets.",
8694
+ { parameter: "useShots", reason: "audio_only", allowed: [false], value: true, assetId },
8695
+ ["useShots"]
8696
+ );
8561
8697
  }
8562
8698
  if (useShots && assetDurationSeconds === void 0) {
8563
- throw new LegacyMuxAiError("Asset has no valid duration.", { type: "validation_error" });
8699
+ throw new MuxAiError("Asset has no valid duration.", {
8700
+ code: MUX_AI_ERROR_CODES.ASSET_DURATION_UNAVAILABLE,
8701
+ type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR,
8702
+ source: MUX_AI_ERROR_SOURCES.ASSET,
8703
+ facts: { assetId }
8704
+ });
8564
8705
  }
8565
8706
  const signingContext = await resolveMuxSigningContext(credentials);
8566
8707
  if (policy === "signed" && !signingContext) {
8567
- throw new LegacyMuxAiError(
8568
- "Signed playback ID requires signing credentials. Set MUX_SIGNING_KEY and MUX_PRIVATE_KEY environment variables.",
8569
- { type: "validation_error" }
8570
- );
8708
+ throw signingCredentialsMissingError();
8571
8709
  }
8572
8710
  const shouldSign = policy === "signed";
8573
8711
  const [transcriptResult, storyboardUrl, shotsResult] = await Promise.all([
@@ -8577,17 +8715,28 @@ async function generateTextInternal(assetId, rawOptions, collectedUsage) {
8577
8715
  shouldSign,
8578
8716
  credentials,
8579
8717
  required: true,
8580
- scope: effectiveScope
8718
+ scope: effectiveScope,
8719
+ classifiedErrors: true
8581
8720
  }),
8582
8721
  isAudioOnly ? void 0 : getStoryboardUrl(playbackId, 640, shouldSign, credentials, storyboardScope),
8583
8722
  useShots ? getCompletedShots(assetId, credentials) : void 0
8584
8723
  ]);
8585
8724
  const transcriptText = transcriptResult.transcriptText.trim();
8586
8725
  if (!transcriptText) {
8587
- throw new LegacyMuxAiError(
8588
- effectiveScope ? "Transcript has no usable content in the requested scope." : "Transcript has no usable content.",
8589
- { type: "validation_error" }
8590
- );
8726
+ const trackId = transcriptResult.track?.id;
8727
+ if (effectiveScope) {
8728
+ throw invalidScopeError(
8729
+ "Transcript has no usable content in the requested scope.",
8730
+ { reason: "no_transcript", ...trackId && { trackId }, ...effectiveScope.startTime !== void 0 && { startTime: effectiveScope.startTime }, ...effectiveScope.endTime !== void 0 && { endTime: effectiveScope.endTime } },
8731
+ ["scope"]
8732
+ );
8733
+ }
8734
+ throw new MuxAiError("Transcript has no usable content.", {
8735
+ code: MUX_AI_ERROR_CODES.TRANSCRIPT_EMPTY,
8736
+ type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR,
8737
+ source: MUX_AI_ERROR_SOURCES.ASSET,
8738
+ facts: { assetId, ...trackId && { trackId } }
8739
+ });
8591
8740
  }
8592
8741
  const resolvedLanguageCode = outputLanguageCode && outputLanguageCode !== "auto" ? outputLanguageCode : getReliableLanguageCode(transcriptResult.track);
8593
8742
  const languageName = resolvedLanguageCode ? getLanguageName(resolvedLanguageCode) : void 0;
@@ -8597,6 +8746,7 @@ async function generateTextInternal(assetId, rawOptions, collectedUsage) {
8597
8746
  }
8598
8747
  const steering = { audience, voice, callToAction, brandTerms };
8599
8748
  const safety = createSafetyReporter();
8749
+ const briefFacts = { call: "extract_brief", provider: modelConfig.provider, model: modelConfig.modelId, assetId };
8600
8750
  const briefStep = await extractBriefWithModel({
8601
8751
  provider: modelConfig.provider,
8602
8752
  modelId: modelConfig.modelId,
@@ -8604,12 +8754,12 @@ async function generateTextInternal(assetId, rawOptions, collectedUsage) {
8604
8754
  userPrompt: buildBriefUserPrompt({ transcriptText, imageCount: imageUrls.length, audience, languageName }),
8605
8755
  imageUrls,
8606
8756
  credentials
8607
- }).catch((error) => legacyWrapError(error, `Failed to extract editorial brief with ${provider}`));
8757
+ }).catch((error) => wrapError(error, `Failed to extract editorial brief with ${provider}`, { ...briefFacts }));
8608
8758
  collectedUsage.push(briefStep.usage);
8609
8759
  for (const key of briefStep.unexpectedKeys) {
8610
8760
  safety.record(`editorial_brief.${key}`, "unexpected_key");
8611
8761
  }
8612
- const brief = scrubBrief(briefStep.brief, safety);
8762
+ const brief = scrubBrief(briefStep.brief, safety, briefFacts);
8613
8763
  const matrix = variants.flatMap((variant) => artifacts.map((artifact) => ({
8614
8764
  variant,
8615
8765
  artifact,
@@ -8623,7 +8773,7 @@ async function generateTextInternal(assetId, rawOptions, collectedUsage) {
8623
8773
  limits,
8624
8774
  protectedTerms: brandTerms,
8625
8775
  credentials
8626
- })), collectedUsage, provider);
8776
+ })), collectedUsage, provider, modelConfig.modelId, assetId);
8627
8777
  const groupedVariants = variants.map((variant, variantIndex) => ({
8628
8778
  key: variant.key,
8629
8779
  artifacts: artifacts.map((artifact, artifactIndex) => {
@@ -8632,13 +8782,30 @@ async function generateTextInternal(assetId, rawOptions, collectedUsage) {
8632
8782
  for (const key of item.unexpectedKeys) {
8633
8783
  safety.record(`${field}.${key}`, "unexpected_key");
8634
8784
  }
8785
+ const artifactFacts = { call: "generate_artifact", provider: modelConfig.provider, model: modelConfig.modelId, assetId, variant: variant.key, artifact: artifact.key };
8635
8786
  if (item.violation === "empty") {
8636
- throw new LegacyMuxAiError(`Generated text for ${field} was empty after a retry.`, { type: "processing_error", retryable: true });
8787
+ throw new MuxAiError(`Generated text for ${field} was empty after a retry.`, {
8788
+ code: MUX_AI_ERROR_CODES.MODEL_OUTPUT_MISSING,
8789
+ type: MUX_AI_ERROR_TYPES.PROCESSING_ERROR,
8790
+ source: MUX_AI_ERROR_SOURCES.UPSTREAM,
8791
+ dependency: MUX_AI_ERROR_DEPENDENCIES.AI_PROVIDER,
8792
+ facts: artifactFacts,
8793
+ transient: false,
8794
+ retryable: true
8795
+ });
8637
8796
  }
8638
8797
  if (item.violation) {
8639
- throw new LegacyMuxAiError(
8798
+ throw new MuxAiError(
8640
8799
  `Generated text for ${field} exceeded the ${item.violation.limit.value} ${item.violation.limit.unit} limit after a retry (${item.violation.actual} returned).`,
8641
- { type: "processing_error", retryable: true }
8800
+ {
8801
+ code: MUX_AI_ERROR_CODES.MODEL_OUTPUT_INVALID,
8802
+ type: MUX_AI_ERROR_TYPES.PROCESSING_ERROR,
8803
+ source: MUX_AI_ERROR_SOURCES.UPSTREAM,
8804
+ dependency: MUX_AI_ERROR_DEPENDENCIES.AI_PROVIDER,
8805
+ facts: { ...artifactFacts, reason: "over_length", limitUnit: item.violation.limit.unit, limit: item.violation.limit.value, actual: item.violation.actual },
8806
+ transient: false,
8807
+ retryable: true
8808
+ }
8642
8809
  );
8643
8810
  }
8644
8811
  return {