@mastra/code-sdk 1.10.1 → 1.10.2-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3,6 +3,7 @@ import { MastraModelGateway } from '@mastra/core/llm';
3
3
  import type { GatewayAuthRequest, GatewayAuthResult, GatewayLanguageModel, MastraModelGatewayInterface, ProviderConfig } from '@mastra/core/llm';
4
4
  import { AuthStorage } from '../auth/storage.js';
5
5
  import type { CredentialStore } from '../auth/types.js';
6
+ import type { AnthropicPromptCacheScope } from '../providers/anthropic-prompt-cache.js';
6
7
  import type { ThinkingLevel } from '../providers/openai-codex.js';
7
8
  export { MASTRA_GATEWAY_PREFIX, OPENAI_PREFIX, remapOpenAIModelForCodexOAuth, stripMastraGatewayPrefix, } from '../providers/model-ids.js';
8
9
  export declare const MASTRACODE_GATEWAY_ID = "mastracode";
@@ -17,6 +18,8 @@ export type MastraCodeGatewayOptions = {
17
18
  mastraGatewayApiKey?: string;
18
19
  routeThroughMastraGateway: boolean;
19
20
  thinkingLevel?: ThinkingLevel;
21
+ /** Anthropic prompt-cache breakpoints to write. Defaults to `conversation`. */
22
+ anthropicPromptCacheScope?: AnthropicPromptCacheScope;
20
23
  customProviders?: MastraCodeCustomProvider[];
21
24
  settingsPath?: string;
22
25
  /**
@@ -43,7 +46,7 @@ export declare class MastraCodeGateway extends MastraModelGateway {
43
46
  #private;
44
47
  readonly id = "mastracode";
45
48
  readonly name = "MastraCode Gateway";
46
- constructor({ mastraGatewayBaseUrl, mastraGatewayApiKey, routeThroughMastraGateway, thinkingLevel, customProviders, settingsPath, credentialStore, }: MastraCodeGatewayOptions);
49
+ constructor({ mastraGatewayBaseUrl, mastraGatewayApiKey, routeThroughMastraGateway, thinkingLevel, anthropicPromptCacheScope, customProviders, settingsPath, credentialStore, }: MastraCodeGatewayOptions);
47
50
  static getMastraGatewayApiKey(): string | undefined;
48
51
  /** @deprecated Renamed to {@link MastraCodeGateway.getMastraGatewayApiKey}. */
49
52
  static getMemoryGatewayApiKey(): string | undefined;
@@ -1 +1 @@
1
- {"version":3,"file":"mastracode-gateway.d.ts","sourceRoot":"","sources":["../../src/agents/mastracode-gateway.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAwB,0BAA0B,EAAE,MAAM,+BAA+B,CAAC;AACtG,OAAO,EAGL,kBAAkB,EAGnB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,KAAK,EACV,kBAAkB,EAClB,iBAAiB,EACjB,oBAAoB,EACpB,2BAA2B,EAC3B,cAAc,EACf,MAAM,kBAAkB,CAAC;AAE1B,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AACjD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AA0BxD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,8BAA8B,CAAC;AAKlE,OAAO,EACL,qBAAqB,EACrB,aAAa,EACb,6BAA6B,EAC7B,wBAAwB,GACzB,MAAM,2BAA2B,CAAC;AAEnC,eAAO,MAAM,qBAAqB,eAAe,CAAC;AAIlD,MAAM,MAAM,wBAAwB,GAAG;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAC;IAAC,MAAM,CAAC,EAAE,MAAM,CAAC;IAAC,MAAM,CAAC,EAAE,MAAM,EAAE,CAAA;CAAE,CAAC;AAEzG,MAAM,MAAM,wBAAwB,GAAG;IACrC,oBAAoB,EAAE,MAAM,CAAC;IAC7B,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAC7B,yBAAyB,EAAE,OAAO,CAAC;IACnC,aAAa,CAAC,EAAE,aAAa,CAAC;IAC9B,eAAe,CAAC,EAAE,wBAAwB,EAAE,CAAC;IAC7C,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB;;;;OAIG;IACH,eAAe,CAAC,EAAE,eAAe,CAAC;CACnC,CAAC;AAcF,wBAAgB,oBAAoB,IAAI,WAAW,CAUlD;AAED,wBAAgB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eAAwC,GACpD,iBAAiB,GAAG,SAAS;IAehC,MAAM,CAAC,0BAA0B,CAAC,OAAO,EAAE,2BAA2B,GAAG,0BAA0B;IA+BnG,0BAA0B,IAAI,0BAA0B;IAWlD,cAAc,IAAI,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,cAAc,CAAC,CAAC;IAuC/D,QAAQ,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,GAAG,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC;IAIrE,SAAS,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IAMjD,WAAW,CAAC,OAAO,EAAE,kBAAkB,GAAG,iBAAiB,GAAG,SAAS;IAevE,oBAAoB,CAAC,IAAI,EAAE;QACzB,OAAO,EAAE,MAAM,CAAC;QAChB,UAAU,EAAE,MAAM,CAAC;QACnB,MAAM,EAAE,MAAM,CAAC;QACf,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;QACjC,SAAS,CAAC,EAAE,GAAG,CAAC;QAChB,kBAAkB,CAAC,EAAE,GAAG,CAAC;KAC1B,GAAG,oBAAoB;CA4PzB"}
@@ -4,7 +4,7 @@ import { MASTRA_GATEWAY_PREFIX, OPENAI_PREFIX, normalizeAnthropicModelId, remapO
4
4
  import { THINKING_LEVEL_TO_REASONING_EFFORT, buildOpenAICodexOAuthFetch, createCodexMiddleware, createReasoningEffortMiddleware, getEffectiveThinkingLevel, openaiCodexProvider } from "../providers/openai-codex.js";
5
5
  import { getCustomProviderId, loadSettings } from "../onboarding/settings.js";
6
6
  import { resolveCustomProviders } from "./custom-provider-source.js";
7
- import { buildAnthropicOAuthFetch, claudeCodeMiddleware, createAnthropicThinkingMiddleware, opencodeClaudeMaxProvider, promptCacheMiddleware } from "../providers/claude-max.js";
7
+ import { buildAnthropicOAuthFetch, claudeCodeMiddleware, createAnthropicThinkingMiddleware, createPromptCacheMiddleware, opencodeClaudeMaxProvider } from "../providers/claude-max.js";
8
8
  import { getCopilotModelCatalog, githubCopilotProvider } from "../providers/github-copilot.js";
9
9
  import { createGoogleThinkingMiddleware } from "../providers/google-thinking.js";
10
10
  import { KIMI_CODING_MODELS, kimiCodingProvider } from "../providers/kimi-coding.js";
@@ -60,7 +60,7 @@ function getOpenAIApiKey(credentials = getGlobalAuthStorage()) {
60
60
  if (dedicatedKey) return dedicatedKey;
61
61
  return credentials.allowEnvironmentFallback === false ? void 0 : process.env.OPENAI_API_KEY?.trim() || void 0;
62
62
  }
63
- function anthropicApiKeyProvider(modelId, apiKey, headers, thinkingLevel) {
63
+ function anthropicApiKeyProvider(modelId, apiKey, headers, thinkingLevel, promptCacheScope) {
64
64
  const anthropic = createAnthropic({
65
65
  apiKey,
66
66
  headers
@@ -68,7 +68,7 @@ function anthropicApiKeyProvider(modelId, apiKey, headers, thinkingLevel) {
68
68
  const thinkingMiddleware = createAnthropicThinkingMiddleware(modelId, thinkingLevel);
69
69
  return wrapLanguageModel({
70
70
  model: anthropic(modelId),
71
- middleware: [promptCacheMiddleware, ...thinkingMiddleware ? [thinkingMiddleware] : []]
71
+ middleware: [createPromptCacheMiddleware(promptCacheScope), ...thinkingMiddleware ? [thinkingMiddleware] : []]
72
72
  });
73
73
  }
74
74
  function openaiApiKeyProvider(modelId, apiKey, headers, thinkingLevel) {
@@ -161,16 +161,18 @@ var MastraCodeGateway = class MastraCodeGateway extends MastraModelGateway {
161
161
  #mastraGatewayApiKey;
162
162
  #routeThroughMastraGateway;
163
163
  #thinkingLevel;
164
+ #anthropicPromptCacheScope;
164
165
  #customProviders;
165
166
  #settingsPath;
166
167
  #credentials;
167
- constructor({ mastraGatewayBaseUrl, mastraGatewayApiKey, routeThroughMastraGateway, thinkingLevel, customProviders, settingsPath, credentialStore }) {
168
+ constructor({ mastraGatewayBaseUrl, mastraGatewayApiKey, routeThroughMastraGateway, thinkingLevel, anthropicPromptCacheScope, customProviders, settingsPath, credentialStore }) {
168
169
  super();
169
170
  this.#mastraGateway = new MastraGateway({ baseUrl: mastraGatewayBaseUrl });
170
171
  this.#mastraGatewayBaseUrl = mastraGatewayBaseUrl;
171
172
  this.#mastraGatewayApiKey = mastraGatewayApiKey;
172
173
  this.#routeThroughMastraGateway = routeThroughMastraGateway;
173
174
  this.#thinkingLevel = thinkingLevel;
175
+ this.#anthropicPromptCacheScope = anthropicPromptCacheScope ?? "conversation";
174
176
  this.#customProviders = customProviders;
175
177
  this.#settingsPath = settingsPath;
176
178
  this.#credentials = credentialStore ?? getGlobalAuthStorage();
@@ -371,7 +373,7 @@ var MastraCodeGateway = class MastraCodeGateway extends MastraModelGateway {
371
373
  })(bareModelId),
372
374
  middleware: [
373
375
  claudeCodeMiddleware,
374
- promptCacheMiddleware,
376
+ createPromptCacheMiddleware(this.#anthropicPromptCacheScope),
375
377
  ...thinkingMiddleware ? [thinkingMiddleware] : []
376
378
  ]
377
379
  });
@@ -388,15 +390,17 @@ var MastraCodeGateway = class MastraCodeGateway extends MastraModelGateway {
388
390
  if (storedCred?.type === "oauth") return opencodeClaudeMaxProvider(bareModelId, {
389
391
  headers: args.headers,
390
392
  authStorage: this.#credentials,
391
- thinkingLevel: this.#thinkingLevel
393
+ thinkingLevel: this.#thinkingLevel,
394
+ promptCacheScope: this.#anthropicPromptCacheScope
392
395
  });
393
- if (storedCred?.type === "api_key" && storedCred.key.trim().length > 0) return anthropicApiKeyProvider(bareModelId, storedCred.key.trim(), args.headers, this.#thinkingLevel);
396
+ if (storedCred?.type === "api_key" && storedCred.key.trim().length > 0) return anthropicApiKeyProvider(bareModelId, storedCred.key.trim(), args.headers, this.#thinkingLevel, this.#anthropicPromptCacheScope);
394
397
  const apiKey = getAnthropicApiKey(this.#credentials);
395
- if (apiKey) return anthropicApiKeyProvider(bareModelId, apiKey, args.headers, this.#thinkingLevel);
398
+ if (apiKey) return anthropicApiKeyProvider(bareModelId, apiKey, args.headers, this.#thinkingLevel, this.#anthropicPromptCacheScope);
396
399
  return opencodeClaudeMaxProvider(bareModelId, {
397
400
  headers: args.headers,
398
401
  authStorage: this.#credentials,
399
- thinkingLevel: this.#thinkingLevel
402
+ thinkingLevel: this.#thinkingLevel,
403
+ promptCacheScope: this.#anthropicPromptCacheScope
400
404
  });
401
405
  }
402
406
  #resolveOpenAIModel(args) {
@@ -1 +1 @@
1
- {"version":3,"file":"mastracode-gateway.js","names":["#mastraGateway","#mastraGatewayBaseUrl","#mastraGatewayApiKey","#routeThroughMastraGateway","#thinkingLevel","#customProviders","#settingsPath","#credentials","#getCustomProviders","#resolveAnthropicModel","#resolveOpenAIModel","#resolveGoogleModel"],"sources":["../../src/agents/mastracode-gateway.ts"],"sourcesContent":["import { createAnthropic } from '@ai-sdk/anthropic';\nimport { createOpenAI } from '@ai-sdk/openai';\nimport { createOpenAICompatible } from '@ai-sdk/openai-compatible';\nimport type { CustomAvailableModel, CustomModelCatalogProvider } from '@mastra/core/agent-controller';\nimport {\n GATEWAY_AUTH_HEADER,\n MastraGateway,\n MastraModelGateway,\n ModelRouterLanguageModel,\n PROVIDER_REGISTRY,\n} from '@mastra/core/llm';\nimport type {\n GatewayAuthRequest,\n GatewayAuthResult,\n GatewayLanguageModel,\n MastraModelGatewayInterface,\n ProviderConfig,\n} from '@mastra/core/llm';\nimport { wrapLanguageModel } from 'ai';\nimport { AuthStorage } from '../auth/storage.js';\nimport type { CredentialStore } from '../auth/types.js';\nimport { getCustomProviderId, loadSettings, MASTRA_GATEWAY_PROVIDER } from '../onboarding/settings.js';\nimport {\n buildAnthropicOAuthFetch,\n claudeCodeMiddleware,\n createAnthropicThinkingMiddleware,\n opencodeClaudeMaxProvider,\n promptCacheMiddleware,\n} from '../providers/claude-max.js';\nimport { getCopilotModelCatalog, githubCopilotProvider } from '../providers/github-copilot.js';\nimport { createGoogleThinkingMiddleware } from '../providers/google-thinking.js';\nimport { KIMI_CODING_MODELS, kimiCodingProvider } from '../providers/kimi-coding.js';\nimport {\n normalizeAnthropicModelId,\n OPENAI_PREFIX,\n remapOpenAIModelForCodexOAuth,\n stripMastraGatewayPrefix,\n} from '../providers/model-ids.js';\nimport {\n buildOpenAICodexOAuthFetch,\n createCodexMiddleware,\n createReasoningEffortMiddleware,\n getEffectiveThinkingLevel,\n openaiCodexProvider,\n THINKING_LEVEL_TO_REASONING_EFFORT,\n} from '../providers/openai-codex.js';\nimport type { ThinkingLevel } from '../providers/openai-codex.js';\nimport { xaiProvider } from '../providers/xai.js';\nimport { getAppDataDir } from '../utils/project.js';\nimport { resolveCustomProviders } from './custom-provider-source.js';\n\nexport {\n MASTRA_GATEWAY_PREFIX,\n OPENAI_PREFIX,\n remapOpenAIModelForCodexOAuth,\n stripMastraGatewayPrefix,\n} from '../providers/model-ids.js';\n\nexport const MASTRACODE_GATEWAY_ID = 'mastracode';\n\ntype ModelRequestHeaders = Record<string, string>;\n\nexport type MastraCodeCustomProvider = { name: string; url: string; apiKey?: string; models?: string[] };\n\nexport type MastraCodeGatewayOptions = {\n mastraGatewayBaseUrl: string;\n mastraGatewayApiKey?: string;\n routeThroughMastraGateway: boolean;\n thinkingLevel?: ThinkingLevel;\n customProviders?: MastraCodeCustomProvider[];\n settingsPath?: string;\n /**\n * Per-tenant credential source for this gateway instance. Defaults to the\n * server-global file-backed `AuthStorage`; deployed web passes the calling\n * tenant's store so model calls use the caller's own credentials.\n */\n credentialStore?: CredentialStore;\n};\n\n/**\n * Global file-backed credential store for local (TUI) model resolution.\n *\n * Constructed lazily, NOT at module scope: `AuthStorage`'s default path is\n * resolved from `MASTRA_APP_DATA_DIR` at construction, and this module is\n * routinely imported before test harnesses / embedders point that variable at\n * an isolated directory — an import-time construction would permanently pin\n * the developer's real app-data dir for every credential read.\n */\nlet authStorageSingleton: AuthStorage | undefined;\nlet authStorageSingletonDir: string | undefined;\n\nexport function getGlobalAuthStorage(): AuthStorage {\n // Keyed by the resolved app-data dir: in-process harnesses re-point\n // MASTRA_APP_DATA_DIR per run inside one long-lived worker, so a store\n // pinned to a previous dir must be discarded, not reused.\n const dir = getAppDataDir();\n if (!authStorageSingleton || authStorageSingletonDir !== dir) {\n authStorageSingleton = new AuthStorage();\n authStorageSingletonDir = dir;\n }\n return authStorageSingleton;\n}\n\nexport function reloadAuthStorage() {\n getGlobalAuthStorage().reload();\n}\n\n/**\n * Resolve the Anthropic API key.\n * Main slot → dedicated apikey: slot → env var.\n */\nexport function getAnthropicApiKey(credentials: CredentialStore = getGlobalAuthStorage()): string | undefined {\n const storedCred = credentials.get('anthropic');\n if (storedCred?.type === 'api_key' && storedCred.key.trim().length > 0) {\n return storedCred.key.trim();\n }\n const dedicatedKey = credentials.getStoredApiKey('anthropic')?.trim();\n if (dedicatedKey) return dedicatedKey;\n return credentials.allowEnvironmentFallback === false\n ? undefined\n : process.env.ANTHROPIC_API_KEY?.trim() || undefined;\n}\n\n/**\n * Resolve the OpenAI API key.\n * Main slot → dedicated apikey: slot → env var.\n */\nexport function getOpenAIApiKey(credentials: CredentialStore = getGlobalAuthStorage()): string | undefined {\n const storedCred = credentials.get('openai-codex');\n if (storedCred?.type === 'api_key' && storedCred.key.trim().length > 0) {\n return storedCred.key.trim();\n }\n const dedicatedKey = credentials.getStoredApiKey('openai-codex')?.trim();\n if (dedicatedKey) return dedicatedKey;\n return credentials.allowEnvironmentFallback === false ? undefined : process.env.OPENAI_API_KEY?.trim() || undefined;\n}\n\nfunction anthropicApiKeyProvider(\n modelId: string,\n apiKey: string,\n headers?: ModelRequestHeaders,\n thinkingLevel?: ThinkingLevel,\n) {\n const anthropic = createAnthropic({ apiKey, headers });\n const thinkingMiddleware = createAnthropicThinkingMiddleware(modelId, thinkingLevel);\n return wrapLanguageModel({\n model: anthropic(modelId),\n middleware: [promptCacheMiddleware, ...(thinkingMiddleware ? [thinkingMiddleware] : [])],\n });\n}\n\nfunction openaiApiKeyProvider(\n modelId: string,\n apiKey: string,\n headers?: ModelRequestHeaders,\n thinkingLevel?: ThinkingLevel,\n) {\n const openai = createOpenAI({ apiKey, baseURL: process.env.OPENAI_BASE_URL, headers });\n const middleware =\n thinkingLevel && thinkingLevel !== 'off'\n ? createReasoningEffortMiddleware(\n 'openai',\n THINKING_LEVEL_TO_REASONING_EFFORT[getEffectiveThinkingLevel(modelId, thinkingLevel)],\n )\n : undefined;\n return wrapLanguageModel({\n model: openai.responses(modelId),\n middleware: middleware ? [middleware] : [],\n });\n}\n\nfunction getAuthProviderId(providerId: string): string {\n return providerId === 'openai' ? 'openai-codex' : providerId;\n}\n\nfunction getProviderAuthKey(\n providerId: string,\n credentials: CredentialStore = getGlobalAuthStorage(),\n): string | undefined {\n const authProviderId = getAuthProviderId(providerId);\n const storedCred = credentials.get(authProviderId);\n if (storedCred?.type === 'api_key' && storedCred.key.trim().length > 0) {\n return storedCred.key.trim();\n }\n const dedicatedKey = credentials.getStoredApiKey(authProviderId)?.trim();\n if (dedicatedKey) return dedicatedKey;\n if (credentials.allowEnvironmentFallback === false) return undefined;\n return authProviderId === 'kimi-for-coding' ? process.env.KIMI_API_KEY?.trim() || undefined : undefined;\n}\n\nexport function resolveAuth(request: GatewayAuthRequest, mastraGatewayApiKey?: string): GatewayAuthResult | undefined {\n return MastraCodeGateway.resolveProviderAuth(request, mastraGatewayApiKey);\n}\n\nfunction getGatewayProviderKey(gatewayId: string, providerId: string): string {\n if (gatewayId === 'models.dev') return providerId;\n return providerId === gatewayId ? gatewayId : `${gatewayId}/${providerId}`;\n}\n\nfunction parseGatewayRouterId(\n routerId: string,\n gateway: MastraModelGatewayInterface,\n): { gatewayId: string; providerId: string; modelId: string } {\n const [firstPart = '', secondPart = '', ...restParts] = routerId.split('/');\n const gatewayId = gateway.id;\n\n if (firstPart === gatewayId && secondPart) {\n return {\n gatewayId,\n providerId: secondPart,\n modelId: restParts.join('/'),\n };\n }\n\n return {\n gatewayId,\n providerId: firstPart,\n modelId: [secondPart, ...restParts].filter(Boolean).join('/'),\n };\n}\n\nfunction hasResolvedAuth(auth: GatewayAuthResult | undefined): boolean {\n if (!auth) return false;\n if (auth.apiKey || auth.bearerToken) return true;\n return auth.headers ? Object.keys(auth.headers).length > 0 : false;\n}\n\nasync function resolveGatewayProviderAuth(\n gateway: MastraModelGatewayInterface,\n routerId: string,\n): Promise<GatewayAuthResult | undefined> {\n if (!gateway.resolveAuth) return undefined;\n\n const parsed = parseGatewayRouterId(routerId, gateway);\n try {\n const result = await gateway.resolveAuth({\n gatewayId: parsed.gatewayId,\n providerId: parsed.providerId,\n modelId: parsed.modelId,\n routerId,\n });\n return hasResolvedAuth(result) ? result : undefined;\n } catch {\n return undefined;\n }\n}\n\nasync function getMastraCodeProviderConfigs(\n gateway: MastraModelGatewayInterface,\n): Promise<Record<string, ProviderConfig>> {\n const providers: Record<string, ProviderConfig> = { ...(PROVIDER_REGISTRY as Record<string, ProviderConfig>) };\n\n try {\n const gatewayProviders = await gateway.fetchProviders();\n for (const [providerId, config] of Object.entries(gatewayProviders)) {\n providers[getGatewayProviderKey(gateway.id, providerId)] = {\n ...config,\n gateway: gateway.id,\n };\n }\n } catch (error) {\n console.warn(`Failed to load providers from gateway ${gateway.id}:`, error);\n }\n\n return providers;\n}\n\nfunction getApiKeyEnvVar(providerConfig: Pick<ProviderConfig, 'apiKeyEnvVar'> | undefined): string | undefined {\n const envVars = providerConfig?.apiKeyEnvVar;\n return Array.isArray(envVars) ? envVars[0] : envVars;\n}\n\nexport class MastraCodeGateway extends MastraModelGateway {\n readonly id = MASTRACODE_GATEWAY_ID;\n readonly name = 'MastraCode Gateway';\n\n readonly #mastraGateway: MastraGateway;\n readonly #mastraGatewayBaseUrl: string;\n readonly #mastraGatewayApiKey?: string;\n readonly #routeThroughMastraGateway: boolean;\n readonly #thinkingLevel?: ThinkingLevel;\n readonly #customProviders?: MastraCodeCustomProvider[];\n readonly #settingsPath?: string;\n readonly #credentials: CredentialStore;\n\n constructor({\n mastraGatewayBaseUrl,\n mastraGatewayApiKey,\n routeThroughMastraGateway,\n thinkingLevel,\n customProviders,\n settingsPath,\n credentialStore,\n }: MastraCodeGatewayOptions) {\n super();\n this.#mastraGateway = new MastraGateway({ baseUrl: mastraGatewayBaseUrl });\n this.#mastraGatewayBaseUrl = mastraGatewayBaseUrl;\n this.#mastraGatewayApiKey = mastraGatewayApiKey;\n this.#routeThroughMastraGateway = routeThroughMastraGateway;\n this.#thinkingLevel = thinkingLevel;\n this.#customProviders = customProviders;\n this.#settingsPath = settingsPath;\n this.#credentials = credentialStore ?? getGlobalAuthStorage();\n }\n\n static getMastraGatewayApiKey(): string | undefined {\n return getGlobalAuthStorage().getStoredApiKey(MASTRA_GATEWAY_PROVIDER) ?? process.env['MASTRA_GATEWAY_API_KEY'];\n }\n\n /** @deprecated Renamed to {@link MastraCodeGateway.getMastraGatewayApiKey}. */\n static getMemoryGatewayApiKey(): string | undefined {\n return MastraCodeGateway.getMastraGatewayApiKey();\n }\n\n /**\n * Claim an unprefixed model id (e.g. a bare `anthropic/...`) when this gateway\n * can authenticate it via OAuth or a stored/env credential. This lets the\n * shared gateway router select MastraCode for auth resolution, so the status\n * bar and `/api-keys` reflect OAuth logins instead of only checking env vars.\n */\n handlesModel(modelId: string): boolean {\n const parsed = parseGatewayRouterId(modelId, this);\n if (!parsed.providerId || !parsed.modelId) return false;\n if (this.#routeThroughMastraGateway && this.#mastraGatewayApiKey) return true;\n const customProvider = this.#getCustomProviders().find(\n provider => parsed.providerId === getCustomProviderId(provider.name),\n );\n if (customProvider?.apiKey) return true;\n return hasResolvedAuth(\n MastraCodeGateway.resolveProviderAuth(\n {\n gatewayId: this.id,\n providerId: parsed.providerId,\n modelId: parsed.modelId,\n routerId: modelId,\n },\n undefined,\n this.#credentials,\n ),\n );\n }\n\n static resolveProviderAuth(\n request: GatewayAuthRequest,\n mastraGatewayApiKey?: string,\n credentials: CredentialStore = getGlobalAuthStorage(),\n ): GatewayAuthResult | undefined {\n if (request.gatewayId === 'mastra' && mastraGatewayApiKey) {\n return { apiKey: mastraGatewayApiKey, source: 'gateway' };\n }\n\n const authProviderId = getAuthProviderId(request.providerId);\n const storedCred = credentials.get(authProviderId);\n if (storedCred?.type === 'oauth') {\n return { bearerToken: 'oauth', source: 'gateway' };\n }\n\n const apiKey = getProviderAuthKey(request.providerId, credentials);\n return apiKey ? { apiKey, source: 'gateway' } : undefined;\n }\n\n static createModelCatalogProvider(gateway: MastraModelGatewayInterface): CustomModelCatalogProvider {\n return async () => {\n const registry = await getMastraCodeProviderConfigs(gateway);\n const models: CustomAvailableModel[] = [];\n\n for (const [provider, providerConfig] of Object.entries(registry)) {\n const apiKeyEnvVar = getApiKeyEnvVar(providerConfig);\n const hasEnvKey = apiKeyEnvVar ? Boolean(process.env[apiKeyEnvVar]) : false;\n const modelNames = providerConfig.models;\n if (!Array.isArray(modelNames)) continue;\n\n const gatewayAuth = modelNames[0]\n ? await resolveGatewayProviderAuth(gateway, `${provider}/${modelNames[0]}`)\n : undefined;\n\n for (const modelName of modelNames) {\n const id = `${provider}/${modelName}`;\n models.push({\n id,\n provider,\n modelName,\n hasApiKey: hasEnvKey || Boolean(gatewayAuth),\n apiKeyEnvVar: apiKeyEnvVar || undefined,\n });\n }\n }\n\n return models;\n };\n }\n\n createModelCatalogProvider(): CustomModelCatalogProvider {\n return MastraCodeGateway.createModelCatalogProvider(this);\n }\n\n #getCustomProviders(): MastraCodeCustomProvider[] {\n // Explicit constructor list wins; then a registered source (deployed web,\n // DB-backed — authoritative, so settings.json is never consulted); then\n // the local file-backed settings.\n return this.#customProviders ?? resolveCustomProviders() ?? loadSettings(this.#settingsPath).customProviders;\n }\n\n async fetchProviders(): Promise<Record<string, ProviderConfig>> {\n const providers: Record<string, ProviderConfig> = {};\n for (const provider of this.#getCustomProviders()) {\n const models = provider.models ?? [];\n if (!models.length) continue;\n providers[getCustomProviderId(provider.name)] = {\n name: provider.name,\n url: provider.url,\n apiKeyEnvVar: '',\n apiKeyHeader: 'Authorization',\n gateway: this.id,\n models,\n };\n }\n\n providers['kimi-for-coding'] = {\n name: 'Kimi For Coding',\n apiKeyEnvVar: 'KIMI_API_KEY',\n apiKeyHeader: 'Authorization',\n gateway: this.id,\n models: [...KIMI_CODING_MODELS],\n };\n\n try {\n const copilotModels = await getCopilotModelCatalog({ authStorage: this.#credentials });\n providers['github-copilot'] = {\n name: 'GitHub Copilot',\n apiKeyEnvVar: '',\n apiKeyHeader: 'Authorization',\n gateway: this.id,\n models: copilotModels.map(model => model.id),\n };\n } catch (error) {\n console.warn('Failed to load GitHub Copilot model catalog:', error);\n }\n\n return providers;\n }\n\n buildUrl(modelId: string): string | undefined | Promise<string | undefined> {\n return this.#routeThroughMastraGateway ? this.#mastraGateway.buildUrl(modelId) : modelId;\n }\n\n async getApiKey(modelId: string): Promise<string> {\n const providerId = stripMastraGatewayPrefix(modelId).split('/', 1)[0];\n if (this.#routeThroughMastraGateway) return this.#mastraGatewayApiKey ?? '';\n return providerId ? (getProviderAuthKey(providerId, this.#credentials) ?? '') : '';\n }\n\n resolveAuth(request: GatewayAuthRequest): GatewayAuthResult | undefined {\n if (this.#routeThroughMastraGateway && this.#mastraGatewayApiKey) {\n return { apiKey: this.#mastraGatewayApiKey, source: 'gateway' };\n }\n\n const customProvider = this.#getCustomProviders().find(\n provider => request.providerId === getCustomProviderId(provider.name),\n );\n if (customProvider?.apiKey) {\n return { apiKey: customProvider.apiKey, source: 'gateway' };\n }\n\n return MastraCodeGateway.resolveProviderAuth(request, undefined, this.#credentials);\n }\n\n resolveLanguageModel(args: {\n modelId: string;\n providerId: string;\n apiKey: string;\n headers?: Record<string, string>;\n transport?: any;\n responsesWebSocket?: any;\n }): GatewayLanguageModel {\n const customProvider = this.#getCustomProviders().find(\n provider => args.providerId === getCustomProviderId(provider.name),\n );\n if (customProvider) {\n const provider = createOpenAICompatible({\n name: args.providerId,\n baseURL: customProvider.url,\n apiKey: args.apiKey,\n headers: args.headers,\n });\n const reasoningEffort = this.#thinkingLevel ? THINKING_LEVEL_TO_REASONING_EFFORT[this.#thinkingLevel] : undefined;\n const middleware = createReasoningEffortMiddleware(args.providerId, reasoningEffort);\n if (!middleware) {\n return provider.chatModel(args.modelId) as unknown as GatewayLanguageModel;\n }\n return wrapLanguageModel({\n model: provider.chatModel(args.modelId),\n middleware: [middleware],\n }) as unknown as GatewayLanguageModel;\n }\n\n if (args.providerId === 'github-copilot') {\n return githubCopilotProvider(args.modelId, {\n headers: args.headers,\n authStorage: this.#credentials,\n }) as unknown as GatewayLanguageModel;\n }\n\n if (args.providerId === 'moonshotai') {\n // Prefer the gateway-resolved key (stored credentials), then the canonical\n // registry env var. Keep the legacy typo name as a fallback for anyone who\n // set it because of the previous error message.\n const apiKey =\n args.apiKey?.trim() || process.env.MOONSHOT_API_KEY?.trim() || process.env.MOONSHOT_AI_API_KEY?.trim();\n if (!apiKey) {\n throw new Error('Need MOONSHOT_API_KEY');\n }\n return createAnthropic({\n apiKey,\n baseURL: 'https://api.moonshot.ai/anthropic/v1',\n name: 'moonshotai.anthropicv1',\n headers: args.headers,\n })(args.modelId) as unknown as GatewayLanguageModel;\n }\n\n if (args.providerId === 'anthropic') {\n return this.#resolveAnthropicModel(args);\n }\n\n if (args.providerId === 'openai') {\n const openaiModel = this.#resolveOpenAIModel(args);\n if (openaiModel) return openaiModel;\n }\n\n if (args.providerId === 'xai' && this.#credentials.get('xai')?.type === 'oauth') {\n return xaiProvider(args.modelId, {\n headers: args.headers,\n authStorage: this.#credentials,\n }) as unknown as GatewayLanguageModel;\n }\n\n if (args.providerId === 'google') {\n return this.#resolveGoogleModel(args);\n }\n\n if (this.#routeThroughMastraGateway) {\n return this.#mastraGateway.resolveLanguageModel(args) as GatewayLanguageModel;\n }\n\n if (args.providerId === 'kimi-for-coding') {\n return kimiCodingProvider(args.modelId, {\n apiKey: args.apiKey,\n headers: args.headers,\n credentialStore: this.#credentials,\n }) as unknown as GatewayLanguageModel;\n }\n\n return new ModelRouterLanguageModel({\n id: `${args.providerId}/${args.modelId}` as `${string}/${string}`,\n apiKey: args.apiKey,\n headers: args.headers,\n }) as unknown as GatewayLanguageModel;\n }\n\n #resolveAnthropicModel(args: {\n modelId: string;\n providerId: string;\n apiKey: string;\n headers?: Record<string, string>;\n transport?: any;\n responsesWebSocket?: any;\n }): GatewayLanguageModel {\n const bareModelId = normalizeAnthropicModelId(args.modelId);\n const storedCred = this.#credentials.get('anthropic');\n const thinkingMiddleware = createAnthropicThinkingMiddleware(bareModelId, this.#thinkingLevel);\n\n if (this.#routeThroughMastraGateway) {\n if (storedCred?.type === 'oauth') {\n const anthropic = createAnthropic({\n apiKey: 'oauth-gateway-placeholder',\n baseURL: `${this.#mastraGatewayBaseUrl}/v1`,\n headers: {\n [GATEWAY_AUTH_HEADER]: `Bearer ${args.apiKey}`,\n ...args.headers,\n },\n fetch: buildAnthropicOAuthFetch({ authStorage: this.#credentials }) as any,\n });\n\n return wrapLanguageModel({\n model: anthropic(bareModelId),\n middleware: [\n claudeCodeMiddleware,\n promptCacheMiddleware,\n ...(thinkingMiddleware ? [thinkingMiddleware] : []),\n ],\n }) as unknown as GatewayLanguageModel;\n }\n\n const gatewayModel = this.#mastraGateway.resolveLanguageModel({\n ...args,\n modelId: bareModelId,\n }) as GatewayLanguageModel;\n if (!thinkingMiddleware) return gatewayModel;\n return wrapLanguageModel({\n model: gatewayModel as any,\n middleware: [thinkingMiddleware],\n }) as unknown as GatewayLanguageModel;\n }\n\n if (storedCred?.type === 'oauth') {\n return opencodeClaudeMaxProvider(bareModelId, {\n headers: args.headers,\n authStorage: this.#credentials,\n thinkingLevel: this.#thinkingLevel,\n }) as unknown as GatewayLanguageModel;\n }\n\n if (storedCred?.type === 'api_key' && storedCred.key.trim().length > 0) {\n return anthropicApiKeyProvider(\n bareModelId,\n storedCred.key.trim(),\n args.headers,\n this.#thinkingLevel,\n ) as unknown as GatewayLanguageModel;\n }\n\n const apiKey = getAnthropicApiKey(this.#credentials);\n if (apiKey) {\n return anthropicApiKeyProvider(\n bareModelId,\n apiKey,\n args.headers,\n this.#thinkingLevel,\n ) as unknown as GatewayLanguageModel;\n }\n\n // No stored credentials: use the OAuth-backed provider so the first request can trigger login.\n return opencodeClaudeMaxProvider(bareModelId, {\n headers: args.headers,\n authStorage: this.#credentials,\n thinkingLevel: this.#thinkingLevel,\n }) as unknown as GatewayLanguageModel;\n }\n\n #resolveOpenAIModel(args: {\n modelId: string;\n providerId: string;\n apiKey: string;\n headers?: Record<string, string>;\n transport?: any;\n responsesWebSocket?: any;\n }): GatewayLanguageModel | undefined {\n const storedCred = this.#credentials.get('openai-codex');\n\n if (this.#routeThroughMastraGateway) {\n if (storedCred?.type === 'oauth') {\n const resolvedModelId = remapOpenAIModelForCodexOAuth(`openai/${args.modelId}`);\n const resolvedBareModelId = resolvedModelId.substring(OPENAI_PREFIX.length);\n const requestedLevel: ThinkingLevel = this.#thinkingLevel ?? 'medium';\n const effectiveLevel = getEffectiveThinkingLevel(resolvedBareModelId, requestedLevel);\n const reasoningEffort = THINKING_LEVEL_TO_REASONING_EFFORT[effectiveLevel];\n const middleware = createCodexMiddleware(reasoningEffort);\n const openai = createOpenAI({\n apiKey: 'oauth-gateway-placeholder',\n baseURL: `${this.#mastraGatewayBaseUrl}/v1`,\n headers: {\n [GATEWAY_AUTH_HEADER]: `Bearer ${args.apiKey}`,\n ...args.headers,\n },\n fetch: buildOpenAICodexOAuthFetch({ authStorage: this.#credentials, rewriteUrl: false }) as any,\n });\n\n return wrapLanguageModel({\n model: openai.responses(resolvedBareModelId),\n middleware: [middleware],\n }) as unknown as GatewayLanguageModel;\n }\n\n return this.#mastraGateway.resolveLanguageModel(args) as GatewayLanguageModel;\n }\n\n if (storedCred?.type === 'oauth') {\n const resolvedModelId = remapOpenAIModelForCodexOAuth(`openai/${args.modelId}`);\n return openaiCodexProvider(resolvedModelId.substring(OPENAI_PREFIX.length), {\n thinkingLevel: this.#thinkingLevel,\n headers: args.headers,\n authStorage: this.#credentials,\n }) as unknown as GatewayLanguageModel;\n }\n\n const apiKey = getOpenAIApiKey(this.#credentials);\n if (apiKey) {\n return openaiApiKeyProvider(\n args.modelId,\n apiKey,\n args.headers,\n this.#thinkingLevel,\n ) as unknown as GatewayLanguageModel;\n }\n\n return undefined;\n }\n\n #resolveGoogleModel(args: {\n modelId: string;\n providerId: string;\n apiKey: string;\n headers?: Record<string, string>;\n transport?: any;\n responsesWebSocket?: any;\n }): GatewayLanguageModel {\n const baseModel = this.#routeThroughMastraGateway\n ? (this.#mastraGateway.resolveLanguageModel(args) as GatewayLanguageModel)\n : (new ModelRouterLanguageModel({\n id: `${args.providerId}/${args.modelId}` as `${string}/${string}`,\n apiKey: args.apiKey,\n headers: args.headers,\n }) as unknown as GatewayLanguageModel);\n\n const thinkingMiddleware = createGoogleThinkingMiddleware(args.modelId, this.#thinkingLevel);\n if (!thinkingMiddleware) return baseModel;\n\n return wrapLanguageModel({\n model: baseModel as any,\n middleware: [thinkingMiddleware],\n }) as unknown as GatewayLanguageModel;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AA0DA,MAAa,wBAAwB;;;;;;;;;;AA8BrC,IAAI;AACJ,IAAI;AAEJ,SAAgB,uBAAoC;CAIlD,MAAM,MAAM,cAAc;CAC1B,IAAI,CAAC,wBAAwB,4BAA4B,KAAK;EAC5D,uBAAuB,IAAI,YAAY;EACvC,0BAA0B;CAC5B;CACA,OAAO;AACT;AAEA,SAAgB,oBAAoB;CAClC,qBAAqB,CAAC,CAAC,OAAO;AAChC;;;;;AAMA,SAAgB,mBAAmB,cAA+B,qBAAqB,GAAuB;CAC5G,MAAM,aAAa,YAAY,IAAI,WAAW;CAC9C,IAAI,YAAY,SAAS,aAAa,WAAW,IAAI,KAAK,CAAC,CAAC,SAAS,GACnE,OAAO,WAAW,IAAI,KAAK;CAE7B,MAAM,eAAe,YAAY,gBAAgB,WAAW,CAAC,EAAE,KAAK;CACpE,IAAI,cAAc,OAAO;CACzB,OAAO,YAAY,6BAA6B,QAC5C,KAAA,IACA,QAAQ,IAAI,mBAAmB,KAAK,KAAK,KAAA;AAC/C;;;;;AAMA,SAAgB,gBAAgB,cAA+B,qBAAqB,GAAuB;CACzG,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I;GACpB,SAAS,KAAK;GACd,aAAa,KAAKG;EACpB,CAAC;EAGH,MAAM,SAAS,gBAAgB,KAAKA,YAAY;EAChD,IAAI,QACF,OAAO,qBACL,KAAK,SACL,QACA,KAAK,SACL,KAAKH,cACP;CAIJ;CAEA,oBAAoB,MAOK;EACvB,MAAM,YAAY,KAAKD,6BAClB,KAAKH,eAAe,qBAAqB,IAAI,IAC7C,IAAI,yBAAyB;GAC5B,IAAI,GAAG,KAAK,WAAW,GAAG,KAAK;GAC/B,QAAQ,KAAK;GACb,SAAS,KAAK;EAChB,CAAC;EAEL,MAAM,qBAAqB,+BAA+B,KAAK,SAAS,KAAKI,cAAc;EAC3F,IAAI,CAAC,oBAAoB,OAAO;EAEhC,OAAO,kBAAkB;GACvB,OAAO;GACP,YAAY,CAAC,kBAAkB;EACjC,CAAC;CACH;AACF"}
1
+ {"version":3,"file":"mastracode-gateway.js","names":["#mastraGateway","#mastraGatewayBaseUrl","#mastraGatewayApiKey","#routeThroughMastraGateway","#thinkingLevel","#anthropicPromptCacheScope","#customProviders","#settingsPath","#credentials","#getCustomProviders","#resolveAnthropicModel","#resolveOpenAIModel","#resolveGoogleModel"],"sources":["../../src/agents/mastracode-gateway.ts"],"sourcesContent":["import { createAnthropic } from '@ai-sdk/anthropic';\nimport { createOpenAI } from '@ai-sdk/openai';\nimport { createOpenAICompatible } from '@ai-sdk/openai-compatible';\nimport type { CustomAvailableModel, CustomModelCatalogProvider } from '@mastra/core/agent-controller';\nimport {\n GATEWAY_AUTH_HEADER,\n MastraGateway,\n MastraModelGateway,\n ModelRouterLanguageModel,\n PROVIDER_REGISTRY,\n} from '@mastra/core/llm';\nimport type {\n GatewayAuthRequest,\n GatewayAuthResult,\n GatewayLanguageModel,\n MastraModelGatewayInterface,\n ProviderConfig,\n} from '@mastra/core/llm';\nimport { wrapLanguageModel } from 'ai';\nimport { AuthStorage } from '../auth/storage.js';\nimport type { CredentialStore } from '../auth/types.js';\nimport { getCustomProviderId, loadSettings, MASTRA_GATEWAY_PROVIDER } from '../onboarding/settings.js';\nimport type { AnthropicPromptCacheScope } from '../providers/anthropic-prompt-cache.js';\nimport {\n buildAnthropicOAuthFetch,\n claudeCodeMiddleware,\n createAnthropicThinkingMiddleware,\n createPromptCacheMiddleware,\n opencodeClaudeMaxProvider,\n} from '../providers/claude-max.js';\nimport { getCopilotModelCatalog, githubCopilotProvider } from '../providers/github-copilot.js';\nimport { createGoogleThinkingMiddleware } from '../providers/google-thinking.js';\nimport { KIMI_CODING_MODELS, kimiCodingProvider } from '../providers/kimi-coding.js';\nimport {\n normalizeAnthropicModelId,\n OPENAI_PREFIX,\n remapOpenAIModelForCodexOAuth,\n stripMastraGatewayPrefix,\n} from '../providers/model-ids.js';\nimport {\n buildOpenAICodexOAuthFetch,\n createCodexMiddleware,\n createReasoningEffortMiddleware,\n getEffectiveThinkingLevel,\n openaiCodexProvider,\n THINKING_LEVEL_TO_REASONING_EFFORT,\n} from '../providers/openai-codex.js';\nimport type { ThinkingLevel } from '../providers/openai-codex.js';\nimport { xaiProvider } from '../providers/xai.js';\nimport { getAppDataDir } from '../utils/project.js';\nimport { resolveCustomProviders } from './custom-provider-source.js';\n\nexport {\n MASTRA_GATEWAY_PREFIX,\n OPENAI_PREFIX,\n remapOpenAIModelForCodexOAuth,\n stripMastraGatewayPrefix,\n} from '../providers/model-ids.js';\n\nexport const MASTRACODE_GATEWAY_ID = 'mastracode';\n\ntype ModelRequestHeaders = Record<string, string>;\n\nexport type MastraCodeCustomProvider = { name: string; url: string; apiKey?: string; models?: string[] };\n\nexport type MastraCodeGatewayOptions = {\n mastraGatewayBaseUrl: string;\n mastraGatewayApiKey?: string;\n routeThroughMastraGateway: boolean;\n thinkingLevel?: ThinkingLevel;\n /** Anthropic prompt-cache breakpoints to write. Defaults to `conversation`. */\n anthropicPromptCacheScope?: AnthropicPromptCacheScope;\n customProviders?: MastraCodeCustomProvider[];\n settingsPath?: string;\n /**\n * Per-tenant credential source for this gateway instance. Defaults to the\n * server-global file-backed `AuthStorage`; deployed web passes the calling\n * tenant's store so model calls use the caller's own credentials.\n */\n credentialStore?: CredentialStore;\n};\n\n/**\n * Global file-backed credential store for local (TUI) model resolution.\n *\n * Constructed lazily, NOT at module scope: `AuthStorage`'s default path is\n * resolved from `MASTRA_APP_DATA_DIR` at construction, and this module is\n * routinely imported before test harnesses / embedders point that variable at\n * an isolated directory — an import-time construction would permanently pin\n * the developer's real app-data dir for every credential read.\n */\nlet authStorageSingleton: AuthStorage | undefined;\nlet authStorageSingletonDir: string | undefined;\n\nexport function getGlobalAuthStorage(): AuthStorage {\n // Keyed by the resolved app-data dir: in-process harnesses re-point\n // MASTRA_APP_DATA_DIR per run inside one long-lived worker, so a store\n // pinned to a previous dir must be discarded, not reused.\n const dir = getAppDataDir();\n if (!authStorageSingleton || authStorageSingletonDir !== dir) {\n authStorageSingleton = new AuthStorage();\n authStorageSingletonDir = dir;\n }\n return authStorageSingleton;\n}\n\nexport function reloadAuthStorage() {\n getGlobalAuthStorage().reload();\n}\n\n/**\n * Resolve the Anthropic API key.\n * Main slot → dedicated apikey: slot → env var.\n */\nexport function getAnthropicApiKey(credentials: CredentialStore = getGlobalAuthStorage()): string | undefined {\n const storedCred = credentials.get('anthropic');\n if (storedCred?.type === 'api_key' && storedCred.key.trim().length > 0) {\n return storedCred.key.trim();\n }\n const dedicatedKey = credentials.getStoredApiKey('anthropic')?.trim();\n if (dedicatedKey) return dedicatedKey;\n return credentials.allowEnvironmentFallback === false\n ? undefined\n : process.env.ANTHROPIC_API_KEY?.trim() || undefined;\n}\n\n/**\n * Resolve the OpenAI API key.\n * Main slot → dedicated apikey: slot → env var.\n */\nexport function getOpenAIApiKey(credentials: CredentialStore = getGlobalAuthStorage()): string | undefined {\n const storedCred = credentials.get('openai-codex');\n if (storedCred?.type === 'api_key' && storedCred.key.trim().length > 0) {\n return storedCred.key.trim();\n }\n const dedicatedKey = credentials.getStoredApiKey('openai-codex')?.trim();\n if (dedicatedKey) return dedicatedKey;\n return credentials.allowEnvironmentFallback === false ? undefined : process.env.OPENAI_API_KEY?.trim() || undefined;\n}\n\nfunction anthropicApiKeyProvider(\n modelId: string,\n apiKey: string,\n headers: ModelRequestHeaders | undefined,\n thinkingLevel: ThinkingLevel | undefined,\n promptCacheScope: AnthropicPromptCacheScope,\n) {\n const anthropic = createAnthropic({ apiKey, headers });\n const thinkingMiddleware = createAnthropicThinkingMiddleware(modelId, thinkingLevel);\n return wrapLanguageModel({\n model: anthropic(modelId),\n middleware: [createPromptCacheMiddleware(promptCacheScope), ...(thinkingMiddleware ? [thinkingMiddleware] : [])],\n });\n}\n\nfunction openaiApiKeyProvider(\n modelId: string,\n apiKey: string,\n headers?: ModelRequestHeaders,\n thinkingLevel?: ThinkingLevel,\n) {\n const openai = createOpenAI({ apiKey, baseURL: process.env.OPENAI_BASE_URL, headers });\n const middleware =\n thinkingLevel && thinkingLevel !== 'off'\n ? createReasoningEffortMiddleware(\n 'openai',\n THINKING_LEVEL_TO_REASONING_EFFORT[getEffectiveThinkingLevel(modelId, thinkingLevel)],\n )\n : undefined;\n return wrapLanguageModel({\n model: openai.responses(modelId),\n middleware: middleware ? [middleware] : [],\n });\n}\n\nfunction getAuthProviderId(providerId: string): string {\n return providerId === 'openai' ? 'openai-codex' : providerId;\n}\n\nfunction getProviderAuthKey(\n providerId: string,\n credentials: CredentialStore = getGlobalAuthStorage(),\n): string | undefined {\n const authProviderId = getAuthProviderId(providerId);\n const storedCred = credentials.get(authProviderId);\n if (storedCred?.type === 'api_key' && storedCred.key.trim().length > 0) {\n return storedCred.key.trim();\n }\n const dedicatedKey = credentials.getStoredApiKey(authProviderId)?.trim();\n if (dedicatedKey) return dedicatedKey;\n if (credentials.allowEnvironmentFallback === false) return undefined;\n return authProviderId === 'kimi-for-coding' ? process.env.KIMI_API_KEY?.trim() || undefined : undefined;\n}\n\nexport function resolveAuth(request: GatewayAuthRequest, mastraGatewayApiKey?: string): GatewayAuthResult | undefined {\n return MastraCodeGateway.resolveProviderAuth(request, mastraGatewayApiKey);\n}\n\nfunction getGatewayProviderKey(gatewayId: string, providerId: string): string {\n if (gatewayId === 'models.dev') return providerId;\n return providerId === gatewayId ? gatewayId : `${gatewayId}/${providerId}`;\n}\n\nfunction parseGatewayRouterId(\n routerId: string,\n gateway: MastraModelGatewayInterface,\n): { gatewayId: string; providerId: string; modelId: string } {\n const [firstPart = '', secondPart = '', ...restParts] = routerId.split('/');\n const gatewayId = gateway.id;\n\n if (firstPart === gatewayId && secondPart) {\n return {\n gatewayId,\n providerId: secondPart,\n modelId: restParts.join('/'),\n };\n }\n\n return {\n gatewayId,\n providerId: firstPart,\n modelId: [secondPart, ...restParts].filter(Boolean).join('/'),\n };\n}\n\nfunction hasResolvedAuth(auth: GatewayAuthResult | undefined): boolean {\n if (!auth) return false;\n if (auth.apiKey || auth.bearerToken) return true;\n return auth.headers ? Object.keys(auth.headers).length > 0 : false;\n}\n\nasync function resolveGatewayProviderAuth(\n gateway: MastraModelGatewayInterface,\n routerId: string,\n): Promise<GatewayAuthResult | undefined> {\n if (!gateway.resolveAuth) return undefined;\n\n const parsed = parseGatewayRouterId(routerId, gateway);\n try {\n const result = await gateway.resolveAuth({\n gatewayId: parsed.gatewayId,\n providerId: parsed.providerId,\n modelId: parsed.modelId,\n routerId,\n });\n return hasResolvedAuth(result) ? result : undefined;\n } catch {\n return undefined;\n }\n}\n\nasync function getMastraCodeProviderConfigs(\n gateway: MastraModelGatewayInterface,\n): Promise<Record<string, ProviderConfig>> {\n const providers: Record<string, ProviderConfig> = { ...(PROVIDER_REGISTRY as Record<string, ProviderConfig>) };\n\n try {\n const gatewayProviders = await gateway.fetchProviders();\n for (const [providerId, config] of Object.entries(gatewayProviders)) {\n providers[getGatewayProviderKey(gateway.id, providerId)] = {\n ...config,\n gateway: gateway.id,\n };\n }\n } catch (error) {\n console.warn(`Failed to load providers from gateway ${gateway.id}:`, error);\n }\n\n return providers;\n}\n\nfunction getApiKeyEnvVar(providerConfig: Pick<ProviderConfig, 'apiKeyEnvVar'> | undefined): string | undefined {\n const envVars = providerConfig?.apiKeyEnvVar;\n return Array.isArray(envVars) ? envVars[0] : envVars;\n}\n\nexport class MastraCodeGateway extends MastraModelGateway {\n readonly id = MASTRACODE_GATEWAY_ID;\n readonly name = 'MastraCode Gateway';\n\n readonly #mastraGateway: MastraGateway;\n readonly #mastraGatewayBaseUrl: string;\n readonly #mastraGatewayApiKey?: string;\n readonly #routeThroughMastraGateway: boolean;\n readonly #thinkingLevel?: ThinkingLevel;\n readonly #anthropicPromptCacheScope: AnthropicPromptCacheScope;\n readonly #customProviders?: MastraCodeCustomProvider[];\n readonly #settingsPath?: string;\n readonly #credentials: CredentialStore;\n\n constructor({\n mastraGatewayBaseUrl,\n mastraGatewayApiKey,\n routeThroughMastraGateway,\n thinkingLevel,\n anthropicPromptCacheScope,\n customProviders,\n settingsPath,\n credentialStore,\n }: MastraCodeGatewayOptions) {\n super();\n this.#mastraGateway = new MastraGateway({ baseUrl: mastraGatewayBaseUrl });\n this.#mastraGatewayBaseUrl = mastraGatewayBaseUrl;\n this.#mastraGatewayApiKey = mastraGatewayApiKey;\n this.#routeThroughMastraGateway = routeThroughMastraGateway;\n this.#thinkingLevel = thinkingLevel;\n this.#anthropicPromptCacheScope = anthropicPromptCacheScope ?? 'conversation';\n this.#customProviders = customProviders;\n this.#settingsPath = settingsPath;\n this.#credentials = credentialStore ?? getGlobalAuthStorage();\n }\n\n static getMastraGatewayApiKey(): string | undefined {\n return getGlobalAuthStorage().getStoredApiKey(MASTRA_GATEWAY_PROVIDER) ?? process.env['MASTRA_GATEWAY_API_KEY'];\n }\n\n /** @deprecated Renamed to {@link MastraCodeGateway.getMastraGatewayApiKey}. */\n static getMemoryGatewayApiKey(): string | undefined {\n return MastraCodeGateway.getMastraGatewayApiKey();\n }\n\n /**\n * Claim an unprefixed model id (e.g. a bare `anthropic/...`) when this gateway\n * can authenticate it via OAuth or a stored/env credential. This lets the\n * shared gateway router select MastraCode for auth resolution, so the status\n * bar and `/api-keys` reflect OAuth logins instead of only checking env vars.\n */\n handlesModel(modelId: string): boolean {\n const parsed = parseGatewayRouterId(modelId, this);\n if (!parsed.providerId || !parsed.modelId) return false;\n if (this.#routeThroughMastraGateway && this.#mastraGatewayApiKey) return true;\n const customProvider = this.#getCustomProviders().find(\n provider => parsed.providerId === getCustomProviderId(provider.name),\n );\n if (customProvider?.apiKey) return true;\n return hasResolvedAuth(\n MastraCodeGateway.resolveProviderAuth(\n {\n gatewayId: this.id,\n providerId: parsed.providerId,\n modelId: parsed.modelId,\n routerId: modelId,\n },\n undefined,\n this.#credentials,\n ),\n );\n }\n\n static resolveProviderAuth(\n request: GatewayAuthRequest,\n mastraGatewayApiKey?: string,\n credentials: CredentialStore = getGlobalAuthStorage(),\n ): GatewayAuthResult | undefined {\n if (request.gatewayId === 'mastra' && mastraGatewayApiKey) {\n return { apiKey: mastraGatewayApiKey, source: 'gateway' };\n }\n\n const authProviderId = getAuthProviderId(request.providerId);\n const storedCred = credentials.get(authProviderId);\n if (storedCred?.type === 'oauth') {\n return { bearerToken: 'oauth', source: 'gateway' };\n }\n\n const apiKey = getProviderAuthKey(request.providerId, credentials);\n return apiKey ? { apiKey, source: 'gateway' } : undefined;\n }\n\n static createModelCatalogProvider(gateway: MastraModelGatewayInterface): CustomModelCatalogProvider {\n return async () => {\n const registry = await getMastraCodeProviderConfigs(gateway);\n const models: CustomAvailableModel[] = [];\n\n for (const [provider, providerConfig] of Object.entries(registry)) {\n const apiKeyEnvVar = getApiKeyEnvVar(providerConfig);\n const hasEnvKey = apiKeyEnvVar ? Boolean(process.env[apiKeyEnvVar]) : false;\n const modelNames = providerConfig.models;\n if (!Array.isArray(modelNames)) continue;\n\n const gatewayAuth = modelNames[0]\n ? await resolveGatewayProviderAuth(gateway, `${provider}/${modelNames[0]}`)\n : undefined;\n\n for (const modelName of modelNames) {\n const id = `${provider}/${modelName}`;\n models.push({\n id,\n provider,\n modelName,\n hasApiKey: hasEnvKey || Boolean(gatewayAuth),\n apiKeyEnvVar: apiKeyEnvVar || undefined,\n });\n }\n }\n\n return models;\n };\n }\n\n createModelCatalogProvider(): CustomModelCatalogProvider {\n return MastraCodeGateway.createModelCatalogProvider(this);\n }\n\n #getCustomProviders(): MastraCodeCustomProvider[] {\n // Explicit constructor list wins; then a registered source (deployed web,\n // DB-backed — authoritative, so settings.json is never consulted); then\n // the local file-backed settings.\n return this.#customProviders ?? resolveCustomProviders() ?? loadSettings(this.#settingsPath).customProviders;\n }\n\n async fetchProviders(): Promise<Record<string, ProviderConfig>> {\n const providers: Record<string, ProviderConfig> = {};\n for (const provider of this.#getCustomProviders()) {\n const models = provider.models ?? [];\n if (!models.length) continue;\n providers[getCustomProviderId(provider.name)] = {\n name: provider.name,\n url: provider.url,\n apiKeyEnvVar: '',\n apiKeyHeader: 'Authorization',\n gateway: this.id,\n models,\n };\n }\n\n providers['kimi-for-coding'] = {\n name: 'Kimi For Coding',\n apiKeyEnvVar: 'KIMI_API_KEY',\n apiKeyHeader: 'Authorization',\n gateway: this.id,\n models: [...KIMI_CODING_MODELS],\n };\n\n try {\n const copilotModels = await getCopilotModelCatalog({ authStorage: this.#credentials });\n providers['github-copilot'] = {\n name: 'GitHub Copilot',\n apiKeyEnvVar: '',\n apiKeyHeader: 'Authorization',\n gateway: this.id,\n models: copilotModels.map(model => model.id),\n };\n } catch (error) {\n console.warn('Failed to load GitHub Copilot model catalog:', error);\n }\n\n return providers;\n }\n\n buildUrl(modelId: string): string | undefined | Promise<string | undefined> {\n return this.#routeThroughMastraGateway ? this.#mastraGateway.buildUrl(modelId) : modelId;\n }\n\n async getApiKey(modelId: string): Promise<string> {\n const providerId = stripMastraGatewayPrefix(modelId).split('/', 1)[0];\n if (this.#routeThroughMastraGateway) return this.#mastraGatewayApiKey ?? '';\n return providerId ? (getProviderAuthKey(providerId, this.#credentials) ?? '') : '';\n }\n\n resolveAuth(request: GatewayAuthRequest): GatewayAuthResult | undefined {\n if (this.#routeThroughMastraGateway && this.#mastraGatewayApiKey) {\n return { apiKey: this.#mastraGatewayApiKey, source: 'gateway' };\n }\n\n const customProvider = this.#getCustomProviders().find(\n provider => request.providerId === getCustomProviderId(provider.name),\n );\n if (customProvider?.apiKey) {\n return { apiKey: customProvider.apiKey, source: 'gateway' };\n }\n\n return MastraCodeGateway.resolveProviderAuth(request, undefined, this.#credentials);\n }\n\n resolveLanguageModel(args: {\n modelId: string;\n providerId: string;\n apiKey: string;\n headers?: Record<string, string>;\n transport?: any;\n responsesWebSocket?: any;\n }): GatewayLanguageModel {\n const customProvider = this.#getCustomProviders().find(\n provider => args.providerId === getCustomProviderId(provider.name),\n );\n if (customProvider) {\n const provider = createOpenAICompatible({\n name: args.providerId,\n baseURL: customProvider.url,\n apiKey: args.apiKey,\n headers: args.headers,\n });\n const reasoningEffort = this.#thinkingLevel ? THINKING_LEVEL_TO_REASONING_EFFORT[this.#thinkingLevel] : undefined;\n const middleware = createReasoningEffortMiddleware(args.providerId, reasoningEffort);\n if (!middleware) {\n return provider.chatModel(args.modelId) as unknown as GatewayLanguageModel;\n }\n return wrapLanguageModel({\n model: provider.chatModel(args.modelId),\n middleware: [middleware],\n }) as unknown as GatewayLanguageModel;\n }\n\n if (args.providerId === 'github-copilot') {\n return githubCopilotProvider(args.modelId, {\n headers: args.headers,\n authStorage: this.#credentials,\n }) as unknown as GatewayLanguageModel;\n }\n\n if (args.providerId === 'moonshotai') {\n // Prefer the gateway-resolved key (stored credentials), then the canonical\n // registry env var. Keep the legacy typo name as a fallback for anyone who\n // set it because of the previous error message.\n const apiKey =\n args.apiKey?.trim() || process.env.MOONSHOT_API_KEY?.trim() || process.env.MOONSHOT_AI_API_KEY?.trim();\n if (!apiKey) {\n throw new Error('Need MOONSHOT_API_KEY');\n }\n return createAnthropic({\n apiKey,\n baseURL: 'https://api.moonshot.ai/anthropic/v1',\n name: 'moonshotai.anthropicv1',\n headers: args.headers,\n })(args.modelId) as unknown as GatewayLanguageModel;\n }\n\n if (args.providerId === 'anthropic') {\n return this.#resolveAnthropicModel(args);\n }\n\n if (args.providerId === 'openai') {\n const openaiModel = this.#resolveOpenAIModel(args);\n if (openaiModel) return openaiModel;\n }\n\n if (args.providerId === 'xai' && this.#credentials.get('xai')?.type === 'oauth') {\n return xaiProvider(args.modelId, {\n headers: args.headers,\n authStorage: this.#credentials,\n }) as unknown as GatewayLanguageModel;\n }\n\n if (args.providerId === 'google') {\n return this.#resolveGoogleModel(args);\n }\n\n if (this.#routeThroughMastraGateway) {\n return this.#mastraGateway.resolveLanguageModel(args) as GatewayLanguageModel;\n }\n\n if (args.providerId === 'kimi-for-coding') {\n return kimiCodingProvider(args.modelId, {\n apiKey: args.apiKey,\n headers: args.headers,\n credentialStore: this.#credentials,\n }) as unknown as GatewayLanguageModel;\n }\n\n return new ModelRouterLanguageModel({\n id: `${args.providerId}/${args.modelId}` as `${string}/${string}`,\n apiKey: args.apiKey,\n headers: args.headers,\n }) as unknown as GatewayLanguageModel;\n }\n\n #resolveAnthropicModel(args: {\n modelId: string;\n providerId: string;\n apiKey: string;\n headers?: Record<string, string>;\n transport?: any;\n responsesWebSocket?: any;\n }): GatewayLanguageModel {\n const bareModelId = normalizeAnthropicModelId(args.modelId);\n const storedCred = this.#credentials.get('anthropic');\n const thinkingMiddleware = createAnthropicThinkingMiddleware(bareModelId, this.#thinkingLevel);\n\n if (this.#routeThroughMastraGateway) {\n if (storedCred?.type === 'oauth') {\n const anthropic = createAnthropic({\n apiKey: 'oauth-gateway-placeholder',\n baseURL: `${this.#mastraGatewayBaseUrl}/v1`,\n headers: {\n [GATEWAY_AUTH_HEADER]: `Bearer ${args.apiKey}`,\n ...args.headers,\n },\n fetch: buildAnthropicOAuthFetch({ authStorage: this.#credentials }) as any,\n });\n\n return wrapLanguageModel({\n model: anthropic(bareModelId),\n middleware: [\n claudeCodeMiddleware,\n createPromptCacheMiddleware(this.#anthropicPromptCacheScope),\n ...(thinkingMiddleware ? [thinkingMiddleware] : []),\n ],\n }) as unknown as GatewayLanguageModel;\n }\n\n const gatewayModel = this.#mastraGateway.resolveLanguageModel({\n ...args,\n modelId: bareModelId,\n }) as GatewayLanguageModel;\n if (!thinkingMiddleware) return gatewayModel;\n return wrapLanguageModel({\n model: gatewayModel as any,\n middleware: [thinkingMiddleware],\n }) as unknown as GatewayLanguageModel;\n }\n\n if (storedCred?.type === 'oauth') {\n return opencodeClaudeMaxProvider(bareModelId, {\n headers: args.headers,\n authStorage: this.#credentials,\n thinkingLevel: this.#thinkingLevel,\n promptCacheScope: this.#anthropicPromptCacheScope,\n }) as unknown as GatewayLanguageModel;\n }\n\n if (storedCred?.type === 'api_key' && storedCred.key.trim().length > 0) {\n return anthropicApiKeyProvider(\n bareModelId,\n storedCred.key.trim(),\n args.headers,\n this.#thinkingLevel,\n this.#anthropicPromptCacheScope,\n ) as unknown as GatewayLanguageModel;\n }\n\n const apiKey = getAnthropicApiKey(this.#credentials);\n if (apiKey) {\n return anthropicApiKeyProvider(\n bareModelId,\n apiKey,\n args.headers,\n this.#thinkingLevel,\n this.#anthropicPromptCacheScope,\n ) as unknown as GatewayLanguageModel;\n }\n\n // No stored credentials: use the OAuth-backed provider so the first request can trigger login.\n return opencodeClaudeMaxProvider(bareModelId, {\n headers: args.headers,\n authStorage: this.#credentials,\n thinkingLevel: this.#thinkingLevel,\n promptCacheScope: this.#anthropicPromptCacheScope,\n }) as unknown as GatewayLanguageModel;\n }\n\n #resolveOpenAIModel(args: {\n modelId: string;\n providerId: string;\n apiKey: string;\n headers?: Record<string, string>;\n transport?: any;\n responsesWebSocket?: any;\n }): GatewayLanguageModel | undefined {\n const storedCred = this.#credentials.get('openai-codex');\n\n if (this.#routeThroughMastraGateway) {\n if (storedCred?.type === 'oauth') {\n const resolvedModelId = remapOpenAIModelForCodexOAuth(`openai/${args.modelId}`);\n const resolvedBareModelId = resolvedModelId.substring(OPENAI_PREFIX.length);\n const requestedLevel: ThinkingLevel = this.#thinkingLevel ?? 'medium';\n const effectiveLevel = getEffectiveThinkingLevel(resolvedBareModelId, requestedLevel);\n const reasoningEffort = THINKING_LEVEL_TO_REASONING_EFFORT[effectiveLevel];\n const middleware = createCodexMiddleware(reasoningEffort);\n const openai = createOpenAI({\n apiKey: 'oauth-gateway-placeholder',\n baseURL: `${this.#mastraGatewayBaseUrl}/v1`,\n headers: {\n [GATEWAY_AUTH_HEADER]: `Bearer ${args.apiKey}`,\n ...args.headers,\n },\n fetch: buildOpenAICodexOAuthFetch({ authStorage: this.#credentials, rewriteUrl: false }) as any,\n });\n\n return wrapLanguageModel({\n model: openai.responses(resolvedBareModelId),\n middleware: [middleware],\n }) as unknown as GatewayLanguageModel;\n }\n\n return this.#mastraGateway.resolveLanguageModel(args) as GatewayLanguageModel;\n }\n\n if (storedCred?.type === 'oauth') {\n const resolvedModelId = remapOpenAIModelForCodexOAuth(`openai/${args.modelId}`);\n return openaiCodexProvider(resolvedModelId.substring(OPENAI_PREFIX.length), {\n thinkingLevel: this.#thinkingLevel,\n headers: args.headers,\n authStorage: this.#credentials,\n }) as unknown as GatewayLanguageModel;\n }\n\n const apiKey = getOpenAIApiKey(this.#credentials);\n if (apiKey) {\n return openaiApiKeyProvider(\n args.modelId,\n apiKey,\n args.headers,\n this.#thinkingLevel,\n ) as unknown as GatewayLanguageModel;\n }\n\n return undefined;\n }\n\n #resolveGoogleModel(args: {\n modelId: string;\n providerId: string;\n apiKey: string;\n headers?: Record<string, string>;\n transport?: any;\n responsesWebSocket?: any;\n }): GatewayLanguageModel {\n const baseModel = this.#routeThroughMastraGateway\n ? (this.#mastraGateway.resolveLanguageModel(args) as GatewayLanguageModel)\n : (new ModelRouterLanguageModel({\n id: `${args.providerId}/${args.modelId}` as `${string}/${string}`,\n apiKey: args.apiKey,\n headers: args.headers,\n }) as unknown as GatewayLanguageModel);\n\n const thinkingMiddleware = createGoogleThinkingMiddleware(args.modelId, this.#thinkingLevel);\n if (!thinkingMiddleware) return baseModel;\n\n return wrapLanguageModel({\n model: baseModel as any,\n middleware: [thinking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AC/B,QAAQ,KAAK;GACb,SAAS,KAAK;EAChB,CAAC;EAEL,MAAM,qBAAqB,+BAA+B,KAAK,SAAS,KAAKI,cAAc;EAC3F,IAAI,CAAC,oBAAoB,OAAO;EAEhC,OAAO,kBAAkB;GACvB,OAAO;GACP,YAAY,CAAC,kBAAkB;EACjC,CAAC;CACH;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"memory.d.ts","sourceRoot":"","sources":["../../src/agents/memory.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AACnE,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,sBAAsB,CAAC;AACjE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAExD,OAAO,EAAE,MAAM,EAAgB,MAAM,gBAAgB,CAAC;AAEtD,OAAO,EAAE,sBAAsB,EAAiC,MAAM,uBAAuB,CAAC;AAE9F,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAgFpD,OAAO,EAAE,sBAAsB,EAAE,CAAC;AA8BlC;;;GAGG;AACH,wBAAgB,qBAAqB,CAAC,MAAM,EAAE,YAAY,GAAG,SAAS,GAAG,OAAO,CAE/E;AAED;;;;;;;GAOG;AACH,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,YAAY,GAAG,SAAS,EAAE,KAAK,EAAE,eAAe,GAAG,SAAS,GAAG,OAAO,CAElH;AAED;;;;GAIG;AACH,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,oBAAoB,EAAE,MAAM,CAAC,EAAE,YAAY,EAAE,YAAY,CAAC,EAAE,MAAM,IAelG,oBAAoB;IAAE,cAAc,EAAE,cAAc,CAAA;CAAE,YAyG/D"}
1
+ {"version":3,"file":"memory.d.ts","sourceRoot":"","sources":["../../src/agents/memory.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AACnE,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,sBAAsB,CAAC;AACjE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAExD,OAAO,EAAE,MAAM,EAAgB,MAAM,gBAAgB,CAAC;AAEtD,OAAO,EAAE,sBAAsB,EAAiC,MAAM,uBAAuB,CAAC;AAG9F,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAiFpD,OAAO,EAAE,sBAAsB,EAAE,CAAC;AA8BlC;;;GAGG;AACH,wBAAgB,qBAAqB,CAAC,MAAM,EAAE,YAAY,GAAG,SAAS,GAAG,OAAO,CAE/E;AAED;;;;;;;GAOG;AACH,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,YAAY,GAAG,SAAS,EAAE,KAAK,EAAE,eAAe,GAAG,SAAS,GAAG,OAAO,CAElH;AAED;;;;GAIG;AACH,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,oBAAoB,EAAE,MAAM,CAAC,EAAE,YAAY,EAAE,YAAY,CAAC,EAAE,MAAM,IAelG,oBAAoB;IAAE,cAAc,EAAE,cAAc,CAAA;CAAE,YA0G/D"}
@@ -2,6 +2,7 @@ import { DEFAULT_OM_MODEL_ID } from "../constants.js";
2
2
  import { getOmScope } from "../utils/project.js";
3
3
  import { loadSettings } from "../onboarding/settings.js";
4
4
  import { LOCAL_KNOWLEDGE_ORG_ID, resolveKnowledgeScopeIdentity } from "../knowledge-scope.js";
5
+ import "../providers/anthropic-prompt-cache.js";
5
6
  import { resolveModel, resolvePackMemoryModelChain } from "./model.js";
6
7
  import { fastembed } from "@mastra/fastembed";
7
8
  import { Memory, Subconscious } from "@mastra/memory";
@@ -21,7 +22,8 @@ function resolveOmRoleModelForRequest(role, requestContext, settingsPath) {
21
22
  const state = controller?.getState();
22
23
  const resolveOptions = {
23
24
  remapForCodexOAuth: true,
24
- requestContext
25
+ requestContext,
26
+ anthropicPromptCacheScope: "system"
25
27
  };
26
28
  const settings = loadSettings(settingsPath);
27
29
  const roleOverride = role === "observer" ? settings.models?.observerModelOverride : settings.models?.reflectorModelOverride;
@@ -145,7 +147,10 @@ function getDynamicMemory(storage, vector, settingsPath) {
145
147
  ...isFactory ? { maxSteps: 25 } : {}
146
148
  }) : void 0,
147
149
  scope: omScope,
148
- activateAfterIdle: "auto",
150
+ activateAfterIdle: {
151
+ default: "auto",
152
+ anthropic: "1h"
153
+ },
149
154
  activateOnProviderChange: true,
150
155
  observation: {
151
156
  bufferTokens: isResourceScope ? false : 1 / 5,
@@ -1 +1 @@
1
- {"version":3,"file":"memory.js","names":[],"sources":["../../src/agents/memory.ts"],"sourcesContent":["import type { AgentControllerRequestContext } from '@mastra/core/agent-controller';\nimport type { GatewayLanguageModel } from '@mastra/core/llm';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport type { MastraCompositeStore } from '@mastra/core/storage';\nimport type { MastraVector } from '@mastra/core/vector';\nimport { fastembed } from '@mastra/fastembed';\nimport { Memory, Subconscious } from '@mastra/memory';\nimport { DEFAULT_OM_MODEL_ID, DEFAULT_OBS_THRESHOLD, DEFAULT_REF_THRESHOLD } from '../constants.js';\nimport { LOCAL_KNOWLEDGE_ORG_ID, resolveKnowledgeScopeIdentity } from '../knowledge-scope.js';\nimport { loadSettings } from '../onboarding/settings.js';\nimport type { MastraCodeState } from '../schema.js';\nimport { getOmScope } from '../utils/project.js';\nimport { resolveModel, resolvePackMemoryModelChain } from './model.js';\nimport type { PackMemoryModelChainEntry } from './model.js';\n\n/**\n * Resolve one OM role's model for this invocation. Lookup order:\n * 1. The explicit role override (`observerModelOverride` / `reflectorModelOverride`).\n * 2. The active mode pack's optional `models.memory`, walking the pack's fallback\n * chain so OM fails over alongside (and independently of) the main agent.\n * The pending pack-hop marker wins over the settled pack id so an immediate\n * retrigger observes on the landed pack.\n * 3. The standalone OM configuration seeded into controller state\n * (`observerModelId` / `reflectorModelId`), then the default OM model.\n */\nfunction resolveOmRoleModelForRequest(\n role: 'observer' | 'reflector',\n requestContext: RequestContext,\n settingsPath?: string,\n): GatewayLanguageModel | PackMemoryModelChainEntry[] {\n const controller = requestContext.get('controller') as AgentControllerRequestContext<MastraCodeState> | undefined;\n const state = controller?.getState() as MastraCodeState | undefined;\n const resolveOptions = { remapForCodexOAuth: true, requestContext } as const;\n\n // The configured settings file, not the default one: a caller that points the\n // agent at another settings path must get the same pack/override resolution\n // for observational memory as it does for the main model.\n const settings = loadSettings(settingsPath);\n const roleOverride =\n role === 'observer' ? settings.models?.observerModelOverride : settings.models?.reflectorModelOverride;\n if (roleOverride) return resolveModel(roleOverride, resolveOptions);\n\n const pendingState = state?.mastracodePendingPackFallback as\n | { toPackId?: unknown; threadId?: unknown }\n | null\n | undefined;\n const pendingPackId =\n pendingState &&\n (pendingState.threadId === undefined || pendingState.threadId === controller?.threadId) &&\n typeof pendingState.toPackId === 'string' &&\n pendingState.toPackId.length > 0\n ? pendingState.toPackId\n : undefined;\n const packId = pendingPackId ?? state?.activeModelPackId ?? settings.models?.activeModelPackId;\n if (typeof packId === 'string' && packId.length > 0) {\n const chained = resolvePackMemoryModelChain(settings, packId, resolveOptions);\n if (chained) return chained;\n }\n\n const stateModelId = role === 'observer' ? state?.observerModelId : state?.reflectorModelId;\n return resolveModel(stateModelId ?? DEFAULT_OM_MODEL_ID, resolveOptions);\n}\n\nconst DYNAMIC_AGENTS_MD_INSTRUCTION =\n 'Messages wrapped in <system-reminder type=\"dynamic-agents-md\" ...>...</system-reminder> are ephemeral project-context instructions injected from files on disk. Do NOT observe or extract information from these messages — they are reloaded automatically when needed and should not be stored in memory.';\n\n// Derived from https://github.com/JuliusBrussee/caveman and adapted for OM use with fixed full-level compression.\nconst CAVEMAN_OM_INSTRUCTION = `Respond terse like smart caveman. All technical substance stay. Only fluff die.\n\nUse full caveman compression style.\n\nDrop: articles (a/an/the), filler (just/really/basically/actually/simply), pleasantries (sure/certainly/of course/happy to), hedging. Fragments OK. Short synonyms (big not extensive, fix not \"implement a solution for\"). Technical terms exact. Code blocks unchanged. Errors quoted exact. Leave out the words \"agent\" and \"assistant\" at the start of each observation line, it is assumed each line is referring to the assistant unless it specifically says it was about the user. Leave out parenthesis and other text characters like * that would not contribute to understanding the observations.\n\nPattern: \\`[thing] [action] [reason]. [next step]\\`\n\nNot: \"Sure! I'd be happy to help you with that. The issue you're experiencing is likely caused by...\"\nYes: \"Bug in auth middleware. Token expiry check use < not <=. Fix:\"\n\nExample 1\n🔴 14:31 user asks why React component rerenders\n🟡 14:32 saw inline object prop create new ref each render, cause rerender\n✅ 14:34 fixed render issue by wrap object in useMemo\n\nExample 2\n🟡 15:10 explained pool reuse DB connections, skip repeat handshake overhead\n\nDon't say \"Agent did x\", say \"did x\". It will be assumed the agent did what was observed. The who should only be specified for the user or other third parties: \"user asked x\"\n\nDrop caveman for: security warnings, irreversible action confirmations, multi-step sequences where fragment order risks misread, user asks to clarify or repeats question, and anything that requires remembering verbatim content. Resume caveman after clear part done`;\n\nexport { LOCAL_KNOWLEDGE_ORG_ID };\n\n// One error per session, not per memory resolution. Keyed on the session id\n// rather than the controller object: the controller is read off the request\n// context on every resolution, so it is a fresh object per request and would\n// dedupe nothing. Bounded so a long-running Factory process cannot grow this\n// without limit — refusing sessions are rare, and losing the oldest ids only\n// costs one extra log line.\nconst REPORTED_ORG_UNRESOLVED_LIMIT = 500;\nconst reportedOrgUnresolved = new Set<string>();\n\nfunction reportOrgUnresolved(\n controller: AgentControllerRequestContext<MastraCodeState> | undefined,\n factoryProjectId: string | undefined,\n reason?: string,\n) {\n const sessionId = controller?.session?.id;\n if (sessionId) {\n if (reportedOrgUnresolved.has(sessionId)) return;\n if (reportedOrgUnresolved.size >= REPORTED_ORG_UNRESOLVED_LIMIT) {\n reportedOrgUnresolved.delete(reportedOrgUnresolved.values().next().value as string);\n }\n reportedOrgUnresolved.add(sessionId);\n }\n const session = controller?.session;\n console.error(\n `[Subconscious] Knowledge curation disabled: no organization resolved for session ${session?.id ?? 'unknown'} (project ${factoryProjectId ?? 'none'})${reason ? `: ${reason}` : ''}. Knowledge is not written rather than written where it cannot be read.`,\n );\n}\n\n/**\n * Whether the experimental subconscious (knowledge graph + reminder sidekick)\n * is switched on for this process: it needs a vector store and the opt-in flag.\n */\nexport function isSubconsciousEnabled(vector: MastraVector | undefined): boolean {\n return Boolean(vector) && process.env.MASTRACODE_EXPERIMENTAL_SUBCONSCIOUS === '1';\n}\n\n/**\n * Whether the subconscious tools (`knowledge_*`, `ask_memory`) are registered\n * for a given session. Beyond the process-level switch, a Factory-owned\n * session that cannot resolve its org refuses the subconscious entirely (see\n * `getDynamicMemory`, which applies the same two checks inline because it also\n * needs the resolved identity). The system prompt's tool guidance calls here so\n * it never advertises tools that `getDynamicMemory` did not register.\n */\nexport function hasSubconsciousTools(vector: MastraVector | undefined, state: MastraCodeState | undefined): boolean {\n return isSubconsciousEnabled(vector) && resolveKnowledgeScopeIdentity(state).resolved;\n}\n\n/**\n * Dynamic memory factory function.\n * Reads OM thresholds from controller state via requestContext.\n * Model functions also read from requestContext (no mutable bridge needed).\n */\nexport function getDynamicMemory(storage: MastraCompositeStore, vector?: MastraVector, settingsPath?: string) {\n // Cache is scoped per storage instance (per getDynamicMemory call) so a\n // Memory bound to one storage is never reused after storage changes.\n let cachedMemory: Memory | null = null;\n let cachedMemoryKey: string | null = null;\n\n // Observer/reflector model functions — read the current model ID from\n // controller state via requestContext (propagated by OM's agent.generate).\n // Bound here so the configured settings path reaches role overrides and pack\n // memory-model resolution.\n const getObserverModel = ({ requestContext }: { requestContext: RequestContext }) =>\n resolveOmRoleModelForRequest('observer', requestContext, settingsPath);\n const getReflectorModel = ({ requestContext }: { requestContext: RequestContext }) =>\n resolveOmRoleModelForRequest('reflector', requestContext, settingsPath);\n\n return ({ requestContext }: { requestContext: RequestContext }) => {\n const controller = requestContext.get('controller') as AgentControllerRequestContext<MastraCodeState> | undefined;\n const state = controller?.getState() as MastraCodeState | undefined;\n const subconsciousEnabled = isSubconsciousEnabled(vector);\n const factoryProjectId = state?.factoryProjectId;\n const isFactory = typeof factoryProjectId === 'string' && factoryProjectId.trim().length > 0;\n\n // A Factory-owned session that could not resolve its org refuses to curate:\n // writing under a substituted identity produces knowledge the fail-closed\n // read path can never see.\n let orgUnresolvedRefusal = false;\n\n if (subconsciousEnabled) {\n const identity = resolveKnowledgeScopeIdentity(state);\n if (identity.resolved) {\n requestContext.set('organizationId', identity.organizationId);\n } else {\n orgUnresolvedRefusal = true;\n reportOrgUnresolved(controller, identity.knowledgeResourceId, identity.reason);\n }\n if (identity.knowledgeResourceId) {\n requestContext.set('knowledgeResourceId', identity.knowledgeResourceId);\n }\n }\n\n const subconsciousAvailable = subconsciousEnabled && !orgUnresolvedRefusal;\n\n const omScope = state?.omScope ?? getOmScope(state?.projectPath);\n\n const obsThreshold = state?.observationThreshold ?? DEFAULT_OBS_THRESHOLD;\n const refThreshold = state?.reflectionThreshold ?? DEFAULT_REF_THRESHOLD;\n const caveman = state?.cavemanObservations ?? false;\n\n const observerPreviousObservationTokens = 1000;\n const observeAttachments = state?.observeAttachments;\n // Factory sessions get a factory-only Subconscious config, so the cache key\n // carries a factory presence bit to keep the two configs from cross-serving.\n const cacheKey = `${obsThreshold}:${refThreshold}:${omScope}:${observerPreviousObservationTokens}:${caveman ? 1 : 0}:${observeAttachments}:${isFactory ? 1 : 0}:${subconsciousAvailable ? 1 : 0}`;\n if (cachedMemory && cachedMemoryKey === cacheKey) {\n return cachedMemory;\n }\n\n // Async buffering is not supported with resource scope — disable it\n const isResourceScope = omScope === 'resource';\n\n const observerInstruction = caveman\n ? `${DYNAMIC_AGENTS_MD_INSTRUCTION}\\n\\n${CAVEMAN_OM_INSTRUCTION}`\n : DYNAMIC_AGENTS_MD_INSTRUCTION;\n const reflectionInstruction = caveman ? CAVEMAN_OM_INSTRUCTION : undefined;\n\n cachedMemory = new Memory({\n storage,\n vector: vector || false,\n embedder: vector ? fastembed.small : undefined,\n options: {\n // Generate a durable title from the first user message. Every client uses\n // the same title in its thread list and active-session chrome. Title\n // generation takes the primary OM model only — its model field does not\n // accept fallback arrays.\n generateTitle: {\n model: ({ requestContext }) => {\n const resolved = getObserverModel({ requestContext });\n return Array.isArray(resolved) ? resolved[0]!.model : resolved;\n },\n },\n observationalMemory: {\n enabled: true,\n temporalMarkers: true,\n retrieval: vector ? { vector: true } : true,\n experimental_subconscious: subconsciousAvailable\n ? new Subconscious({\n defaultScope: 'resource',\n maxScope: 'resource',\n pins: true,\n ...(isFactory ? { maxSteps: 25 } : {}),\n })\n : undefined,\n scope: omScope,\n activateAfterIdle: 'auto',\n activateOnProviderChange: true,\n observation: {\n bufferTokens: isResourceScope ? false : 1 / 5,\n bufferActivation: isResourceScope ? undefined : 2000,\n model: getObserverModel,\n messageTokens: obsThreshold,\n blockAfter: 2,\n previousObserverTokens: observerPreviousObservationTokens,\n threadTitle: true,\n instruction: observerInstruction,\n observeAttachments,\n },\n reflection: {\n bufferActivation: isResourceScope ? undefined : 1 / 2,\n blockAfter: 1.1,\n model: getReflectorModel,\n observationTokens: refThreshold,\n instruction: reflectionInstruction,\n },\n },\n },\n });\n cachedMemoryKey = cacheKey;\n\n return cachedMemory;\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAyBA,SAAS,6BACP,MACA,gBACA,cACoD;CACpD,MAAM,aAAa,eAAe,IAAI,YAAY;CAClD,MAAM,QAAQ,YAAY,SAAS;CACnC,MAAM,iBAAiB;EAAE,oBAAoB;EAAM;CAAe;CAKlE,MAAM,WAAW,aAAa,YAAY;CAC1C,MAAM,eACJ,SAAS,aAAa,SAAS,QAAQ,wBAAwB,SAAS,QAAQ;CAClF,IAAI,cAAc,OAAO,aAAa,cAAc,cAAc;CAElE,MAAM,eAAe,OAAO;CAW5B,MAAM,UANJ,iBACC,aAAa,aAAa,KAAA,KAAa,aAAa,aAAa,YAAY,aAC9E,OAAO,aAAa,aAAa,YACjC,aAAa,SAAS,SAAS,IAC3B,aAAa,WACb,KAAA,MAC0B,OAAO,qBAAqB,SAAS,QAAQ;CAC7E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BAAiB;KACjB,WAAW,SAAS,EAAE,QAAQ,KAAK,IAAI;KACvC,2BAA2B,wBACvB,IAAI,aAAa;MACf,cAAc;MACd,UAAU;MACV,MAAM;MACN,GAAI,YAAY,EAAE,UAAU,GAAG,IAAI,CAAC;KACtC,CAAC,IACD,KAAA;KACJ,OAAO;KACP,mBAAmB;KACnB,0BAA0B;KAC1B,aAAa;MACX,cAAc,kBAAkB,QAAQ,IAAI;MAC5C,kBAAkB,kBAAkB,KAAA,IAAY;MAChD,OAAO;MACP,eAAe;MACf,YAAY;MACZ,wBAAwB;MACxB,aAAa;MACb,aAAa;MACb;KACF;KACA,YAAY;MACV,kBAAkB,kBAAkB,KAAA,IAAY,IAAI;MACpD,YAAY;MACZ,OAAO;MACP,mBAAmB;MACnB,aAAa;KACf;IACF;GACF;EACF,CAAC;EACD,kBAAkB;EAElB,OAAO;CACT;AACF"}
1
+ {"version":3,"file":"memory.js","names":[],"sources":["../../src/agents/memory.ts"],"sourcesContent":["import type { AgentControllerRequestContext } from '@mastra/core/agent-controller';\nimport type { GatewayLanguageModel } from '@mastra/core/llm';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport type { MastraCompositeStore } from '@mastra/core/storage';\nimport type { MastraVector } from '@mastra/core/vector';\nimport { fastembed } from '@mastra/fastembed';\nimport { Memory, Subconscious } from '@mastra/memory';\nimport { DEFAULT_OM_MODEL_ID, DEFAULT_OBS_THRESHOLD, DEFAULT_REF_THRESHOLD } from '../constants.js';\nimport { LOCAL_KNOWLEDGE_ORG_ID, resolveKnowledgeScopeIdentity } from '../knowledge-scope.js';\nimport { loadSettings } from '../onboarding/settings.js';\nimport { ANTHROPIC_PROMPT_CACHE_TTL } from '../providers/anthropic-prompt-cache.js';\nimport type { MastraCodeState } from '../schema.js';\nimport { getOmScope } from '../utils/project.js';\nimport { resolveModel, resolvePackMemoryModelChain } from './model.js';\nimport type { PackMemoryModelChainEntry } from './model.js';\n\n/**\n * Resolve one OM role's model for this invocation. Lookup order:\n * 1. The explicit role override (`observerModelOverride` / `reflectorModelOverride`).\n * 2. The active mode pack's optional `models.memory`, walking the pack's fallback\n * chain so OM fails over alongside (and independently of) the main agent.\n * The pending pack-hop marker wins over the settled pack id so an immediate\n * retrigger observes on the landed pack.\n * 3. The standalone OM configuration seeded into controller state\n * (`observerModelId` / `reflectorModelId`), then the default OM model.\n */\nfunction resolveOmRoleModelForRequest(\n role: 'observer' | 'reflector',\n requestContext: RequestContext,\n settingsPath?: string,\n): GatewayLanguageModel | PackMemoryModelChainEntry[] {\n const controller = requestContext.get('controller') as AgentControllerRequestContext<MastraCodeState> | undefined;\n const state = controller?.getState() as MastraCodeState | undefined;\n // OM calls send different content every time, so only their shared instructions are worth caching.\n const resolveOptions = { remapForCodexOAuth: true, requestContext, anthropicPromptCacheScope: 'system' } as const;\n\n // The configured settings file, not the default one: a caller that points the\n // agent at another settings path must get the same pack/override resolution\n // for observational memory as it does for the main model.\n const settings = loadSettings(settingsPath);\n const roleOverride =\n role === 'observer' ? settings.models?.observerModelOverride : settings.models?.reflectorModelOverride;\n if (roleOverride) return resolveModel(roleOverride, resolveOptions);\n\n const pendingState = state?.mastracodePendingPackFallback as\n | { toPackId?: unknown; threadId?: unknown }\n | null\n | undefined;\n const pendingPackId =\n pendingState &&\n (pendingState.threadId === undefined || pendingState.threadId === controller?.threadId) &&\n typeof pendingState.toPackId === 'string' &&\n pendingState.toPackId.length > 0\n ? pendingState.toPackId\n : undefined;\n const packId = pendingPackId ?? state?.activeModelPackId ?? settings.models?.activeModelPackId;\n if (typeof packId === 'string' && packId.length > 0) {\n const chained = resolvePackMemoryModelChain(settings, packId, resolveOptions);\n if (chained) return chained;\n }\n\n const stateModelId = role === 'observer' ? state?.observerModelId : state?.reflectorModelId;\n return resolveModel(stateModelId ?? DEFAULT_OM_MODEL_ID, resolveOptions);\n}\n\nconst DYNAMIC_AGENTS_MD_INSTRUCTION =\n 'Messages wrapped in <system-reminder type=\"dynamic-agents-md\" ...>...</system-reminder> are ephemeral project-context instructions injected from files on disk. Do NOT observe or extract information from these messages — they are reloaded automatically when needed and should not be stored in memory.';\n\n// Derived from https://github.com/JuliusBrussee/caveman and adapted for OM use with fixed full-level compression.\nconst CAVEMAN_OM_INSTRUCTION = `Respond terse like smart caveman. All technical substance stay. Only fluff die.\n\nUse full caveman compression style.\n\nDrop: articles (a/an/the), filler (just/really/basically/actually/simply), pleasantries (sure/certainly/of course/happy to), hedging. Fragments OK. Short synonyms (big not extensive, fix not \"implement a solution for\"). Technical terms exact. Code blocks unchanged. Errors quoted exact. Leave out the words \"agent\" and \"assistant\" at the start of each observation line, it is assumed each line is referring to the assistant unless it specifically says it was about the user. Leave out parenthesis and other text characters like * that would not contribute to understanding the observations.\n\nPattern: \\`[thing] [action] [reason]. [next step]\\`\n\nNot: \"Sure! I'd be happy to help you with that. The issue you're experiencing is likely caused by...\"\nYes: \"Bug in auth middleware. Token expiry check use < not <=. Fix:\"\n\nExample 1\n🔴 14:31 user asks why React component rerenders\n🟡 14:32 saw inline object prop create new ref each render, cause rerender\n✅ 14:34 fixed render issue by wrap object in useMemo\n\nExample 2\n🟡 15:10 explained pool reuse DB connections, skip repeat handshake overhead\n\nDon't say \"Agent did x\", say \"did x\". It will be assumed the agent did what was observed. The who should only be specified for the user or other third parties: \"user asked x\"\n\nDrop caveman for: security warnings, irreversible action confirmations, multi-step sequences where fragment order risks misread, user asks to clarify or repeats question, and anything that requires remembering verbatim content. Resume caveman after clear part done`;\n\nexport { LOCAL_KNOWLEDGE_ORG_ID };\n\n// One error per session, not per memory resolution. Keyed on the session id\n// rather than the controller object: the controller is read off the request\n// context on every resolution, so it is a fresh object per request and would\n// dedupe nothing. Bounded so a long-running Factory process cannot grow this\n// without limit — refusing sessions are rare, and losing the oldest ids only\n// costs one extra log line.\nconst REPORTED_ORG_UNRESOLVED_LIMIT = 500;\nconst reportedOrgUnresolved = new Set<string>();\n\nfunction reportOrgUnresolved(\n controller: AgentControllerRequestContext<MastraCodeState> | undefined,\n factoryProjectId: string | undefined,\n reason?: string,\n) {\n const sessionId = controller?.session?.id;\n if (sessionId) {\n if (reportedOrgUnresolved.has(sessionId)) return;\n if (reportedOrgUnresolved.size >= REPORTED_ORG_UNRESOLVED_LIMIT) {\n reportedOrgUnresolved.delete(reportedOrgUnresolved.values().next().value as string);\n }\n reportedOrgUnresolved.add(sessionId);\n }\n const session = controller?.session;\n console.error(\n `[Subconscious] Knowledge curation disabled: no organization resolved for session ${session?.id ?? 'unknown'} (project ${factoryProjectId ?? 'none'})${reason ? `: ${reason}` : ''}. Knowledge is not written rather than written where it cannot be read.`,\n );\n}\n\n/**\n * Whether the experimental subconscious (knowledge graph + reminder sidekick)\n * is switched on for this process: it needs a vector store and the opt-in flag.\n */\nexport function isSubconsciousEnabled(vector: MastraVector | undefined): boolean {\n return Boolean(vector) && process.env.MASTRACODE_EXPERIMENTAL_SUBCONSCIOUS === '1';\n}\n\n/**\n * Whether the subconscious tools (`knowledge_*`, `ask_memory`) are registered\n * for a given session. Beyond the process-level switch, a Factory-owned\n * session that cannot resolve its org refuses the subconscious entirely (see\n * `getDynamicMemory`, which applies the same two checks inline because it also\n * needs the resolved identity). The system prompt's tool guidance calls here so\n * it never advertises tools that `getDynamicMemory` did not register.\n */\nexport function hasSubconsciousTools(vector: MastraVector | undefined, state: MastraCodeState | undefined): boolean {\n return isSubconsciousEnabled(vector) && resolveKnowledgeScopeIdentity(state).resolved;\n}\n\n/**\n * Dynamic memory factory function.\n * Reads OM thresholds from controller state via requestContext.\n * Model functions also read from requestContext (no mutable bridge needed).\n */\nexport function getDynamicMemory(storage: MastraCompositeStore, vector?: MastraVector, settingsPath?: string) {\n // Cache is scoped per storage instance (per getDynamicMemory call) so a\n // Memory bound to one storage is never reused after storage changes.\n let cachedMemory: Memory | null = null;\n let cachedMemoryKey: string | null = null;\n\n // Observer/reflector model functions — read the current model ID from\n // controller state via requestContext (propagated by OM's agent.generate).\n // Bound here so the configured settings path reaches role overrides and pack\n // memory-model resolution.\n const getObserverModel = ({ requestContext }: { requestContext: RequestContext }) =>\n resolveOmRoleModelForRequest('observer', requestContext, settingsPath);\n const getReflectorModel = ({ requestContext }: { requestContext: RequestContext }) =>\n resolveOmRoleModelForRequest('reflector', requestContext, settingsPath);\n\n return ({ requestContext }: { requestContext: RequestContext }) => {\n const controller = requestContext.get('controller') as AgentControllerRequestContext<MastraCodeState> | undefined;\n const state = controller?.getState() as MastraCodeState | undefined;\n const subconsciousEnabled = isSubconsciousEnabled(vector);\n const factoryProjectId = state?.factoryProjectId;\n const isFactory = typeof factoryProjectId === 'string' && factoryProjectId.trim().length > 0;\n\n // A Factory-owned session that could not resolve its org refuses to curate:\n // writing under a substituted identity produces knowledge the fail-closed\n // read path can never see.\n let orgUnresolvedRefusal = false;\n\n if (subconsciousEnabled) {\n const identity = resolveKnowledgeScopeIdentity(state);\n if (identity.resolved) {\n requestContext.set('organizationId', identity.organizationId);\n } else {\n orgUnresolvedRefusal = true;\n reportOrgUnresolved(controller, identity.knowledgeResourceId, identity.reason);\n }\n if (identity.knowledgeResourceId) {\n requestContext.set('knowledgeResourceId', identity.knowledgeResourceId);\n }\n }\n\n const subconsciousAvailable = subconsciousEnabled && !orgUnresolvedRefusal;\n\n const omScope = state?.omScope ?? getOmScope(state?.projectPath);\n\n const obsThreshold = state?.observationThreshold ?? DEFAULT_OBS_THRESHOLD;\n const refThreshold = state?.reflectionThreshold ?? DEFAULT_REF_THRESHOLD;\n const caveman = state?.cavemanObservations ?? false;\n\n const observerPreviousObservationTokens = 1000;\n const observeAttachments = state?.observeAttachments;\n // Factory sessions get a factory-only Subconscious config, so the cache key\n // carries a factory presence bit to keep the two configs from cross-serving.\n const cacheKey = `${obsThreshold}:${refThreshold}:${omScope}:${observerPreviousObservationTokens}:${caveman ? 1 : 0}:${observeAttachments}:${isFactory ? 1 : 0}:${subconsciousAvailable ? 1 : 0}`;\n if (cachedMemory && cachedMemoryKey === cacheKey) {\n return cachedMemory;\n }\n\n // Async buffering is not supported with resource scope — disable it\n const isResourceScope = omScope === 'resource';\n\n const observerInstruction = caveman\n ? `${DYNAMIC_AGENTS_MD_INSTRUCTION}\\n\\n${CAVEMAN_OM_INSTRUCTION}`\n : DYNAMIC_AGENTS_MD_INSTRUCTION;\n const reflectionInstruction = caveman ? CAVEMAN_OM_INSTRUCTION : undefined;\n\n cachedMemory = new Memory({\n storage,\n vector: vector || false,\n embedder: vector ? fastembed.small : undefined,\n options: {\n // Generate a durable title from the first user message. Every client uses\n // the same title in its thread list and active-session chrome. Title\n // generation takes the primary OM model only — its model field does not\n // accept fallback arrays.\n generateTitle: {\n model: ({ requestContext }) => {\n const resolved = getObserverModel({ requestContext });\n return Array.isArray(resolved) ? resolved[0]!.model : resolved;\n },\n },\n observationalMemory: {\n enabled: true,\n temporalMarkers: true,\n retrieval: vector ? { vector: true } : true,\n experimental_subconscious: subconsciousAvailable\n ? new Subconscious({\n defaultScope: 'resource',\n maxScope: 'resource',\n pins: true,\n ...(isFactory ? { maxSteps: 25 } : {}),\n })\n : undefined,\n scope: omScope,\n // The main agent writes Anthropic cache entries with this TTL; 'auto' can't see it.\n activateAfterIdle: { default: 'auto', anthropic: ANTHROPIC_PROMPT_CACHE_TTL },\n activateOnProviderChange: true,\n observation: {\n bufferTokens: isResourceScope ? false : 1 / 5,\n bufferActivation: isResourceScope ? undefined : 2000,\n model: getObserverModel,\n messageTokens: obsThreshold,\n blockAfter: 2,\n previousObserverTokens: observerPreviousObservationTokens,\n threadTitle: true,\n instruction: observerInstruction,\n observeAttachments,\n },\n reflection: {\n bufferActivation: isResourceScope ? undefined : 1 / 2,\n blockAfter: 1.1,\n model: getReflectorModel,\n observationTokens: refThreshold,\n instruction: reflectionInstruction,\n },\n },\n },\n });\n cachedMemoryKey = cacheKey;\n\n return cachedMemory;\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA0BA,SAAS,6BACP,MACA,gBACA,cACoD;CACpD,MAAM,aAAa,eAAe,IAAI,YAAY;CAClD,MAAM,QA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B,UACtC,OAAO;EAIT,MAAM,kBAAkB,YAAY;EAEpC,MAAM,sBAAsB,UACxB,GAAG,8BAA8B,MAAM,2BACvC;EACJ,MAAM,wBAAwB,UAAU,yBAAyB,KAAA;EAEjE,eAAe,IAAI,OAAO;GACxB;GACA,QAAQ,UAAU;GAClB,UAAU,SAAS,UAAU,QAAQ,KAAA;GACrC,SAAS;IAKP,eAAe,EACb,QAAQ,EAAE,qBAAqB;KAC7B,MAAM,WAAW,iBAAiB,EAAE,eAAe,CAAC;KACpD,OAAO,MAAM,QAAQ,QAAQ,IAAI,SAAS,EAAE,CAAE,QAAQ;IACxD,EACF;IACA,qBAAqB;KACnB,SAAS;KACT,iBAAiB;KACjB,WAAW,SAAS,EAAE,QAAQ,KAAK,IAAI;KACvC,2BAA2B,wBACvB,IAAI,aAAa;MACf,cAAc;MACd,UAAU;MACV,MAAM;MACN,GAAI,YAAY,EAAE,UAAU,GAAG,IAAI,CAAC;KACtC,CAAC,IACD,KAAA;KACJ,OAAO;KAEP,mBAAmB;MAAE,SAAS;MAAQ,WAAA;KAAsC;KAC5E,0BAA0B;KAC1B,aAAa;MACX,cAAc,kBAAkB,QAAQ,IAAI;MAC5C,kBAAkB,kBAAkB,KAAA,IAAY;MAChD,OAAO;MACP,eAAe;MACf,YAAY;MACZ,wBAAwB;MACxB,aAAa;MACb,aAAa;MACb;KACF;KACA,YAAY;MACV,kBAAkB,kBAAkB,KAAA,IAAY,IAAI;MACpD,YAAY;MACZ,OAAO;MACP,mBAAmB;MACnB,aAAa;KACf;IACF;GACF;EACF,CAAC;EACD,kBAAkB;EAElB,OAAO;CACT;AACF"}
@@ -3,6 +3,7 @@ import type { GatewayLanguageModel, MastraModelGatewayInterface } from '@mastra/
3
3
  import type { RequestContext } from '@mastra/core/request-context';
4
4
  import type { CredentialStore } from '../auth/types.js';
5
5
  import { loadSettings } from '../onboarding/settings.js';
6
+ import type { AnthropicPromptCacheScope } from '../providers/anthropic-prompt-cache.js';
6
7
  import type { ThinkingLevelSetting } from '../thinking.js';
7
8
  import { MastraCodeGateway } from './mastracode-gateway.js';
8
9
  import type { MastraCodeGatewayOptions } from './mastracode-gateway.js';
@@ -35,6 +36,7 @@ export declare function resolveModel(modelId: string, options?: {
35
36
  thinkingLevel?: ThinkingLevelSetting;
36
37
  remapForCodexOAuth?: boolean;
37
38
  requestContext?: RequestContext;
39
+ anthropicPromptCacheScope?: AnthropicPromptCacheScope;
38
40
  }): GatewayLanguageModel;
39
41
  export interface ThinkingRequestContext {
40
42
  state?: {
@@ -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,KAAK,EAAE,oBAAoB,EAAE,2BAA2B,EAAE,MAAM,kBAAkB,CAAC;AAC1F,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAGnE,OAAO,KAAK,EAAE,eAAe,EAAsB,MAAM,kBAAkB,CAAC;AAE5E,OAAO,EAEL,YAAY,EAIb,MAAM,2BAA2B,CAAC;AAGnC,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAC;AAG3D,OAAO,EAGL,iBAAiB,EAIlB,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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AAc,EAAE,cAAc,CAAA;CAAE,EACtD,YAAY,CAAC,EAAE,MAAM,GACpB,aAAa,GAAG,SAAS,CAI3B"}
@@ -114,6 +114,7 @@ function resolveModel(modelId, options) {
114
114
  mastraGatewayApiKey: mgApiKey,
115
115
  routeThroughMastraGateway: Boolean(mgApiKey && isMastraGatewayModel),
116
116
  thinkingLevel: options?.thinkingLevel,
117
+ anthropicPromptCacheScope: options?.anthropicPromptCacheScope,
117
118
  customProviders,
118
119
  credentialStore
119
120
  });
@@ -1 +1 @@
1
- {"version":3,"file":"model.js","names":[],"sources":["../../src/agents/model.ts"],"sourcesContent":["import type { ModelWithRetries } from '@mastra/core/agent';\nimport type { AgentControllerRequestContext } from '@mastra/core/agent-controller';\nimport type { GatewayLanguageModel, MastraModelGatewayInterface } from '@mastra/core/llm';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport { getRequestAccountSelection, isRequestAccountRoutingExhausted } from '../auth/account-routing-context.js';\nimport { ProviderAuthRequiredError } from '../auth/provider-auth-error.js';\nimport type { CredentialStore, OAuthAccountRecord } from '../auth/types.js';\nimport { listBuiltinModePacks, resolveModePackFallbackChain } from '../onboarding/packs.js';\nimport {\n findModePackForModel,\n loadSettings,\n resolveDefaultThinkingLevel,\n resolveModePackModels,\n stripMastraCodeCustomProviderPrefix,\n} from '../onboarding/settings.js';\nimport { AMAZON_BEDROCK_GATEWAY_ID, createAmazonBedrockGateway } from '../providers/amazon-bedrock-gateway.js';\nimport { isThinkingLevelSetting } from '../thinking.js';\nimport type { ThinkingLevelSetting } from '../thinking.js';\nimport { resolveCredentialStore } from './credential-resolver.js';\nimport { resolveCustomProviders } from './custom-provider-source.js';\nimport {\n MASTRA_GATEWAY_PREFIX,\n MASTRACODE_GATEWAY_ID,\n MastraCodeGateway,\n getGlobalAuthStorage,\n reloadAuthStorage,\n stripMastraGatewayPrefix,\n} from './mastracode-gateway.js';\nimport type { MastraCodeGatewayOptions } from './mastracode-gateway.js';\n\nexport {\n getAnthropicApiKey,\n getOpenAIApiKey,\n MASTRACODE_GATEWAY_ID,\n MastraCodeGateway,\n remapOpenAIModelForCodexOAuth,\n resolveAuth,\n} from './mastracode-gateway.js';\nexport type { MastraCodeCustomProvider, MastraCodeGatewayOptions } from './mastracode-gateway.js';\nexport {\n setCredentialStoreProvider,\n hasCredentialStoreProvider,\n resolveTenantFromRequestContext,\n} from './credential-resolver.js';\nexport type { CredentialTenant, CredentialStoreProvider } from './credential-resolver.js';\nexport {\n setCustomProvidersSource,\n hasCustomProvidersSource,\n resolveCustomProviders,\n} from './custom-provider-source.js';\nexport type { CustomProvidersSource } from './custom-provider-source.js';\n\ntype ResolvedModel = GatewayLanguageModel;\ntype ModelRequestHeaders = Record<string, string>;\n\nfunction getAgentControllerHeaders(requestContext?: RequestContext): ModelRequestHeaders | undefined {\n const agentControllerContext = requestContext?.get('controller') as AgentControllerRequestContext<any> | undefined;\n const headers = {\n ...(agentControllerContext?.threadId ? { 'x-thread-id': agentControllerContext.threadId } : {}),\n ...(agentControllerContext?.resourceId ? { 'x-resource-id': agentControllerContext.resourceId } : {}),\n };\n\n return Object.keys(headers).length > 0 ? headers : undefined;\n}\n\nfunction accountCredential(account: OAuthAccountRecord) {\n const { type: _type, id: _id, label: _label, addedAt: _addedAt, active: _active, ...credential } = account;\n return { type: 'oauth' as const, ...credential };\n}\n\nexport function createRequestScopedCredentialStore(\n base: CredentialStore,\n requestContext?: RequestContext,\n): CredentialStore {\n const selectedId = (providerId: string) => getRequestAccountSelection(requestContext, providerId);\n const selectedAccount = (providerId: string) => {\n const accountInstanceId = selectedId(providerId);\n return accountInstanceId\n ? base.listAccounts?.(providerId).find(account => account.id === accountInstanceId)\n : undefined;\n };\n // Routing rejected every account for this provider on this request. Fail\n // closed on every credential read: falling through to `base` would use the\n // provider's active account — the exhausted one routing just refused.\n const rejectAll = (providerId: string) => isRequestAccountRoutingExhausted(requestContext, providerId);\n\n return {\n allowEnvironmentFallback: base.allowEnvironmentFallback,\n reload: () => base.reload(),\n get: providerId => {\n if (rejectAll(providerId)) return undefined;\n // A selection that no longer resolves (the account was removed between\n // routing and the credential read) must not fall through to the active\n // account — that is the account routing deliberately passed over.\n const accountInstanceId = selectedId(providerId);\n if (accountInstanceId === undefined) return base.get(providerId);\n const selected = selectedAccount(providerId);\n return selected ? accountCredential(selected) : undefined;\n },\n getStoredApiKey: providerId => {\n if (rejectAll(providerId)) return undefined;\n // The provider-wide `apikey:` slot is never the credential routing\n // selected, so serving it to a routed request is an OAuth -> API-key\n // fallback of the same provider — the one combination this feature\n // forbids. Unlike `get`, this read has no account argument to pass\n // through, so a selection fails it closed instead.\n if (selectedId(providerId) !== undefined) return undefined;\n return base.getStoredApiKey(providerId);\n },\n getApiKey: providerId =>\n rejectAll(providerId) ? Promise.resolve(undefined) : base.getApiKey(providerId, selectedId(providerId)),\n getOAuthCredential: base.getOAuthCredential\n ? providerId =>\n rejectAll(providerId)\n ? Promise.resolve(undefined)\n : base.getOAuthCredential!(providerId, selectedId(providerId))\n : undefined,\n listAccounts: base.listAccounts ? providerId => base.listAccounts!(providerId) : undefined,\n getActiveAccount: base.getActiveAccount ? providerId => base.getActiveAccount!(providerId) : undefined,\n activateAccount: base.activateAccount\n ? (providerId, accountInstanceId) => base.activateAccount!(providerId, accountInstanceId)\n : undefined,\n removeAccount: base.removeAccount\n ? (providerId, accountInstanceId) => base.removeAccount!(providerId, accountInstanceId)\n : undefined,\n };\n}\n\nexport function createMastraCodeGateway(options: MastraCodeGatewayOptions): MastraCodeGateway {\n return new MastraCodeGateway(options);\n}\n\nexport function createMastraCodeModelCatalogProvider(gateway: MastraModelGatewayInterface) {\n return gateway instanceof MastraCodeGateway\n ? gateway.createModelCatalogProvider()\n : MastraCodeGateway.createModelCatalogProvider(gateway);\n}\n\n/**\n * Placeholder for future model ID normalization.\n * Currently returns the input unchanged, but exists as a seam\n * for aliasing, casing fixes, or validation in the future.\n */\nexport function resolveModelId(modelId: string): string {\n return modelId;\n}\n\n/**\n * Resolve a model ID to the correct provider instance.\n * Shared by the main agent, observer, and reflector.\n *\n * - For anthropic/* models: Uses stored OAuth credentials when present, otherwise direct API key\n * - For openai/* models: Uses OAuth when configured, otherwise direct API key from AuthStorage\n * - For moonshotai/* models: Uses Moonshot AI Anthropic-compatible endpoint\n * - For all other providers: Uses Mastra's model router (models.dev gateway)\n */\nexport function resolveModel(\n modelId: string,\n options?: { thinkingLevel?: ThinkingLevelSetting; remapForCodexOAuth?: boolean; requestContext?: RequestContext },\n): GatewayLanguageModel {\n reloadAuthStorage();\n const headers = getAgentControllerHeaders(options?.requestContext);\n const settings = loadSettings();\n // Bedrock was previously cataloged under the MastraCode gateway namespace\n // (`mastracode/amazon-bedrock/<model>`). Normalize any legacy saved ids to the\n // standalone `amazon-bedrock/<model>` form so they resolve through the\n // dedicated Bedrock gateway.\n const bedrockLegacyPrefix = `${MASTRACODE_GATEWAY_ID}/amazon-bedrock/`;\n const bedrockNormalizedInput = modelId.startsWith(bedrockLegacyPrefix)\n ? modelId.slice(MASTRACODE_GATEWAY_ID.length + 1)\n : modelId;\n // Deployed web registers a custom providers source (DB-backed, tenant\n // scoped); when registered it is authoritative and settings.json custom\n // providers are ignored. Undefined = local settings-based behavior.\n const customProviders = resolveCustomProviders(options?.requestContext) ?? settings.customProviders;\n // Ids selected from the shared /models catalog were previously persisted in\n // the gateway-qualified `mastracode/<customProviderId>/<model>` form, which\n // parses the provider as `mastracode` and breaks provider config lookup.\n // Normalize at resolution time (in addition to stripping at selection time)\n // so already-saved ids and any surface that persists the raw catalog id\n // still resolve to the custom provider.\n const normalizedInput = stripMastraCodeCustomProviderPrefix(bedrockNormalizedInput, customProviders);\n const isMastraGatewayModel = normalizedInput.startsWith(MASTRA_GATEWAY_PREFIX);\n const normalizedModelId = stripMastraGatewayPrefix(normalizedInput);\n const [providerId, ...modelParts] = normalizedModelId.split('/');\n const bareModelId = modelParts.join('/');\n if (!providerId || !bareModelId) {\n throw new Error(`Invalid model id: ${modelId}`);\n }\n\n if (providerId === AMAZON_BEDROCK_GATEWAY_ID) {\n const bedrockGateway = createAmazonBedrockGateway();\n const routerId = `${AMAZON_BEDROCK_GATEWAY_ID}/${bareModelId}`;\n const auth = bedrockGateway.resolveAuth({\n gatewayId: AMAZON_BEDROCK_GATEWAY_ID,\n providerId: AMAZON_BEDROCK_GATEWAY_ID,\n modelId: bareModelId,\n routerId,\n });\n return bedrockGateway.resolveLanguageModel({\n providerId: AMAZON_BEDROCK_GATEWAY_ID,\n modelId: bareModelId,\n apiKey: auth?.apiKey ?? '',\n headers,\n });\n }\n\n const routerId = `${MASTRACODE_GATEWAY_ID}/${normalizedModelId}`;\n\n const mgApiKey = MastraCodeGateway.getMastraGatewayApiKey();\n const rawGatewayBase =\n settings.memoryGateway?.baseUrl ?? process.env['MASTRA_GATEWAY_URL'] ?? 'https://gateway-api.mastra.ai';\n // Deployed web registers a per-tenant credential store provider; when the\n // request carries an authenticated tenant, resolve credentials through the\n // caller's own store (user > org > env). Undefined = global AuthStorage.\n const baseCredentialStore = resolveCredentialStore(options?.requestContext) ?? getGlobalAuthStorage();\n const credentialStore = createRequestScopedCredentialStore(baseCredentialStore, options?.requestContext);\n const gateway = createMastraCodeGateway({\n mastraGatewayBaseUrl: rawGatewayBase.replace(/\\/+$/, '').replace(/\\/v1$/, ''),\n mastraGatewayApiKey: mgApiKey,\n routeThroughMastraGateway: Boolean(mgApiKey && isMastraGatewayModel),\n thinkingLevel: options?.thinkingLevel,\n customProviders,\n credentialStore,\n });\n\n const auth = gateway.resolveAuth({\n gatewayId: MASTRACODE_GATEWAY_ID,\n providerId,\n modelId: bareModelId,\n routerId,\n });\n\n if (!auth && credentialStore?.allowEnvironmentFallback === false) {\n throw new ProviderAuthRequiredError(\n `No usable ${providerId} credential is configured for this signed-in Factory account. Connect the provider or add an organization credential, then try again.`,\n );\n }\n\n return gateway.resolveLanguageModel({\n providerId,\n modelId: bareModelId,\n apiKey: auth?.apiKey ?? '',\n headers,\n });\n}\n\nexport interface ThinkingRequestContext {\n state?: { thinkingLevel?: unknown };\n session?: { modeId?: string };\n}\n/**\n * Resolve the effective thinking level for the current request.\n *\n * Precedence:\n * 1. Session override (`state.thinkingLevel`, set via /think or the session\n * settings panel).\n * 2. Per-mode default from settings (`models.modeThinkingDefaults[mode]`).\n * 3. Global default (`preferences.thinkingLevel`).\n *\n * Resolved per-request (not seeded at session start) so configuration changes\n * apply to the next request of every session — including automated\n * (rule-driven) Factory runs that nobody ever opens interactively.\n */\n\nexport function resolveRequestThinkingLevel(\n agentControllerContext: ThinkingRequestContext | undefined,\n settingsPath?: string,\n): ThinkingLevelSetting {\n const override = agentControllerContext?.state?.thinkingLevel;\n if (isThinkingLevelSetting(override)) return override;\n const modeId = agentControllerContext?.session?.modeId;\n return resolveDefaultThinkingLevel(loadSettings(settingsPath), modeId).level;\n}\n\n/** Structural pack shape for fallback resolution (custom pack models are partial by nature). */\nexport interface ResolvableModePack {\n id: string;\n name: string;\n models: Record<string, string>;\n}\n\n/** All packs a fallback chain may reference: every builtin plus saved customs. */\nexport function listResolvableModePacks(settings: ReturnType<typeof loadSettings>): ResolvableModePack[] {\n return [\n ...listBuiltinModePacks(),\n ...settings.customModelPacks.map(pack => ({\n id: `custom:${pack.name}`,\n name: pack.name,\n models: { ...pack.models },\n })),\n ];\n}\n\n/**\n * Dynamic model function that reads the current model from controller state.\n * This allows runtime model switching via the /models picker.\n *\n * When the session's model came from a pack with a fallback chain configured\n * (`settings.models.packFallbacks`), returns core's `ModelWithRetries[]`\n * fallback array instead of a bare model: the active pack's model first, then\n * each fallback pack's model for the same mode. Core advances the array when\n * the error processors decline to retry (pool exhausted / persistent outage —\n * see AccountRotationProcessor). Entry ids are unique per occurrence — the\n * one allowed revisit of a pack gets `<packId>#2` — because core re-resolves\n * the active fallback index by id across agentic steps.\n */\nexport function getDynamicModel(\n { requestContext }: { requestContext: RequestContext },\n settingsPath?: string,\n): ResolvedModel | ModelWithRetries[] {\n const agentControllerContext = requestContext.get('controller') as AgentControllerRequestContext<any> | undefined;\n\n const controllerState = agentControllerContext?.getState?.() as\n | {\n activeModelPackId?: unknown;\n mastracodePendingPackFallback?: { toPackId?: unknown; toModelId?: unknown; threadId?: unknown } | null;\n }\n | undefined;\n const pendingState = controllerState?.mastracodePendingPackFallback;\n const pendingFallback =\n pendingState &&\n (pendingState.threadId === undefined ||\n (typeof pendingState.threadId === 'string' && pendingState.threadId === agentControllerContext?.threadId))\n ? pendingState\n : undefined;\n const pendingModelId =\n pendingFallback && typeof pendingFallback.toModelId === 'string' && pendingFallback.toModelId.length > 0\n ? pendingFallback.toModelId\n : undefined;\n const modelId = pendingModelId ?? agentControllerContext?.session?.modelId;\n if (!modelId) {\n // A missing controller context means the run was started without session\n // request context at all (e.g. a signal delivered to an idle thread) —\n // \"use /models\" would mislead there, the user's selection was never the\n // problem.\n if (!agentControllerContext) {\n throw new Error(\n 'No model available: this run started without a controller session context, so no model selection could be resolved.',\n );\n }\n throw new Error('No model selected. Use /models to select a model first.');\n }\n\n const thinkingLevel = resolveRequestThinkingLevel(agentControllerContext, settingsPath);\n const resolveOptions = { thinkingLevel, remapForCodexOAuth: true, requestContext } as const;\n const primary = resolveModel(modelId, resolveOptions);\n\n const settings = loadSettings(settingsPath);\n // `models?` tolerates partial settings mocks; loaded settings always carry it.\n const fallbacks = settings.models?.packFallbacks ?? {};\n if (Object.keys(fallbacks).length === 0) return primary;\n\n const modeId = agentControllerContext?.session?.modeId ?? 'build';\n const packs = listResolvableModePacks(settings);\n const pendingPackId =\n pendingFallback && typeof pendingFallback.toPackId === 'string' && pendingFallback.toPackId.length > 0\n ? pendingFallback.toPackId\n : undefined;\n const statePackId = pendingPackId ?? controllerState?.activeModelPackId ?? settings.models.activeModelPackId;\n const activePack = findModePackForModel(\n settings,\n packs,\n modelId,\n modeId,\n typeof statePackId === 'string' ? statePackId : undefined,\n );\n if (!activePack) return primary;\n\n const chain = resolveModePackFallbackChain(fallbacks, activePack.id, settings.customModelPacks);\n if (chain.length < 2) return primary;\n\n const entries: ModelWithRetries[] = [{ id: activePack.id, model: primary }];\n const appearances = new Map<string, number>([[activePack.id, 1]]);\n for (const packId of chain.slice(1)) {\n const pack = packs.find(candidate => candidate.id === packId);\n if (!pack) break;\n const entryModelId = resolveModePackModels(settings, pack)[modeId];\n if (!entryModelId) break;\n // Best-effort resolution: an unresolvable fallback (e.g. unconnected\n // provider in deployed fail-closed mode) truncates the chain here rather\n // than failing the request before the primary is ever tried.\n let entryModel: ResolvedModel;\n try {\n entryModel = resolveModel(entryModelId, resolveOptions);\n } catch {\n break;\n }\n const occurrence = (appearances.get(packId) ?? 0) + 1;\n appearances.set(packId, occurrence);\n entries.push({\n id: occurrence === 1 ? packId : `${packId}#${occurrence}`,\n model: entryModel,\n });\n }\n // A chain that truncated to the primary alone is indistinguishable from no\n // chain — return the bare model so core never sees a one-entry array.\n if (entries.length < 2) return primary;\n return entries;\n}\n\n/** OM fallback-chain entry: a pack's OM model resolved through the gateway. Assignable to `ModelWithRetries`. */\nexport type PackMemoryModelChainEntry = { id: string; model: GatewayLanguageModel };\n\n/**\n * Resolve the observational-memory model for the active mode pack, walking the\n * pack's fallback chain (`settings.models.packFallbacks`) and collecting each\n * pack's optional `models.memory` entry. Packs without an OM model are skipped\n * (the field is optional, so absence must not truncate the chain); duplicate\n * model ids collapse so an A⇄B cycle never retries an identical OM model.\n *\n * Returns a bare model for a single entry, a fallback array for multiple\n * entries (OM's internal agents run the same agentic loop, so the array gives\n * OM its own cross-pack failover), or `undefined` when no pack in the chain\n * defines an OM model — callers then fall back to the standalone OM\n * configuration.\n */\nexport function resolvePackMemoryModelChain(\n settings: ReturnType<typeof loadSettings>,\n startPackId: string,\n resolveOptions: Parameters<typeof resolveModel>[1],\n): GatewayLanguageModel | PackMemoryModelChainEntry[] | undefined {\n const packs = listResolvableModePacks(settings);\n if (!packs.some(pack => pack.id === startPackId)) return undefined;\n\n const chain = resolveModePackFallbackChain(\n settings.models?.packFallbacks ?? {},\n startPackId,\n settings.customModelPacks,\n );\n const seenModelIds = new Set<string>();\n const entries: PackMemoryModelChainEntry[] = [];\n for (const packId of chain) {\n const pack = packs.find(candidate => candidate.id === packId);\n if (!pack) break;\n const memoryModelId = resolveModePackModels(settings, pack).memory;\n if (!memoryModelId || seenModelIds.has(memoryModelId)) continue;\n seenModelIds.add(memoryModelId);\n // Best-effort resolution: an unresolvable OM entry (e.g. unconnected\n // provider in deployed fail-closed mode) truncates the chain here rather\n // than failing observation before the pack's own OM model is tried.\n let entryModel: ResolvedModel;\n try {\n entryModel = resolveModel(memoryModelId, resolveOptions);\n } catch {\n break;\n }\n entries.push({ id: `${packId}:memory`, model: entryModel });\n }\n\n if (entries.length === 0) return undefined;\n if (entries.length === 1) return entries[0]!.model;\n return entries;\n}\n\n/**\n * Goal judge model resolver for the agent's `goal.judge` config. Resolves the\n * configured goal judge model through mastracode's gateway so provider\n * credentials (stored in auth storage, not just env) are injected — a bare model\n * id handed to core's default model router would fail to find the API key.\n *\n * Returns `undefined` when no judge model is configured, which keeps the goal\n * step a complete no-op (the goal mechanism requires a judge to do anything).\n *\n * `settingsPath` must be the same source `createMastraCode()` reads from so the\n * judge model and the goal budget (`goalMaxTurns`) come from one config — with a\n * custom `settingsPath` a bare `loadSettings()` here could read a different file\n * and silently turn the goal step into a no-op.\n */\nexport function getGoalJudgeModel(\n { requestContext }: { requestContext: RequestContext },\n settingsPath?: string,\n): ResolvedModel | undefined {\n const judgeModelId = loadSettings(settingsPath).models.goalJudgeModel;\n if (!judgeModelId) return undefined;\n return resolveModel(judgeModelId, { remapForCodexOAuth: true, requestContext });\n}\n"],"mappings":";;;;;;;;;;;AAuDA,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;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W,CAAC;CAC5D;CAEA,IAAI,QAAQ,WAAW,GAAG,OAAO,KAAA;CACjC,IAAI,QAAQ,WAAW,GAAG,OAAO,QAAQ,EAAE,CAAE;CAC7C,OAAO;AACT;;;;;;;;;;;;;;;AAgBA,SAAgB,kBACd,EAAE,kBACF,cAC2B;CAC3B,MAAM,eAAe,aAAa,YAAY,CAAC,CAAC,OAAO;CACvD,IAAI,CAAC,cAAc,OAAO,KAAA;CAC1B,OAAO,aAAa,cAAc;EAAE,oBAAoB;EAAM;CAAe,CAAC;AAChF"}
1
+ {"version":3,"file":"model.js","names":[],"sources":["../../src/agents/model.ts"],"sourcesContent":["import type { ModelWithRetries } from '@mastra/core/agent';\nimport type { AgentControllerRequestContext } from '@mastra/core/agent-controller';\nimport type { GatewayLanguageModel, MastraModelGatewayInterface } from '@mastra/core/llm';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport { getRequestAccountSelection, isRequestAccountRoutingExhausted } from '../auth/account-routing-context.js';\nimport { ProviderAuthRequiredError } from '../auth/provider-auth-error.js';\nimport type { CredentialStore, OAuthAccountRecord } from '../auth/types.js';\nimport { listBuiltinModePacks, resolveModePackFallbackChain } from '../onboarding/packs.js';\nimport {\n findModePackForModel,\n loadSettings,\n resolveDefaultThinkingLevel,\n resolveModePackModels,\n stripMastraCodeCustomProviderPrefix,\n} from '../onboarding/settings.js';\nimport { AMAZON_BEDROCK_GATEWAY_ID, createAmazonBedrockGateway } from '../providers/amazon-bedrock-gateway.js';\nimport type { AnthropicPromptCacheScope } from '../providers/anthropic-prompt-cache.js';\nimport { isThinkingLevelSetting } from '../thinking.js';\nimport type { ThinkingLevelSetting } from '../thinking.js';\nimport { resolveCredentialStore } from './credential-resolver.js';\nimport { resolveCustomProviders } from './custom-provider-source.js';\nimport {\n MASTRA_GATEWAY_PREFIX,\n MASTRACODE_GATEWAY_ID,\n MastraCodeGateway,\n getGlobalAuthStorage,\n reloadAuthStorage,\n stripMastraGatewayPrefix,\n} from './mastracode-gateway.js';\nimport type { MastraCodeGatewayOptions } from './mastracode-gateway.js';\n\nexport {\n getAnthropicApiKey,\n getOpenAIApiKey,\n MASTRACODE_GATEWAY_ID,\n MastraCodeGateway,\n remapOpenAIModelForCodexOAuth,\n resolveAuth,\n} from './mastracode-gateway.js';\nexport type { MastraCodeCustomProvider, MastraCodeGatewayOptions } from './mastracode-gateway.js';\nexport {\n setCredentialStoreProvider,\n hasCredentialStoreProvider,\n resolveTenantFromRequestContext,\n} from './credential-resolver.js';\nexport type { CredentialTenant, CredentialStoreProvider } from './credential-resolver.js';\nexport {\n setCustomProvidersSource,\n hasCustomProvidersSource,\n resolveCustomProviders,\n} from './custom-provider-source.js';\nexport type { CustomProvidersSource } from './custom-provider-source.js';\n\ntype ResolvedModel = GatewayLanguageModel;\ntype ModelRequestHeaders = Record<string, string>;\n\nfunction getAgentControllerHeaders(requestContext?: RequestContext): ModelRequestHeaders | undefined {\n const agentControllerContext = requestContext?.get('controller') as AgentControllerRequestContext<any> | undefined;\n const headers = {\n ...(agentControllerContext?.threadId ? { 'x-thread-id': agentControllerContext.threadId } : {}),\n ...(agentControllerContext?.resourceId ? { 'x-resource-id': agentControllerContext.resourceId } : {}),\n };\n\n return Object.keys(headers).length > 0 ? headers : undefined;\n}\n\nfunction accountCredential(account: OAuthAccountRecord) {\n const { type: _type, id: _id, label: _label, addedAt: _addedAt, active: _active, ...credential } = account;\n return { type: 'oauth' as const, ...credential };\n}\n\nexport function createRequestScopedCredentialStore(\n base: CredentialStore,\n requestContext?: RequestContext,\n): CredentialStore {\n const selectedId = (providerId: string) => getRequestAccountSelection(requestContext, providerId);\n const selectedAccount = (providerId: string) => {\n const accountInstanceId = selectedId(providerId);\n return accountInstanceId\n ? base.listAccounts?.(providerId).find(account => account.id === accountInstanceId)\n : undefined;\n };\n // Routing rejected every account for this provider on this request. Fail\n // closed on every credential read: falling through to `base` would use the\n // provider's active account — the exhausted one routing just refused.\n const rejectAll = (providerId: string) => isRequestAccountRoutingExhausted(requestContext, providerId);\n\n return {\n allowEnvironmentFallback: base.allowEnvironmentFallback,\n reload: () => base.reload(),\n get: providerId => {\n if (rejectAll(providerId)) return undefined;\n // A selection that no longer resolves (the account was removed between\n // routing and the credential read) must not fall through to the active\n // account — that is the account routing deliberately passed over.\n const accountInstanceId = selectedId(providerId);\n if (accountInstanceId === undefined) return base.get(providerId);\n const selected = selectedAccount(providerId);\n return selected ? accountCredential(selected) : undefined;\n },\n getStoredApiKey: providerId => {\n if (rejectAll(providerId)) return undefined;\n // The provider-wide `apikey:` slot is never the credential routing\n // selected, so serving it to a routed request is an OAuth -> API-key\n // fallback of the same provider — the one combination this feature\n // forbids. Unlike `get`, this read has no account argument to pass\n // through, so a selection fails it closed instead.\n if (selectedId(providerId) !== undefined) return undefined;\n return base.getStoredApiKey(providerId);\n },\n getApiKey: providerId =>\n rejectAll(providerId) ? Promise.resolve(undefined) : base.getApiKey(providerId, selectedId(providerId)),\n getOAuthCredential: base.getOAuthCredential\n ? providerId =>\n rejectAll(providerId)\n ? Promise.resolve(undefined)\n : base.getOAuthCredential!(providerId, selectedId(providerId))\n : undefined,\n listAccounts: base.listAccounts ? providerId => base.listAccounts!(providerId) : undefined,\n getActiveAccount: base.getActiveAccount ? providerId => base.getActiveAccount!(providerId) : undefined,\n activateAccount: base.activateAccount\n ? (providerId, accountInstanceId) => base.activateAccount!(providerId, accountInstanceId)\n : undefined,\n removeAccount: base.removeAccount\n ? (providerId, accountInstanceId) => base.removeAccount!(providerId, accountInstanceId)\n : undefined,\n };\n}\n\nexport function createMastraCodeGateway(options: MastraCodeGatewayOptions): MastraCodeGateway {\n return new MastraCodeGateway(options);\n}\n\nexport function createMastraCodeModelCatalogProvider(gateway: MastraModelGatewayInterface) {\n return gateway instanceof MastraCodeGateway\n ? gateway.createModelCatalogProvider()\n : MastraCodeGateway.createModelCatalogProvider(gateway);\n}\n\n/**\n * Placeholder for future model ID normalization.\n * Currently returns the input unchanged, but exists as a seam\n * for aliasing, casing fixes, or validation in the future.\n */\nexport function resolveModelId(modelId: string): string {\n return modelId;\n}\n\n/**\n * Resolve a model ID to the correct provider instance.\n * Shared by the main agent, observer, and reflector.\n *\n * - For anthropic/* models: Uses stored OAuth credentials when present, otherwise direct API key\n * - For openai/* models: Uses OAuth when configured, otherwise direct API key from AuthStorage\n * - For moonshotai/* models: Uses Moonshot AI Anthropic-compatible endpoint\n * - For all other providers: Uses Mastra's model router (models.dev gateway)\n */\nexport function resolveModel(\n modelId: string,\n options?: {\n thinkingLevel?: ThinkingLevelSetting;\n remapForCodexOAuth?: boolean;\n requestContext?: RequestContext;\n anthropicPromptCacheScope?: AnthropicPromptCacheScope;\n },\n): GatewayLanguageModel {\n reloadAuthStorage();\n const headers = getAgentControllerHeaders(options?.requestContext);\n const settings = loadSettings();\n // Bedrock was previously cataloged under the MastraCode gateway namespace\n // (`mastracode/amazon-bedrock/<model>`). Normalize any legacy saved ids to the\n // standalone `amazon-bedrock/<model>` form so they resolve through the\n // dedicated Bedrock gateway.\n const bedrockLegacyPrefix = `${MASTRACODE_GATEWAY_ID}/amazon-bedrock/`;\n const bedrockNormalizedInput = modelId.startsWith(bedrockLegacyPrefix)\n ? modelId.slice(MASTRACODE_GATEWAY_ID.length + 1)\n : modelId;\n // Deployed web registers a custom providers source (DB-backed, tenant\n // scoped); when registered it is authoritative and settings.json custom\n // providers are ignored. Undefined = local settings-based behavior.\n const customProviders = resolveCustomProviders(options?.requestContext) ?? settings.customProviders;\n // Ids selected from the shared /models catalog were previously persisted in\n // the gateway-qualified `mastracode/<customProviderId>/<model>` form, which\n // parses the provider as `mastracode` and breaks provider config lookup.\n // Normalize at resolution time (in addition to stripping at selection time)\n // so already-saved ids and any surface that persists the raw catalog id\n // still resolve to the custom provider.\n const normalizedInput = stripMastraCodeCustomProviderPrefix(bedrockNormalizedInput, customProviders);\n const isMastraGatewayModel = normalizedInput.startsWith(MASTRA_GATEWAY_PREFIX);\n const normalizedModelId = stripMastraGatewayPrefix(normalizedInput);\n const [providerId, ...modelParts] = normalizedModelId.split('/');\n const bareModelId = modelParts.join('/');\n if (!providerId || !bareModelId) {\n throw new Error(`Invalid model id: ${modelId}`);\n }\n\n if (providerId === AMAZON_BEDROCK_GATEWAY_ID) {\n const bedrockGateway = createAmazonBedrockGateway();\n const routerId = `${AMAZON_BEDROCK_GATEWAY_ID}/${bareModelId}`;\n const auth = bedrockGateway.resolveAuth({\n gatewayId: AMAZON_BEDROCK_GATEWAY_ID,\n providerId: AMAZON_BEDROCK_GATEWAY_ID,\n modelId: bareModelId,\n routerId,\n });\n return bedrockGateway.resolveLanguageModel({\n providerId: AMAZON_BEDROCK_GATEWAY_ID,\n modelId: bareModelId,\n apiKey: auth?.apiKey ?? '',\n headers,\n });\n }\n\n const routerId = `${MASTRACODE_GATEWAY_ID}/${normalizedModelId}`;\n\n const mgApiKey = MastraCodeGateway.getMastraGatewayApiKey();\n const rawGatewayBase =\n settings.memoryGateway?.baseUrl ?? process.env['MASTRA_GATEWAY_URL'] ?? 'https://gateway-api.mastra.ai';\n // Deployed web registers a per-tenant credential store provider; when the\n // request carries an authenticated tenant, resolve credentials through the\n // caller's own store (user > org > env). Undefined = global AuthStorage.\n const baseCredentialStore = resolveCredentialStore(options?.requestContext) ?? getGlobalAuthStorage();\n const credentialStore = createRequestScopedCredentialStore(baseCredentialStore, options?.requestContext);\n const gateway = createMastraCodeGateway({\n mastraGatewayBaseUrl: rawGatewayBase.replace(/\\/+$/, '').replace(/\\/v1$/, ''),\n mastraGatewayApiKey: mgApiKey,\n routeThroughMastraGateway: Boolean(mgApiKey && isMastraGatewayModel),\n thinkingLevel: options?.thinkingLevel,\n anthropicPromptCacheScope: options?.anthropicPromptCacheScope,\n customProviders,\n credentialStore,\n });\n\n const auth = gateway.resolveAuth({\n gatewayId: MASTRACODE_GATEWAY_ID,\n providerId,\n modelId: bareModelId,\n routerId,\n });\n\n if (!auth && credentialStore?.allowEnvironmentFallback === false) {\n throw new ProviderAuthRequiredError(\n `No usable ${providerId} credential is configured for this signed-in Factory account. Connect the provider or add an organization credential, then try again.`,\n );\n }\n\n return gateway.resolveLanguageModel({\n providerId,\n modelId: bareModelId,\n apiKey: auth?.apiKey ?? '',\n headers,\n });\n}\n\nexport interface ThinkingRequestContext {\n state?: { thinkingLevel?: unknown };\n session?: { modeId?: string };\n}\n/**\n * Resolve the effective thinking level for the current request.\n *\n * Precedence:\n * 1. Session override (`state.thinkingLevel`, set via /think or the session\n * settings panel).\n * 2. Per-mode default from settings (`models.modeThinkingDefaults[mode]`).\n * 3. Global default (`preferences.thinkingLevel`).\n *\n * Resolved per-request (not seeded at session start) so configuration changes\n * apply to the next request of every session — including automated\n * (rule-driven) Factory runs that nobody ever opens interactively.\n */\n\nexport function resolveRequestThinkingLevel(\n agentControllerContext: ThinkingRequestContext | undefined,\n settingsPath?: string,\n): ThinkingLevelSetting {\n const override = agentControllerContext?.state?.thinkingLevel;\n if (isThinkingLevelSetting(override)) return override;\n const modeId = agentControllerContext?.session?.modeId;\n return resolveDefaultThinkingLevel(loadSettings(settingsPath), modeId).level;\n}\n\n/** Structural pack shape for fallback resolution (custom pack models are partial by nature). */\nexport interface ResolvableModePack {\n id: string;\n name: string;\n models: Record<string, string>;\n}\n\n/** All packs a fallback chain may reference: every builtin plus saved customs. */\nexport function listResolvableModePacks(settings: ReturnType<typeof loadSettings>): ResolvableModePack[] {\n return [\n ...listBuiltinModePacks(),\n ...settings.customModelPacks.map(pack => ({\n id: `custom:${pack.name}`,\n name: pack.name,\n models: { ...pack.models },\n })),\n ];\n}\n\n/**\n * Dynamic model function that reads the current model from controller state.\n * This allows runtime model switching via the /models picker.\n *\n * When the session's model came from a pack with a fallback chain configured\n * (`settings.models.packFallbacks`), returns core's `ModelWithRetries[]`\n * fallback array instead of a bare model: the active pack's model first, then\n * each fallback pack's model for the same mode. Core advances the array when\n * the error processors decline to retry (pool exhausted / persistent outage —\n * see AccountRotationProcessor). Entry ids are unique per occurrence — the\n * one allowed revisit of a pack gets `<packId>#2` — because core re-resolves\n * the active fallback index by id across agentic steps.\n */\nexport function getDynamicModel(\n { requestContext }: { requestContext: RequestContext },\n settingsPath?: string,\n): ResolvedModel | ModelWithRetries[] {\n const agentControllerContext = requestContext.get('controller') as AgentControllerRequestContext<any> | undefined;\n\n const controllerState = agentControllerContext?.getState?.() as\n | {\n activeModelPackId?: unknown;\n mastracodePendingPackFallback?: { toPackId?: unknown; toModelId?: unknown; threadId?: unknown } | null;\n }\n | undefined;\n const pendingState = controllerState?.mastracodePendingPackFallback;\n const pendingFallback =\n pendingState &&\n (pendingState.threadId === undefined ||\n (typeof pendingState.threadId === 'string' && pendingState.threadId === agentControllerContext?.threadId))\n ? pendingState\n : undefined;\n const pendingModelId =\n pendingFallback && typeof pendingFallback.toModelId === 'string' && pendingFallback.toModelId.length > 0\n ? pendingFallback.toModelId\n : undefined;\n const modelId = pendingModelId ?? agentControllerContext?.session?.modelId;\n if (!modelId) {\n // A missing controller context means the run was started without session\n // request context at all (e.g. a signal delivered to an idle thread) —\n // \"use /models\" would mislead there, the user's selection was never the\n // problem.\n if (!agentControllerContext) {\n throw new Error(\n 'No model available: this run started without a controller session context, so no model selection could be resolved.',\n );\n }\n throw new Error('No model selected. Use /models to select a model first.');\n }\n\n const thinkingLevel = resolveRequestThinkingLevel(agentControllerContext, settingsPath);\n const resolveOptions = { thinkingLevel, remapForCodexOAuth: true, requestContext } as const;\n const primary = resolveModel(modelId, resolveOptions);\n\n const settings = loadSettings(settingsPath);\n // `models?` tolerates partial settings mocks; loaded settings always carry it.\n const fallbacks = settings.models?.packFallbacks ?? {};\n if (Object.keys(fallbacks).length === 0) return primary;\n\n const modeId = agentControllerContext?.session?.modeId ?? 'build';\n const packs = listResolvableModePacks(settings);\n const pendingPackId =\n pendingFallback && typeof pendingFallback.toPackId === 'string' && pendingFallback.toPackId.length > 0\n ? pendingFallback.toPackId\n : undefined;\n const statePackId = pendingPackId ?? controllerState?.activeModelPackId ?? settings.models.activeModelPackId;\n const activePack = findModePackForModel(\n settings,\n packs,\n modelId,\n modeId,\n typeof statePackId === 'string' ? statePackId : undefined,\n );\n if (!activePack) return primary;\n\n const chain = resolveModePackFallbackChain(fallbacks, activePack.id, settings.customModelPacks);\n if (chain.length < 2) return primary;\n\n const entries: ModelWithRetries[] = [{ id: activePack.id, model: primary }];\n const appearances = new Map<string, number>([[activePack.id, 1]]);\n for (const packId of chain.slice(1)) {\n const pack = packs.find(candidate => candidate.id === packId);\n if (!pack) break;\n const entryModelId = resolveModePackModels(settings, pack)[modeId];\n if (!entryModelId) break;\n // Best-effort resolution: an unresolvable fallback (e.g. unconnected\n // provider in deployed fail-closed mode) truncates the chain here rather\n // than failing the request before the primary is ever tried.\n let entryModel: ResolvedModel;\n try {\n entryModel = resolveModel(entryModelId, resolveOptions);\n } catch {\n break;\n }\n const occurrence = (appearances.get(packId) ?? 0) + 1;\n appearances.set(packId, occurrence);\n entries.push({\n id: occurrence === 1 ? packId : `${packId}#${occurrence}`,\n model: entryModel,\n });\n }\n // A chain that truncated to the primary alone is indistinguishable from no\n // chain — return the bare model so core never sees a one-entry array.\n if (entries.length < 2) return primary;\n return entries;\n}\n\n/** OM fallback-chain entry: a pack's OM model resolved through the gateway. Assignable to `ModelWithRetries`. */\nexport type PackMemoryModelChainEntry = { id: string; model: GatewayLanguageModel };\n\n/**\n * Resolve the observational-memory model for the active mode pack, walking the\n * pack's fallback chain (`settings.models.packFallbacks`) and collecting each\n * pack's optional `models.memory` entry. Packs without an OM model are skipped\n * (the field is optional, so absence must not truncate the chain); duplicate\n * model ids collapse so an A⇄B cycle never retries an identical OM model.\n *\n * Returns a bare model for a single entry, a fallback array for multiple\n * entries (OM's internal agents run the same agentic loop, so the array gives\n * OM its own cross-pack failover), or `undefined` when no pack in the chain\n * defines an OM model — callers then fall back to the standalone OM\n * configuration.\n */\nexport function resolvePackMemoryModelChain(\n settings: ReturnType<typeof loadSettings>,\n startPackId: string,\n resolveOptions: Parameters<typeof resolveModel>[1],\n): GatewayLanguageModel | PackMemoryModelChainEntry[] | undefined {\n const packs = listResolvableModePacks(settings);\n if (!packs.some(pack => pack.id === startPackId)) return undefined;\n\n const chain = resolveModePackFallbackChain(\n settings.models?.packFallbacks ?? {},\n startPackId,\n settings.customModelPacks,\n );\n const seenModelIds = new Set<string>();\n const entries: PackMemoryModelChainEntry[] = [];\n for (const packId of chain) {\n const pack = packs.find(candidate => candidate.id === packId);\n if (!pack) break;\n const memoryModelId = resolveModePackModels(settings, pack).memory;\n if (!memoryModelId || seenModelIds.has(memoryModelId)) continue;\n seenModelIds.add(memoryModelId);\n // Best-effort resolution: an unresolvable OM entry (e.g. unconnected\n // provider in deployed fail-closed mode) truncates the chain here rather\n // than failing observation before the pack's own OM model is tried.\n let entryModel: ResolvedModel;\n try {\n entryModel = resolveModel(memoryModelId, resolveOptions);\n } catch {\n break;\n }\n entries.push({ id: `${packId}:memory`, model: entryModel });\n }\n\n if (entries.length === 0) return undefined;\n if (entries.length === 1) return entries[0]!.model;\n return entries;\n}\n\n/**\n * Goal judge model resolver for the agent's `goal.judge` config. Resolves the\n * configured goal judge model through mastracode's gateway so provider\n * credentials (stored in auth storage, not just env) are injected — a bare model\n * id handed to core's default model router would fail to find the API key.\n *\n * Returns `undefined` when no judge model is configured, which keeps the goal\n * step a complete no-op (the goal mechanism requires a judge to do anything).\n *\n * `settingsPath` must be the same source `createMastraCode()` reads from so the\n * judge model and the goal budget (`goalMaxTurns`) come from one config — with a\n * custom `settingsPath` a bare `loadSettings()` here could read a different file\n * and silently turn the goal step into a no-op.\n */\nexport function getGoalJudgeModel(\n { requestContext }: { requestContext: RequestContext },\n settingsPath?: string,\n): ResolvedModel | undefined {\n const judgeModelId = loadSettings(settingsPath).models.goalJudgeModel;\n if (!judgeModelId) return undefined;\n return resolveModel(judgeModelId, { remapForCodexOAuth: true, requestContext });\n}\n"],"mappings":";;;;;;;;;;;AAwDA,SAAS,0BAA0B,gBAAkE;CACnG,MAAM,yBAAyB,gBAAgB,IAAI,YAAY;CAC/D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