@mastra/code-sdk 1.7.2 → 1.8.0-alpha.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/acp/event-mapper.d.ts +1 -0
- package/dist/acp/event-mapper.d.ts.map +1 -1
- package/dist/acp/event-mapper.js +13 -15
- package/dist/acp/event-mapper.js.map +1 -1
- package/dist/agent-connections/tools.d.ts.map +1 -1
- package/dist/agent-connections/tools.js +26 -8
- package/dist/agent-connections/tools.js.map +1 -1
- package/dist/agents/background-completion-events.d.ts +16 -0
- package/dist/agents/background-completion-events.d.ts.map +1 -0
- package/dist/agents/background-completion-events.js +19 -0
- package/dist/agents/background-completion-events.js.map +1 -0
- package/dist/agents/background-completion.d.ts +9 -0
- package/dist/agents/background-completion.d.ts.map +1 -0
- package/dist/agents/background-completion.js +59 -0
- package/dist/agents/background-completion.js.map +1 -0
- package/dist/agents/mastracode-gateway.d.ts +2 -0
- package/dist/agents/mastracode-gateway.d.ts.map +1 -1
- package/dist/agents/mastracode-gateway.js +29 -10
- package/dist/agents/mastracode-gateway.js.map +1 -1
- package/dist/agents/memory.d.ts +1 -1
- package/dist/agents/memory.d.ts.map +1 -1
- package/dist/agents/memory.js +32 -25
- package/dist/agents/memory.js.map +1 -1
- package/dist/agents/model.d.ts +41 -1
- package/dist/agents/model.d.ts.map +1 -1
- package/dist/agents/model.js +141 -7
- package/dist/agents/model.js.map +1 -1
- package/dist/agents/tool-availability.d.ts +2 -0
- package/dist/agents/tool-availability.d.ts.map +1 -1
- package/dist/agents/tool-availability.js +33 -4
- package/dist/agents/tool-availability.js.map +1 -1
- package/dist/agents/tools.d.ts +1 -1
- package/dist/agents/tools.d.ts.map +1 -1
- package/dist/agents/tools.js +30 -2
- package/dist/agents/tools.js.map +1 -1
- package/dist/agents/workspace.d.ts +2 -1
- package/dist/agents/workspace.d.ts.map +1 -1
- package/dist/agents/workspace.js +3 -3
- package/dist/agents/workspace.js.map +1 -1
- package/dist/auth/account-rotation-processor.d.ts +207 -0
- package/dist/auth/account-rotation-processor.d.ts.map +1 -0
- package/dist/auth/account-rotation-processor.js +669 -0
- package/dist/auth/account-rotation-processor.js.map +1 -0
- package/dist/auth/account-routing-context.d.ts +13 -0
- package/dist/auth/account-routing-context.d.ts.map +1 -0
- package/dist/auth/account-routing-context.js +41 -0
- package/dist/auth/account-routing-context.js.map +1 -0
- package/dist/auth/index.d.ts +1 -0
- package/dist/auth/index.d.ts.map +1 -1
- package/dist/auth/index.js +2 -1
- package/dist/auth/providers/anthropic.d.ts.map +1 -1
- package/dist/auth/providers/anthropic.js +2 -8
- package/dist/auth/providers/anthropic.js.map +1 -1
- package/dist/auth/providers/github-copilot.d.ts.map +1 -1
- package/dist/auth/providers/github-copilot.js +34 -12
- package/dist/auth/providers/github-copilot.js.map +1 -1
- package/dist/auth/providers/kimi-coding.d.ts.map +1 -1
- package/dist/auth/providers/kimi-coding.js +2 -6
- package/dist/auth/providers/kimi-coding.js.map +1 -1
- package/dist/auth/providers/openai-codex.d.ts +3 -1
- package/dist/auth/providers/openai-codex.d.ts.map +1 -1
- package/dist/auth/providers/openai-codex.js +50 -24
- package/dist/auth/providers/openai-codex.js.map +1 -1
- package/dist/auth/providers/xai.d.ts +1 -1
- package/dist/auth/providers/xai.d.ts.map +1 -1
- package/dist/auth/providers/xai.js +36 -16
- package/dist/auth/providers/xai.js.map +1 -1
- package/dist/auth/storage.d.ts +130 -8
- package/dist/auth/storage.d.ts.map +1 -1
- package/dist/auth/storage.js +602 -39
- package/dist/auth/storage.js.map +1 -1
- package/dist/auth/types.d.ts +69 -2
- package/dist/auth/types.d.ts.map +1 -1
- package/dist/goal-signal.d.ts +1 -1
- package/dist/goal-signal.d.ts.map +1 -1
- package/dist/goal-signal.js +1 -1
- package/dist/goal-signal.js.map +1 -1
- package/dist/headless/format.d.ts +1 -0
- package/dist/headless/format.d.ts.map +1 -1
- package/dist/headless/format.js +13 -17
- package/dist/headless/format.js.map +1 -1
- package/dist/headless/run-mc.d.ts.map +1 -1
- package/dist/headless/run-mc.js +11 -5
- package/dist/headless/run-mc.js.map +1 -1
- package/dist/index.d.ts +4 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +155 -38
- package/dist/index.js.map +1 -1
- package/dist/mcp/config.d.ts +17 -2
- package/dist/mcp/config.d.ts.map +1 -1
- package/dist/mcp/config.js +18 -3
- package/dist/mcp/config.js.map +1 -1
- package/dist/mcp/manager.d.ts +2 -1
- package/dist/mcp/manager.d.ts.map +1 -1
- package/dist/mcp/manager.js +13 -8
- package/dist/mcp/manager.js.map +1 -1
- package/dist/mcp/types.d.ts +15 -3
- package/dist/mcp/types.d.ts.map +1 -1
- package/dist/onboarding/custom-packs.d.ts.map +1 -1
- package/dist/onboarding/custom-packs.js +3 -0
- package/dist/onboarding/custom-packs.js.map +1 -1
- package/dist/onboarding/index.js +1 -1
- package/dist/onboarding/packs.d.ts +44 -0
- package/dist/onboarding/packs.d.ts.map +1 -1
- package/dist/onboarding/packs.js +80 -2
- package/dist/onboarding/packs.js.map +1 -1
- package/dist/onboarding/settings.d.ts +33 -0
- package/dist/onboarding/settings.d.ts.map +1 -1
- package/dist/onboarding/settings.js +88 -8
- package/dist/onboarding/settings.js.map +1 -1
- package/dist/plugin.d.ts +12 -0
- package/dist/plugin.d.ts.map +1 -1
- package/dist/plugin.js.map +1 -1
- package/dist/plugins/loader.d.ts.map +1 -1
- package/dist/plugins/loader.js +2 -1
- package/dist/plugins/loader.js.map +1 -1
- package/dist/providers/claude-max.d.ts.map +1 -1
- package/dist/providers/claude-max.js +4 -5
- package/dist/providers/claude-max.js.map +1 -1
- package/dist/providers/github-copilot.d.ts +1 -1
- package/dist/providers/github-copilot.d.ts.map +1 -1
- package/dist/providers/github-copilot.js +89 -37
- package/dist/providers/github-copilot.js.map +1 -1
- package/dist/providers/kimi-coding.d.ts.map +1 -1
- package/dist/providers/kimi-coding.js +16 -2
- package/dist/providers/kimi-coding.js.map +1 -1
- package/dist/providers/openai-codex.d.ts.map +1 -1
- package/dist/providers/openai-codex.js +42 -27
- package/dist/providers/openai-codex.js.map +1 -1
- package/dist/schema.d.ts +28 -1
- package/dist/schema.d.ts.map +1 -1
- package/dist/schema.js +9 -0
- package/dist/schema.js.map +1 -1
- package/dist/tools/workflows/save-workflow.d.ts +1 -1
- package/dist/tools/workflows/save-workflow.d.ts.map +1 -1
- package/dist/workflows/register-primitives.js +2 -2
- package/dist/workflows/register-primitives.js.map +1 -1
- package/package.json +18 -18
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { getAppDataDir } from "../utils/project.js";
|
|
1
2
|
import { AuthStorage } from "../auth/storage.js";
|
|
2
3
|
import { THINKING_LEVEL_TO_REASONING_EFFORT, buildOpenAICodexOAuthFetch, createCodexMiddleware, getEffectiveThinkingLevel, openaiCodexProvider } from "../providers/openai-codex.js";
|
|
3
4
|
import { getCustomProviderId, loadSettings } from "../onboarding/settings.js";
|
|
@@ -22,9 +23,27 @@ const CODEX_OPENAI_MODEL_REMAPS = {
|
|
|
22
23
|
"gpt-5.1-mini": "gpt-5.1-codex-mini",
|
|
23
24
|
"gpt-5": "gpt-5-codex"
|
|
24
25
|
};
|
|
25
|
-
|
|
26
|
+
/**
|
|
27
|
+
* Global file-backed credential store for local (TUI) model resolution.
|
|
28
|
+
*
|
|
29
|
+
* Constructed lazily, NOT at module scope: `AuthStorage`'s default path is
|
|
30
|
+
* resolved from `MASTRA_APP_DATA_DIR` at construction, and this module is
|
|
31
|
+
* routinely imported before test harnesses / embedders point that variable at
|
|
32
|
+
* an isolated directory — an import-time construction would permanently pin
|
|
33
|
+
* the developer's real app-data dir for every credential read.
|
|
34
|
+
*/
|
|
35
|
+
let authStorageSingleton;
|
|
36
|
+
let authStorageSingletonDir;
|
|
37
|
+
function getGlobalAuthStorage() {
|
|
38
|
+
const dir = getAppDataDir();
|
|
39
|
+
if (!authStorageSingleton || authStorageSingletonDir !== dir) {
|
|
40
|
+
authStorageSingleton = new AuthStorage();
|
|
41
|
+
authStorageSingletonDir = dir;
|
|
42
|
+
}
|
|
43
|
+
return authStorageSingleton;
|
|
44
|
+
}
|
|
26
45
|
function reloadAuthStorage() {
|
|
27
|
-
|
|
46
|
+
getGlobalAuthStorage().reload();
|
|
28
47
|
}
|
|
29
48
|
function stripMastraGatewayPrefix(modelId) {
|
|
30
49
|
return modelId.startsWith("mastra/") ? modelId.substring(7) : modelId;
|
|
@@ -46,7 +65,7 @@ function remapOpenAIModelForCodexOAuth(modelId) {
|
|
|
46
65
|
* Resolve the Anthropic API key.
|
|
47
66
|
* Main slot → dedicated apikey: slot → env var.
|
|
48
67
|
*/
|
|
49
|
-
function getAnthropicApiKey(credentials =
|
|
68
|
+
function getAnthropicApiKey(credentials = getGlobalAuthStorage()) {
|
|
50
69
|
const storedCred = credentials.get("anthropic");
|
|
51
70
|
if (storedCred?.type === "api_key" && storedCred.key.trim().length > 0) return storedCred.key.trim();
|
|
52
71
|
const dedicatedKey = credentials.getStoredApiKey("anthropic")?.trim();
|
|
@@ -57,7 +76,7 @@ function getAnthropicApiKey(credentials = authStorage) {
|
|
|
57
76
|
* Resolve the OpenAI API key.
|
|
58
77
|
* Main slot → dedicated apikey: slot → env var.
|
|
59
78
|
*/
|
|
60
|
-
function getOpenAIApiKey(credentials =
|
|
79
|
+
function getOpenAIApiKey(credentials = getGlobalAuthStorage()) {
|
|
61
80
|
const storedCred = credentials.get("openai-codex");
|
|
62
81
|
if (storedCred?.type === "api_key" && storedCred.key.trim().length > 0) return storedCred.key.trim();
|
|
63
82
|
const dedicatedKey = credentials.getStoredApiKey("openai-codex")?.trim();
|
|
@@ -88,7 +107,7 @@ function openaiApiKeyProvider(modelId, apiKey, headers) {
|
|
|
88
107
|
function getAuthProviderId(providerId) {
|
|
89
108
|
return providerId === "openai" ? "openai-codex" : providerId;
|
|
90
109
|
}
|
|
91
|
-
function getProviderAuthKey(providerId, credentials =
|
|
110
|
+
function getProviderAuthKey(providerId, credentials = getGlobalAuthStorage()) {
|
|
92
111
|
const authProviderId = getAuthProviderId(providerId);
|
|
93
112
|
const storedCred = credentials.get(authProviderId);
|
|
94
113
|
if (storedCred?.type === "api_key" && storedCred.key.trim().length > 0) return storedCred.key.trim();
|
|
@@ -175,10 +194,10 @@ var MastraCodeGateway = class MastraCodeGateway extends MastraModelGateway {
|
|
|
175
194
|
this.#thinkingLevel = thinkingLevel;
|
|
176
195
|
this.#customProviders = customProviders;
|
|
177
196
|
this.#settingsPath = settingsPath;
|
|
178
|
-
this.#credentials = credentialStore ??
|
|
197
|
+
this.#credentials = credentialStore ?? getGlobalAuthStorage();
|
|
179
198
|
}
|
|
180
199
|
static getMastraGatewayApiKey() {
|
|
181
|
-
return
|
|
200
|
+
return getGlobalAuthStorage().getStoredApiKey("mastra-gateway") ?? process.env["MASTRA_GATEWAY_API_KEY"];
|
|
182
201
|
}
|
|
183
202
|
/** @deprecated Renamed to {@link MastraCodeGateway.getMastraGatewayApiKey}. */
|
|
184
203
|
static getMemoryGatewayApiKey() {
|
|
@@ -202,7 +221,7 @@ var MastraCodeGateway = class MastraCodeGateway extends MastraModelGateway {
|
|
|
202
221
|
routerId: modelId
|
|
203
222
|
}, void 0, this.#credentials));
|
|
204
223
|
}
|
|
205
|
-
static resolveProviderAuth(request, mastraGatewayApiKey, credentials =
|
|
224
|
+
static resolveProviderAuth(request, mastraGatewayApiKey, credentials = getGlobalAuthStorage()) {
|
|
206
225
|
if (request.gatewayId === "mastra" && mastraGatewayApiKey) return {
|
|
207
226
|
apiKey: mastraGatewayApiKey,
|
|
208
227
|
source: "gateway"
|
|
@@ -270,7 +289,7 @@ var MastraCodeGateway = class MastraCodeGateway extends MastraModelGateway {
|
|
|
270
289
|
models: [...KIMI_CODING_MODELS]
|
|
271
290
|
};
|
|
272
291
|
try {
|
|
273
|
-
const copilotModels = await getCopilotModelCatalog({ authStorage });
|
|
292
|
+
const copilotModels = await getCopilotModelCatalog({ authStorage: this.#credentials });
|
|
274
293
|
providers["github-copilot"] = {
|
|
275
294
|
name: "GitHub Copilot",
|
|
276
295
|
apiKeyEnvVar: "",
|
|
@@ -426,6 +445,6 @@ var MastraCodeGateway = class MastraCodeGateway extends MastraModelGateway {
|
|
|
426
445
|
}
|
|
427
446
|
};
|
|
428
447
|
//#endregion
|
|
429
|
-
export { MASTRACODE_GATEWAY_ID, MASTRA_GATEWAY_PREFIX, MastraCodeGateway, OPENAI_PREFIX, getAnthropicApiKey, getOpenAIApiKey, reloadAuthStorage, remapOpenAIModelForCodexOAuth, resolveAuth, stripMastraGatewayPrefix };
|
|
448
|
+
export { MASTRACODE_GATEWAY_ID, MASTRA_GATEWAY_PREFIX, MastraCodeGateway, OPENAI_PREFIX, getAnthropicApiKey, getGlobalAuthStorage, getOpenAIApiKey, reloadAuthStorage, remapOpenAIModelForCodexOAuth, resolveAuth, stripMastraGatewayPrefix };
|
|
430
449
|
|
|
431
450
|
//# sourceMappingURL=mastracode-gateway.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mastracode-gateway.js","names":["#mastraGateway","#mastraGatewayBaseUrl","#mastraGatewayApiKey","#routeThroughMastraGateway","#thinkingLevel","#customProviders","#settingsPath","#credentials","#getCustomProviders","#resolveAnthropicModel","#resolveOpenAIModel"],"sources":["../../src/agents/mastracode-gateway.ts"],"sourcesContent":["import { createAnthropic } from '@ai-sdk/anthropic';\nimport { createOpenAI } from '@ai-sdk/openai';\nimport { createOpenAICompatible } from '@ai-sdk/openai-compatible';\nimport type { CustomAvailableModel, CustomModelCatalogProvider } from '@mastra/core/agent-controller';\nimport {\n GATEWAY_AUTH_HEADER,\n MastraGateway,\n MastraModelGateway,\n ModelRouterLanguageModel,\n PROVIDER_REGISTRY,\n} from '@mastra/core/llm';\nimport type {\n GatewayAuthRequest,\n GatewayAuthResult,\n GatewayLanguageModel,\n MastraModelGatewayInterface,\n ProviderConfig,\n} from '@mastra/core/llm';\nimport { wrapLanguageModel } from 'ai';\nimport { AuthStorage } from '../auth/storage.js';\nimport type { CredentialStore } from '../auth/types.js';\nimport { getCustomProviderId, loadSettings, MASTRA_GATEWAY_PROVIDER } from '../onboarding/settings.js';\nimport {\n buildAnthropicOAuthFetch,\n claudeCodeMiddleware,\n createAnthropicThinkingMiddleware,\n opencodeClaudeMaxProvider,\n promptCacheMiddleware,\n} from '../providers/claude-max.js';\nimport { getCopilotModelCatalog, githubCopilotProvider } from '../providers/github-copilot.js';\nimport { KIMI_CODING_MODELS, kimiCodingProvider } from '../providers/kimi-coding.js';\nimport {\n buildOpenAICodexOAuthFetch,\n createCodexMiddleware,\n getEffectiveThinkingLevel,\n openaiCodexProvider,\n THINKING_LEVEL_TO_REASONING_EFFORT,\n} from '../providers/openai-codex.js';\nimport type { ThinkingLevel } from '../providers/openai-codex.js';\nimport { xaiProvider } from '../providers/xai.js';\nimport { resolveCustomProviders } from './custom-provider-source.js';\n\nexport const OPENAI_PREFIX = 'openai/';\nexport const MASTRA_GATEWAY_PREFIX = 'mastra/';\nexport const MASTRACODE_GATEWAY_ID = 'mastracode';\n\nconst CODEX_OPENAI_MODEL_REMAPS: Record<string, string> = {\n 'gpt-5.3': 'gpt-5.3-codex',\n 'gpt-5.2': 'gpt-5.2-codex',\n 'gpt-5.1': 'gpt-5.1-codex',\n 'gpt-5.1-mini': 'gpt-5.1-codex-mini',\n 'gpt-5': 'gpt-5-codex',\n};\n\ntype ModelRequestHeaders = Record<string, string>;\n\nexport type MastraCodeCustomProvider = { name: string; url: string; apiKey?: string; models?: string[] };\n\nexport type MastraCodeGatewayOptions = {\n mastraGatewayBaseUrl: string;\n mastraGatewayApiKey?: string;\n routeThroughMastraGateway: boolean;\n thinkingLevel?: ThinkingLevel;\n customProviders?: MastraCodeCustomProvider[];\n settingsPath?: string;\n /**\n * Per-tenant credential source for this gateway instance. Defaults to the\n * server-global file-backed `AuthStorage`; deployed web passes the calling\n * tenant's store so model calls use the caller's own credentials.\n */\n credentialStore?: CredentialStore;\n};\n\nconst authStorage = new AuthStorage();\n\nexport function reloadAuthStorage() {\n authStorage.reload();\n}\n\nexport function stripMastraGatewayPrefix(modelId: string): string {\n return modelId.startsWith(MASTRA_GATEWAY_PREFIX) ? modelId.substring(MASTRA_GATEWAY_PREFIX.length) : modelId;\n}\n\nfunction normalizeAnthropicModelId(modelId: string): string {\n return modelId.replace(/\\.(?=\\d)/g, '-');\n}\n\nexport function remapOpenAIModelForCodexOAuth(modelId: string): string {\n const normalizedModelId = stripMastraGatewayPrefix(modelId);\n\n if (!normalizedModelId.startsWith(OPENAI_PREFIX)) {\n return modelId;\n }\n\n const openaiModelId = normalizedModelId.substring(OPENAI_PREFIX.length);\n\n if (openaiModelId.includes('-codex')) {\n return modelId;\n }\n\n const codexModelId = CODEX_OPENAI_MODEL_REMAPS[openaiModelId];\n if (!codexModelId) {\n return modelId;\n }\n\n const remappedModelId = `${OPENAI_PREFIX}${codexModelId}`;\n return modelId.startsWith(MASTRA_GATEWAY_PREFIX) ? `${MASTRA_GATEWAY_PREFIX}${remappedModelId}` : remappedModelId;\n}\n\n/**\n * Resolve the Anthropic API key.\n * Main slot → dedicated apikey: slot → env var.\n */\nexport function getAnthropicApiKey(credentials: CredentialStore = authStorage): string | undefined {\n const storedCred = credentials.get('anthropic');\n if (storedCred?.type === 'api_key' && storedCred.key.trim().length > 0) {\n return storedCred.key.trim();\n }\n const dedicatedKey = credentials.getStoredApiKey('anthropic')?.trim();\n if (dedicatedKey) return dedicatedKey;\n return credentials.allowEnvironmentFallback === false\n ? undefined\n : process.env.ANTHROPIC_API_KEY?.trim() || undefined;\n}\n\n/**\n * Resolve the OpenAI API key.\n * Main slot → dedicated apikey: slot → env var.\n */\nexport function getOpenAIApiKey(credentials: CredentialStore = authStorage): string | undefined {\n const storedCred = credentials.get('openai-codex');\n if (storedCred?.type === 'api_key' && storedCred.key.trim().length > 0) {\n return storedCred.key.trim();\n }\n const dedicatedKey = credentials.getStoredApiKey('openai-codex')?.trim();\n if (dedicatedKey) return dedicatedKey;\n return credentials.allowEnvironmentFallback === false ? undefined : process.env.OPENAI_API_KEY?.trim() || undefined;\n}\n\nfunction anthropicApiKeyProvider(\n modelId: string,\n apiKey: string,\n headers?: ModelRequestHeaders,\n thinkingLevel?: ThinkingLevel,\n) {\n const anthropic = createAnthropic({ apiKey, headers });\n const thinkingMiddleware = createAnthropicThinkingMiddleware(modelId, thinkingLevel);\n return wrapLanguageModel({\n model: anthropic(modelId),\n middleware: [promptCacheMiddleware, ...(thinkingMiddleware ? [thinkingMiddleware] : [])],\n });\n}\n\nfunction openaiApiKeyProvider(modelId: string, apiKey: string, headers?: ModelRequestHeaders) {\n const openai = createOpenAI({ apiKey, baseURL: process.env.OPENAI_BASE_URL, headers });\n return wrapLanguageModel({\n model: openai.responses(modelId),\n middleware: [],\n });\n}\n\nfunction getAuthProviderId(providerId: string): string {\n return providerId === 'openai' ? 'openai-codex' : providerId;\n}\n\nfunction getProviderAuthKey(providerId: string, credentials: CredentialStore = authStorage): string | undefined {\n const authProviderId = getAuthProviderId(providerId);\n const storedCred = credentials.get(authProviderId);\n if (storedCred?.type === 'api_key' && storedCred.key.trim().length > 0) {\n return storedCred.key.trim();\n }\n const dedicatedKey = credentials.getStoredApiKey(authProviderId)?.trim();\n if (dedicatedKey) return dedicatedKey;\n if (credentials.allowEnvironmentFallback === false) return undefined;\n return authProviderId === 'kimi-for-coding' ? process.env.KIMI_API_KEY?.trim() || undefined : undefined;\n}\n\nexport function resolveAuth(request: GatewayAuthRequest, mastraGatewayApiKey?: string): GatewayAuthResult | undefined {\n return MastraCodeGateway.resolveProviderAuth(request, mastraGatewayApiKey);\n}\n\nfunction getGatewayProviderKey(gatewayId: string, providerId: string): string {\n if (gatewayId === 'models.dev') return providerId;\n return providerId === gatewayId ? gatewayId : `${gatewayId}/${providerId}`;\n}\n\nfunction parseGatewayRouterId(\n routerId: string,\n gateway: MastraModelGatewayInterface,\n): { gatewayId: string; providerId: string; modelId: string } {\n const [firstPart = '', secondPart = '', ...restParts] = routerId.split('/');\n const gatewayId = gateway.id;\n\n if (firstPart === gatewayId && secondPart) {\n return {\n gatewayId,\n providerId: secondPart,\n modelId: restParts.join('/'),\n };\n }\n\n return {\n gatewayId,\n providerId: firstPart,\n modelId: [secondPart, ...restParts].filter(Boolean).join('/'),\n };\n}\n\nfunction hasResolvedAuth(auth: GatewayAuthResult | undefined): boolean {\n if (!auth) return false;\n if (auth.apiKey || auth.bearerToken) return true;\n return auth.headers ? Object.keys(auth.headers).length > 0 : false;\n}\n\nasync function resolveGatewayProviderAuth(\n gateway: MastraModelGatewayInterface,\n routerId: string,\n): Promise<GatewayAuthResult | undefined> {\n if (!gateway.resolveAuth) return undefined;\n\n const parsed = parseGatewayRouterId(routerId, gateway);\n try {\n const result = await gateway.resolveAuth({\n gatewayId: parsed.gatewayId,\n providerId: parsed.providerId,\n modelId: parsed.modelId,\n routerId,\n });\n return hasResolvedAuth(result) ? result : undefined;\n } catch {\n return undefined;\n }\n}\n\nasync function getMastraCodeProviderConfigs(\n gateway: MastraModelGatewayInterface,\n): Promise<Record<string, ProviderConfig>> {\n const providers: Record<string, ProviderConfig> = { ...(PROVIDER_REGISTRY as Record<string, ProviderConfig>) };\n\n try {\n const gatewayProviders = await gateway.fetchProviders();\n for (const [providerId, config] of Object.entries(gatewayProviders)) {\n providers[getGatewayProviderKey(gateway.id, providerId)] = {\n ...config,\n gateway: gateway.id,\n };\n }\n } catch (error) {\n console.warn(`Failed to load providers from gateway ${gateway.id}:`, error);\n }\n\n return providers;\n}\n\nfunction getApiKeyEnvVar(providerConfig: Pick<ProviderConfig, 'apiKeyEnvVar'> | undefined): string | undefined {\n const envVars = providerConfig?.apiKeyEnvVar;\n return Array.isArray(envVars) ? envVars[0] : envVars;\n}\n\nexport class MastraCodeGateway extends MastraModelGateway {\n readonly id = MASTRACODE_GATEWAY_ID;\n readonly name = 'MastraCode Gateway';\n\n readonly #mastraGateway: MastraGateway;\n readonly #mastraGatewayBaseUrl: string;\n readonly #mastraGatewayApiKey?: string;\n readonly #routeThroughMastraGateway: boolean;\n readonly #thinkingLevel?: ThinkingLevel;\n readonly #customProviders?: MastraCodeCustomProvider[];\n readonly #settingsPath?: string;\n readonly #credentials: CredentialStore;\n\n constructor({\n mastraGatewayBaseUrl,\n mastraGatewayApiKey,\n routeThroughMastraGateway,\n thinkingLevel,\n customProviders,\n settingsPath,\n credentialStore,\n }: MastraCodeGatewayOptions) {\n super();\n this.#mastraGateway = new MastraGateway({ baseUrl: mastraGatewayBaseUrl });\n this.#mastraGatewayBaseUrl = mastraGatewayBaseUrl;\n this.#mastraGatewayApiKey = mastraGatewayApiKey;\n this.#routeThroughMastraGateway = routeThroughMastraGateway;\n this.#thinkingLevel = thinkingLevel;\n this.#customProviders = customProviders;\n this.#settingsPath = settingsPath;\n this.#credentials = credentialStore ?? authStorage;\n }\n\n static getMastraGatewayApiKey(): string | undefined {\n return authStorage.getStoredApiKey(MASTRA_GATEWAY_PROVIDER) ?? process.env['MASTRA_GATEWAY_API_KEY'];\n }\n\n /** @deprecated Renamed to {@link MastraCodeGateway.getMastraGatewayApiKey}. */\n static getMemoryGatewayApiKey(): string | undefined {\n return MastraCodeGateway.getMastraGatewayApiKey();\n }\n\n /**\n * Claim an unprefixed model id (e.g. a bare `anthropic/...`) when this gateway\n * can authenticate it via OAuth or a stored/env credential. This lets the\n * shared gateway router select MastraCode for auth resolution, so the status\n * bar and `/api-keys` reflect OAuth logins instead of only checking env vars.\n */\n handlesModel(modelId: string): boolean {\n const parsed = parseGatewayRouterId(modelId, this);\n if (!parsed.providerId || !parsed.modelId) return false;\n if (this.#routeThroughMastraGateway && this.#mastraGatewayApiKey) return true;\n const customProvider = this.#getCustomProviders().find(\n provider => parsed.providerId === getCustomProviderId(provider.name),\n );\n if (customProvider?.apiKey) return true;\n return hasResolvedAuth(\n MastraCodeGateway.resolveProviderAuth(\n {\n gatewayId: this.id,\n providerId: parsed.providerId,\n modelId: parsed.modelId,\n routerId: modelId,\n },\n undefined,\n this.#credentials,\n ),\n );\n }\n\n static resolveProviderAuth(\n request: GatewayAuthRequest,\n mastraGatewayApiKey?: string,\n credentials: CredentialStore = authStorage,\n ): GatewayAuthResult | undefined {\n if (request.gatewayId === 'mastra' && mastraGatewayApiKey) {\n return { apiKey: mastraGatewayApiKey, source: 'gateway' };\n }\n\n const authProviderId = getAuthProviderId(request.providerId);\n const storedCred = credentials.get(authProviderId);\n if (storedCred?.type === 'oauth') {\n return { bearerToken: 'oauth', source: 'gateway' };\n }\n\n const apiKey = getProviderAuthKey(request.providerId, credentials);\n return apiKey ? { apiKey, source: 'gateway' } : undefined;\n }\n\n static createModelCatalogProvider(gateway: MastraModelGatewayInterface): CustomModelCatalogProvider {\n return async () => {\n const registry = await getMastraCodeProviderConfigs(gateway);\n const models: CustomAvailableModel[] = [];\n\n for (const [provider, providerConfig] of Object.entries(registry)) {\n const apiKeyEnvVar = getApiKeyEnvVar(providerConfig);\n const hasEnvKey = apiKeyEnvVar ? Boolean(process.env[apiKeyEnvVar]) : false;\n const modelNames = providerConfig.models;\n if (!Array.isArray(modelNames)) continue;\n\n const gatewayAuth = modelNames[0]\n ? await resolveGatewayProviderAuth(gateway, `${provider}/${modelNames[0]}`)\n : undefined;\n\n for (const modelName of modelNames) {\n const id = `${provider}/${modelName}`;\n models.push({\n id,\n provider,\n modelName,\n hasApiKey: hasEnvKey || Boolean(gatewayAuth),\n apiKeyEnvVar: apiKeyEnvVar || undefined,\n });\n }\n }\n\n return models;\n };\n }\n\n createModelCatalogProvider(): CustomModelCatalogProvider {\n return MastraCodeGateway.createModelCatalogProvider(this);\n }\n\n #getCustomProviders(): MastraCodeCustomProvider[] {\n // Explicit constructor list wins; then a registered source (deployed web,\n // DB-backed — authoritative, so settings.json is never consulted); then\n // the local file-backed settings.\n return this.#customProviders ?? resolveCustomProviders() ?? loadSettings(this.#settingsPath).customProviders;\n }\n\n async fetchProviders(): Promise<Record<string, ProviderConfig>> {\n const providers: Record<string, ProviderConfig> = {};\n for (const provider of this.#getCustomProviders()) {\n const models = provider.models ?? [];\n if (!models.length) continue;\n providers[getCustomProviderId(provider.name)] = {\n name: provider.name,\n url: provider.url,\n apiKeyEnvVar: '',\n apiKeyHeader: 'Authorization',\n gateway: this.id,\n models,\n };\n }\n\n providers['kimi-for-coding'] = {\n name: 'Kimi For Coding',\n apiKeyEnvVar: 'KIMI_API_KEY',\n apiKeyHeader: 'Authorization',\n gateway: this.id,\n models: [...KIMI_CODING_MODELS],\n };\n\n try {\n const copilotModels = await getCopilotModelCatalog({ authStorage });\n providers['github-copilot'] = {\n name: 'GitHub Copilot',\n apiKeyEnvVar: '',\n apiKeyHeader: 'Authorization',\n gateway: this.id,\n models: copilotModels.map(model => model.id),\n };\n } catch (error) {\n console.warn('Failed to load GitHub Copilot model catalog:', error);\n }\n\n return providers;\n }\n\n buildUrl(modelId: string): string | undefined | Promise<string | undefined> {\n return this.#routeThroughMastraGateway ? this.#mastraGateway.buildUrl(modelId) : modelId;\n }\n\n async getApiKey(modelId: string): Promise<string> {\n const providerId = stripMastraGatewayPrefix(modelId).split('/', 1)[0];\n if (this.#routeThroughMastraGateway) return this.#mastraGatewayApiKey ?? '';\n return providerId ? (getProviderAuthKey(providerId, this.#credentials) ?? '') : '';\n }\n\n resolveAuth(request: GatewayAuthRequest): GatewayAuthResult | undefined {\n if (this.#routeThroughMastraGateway && this.#mastraGatewayApiKey) {\n return { apiKey: this.#mastraGatewayApiKey, source: 'gateway' };\n }\n\n const customProvider = this.#getCustomProviders().find(\n provider => request.providerId === getCustomProviderId(provider.name),\n );\n if (customProvider?.apiKey) {\n return { apiKey: customProvider.apiKey, source: 'gateway' };\n }\n\n return MastraCodeGateway.resolveProviderAuth(request, undefined, this.#credentials);\n }\n\n resolveLanguageModel(args: {\n modelId: string;\n providerId: string;\n apiKey: string;\n headers?: Record<string, string>;\n transport?: any;\n responsesWebSocket?: any;\n }): GatewayLanguageModel {\n const customProvider = this.#getCustomProviders().find(\n provider => args.providerId === getCustomProviderId(provider.name),\n );\n if (customProvider) {\n const provider = createOpenAICompatible({\n name: args.providerId,\n baseURL: customProvider.url,\n apiKey: args.apiKey,\n headers: args.headers,\n });\n return provider.chatModel(args.modelId) as unknown as GatewayLanguageModel;\n }\n\n if (args.providerId === 'github-copilot') {\n return githubCopilotProvider(args.modelId, {\n headers: args.headers,\n authStorage: this.#credentials,\n }) as unknown as GatewayLanguageModel;\n }\n\n if (args.providerId === 'moonshotai') {\n // Prefer the gateway-resolved key (stored credentials), then the canonical\n // registry env var. Keep the legacy typo name as a fallback for anyone who\n // set it because of the previous error message.\n const apiKey =\n args.apiKey?.trim() || process.env.MOONSHOT_API_KEY?.trim() || process.env.MOONSHOT_AI_API_KEY?.trim();\n if (!apiKey) {\n throw new Error('Need MOONSHOT_API_KEY');\n }\n return createAnthropic({\n apiKey,\n baseURL: 'https://api.moonshot.ai/anthropic/v1',\n name: 'moonshotai.anthropicv1',\n headers: args.headers,\n })(args.modelId) as unknown as GatewayLanguageModel;\n }\n\n if (args.providerId === 'anthropic') {\n return this.#resolveAnthropicModel(args);\n }\n\n if (args.providerId === 'openai') {\n const openaiModel = this.#resolveOpenAIModel(args);\n if (openaiModel) return openaiModel;\n }\n\n if (args.providerId === 'xai' && this.#credentials.get('xai')?.type === 'oauth') {\n return xaiProvider(args.modelId, {\n headers: args.headers,\n authStorage: this.#credentials,\n }) as unknown as GatewayLanguageModel;\n }\n\n if (this.#routeThroughMastraGateway) {\n return this.#mastraGateway.resolveLanguageModel(args) as GatewayLanguageModel;\n }\n\n if (args.providerId === 'kimi-for-coding') {\n return kimiCodingProvider(args.modelId, {\n apiKey: args.apiKey,\n headers: args.headers,\n credentialStore: this.#credentials,\n }) as unknown as GatewayLanguageModel;\n }\n\n return new ModelRouterLanguageModel({\n id: `${args.providerId}/${args.modelId}` as `${string}/${string}`,\n apiKey: args.apiKey,\n headers: args.headers,\n }) as unknown as GatewayLanguageModel;\n }\n\n #resolveAnthropicModel(args: {\n modelId: string;\n providerId: string;\n apiKey: string;\n headers?: Record<string, string>;\n transport?: any;\n responsesWebSocket?: any;\n }): GatewayLanguageModel {\n const bareModelId = normalizeAnthropicModelId(args.modelId);\n const storedCred = this.#credentials.get('anthropic');\n const thinkingMiddleware = createAnthropicThinkingMiddleware(bareModelId, this.#thinkingLevel);\n\n if (this.#routeThroughMastraGateway) {\n if (storedCred?.type === 'oauth') {\n const anthropic = createAnthropic({\n apiKey: 'oauth-gateway-placeholder',\n baseURL: `${this.#mastraGatewayBaseUrl}/v1`,\n headers: {\n [GATEWAY_AUTH_HEADER]: `Bearer ${args.apiKey}`,\n ...args.headers,\n },\n fetch: buildAnthropicOAuthFetch({ authStorage: this.#credentials }) as any,\n });\n\n return wrapLanguageModel({\n model: anthropic(bareModelId),\n middleware: [\n claudeCodeMiddleware,\n promptCacheMiddleware,\n ...(thinkingMiddleware ? [thinkingMiddleware] : []),\n ],\n }) as unknown as GatewayLanguageModel;\n }\n\n const gatewayModel = this.#mastraGateway.resolveLanguageModel({\n ...args,\n modelId: bareModelId,\n }) as GatewayLanguageModel;\n if (!thinkingMiddleware) return gatewayModel;\n return wrapLanguageModel({\n model: gatewayModel as any,\n middleware: [thinkingMiddleware],\n }) as unknown as GatewayLanguageModel;\n }\n\n if (storedCred?.type === 'oauth') {\n return opencodeClaudeMaxProvider(bareModelId, {\n headers: args.headers,\n authStorage: this.#credentials,\n thinkingLevel: this.#thinkingLevel,\n }) as unknown as GatewayLanguageModel;\n }\n\n if (storedCred?.type === 'api_key' && storedCred.key.trim().length > 0) {\n return anthropicApiKeyProvider(\n bareModelId,\n storedCred.key.trim(),\n args.headers,\n this.#thinkingLevel,\n ) as unknown as GatewayLanguageModel;\n }\n\n const apiKey = getAnthropicApiKey(this.#credentials);\n if (apiKey) {\n return anthropicApiKeyProvider(\n bareModelId,\n apiKey,\n args.headers,\n this.#thinkingLevel,\n ) as unknown as GatewayLanguageModel;\n }\n\n // No stored credentials: use the OAuth-backed provider so the first request can trigger login.\n return opencodeClaudeMaxProvider(bareModelId, {\n headers: args.headers,\n authStorage: this.#credentials,\n thinkingLevel: this.#thinkingLevel,\n }) as unknown as GatewayLanguageModel;\n }\n\n #resolveOpenAIModel(args: {\n modelId: string;\n providerId: string;\n apiKey: string;\n headers?: Record<string, string>;\n transport?: any;\n responsesWebSocket?: any;\n }): GatewayLanguageModel | undefined {\n const storedCred = this.#credentials.get('openai-codex');\n\n if (this.#routeThroughMastraGateway) {\n if (storedCred?.type === 'oauth') {\n const resolvedModelId = remapOpenAIModelForCodexOAuth(`openai/${args.modelId}`);\n const resolvedBareModelId = resolvedModelId.substring(OPENAI_PREFIX.length);\n const requestedLevel: ThinkingLevel = this.#thinkingLevel ?? 'medium';\n const effectiveLevel = getEffectiveThinkingLevel(resolvedBareModelId, requestedLevel);\n const reasoningEffort = THINKING_LEVEL_TO_REASONING_EFFORT[effectiveLevel];\n const middleware = createCodexMiddleware(reasoningEffort);\n const openai = createOpenAI({\n apiKey: 'oauth-gateway-placeholder',\n baseURL: `${this.#mastraGatewayBaseUrl}/v1`,\n headers: {\n [GATEWAY_AUTH_HEADER]: `Bearer ${args.apiKey}`,\n ...args.headers,\n },\n fetch: buildOpenAICodexOAuthFetch({ authStorage: this.#credentials, rewriteUrl: false }) as any,\n });\n\n return wrapLanguageModel({\n model: openai.responses(resolvedBareModelId),\n middleware: [middleware],\n }) as unknown as GatewayLanguageModel;\n }\n\n return this.#mastraGateway.resolveLanguageModel(args) as GatewayLanguageModel;\n }\n\n if (storedCred?.type === 'oauth') {\n const resolvedModelId = remapOpenAIModelForCodexOAuth(`openai/${args.modelId}`);\n return openaiCodexProvider(resolvedModelId.substring(OPENAI_PREFIX.length), {\n thinkingLevel: this.#thinkingLevel,\n headers: args.headers,\n authStorage: this.#credentials,\n }) as unknown as GatewayLanguageModel;\n }\n\n const apiKey = getOpenAIApiKey(this.#credentials);\n if (apiKey) {\n return openaiApiKeyProvider(args.modelId, apiKey, args.headers) as unknown as GatewayLanguageModel;\n }\n\n return undefined;\n }\n}\n"],"mappings":";;;;;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vD,IAAI,KAAKJ,4BAA4B;GACnC,IAAI,YAAY,SAAS,SAAS;IAEhC,MAAM,sBADkB,8BAA8B,UAAU,KAAK,SAC3B,CAAC,CAAC,UAAU,CAAoB;IAG1E,MAAM,kBAAkB,mCADD,0BAA0B,qBADX,KAAKC,kBAAkB,QAEW;IACxE,MAAM,aAAa,sBAAsB,eAAe;IAWxD,OAAO,kBAAkB;KACvB,OAXa,aAAa;MAC1B,QAAQ;MACR,SAAS,GAAG,KAAKH,sBAAsB;MACvC,SAAS;QACN,sBAAsB,UAAU,KAAK;OACtC,GAAG,KAAK;MACV;MACA,OAAO,2BAA2B;OAAE,aAAa,KAAKM;OAAc,YAAY;MAAM,CAAC;KACzF,CAGc,CAAC,CAAC,UAAU,mBAAmB;KAC3C,YAAY,CAAC,UAAU;IACzB,CAAC;GACH;GAEA,OAAO,KAAKP,eAAe,qBAAqB,IAAI;EACtD;EAEA,IAAI,YAAY,SAAS,SAEvB,OAAO,oBADiB,8BAA8B,UAAU,KAAK,SAC5B,CAAC,CAAC,UAAU,CAAoB,GAAG;GAC1E,eAAe,KAAKI;GACpB,SAAS,KAAK;GACd,aAAa,KAAKG;EACpB,CAAC;EAGH,MAAM,SAAS,gBAAgB,KAAKA,YAAY;EAChD,IAAI,QACF,OAAO,qBAAqB,KAAK,SAAS,QAAQ,KAAK,OAAO;CAIlE;AACF"}
|
|
1
|
+
{"version":3,"file":"mastracode-gateway.js","names":["#mastraGateway","#mastraGatewayBaseUrl","#mastraGatewayApiKey","#routeThroughMastraGateway","#thinkingLevel","#customProviders","#settingsPath","#credentials","#getCustomProviders","#resolveAnthropicModel","#resolveOpenAIModel"],"sources":["../../src/agents/mastracode-gateway.ts"],"sourcesContent":["import { createAnthropic } from '@ai-sdk/anthropic';\nimport { createOpenAI } from '@ai-sdk/openai';\nimport { createOpenAICompatible } from '@ai-sdk/openai-compatible';\nimport type { CustomAvailableModel, CustomModelCatalogProvider } from '@mastra/core/agent-controller';\nimport {\n GATEWAY_AUTH_HEADER,\n MastraGateway,\n MastraModelGateway,\n ModelRouterLanguageModel,\n PROVIDER_REGISTRY,\n} from '@mastra/core/llm';\nimport type {\n GatewayAuthRequest,\n GatewayAuthResult,\n GatewayLanguageModel,\n MastraModelGatewayInterface,\n ProviderConfig,\n} from '@mastra/core/llm';\nimport { wrapLanguageModel } from 'ai';\nimport { AuthStorage } from '../auth/storage.js';\nimport type { CredentialStore } from '../auth/types.js';\nimport { getCustomProviderId, loadSettings, MASTRA_GATEWAY_PROVIDER } from '../onboarding/settings.js';\nimport {\n buildAnthropicOAuthFetch,\n claudeCodeMiddleware,\n createAnthropicThinkingMiddleware,\n opencodeClaudeMaxProvider,\n promptCacheMiddleware,\n} from '../providers/claude-max.js';\nimport { getCopilotModelCatalog, githubCopilotProvider } from '../providers/github-copilot.js';\nimport { KIMI_CODING_MODELS, kimiCodingProvider } from '../providers/kimi-coding.js';\nimport {\n buildOpenAICodexOAuthFetch,\n createCodexMiddleware,\n getEffectiveThinkingLevel,\n openaiCodexProvider,\n THINKING_LEVEL_TO_REASONING_EFFORT,\n} from '../providers/openai-codex.js';\nimport type { ThinkingLevel } from '../providers/openai-codex.js';\nimport { xaiProvider } from '../providers/xai.js';\nimport { getAppDataDir } from '../utils/project.js';\nimport { resolveCustomProviders } from './custom-provider-source.js';\n\nexport const OPENAI_PREFIX = 'openai/';\nexport const MASTRA_GATEWAY_PREFIX = 'mastra/';\nexport const MASTRACODE_GATEWAY_ID = 'mastracode';\n\nconst CODEX_OPENAI_MODEL_REMAPS: Record<string, string> = {\n 'gpt-5.3': 'gpt-5.3-codex',\n 'gpt-5.2': 'gpt-5.2-codex',\n 'gpt-5.1': 'gpt-5.1-codex',\n 'gpt-5.1-mini': 'gpt-5.1-codex-mini',\n 'gpt-5': 'gpt-5-codex',\n};\n\ntype ModelRequestHeaders = Record<string, string>;\n\nexport type MastraCodeCustomProvider = { name: string; url: string; apiKey?: string; models?: string[] };\n\nexport type MastraCodeGatewayOptions = {\n mastraGatewayBaseUrl: string;\n mastraGatewayApiKey?: string;\n routeThroughMastraGateway: boolean;\n thinkingLevel?: ThinkingLevel;\n customProviders?: MastraCodeCustomProvider[];\n settingsPath?: string;\n /**\n * Per-tenant credential source for this gateway instance. Defaults to the\n * server-global file-backed `AuthStorage`; deployed web passes the calling\n * tenant's store so model calls use the caller's own credentials.\n */\n credentialStore?: CredentialStore;\n};\n\n/**\n * Global file-backed credential store for local (TUI) model resolution.\n *\n * Constructed lazily, NOT at module scope: `AuthStorage`'s default path is\n * resolved from `MASTRA_APP_DATA_DIR` at construction, and this module is\n * routinely imported before test harnesses / embedders point that variable at\n * an isolated directory — an import-time construction would permanently pin\n * the developer's real app-data dir for every credential read.\n */\nlet authStorageSingleton: AuthStorage | undefined;\nlet authStorageSingletonDir: string | undefined;\n\nexport function getGlobalAuthStorage(): AuthStorage {\n // Keyed by the resolved app-data dir: in-process harnesses re-point\n // MASTRA_APP_DATA_DIR per run inside one long-lived worker, so a store\n // pinned to a previous dir must be discarded, not reused.\n const dir = getAppDataDir();\n if (!authStorageSingleton || authStorageSingletonDir !== dir) {\n authStorageSingleton = new AuthStorage();\n authStorageSingletonDir = dir;\n }\n return authStorageSingleton;\n}\n\nexport function reloadAuthStorage() {\n getGlobalAuthStorage().reload();\n}\n\nexport function stripMastraGatewayPrefix(modelId: string): string {\n return modelId.startsWith(MASTRA_GATEWAY_PREFIX) ? modelId.substring(MASTRA_GATEWAY_PREFIX.length) : modelId;\n}\n\nfunction normalizeAnthropicModelId(modelId: string): string {\n return modelId.replace(/\\.(?=\\d)/g, '-');\n}\n\nexport function remapOpenAIModelForCodexOAuth(modelId: string): string {\n const normalizedModelId = stripMastraGatewayPrefix(modelId);\n\n if (!normalizedModelId.startsWith(OPENAI_PREFIX)) {\n return modelId;\n }\n\n const openaiModelId = normalizedModelId.substring(OPENAI_PREFIX.length);\n\n if (openaiModelId.includes('-codex')) {\n return modelId;\n }\n\n const codexModelId = CODEX_OPENAI_MODEL_REMAPS[openaiModelId];\n if (!codexModelId) {\n return modelId;\n }\n\n const remappedModelId = `${OPENAI_PREFIX}${codexModelId}`;\n return modelId.startsWith(MASTRA_GATEWAY_PREFIX) ? `${MASTRA_GATEWAY_PREFIX}${remappedModelId}` : remappedModelId;\n}\n\n/**\n * Resolve the Anthropic API key.\n * Main slot → dedicated apikey: slot → env var.\n */\nexport function getAnthropicApiKey(credentials: CredentialStore = getGlobalAuthStorage()): string | undefined {\n const storedCred = credentials.get('anthropic');\n if (storedCred?.type === 'api_key' && storedCred.key.trim().length > 0) {\n return storedCred.key.trim();\n }\n const dedicatedKey = credentials.getStoredApiKey('anthropic')?.trim();\n if (dedicatedKey) return dedicatedKey;\n return credentials.allowEnvironmentFallback === false\n ? undefined\n : process.env.ANTHROPIC_API_KEY?.trim() || undefined;\n}\n\n/**\n * Resolve the OpenAI API key.\n * Main slot → dedicated apikey: slot → env var.\n */\nexport function getOpenAIApiKey(credentials: CredentialStore = getGlobalAuthStorage()): string | undefined {\n const storedCred = credentials.get('openai-codex');\n if (storedCred?.type === 'api_key' && storedCred.key.trim().length > 0) {\n return storedCred.key.trim();\n }\n const dedicatedKey = credentials.getStoredApiKey('openai-codex')?.trim();\n if (dedicatedKey) return dedicatedKey;\n return credentials.allowEnvironmentFallback === false ? undefined : process.env.OPENAI_API_KEY?.trim() || undefined;\n}\n\nfunction anthropicApiKeyProvider(\n modelId: string,\n apiKey: string,\n headers?: ModelRequestHeaders,\n thinkingLevel?: ThinkingLevel,\n) {\n const anthropic = createAnthropic({ apiKey, headers });\n const thinkingMiddleware = createAnthropicThinkingMiddleware(modelId, thinkingLevel);\n return wrapLanguageModel({\n model: anthropic(modelId),\n middleware: [promptCacheMiddleware, ...(thinkingMiddleware ? [thinkingMiddleware] : [])],\n });\n}\n\nfunction openaiApiKeyProvider(modelId: string, apiKey: string, headers?: ModelRequestHeaders) {\n const openai = createOpenAI({ apiKey, baseURL: process.env.OPENAI_BASE_URL, headers });\n return wrapLanguageModel({\n model: openai.responses(modelId),\n middleware: [],\n });\n}\n\nfunction getAuthProviderId(providerId: string): string {\n return providerId === 'openai' ? 'openai-codex' : providerId;\n}\n\nfunction getProviderAuthKey(\n providerId: string,\n credentials: CredentialStore = getGlobalAuthStorage(),\n): string | undefined {\n const authProviderId = getAuthProviderId(providerId);\n const storedCred = credentials.get(authProviderId);\n if (storedCred?.type === 'api_key' && storedCred.key.trim().length > 0) {\n return storedCred.key.trim();\n }\n const dedicatedKey = credentials.getStoredApiKey(authProviderId)?.trim();\n if (dedicatedKey) return dedicatedKey;\n if (credentials.allowEnvironmentFallback === false) return undefined;\n return authProviderId === 'kimi-for-coding' ? process.env.KIMI_API_KEY?.trim() || undefined : undefined;\n}\n\nexport function resolveAuth(request: GatewayAuthRequest, mastraGatewayApiKey?: string): GatewayAuthResult | undefined {\n return MastraCodeGateway.resolveProviderAuth(request, mastraGatewayApiKey);\n}\n\nfunction getGatewayProviderKey(gatewayId: string, providerId: string): string {\n if (gatewayId === 'models.dev') return providerId;\n return providerId === gatewayId ? gatewayId : `${gatewayId}/${providerId}`;\n}\n\nfunction parseGatewayRouterId(\n routerId: string,\n gateway: MastraModelGatewayInterface,\n): { gatewayId: string; providerId: string; modelId: string } {\n const [firstPart = '', secondPart = '', ...restParts] = routerId.split('/');\n const gatewayId = gateway.id;\n\n if (firstPart === gatewayId && secondPart) {\n return {\n gatewayId,\n providerId: secondPart,\n modelId: restParts.join('/'),\n };\n }\n\n return {\n gatewayId,\n providerId: firstPart,\n modelId: [secondPart, ...restParts].filter(Boolean).join('/'),\n };\n}\n\nfunction hasResolvedAuth(auth: GatewayAuthResult | undefined): boolean {\n if (!auth) return false;\n if (auth.apiKey || auth.bearerToken) return true;\n return auth.headers ? Object.keys(auth.headers).length > 0 : false;\n}\n\nasync function resolveGatewayProviderAuth(\n gateway: MastraModelGatewayInterface,\n routerId: string,\n): Promise<GatewayAuthResult | undefined> {\n if (!gateway.resolveAuth) return undefined;\n\n const parsed = parseGatewayRouterId(routerId, gateway);\n try {\n const result = await gateway.resolveAuth({\n gatewayId: parsed.gatewayId,\n providerId: parsed.providerId,\n modelId: parsed.modelId,\n routerId,\n });\n return hasResolvedAuth(result) ? result : undefined;\n } catch {\n return undefined;\n }\n}\n\nasync function getMastraCodeProviderConfigs(\n gateway: MastraModelGatewayInterface,\n): Promise<Record<string, ProviderConfig>> {\n const providers: Record<string, ProviderConfig> = { ...(PROVIDER_REGISTRY as Record<string, ProviderConfig>) };\n\n try {\n const gatewayProviders = await gateway.fetchProviders();\n for (const [providerId, config] of Object.entries(gatewayProviders)) {\n providers[getGatewayProviderKey(gateway.id, providerId)] = {\n ...config,\n gateway: gateway.id,\n };\n }\n } catch (error) {\n console.warn(`Failed to load providers from gateway ${gateway.id}:`, error);\n }\n\n return providers;\n}\n\nfunction getApiKeyEnvVar(providerConfig: Pick<ProviderConfig, 'apiKeyEnvVar'> | undefined): string | undefined {\n const envVars = providerConfig?.apiKeyEnvVar;\n return Array.isArray(envVars) ? envVars[0] : envVars;\n}\n\nexport class MastraCodeGateway extends MastraModelGateway {\n readonly id = MASTRACODE_GATEWAY_ID;\n readonly name = 'MastraCode Gateway';\n\n readonly #mastraGateway: MastraGateway;\n readonly #mastraGatewayBaseUrl: string;\n readonly #mastraGatewayApiKey?: string;\n readonly #routeThroughMastraGateway: boolean;\n readonly #thinkingLevel?: ThinkingLevel;\n readonly #customProviders?: MastraCodeCustomProvider[];\n readonly #settingsPath?: string;\n readonly #credentials: CredentialStore;\n\n constructor({\n mastraGatewayBaseUrl,\n mastraGatewayApiKey,\n routeThroughMastraGateway,\n thinkingLevel,\n customProviders,\n settingsPath,\n credentialStore,\n }: MastraCodeGatewayOptions) {\n super();\n this.#mastraGateway = new MastraGateway({ baseUrl: mastraGatewayBaseUrl });\n this.#mastraGatewayBaseUrl = mastraGatewayBaseUrl;\n this.#mastraGatewayApiKey = mastraGatewayApiKey;\n this.#routeThroughMastraGateway = routeThroughMastraGateway;\n this.#thinkingLevel = thinkingLevel;\n this.#customProviders = customProviders;\n this.#settingsPath = settingsPath;\n this.#credentials = credentialStore ?? getGlobalAuthStorage();\n }\n\n static getMastraGatewayApiKey(): string | undefined {\n return getGlobalAuthStorage().getStoredApiKey(MASTRA_GATEWAY_PROVIDER) ?? process.env['MASTRA_GATEWAY_API_KEY'];\n }\n\n /** @deprecated Renamed to {@link MastraCodeGateway.getMastraGatewayApiKey}. */\n static getMemoryGatewayApiKey(): string | undefined {\n return MastraCodeGateway.getMastraGatewayApiKey();\n }\n\n /**\n * Claim an unprefixed model id (e.g. a bare `anthropic/...`) when this gateway\n * can authenticate it via OAuth or a stored/env credential. This lets the\n * shared gateway router select MastraCode for auth resolution, so the status\n * bar and `/api-keys` reflect OAuth logins instead of only checking env vars.\n */\n handlesModel(modelId: string): boolean {\n const parsed = parseGatewayRouterId(modelId, this);\n if (!parsed.providerId || !parsed.modelId) return false;\n if (this.#routeThroughMastraGateway && this.#mastraGatewayApiKey) return true;\n const customProvider = this.#getCustomProviders().find(\n provider => parsed.providerId === getCustomProviderId(provider.name),\n );\n if (customProvider?.apiKey) return true;\n return hasResolvedAuth(\n MastraCodeGateway.resolveProviderAuth(\n {\n gatewayId: this.id,\n providerId: parsed.providerId,\n modelId: parsed.modelId,\n routerId: modelId,\n },\n undefined,\n this.#credentials,\n ),\n );\n }\n\n static resolveProviderAuth(\n request: GatewayAuthRequest,\n mastraGatewayApiKey?: string,\n credentials: CredentialStore = getGlobalAuthStorage(),\n ): GatewayAuthResult | undefined {\n if (request.gatewayId === 'mastra' && mastraGatewayApiKey) {\n return { apiKey: mastraGatewayApiKey, source: 'gateway' };\n }\n\n const authProviderId = getAuthProviderId(request.providerId);\n const storedCred = credentials.get(authProviderId);\n if (storedCred?.type === 'oauth') {\n return { bearerToken: 'oauth', source: 'gateway' };\n }\n\n const apiKey = getProviderAuthKey(request.providerId, credentials);\n return apiKey ? { apiKey, source: 'gateway' } : undefined;\n }\n\n static createModelCatalogProvider(gateway: MastraModelGatewayInterface): CustomModelCatalogProvider {\n return async () => {\n const registry = await getMastraCodeProviderConfigs(gateway);\n const models: CustomAvailableModel[] = [];\n\n for (const [provider, providerConfig] of Object.entries(registry)) {\n const apiKeyEnvVar = getApiKeyEnvVar(providerConfig);\n const hasEnvKey = apiKeyEnvVar ? Boolean(process.env[apiKeyEnvVar]) : false;\n const modelNames = providerConfig.models;\n if (!Array.isArray(modelNames)) continue;\n\n const gatewayAuth = modelNames[0]\n ? await resolveGatewayProviderAuth(gateway, `${provider}/${modelNames[0]}`)\n : undefined;\n\n for (const modelName of modelNames) {\n const id = `${provider}/${modelName}`;\n models.push({\n id,\n provider,\n modelName,\n hasApiKey: hasEnvKey || Boolean(gatewayAuth),\n apiKeyEnvVar: apiKeyEnvVar || undefined,\n });\n }\n }\n\n return models;\n };\n }\n\n createModelCatalogProvider(): CustomModelCatalogProvider {\n return MastraCodeGateway.createModelCatalogProvider(this);\n }\n\n #getCustomProviders(): MastraCodeCustomProvider[] {\n // Explicit constructor list wins; then a registered source (deployed web,\n // DB-backed — authoritative, so settings.json is never consulted); then\n // the local file-backed settings.\n return this.#customProviders ?? resolveCustomProviders() ?? loadSettings(this.#settingsPath).customProviders;\n }\n\n async fetchProviders(): Promise<Record<string, ProviderConfig>> {\n const providers: Record<string, ProviderConfig> = {};\n for (const provider of this.#getCustomProviders()) {\n const models = provider.models ?? [];\n if (!models.length) continue;\n providers[getCustomProviderId(provider.name)] = {\n name: provider.name,\n url: provider.url,\n apiKeyEnvVar: '',\n apiKeyHeader: 'Authorization',\n gateway: this.id,\n models,\n };\n }\n\n providers['kimi-for-coding'] = {\n name: 'Kimi For Coding',\n apiKeyEnvVar: 'KIMI_API_KEY',\n apiKeyHeader: 'Authorization',\n gateway: this.id,\n models: [...KIMI_CODING_MODELS],\n };\n\n try {\n const copilotModels = await getCopilotModelCatalog({ authStorage: this.#credentials });\n providers['github-copilot'] = {\n name: 'GitHub Copilot',\n apiKeyEnvVar: '',\n apiKeyHeader: 'Authorization',\n gateway: this.id,\n models: copilotModels.map(model => model.id),\n };\n } catch (error) {\n console.warn('Failed to load GitHub Copilot model catalog:', error);\n }\n\n return providers;\n }\n\n buildUrl(modelId: string): string | undefined | Promise<string | undefined> {\n return this.#routeThroughMastraGateway ? this.#mastraGateway.buildUrl(modelId) : modelId;\n }\n\n async getApiKey(modelId: string): Promise<string> {\n const providerId = stripMastraGatewayPrefix(modelId).split('/', 1)[0];\n if (this.#routeThroughMastraGateway) return this.#mastraGatewayApiKey ?? '';\n return providerId ? (getProviderAuthKey(providerId, this.#credentials) ?? '') : '';\n }\n\n resolveAuth(request: GatewayAuthRequest): GatewayAuthResult | undefined {\n if (this.#routeThroughMastraGateway && this.#mastraGatewayApiKey) {\n return { apiKey: this.#mastraGatewayApiKey, source: 'gateway' };\n }\n\n const customProvider = this.#getCustomProviders().find(\n provider => request.providerId === getCustomProviderId(provider.name),\n );\n if (customProvider?.apiKey) {\n return { apiKey: customProvider.apiKey, source: 'gateway' };\n }\n\n return MastraCodeGateway.resolveProviderAuth(request, undefined, this.#credentials);\n }\n\n resolveLanguageModel(args: {\n modelId: string;\n providerId: string;\n apiKey: string;\n headers?: Record<string, string>;\n transport?: any;\n responsesWebSocket?: any;\n }): GatewayLanguageModel {\n const customProvider = this.#getCustomProviders().find(\n provider => args.providerId === getCustomProviderId(provider.name),\n );\n if (customProvider) {\n const provider = createOpenAICompatible({\n name: args.providerId,\n baseURL: customProvider.url,\n apiKey: args.apiKey,\n headers: args.headers,\n });\n return provider.chatModel(args.modelId) as unknown as GatewayLanguageModel;\n }\n\n if (args.providerId === 'github-copilot') {\n return githubCopilotProvider(args.modelId, {\n headers: args.headers,\n authStorage: this.#credentials,\n }) as unknown as GatewayLanguageModel;\n }\n\n if (args.providerId === 'moonshotai') {\n // Prefer the gateway-resolved key (stored credentials), then the canonical\n // registry env var. Keep the legacy typo name as a fallback for anyone who\n // set it because of the previous error message.\n const apiKey =\n args.apiKey?.trim() || process.env.MOONSHOT_API_KEY?.trim() || process.env.MOONSHOT_AI_API_KEY?.trim();\n if (!apiKey) {\n throw new Error('Need MOONSHOT_API_KEY');\n }\n return createAnthropic({\n apiKey,\n baseURL: 'https://api.moonshot.ai/anthropic/v1',\n name: 'moonshotai.anthropicv1',\n headers: args.headers,\n })(args.modelId) as unknown as GatewayLanguageModel;\n }\n\n if (args.providerId === 'anthropic') {\n return this.#resolveAnthropicModel(args);\n }\n\n if (args.providerId === 'openai') {\n const openaiModel = this.#resolveOpenAIModel(args);\n if (openaiModel) return openaiModel;\n }\n\n if (args.providerId === 'xai' && this.#credentials.get('xai')?.type === 'oauth') {\n return xaiProvider(args.modelId, {\n headers: args.headers,\n authStorage: this.#credentials,\n }) as unknown as GatewayLanguageModel;\n }\n\n if (this.#routeThroughMastraGateway) {\n return this.#mastraGateway.resolveLanguageModel(args) as GatewayLanguageModel;\n }\n\n if (args.providerId === 'kimi-for-coding') {\n return kimiCodingProvider(args.modelId, {\n apiKey: args.apiKey,\n headers: args.headers,\n credentialStore: this.#credentials,\n }) as unknown as GatewayLanguageModel;\n }\n\n return new ModelRouterLanguageModel({\n id: `${args.providerId}/${args.modelId}` as `${string}/${string}`,\n apiKey: args.apiKey,\n headers: args.headers,\n }) as unknown as GatewayLanguageModel;\n }\n\n #resolveAnthropicModel(args: {\n modelId: string;\n providerId: string;\n apiKey: string;\n headers?: Record<string, string>;\n transport?: any;\n responsesWebSocket?: any;\n }): GatewayLanguageModel {\n const bareModelId = normalizeAnthropicModelId(args.modelId);\n const storedCred = this.#credentials.get('anthropic');\n const thinkingMiddleware = createAnthropicThinkingMiddleware(bareModelId, this.#thinkingLevel);\n\n if (this.#routeThroughMastraGateway) {\n if (storedCred?.type === 'oauth') {\n const anthropic = createAnthropic({\n apiKey: 'oauth-gateway-placeholder',\n baseURL: `${this.#mastraGatewayBaseUrl}/v1`,\n headers: {\n [GATEWAY_AUTH_HEADER]: `Bearer ${args.apiKey}`,\n ...args.headers,\n },\n fetch: buildAnthropicOAuthFetch({ authStorage: this.#credentials }) as any,\n });\n\n return wrapLanguageModel({\n model: anthropic(bareModelId),\n middleware: [\n claudeCodeMiddleware,\n promptCacheMiddleware,\n ...(thinkingMiddleware ? [thinkingMiddleware] : []),\n ],\n }) as unknown as GatewayLanguageModel;\n }\n\n const gatewayModel = this.#mastraGateway.resolveLanguageModel({\n ...args,\n modelId: bareModelId,\n }) as GatewayLanguageModel;\n if (!thinkingMiddleware) return gatewayModel;\n return wrapLanguageModel({\n model: gatewayModel as any,\n middleware: [thinkingMiddleware],\n }) as unknown as GatewayLanguageModel;\n }\n\n if (storedCred?.type === 'oauth') {\n return opencodeClaudeMaxProvider(bareModelId, {\n headers: args.headers,\n authStorage: this.#credentials,\n thinkingLevel: this.#thinkingLevel,\n }) as unknown as GatewayLanguageModel;\n }\n\n if (storedCred?.type === 'api_key' && storedCred.key.trim().length > 0) {\n return anthropicApiKeyProvider(\n bareModelId,\n storedCred.key.trim(),\n args.headers,\n this.#thinkingLevel,\n ) as unknown as GatewayLanguageModel;\n }\n\n const apiKey = getAnthropicApiKey(this.#credentials);\n if (apiKey) {\n return anthropicApiKeyProvider(\n bareModelId,\n apiKey,\n args.headers,\n this.#thinkingLevel,\n ) as unknown as GatewayLanguageModel;\n }\n\n // No stored credentials: use the OAuth-backed provider so the first request can trigger login.\n return opencodeClaudeMaxProvider(bareModelId, {\n headers: args.headers,\n authStorage: this.#credentials,\n thinkingLevel: this.#thinkingLevel,\n }) as unknown as GatewayLanguageModel;\n }\n\n #resolveOpenAIModel(args: {\n modelId: string;\n providerId: string;\n apiKey: string;\n headers?: Record<string, string>;\n transport?: any;\n responsesWebSocket?: any;\n }): GatewayLanguageModel | undefined {\n const storedCred = this.#credentials.get('openai-codex');\n\n if (this.#routeThroughMastraGateway) {\n if (storedCred?.type === 'oauth') {\n const resolvedModelId = remapOpenAIModelForCodexOAuth(`openai/${args.modelId}`);\n const resolvedBareModelId = resolvedModelId.substring(OPENAI_PREFIX.length);\n const requestedLevel: ThinkingLevel = this.#thinkingLevel ?? 'medium';\n const effectiveLevel = getEffectiveThinkingLevel(resolvedBareModelId, requestedLevel);\n const reasoningEffort = THINKING_LEVEL_TO_REASONING_EFFORT[effectiveLevel];\n const middleware = createCodexMiddleware(reasoningEffort);\n const openai = createOpenAI({\n apiKey: 'oauth-gateway-placeholder',\n baseURL: `${this.#mastraGatewayBaseUrl}/v1`,\n headers: {\n [GATEWAY_AUTH_HEADER]: `Bearer ${args.apiKey}`,\n ...args.headers,\n },\n fetch: buildOpenAICodexOAuthFetch({ authStorage: this.#credentials, rewriteUrl: false }) as any,\n });\n\n return wrapLanguageModel({\n model: openai.responses(resolvedBareModelId),\n middleware: [middleware],\n }) as unknown as GatewayLanguageModel;\n }\n\n return this.#mastraGateway.resolveLanguageModel(args) as GatewayLanguageModel;\n }\n\n if (storedCred?.type === 'oauth') {\n const resolvedModelId = remapOpenAIModelForCodexOAuth(`openai/${args.modelId}`);\n return openaiCodexProvider(resolvedModelId.substring(OPENAI_PREFIX.length), {\n thinkingLevel: this.#thinkingLevel,\n headers: args.headers,\n authStorage: this.#credentials,\n }) as unknown as GatewayLanguageModel;\n }\n\n const apiKey = getOpenAIApiKey(this.#credentials);\n if (apiKey) {\n return openaiApiKeyProvider(args.modelId, apiKey, args.headers) as unknown as GatewayLanguageModel;\n }\n\n return undefined;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AA2CA,MAAa,gBAAgB;AAC7B,MAAa,wBAAwB;AACrC,MAAa,wBAAwB;AAErC,MAAM,4BAAoD;CACxD,WAAW;CACX,WAAW;CACX,WAAW;CACX,gBAAgB;CAChB,SAAS;AACX;;;;;;;;;;AA8BA,IAAI;AACJ,IAAI;AAEJ,SAAgB,uBAAoC;CAIlD,MAAM,MAAM,cAAc;CAC1B,IAAI,CAAC,wBAAwB,4BAA4B,KAAK;EAC5D,uBAAuB,IAAI,YAAY;EACvC,0BAA0B;CAC5B;CACA,OAAO;AACT;AAEA,SAAgB,oBAAoB;CAClC,qBAAqB,CAAC,CAAC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BAA0B,qBADX,KAAKC,kBAAkB,QAEW;IACxE,MAAM,aAAa,sBAAsB,eAAe;IAWxD,OAAO,kBAAkB;KACvB,OAXa,aAAa;MAC1B,QAAQ;MACR,SAAS,GAAG,KAAKH,sBAAsB;MACvC,SAAS;QACN,sBAAsB,UAAU,KAAK;OACtC,GAAG,KAAK;MACV;MACA,OAAO,2BAA2B;OAAE,aAAa,KAAKM;OAAc,YAAY;MAAM,CAAC;KACzF,CAGc,CAAC,CAAC,UAAU,mBAAmB;KAC3C,YAAY,CAAC,UAAU;IACzB,CAAC;GACH;GAEA,OAAO,KAAKP,eAAe,qBAAqB,IAAI;EACtD;EAEA,IAAI,YAAY,SAAS,SAEvB,OAAO,oBADiB,8BAA8B,UAAU,KAAK,SAC5B,CAAC,CAAC,UAAU,CAAoB,GAAG;GAC1E,eAAe,KAAKI;GACpB,SAAS,KAAK;GACd,aAAa,KAAKG;EACpB,CAAC;EAGH,MAAM,SAAS,gBAAgB,KAAKA,YAAY;EAChD,IAAI,QACF,OAAO,qBAAqB,KAAK,SAAS,QAAQ,KAAK,OAAO;CAIlE;AACF"}
|
package/dist/agents/memory.d.ts
CHANGED
|
@@ -24,7 +24,7 @@ export declare function hasSubconsciousTools(vector: MastraVector | undefined, s
|
|
|
24
24
|
* Reads OM thresholds from controller state via requestContext.
|
|
25
25
|
* Model functions also read from requestContext (no mutable bridge needed).
|
|
26
26
|
*/
|
|
27
|
-
export declare function getDynamicMemory(storage: MastraCompositeStore, vector?: MastraVector): ({ requestContext }: {
|
|
27
|
+
export declare function getDynamicMemory(storage: MastraCompositeStore, vector?: MastraVector, settingsPath?: string): ({ requestContext }: {
|
|
28
28
|
requestContext: RequestContext;
|
|
29
29
|
}) => Memory;
|
|
30
30
|
//# sourceMappingURL=memory.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"memory.d.ts","sourceRoot":"","sources":["../../src/agents/memory.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"memory.d.ts","sourceRoot":"","sources":["../../src/agents/memory.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AACnE,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,sBAAsB,CAAC;AACjE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAExD,OAAO,EAAE,MAAM,EAAgB,MAAM,gBAAgB,CAAC;AAEtD,OAAO,EAAE,sBAAsB,EAAiC,MAAM,uBAAuB,CAAC;AAE9F,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAgFpD,OAAO,EAAE,sBAAsB,EAAE,CAAC;AA8BlC;;;GAGG;AACH,wBAAgB,qBAAqB,CAAC,MAAM,EAAE,YAAY,GAAG,SAAS,GAAG,OAAO,CAE/E;AAED;;;;;;;GAOG;AACH,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,YAAY,GAAG,SAAS,EAAE,KAAK,EAAE,eAAe,GAAG,SAAS,GAAG,OAAO,CAElH;AAED;;;;GAIG;AACH,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,oBAAoB,EAAE,MAAM,CAAC,EAAE,YAAY,EAAE,YAAY,CAAC,EAAE,MAAM,IAelG,oBAAoB;IAAE,cAAc,EAAE,cAAc,CAAA;CAAE,YAyG/D"}
|
package/dist/agents/memory.js
CHANGED
|
@@ -1,36 +1,38 @@
|
|
|
1
1
|
import { DEFAULT_OM_MODEL_ID } from "../constants.js";
|
|
2
2
|
import { getOmScope } from "../utils/project.js";
|
|
3
|
+
import { loadSettings } from "../onboarding/settings.js";
|
|
3
4
|
import { LOCAL_KNOWLEDGE_ORG_ID, resolveKnowledgeScopeIdentity } from "../knowledge-scope.js";
|
|
4
|
-
import { resolveModel } from "./model.js";
|
|
5
|
+
import { resolveModel, resolvePackMemoryModelChain } from "./model.js";
|
|
5
6
|
import { fastembed } from "@mastra/fastembed";
|
|
6
7
|
import { Memory, Subconscious } from "@mastra/memory";
|
|
7
8
|
//#region src/agents/memory.ts
|
|
8
9
|
/**
|
|
9
|
-
*
|
|
10
|
-
*
|
|
10
|
+
* Resolve one OM role's model for this invocation. Lookup order:
|
|
11
|
+
* 1. The explicit role override (`observerModelOverride` / `reflectorModelOverride`).
|
|
12
|
+
* 2. The active mode pack's optional `models.memory`, walking the pack's fallback
|
|
13
|
+
* chain so OM fails over alongside (and independently of) the main agent.
|
|
14
|
+
* The pending pack-hop marker wins over the settled pack id so an immediate
|
|
15
|
+
* retrigger observes on the landed pack.
|
|
16
|
+
* 3. The standalone OM configuration seeded into controller state
|
|
17
|
+
* (`observerModelId` / `reflectorModelId`), then the default OM model.
|
|
11
18
|
*/
|
|
12
|
-
function
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
* Observer model function — reads the current observer model ID from
|
|
17
|
-
* controller state via requestContext (now propagated by OM's agent.generate).
|
|
18
|
-
*/
|
|
19
|
-
function getObserverModel({ requestContext }) {
|
|
20
|
-
return resolveModel(getAgentControllerState(requestContext)?.observerModelId ?? DEFAULT_OM_MODEL_ID, {
|
|
21
|
-
remapForCodexOAuth: true,
|
|
22
|
-
requestContext
|
|
23
|
-
});
|
|
24
|
-
}
|
|
25
|
-
/**
|
|
26
|
-
* Reflector model function — reads the current reflector model ID from
|
|
27
|
-
* controller state via requestContext (now propagated by OM's agent.generate).
|
|
28
|
-
*/
|
|
29
|
-
function getReflectorModel({ requestContext }) {
|
|
30
|
-
return resolveModel(getAgentControllerState(requestContext)?.reflectorModelId ?? DEFAULT_OM_MODEL_ID, {
|
|
19
|
+
function resolveOmRoleModelForRequest(role, requestContext, settingsPath) {
|
|
20
|
+
const controller = requestContext.get("controller");
|
|
21
|
+
const state = controller?.getState();
|
|
22
|
+
const resolveOptions = {
|
|
31
23
|
remapForCodexOAuth: true,
|
|
32
24
|
requestContext
|
|
33
|
-
}
|
|
25
|
+
};
|
|
26
|
+
const settings = loadSettings(settingsPath);
|
|
27
|
+
const roleOverride = role === "observer" ? settings.models?.observerModelOverride : settings.models?.reflectorModelOverride;
|
|
28
|
+
if (roleOverride) return resolveModel(roleOverride, resolveOptions);
|
|
29
|
+
const pendingState = state?.mastracodePendingPackFallback;
|
|
30
|
+
const packId = (pendingState && (pendingState.threadId === void 0 || pendingState.threadId === controller?.threadId) && typeof pendingState.toPackId === "string" && pendingState.toPackId.length > 0 ? pendingState.toPackId : void 0) ?? state?.activeModelPackId ?? settings.models?.activeModelPackId;
|
|
31
|
+
if (typeof packId === "string" && packId.length > 0) {
|
|
32
|
+
const chained = resolvePackMemoryModelChain(settings, packId, resolveOptions);
|
|
33
|
+
if (chained) return chained;
|
|
34
|
+
}
|
|
35
|
+
return resolveModel((role === "observer" ? state?.observerModelId : state?.reflectorModelId) ?? DEFAULT_OM_MODEL_ID, resolveOptions);
|
|
34
36
|
}
|
|
35
37
|
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.";
|
|
36
38
|
const CAVEMAN_OM_INSTRUCTION = `Respond terse like smart caveman. All technical substance stay. Only fluff die.
|
|
@@ -90,9 +92,11 @@ function hasSubconsciousTools(vector, state) {
|
|
|
90
92
|
* Reads OM thresholds from controller state via requestContext.
|
|
91
93
|
* Model functions also read from requestContext (no mutable bridge needed).
|
|
92
94
|
*/
|
|
93
|
-
function getDynamicMemory(storage, vector) {
|
|
95
|
+
function getDynamicMemory(storage, vector, settingsPath) {
|
|
94
96
|
let cachedMemory = null;
|
|
95
97
|
let cachedMemoryKey = null;
|
|
98
|
+
const getObserverModel = ({ requestContext }) => resolveOmRoleModelForRequest("observer", requestContext, settingsPath);
|
|
99
|
+
const getReflectorModel = ({ requestContext }) => resolveOmRoleModelForRequest("reflector", requestContext, settingsPath);
|
|
96
100
|
return ({ requestContext }) => {
|
|
97
101
|
const controller = requestContext.get("controller");
|
|
98
102
|
const state = controller?.getState();
|
|
@@ -126,7 +130,10 @@ function getDynamicMemory(storage, vector) {
|
|
|
126
130
|
vector: vector || false,
|
|
127
131
|
embedder: vector ? fastembed.small : void 0,
|
|
128
132
|
options: {
|
|
129
|
-
generateTitle: { model:
|
|
133
|
+
generateTitle: { model: ({ requestContext }) => {
|
|
134
|
+
const resolved = getObserverModel({ requestContext });
|
|
135
|
+
return Array.isArray(resolved) ? resolved[0].model : resolved;
|
|
136
|
+
} },
|
|
130
137
|
observationalMemory: {
|
|
131
138
|
enabled: true,
|
|
132
139
|
temporalMarkers: true,
|
|
@@ -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 { RequestContext } from '@mastra/core/request-context';\nimport type { MastraCompositeStore } from '@mastra/core/storage';\nimport type { MastraVector } from '@mastra/core/vector';\nimport { fastembed } from '@mastra/fastembed';\nimport { Memory, Subconscious } from '@mastra/memory';\nimport { DEFAULT_OM_MODEL_ID, DEFAULT_OBS_THRESHOLD, DEFAULT_REF_THRESHOLD } from '../constants.js';\nimport { LOCAL_KNOWLEDGE_ORG_ID, resolveKnowledgeScopeIdentity } from '../knowledge-scope.js';\nimport type { MastraCodeState } from '../schema.js';\nimport { getOmScope } from '../utils/project.js';\nimport { resolveModel } from './model.js';\n\n/**\n * Read controller state from requestContext.\n * Used by both the memory factory and the OM model functions.\n */\nfunction getAgentControllerState(requestContext: RequestContext): MastraCodeState | undefined {\n const ctx = requestContext.get('controller') as AgentControllerRequestContext<MastraCodeState> | undefined;\n return ctx?.getState() as MastraCodeState | undefined;\n}\n\n/**\n * Observer model function — reads the current observer model ID from\n * controller state via requestContext (now propagated by OM's agent.generate).\n */\nfunction getObserverModel({ requestContext }: { requestContext: RequestContext }) {\n const state = getAgentControllerState(requestContext);\n return resolveModel(state?.observerModelId ?? DEFAULT_OM_MODEL_ID, {\n remapForCodexOAuth: true,\n requestContext,\n });\n}\n\n/**\n * Reflector model function — reads the current reflector model ID from\n * controller state via requestContext (now propagated by OM's agent.generate).\n */\nfunction getReflectorModel({ requestContext }: { requestContext: RequestContext }) {\n const state = getAgentControllerState(requestContext);\n return resolveModel(state?.reflectorModelId ?? DEFAULT_OM_MODEL_ID, {\n remapForCodexOAuth: true,\n requestContext,\n });\n}\n\nconst DYNAMIC_AGENTS_MD_INSTRUCTION =\n 'Messages wrapped in <system-reminder type=\"dynamic-agents-md\" ...>...</system-reminder> are ephemeral project-context instructions injected from files on disk. Do NOT observe or extract information from these messages — they are reloaded automatically when needed and should not be stored in memory.';\n\n// Derived from https://github.com/JuliusBrussee/caveman and adapted for OM use with fixed full-level compression.\nconst CAVEMAN_OM_INSTRUCTION = `Respond terse like smart caveman. All technical substance stay. Only fluff die.\n\nUse full caveman compression style.\n\nDrop: articles (a/an/the), filler (just/really/basically/actually/simply), pleasantries (sure/certainly/of course/happy to), hedging. Fragments OK. Short synonyms (big not extensive, fix not \"implement a solution for\"). Technical terms exact. Code blocks unchanged. Errors quoted exact. Leave out the words \"agent\" and \"assistant\" at the start of each observation line, it is assumed each line is referring to the assistant unless it specifically says it was about the user. Leave out parenthesis and other text characters like * that would not contribute to understanding the observations.\n\nPattern: \\`[thing] [action] [reason]. [next step]\\`\n\nNot: \"Sure! I'd be happy to help you with that. The issue you're experiencing is likely caused by...\"\nYes: \"Bug in auth middleware. Token expiry check use < not <=. Fix:\"\n\nExample 1\n🔴 14:31 user asks why React component rerenders\n🟡 14:32 saw inline object prop create new ref each render, cause rerender\n✅ 14:34 fixed render issue by wrap object in useMemo\n\nExample 2\n🟡 15:10 explained pool reuse DB connections, skip repeat handshake overhead\n\nDon't say \"Agent did x\", say \"did x\". It will be assumed the agent did what was observed. The who should only be specified for the user or other third parties: \"user asked x\"\n\nDrop caveman for: security warnings, irreversible action confirmations, multi-step sequences where fragment order risks misread, user asks to clarify or repeats question, and anything that requires remembering verbatim content. Resume caveman after clear part done`;\n\nexport { LOCAL_KNOWLEDGE_ORG_ID };\n\n// One error per session, not per memory resolution. Keyed on the session id\n// rather than the controller object: the controller is read off the request\n// context on every resolution, so it is a fresh object per request and would\n// dedupe nothing. Bounded so a long-running Factory process cannot grow this\n// without limit — refusing sessions are rare, and losing the oldest ids only\n// costs one extra log line.\nconst REPORTED_ORG_UNRESOLVED_LIMIT = 500;\nconst reportedOrgUnresolved = new Set<string>();\n\nfunction reportOrgUnresolved(\n controller: AgentControllerRequestContext<MastraCodeState> | undefined,\n factoryProjectId: string | undefined,\n reason?: string,\n) {\n const sessionId = controller?.session?.id;\n if (sessionId) {\n if (reportedOrgUnresolved.has(sessionId)) return;\n if (reportedOrgUnresolved.size >= REPORTED_ORG_UNRESOLVED_LIMIT) {\n reportedOrgUnresolved.delete(reportedOrgUnresolved.values().next().value as string);\n }\n reportedOrgUnresolved.add(sessionId);\n }\n const session = controller?.session;\n console.error(\n `[Subconscious] Knowledge curation disabled: no organization resolved for session ${session?.id ?? 'unknown'} (project ${factoryProjectId ?? 'none'})${reason ? `: ${reason}` : ''}. Knowledge is not written rather than written where it cannot be read.`,\n );\n}\n\n/**\n * Whether the experimental subconscious (knowledge graph + reminder sidekick)\n * is switched on for this process: it needs a vector store and the opt-in flag.\n */\nexport function isSubconsciousEnabled(vector: MastraVector | undefined): boolean {\n return Boolean(vector) && process.env.MASTRACODE_EXPERIMENTAL_SUBCONSCIOUS === '1';\n}\n\n/**\n * Whether the subconscious tools (`knowledge_*`, `ask_memory`) are registered\n * for a given session. Beyond the process-level switch, a Factory-owned\n * session that cannot resolve its org refuses the subconscious entirely (see\n * `getDynamicMemory`, which applies the same two checks inline because it also\n * needs the resolved identity). The system prompt's tool guidance calls here so\n * it never advertises tools that `getDynamicMemory` did not register.\n */\nexport function hasSubconsciousTools(vector: MastraVector | undefined, state: MastraCodeState | undefined): boolean {\n return isSubconsciousEnabled(vector) && resolveKnowledgeScopeIdentity(state).resolved;\n}\n\n/**\n * Dynamic memory factory function.\n * Reads OM thresholds from controller state via requestContext.\n * Model functions also read from requestContext (no mutable bridge needed).\n */\nexport function getDynamicMemory(storage: MastraCompositeStore, vector?: MastraVector) {\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 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.\n generateTitle: { model: getObserverModel },\n observationalMemory: {\n enabled: true,\n temporalMarkers: true,\n retrieval: vector ? { vector: true } : true,\n experimental_subconscious: subconsciousAvailable\n ? new Subconscious({\n defaultScope: 'resource',\n maxScope: 'resource',\n pins: true,\n ...(isFactory ? { maxSteps: 25 } : {}),\n })\n : undefined,\n scope: omScope,\n activateAfterIdle: 'auto',\n activateOnProviderChange: true,\n observation: {\n bufferTokens: isResourceScope ? false : 1 / 5,\n bufferActivation: isResourceScope ? undefined : 2000,\n model: getObserverModel,\n messageTokens: obsThreshold,\n blockAfter: 2,\n previousObserverTokens: observerPreviousObservationTokens,\n threadTitle: true,\n instruction: observerInstruction,\n observeAttachments,\n },\n reflection: {\n bufferActivation: isResourceScope ? undefined : 1 / 2,\n blockAfter: 1.1,\n model: getReflectorModel,\n observationTokens: refThreshold,\n instruction: reflectionInstruction,\n },\n },\n },\n });\n cachedMemoryKey = cacheKey;\n\n return cachedMemory;\n };\n}\n"],"mappings":";;;;;;;;;;;AAgBA,SAAS,wBAAwB,gBAA6D;CAE5F,OADY,eAAe,IAAI,YACtB,CAAC,EAAE,SAAS;AACvB;;;;;AAMA,SAAS,iBAAiB,EAAE,kBAAsD;CAEhF,OAAO,aADO,wBAAwB,cACd,CAAC,EAAE,mBAAmB,qBAAqB;EACjE,oBAAoB;EACpB;CACF,CA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OAAO;MACP,eAAe;MACf,YAAY;MACZ,wBAAwB;MACxB,aAAa;MACb,aAAa;MACb;KACF;KACA,YAAY;MACV,kBAAkB,kBAAkB,KAAA,IAAY,IAAI;MACpD,YAAY;MACZ,OAAO;MACP,mBAAmB;MACnB,aAAa;KACf;IACF;GACF;EACF,CAAC;EACD,kBAAkB;EAElB,OAAO;CACT;AACF"}
|
|
1
|
+
{"version":3,"file":"memory.js","names":[],"sources":["../../src/agents/memory.ts"],"sourcesContent":["import type { AgentControllerRequestContext } from '@mastra/core/agent-controller';\nimport type { GatewayLanguageModel } from '@mastra/core/llm';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport type { MastraCompositeStore } from '@mastra/core/storage';\nimport type { MastraVector } from '@mastra/core/vector';\nimport { fastembed } from '@mastra/fastembed';\nimport { Memory, Subconscious } from '@mastra/memory';\nimport { DEFAULT_OM_MODEL_ID, DEFAULT_OBS_THRESHOLD, DEFAULT_REF_THRESHOLD } from '../constants.js';\nimport { LOCAL_KNOWLEDGE_ORG_ID, resolveKnowledgeScopeIdentity } from '../knowledge-scope.js';\nimport { loadSettings } from '../onboarding/settings.js';\nimport type { MastraCodeState } from '../schema.js';\nimport { getOmScope } from '../utils/project.js';\nimport { resolveModel, resolvePackMemoryModelChain } from './model.js';\nimport type { PackMemoryModelChainEntry } from './model.js';\n\n/**\n * Resolve one OM role's model for this invocation. Lookup order:\n * 1. The explicit role override (`observerModelOverride` / `reflectorModelOverride`).\n * 2. The active mode pack's optional `models.memory`, walking the pack's fallback\n * chain so OM fails over alongside (and independently of) the main agent.\n * The pending pack-hop marker wins over the settled pack id so an immediate\n * retrigger observes on the landed pack.\n * 3. The standalone OM configuration seeded into controller state\n * (`observerModelId` / `reflectorModelId`), then the default OM model.\n */\nfunction resolveOmRoleModelForRequest(\n role: 'observer' | 'reflector',\n requestContext: RequestContext,\n settingsPath?: string,\n): GatewayLanguageModel | PackMemoryModelChainEntry[] {\n const controller = requestContext.get('controller') as AgentControllerRequestContext<MastraCodeState> | undefined;\n const state = controller?.getState() as MastraCodeState | undefined;\n const resolveOptions = { remapForCodexOAuth: true, requestContext } as const;\n\n // The configured settings file, not the default one: a caller that points the\n // agent at another settings path must get the same pack/override resolution\n // for observational memory as it does for the main model.\n const settings = loadSettings(settingsPath);\n const roleOverride =\n role === 'observer' ? settings.models?.observerModelOverride : settings.models?.reflectorModelOverride;\n if (roleOverride) return resolveModel(roleOverride, resolveOptions);\n\n const pendingState = state?.mastracodePendingPackFallback as\n | { toPackId?: unknown; threadId?: unknown }\n | null\n | undefined;\n const pendingPackId =\n pendingState &&\n (pendingState.threadId === undefined || pendingState.threadId === controller?.threadId) &&\n typeof pendingState.toPackId === 'string' &&\n pendingState.toPackId.length > 0\n ? pendingState.toPackId\n : undefined;\n const packId = pendingPackId ?? state?.activeModelPackId ?? settings.models?.activeModelPackId;\n if (typeof packId === 'string' && packId.length > 0) {\n const chained = resolvePackMemoryModelChain(settings, packId, resolveOptions);\n if (chained) return chained;\n }\n\n const stateModelId = role === 'observer' ? state?.observerModelId : state?.reflectorModelId;\n return resolveModel(stateModelId ?? DEFAULT_OM_MODEL_ID, resolveOptions);\n}\n\nconst DYNAMIC_AGENTS_MD_INSTRUCTION =\n 'Messages wrapped in <system-reminder type=\"dynamic-agents-md\" ...>...</system-reminder> are ephemeral project-context instructions injected from files on disk. Do NOT observe or extract information from these messages — they are reloaded automatically when needed and should not be stored in memory.';\n\n// Derived from https://github.com/JuliusBrussee/caveman and adapted for OM use with fixed full-level compression.\nconst CAVEMAN_OM_INSTRUCTION = `Respond terse like smart caveman. All technical substance stay. Only fluff die.\n\nUse full caveman compression style.\n\nDrop: articles (a/an/the), filler (just/really/basically/actually/simply), pleasantries (sure/certainly/of course/happy to), hedging. Fragments OK. Short synonyms (big not extensive, fix not \"implement a solution for\"). Technical terms exact. Code blocks unchanged. Errors quoted exact. Leave out the words \"agent\" and \"assistant\" at the start of each observation line, it is assumed each line is referring to the assistant unless it specifically says it was about the user. Leave out parenthesis and other text characters like * that would not contribute to understanding the observations.\n\nPattern: \\`[thing] [action] [reason]. [next step]\\`\n\nNot: \"Sure! I'd be happy to help you with that. The issue you're experiencing is likely caused by...\"\nYes: \"Bug in auth middleware. Token expiry check use < not <=. Fix:\"\n\nExample 1\n🔴 14:31 user asks why React component rerenders\n🟡 14:32 saw inline object prop create new ref each render, cause rerender\n✅ 14:34 fixed render issue by wrap object in useMemo\n\nExample 2\n🟡 15:10 explained pool reuse DB connections, skip repeat handshake overhead\n\nDon't say \"Agent did x\", say \"did x\". It will be assumed the agent did what was observed. The who should only be specified for the user or other third parties: \"user asked x\"\n\nDrop caveman for: security warnings, irreversible action confirmations, multi-step sequences where fragment order risks misread, user asks to clarify or repeats question, and anything that requires remembering verbatim content. Resume caveman after clear part done`;\n\nexport { LOCAL_KNOWLEDGE_ORG_ID };\n\n// One error per session, not per memory resolution. Keyed on the session id\n// rather than the controller object: the controller is read off the request\n// context on every resolution, so it is a fresh object per request and would\n// dedupe nothing. Bounded so a long-running Factory process cannot grow this\n// without limit — refusing sessions are rare, and losing the oldest ids only\n// costs one extra log line.\nconst REPORTED_ORG_UNRESOLVED_LIMIT = 500;\nconst reportedOrgUnresolved = new Set<string>();\n\nfunction reportOrgUnresolved(\n controller: AgentControllerRequestContext<MastraCodeState> | undefined,\n factoryProjectId: string | undefined,\n reason?: string,\n) {\n const sessionId = controller?.session?.id;\n if (sessionId) {\n if (reportedOrgUnresolved.has(sessionId)) return;\n if (reportedOrgUnresolved.size >= REPORTED_ORG_UNRESOLVED_LIMIT) {\n reportedOrgUnresolved.delete(reportedOrgUnresolved.values().next().value as string);\n }\n reportedOrgUnresolved.add(sessionId);\n }\n const session = controller?.session;\n console.error(\n `[Subconscious] Knowledge curation disabled: no organization resolved for session ${session?.id ?? 'unknown'} (project ${factoryProjectId ?? 'none'})${reason ? `: ${reason}` : ''}. Knowledge is not written rather than written where it cannot be read.`,\n );\n}\n\n/**\n * Whether the experimental subconscious (knowledge graph + reminder sidekick)\n * is switched on for this process: it needs a vector store and the opt-in flag.\n */\nexport function isSubconsciousEnabled(vector: MastraVector | undefined): boolean {\n return Boolean(vector) && process.env.MASTRACODE_EXPERIMENTAL_SUBCONSCIOUS === '1';\n}\n\n/**\n * Whether the subconscious tools (`knowledge_*`, `ask_memory`) are registered\n * for a given session. Beyond the process-level switch, a Factory-owned\n * session that cannot resolve its org refuses the subconscious entirely (see\n * `getDynamicMemory`, which applies the same two checks inline because it also\n * needs the resolved identity). The system prompt's tool guidance calls here so\n * it never advertises tools that `getDynamicMemory` did not register.\n */\nexport function hasSubconsciousTools(vector: MastraVector | undefined, state: MastraCodeState | undefined): boolean {\n return isSubconsciousEnabled(vector) && resolveKnowledgeScopeIdentity(state).resolved;\n}\n\n/**\n * Dynamic memory factory function.\n * Reads OM thresholds from controller state via requestContext.\n * Model functions also read from requestContext (no mutable bridge needed).\n */\nexport function getDynamicMemory(storage: MastraCompositeStore, vector?: MastraVector, settingsPath?: string) {\n // Cache is scoped per storage instance (per getDynamicMemory call) so a\n // Memory bound to one storage is never reused after storage changes.\n let cachedMemory: Memory | null = null;\n let cachedMemoryKey: string | null = null;\n\n // Observer/reflector model functions — read the current model ID from\n // controller state via requestContext (propagated by OM's agent.generate).\n // Bound here so the configured settings path reaches role overrides and pack\n // memory-model resolution.\n const getObserverModel = ({ requestContext }: { requestContext: RequestContext }) =>\n resolveOmRoleModelForRequest('observer', requestContext, settingsPath);\n const getReflectorModel = ({ requestContext }: { requestContext: RequestContext }) =>\n resolveOmRoleModelForRequest('reflector', requestContext, settingsPath);\n\n return ({ requestContext }: { requestContext: RequestContext }) => {\n const controller = requestContext.get('controller') as AgentControllerRequestContext<MastraCodeState> | undefined;\n const state = controller?.getState() as MastraCodeState | undefined;\n const subconsciousEnabled = isSubconsciousEnabled(vector);\n const factoryProjectId = state?.factoryProjectId;\n const isFactory = typeof factoryProjectId === 'string' && factoryProjectId.trim().length > 0;\n\n // A Factory-owned session that could not resolve its org refuses to curate:\n // writing under a substituted identity produces knowledge the fail-closed\n // read path can never see.\n let orgUnresolvedRefusal = false;\n\n if (subconsciousEnabled) {\n const identity = resolveKnowledgeScopeIdentity(state);\n if (identity.resolved) {\n requestContext.set('organizationId', identity.organizationId);\n } else {\n orgUnresolvedRefusal = true;\n reportOrgUnresolved(controller, identity.knowledgeResourceId, identity.reason);\n }\n if (identity.knowledgeResourceId) {\n requestContext.set('knowledgeResourceId', identity.knowledgeResourceId);\n }\n }\n\n const subconsciousAvailable = subconsciousEnabled && !orgUnresolvedRefusal;\n\n const omScope = state?.omScope ?? getOmScope(state?.projectPath);\n\n const obsThreshold = state?.observationThreshold ?? DEFAULT_OBS_THRESHOLD;\n const refThreshold = state?.reflectionThreshold ?? DEFAULT_REF_THRESHOLD;\n const caveman = state?.cavemanObservations ?? false;\n\n const observerPreviousObservationTokens = 1000;\n const observeAttachments = state?.observeAttachments;\n // Factory sessions get a factory-only Subconscious config, so the cache key\n // carries a factory presence bit to keep the two configs from cross-serving.\n const cacheKey = `${obsThreshold}:${refThreshold}:${omScope}:${observerPreviousObservationTokens}:${caveman ? 1 : 0}:${observeAttachments}:${isFactory ? 1 : 0}:${subconsciousAvailable ? 1 : 0}`;\n if (cachedMemory && cachedMemoryKey === cacheKey) {\n return cachedMemory;\n }\n\n // Async buffering is not supported with resource scope — disable it\n const isResourceScope = omScope === 'resource';\n\n const observerInstruction = caveman\n ? `${DYNAMIC_AGENTS_MD_INSTRUCTION}\\n\\n${CAVEMAN_OM_INSTRUCTION}`\n : DYNAMIC_AGENTS_MD_INSTRUCTION;\n const reflectionInstruction = caveman ? CAVEMAN_OM_INSTRUCTION : undefined;\n\n cachedMemory = new Memory({\n storage,\n vector: vector || false,\n embedder: vector ? fastembed.small : undefined,\n options: {\n // Generate a durable title from the first user message. Every client uses\n // the same title in its thread list and active-session chrome. Title\n // generation takes the primary OM model only — its model field does not\n // accept fallback arrays.\n generateTitle: {\n model: ({ requestContext }) => {\n const resolved = getObserverModel({ requestContext });\n return Array.isArray(resolved) ? resolved[0]!.model : resolved;\n },\n },\n observationalMemory: {\n enabled: true,\n temporalMarkers: true,\n retrieval: vector ? { vector: true } : true,\n experimental_subconscious: subconsciousAvailable\n ? new Subconscious({\n defaultScope: 'resource',\n maxScope: 'resource',\n pins: true,\n ...(isFactory ? { maxSteps: 25 } : {}),\n })\n : undefined,\n scope: omScope,\n activateAfterIdle: 'auto',\n activateOnProviderChange: true,\n observation: {\n bufferTokens: isResourceScope ? false : 1 / 5,\n bufferActivation: isResourceScope ? undefined : 2000,\n model: getObserverModel,\n messageTokens: obsThreshold,\n blockAfter: 2,\n previousObserverTokens: observerPreviousObservationTokens,\n threadTitle: true,\n instruction: observerInstruction,\n observeAttachments,\n },\n reflection: {\n bufferActivation: isResourceScope ? undefined : 1 / 2,\n blockAfter: 1.1,\n model: getReflectorModel,\n observationTokens: refThreshold,\n instruction: reflectionInstruction,\n },\n },\n },\n });\n cachedMemoryKey = cacheKey;\n\n return cachedMemory;\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAyBA,SAAS,6BACP,MACA,gBACA,cACoD;CACpD,MAAM,aAAa,eAAe,IAAI,YAAY;CAClD,MAAM,QAAQ,YAAY,SAAS;CACnC,MAAM,iBAAiB;EAAE,oBAAoB;EAAM;CAAe;CAKlE,MAAM,WAAW,aAAa,YAAY;CAC1C,MAAM,eACJ,SAAS,aAAa,SAAS,QAAQ,wBAAwB,SAAS,QAAQ;CAClF,IAAI,cAAc,OAAO,aAAa,cAAc,cAAc;CAElE,MAAM,eAAe,OAAO;CAW5B,MAAM,UANJ,iBACC,aAAa,aAAa,KAAA,KAAa,aAAa,aAAa,YAAY,aAC9E,OAAO,aAAa,aAAa,YACjC,aAAa,SAAS,SAAS,IAC3B,aAAa,WACb,KAAA,MAC0B,OAAO,qBAAqB,SAAS,QAAQ;CAC7E,IAAI,OAAO,WAAW,YAAY,OAAO,SAAS,GAAG;EACnD,MAAM,UAAU,4BAA4B,UAAU,QAAQ,cAAc;EA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Ac;MACd,UAAU;MACV,MAAM;MACN,GAAI,YAAY,EAAE,UAAU,GAAG,IAAI,CAAC;KACtC,CAAC,IACD,KAAA;KACJ,OAAO;KACP,mBAAmB;KACnB,0BAA0B;KAC1B,aAAa;MACX,cAAc,kBAAkB,QAAQ,IAAI;MAC5C,kBAAkB,kBAAkB,KAAA,IAAY;MAChD,OAAO;MACP,eAAe;MACf,YAAY;MACZ,wBAAwB;MACxB,aAAa;MACb,aAAa;MACb;KACF;KACA,YAAY;MACV,kBAAkB,kBAAkB,KAAA,IAAY,IAAI;MACpD,YAAY;MACZ,OAAO;MACP,mBAAmB;MACnB,aAAa;KACf;IACF;GACF;EACF,CAAC;EACD,kBAAkB;EAElB,OAAO;CACT;AACF"}
|
package/dist/agents/model.d.ts
CHANGED
|
@@ -1,5 +1,8 @@
|
|
|
1
|
+
import type { ModelWithRetries } from '@mastra/core/agent';
|
|
1
2
|
import type { GatewayLanguageModel, MastraModelGatewayInterface } from '@mastra/core/llm';
|
|
2
3
|
import type { RequestContext } from '@mastra/core/request-context';
|
|
4
|
+
import type { CredentialStore } from '../auth/types.js';
|
|
5
|
+
import { loadSettings } from '../onboarding/settings.js';
|
|
3
6
|
import type { ThinkingLevelSetting } from '../thinking.js';
|
|
4
7
|
import { MastraCodeGateway } from './mastracode-gateway.js';
|
|
5
8
|
import type { MastraCodeGatewayOptions } from './mastracode-gateway.js';
|
|
@@ -10,6 +13,7 @@ export type { CredentialTenant, CredentialStoreProvider } from './credential-res
|
|
|
10
13
|
export { setCustomProvidersSource, hasCustomProvidersSource, resolveCustomProviders, } from './custom-provider-source.js';
|
|
11
14
|
export type { CustomProvidersSource } from './custom-provider-source.js';
|
|
12
15
|
type ResolvedModel = GatewayLanguageModel;
|
|
16
|
+
export declare function createRequestScopedCredentialStore(base: CredentialStore, requestContext?: RequestContext): CredentialStore;
|
|
13
17
|
export declare function createMastraCodeGateway(options: MastraCodeGatewayOptions): MastraCodeGateway;
|
|
14
18
|
export declare function createMastraCodeModelCatalogProvider(gateway: MastraModelGatewayInterface): import("@mastra/core/harness").CustomModelCatalogProvider;
|
|
15
19
|
/**
|
|
@@ -54,13 +58,49 @@ export interface ThinkingRequestContext {
|
|
|
54
58
|
* (rule-driven) Factory runs that nobody ever opens interactively.
|
|
55
59
|
*/
|
|
56
60
|
export declare function resolveRequestThinkingLevel(agentControllerContext: ThinkingRequestContext | undefined, settingsPath?: string): ThinkingLevelSetting;
|
|
61
|
+
/** Structural pack shape for fallback resolution (custom pack models are partial by nature). */
|
|
62
|
+
export interface ResolvableModePack {
|
|
63
|
+
id: string;
|
|
64
|
+
name: string;
|
|
65
|
+
models: Record<string, string>;
|
|
66
|
+
}
|
|
67
|
+
/** All packs a fallback chain may reference: every builtin plus saved customs. */
|
|
68
|
+
export declare function listResolvableModePacks(settings: ReturnType<typeof loadSettings>): ResolvableModePack[];
|
|
57
69
|
/**
|
|
58
70
|
* Dynamic model function that reads the current model from controller state.
|
|
59
71
|
* This allows runtime model switching via the /models picker.
|
|
72
|
+
*
|
|
73
|
+
* When the session's model came from a pack with a fallback chain configured
|
|
74
|
+
* (`settings.models.packFallbacks`), returns core's `ModelWithRetries[]`
|
|
75
|
+
* fallback array instead of a bare model: the active pack's model first, then
|
|
76
|
+
* each fallback pack's model for the same mode. Core advances the array when
|
|
77
|
+
* the error processors decline to retry (pool exhausted / persistent outage —
|
|
78
|
+
* see AccountRotationProcessor). Entry ids are unique per occurrence — the
|
|
79
|
+
* one allowed revisit of a pack gets `<packId>#2` — because core re-resolves
|
|
80
|
+
* the active fallback index by id across agentic steps.
|
|
60
81
|
*/
|
|
61
82
|
export declare function getDynamicModel({ requestContext }: {
|
|
62
83
|
requestContext: RequestContext;
|
|
63
|
-
}, settingsPath?: string): ResolvedModel;
|
|
84
|
+
}, settingsPath?: string): ResolvedModel | ModelWithRetries[];
|
|
85
|
+
/** OM fallback-chain entry: a pack's OM model resolved through the gateway. Assignable to `ModelWithRetries`. */
|
|
86
|
+
export type PackMemoryModelChainEntry = {
|
|
87
|
+
id: string;
|
|
88
|
+
model: GatewayLanguageModel;
|
|
89
|
+
};
|
|
90
|
+
/**
|
|
91
|
+
* Resolve the observational-memory model for the active mode pack, walking the
|
|
92
|
+
* pack's fallback chain (`settings.models.packFallbacks`) and collecting each
|
|
93
|
+
* pack's optional `models.memory` entry. Packs without an OM model are skipped
|
|
94
|
+
* (the field is optional, so absence must not truncate the chain); duplicate
|
|
95
|
+
* model ids collapse so an A⇄B cycle never retries an identical OM model.
|
|
96
|
+
*
|
|
97
|
+
* Returns a bare model for a single entry, a fallback array for multiple
|
|
98
|
+
* entries (OM's internal agents run the same agentic loop, so the array gives
|
|
99
|
+
* OM its own cross-pack failover), or `undefined` when no pack in the chain
|
|
100
|
+
* defines an OM model — callers then fall back to the standalone OM
|
|
101
|
+
* configuration.
|
|
102
|
+
*/
|
|
103
|
+
export declare function resolvePackMemoryModelChain(settings: ReturnType<typeof loadSettings>, startPackId: string, resolveOptions: Parameters<typeof resolveModel>[1]): GatewayLanguageModel | PackMemoryModelChainEntry[] | undefined;
|
|
64
104
|
/**
|
|
65
105
|
* Goal judge model resolver for the agent's `goal.judge` config. Resolves the
|
|
66
106
|
* 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":"
|
|
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;AAEnE,OAAO,KAAK,EAAE,eAAe,EAAsB,MAAM,kBAAkB,CAAC;AAE5E,OAAO,EAEL,YAAY,EAIb,MAAM,2BAA2B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