@mastra/code-sdk 1.18.0-alpha.1 → 1.18.0-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.
@@ -1 +1 @@
1
- {"version":3,"file":"model.d.ts","sourceRoot":"","sources":["../../src/agents/model.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAE3D,OAAO,EAAE,wBAAwB,EAAE,MAAM,kBAAkB,CAAC;AAC5D,OAAO,KAAK,EAAE,oBAAoB,EAAE,qBAAqB,EAAE,2BAA2B,EAAE,MAAM,kBAAkB,CAAC;AACjH,OAAO,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAG9D,OAAO,KAAK,EAAE,eAAe,EAAsB,MAAM,kBAAkB,CAAC;AAS5E,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,wCAAwC,CAAC;AAGxF,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAC;AAQ3D,OAAO,EAGL,iBAAiB,EAKlB,MAAM,yBAAyB,CAAC;AACjC,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,yBAAyB,CAAC;AAExE,OAAO,EACL,kBAAkB,EAClB,eAAe,EACf,qBAAqB,EACrB,iBAAiB,EACjB,6BAA6B,EAC7B,WAAW,GACZ,MAAM,yBAAyB,CAAC;AACjC,YAAY,EAAE,wBAAwB,EAAE,wBAAwB,EAAE,MAAM,yBAAyB,CAAC;AAClG,OAAO,EACL,0BAA0B,EAC1B,0BAA0B,EAC1B,+BAA+B,GAChC,MAAM,0BAA0B,CAAC;AAClC,YAAY,EAAE,gBAAgB,EAAE,uBAAuB,EAAE,MAAM,0BAA0B,CAAC;AAC1F,OAAO,EACL,wBAAwB,EACxB,wBAAwB,EACxB,sBAAsB,GACvB,MAAM,6BAA6B,CAAC;AACrC,YAAY,EAAE,qBAAqB,EAAE,MAAM,6BAA6B,CAAC;AA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redentialStoreProvider, hasCredentialTenantResolver, prepareCredentialTenant, resolveCredentialScope, resolveCredentialStore, resolveTenantFromRequestContext, setCredentialStoreProvider } from "./credential-resolver.js";
8
8
  import { getRequestAccountSelection, isRequestAccountRoutingExhausted } from "../auth/account-routing-context.js";
9
9
  import { AMAZON_BEDROCK_GATEWAY_ID, createAmazonBedrockGateway } from "../providers/amazon-bedrock-gateway.js";
10
+ import { GOOGLE_VERTEX_GATEWAY_ID, createGoogleVertexGateway } from "../providers/google-vertex-gateway.js";
10
11
  import { hasCustomProvidersSource, resolveCustomProviders, setCustomProvidersSource } from "./custom-provider-source.js";
11
12
  import { MASTRACODE_GATEWAY_ID, MastraCodeGateway, getAnthropicApiKey, getGlobalAuthStorage, getOpenAIApiKey, hasProviderEnvironmentKey, reloadAuthStorage, resolveAuth } from "./mastracode-gateway.js";
12
13
  import { ModelRouterLanguageModel } from "@mastra/core/llm";
@@ -142,6 +143,23 @@ function resolveModelForRequest(modelId, options) {
142
143
  headers
143
144
  });
144
145
  }
146
+ if (providerId === "google-vertex") {
147
+ if (tenantCredentialStore?.allowEnvironmentFallback === false && !tenantCredentialStore.allowsDeploymentCredentials?.("google-vertex")) throw new ProviderAuthRequiredError("Google Vertex AI is not enabled for this Factory deployment. The operator must configure Application Default Credentials, GOOGLE_VERTEX_PROJECT, GOOGLE_VERTEX_LOCATION, and FACTORY_DEPLOYMENT_MODEL_PROVIDERS=google-vertex.");
148
+ const vertexGateway = createGoogleVertexGateway();
149
+ const auth = vertexGateway.resolveAuth({
150
+ gatewayId: GOOGLE_VERTEX_GATEWAY_ID,
151
+ providerId: GOOGLE_VERTEX_GATEWAY_ID,
152
+ modelId: bareModelId,
153
+ routerId: normalizedModelId
154
+ });
155
+ if (!auth) throw new Error("Google Vertex ADC requires GOOGLE_VERTEX_PROJECT and GOOGLE_VERTEX_LOCATION. Configure Application Default Credentials in the deployment environment.");
156
+ return vertexGateway.resolveLanguageModel({
157
+ providerId: GOOGLE_VERTEX_GATEWAY_ID,
158
+ modelId: bareModelId,
159
+ apiKey: auth.apiKey ?? "",
160
+ headers
161
+ });
162
+ }
145
163
  const routerId = `${MASTRACODE_GATEWAY_ID}/${normalizedModelId}`;
146
164
  const mgApiKey = MastraCodeGateway.getMastraGatewayApiKey();
147
165
  const rawGatewayBase = settings.memoryGateway?.baseUrl ?? process.env["MASTRA_GATEWAY_URL"] ?? "https://gateway-api.mastra.ai";
