File size: 25,588 Bytes
25d91a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
// Shares media-generation runtime polling and response helpers across providers.
import { clampTimerTimeoutMs } from "@openclaw/normalization-core/number-coercion";
import { normalizeOptionalString } from "@openclaw/normalization-core/string-coerce";
import { resolveCapabilityModelRefForProviders } from "../../packages/media-generation-core/src/capability-model-ref.js";
import type { MediaGenerationNormalizationMetadataInput } from "../../packages/media-generation-core/src/normalization.js";
import { DEFAULT_PROVIDER } from "../agents/defaults.js";
import { describeFailoverError, isFailoverError } from "../agents/failover-error.js";
import type { FallbackAttempt } from "../agents/model-fallback.types.js";
import {
  resolveAgentModelFallbackValues,
  resolveAgentModelPrimaryValue,
} from "../config/model-input.js";
import type { AgentModelConfig } from "../config/types.agents-shared.js";
import type { OpenClawConfig } from "../config/types.js";
import { formatErrorMessage, toErrorObject } from "../infra/errors.js";
import { isProviderApiKeyConfigured } from "../plugin-sdk/provider-auth.js";
import { getProviderEnvVars as getDefaultProviderEnvVars } from "../secrets/provider-env-vars.js";

// Shared media-generation runtime helpers for provider fallback, request
// timeout normalization, model selection, and capability value normalization.
export { hasMediaNormalizationEntry } from "../../packages/media-generation-core/src/normalization.js";

type ParsedProviderModelRef = {
  provider: string;
  model: string;
};

function buildCapabilityCandidateFailure(
  candidate: ParsedProviderModelRef,
  error: unknown,
): FallbackAttempt {
  const described = isFailoverError(error) ? describeFailoverError(error) : undefined;
  return {
    provider: candidate.provider,
    model: candidate.model,
    error: described?.message ?? formatErrorMessage(error),
    reason: described?.reason,
    status: described?.status,
    code: described?.code,
  };
}

type PreparedMediaGenerationCandidate<TResult> =
  | string
  | ((attempts: FallbackAttempt[]) => Promise<TResult>);

/** Keeps provider lookup and capability preflight outside the generation fallback catch. */
export async function runMediaGenerationCandidates<TProvider extends object, TResult>(params: {
  candidates: readonly ParsedProviderModelRef[];
  capability: "image" | "music" | "video";
  getProvider: (providerId: string) => TProvider | undefined;
  prepareCandidate: (
    candidate: ParsedProviderModelRef,
    provider: TProvider,
  ) =>
    | PreparedMediaGenerationCandidate<TResult>
    | Promise<PreparedMediaGenerationCandidate<TResult>>;
  /** Image/music skip records retain optional failure fields; video skip records do not. */
  includeSkipFailureDetails?: boolean;
  onMissingProvider?: (attempt: FallbackAttempt) => void;
  onFailure?: (attempt: FallbackAttempt) => void;
}): Promise<TResult> {
  const attempts: FallbackAttempt[] = [];
  let lastError: unknown;
  for (const candidate of params.candidates) {
    const provider = params.getProvider(candidate.provider);
    const preparation = provider
      ? params.prepareCandidate(candidate, provider)
      : `No ${params.capability}-generation provider registered for ${candidate.provider}`;
    // Image/music preflight is synchronous; only video's capability overlay yields.
    const prepared = preparation instanceof Promise ? await preparation : preparation;
    if (typeof prepared === "string") {
      const attempt =
        provider && params.includeSkipFailureDetails
          ? buildCapabilityCandidateFailure(candidate, prepared)
          : { provider: candidate.provider, model: candidate.model, error: prepared };
      attempts.push(attempt);
      lastError = new Error(prepared);
      if (!provider) {
        params.onMissingProvider?.(attempt);
      }
      continue;
    }
    try {
      return await prepared(attempts);
    } catch (error) {
      lastError = error;
      const attempt = buildCapabilityCandidateFailure(candidate, error);
      attempts.push(attempt);
      params.onFailure?.(attempt);
    }
  }
  return throwCapabilityGenerationFailure({
    capabilityLabel: `${params.capability} generation`,
    attempts,
    lastError,
  });
}

