@mastra/code-sdk 1.12.0-alpha.3 → 1.12.0-alpha.4

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.
Files changed (51) hide show
  1. package/dist/acp/agent.d.ts.map +1 -1
  2. package/dist/acp/agent.js +0 -6
  3. package/dist/acp/agent.js.map +1 -1
  4. package/dist/acp/runtime.js +1 -1
  5. package/dist/agents/mastracode-gateway.d.ts.map +1 -1
  6. package/dist/agents/mastracode-gateway.js +9 -5
  7. package/dist/agents/mastracode-gateway.js.map +1 -1
  8. package/dist/agents/memory.d.ts +2 -1
  9. package/dist/agents/memory.d.ts.map +1 -1
  10. package/dist/agents/memory.js +92 -34
  11. package/dist/agents/memory.js.map +1 -1
  12. package/dist/agents/model.d.ts +33 -2
  13. package/dist/agents/model.d.ts.map +1 -1
  14. package/dist/agents/model.js +32 -4
  15. package/dist/agents/model.js.map +1 -1
  16. package/dist/index.d.ts +17 -4
  17. package/dist/index.d.ts.map +1 -1
  18. package/dist/index.js +80 -22
  19. package/dist/index.js.map +1 -1
  20. package/dist/knowledge-inspector.d.ts +4 -0
  21. package/dist/knowledge-inspector.d.ts.map +1 -1
  22. package/dist/knowledge-inspector.js +10 -1
  23. package/dist/knowledge-inspector.js.map +1 -1
  24. package/dist/onboarding/om-settings.d.ts +29 -8
  25. package/dist/onboarding/om-settings.d.ts.map +1 -1
  26. package/dist/onboarding/om-settings.js +42 -15
  27. package/dist/onboarding/om-settings.js.map +1 -1
  28. package/dist/onboarding/packs.d.ts +12 -3
  29. package/dist/onboarding/packs.d.ts.map +1 -1
  30. package/dist/onboarding/packs.js +20 -2
  31. package/dist/onboarding/packs.js.map +1 -1
  32. package/dist/onboarding/settings.d.ts +5 -0
  33. package/dist/onboarding/settings.d.ts.map +1 -1
  34. package/dist/onboarding/settings.js +7 -2
  35. package/dist/onboarding/settings.js.map +1 -1
  36. package/dist/providers/claude-max.js +1 -1
  37. package/dist/providers/deepseek-thinking.d.ts +4 -0
  38. package/dist/providers/deepseek-thinking.d.ts.map +1 -0
  39. package/dist/providers/deepseek-thinking.js +16 -0
  40. package/dist/providers/deepseek-thinking.js.map +1 -0
  41. package/dist/providers/openai-codex.js +1 -1
  42. package/dist/providers/provider-thinking.d.ts +18 -0
  43. package/dist/providers/provider-thinking.d.ts.map +1 -0
  44. package/dist/providers/provider-thinking.js +34 -0
  45. package/dist/providers/provider-thinking.js.map +1 -0
  46. package/dist/schema.d.ts +199 -6
  47. package/dist/schema.d.ts.map +1 -1
  48. package/dist/schema.js +10 -4
  49. package/dist/schema.js.map +1 -1
  50. package/dist/thinking.js +1 -1
  51. package/package.json +8 -8
@@ -1,51 +1,99 @@
1
- import { DEFAULT_OM_MODEL_ID } from "../constants.js";
1
+ import "../constants.js";
2
2
  import { getOmScope } from "../utils/project.js";
3
+ import { MASTRACODE_AUTO_OM_MODELS, resolveAutoOMModelId } from "../onboarding/packs.js";
3
4
  import { loadSettings } from "../onboarding/settings.js";
4
5
  import { LOCAL_KNOWLEDGE_ORG_ID, resolveKnowledgeScopeIdentity } from "../knowledge-scope.js";
5
6
  import "../providers/anthropic-prompt-cache.js";
6
- import { resolveModel } from "./model.js";
7
- import { fastembed } from "@mastra/fastembed";
7
+ import { getActiveMemoryRoute, resolveModel } from "./model.js";
8
8
  import { Memory, Subconscious } from "@mastra/memory";
9
+ import { fastembed } from "@mastra/fastembed";
9
10
  //#region src/agents/memory.ts