@@ -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 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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AA;CAC3F,MAAM,eAAe,OAAO,YAAY,SAAS,MAAM,GAAA,EAA0B,KAAK,CAAC;CACvF,MAAM,eAAe,oBACjB,aAAa,WAAU,UAAS,MAAM,OAAO,kBAAkB,SAAS,IACxE;CACJ,OAAO,gBAAgB,IAAI,aAAa,MAAM,YAAY,IAAI;AAChE;;;;;;AAOA,SAAgB,4BACd,OACA,UACoB;CACpB,MAAM,QAAQ,qBAAqB,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"}
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 { GOOGLE_VERTEX_GATEWAY_ID, createGoogleVertexGateway } from '../providers/google-vertex-gateway.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 if (providerId === GOOGLE_VERTEX_GATEWAY_ID) {\n if (\n tenantCredentialStore?.allowEnvironmentFallback === false &&\n !tenantCredentialStore.allowsDeploymentCredentials?.(GOOGLE_VERTEX_GATEWAY_ID)\n ) {\n throw new ProviderAuthRequiredError(\n 'Google Vertex AI is not enabled for this Factory deployment. The operator must configure Application Default Credentials, GOOGLE_VERTEX_PROJECT, GOOGLE_VERTEX_LOCATION, and FACTORY_DEPLOYMENT_MODEL_PROVIDERS=google-vertex.',\n );\n }\n\n const vertexGateway = createGoogleVertexGateway();\n const auth = vertexGateway.resolveAuth({\n gatewayId: GOOGLE_VERTEX_GATEWAY_ID,\n providerId: GOOGLE_VERTEX_GATEWAY_ID,\n modelId: bareModelId,\n routerId: normalizedModelId,\n });\n if (!auth) {\n throw new Error(\n 'Google Vertex ADC requires GOOGLE_VERTEX_PROJECT and GOOGLE_VERTEX_LOCATION. Configure Application Default Credentials in the deployment environment.',\n );\n }\n\n return vertexGateway.resolveLanguageModel({\n providerId: GOOGLE_VERTEX_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":";;;;;;;;;;;;;;;AAgEA,SAAS,0BA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G,SAAS;YAAU,MAAM;cAAY,OAAO;GAM9F;AAED,2FAA2F;AAC3F,wBAAgB,eAAe,IAAI,MAAM,CAmBxC"}
@@ -169,6 +169,12 @@ const FLAGS = [
169
169
  short: "h",
170
170
  type: "boolean",
171
171
  help: "Show this help and exit"
172
+ },
173
+ {
174
+ key: "version",
175
+ short: "v",
176
+ type: "boolean",
177
+ help: "Print the Mastra Code version and exit"
172
178
  }
173
179
  ];
174
180
  /** `parseArgs` option config derived from {@link FLAGS}. */
