@mastra/code-sdk 1.21.0 → 1.22.0-alpha.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agents/custom-provider-check.d.ts +98 -0
- package/dist/agents/custom-provider-check.js +700 -0
- package/dist/agents/mastracode-gateway.d.ts +9 -0
- package/dist/agents/mastracode-gateway.js +18 -15
- package/dist/agents/model.d.ts +23 -21
- package/dist/agents/model.js +97 -18
- package/dist/auth/account-rotation-processor.d.ts +19 -53
- package/dist/auth/account-rotation-processor.js +28 -69
- package/dist/auth/index.js +2 -1
- package/dist/headless/run-mc.js +1 -1
- package/dist/index.d.ts +5 -0
- package/dist/index.js +10 -7
- package/dist/model-fallback.d.ts +75 -0
- package/dist/model-fallback.js +48 -0
- package/dist/onboarding/custom-provider-headers.d.ts +50 -0
- package/dist/onboarding/custom-provider-headers.js +112 -0
- package/dist/onboarding/custom-providers.js +11 -0
- package/dist/onboarding/settings.d.ts +13 -0
- package/dist/onboarding/settings.js +27 -0
- package/dist/processors/route-aware-stream-error-retry.d.ts +6 -0
- package/dist/processors/route-aware-stream-error-retry.js +15 -0
- package/dist/restricted.d.ts +115 -0
- package/dist/restricted.js +257 -0
- package/dist/schema.d.ts +5 -8
- package/dist/schema.js +2 -8
- package/package.json +6 -6
|
@@ -3,6 +3,7 @@ import { MastraModelGateway } from '@mastra/core/llm';
|
|
|
3
3
|
import type { GatewayAuthRequest, GatewayAuthResult, GatewayLanguageModel, MastraModelGatewayInterface, ProviderConfig } from '@mastra/core/llm';
|
|
4
4
|
import { AuthStorage } from '../auth/storage.js';
|
|
5
5
|
import type { CredentialStore } from '../auth/types.js';
|
|
6
|
+
import type { CustomProviderAuthScheme, CustomProviderHeader } from '../onboarding/settings.js';
|
|
6
7
|
import type { AnthropicPromptCacheScope } from '../providers/anthropic-prompt-cache.js';
|
|
7
8
|
import type { CodexServiceTier } from '../providers/model-ids.js';
|
|
8
9
|
import type { ThinkingLevel } from '../providers/openai-codex.js';
|
|
@@ -12,6 +13,9 @@ export type MastraCodeCustomProvider = {
|
|
|
12
13
|
name: string;
|
|
13
14
|
url: string;
|
|
14
15
|
apiKey?: string;
|
|
16
|
+
/** Absent means `bearer`. */
|
|
17
|
+
authScheme?: CustomProviderAuthScheme;
|
|
18
|
+
headers?: CustomProviderHeader[];
|
|
15
19
|
models?: string[];
|
|
16
20
|
};
|
|
17
21
|
export type MastraCodeGatewayOptions = {
|
|
@@ -68,10 +72,15 @@ export declare class MastraCodeGateway extends MastraModelGateway {
|
|
|
68
72
|
static resolveProviderAuth(request: GatewayAuthRequest, mastraGatewayApiKey?: string, credentials?: CredentialStore): GatewayAuthResult | undefined;
|
|
69
73
|
static createModelCatalogProvider(gateway: MastraModelGatewayInterface): CustomModelCatalogProvider;
|
|
70
74
|
createModelCatalogProvider(): CustomModelCatalogProvider;
|
|
75
|
+
/** The catalog entries for custom providers that list at least one model. */
|
|
71
76
|
fetchProviders(): Promise<Record<string, ProviderConfig>>;
|
|
72
77
|
buildUrl(modelId: string): string | undefined | Promise<string | undefined>;
|
|
73
78
|
getApiKey(modelId: string): Promise<string>;
|
|
74
79
|
resolveAuth(request: GatewayAuthRequest): GatewayAuthResult | undefined;
|
|
80
|
+
/**
|
|
81
|
+
* The model a session calls. A custom provider wins over a built-in provider
|
|
82
|
+
* with the same id, and `args.headers` are Mastra's per-request headers.
|
|
83
|
+
*/
|
|
75
84
|
resolveLanguageModel(args: {
|
|
76
85
|
modelId: string;
|
|
77
86
|
providerId: string;
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { AuthStorage } from "../auth/storage.js";
|
|
2
|
+
import { customProviderAuthHeaderName } from "../onboarding/custom-provider-headers.js";
|
|
2
3
|
import { getCustomProviderId, loadSettings } from "../onboarding/settings.js";
|
|
3
4
|
import { buildAnthropicOAuthFetch, claudeCodeMiddleware, createAnthropicThinkingMiddleware, createPromptCacheMiddleware, opencodeClaudeMaxProvider } from "../providers/claude-max.js";
|
|
4
5
|
import { githubCopilotProvider } from "../providers/github-copilot.js";
|
|
@@ -9,12 +10,12 @@ import { THINKING_LEVEL_TO_REASONING_EFFORT, buildOpenAICodexOAuthFetch, createC
|
|
|
9
10
|
import { ModelRouterLanguageModelWithThinking, providerThinkingOptions, withThinkingOptionsModel } from "../providers/provider-thinking.js";
|
|
10
11
|
import { xaiProvider } from "../providers/xai.js";
|
|
11
12
|
import { getAppDataDir } from "../utils/project.js";
|
|
13
|
+
import { createCustomProviderChatModel } from "./custom-provider-check.js";
|
|
12
14
|
import { resolveCustomProviders } from "./custom-provider-source.js";
|
|
13
15
|
import { GATEWAY_AUTH_HEADER, MastraGateway, MastraModelGateway, ModelRouterLanguageModel, PROVIDER_REGISTRY } from "@mastra/core/llm";
|
|
14
16
|
import { createOpenAI } from "@ai-sdk/openai";
|
|
15
17
|
import { wrapLanguageModel } from "ai";
|
|
16
18
|
import { createAnthropic } from "@ai-sdk/anthropic";
|
|
17
|
-
import { createOpenAICompatible } from "@ai-sdk/openai-compatible";
|
|
18
19
|
// src/agents/mastracode-gateway.ts
|
|
19
20
|
const PROVIDERS = PROVIDER_REGISTRY;
|
|
20
21
|
const MASTRACODE_GATEWAY_ID = "mastracode";
|
|
@@ -174,11 +175,6 @@ function hasProviderEnvironmentKey(providerId) {
|
|
|
174
175
|
if (!envVars) return false;
|
|
175
176
|
return (Array.isArray(envVars) ? envVars : [envVars]).some((envVar) => Boolean(process.env[envVar]?.trim()));
|
|
176
177
|
}
|
|
177
|
-
/** Servers call custom endpoints too: a redirect could aim that call at an address the saved URL never named. */
|
|
178
|
-
const fetchWithoutRedirects = (input, init) => fetch(input, {
|
|
179
|
-
...init,
|
|
180
|
-
redirect: "error"
|
|
181
|
-
});
|
|
182
178
|
var MastraCodeGateway = class MastraCodeGateway extends MastraModelGateway {
|
|
183
179
|
id = MASTRACODE_GATEWAY_ID;
|
|
184
180
|
name = "MastraCode Gateway";
|
|
@@ -286,6 +282,7 @@ var MastraCodeGateway = class MastraCodeGateway extends MastraModelGateway {
|
|
|
286
282
|
if (this.#routeThroughMastraGateway) return void 0;
|
|
287
283
|
return this.#getCustomProviders().find((provider) => providerId === getCustomProviderId(provider.name));
|
|
288
284
|
}
|
|
285
|
+
/** The catalog entries for custom providers that list at least one model. */
|
|
289
286
|
async fetchProviders() {
|
|
290
287
|
this.#credentials.reload();
|
|
291
288
|
const providers = {};
|
|
@@ -296,7 +293,7 @@ var MastraCodeGateway = class MastraCodeGateway extends MastraModelGateway {
|
|
|
296
293
|
name: provider.name,
|
|
297
294
|
url: provider.url,
|
|
298
295
|
apiKeyEnvVar: "",
|
|
299
|
-
apiKeyHeader:
|
|
296
|
+
apiKeyHeader: customProviderAuthHeaderName(provider.authScheme),
|
|
300
297
|
gateway: this.id,
|
|
301
298
|
models
|
|
302
299
|
};
|
|
@@ -326,6 +323,10 @@ var MastraCodeGateway = class MastraCodeGateway extends MastraModelGateway {
|
|
|
326
323
|
} : { source: "gateway" };
|
|
327
324
|
return MastraCodeGateway.resolveProviderAuth(request, void 0, this.#credentials);
|
|
328
325
|
}
|
|
326
|
+
/**
|
|
327
|
+
* The model a session calls. A custom provider wins over a built-in provider
|
|
328
|
+
* with the same id, and `args.headers` are Mastra's per-request headers.
|
|
329
|
+
*/
|
|
329
330
|
resolveLanguageModel(args) {
|
|
330
331
|
const customProvider = this.#customProvider(args.providerId);
|
|
331
332
|
const selection = customProvider ? void 0 : parseCodexModelSelection(`${args.providerId}/${args.modelId}`);
|
|
@@ -335,18 +336,20 @@ var MastraCodeGateway = class MastraCodeGateway extends MastraModelGateway {
|
|
|
335
336
|
...selection.codexServiceTier ? { codexServiceTier: selection.codexServiceTier } : {}
|
|
336
337
|
};
|
|
337
338
|
if (customProvider) {
|
|
338
|
-
const
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
339
|
+
const model = createCustomProviderChatModel({
|
|
340
|
+
providerId: args.providerId,
|
|
341
|
+
connection: {
|
|
342
|
+
...customProvider,
|
|
343
|
+
apiKey: args.apiKey
|
|
344
|
+
},
|
|
345
|
+
modelId: args.modelId,
|
|
346
|
+
requestHeaders: args.headers
|
|
344
347
|
});
|
|
345
348
|
const reasoningEffort = this.#thinkingLevel ? THINKING_LEVEL_TO_REASONING_EFFORT[this.#thinkingLevel] : void 0;
|
|
346
349
|
const middleware = createReasoningEffortMiddleware(args.providerId, reasoningEffort);
|
|
347
|
-
if (!middleware) return
|
|
350
|
+
if (!middleware) return model;
|
|
348
351
|
return wrapLanguageModel({
|
|
349
|
-
model
|
|
352
|
+
model,
|
|
350
353
|
middleware: [middleware]
|
|
351
354
|
});
|
|
352
355
|
}
|
package/dist/agents/model.d.ts
CHANGED
|
@@ -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
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
}
|
|
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
|
package/dist/agents/model.js
CHANGED
|
@@ -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
|
|
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
|
|
379
|
+
thinkingLevel,
|
|
300
380
|
remapForCodexOAuth: true,
|
|
301
381
|
requestContext
|
|
302
382
|
};
|
|
303
|
-
const primary = identifyModel(modelId, resolveModel(modelId,
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
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,
|
|
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
|
|
345
|
-
|
|
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' |
|
|
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
|