10
- /** Resolve one OM role's model for this invocation. */
11
- function resolveOmRoleModelForRequest(role, requestContext, settingsPath, options) {
12
- const controller = requestContext.get("controller");
13
- const state = controller?.getState();
14
- const resolveOptions = {
15
- remapForCodexOAuth: true,
16
- requestContext,
17
- anthropicPromptCacheScope: "system"
18
- };
19
- if (!options?.disableSettingsOmSeed) {
20
- const settings = loadSettings(settingsPath);
21
- const roleOverride = role === "observer" ? settings.models?.observerModelOverride : settings.models?.reflectorModelOverride;
22
- if (roleOverride) return resolveModel(roleOverride, resolveOptions);
23
- }
24
- const pending = state?.mastracodePendingModelFallback;
25
- const sameThreadPending = pending && (pending.threadId === void 0 || pending.threadId === controller?.threadId) ? pending : void 0;
26
- const routeEntries = state?.modelRoute?.entries?.slice(0, 32) ?? [];
27
- const pendingIndex = sameThreadPending ? routeEntries.findIndex((entry) => entry.id === sameThreadPending.toEntryId) : -1;
28
- const memoryRoute = pendingIndex >= 0 ? routeEntries.slice(pendingIndex) : routeEntries;
11
+ /**
12
+ * Resolve the active model route's memory models, starting at a same-thread
13
+ * pending fallback hop. Returns `'auto'` when the route's first memory model is
14
+ * Auto, and `undefined` when the route sets no memory model.
15
+ */
16
+ function resolveRouteMemoryModels(state, threadId, resolve) {
17
+ const memoryRoute = getActiveMemoryRoute(state, threadId);
18
+ if (memoryRoute[0]?.memoryModelId === "auto") return "auto";
29
19
  const seenModelIds = /* @__PURE__ */ new Set();
30
20
  const appearances = /* @__PURE__ */ new Map();
31
21
  const entries = [];
32
22
  for (const entry of memoryRoute) {
33
- if (!entry.memoryModelId || seenModelIds.has(entry.memoryModelId)) continue;
23
+ if (!entry.memoryModelId || entry.memoryModelId === "auto" || seenModelIds.has(entry.memoryModelId)) continue;
34
24
  seenModelIds.add(entry.memoryModelId);
35
25
  const occurrence = (appearances.get(entry.id) ?? 0) + 1;
36
26
  appearances.set(entry.id, occurrence);
37
27
  try {
38
28
  entries.push({
39
29
  id: `${entry.id}:memory${occurrence === 1 ? "" : `#${occurrence}`}`,
40
- model: resolveModel(entry.memoryModelId, resolveOptions)
30
+ model: resolve(entry.memoryModelId)
41
31
  });
42
32
  } catch {
43
33
  break;
44
34
  }
45
35
  }
46
- if (entries.length === 1) return entries[0].model;
47
- if (entries.length > 1) return entries;
48
- return resolveModel((role === "observer" ? state?.observerModelId : state?.reflectorModelId) ?? DEFAULT_OM_MODEL_ID, resolveOptions);
36
+ return entries.length > 0 ? entries : void 0;
37
+ }
38
+ function getFactoryMemorySettingsContext(requestContext) {
39
+ return requestContext.get("mastra__factoryMemorySettings");
40
+ }
41
+ function isFactoryMemorySettingsUnavailable(settings) {
42
+ return settings !== null && typeof settings === "object" && "status" in settings && settings.status === "unavailable";
43
+ }
44
+ function getMainModelId(requestContext) {
45
+ const controller = requestContext.get("controller");
46
+ return controller?.session.modelId || controller?.getState()?.currentModelId;
47
+ }
48
+ /**
49
+ * Resolve one OM role's model for this invocation. Returns `'auto'` for Memory's
50
+ * auto policy, or a concrete model. Factory's DB row is authoritative for
51
+ * Factory sessions (an unreadable row falls back to auto). Otherwise the active
52
+ * model route's memory models win, then the per-role selection, then legacy
53
+ * concrete settings.
54
+ */
55
+ function resolveOmRoleModelForRequest(role, requestContext, settingsPath, options) {
56
+ const controller = requestContext.get("controller");
57
+ const state = controller?.getState();
58
+ const resolveOptions = {
59
+ remapForCodexOAuth: true,
60
+ requestContext,
61
+ anthropicPromptCacheScope: "system"
62
+ };
63
+ const factorySettingsContext = getFactoryMemorySettingsContext(requestContext);
64
+ const isFactory = typeof state?.factoryProjectId === "string";
65
+ const useModel = (modelId) => {
66
+ requestContext.set(`om.${role}.selectionMode`, "model");
67
+ requestContext.set(`om.${role}.effectiveModelId`, modelId);
68
+ return resolveModel(modelId, resolveOptions);
69
+ };
70
+ const useAuto = () => {
71
+ requestContext.set(`om.${role}.selectionMode`, "auto");
72
+ requestContext.set(`om.${role}.effectiveModelId`, resolveAutoOMModelId(getMainModelId(requestContext)));
73
+ return "auto";
74
+ };
75
+ if (isFactoryMemorySettingsUnavailable(factorySettingsContext) || factorySettingsContext === void 0 && isFactory) return useAuto();
76
+ if (factorySettingsContext !== void 0) {
77
+ const factoryModelId = factorySettingsContext?.[`${role}ModelId`];
78
+ return factoryModelId ? useModel(factoryModelId) : useAuto();
79
+ }
80
+ const settings = options?.disableSettingsOmSeed ? void 0 : loadSettings(settingsPath);
81
+ const routeMemory = resolveRouteMemoryModels(state, controller?.threadId, (modelId) => resolveModel(modelId, resolveOptions));
82
+ if (routeMemory === "auto") return useAuto();
83
+ if (routeMemory) {
84
+ requestContext.set(`om.${role}.selectionMode`, "model");
85
+ requestContext.set(`om.${role}.effectiveModelId`, routeMemory[0]?.model.modelId);
86
+ return routeMemory.length === 1 ? routeMemory[0].model : routeMemory;
87
+ }
88
+ const selection = state?.[`${role}ModelSelection`];
89
+ if (selection === "auto") return useAuto();
90
+ if (typeof selection === "string" && selection) return useModel(selection);
91
+ if (selection && typeof selection === "object" && "modelId" in selection && typeof selection.modelId === "string" && selection.modelId) return useModel(selection.modelId);
92
+ const roleOverride = role === "observer" ? settings?.models?.observerModelOverride : settings?.models?.reflectorModelOverride;
93
+ if (roleOverride) return useModel(roleOverride);
94
+ const legacyModelId = state?.[`${role}ModelId`];
95
+ if (typeof legacyModelId === "string" && legacyModelId) return useModel(legacyModelId);
96
+ return useAuto();
49
97
  }
50
98
  const DYNAMIC_AGENTS_MD_INSTRUCTION = "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.";
51
99
  const CAVEMAN_OM_INSTRUCTION = `Respond terse like smart caveman. All technical substance stay. Only fluff die.
@@ -105,11 +153,16 @@ function hasSubconsciousTools(vector, state) {
105
153
  * Reads OM thresholds from controller state via requestContext.
106
154
  * Model functions also read from requestContext (no mutable bridge needed).
107
155
  */
108
- function getDynamicMemory(storage, vector, settingsPath, options) {
156
+ function getDynamicMemory(storage, vector, settingsPath, options, knowledge) {
109
157
  let cachedMemory = null;
110
158
  let cachedMemoryKey = null;
111
159
  const getObserverModel = ({ requestContext }) => resolveOmRoleModelForRequest("observer", requestContext, settingsPath, options);
112
160
  const getReflectorModel = ({ requestContext }) => resolveOmRoleModelForRequest("reflector", requestContext, settingsPath, options);
161
+ const resolveMemoryModel = (modelId, { requestContext }) => resolveModel(modelId, {
162
+ remapForCodexOAuth: true,
163
+ requestContext,
164
+ anthropicPromptCacheScope: "system"
165
+ });
113
166
  return ({ requestContext }) => {
114
167
  const controller = requestContext.get("controller");
115
168
  const state = controller?.getState();
@@ -128,11 +181,13 @@ function getDynamicMemory(storage, vector, settingsPath, options) {
128
181
  }
129
182
  const subconsciousAvailable = subconsciousEnabled && !orgUnresolvedRefusal;
130
183
  const omScope = state?.omScope ?? getOmScope(state?.projectPath);
131
- const obsThreshold = state?.observationThreshold ?? 3e4;
132
- const refThreshold = state?.reflectionThreshold ?? 4e4;
184
+ const factorySettingsContext = getFactoryMemorySettingsContext(requestContext);
185
+ const factorySettings = isFactoryMemorySettingsUnavailable(factorySettingsContext) || factorySettingsContext === void 0 && isFactory ? null : factorySettingsContext;
186
+ const obsThreshold = factorySettings !== void 0 ? factorySettings?.observationThreshold ?? 3e4 : state?.observationThreshold ?? 3e4;
187
+ const refThreshold = factorySettings !== void 0 ? factorySettings?.reflectionThreshold ?? 4e4 : state?.reflectionThreshold ?? 4e4;
133
188
  const caveman = state?.cavemanObservations ?? false;
134
189
  const observerPreviousObservationTokens = 1e3;
135
- const observeAttachments = state?.observeAttachments;
190
+ const observeAttachments = factorySettings !== void 0 ? factorySettings?.observeAttachments ?? "auto" : state?.observeAttachments;
136
191
  const cacheKey = `${obsThreshold}:${refThreshold}:${omScope}:${observerPreviousObservationTokens}:${caveman ? 1 : 0}:${observeAttachments}:${isFactory ? 1 : 0}:${subconsciousAvailable ? 1 : 0}`;
137
192
  if (cachedMemory && cachedMemoryKey === cacheKey) return cachedMemory;
138
193
  const isResourceScope = omScope === "resource";
@@ -140,20 +195,23 @@ function getDynamicMemory(storage, vector, settingsPath, options) {
140
195
  const reflectionInstruction = caveman ? CAVEMAN_OM_INSTRUCTION : void 0;
141
196
  cachedMemory = new Memory({
142
197
  storage,
198
+ ...knowledge ? { knowledge } : {},
143
199
  vector: vector || false,
144
200
  embedder: vector ? fastembed.small : void 0,
145
201
  options: {
146
- generateTitle: { model: ({ requestContext }) => {
202
+ generateTitle: process.env.MASTRACODE_DISABLE_TITLE_GENERATION === "1" ? false : { model: ({ requestContext }) => {
147
203
  const resolved = getObserverModel({ requestContext });
204
+ if (resolved === "auto") return resolveMemoryModel(resolveAutoOMModelId(getMainModelId(requestContext)), { requestContext });
148
205
  return Array.isArray(resolved) ? resolved[0].model : resolved;
149
206
  } },
150
- observationalMemory: {
207
+ observationalMemory: process.env.MASTRACODE_DISABLE_OBSERVATIONAL_MEMORY === "1" ? false : {
151
208
  enabled: true,
209
+ autoModels: MASTRACODE_AUTO_OM_MODELS,
210
+ resolveModel: resolveMemoryModel,
152
211
  temporalMarkers: true,
153
212
  retrieval: vector ? { vector: true } : true,
154
213
  experimental_subconscious: subconsciousAvailable ? new Subconscious({
155
214
  defaultScope: "resource",
156
- maxScope: "resource",
157
215
  pins: true,
158
216
  ...isFactory ? { maxSteps: 25 } : {}
159
217
  }) : void 0,
@@ -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 {\n DEFAULT_OM_MODEL_ID,\n DEFAULT_OBS_THRESHOLD,\n DEFAULT_REF_THRESHOLD,\n MODEL_ROUTE_MAX_ENTRIES,\n} 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 } from './model.js';\n\n/** Route-backed OM fallback entry. */\ntype MemoryModelRouteEntry = { id: string; model: GatewayLanguageModel };\n\n/** Resolve one OM role's model for this invocation. */\nfunction resolveOmRoleModelForRequest(\n role: 'observer' | 'reflector',\n requestContext: RequestContext,\n settingsPath?: string,\n options?: { disableSettingsOmSeed?: boolean },\n): GatewayLanguageModel | MemoryModelRouteEntry[] {\n const controller = requestContext.get('controller') as AgentControllerRequestContext<MastraCodeState> | undefined;\n const state = controller?.getState() as MastraCodeState | undefined;\n const resolveOptions = { remapForCodexOAuth: true, requestContext, anthropicPromptCacheScope: 'system' } as const;\n\n if (!options?.disableSettingsOmSeed) {\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\n const pending = state?.mastracodePendingModelFallback;\n const sameThreadPending =\n pending && (pending.threadId === undefined || pending.threadId === controller?.threadId) ? pending : undefined;\n const routeEntries = state?.modelRoute?.entries?.slice(0, MODEL_ROUTE_MAX_ENTRIES) ?? [];\n const pendingIndex = sameThreadPending\n ? routeEntries.findIndex(entry => entry.id === sameThreadPending.toEntryId)\n : -1;\n const memoryRoute = pendingIndex >= 0 ? routeEntries.slice(pendingIndex) : routeEntries;\n const seenModelIds = new Set<string>();\n const appearances = new Map<string, number>();\n const entries: MemoryModelRouteEntry[] = [];\n for (const entry of memoryRoute) {\n if (!entry.memoryModelId || seenModelIds.has(entry.memoryModelId)) continue;\n seenModelIds.add(entry.memoryModelId);\n const occurrence = (appearances.get(entry.id) ?? 0) + 1;\n appearances.set(entry.id, occurrence);\n try {\n entries.push({\n id: `${entry.id}:memory${occurrence === 1 ? '' : `#${occurrence}`}`,\n model: resolveModel(entry.memoryModelId, resolveOptions),\n });\n } catch {\n break;\n }\n }\n if (entries.length === 1) return entries[0]!.model;\n if (entries.length > 1) return entries;\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(\n storage: MastraCompositeStore,\n vector?: MastraVector,\n settingsPath?: string,\n options?: { disableSettingsOmSeed?: boolean },\n) {\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, options);\n const getReflectorModel = ({ requestContext }: { requestContext: RequestContext }) =>\n resolveOmRoleModelForRequest('reflector', requestContext, settingsPath, options);\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":";;;;;;;;;;AAwBA,SAAS,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,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"}
1
+ {"version":3,"file":"memory.js","names":[],"sources":["../../src/agents/memory.ts"],"sourcesContent":["import type { AgentControllerRequestContext } from '@mastra/core/agent-controller';\nimport type { Knowledge } from '@mastra/core/knowledge';\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_OBS_THRESHOLD, DEFAULT_REF_THRESHOLD } from '../constants.js';\nimport { LOCAL_KNOWLEDGE_ORG_ID, resolveKnowledgeScopeIdentity } from '../knowledge-scope.js';\nimport { MASTRACODE_AUTO_OM_MODELS, resolveAutoOMModelId } from '../onboarding/packs.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 { getActiveMemoryRoute, resolveModel } from './model.js';\n\n/** Route-backed OM fallback entry. */\ntype MemoryModelRouteEntry = { id: string; model: GatewayLanguageModel };\n\n/**\n * Resolve the active model route's memory models, starting at a same-thread\n * pending fallback hop. Returns `'auto'` when the route's first memory model is\n * Auto, and `undefined` when the route sets no memory model.\n */\nfunction resolveRouteMemoryModels(\n state: MastraCodeState | undefined,\n threadId: string | null | undefined,\n resolve: (modelId: string) => GatewayLanguageModel,\n): MemoryModelRouteEntry[] | 'auto' | undefined {\n const memoryRoute = getActiveMemoryRoute(state, threadId);\n if (memoryRoute[0]?.memoryModelId === 'auto') return 'auto';\n const seenModelIds = new Set<string>();\n const appearances = new Map<string, number>();\n const entries: MemoryModelRouteEntry[] = [];\n for (const entry of memoryRoute) {\n if (!entry.memoryModelId || entry.memoryModelId === 'auto' || seenModelIds.has(entry.memoryModelId)) continue;\n seenModelIds.add(entry.memoryModelId);\n const occurrence = (appearances.get(entry.id) ?? 0) + 1;\n appearances.set(entry.id, occurrence);\n try {\n entries.push({\n id: `${entry.id}:memory${occurrence === 1 ? '' : `#${occurrence}`}`,\n model: resolve(entry.memoryModelId),\n });\n } catch {\n break;\n }\n }\n return entries.length > 0 ? entries : undefined;\n}\n\n/**\n * The authoritative per-caller Factory memory-settings row, placed on the request\n * context before Factory's model-dependent processors run. `null` means the row\n * exists but is empty (every role auto). An unavailable sentinel or a missing\n * value on a Factory-owned session falls back to Auto roles and default\n * thresholds/attachments, so memory keeps working while Factory reports the error.\n */\ninterface FactoryMemorySettings {\n observerModelId: string | null;\n reflectorModelId: string | null;\n observationThreshold: number | null;\n reflectionThreshold: number | null;\n observeAttachments: 'auto' | boolean | null;\n}\n\ntype FactoryMemorySettingsContext =\n | FactoryMemorySettings\n | null\n | { status: 'unavailable'; reason: string }\n | undefined;\n\nfunction getFactoryMemorySettingsContext(requestContext: RequestContext): FactoryMemorySettingsContext {\n return requestContext.get('mastra__factoryMemorySettings') as FactoryMemorySettingsContext;\n}\n\nfunction isFactoryMemorySettingsUnavailable(\n settings: FactoryMemorySettingsContext,\n): settings is { status: 'unavailable'; reason: string } {\n return settings !== null && typeof settings === 'object' && 'status' in settings && settings.status === 'unavailable';\n}\n\nfunction getMainModelId(requestContext: RequestContext): string | undefined {\n const controller = requestContext.get('controller') as AgentControllerRequestContext<MastraCodeState> | undefined;\n return controller?.session.modelId || (controller?.getState()?.currentModelId as string | undefined);\n}\n\n/**\n * Resolve one OM role's model for this invocation. Returns `'auto'` for Memory's\n * auto policy, or a concrete model. Factory's DB row is authoritative for\n * Factory sessions (an unreadable row falls back to auto). Otherwise the active\n * model route's memory models win, then the per-role selection, then legacy\n * concrete settings.\n */\nfunction resolveOmRoleModelForRequest(\n role: 'observer' | 'reflector',\n requestContext: RequestContext,\n settingsPath?: string,\n options?: { disableSettingsOmSeed?: boolean },\n): 'auto' | GatewayLanguageModel | MemoryModelRouteEntry[] {\n const controller = requestContext.get('controller') as AgentControllerRequestContext<MastraCodeState> | undefined;\n const state = controller?.getState() as MastraCodeState | undefined;\n const resolveOptions = { remapForCodexOAuth: true, requestContext, anthropicPromptCacheScope: 'system' } as const;\n const factorySettingsContext = getFactoryMemorySettingsContext(requestContext);\n const isFactory = typeof state?.factoryProjectId === 'string';\n\n const useModel = (modelId: string) => {\n requestContext.set(`om.${role}.selectionMode`, 'model');\n requestContext.set(`om.${role}.effectiveModelId`, modelId);\n return resolveModel(modelId, resolveOptions);\n };\n const useAuto = () => {\n requestContext.set(`om.${role}.selectionMode`, 'auto');\n // These two keys are declared in the span-context allowlist\n // (`mastracode/sdk/src/index.ts`), so traces can report intent separately from\n // the effective concrete model without either being mistaken for a model ID.\n requestContext.set(`om.${role}.effectiveModelId`, resolveAutoOMModelId(getMainModelId(requestContext)));\n return 'auto' as const;\n };\n\n if (\n isFactoryMemorySettingsUnavailable(factorySettingsContext) ||\n (factorySettingsContext === undefined && isFactory)\n ) {\n return useAuto();\n }\n if (factorySettingsContext !== undefined) {\n const factoryModelId = factorySettingsContext?.[`${role}ModelId`];\n return factoryModelId ? useModel(factoryModelId) : useAuto();\n }\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 override resolution for\n // observational memory as it does for the main model. Hosts that disable the\n // settings seed never read it.\n const settings = options?.disableSettingsOmSeed ? undefined : loadSettings(settingsPath);\n const routeMemory = resolveRouteMemoryModels(state, controller?.threadId, modelId =>\n resolveModel(modelId, resolveOptions),\n );\n if (routeMemory === 'auto') return useAuto();\n if (routeMemory) {\n requestContext.set(`om.${role}.selectionMode`, 'model');\n requestContext.set(`om.${role}.effectiveModelId`, routeMemory[0]?.model.modelId);\n return routeMemory.length === 1 ? routeMemory[0]!.model : routeMemory;\n }\n\n const selection: unknown = state?.[`${role}ModelSelection`];\n if (selection === 'auto') return useAuto();\n if (typeof selection === 'string' && selection) return useModel(selection);\n if (\n selection &&\n typeof selection === 'object' &&\n 'modelId' in selection &&\n typeof selection.modelId === 'string' &&\n selection.modelId\n ) {\n return useModel(selection.modelId);\n }\n\n const roleOverride =\n role === 'observer' ? settings?.models?.observerModelOverride : settings?.models?.reflectorModelOverride;\n if (roleOverride) return useModel(roleOverride);\n const legacyModelId = state?.[`${role}ModelId`];\n if (typeof legacyModelId === 'string' && legacyModelId) return useModel(legacyModelId);\n return useAuto();\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(\n storage: MastraCompositeStore,\n vector?: MastraVector,\n settingsPath?: string,\n options?: { disableSettingsOmSeed?: boolean },\n knowledge?: Knowledge,\n) {\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, options);\n const getReflectorModel = ({ requestContext }: { requestContext: RequestContext }) =>\n resolveOmRoleModelForRequest('reflector', requestContext, settingsPath, options);\n // Routes the concrete model Memory's `'auto'` picks through Mastra Code's\n // credential-aware resolver, like every other Mastra Code model.\n const resolveMemoryModel = (modelId: string, { requestContext }: { requestContext?: RequestContext }) =>\n resolveModel(modelId, { remapForCodexOAuth: true, requestContext, anthropicPromptCacheScope: 'system' });\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 // The Factory row is authoritative and read per invocation, so a stored\n // threshold/attachment change reaches the running Memory without a session.\n const factorySettingsContext = getFactoryMemorySettingsContext(requestContext);\n const factorySettingsUnavailable =\n isFactoryMemorySettingsUnavailable(factorySettingsContext) || (factorySettingsContext === undefined && isFactory);\n const factorySettings = factorySettingsUnavailable ? null : factorySettingsContext;\n const obsThreshold =\n factorySettings !== undefined\n ? (factorySettings?.observationThreshold ?? DEFAULT_OBS_THRESHOLD)\n : (state?.observationThreshold ?? DEFAULT_OBS_THRESHOLD);\n const refThreshold =\n factorySettings !== undefined\n ? (factorySettings?.reflectionThreshold ?? DEFAULT_REF_THRESHOLD)\n : (state?.reflectionThreshold ?? DEFAULT_REF_THRESHOLD);\n const caveman = state?.cavemanObservations ?? false;\n\n const observerPreviousObservationTokens = 1000;\n // The row is authoritative: an absent value means the user left it on Auto,\n // which the config API reports as 'auto' and Memory resolves by model\n // capability.\n const observeAttachments =\n factorySettings !== undefined ? (factorySettings?.observeAttachments ?? 'auto') : state?.observeAttachments;\n // Factory sessions get a factory-only Subconscious config, so the cache key\n // carries Factory presence and settings availability to keep those configs\n // 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 ...(knowledge ? { knowledge } : {}),\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 process.env.MASTRACODE_DISABLE_TITLE_GENERATION === '1'\n ? false\n : {\n model: ({ requestContext }) => {\n const resolved = getObserverModel({ requestContext });\n if (resolved === 'auto') {\n return resolveMemoryModel(resolveAutoOMModelId(getMainModelId(requestContext)), { requestContext });\n }\n return Array.isArray(resolved) ? resolved[0]!.model : resolved;\n },\n },\n observationalMemory:\n process.env.MASTRACODE_DISABLE_OBSERVATIONAL_MEMORY === '1'\n ? false\n : {\n enabled: true,\n autoModels: MASTRACODE_AUTO_OM_MODELS,\n resolveModel: resolveMemoryModel,\n temporalMarkers: true,\n retrieval: vector ? { vector: true } : true,\n experimental_subconscious: subconsciousAvailable\n ? new Subconscious({\n defaultScope: '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":";;;;;;;;;;;;;;;AAyBA,SAAS,yBACP,OACA,UACA,SAC8C;CAC9C,MAAM,cAAc,qBAAqB,OAAO,QAAQ;CACxD,IAAI,YAAY,EAAE,EAAE,kBAAkB,QAAQ,OAAO;CACrD,MAAM,+BAAe,IAAI,IAAY;CACrC,MAAM,8BAAc,IAAI,IAAoB;CAC5C,MAAM,UAAmC,CAAC;CAC1C,KAAK,MAAM,SAAS,aAAa;EAC/B,IAAI,CAAC,MAAM,iBAAiB,MAAM,kBAAkB,UAAU,aAAa,IAAI,MAAM,aAAa,GAAG;EACrG,aAAa,IAAI,MAAM,aAAa;EACpC,MAAM,cAAc,YAAY,IAAI,MAAM,EAAE,KAAK,KAAK;EACtD,YAAY,IAAI,MAAM,IAAI,UAAU;EACpC,IAAI;GACF,QAAQ,KAAK;IACX,IAAI,GAAG,MAAM,GAAG,SAAS,eAAe,IAAI,KAAK,IAAI;IACrD,OAAO,QAAQ,MAAM,aAAa;GACpC,CAAC;EACH,QAAQ;GACN;EACF;CACF;CACA,OAAO,QAAQ,SAAS,IAAI,UAAU,KAAA;AACxC;AAuBA,SAAS,gCAAgC,gBAA8D;CACrG,OAAO,eAAe,IAAI,+BAA+B;AAC3D;AAEA,SAAS,mCACP,UACuD;CACvD,OAAO,aAAa,QAAQ,OAAO,aAAa,YAAY,YAAY,YAAY,SAAS,WAAW;AAC1G;AAEA,SAAS,eAAe,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;KACF;KACA,YAAY;MACV,kBAAkB,kBAAkB,KAAA,IAAY,IAAI;MACpD,YAAY;MACZ,OAAO;MACP,mBAAmB;MACnB,aAAa;KACf;IACF;GACR;EACF,CAAC;EACD,kBAAkB;EAElB,OAAO;CACT;AACF"}
@@ -1,5 +1,5 @@
1
1
  import type { ModelWithRetries } from '@mastra/core/agent';
2
- import type { GatewayLanguageModel, MastraModelGatewayInterface } from '@mastra/core/llm';
2
+ import type { GatewayLanguageModel, IdentifiedModelConfig, MastraModelGatewayInterface } from '@mastra/core/llm';
3
3
  import type { RequestContext } from '@mastra/core/request-context';
4
4
  import type { CredentialStore } from '../auth/types.js';
5
5
  import type { AnthropicPromptCacheScope } from '../providers/anthropic-prompt-cache.js';
@@ -67,7 +67,38 @@ export declare function resolveRequestThinkingLevel(agentControllerContext: Thin
67
67
  */
68
68
  export declare function getDynamicModel({ requestContext }: {
69
69
  requestContext: RequestContext;
70
- }, settingsPath?: string): ResolvedModel | ModelWithRetries[];
70
+ }, settingsPath?: string): IdentifiedModelConfig | ModelWithRetries[];
71
+ type MemoryRouteState = {
72
+ modelRoute?: {
73
+ entries?: Array<{
74
+ id?: unknown;
75
+ memoryModelId?: unknown;
76
+ }>;
77
+ };
78
+ mastracodePendingModelFallback?: {
79
+ toEntryId?: unknown;
80
+ threadId?: unknown;
81
+ } | null;
82
+ };
83
+ /**
84
+ * The active model route for memory: the session route, starting at a pending
85
+ * fallback hop captured for this thread.
86
+ */
87
+ export declare function getActiveMemoryRoute<TEntry extends {
88
+ id?: unknown;
89
+ memoryModelId?: unknown;
90
+ }>(state: {
91
+ modelRoute?: {
92
+ entries?: TEntry[];
93
+ };
94
+ mastracodePendingModelFallback?: MemoryRouteState['mastracodePendingModelFallback'];
95
+ } | undefined, threadId?: string | null): TEntry[];
96
+ /**
97
+ * The memory model the active route applies to both OM roles: `'auto'`, the
98
+ * first concrete memory model, or `undefined` when the route sets none (both
99
+ * roles then follow their `/om` settings).
100
+ */
101
+ export declare function getActiveRouteMemoryModelId(state: Readonly<Record<string, unknown>> | undefined, threadId?: string | null): string | undefined;
71
102
  /**
72
103
  * Goal judge model resolver for the agent's `goal.judge` config. Resolves the
73
104
  * configured goal judge model through mastracode's gateway so provider
@@ -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;AAQ5E,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,wCAAwC,CAAC;AAExF,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,OAAO,EACL,wBAAwB,EACxB,wBAAwB,EACxB,sBAAsB,GACvB,MAAM,6BAA6B,CAAC;AACrC,YAAY,EAAE,qBAAqB,EAAE,MAAM,6BAA6B,CAAC;AAEzE,KAAK,aAAa,GAAG,oBAAoB,CAAC;AAkB1C,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,CAAC;AAEF;;;GAGG;AACH,wBAAgB,oBAAoB,CAAC,MAAM,SAAS;IAAE,EAAE,CAAC,EAAE,OAAO,CAAC;IAAC,aAAa,CAAC,EAAE,OAAO,CAAA;CAAE,EAC3F,KAAK,EACD;IACE,UAAU,CAAC,EAAE;QAAE,OAAO,CAAC,EAAE,MAAM,EAAE,CAAA;KAAE,CAAC;IACpC,8BAA8B,CAAC,EAAE,gBAAgB,CAAC,gCAAgC,CAAC,CAAC;CACrF,GACD,SAAS,EACb,QAAQ,CAAC,EAAE,MAAM,GAAG,IAAI,GACvB,MAAM,EAAE,CASV;AAED;;;;GAIG;AACH,wBAAgB,2BAA2B,CACzC,KAAK,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,GAAG,SAAS,EACpD,QAAQ,CAAC,EAAE,MAAM,GAAG,IAAI,GACvB,MAAM,GAAG,SAAS,CAQpB;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAgB,iBAAiB,CAC/B,EAAE,cAAc,EAAE,EAAE;IAAE,cAAc,EAAE,cAAc,CAAA;CAAE,EACtD,YAAY,CAAC,EAAE,MAAM,GACpB,aAAa,GAAG,SAAS,CAI3B"}
@@ -1,7 +1,8 @@
1
1
  import "../constants.js";
2
2
  import { MASTRA_GATEWAY_PREFIX, remapOpenAIModelForCodexOAuth, stripMastraGatewayPrefix } from "../providers/model-ids.js";
3
- import { ProviderAuthRequiredError } from "../auth/provider-auth-error.js";
4
3
  import { isThinkingLevelSetting } from "../thinking.js";
4
+ import { ProviderAuthRequiredError } from "../auth/provider-auth-error.js";
5
+ import { toMemoryModelId } from "../onboarding/packs.js";
5
6
  import { loadSettings, resolveDefaultThinkingLevel, stripMastraCodeCustomProviderPrefix } from "../onboarding/settings.js";
6
7
  import { hasCredentialStoreProvider, resolveCredentialStore, resolveTenantFromRequestContext, setCredentialStoreProvider } from "./credential-resolver.js";
7
8
  import { getRequestAccountSelection, isRequestAccountRoutingExhausted } from "../auth/account-routing-context.js";
@@ -175,7 +176,7 @@ function getDynamicModel({ requestContext }, settingsPath) {
175
176
  remapForCodexOAuth: true,
176
177
  requestContext
177
178
  };
178
- const primary = resolveModel(modelId, resolveOptions);
179
+ const primary = identifyModel(modelId, resolveModel(modelId, resolveOptions));
179
180
  const route = state?.modelRoute?.entries?.slice(0, 32);
180
181
  const pendingEntryId = pendingFallback && typeof pendingFallback.toEntryId === "string" ? pendingFallback.toEntryId : void 0;
181
182
  const startIndex = pendingEntryId ? route?.findIndex((entry) => entry.id === pendingEntryId) : 0;
@@ -200,11 +201,38 @@ function getDynamicModel({ requestContext }, settingsPath) {
200
201
  appearances.set(routeEntry.id, occurrence);
201
202
  entries.push({
202
203
  id: occurrence === 1 ? routeEntry.id : `${routeEntry.id}#${occurrence}`,
203
- model: entryModel
204
+ model: identifyModel(routeEntry.modelId, entryModel)
204
205
  });
