@mastra/code-sdk 1.11.0-alpha.8 → 1.11.1-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.
- package/dist/acp/agent.d.ts.map +1 -1
- package/dist/acp/agent.js +8 -6
- package/dist/acp/agent.js.map +1 -1
- package/dist/agents/memory.d.ts +3 -1
- package/dist/agents/memory.d.ts.map +1 -1
- package/dist/agents/memory.js +34 -23
- package/dist/agents/memory.js.map +1 -1
- package/dist/agents/model.d.ts +4 -39
- package/dist/agents/model.d.ts.map +1 -1
- package/dist/agents/model.js +34 -93
- package/dist/agents/model.js.map +1 -1
- package/dist/auth/account-rotation-processor.d.ts +26 -54
- package/dist/auth/account-rotation-processor.d.ts.map +1 -1
- package/dist/auth/account-rotation-processor.js +105 -154
- package/dist/auth/account-rotation-processor.js.map +1 -1
- package/dist/auth/index.js +2 -2
- package/dist/auth/types.d.ts +7 -0
- package/dist/auth/types.d.ts.map +1 -1
- package/dist/constants.d.ts +2 -0
- package/dist/constants.d.ts.map +1 -1
- package/dist/constants.js +3 -1
- package/dist/constants.js.map +1 -1
- package/dist/headless/cli.d.ts.map +1 -1
- package/dist/headless/cli.js +4 -1
- package/dist/headless/cli.js.map +1 -1
- package/dist/headless/run-mc.d.ts.map +1 -1
- package/dist/headless/run-mc.js +46 -42
- package/dist/headless/run-mc.js.map +1 -1
- package/dist/index.d.ts +0 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +27 -23
- package/dist/index.js.map +1 -1
- package/dist/schema.d.ts +34 -19
- package/dist/schema.d.ts.map +1 -1
- package/dist/schema.js +10 -4
- package/dist/schema.js.map +1 -1
- package/package.json +14 -14
package/dist/agents/model.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import
|
|
1
|
+
import "../constants.js";
|
|
2
2
|
import { MASTRA_GATEWAY_PREFIX, remapOpenAIModelForCodexOAuth, stripMastraGatewayPrefix } from "../providers/model-ids.js";
|
|
3
3
|
import { ProviderAuthRequiredError } from "../auth/provider-auth-error.js";
|
|
4
4
|
import { isThinkingLevelSetting } from "../thinking.js";
|
|
5
|
-
import {
|
|
5
|
+
import { loadSettings, resolveDefaultThinkingLevel, stripMastraCodeCustomProviderPrefix } from "../onboarding/settings.js";
|
|
6
6
|
import { hasCredentialStoreProvider, resolveCredentialStore, resolveTenantFromRequestContext, setCredentialStoreProvider } from "./credential-resolver.js";
|
|
7
7
|
import { getRequestAccountSelection, isRequestAccountRoutingExhausted } from "../auth/account-routing-context.js";
|
|
8
8
|
import { AMAZON_BEDROCK_GATEWAY_ID, createAmazonBedrockGateway } from "../providers/amazon-bedrock-gateway.js";
|
|
@@ -89,7 +89,10 @@ function resolveModel(modelId, options) {
|
|
|
89
89
|
const [providerId, ...modelParts] = normalizedModelId.split("/");
|
|
90
90
|
const bareModelId = modelParts.join("/");
|
|
91
91
|
if (!providerId || !bareModelId) throw new Error(`Invalid model id: ${modelId}`);
|
|
92
|
+
const tenantCredentialStore = resolveCredentialStore(options?.requestContext);
|
|
93
|
+
const baseCredentialStore = tenantCredentialStore ?? getGlobalAuthStorage();
|
|
92
94
|
if (providerId === "amazon-bedrock") {
|
|
95
|
+
if (tenantCredentialStore?.allowEnvironmentFallback === false && !tenantCredentialStore.allowsDeploymentCredentials?.("amazon-bedrock")) throw new ProviderAuthRequiredError("Amazon Bedrock is not enabled for this Factory deployment. The operator must provide AWS credentials to the server and set FACTORY_DEPLOYMENT_MODEL_PROVIDERS=amazon-bedrock.");
|
|
93
96
|
const bedrockGateway = createAmazonBedrockGateway();
|
|
94
97
|
const routerId = `${AMAZON_BEDROCK_GATEWAY_ID}/${bareModelId}`;
|
|
95
98
|
const auth = bedrockGateway.resolveAuth({
|
|
@@ -108,7 +111,7 @@ function resolveModel(modelId, options) {
|
|
|
108
111
|
const routerId = `${MASTRACODE_GATEWAY_ID}/${normalizedModelId}`;
|
|
109
112
|
const mgApiKey = MastraCodeGateway.getMastraGatewayApiKey();
|
|
110
113
|
const rawGatewayBase = settings.memoryGateway?.baseUrl ?? process.env["MASTRA_GATEWAY_URL"] ?? "https://gateway-api.mastra.ai";
|
|
111
|
-
const credentialStore = createRequestScopedCredentialStore(
|
|
114
|
+
const credentialStore = createRequestScopedCredentialStore(baseCredentialStore, options?.requestContext);
|
|
112
115
|
const gateway = createMastraCodeGateway({
|
|
113
116
|
mastraGatewayBaseUrl: rawGatewayBase.replace(/\/+$/, "").replace(/\/v1$/, ""),
|
|
114
117
|
mastraGatewayApiKey: mgApiKey,
|
|
@@ -151,118 +154,56 @@ function resolveRequestThinkingLevel(agentControllerContext, settingsPath) {
|
|
|
151
154
|
const modeId = agentControllerContext?.session?.modeId;
|
|
152
155
|
return resolveDefaultThinkingLevel(loadSettings(settingsPath), modeId).level;
|
|
153
156
|
}
|
|
154
|
-
/** All packs a fallback chain may reference: every builtin plus saved customs. */
|
|
155
|
-
function listResolvableModePacks(settings) {
|
|
156
|
-
return [...listBuiltinModePacks(), ...settings.customModelPacks.map((pack) => ({
|
|
157
|
-
id: `custom:${pack.name}`,
|
|
158
|
-
name: pack.name,
|
|
159
|
-
models: { ...pack.models }
|
|
160
|
-
}))];
|
|
161
|
-
}
|
|
162
157
|
/**
|
|
163
|
-
* Dynamic model function that reads the current model
|
|
164
|
-
*
|
|
165
|
-
*
|
|
166
|
-
*
|
|
167
|
-
* (`settings.models.packFallbacks`), returns core's `ModelWithRetries[]`
|
|
168
|
-
* fallback array instead of a bare model: the active pack's model first, then
|
|
169
|
-
* each fallback pack's model for the same mode. Core advances the array when
|
|
170
|
-
* the error processors decline to retry (pool exhausted / persistent outage —
|
|
171
|
-
* see AccountRotationProcessor). Entry ids are unique per occurrence — the
|
|
172
|
-
* one allowed revisit of a pack gets `<packId>#2` — because core re-resolves
|
|
173
|
-
* the active fallback index by id across agentic steps.
|
|
158
|
+
* Dynamic model function that reads the current model and optional ordered
|
|
159
|
+
* fallback route from controller state. Route entry ids are opaque host-owned
|
|
160
|
+
* identifiers; repeated ids receive occurrence suffixes because core tracks the
|
|
161
|
+
* active fallback index by id across agentic steps.
|
|
174
162
|
*/
|
|
175
163
|
function getDynamicModel({ requestContext }, settingsPath) {
|
|
176
|
-
const
|
|
177
|
-
const
|
|
178
|
-
const pendingState =
|
|
179
|
-
const pendingFallback = pendingState && (pendingState.threadId === void 0 || typeof pendingState.threadId === "string" && pendingState.threadId ===
|
|
180
|
-
const modelId = (pendingFallback && typeof pendingFallback.toModelId === "string" && pendingFallback.toModelId.length > 0 ? pendingFallback.toModelId : void 0) ??
|
|
164
|
+
const controller = requestContext.get("controller");
|
|
165
|
+
const state = controller?.getState?.();
|
|
166
|
+
const pendingState = state?.mastracodePendingModelFallback;
|
|
167
|
+
const pendingFallback = pendingState && (pendingState.threadId === void 0 || typeof pendingState.threadId === "string" && pendingState.threadId === controller?.threadId) ? pendingState : void 0;
|
|
168
|
+
const modelId = (pendingFallback && typeof pendingFallback.toModelId === "string" && pendingFallback.toModelId.length > 0 ? pendingFallback.toModelId : void 0) ?? controller?.session?.modelId;
|
|
181
169
|
if (!modelId) {
|
|
182
|
-
if (!
|
|
170
|
+
if (!controller) throw new Error("No model available: this run started without a controller session context, so no model selection could be resolved.");
|
|
183
171
|
throw new Error("No model selected. Use /models to select a model first.");
|
|
184
172
|
}
|
|
185
173
|
const resolveOptions = {
|
|
186
|
-
thinkingLevel: resolveRequestThinkingLevel(
|
|
174
|
+
thinkingLevel: resolveRequestThinkingLevel(controller, settingsPath),
|
|
187
175
|
remapForCodexOAuth: true,
|
|
188
176
|
requestContext
|
|
189
177
|
};
|
|
190
178
|
const primary = resolveModel(modelId, resolveOptions);
|
|
191
|
-
const
|
|
192
|
-
const
|
|
193
|
-
|
|
194
|
-
const
|
|
195
|
-
|
|
196
|
-
const
|
|
197
|
-
|
|
198
|
-
if (!activePack) return primary;
|
|
199
|
-
const chain = resolveModePackFallbackChain(fallbacks, activePack.id, settings.customModelPacks);
|
|
200
|
-
if (chain.length < 2) return primary;
|
|
179
|
+
const route = state?.modelRoute?.entries?.slice(0, 32);
|
|
180
|
+
const pendingEntryId = pendingFallback && typeof pendingFallback.toEntryId === "string" ? pendingFallback.toEntryId : void 0;
|
|
181
|
+
const startIndex = pendingEntryId ? route?.findIndex((entry) => entry.id === pendingEntryId) : 0;
|
|
182
|
+
const activeRoute = route && startIndex !== void 0 && startIndex >= 0 ? route.slice(startIndex) : void 0;
|
|
183
|
+
if (!activeRoute || activeRoute.length < 2 || activeRoute[0]?.modelId !== modelId) return primary;
|
|
184
|
+
const firstId = typeof activeRoute[0]?.id === "string" && activeRoute[0].id.length > 0 ? activeRoute[0].id : void 0;
|
|
185
|
+
if (!firstId) return primary;
|
|
201
186
|
const entries = [{
|
|
202
|
-
id:
|
|
187
|
+
id: firstId,
|
|
203
188
|
model: primary
|
|
204
189
|
}];
|
|
205
|
-
const appearances = /* @__PURE__ */ new Map([[
|
|
206
|
-
for (const
|
|
207
|
-
|
|
208
|
-
if (!pack) break;
|
|
209
|
-
const entryModelId = resolveModePackModels(settings, pack)[modeId];
|
|
210
|
-
if (!entryModelId) break;
|
|
211
|
-
let entryModel;
|
|
212
|
-
try {
|
|
213
|
-
entryModel = resolveModel(entryModelId, resolveOptions);
|
|
214
|
-
} catch {
|
|
215
|
-
break;
|
|
216
|
-
}
|
|
217
|
-
const occurrence = (appearances.get(packId) ?? 0) + 1;
|
|
218
|
-
appearances.set(packId, occurrence);
|
|
219
|
-
entries.push({
|
|
220
|
-
id: occurrence === 1 ? packId : `${packId}#${occurrence}`,
|
|
221
|
-
model: entryModel
|
|
222
|
-
});
|
|
223
|
-
}
|
|
224
|
-
if (entries.length < 2) return primary;
|
|
225
|
-
return entries;
|
|
226
|
-
}
|
|
227
|
-
/**
|
|
228
|
-
* Resolve the observational-memory model for the active mode pack, walking the
|
|
229
|
-
* pack's fallback chain (`settings.models.packFallbacks`) and collecting each
|
|
230
|
-
* pack's optional `models.memory` entry. Packs without an OM model are skipped
|
|
231
|
-
* (the field is optional, so absence must not truncate the chain); duplicate
|
|
232
|
-
* model ids collapse so an A⇄B cycle never retries an identical OM model.
|
|
233
|
-
*
|
|
234
|
-
* Returns a bare model for a single entry, a fallback array for multiple
|
|
235
|
-
* entries (OM's internal agents run the same agentic loop, so the array gives
|
|
236
|
-
* OM its own cross-pack failover), or `undefined` when no pack in the chain
|
|
237
|
-
* defines an OM model — callers then fall back to the standalone OM
|
|
238
|
-
* configuration.
|
|
239
|
-
*/
|
|
240
|
-
function resolvePackMemoryModelChain(settings, startPackId, resolveOptions) {
|
|
241
|
-
const packs = listResolvableModePacks(settings);
|
|
242
|
-
if (!packs.some((pack) => pack.id === startPackId)) return void 0;
|
|
243
|
-
const chain = resolveModePackFallbackChain(settings.models?.packFallbacks ?? {}, startPackId, settings.customModelPacks);
|
|
244
|
-
const seenModelIds = /* @__PURE__ */ new Set();
|
|
245
|
-
const entries = [];
|
|
246
|
-
for (const packId of chain) {
|
|
247
|
-
const pack = packs.find((candidate) => candidate.id === packId);
|
|
248
|
-
if (!pack) break;
|
|
249
|
-
const memoryModelId = resolveModePackModels(settings, pack).memory;
|
|
250
|
-
if (!memoryModelId || seenModelIds.has(memoryModelId)) continue;
|
|
251
|
-
seenModelIds.add(memoryModelId);
|
|
190
|
+
const appearances = /* @__PURE__ */ new Map([[firstId, 1]]);
|
|
191
|
+
for (const routeEntry of activeRoute.slice(1)) {
|
|
192
|
+
if (typeof routeEntry.id !== "string" || routeEntry.id.length === 0 || typeof routeEntry.modelId !== "string" || routeEntry.modelId.length === 0) break;
|
|
252
193
|
let entryModel;
|
|
253
194
|
try {
|
|
254
|
-
entryModel = resolveModel(
|
|
195
|
+
entryModel = resolveModel(routeEntry.modelId, resolveOptions);
|
|
255
196
|
} catch {
|
|
256
197
|
break;
|
|
257
198
|
}
|
|
199
|
+
const occurrence = (appearances.get(routeEntry.id) ?? 0) + 1;
|
|
200
|
+
appearances.set(routeEntry.id, occurrence);
|
|
258
201
|
entries.push({
|
|
259
|
-
id: `${
|
|
202
|
+
id: occurrence === 1 ? routeEntry.id : `${routeEntry.id}#${occurrence}`,
|
|
260
203
|
model: entryModel
|
|
261
204
|
});
|
|
262
205
|
}
|
|
263
|
-
|
|
264
|
-
if (entries.length === 1) return entries[0].model;
|
|
265
|
-
return entries;
|
|
206
|
+
return entries.length < 2 ? primary : entries;
|
|
266
207
|
}
|
|
267
208
|
/**
|
|
268
209
|
* Goal judge model resolver for the agent's `goal.judge` config. Resolves the
|
|
@@ -287,6 +228,6 @@ function getGoalJudgeModel({ requestContext }, settingsPath) {
|
|
|
287
228
|
});
|
|
288
229
|
}
|
|
289
230
|
//#endregion
|
|
290
|
-
export { MASTRACODE_GATEWAY_ID, MastraCodeGateway, createMastraCodeGateway, createMastraCodeModelCatalogProvider, createRequestScopedCredentialStore, getAnthropicApiKey, getDynamicModel, getGoalJudgeModel, getOpenAIApiKey, hasCredentialStoreProvider, hasCustomProvidersSource,
|
|
231
|
+
export { MASTRACODE_GATEWAY_ID, MastraCodeGateway, createMastraCodeGateway, createMastraCodeModelCatalogProvider, createRequestScopedCredentialStore, getAnthropicApiKey, getDynamicModel, getGoalJudgeModel, getOpenAIApiKey, hasCredentialStoreProvider, hasCustomProvidersSource, remapOpenAIModelForCodexOAuth, resolveAuth, resolveCustomProviders, resolveModel, resolveModelId, resolveRequestThinkingLevel, resolveTenantFromRequestContext, setCredentialStoreProvider, setCustomProvidersSource };
|
|
291
232
|
|
|
292
233
|
//# sourceMappingURL=model.js.map
|
package/dist/agents/model.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"model.js","names":[],"sources":["../../src/agents/model.ts"],"sourcesContent":["import type { ModelWithRetries } from '@mastra/core/agent';\nimport type { AgentControllerRequestContext } from '@mastra/core/agent-controller';\nimport type { GatewayLanguageModel, MastraModelGatewayInterface } from '@mastra/core/llm';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport { getRequestAccountSelection, isRequestAccountRoutingExhausted } from '../auth/account-routing-context.js';\nimport { ProviderAuthRequiredError } from '../auth/provider-auth-error.js';\nimport type { CredentialStore, OAuthAccountRecord } from '../auth/types.js';\nimport { listBuiltinModePacks, resolveModePackFallbackChain } from '../onboarding/packs.js';\nimport {\n findModePackForModel,\n loadSettings,\n resolveDefaultThinkingLevel,\n resolveModePackModels,\n stripMastraCodeCustomProviderPrefix,\n} from '../onboarding/settings.js';\nimport { AMAZON_BEDROCK_GATEWAY_ID, createAmazonBedrockGateway } from '../providers/amazon-bedrock-gateway.js';\nimport type { AnthropicPromptCacheScope } from '../providers/anthropic-prompt-cache.js';\nimport { isThinkingLevelSetting } from '../thinking.js';\nimport type { ThinkingLevelSetting } from '../thinking.js';\nimport { resolveCredentialStore } from './credential-resolver.js';\nimport { resolveCustomProviders } from './custom-provider-source.js';\nimport {\n MASTRA_GATEWAY_PREFIX,\n MASTRACODE_GATEWAY_ID,\n MastraCodeGateway,\n getGlobalAuthStorage,\n reloadAuthStorage,\n stripMastraGatewayPrefix,\n} from './mastracode-gateway.js';\nimport type { MastraCodeGatewayOptions } from './mastracode-gateway.js';\n\nexport {\n getAnthropicApiKey,\n getOpenAIApiKey,\n MASTRACODE_GATEWAY_ID,\n MastraCodeGateway,\n remapOpenAIModelForCodexOAuth,\n resolveAuth,\n} from './mastracode-gateway.js';\nexport type { MastraCodeCustomProvider, MastraCodeGatewayOptions } from './mastracode-gateway.js';\nexport {\n setCredentialStoreProvider,\n hasCredentialStoreProvider,\n resolveTenantFromRequestContext,\n} from './credential-resolver.js';\nexport type { CredentialTenant, CredentialStoreProvider } from './credential-resolver.js';\nexport {\n setCustomProvidersSource,\n hasCustomProvidersSource,\n resolveCustomProviders,\n} from './custom-provider-source.js';\nexport type { CustomProvidersSource } from './custom-provider-source.js';\n\ntype ResolvedModel = GatewayLanguageModel;\ntype ModelRequestHeaders = Record<string, string>;\n\nfunction getAgentControllerHeaders(requestContext?: RequestContext): ModelRequestHeaders | undefined {\n const agentControllerContext = requestContext?.get('controller') as AgentControllerRequestContext<any> | undefined;\n const headers = {\n ...(agentControllerContext?.threadId ? { 'x-thread-id': agentControllerContext.threadId } : {}),\n ...(agentControllerContext?.resourceId ? { 'x-resource-id': agentControllerContext.resourceId } : {}),\n };\n\n return Object.keys(headers).length > 0 ? headers : undefined;\n}\n\nfunction accountCredential(account: OAuthAccountRecord) {\n const { type: _type, id: _id, label: _label, addedAt: _addedAt, active: _active, ...credential } = account;\n return { type: 'oauth' as const, ...credential };\n}\n\nexport function createRequestScopedCredentialStore(\n base: CredentialStore,\n requestContext?: RequestContext,\n): CredentialStore {\n const selectedId = (providerId: string) => getRequestAccountSelection(requestContext, providerId);\n const selectedAccount = (providerId: string) => {\n const accountInstanceId = selectedId(providerId);\n return accountInstanceId\n ? base.listAccounts?.(providerId).find(account => account.id === accountInstanceId)\n : undefined;\n };\n // Routing rejected every account for this provider on this request. Fail\n // closed on every credential read: falling through to `base` would use the\n // provider's active account — the exhausted one routing just refused.\n const rejectAll = (providerId: string) => isRequestAccountRoutingExhausted(requestContext, providerId);\n\n return {\n allowEnvironmentFallback: base.allowEnvironmentFallback,\n reload: () => base.reload(),\n get: providerId => {\n if (rejectAll(providerId)) return undefined;\n // A selection that no longer resolves (the account was removed between\n // routing and the credential read) must not fall through to the active\n // account — that is the account routing deliberately passed over.\n const accountInstanceId = selectedId(providerId);\n if (accountInstanceId === undefined) return base.get(providerId);\n const selected = selectedAccount(providerId);\n return selected ? accountCredential(selected) : undefined;\n },\n getStoredApiKey: providerId => {\n if (rejectAll(providerId)) return undefined;\n // The provider-wide `apikey:` slot is never the credential routing\n // selected, so serving it to a routed request is an OAuth -> API-key\n // fallback of the same provider — the one combination this feature\n // forbids. Unlike `get`, this read has no account argument to pass\n // through, so a selection fails it closed instead.\n if (selectedId(providerId) !== undefined) return undefined;\n return base.getStoredApiKey(providerId);\n },\n getApiKey: providerId =>\n rejectAll(providerId) ? Promise.resolve(undefined) : base.getApiKey(providerId, selectedId(providerId)),\n getOAuthCredential: base.getOAuthCredential\n ? providerId =>\n rejectAll(providerId)\n ? Promise.resolve(undefined)\n : base.getOAuthCredential!(providerId, selectedId(providerId))\n : undefined,\n listAccounts: base.listAccounts ? providerId => base.listAccounts!(providerId) : undefined,\n getActiveAccount: base.getActiveAccount ? providerId => base.getActiveAccount!(providerId) : undefined,\n activateAccount: base.activateAccount\n ? (providerId, accountInstanceId) => base.activateAccount!(providerId, accountInstanceId)\n : undefined,\n removeAccount: base.removeAccount\n ? (providerId, accountInstanceId) => base.removeAccount!(providerId, accountInstanceId)\n : undefined,\n };\n}\n\nexport function createMastraCodeGateway(options: MastraCodeGatewayOptions): MastraCodeGateway {\n return new MastraCodeGateway(options);\n}\n\nexport function createMastraCodeModelCatalogProvider(gateway: MastraModelGatewayInterface) {\n return gateway instanceof MastraCodeGateway\n ? gateway.createModelCatalogProvider()\n : MastraCodeGateway.createModelCatalogProvider(gateway);\n}\n\n/**\n * Placeholder for future model ID normalization.\n * Currently returns the input unchanged, but exists as a seam\n * for aliasing, casing fixes, or validation in the future.\n */\nexport function resolveModelId(modelId: string): string {\n return modelId;\n}\n\n/**\n * Resolve a model ID to the correct provider instance.\n * Shared by the main agent, observer, and reflector.\n *\n * - For anthropic/* models: Uses stored OAuth credentials when present, otherwise direct API key\n * - For openai/* models: Uses OAuth when configured, otherwise direct API key from AuthStorage\n * - For moonshotai/* models: Uses Moonshot AI Anthropic-compatible endpoint\n * - For all other providers: Uses Mastra's model router (models.dev gateway)\n */\nexport function resolveModel(\n modelId: string,\n options?: {\n thinkingLevel?: ThinkingLevelSetting;\n remapForCodexOAuth?: boolean;\n requestContext?: RequestContext;\n anthropicPromptCacheScope?: AnthropicPromptCacheScope;\n },\n): GatewayLanguageModel {\n reloadAuthStorage();\n const headers = getAgentControllerHeaders(options?.requestContext);\n const settings = loadSettings();\n // Bedrock was previously cataloged under the MastraCode gateway namespace\n // (`mastracode/amazon-bedrock/<model>`). Normalize any legacy saved ids to the\n // standalone `amazon-bedrock/<model>` form so they resolve through the\n // dedicated Bedrock gateway.\n const bedrockLegacyPrefix = `${MASTRACODE_GATEWAY_ID}/amazon-bedrock/`;\n const bedrockNormalizedInput = modelId.startsWith(bedrockLegacyPrefix)\n ? modelId.slice(MASTRACODE_GATEWAY_ID.length + 1)\n : modelId;\n // Deployed web registers a custom providers source (DB-backed, tenant\n // scoped); when registered it is authoritative and settings.json custom\n // providers are ignored. Undefined = local settings-based behavior.\n const customProviders = resolveCustomProviders(options?.requestContext) ?? settings.customProviders;\n // Ids selected from the shared /models catalog were previously persisted in\n // the gateway-qualified `mastracode/<customProviderId>/<model>` form, which\n // parses the provider as `mastracode` and breaks provider config lookup.\n // Normalize at resolution time (in addition to stripping at selection time)\n // so already-saved ids and any surface that persists the raw catalog id\n // still resolve to the custom provider.\n const normalizedInput = stripMastraCodeCustomProviderPrefix(bedrockNormalizedInput, customProviders);\n const isMastraGatewayModel = normalizedInput.startsWith(MASTRA_GATEWAY_PREFIX);\n const normalizedModelId = stripMastraGatewayPrefix(normalizedInput);\n const [providerId, ...modelParts] = normalizedModelId.split('/');\n const bareModelId = modelParts.join('/');\n if (!providerId || !bareModelId) {\n throw new Error(`Invalid model id: ${modelId}`);\n }\n\n if (providerId === AMAZON_BEDROCK_GATEWAY_ID) {\n const bedrockGateway = createAmazonBedrockGateway();\n const routerId = `${AMAZON_BEDROCK_GATEWAY_ID}/${bareModelId}`;\n const auth = bedrockGateway.resolveAuth({\n gatewayId: AMAZON_BEDROCK_GATEWAY_ID,\n providerId: AMAZON_BEDROCK_GATEWAY_ID,\n modelId: bareModelId,\n routerId,\n });\n return bedrockGateway.resolveLanguageModel({\n providerId: AMAZON_BEDROCK_GATEWAY_ID,\n modelId: bareModelId,\n apiKey: auth?.apiKey ?? '',\n headers,\n });\n }\n\n const routerId = `${MASTRACODE_GATEWAY_ID}/${normalizedModelId}`;\n\n const mgApiKey = MastraCodeGateway.getMastraGatewayApiKey();\n const rawGatewayBase =\n settings.memoryGateway?.baseUrl ?? process.env['MASTRA_GATEWAY_URL'] ?? 'https://gateway-api.mastra.ai';\n // Deployed web registers a per-tenant credential store provider; when the\n // request carries an authenticated tenant, resolve credentials through the\n // caller's own store (user > org > env). Undefined = global AuthStorage.\n const baseCredentialStore = resolveCredentialStore(options?.requestContext) ?? getGlobalAuthStorage();\n const credentialStore = createRequestScopedCredentialStore(baseCredentialStore, options?.requestContext);\n const gateway = createMastraCodeGateway({\n mastraGatewayBaseUrl: rawGatewayBase.replace(/\\/+$/, '').replace(/\\/v1$/, ''),\n mastraGatewayApiKey: mgApiKey,\n routeThroughMastraGateway: Boolean(mgApiKey && isMastraGatewayModel),\n thinkingLevel: options?.thinkingLevel,\n anthropicPromptCacheScope: options?.anthropicPromptCacheScope,\n customProviders,\n credentialStore,\n });\n\n const auth = gateway.resolveAuth({\n gatewayId: MASTRACODE_GATEWAY_ID,\n providerId,\n modelId: bareModelId,\n routerId,\n });\n\n if (!auth && credentialStore?.allowEnvironmentFallback === false) {\n throw new ProviderAuthRequiredError(\n `No usable ${providerId} credential is configured for this signed-in Factory account. Connect the provider or add an organization credential, then try again.`,\n );\n }\n\n return gateway.resolveLanguageModel({\n providerId,\n modelId: bareModelId,\n apiKey: auth?.apiKey ?? '',\n headers,\n });\n}\n\nexport interface ThinkingRequestContext {\n state?: { thinkingLevel?: unknown };\n session?: { modeId?: string };\n}\n/**\n * Resolve the effective thinking level for the current request.\n *\n * Precedence:\n * 1. Session override (`state.thinkingLevel`, set via /think or the session\n * settings panel).\n * 2. Per-mode default from settings (`models.modeThinkingDefaults[mode]`).\n * 3. Global default (`preferences.thinkingLevel`).\n *\n * Resolved per-request (not seeded at session start) so configuration changes\n * apply to the next request of every session — including automated\n * (rule-driven) Factory runs that nobody ever opens interactively.\n */\n\nexport function resolveRequestThinkingLevel(\n agentControllerContext: ThinkingRequestContext | undefined,\n settingsPath?: string,\n): ThinkingLevelSetting {\n const override = agentControllerContext?.state?.thinkingLevel;\n if (isThinkingLevelSetting(override)) return override;\n const modeId = agentControllerContext?.session?.modeId;\n return resolveDefaultThinkingLevel(loadSettings(settingsPath), modeId).level;\n}\n\n/** Structural pack shape for fallback resolution (custom pack models are partial by nature). */\nexport interface ResolvableModePack {\n id: string;\n name: string;\n models: Record<string, string>;\n}\n\n/** All packs a fallback chain may reference: every builtin plus saved customs. */\nexport function listResolvableModePacks(settings: ReturnType<typeof loadSettings>): ResolvableModePack[] {\n return [\n ...listBuiltinModePacks(),\n ...settings.customModelPacks.map(pack => ({\n id: `custom:${pack.name}`,\n name: pack.name,\n models: { ...pack.models },\n })),\n ];\n}\n\n/**\n * Dynamic model function that reads the current model from controller state.\n * This allows runtime model switching via the /models picker.\n *\n * When the session's model came from a pack with a fallback chain configured\n * (`settings.models.packFallbacks`), returns core's `ModelWithRetries[]`\n * fallback array instead of a bare model: the active pack's model first, then\n * each fallback pack's model for the same mode. Core advances the array when\n * the error processors decline to retry (pool exhausted / persistent outage —\n * see AccountRotationProcessor). Entry ids are unique per occurrence — the\n * one allowed revisit of a pack gets `<packId>#2` — because core re-resolves\n * the active fallback index by id across agentic steps.\n */\nexport function getDynamicModel(\n { requestContext }: { requestContext: RequestContext },\n settingsPath?: string,\n): ResolvedModel | ModelWithRetries[] {\n const agentControllerContext = requestContext.get('controller') as AgentControllerRequestContext<any> | undefined;\n\n const controllerState = agentControllerContext?.getState?.() as\n | {\n activeModelPackId?: unknown;\n mastracodePendingPackFallback?: { toPackId?: unknown; toModelId?: unknown; threadId?: unknown } | null;\n }\n | undefined;\n const pendingState = controllerState?.mastracodePendingPackFallback;\n const pendingFallback =\n pendingState &&\n (pendingState.threadId === undefined ||\n (typeof pendingState.threadId === 'string' && pendingState.threadId === agentControllerContext?.threadId))\n ? pendingState\n : undefined;\n const pendingModelId =\n pendingFallback && typeof pendingFallback.toModelId === 'string' && pendingFallback.toModelId.length > 0\n ? pendingFallback.toModelId\n : undefined;\n const modelId = pendingModelId ?? agentControllerContext?.session?.modelId;\n if (!modelId) {\n // A missing controller context means the run was started without session\n // request context at all (e.g. a signal delivered to an idle thread) —\n // \"use /models\" would mislead there, the user's selection was never the\n // problem.\n if (!agentControllerContext) {\n throw new Error(\n 'No model available: this run started without a controller session context, so no model selection could be resolved.',\n );\n }\n throw new Error('No model selected. Use /models to select a model first.');\n }\n\n const thinkingLevel = resolveRequestThinkingLevel(agentControllerContext, settingsPath);\n const resolveOptions = { thinkingLevel, remapForCodexOAuth: true, requestContext } as const;\n const primary = resolveModel(modelId, resolveOptions);\n\n const settings = loadSettings(settingsPath);\n // `models?` tolerates partial settings mocks; loaded settings always carry it.\n const fallbacks = settings.models?.packFallbacks ?? {};\n if (Object.keys(fallbacks).length === 0) return primary;\n\n const modeId = agentControllerContext?.session?.modeId ?? 'build';\n const packs = listResolvableModePacks(settings);\n const pendingPackId =\n pendingFallback && typeof pendingFallback.toPackId === 'string' && pendingFallback.toPackId.length > 0\n ? pendingFallback.toPackId\n : undefined;\n const statePackId = pendingPackId ?? controllerState?.activeModelPackId ?? settings.models.activeModelPackId;\n const activePack = findModePackForModel(\n settings,\n packs,\n modelId,\n modeId,\n typeof statePackId === 'string' ? statePackId : undefined,\n );\n if (!activePack) return primary;\n\n const chain = resolveModePackFallbackChain(fallbacks, activePack.id, settings.customModelPacks);\n if (chain.length < 2) return primary;\n\n const entries: ModelWithRetries[] = [{ id: activePack.id, model: primary }];\n const appearances = new Map<string, number>([[activePack.id, 1]]);\n for (const packId of chain.slice(1)) {\n const pack = packs.find(candidate => candidate.id === packId);\n if (!pack) break;\n const entryModelId = resolveModePackModels(settings, pack)[modeId];\n if (!entryModelId) break;\n // Best-effort resolution: an unresolvable fallback (e.g. unconnected\n // provider in deployed fail-closed mode) truncates the chain here rather\n // than failing the request before the primary is ever tried.\n let entryModel: ResolvedModel;\n try {\n entryModel = resolveModel(entryModelId, resolveOptions);\n } catch {\n break;\n }\n const occurrence = (appearances.get(packId) ?? 0) + 1;\n appearances.set(packId, occurrence);\n entries.push({\n id: occurrence === 1 ? packId : `${packId}#${occurrence}`,\n model: entryModel,\n });\n }\n // A chain that truncated to the primary alone is indistinguishable from no\n // chain — return the bare model so core never sees a one-entry array.\n if (entries.length < 2) return primary;\n return entries;\n}\n\n/** OM fallback-chain entry: a pack's OM model resolved through the gateway. Assignable to `ModelWithRetries`. */\nexport type PackMemoryModelChainEntry = { id: string; model: GatewayLanguageModel };\n\n/**\n * Resolve the observational-memory model for the active mode pack, walking the\n * pack's fallback chain (`settings.models.packFallbacks`) and collecting each\n * pack's optional `models.memory` entry. Packs without an OM model are skipped\n * (the field is optional, so absence must not truncate the chain); duplicate\n * model ids collapse so an A⇄B cycle never retries an identical OM model.\n *\n * Returns a bare model for a single entry, a fallback array for multiple\n * entries (OM's internal agents run the same agentic loop, so the array gives\n * OM its own cross-pack failover), or `undefined` when no pack in the chain\n * defines an OM model — callers then fall back to the standalone OM\n * configuration.\n */\nexport function resolvePackMemoryModelChain(\n settings: ReturnType<typeof loadSettings>,\n startPackId: string,\n resolveOptions: Parameters<typeof resolveModel>[1],\n): GatewayLanguageModel | PackMemoryModelChainEntry[] | undefined {\n const packs = listResolvableModePacks(settings);\n if (!packs.some(pack => pack.id === startPackId)) return undefined;\n\n const chain = resolveModePackFallbackChain(\n settings.models?.packFallbacks ?? {},\n startPackId,\n settings.customModelPacks,\n );\n const seenModelIds = new Set<string>();\n const entries: PackMemoryModelChainEntry[] = [];\n for (const packId of chain) {\n const pack = packs.find(candidate => candidate.id === packId);\n if (!pack) break;\n const memoryModelId = resolveModePackModels(settings, pack).memory;\n if (!memoryModelId || seenModelIds.has(memoryModelId)) continue;\n seenModelIds.add(memoryModelId);\n // Best-effort resolution: an unresolvable OM entry (e.g. unconnected\n // provider in deployed fail-closed mode) truncates the chain here rather\n // than failing observation before the pack's own OM model is tried.\n let entryModel: ResolvedModel;\n try {\n entryModel = resolveModel(memoryModelId, resolveOptions);\n } catch {\n break;\n }\n entries.push({ id: `${packId}:memory`, model: entryModel });\n }\n\n if (entries.length === 0) return undefined;\n if (entries.length === 1) return entries[0]!.model;\n return entries;\n}\n\n/**\n * Goal judge model resolver for the agent's `goal.judge` config. Resolves the\n * configured goal judge model through mastracode's gateway so provider\n * credentials (stored in auth storage, not just env) are injected — a bare model\n * id handed to core's default model router would fail to find the API key.\n *\n * Returns `undefined` when no judge model is configured, which keeps the goal\n * step a complete no-op (the goal mechanism requires a judge to do anything).\n *\n * `settingsPath` must be the same source `createMastraCode()` reads from so the\n * judge model and the goal budget (`goalMaxTurns`) come from one config — with a\n * custom `settingsPath` a bare `loadSettings()` here could read a different file\n * and silently turn the goal step into a no-op.\n */\nexport function getGoalJudgeModel(\n { requestContext }: { requestContext: RequestContext },\n settingsPath?: string,\n): ResolvedModel | undefined {\n const judgeModelId = loadSettings(settingsPath).models.goalJudgeModel;\n if (!judgeModelId) return undefined;\n return resolveModel(judgeModelId, { remapForCodexOAuth: true, requestContext });\n}\n"],"mappings":";;;;;;;;;;;AAwDA,SAAS,0BAA0B,gBAAkE;CACnG,MAAM,yBAAyB,gBAAgB,IAAI,YAAY;CAC/D,MAAM,UAAU;EACd,GAAI,wBAAwB,WAAW,EAAE,eAAe,uBAAuB,SAAS,IAAI,CAAC;EAC7F,GAAI,wBAAwB,aAAa,EAAE,iBAAiB,uBAAuB,WAAW,IAAI,CAAC;CACrG;CAEA,OAAO,OAAO,KAAK,OAAO,CAAC,CAAC,SAAS,IAAI,UAAU,KAAA;AACrD;AAEA,SAAS,kBAAkB,SAA6B;CACtD,MAAM,EAAE,MAAM,OAAO,IAAI,KAAK,OAAO,QAAQ,SAAS,UAAU,QAAQ,SAAS,GAAG,eAAe;CACnG,OAAO;EAAE,MAAM;EAAkB,GAAG;CAAW;AACjD;AAEA,SAAgB,mCACd,MACA,gBACiB;CACjB,MAAM,cAAc,eAAuB,2BAA2B,gBAAgB,UAAU;CAChG,MAAM,mBAAmB,eAAuB;EAC9C,MAAM,oBAAoB,WAAW,UAAU;EAC/C,OAAO,oBACH,KAAK,eAAe,UAAU,CAAC,CAAC,MAAK,YAAW,QAAQ,OAAO,iBAAi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IAAI,SAAS,GAAG,OAAO,GAAG;GAC7C,OAAO;EACT,CAAC;CACH;CAGA,IAAI,QAAQ,SAAS,GAAG,OAAO;CAC/B,OAAO;AACT;;;;;;;;;;;;;;AAkBA,SAAgB,4BACd,UACA,aACA,gBACgE;CAChE,MAAM,QAAQ,wBAAwB,QAAQ;CAC9C,IAAI,CAAC,MAAM,MAAK,SAAQ,KAAK,OAAO,WAAW,GAAG,OAAO,KAAA;CAEzD,MAAM,QAAQ,6BACZ,SAAS,QAAQ,iBAAiB,CAAC,GACnC,aACA,SAAS,gBACX;CACA,MAAM,+BAAe,IAAI,IAAY;CACrC,MAAM,UAAuC,CAAC;CAC9C,KAAK,MAAM,UAAU,OAAO;EAC1B,MAAM,OAAO,MAAM,MAAK,cAAa,UAAU,OAAO,MAAM;EAC5D,IAAI,CAAC,MAAM;EACX,MAAM,gBAAgB,sBAAsB,UAAU,IAAI,CAAC,CAAC;EAC5D,IAAI,CAAC,iBAAiB,aAAa,IAAI,aAAa,GAAG;EACvD,aAAa,IAAI,aAAa;EAI9B,IAAI;EACJ,IAAI;GACF,aAAa,aAAa,eAAe,cAAc;EACzD,QAAQ;GACN;EACF;EACA,QAAQ,KAAK;GAAE,IAAI,GAAG,OAAO;GAAU,OAAO;EAAW,CAAC;CAC5D;CAEA,IAAI,QAAQ,WAAW,GAAG,OAAO,KAAA;CACjC,IAAI,QAAQ,WAAW,GAAG,OAAO,QAAQ,EAAE,CAAE;CAC7C,OAAO;AACT;;;;;;;;;;;;;;;AAgBA,SAAgB,kBACd,EAAE,kBACF,cAC2B;CAC3B,MAAM,eAAe,aAAa,YAAY,CAAC,CAAC,OAAO;CACvD,IAAI,CAAC,cAAc,OAAO,KAAA;CAC1B,OAAO,aAAa,cAAc;EAAE,oBAAoB;EAAM;CAAe,CAAC;AAChF"}
|
|
1
|
+
{"version":3,"file":"model.js","names":[],"sources":["../../src/agents/model.ts"],"sourcesContent":["import type { ModelWithRetries } from '@mastra/core/agent';\nimport type { AgentControllerRequestContext } from '@mastra/core/agent-controller';\nimport type { GatewayLanguageModel, MastraModelGatewayInterface } from '@mastra/core/llm';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport { getRequestAccountSelection, isRequestAccountRoutingExhausted } from '../auth/account-routing-context.js';\nimport { ProviderAuthRequiredError } from '../auth/provider-auth-error.js';\nimport type { CredentialStore, OAuthAccountRecord } from '../auth/types.js';\nimport { MODEL_ROUTE_MAX_ENTRIES } from '../constants.js';\nimport {\n loadSettings,\n resolveDefaultThinkingLevel,\n stripMastraCodeCustomProviderPrefix,\n} from '../onboarding/settings.js';\nimport { AMAZON_BEDROCK_GATEWAY_ID, createAmazonBedrockGateway } from '../providers/amazon-bedrock-gateway.js';\nimport type { AnthropicPromptCacheScope } from '../providers/anthropic-prompt-cache.js';\nimport { isThinkingLevelSetting } from '../thinking.js';\nimport type { ThinkingLevelSetting } from '../thinking.js';\nimport { resolveCredentialStore } from './credential-resolver.js';\nimport { resolveCustomProviders } from './custom-provider-source.js';\nimport {\n MASTRA_GATEWAY_PREFIX,\n MASTRACODE_GATEWAY_ID,\n MastraCodeGateway,\n getGlobalAuthStorage,\n reloadAuthStorage,\n stripMastraGatewayPrefix,\n} from './mastracode-gateway.js';\nimport type { MastraCodeGatewayOptions } from './mastracode-gateway.js';\n\nexport {\n getAnthropicApiKey,\n getOpenAIApiKey,\n MASTRACODE_GATEWAY_ID,\n MastraCodeGateway,\n remapOpenAIModelForCodexOAuth,\n resolveAuth,\n} from './mastracode-gateway.js';\nexport type { MastraCodeCustomProvider, MastraCodeGatewayOptions } from './mastracode-gateway.js';\nexport {\n setCredentialStoreProvider,\n hasCredentialStoreProvider,\n resolveTenantFromRequestContext,\n} from './credential-resolver.js';\nexport type { CredentialTenant, CredentialStoreProvider } from './credential-resolver.js';\nexport {\n setCustomProvidersSource,\n hasCustomProvidersSource,\n resolveCustomProviders,\n} from './custom-provider-source.js';\nexport type { CustomProvidersSource } from './custom-provider-source.js';\n\ntype ResolvedModel = GatewayLanguageModel;\ntype ModelRequestHeaders = Record<string, string>;\n\nfunction getAgentControllerHeaders(requestContext?: RequestContext): ModelRequestHeaders | undefined {\n const agentControllerContext = requestContext?.get('controller') as AgentControllerRequestContext<any> | undefined;\n const headers = {\n ...(agentControllerContext?.threadId ? { 'x-thread-id': agentControllerContext.threadId } : {}),\n ...(agentControllerContext?.resourceId ? { 'x-resource-id': agentControllerContext.resourceId } : {}),\n };\n\n return Object.keys(headers).length > 0 ? headers : undefined;\n}\n\nfunction accountCredential(account: OAuthAccountRecord) {\n const { type: _type, id: _id, label: _label, addedAt: _addedAt, active: _active, ...credential } = account;\n return { type: 'oauth' as const, ...credential };\n}\n\nexport function createRequestScopedCredentialStore(\n base: CredentialStore,\n requestContext?: RequestContext,\n): CredentialStore {\n const selectedId = (providerId: string) => getRequestAccountSelection(requestContext, providerId);\n const selectedAccount = (providerId: string) => {\n const accountInstanceId = selectedId(providerId);\n return accountInstanceId\n ? base.listAccounts?.(providerId).find(account => account.id === accountInstanceId)\n : undefined;\n };\n // Routing rejected every account for this provider on this request. Fail\n // closed on every credential read: falling through to `base` would use the\n // provider's active account — the exhausted one routing just refused.\n const rejectAll = (providerId: string) => isRequestAccountRoutingExhausted(requestContext, providerId);\n\n return {\n allowEnvironmentFallback: base.allowEnvironmentFallback,\n reload: () => base.reload(),\n get: providerId => {\n if (rejectAll(providerId)) return undefined;\n // A selection that no longer resolves (the account was removed between\n // routing and the credential read) must not fall through to the active\n // account — that is the account routing deliberately passed over.\n const accountInstanceId = selectedId(providerId);\n if (accountInstanceId === undefined) return base.get(providerId);\n const selected = selectedAccount(providerId);\n return selected ? accountCredential(selected) : undefined;\n },\n getStoredApiKey: providerId => {\n if (rejectAll(providerId)) return undefined;\n // The provider-wide `apikey:` slot is never the credential routing\n // selected, so serving it to a routed request is an OAuth -> API-key\n // fallback of the same provider — the one combination this feature\n // forbids. Unlike `get`, this read has no account argument to pass\n // through, so a selection fails it closed instead.\n if (selectedId(providerId) !== undefined) return undefined;\n return base.getStoredApiKey(providerId);\n },\n getApiKey: providerId =>\n rejectAll(providerId) ? Promise.resolve(undefined) : base.getApiKey(providerId, selectedId(providerId)),\n getOAuthCredential: base.getOAuthCredential\n ? providerId =>\n rejectAll(providerId)\n ? Promise.resolve(undefined)\n : base.getOAuthCredential!(providerId, selectedId(providerId))\n : undefined,\n listAccounts: base.listAccounts ? providerId => base.listAccounts!(providerId) : undefined,\n getActiveAccount: base.getActiveAccount ? providerId => base.getActiveAccount!(providerId) : undefined,\n activateAccount: base.activateAccount\n ? (providerId, accountInstanceId) => base.activateAccount!(providerId, accountInstanceId)\n : undefined,\n removeAccount: base.removeAccount\n ? (providerId, accountInstanceId) => base.removeAccount!(providerId, accountInstanceId)\n : undefined,\n };\n}\n\nexport function createMastraCodeGateway(options: MastraCodeGatewayOptions): MastraCodeGateway {\n return new MastraCodeGateway(options);\n}\n\nexport function createMastraCodeModelCatalogProvider(gateway: MastraModelGatewayInterface) {\n return gateway instanceof MastraCodeGateway\n ? gateway.createModelCatalogProvider()\n : MastraCodeGateway.createModelCatalogProvider(gateway);\n}\n\n/**\n * Placeholder for future model ID normalization.\n * Currently returns the input unchanged, but exists as a seam\n * for aliasing, casing fixes, or validation in the future.\n */\nexport function resolveModelId(modelId: string): string {\n return modelId;\n}\n\n/**\n * Resolve a model ID to the correct provider instance.\n * Shared by the main agent, observer, and reflector.\n *\n * - For anthropic/* models: Uses stored OAuth credentials when present, otherwise direct API key\n * - For openai/* models: Uses OAuth when configured, otherwise direct API key from AuthStorage\n * - For moonshotai/* models: Uses Moonshot AI Anthropic-compatible endpoint\n * - For all other providers: Uses Mastra's model router (models.dev gateway)\n */\nexport function resolveModel(\n modelId: string,\n options?: {\n thinkingLevel?: ThinkingLevelSetting;\n remapForCodexOAuth?: boolean;\n requestContext?: RequestContext;\n anthropicPromptCacheScope?: AnthropicPromptCacheScope;\n },\n): GatewayLanguageModel {\n reloadAuthStorage();\n const headers = getAgentControllerHeaders(options?.requestContext);\n const settings = loadSettings();\n // Bedrock was previously cataloged under the MastraCode gateway namespace\n // (`mastracode/amazon-bedrock/<model>`). Normalize any legacy saved ids to the\n // standalone `amazon-bedrock/<model>` form so they resolve through the\n // dedicated Bedrock gateway.\n const bedrockLegacyPrefix = `${MASTRACODE_GATEWAY_ID}/amazon-bedrock/`;\n const bedrockNormalizedInput = modelId.startsWith(bedrockLegacyPrefix)\n ? modelId.slice(MASTRACODE_GATEWAY_ID.length + 1)\n : modelId;\n // Deployed web registers a custom providers source (DB-backed, tenant\n // scoped); when registered it is authoritative and settings.json custom\n // providers are ignored. Undefined = local settings-based behavior.\n const customProviders = resolveCustomProviders(options?.requestContext) ?? settings.customProviders;\n // Ids selected from the shared /models catalog were previously persisted in\n // the gateway-qualified `mastracode/<customProviderId>/<model>` form, which\n // parses the provider as `mastracode` and breaks provider config lookup.\n // Normalize at resolution time (in addition to stripping at selection time)\n // so already-saved ids and any surface that persists the raw catalog id\n // still resolve to the custom provider.\n const normalizedInput = stripMastraCodeCustomProviderPrefix(bedrockNormalizedInput, customProviders);\n const isMastraGatewayModel = normalizedInput.startsWith(MASTRA_GATEWAY_PREFIX);\n const normalizedModelId = stripMastraGatewayPrefix(normalizedInput);\n const [providerId, ...modelParts] = normalizedModelId.split('/');\n const bareModelId = modelParts.join('/');\n if (!providerId || !bareModelId) {\n throw new Error(`Invalid model id: ${modelId}`);\n }\n\n // Deployed web registers a per-tenant credential store provider; when the\n // request carries an authenticated tenant, resolve credentials through the\n // caller's own store (user > org > env). Undefined = global AuthStorage.\n const tenantCredentialStore = resolveCredentialStore(options?.requestContext);\n const baseCredentialStore = tenantCredentialStore ?? getGlobalAuthStorage();\n\n if (providerId === AMAZON_BEDROCK_GATEWAY_ID) {\n // Bedrock authenticates through the server process's AWS credential chain,\n // never a tenant credential. A tenant store only lets it through when the\n // operator opted the deployment in.\n if (\n tenantCredentialStore?.allowEnvironmentFallback === false &&\n !tenantCredentialStore.allowsDeploymentCredentials?.(AMAZON_BEDROCK_GATEWAY_ID)\n ) {\n throw new ProviderAuthRequiredError(\n 'Amazon Bedrock is not enabled for this Factory deployment. The operator must provide AWS credentials to the server and set FACTORY_DEPLOYMENT_MODEL_PROVIDERS=amazon-bedrock.',\n );\n }\n const bedrockGateway = createAmazonBedrockGateway();\n const routerId = `${AMAZON_BEDROCK_GATEWAY_ID}/${bareModelId}`;\n const auth = bedrockGateway.resolveAuth({\n gatewayId: AMAZON_BEDROCK_GATEWAY_ID,\n providerId: AMAZON_BEDROCK_GATEWAY_ID,\n modelId: bareModelId,\n routerId,\n });\n return bedrockGateway.resolveLanguageModel({\n providerId: AMAZON_BEDROCK_GATEWAY_ID,\n modelId: bareModelId,\n apiKey: auth?.apiKey ?? '',\n headers,\n });\n }\n\n const routerId = `${MASTRACODE_GATEWAY_ID}/${normalizedModelId}`;\n\n const mgApiKey = MastraCodeGateway.getMastraGatewayApiKey();\n const rawGatewayBase =\n settings.memoryGateway?.baseUrl ?? process.env['MASTRA_GATEWAY_URL'] ?? 'https://gateway-api.mastra.ai';\n const credentialStore = createRequestScopedCredentialStore(baseCredentialStore, options?.requestContext);\n const gateway = createMastraCodeGateway({\n mastraGatewayBaseUrl: rawGatewayBase.replace(/\\/+$/, '').replace(/\\/v1$/, ''),\n mastraGatewayApiKey: mgApiKey,\n routeThroughMastraGateway: Boolean(mgApiKey && isMastraGatewayModel),\n thinkingLevel: options?.thinkingLevel,\n anthropicPromptCacheScope: options?.anthropicPromptCacheScope,\n customProviders,\n credentialStore,\n });\n\n const auth = gateway.resolveAuth({\n gatewayId: MASTRACODE_GATEWAY_ID,\n providerId,\n modelId: bareModelId,\n routerId,\n });\n\n if (!auth && credentialStore?.allowEnvironmentFallback === false) {\n throw new ProviderAuthRequiredError(\n `No usable ${providerId} credential is configured for this signed-in Factory account. Connect the provider or add an organization credential, then try again.`,\n );\n }\n\n return gateway.resolveLanguageModel({\n providerId,\n modelId: bareModelId,\n apiKey: auth?.apiKey ?? '',\n headers,\n });\n}\n\nexport interface ThinkingRequestContext {\n state?: { thinkingLevel?: unknown };\n session?: { modeId?: string };\n}\n/**\n * Resolve the effective thinking level for the current request.\n *\n * Precedence:\n * 1. Session override (`state.thinkingLevel`, set via /think or the session\n * settings panel).\n * 2. Per-mode default from settings (`models.modeThinkingDefaults[mode]`).\n * 3. Global default (`preferences.thinkingLevel`).\n *\n * Resolved per-request (not seeded at session start) so configuration changes\n * apply to the next request of every session — including automated\n * (rule-driven) Factory runs that nobody ever opens interactively.\n */\n\nexport function resolveRequestThinkingLevel(\n agentControllerContext: ThinkingRequestContext | undefined,\n settingsPath?: string,\n): ThinkingLevelSetting {\n const override = agentControllerContext?.state?.thinkingLevel;\n if (isThinkingLevelSetting(override)) return override;\n const modeId = agentControllerContext?.session?.modeId;\n return resolveDefaultThinkingLevel(loadSettings(settingsPath), modeId).level;\n}\n\n/**\n * Dynamic model function that reads the current model and optional ordered\n * fallback route from controller state. Route entry ids are opaque host-owned\n * identifiers; repeated ids receive occurrence suffixes because core tracks the\n * active fallback index by id across agentic steps.\n */\nexport function getDynamicModel(\n { requestContext }: { requestContext: RequestContext },\n settingsPath?: string,\n): ResolvedModel | ModelWithRetries[] {\n const controller = requestContext.get('controller') as AgentControllerRequestContext<any> | undefined;\n const state = controller?.getState?.() as\n | {\n modelRoute?: {\n entries?: Array<{ id?: unknown; modelId?: unknown }>;\n };\n mastracodePendingModelFallback?: { toEntryId?: unknown; toModelId?: unknown; threadId?: unknown } | null;\n }\n | undefined;\n const pendingState = state?.mastracodePendingModelFallback;\n const pendingFallback =\n pendingState &&\n (pendingState.threadId === undefined ||\n (typeof pendingState.threadId === 'string' && pendingState.threadId === controller?.threadId))\n ? pendingState\n : undefined;\n const pendingModelId =\n pendingFallback && typeof pendingFallback.toModelId === 'string' && pendingFallback.toModelId.length > 0\n ? pendingFallback.toModelId\n : undefined;\n const modelId = pendingModelId ?? controller?.session?.modelId;\n if (!modelId) {\n if (!controller) {\n throw new Error(\n 'No model available: this run started without a controller session context, so no model selection could be resolved.',\n );\n }\n throw new Error('No model selected. Use /models to select a model first.');\n }\n\n const thinkingLevel = resolveRequestThinkingLevel(controller, settingsPath);\n const resolveOptions = { thinkingLevel, remapForCodexOAuth: true, requestContext } as const;\n const primary = resolveModel(modelId, resolveOptions);\n const route = state?.modelRoute?.entries?.slice(0, MODEL_ROUTE_MAX_ENTRIES);\n const pendingEntryId =\n pendingFallback && typeof pendingFallback.toEntryId === 'string' ? pendingFallback.toEntryId : undefined;\n const startIndex = pendingEntryId ? route?.findIndex(entry => entry.id === pendingEntryId) : 0;\n const activeRoute = route && startIndex !== undefined && startIndex >= 0 ? route.slice(startIndex) : undefined;\n if (!activeRoute || activeRoute.length < 2 || activeRoute[0]?.modelId !== modelId) return primary;\n\n const firstId =\n typeof activeRoute[0]?.id === 'string' && activeRoute[0].id.length > 0 ? activeRoute[0].id : undefined;\n if (!firstId) return primary;\n\n const entries: ModelWithRetries[] = [{ id: firstId, model: primary }];\n const appearances = new Map<string, number>([[firstId, 1]]);\n for (const routeEntry of activeRoute.slice(1)) {\n if (\n typeof routeEntry.id !== 'string' ||\n routeEntry.id.length === 0 ||\n typeof routeEntry.modelId !== 'string' ||\n routeEntry.modelId.length === 0\n ) {\n break;\n }\n let entryModel: ResolvedModel;\n try {\n entryModel = resolveModel(routeEntry.modelId, resolveOptions);\n } catch {\n break;\n }\n const occurrence = (appearances.get(routeEntry.id) ?? 0) + 1;\n appearances.set(routeEntry.id, occurrence);\n entries.push({\n id: occurrence === 1 ? routeEntry.id : `${routeEntry.id}#${occurrence}`,\n model: entryModel,\n });\n }\n\n return entries.length < 2 ? primary : entries;\n}\n\n/**\n * Goal judge model resolver for the agent's `goal.judge` config. Resolves the\n * configured goal judge model through mastracode's gateway so provider\n * credentials (stored in auth storage, not just env) are injected — a bare model\n * id handed to core's default model router would fail to find the API key.\n *\n * Returns `undefined` when no judge model is configured, which keeps the goal\n * step a complete no-op (the goal mechanism requires a judge to do anything).\n *\n * `settingsPath` must be the same source `createMastraCode()` reads from so the\n * judge model and the goal budget (`goalMaxTurns`) come from one config — with a\n * custom `settingsPath` a bare `loadSettings()` here could read a different file\n * and silently turn the goal step into a no-op.\n */\nexport function getGoalJudgeModel(\n { requestContext }: { requestContext: RequestContext },\n settingsPath?: string,\n): ResolvedModel | undefined {\n const judgeModelId = loadSettings(settingsPath).models.goalJudgeModel;\n if (!judgeModelId) return undefined;\n return resolveModel(judgeModelId, { remapForCodexOAuth: true, requestContext });\n}\n"],"mappings":";;;;;;;;;;;AAsDA,SAAS,0BAA0B,gBAAkE;CACnG,MAAM,yBAAyB,gBAAgB,IAAI,YAAY;CAC/D,MAAM,UAAU;EACd,GAAI,wBAAwB,WAAW,EAAE,eAAe,uBAAuB,SAAS,IAAI,CAAC;EAC7F,GAAI,wBAAwB,aAAa,EAAE,iBAAiB,uBAAuB,WAAW,IAAI,CAAC;CACrG;CAEA,OAAO,OAAO,KAAK,OAAO,CAAC,CAAC,SAAS,IAAI,UAAU,KAAA;AACrD;AAEA,SAAS,kBAAkB,SAA6B;CACtD,MAAM,EAAE,MAAM,OAAO,IAAI,KAAK,OAAO,QAAQ,SAAS,UAAU,QAAQ,SAAS,GAAG,eAAe;CACnG,OAAO;EAAE,MAAM;EAAkB,GAAG;CAAW;AACjD;AAEA,SAAgB,mCACd,MACA,gBACiB;CACjB,MAAM,cAAc,eAAuB,2BAA2B,gBAAgB,UAAU;CAChG,MAAM,mBAAmB,eAAuB;EAC9C,MAAM,oBAAoB,WAAW,UAAU;EAC/C,OAAO,oBACH,KAAK,eAAe,UAAU,CAAC,CAAC,MAAK,YAAW,QAAQ,OAAO,iBAAiB,IAChF,KAAA;CACN;CAIA,MAAM,aAAa,eAAuB,iCAAiC,gBAAgB,UAAU;CAErG,OAAO;EACL,0BAA0B,KAAK;EAC/B,cAAc,KAAK,OAAO;EAC1B,MAAK,eAAc;GACjB,IAAI,UAAU,UAAU,GAAG,OAAO,KAAA;GAKlC,IAD0B,WAAW,UACjB,MAAM,KAAA,G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
|
34
34
|
forceRefreshActiveAccount?(providerId: string, accountInstanceId?: string): Promise<string | undefined>;
|
|
35
35
|
};
|
|
36
|
-
/** Persisted data-part type for a
|
|
37
|
-
export declare const
|
|
38
|
-
/**
|
|
39
|
-
|
|
40
|
-
* core's fallback array advances to, and why. Labels and pack ids only —
|
|
41
|
-
* never credential material.
|
|
42
|
-
*/
|
|
43
|
-
export interface PackFallbackPartData {
|
|
36
|
+
/** Persisted data-part type for a model-route hop. */
|
|
37
|
+
export declare const MODEL_FALLBACK_PART_TYPE: "data-mastracode-model-fallback";
|
|
38
|
+
/** Non-secret transcript payload for a model-route hop. */
|
|
39
|
+
export interface ModelFallbackPartData {
|
|
44
40
|
from: {
|
|
45
|
-
|
|
41
|
+
entryId: string;
|
|
46
42
|
label: string;
|
|
47
43
|
};
|
|
48
44
|
to: {
|
|
49
|
-
|
|
45
|
+
entryId: string;
|
|
50
46
|
label: string;
|
|
51
47
|
};
|
|
52
48
|
reason: 'pool-exhausted' | 'persistent-outage';
|
|
53
49
|
at: string;
|
|
54
50
|
}
|
|
55
|
-
/**
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
/** Payload written to session state under PACK_FALLBACK_STATE_KEY. */
|
|
62
|
-
export interface PendingPackFallback {
|
|
63
|
-
fromPackId: string;
|
|
64
|
-
toPackId: string;
|
|
65
|
-
/** Landed pack's model for the mode the cascade is serving. */
|
|
51
|
+
/** Session-state key set when account rotation advances the model route. */
|
|
52
|
+
export declare const MODEL_FALLBACK_STATE_KEY: "mastracodePendingModelFallback";
|
|
53
|
+
/** Payload written to session state under MODEL_FALLBACK_STATE_KEY. */
|
|
54
|
+
export interface PendingModelFallback {
|
|
55
|
+
fromEntryId: string;
|
|
56
|
+
toEntryId: string;
|
|
66
57
|
toModelId: string;
|
|
67
|
-
/** Originating thread. Absent only on pending hops written by older clients. */
|
|
68
58
|
threadId?: string;
|
|
69
59
|
reason: 'pool-exhausted' | 'persistent-outage';
|
|
70
60
|
at: string;
|
|
@@ -105,21 +95,16 @@ export declare function isAccountSwitchReason(value: unknown): value is AccountS
|
|
|
105
95
|
* history rendering of the persisted part — one formatter, identical text.
|
|
106
96
|
*/
|
|
107
97
|
export declare function accountSwitchNoticeText(data: AccountSwitchPartData): string;
|
|
108
|
-
/** Transcript line for a
|
|
109
|
-
export declare function
|
|
98
|
+
/** Transcript line for a model-route hop; shared by the live info event and the TUI's history render. */
|
|
99
|
+
export declare function modelFallbackNoticeText(data: ModelFallbackPartData): string;
|
|
110
100
|
/**
|
|
111
|
-
* Whether a persisted
|
|
101
|
+
* Whether a persisted model-fallback reason is one this build understands.
|
|
112
102
|
* `REASON_TEXT` also covers the account-switch reasons, so the notice text
|
|
113
103
|
* alone would happily render a foreign value such as `rate-limit` as a
|
|
114
|
-
*
|
|
104
|
+
* model-fallback reason; history parsed from another build's part must be
|
|
115
105
|
* rejected instead.
|
|
116
106
|
*/
|
|
117
|
-
export declare function
|
|
118
|
-
/**
|
|
119
|
-
* Controller-shaped accessors for a thread's routing metadata. Core supplies this
|
|
120
|
-
* via `requestContext.get('controller')`; the TUI builds the same shape from its
|
|
121
|
-
* session so both writers share one serialization key and one read source.
|
|
122
|
-
*/
|
|
107
|
+
export declare function isModelFallbackReason(value: unknown): value is ModelFallbackPartData['reason'];
|
|
123
108
|
export type RoutingControllerContext = {
|
|
124
109
|
session?: {
|
|
125
110
|
modelId?: unknown;
|
|
@@ -147,20 +132,15 @@ export declare class AccountRotationProcessor implements Processor {
|
|
|
147
132
|
retry: boolean;
|
|
148
133
|
}>;
|
|
149
134
|
/**
|
|
150
|
-
*
|
|
151
|
-
*
|
|
152
|
-
*
|
|
153
|
-
* cascade never promises a hop core's fallback array cannot make. The
|
|
154
|
-
* position advances per hop, so a second hop in the same turn reports B→C
|
|
155
|
-
* even though the session modelId still points at pack A (stickiness lands
|
|
156
|
-
* TUI-side only after the part renders). Returns null when the session has
|
|
157
|
-
* no active pack or the pack has no fallback chain.
|
|
135
|
+
* Resolve the request's host-supplied model route once and cache the reachable
|
|
136
|
+
* prefix in processor state. Resolution mirrors getDynamicModel so a hop is
|
|
137
|
+
* never announced for an entry core cannot reach.
|
|
158
138
|
*/
|
|
159
|
-
private
|
|
139
|
+
private getModelRouteCascade;
|
|
160
140
|
/**
|
|
161
|
-
* Q14 gate: 400/unknown/unattributable errors never
|
|
141
|
+
* Q14 gate: 400/unknown/unattributable errors never advance routes. Core's
|
|
162
142
|
* fallback array advances on ANY thrown error except TripWire
|
|
163
|
-
* (llm-execution-step.ts), so when the session
|
|
143
|
+
* (llm-execution-step.ts), so when the session route has another entry and the
|
|
164
144
|
* current entry is non-last, a bare `retry: false` would silently hop on an
|
|
165
145
|
* error class the user excluded from hop triggers. TripWire is the only
|
|
166
146
|
* no-advance escape: the runner rethrows it and the fallback loop declines
|
|
@@ -168,19 +148,12 @@ export declare class AccountRotationProcessor implements Processor {
|
|
|
168
148
|
* plain `retry: false` surface the error exactly as before.
|
|
169
149
|
*/
|
|
170
150
|
private gateChainHop;
|
|
171
|
-
/**
|
|
172
|
-
|
|
173
|
-
* queue the thread stickiness trigger. Core's fallback array does the hop
|
|
174
|
-
* itself on `retry: false`; this only announces it. The cascade is
|
|
175
|
-
* truncated exactly like getDynamicModel's chain (missing mode model or
|
|
176
|
-
* unresolvable model), so an announced hop is always one core can make;
|
|
177
|
-
* the toModelId guard stays as defense against a stale cache.
|
|
178
|
-
*/
|
|
179
|
-
private emitPackFallbackPart;
|
|
151
|
+
/** Announce and persist the next model-route hop before core advances. */
|
|
152
|
+
private emitModelFallbackPart;
|
|
180
153
|
/**
|
|
181
154
|
* Pool done for this request: every instance recorded in the tried-set and
|
|
182
155
|
* a `to: null` part emitted. Returns `retry: false` so core's fallback
|
|
183
|
-
* array can hop to the next
|
|
156
|
+
* array can hop to the next route entry (announced by `emitModelFallbackPart`).
|
|
184
157
|
* Silent on the account part when the provider has no registry at all —
|
|
185
158
|
* there are no accounts to declare unavailable, but the hop still applies.
|
|
186
159
|
*/
|
|
@@ -200,7 +173,6 @@ export declare class AccountStartNoticeProcessor implements Processor {
|
|
|
200
173
|
readonly id: "mastracode-account-start-notice";
|
|
201
174
|
constructor(options: {
|
|
202
175
|
credentialStore: CredentialStore;
|
|
203
|
-
settingsPath?: string;
|
|
204
176
|
});
|
|
205
177
|
processInput(args: ProcessInputArgs): Promise<ProcessInputResult>;
|
|
206
178
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"account-rotation-processor.d.ts","sourceRoot":"","sources":["../../src/auth/account-rotation-processor.ts"],"names":[],"mappings":"AAsBA,OAAO,KAAK,EAAE,mBAAmB,EAAE,gBAAgB,EAAE,kBAAkB,EAAE,SAAS,EAAE,MAAM,yBAAyB,CAAC;
|
|
1
|
+
{"version":3,"file":"account-rotation-processor.d.ts","sourceRoot":"","sources":["../../src/auth/account-rotation-processor.ts"],"names":[],"mappings":"AAsBA,OAAO,KAAK,EAAE,mBAAmB,EAAE,gBAAgB,EAAE,kBAAkB,EAAE,SAAS,EAAE,MAAM,yBAAyB,CAAC;AAYpH,OAAO,KAAK,EAAE,eAAe,EAAsB,MAAM,YAAY,CAAC;AAEtE,eAAO,MAAM,wBAAwB,mCAAmC,CAAC;AAEzE,yEAAyE;AACzE,MAAM,WAAW,qBAAqB;IACpC,QAAQ,EAAE,MAAM,CAAC;IACjB,IAAI,EAAE;QAAE,EAAE,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,GAAG,IAAI,CAAC;IAC3C,EAAE,EAAE;QAAE,EAAE,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,GAAG,IAAI,CAAC;IACzC,MAAM,EACF,YAAY,GACZ,iBAAiB,GACjB,aAAa,GACb,gBAAgB,GAChB,mBAAmB,GACnB,mBAAmB,GACnB,qBAAqB,CAAC;IAC1B,EAAE,EAAE,MAAM,CAAC;IACX;;;;;OAKG;IACH,SAAS,CAAC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