/** Reject edit requests before provider I/O, including providers with incomplete limits. */
export function resolveReferenceImageCapabilityError(params: {
  candidateRef: string;
  inputImageCount: number;
  edit?: { enabled: boolean; maxInputImages?: number };
}): string | undefined {
  if (params.inputImageCount === 0) {
    return undefined;
  }
  if (!params.edit?.enabled) {
    return `${params.candidateRef} does not support reference-image edit inputs`;
  }
  const maxInputImages = params.edit.maxInputImages ?? 10;
  return params.inputImageCount > maxInputImages
    ? `${params.candidateRef} supports at most ${maxInputImages} reference image${maxInputImages === 1 ? "" : "s"}, ${params.inputImageCount} requested`
    : undefined;
}

const IMAGE_RESOLUTION_ORDER = ["1K", "2K", "4K"] as const;

function resolveMediaProviderDefaultTimeoutMs(timeoutMs: number | undefined): number | undefined {
  return typeof timeoutMs === "number" && Number.isFinite(timeoutMs) && timeoutMs > 0
    ? clampTimerTimeoutMs(timeoutMs)
    : undefined;
}

/** Resolves a request timeout, preferring per-request over provider defaults. */
export function resolveMediaProviderRequestTimeoutMs(params: {
  timeoutMs?: number;
  providerDefaultTimeoutMs?: number;
}): number | undefined {
  return (
    resolveMediaProviderDefaultTimeoutMs(params.timeoutMs) ??
    resolveMediaProviderDefaultTimeoutMs(params.providerDefaultTimeoutMs)
  );
}

type CapabilityProviderCandidate = {
  id: string;
  aliases?: readonly string[];
  defaultModel?: string | null;
  models?: readonly string[];
  isConfigured?: (ctx: { cfg?: OpenClawConfig; agentDir?: string }) => boolean;
};

type ParsedAspectRatio = {
  width: number;
  height: number;
  value: number;
};

type ParsedSize = {
  width: number;
  height: number;
  aspectRatio: number;
  area: number;
};

function resolveCurrentDefaultProviderId(cfg?: OpenClawConfig): string {
  const configured = resolveAgentModelPrimaryValue(cfg?.agents?.defaults?.model);
  const trimmed = normalizeOptionalString(configured);
  if (!trimmed) {
    return DEFAULT_PROVIDER;
  }
  const slash = trimmed.indexOf("/");
  if (slash <= 0) {
    return DEFAULT_PROVIDER;
  }
  const provider = normalizeOptionalString(trimmed.slice(0, slash));
  return provider || DEFAULT_PROVIDER;
}

function isCapabilityProviderConfigured(params: {
  provider: CapabilityProviderCandidate;
  cfg?: OpenClawConfig;
  agentDir?: string;
}): boolean {
  if (params.provider.isConfigured) {
    return params.provider.isConfigured({
      cfg: params.cfg,
      agentDir: params.agentDir,
    });
  }
  return isProviderApiKeyConfigured({
    provider: params.provider.id,
    cfg: params.cfg,
    agentDir: params.agentDir,
  });
}

function resolveAutoCapabilityFallbackRefs(params: {
  cfg: OpenClawConfig;
  agentDir?: string;
  listProviders: (cfg?: OpenClawConfig) => CapabilityProviderCandidate[];
}): string[] {
  const providerDefaults = new Map<string, { ref: string; aliases: string[] }>();
  for (const provider of params.listProviders(params.cfg)) {
    const providerId = normalizeOptionalString(provider.id);
    const modelId = normalizeOptionalString(provider.defaultModel);
    if (
      !providerId ||
      !modelId ||
      providerDefaults.has(providerId) ||
      !isCapabilityProviderConfigured({
        provider,
        cfg: params.cfg,
        agentDir: params.agentDir,
      })
    ) {
      continue;
    }
    const aliases = (provider.aliases ?? []).flatMap((alias) => {
      const normalized = normalizeOptionalString(alias);
      return normalized ? [normalized] : [];
    });
    providerDefaults.set(providerId, { ref: `${providerId}/${modelId}`, aliases });
  }

  const defaultProvider = resolveCurrentDefaultProviderId(params.cfg);
  const providerIds = [...providerDefaults.keys()].toSorted();
  const matchesDefaultProvider = (providerId: string): boolean => {
    const entry = providerDefaults.get(providerId);
    return providerId === defaultProvider || (entry?.aliases ?? []).includes(defaultProvider);
  };
  const orderedProviders = [
    ...providerIds.filter(matchesDefaultProvider),
    ...providerIds.filter((providerId) => !matchesDefaultProvider(providerId)),
  ];
  // Keep the user's default text provider first when it also has media support;
  // then add the remaining configured media providers deterministically.
  return orderedProviders.flatMap((providerId) => {
    const entry = providerDefaults.get(providerId);
    return entry ? [entry.ref] : [];
  });
}