205
206
  }
206
207
  return entries.length < 2 ? primary : entries;
207
208
  }
209
+ function identifyModel(modelId, model) {
210
+ return {
211
+ model,
212
+ id: toMemoryModelId(modelId)
213
+ };
214
+ }
215
+ /**
216
+ * The active model route for memory: the session route, starting at a pending
217
+ * fallback hop captured for this thread.
218
+ */
219
+ function getActiveMemoryRoute(state, threadId) {
220
+ const pending = state?.mastracodePendingModelFallback;
221
+ const sameThreadPending = pending && (pending.threadId === void 0 || pending.threadId === threadId) ? pending : void 0;
222
+ const routeEntries = state?.modelRoute?.entries?.slice(0, 32) ?? [];
223
+ const pendingIndex = sameThreadPending ? routeEntries.findIndex((entry) => entry.id === sameThreadPending.toEntryId) : -1;
224
+ return pendingIndex >= 0 ? routeEntries.slice(pendingIndex) : routeEntries;
225
+ }
226
+ /**
227
+ * The memory model the active route applies to both OM roles: `'auto'`, the
228
+ * first concrete memory model, or `undefined` when the route sets none (both
229
+ * roles then follow their `/om` settings).
230
+ */
231
+ function getActiveRouteMemoryModelId(state, threadId) {
232
+ const route = getActiveMemoryRoute(state, threadId);
233
+ if (route[0]?.memoryModelId === "auto") return "auto";
234
+ return route.find((candidate) => typeof candidate.memoryModelId === "string" && candidate.memoryModelId && candidate.memoryModelId !== "auto")?.memoryModelId;
235
+ }
208
236
  /**
209
237
  * Goal judge model resolver for the agent's `goal.judge` config. Resolves the
210
238
  * configured goal judge model through mastracode's gateway so provider
@@ -228,6 +256,6 @@ function getGoalJudgeModel({ requestContext }, settingsPath) {
228
256
  });
229
257
  }
230
258
  //#endregion
231
- export { MASTRACODE_GATEWAY_ID, MastraCodeGateway, createMastraCodeGateway, createMastraCodeModelCatalogProvider, createRequestScopedCredentialStore, getAnthropicApiKey, getDynamicModel, getGoalJudgeModel, getOpenAIApiKey, hasCredentialStoreProvider, hasCustomProvidersSource, remapOpenAIModelForCodexOAuth, resolveAuth, resolveCustomProviders, resolveModel, resolveModelId, resolveRequestThinkingLevel, resolveTenantFromRequestContext, setCredentialStoreProvider, setCustomProvidersSource };
259
+ export { MASTRACODE_GATEWAY_ID, MastraCodeGateway, createMastraCodeGateway, createMastraCodeModelCatalogProvider, createRequestScopedCredentialStore, getActiveMemoryRoute, getActiveRouteMemoryModelId, getAnthropicApiKey, getDynamicModel, getGoalJudgeModel, getOpenAIApiKey, hasCredentialStoreProvider, hasCustomProvidersSource, remapOpenAIModelForCodexOAuth, resolveAuth, resolveCustomProviders, resolveModel, resolveModelId, resolveRequestThinkingLevel, resolveTenantFromRequestContext, setCredentialStoreProvider, setCustomProvidersSource };
232
260
 
233
261
  //# sourceMappingURL=model.js.map
@@ -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 { MODEL_ROUTE_MAX_ENTRIES } from '../constants.js';\nimport {\n loadSettings,\n resolveDefaultThinkingLevel,\n stripMastraCodeCustomProviderPrefix,\n} from '../onboarding/settings.js';\nimport { AMAZON_BEDROCK_GATEWAY_ID, createAmazonBedrockGateway } from '../providers/amazon-bedrock-gateway.js';\nimport type { AnthropicPromptCacheScope } from '../providers/anthropic-prompt-cache.js';\nimport { isThinkingLevelSetting } from '../thinking.js';\nimport type { ThinkingLevelSetting } from '../thinking.js';\nimport { resolveCredentialStore } from './credential-resolver.js';\nimport { resolveCustomProviders } from './custom-provider-source.js';\nimport {\n MASTRA_GATEWAY_PREFIX,\n MASTRACODE_GATEWAY_ID,\n MastraCodeGateway,\n getGlobalAuthStorage,\n reloadAuthStorage,\n stripMastraGatewayPrefix,\n} from './mastracode-gateway.js';\nimport type { MastraCodeGatewayOptions } from './mastracode-gateway.js';\n\nexport {\n getAnthropicApiKey,\n getOpenAIApiKey,\n MASTRACODE_GATEWAY_ID,\n MastraCodeGateway,\n remapOpenAIModelForCodexOAuth,\n resolveAuth,\n} from './mastracode-gateway.js';\nexport type { MastraCodeCustomProvider, MastraCodeGatewayOptions } from './mastracode-gateway.js';\nexport {\n setCredentialStoreProvider,\n hasCredentialStoreProvider,\n resolveTenantFromRequestContext,\n} from './credential-resolver.js';\nexport type { CredentialTenant, CredentialStoreProvider } from './credential-resolver.js';\nexport {\n setCustomProvidersSource,\n hasCustomProvidersSource,\n resolveCustomProviders,\n} from './custom-provider-source.js';\nexport type { CustomProvidersSource } from './custom-provider-source.js';\n\ntype ResolvedModel = GatewayLanguageModel;\ntype ModelRequestHeaders = Record<string, string>;\n\nfunction getAgentControllerHeaders(requestContext?: RequestContext): ModelRequestHeaders | undefined {\n const agentControllerContext = requestContext?.get('controller') as AgentControllerRequestContext<any> | undefined;\n const headers = {\n ...(agentControllerContext?.threadId ? { 'x-thread-id': agentControllerContext.threadId } : {}),\n ...(agentControllerContext?.resourceId ? { 'x-resource-id': agentControllerContext.resourceId } : {}),\n };\n\n return Object.keys(headers).length > 0 ? headers : undefined;\n}\n\nfunction accountCredential(account: OAuthAccountRecord) {\n const { type: _type, id: _id, label: _label, addedAt: _addedAt, active: _active, ...credential } = account;\n return { type: 'oauth' as const, ...credential };\n}\n\nexport function createRequestScopedCredentialStore(\n base: CredentialStore,\n requestContext?: RequestContext,\n): CredentialStore {\n const selectedId = (providerId: string) => getRequestAccountSelection(requestContext, providerId);\n const selectedAccount = (providerId: string) => {\n const accountInstanceId = selectedId(providerId);\n return accountInstanceId\n ? base.listAccounts?.(providerId).find(account => account.id === accountInstanceId)\n : undefined;\n };\n // Routing rejected every account for this provider on this request. Fail\n // closed on every credential read: falling through to `base` would use the\n // provider's active account — the exhausted one routing just refused.\n const rejectAll = (providerId: string) => isRequestAccountRoutingExhausted(requestContext, providerId);\n\n return {\n allowEnvironmentFallback: base.allowEnvironmentFallback,\n reload: () => base.reload(),\n get: providerId => {\n if (rejectAll(providerId)) return undefined;\n // A selection that no longer resolves (the account was removed between\n // routing and the credential read) must not fall through to the active\n // account — that is the account routing deliberately passed over.\n const accountInstanceId = selectedId(providerId);\n if (accountInstanceId === undefined) return base.get(providerId);\n const selected = selectedAccount(providerId);\n return selected ? accountCredential(selected) : undefined;\n },\n getStoredApiKey: providerId => {\n if (rejectAll(providerId)) return undefined;\n // The provider-wide `apikey:` slot is never the credential routing\n // selected, so serving it to a routed request is an OAuth -> API-key\n // fallback of the same provider — the one combination this feature\n // forbids. Unlike `get`, this read has no account argument to pass\n // through, so a selection fails it closed instead.\n if (selectedId(providerId) !== undefined) return undefined;\n return base.getStoredApiKey(providerId);\n },\n getApiKey: providerId =>\n rejectAll(providerId) ? Promise.resolve(undefined) : base.getApiKey(providerId, selectedId(providerId)),\n getOAuthCredential: base.getOAuthCredential\n ? providerId =>\n rejectAll(providerId)\n ? Promise.resolve(undefined)\n : base.getOAuthCredential!(providerId, selectedId(providerId))\n : undefined,\n listAccounts: base.listAccounts ? providerId => base.listAccounts!(providerId) : undefined,\n getActiveAccount: base.getActiveAccount ? providerId => base.getActiveAccount!(providerId) : undefined,\n activateAccount: base.activateAccount\n ? (providerId, accountInstanceId) => base.activateAccount!(providerId, accountInstanceId)\n : undefined,\n removeAccount: base.removeAccount\n ? (providerId, accountInstanceId) => base.removeAccount!(providerId, accountInstanceId)\n : undefined,\n };\n}\n\nexport function createMastraCodeGateway(options: MastraCodeGatewayOptions): MastraCodeGateway {\n return new MastraCodeGateway(options);\n}\n\nexport function createMastraCodeModelCatalogProvider(gateway: MastraModelGatewayInterface) {\n return gateway instanceof MastraCodeGateway\n ? gateway.createModelCatalogProvider()\n : MastraCodeGateway.createModelCatalogProvider(gateway);\n}\n\n/**\n * Placeholder for future model ID normalization.\n * Currently returns the input unchanged, but exists as a seam\n * for aliasing, casing fixes, or validation in the future.\n */\nexport function resolveModelId(modelId: string): string {\n return modelId;\n}\n\n/**\n * Resolve a model ID to the correct provider instance.\n * Shared by the main agent, observer, and reflector.\n *\n * - For anthropic/* models: Uses stored OAuth credentials when present, otherwise direct API key\n * - For openai/* models: Uses OAuth when configured, otherwise direct API key from AuthStorage\n * - For moonshotai/* models: Uses Moonshot AI Anthropic-compatible endpoint\n * - For all other providers: Uses Mastra's model router (models.dev gateway)\n */\nexport function resolveModel(\n modelId: string,\n options?: {\n thinkingLevel?: ThinkingLevelSetting;\n remapForCodexOAuth?: boolean;\n requestContext?: RequestContext;\n anthropicPromptCacheScope?: AnthropicPromptCacheScope;\n },\n): GatewayLanguageModel {\n reloadAuthStorage();\n const headers = getAgentControllerHeaders(options?.requestContext);\n const settings = loadSettings();\n // Bedrock was previously cataloged under the MastraCode gateway namespace\n // (`mastracode/amazon-bedrock/<model>`). Normalize any legacy saved ids to the\n // standalone `amazon-bedrock/<model>` form so they resolve through the\n // dedicated Bedrock gateway.\n const bedrockLegacyPrefix = `${MASTRACODE_GATEWAY_ID}/amazon-bedrock/`;\n const bedrockNormalizedInput = modelId.startsWith(bedrockLegacyPrefix)\n ? modelId.slice(MASTRACODE_GATEWAY_ID.length + 1)\n : modelId;\n // Deployed web registers a custom providers source (DB-backed, tenant\n // scoped); when registered it is authoritative and settings.json custom\n // providers are ignored. Undefined = local settings-based behavior.\n const customProviders = resolveCustomProviders(options?.requestContext) ?? settings.customProviders;\n // Ids selected from the shared /models catalog were previously persisted in\n // the gateway-qualified `mastracode/<customProviderId>/<model>` form, which\n // parses the provider as `mastracode` and breaks provider config lookup.\n // Normalize at resolution time (in addition to stripping at selection time)\n // so already-saved ids and any surface that persists the raw catalog id\n // still resolve to the custom provider.\n const normalizedInput = stripMastraCodeCustomProviderPrefix(bedrockNormalizedInput, customProviders);\n const isMastraGatewayModel = normalizedInput.startsWith(MASTRA_GATEWAY_PREFIX);\n const normalizedModelId = stripMastraGatewayPrefix(normalizedInput);\n const [providerId, ...modelParts] = normalizedModelId.split('/');\n const bareModelId = modelParts.join('/');\n if (!providerId || !bareModelId) {\n throw new Error(`Invalid model id: ${modelId}`);\n }\n\n // Deployed web registers a per-tenant credential store provider; when the\n // request carries an authenticated tenant, resolve credentials through the\n // caller's own store (user > org > env). Undefined = global AuthStorage.\n const tenantCredentialStore = resolveCredentialStore(options?.requestContext);\n const baseCredentialStore = tenantCredentialStore ?? getGlobalAuthStorage();\n\n if (providerId === AMAZON_BEDROCK_GATEWAY_ID) {\n // Bedrock authenticates through the server process's AWS credential chain,\n // never a tenant credential. A tenant store only lets it through when the\n // operator opted the deployment in.\n if (\n tenantCredentialStore?.allowEnvironmentFallback === false &&\n !tenantCredentialStore.allowsDeploymentCredentials?.(AMAZON_BEDROCK_GATEWAY_ID)\n ) {\n throw new ProviderAuthRequiredError(\n 'Amazon Bedrock is not enabled for this Factory deployment. The operator must provide AWS credentials to the server and set FACTORY_DEPLOYMENT_MODEL_PROVIDERS=amazon-bedrock.',\n );\n }\n const bedrockGateway = createAmazonBedrockGateway();\n const routerId = `${AMAZON_BEDROCK_GATEWAY_ID}/${bareModelId}`;\n const auth = bedrockGateway.resolveAuth({\n gatewayId: AMAZON_BEDROCK_GATEWAY_ID,\n providerId: AMAZON_BEDROCK_GATEWAY_ID,\n modelId: bareModelId,\n routerId,\n });\n return bedrockGateway.resolveLanguageModel({\n providerId: AMAZON_BEDROCK_GATEWAY_ID,\n modelId: bareModelId,\n apiKey: auth?.apiKey ?? '',\n headers,\n });\n }\n\n const routerId = `${MASTRACODE_GATEWAY_ID}/${normalizedModelId}`;\n\n const mgApiKey = MastraCodeGateway.getMastraGatewayApiKey();\n const rawGatewayBase =\n settings.memoryGateway?.baseUrl ?? process.env['MASTRA_GATEWAY_URL'] ?? 'https://gateway-api.mastra.ai';\n const credentialStore = createRequestScopedCredentialStore(baseCredentialStore, options?.requestContext);\n const gateway = createMastraCodeGateway({\n mastraGatewayBaseUrl: rawGatewayBase.replace(/\\/+$/, '').replace(/\\/v1$/, ''),\n mastraGatewayApiKey: mgApiKey,\n routeThroughMastraGateway: Boolean(mgApiKey && isMastraGatewayModel),\n thinkingLevel: options?.thinkingLevel,\n anthropicPromptCacheScope: options?.anthropicPromptCacheScope,\n customProviders,\n credentialStore,\n });\n\n const auth = gateway.resolveAuth({\n gatewayId: MASTRACODE_GATEWAY_ID,\n providerId,\n modelId: bareModelId,\n routerId,\n });\n\n if (!auth && credentialStore?.allowEnvironmentFallback === false) {\n throw new ProviderAuthRequiredError(\n `No usable ${providerId} credential is configured for this signed-in Factory account. Connect the provider or add an organization credential, then try again.`,\n );\n }\n\n return gateway.resolveLanguageModel({\n providerId,\n modelId: bareModelId,\n apiKey: auth?.apiKey ?? '',\n headers,\n });\n}\n\nexport interface ThinkingRequestContext {\n state?: { thinkingLevel?: unknown };\n session?: { modeId?: string };\n}\n/**\n * Resolve the effective thinking level for the current request.\n *\n * Precedence:\n * 1. Session override (`state.thinkingLevel`, set via /think or the session\n * settings panel).\n * 2. Per-mode default from settings (`models.modeThinkingDefaults[mode]`).\n * 3. Global default (`preferences.thinkingLevel`).\n *\n * Resolved per-request (not seeded at session start) so configuration changes\n * apply to the next request of every session — including automated\n * (rule-driven) Factory runs that nobody ever opens interactively.\n */\n\nexport function resolveRequestThinkingLevel(\n agentControllerContext: ThinkingRequestContext | undefined,\n settingsPath?: string,\n): ThinkingLevelSetting {\n const override = agentControllerContext?.state?.thinkingLevel;\n if (isThinkingLevelSetting(override)) return override;\n const modeId = agentControllerContext?.session?.modeId;\n return resolveDefaultThinkingLevel(loadSettings(settingsPath), modeId).level;\n}\n\n/**\n * Dynamic model function that reads the current model and optional ordered\n * fallback route from controller state. Route entry ids are opaque host-owned\n * identifiers; repeated ids receive occurrence suffixes because core tracks the\n * active fallback index by id across agentic steps.\n */\nexport function getDynamicModel(\n { requestContext }: { requestContext: RequestContext },\n settingsPath?: string,\n): ResolvedModel | ModelWithRetries[] {\n const controller = requestContext.get('controller') as AgentControllerRequestContext<any> | undefined;\n const state = controller?.getState?.() as\n | {\n modelRoute?: {\n entries?: Array<{ id?: unknown; modelId?: unknown }>;\n };\n mastracodePendingModelFallback?: { toEntryId?: unknown; toModelId?: unknown; threadId?: unknown } | null;\n }\n | undefined;\n const pendingState = state?.mastracodePendingModelFallback;\n const pendingFallback =\n pendingState &&\n (pendingState.threadId === undefined ||\n (typeof pendingState.threadId === 'string' && pendingState.threadId === controller?.threadId))\n ? pendingState\n : undefined;\n const pendingModelId =\n pendingFallback && typeof pendingFallback.toModelId === 'string' && pendingFallback.toModelId.length > 0\n ? pendingFallback.toModelId\n : undefined;\n const modelId = pendingModelId ?? controller?.session?.modelId;\n if (!modelId) {\n if (!controller) {\n throw new Error(\n 'No model available: this run started without a controller session context, so no model selection could be resolved.',\n );\n }\n throw new Error('No model selected. Use /models to select a model first.');\n }\n\n const thinkingLevel = resolveRequestThinkingLevel(controller, settingsPath);\n const resolveOptions = { thinkingLevel, remapForCodexOAuth: true, requestContext } as const;\n const primary = resolveModel(modelId, resolveOptions);\n const route = state?.modelRoute?.entries?.slice(0, MODEL_ROUTE_MAX_ENTRIES);\n const pendingEntryId =\n pendingFallback && typeof pendingFallback.toEntryId === 'string' ? pendingFallback.toEntryId : undefined;\n const startIndex = pendingEntryId ? route?.findIndex(entry => entry.id === pendingEntryId) : 0;\n const activeRoute = route && startIndex !== undefined && startIndex >= 0 ? route.slice(startIndex) : undefined;\n if (!activeRoute || activeRoute.length < 2 || activeRoute[0]?.modelId !== modelId) return primary;\n\n const firstId =\n typeof activeRoute[0]?.id === 'string' && activeRoute[0].id.length > 0 ? activeRoute[0].id : undefined;\n if (!firstId) return primary;\n\n const entries: ModelWithRetries[] = [{ id: firstId, model: primary }];\n const appearances = new Map<string, number>([[firstId, 1]]);\n for (const routeEntry of activeRoute.slice(1)) {\n if (\n typeof routeEntry.id !== 'string' ||\n routeEntry.id.length === 0 ||\n typeof routeEntry.modelId !== 'string' ||\n routeEntry.modelId.length === 0\n ) {\n break;\n }\n let entryModel: ResolvedModel;\n try {\n entryModel = resolveModel(routeEntry.modelId, resolveOptions);\n } catch {\n break;\n }\n const occurrence = (appearances.get(routeEntry.id) ?? 0) + 1;\n appearances.set(routeEntry.id, occurrence);\n entries.push({\n id: occurrence === 1 ? routeEntry.id : `${routeEntry.id}#${occurrence}`,\n model: entryModel,\n });\n }\n\n return entries.length < 2 ? primary : entries;\n}\n\n/**\n * Goal judge model resolver for the agent's `goal.judge` config. Resolves the\n * configured goal judge model through mastracode's gateway so provider\n * credentials (stored in auth storage, not just env) are injected — a bare model\n * id handed to core's default model router would fail to find the API key.\n *\n * Returns `undefined` when no judge model is configured, which keeps the goal\n * step a complete no-op (the goal mechanism requires a judge to do anything).\n *\n * `settingsPath` must be the same source `createMastraCode()` reads from so the\n * judge model and the goal budget (`goalMaxTurns`) come from one config — with a\n * custom `settingsPath` a bare `loadSettings()` here could read a different file\n * and silently turn the goal step into a no-op.\n */\nexport function getGoalJudgeModel(\n { requestContext }: { requestContext: RequestContext },\n settingsPath?: string,\n): ResolvedModel | undefined {\n const judgeModelId = loadSettings(settingsPath).models.goalJudgeModel;\n if (!judgeModelId) return undefined;\n return resolveModel(judgeModelId, { remapForCodexOAuth: true, requestContext });\n}\n"],"mappings":";;;;;;;;;;;AAsDA,SAAS,0BAA0B,gBAAkE;CACnG,MAAM,yBAAyB,gBAAgB,IAAI,YAAY;CAC/D,MAAM,UAAU;EACd,GAAI,wBAAwB,WAAW,EAAE,eAAe,uBAAuB,SAAS,IAAI,CAAC;EAC7F,GAAI,wBAAwB,aAAa,EAAE,iBAAiB,uBAAuB,WAAW,IAAI,CAAC;CACrG;CAEA,OAAO,OAAO,KAAK,OAAO,CAAC,CAAC,SAAS,IAAI,UAAU,KAAA;AACrD;AAEA,SAAS,kBAAkB,SAA6B;CACtD,MAAM,EAAE,MAAM,OAAO,IAAI,KAAK,OAAO,QAAQ,SAAS,UAAU,QAAQ,SAAS,GAAG,eAAe;CACnG,OAAO;EAAE,MAAM;EAAkB,GAAG;CAAW;AACjD;AAEA,SAAgB,mCACd,MACA,gBACiB;CACjB,MAAM,cAAc,eAAuB,2BAA2B,gBAAgB,UAAU;CAChG,MAAM,mBAAmB,eAAuB;EAC9C,MAAM,oBAAoB,WAAW,UAAU;EAC/C,OAAO,oBACH,KAAK,eAAe,UAAU,CAAC,CAAC,MAAK,YAAW,QAAQ,OAAO,iBAAiB,IAChF,KAAA;CACN;CAIA,MAAM,aAAa,eAAuB,iCAAiC,gBAAgB,UAAU;CAErG,OAAO;EACL,0BAA0B,KAAK;EAC/B,cAAc,KAAK,OAAO;EAC1B,MAAK,eAAc;GACjB,IAAI,UAAU,UAAU,GAAG,OAAO,KAAA;GAKlC,IAD0B,WAAW,UACjB,MAAM,KAAA,GAAW,OAAO,KAAK,IAAI,UAAU;GAC/D,MAAM,WAAW,gBAAgB,UAAU;GAC3C,OAAO,WAAW,kBAAkB,QAAQ,IAAI,KAAA;EAClD;EACA,kBAAiB,eAAc;GAC7B,IAAI,UAAU,UAAU,GAAG,OAAO,KAAA;GAMlC,IAAI,WAAW,UAAU,MAA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AAO,YAAY,EAAE,EAAE,OAAO,YAAY,YAAY,EAAE,CAAC,GAAG,SAAS,IAAI,YAAY,EAAE,CAAC,KAAK,KAAA;CAC/F,IAAI,CAAC,SAAS,OAAO;CAErB,MAAM,UAA8B,CAAC;EAAE,IAAI;EAAS,OAAO;CAAQ,CAAC;CACpE,MAAM,8BAAc,IAAI,IAAoB,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC;CAC1D,KAAK,MAAM,cAAc,YAAY,MAAM,CAAC,GAAG;EAC7C,IACE,OAAO,WAAW,OAAO,YACzB,WAAW,GAAG,WAAW,KACzB,OAAO,WAAW,YAAY,YAC9B,WAAW,QAAQ,WAAW,GAE9B;EAEF,IAAI;EACJ,IAAI;GACF,aAAa,aAAa,WAAW,SAAS,cAAc;EAC9D,QAAQ;GACN;EACF;EACA,MAAM,cAAc,YAAY,IAAI,WAAW,EAAE,KAAK,KAAK;EAC3D,YAAY,IAAI,WAAW,IAAI,UAAU;EACzC,QAAQ,KAAK;GACX,IAAI,eAAe,IAAI,WAAW,KAAK,GAAG,WAAW,GAAG,GAAG;GAC3D,OAAO;EACT,CAAC;CACH;CAEA,OAAO,QAAQ,SAAS,IAAI,UAAU;AACxC;;;;;;;;;;;;;;;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, IdentifiedModelConfig, MastraModelGatewayInterface } from '@mastra/core/llm';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport { getRequestAccountSelection, isRequestAccountRoutingExhausted } from '../auth/account-routing-context.js';\nimport { ProviderAuthRequiredError } from '../auth/provider-auth-error.js';\nimport type { CredentialStore, OAuthAccountRecord } from '../auth/types.js';\nimport { MODEL_ROUTE_MAX_ENTRIES } from '../constants.js';\nimport { toMemoryModelId } from '../onboarding/packs.js';\nimport {\n loadSettings,\n resolveDefaultThinkingLevel,\n stripMastraCodeCustomProviderPrefix,\n} from '../onboarding/settings.js';\nimport { AMAZON_BEDROCK_GATEWAY_ID, createAmazonBedrockGateway } from '../providers/amazon-bedrock-gateway.js';\nimport type { AnthropicPromptCacheScope } from '../providers/anthropic-prompt-cache.js';\nimport { isThinkingLevelSetting } from '../thinking.js';\nimport type { ThinkingLevelSetting } from '../thinking.js';\nimport { resolveCredentialStore } from './credential-resolver.js';\nimport { resolveCustomProviders } from './custom-provider-source.js';\nimport {\n MASTRA_GATEWAY_PREFIX,\n MASTRACODE_GATEWAY_ID,\n MastraCodeGateway,\n getGlobalAuthStorage,\n reloadAuthStorage,\n stripMastraGatewayPrefix,\n} from './mastracode-gateway.js';\nimport type { MastraCodeGatewayOptions } from './mastracode-gateway.js';\n\nexport {\n getAnthropicApiKey,\n getOpenAIApiKey,\n MASTRACODE_GATEWAY_ID,\n MastraCodeGateway,\n remapOpenAIModelForCodexOAuth,\n resolveAuth,\n} from './mastracode-gateway.js';\nexport type { MastraCodeCustomProvider, MastraCodeGatewayOptions } from './mastracode-gateway.js';\nexport {\n setCredentialStoreProvider,\n hasCredentialStoreProvider,\n resolveTenantFromRequestContext,\n} from './credential-resolver.js';\nexport type { CredentialTenant, CredentialStoreProvider } from './credential-resolver.js';\nexport {\n setCustomProvidersSource,\n hasCustomProvidersSource,\n resolveCustomProviders,\n} from './custom-provider-source.js';\nexport type { CustomProvidersSource } from './custom-provider-source.js';\n\ntype ResolvedModel = GatewayLanguageModel;\ntype ModelRequestHeaders = Record<string, string>;\n\nfunction getAgentControllerHeaders(requestContext?: RequestContext): ModelRequestHeaders | undefined {\n const agentControllerContext = requestContext?.get('controller') as AgentControllerRequestContext<any> | undefined;\n const headers = {\n ...(agentControllerContext?.threadId ? { 'x-thread-id': agentControllerContext.threadId } : {}),\n ...(agentControllerContext?.resourceId ? { 'x-resource-id': agentControllerContext.resourceId } : {}),\n };\n\n return Object.keys(headers).length > 0 ? headers : undefined;\n}\n\nfunction accountCredential(account: OAuthAccountRecord) {\n const { type: _type, id: _id, label: _label, addedAt: _addedAt, active: _active, ...credential } = account;\n return { type: 'oauth' as const, ...credential };\n}\n\nexport function createRequestScopedCredentialStore(\n base: CredentialStore,\n requestContext?: RequestContext,\n): CredentialStore {\n const selectedId = (providerId: string) => getRequestAccountSelection(requestContext, providerId);\n const selectedAccount = (providerId: string) => {\n const accountInstanceId = selectedId(providerId);\n return accountInstanceId\n ? base.listAccounts?.(providerId).find(account => account.id === accountInstanceId)\n : undefined;\n };\n // Routing rejected every account for this provider on this request. Fail\n // closed on every credential read: falling through to `base` would use the\n // provider's active account — the exhausted one routing just refused.\n const rejectAll = (providerId: string) => isRequestAccountRoutingExhausted(requestContext, providerId);\n\n return {\n allowEnvironmentFallback: base.allowEnvironmentFallback,\n reload: () => base.reload(),\n get: providerId => {\n if (rejectAll(providerId)) return undefined;\n // A selection that no longer resolves (the account was removed between\n // routing and the credential read) must not fall through to the active\n // account — that is the account routing deliberately passed over.\n const accountInstanceId = selectedId(providerId);\n if (accountInstanceId === undefined) return base.get(providerId);\n const selected = selectedAccount(providerId);\n return selected ? accountCredential(selected) : undefined;\n },\n getStoredApiKey: providerId => {\n if (rejectAll(providerId)) return undefined;\n // The provider-wide `apikey:` slot is never the credential routing\n // selected, so serving it to a routed request is an OAuth -> API-key\n // fallback of the same provider — the one combination this feature\n // forbids. Unlike `get`, this read has no account argument to pass\n // through, so a selection fails it closed instead.\n if (selectedId(providerId) !== undefined) return undefined;\n return base.getStoredApiKey(providerId);\n },\n getApiKey: providerId =>\n rejectAll(providerId) ? Promise.resolve(undefined) : base.getApiKey(providerId, selectedId(providerId)),\n getOAuthCredential: base.getOAuthCredential\n ? providerId =>\n rejectAll(providerId)\n ? Promise.resolve(undefined)\n : base.getOAuthCredential!(providerId, selectedId(providerId))\n : undefined,\n listAccounts: base.listAccounts ? providerId => base.listAccounts!(providerId) : undefined,\n getActiveAccount: base.getActiveAccount ? providerId => base.getActiveAccount!(providerId) : undefined,\n activateAccount: base.activateAccount\n ? (providerId, accountInstanceId) => base.activateAccount!(providerId, accountInstanceId)\n : undefined,\n removeAccount: base.removeAccount\n ? (providerId, accountInstanceId) => base.removeAccount!(providerId, accountInstanceId)\n : undefined,\n };\n}\n\nexport function createMastraCodeGateway(options: MastraCodeGatewayOptions): MastraCodeGateway {\n return new MastraCodeGateway(options);\n}\n\nexport function createMastraCodeModelCatalogProvider(gateway: MastraModelGatewayInterface) {\n return gateway instanceof MastraCodeGateway\n ? gateway.createModelCatalogProvider()\n : MastraCodeGateway.createModelCatalogProvider(gateway);\n}\n\n/**\n * Placeholder for future model ID normalization.\n * Currently returns the input unchanged, but exists as a seam\n * for aliasing, casing fixes, or validation in the future.\n */\nexport function resolveModelId(modelId: string): string {\n return modelId;\n}\n\n/**\n * Resolve a model ID to the correct provider instance.\n * Shared by the main agent, observer, and reflector.\n *\n * - For anthropic/* models: Uses stored OAuth credentials when present, otherwise direct API key\n * - For openai/* models: Uses OAuth when configured, otherwise direct API key from AuthStorage\n * - For moonshotai/* models: Uses Moonshot AI Anthropic-compatible endpoint\n * - For all other providers: Uses Mastra's model router (models.dev gateway)\n */\nexport function resolveModel(\n modelId: string,\n options?: {\n thinkingLevel?: ThinkingLevelSetting;\n remapForCodexOAuth?: boolean;\n requestContext?: RequestContext;\n anthropicPromptCacheScope?: AnthropicPromptCacheScope;\n },\n): GatewayLanguageModel {\n reloadAuthStorage();\n const headers = getAgentControllerHeaders(options?.requestContext);\n const settings = loadSettings();\n // Bedrock was previously cataloged under the MastraCode gateway namespace\n // (`mastracode/amazon-bedrock/<model>`). Normalize any legacy saved ids to the\n // standalone `amazon-bedrock/<model>` form so they resolve through the\n // dedicated Bedrock gateway.\n const bedrockLegacyPrefix = `${MASTRACODE_GATEWAY_ID}/amazon-bedrock/`;\n const bedrockNormalizedInput = modelId.startsWith(bedrockLegacyPrefix)\n ? modelId.slice(MASTRACODE_GATEWAY_ID.length + 1)\n : modelId;\n // Deployed web registers a custom providers source (DB-backed, tenant\n // scoped); when registered it is authoritative and settings.json custom\n // providers are ignored. Undefined = local settings-based behavior.\n const customProviders = resolveCustomProviders(options?.requestContext) ?? settings.customProviders;\n // Ids selected from the shared /models catalog were previously persisted in\n // the gateway-qualified `mastracode/<customProviderId>/<model>` form, which\n // parses the provider as `mastracode` and breaks provider config lookup.\n // Normalize at resolution time (in addition to stripping at selection time)\n // so already-saved ids and any surface that persists the raw catalog id\n // still resolve to the custom provider.\n const normalizedInput = stripMastraCodeCustomProviderPrefix(bedrockNormalizedInput, customProviders);\n const isMastraGatewayModel = normalizedInput.startsWith(MASTRA_GATEWAY_PREFIX);\n const normalizedModelId = stripMastraGatewayPrefix(normalizedInput);\n const [providerId, ...modelParts] = normalizedModelId.split('/');\n const bareModelId = modelParts.join('/');\n if (!providerId || !bareModelId) {\n throw new Error(`Invalid model id: ${modelId}`);\n }\n\n // Deployed web registers a per-tenant credential store provider; when the\n // request carries an authenticated tenant, resolve credentials through the\n // caller's own store (user > org > env). Undefined = global AuthStorage.\n const tenantCredentialStore = resolveCredentialStore(options?.requestContext);\n const baseCredentialStore = tenantCredentialStore ?? getGlobalAuthStorage();\n\n if (providerId === AMAZON_BEDROCK_GATEWAY_ID) {\n // Bedrock authenticates through the server process's AWS credential chain,\n // never a tenant credential. A tenant store only lets it through when the\n // operator opted the deployment in.\n if (\n tenantCredentialStore?.allowEnvironmentFallback === false &&\n !tenantCredentialStore.allowsDeploymentCredentials?.(AMAZON_BEDROCK_GATEWAY_ID)\n ) {\n throw new ProviderAuthRequiredError(\n 'Amazon Bedrock is not enabled for this Factory deployment. The operator must provide AWS credentials to the server and set FACTORY_DEPLOYMENT_MODEL_PROVIDERS=amazon-bedrock.',\n );\n }\n const bedrockGateway = createAmazonBedrockGateway();\n const routerId = `${AMAZON_BEDROCK_GATEWAY_ID}/${bareModelId}`;\n const auth = bedrockGateway.resolveAuth({\n gatewayId: AMAZON_BEDROCK_GATEWAY_ID,\n providerId: AMAZON_BEDROCK_GATEWAY_ID,\n modelId: bareModelId,\n routerId,\n });\n return bedrockGateway.resolveLanguageModel({\n providerId: AMAZON_BEDROCK_GATEWAY_ID,\n modelId: bareModelId,\n apiKey: auth?.apiKey ?? '',\n headers,\n });\n }\n\n const routerId = `${MASTRACODE_GATEWAY_ID}/${normalizedModelId}`;\n\n const mgApiKey = MastraCodeGateway.getMastraGatewayApiKey();\n const rawGatewayBase =\n settings.memoryGateway?.baseUrl ?? process.env['MASTRA_GATEWAY_URL'] ?? 'https://gateway-api.mastra.ai';\n const credentialStore = createRequestScopedCredentialStore(baseCredentialStore, options?.requestContext);\n const gateway = createMastraCodeGateway({\n mastraGatewayBaseUrl: rawGatewayBase.replace(/\\/+$/, '').replace(/\\/v1$/, ''),\n mastraGatewayApiKey: mgApiKey,\n routeThroughMastraGateway: Boolean(mgApiKey && isMastraGatewayModel),\n thinkingLevel: options?.thinkingLevel,\n anthropicPromptCacheScope: options?.anthropicPromptCacheScope,\n customProviders,\n credentialStore,\n });\n\n const auth = gateway.resolveAuth({\n gatewayId: MASTRACODE_GATEWAY_ID,\n providerId,\n modelId: bareModelId,\n routerId,\n });\n\n if (!auth && credentialStore?.allowEnvironmentFallback === false) {\n throw new ProviderAuthRequiredError(\n `No usable ${providerId} credential is configured for this signed-in Factory account. Connect the provider or add an organization credential, then try again.`,\n );\n }\n\n return gateway.resolveLanguageModel({\n providerId,\n modelId: bareModelId,\n apiKey: auth?.apiKey ?? '',\n headers,\n });\n}\n\nexport interface ThinkingRequestContext {\n state?: { thinkingLevel?: unknown };\n session?: { modeId?: string };\n}\n/**\n * Resolve the effective thinking level for the current request.\n *\n * Precedence:\n * 1. Session override (`state.thinkingLevel`, set via /think or the session\n * settings panel).\n * 2. Per-mode default from settings (`models.modeThinkingDefaults[mode]`).\n * 3. Global default (`preferences.thinkingLevel`).\n *\n * Resolved per-request (not seeded at session start) so configuration changes\n * apply to the next request of every session — including automated\n * (rule-driven) Factory runs that nobody ever opens interactively.\n */\n\nexport function resolveRequestThinkingLevel(\n agentControllerContext: ThinkingRequestContext | undefined,\n settingsPath?: string,\n): ThinkingLevelSetting {\n const override = agentControllerContext?.state?.thinkingLevel;\n if (isThinkingLevelSetting(override)) return override;\n const modeId = agentControllerContext?.session?.modeId;\n return resolveDefaultThinkingLevel(loadSettings(settingsPath), modeId).level;\n}\n\n/**\n * Dynamic model function that reads the current model and optional ordered\n * fallback route from controller state. Route entry ids are opaque host-owned\n * identifiers; repeated ids receive occurrence suffixes because core tracks the\n * active fallback index by id across agentic steps.\n */\nexport function getDynamicModel(\n { requestContext }: { requestContext: RequestContext },\n settingsPath?: string,\n): IdentifiedModelConfig | ModelWithRetries[] {\n const controller = requestContext.get('controller') as AgentControllerRequestContext<any> | undefined;\n const state = controller?.getState?.() as\n | {\n modelRoute?: {\n entries?: Array<{ id?: unknown; modelId?: unknown }>;\n };\n mastracodePendingModelFallback?: { toEntryId?: unknown; toModelId?: unknown; threadId?: unknown } | null;\n }\n | undefined;\n const pendingState = state?.mastracodePendingModelFallback;\n const pendingFallback =\n pendingState &&\n (pendingState.threadId === undefined ||\n (typeof pendingState.threadId === 'string' && pendingState.threadId === controller?.threadId))\n ? pendingState\n : undefined;\n const pendingModelId =\n pendingFallback && typeof pendingFallback.toModelId === 'string' && pendingFallback.toModelId.length > 0\n ? pendingFallback.toModelId\n : undefined;\n const modelId = pendingModelId ?? controller?.session?.modelId;\n if (!modelId) {\n if (!controller) {\n throw new Error(\n 'No model available: this run started without a controller session context, so no model selection could be resolved.',\n );\n }\n throw new Error('No model selected. Use /models to select a model first.');\n }\n\n const thinkingLevel = resolveRequestThinkingLevel(controller, settingsPath);\n const resolveOptions = { thinkingLevel, remapForCodexOAuth: true, requestContext } as const;\n // Label each resolved model with its full ID: the resolved gateway model only\n // knows its bare provider model, and Memory's `'auto'` reads this label.\n const primary = identifyModel(modelId, resolveModel(modelId, resolveOptions));\n const route = state?.modelRoute?.entries?.slice(0, MODEL_ROUTE_MAX_ENTRIES);\n const pendingEntryId =\n pendingFallback && typeof pendingFallback.toEntryId === 'string' ? pendingFallback.toEntryId : undefined;\n const startIndex = pendingEntryId ? route?.findIndex(entry => entry.id === pendingEntryId) : 0;\n const activeRoute = route && startIndex !== undefined && startIndex >= 0 ? route.slice(startIndex) : undefined;\n if (!activeRoute || activeRoute.length < 2 || activeRoute[0]?.modelId !== modelId) return primary;\n\n const firstId =\n typeof activeRoute[0]?.id === 'string' && activeRoute[0].id.length > 0 ? activeRoute[0].id : undefined;\n if (!firstId) return primary;\n\n const entries: ModelWithRetries[] = [{ id: firstId, model: primary }];\n const appearances = new Map<string, number>([[firstId, 1]]);\n for (const routeEntry of activeRoute.slice(1)) {\n if (\n typeof routeEntry.id !== 'string' ||\n routeEntry.id.length === 0 ||\n typeof routeEntry.modelId !== 'string' ||\n routeEntry.modelId.length === 0\n ) {\n break;\n }\n let entryModel: ResolvedModel;\n try {\n entryModel = resolveModel(routeEntry.modelId, resolveOptions);\n } catch {\n break;\n }\n const occurrence = (appearances.get(routeEntry.id) ?? 0) + 1;\n appearances.set(routeEntry.id, occurrence);\n entries.push({\n id: occurrence === 1 ? routeEntry.id : `${routeEntry.id}#${occurrence}`,\n model: identifyModel(routeEntry.modelId, entryModel),\n });\n }\n\n return entries.length < 2 ? primary : entries;\n}\n\nfunction identifyModel(modelId: string, model: ResolvedModel): IdentifiedModelConfig {\n return { model, id: toMemoryModelId(modelId) };\n}\n\ntype MemoryRouteState = {\n modelRoute?: { entries?: Array<{ id?: unknown; memoryModelId?: unknown }> };\n mastracodePendingModelFallback?: { toEntryId?: unknown; threadId?: unknown } | null;\n};\n\n/**\n * The active model route for memory: the session route, starting at a pending\n * fallback hop captured for this thread.\n */\nexport function getActiveMemoryRoute<TEntry extends { id?: unknown; memoryModelId?: unknown }>(\n state:\n | {\n modelRoute?: { entries?: TEntry[] };\n mastracodePendingModelFallback?: MemoryRouteState['mastracodePendingModelFallback'];\n }\n | undefined,\n threadId?: string | null,\n): TEntry[] {\n const pending = state?.mastracodePendingModelFallback;\n const sameThreadPending =\n pending && (pending.threadId === undefined || pending.threadId === threadId) ? pending : undefined;\n const routeEntries = state?.modelRoute?.entries?.slice(0, MODEL_ROUTE_MAX_ENTRIES) ?? [];\n const pendingIndex = sameThreadPending\n ? routeEntries.findIndex(entry => entry.id === sameThreadPending.toEntryId)\n : -1;\n return pendingIndex >= 0 ? routeEntries.slice(pendingIndex) : routeEntries;\n}\n\n/**\n * The memory model the active route applies to both OM roles: `'auto'`, the\n * first concrete memory model, or `undefined` when the route sets none (both\n * roles then follow their `/om` settings).\n */\nexport function getActiveRouteMemoryModelId(\n state: Readonly<Record<string, unknown>> | undefined,\n threadId?: string | null,\n): string | undefined {\n const route = getActiveMemoryRoute(state as MemoryRouteState | undefined, threadId);\n if (route[0]?.memoryModelId === 'auto') return 'auto';\n const entry = route.find(\n candidate =>\n typeof candidate.memoryModelId === 'string' && candidate.memoryModelId && candidate.memoryModelId !== 'auto',\n );\n return entry?.memoryModelId as string | undefined;\n}\n\n/**\n * Goal judge model resolver for the agent's `goal.judge` config. Resolves the\n * configured goal judge model through mastracode's gateway so provider\n * credentials (stored in auth storage, not just env) are injected — a bare model\n * id handed to core's default model router would fail to find the API key.\n *\n * Returns `undefined` when no judge model is configured, which keeps the goal\n * step a complete no-op (the goal mechanism requires a judge to do anything).\n *\n * `settingsPath` must be the same source `createMastraCode()` reads from so the\n * judge model and the goal budget (`goalMaxTurns`) come from one config — with a\n * custom `settingsPath` a bare `loadSettings()` here could read a different file\n * and silently turn the goal step into a no-op.\n */\nexport function getGoalJudgeModel(\n { requestContext }: { requestContext: RequestContext },\n settingsPath?: string,\n): ResolvedModel | undefined {\n const judgeModelId = loadSettings(settingsPath).models.goalJudgeModel;\n if (!judgeModelId) return undefined;\n return resolveModel(judgeModelId, { remapForCodexOAuth: true, requestContext });\n}\n"],"mappings":";;;;;;;;;;;;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;CACrG;CAEA,OAAO,OAAO,KAAK,OAAO,CAAC,CAAC,SAAS,IAAI,UAAU,KAAA;AACrD;AAEA,SAAS,kBAAkB,SAA6B;CACtD,MAAM,EAAE,MAAM,OAAO,IAAI,KAAK,OAAO,QAAQ,SAAS,UAAU,QAAQ,SAAS,GAAG,eAAe;CACnG,OAAO;EAAE,MAAM;EAAkB,GAAG;CAAW;AACjD;AAEA,SAAgB,mCACd,MACA,gBACiB;CACjB,MAAM,cAAc,eAAuB,2BAA2B,gBAAgB,UAAU;CAChG,MAAM,mBAAmB,eAAuB;EAC9C,MAAM,oBAAoB,WAAW,UAAU;EAC/C,OAAO,oBACH,KAAK,eAAe,UAAU,CAAC,CAAC,MAAK,YAAW,QAAQ,OAAO,iBAAiB,IAChF,KAAA;CACN;CAIA,MAAM,aAAa,eAAuB,iCAAiC,gBAAgB,UAAU;CAErG,OAAO;EACL,0BAA0B,KAAK;EAC/B,cAAc,KAAK,OAAO;EAC1B,MAAK,eAAc;GACjB,IAAI,UAAU,UAAU,GAAG,OAAO,KAAA;GAKlC,IAD0B,WAAW,UACjB,MAAM,KAAA,GAAW,OAAO,KAAK,IAAI,UAAU;GAC/D,MAAM,WAAW,gBAAgB,UAAU;GAC3C,OAAO,WAAW,kBAAkB,QAAQ,IAAI,KAAA;EAClD;EACA,kBAAiB,eAAc;GAC7B,IAAI,UAAU,UAAU,GAAG,OAAO,KAAA;GAMlC,IAAI,WAAW,UAAU,M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;;;AAOA,SAAgB,4BACd,OACA,UACoB;CACpB,MAAM,QAAQ,qBAAqB,OAAuC,QAAQ;CAClF,IAAI,MAAM,EAAE,EAAE,kBAAkB,QAAQ,OAAO;CAK/C,OAJc,MAAM,MAClB,cACE,OAAO,UAAU,kBAAkB,YAAY,UAAU,iBAAiB,UAAU,kBAAkB,MAE/F,CAAC,EAAE;AAChB;;;;;;;;;;;;;;;AAgBA,SAAgB,kBACd,EAAE,kBACF,cAC2B;CAC3B,MAAM,eAAe,aAAa,YAAY,CAAC,CAAC,OAAO;CACvD,IAAI,CAAC,cAAc,OAAO,KAAA;CAC1B,OAAO,aAAa,cAAc;EAAE,oBAAoB;EAAM;CAAe,CAAC;AAChF"}
package/dist/index.d.ts CHANGED
@@ -2,6 +2,7 @@ import type { Agent } from '@mastra/core/agent';
2
2
  import { AgentController } from '@mastra/core/agent-controller';
3
3
  import type { IntervalHandler, AgentControllerConfig, AgentControllerMode, AgentControllerSubagent, Session } from '@mastra/core/agent-controller';
4
4
  import type { PubSub } from '@mastra/core/events';
5
+ import { Knowledge } from '@mastra/core/knowledge';
5
6
  import { Mastra } from '@mastra/core/mastra';
6
7
  import type { InputProcessor } from '@mastra/core/processors';
7
8
  import { RequestContext } from '@mastra/core/request-context';
@@ -38,10 +39,13 @@ export interface MastraCodeConfig {
38
39
  /** Observe completed tool calls without replacing or modifying the built-in tool implementation. */
39
40
  postToolObserver?: PostToolObserver;
40
41
  /**
41
- * Stateless input processor instances prepended before Mastra Code's mandatory processors.
42
+ * Stateless input processor instances prepended before Mastra Code's mandatory processors,
43
+ * or a per-request resolver for processors that depend on trusted request context.
42
44
  * Embedders may extend processing but cannot replace built-in safety and compatibility policy.
43
45
  */
44
- inputProcessors?: InputProcessor[];
46
+ inputProcessors?: InputProcessor[] | ((args: {
47
+ requestContext: RequestContext;
48
+ }) => InputProcessor[] | Promise<InputProcessor[]>);
45
49
  /** Tools removed from the dynamic tool set before exposure to the model */
46
50
  disabledTools?: string[];
47
51
  /**
@@ -54,6 +58,11 @@ export interface MastraCodeConfig {
54
58
  storageBackend?: 'libsql' | 'pg';
55
59
  /** Pre-built vector store instance for recall search. Skips the default vector store creation. */
56
60
  vector?: MastraVector;
61
+ /** Host-owned Knowledge instance and the key used to register it on the mounted Mastra runtime. */
62
+ knowledge?: {
63
+ key: string;
64
+ instance: Knowledge;
65
+ };
57
66
  /** Observational memory scope. Default: auto-detected from env/config files, falls back to 'thread' */
58
67
  omScope?: 'thread' | 'resource';
59
68
  /** Path to a custom settings.json file. Default: global settings */
@@ -168,11 +177,13 @@ export declare function createMastraCodeAgentController(config?: MastraCodeConfi
168
177
  controller: AgentController<MastraCodeState>;
169
178
  storage: MastraCompositeStore;
170
179
  storageMaintenance: StorageMaintenance;
171
- createKnowledgeInspector: (session: Session<MastraCodeState>) => Promise<import("./knowledge-inspector.js").KnowledgeInspector | undefined>;
180
+ createKnowledgeInspector: (session: Session<MastraCodeState>, knowledgeKey?: string) => Promise<import("./knowledge-inspector.js").KnowledgeInspector | undefined>;
172
181
  observability: Observability;
173
182
  memory: import("@mastra/core/types").DynamicArgument<import("@mastra/core/memory").MastraMemory> | (({ requestContext }: {
174
183
  requestContext: RequestContext;
175
184
  }) => import("@mastra/memory").Memory) | undefined;
185
+ knowledge: Knowledge | undefined;
186
+ knowledgeKey: string;
176
187
  mcpManager: import("./mcp/manager.js").McpManager | undefined;
177
188
  hookManager: HookManager | undefined;
178
189
  pluginManager: PluginManager | undefined;
@@ -273,11 +284,13 @@ export declare function bootLocalAgentController(config?: MastraCodeConfig): Pro
273
284
  controller: AgentController<MastraCodeState>;
274
285
  storage: MastraCompositeStore;
275
286
  storageMaintenance: StorageMaintenance;
276
- createKnowledgeInspector: (session: Session<MastraCodeState>) => Promise<import("./knowledge-inspector.js").KnowledgeInspector | undefined>;
287
+ createKnowledgeInspector: (session: Session<MastraCodeState>, knowledgeKey?: string) => Promise<import("./knowledge-inspector.js").KnowledgeInspector | undefined>;
277
288
  observability: Observability;
278
289
  memory: import("@mastra/core/types").DynamicArgument<import("@mastra/core/memory").MastraMemory> | (({ requestContext }: {
279
290
  requestContext: RequestContext;
280
291
  }) => import("@mastra/memory").Memory) | undefined;
292
+ knowledge: Knowledge | undefined;
293
+ knowledgeKey: string;
281
294
  mcpManager: import("./mcp/manager.js").McpManager | undefined;
282
295
  hookManager: HookManager | undefined;
283
296
  pluginManager: PluginManager | undefined;