Repository navigation
Expand file tree
/
Copy pathretry-fallback-chains.ts
More file actions
663 lines (624 loc) · 26.2 KB
/
Copy pathretry-fallback-chains.ts
File metadata and controls
663 lines (624 loc) · 26.2 KB
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
import type { ThinkingLevel } from "@oh-my-pi/pi-agent-core";
import type { Model } from "@oh-my-pi/pi-ai";
import type { ModelRegistry } from "../config/model-registry";
import { cfgModelRoles } from "../config/model-settings";
import { formatModelSelectorValue, parseModelString } from "@oh-my-pi/pi-tui/overlays/model-selector";
import { formatModelString, formatModelStringWithRouting } from "../config/model-resolver";
import type { Settings } from "../config/settings";
import {
type ConfiguredThinkingLevel,
concreteThinkingLevel,
resolveThinkingLevelForModel,
} from "@oh-my-pi/pi-tui/thinking";
import { resolveConfiguredModelPatterns, resolveModelRoleValue } from "../config/model-resolver";
import { getRoleInfo, isKindRole } from "../config/model-roles";
import { cfgRetryFallbackChains, cfgRetryFallbackRevertPolicy, type RetrySettings } from "./settings";
/** Configured fallback chains keyed by role or model selector. */
export type RetryFallbackChains = Record<string, string[]>;
/** Policy controlling restoration of a fallback chain's primary model. */
export type RetryFallbackRevertPolicy = "never" | "cooldown-expiry";
/** Parsed model selector used by retry fallback resolution. */
export interface RetryFallbackSelector {
raw: string;
provider: string;
id: string;
thinkingLevel: ThinkingLevel | undefined;
}
/** Minimal model lookup needed by fallback-chain resolution. */
export interface RetryFallbackModelLookup {
find(provider: string, id: string): Model | undefined;
hasProvider(provider: string): boolean;
}
/**
* Inputs shared by startup (sdk) and runtime (turn-recovery) fallback-chain
* resolution. `chains` is pre-expanded so callers can apply the default chain
* to roles beyond the configured model roles (e.g. a subagent fallback role).
*/
export interface RetryFallbackResolutionContext {
chains: RetryFallbackChains;
getModelRole(role: string): string | undefined;
modelLookup: RetryFallbackModelLookup;
}
/** Active retry fallback state retained until the primary can be restored. */
export interface ActiveRetryFallbackState {
/** Chain key that produced this fallback: a model-role name or a model-selector key. */
role: string;
originalSelector: string;
originalThinkingLevel: ConfiguredThinkingLevel | undefined;
lastAppliedFallbackThinkingLevel: ConfiguredThinkingLevel | undefined;
pinned: boolean;
/**
* Set once a turn on the fallback target settles successfully. Until then the
* switch is only a routing decision — nothing has been produced by the new
* model, so no observer may report the run as having used it.
*/
served?: boolean;
}
/** Model a session's produced work is attributed to. */
export interface ServingModel {
/** Full selector including routing and thinking level. */
selector: string;
/** Provider/id including routing, with no added thinking suffix. */
modelIdentity?: string;
/** Concrete thinking level captured with the attributed model. */
thinkingLevel?: ThinkingLevel;
/** Whether fallback routing, rather than the configured primary, owns it. */
isFallback: boolean;
/**
* Context window of the attributed model, carried verbatim from
* {@link Model.contextWindow} (`null` when the model declares none), so
* observers size context usage against the model that produced the turn
* instead of the one the run started on.
*/
contextWindow?: number | null;
}
const RETRY_BACKOFF_MAX_DELAY_MS = 8_000;
const RETRY_BACKOFF_JITTER_RATIO = 0.25;
/** Calculates capped exponential retry delay with downward jitter. */
export function calculateRetryBackoffDelayMs(baseDelayMs: number, attempt: number): number {
const cappedDelayMs = Math.min(Math.max(0, baseDelayMs) * 2 ** Math.max(0, attempt - 1), RETRY_BACKOFF_MAX_DELAY_MS);
const jitter = 1 - Math.random() * RETRY_BACKOFF_JITTER_RATIO;
return cappedDelayMs * jitter;
}
/** Parses a configured retry fallback selector. */
export function parseRetryFallbackSelector(
selector: string,
modelLookup?: Pick<RetryFallbackModelLookup, "find">,
): RetryFallbackSelector | undefined {
const trimmed = selector.trim();
if (!trimmed) return undefined;
const parsed = parseModelString(trimmed, {
allowMaxSuffix: true,
allowAutoAlias: true,
isLiteralModelId: (provider, id) => modelLookup?.find(provider, id) !== undefined,
});
if (!parsed) return undefined;
return {
raw: trimmed,
provider: parsed.provider,
id: parsed.id,
thinkingLevel: concreteThinkingLevel(parsed.thinkingLevel),
};
}
/** Whether a fallback-chain key is a model selector rather than a role. */
export function isRetryFallbackModelKey(key: string): boolean {
return key.includes("/");
}
/** Whether a fallback-chain key or entry is a provider wildcard. */
export function isRetryFallbackWildcardKey(key: string): boolean {
return key.endsWith("/*");
}
/** Splits a wildcard selector into provider and optional model-id prefix. */
export function parseRetryFallbackWildcard(
key: string,
isKnownProvider: (provider: string) => boolean,
): { provider: string; idPrefix: string | undefined } {
const template = key.slice(0, -2);
const slash = template.indexOf("/");
if (slash < 0 || isKnownProvider(template)) return { provider: template, idPrefix: undefined };
return { provider: template.slice(0, slash), idPrefix: template.slice(slash + 1) };
}
/** Formats a concrete model and thinking level as a fallback selector. */
export function formatRetryFallbackSelector(model: Model, thinkingLevel: ThinkingLevel | undefined): string {
return formatModelSelectorValue(formatModelStringWithRouting(model), thinkingLevel);
}
/** Formats the model-only portion of a parsed fallback selector (`provider/id`, no thinking level). */
export function formatRetryFallbackBaseSelector(selector: RetryFallbackSelector): string {
return `${selector.provider}/${selector.id}`;
}
/** Whether a provider is registered or configured for discovery. */
export function isKnownProvider(
modelRegistry: Pick<RetryFallbackModelLookup, "hasProvider">,
provider: string,
): boolean {
return modelRegistry.hasProvider(provider);
}
/** Apply the configured default chain to roles without their own chain. */
export function expandDefaultRetryFallbackChains(
configuredChains: RetryFallbackChains,
roleNames: readonly string[],
): RetryFallbackChains {
const chains: RetryFallbackChains = { ...configuredChains };
const defaultChain = chains.default;
if (!Array.isArray(defaultChain)) return chains;
for (const role of roleNames) {
if (role !== "default" && !isKindRole(role) && chains[role] === undefined) chains[role] = defaultChain;
}
return chains;
}
/** Resolves configured fallback chains, applying the default chain to named roles. */
export function getRetryFallbackChains(settings: Settings): RetryFallbackChains {
const configuredChains = cfgRetryFallbackChains.get(settings);
if (!configuredChains || typeof configuredChains !== "object") return {};
return expandDefaultRetryFallbackChains(configuredChains, Object.keys(settings.getModelRoles()));
}
/**
* A dynamic role pinned to one model selector with its own fallback chain.
* Subagents own one under `subagent:<id>`; `session_init` persists it so cold
* revival restores the same routing the spawn installed.
*/
export interface RetryFallbackRole {
/** Selector the role is assigned (the chain's primary). */
primary: string;
/** Fallback selectors walked after the primary; empty explicitly disables fallbacks. */
chain: string[];
}
/** Reads the primary and chain installed for `role`, including an explicitly empty chain. */
export function getRetryFallbackRole(settings: Settings, role: string): RetryFallbackRole | undefined {
const primary = settings.getModelRole(role);
const chain = cfgRetryFallbackChains.get(settings)[role];
if (!primary || !Array.isArray(chain)) return undefined;
return { primary, chain };
}
/**
* Assigns `role` its primary and installs its chain ahead of every configured
* chain, so another role assigned the same model cannot capture its routing.
* Overrides are session-scoped: nothing is written to the user's config.
*/
export function installRetryFallbackRole(
settings: Settings,
role: string,
{ primary, chain }: RetryFallbackRole,
): void {
const modelRoles: Record<string, string> = {};
const existingRoles = settings.getModelRoles();
for (const key in existingRoles) {
const selector = existingRoles[key];
if (selector) modelRoles[key] = selector;
}
modelRoles[role] = primary;
cfgModelRoles.override(settings, modelRoles);
const fallbackChains: RetryFallbackChains = { [role]: chain };
const existingChains = cfgRetryFallbackChains.get(settings);
for (const key in existingChains) {
if (key !== role) fallbackChains[key] = existingChains[key];
}
cfgRetryFallbackChains.override(settings, fallbackChains);
}
/**
* Catalog slice covering every provider a selector's patterns name, or
* `undefined` when a pattern is provider-less and needs the whole catalog.
*/
function providerScopedPool(
modelRegistry: Pick<ModelRegistry, "find" | "getProviderModels">,
patterns: readonly string[],
): Model[] | undefined {
const providers = new Set<string>();
for (const pattern of patterns) {
const parsed = parseRetryFallbackSelector(pattern, modelRegistry);
if (!parsed) return undefined;
providers.add(parsed.provider);
}
const pool: Model[] = [];
for (const provider of providers) pool.push(...modelRegistry.getProviderModels(provider));
return pool;
}
/**
* Validates configured fallback chains and reports each warning via `warn`.
*
* `options.isDiscoveryPending` suppresses "unknown model" warnings for
* selectors whose provider discovery has not settled yet: a cold discovery
* cache after `omp update` bumps the cache namespace (#10048), or a startup
* cache replay the pending online refresh may still extend. Such selectors
* are re-checked once background discovery settles. Logging is the caller's
* responsibility so a post-discovery re-run does not double-log persistent
* warnings.
*/
export function validateRetryFallbackChains(
settings: Settings,
modelRegistry: Pick<ModelRegistry, "getAll" | "find" | "hasProvider" | "getProviderModels">,
warn: (message: string) => void,
options: { isDiscoveryPending?: (provider: string) => boolean } = {},
): void {
const configuredChains = cfgRetryFallbackChains.get(settings);
if (configuredChains === undefined) return;
const report = warn;
const isDiscoveryPending = options.isDiscoveryPending ?? (() => false);
if (!configuredChains || typeof configuredChains !== "object" || Array.isArray(configuredChains)) {
report("retry.fallbackChains must be a mapping of role names or model selectors to selector arrays.");
return;
}
for (const key in configuredChains) {
const chain = configuredChains[key];
const keyKind = isRetryFallbackModelKey(key) ? "model" : "role";
if (keyKind === "model") {
if (isRetryFallbackWildcardKey(key)) {
const { provider } = parseRetryFallbackWildcard(key, candidate =>
isKnownProvider(modelRegistry, candidate),
);
if (!isKnownProvider(modelRegistry, provider)) {
report(`retry.fallbackChains wildcard key references unknown provider: ${key}`);
}
} else {
const parsedKey = parseRetryFallbackSelector(key, modelRegistry);
if (!parsedKey) {
report(`Invalid model selector key in retry.fallbackChains: ${key}`);
} else if (
!modelRegistry.find(parsedKey.provider, parsedKey.id) &&
!isDiscoveryPending(parsedKey.provider)
) {
report(`retry.fallbackChains key references unknown model: ${key}`);
}
}
}
if (!Array.isArray(chain)) {
report(`Fallback chain for ${keyKind} '${key}' must be an array of selector strings.`);
continue;
}
// Compatibility is a catalog property, independent of credentials and enabled providers.
const kindRole = keyKind === "role" && isKindRole(key) ? getRoleInfo(key, settings) : undefined;
// Provider-qualified selectors are checked against their providers' slices
// first; the full catalog (expensive to compose) only backs a failed check,
// so warnings are unchanged while the happy path stays cheap.
let kindRoleCatalog: Model[] | undefined;
const resolvesForKindRole = (selectorStr: string, pool: Model[] | undefined): boolean =>
pool !== undefined &&
kindRole !== undefined &&
resolveModelRoleValue(selectorStr, pool.filter(kindRole.accepts), { settings }).model !== undefined;
for (const selectorStr of chain) {
if (typeof selectorStr !== "string") {
report(`Fallback chain for ${keyKind} '${key}' contains a non-string selector.`);
continue;
}
if (kindRole) {
const patterns = resolveConfiguredModelPatterns(selectorStr, settings);
if (resolvesForKindRole(selectorStr, providerScopedPool(modelRegistry, patterns))) continue;
kindRoleCatalog ??= modelRegistry.getAll("all");
if (resolvesForKindRole(selectorStr, kindRoleCatalog)) continue;
const pending =
patterns.length > 0 &&
patterns.every(pattern => {
const parsed = parseRetryFallbackSelector(pattern, modelRegistry);
return parsed ? isDiscoveryPending(parsed.provider) : false;
});
if (!pending) {
report(`Fallback chain for role '${key}' does not resolve to a compatible model: ${selectorStr}`);
}
continue;
}
if (isRetryFallbackWildcardKey(selectorStr)) {
const { provider } = parseRetryFallbackWildcard(selectorStr, candidate =>
isKnownProvider(modelRegistry, candidate),
);
if (!isKnownProvider(modelRegistry, provider)) {
report(`Fallback chain for ${keyKind} '${key}' references unknown provider: ${selectorStr}`);
}
continue;
}
const parsed = parseRetryFallbackSelector(selectorStr, modelRegistry);
if (!parsed) {
report(`Invalid fallback selector format in ${keyKind} '${key}': ${selectorStr}`);
continue;
}
if (!modelRegistry.find(parsed.provider, parsed.id) && !isDiscoveryPending(parsed.provider)) {
report(`Fallback chain for ${keyKind} '${key}' references unknown model: ${selectorStr}`);
}
}
}
}
/** Returns the configured fallback-primary restoration policy. */
export function getRetryFallbackRevertPolicy(settings: Settings): RetryFallbackRevertPolicy {
return cfgRetryFallbackRevertPolicy.get(settings) === "never" ? "never" : "cooldown-expiry";
}
/** Whether `retry.fallbackOn` lets a failure walk the fallback chain. */
export function retryFallbackAdmits(fallbackOn: RetrySettings["fallbackOn"], usageLimit: boolean): boolean {
switch (fallbackOn) {
case "any":
return true;
case "usage-limit":
return usageLimit;
case "except-usage-limit":
return !usageLimit;
}
}
/** Resolves the primary selector represented by a fallback-chain key. */
function getRetryFallbackPrimarySelector(
context: RetryFallbackResolutionContext,
chainKey: string,
): RetryFallbackSelector | undefined {
if (isRetryFallbackWildcardKey(chainKey)) return undefined;
if (isRetryFallbackModelKey(chainKey)) return parseRetryFallbackSelector(chainKey, context.modelLookup);
const configuredSelector = context.getModelRole(chainKey);
return configuredSelector ? parseRetryFallbackSelector(configuredSelector, context.modelLookup) : undefined;
}
/** How a chain key's primary selector matches the current selector. */
type SelectorMatchKind = "exact" | "normalized" | "base" | "effort" | "none";
/**
* Classify how a chain key's primary selector matches the current selector.
* Comparisons use parsed model + thinking-level values, so effort aliases
* (`hi`/`med`/`min`) match their canonical forms (`high`/`medium`/`minimal`).
*
* - `exact` — same provider/model and parsed effort.
* - `normalized` — same provider/model and both efforts clamp to the same
* level supported by the active model (`max` and `high` on a high-capped
* model).
* - `base` — a suffixless key naming the same provider/model, so it applies
* to that model at any effort.
* - `effort` — same provider/model at an explicit effort that stays distinct
* after model normalization. Model-selector keys treat this as no match;
* role keys accept it as their weakest tier, since a role's chain follows
* its assigned model across runtime effort changes.
* - `none` — a different model, or no primary.
*/
function selectorMatchKind(
primary: RetryFallbackSelector | undefined,
current: RetryFallbackSelector,
currentPlain: RetryFallbackSelector | undefined,
currentModel: Model | null | undefined,
): SelectorMatchKind {
if (!primary) return "none";
const provider = primary.provider;
const id = primary.id;
const level = primary.thinkingLevel;
let matchedCurrent: RetryFallbackSelector | undefined;
if (provider === current.provider && id === current.id) {
matchedCurrent = current;
} else if (currentPlain !== undefined && provider === currentPlain.provider && id === currentPlain.id) {
matchedCurrent = currentPlain;
}
if (!matchedCurrent) return "none";
if (level === matchedCurrent.thinkingLevel) return "exact";
if (level === undefined) return "base";
if (
currentModel &&
resolveThinkingLevelForModel(currentModel, level) ===
resolveThinkingLevelForModel(currentModel, matchedCurrent.thinkingLevel)
) {
return "normalized";
}
return "effort";
}
/**
* Resolve the chain key for a concrete selector by specificity: exact model,
* longest matching wildcard, hinted role, then matching role keys with
* `default` preferred over other shared assignments, then default.
*/
export function resolveRetryFallbackChainKey(
context: RetryFallbackResolutionContext,
currentSelector: string,
currentModel?: Model | null,
roleHint?: string,
): string | undefined {
const parsedConfigured = parseRetryFallbackSelector(currentSelector, context.modelLookup);
const currentPlainSelector = currentModel
? formatModelSelectorValue(formatModelString(currentModel), parsedConfigured?.thinkingLevel)
: undefined;
const parsedCurrent =
parsedConfigured ??
(currentPlainSelector ? parseRetryFallbackSelector(currentPlainSelector, context.modelLookup) : undefined);
if (!parsedCurrent) {
if (roleHint && Array.isArray(context.chains[roleHint])) return roleHint;
return undefined;
}
const parsedPlainCurrent =
currentPlainSelector && currentPlainSelector !== currentSelector
? (parseRetryFallbackSelector(currentPlainSelector, context.modelLookup) ?? parsedCurrent)
: undefined;
// 1. Model-selector keys — most specific. Parsed exact effort beats
// model-normalized effort, which beats a suffixless (any-effort) key,
// regardless of object/YAML order. Efforts that remain distinct after
// normalization never match.
let normalizedModelKey: string | undefined;
let baseModelKey: string | undefined;
for (const key in context.chains) {
if (!isRetryFallbackModelKey(key) || isRetryFallbackWildcardKey(key)) continue;
const kind = selectorMatchKind(
getRetryFallbackPrimarySelector(context, key),
parsedCurrent,
parsedPlainCurrent,
currentModel,
);
if (kind === "exact") return key;
if (kind === "normalized") normalizedModelKey ??= key;
if (kind === "base") baseModelKey ??= key;
}
if (normalizedModelKey) return normalizedModelKey;
if (baseModelKey) return baseModelKey;
// 2. Provider wildcards — an id-prefixed key (`openrouter/google/*`)
// beats the plain `provider/*` key for ids under its prefix.
let wildcardMatch: string | undefined;
let wildcardPrefixLength = -1;
for (const key in context.chains) {
if (!isRetryFallbackWildcardKey(key) || !Array.isArray(context.chains[key])) continue;
const { provider, idPrefix } = parseRetryFallbackWildcard(key, provider =>
context.modelLookup.hasProvider(provider),
);
if (provider !== parsedCurrent.provider) continue;
if (idPrefix !== undefined && !parsedCurrent.id.startsWith(`${idPrefix}/`)) continue;
const prefixLength = idPrefix?.length ?? 0;
if (prefixLength > wildcardPrefixLength) {
wildcardMatch = key;
wildcardPrefixLength = prefixLength;
}
}
if (wildcardMatch) return wildcardMatch;
// 3. The hinted role, then role keys matched by their assigned model.
// A shared assignment (default and vision both the same model) must not
// let yaml insertion order steal the live role's chain. Prefer the hint,
// then `default` when it also matches. A role assigned the live model at a
// different explicit effort (spawn `effort`, `/thinking`) still owns it,
// but only after every role whose effort matches.
if (roleHint && Array.isArray(context.chains[roleHint])) return roleHint;
let matchedRole: string | undefined;
let effortRole: string | undefined;
for (const key in context.chains) {
if (isRetryFallbackModelKey(key)) continue;
const kind = selectorMatchKind(
getRetryFallbackPrimarySelector(context, key),
parsedCurrent,
parsedPlainCurrent,
currentModel,
);
if (kind === "none") continue;
if (kind === "effort") {
if (key === "default" || effortRole === undefined) effortRole = key;
continue;
}
if (key === "default") return "default";
matchedRole ??= key;
}
if (matchedRole) return matchedRole;
if (effortRole) return effortRole;
// 4. The default chain. Use it even when `default` has an explicit role
// primary that is a *different* model than the live one (#12421): a
// /model switch or a mid-chain hop onto Fable/Astra must still reach
// glm/grok/… instead of resolving no key and aborting on wait > maxDelayMs.
const defaultChain = context.chains.default;
if (Array.isArray(defaultChain) && defaultChain.length > 0) {
return "default";
}
return undefined;
}
/**
* Parse one configured chain entry. A `provider/*` entry keeps the failing
* model's id and swaps the provider (google-antigravity/x → google/x); an
* id-prefixed `provider/prefix/*` entry re-prefixes the failing model's
* bare id instead (openrouter/google/* : google-antigravity/x →
* openrouter/google/x). Ids the target provider lacks are skipped by the
* candidate loop's registry lookup.
*/
function parseRetryFallbackChainEntry(
context: RetryFallbackResolutionContext,
entry: string,
current: RetryFallbackSelector | undefined,
): RetryFallbackSelector | undefined {
if (!isRetryFallbackWildcardKey(entry)) return parseRetryFallbackSelector(entry, context.modelLookup);
if (!current) return undefined;
const { provider, idPrefix } = parseRetryFallbackWildcard(entry, candidate =>
context.modelLookup.hasProvider(candidate),
);
const bareId = current.id.slice(current.id.lastIndexOf("/") + 1);
let id: string;
if (idPrefix !== undefined) {
id = `${idPrefix}/${bareId}`;
} else if (
bareId !== current.id &&
!context.modelLookup.find(provider, current.id) &&
context.modelLookup.find(provider, bareId)
) {
// Aggregator → direct: the failing id carries a vendor prefix the
// target provider does not use (openrouter/google/x → google-vertex/x).
id = bareId;
} else {
id = current.id;
}
return { raw: `${provider}/${id}`, provider, id, thinkingLevel: undefined };
}
/** Builds a fallback chain beginning with its effective primary selector. */
function getRetryFallbackEffectiveChain(
context: RetryFallbackResolutionContext,
chainKey: string,
currentSelector: string,
currentModel: Model | null | undefined,
allowMissingPrimary: boolean,
): RetryFallbackSelector[] {
const parsedConfigured = parseRetryFallbackSelector(currentSelector, context.modelLookup);
const parsedCurrent =
parsedConfigured ??
(currentModel
? parseRetryFallbackSelector(
formatModelSelectorValue(formatModelString(currentModel), undefined),
context.modelLookup,
)
: undefined);
const seen = new Set<string>();
const chain: RetryFallbackSelector[] = [];
if (isRetryFallbackWildcardKey(chainKey)) {
// A wildcard key has no fixed primary: the active model is the
// primary, followed by the configured provider-level fallbacks.
if (parsedCurrent) {
chain.push(parsedCurrent);
seen.add(parsedCurrent.raw);
}
} else {
const primarySelector = getRetryFallbackPrimarySelector(context, chainKey);
if (primarySelector) {
chain.push(primarySelector);
seen.add(primarySelector.raw);
} else if ((chainKey === "default" || allowMissingPrimary) && parsedCurrent) {
chain.push(parsedCurrent);
seen.add(parsedCurrent.raw);
} else if (!allowMissingPrimary) {
return [];
}
}
for (const selector of context.chains[chainKey] ?? []) {
const parsed = parseRetryFallbackChainEntry(context, selector, parsedCurrent);
if (!parsed || seen.has(parsed.raw)) continue;
seen.add(parsed.raw);
chain.push(parsed);
}
return chain;
}
/**
* Return candidates after the current selector in an effective chain.
* `wrapAround` additionally appends entries before the current selector,
* without returning the current selector itself.
*/
export function findRetryFallbackCandidates(
context: RetryFallbackResolutionContext,
chainKey: string,
currentSelector: string,
currentModel?: Model | null,
options?: { allowMissingPrimary?: boolean; wrapAround?: boolean },
): RetryFallbackSelector[] {
const chain = getRetryFallbackEffectiveChain(
context,
chainKey,
currentSelector,
currentModel,
options?.allowMissingPrimary === true,
);
const parsedConfigured = parseRetryFallbackSelector(currentSelector, context.modelLookup);
const currentPlainSelector = currentModel
? formatModelSelectorValue(formatModelString(currentModel), parsedConfigured?.thinkingLevel)
: undefined;
const parsedCurrent =
parsedConfigured ??
(currentPlainSelector ? parseRetryFallbackSelector(currentPlainSelector, context.modelLookup) : undefined);
if (!parsedCurrent) return chain;
if (chain.length <= 1) return [];
const currentBaseSelector = formatRetryFallbackBaseSelector(parsedCurrent);
const currentPlainBaseSelector =
parsedCurrent && currentPlainSelector && currentPlainSelector !== currentSelector
? formatRetryFallbackBaseSelector(parseRetryFallbackSelector(currentPlainSelector) ?? parsedCurrent)
: undefined;
const exactIndex = chain.findIndex(
selector => selector.raw === currentSelector || selector.raw === currentPlainSelector,
);
if (exactIndex >= 0) {
const candidatesAfter = chain.slice(exactIndex + 1);
return options?.wrapAround ? [...candidatesAfter, ...chain.slice(0, exactIndex)] : candidatesAfter;
}
const baseIndex = currentBaseSelector
? chain.findIndex(selector => {
const selectorBase = formatRetryFallbackBaseSelector(selector);
return selectorBase === currentBaseSelector || selectorBase === currentPlainBaseSelector;
})
: -1;
if (baseIndex >= 0) {
const candidatesAfter = chain.slice(baseIndex + 1);
return options?.wrapAround ? [...candidatesAfter, ...chain.slice(0, baseIndex)] : candidatesAfter;
}
return chain;
}