/** Builds ordered provider/model candidates for one media capability request. */
export function resolveCapabilityModelCandidates(params: {
  cfg: OpenClawConfig;
  modelConfig: AgentModelConfig | undefined;
  modelOverride?: string;
  parseModelRef: (raw: string | undefined) => ParsedProviderModelRef | null;
  agentDir?: string;
  listProviders?: (cfg?: OpenClawConfig) => CapabilityProviderCandidate[];
  autoProviderFallback?: boolean;
}): ParsedProviderModelRef[] {
  const candidates: ParsedProviderModelRef[] = [];
  const seen = new Set<string>();
  let providers: CapabilityProviderCandidate[] | undefined;
  const getProviders = (): CapabilityProviderCandidate[] => {
    providers ??= params.listProviders?.(params.cfg) ?? [];
    return providers;
  };
  const resolveCandidate = (raw: string | undefined, options: { useProviderMetadata: boolean }) => {
    const trimmed = normalizeOptionalString(raw);
    if (!trimmed) {
      return null;
    }
    if (!options.useProviderMetadata) {
      return params.parseModelRef(raw);
    }
    return resolveCapabilityModelRefForProviders({
      raw: trimmed,
      providers: getProviders(),
      parseModelRef: params.parseModelRef,
    });
  };
  const add = (raw: string | undefined, options: { useProviderMetadata: boolean }) => {
    const candidate = resolveCandidate(raw, options);
    if (!candidate) {
      return;
    }
    const key = `${candidate.provider}/${candidate.model}`;
    if (seen.has(key)) {
      return;
    }
    seen.add(key);
    candidates.push(candidate);
  };

  const override = (() => {
    return resolveCandidate(params.modelOverride, { useProviderMetadata: true });
  })();
  if (override) {
    // Explicit model overrides are authoritative and should not be expanded into
    // auto provider fallback candidates.
    return [override];
  }

  // Cross-provider fallback is a fixed product policy; Doctor removes the retired opt-out.
  const autoProviderFallbackEnabled = params.autoProviderFallback ?? true;
  add(params.modelOverride, { useProviderMetadata: true });
  add(resolveAgentModelPrimaryValue(params.modelConfig), {
    useProviderMetadata: autoProviderFallbackEnabled,
  });
  for (const fallback of resolveAgentModelFallbackValues(params.modelConfig)) {
    add(fallback, { useProviderMetadata: autoProviderFallbackEnabled });
  }
  if (autoProviderFallbackEnabled && params.listProviders) {
    for (const candidate of resolveAutoCapabilityFallbackRefs({
      cfg: params.cfg,
      agentDir: params.agentDir,
      listProviders: () => getProviders(),
    })) {
      add(candidate, { useProviderMetadata: false });
    }
  }
  return candidates;
}

function normalizeSupportedValues<TValue extends string>(values?: readonly TValue[]): TValue[] {
  return (values ?? []).flatMap((entry) => {
    const normalized = normalizeOptionalString(entry);
    return normalized ? [entry] : [];
  });
}

function compareScores(
  next: { primary: number; secondary: number; tertiary: string },
  best: { primary: number; secondary: number; tertiary: string } | null,
): boolean {
  if (!best) {
    return true;
  }
  if (next.primary !== best.primary) {
    return next.primary < best.primary;
  }
  if (next.secondary !== best.secondary) {
    return next.secondary < best.secondary;
  }
  return next.tertiary.localeCompare(best.tertiary) < 0;
}

function parsePositiveDimensionPair(
  raw: string | null | undefined,
  pattern: RegExp,
): { width: number; height: number } | null {
  const trimmed = normalizeOptionalString(raw);
  if (!trimmed) {
    return null;
  }
  const match = pattern.exec(trimmed);
  if (!match) {
    return null;
  }
  const width = Number(match[1]);
  const height = Number(match[2]);
  if (!Number.isFinite(width) || !Number.isFinite(height) || width <= 0 || height <= 0) {
    return null;
  }
  return { width, height };
}

function parseAspectRatioValue(raw?: string | null): ParsedAspectRatio | null {
  const pair = parsePositiveDimensionPair(raw, /^(\d+(?:\.\d+)?)\s*:\s*(\d+(?:\.\d+)?)$/);
  if (!pair) {
    return null;
  }
  return {
    width: pair.width,
    height: pair.height,
    value: pair.width / pair.height,
  };
}

