@mastra/code-sdk 1.21.0-alpha.9 → 1.22.0-alpha.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.
@@ -4,7 +4,10 @@ import type { GatewayLanguageModel, IdentifiedModelConfig, MastraModelGatewayInt
4
4
  import { RequestContext } from '@mastra/core/request-context';
5
5
  import type { RequestContextReader } from '../auth/account-routing-context.js';
6
6
  import type { CredentialStore } from '../auth/types.js';
7
+ import { MODEL_FALLBACK_STATE_KEY } from '../model-fallback.js';
8
+ import type { ModelFallback } from '../model-fallback.js';
7
9
  import type { AnthropicPromptCacheScope } from '../providers/anthropic-prompt-cache.js';
10
+ import type { ModelRouteEntry } from '../schema.js';
8
11
  import type { ThinkingLevelSetting } from '../thinking.js';
9
12
  import { MastraCodeGateway } from './mastracode-gateway.js';
10
13
  import type { MastraCodeGatewayOptions } from './mastracode-gateway.js';
@@ -95,6 +98,22 @@ export interface ThinkingRequestContext {
95
98
  * (rule-driven) Factory runs that nobody ever opens interactively.
96
99
  */
97
100
  export declare function resolveRequestThinkingLevel(agentControllerContext: ThinkingRequestContext | undefined, settingsPath?: string, hostDefault?: ThinkingLevelSetting): ThinkingLevelSetting;
101
+ export declare function setHostModelRoute(requestContext: RequestContext, route: readonly ModelFallback[] | undefined): void;
102
+ export declare function advanceHostModelRoute(requestContext: RequestContext): void;
103
+ export declare function requestRouteHasNextModel(requestContext: RequestContextReader | undefined, controller: Parameters<typeof requestModelRoute>[1]): boolean;
104
+ interface RequestModelRoute {
105
+ entries: ModelRouteEntry[];
106
+ host: boolean;
107
+ modelId: string | undefined;
108
+ thinkingLevel: ThinkingLevelSetting | undefined;
109
+ }
110
+ export declare function requestModelRoute(requestContext: RequestContextReader | undefined, controller: {
111
+ getState?: () => Record<string, unknown> | undefined;
112
+ threadId?: unknown;
113
+ session?: {
114
+ modelId?: unknown;
115
+ };
116
+ } | undefined): RequestModelRoute;
98
117
  /**
99
118
  * Dynamic model function that reads the current model and optional ordered
100
119
  * fallback route from controller state. Route entry ids are opaque host-owned
@@ -107,31 +126,14 @@ export declare function getDynamicModel({ requestContext }: {
107
126
  modeless?: boolean;
108
127
  defaultThinkingLevel?: ThinkingLevelSetting;
109
128
  }): IdentifiedModelConfig | ModelWithRetries[];
110
- type MemoryRouteState = {
111
- modelRoute?: {
112
- entries?: Array<{
113
- id?: unknown;
114
- memoryModelId?: unknown;
115
- }>;
116
- };
117
- mastracodePendingModelFallback?: {
118
- toEntryId?: unknown;
119
- threadId?: unknown;
120
- } | null;
121
- };
122
129
  /**
123
130
  * The active model route for memory: the session route, starting at a pending
124
131
  * fallback hop captured for this thread.
125
132
  */
126
- export declare function getActiveMemoryRoute<TEntry extends {
127
- id?: unknown;
128
- memoryModelId?: unknown;
129
- }>(state: {
130
- modelRoute?: {
131
- entries?: TEntry[];
132
- };
133
- mastracodePendingModelFallback?: MemoryRouteState['mastracodePendingModelFallback'];
134
- } | undefined, threadId?: string | null): TEntry[];
133
+ export declare function getActiveMemoryRoute(state: {
134
+ modelRoute?: unknown;
135
+ [MODEL_FALLBACK_STATE_KEY]?: unknown;
136
+ } | undefined, threadId?: string | null): ModelRouteEntry[];
135
137
  /**
136
138
  * The memory model the active route applies to both OM roles: `'auto'`, the
137
139
  * first concrete memory model, or `undefined` when the route sets none (both
@@ -1,6 +1,7 @@
1
1
  import { getRequestAccountSelection, isRequestAccountRoutingExhausted } from "../auth/account-routing-context.js";
2
2
  import { ProviderAuthRequiredError } from "../auth/provider-auth-error.js";
3
3
  import "../constants.js";
4
+ import { MODEL_FALLBACK_STATE_KEY, parsePendingModelFallback } from "../model-fallback.js";
4
5
  import { toMemoryModelId } from "../onboarding/packs.js";
5
6
  import { getCustomProviderId, loadSettings, resolveDefaultThinkingLevel, stripMastraCodeCustomProviderPrefix } from "../onboarding/settings.js";
6
7
  import { AMAZON_BEDROCK_GATEWAY_ID, createAmazonBedrockGateway } from "../providers/amazon-bedrock-gateway.js";
@@ -279,6 +280,87 @@ function resolveRequestThinkingLevel(agentControllerContext, settingsPath, hostD
279
280
  const modeId = agentControllerContext?.session?.modeId;
280
281
  return resolveDefaultThinkingLevel(loadSettings(settingsPath), modeId).level;
281
282
  }
283
+ const HOST_MODEL_ROUTE_CONTEXT_KEY = "mastracodeHostModelRoute";
284
+ const HOST_MODEL_ROUTE_POSITION_CONTEXT_KEY = "mastracodeHostModelRoutePosition";
285
+ function setHostModelRoute(requestContext, route) {
286
+ requestContext.delete(HOST_MODEL_ROUTE_POSITION_CONTEXT_KEY);
287
+ if (!route) {
288
+ requestContext.delete(HOST_MODEL_ROUTE_CONTEXT_KEY);
289
+ return;
290
+ }
291
+ const [primary, ...fallbacks] = route;
292
+ const entries = primary ? [primary, ...modelFallbacksToTry(primary.modelId, fallbacks, requestContext)] : [];
293
+ requestContext.set(HOST_MODEL_ROUTE_CONTEXT_KEY, entries.map(hostRouteEntry));
294
+ }
295
+ function advanceHostModelRoute(requestContext) {
296
+ requestContext.set(HOST_MODEL_ROUTE_POSITION_CONTEXT_KEY, hostModelRoutePosition(requestContext) + 1);
297
+ }
298
+ function hostModelRoutePosition(requestContext) {
299
+ const position = requestContext?.get(HOST_MODEL_ROUTE_POSITION_CONTEXT_KEY);
300
+ return typeof position === "number" ? position : 0;
301
+ }
302
+ function requestRouteHasNextModel(requestContext, controller) {
303
+ const route = requestModelRoute(requestContext, controller);
304
+ const position = route.host ? hostModelRoutePosition(requestContext) : 0;
305
+ return route.entries.length - 1 > position;
306
+ }
307
+ function modelFallbacksToTry(primaryModelId, fallbacks, requestContext) {
308
+ const usable = [];
309
+ const seen = /* @__PURE__ */ new Set([primaryModelId]);
310
+ for (const fallback of fallbacks) {
311
+ if (seen.has(fallback.modelId)) continue;
312
+ seen.add(fallback.modelId);
313
+ if (canAuthenticateModel(fallback.modelId, requestContext)) usable.push(fallback);
314
+ }
315
+ return usable;
316
+ }
317
+ function hostRouteEntry({ modelId, thinkingLevel }) {
318
+ return {
319
+ id: modelId,
320
+ label: modelId,
321
+ modelId,
322
+ ...thinkingLevel ? { thinkingLevel } : {}
323
+ };
324
+ }
325
+ function requestModelRoute(requestContext, controller) {
326
+ const sessionModelId = typeof controller?.session?.modelId === "string" ? controller.session.modelId : void 0;
327
+ const hostRoute = requestContext?.get(HOST_MODEL_ROUTE_CONTEXT_KEY);
328
+ if (hostRoute) return {
329
+ entries: hostRoute,
330
+ host: true,
331
+ modelId: hostRoute[0]?.modelId ?? sessionModelId,
332
+ thinkingLevel: hostRoute[0]?.thinkingLevel
333
+ };
334
+ const { entries, pending, pendingIndex } = sessionModelRoute(controller?.getState?.(), controller?.threadId);
335
+ const modelId = pending?.toModelId ?? sessionModelId;
336
+ const startIndex = pending ? pendingIndex : findRouteModelIndex(entries, modelId);
337
+ const active = startIndex < 0 ? [] : entries.slice(startIndex);
338
+ return {
339
+ entries: findRouteModelIndex(active, modelId) === 0 ? active : [],
340
+ host: false,
341
+ modelId,
342
+ thinkingLevel: void 0
343
+ };
344
+ }
345
+ function sessionModelRoute(state, threadId) {
346
+ const route = (state?.modelRoute)?.entries;
347
+ const entries = Array.isArray(route) ? route.slice(0, 32) : [];
348
+ const pending = parsePendingModelFallback(state?.[MODEL_FALLBACK_STATE_KEY]);
349
+ const threadPending = pending && (pending.threadId === void 0 || pending.threadId === threadId) ? pending : null;
350
+ return {
351
+ entries,
352
+ pending: threadPending,
353
+ pendingIndex: threadPending ? entries.findIndex((entry) => entry.id === threadPending.toEntryId) : -1
354
+ };
355
+ }
356
+ function canAuthenticateModel(modelId, requestContext) {
357
+ try {
358
+ resolveModelForRequest(modelId, { requestContext });
359
+ return true;
360
+ } catch {
361
+ return false;
362
+ }
363
+ }
282
364
  /**
283
365
  * Dynamic model function that reads the current model and optional ordered
284
366
  * fallback route from controller state. Route entry ids are opaque host-owned
@@ -287,25 +369,22 @@ function resolveRequestThinkingLevel(agentControllerContext, settingsPath, hostD
287
369
  */
288
370
  function getDynamicModel({ requestContext }, settingsPath, { modeless = false, defaultThinkingLevel } = {}) {
289
371
  const controller = requestContext.get("controller");
290
- const state = controller?.getState?.();
291
- const pendingState = state?.mastracodePendingModelFallback;
292
- const pendingFallback = pendingState && (pendingState.threadId === void 0 || typeof pendingState.threadId === "string" && pendingState.threadId === controller?.threadId) ? pendingState : void 0;
293
- const modelId = (pendingFallback && typeof pendingFallback.toModelId === "string" && pendingFallback.toModelId.length > 0 ? pendingFallback.toModelId : void 0) ?? controller?.session?.modelId;
372
+ const { entries: activeRoute, modelId, thinkingLevel: primaryThinkingLevel } = requestModelRoute(requestContext, controller);
294
373
  if (!modelId) {
295
374
  if (!controller) throw new Error("No model available: this run started without a controller session context, so no model selection could be resolved.");
296
375
  throw new Error("No model selected. Use /models to select a model first.");
297
376
  }
377
+ const thinkingLevel = resolveRequestThinkingLevel(modeless ? { state: controller?.state } : controller, settingsPath, defaultThinkingLevel);
298
378
  const resolveOptions = {
299
- thinkingLevel: resolveRequestThinkingLevel(modeless ? { state: controller?.state } : controller, settingsPath, defaultThinkingLevel),
379
+ thinkingLevel,
300
380
  remapForCodexOAuth: true,
301
381
  requestContext
302
382
  };
303
- const primary = identifyModel(modelId, resolveModel(modelId, resolveOptions));
304
- const route = state?.modelRoute?.entries?.slice(0, 32);
305
- const pendingEntryId = pendingFallback && typeof pendingFallback.toEntryId === "string" ? pendingFallback.toEntryId : void 0;
306
- const startIndex = pendingEntryId ? route?.findIndex((entry) => entry.id === pendingEntryId) : 0;
307
- const activeRoute = route && startIndex !== void 0 && startIndex >= 0 ? route.slice(startIndex) : void 0;
308
- if (!activeRoute || activeRoute.length < 2 || findRouteModelIndex(activeRoute, modelId) !== 0) return primary;
383
+ const primary = identifyModel(modelId, resolveModel(modelId, {
384
+ ...resolveOptions,
385
+ thinkingLevel: primaryThinkingLevel ?? thinkingLevel
386
+ }));
387
+ if (activeRoute.length < 2) return primary;
309
388
  const firstId = typeof activeRoute[0]?.id === "string" && activeRoute[0].id.length > 0 ? activeRoute[0].id : void 0;
310
389
  if (!firstId) return primary;
311
390
  const entries = [{
@@ -317,7 +396,10 @@ function getDynamicModel({ requestContext }, settingsPath, { modeless = false, d
317
396
  if (typeof routeEntry.id !== "string" || routeEntry.id.length === 0 || typeof routeEntry.modelId !== "string" || routeEntry.modelId.length === 0) break;
318
397
  let entryModel;
319
398
  try {
320
- entryModel = resolveModel(routeEntry.modelId, resolveOptions);
399
+ entryModel = resolveModel(routeEntry.modelId, {
400
+ ...resolveOptions,
401
+ thinkingLevel: routeEntry.thinkingLevel ?? thinkingLevel
402
+ });
321
403
  } catch {
322
404
  break;
323
405
  }
@@ -341,11 +423,8 @@ function identifyModel(modelId, model) {
341
423
  * fallback hop captured for this thread.
342
424
  */
343
425
  function getActiveMemoryRoute(state, threadId) {
344
- const pending = state?.mastracodePendingModelFallback;
345
- const sameThreadPending = pending && (pending.threadId === void 0 || pending.threadId === threadId) ? pending : void 0;
346
- const routeEntries = state?.modelRoute?.entries?.slice(0, 32) ?? [];
347
- const pendingIndex = sameThreadPending ? routeEntries.findIndex((entry) => entry.id === sameThreadPending.toEntryId) : -1;
348
- return pendingIndex >= 0 ? routeEntries.slice(pendingIndex) : routeEntries;
426
+ const { entries, pendingIndex } = sessionModelRoute(state, threadId);
427
+ return pendingIndex >= 0 ? entries.slice(pendingIndex) : entries;
349
428
  }
350
429
  /**
351
430
  * The memory model the active route applies to both OM roles: `'auto'`, the
@@ -379,4 +458,4 @@ function getGoalJudgeModel({ requestContext }, settingsPath) {
379
458
  requestContext
380
459
  });
381
460
  }
382
- export { MASTRACODE_GATEWAY_ID, MastraCodeGateway, canUseProvider, createMastraCodeGateway, createMastraCodeModelCatalogProvider, createRequestScopedCredentialStore, getActiveMemoryRoute, getActiveRouteMemoryModelId, getAnthropicApiKey, getDynamicModel, getGoalJudgeModel, getOpenAIApiKey, hasCredentialStoreProvider, hasCustomProvidersSource, prepareProviderWebSearchRoute, remapOpenAIModelForCodexOAuth, resolveAuth, resolveCustomProviders, resolveModel, resolveModelId, resolveProviderWebSearchRoute, resolveRequestThinkingLevel, resolveTenantFromRequestContext, setCredentialStoreProvider, setCustomProvidersSource };
461
+ export { MASTRACODE_GATEWAY_ID, MastraCodeGateway, advanceHostModelRoute, canUseProvider, createMastraCodeGateway, createMastraCodeModelCatalogProvider, createRequestScopedCredentialStore, getActiveMemoryRoute, getActiveRouteMemoryModelId, getAnthropicApiKey, getDynamicModel, getGoalJudgeModel, getOpenAIApiKey, hasCredentialStoreProvider, hasCustomProvidersSource, prepareProviderWebSearchRoute, remapOpenAIModelForCodexOAuth, requestModelRoute, requestRouteHasNextModel, resolveAuth, resolveCustomProviders, resolveModel, resolveModelId, resolveProviderWebSearchRoute, resolveRequestThinkingLevel, resolveTenantFromRequestContext, setCredentialStoreProvider, setCustomProvidersSource, setHostModelRoute };
@@ -1,7 +1,22 @@
1
- import type { ProcessAPIErrorArgs, ProcessInputArgs, ProcessInputResult, Processor } from '@mastra/core/processors';
1
+ import type { ProcessAPIErrorArgs, ProcessAPIErrorResult, ProcessInputArgs, ProcessInputResult, Processor } from '@mastra/core/processors';
2
2
  import type { RequestContext } from '@mastra/core/request-context';
3
+ import type { ModelFallbackReason } from '../model-fallback.js';
3
4
  import type { ThinkingLevelSetting } from '../thinking.js';
4
5
  import type { CredentialStore } from './types.js';
6
+ export {
7
+ /** @deprecated Import from `@mastra/code-sdk/model-fallback`. */
8
+ MODEL_FALLBACK_PART_TYPE,
9
+ /** @deprecated Import from `@mastra/code-sdk/model-fallback`. */
10
+ MODEL_FALLBACK_STATE_KEY,
11
+ /** @deprecated Import from `@mastra/code-sdk/model-fallback`. */
12
+ modelFallbackNoticeText, } from '../model-fallback.js';
13
+ export type {
14
+ /** @deprecated Import from `@mastra/code-sdk/model-fallback`. */
15
+ ModelFallbackPartData,
16
+ /** @deprecated Import from `@mastra/code-sdk/model-fallback`. */
17
+ PendingModelFallback, } from '../model-fallback.js';
18
+ /** @deprecated Parse the whole part with `parseModelFallbackPart` from `@mastra/code-sdk/model-fallback`. */
19
+ export declare function isModelFallbackReason(value: unknown): value is ModelFallbackReason;
5
20
  export declare const ACCOUNT_SWITCH_PART_TYPE = "data-mastracode-account-switch";
6
21
  /** Labels and instance ids only — never token material (do-not list). */
7
22
  export interface AccountSwitchPartData {
@@ -14,7 +29,7 @@ export interface AccountSwitchPartData {
14
29
  id: string;
15
30
  label: string;
16
31
  } | null;
17
- reason: 'rate-limit' | 'quota-exhausted' | 'auth-failed' | 'pool-exhausted' | 'persistent-outage' | 'preferred-routing';
32
+ reason: 'rate-limit' | 'quota-exhausted' | 'auth-failed' | ModelFallbackReason | 'preferred-routing';
18
33
  at: string;
19
34
  /**
20
35
  * Set on a `to: null` part when a route pinned to a single account reported
@@ -34,32 +49,6 @@ export type RotationCredentialStore = CredentialStore & {
34
49
  */
35
50
  forceRefreshActiveAccount?(providerId: string, accountInstanceId?: string): Promise<string | undefined>;
36
51
  };
37
- /** Persisted data-part type for a model-route hop. */
38
- export declare const MODEL_FALLBACK_PART_TYPE: 'data-mastracode-model-fallback';
39
- /** Non-secret transcript payload for a model-route hop. */
40
- export interface ModelFallbackPartData {
41
- from: {
42
- entryId: string;
43
- label: string;
44
- };
45
- to: {
46
- entryId: string;
47
- label: string;
48
- };
49
- reason: 'pool-exhausted' | 'persistent-outage';
50
- at: string;
51
- }
52
- /** Session-state key set when account rotation advances the model route. */
53
- export declare const MODEL_FALLBACK_STATE_KEY: 'mastracodePendingModelFallback';
54
- /** Payload written to session state under MODEL_FALLBACK_STATE_KEY. */
55
- export interface PendingModelFallback {
56
- fromEntryId: string;
57
- toEntryId: string;
58
- toModelId: string;
59
- threadId?: string;
60
- reason: 'pool-exhausted' | 'persistent-outage';
61
- at: string;
62
- }
63
52
  export type RotationClassification = {
64
53
  kind: 'rotate';
65
54
  reason: 'rate-limit' | 'quota-exhausted' | 'auth-failed';
@@ -119,16 +108,6 @@ export declare function isAccountSwitchReason(value: unknown): value is AccountS
119
108
  * history rendering of the persisted part — one formatter, identical text.
120
109
  */
121
110
  export declare function accountSwitchNoticeText(data: AccountSwitchPartData): string;
122
- /** Transcript line for a model-route hop; shared by the live info event and the TUI's history render. */
123
- export declare function modelFallbackNoticeText(data: ModelFallbackPartData): string;
124
- /**
125
- * Whether a persisted model-fallback reason is one this build understands.
126
- * `REASON_TEXT` also covers the account-switch reasons, so the notice text
127
- * alone would happily render a foreign value such as `rate-limit` as a
128
- * model-fallback reason; history parsed from another build's part must be
129
- * rejected instead.
130
- */
131
- export declare function isModelFallbackReason(value: unknown): value is ModelFallbackPartData['reason'];
132
111
  export type RoutingControllerContext = {
133
112
  session?: {
134
113
  modelId?: unknown;
@@ -158,27 +137,14 @@ export declare class AccountRotationProcessor implements Processor {
158
137
  requestContext: RequestContext;
159
138
  }) => ThinkingLevelSetting | Promise<ThinkingLevelSetting>;
160
139
  });
161
- processAPIError(args: ProcessAPIErrorArgs): Promise<{
162
- retry: boolean;
163
- }>;
140
+ processAPIError(args: ProcessAPIErrorArgs): Promise<ProcessAPIErrorResult>;
164
141
  /**
165
142
  * Resolve the request's host-supplied model route once and cache the reachable
166
143
  * prefix in processor state. Resolution mirrors getDynamicModel so a hop is
167
144
  * never announced for an entry core cannot reach.
168
145
  */
169
146
  private getModelRouteCascade;
170
- /**
171
- * Q14 gate: 400/unknown/unattributable errors never advance routes. Core's
172
- * fallback array advances on ANY thrown error except TripWire
173
- * (llm-execution-step.ts), so when the session route has another entry and the
174
- * current entry is non-last, a bare `retry: false` would silently hop on an
175
- * error class the user excluded from hop triggers. TripWire is the only
176
- * no-advance escape: the runner rethrows it and the fallback loop declines
177
- * to advance. No chain (or already on the last entry) → return and let the
178
- * plain `retry: false` surface the error exactly as before.
179
- */
180
- private gateChainHop;
181
- /** Announce and persist the next model-route hop before core advances. */
147
+ private hopToNextModel;
182
148
  private emitModelFallbackPart;
183
149
  /**
184
150
  * Pool done for this request: every instance recorded in the tried-set and
@@ -1,11 +1,11 @@
1
1
  import { resolveCredentialStore } from "../agents/credential-resolver.js";
2
- import { resolveModel, resolveRequestThinkingLevel } from "../agents/model.js";
3
- import { findRouteModelIndex, getCredentialProviderId, normalizeLegacyModelId } from "../providers/model-ids.js";
2
+ import { advanceHostModelRoute, requestModelRoute, resolveModel, resolveRequestThinkingLevel } from "../agents/model.js";
3
+ import { MODEL_FALLBACK_PART_TYPE, MODEL_FALLBACK_STATE_KEY, modelFallbackNoticeText, pendingModelFallbackSchema } from "../model-fallback.js";
4
+ import { getCredentialProviderId, normalizeLegacyModelId } from "../providers/model-ids.js";
4
5
  import { isThinkingLevelSetting } from "../thinking.js";
5
6
  import { getRequestAccountSelection, isRequestAccountRoutingExhausted, markRequestAccountRoutingExhausted, setRequestAccountSelection } from "./account-routing-context.js";
6
7
  import { ProviderAuthRequiredError } from "./provider-auth-error.js";
7
8
  import { getOAuthProviders } from "./storage.js";
8
- import { TripWire } from "@mastra/core/agent";
9
9
  import { classifyProviderError } from "@mastra/core/error";
10
10
  // src/auth/account-rotation-processor.ts
11
11
  /**
@@ -29,6 +29,10 @@ import { classifyProviderError } from "@mastra/core/error";
29
29
  * `StreamErrorRetryProcessor`; `AccountStartNoticeProcessor` implements
30
30
  * `processInput` only and is registered in `inputProcessors`.
31
31
  */
32
+ /** @deprecated Parse the whole part with `parseModelFallbackPart` from `@mastra/code-sdk/model-fallback`. */
33
+ function isModelFallbackReason(value) {
34
+ return pendingModelFallbackSchema.shape.reason.safeParse(value).success;
35
+ }
32
36
  const ACCOUNT_SWITCH_PART_TYPE = "data-mastracode-account-switch";
33
37
  /** Rotatable providers = the OAuth provider registry; API-key-only providers never rotate. */
34
38
  const KNOWN_PROVIDER_IDS = new Set(getOAuthProviders().map((provider) => provider.id));
@@ -54,10 +58,6 @@ const NETWORK_ERROR_CODES = /* @__PURE__ */ new Set([
54
58
  ]);
55
59
  const NETWORK_MESSAGE_PATTERN = /fetch failed|network error|socket hang up|getaddrinfo|econnrefused|enotfound|etimedout|connection (?:refused|reset|closed|timed out)|other side closed|write epipe/i;
56
60
  const MAX_CAUSE_DEPTH = 4;
57
- /** Persisted data-part type for a model-route hop. */
58
- const MODEL_FALLBACK_PART_TYPE = "data-mastracode-model-fallback";
59
- /** Session-state key set when account rotation advances the model route. */
60
- const MODEL_FALLBACK_STATE_KEY = "mastracodePendingModelFallback";
61
61
  /**
62
62
  * Same-account retries for a stream the provider cut after accepting the
63
63
  * request. Each one can cost a full stream (900 s on the ChatGPT Codex route),
@@ -276,21 +276,6 @@ function accountSwitchNoticeText(data) {
276
276
  }
277
277
  return `Switched ${provider} account: ${data.from?.label ?? "unknown"} → ${data.to.label} (${reason})`;
278
278
  }
279
- /** Transcript line for a model-route hop; shared by the live info event and the TUI's history render. */
280
- function modelFallbackNoticeText(data) {
281
- const reason = REASON_TEXT[data.reason] ?? data.reason;
282
- return `Switched model route: ${data.from.label} → ${data.to.label} (${reason})`;
283
- }
284
- /**
285
- * Whether a persisted model-fallback reason is one this build understands.
286
- * `REASON_TEXT` also covers the account-switch reasons, so the notice text
287
- * alone would happily render a foreign value such as `rate-limit` as a
288
- * model-fallback reason; history parsed from another build's part must be
289
- * rejected instead.
290
- */
291
- function isModelFallbackReason(value) {
292
- return value === "pool-exhausted" || value === "persistent-outage";
293
- }
294
279
  async function emitAccountSwitchPart(args, data) {
295
280
  await args.writer?.custom({
296
281
  type: ACCOUNT_SWITCH_PART_TYPE,
@@ -308,8 +293,8 @@ async function emitAccountSwitchPart(args, data) {
308
293
  * before any HTTP request exists).
309
294
  */
310
295
  function providerFromSession(args) {
311
- const modelId = (args.requestContext?.get("controller"))?.session?.modelId;
312
- return typeof modelId === "string" ? providerFromModelId(modelId) : void 0;
296
+ const { modelId } = requestModelRoute(args.requestContext, getRoutingController(args));
297
+ return modelId ? providerFromModelId(modelId) : void 0;
313
298
  }
314
299
  function getRoutingController(args) {
315
300
  return args.requestContext?.get("controller");
@@ -325,12 +310,7 @@ function getRequestActiveAccount(args, store, providerId) {
325
310
  return store.getActiveAccount?.(providerId) ?? store.listAccounts?.(providerId).find((account) => account.active);
326
311
  }
327
312
  function resolveAccountRoute(args, explicit) {
328
- const controller = getRoutingController(args);
329
- const state = controller?.getState?.();
330
- const pending = state?.mastracodePendingModelFallback;
331
- const pendingMatchesThread = pending && typeof pending.toEntryId === "string" && typeof pending.toModelId === "string" && (pending.threadId === void 0 || pending.threadId === controller?.threadId);
332
- const routeEntries = Array.isArray((state?.modelRoute)?.entries) ? (state?.modelRoute).entries ?? [] : [];
333
- const entry = explicit ? explicit : pendingMatchesThread ? routeEntries.find((candidate) => candidate.id === pending.toEntryId && candidate.modelId === pending.toModelId) : routeEntries[findRouteModelIndex(routeEntries, controller?.session?.modelId)];
313
+ const entry = explicit ?? requestModelRoute(args.requestContext, getRoutingController(args)).entries[0];
334
314
  if (!entry || typeof entry.id !== "string" || typeof entry.modelId !== "string") return null;
335
315
  const providerId = providerFromModelId(entry.modelId);
336
316
  if (!providerId) return null;
@@ -401,22 +381,13 @@ var AccountRotationProcessor = class {
401
381
  }
402
382
  async processAPIError(args) {
403
383
  const { error, state } = args;
404
- if (args.retryCount >= this.options.maxProcessorRetries) {
405
- await this.gateChainHop(args, error);
406
- return { retry: false };
407
- }
384
+ if (args.retryCount >= this.options.maxProcessorRetries) return this.hopToNextModel(args);
408
385
  const classification = classifyRotationError(error);
409
- if (classification.kind === "never") {
410
- await this.gateChainHop(args, error);
411
- return { retry: false };
412
- }
386
+ if (classification.kind === "never") return this.hopToNextModel(args);
413
387
  if (classification.kind === "stream-cut") {
414
388
  const budget = state.streamCutRetries;
415
389
  const cuts = budget?.step === args.stepNumber ? budget.count : 0;
416
- if (cuts >= 2) {
417
- await this.gateChainHop(args, error);
418
- return { retry: false };
419
- }
390
+ if (cuts >= 2) return this.hopToNextModel(args);
420
391
  state.streamCutRetries = {
421
392
  step: args.stepNumber,
422
393
  count: cuts + 1
@@ -485,10 +456,8 @@ var AccountRotationProcessor = class {
485
456
  if (args.state.modelRouteCascade !== void 0) return args.state.modelRouteCascade ?? null;
486
457
  const controller = getRoutingController(args);
487
458
  const state = controller?.getState?.();
488
- const route = (state?.modelRoute)?.entries;
489
- const pending = state?.mastracodePendingModelFallback;
490
- const startIndex = pending && typeof pending.toEntryId === "string" && (pending.threadId === void 0 || pending.threadId === controller?.threadId) ? route?.findIndex((entry) => entry.id === pending.toEntryId) : route && findRouteModelIndex(route, controller?.session?.modelId);
491
- if (!route || startIndex === void 0 || startIndex < 0 || route.length - startIndex < 2) {
459
+ const { entries: route } = requestModelRoute(args.requestContext, controller);
460
+ if (route.length < 2) {
492
461
  args.state.modelRouteCascade = null;
493
462
  return null;
494
463
  }
@@ -497,7 +466,7 @@ var AccountRotationProcessor = class {
497
466
  ...!this.options.modeless && { session: { modeId: typeof controller?.session?.modeId === "string" ? controller.session.modeId : "build" } }
498
467
  }, this.options.settingsPath, args.requestContext && !isThinkingLevelSetting(state?.thinkingLevel) ? await this.options.resolveDefaultThinkingLevel?.({ requestContext: args.requestContext }) : void 0);
499
468
  const entries = [];
500
- for (const entry of route.slice(startIndex)) {
469
+ for (const entry of route) {
501
470
  if (typeof entry.id !== "string" || entry.id.length === 0 || typeof entry.modelId !== "string" || entry.modelId.length === 0) break;
502
471
  if (entries.length > 0) try {
503
472
  resolveModel(entry.modelId, {
@@ -526,24 +495,10 @@ var AccountRotationProcessor = class {
526
495
  args.state.modelRouteCascade = cascade;
527
496
  return cascade;
528
497
  }
529
- /**
530
- * Q14 gate: 400/unknown/unattributable errors never advance routes. Core's
531
- * fallback array advances on ANY thrown error except TripWire
532
- * (llm-execution-step.ts), so when the session route has another entry and the
533
- * current entry is non-last, a bare `retry: false` would silently hop on an
534
- * error class the user excluded from hop triggers. TripWire is the only
535
- * no-advance escape: the runner rethrows it and the fallback loop declines
536
- * to advance. No chain (or already on the last entry) → return and let the
537
- * plain `retry: false` surface the error exactly as before.
538
- */
539
- async gateChainHop(args, error) {
540
- const cascade = await this.getModelRouteCascade(args);
541
- if (!cascade) return;
542
- if (cascade.position >= cascade.entries.length - 1) return;
543
- const reason = error instanceof Error ? error.message : String(error);
544
- throw new TripWire(reason, {}, this.id);
498
+ async hopToNextModel(args) {
499
+ await this.emitModelFallbackPart(args, "pool-exhausted");
500
+ return { retry: false };
545
501
  }
546
- /** Announce and persist the next model-route hop before core advances. */
547
502
  async emitModelFallbackPart(args, reason) {
548
503
  const cascade = await this.getModelRouteCascade(args);
549
504
  if (!cascade) return;
@@ -552,6 +507,7 @@ var AccountRotationProcessor = class {
552
507
  if (!from || !to) return;
553
508
  const controller = args.requestContext?.get("controller");
554
509
  const at = (/* @__PURE__ */ new Date()).toISOString();
510
+ const failure = { kind: isProviderAuthRequiredError(args.error) ? "auth" : classifyProviderError(args.error) };
555
511
  const threadId = typeof controller?.threadId === "string" ? controller.threadId : void 0;
556
512
  const pending = {
557
513
  fromEntryId: from.id,
@@ -561,7 +517,8 @@ var AccountRotationProcessor = class {
561
517
  reason,
562
518
  at
563
519
  };
564
- await controller?.setThreadSetting?.({
520
+ const sticky = !requestModelRoute(args.requestContext, getRoutingController(args)).host;
521
+ if (sticky) await controller?.setThreadSetting?.({
565
522
  key: MODEL_FALLBACK_STATE_KEY,
566
523
  value: pending
567
524
  });
@@ -575,7 +532,8 @@ var AccountRotationProcessor = class {
575
532
  label: to.label
576
533
  },
577
534
  reason,
578
- at
535
+ at,
536
+ failure
579
537
  };
580
538
  try {
581
539
  await args.writer?.custom({
@@ -583,21 +541,22 @@ var AccountRotationProcessor = class {
583
541
  data
584
542
  });
585
543
  } catch (error) {
586
- await controller?.setThreadSetting?.({
544
+ if (sticky) await controller?.setThreadSetting?.({
587
545
  key: MODEL_FALLBACK_STATE_KEY,
588
546
  value: void 0
589
547
  });
590
548
  throw error;
591
549
  }
592
- await controller?.setState?.({ [MODEL_FALLBACK_STATE_KEY]: pending });
550
+ if (sticky) await controller?.setState?.({ [MODEL_FALLBACK_STATE_KEY]: pending });
593
551
  args.state.startNoticeEmitted = false;
594
552
  const targetRoute = resolveAccountRoute(args, to);
595
553
  if (targetRoute) await applyPreferredAccountRoute(args, resolveCredentialStore(args.requestContext) ?? this.options.credentialStore, targetRoute).catch(() => void 0);
596
- controller?.emitEvent?.({
554
+ if (sticky) controller?.emitEvent?.({
597
555
  type: "info",
598
556
  message: modelFallbackNoticeText(data)
599
557
  });
600
558
  cascade.position++;
559
+ if (!sticky && args.requestContext) advanceHostModelRoute(args.requestContext);
601
560
  }
602
561
  /**
603
562
  * Pool done for this request: every instance recorded in the tried-set and
@@ -1,9 +1,10 @@
1
1
  import { PROVIDER_AUTH_REQUIRED_ERROR, ProviderAuthRequiredError, rejectUnauthorizedResponse } from "./provider-auth-error.js";
2
2
  import { AuthStorage, PROVIDER_DEFAULT_MODELS, getOAuthProvider, getOAuthProviders } from "./storage.js";
3
- import { ACCOUNT_SWITCH_PART_TYPE, AccountRotationProcessor, AccountStartNoticeProcessor, MAX_STREAM_CUT_RETRIES, MODEL_FALLBACK_PART_TYPE, MODEL_FALLBACK_STATE_KEY, PROVIDER_DISPLAY_NAMES, accountSwitchNoticeText, classifyRotationError, isAccountSwitchReason, isModelFallbackReason, isStreamCutAfterResponse, modelFallbackNoticeText, providerFromError, providerFromModelId } from "./account-rotation-processor.js";
3
+ import { ACCOUNT_SWITCH_PART_TYPE, AccountRotationProcessor, AccountStartNoticeProcessor, MAX_STREAM_CUT_RETRIES, PROVIDER_DISPLAY_NAMES, accountSwitchNoticeText, classifyRotationError, isAccountSwitchReason, isModelFallbackReason, isStreamCutAfterResponse, providerFromError, providerFromModelId } from "./account-rotation-processor.js";
4
4
  import { anthropicOAuthProvider } from "./providers/anthropic.js";
5
5
  import { githubCopilotOAuthProvider } from "./providers/github-copilot.js";
6
6
  import { kimiCodingOAuthProvider } from "./providers/kimi-coding.js";
7
7
  import { openaiCodexOAuthProvider } from "./providers/openai-codex.js";
8
+ import { MODEL_FALLBACK_PART_TYPE, MODEL_FALLBACK_STATE_KEY, modelFallbackNoticeText } from "../model-fallback.js";
8
9
  import { xaiOAuthProvider } from "./providers/xai.js";
9
10
  export { ACCOUNT_SWITCH_PART_TYPE, AccountRotationProcessor, AccountStartNoticeProcessor, AuthStorage, MAX_STREAM_CUT_RETRIES, MODEL_FALLBACK_PART_TYPE, MODEL_FALLBACK_STATE_KEY, PROVIDER_AUTH_REQUIRED_ERROR, PROVIDER_DEFAULT_MODELS, PROVIDER_DISPLAY_NAMES, ProviderAuthRequiredError, accountSwitchNoticeText, anthropicOAuthProvider, classifyRotationError, getOAuthProvider, getOAuthProviders, githubCopilotOAuthProvider, isAccountSwitchReason, isModelFallbackReason, isStreamCutAfterResponse, kimiCodingOAuthProvider, modelFallbackNoticeText, openaiCodexOAuthProvider, providerFromError, providerFromModelId, rejectUnauthorizedResponse, xaiOAuthProvider };
@@ -1,6 +1,6 @@
1
- import { MODEL_FALLBACK_STATE_KEY } from "../auth/account-rotation-processor.js";
2
1
  import { GoalManager } from "../goal-manager.js";
3
2
  import { createGoalReminderSignal } from "../goal-signal.js";
3
+ import { MODEL_FALLBACK_STATE_KEY } from "../model-fallback.js";
4
4
  import { THREAD_ACTIVE_MODEL_PACK_ID_KEY } from "../onboarding/settings.js";
5
5
  import { parseCodexModelSelection } from "../providers/model-ids.js";
6
6
  import { autoApprovePolicy } from "./policy.js";
package/dist/index.d.ts CHANGED
@@ -19,6 +19,7 @@ import type { PostToolObserver, ToolLike } from './agents/tools.js';
19
19
  import { AuthStorage } from './auth/storage.js';
20
20
  import { HookManager } from './hooks/index.js';
21
21
  import type { McpServerConfig } from './mcp/index.js';
22
+ import type { ModelFallback } from './model-fallback.js';
22
23
  import { loadSettings } from './onboarding/settings.js';
23
24
  import { PluginManager } from './plugins/manager.js';
24
25
  import { ThreadScheduler } from './schedules/index.js';
@@ -136,6 +137,10 @@ export interface MastraCodeConfig {
136
137
  resolveDefaultThinkingLevel?: (ctx: {
137
138
  requestContext: RequestContext;
138
139
  }) => ThinkingLevelSetting | Promise<ThinkingLevelSetting>;
140
+ /** Host-owned model route for the current request, called on every model resolution. */
141
+ resolveModelRoute?: (ctx: {
142
+ requestContext: RequestContext;
143
+ }) => readonly ModelFallback[] | Promise<readonly ModelFallback[]>;
139
144
  /** Create a thread during local boot when no existing thread matches. Default: true */
140
145
  createInitialThread?: boolean;
141
146
  /** Trusted host instructions resolved outside mutable session state. */