@mastra/code-sdk 1.15.1-alpha.0 → 1.15.1-alpha.2
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/model.js +1 -1
- package/dist/agents/model.js.map +1 -1
- package/package.json +12 -12
package/dist/agents/model.js
CHANGED
|
@@ -161,7 +161,7 @@ function resolveModelForRequest(modelId, options) {
|
|
|
161
161
|
modelId: bareModelId,
|
|
162
162
|
routerId
|
|
163
163
|
});
|
|
164
|
-
if (!auth && credentialStore?.allowEnvironmentFallback === false) throw new ProviderAuthRequiredError(resolveCredentialScope(options?.requestContext) === "factory" ? `No usable ${providerId} credential is available. This Factory uses organization credentials only, so personal provider sign-ins don't apply. Add an organization credential, then try again.` : `No usable ${providerId} credential is available. This Factory uses personal credentials only, so organization credentials don't apply. Connect the provider, then try again.`);
|
|
164
|
+
if (!auth && credentialStore?.allowEnvironmentFallback === false) throw new ProviderAuthRequiredError(resolveCredentialScope(options?.requestContext) === "factory" ? `No usable ${providerId} credential is available for ${normalizedModelId}. This Factory uses organization credentials only, so personal provider sign-ins don't apply. Add an organization credential, then try again.` : `No usable ${providerId} credential is available for ${normalizedModelId}. This Factory uses personal credentials only, so organization credentials don't apply. Connect the provider, then try again.`);
|
|
165
165
|
return gateway.resolveLanguageModel({
|
|
166
166
|
providerId,
|
|
167
167
|
modelId: bareModelId,
|
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 { ModelRouterLanguageModel } from '@mastra/core/llm';\nimport type { GatewayLanguageModel, IdentifiedModelConfig, MastraModelGatewayInterface } from '@mastra/core/llm';\nimport { 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 { toMemoryModelId } from '../onboarding/packs.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 { normalizeLegacyModelId } from '../providers/model-ids.js';\nimport { isThinkingLevelSetting } from '../thinking.js';\nimport type { ThinkingLevelSetting } from '../thinking.js';\nimport {\n hasCredentialTenantResolver,\n prepareCredentialTenant,\n resolveCredentialScope,\n resolveCredentialStore,\n} 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 hasProviderEnvironmentKey,\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 | ModelRouterLanguageModel;\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): ResolvedModel {\n if (!hasCredentialTenantResolver()) return resolveModelForRequest(modelId, options);\n const createRequestModel = () => {\n const requestContext = options?.requestContext ? new RequestContext(options.requestContext.entries()) : undefined;\n // The router supplies stable SDK metadata and adapts whichever provider the refreshed policy selects.\n // Each invocation owns its policy context and model cache, including concurrent OM and subagent calls.\n return new ModelRouterLanguageModel({ id: `${MASTRACODE_GATEWAY_ID}/${modelId}` }, [\n {\n id: MASTRACODE_GATEWAY_ID,\n name: 'Request-scoped MastraCode',\n fetchProviders: async () => ({}),\n buildUrl: () => undefined,\n getApiKey: async () => '',\n resolveAuth: () => ({ apiKey: 'request-scoped' }),\n resolveLanguageModel: async () => {\n await prepareCredentialTenant(requestContext);\n return resolveModelForRequest(modelId, { ...options, requestContext });\n },\n },\n ]);\n };\n let currentModel = createRequestModel();\n return new Proxy(currentModel, {\n get(_target, property) {\n if (property === 'supportedUrls') return createRequestModel().supportedUrls;\n if (property === 'doStream' || property === 'doGenerate') {\n return async (...args: unknown[]) => {\n const refreshed = createRequestModel();\n currentModel = refreshed;\n return Reflect.apply(Reflect.get(refreshed, property), refreshed, args);\n };\n }\n const value = Reflect.get(currentModel, property, currentModel);\n return typeof value === 'function' ? value.bind(currentModel) : value;\n },\n });\n}\n\nfunction resolveModelForRequest(modelId: string, options?: Parameters<typeof resolveModel>[1]): GatewayLanguageModel {\n reloadAuthStorage();\n const headers = getAgentControllerHeaders(options?.requestContext);\n const settings = loadSettings();\n // Older versions cataloged Bedrock, Copilot and Kimi under the MastraCode\n // gateway namespace, and Kimi under its own `kimi-for-coding` provider. Map\n // already-saved ids (packs, OM settings, thread metadata) to current ids.\n const legacyNormalizedInput = normalizeLegacyModelId(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(legacyNormalizedInput, 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 hosts resolve exactly the trusted policy's credential scope.\n // Only local mode falls back to 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 // Scopes are exclusive, so name the one in effect: otherwise a user with a\n // personal sign-in can't tell why an organization-scoped Factory fails.\n throw new ProviderAuthRequiredError(\n resolveCredentialScope(options?.requestContext) === 'factory'\n ? `No usable ${providerId} credential is available. This Factory uses organization credentials only, so personal provider sign-ins don't apply. Add an organization credential, then try again.`\n : `No usable ${providerId} credential is available. This Factory uses personal credentials only, so organization credentials don't apply. Connect the provider, then try again.`,\n );\n }\n\n return gateway.resolveLanguageModel({\n providerId,\n modelId: bareModelId,\n apiKey: auth?.apiKey ?? '',\n headers,\n });\n}\n\n/**\n * Whether `resolveModel` can authenticate a provider for this request, using the\n * same credential lookup: the tenant store in deployed Factory (no environment\n * keys), otherwise local auth and then the provider's environment keys.\n */\nexport function canUseProvider(providerId: string, options?: { requestContext?: RequestContext }): boolean {\n reloadAuthStorage();\n const baseCredentialStore = resolveCredentialStore(options?.requestContext) ?? getGlobalAuthStorage();\n const credentialStore = createRequestScopedCredentialStore(baseCredentialStore, options?.requestContext);\n const gateway = createMastraCodeGateway({\n mastraGatewayBaseUrl: '',\n routeThroughMastraGateway: false,\n customProviders: resolveCustomProviders(options?.requestContext) ?? loadSettings().customProviders,\n credentialStore,\n });\n const auth = gateway.resolveAuth({\n gatewayId: MASTRACODE_GATEWAY_ID,\n providerId,\n modelId: '',\n routerId: `${MASTRACODE_GATEWAY_ID}/${providerId}`,\n });\n if (auth) return true;\n // resolveModel lets the models.dev gateway read environment keys only when the store allows it.\n return credentialStore.allowEnvironmentFallback !== false && hasProviderEnvironmentKey(providerId);\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. The host's default for this request (`hostDefault`), when the host\n * stores thinking defaults itself (the Factory keeps one per Factory).\n * 3. Per-mode default from settings (`models.modeThinkingDefaults[mode]`),\n * only when the context carries a session mode.\n * 4. 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 */\nexport function resolveRequestThinkingLevel(\n agentControllerContext: ThinkingRequestContext | undefined,\n settingsPath?: string,\n hostDefault?: ThinkingLevelSetting,\n): ThinkingLevelSetting {\n const override = agentControllerContext?.state?.thinkingLevel;\n if (isThinkingLevelSetting(override)) return override;\n if (hostDefault) return hostDefault;\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 { modeless = false, defaultThinkingLevel }: { modeless?: boolean; defaultThinkingLevel?: ThinkingLevelSetting } = {},\n): IdentifiedModelConfig | 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(\n modeless ? { state: controller?.state } : controller,\n settingsPath,\n defaultThinkingLevel,\n );\n const resolveOptions = { thinkingLevel, remapForCodexOAuth: true, requestContext } as const;\n // Label each resolved model with its full ID: the resolved gateway model only\n // knows its bare provider model, and Memory's `'auto'` reads this label.\n const primary = identifyModel(modelId, 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: identifyModel(routeEntry.modelId, entryModel),\n });\n }\n\n return entries.length < 2 ? primary : entries;\n}\n\nfunction identifyModel(modelId: string, model: ResolvedModel): IdentifiedModelConfig {\n return { model, id: toMemoryModelId(modelId) };\n}\n\ntype MemoryRouteState = {\n modelRoute?: { entries?: Array<{ id?: unknown; memoryModelId?: unknown }> };\n mastracodePendingModelFallback?: { toEntryId?: unknown; threadId?: unknown } | null;\n};\n\n/**\n * The active model route for memory: the session route, starting at a pending\n * fallback hop captured for this thread.\n */\nexport function getActiveMemoryRoute<TEntry extends { id?: unknown; memoryModelId?: unknown }>(\n state:\n | {\n modelRoute?: { entries?: TEntry[] };\n mastracodePendingModelFallback?: MemoryRouteState['mastracodePendingModelFallback'];\n }\n | undefined,\n threadId?: string | null,\n): TEntry[] {\n const pending = state?.mastracodePendingModelFallback;\n const sameThreadPending =\n pending && (pending.threadId === undefined || pending.threadId === threadId) ? pending : undefined;\n const routeEntries = state?.modelRoute?.entries?.slice(0, MODEL_ROUTE_MAX_ENTRIES) ?? [];\n const pendingIndex = sameThreadPending\n ? routeEntries.findIndex(entry => entry.id === sameThreadPending.toEntryId)\n : -1;\n return pendingIndex >= 0 ? routeEntries.slice(pendingIndex) : routeEntries;\n}\n\n/**\n * The memory model the active route applies to both OM roles: `'auto'`, the\n * first concrete memory model, or `undefined` when the route sets none (both\n * roles then follow their `/om` settings).\n */\nexport function getActiveRouteMemoryModelId(\n state: Readonly<Record<string, unknown>> | undefined,\n threadId?: string | null,\n): string | undefined {\n const route = getActiveMemoryRoute(state as MemoryRouteState | undefined, threadId);\n if (route[0]?.memoryModelId === 'auto') return 'auto';\n const entry = route.find(\n candidate =>\n typeof candidate.memoryModelId === 'string' && candidate.memoryModelId && candidate.memoryModelId !== 'auto',\n );\n return entry?.memoryModelId as string | undefined;\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":";;;;;;;;;;;;;;AA+DA,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;C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F"}
|
|
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 { ModelRouterLanguageModel } from '@mastra/core/llm';\nimport type { GatewayLanguageModel, IdentifiedModelConfig, MastraModelGatewayInterface } from '@mastra/core/llm';\nimport { 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 { toMemoryModelId } from '../onboarding/packs.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 { normalizeLegacyModelId } from '../providers/model-ids.js';\nimport { isThinkingLevelSetting } from '../thinking.js';\nimport type { ThinkingLevelSetting } from '../thinking.js';\nimport {\n hasCredentialTenantResolver,\n prepareCredentialTenant,\n resolveCredentialScope,\n resolveCredentialStore,\n} 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 hasProviderEnvironmentKey,\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 | ModelRouterLanguageModel;\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): ResolvedModel {\n if (!hasCredentialTenantResolver()) return resolveModelForRequest(modelId, options);\n const createRequestModel = () => {\n const requestContext = options?.requestContext ? new RequestContext(options.requestContext.entries()) : undefined;\n // The router supplies stable SDK metadata and adapts whichever provider the refreshed policy selects.\n // Each invocation owns its policy context and model cache, including concurrent OM and subagent calls.\n return new ModelRouterLanguageModel({ id: `${MASTRACODE_GATEWAY_ID}/${modelId}` }, [\n {\n id: MASTRACODE_GATEWAY_ID,\n name: 'Request-scoped MastraCode',\n fetchProviders: async () => ({}),\n buildUrl: () => undefined,\n getApiKey: async () => '',\n resolveAuth: () => ({ apiKey: 'request-scoped' }),\n resolveLanguageModel: async () => {\n await prepareCredentialTenant(requestContext);\n return resolveModelForRequest(modelId, { ...options, requestContext });\n },\n },\n ]);\n };\n let currentModel = createRequestModel();\n return new Proxy(currentModel, {\n get(_target, property) {\n if (property === 'supportedUrls') return createRequestModel().supportedUrls;\n if (property === 'doStream' || property === 'doGenerate') {\n return async (...args: unknown[]) => {\n const refreshed = createRequestModel();\n currentModel = refreshed;\n return Reflect.apply(Reflect.get(refreshed, property), refreshed, args);\n };\n }\n const value = Reflect.get(currentModel, property, currentModel);\n return typeof value === 'function' ? value.bind(currentModel) : value;\n },\n });\n}\n\nfunction resolveModelForRequest(modelId: string, options?: Parameters<typeof resolveModel>[1]): GatewayLanguageModel {\n reloadAuthStorage();\n const headers = getAgentControllerHeaders(options?.requestContext);\n const settings = loadSettings();\n // Older versions cataloged Bedrock, Copilot and Kimi under the MastraCode\n // gateway namespace, and Kimi under its own `kimi-for-coding` provider. Map\n // already-saved ids (packs, OM settings, thread metadata) to current ids.\n const legacyNormalizedInput = normalizeLegacyModelId(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(legacyNormalizedInput, 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 hosts resolve exactly the trusted policy's credential scope.\n // Only local mode falls back to 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 // Scopes are exclusive, so name the one in effect: otherwise a user with a\n // personal sign-in can't tell why an organization-scoped Factory fails.\n throw new ProviderAuthRequiredError(\n resolveCredentialScope(options?.requestContext) === 'factory'\n ? `No usable ${providerId} credential is available for ${normalizedModelId}. This Factory uses organization credentials only, so personal provider sign-ins don't apply. Add an organization credential, then try again.`\n : `No usable ${providerId} credential is available for ${normalizedModelId}. This Factory uses personal credentials only, so organization credentials don't apply. Connect the provider, then try again.`,\n );\n }\n\n return gateway.resolveLanguageModel({\n providerId,\n modelId: bareModelId,\n apiKey: auth?.apiKey ?? '',\n headers,\n });\n}\n\n/**\n * Whether `resolveModel` can authenticate a provider for this request, using the\n * same credential lookup: the tenant store in deployed Factory (no environment\n * keys), otherwise local auth and then the provider's environment keys.\n */\nexport function canUseProvider(providerId: string, options?: { requestContext?: RequestContext }): boolean {\n reloadAuthStorage();\n const baseCredentialStore = resolveCredentialStore(options?.requestContext) ?? getGlobalAuthStorage();\n const credentialStore = createRequestScopedCredentialStore(baseCredentialStore, options?.requestContext);\n const gateway = createMastraCodeGateway({\n mastraGatewayBaseUrl: '',\n routeThroughMastraGateway: false,\n customProviders: resolveCustomProviders(options?.requestContext) ?? loadSettings().customProviders,\n credentialStore,\n });\n const auth = gateway.resolveAuth({\n gatewayId: MASTRACODE_GATEWAY_ID,\n providerId,\n modelId: '',\n routerId: `${MASTRACODE_GATEWAY_ID}/${providerId}`,\n });\n if (auth) return true;\n // resolveModel lets the models.dev gateway read environment keys only when the store allows it.\n return credentialStore.allowEnvironmentFallback !== false && hasProviderEnvironmentKey(providerId);\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. The host's default for this request (`hostDefault`), when the host\n * stores thinking defaults itself (the Factory keeps one per Factory).\n * 3. Per-mode default from settings (`models.modeThinkingDefaults[mode]`),\n * only when the context carries a session mode.\n * 4. 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 */\nexport function resolveRequestThinkingLevel(\n agentControllerContext: ThinkingRequestContext | undefined,\n settingsPath?: string,\n hostDefault?: ThinkingLevelSetting,\n): ThinkingLevelSetting {\n const override = agentControllerContext?.state?.thinkingLevel;\n if (isThinkingLevelSetting(override)) return override;\n if (hostDefault) return hostDefault;\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 { modeless = false, defaultThinkingLevel }: { modeless?: boolean; defaultThinkingLevel?: ThinkingLevelSetting } = {},\n): IdentifiedModelConfig | 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(\n modeless ? { state: controller?.state } : controller,\n settingsPath,\n defaultThinkingLevel,\n );\n const resolveOptions = { thinkingLevel, remapForCodexOAuth: true, requestContext } as const;\n // Label each resolved model with its full ID: the resolved gateway model only\n // knows its bare provider model, and Memory's `'auto'` reads this label.\n const primary = identifyModel(modelId, 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: identifyModel(routeEntry.modelId, entryModel),\n });\n }\n\n return entries.length < 2 ? primary : entries;\n}\n\nfunction identifyModel(modelId: string, model: ResolvedModel): IdentifiedModelConfig {\n return { model, id: toMemoryModelId(modelId) };\n}\n\ntype MemoryRouteState = {\n modelRoute?: { entries?: Array<{ id?: unknown; memoryModelId?: unknown }> };\n mastracodePendingModelFallback?: { toEntryId?: unknown; threadId?: unknown } | null;\n};\n\n/**\n * The active model route for memory: the session route, starting at a pending\n * fallback hop captured for this thread.\n */\nexport function getActiveMemoryRoute<TEntry extends { id?: unknown; memoryModelId?: unknown }>(\n state:\n | {\n modelRoute?: { entries?: TEntry[] };\n mastracodePendingModelFallback?: MemoryRouteState['mastracodePendingModelFallback'];\n }\n | undefined,\n threadId?: string | null,\n): TEntry[] {\n const pending = state?.mastracodePendingModelFallback;\n const sameThreadPending =\n pending && (pending.threadId === undefined || pending.threadId === threadId) ? pending : undefined;\n const routeEntries = state?.modelRoute?.entries?.slice(0, MODEL_ROUTE_MAX_ENTRIES) ?? [];\n const pendingIndex = sameThreadPending\n ? routeEntries.findIndex(entry => entry.id === sameThreadPending.toEntryId)\n : -1;\n return pendingIndex >= 0 ? routeEntries.slice(pendingIndex) : routeEntries;\n}\n\n/**\n * The memory model the active route applies to both OM roles: `'auto'`, the\n * first concrete memory model, or `undefined` when the route sets none (both\n * roles then follow their `/om` settings).\n */\nexport function getActiveRouteMemoryModelId(\n state: Readonly<Record<string, unknown>> | undefined,\n threadId?: string | null,\n): string | undefined {\n const route = getActiveMemoryRoute(state as MemoryRouteState | undefined, threadId);\n if (route[0]?.memoryModelId === 'auto') return 'auto';\n const entry = route.find(\n candidate =>\n typeof candidate.memoryModelId === 'string' && candidate.memoryModelId && candidate.memoryModelId !== 'auto',\n );\n return entry?.memoryModelId as string | undefined;\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":";;;;;;;;;;;;;;AA+DA,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,uBA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AqB,OAAuC,QAAQ;CAClF,IAAI,MAAM,EAAE,EAAE,kBAAkB,QAAQ,OAAO;CAK/C,OAJc,MAAM,MAClB,cACE,OAAO,UAAU,kBAAkB,YAAY,UAAU,iBAAiB,UAAU,kBAAkB,MAE/F,CAAC,EAAE;AAChB;;;;;;;;;;;;;;;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"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mastra/code-sdk",
|
|
3
|
-
"version": "1.15.1-alpha.
|
|
3
|
+
"version": "1.15.1-alpha.2",
|
|
4
4
|
"description": "Mastra Code SDK: the agent core behind Mastra Code (everything except the TUI) — build your own UIs and surfaces on top of it",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"publishConfig": {
|
|
@@ -62,21 +62,21 @@
|
|
|
62
62
|
"vscode-languageserver-protocol": "^3.18.4",
|
|
63
63
|
"yaml": "^2.7.1",
|
|
64
64
|
"zod": "^4.6.7",
|
|
65
|
+
"@mastra/client-js": "1.57.0-alpha.2",
|
|
65
66
|
"@mastra/agent-browser": "0.5.4",
|
|
66
|
-
"@mastra/client-js": "1.57.0-alpha.0",
|
|
67
67
|
"@mastra/duckdb": "1.16.0-alpha.0",
|
|
68
|
+
"@mastra/core": "1.80.0-alpha.2",
|
|
68
69
|
"@mastra/github-signals": "0.5.2",
|
|
69
|
-
"@mastra/
|
|
70
|
-
"@mastra/fastembed": "1.3.5-alpha.0",
|
|
71
|
-
"@mastra/core": "1.80.0-alpha.0",
|
|
72
|
-
"@mastra/observability": "1.21.1-alpha.0",
|
|
70
|
+
"@mastra/fastembed": "1.3.5-alpha.1",
|
|
73
71
|
"@mastra/mcp": "2.6.0-alpha.0",
|
|
72
|
+
"@mastra/libsql": "1.27.0",
|
|
74
73
|
"@mastra/memory": "1.39.1-alpha.0",
|
|
75
|
-
"@mastra/
|
|
74
|
+
"@mastra/observability": "1.21.1-alpha.1",
|
|
76
75
|
"@mastra/parallel": "0.1.3",
|
|
76
|
+
"@mastra/pg": "1.33.0-alpha.1",
|
|
77
|
+
"@mastra/stagehand": "0.3.7-alpha.0",
|
|
77
78
|
"@mastra/tavily": "1.1.3",
|
|
78
|
-
"@mastra/schema-compat": "1.3.16"
|
|
79
|
-
"@mastra/stagehand": "0.3.7-alpha.0"
|
|
79
|
+
"@mastra/schema-compat": "1.3.16"
|
|
80
80
|
},
|
|
81
81
|
"devDependencies": {
|
|
82
82
|
"@copilotkit/aimock": "^1.29.0",
|
|
@@ -85,10 +85,10 @@
|
|
|
85
85
|
"tsdown": "0.23.1",
|
|
86
86
|
"tsx": "^4.23.1",
|
|
87
87
|
"typescript": "^6.0.3",
|
|
88
|
-
"vitest": "4.1.
|
|
88
|
+
"vitest": "4.1.12",
|
|
89
89
|
"@internal/lint": "0.0.145",
|
|
90
|
-
"@internal/
|
|
91
|
-
"@internal/
|
|
90
|
+
"@internal/workspace-test-utils": "0.0.89",
|
|
91
|
+
"@internal/types-builder": "0.0.120"
|
|
92
92
|
},
|
|
93
93
|
"engines": {
|
|
94
94
|
"node": ">=22.19.0"
|