function parseSizeValue(raw?: string | null): ParsedSize | null {
  const pair = parsePositiveDimensionPair(raw, /^(\d+)\s*x\s*(\d+)$/i);
  if (!pair) {
    return null;
  }
  if (!Number.isSafeInteger(pair.width) || !Number.isSafeInteger(pair.height)) {
    return null;
  }
  return {
    width: pair.width,
    height: pair.height,
    aspectRatio: pair.width / pair.height,
    area: pair.width * pair.height,
  };
}

function greatestCommonDivisor(a: number, b: number): number {
  let left = Math.abs(a);
  let right = Math.abs(b);
  while (right !== 0) {
    const next = left % right;
    left = right;
    right = next;
  }
  return left || 1;
}

/** Derives a reduced aspect ratio string from a WIDTHxHEIGHT size. */
function deriveAspectRatioFromSize(size?: string): string | undefined {
  const parsed = parseSizeValue(size);
  if (!parsed) {
    return undefined;
  }
  const divisor = greatestCommonDivisor(parsed.width, parsed.height);
  return `${parsed.width / divisor}:${parsed.height / divisor}`;
}

/** Chooses the closest supported aspect ratio for a request. */
export function resolveClosestAspectRatio(params: {
  requestedAspectRatio?: string;
  requestedSize?: string;
  supportedAspectRatios?: readonly string[];
}): string | undefined {
  const supported = normalizeSupportedValues(params.supportedAspectRatios);
  if (supported.length === 0) {
    return params.requestedAspectRatio ?? deriveAspectRatioFromSize(params.requestedSize);
  }
  if (params.requestedAspectRatio && supported.includes(params.requestedAspectRatio)) {
    return params.requestedAspectRatio;
  }
  const requested =
    parseAspectRatioValue(params.requestedAspectRatio) ??
    parseAspectRatioValue(deriveAspectRatioFromSize(params.requestedSize));
  if (!requested) {
    return undefined;
  }

  let bestValue: string | undefined;
  let bestScore: { primary: number; secondary: number; tertiary: string } | null = null;
  for (const candidate of supported) {
    const parsed = parseAspectRatioValue(candidate);
    if (!parsed) {
      continue;
    }
    const score = {
      primary: Math.abs(Math.log(parsed.value / requested.value)),
      secondary: Math.abs(parsed.width * requested.height - requested.width * parsed.height),
      tertiary: candidate,
    };
    if (compareScores(score, bestScore)) {
      bestValue = candidate;
      bestScore = score;
    }
  }
  return bestValue;
}

/** Chooses the closest supported size by aspect ratio and area. */
export function resolveClosestSize(params: {
  requestedSize?: string;
  requestedAspectRatio?: string;
  supportedSizes?: readonly string[];
}): string | undefined {
  const supported = normalizeSupportedValues(params.supportedSizes);
  if (supported.length === 0) {
    return params.requestedSize;
  }
  if (params.requestedSize && supported.includes(params.requestedSize)) {
    return params.requestedSize;
  }
  const requested = parseSizeValue(params.requestedSize);
  const requestedAspectRatio = parseAspectRatioValue(params.requestedAspectRatio);
  if (!requested && !requestedAspectRatio) {
    return undefined;
  }

  let bestValue: string | undefined;
  let bestScore: { primary: number; secondary: number; tertiary: string } | null = null;
  for (const candidate of supported) {
    const parsed = parseSizeValue(candidate);
    if (!parsed) {
      continue;
    }
    const score = {
      primary: Math.abs(
        Math.log(parsed.aspectRatio / (requested?.aspectRatio ?? requestedAspectRatio!.value)),
      ),
      secondary: requested ? Math.abs(Math.log(parsed.area / requested.area)) : parsed.area,
      tertiary: candidate,
    };
    if (compareScores(score, bestScore)) {
      bestValue = candidate;
      bestScore = score;
    }
  }
  return bestValue;
}

