@mux/ai 0.54.0 → 0.56.0

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.
@@ -1,5 +1,5 @@
1
1
  import { LanguageModel, generateText as generateText$1 } from 'ai';
2
- import { l as WorkflowCredentialsInput, M as MuxAsset, A as AssetTextTrack, i as TokenUsage, f as ScopedMuxAIOptions, I as ImageSubmissionMode, d as MuxAIOptions, b as ChunkingStrategy, k as VideoEmbeddingsResult, H as Hotspot, y as Shot, q as VTTCue, j as ToneType, g as StorageAdapter } from './transcripts-BCtzC8hZ.js';
2
+ import { l as WorkflowCredentialsInput, M as MuxAsset, A as AssetTextTrack, T as TokenUsage, f as ScopedMuxAIOptions, I as ImageSubmissionMode, d as MuxAIOptions, b as ChunkingStrategy, k as VideoEmbeddingsResult, H as Hotspot, y as Shot, q as VTTCue, j as ToneType, g as StorageAdapter } from './transcripts-Brw74qlV.js';
3
3
  import { z } from 'zod';
4
4
  import { S as SafetyReport, e as PromptOverrides, h as SceneContextItemV1, D as DEFAULT_DESCRIPTION_LENGTH, a as DEFAULT_SUMMARY_KEYWORD_LIMIT, b as DEFAULT_TITLE_LENGTH } from './summarization-BFmhXeAu.js';
5
5
  import { createAnthropic } from '@ai-sdk/anthropic';
@@ -1,4 +1,4 @@
1
- import { l as WorkflowCredentialsInput, n as WorkflowScope, T as TextChunk, b as ChunkingStrategy, q as VTTCue, r as CompletedShotsResult, D as DeletedShotsResult, s as ErroredShotsResult, H as Hotspot, t as HotspotOptions, u as HotspotResponse, L as LOW_CONFIDENCE_THRESHOLD, v as MAX_CUE_TEXT_CHARS, w as ParseVTTCuesOptions, x as PendingShotsResult, y as Shot, z as ShotRequestOptions, B as ShotsResult, F as SkippedShotsResult, G as TranscriptEmptyReason, J as TranscriptFetchOptions, K as TranscriptFetchStepResult, N as TranscriptResult, O as WaitForShotsOptions, Q as buildTranscriptUrl, R as buildVttFromCueBlocks, X as buildVttFromTranslatedCueBlocks, Y as concatenateVttSegments, Z as extractTextFromVTT, _ as extractTimestampedTranscript, $ as fetchTranscriptDataForUrl, a0 as fetchTranscriptForAsset, a1 as filterVttByScope, a2 as findCaptionTrack, a3 as getHotspotsForAsset, a4 as getHotspotsForPlaybackId, a5 as getHotspotsForVideo, a6 as getReadyTextTracks, a7 as getReliableLanguageCode, a8 as getShotsForAsset, a9 as parseVTTCues, aa as replaceCueText, ab as requestShotsForAsset, ac as sanitizeUntrustedText, ad as secondsToTimestamp, ae as splitVttPreambleAndCueBlocks, af as stripVttMetadataBlocks, ag as vttTimestampToSeconds, ah as waitForShotsForAsset } from './transcripts-BCtzC8hZ.js';
1
+ import { l as WorkflowCredentialsInput, n as WorkflowScope, h as TextChunk, b as ChunkingStrategy, q as VTTCue, r as CompletedShotsResult, D as DeletedShotsResult, s as ErroredShotsResult, H as Hotspot, t as HotspotOptions, u as HotspotResponse, L as LOW_CONFIDENCE_THRESHOLD, v as MAX_CUE_TEXT_CHARS, w as ParseVTTCuesOptions, x as PendingShotsResult, y as Shot, z as ShotRequestOptions, B as ShotsResult, F as SkippedShotsResult, G as TranscriptEmptyReason, J as TranscriptFetchOptions, K as TranscriptFetchStepResult, N as TranscriptResult, O as WaitForShotsOptions, Q as buildTranscriptUrl, R as buildVttFromCueBlocks, X as buildVttFromTranslatedCueBlocks, Y as concatenateVttSegments, Z as extractTextFromVTT, _ as extractTimestampedTranscript, $ as fetchTranscriptDataForUrl, a0 as fetchTranscriptForAsset, a1 as filterVttByScope, a2 as findCaptionTrack, a3 as getHotspotsForAsset, a4 as getHotspotsForPlaybackId, a5 as getHotspotsForVideo, a6 as getReadyTextTracks, a7 as getReliableLanguageCode, a8 as getShotsForAsset, a9 as parseVTTCues, aa as replaceCueText, ab as requestShotsForAsset, ac as sanitizeUntrustedText, ad as secondsToTimestamp, ae as splitVttPreambleAndCueBlocks, af as stripVttMetadataBlocks, ag as vttTimestampToSeconds, ah as waitForShotsForAsset } from './transcripts-Brw74qlV.js';
2
2
 