@@ -1 +1 @@
1
- {"version":3,"file":"flags.js","names":[],"sources":["../../src/headless/flags.ts"],"sourcesContent":["/**\n * Declarative flag specification for the headless CLI.\n *\n * A single table is the source of truth for three things that previously drifted\n * apart in `cli.ts`:\n * 1. the `node:util` `parseArgs` option config,\n * 2. per-flag value coercion + validation, and\n * 3. the `--help` usage text.\n *\n * Adding a flag means adding one row here; parsing, validation, and the usage\n * listing all follow automatically.\n */\nimport type { OutputMode } from './cli.js';\nimport type { PermissionMode, RunMode, ThinkingLevel } from './types.js';\nimport { VALID_MODES, VALID_PERMISSION_MODES, VALID_THINKING_LEVELS } from './types.js';\n\nexport const VALID_OUTPUTS = ['human', 'json', 'jsonl'] as const;\n\n/** Reusable validators. Each throws a descriptive Error or returns the typed value. */\nconst validate = {\n /** Restrict to a fixed set of string literals. */\n enum<T extends string>(flag: string, allowed: readonly T[]) {\n return (raw: string): T => {\n if (!(allowed as readonly string[]).includes(raw)) {\n throw new Error(`${flag} must be one of: ${allowed.join(', ')}`);\n }\n return raw as T;\n };\n },\n /** Require a positive (>0) integer. */\n positiveInt(flag: string) {\n return (raw: string): number => {\n const parsed = Number(raw);\n if (!Number.isInteger(parsed) || parsed <= 0) {\n throw new Error(`${flag} must be a positive integer`);\n }\n return parsed;\n };\n },\n /** Pass a string through unchanged. */\n string(raw: string): string {\n return raw;\n },\n};\n\n/**\n * One CLI flag. `key` is the long name (e.g. `output`); `field` is the\n * {@link import('./cli.js').HeadlessArgs} property it populates. `coerce`\n * converts the raw string and validates it. Boolean flags omit `coerce` and set\n * `field` to `true` when present.\n */\nexport interface FlagSpec {\n /** Long flag name without the leading `--`. */\n key: string;\n /** Single-character alias (without the leading `-`), if any. */\n short?: string;\n /** Whether the flag takes a value (`string`) or is a switch (`boolean`). */\n type: 'string' | 'boolean';\n /** Target field on `HeadlessArgs`. Omit for flags handled out-of-band (e.g. help). */\n field?: string;\n /** Coerce/validate a string value. Required for `type: 'string'` flags that map to a field. */\n coerce?: (raw: string) => unknown;\n /** `<...>` value placeholder shown in usage, e.g. `<text>`. */\n placeholder?: string;\n /** One-line (or multi-line) help description shown in usage. */\n help: string | string[];\n}\n\nexport const FLAGS: FlagSpec[] = [\n {\n key: 'prompt',\n short: 'p',\n type: 'string',\n field: 'prompt',\n coerce: validate.string,\n placeholder: '<text>',\n help: 'The task to execute (required, or pipe via stdin)',\n },\n {\n key: 'continue',\n short: 'c',\n type: 'boolean',\n field: 'continue_',\n help: 'Resume the most recent thread instead of creating a new one',\n },\n {\n key: 'thread',\n short: 't',\n type: 'string',\n field: 'thread',\n coerce: validate.string,\n placeholder: '<id>',\n help: 'Resume a specific thread by ID',\n },\n {\n key: 'title',\n type: 'string',\n field: 'title',\n coerce: validate.string,\n placeholder: '<title>',\n help: 'Set or rename the thread title',\n },\n {\n key: 'clone-thread',\n type: 'boolean',\n field: 'cloneThread',\n help: 'Clone the current thread before running (work on a copy)',\n },\n {\n key: 'resource-id',\n type: 'string',\n field: 'resourceId',\n coerce: validate.string,\n placeholder: '<id>',\n help: 'Set the resource ID for thread scoping',\n },\n {\n key: 'timeout',\n type: 'string',\n field: 'timeout',\n coerce: validate.positiveInt('--timeout'),\n placeholder: '<seconds>',\n help: 'Exit with code 2 if not complete within timeout',\n },\n {\n key: 'max-turns',\n type: 'string',\n field: 'maxTurns',\n coerce: validate.positiveInt('--max-turns'),\n placeholder: '<n>',\n help: 'Abort after N agentic turns (exit code 1)',\n },\n {\n key: 'permission-mode',\n type: 'string',\n field: 'permissionMode',\n coerce: validate.enum<PermissionMode>('--permission-mode', VALID_PERMISSION_MODES),\n placeholder: '<mode>',\n help: [\n 'How tool approvals/suspensions resolve:',\n ' auto approve everything (default)',\n ' deny refuse approvals, abort on suspension',\n ],\n },\n {\n key: 'output',\n short: 'o',\n type: 'string',\n field: 'output',\n coerce: validate.enum<OutputMode>('--output', VALID_OUTPUTS),\n placeholder: '<mode>',\n help: [\n 'Output mode: \"human\" (default), \"json\", or \"jsonl\"',\n ' human streaming text to stdout, activity to stderr',\n ' json single final JSON object (text, usage, tools)',\n ' jsonl newline-delimited JSON event stream',\n ' (omits display_state_changed UI snapshots)',\n ],\n },\n {\n key: 'model',\n short: 'm',\n type: 'string',\n field: 'model',\n coerce: validate.string,\n placeholder: '<id>',\n help: 'Model override (e.g., a provider/model id); wins over --pack for the active mode',\n },\n {\n key: 'pack',\n type: 'string',\n field: 'pack',\n coerce: validate.string,\n placeholder: '<id>',\n help: [\n 'Model pack to activate (like /models → Activate): a builtin pack id',\n '(anthropic, openai, github-copilot) or a saved custom pack, by',\n '\"custom:<name>\" or its bare name. Sets the pack for every mode and',\n 'becomes the global default pack. --model overrides it for the active mode.',\n ],\n },\n {\n key: 'mode',\n type: 'string',\n field: 'mode',\n coerce: validate.enum<RunMode>('--mode', VALID_MODES),\n placeholder: '{build|plan|fast}',\n help: 'Execution mode — defaults to \"build\" if omitted',\n },\n {\n key: 'thinking-level',\n type: 'string',\n field: 'thinkingLevel',\n coerce: validate.enum<ThinkingLevel>('--thinking-level', VALID_THINKING_LEVELS),\n placeholder: '<level>',\n help: 'Thinking level: off, low, medium, high, xhigh, max',\n },\n {\n key: 'settings',\n type: 'string',\n field: 'settings',\n coerce: validate.string,\n placeholder: '<path>',\n help: 'Path to settings.json file (default: global settings)',\n },\n {\n key: 'help',\n short: 'h',\n type: 'boolean',\n help: 'Show this help and exit',\n },\n];\n\n/** `parseArgs` option config derived from {@link FLAGS}. */\nexport function buildParseArgsOptions() {\n const options: Record<string, { type: 'string' | 'boolean'; short?: string; default?: boolean }> = {};\n for (const flag of FLAGS) {\n options[flag.key] = flag.type === 'boolean' ? { type: 'boolean', default: false } : { type: 'string' };\n if (flag.short) options[flag.key]!.short = flag.short;\n }\n return options;\n}\n\n/** Render the aligned `--flag description` block of the usage text from {@link FLAGS}. */\nexport function renderFlagUsage(): string {\n const left = (flag: FlagSpec): string => {\n const long = `--${flag.key}`;\n const short = flag.short ? `, -${flag.short}` : '';\n const value = flag.placeholder ? ` ${flag.placeholder}` : '';\n return ` ${long}${short}${value}`;\n };\n\n const rows = FLAGS.map(flag => ({ flag, label: left(flag) }));\n const width = Math.max(...rows.map(r => r.label.length)) + 2;\n\n return rows\n .map(({ flag, label }) => {\n const lines = Array.isArray(flag.help) ? flag.help : [flag.help];\n const first = `${label.padEnd(width)}${lines[0]}`;\n const rest = lines.slice(1).map(line => `${' '.repeat(width)}${line}`);\n return [first, ...rest].join('\\n');\n })\n .join('\\n');\n}\n"],"mappings":";;AAgBA,MAAa,gBAAgB;CAAC;CAAS;CAAQ;AAAO;;AAGtD,MAAM,WAAW;;CAEf,KAAuB,MAAc,SAAuB;EAC1D,QAAQ,QAAmB;GACzB,IAAI,CAAE,QAA8B,SAAS,GAAG,GAC9C,MAAM,IAAI,MAAM,GAAG,KAAK,mBAAmB,QAAQ,KAAK,IAAI,GAAG;GAEjE,OAAO;EACT;CACF;;CAEA,YAAY,MAAc;EACxB,QAAQ,QAAwB;GAC9B,MAAM,SAAS,OAAO,GAAG;GACzB,IAAI,CAAC,OAAO,UAAU,MAAM,KAAK,UAAU,GACzC,MAAM,IAAI,MAAM,GAAG,KAAK,4BAA4B;GAEtD,OAAO;EACT;CACF;;CAEA,OAAO,KAAqB;EAC1B,OAAO;CACT;AACF;AAyBA,MAAa,QAAoB;CAC/B;EACE,KAAK;EACL,OAAO;EACP,MAAM;EACN,OAAO;EACP,QAAQ,SAAS;EACjB,aAAa;EACb,MAAM;CACR;CACA;EACE,KAAK;EACL,OAAO;EACP,M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K;EACL,MAAM;EACN,OAAO;EACP,QAAQ,SAAS;EACjB,aAAa;EACb,MAAM;CACR;CACA;EACE,KAAK;EACL,OAAO;EACP,MAAM;EACN,MAAM;CACR;AACF;;AAGA,SAAgB,wBAAwB;CACtC,MAAM,UAA6F,CAAC;CACpG,KAAK,MAAM,QAAQ,OAAO;EACxB,QAAQ,KAAK,OAAO,KAAK,SAAS,YAAY;GAAE,MAAM;GAAW,SAAS;EAAM,IAAI,EAAE,MAAM,SAAS;EACrG,IAAI,KAAK,OAAO,QAAQ,KAAK,IAAI,CAAE,QAAQ,KAAK;CAClD;CACA,OAAO;AACT;;AAGA,SAAgB,kBAA0B;CACxC,MAAM,QAAQ,SAA2B;EAIvC,OAAO,KAAK,KAHM,KAAK,QACT,KAAK,QAAQ,MAAM,KAAK,UAAU,KAClC,KAAK,cAAc,IAAI,KAAK,gBAAgB;CAE5D;CAEA,MAAM,OAAO,MAAM,KAAI,UAAS;EAAE;EAAM,OAAO,KAAK,IAAI;CAAE,EAAE;CAC5D,MAAM,QAAQ,KAAK,IAAI,GAAG,KAAK,KAAI,MAAK,EAAE,MAAM,MAAM,CAAC,IAAI;CAE3D,OAAO,KACJ,KAAK,EAAE,MAAM,YAAY;EACxB,MAAM,QAAQ,MAAM,QAAQ,KAAK,IAAI,IAAI,KAAK,OAAO,CAAC,KAAK,IAAI;EAG/D,OAAO,CAAC,GAFS,MAAM,OAAO,KAAK,IAAI,MAAM,MAE9B,GADF,MAAM,MAAM,CAAC,CAAC,CAAC,KAAI,SAAQ,GAAG,IAAI,OAAO,KAAK,IAAI,MAC1C,CAAC,CAAC,CAAC,KAAK,IAAI;CACnC,CAAC,CAAC,CACD,KAAK,IAAI;AACd"}
1
+ {"version":3,"file":"flags.js","names":[],"sources":["../../src/headless/flags.ts"],"sourcesContent":["/**\n * Declarative flag specification for the headless CLI.\n *\n * A single table is the source of truth for three things that previously drifted\n * apart in `cli.ts`:\n * 1. the `node:util` `parseArgs` option config,\n * 2. per-flag value coercion + validation, and\n * 3. the `--help` usage text.\n *\n * Adding a flag means adding one row here; parsing, validation, and the usage\n * listing all follow automatically.\n */\nimport type { OutputMode } from './cli.js';\nimport type { PermissionMode, RunMode, ThinkingLevel } from './types.js';\nimport { VALID_MODES, VALID_PERMISSION_MODES, VALID_THINKING_LEVELS } from './types.js';\n\nexport const VALID_OUTPUTS = ['human', 'json', 'jsonl'] as const;\n\n/** Reusable validators. Each throws a descriptive Error or returns the typed value. */\nconst validate = {\n /** Restrict to a fixed set of string literals. */\n enum<T extends string>(flag: string, allowed: readonly T[]) {\n return (raw: string): T => {\n if (!(allowed as readonly string[]).includes(raw)) {\n throw new Error(`${flag} must be one of: ${allowed.join(', ')}`);\n }\n return raw as T;\n };\n },\n /** Require a positive (>0) integer. */\n positiveInt(flag: string) {\n return (raw: string): number => {\n const parsed = Number(raw);\n if (!Number.isInteger(parsed) || parsed <= 0) {\n throw new Error(`${flag} must be a positive integer`);\n }\n return parsed;\n };\n },\n /** Pass a string through unchanged. */\n string(raw: string): string {\n return raw;\n },\n};\n\n/**\n * One CLI flag. `key` is the long name (e.g. `output`); `field` is the\n * {@link import('./cli.js').HeadlessArgs} property it populates. `coerce`\n * converts the raw string and validates it. Boolean flags omit `coerce` and set\n * `field` to `true` when present.\n */\nexport interface FlagSpec {\n /** Long flag name without the leading `--`. */\n key: string;\n /** Single-character alias (without the leading `-`), if any. */\n short?: string;\n /** Whether the flag takes a value (`string`) or is a switch (`boolean`). */\n type: 'string' | 'boolean';\n /** Target field on `HeadlessArgs`. Omit for flags handled out-of-band (e.g. help). */\n field?: string;\n /** Coerce/validate a string value. Required for `type: 'string'` flags that map to a field. */\n coerce?: (raw: string) => unknown;\n /** `<...>` value placeholder shown in usage, e.g. `<text>`. */\n placeholder?: string;\n /** One-line (or multi-line) help description shown in usage. */\n help: string | string[];\n}\n\nexport const FLAGS: FlagSpec[] = [\n {\n key: 'prompt',\n short: 'p',\n type: 'string',\n field: 'prompt',\n coerce: validate.string,\n placeholder: '<text>',\n help: 'The task to execute (required, or pipe via stdin)',\n },\n {\n key: 'continue',\n short: 'c',\n type: 'boolean',\n field: 'continue_',\n help: 'Resume the most recent thread instead of creating a new one',\n },\n {\n key: 'thread',\n short: 't',\n type: 'string',\n field: 'thread',\n coerce: validate.string,\n placeholder: '<id>',\n help: 'Resume a specific thread by ID',\n },\n {\n key: 'title',\n type: 'string',\n field: 'title',\n coerce: validate.string,\n placeholder: '<title>',\n help: 'Set or rename the thread title',\n },\n {\n key: 'clone-thread',\n type: 'boolean',\n field: 'cloneThread',\n help: 'Clone the current thread before running (work on a copy)',\n },\n {\n key: 'resource-id',\n type: 'string',\n field: 'resourceId',\n coerce: validate.string,\n placeholder: '<id>',\n help: 'Set the resource ID for thread scoping',\n },\n {\n key: 'timeout',\n type: 'string',\n field: 'timeout',\n coerce: validate.positiveInt('--timeout'),\n placeholder: '<seconds>',\n help: 'Exit with code 2 if not complete within timeout',\n },\n {\n key: 'max-turns',\n type: 'string',\n field: 'maxTurns',\n coerce: validate.positiveInt('--max-turns'),\n placeholder: '<n>',\n help: 'Abort after N agentic turns (exit code 1)',\n },\n {\n key: 'permission-mode',\n type: 'string',\n field: 'permissionMode',\n coerce: validate.enum<PermissionMode>('--permission-mode', VALID_PERMISSION_MODES),\n placeholder: '<mode>',\n help: [\n 'How tool approvals/suspensions resolve:',\n ' auto approve everything (default)',\n ' deny refuse approvals, abort on suspension',\n ],\n },\n {\n key: 'output',\n short: 'o',\n type: 'string',\n field: 'output',\n coerce: validate.enum<OutputMode>('--output', VALID_OUTPUTS),\n placeholder: '<mode>',\n help: [\n 'Output mode: \"human\" (default), \"json\", or \"jsonl\"',\n ' human streaming text to stdout, activity to stderr',\n ' json single final JSON object (text, usage, tools)',\n ' jsonl newline-delimited JSON event stream',\n ' (omits display_state_changed UI snapshots)',\n ],\n },\n {\n key: 'model',\n short: 'm',\n type: 'string',\n field: 'model',\n coerce: validate.string,\n placeholder: '<id>',\n help: 'Model override (e.g., a provider/model id); wins over --pack for the active mode',\n },\n {\n key: 'pack',\n type: 'string',\n field: 'pack',\n coerce: validate.string,\n placeholder: '<id>',\n help: [\n 'Model pack to activate (like /models → Activate): a builtin pack id',\n '(anthropic, openai, github-copilot) or a saved custom pack, by',\n '\"custom:<name>\" or its bare name. Sets the pack for every mode and',\n 'becomes the global default pack. --model overrides it for the active mode.',\n ],\n },\n {\n key: 'mode',\n type: 'string',\n field: 'mode',\n coerce: validate.enum<RunMode>('--mode', VALID_MODES),\n placeholder: '{build|plan|fast}',\n help: 'Execution mode — defaults to \"build\" if omitted',\n },\n {\n key: 'thinking-level',\n type: 'string',\n field: 'thinkingLevel',\n coerce: validate.enum<ThinkingLevel>('--thinking-level', VALID_THINKING_LEVELS),\n placeholder: '<level>',\n help: 'Thinking level: off, low, medium, high, xhigh, max',\n },\n {\n key: 'settings',\n type: 'string',\n field: 'settings',\n coerce: validate.string,\n placeholder: '<path>',\n help: 'Path to settings.json file (default: global settings)',\n },\n {\n key: 'help',\n short: 'h',\n type: 'boolean',\n help: 'Show this help and exit',\n },\n {\n key: 'version',\n short: 'v',\n type: 'boolean',\n help: 'Print the Mastra Code version and exit',\n },\n];\n\n/** `parseArgs` option config derived from {@link FLAGS}. */\nexport function buildParseArgsOptions() {\n const options: Record<string, { type: 'string' | 'boolean'; short?: string; default?: boolean }> = {};\n for (const flag of FLAGS) {\n options[flag.key] = flag.type === 'boolean' ? { type: 'boolean', default: false } : { type: 'string' };\n if (flag.short) options[flag.key]!.short = flag.short;\n }\n return options;\n}\n\n/** Render the aligned `--flag description` block of the usage text from {@link FLAGS}. */\nexport function renderFlagUsage(): string {\n const left = (flag: FlagSpec): string => {\n const long = `--${flag.key}`;\n const short = flag.short ? `, -${flag.short}` : '';\n const value = flag.placeholder ? ` ${flag.placeholder}` : '';\n return ` ${long}${short}${value}`;\n };\n\n const rows = FLAGS.map(flag => ({ flag, label: left(flag) }));\n const width = Math.max(...rows.map(r => r.label.length)) + 2;\n\n return rows\n .map(({ flag, label }) => {\n const lines = Array.isArray(flag.help) ? flag.help : [flag.help];\n const first = `${label.padEnd(width)}${lines[0]}`;\n const rest = lines.slice(1).map(line => `${' '.repeat(width)}${line}`);\n return [first, ...rest].join('\\n');\n })\n .join('\\n');\n}\n"],"mappings":";;AAgBA,MAAa,gBAAgB;CAAC;CAAS;CAAQ;AAAO;;AAGtD,MAAM,WAAW;;CAEf,KAAuB,MAAc,SAAuB;EAC1D,QAAQ,QAAmB;GACzB,IAAI,CAAE,QAA8B,SAAS,GAAG,GAC9C,MAAM,IAAI,MAAM,GAAG,KAAK,mBAAmB,QAAQ,KAAK,IAAI,GAAG;GAEjE,OAAO;EACT;CACF;;CAEA,YAAY,MAAc;EACxB,QAAQ,QAAwB;GAC9B,MAAM,SAAS,OAAO,GAAG;GACzB,IAAI,CAAC,OAAO,UAAU,MAAM,KAAK,UAAU,GACzC,MAAM,IAAI,MAAM,GAAG,KAAK,4BAA4B;GAEtD,OAAO;EACT;CACF;;CAEA,OAAO,KAAqB;EAC1B,OAAO;CACT;AACF;AAyBA,MAAa,QAAoB;CAC/B;EACE,KAAK;EACL,OAAO;EACP,MAAM;EACN,OAAO;EACP,QAAQ,SAAS;EACjB,aAAa;EACb,MAAM;CACR;CACA;EACE,KAAK;EACL,OAAO;EACP,MAAM;EACN,OAAO;EACP,MAAM;CACR;CACA;EACE,KAAK;EACL,OAAO;EACP,MAAM;EACN,OAAO;EACP,QAAQ,SAAS;EACjB,aAAa;EACb,MAAM;CACR;CACA;EACE,KAAK;EACL,MAAM;EACN,OAAO;EACP,QAAQ,SAAS;EACjB,aAAa;EACb,MAAM;CACR;CACA;EACE,KAAK;EACL,MAAM;EACN,OAAO;EACP,MAAM;CACR;CACA;EACE,KAAK;EACL,MAAM;EACN,OAAO;EACP,QAAQ,SAAS;EACjB,aAAa;EACb,MAAM;CACR;CACA;EACE,KAAK;EACL,MAAM;EACN,OAAO;EACP,QAAQ,SAAS,YAAY,WAAW;EACxC,aAAa;EACb,MAAM;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O;AACT;;AAGA,SAAgB,kBAA0B;CACxC,MAAM,QAAQ,SAA2B;EAIvC,OAAO,KAAK,KAHM,KAAK,QACT,KAAK,QAAQ,MAAM,KAAK,UAAU,KAClC,KAAK,cAAc,IAAI,KAAK,gBAAgB;CAE5D;CAEA,MAAM,OAAO,MAAM,KAAI,UAAS;EAAE;EAAM,OAAO,KAAK,IAAI;CAAE,EAAE;CAC5D,MAAM,QAAQ,KAAK,IAAI,GAAG,KAAK,KAAI,MAAK,EAAE,MAAM,MAAM,CAAC,IAAI;CAE3D,OAAO,KACJ,KAAK,EAAE,MAAM,YAAY;EACxB,MAAM,QAAQ,MAAM,QAAQ,KAAK,IAAI,IAAI,KAAK,OAAO,CAAC,KAAK,IAAI;EAG/D,OAAO,CAAC,GAFS,MAAM,OAAO,KAAK,IAAI,MAAM,MAE9B,GADF,MAAM,MAAM,CAAC,CAAC,CAAC,KAAI,SAAQ,GAAG,IAAI,OAAO,KAAK,IAAI,MAC1C,CAAC,CAAC,CAAC,KAAK,IAAI;CACnC,CAAC,CAAC,CACD,KAAK,IAAI;AACd"}
package/dist/index.d.ts CHANGED
@@ -239,6 +239,7 @@ export declare function createMastraCodeAgentController(config?: MastraCodeConfi
239
239
  storageMaintenance: StorageMaintenance;
240
240
  createKnowledgeInspector: (session: Session<MastraCodeState>, knowledgeKey?: string) => Promise<import("./knowledge-inspector.js").KnowledgeInspector | undefined>;
241
241
  observability: Observability;
242
+ observabilityExports: boolean;
242
243
  memory: import("@mastra/core/base").DynamicArgument<import("@mastra/core/memory").MastraMemory> | (((ctx: {
243
244
  requestContext: RequestContext;
244
245
  }) => Promise<import("@mastra/memory").Memory>) & {
@@ -345,6 +346,7 @@ export declare function bootLocalAgentController(config?: MastraCodeConfig): Pro
345
346
  storageMaintenance: StorageMaintenance;
346
347
  createKnowledgeInspector: (session: Session<MastraCodeState>, knowledgeKey?: string) => Promise<import("./knowledge-inspector.js").KnowledgeInspector | undefined>;
347
348
  observability: Observability;
349
+ observabilityExports: boolean;
348
350
  memory: import("@mastra/core/base").DynamicArgument<import("@mastra/core/memory").MastraMemory> | (((ctx: {
349
351
  requestContext: RequestContext;
350
352
  }) => Promise<import("@mastra/memory").Memory>) & {
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAC;AAChD,OAAO,EAAE,eAAe,EAAkC,MAAM,+BAA+B,CAAC;AAChG,OAAO,KAAK,EACV,eAAe,EACf,qBAAqB,EAErB,mBAAmB,EACnB,uBAAuB,EAEvB,aAAa,EACb,OAAO,EACR,MAAM,+BAA+B,CAAC;AAGvC,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAClD,OAAO,EAAE,SAAS,EAAyB,MAAM,wBAAwB,CAAC;AAG1E,OAAO,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAU7C,OAAO,KAAK,EAAE,cAAc,EAAE,eAAe,EAAa,MAAM,yBAAyB,CAAC;AAC1F,OAAO,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAE9D,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAGpD,OAAO,EAAE,oBAAoB,EAAE,MAAM,sBAAsB,CAAC;AAE5D,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAGxD,OAAO,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAC;AAEvD,OAAO,EACL,aAAa,EAId,MAAM,uBAAuB,CAAC;AAI/B,OAAO,KAAK,EAAE,qCAAqC,EAAE,MAAM,wCAAwC,CAAC;AAUpG,OAAO,EAKL,YAAY,EACb,MAAM,mBAAmB,CAAC;AAa3B,OAAO,KAAK,EAAE,gBAAgB,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AASpE,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AA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QAAQ,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;CAC/B,CAAC,CAqED;AAED;;;;;GAKG;AACH,eAAO,MAAM,gBAAgB,iCAA2B,CAAC;AACzD,OAAO,EAAE,gBAAgB,EAAE,uBAAuB,EAAE,MAAM,6BAA6B,CAAC;AACxF,cAAc,0BAA0B,CAAC;AACzC,OAAO,EAAE,sBAAsB,EAAE,MAAM,sBAAsB,CAAC;AAE9D;;;;GAIG;AACH,OAAO,EACL,KAAK,EACL,QAAQ,EACR,eAAe,EACf,iBAAiB,EACjB,UAAU,EACV,sBAAsB,EACtB,WAAW,EACX,WAAW,EACX,gBAAgB,EAChB,gBAAgB,GACjB,MAAM,qBAAqB,CAAC;AAC7B,YAAY,EACV,YAAY,EACZ,WAAW,EACX,WAAW,EACX,UAAU,EACV,aAAa,EACb,eAAe,EACf,UAAU,EACV,kBAAkB,EAClB,KAAK,EACL,gBAAgB,EAChB,cAAc,GACf,MAAM,qBAAqB,CAAC"}
package/dist/index.js CHANGED
@@ -17,6 +17,7 @@ import { createGitRefReminderReader, instructionSourcePaths, loadSessionInstruct
17
17
  import { getDynamicInstructions } from "./agents/instructions.js";
18
18
  import { LOCAL_KNOWLEDGE_ORG_ID, knowledgeUnresolvedScopes, resolveKnowledgeSessionScopes } from "./knowledge-scope.js";
19
19
  import { createAmazonBedrockGateway } from "./providers/amazon-bedrock-gateway.js";
20
+ import { createGoogleVertexGateway } from "./providers/google-vertex-gateway.js";
20
21
  import { setAuthStorage as setAuthStorage$1 } from "./providers/claude-max.js";
21
22
  import { setAuthStorage as setAuthStorage$2 } from "./providers/github-copilot.js";
22
23
  import { setAuthStorage as setAuthStorage$3 } from "./providers/kimi-coding.js";
@@ -289,6 +290,7 @@ async function createMastraCodeAgentController(config) {
289
290
  settingsPath: config?.settingsPath
290
291
  });
291
292
  const amazonBedrockGateway = createAmazonBedrockGateway();
293
+ const googleVertexGateway = createGoogleVertexGateway();
292
294
  const githubCopilotGateway = createGitHubCopilotGateway();
293
295
  const project = detectProject(cwd);
294
296
  const resourceIdOverride = getResourceIdOverride(project.rootPath, configDir);
@@ -696,6 +698,14 @@ async function createMastraCodeAgentController(config) {
696
698
  return NO_PLUGIN_PROCESSORS;
697
699
  }
698
700
  };
701
+ const resolveTenantSessionModel = withCredentialTenantPreparation(async (ctx) => {
702
+ const controller = ctx.requestContext.get("controller");
703
+ const hasSessionLevel = isThinkingLevelSetting(controller?.state?.thinkingLevel);
704
+ return getDynamicModel(ctx, config?.settingsPath, {
705
+ modeless,
706
+ defaultThinkingLevel: hasSessionLevel ? void 0 : await config?.resolveDefaultThinkingLevel?.(ctx)
707
+ });
708
+ });
699
709
  const baseCodeAgent = createCodingAgent({
700
710
  id: CODE_AGENT_ID,
701
711
  name: "Code Agent",
@@ -719,14 +729,7 @@ async function createMastraCodeAgentController(config) {
719
729
  disabledBuiltinTools: config?.disableBuiltinTools
720
730
  });
721
731
  },
722
- model: withCredentialTenantPreparation(async (ctx) => {
723
- const controller = ctx.requestContext.get("controller");
724
- const hasSessionLevel = isThinkingLevelSetting(controller?.state?.thinkingLevel);
725
- return getDynamicModel(ctx, config?.settingsPath, {
726
- modeless,
727
- defaultThinkingLevel: hasSessionLevel ? void 0 : await config?.resolveDefaultThinkingLevel?.(ctx)
728
- });
729
- }),
732
+ model: async (ctx) => ctx.requestContext.get("controller") ? resolveTenantSessionModel(ctx) : getDynamicModel(ctx, config?.settingsPath, { modeless }),
730
733
  notifications: { deliveryPolicy: { decide: async (input) => {
731
734
  const decision = defaultNotificationDeliveryDecision(input);
732
735
  if (!input.record.resourceId) return decision;
@@ -965,6 +968,7 @@ async function createMastraCodeAgentController(config) {
965
968
  ...backgroundToolsEnabled ? { backgroundTasks: {
966
969
  enabled: true,
967
970
  recoverStaleTasksOnStart: false,
971
+ notifyAgentOnFinish: false,
968
972
  ...createBackgroundCompletionCallbacks(() => sessionRouter, backgroundCompletionEvents)
969
973
  } } : {},
970
974
  observability,
@@ -984,11 +988,13 @@ async function createMastraCodeAgentController(config) {
984
988
  resolveSubagentModel: (modelId, { requestContext }) => routesToOtherGateway(modelId, Object.values(controller.getMastra()?.listGateways() ?? {}), /* @__PURE__ */ new Set([
985
989
  mastraCodeGateway.id,
986
990
  amazonBedrockGateway.id,
991
+ googleVertexGateway.id,
987
992
  githubCopilotGateway.id,
988
993
  "models.dev"
989
994
  ])) ? modelId : resolveModel(modelId, { requestContext }),
990
995
  gateways: [
991
996
  amazonBedrockGateway,
997
+ googleVertexGateway,
992
998
  githubCopilotGateway,
993
999
  mastraCodeGateway
994
1000
  ],
@@ -1069,6 +1075,7 @@ async function createMastraCodeAgentController(config) {
1069
1075
  hostScopes: knowledgeHostScopes
1070
1076
  }),
1071
1077
  observability,
1078
+ observabilityExports: Boolean(observabilityDomain || cloudObservabilityConfig),
1072
1079
  memory,
1073
1080
  knowledge,
1074
1081
  knowledgeKey,
@@ -1331,10 +1338,11 @@ async function prepareAgentControllerMount(config) {
1331
1338
  const mastraArgs = {
1332
1339
  agentControllers: { [controllerId]: controller },
1333
1340
  storage,
1334
- observability: base.observability,
1341
+ ...base.observabilityExports ? { observability: base.observability } : {},
1335
1342
  ...backgroundToolsEnabled ? { backgroundTasks: {
1336
1343
  enabled: true,
1337
1344
  recoverStaleTasksOnStart: false,
1345
+ notifyAgentOnFinish: false,
1338
1346
  ...createBackgroundCompletionCallbacks(() => controller, backgroundCompletionEvents)
1339
1347
  } } : {},
1340
1348
  ...base.knowledge ? { knowledge: { [base.knowledgeKey]: base.knowledge } } : {},