/** Chooses the closest supported resolution by numeric rank or custom order. */
export function resolveClosestResolution<TResolution extends string>(params: {
  requestedResolution?: TResolution;
  supportedResolutions?: readonly TResolution[];
  order?: readonly TResolution[];
}): TResolution | undefined {
  const supported = normalizeSupportedValues(params.supportedResolutions);
  if (supported.length === 0) {
    return params.requestedResolution;
  }
  if (params.requestedResolution && supported.includes(params.requestedResolution)) {
    return params.requestedResolution;
  }
  const requestedNumeric = parseResolutionRank(params.requestedResolution);
  if (requestedNumeric) {
    let bestValue: TResolution | undefined;
    let bestScore: { primary: number; secondary: number; tertiary: string } | null = null;
    for (const candidate of supported) {
      const candidateNumeric = parseResolutionRank(candidate);
      if (!candidateNumeric || candidateNumeric.unit !== requestedNumeric.unit) {
        continue;
      }
      const score = {
        primary: Math.abs(candidateNumeric.value - requestedNumeric.value),
        secondary: candidateNumeric.value < requestedNumeric.value ? 1 : 0,
        tertiary: candidate,
      };
      if (compareScores(score, bestScore)) {
        bestValue = candidate;
        bestScore = score;
      }
    }
    if (bestValue) {
      return bestValue;
    }
  }
  const order: readonly string[] = params.order ?? IMAGE_RESOLUTION_ORDER;
  const requestedIndex = params.requestedResolution
    ? order.indexOf(params.requestedResolution)
    : -1;
  if (requestedIndex < 0) {
    return undefined;
  }

  let bestValue: TResolution | undefined;
  let bestScore: { primary: number; secondary: number; tertiary: string } | null = null;
  for (const candidate of supported) {
    const candidateIndex = order.indexOf(candidate);
    if (candidateIndex < 0) {
      continue;
    }
    const score = {
      primary: Math.abs(candidateIndex - requestedIndex),
      secondary: candidateIndex,
      tertiary: candidate,
    };
    if (compareScores(score, bestScore)) {
      bestValue = candidate;
      bestScore = score;
    }
  }
  return bestValue;
}

function parseResolutionRank(
  resolution: string | undefined,
): { value: number; unit: "K" | "P" } | undefined {
  const match = resolution?.trim().match(/^(\d+(?:\.\d+)?)([kp])$/iu);
  if (!match) {
    return undefined;
  }
  const value = Number(match[1]);
  if (!Number.isFinite(value)) {
    return undefined;
  }
  const unit = match[2]?.toUpperCase() === "K" ? "K" : "P";
  return {
    value: unit === "K" ? value * 1000 : value,
    unit,
  };
}

/** Rounds duration and clamps it to a provider maximum when supplied. */
export function normalizeDurationToClosestMax(
  durationSeconds?: number,
  maxDurationSeconds?: number,
) {
  if (typeof durationSeconds !== "number" || !Number.isFinite(durationSeconds)) {
    return undefined;
  }
  const rounded = Math.max(1, Math.round(durationSeconds));
  if (
    typeof maxDurationSeconds !== "number" ||
    !Number.isFinite(maxDurationSeconds) ||
    maxDurationSeconds <= 0
  ) {
    return rounded;
  }
  return Math.min(rounded, Math.max(1, Math.round(maxDurationSeconds)));
}

/** Builds user-visible metadata describing provider normalization decisions. */
export function buildMediaGenerationNormalizationMetadata(params: {
  normalization?: MediaGenerationNormalizationMetadataInput;
  requestedSizeForDerivedAspectRatio?: string;
  includeSupportedDurationSeconds?: boolean;
}): Record<string, unknown> {
  const metadata: Record<string, unknown> = {};
  const { normalization } = params;
  if (normalization?.size?.requested !== undefined && normalization.size.applied !== undefined) {
    metadata.requestedSize = normalization.size.requested;
    metadata.normalizedSize = normalization.size.applied;
  }
  if (normalization?.aspectRatio?.applied !== undefined) {
    if (normalization.aspectRatio.requested !== undefined) {
      metadata.requestedAspectRatio = normalization.aspectRatio.requested;
    }
    metadata.normalizedAspectRatio = normalization.aspectRatio.applied;
    if (
      normalization.aspectRatio.derivedFrom === "size" &&
      params.requestedSizeForDerivedAspectRatio
    ) {
      metadata.requestedSize = params.requestedSizeForDerivedAspectRatio;
      metadata.aspectRatioDerivedFromSize = deriveAspectRatioFromSize(
        params.requestedSizeForDerivedAspectRatio,
      );
    }
  }
  if (
    normalization?.resolution?.requested !== undefined &&
    normalization.resolution.applied !== undefined
  ) {
    metadata.requestedResolution = normalization.resolution.requested;
    metadata.normalizedResolution = normalization.resolution.applied;
  }
  if (
    normalization?.durationSeconds?.requested !== undefined &&
    normalization.durationSeconds.applied !== undefined
  ) {
    metadata.requestedDurationSeconds = normalization.durationSeconds.requested;
    metadata.normalizedDurationSeconds = normalization.durationSeconds.applied;
    if (
      params.includeSupportedDurationSeconds &&
      normalization.durationSeconds.supportedValues?.length
    ) {
      metadata.supportedDurationSeconds = normalization.durationSeconds.supportedValues;
    }
  }
  return metadata;
}

