@mux/ai 0.67.0 → 0.68.0-canary.113
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.
- package/dist/{index-D1v-3Mgj.d.ts → index-CxDX1bX1.d.ts} +62 -22
- package/dist/{index-CV-IZBbE.d.ts → index-DbEwilAW.d.ts} +1 -1
- package/dist/index.d.ts +14 -10
- package/dist/index.js +4368 -4113
- package/dist/index.js.map +1 -1
- package/dist/primitives/index.d.ts +2 -2
- package/dist/primitives/index.js +7 -6
- package/dist/primitives/index.js.map +1 -1
- package/dist/{transcripts-BkjWyvVz.d.ts → transcripts-Cs-n8X_l.d.ts} +22 -21
- package/dist/workflows/index.d.ts +2 -2
- package/dist/workflows/index.js +330 -123
- package/dist/workflows/index.js.map +1 -1
- package/package.json +1 -1
package/dist/workflows/index.js
CHANGED
|
@@ -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`,
|
|
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",
|
|
@@ -646,14 +643,15 @@ var MUX_AI_ERROR_CODES = {
|
|
|
646
643
|
/**
|
|
647
644
|
* The provider says the account the service running the SDK uses is out of credits or
|
|
648
645
|
* quota, or hit a spend or usage limit. Retrying won't help until someone changes the
|
|
649
|
-
* account. The site names the dependency. Facts: `call`, `status`, `providerCode
|
|
646
|
+
* account. The site names the dependency. Facts: `call`, `status`, and `providerCode`
|
|
647
|
+
* when the provider gave one.
|
|
650
648
|
*/
|
|
651
649
|
PROVIDER_QUOTA_EXHAUSTED: "provider_quota_exhausted",
|
|
652
|
-
/** The provider rejected the key the service running the SDK uses, or the key lacks permission for this model or feature. The site names the dependency. Facts: `call`, `status`, `providerCode
|
|
650
|
+
/** The provider rejected the key the service running the SDK uses, or the key lacks permission for this model or feature. The site names the dependency. Facts: `call`, `status`, and `providerCode` when the provider gave one. */
|
|
653
651
|
PROVIDER_CREDENTIALS_REJECTED: "provider_credentials_rejected",
|
|
654
|
-
/** The provider says requests are over its rate or concurrency limit. The site names the dependency. Facts: `call`, `status`, `providerCode
|
|
652
|
+
/** The provider says requests are over its rate or concurrency limit. The site names the dependency. Facts: `call`, `status`, and `providerCode` when the provider gave one. */
|
|
655
653
|
PROVIDER_RATE_LIMITED: "provider_rate_limited",
|
|
656
|
-
/** The provider says it's overloaded or down for maintenance. The site names the dependency. Facts: `call`, `status`, `providerCode
|
|
654
|
+
/** The provider says it's overloaded or down for maintenance. The site names the dependency. Facts: `call`, `status`, and `providerCode` when the provider gave one. */
|
|
657
655
|
PROVIDER_UNAVAILABLE: "provider_unavailable",
|
|
658
656
|
/** 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
657
|
AUDIO_UNPROCESSABLE: "audio_unprocessable",
|
|
@@ -1128,12 +1126,16 @@ function dependencyErrorFrom(error, message, init) {
|
|
|
1128
1126
|
}
|
|
1129
1127
|
|
|
1130
1128
|
// src/lib/google-errors.ts
|
|
1131
|
-
|
|
1129
|
+
import { z as z2 } from "zod";
|
|
1130
|
+
var GoogleTokenSchema = z2.string().regex(/^[\w.-]{1,128}$/).optional().catch(void 0);
|
|
1132
1131
|
var GoogleErrorBodySchema = z2.object({
|
|
1133
1132
|
error: z2.object({
|
|
1134
|
-
status: GoogleTokenSchema
|
|
1133
|
+
status: GoogleTokenSchema,
|
|
1134
|
+
code: z2.union([z2.string().regex(/^[\w.-]{1,128}$/), z2.number()]).optional().catch(void 0),
|
|
1135
1135
|
details: z2.array(z2.object({
|
|
1136
|
-
|
|
1136
|
+
// `ErrorInfo`'s reason, e.g. `API_KEY_INVALID`.
|
|
1137
|
+
reason: GoogleTokenSchema,
|
|
1138
|
+
violations: z2.array(z2.object({ quotaId: GoogleTokenSchema })).max(16).optional()
|
|
1137
1139
|
})).max(16).optional()
|
|
1138
1140
|
})
|
|
1139
1141
|
});
|
|
@@ -1152,18 +1154,54 @@ function googleErrorFacts(responseBody) {
|
|
|
1152
1154
|
return {};
|
|
1153
1155
|
}
|
|
1154
1156
|
const quotaIds = [...new Set((parsed.data.error.details ?? []).flatMap((detail) => detail.violations ?? []).map((violation) => violation.quotaId).filter((quotaId) => quotaId !== void 0))];
|
|
1157
|
+
const code = parsed.data.error.code;
|
|
1158
|
+
const reason = (parsed.data.error.details ?? []).find((detail) => detail.reason !== void 0)?.reason;
|
|
1155
1159
|
return {
|
|
1156
1160
|
...parsed.data.error.status && { providerStatus: parsed.data.error.status },
|
|
1161
|
+
// Google's own code, as every provider rule's `providerCode`: the snake_case code, else its status.
|
|
1162
|
+
...(typeof code === "string" || parsed.data.error.status) && { providerCode: typeof code === "string" ? code : parsed.data.error.status },
|
|
1163
|
+
...reason && { providerReason: reason },
|
|
1157
1164
|
...quotaIds.length > 0 && { quotaIds }
|
|
1158
1165
|
};
|
|
1159
1166
|
}
|
|
1167
|
+
var GOOGLE_PER_DAY_QUOTA = /PerDay/i;
|
|
1168
|
+
var GOOGLE_QUOTA_EXCEEDED_CODE = "quota_exceeded";
|
|
1169
|
+
var GOOGLE_API_KEY_REASONS = /* @__PURE__ */ new Set([
|
|
1170
|
+
"API_KEY_INVALID",
|
|
1171
|
+
"API_KEY_SERVICE_BLOCKED",
|
|
1172
|
+
"API_KEY_HTTP_REFERRER_BLOCKED",
|
|
1173
|
+
"API_KEY_IP_ADDRESS_BLOCKED",
|
|
1174
|
+
"API_KEY_ANDROID_APP_BLOCKED",
|
|
1175
|
+
"API_KEY_IOS_APP_BLOCKED"
|
|
1176
|
+
]);
|
|
1177
|
+
function googleCallRule(status, facts) {
|
|
1178
|
+
const quotaIds = Array.isArray(facts.quotaIds) ? facts.quotaIds.map(String) : [];
|
|
1179
|
+
if (status === 402) {
|
|
1180
|
+
return { code: MUX_AI_ERROR_CODES.PROVIDER_QUOTA_EXHAUSTED };
|
|
1181
|
+
}
|
|
1182
|
+
if (status === 429) {
|
|
1183
|
+
const perDay = facts.providerCode === GOOGLE_QUOTA_EXCEEDED_CODE || quotaIds.some((id) => GOOGLE_PER_DAY_QUOTA.test(id));
|
|
1184
|
+
return { code: perDay ? MUX_AI_ERROR_CODES.PROVIDER_QUOTA_EXHAUSTED : MUX_AI_ERROR_CODES.PROVIDER_RATE_LIMITED };
|
|
1185
|
+
}
|
|
1186
|
+
if (status === 401 || status === 403 || GOOGLE_API_KEY_REASONS.has(String(facts.providerReason))) {
|
|
1187
|
+
return { code: MUX_AI_ERROR_CODES.PROVIDER_CREDENTIALS_REJECTED };
|
|
1188
|
+
}
|
|
1189
|
+
if (status === 503) {
|
|
1190
|
+
return { code: MUX_AI_ERROR_CODES.PROVIDER_UNAVAILABLE };
|
|
1191
|
+
}
|
|
1192
|
+
return status === 504 ? { timedOut: true } : void 0;
|
|
1193
|
+
}
|
|
1160
1194
|
function googleCallError(apiError, message, init) {
|
|
1195
|
+
const facts = { ...init.facts, ...googleErrorFacts(apiError.responseBody) };
|
|
1196
|
+
const rule = googleCallRule(apiError.statusCode, facts);
|
|
1161
1197
|
return dependencyError(message, {
|
|
1162
1198
|
dependency: MUX_AI_ERROR_DEPENDENCIES.AI_PROVIDER,
|
|
1163
1199
|
call: init.call,
|
|
1164
1200
|
status: apiError.statusCode,
|
|
1165
1201
|
requestId: requestIdOf(apiError.responseHeaders),
|
|
1166
|
-
facts
|
|
1202
|
+
facts,
|
|
1203
|
+
...rule?.code && { code: rule.code },
|
|
1204
|
+
...rule?.timedOut && { timedOut: true },
|
|
1167
1205
|
cause: init.cause ?? apiError
|
|
1168
1206
|
});
|
|
1169
1207
|
}
|
|
@@ -1587,6 +1625,15 @@ function classifyModelCallError(error, context) {
|
|
|
1587
1625
|
if (unusable) {
|
|
1588
1626
|
return unusable;
|
|
1589
1627
|
}
|
|
1628
|
+
if (isClientTimeout(last)) {
|
|
1629
|
+
return withUsage(dependencyError(`${context.call} timed out`, {
|
|
1630
|
+
dependency: MUX_AI_ERROR_DEPENDENCIES.AI_PROVIDER,
|
|
1631
|
+
call: context.call,
|
|
1632
|
+
timedOut: true,
|
|
1633
|
+
facts: modelCallFacts(context),
|
|
1634
|
+
cause: error
|
|
1635
|
+
}), getErrorTokenUsage(error));
|
|
1636
|
+
}
|
|
1590
1637
|
const apiError = findProviderCallError(error);
|
|
1591
1638
|
if (!apiError) {
|
|
1592
1639
|
return void 0;
|
|
@@ -1601,6 +1648,9 @@ function classifyModelCallError(error, context) {
|
|
|
1601
1648
|
return void 0;
|
|
1602
1649
|
}
|
|
1603
1650
|
}
|
|
1651
|
+
function isClientTimeout(error) {
|
|
1652
|
+
return typeof error === "object" && error !== null && error.name === "TimeoutError";
|
|
1653
|
+
}
|
|
1604
1654
|
function classifyUnusableOutput(last, error, context) {
|
|
1605
1655
|
const parse = NoObjectGeneratedError.isInstance(last);
|
|
1606
1656
|
if (!parse && !NoOutputGeneratedError2.isInstance(last)) {
|
|
@@ -1846,7 +1896,6 @@ function modelStepError(error, message, facts) {
|
|
|
1846
1896
|
}
|
|
1847
1897
|
|
|
1848
1898
|
// src/lib/model-call-diagnostics.ts
|
|
1849
|
-
import { APICallError as APICallError3 } from "ai";
|
|
1850
1899
|
function recordModelCallFailure(error, diagnostics, observedUsage = getErrorTokenUsage(error)) {
|
|
1851
1900
|
if (typeof error !== "object" || error === null) {
|
|
1852
1901
|
return;
|
|
@@ -1856,12 +1905,14 @@ function recordModelCallFailure(error, diagnostics, observedUsage = getErrorToke
|
|
|
1856
1905
|
return;
|
|
1857
1906
|
}
|
|
1858
1907
|
failure.diagnostics = { ...diagnostics };
|
|
1908
|
+
const providerError = findProviderServiceError(error);
|
|
1909
|
+
const reported = providerError ?? error;
|
|
1859
1910
|
console.warn("[@mux/ai] Model call failed.", {
|
|
1860
1911
|
...diagnostics,
|
|
1861
1912
|
finishReason: failure.finishReason,
|
|
1862
|
-
statusCode: failure.statusCode,
|
|
1863
|
-
errorName:
|
|
1864
|
-
requestId:
|
|
1913
|
+
statusCode: providerError?.statusCode ?? failure.statusCode,
|
|
1914
|
+
errorName: reported instanceof Error ? reported.name : void 0,
|
|
1915
|
+
requestId: providerError?.responseHeaders?.["x-request-id"] ?? providerError?.responseHeaders?.["request-id"],
|
|
1865
1916
|
usage: observedUsage
|
|
1866
1917
|
});
|
|
1867
1918
|
}
|
|
@@ -1977,25 +2028,32 @@ function repairJsonSchema(plan) {
|
|
|
1977
2028
|
properties: Object.fromEntries(plan.spans.map((span) => [span.id, { type: "string" }]))
|
|
1978
2029
|
};
|
|
1979
2030
|
}
|
|
2031
|
+
function rejected(code, reason) {
|
|
2032
|
+
return { accepted: false, code, reason };
|
|
2033
|
+
}
|
|
1980
2034
|
function applyTextRepair(content, plan, replacements) {
|
|
1981
2035
|
if (!replacements || typeof replacements !== "object" || Array.isArray(replacements))
|
|
1982
|
-
return
|
|
2036
|
+
return rejected("invalid_object", "Invalid replacement object");
|
|
1983
2037
|
const values = replacements;
|
|
1984
2038
|
if (Object.keys(values).length !== plan.spans.length || Object.keys(values).some((key) => !plan.spans.some((span) => span.id === key)))
|
|
1985
|
-
return
|
|
2039
|
+
return rejected("span_ids", "Unexpected or missing span IDs");
|
|
1986
2040
|
const parts = split(content);
|
|
1987
2041
|
for (const span of plan.spans) {
|
|
1988
2042
|
const index = Number(span.id.slice(2));
|
|
1989
2043
|
const replacement = values[span.id];
|
|
1990
2044
|
if (parts[index] !== span.text)
|
|
1991
|
-
return
|
|
1992
|
-
if (typeof replacement !== "string" || !replacement.trim()
|
|
1993
|
-
return
|
|
2045
|
+
return rejected("stale_plan", "Stale repair plan");
|
|
2046
|
+
if (typeof replacement !== "string" || !replacement.trim())
|
|
2047
|
+
return rejected("empty_replacement", "Empty or incompatible paragraph replacement");
|
|
2048
|
+
if (INVALID_REPLACEMENT.test(replacement))
|
|
2049
|
+
return rejected("split_paragraph", "Empty or incompatible paragraph replacement");
|
|
2050
|
+
if (introducesLiteralEscapes(span.text, replacement))
|
|
2051
|
+
return rejected("literal_escapes", "Empty or incompatible paragraph replacement");
|
|
1994
2052
|
parts[index] = replacement;
|
|
1995
2053
|
}
|
|
1996
2054
|
const editedText = plan.spans.map((span) => values[span.id]).join("\n\n");
|
|
1997
2055
|
if (plan.protectedTerms.some((term) => !editedText.includes(term)))
|
|
1998
|
-
return
|
|
2056
|
+
return rejected("protected_term", "Protected term removed from edited spans");
|
|
1999
2057
|
return { accepted: true, content: parts.join("") };
|
|
2000
2058
|
}
|
|
2001
2059
|
function introducesLiteralEscapes(source, replacement) {
|
|
@@ -2010,24 +2068,30 @@ async function runTextRepairLoop(options) {
|
|
|
2010
2068
|
let content = options.content;
|
|
2011
2069
|
const attempts = [];
|
|
2012
2070
|
if (!content.trim())
|
|
2013
|
-
return { status: "failed", attempts, reason: "Empty draft has no substance to preserve" };
|
|
2071
|
+
return { status: "failed", attempts, reason: "Empty draft has no substance to preserve", outcome: "empty_draft" };
|
|
2014
2072
|
for (let index = 0; index < maxAttempts; index++) {
|
|
2015
2073
|
if (!findGenerateTextLengthViolation(content, options.limits))
|
|
2016
2074
|
return { status: "valid", content, attempts };
|
|
2017
2075
|
const plan = planTextRepair(content, options.limits, options.protectedTerms);
|
|
2018
2076
|
if (!plan)
|
|
2019
|
-
return { status: "failed", attempts, reason: "No feasible span budget" };
|
|
2077
|
+
return { status: "failed", attempts, reason: "No feasible span budget", outcome: "no_plan" };
|
|
2020
2078
|
const call = await options.generate(plan);
|
|
2021
2079
|
const applied = applyTextRepair(content, plan, call.replacements);
|
|
2022
|
-
|
|
2080
|
+
const overLimit = applied.accepted ? findGenerateTextLengthViolation(applied.content, options.limits) : void 0;
|
|
2081
|
+
attempts.push({
|
|
2082
|
+
plan,
|
|
2083
|
+
call,
|
|
2084
|
+
...!applied.accepted && { rejection: applied.reason, rejectionCode: applied.code },
|
|
2085
|
+
...overLimit && { overLimit }
|
|
2086
|
+
});
|
|
2023
2087
|
if (call.error)
|
|
2024
|
-
return { status: "failed", attempts, reason: call.error };
|
|
2025
|
-
if (applied.accepted && !
|
|
2088
|
+
return { status: "failed", attempts, reason: call.error, outcome: "call_failed" };
|
|
2089
|
+
if (applied.accepted && !overLimit)
|
|
2026
2090
|
return { status: "valid", content: applied.content, attempts };
|
|
2027
2091
|
if (applied.accepted && options.limits.every((limit) => measureGenerateTextLength(applied.content, limit.unit) <= measureGenerateTextLength(content, limit.unit)))
|
|
2028
2092
|
content = applied.content;
|
|
2029
2093
|
}
|
|
2030
|
-
return !findGenerateTextLengthViolation(content, options.limits) ? { status: "valid", content, attempts } : { status: "failed", attempts, reason: "Repair budget exhausted without a valid output" };
|
|
2094
|
+
return !findGenerateTextLengthViolation(content, options.limits) ? { status: "valid", content, attempts } : { status: "failed", attempts, reason: "Repair budget exhausted without a valid output", outcome: "exhausted" };
|
|
2031
2095
|
}
|
|
2032
2096
|
|
|
2033
2097
|
// src/lib/text-repair-model.ts
|
|
@@ -2061,15 +2125,15 @@ function createTextRepairGenerator(options) {
|
|
|
2061
2125
|
onStepFinish: (step) => {
|
|
2062
2126
|
usage = getErrorTokenUsage(step);
|
|
2063
2127
|
}
|
|
2064
|
-
}));
|
|
2128
|
+
}), options.context);
|
|
2065
2129
|
usage = getErrorTokenUsage(response);
|
|
2066
|
-
const output = getGeneratedOutputWithContentPolicyHandling(response);
|
|
2130
|
+
const output = getGeneratedOutputWithContentPolicyHandling(response, options.context);
|
|
2067
2131
|
if (!output) {
|
|
2068
2132
|
return { usage, elapsedMs: Date.now() - started, error: "Repair output missing" };
|
|
2069
2133
|
}
|
|
2070
2134
|
return { replacements: output, usage, elapsedMs: Date.now() - started };
|
|
2071
2135
|
} catch (error) {
|
|
2072
|
-
const cause = NoObjectGeneratedError2.isInstance(error) && error.finishReason && error.finishReason !== "stop" ? new IncompleteGenerationError(error.finishReason, void 0, getErrorTokenUsage(error)) : error;
|
|
2136
|
+
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
2137
|
recordModelCallFailure(cause, {
|
|
2074
2138
|
phase: "length_repair",
|
|
2075
2139
|
provider: typeof options.model === "object" ? options.model.provider : "gateway",
|
|
@@ -7958,7 +8022,7 @@ async function generateEngagementInsightsInternal(assetId, options, collectedUsa
|
|
|
7958
8022
|
}
|
|
7959
8023
|
|
|
7960
8024
|
// src/workflows/generate-text.ts
|
|
7961
|
-
import {
|
|
8025
|
+
import { generateText as generateTextWithModel, Output as Output7 } from "ai";
|
|
7962
8026
|
import { z as z11 } from "zod";
|
|
7963
8027
|
var GENERATE_TEXT_MAX_VARIANTS = 5;
|
|
7964
8028
|
var GENERATE_TEXT_MAX_ARTIFACTS = 5;
|
|
@@ -7981,96 +8045,151 @@ var GENERATE_TEXT_CHANNEL_CEILINGS = {
|
|
|
7981
8045
|
x: { unit: "characters", value: 280 }
|
|
7982
8046
|
};
|
|
7983
8047
|
var KEY_PATTERN = /^[a-z][a-z0-9_]{0,63}$/;
|
|
8048
|
+
var KEY_FORMAT = "lowercase snake_case beginning with a letter, up to 64 characters";
|
|
7984
8049
|
var LANGUAGE_TAG_PATTERN = /^[a-z]{2,3}(?:-[a-z0-9]{2,8})*$/i;
|
|
8050
|
+
var LANGUAGE_TAG_FORMAT = "a BCP 47 language tag such as 'en' or 'pt-BR'";
|
|
7985
8051
|
var LENGTH_UNITS = ["characters", "words"];
|
|
7986
|
-
function
|
|
7987
|
-
return new
|
|
8052
|
+
function invalidOptionError3(message, facts, inputs) {
|
|
8053
|
+
return new MuxAiError(message, {
|
|
8054
|
+
code: MUX_AI_ERROR_CODES.INVALID_PARAMETER,
|
|
8055
|
+
type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR,
|
|
8056
|
+
source: MUX_AI_ERROR_SOURCES.REQUEST,
|
|
8057
|
+
facts: { ...facts, inputs }
|
|
8058
|
+
});
|
|
7988
8059
|
}
|
|
7989
|
-
function
|
|
8060
|
+
function outOfRangeError(message, facts, inputs) {
|
|
8061
|
+
return new MuxAiError(message, {
|
|
8062
|
+
code: MUX_AI_ERROR_CODES.PARAMETER_OUT_OF_RANGE,
|
|
8063
|
+
type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR,
|
|
8064
|
+
source: MUX_AI_ERROR_SOURCES.REQUEST,
|
|
8065
|
+
facts: { ...facts, inputs }
|
|
8066
|
+
});
|
|
8067
|
+
}
|
|
8068
|
+
var ECHOABLE_VALUE = /^[\w.-]{1,40}$/;
|
|
8069
|
+
function echoableValue(value) {
|
|
8070
|
+
return typeof value === "string" && ECHOABLE_VALUE.test(value) ? { value } : {};
|
|
8071
|
+
}
|
|
8072
|
+
function assertOneOf(value, allowed, label, parameter, input) {
|
|
7990
8073
|
if (!allowed.includes(value)) {
|
|
7991
|
-
throw
|
|
8074
|
+
throw invalidOptionError3(
|
|
8075
|
+
`Invalid ${label} "${value}". Valid values are: ${allowed.join(", ")}.`,
|
|
8076
|
+
{ parameter, reason: "not_allowed", allowed: [...allowed], ...echoableValue(value) },
|
|
8077
|
+
[input]
|
|
8078
|
+
);
|
|
7992
8079
|
}
|
|
7993
8080
|
}
|
|
7994
|
-
function assertBoundedText(value, max, label) {
|
|
8081
|
+
function assertBoundedText(value, max, label, parameter, input) {
|
|
7995
8082
|
const length = value.trim().length;
|
|
7996
8083
|
if (length === 0 || length > max) {
|
|
7997
|
-
throw
|
|
8084
|
+
throw invalidOptionError3(
|
|
8085
|
+
`${label} must be 1-${max} characters.`,
|
|
8086
|
+
length === 0 ? { parameter, reason: "empty" } : { parameter, reason: "too_long", length, maxLength: max },
|
|
8087
|
+
[input]
|
|
8088
|
+
);
|
|
7998
8089
|
}
|
|
7999
8090
|
return length;
|
|
8000
8091
|
}
|
|
8001
|
-
function assertKeyedItems(items, noun, max) {
|
|
8092
|
+
function assertKeyedItems(items, noun, parameter, max) {
|
|
8002
8093
|
if (items.length === 0) {
|
|
8003
|
-
throw
|
|
8094
|
+
throw invalidOptionError3(`At least one ${noun} is required.`, { parameter, reason: "empty" }, [parameter]);
|
|
8004
8095
|
}
|
|
8005
8096
|
if (items.length > max) {
|
|
8006
|
-
throw
|
|
8097
|
+
throw invalidOptionError3(
|
|
8098
|
+
`At most ${max} ${noun}s are supported (received ${items.length}).`,
|
|
8099
|
+
{ parameter, reason: "too_many", count: items.length, max },
|
|
8100
|
+
[parameter]
|
|
8101
|
+
);
|
|
8007
8102
|
}
|
|
8008
8103
|
const seen = /* @__PURE__ */ new Set();
|
|
8009
|
-
|
|
8104
|
+
items.forEach(({ key, instructions }, index) => {
|
|
8010
8105
|
if (!KEY_PATTERN.test(key ?? "")) {
|
|
8011
|
-
throw
|
|
8106
|
+
throw invalidOptionError3(
|
|
8107
|
+
`${noun} key "${key}" must be lowercase snake_case beginning with a letter, up to 64 characters.`,
|
|
8108
|
+
{ parameter: `${parameter}[${index}].key`, reason: "invalid_format", format: KEY_FORMAT },
|
|
8109
|
+
[parameter]
|
|
8110
|
+
);
|
|
8012
8111
|
}
|
|
8013
8112
|
if (seen.has(key)) {
|
|
8014
|
-
throw
|
|
8113
|
+
throw invalidOptionError3(`Duplicate ${noun} key "${key}".`, { parameter, reason: "duplicate", value: key, index }, [parameter]);
|
|
8015
8114
|
}
|
|
8016
8115
|
seen.add(key);
|
|
8017
8116
|
if (instructions !== void 0) {
|
|
8018
|
-
assertBoundedText(instructions, GENERATE_TEXT_MAX_INSTRUCTIONS_CHARS, `${noun} "${key}" instructions
|
|
8117
|
+
assertBoundedText(instructions, GENERATE_TEXT_MAX_INSTRUCTIONS_CHARS, `${noun} "${key}" instructions`, `${parameter}[${index}].instructions`, parameter);
|
|
8019
8118
|
}
|
|
8020
|
-
}
|
|
8119
|
+
});
|
|
8021
8120
|
}
|
|
8022
|
-
function assertArtifact(artifact) {
|
|
8121
|
+
function assertArtifact(artifact, index) {
|
|
8122
|
+
const parameter = `artifacts[${index}]`;
|
|
8023
8123
|
if (artifact.channel !== void 0) {
|
|
8024
|
-
assertOneOf(artifact.channel, GENERATE_TEXT_CHANNELS, `artifact "${artifact.key}" channel
|
|
8124
|
+
assertOneOf(artifact.channel, GENERATE_TEXT_CHANNELS, `artifact "${artifact.key}" channel`, `${parameter}.channel`, "artifacts");
|
|
8025
8125
|
}
|
|
8026
8126
|
if (artifact.format !== void 0) {
|
|
8027
|
-
assertOneOf(artifact.format, GENERATE_TEXT_FORMATS, `artifact "${artifact.key}" format
|
|
8127
|
+
assertOneOf(artifact.format, GENERATE_TEXT_FORMATS, `artifact "${artifact.key}" format`, `${parameter}.format`, "artifacts");
|
|
8028
8128
|
}
|
|
8029
8129
|
if (artifact.maxLength === void 0) {
|
|
8030
8130
|
return;
|
|
8031
8131
|
}
|
|
8032
8132
|
const { unit, value } = artifact.maxLength;
|
|
8033
|
-
assertOneOf(unit, LENGTH_UNITS, `artifact "${artifact.key}" maxLength.unit
|
|
8133
|
+
assertOneOf(unit, LENGTH_UNITS, `artifact "${artifact.key}" maxLength.unit`, `${parameter}.maxLength.unit`, "artifacts");
|
|
8034
8134
|
const bounds = GENERATE_TEXT_LENGTH_BOUNDS[unit];
|
|
8035
8135
|
if (!Number.isInteger(value) || value < bounds.min || value > bounds.max) {
|
|
8036
|
-
throw
|
|
8136
|
+
throw outOfRangeError(
|
|
8137
|
+
`Artifact "${artifact.key}" maxLength.value must be an integer between ${bounds.min} and ${bounds.max} ${unit} (received ${value}).`,
|
|
8138
|
+
{ 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 },
|
|
8139
|
+
["artifacts"]
|
|
8140
|
+
);
|
|
8037
8141
|
}
|
|
8038
8142
|
const ceiling = artifact.channel ? GENERATE_TEXT_CHANNEL_CEILINGS[artifact.channel] : void 0;
|
|
8039
8143
|
if (ceiling && ceiling.unit === unit && value > ceiling.value) {
|
|
8040
|
-
throw
|
|
8144
|
+
throw outOfRangeError(
|
|
8145
|
+
`Artifact "${artifact.key}" targets ${artifact.channel} and supports at most ${ceiling.value} ${ceiling.unit}.`,
|
|
8146
|
+
{ parameter: `${parameter}.maxLength.value`, value, min: bounds.min, max: ceiling.value, integer: true, unit, channel: artifact.channel },
|
|
8147
|
+
["artifacts"]
|
|
8148
|
+
);
|
|
8041
8149
|
}
|
|
8042
8150
|
}
|
|
8043
|
-
function assertLanguageTag(value,
|
|
8151
|
+
function assertLanguageTag(value, parameter) {
|
|
8044
8152
|
if (value.length > 35 || !LANGUAGE_TAG_PATTERN.test(value)) {
|
|
8045
|
-
throw
|
|
8153
|
+
throw invalidOptionError3(
|
|
8154
|
+
`${parameter} must be a BCP 47 language tag such as "en" or "pt-BR".`,
|
|
8155
|
+
{ parameter, reason: "invalid_format", format: LANGUAGE_TAG_FORMAT },
|
|
8156
|
+
[parameter]
|
|
8157
|
+
);
|
|
8046
8158
|
}
|
|
8047
8159
|
}
|
|
8048
8160
|
function resolveGenerateTextOptions(options) {
|
|
8049
8161
|
const variants = options.variants ?? [{ key: "default" }];
|
|
8050
|
-
assertKeyedItems(variants, "variant", GENERATE_TEXT_MAX_VARIANTS);
|
|
8051
|
-
assertKeyedItems(options.artifacts, "artifact", GENERATE_TEXT_MAX_ARTIFACTS);
|
|
8052
|
-
|
|
8053
|
-
assertArtifact(artifact);
|
|
8054
|
-
}
|
|
8162
|
+
assertKeyedItems(variants, "variant", "variants", GENERATE_TEXT_MAX_VARIANTS);
|
|
8163
|
+
assertKeyedItems(options.artifacts, "artifact", "artifacts", GENERATE_TEXT_MAX_ARTIFACTS);
|
|
8164
|
+
options.artifacts.forEach(assertArtifact);
|
|
8055
8165
|
if (options.audience !== void 0) {
|
|
8056
|
-
assertBoundedText(options.audience, GENERATE_TEXT_MAX_AUDIENCE_CHARS, "audience");
|
|
8166
|
+
assertBoundedText(options.audience, GENERATE_TEXT_MAX_AUDIENCE_CHARS, "audience", "audience", "audience");
|
|
8057
8167
|
}
|
|
8058
8168
|
if (options.voice !== void 0) {
|
|
8059
|
-
assertOneOf(options.voice, GENERATE_TEXT_VOICES, "voice");
|
|
8169
|
+
assertOneOf(options.voice, GENERATE_TEXT_VOICES, "voice", "voice", "voice");
|
|
8060
8170
|
}
|
|
8061
8171
|
if (options.callToAction !== void 0) {
|
|
8062
|
-
assertOneOf(options.callToAction, GENERATE_TEXT_CALLS_TO_ACTION, "callToAction");
|
|
8172
|
+
assertOneOf(options.callToAction, GENERATE_TEXT_CALLS_TO_ACTION, "callToAction", "callToAction", "callToAction");
|
|
8063
8173
|
}
|
|
8064
8174
|
if (options.brandTerms !== void 0) {
|
|
8065
|
-
|
|
8066
|
-
|
|
8175
|
+
const count = options.brandTerms.length;
|
|
8176
|
+
if (count === 0 || count > GENERATE_TEXT_MAX_BRAND_TERMS) {
|
|
8177
|
+
throw invalidOptionError3(
|
|
8178
|
+
`brandTerms must contain 1-${GENERATE_TEXT_MAX_BRAND_TERMS} terms.`,
|
|
8179
|
+
count === 0 ? { parameter: "brandTerms", reason: "empty" } : { parameter: "brandTerms", reason: "too_many", count, max: GENERATE_TEXT_MAX_BRAND_TERMS },
|
|
8180
|
+
["brandTerms"]
|
|
8181
|
+
);
|
|
8067
8182
|
}
|
|
8068
8183
|
const total = options.brandTerms.reduce(
|
|
8069
|
-
(sum, term) => sum + assertBoundedText(term, GENERATE_TEXT_MAX_BRAND_TERM_CHARS, "Each brand term"),
|
|
8184
|
+
(sum, term, index) => sum + assertBoundedText(term, GENERATE_TEXT_MAX_BRAND_TERM_CHARS, "Each brand term", `brandTerms[${index}]`, "brandTerms"),
|
|
8070
8185
|
0
|
|
8071
8186
|
);
|
|
8072
8187
|
if (total > GENERATE_TEXT_MAX_BRAND_TERMS_TOTAL_CHARS) {
|
|
8073
|
-
throw
|
|
8188
|
+
throw invalidOptionError3(
|
|
8189
|
+
`Combined brandTerms must be ${GENERATE_TEXT_MAX_BRAND_TERMS_TOTAL_CHARS} characters or fewer.`,
|
|
8190
|
+
{ parameter: "brandTerms", reason: "too_long", length: total, maxLength: GENERATE_TEXT_MAX_BRAND_TERMS_TOTAL_CHARS },
|
|
8191
|
+
["brandTerms"]
|
|
8192
|
+
);
|
|
8074
8193
|
}
|
|
8075
8194
|
}
|
|
8076
8195
|
if (options.languageCode !== void 0) {
|
|
@@ -8164,14 +8283,20 @@ function clampBriefArrays(brief) {
|
|
|
8164
8283
|
}
|
|
8165
8284
|
return clamped;
|
|
8166
8285
|
}
|
|
8167
|
-
function scrubBrief(brief, safety) {
|
|
8286
|
+
function scrubBrief(brief, safety, facts) {
|
|
8168
8287
|
const centralIdea = safety.scrubDetailed(brief.centralIdea, "editorial_brief.centralIdea");
|
|
8169
8288
|
const readerValue = safety.scrubDetailed(brief.readerValue, "editorial_brief.readerValue");
|
|
8170
8289
|
if (centralIdea.leaked || readerValue.leaked || !centralIdea.text.trim()) {
|
|
8171
|
-
throw new
|
|
8172
|
-
|
|
8173
|
-
|
|
8174
|
-
|
|
8290
|
+
throw new MuxAiError("The editorial brief was suppressed by the output safety filter.", {
|
|
8291
|
+
code: MUX_AI_ERROR_CODES.MODEL_OUTPUT_SUPPRESSED,
|
|
8292
|
+
type: MUX_AI_ERROR_TYPES.PROCESSING_ERROR,
|
|
8293
|
+
source: MUX_AI_ERROR_SOURCES.UPSTREAM,
|
|
8294
|
+
dependency: MUX_AI_ERROR_DEPENDENCIES.AI_PROVIDER,
|
|
8295
|
+
facts,
|
|
8296
|
+
// Resubmittable, as before classification: a new brief may not trip the filter.
|
|
8297
|
+
transient: false,
|
|
8298
|
+
retryable: true
|
|
8299
|
+
});
|
|
8175
8300
|
}
|
|
8176
8301
|
const scrubbed = { ...brief, centralIdea: centralIdea.text, readerValue: readerValue.text };
|
|
8177
8302
|
for (const field of Object.keys(BRIEF_LIST_LIMITS)) {
|
|
@@ -8368,10 +8493,65 @@ function describeLengthRevision({ limit, actual }) {
|
|
|
8368
8493
|
function readUsage(response) {
|
|
8369
8494
|
return getErrorTokenUsage(response) ?? {};
|
|
8370
8495
|
}
|
|
8496
|
+
function invalidModelOutputError(context, cause) {
|
|
8497
|
+
return new MuxAiError(`${context.call} returned output that doesn't match its schema`, {
|
|
8498
|
+
code: MUX_AI_ERROR_CODES.MODEL_OUTPUT_INVALID,
|
|
8499
|
+
type: MUX_AI_ERROR_TYPES.PROCESSING_ERROR,
|
|
8500
|
+
source: MUX_AI_ERROR_SOURCES.UPSTREAM,
|
|
8501
|
+
dependency: MUX_AI_ERROR_DEPENDENCIES.AI_PROVIDER,
|
|
8502
|
+
facts: { call: context.call, provider: context.provider, ...context.model && { model: context.model } },
|
|
8503
|
+
transient: true,
|
|
8504
|
+
cause
|
|
8505
|
+
});
|
|
8506
|
+
}
|
|
8507
|
+
function lengthRepairError(repaired, context, draft) {
|
|
8508
|
+
const cause = repaired.attempts.at(-1)?.call.errorCause;
|
|
8509
|
+
const facts = { call: context.call, provider: context.provider, ...context.model && { model: context.model } };
|
|
8510
|
+
if (cause === void 0) {
|
|
8511
|
+
return new MuxAiError("Unable to bring the generated text within its length limit.", {
|
|
8512
|
+
code: MUX_AI_ERROR_CODES.MODEL_OUTPUT_INVALID,
|
|
8513
|
+
type: MUX_AI_ERROR_TYPES.PROCESSING_ERROR,
|
|
8514
|
+
source: MUX_AI_ERROR_SOURCES.UPSTREAM,
|
|
8515
|
+
dependency: MUX_AI_ERROR_DEPENDENCIES.AI_PROVIDER,
|
|
8516
|
+
// The draft's own length, then why the repair stopped (no feasible plan, or its calls
|
|
8517
|
+
// used up) and what each call produced: rejected replacements, or text still over a limit.
|
|
8518
|
+
facts: {
|
|
8519
|
+
...facts,
|
|
8520
|
+
reason: "over_length",
|
|
8521
|
+
limitUnit: draft.limit.unit,
|
|
8522
|
+
limit: draft.limit.value,
|
|
8523
|
+
actual: draft.actual,
|
|
8524
|
+
...repaired.outcome && { repairOutcome: repaired.outcome },
|
|
8525
|
+
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 } : {})
|
|
8526
|
+
},
|
|
8527
|
+
transient: false,
|
|
8528
|
+
retryable: true
|
|
8529
|
+
});
|
|
8530
|
+
}
|
|
8531
|
+
const classified = MuxAiError.is(cause) ? cause : modelStepError(cause, "Unable to complete text generation.", { ...context });
|
|
8532
|
+
const retryable = classified.dependency ? classified.retryable : findProviderServiceError(cause)?.isRetryable ?? true;
|
|
8533
|
+
const failure = classified.transient || classified.retryable !== retryable ? new MuxAiError(classified.message, {
|
|
8534
|
+
...classified.code && { code: classified.code },
|
|
8535
|
+
type: classified.type,
|
|
8536
|
+
source: classified.source,
|
|
8537
|
+
...classified.dependency && { dependency: classified.dependency },
|
|
8538
|
+
facts: classified.facts,
|
|
8539
|
+
transient: false,
|
|
8540
|
+
retryable,
|
|
8541
|
+
// The raw failure, so the cause chain stays the provider's own error, not a second wrapper of it.
|
|
8542
|
+
cause: MuxAiError.is(cause) ? classified.cause ?? classified : cause
|
|
8543
|
+
}) : classified;
|
|
8544
|
+
delete failure.usage;
|
|
8545
|
+
if (typeof cause === "object" && cause !== null && "diagnostics" in cause) {
|
|
8546
|
+
failure.diagnostics = cause.diagnostics;
|
|
8547
|
+
}
|
|
8548
|
+
return failure;
|
|
8549
|
+
}
|
|
8371
8550
|
async function extractBriefWithModel(args) {
|
|
8372
8551
|
"use step";
|
|
8373
8552
|
return withModelCallDiagnostics({ phase: "brief", provider: args.provider, modelId: args.modelId }, async () => {
|
|
8374
8553
|
const model = await createLanguageModelFromConfig(args.provider, args.modelId, args.credentials);
|
|
8554
|
+
const context = { call: "extract_brief", provider: args.provider, model: args.modelId };
|
|
8375
8555
|
const response = await withContentPolicyAwareRetry(() => generateTextWithModel({
|
|
8376
8556
|
model,
|
|
8377
8557
|
maxRetries: 0,
|
|
@@ -8390,13 +8570,16 @@ async function extractBriefWithModel(args) {
|
|
|
8390
8570
|
]
|
|
8391
8571
|
}
|
|
8392
8572
|
]
|
|
8393
|
-
}))
|
|
8394
|
-
|
|
8395
|
-
|
|
8396
|
-
|
|
8573
|
+
}), void 0, context).catch((error) => {
|
|
8574
|
+
throw modelStepError(error, "Editorial brief model call failed", { ...context });
|
|
8575
|
+
});
|
|
8576
|
+
const output = getGeneratedOutputWithContentPolicyHandling(response, context);
|
|
8577
|
+
const parsed = briefSchema.safeParse(output);
|
|
8578
|
+
if (!parsed.success) {
|
|
8579
|
+
throw invalidModelOutputError(context, parsed.error);
|
|
8397
8580
|
}
|
|
8398
8581
|
return {
|
|
8399
|
-
brief: clampBriefArrays(
|
|
8582
|
+
brief: clampBriefArrays(parsed.data),
|
|
8400
8583
|
usage: readUsage(response),
|
|
8401
8584
|
unexpectedKeys: detectUnexpectedKeysFromRawText(response.text, briefSchema.keyof().options)
|
|
8402
8585
|
};
|
|
@@ -8408,6 +8591,7 @@ async function generateArtifactWithModel(args) {
|
|
|
8408
8591
|
const diagnostics = { phase: "draft", provider: args.provider, modelId: args.modelId };
|
|
8409
8592
|
return withModelCallDiagnostics(diagnostics, async () => {
|
|
8410
8593
|
const model = await createLanguageModelFromConfig(args.provider, args.modelId, args.credentials);
|
|
8594
|
+
const context = { call: "generate_artifact", provider: args.provider, model: args.modelId };
|
|
8411
8595
|
const attempt = async (messages) => {
|
|
8412
8596
|
const response = await withContentPolicyAwareRetry(() => generateTextWithModel({
|
|
8413
8597
|
model,
|
|
@@ -8419,13 +8603,16 @@ async function generateArtifactWithModel(args) {
|
|
|
8419
8603
|
}),
|
|
8420
8604
|
system: args.systemPrompt,
|
|
8421
8605
|
messages
|
|
8422
|
-
}))
|
|
8423
|
-
|
|
8424
|
-
|
|
8425
|
-
|
|
8606
|
+
}), void 0, context).catch((error) => {
|
|
8607
|
+
throw modelStepError(error, "Text generation model call failed", { ...context });
|
|
8608
|
+
});
|
|
8609
|
+
const output = getGeneratedOutputWithContentPolicyHandling(response, context);
|
|
8610
|
+
const parsed = artifactSchema.safeParse(output);
|
|
8611
|
+
if (!parsed.success) {
|
|
8612
|
+
throw invalidModelOutputError(context, parsed.error);
|
|
8426
8613
|
}
|
|
8427
8614
|
return {
|
|
8428
|
-
content:
|
|
8615
|
+
content: parsed.data.content.trim(),
|
|
8429
8616
|
usage: readUsage(response),
|
|
8430
8617
|
unexpectedKeys: detectUnexpectedKeysFromRawText(response.text, artifactSchema.keyof().options)
|
|
8431
8618
|
};
|
|
@@ -8463,28 +8650,12 @@ ${renderSection({ tag: "revision_request", content: "The previous draft was empt
|
|
|
8463
8650
|
content: candidate.content,
|
|
8464
8651
|
limits: args.limits,
|
|
8465
8652
|
protectedTerms: args.protectedTerms,
|
|
8466
|
-
model
|
|
8653
|
+
model,
|
|
8654
|
+
context
|
|
8467
8655
|
});
|
|
8468
8656
|
usages.push(...repaired.attempts.flatMap((item) => item.call.usage ? [item.call.usage] : []));
|
|
8469
8657
|
if (repaired.status !== "valid") {
|
|
8470
|
-
|
|
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);
|
|
8658
|
+
rethrowWithTokenUsage(lengthRepairError(repaired, context, violation), usages);
|
|
8488
8659
|
}
|
|
8489
8660
|
return { content: repaired.content, usages, unexpectedKeys };
|
|
8490
8661
|
});
|
|
@@ -8498,7 +8669,7 @@ async function generateText7(assetId, options) {
|
|
|
8498
8669
|
rethrowWithTokenUsage(error, collectedUsage);
|
|
8499
8670
|
}
|
|
8500
8671
|
}
|
|
8501
|
-
async function generateArtifactsInBatches(requests, collectedUsage, provider) {
|
|
8672
|
+
async function generateArtifactsInBatches(requests, collectedUsage, provider, model, assetId) {
|
|
8502
8673
|
const results = [];
|
|
8503
8674
|
for (let start = 0; start < requests.length; start += GENERATE_TEXT_MAX_CONCURRENT_GENERATIONS) {
|
|
8504
8675
|
const batch = requests.slice(start, start + GENERATE_TEXT_MAX_CONCURRENT_GENERATIONS);
|
|
@@ -8519,7 +8690,7 @@ async function generateArtifactsInBatches(requests, collectedUsage, provider) {
|
|
|
8519
8690
|
collectedUsage.push(usage);
|
|
8520
8691
|
}
|
|
8521
8692
|
}
|
|
8522
|
-
|
|
8693
|
+
wrapError(failures[0], `Failed to generate text with ${provider}`, { call: "generate_artifact", provider, model, assetId });
|
|
8523
8694
|
}
|
|
8524
8695
|
}
|
|
8525
8696
|
return results;
|
|
@@ -8546,28 +8717,35 @@ async function generateTextInternal(assetId, rawOptions, collectedUsage) {
|
|
|
8546
8717
|
model,
|
|
8547
8718
|
provider
|
|
8548
8719
|
});
|
|
8549
|
-
const { asset, playbackId, policy } = await getPlaybackIdForAsset(assetId, credentials, options.assetSnapshot);
|
|
8720
|
+
const { asset, playbackId, policy } = await getPlaybackIdForAsset(assetId, credentials, options.assetSnapshot, { classifiedErrors: true });
|
|
8550
8721
|
const assetDurationSeconds = getAssetDurationSecondsFromAsset(asset);
|
|
8551
8722
|
const isAudioOnly = isAudioOnlyAsset(asset);
|
|
8552
8723
|
const effectiveScope = hasWorkflowScopeBoundaries(scope) ? scope : void 0;
|
|
8553
|
-
const resolvedScope = effectiveScope ? resolveWorkflowScope(effectiveScope, assetDurationSeconds) : void 0;
|
|
8724
|
+
const resolvedScope = effectiveScope ? resolveWorkflowScope(effectiveScope, assetDurationSeconds, { classifiedErrors: true, assetId }) : void 0;
|
|
8554
8725
|
const storyboardScope = isAudioOnly ? void 0 : resolveRenderableVideoScope(
|
|
8555
8726
|
effectiveScope,
|
|
8556
8727
|
assetDurationSeconds,
|
|
8557
|
-
getVideoTrackDurationSecondsFromAsset(asset)
|
|
8728
|
+
getVideoTrackDurationSecondsFromAsset(asset),
|
|
8729
|
+
{ classifiedErrors: true, assetId }
|
|
8558
8730
|
);
|
|
8559
8731
|
if (useShots && isAudioOnly) {
|
|
8560
|
-
throw
|
|
8732
|
+
throw invalidOptionError3(
|
|
8733
|
+
"useShots is not supported for audio-only assets.",
|
|
8734
|
+
{ parameter: "useShots", reason: "audio_only", allowed: [false], value: true, assetId },
|
|
8735
|
+
["useShots"]
|
|
8736
|
+
);
|
|
8561
8737
|
}
|
|
8562
8738
|
if (useShots && assetDurationSeconds === void 0) {
|
|
8563
|
-
throw new
|
|
8739
|
+
throw new MuxAiError("Asset has no valid duration.", {
|
|
8740
|
+
code: MUX_AI_ERROR_CODES.ASSET_DURATION_UNAVAILABLE,
|
|
8741
|
+
type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR,
|
|
8742
|
+
source: MUX_AI_ERROR_SOURCES.ASSET,
|
|
8743
|
+
facts: { assetId }
|
|
8744
|
+
});
|
|
8564
8745
|
}
|
|
8565
8746
|
const signingContext = await resolveMuxSigningContext(credentials);
|
|
8566
8747
|
if (policy === "signed" && !signingContext) {
|
|
8567
|
-
throw
|
|
8568
|
-
"Signed playback ID requires signing credentials. Set MUX_SIGNING_KEY and MUX_PRIVATE_KEY environment variables.",
|
|
8569
|
-
{ type: "validation_error" }
|
|
8570
|
-
);
|
|
8748
|
+
throw signingCredentialsMissingError();
|
|
8571
8749
|
}
|
|
8572
8750
|
const shouldSign = policy === "signed";
|
|
8573
8751
|
const [transcriptResult, storyboardUrl, shotsResult] = await Promise.all([
|
|
@@ -8577,17 +8755,28 @@ async function generateTextInternal(assetId, rawOptions, collectedUsage) {
|
|
|
8577
8755
|
shouldSign,
|
|
8578
8756
|
credentials,
|
|
8579
8757
|
required: true,
|
|
8580
|
-
scope: effectiveScope
|
|
8758
|
+
scope: effectiveScope,
|
|
8759
|
+
classifiedErrors: true
|
|
8581
8760
|
}),
|
|
8582
8761
|
isAudioOnly ? void 0 : getStoryboardUrl(playbackId, 640, shouldSign, credentials, storyboardScope),
|
|
8583
8762
|
useShots ? getCompletedShots(assetId, credentials) : void 0
|
|
8584
8763
|
]);
|
|
8585
8764
|
const transcriptText = transcriptResult.transcriptText.trim();
|
|
8586
8765
|
if (!transcriptText) {
|
|
8587
|
-
|
|
8588
|
-
|
|
8589
|
-
|
|
8590
|
-
|
|
8766
|
+
const trackId = transcriptResult.track?.id;
|
|
8767
|
+
if (effectiveScope) {
|
|
8768
|
+
throw invalidScopeError(
|
|
8769
|
+
"Transcript has no usable content in the requested scope.",
|
|
8770
|
+
{ reason: "no_transcript", ...trackId && { trackId }, ...effectiveScope.startTime !== void 0 && { startTime: effectiveScope.startTime }, ...effectiveScope.endTime !== void 0 && { endTime: effectiveScope.endTime } },
|
|
8771
|
+
["scope"]
|
|
8772
|
+
);
|
|
8773
|
+
}
|
|
8774
|
+
throw new MuxAiError("Transcript has no usable content.", {
|
|
8775
|
+
code: MUX_AI_ERROR_CODES.TRANSCRIPT_EMPTY,
|
|
8776
|
+
type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR,
|
|
8777
|
+
source: MUX_AI_ERROR_SOURCES.ASSET,
|
|
8778
|
+
facts: { assetId, ...trackId && { trackId } }
|
|
8779
|
+
});
|
|
8591
8780
|
}
|
|
8592
8781
|
const resolvedLanguageCode = outputLanguageCode && outputLanguageCode !== "auto" ? outputLanguageCode : getReliableLanguageCode(transcriptResult.track);
|
|
8593
8782
|
const languageName = resolvedLanguageCode ? getLanguageName(resolvedLanguageCode) : void 0;
|
|
@@ -8597,6 +8786,7 @@ async function generateTextInternal(assetId, rawOptions, collectedUsage) {
|
|
|
8597
8786
|
}
|
|
8598
8787
|
const steering = { audience, voice, callToAction, brandTerms };
|
|
8599
8788
|
const safety = createSafetyReporter();
|
|
8789
|
+
const briefFacts = { call: "extract_brief", provider: modelConfig.provider, model: modelConfig.modelId, assetId };
|
|
8600
8790
|
const briefStep = await extractBriefWithModel({
|
|
8601
8791
|
provider: modelConfig.provider,
|
|
8602
8792
|
modelId: modelConfig.modelId,
|
|
@@ -8604,12 +8794,12 @@ async function generateTextInternal(assetId, rawOptions, collectedUsage) {
|
|
|
8604
8794
|
userPrompt: buildBriefUserPrompt({ transcriptText, imageCount: imageUrls.length, audience, languageName }),
|
|
8605
8795
|
imageUrls,
|
|
8606
8796
|
credentials
|
|
8607
|
-
}).catch((error) =>
|
|
8797
|
+
}).catch((error) => wrapError(error, `Failed to extract editorial brief with ${provider}`, { ...briefFacts }));
|
|
8608
8798
|
collectedUsage.push(briefStep.usage);
|
|
8609
8799
|
for (const key of briefStep.unexpectedKeys) {
|
|
8610
8800
|
safety.record(`editorial_brief.${key}`, "unexpected_key");
|
|
8611
8801
|
}
|
|
8612
|
-
const brief = scrubBrief(briefStep.brief, safety);
|
|
8802
|
+
const brief = scrubBrief(briefStep.brief, safety, briefFacts);
|
|
8613
8803
|
const matrix = variants.flatMap((variant) => artifacts.map((artifact) => ({
|
|
8614
8804
|
variant,
|
|
8615
8805
|
artifact,
|
|
@@ -8623,7 +8813,7 @@ async function generateTextInternal(assetId, rawOptions, collectedUsage) {
|
|
|
8623
8813
|
limits,
|
|
8624
8814
|
protectedTerms: brandTerms,
|
|
8625
8815
|
credentials
|
|
8626
|
-
})), collectedUsage, provider);
|
|
8816
|
+
})), collectedUsage, provider, modelConfig.modelId, assetId);
|
|
8627
8817
|
const groupedVariants = variants.map((variant, variantIndex) => ({
|
|
8628
8818
|
key: variant.key,
|
|
8629
8819
|
artifacts: artifacts.map((artifact, artifactIndex) => {
|
|
@@ -8632,13 +8822,30 @@ async function generateTextInternal(assetId, rawOptions, collectedUsage) {
|
|
|
8632
8822
|
for (const key of item.unexpectedKeys) {
|
|
8633
8823
|
safety.record(`${field}.${key}`, "unexpected_key");
|
|
8634
8824
|
}
|
|
8825
|
+
const artifactFacts = { call: "generate_artifact", provider: modelConfig.provider, model: modelConfig.modelId, assetId, variant: variant.key, artifact: artifact.key };
|
|
8635
8826
|
if (item.violation === "empty") {
|
|
8636
|
-
throw new
|
|
8827
|
+
throw new MuxAiError(`Generated text for ${field} was empty after a retry.`, {
|
|
8828
|
+
code: MUX_AI_ERROR_CODES.MODEL_OUTPUT_MISSING,
|
|
8829
|
+
type: MUX_AI_ERROR_TYPES.PROCESSING_ERROR,
|
|
8830
|
+
source: MUX_AI_ERROR_SOURCES.UPSTREAM,
|
|
8831
|
+
dependency: MUX_AI_ERROR_DEPENDENCIES.AI_PROVIDER,
|
|
8832
|
+
facts: artifactFacts,
|
|
8833
|
+
transient: false,
|
|
8834
|
+
retryable: true
|
|
8835
|
+
});
|
|
8637
8836
|
}
|
|
8638
8837
|
if (item.violation) {
|
|
8639
|
-
throw new
|
|
8838
|
+
throw new MuxAiError(
|
|
8640
8839
|
`Generated text for ${field} exceeded the ${item.violation.limit.value} ${item.violation.limit.unit} limit after a retry (${item.violation.actual} returned).`,
|
|
8641
|
-
{
|
|
8840
|
+
{
|
|
8841
|
+
code: MUX_AI_ERROR_CODES.MODEL_OUTPUT_INVALID,
|
|
8842
|
+
type: MUX_AI_ERROR_TYPES.PROCESSING_ERROR,
|
|
8843
|
+
source: MUX_AI_ERROR_SOURCES.UPSTREAM,
|
|
8844
|
+
dependency: MUX_AI_ERROR_DEPENDENCIES.AI_PROVIDER,
|
|
8845
|
+
facts: { ...artifactFacts, reason: "over_length", limitUnit: item.violation.limit.unit, limit: item.violation.limit.value, actual: item.violation.actual },
|
|
8846
|
+
transient: false,
|
|
8847
|
+
retryable: true
|
|
8848
|
+
}
|
|
8642
8849
|
);
|
|
8643
8850
|
}
|
|
8644
8851
|
return {
|