3
3
  interface HeatmapOptions {
4
4
  /** Time window for results, e.g., '7:days' (default: '7:days') */
package/dist/index.d.ts CHANGED
@@ -1,8 +1,8 @@
1
- export { I as ISO639_1, a as ISO639_3, L as LanguageCodePair, M as MUX_TRACK_PASSTHROUGH_MAX_CHARS, R as ReplaceAndCreateTextTrackInput, b as ReplaceAndCreateTextTrackResult, c as ReplaceAndCreateTrackInput, d as ReplaceExistingTracksPolicy, e as ReplaceSourceTrackInput, f as ReplaceableTrackType, S as SourceTrackReplacementPolicy, g as SupportedISO639_1, h as SupportedISO639_3, T as TextTrackReplacementPlan, i as TextTrackSummary, j as TextTrackTarget, k as TrackSummary, l as TrackTarget, m as buildMuxAiTrackPassthrough, n as findNameCollisionTextTracks, o as findSameLanguageTextTracks, p as getLanguageCodePair, q as getLanguageName, r as isDuplicateTrackNameError, s as isMuxGeneratedTextTrack, t as isUndeterminedLanguageCode, u as isValidISO639_1, v as isValidISO639_3, w as normalizeTrackLanguageCode, x as normalizeTrackName, y as planSourceTrackReplacement, z as planTextTrackReplacement, A as replaceAndCreateTextTrack, B as replaceAndCreateTrack, C as replaceSourceTrack, D as summarizeTextTrack, E as toISO639_1, F as toISO639_3, G as validateTrackPassthrough, H as workflows } from './index-CmTC1w4V.js';
2
- import { M as MuxAsset, W as WorkflowCredentials, S as StoragePutObjectInput, a as StoragePresignGetObjectInput } from './transcripts-BCtzC8hZ.js';
3
- export { A as AssetTextTrack, C as ChunkEmbedding, b as ChunkingStrategy, E as Encrypted, c as EncryptedPayload, I as ImageSubmissionMode, d as MuxAIOptions, P as PlaybackAsset, e as PlaybackPolicy, f as ScopedMuxAIOptions, g as StorageAdapter, T as TextChunk, h as TokenChunkingConfig, i as TokenUsage, j as ToneType, U as UsageMetadata, V as VTTChunkingConfig, k as VideoEmbeddingsResult, l as WorkflowCredentialsInput, m as WorkflowMuxClient, n as WorkflowScope, o as decryptFromWorkflow, p as encryptForWorkflow } from './transcripts-BCtzC8hZ.js';
1
+ export { I as ISO639_1, a as ISO639_3, L as LanguageCodePair, M as MUX_TRACK_PASSTHROUGH_MAX_CHARS, R as ReplaceAndCreateTextTrackInput, b as ReplaceAndCreateTextTrackResult, c as ReplaceAndCreateTrackInput, d as ReplaceExistingTracksPolicy, e as ReplaceSourceTrackInput, f as ReplaceableTrackType, S as SourceTrackReplacementPolicy, g as SupportedISO639_1, h as SupportedISO639_3, T as TextTrackReplacementPlan, i as TextTrackSummary, j as TextTrackTarget, k as TrackSummary, l as TrackTarget, m as buildMuxAiTrackPassthrough, n as findNameCollisionTextTracks, o as findSameLanguageTextTracks, p as getLanguageCodePair, q as getLanguageName, r as isDuplicateTrackNameError, s as isMuxGeneratedTextTrack, t as isUndeterminedLanguageCode, u as isValidISO639_1, v as isValidISO639_3, w as normalizeTrackLanguageCode, x as normalizeTrackName, y as planSourceTrackReplacement, z as planTextTrackReplacement, A as replaceAndCreateTextTrack, B as replaceAndCreateTrack, C as replaceSourceTrack, D as summarizeTextTrack, E as toISO639_1, F as toISO639_3, G as validateTrackPassthrough, H as workflows } from './index-Bav9fNtf.js';
4
2
  import { WORKFLOW_SERIALIZE, WORKFLOW_DESERIALIZE } from '@workflow/serde';
5
- export { i as primitives } from './index-cbaPe-aE.js';
3
+ import { T as TokenUsage, M as MuxAsset, W as WorkflowCredentials, S as StoragePutObjectInput, a as StoragePresignGetObjectInput } from './transcripts-Brw74qlV.js';
4
+ export { A as AssetTextTrack, C as ChunkEmbedding, b as ChunkingStrategy, E as Encrypted, c as EncryptedPayload, I as ImageSubmissionMode, d as MuxAIOptions, P as PlaybackAsset, e as PlaybackPolicy, f as ScopedMuxAIOptions, g as StorageAdapter, h as TextChunk, i as TokenChunkingConfig, j as ToneType, U as UsageMetadata, V as VTTChunkingConfig, k as VideoEmbeddingsResult, l as WorkflowCredentialsInput, m as WorkflowMuxClient, n as WorkflowScope, o as decryptFromWorkflow, p as encryptForWorkflow } from './transcripts-Brw74qlV.js';
5
+ export { i as primitives } from './index-DiuqBw6I.js';
6
6
  import 'ai';
7
7
  import 'zod';
8
8
  import './summarization-BFmhXeAu.js';
@@ -11,9 +11,25 @@ import '@ai-sdk/google';
11
11
  import '@ai-sdk/openai';
12
12
  import '@mux/ts';
13
13
 
14
- var version = "0.54.0";
14
+ var version = "0.56.0";
15
15
 
16
16
  type MuxAiErrorType = "validation_error" | "processing_error" | "timeout_error" | "content_policy_error";
17
+ interface ModelCallDiagnostics {
18
+ phase: "brief" | "draft" | "format_repair" | "length_repair";
19
+ provider: string;
20
+ modelId: string;
21
+ maxOutputTokens?: number;
22
+ }
23
+ interface SerializedMuxAiError {
24
+ message: string;
25
+ publicType: MuxAiErrorType;
26
+ retryable: boolean;
27
+ stack?: string;
28
+ usage?: TokenUsage;
29
+ finishReason?: string;
30
+ rawFinishReason?: string;
31
+ diagnostics?: ModelCallDiagnostics;
32
+ }
17
33
  /**
18
34
  * An error whose message is safe to surface verbatim to the customer.
19
35
  *
@@ -23,9 +39,8 @@ type MuxAiErrorType = "validation_error" | "processing_error" | "timeout_error"
23
39
  * this brand (unexpected SDK failures, upstream provider errors, etc.)
24
40
  * should be treated as internal and obfuscated.
25
41
  *
26
- * Own properties (`publicMessage`, `publicType`, `retryable`) survive
27
- * JSON serialization across workflow step boundaries, unlike inherited
28
- * `Error.message`.
42
+ * Custom Workflow serializers preserve safe metadata across step boundaries.
43
+ * The runtime's built-in Error serializer drops arbitrary own properties.
29
44
  */
30
45
  declare class MuxAiError extends Error {
31
46
  /** Structural brand for duck-type identification. */
@@ -36,6 +51,8 @@ declare class MuxAiError extends Error {
36
51
  readonly publicMessage: string;
37
52
  /** Whether the customer should retry the job. */
38
53
  readonly retryable: boolean;
54
+ usage?: TokenUsage;
55
+ diagnostics?: ModelCallDiagnostics;
39
56
  /** Internal diagnostic failure; non-enumerable and excluded from JSON. */
40
57
  readonly cause?: unknown;
41
58
  constructor(message: string, opts?: {
@@ -44,6 +61,8 @@ declare class MuxAiError extends Error {
44
61
  cause?: unknown;
45
62
  });
46
63
  static is(value: unknown): value is MuxAiError;
64
+ static [WORKFLOW_SERIALIZE](instance: MuxAiError): SerializedMuxAiError;
65
+ static [WORKFLOW_DESERIALIZE](value: SerializedMuxAiError): MuxAiError;
47
66
  }
48
67
  declare function wrapError(error: unknown, message: string): never;
49
68
 
@@ -131,4 +150,4 @@ declare class WorkflowStorageClient {
131
150
  }
132
151
  declare function createWorkflowStorageClient(options?: WorkflowStorageClientOptions): WorkflowStorageClient;
133
152
 
134
- export { type LegacyMp4SupportRendition, MuxAiError, type MuxAiErrorType, MuxAsset, type MuxPlaybackService, STATIC_RENDITIONS_GUIDE_URL, StoragePresignGetObjectInput, StoragePutObjectInput, WorkflowCredentials, type WorkflowCredentialsProvider, WorkflowStorageClient, createWorkflowStorageClient, getLegacyMp4SupportRenditionSizeError, getMuxPlaybackOrigin, resolveLegacyMp4SupportRendition, setWorkflowCredentialsProvider, usesLegacyMp4Support, version, wrapError };
153
+ export { type LegacyMp4SupportRendition, MuxAiError, type MuxAiErrorType, MuxAsset, type MuxPlaybackService, STATIC_RENDITIONS_GUIDE_URL, StoragePresignGetObjectInput, StoragePutObjectInput, TokenUsage, WorkflowCredentials, type WorkflowCredentialsProvider, WorkflowStorageClient, createWorkflowStorageClient, getLegacyMp4SupportRenditionSizeError, getMuxPlaybackOrigin, resolveLegacyMp4SupportRendition, setWorkflowCredentialsProvider, usesLegacyMp4Support, version, wrapError };
package/dist/index.js CHANGED
@@ -5,7 +5,7 @@ var __export = (target, all) => {
5
5
  };
6
6
 
7
7
  // package.json
8
- var version = "0.54.0";
8
+ var version = "0.56.0";
9
9
 
10
10
  // src/lib/language-codes.ts
11
11
  var ISO639_1_TO_3 = {
@@ -178,6 +178,10 @@ function getLanguageName(code) {
178
178
  }
179
179
  }
180
180
 
181
+ // node_modules/@workflow/serde/dist/index.js
182
+ var WORKFLOW_SERIALIZE = /* @__PURE__ */ Symbol.for("workflow-serialize");
183
+ var WORKFLOW_DESERIALIZE = /* @__PURE__ */ Symbol.for("workflow-deserialize");
184
+
181
185
  // src/lib/prompt-fragments.ts
182
186
  import dedent from "dedent";
183
187
 
@@ -699,7 +703,7 @@ function rethrowWithTokenUsage(error, collectedUsage) {
699
703
  }
700
704
 
701
705
  // src/lib/mux-ai-error.ts
702
- var MuxAiError = class extends Error {
706
+ var MuxAiError = class _MuxAiError extends Error {
703
707
  constructor(message, opts) {
704
708
  super(message);
705
709
  /** Structural brand for duck-type identification. */
@@ -715,6 +719,32 @@ var MuxAiError = class extends Error {
715
719
  static is(value) {
716
720
  return typeof value === "object" && value !== null && "__robots_error" in value && value.__robots_error === true;
717
721
  }
722
+ static [WORKFLOW_SERIALIZE](instance) {
723
+ const incomplete = instance;
724
+ return {
725
+ message: instance.publicMessage,
726
+ publicType: instance.publicType,
727
+ retryable: instance.retryable,
728
+ stack: instance.stack,
729
+ usage: getErrorTokenUsage(instance),
730
+ finishReason: incomplete.finishReason,
731
+ rawFinishReason: incomplete.rawFinishReason,
732
+ diagnostics: instance.diagnostics
733
+ };
734
+ }
735
+ static [WORKFLOW_DESERIALIZE](value) {
736
+ const error = new _MuxAiError(value.message, { type: value.publicType, retryable: value.retryable });
737
+ Object.assign(error, {
738
+ usage: value.usage,
739
+ diagnostics: value.diagnostics,
740
+ ...value.finishReason !== void 0 && { finishReason: value.finishReason },
741
+ ...value.rawFinishReason !== void 0 && { rawFinishReason: value.rawFinishReason }
742
+ });
743
+ if (value.stack !== void 0) {
744
+ error.stack = value.stack;
745
+ }
746
+ return error;
747
+ }
718
748
  };
719
749
  function extractErrorDetail(error) {
720
750
  if (error instanceof Error && error.message) {
@@ -1528,10 +1558,6 @@ async function getMuxThumbnailBaseUrl(playbackId, credentials) {
1528
1558
  return getMuxImageBaseUrl(playbackId, "thumbnail", credentials);
1529
1559
  }
1530
1560
 
1531
- // node_modules/@workflow/serde/dist/index.js
1532
- var WORKFLOW_SERIALIZE = /* @__PURE__ */ Symbol.for("workflow-serialize");
1533
- var WORKFLOW_DESERIALIZE = /* @__PURE__ */ Symbol.for("workflow-deserialize");
1534
-
1535
1561
  // src/lib/s3-sigv4.ts
1536
1562
  var AWS4_ALGORITHM = "AWS4-HMAC-SHA256";
1537
1563
  var AWS4_REQUEST_TERMINATOR = "aws4_request";
@@ -3086,14 +3112,13 @@ function extractTextFromVTT(vttContent) {
3086
3112
  textLines.join(" ").replace(/\s+/g, " ").trim()
3087
3113
  );
3088
3114
  }
3115
+ var VTT_TIMESTAMP_RE = /^(?:(\d+):)?(\d{2}):(\d{2})(?:\.(\d{3}))?$/;
3089
3116
  function vttTimestampToSeconds(timestamp) {
3090
- const parts = timestamp.split(":");
3091
- if (parts.length !== 3)
3092
- return 0;
3093
- const hours = Number.parseInt(parts[0], 10) || 0;
3094
- const minutes = Number.parseInt(parts[1], 10) || 0;
3095
- const seconds = Number.parseFloat(parts[2]) || 0;
3096
- return hours * 3600 + minutes * 60 + seconds;
3117
+ const match = VTT_TIMESTAMP_RE.exec(timestamp);
3118
+ if (!match)
3119
+ return void 0;
3120
+ const [, hours = "0", minutes, seconds, millis = "0"] = match;
3121
+ return Number(hours) * 3600 + Number(minutes) * 60 + Number(seconds) + Number(millis) / 1e3;
3097
3122
  }
3098
3123
  function secondsToTimestamp(seconds) {
3099
3124
  const rounded = Math.max(0, Math.floor(seconds));
@@ -3116,6 +3141,8 @@ function extractTimestampedTranscript(vttContent) {
3116
3141
  if (line.includes("-->")) {
3117
3142
  const startTime = line.split(" --> ")[0].trim();
3118
3143
  const timeInSeconds = vttTimestampToSeconds(startTime);
3144
+ if (timeInSeconds === void 0)
3145
+ continue;
3119
3146
  let j = i + 1;
3120
3147
  while (j < lines.length && !lines[j].trim()) {
3121
3148
  j++;
@@ -3144,13 +3171,17 @@ function parseVTTCues(vttContent, options = {}) {
3144
3171
  if (isTimingLine(line)) {
3145
3172
  const [startStr, endStr] = line.split(" --> ").map((s) => s.trim());
3146
3173
  const startTime = vttTimestampToSeconds(startStr);
3147
- const endTime = vttTimestampToSeconds(endStr.split(" ")[0]);
3174
+ const endTime = vttTimestampToSeconds(endStr?.split(/\s+/)[0] ?? "");
3148
3175
  const currentCueIdentifierLine = lines[i - 1]?.trim() ?? "";
3149
3176
  const currentCueIdentifier = isLikelyCueIdentifier({
3150
3177
  line: currentCueIdentifierLine,
3151
3178
  nextLine: line,
3152
3179
  previousCueIdentifier
3153
3180
  }) ? parseNumericCueIdentifier(currentCueIdentifierLine) : null;
3181
+ if (startTime === void 0 || endTime === void 0) {
3182
+ previousCueIdentifier = currentCueIdentifier;
3183
+ continue;
3184
+ }
3154
3185
  const rawTextLines = [];
3155
3186
  let j = i + 1;
3156
3187
  while (j < lines.length && lines[j].trim() && !isTimingLine(lines[j].trim())) {
@@ -3487,7 +3518,8 @@ async function withRetry(fn, {
3487
3518
  maxRetries = DEFAULT_RETRY_OPTIONS.maxRetries,
3488
3519
  baseDelay = DEFAULT_RETRY_OPTIONS.baseDelay,
3489
3520
  maxDelay = DEFAULT_RETRY_OPTIONS.maxDelay,
3490
- shouldRetry = defaultShouldRetry
3521
+ shouldRetry = defaultShouldRetry,
3522
+ onRetry
3491
3523
  } = {}) {
3492
3524
  let lastError;
3493
3525
  for (let attempt = 0; attempt <= maxRetries; attempt++) {
@@ -3500,6 +3532,7 @@ async function withRetry(fn, {
3500
3532
  if (isLastAttempt || !shouldRetry(retryError, attempt + 1)) {
3501
3533
  throw error;
3502
3534
  }
3535
+ onRetry?.(error, attempt + 1);
3503
3536
  const delay = calculateDelay(attempt + 1, baseDelay, maxDelay);
3504
3537
  console.warn(
3505
3538
  `Attempt ${attempt + 1} failed: ${retryError.message}. Retrying in ${Math.round(delay)}ms...`
@@ -3593,10 +3626,54 @@ async function withContentPolicyErrorHandling(operation) {
3593
3626
  }
3594
3627
  }
3595
3628
  async function withContentPolicyAwareRetry(operation, retryOptions) {
3596
- return withRetry(
3597
- () => withContentPolicyErrorHandling(operation),
3598
- retryOptions
3599
- );
3629
+ const retriedUsage = [];
3630
+ try {
3631
+ const response = await withRetry(
3632
+ () => withContentPolicyErrorHandling(operation),
3633
+ {
3634
+ ...retryOptions,
3635
+ onRetry: (error, attempt) => {
3636
+ const usage = getErrorTokenUsage(error);
3637
+ if (usage) {
3638
+ retriedUsage.push(usage);
3639
+ }
3640
+ retryOptions?.onRetry?.(error, attempt);
3641
+ }
3642
+ }
3643
+ );
3644
+ return includeRetriedUsage(response, retriedUsage);
3645
+ } catch (error) {
3646
+ rethrowWithTokenUsage(error, retriedUsage);
3647
+ }
3648
+ }
3649
+ function includeRetriedUsage(response, retriedUsage) {
3650
+ if (!retriedUsage.length || typeof response !== "object" || response === null) {
3651
+ return response;
3652
+ }
3653
+ const result = response;
3654
+ const merge = (usage) => {
3655
+ const combined = aggregateTokenUsage([...retriedUsage, getErrorTokenUsage({ usage }) ?? {}]);
3656
+ return {
3657
+ ...usage,
3658
+ ...combined,
3659
+ ...combined.cachedInputTokens !== void 0 || combined.cacheWriteTokens !== void 0 ? {
3660
+ inputTokenDetails: {
3661
+ ...usage?.inputTokenDetails,
3662
+ ...combined.cachedInputTokens !== void 0 && { cacheReadTokens: combined.cachedInputTokens },
3663
+ ...combined.cacheWriteTokens !== void 0 && { cacheWriteTokens: combined.cacheWriteTokens }
3664
+ }
3665
+ } : {},
3666
+ ...combined.reasoningTokens !== void 0 ? {
3667
+ outputTokenDetails: { ...usage?.outputTokenDetails, reasoningTokens: combined.reasoningTokens }
3668
+ } : {}
3669
+ };
3670
+ };
3671
+ const descriptors = Object.getOwnPropertyDescriptors(response);
3672
+ descriptors.usage = { value: merge(result.usage), enumerable: true, configurable: true };
3673
+ if ("totalUsage" in result) {
3674
+ descriptors.totalUsage = { value: merge(result.totalUsage), enumerable: true, configurable: true };
3675
+ }
3676
+ return Object.create(Object.getPrototypeOf(response), descriptors);
3600
3677
  }
3601
3678
  function rethrowContentPolicyError(error) {
3602
3679
  const block = extractContentPolicyBlock(error);
@@ -3732,6 +3809,35 @@ function findBlockedCategory(ratings) {
3732
3809
  return ratings?.find((rating) => rating.blocked === true)?.category ?? void 0;
3733
3810
  }
3734
3811
 
3812
+ // src/lib/model-call-diagnostics.ts
3813
+ import { APICallError as APICallError3 } from "ai";
3814
+ function recordModelCallFailure(error, diagnostics, observedUsage = getErrorTokenUsage(error)) {
3815
+ if (typeof error !== "object" || error === null) {
3816
+ return;
3817
+ }
3818
+ const failure = error;
3819
+ if (failure.diagnostics) {
3820
+ return;
3821
+ }
3822
+ failure.diagnostics = { ...diagnostics };
3823
+ console.warn("[@mux/ai] Model call failed.", {
3824
+ ...diagnostics,
3825
+ finishReason: failure.finishReason,
3826
+ statusCode: failure.statusCode,
3827
+ errorName: error instanceof Error ? error.name : void 0,
3828
+ requestId: APICallError3.isInstance(error) ? error.responseHeaders?.["x-request-id"] ?? error.responseHeaders?.["request-id"] : void 0,
3829
+ usage: observedUsage
3830
+ });
3831
+ }
3832
+ async function withModelCallDiagnostics(diagnostics, operation) {
3833
+ try {
3834
+ return await operation();
3835
+ } catch (error) {
3836
+ recordModelCallFailure(error, diagnostics);
3837
+ throw error;
3838
+ }
3839
+ }
3840
+
3735
3841
  // src/lib/text-repair-capabilities.ts
3736
3842
  var OPENAI_REPAIR_CAPABILITIES = {
3737
3843
  "gpt-5.1": { supportsReasoningNone: true },
@@ -3893,13 +3999,14 @@ function createTextRepairGenerator(options) {
3893
3999
  return async (plan) => {
3894
4000
  let usage;
3895
4001
  const started = Date.now();
4002
+ const maxOutputTokens = options.maxOutputTokens ?? Math.min(32768, Math.max(1024, plan.spans.reduce((total, span) => total + Math.min(...span.budgets.map((limit) => limit.value * (limit.unit === "words" ? 4 : 2))), 0) + 128));
3896
4003
  try {
3897
4004
  const response = await withContentPolicyErrorHandling(() => generateText({
3898
4005
  model: options.model,
3899
4006
  providerOptions: options.providerOptions ?? getTextRepairProviderOptions(options.model),
3900
4007
  maxRetries: 0,
3901
4008
  abortSignal: AbortSignal.timeout(options.timeoutMs ?? 3e4),
3902
- maxOutputTokens: options.maxOutputTokens ?? Math.min(32768, Math.max(1024, plan.spans.reduce((total, span) => total + Math.min(...span.budgets.map((limit) => limit.value * (limit.unit === "words" ? 4 : 2))), 0) + 128)),
4009
+ maxOutputTokens,
3903
4010
  output: Output.object({ schema: jsonSchema(repairJsonSchema(plan)), name: "paragraph_replacements" }),
3904
4011
  system: promptDedent`
3905
4012
  ${NON_DISCLOSURE_CONSTRAINT}
@@ -3927,6 +4034,12 @@ function createTextRepairGenerator(options) {
3927
4034
  return { replacements: output, usage, elapsedMs: Date.now() - started };
3928
4035
  } catch (error) {
3929
4036
  const cause = NoObjectGeneratedError2.isInstance(error) && error.finishReason && error.finishReason !== "stop" ? new IncompleteGenerationError(error.finishReason, void 0, getErrorTokenUsage(error)) : error;
4037
+ recordModelCallFailure(cause, {
4038
+ phase: "length_repair",
4039
+ provider: typeof options.model === "object" ? options.model.provider : "gateway",
4040
+ modelId: typeof options.model === "object" ? options.model.modelId : options.model,
4041
+ maxOutputTokens
4042
+ }, usage ?? getErrorTokenUsage(cause));
3930
4043
  return { usage: usage ?? getErrorTokenUsage(cause), elapsedMs: Date.now() - started, error: cause instanceof Error ? cause.message : String(cause), errorCause: cause };
3931
4044
  }
3932
4045
  };
@@ -5547,7 +5660,7 @@ function transformCueText(rawVtt, transform) {
5547
5660
  const transformed = lines.map((line) => {
5548
5661
  if (line.includes("-->")) {
5549
5662
  const startTimestamp = line.split("-->")[0].trim();
5550
- currentCueStartTime = vttTimestampToSeconds(startTimestamp);
5663
+ currentCueStartTime = vttTimestampToSeconds(startTimestamp) ?? currentCueStartTime;
5551
5664
  inCueText = true;
5552
5665
  return line;
5553
5666
  }
@@ -5579,7 +5692,7 @@ function transformCueTextBlocks(rawVtt, transform) {
5579
5692
  if (line.includes("-->")) {
5580
5693
  flushCueText();
5581
5694
  const startTimestamp = line.split("-->")[0].trim();
5582
- currentCueStartTime = vttTimestampToSeconds(startTimestamp);
5695
+ currentCueStartTime = vttTimestampToSeconds(startTimestamp) ?? currentCueStartTime;
5583
5696
  transformed.push(line);
5584
5697
  cueTextLines = [];
5585
5698
  continue;
@@ -6789,7 +6902,7 @@ async function generateEngagementInsightsInternal(assetId, options, collectedUsa
6789
6902
  }
6790
6903
 
6791
6904
  // src/workflows/generate-text.ts
6792
- import { APICallError as APICallError3, generateText as generateTextWithModel, Output as Output7 } from "ai";
6905
+ import { APICallError as APICallError4, generateText as generateTextWithModel, Output as Output7 } from "ai";
6793
6906
  import { z as z8 } from "zod";
6794
6907
  var GENERATE_TEXT_MAX_VARIANTS = 5;
6795
6908
  var GENERATE_TEXT_MAX_ARTIFACTS = 5;
@@ -6912,7 +7025,7 @@ function resolveGenerateTextOptions(options) {
6912
7025
  }
6913
7026
  return { ...options, variants };
6914
7027
  }
6915
- var LENGTH_TARGET_RATIO = 0.9;
7028
+ var LENGTH_TARGET_RATIO = 0.85;
6916
7029
  function resolveLengthTarget(limit) {
6917
7030
  return Math.max(1, Math.floor(limit.value * LENGTH_TARGET_RATIO));
6918
7031
  }
@@ -7201,122 +7314,124 @@ function readUsage(response) {
7201
7314
  }
7202
7315
  async function extractBriefWithModel(args) {
7203
7316
  "use step";
7204
- const model = await createLanguageModelFromConfig(args.provider, args.modelId, args.credentials);
7205
- const response = await withContentPolicyAwareRetry(() => generateTextWithModel({
7206
- model,
7207
- maxRetries: 0,
7208
- output: Output7.object({
7209
- name: "editorial_brief",
7210
- description: "Source-grounded editorial brief used to write every requested artifact.",
7211
- schema: briefSchema
7212
- }),
7213
- system: args.systemPrompt,
7214
- messages: [
7215
- {
7216
- role: "user",
7217
- content: [
7218
- { type: "text", text: args.userPrompt },
7219
- ...args.imageUrls.map((url) => ({ type: "image", image: url }))
7220
- ]
7221
- }
7222
- ]
7223
- }));
7224
- const output = getGeneratedOutputWithContentPolicyHandling(response);
7225
- if (!output) {
7226
- throw new Error("Editorial brief output missing");
7227
- }
7228
- return {
7229
- brief: clampBriefArrays(briefSchema.parse(output)),
7230
- usage: readUsage(response),
7231
- unexpectedKeys: detectUnexpectedKeysFromRawText(response.text, briefSchema.keyof().options)
7232
- };
7233
- }
7234
- var artifactSchema = z8.object({ content: z8.string() });
7235
- async function generateArtifactWithModel(args) {
7236
- "use step";
7237
- const model = await createLanguageModelFromConfig(args.provider, args.modelId, args.credentials);
7238
- const attempt = async (messages) => {
7317
+ return withModelCallDiagnostics({ phase: "brief", provider: args.provider, modelId: args.modelId }, async () => {
7318
+ const model = await createLanguageModelFromConfig(args.provider, args.modelId, args.credentials);
7239
7319
  const response = await withContentPolicyAwareRetry(() => generateTextWithModel({
7240
7320
  model,
7241
7321
  maxRetries: 0,
7242
7322
  output: Output7.object({
7243
- name: "generated_text",
7244
- description: "One finished artifact written from the editorial brief.",
7245
- schema: artifactSchema
7323
+ name: "editorial_brief",
7324
+ description: "Source-grounded editorial brief used to write every requested artifact.",
7325
+ schema: briefSchema
7246
7326
  }),
7247
7327
  system: args.systemPrompt,
7248
- messages
7328
+ messages: [
7329
+ {
7330
+ role: "user",
7331
+ content: [
7332
+ { type: "text", text: args.userPrompt },
7333
+ ...args.imageUrls.map((url) => ({ type: "image", image: url }))
7334
+ ]
7335
+ }
7336
+ ]
7249
7337
  }));
7250
7338
  const output = getGeneratedOutputWithContentPolicyHandling(response);
7251
7339
  if (!output) {
7252
- throw new Error("Generated text output missing");
7340
+ throw new Error("Editorial brief output missing");
7253
7341
  }
7254
7342
  return {
7255
- content: artifactSchema.parse(output).content.trim(),
7343
+ brief: clampBriefArrays(briefSchema.parse(output)),
7256
7344
  usage: readUsage(response),
7257
- unexpectedKeys: detectUnexpectedKeysFromRawText(response.text, artifactSchema.keyof().options)
7345
+ unexpectedKeys: detectUnexpectedKeysFromRawText(response.text, briefSchema.keyof().options)
7258
7346
  };
7259
- };
7260
- const judge = (content) => content ? findGenerateTextLengthViolation(content, args.limits) : "empty";
7261
- const initialMessages = [{ role: "user", content: args.userPrompt }];
7262
- const first = await attempt(initialMessages);
7263
- const firstViolation = judge(first.content);
7264
- const firstEscaped = hasEscapedLineBreaks(first.content);
7265
- if (!firstViolation && !firstEscaped) {
7266
- return { content: first.content, usages: [first.usage], unexpectedKeys: first.unexpectedKeys };
7267
- }
7268
- let candidate = first;
7269
- const usages = [first.usage];
7270
- const unexpectedKeys = [...first.unexpectedKeys];
7271
- if (firstViolation === "empty" || firstEscaped) {
7272
- const feedback = [
7273
- firstViolation && firstViolation !== "empty" ? describeLengthRevision(firstViolation) : void 0,
7274
- firstEscaped ? ESCAPED_TEXT_REVISION : void 0
7275
- ].filter((line) => Boolean(line)).join("\n");
7276
- const revisionMessages = firstViolation === "empty" ? [{ role: "user", content: `${args.userPrompt}
7347
+ });
7348
+ }
7349
+ var artifactSchema = z8.object({ content: z8.string() });
7350
+ async function generateArtifactWithModel(args) {
7351
+ "use step";
7352
+ const diagnostics = { phase: "draft", provider: args.provider, modelId: args.modelId };
7353
+ return withModelCallDiagnostics(diagnostics, async () => {
7354
+ const model = await createLanguageModelFromConfig(args.provider, args.modelId, args.credentials);
7355
+ const attempt = async (messages) => {
7356
+ const response = await withContentPolicyAwareRetry(() => generateTextWithModel({
7357
+ model,
7358
+ maxRetries: 0,
7359
+ output: Output7.object({
7360
+ name: "generated_text",
7361
+ description: "One finished artifact written from the editorial brief.",
7362
+ schema: artifactSchema
7363
+ }),
7364
+ system: args.systemPrompt,
7365
+ messages
7366
+ }));
7367
+ const output = getGeneratedOutputWithContentPolicyHandling(response);
7368
+ if (!output) {
7369
+ throw new Error("Generated text output missing");
7370
+ }
7371
+ return {
7372
+ content: artifactSchema.parse(output).content.trim(),
7373
+ usage: readUsage(response),
7374
+ unexpectedKeys: detectUnexpectedKeysFromRawText(response.text, artifactSchema.keyof().options)
7375
+ };
7376
+ };
7377
+ const judge = (content) => content ? findGenerateTextLengthViolation(content, args.limits) : "empty";
7378
+ const initialMessages = [{ role: "user", content: args.userPrompt }];
7379
+ const first = await attempt(initialMessages);
7380
+ const firstViolation = judge(first.content);
7381
+ const firstEscaped = hasEscapedLineBreaks(first.content);
7382
+ if (!firstViolation && !firstEscaped) {
7383
+ return { content: first.content, usages: [first.usage], unexpectedKeys: first.unexpectedKeys };
7384
+ }
7385
+ let candidate = first;
7386
+ const usages = [first.usage];
7387
+ const unexpectedKeys = [...first.unexpectedKeys];
7388
+ if (firstViolation === "empty" || firstEscaped) {
7389
+ const feedback = [
7390
+ firstViolation && firstViolation !== "empty" ? describeLengthRevision(firstViolation) : void 0,
7391
+ firstEscaped ? ESCAPED_TEXT_REVISION : void 0
7392
+ ].filter((line) => Boolean(line)).join("\n");
7393
+ const revisionMessages = firstViolation === "empty" ? [{ role: "user", content: `${args.userPrompt}
7277
7394
 
7278
7395
  ${renderSection({ tag: "revision_request", content: "The previous draft was empty. Write the complete artifact." })}` }] : [...initialMessages, { role: "assistant", content: JSON.stringify({ content: first.content }) }, { role: "user", content: renderSection({ tag: "revision_request", content: feedback }) }];
7279
- candidate = await attempt(revisionMessages).catch((error) => rethrowWithTokenUsage(error, usages));
7280
- usages.push(candidate.usage);
7281
- unexpectedKeys.push(...candidate.unexpectedKeys);
7282
- }
7283
- const violation = judge(candidate.content);
7284
- if (!violation || violation === "empty") {
7285
- return { content: candidate.content, usages, unexpectedKeys, violation };
7286
- }
7287
- const repaired = await repairText({
7288
- content: candidate.content,
7289
- limits: args.limits,
7290
- protectedTerms: args.protectedTerms,
7291
- model
7292
- });
7293
- usages.push(...repaired.attempts.flatMap((item) => item.call.usage ? [item.call.usage] : []));
7294
- if (repaired.status !== "valid") {
7295
- const cause = repaired.attempts.at(-1)?.call.errorCause;
7296
- let failure;
7297
- if (isIncompleteGenerationError(cause)) {
7298
- failure = new IncompleteGenerationError(cause.finishReason, cause.rawFinishReason);
7299
- } else if (MuxAiError.is(cause)) {
7300
- failure = new MuxAiError(cause.publicMessage, { type: cause.publicType, retryable: cause.retryable });
7301
- } else {
7302
- const apiError = APICallError3.isInstance(cause) ? cause : void 0;
7303
- console.warn("[@mux/ai] Bounded text repair failed.", {
7304
- provider: args.provider,
7305
- modelId: args.modelId,
7306
- reason: repaired.reason,
7307
- errorName: cause instanceof Error ? cause.name : void 0,
7308
- statusCode: apiError?.statusCode,
7309
- requestId: apiError?.responseHeaders?.["x-request-id"] ?? apiError?.responseHeaders?.["request-id"]
7310
- });
7311
- failure = new MuxAiError("Unable to complete text generation.", {
7312
- type: "processing_error",
7313
- retryable: apiError?.isRetryable ?? true,
7314
- cause
7315
- });
7396
+ diagnostics.phase = "format_repair";
7397
+ candidate = await attempt(revisionMessages).catch((error) => rethrowWithTokenUsage(error, usages));
7398
+ usages.push(candidate.usage);
7399
+ unexpectedKeys.push(...candidate.unexpectedKeys);
7400
+ }
7401
+ const violation = judge(candidate.content);
7402
+ if (!violation || violation === "empty") {
7403
+ return { content: candidate.content, usages, unexpectedKeys, violation };
7404
+ }
7405
+ diagnostics.phase = "length_repair";
7406
+ const repaired = await repairText({
7407
+ content: candidate.content,
7408
+ limits: args.limits,
7409
+ protectedTerms: args.protectedTerms,
7410
+ model
7411
+ });
7412
+ usages.push(...repaired.attempts.flatMap((item) => item.call.usage ? [item.call.usage] : []));
7413
+ if (repaired.status !== "valid") {
7414
+ const cause = repaired.attempts.at(-1)?.call.errorCause;
7415
+ let failure;
7416
+ if (isIncompleteGenerationError(cause)) {
7417
+ failure = new IncompleteGenerationError(cause.finishReason, cause.rawFinishReason);
7418
+ } else if (MuxAiError.is(cause)) {
7419
+ failure = new MuxAiError(cause.publicMessage, { type: cause.publicType, retryable: cause.retryable });
7420
+ } else {
7421
+ const apiError = APICallError4.isInstance(cause) ? cause : void 0;
7422
+ failure = new MuxAiError("Unable to complete text generation.", {
7423
+ type: "processing_error",
7424
+ retryable: apiError?.isRetryable ?? true,
7425
+ cause
7426
+ });
7427
+ }
7428
+ if (typeof cause === "object" && cause !== null && "diagnostics" in cause) {
7429
+ failure.diagnostics = cause.diagnostics;
7430
+ }
7431
+ rethrowWithTokenUsage(failure, usages);
7316
7432
  }
7317
- rethrowWithTokenUsage(failure, usages);
7318
- }
7319
- return { content: repaired.content, usages, unexpectedKeys };
7433
+ return { content: repaired.content, usages, unexpectedKeys };
7434
+ });
7320
7435
  }
7321
7436
  async function generateText7(assetId, options) {
7322
7437
  "use workflow";
@@ -9702,7 +9817,7 @@ async function translateAudio(assetId, toLanguageCode, options = {}) {
9702
9817
 
9703
9818
  // src/workflows/translate-captions.ts
9704
9819
  import {
9705
- APICallError as APICallError4,
9820
+ APICallError as APICallError5,
9706
9821
  generateText as generateText9,
9707
9822
  NoObjectGeneratedError as NoObjectGeneratedError3,
9708
9823
  NoOutputGeneratedError as NoOutputGeneratedError2,
@@ -9857,7 +9972,7 @@ function isProviderServiceError(error) {
9857
9972
  if (RetryError2.isInstance(error)) {
9858
9973
  return isProviderServiceError(error.lastError);
9859
9974
  }
9860
- if (APICallError4.isInstance(error)) {
9975
+ if (APICallError5.isInstance(error)) {
9861
9976
  return true;
9862
9977
  }
9863
9978
  if (error instanceof Error && "cause" in error) {