/** Throws a summarized error after all provider/model candidates fail. */
export function throwCapabilityGenerationFailure(params: {
  capabilityLabel: string;
  attempts: FallbackAttempt[];
  lastError: unknown;
}): never {
  if (params.attempts.length <= 1 && params.lastError) {
    throw toErrorObject(params.lastError, "Non-Error thrown");
  }
  const summary = formatCapabilityFailureAttempts(params.attempts);
  throw new Error(
    `All ${params.capabilityLabel} models failed (${params.attempts.length}): ${summary}`,
    {
      cause: params.lastError instanceof Error ? params.lastError : undefined,
    },
  );
}

function formatCapabilityFailureAttempts(attempts: FallbackAttempt[]): string {
  if (attempts.length === 0) {
    return "unknown";
  }

  const abortedAttempts = attempts.filter(isAbortLikeFallbackAttempt);
  if (abortedAttempts.length === 0) {
    return attempts.map(formatCapabilityFailureAttempt).join(" | ");
  }
  if (abortedAttempts.length === attempts.length) {
    return `${abortedAttempts.length} fallback(s) aborted after the request was cancelled or timed out: ${abortedAttempts.map(formatCapabilityAttemptRef).join(", ")}`;
  }

  const primaryFailures = attempts.filter((attempt) => !isAbortLikeFallbackAttempt(attempt));
  return [
    primaryFailures.map(formatCapabilityFailureAttempt).join(" | "),
    `${abortedAttempts.length} fallback(s) aborted after the request was cancelled or timed out: ${abortedAttempts.map(formatCapabilityAttemptRef).join(", ")}`,
  ].join(" | ");
}

function formatCapabilityFailureAttempt(attempt: FallbackAttempt): string {
  return `${formatCapabilityAttemptRef(attempt)}: ${attempt.error}`;
}

function formatCapabilityAttemptRef(attempt: FallbackAttempt): string {
  return `${attempt.provider}/${attempt.model}`;
}

function isAbortLikeFallbackAttempt(attempt: FallbackAttempt): boolean {
  const message = attempt.error.trim().toLowerCase();
  return (
    message === "this operation was aborted" ||
    message === "operation was aborted" ||
    message.includes("operation was aborted") ||
    message.includes("request was aborted")
  );
}

/** Formats setup guidance when no model is configured for a media capability. */
export function buildNoCapabilityModelConfiguredMessage(params: {
  capabilityLabel: string;
  modelConfigKey: string;
  providers: Array<{ id: string; defaultModel?: string | null }>;
  fallbackSampleRef?: string;
  getProviderEnvVars?: typeof getDefaultProviderEnvVars;
}): string {
  const getProviderEnvVars = params.getProviderEnvVars ?? getDefaultProviderEnvVars;
  const sampleModel = params.providers.find(
    (provider) =>
      normalizeOptionalString(provider.id) && normalizeOptionalString(provider.defaultModel),
  );
  const sampleRef = sampleModel
    ? `${sampleModel.id}/${sampleModel.defaultModel}`
    : (params.fallbackSampleRef ?? "<provider>/<model>");
  const authHints = params.providers
    .flatMap((provider) => {
      const envVars = getProviderEnvVars(provider.id);
      if (envVars.length === 0) {
        return [];
      }
      return [`${provider.id}: ${envVars.join(" / ")}`];
    })
    .slice(0, 3);
  return [
    `No ${params.capabilityLabel} model configured. Set agents.defaults.${params.modelConfigKey}.primary to a provider/model like "${sampleRef}".`,
    authHints.length > 0
      ? `If you want a specific provider, also configure that provider's auth/API key first (${authHints.join("; ")}).`
      : "If you want a specific provider, also configure that provider's auth/API key first.",
  ].join(" ");
}