@mastra/code-sdk 1.6.0-alpha.2 → 1.6.0-alpha.3
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/CHANGELOG.md +6 -0
- package/dist/agents/credential-resolver.d.ts.map +1 -1
- package/dist/agents/credential-resolver.js +19 -2
- package/dist/agents/credential-resolver.js.map +1 -1
- package/dist/agents/model.d.ts.map +1 -1
- package/dist/agents/model.js +1 -0
- package/dist/agents/model.js.map +1 -1
- package/package.json +6 -6
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,11 @@
|
|
|
1
1
|
# @mastra/code-sdk
|
|
2
2
|
|
|
3
|
+
## 1.6.0-alpha.3
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- Improved diagnostics and error guidance when deployed tenant credential resolution fails closed. ([#22721](https://github.com/mastra-ai/mastra/pull/22721))
|
|
8
|
+
|
|
3
9
|
## 1.6.0-alpha.2
|
|
4
10
|
|
|
5
11
|
### Minor Changes
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"credential-resolver.d.ts","sourceRoot":"","sources":["../../src/agents/credential-resolver.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AACnE,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAExD,qDAAqD;AACrD,MAAM,WAAW,gBAAgB;IAC/B,iFAAiF;IACjF,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,gDAAgD;IAChD,MAAM,EAAE,MAAM,CAAC;IACf;;;;OAIG;IACH,QAAQ,CAAC,EAAE,OAAO,CAAC;CACpB;AAED;;;;;GAKG;AACH,MAAM,MAAM,uBAAuB,GAAG,CAAC,MAAM,EAAE,gBAAgB,KAAK,eAAe,GAAG,SAAS,CAAC;AAkBhG,mFAAmF;AACnF,wBAAgB,0BAA0B,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function resolveTenantFromRequestContext(requestContext) {
|
|
|
71
71
|
function resolveCredentialStore(requestContext) {
|
|
72
72
|
if (!credentialStoreProvider) return void 0;
|
|
73
73
|
const tenant = resolveTenantFromRequestContext(requestContext);
|
|
74
|
-
if (!tenant)
|
|
75
|
-
|
|
74
|
+
if (!tenant) {
|
|
75
|
+
const rawUser = requestContext?.get("user");
|
|
76
|
+
console.warn("[MastraCode] Tenant credential resolution failed closed", {
|
|
77
|
+
reason: rawUser === void 0 ? "missing-user-context" : "invalid-principal-shape",
|
|
78
|
+
hasRequestContext: requestContext !== void 0,
|
|
79
|
+
factorySession: isFactorySessionContext(requestContext)
|
|
80
|
+
});
|
|
81
|
+
return unavailableTenantCredentialStore;
|
|
82
|
+
}
|
|
83
|
+
const store = credentialStoreProvider(tenant);
|
|
84
|
+
if (!store) {
|
|
85
|
+
console.warn("[MastraCode] Tenant credential resolution failed closed", {
|
|
86
|
+
reason: "credential-store-unavailable",
|
|
87
|
+
hasOrganization: tenant.orgId !== void 0,
|
|
88
|
+
orgFirst: tenant.orgFirst === true
|
|
89
|
+
});
|
|
90
|
+
return unavailableTenantCredentialStore;
|
|
91
|
+
}
|
|
92
|
+
return store;
|
|
76
93
|
}
|
|
77
94
|
//#endregion
|
|
78
95
|
export { hasCredentialStoreProvider, resolveCredentialStore, resolveTenantFromRequestContext, setCredentialStoreProvider };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"credential-resolver.js","names":[],"sources":["../../src/agents/credential-resolver.ts"],"sourcesContent":["/**\n * Per-tenant credential resolution seam for deployed (multi-user) servers.\n *\n * Locally, model resolution reads the server-global file-backed `AuthStorage`.\n * A deployed web host registers a {@link CredentialStoreProvider} at boot; from\n * then on `resolveModel` derives the calling tenant from the request context\n * (the web auth gate stashes the authenticated user under the `user` key) and\n * resolves credentials through the tenant's own store — user credentials over\n * org credentials over server env vars, with OAuth refresh owned by the store.\n *\n * When no provider is registered (TUI, local web), everything falls through to\n * the existing global behavior unchanged.\n */\n\nimport type { RequestContext } from '@mastra/core/request-context';\nimport type { CredentialStore } from '../auth/types.js';\n\n/** The identity a credential lookup is scoped to. */\nexport interface CredentialTenant {\n /** Org tenant; absent for personal accounts (store impls may synthesize one). */\n orgId?: string;\n /** Stable user id from the web auth adapter. */\n userId: string;\n /**\n * Resolve org-shared credentials over the user's personal ones. Set by\n * trusted server code for automated (factory) runs so they ride the org's\n * shared keys first and only fall back to the acting user's credentials.\n */\n orgFirst?: boolean;\n}\n\n/**\n * Returns a tenant-scoped {@link CredentialStore}, or `undefined` to fall back\n * to the global store (e.g. tenant storage temporarily unavailable). Must be\n * synchronous — implementations serve from a primed snapshot and do\n * authoritative async work inside `getApiKey`.\n */\nexport type CredentialStoreProvider = (tenant: CredentialTenant) => CredentialStore | undefined;\n\nlet credentialStoreProvider: CredentialStoreProvider | undefined;\n\nconst unavailableTenantCredentialStore: CredentialStore = {\n allowEnvironmentFallback: false,\n reload() {},\n get() {\n return undefined;\n },\n getStoredApiKey() {\n return undefined;\n },\n async getApiKey() {\n return undefined;\n },\n};\n\n/** Register (or clear) the tenant credential store provider. Deployed-web only. */\nexport function setCredentialStoreProvider(provider: CredentialStoreProvider | undefined): void {\n credentialStoreProvider = provider;\n}\n\n/**\n * Whether a tenant provider is registered. Used to disable the\n * `loadStoredApiKeysIntoEnv` side-channel in deployed mode — per-tenant\n * credentials must never leak into process-global env vars.\n */\nexport function hasCredentialStoreProvider(): boolean {\n return credentialStoreProvider !== undefined;\n}\n\n/** Shape the web auth gate stashes on the request context under `user`. */\ninterface RequestContextUser {\n workosId?: string;\n id?: string;\n organizationId?: string;\n /** Trusted server code marks automated runs to resolve org > user credentials. */\n orgFirstCredentials?: boolean;\n}\n\n/**\n * Session-shaped `authenticateToken` results (better-auth) arrive as a wrapper\n * whose active org lives on the session half rather than on the user.\n */\ninterface RequestContextSession {\n user?: RequestContextUser;\n session?: { activeOrganizationId?: string };\n}\n\n/**\n * Whether the request context belongs to a run on a factory-owned session.\n *\n * The agent controller stamps the session's state onto the request context\n * under `controller`, and only trusted factory server code ever writes\n * `factoryProjectId` into session state (board-run creation) — interactive\n * chat sessions never carry it. Runs on such sessions resolve credentials\n * org > user regardless of who sent the message: a board run continued\n * interactively, or a model switch inside it, is still org work.\n */\nfunction isFactorySessionContext(requestContext?: RequestContext): boolean {\n const controller = requestContext?.get('controller') as { state?: { factoryProjectId?: unknown } } | undefined;\n if (!controller || typeof controller !== 'object') return false;\n const factoryProjectId = controller.state?.factoryProjectId;\n return typeof factoryProjectId === 'string' && factoryProjectId.length > 0;\n}\n\n/**\n * Derive the calling tenant from a request context, if an authenticated web\n * user was stashed on it. Mirrors the web layer's stable-id resolution\n * (`workosId` falling back to the provider `id`).\n *\n * The value under `user` is whatever the active auth provider's\n * `authenticateToken` returned, so its shape follows the provider: a flat user\n * (WorkOS) or a `{ session, user }` wrapper (better-auth). Reading only the\n * flat shape resolves no tenant at all for the wrapper, which in deployed mode\n * fails closed to an empty credential store.\n */\nexport function resolveTenantFromRequestContext(requestContext?: RequestContext): CredentialTenant | undefined {\n const raw = requestContext?.get('user') as (RequestContextUser & RequestContextSession) | undefined;\n if (!raw || typeof raw !== 'object') return undefined;\n\n // Precedence matches `toFactoryAuthUser` in `@mastra/factory`: a wrapper's org\n // comes from the session half only, never from the inner user. The two parsers\n // cannot share code across the package boundary, so they must agree by rule.\n const wrapped = Boolean(raw.user && typeof raw.user === 'object' && raw.session && typeof raw.session === 'object');\n const user = wrapped ? (raw.user as RequestContextUser) : raw;\n const orgId = wrapped ? raw.session?.activeOrganizationId : user.organizationId;\n const userId = user.workosId ?? user.id;\n // The slot holds whatever the provider returned, so the declared string\n // types are hopes, not guarantees. A non-string id must refuse the tenant\n // (fail closed), not flow onward as a mistyped key.\n if (typeof userId !== 'string' || !userId) return undefined;\n if (orgId !== undefined && typeof orgId !== 'string') return undefined;\n // Only an exact `true` flips precedence — anything else keeps user > org.\n // Server code stamps the flag on the stashed value itself, so read it from\n // the top level as well as the unwrapped user (better-auth wrapper shape).\n const orgFirst =\n raw.orgFirstCredentials === true || user.orgFirstCredentials === true || isFactorySessionContext(requestContext);\n return { orgId, userId, ...(orgFirst ? { orgFirst } : {}) };\n}\n\n/**\n * Resolve the credential store for a request. Local mode returns `undefined`\n * and keeps the global `AuthStorage` behavior. Once deployed web registers a\n * provider, missing tenant identity or unavailable tenant storage fails closed\n * through an empty store that also disables process-environment fallback.\n */\nexport function resolveCredentialStore(requestContext?: RequestContext): CredentialStore | undefined {\n if (!credentialStoreProvider) return undefined;\n const tenant = resolveTenantFromRequestContext(requestContext);\n if (!tenant) return unavailableTenantCredentialStore;\n
|
|
1
|
+
{"version":3,"file":"credential-resolver.js","names":[],"sources":["../../src/agents/credential-resolver.ts"],"sourcesContent":["/**\n * Per-tenant credential resolution seam for deployed (multi-user) servers.\n *\n * Locally, model resolution reads the server-global file-backed `AuthStorage`.\n * A deployed web host registers a {@link CredentialStoreProvider} at boot; from\n * then on `resolveModel` derives the calling tenant from the request context\n * (the web auth gate stashes the authenticated user under the `user` key) and\n * resolves credentials through the tenant's own store — user credentials over\n * org credentials over server env vars, with OAuth refresh owned by the store.\n *\n * When no provider is registered (TUI, local web), everything falls through to\n * the existing global behavior unchanged.\n */\n\nimport type { RequestContext } from '@mastra/core/request-context';\nimport type { CredentialStore } from '../auth/types.js';\n\n/** The identity a credential lookup is scoped to. */\nexport interface CredentialTenant {\n /** Org tenant; absent for personal accounts (store impls may synthesize one). */\n orgId?: string;\n /** Stable user id from the web auth adapter. */\n userId: string;\n /**\n * Resolve org-shared credentials over the user's personal ones. Set by\n * trusted server code for automated (factory) runs so they ride the org's\n * shared keys first and only fall back to the acting user's credentials.\n */\n orgFirst?: boolean;\n}\n\n/**\n * Returns a tenant-scoped {@link CredentialStore}, or `undefined` to fall back\n * to the global store (e.g. tenant storage temporarily unavailable). Must be\n * synchronous — implementations serve from a primed snapshot and do\n * authoritative async work inside `getApiKey`.\n */\nexport type CredentialStoreProvider = (tenant: CredentialTenant) => CredentialStore | undefined;\n\nlet credentialStoreProvider: CredentialStoreProvider | undefined;\n\nconst unavailableTenantCredentialStore: CredentialStore = {\n allowEnvironmentFallback: false,\n reload() {},\n get() {\n return undefined;\n },\n getStoredApiKey() {\n return undefined;\n },\n async getApiKey() {\n return undefined;\n },\n};\n\n/** Register (or clear) the tenant credential store provider. Deployed-web only. */\nexport function setCredentialStoreProvider(provider: CredentialStoreProvider | undefined): void {\n credentialStoreProvider = provider;\n}\n\n/**\n * Whether a tenant provider is registered. Used to disable the\n * `loadStoredApiKeysIntoEnv` side-channel in deployed mode — per-tenant\n * credentials must never leak into process-global env vars.\n */\nexport function hasCredentialStoreProvider(): boolean {\n return credentialStoreProvider !== undefined;\n}\n\n/** Shape the web auth gate stashes on the request context under `user`. */\ninterface RequestContextUser {\n workosId?: string;\n id?: string;\n organizationId?: string;\n /** Trusted server code marks automated runs to resolve org > user credentials. */\n orgFirstCredentials?: boolean;\n}\n\n/**\n * Session-shaped `authenticateToken` results (better-auth) arrive as a wrapper\n * whose active org lives on the session half rather than on the user.\n */\ninterface RequestContextSession {\n user?: RequestContextUser;\n session?: { activeOrganizationId?: string };\n}\n\n/**\n * Whether the request context belongs to a run on a factory-owned session.\n *\n * The agent controller stamps the session's state onto the request context\n * under `controller`, and only trusted factory server code ever writes\n * `factoryProjectId` into session state (board-run creation) — interactive\n * chat sessions never carry it. Runs on such sessions resolve credentials\n * org > user regardless of who sent the message: a board run continued\n * interactively, or a model switch inside it, is still org work.\n */\nfunction isFactorySessionContext(requestContext?: RequestContext): boolean {\n const controller = requestContext?.get('controller') as { state?: { factoryProjectId?: unknown } } | undefined;\n if (!controller || typeof controller !== 'object') return false;\n const factoryProjectId = controller.state?.factoryProjectId;\n return typeof factoryProjectId === 'string' && factoryProjectId.length > 0;\n}\n\n/**\n * Derive the calling tenant from a request context, if an authenticated web\n * user was stashed on it. Mirrors the web layer's stable-id resolution\n * (`workosId` falling back to the provider `id`).\n *\n * The value under `user` is whatever the active auth provider's\n * `authenticateToken` returned, so its shape follows the provider: a flat user\n * (WorkOS) or a `{ session, user }` wrapper (better-auth). Reading only the\n * flat shape resolves no tenant at all for the wrapper, which in deployed mode\n * fails closed to an empty credential store.\n */\nexport function resolveTenantFromRequestContext(requestContext?: RequestContext): CredentialTenant | undefined {\n const raw = requestContext?.get('user') as (RequestContextUser & RequestContextSession) | undefined;\n if (!raw || typeof raw !== 'object') return undefined;\n\n // Precedence matches `toFactoryAuthUser` in `@mastra/factory`: a wrapper's org\n // comes from the session half only, never from the inner user. The two parsers\n // cannot share code across the package boundary, so they must agree by rule.\n const wrapped = Boolean(raw.user && typeof raw.user === 'object' && raw.session && typeof raw.session === 'object');\n const user = wrapped ? (raw.user as RequestContextUser) : raw;\n const orgId = wrapped ? raw.session?.activeOrganizationId : user.organizationId;\n const userId = user.workosId ?? user.id;\n // The slot holds whatever the provider returned, so the declared string\n // types are hopes, not guarantees. A non-string id must refuse the tenant\n // (fail closed), not flow onward as a mistyped key.\n if (typeof userId !== 'string' || !userId) return undefined;\n if (orgId !== undefined && typeof orgId !== 'string') return undefined;\n // Only an exact `true` flips precedence — anything else keeps user > org.\n // Server code stamps the flag on the stashed value itself, so read it from\n // the top level as well as the unwrapped user (better-auth wrapper shape).\n const orgFirst =\n raw.orgFirstCredentials === true || user.orgFirstCredentials === true || isFactorySessionContext(requestContext);\n return { orgId, userId, ...(orgFirst ? { orgFirst } : {}) };\n}\n\n/**\n * Resolve the credential store for a request. Local mode returns `undefined`\n * and keeps the global `AuthStorage` behavior. Once deployed web registers a\n * provider, missing tenant identity or unavailable tenant storage fails closed\n * through an empty store that also disables process-environment fallback.\n */\nexport function resolveCredentialStore(requestContext?: RequestContext): CredentialStore | undefined {\n if (!credentialStoreProvider) return undefined;\n const tenant = resolveTenantFromRequestContext(requestContext);\n if (!tenant) {\n const rawUser = requestContext?.get('user');\n console.warn('[MastraCode] Tenant credential resolution failed closed', {\n reason: rawUser === undefined ? 'missing-user-context' : 'invalid-principal-shape',\n hasRequestContext: requestContext !== undefined,\n factorySession: isFactorySessionContext(requestContext),\n });\n return unavailableTenantCredentialStore;\n }\n const store = credentialStoreProvider(tenant);\n if (!store) {\n console.warn('[MastraCode] Tenant credential resolution failed closed', {\n reason: 'credential-store-unavailable',\n hasOrganization: tenant.orgId !== undefined,\n orgFirst: tenant.orgFirst === true,\n });\n return unavailableTenantCredentialStore;\n }\n return store;\n}\n"],"mappings":";AAuCA,IAAI;AAEJ,MAAM,mCAAoD;CACxD,0BAA0B;CAC1B,SAAS,CAAC;CACV,MAAM,CAEN;CACA,kBAAkB,CAElB;CACA,MAAM,YAAY,CAElB;AACF;;AAGA,SAAgB,2BAA2B,UAAqD;CAC9F,0BAA0B;AAC5B;;;;;;AAOA,SAAgB,6BAAsC;CACpD,OAAO,4BAA4B,KAAA;AACrC;;;;;;;;;;;AA8BA,SAAS,wBAAwB,gBAA0C;CACzE,MAAM,aAAa,gBAAgB,IAAI,YAAY;CACnD,IAAI,CAAC,cAAc,OAAO,eAAe,UAAU,OAAO;CAC1D,MAAM,mBAAmB,WAAW,OAAO;CAC3C,OAAO,OAAO,qBAAqB,YAAY,iBAAiB,SAAS;AAC3E;;;;;;;;;;;;AAaA,SAAgB,gCAAgC,gBAA+D;CAC7G,MAAM,MAAM,gBAAgB,IAAI,MAAM;CACtC,IAAI,CAAC,OAAO,OAAO,QAAQ,UAAU,OAAO,KAAA;CAK5C,MAAM,UAAU,QAAQ,IAAI,QAAQ,OAAO,IAAI,SAAS,YAAY,IAAI,WAAW,OAAO,IAAI,YAAY,QAAQ;CAClH,MAAM,OAAO,UAAW,IAAI,OAA8B;CAC1D,MAAM,QAAQ,UAAU,IAAI,SAAS,uBAAuB,KAAK;CACjE,MAAM,SAAS,KAAK,YAAY,KAAK;CAIrC,IAAI,OAAO,WAAW,YAAY,CAAC,QAAQ,OAAO,KAAA;CAClD,IAAI,UAAU,KAAA,KAAa,OAAO,UAAU,UAAU,OAAO,KAAA;CAI7D,MAAM,WACJ,IA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c,EAAE,EAAE;IAAE,cAAc,EAAE,cAAc,CAAA;CAAE,EACtD,YAAY,CAAC,EAAE,MAAM,GACpB,aAAa,CAoBf;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAgB,iBAAiB,CAC/B,EAAE,cAAc,EAAE,EAAE;IAAE,cAAc,EAAE,cAAc,CAAA;CAAE,EACtD,YAAY,CAAC,EAAE,MAAM,GACpB,aAAa,GAAG,SAAS,CAI3B"}
|
package/dist/agents/model.js
CHANGED
|
@@ -83,6 +83,7 @@ function resolveModel(modelId, options) {
|
|
|
83
83
|
modelId: bareModelId,
|
|
84
84
|
routerId
|
|
85
85
|
});
|
|
86
|
+
if (!auth && credentialStore?.allowEnvironmentFallback === false) throw new Error(`No usable ${providerId} credential is configured for this signed-in Factory account. Connect the provider or add an organization credential, then try again.`);
|
|
86
87
|
return gateway.resolveLanguageModel({
|
|
87
88
|
providerId,
|
|
88
89
|
modelId: bareModelId,
|
package/dist/agents/model.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"model.js","names":[],"sources":["../../src/agents/model.ts"],"sourcesContent":["import type { AgentControllerRequestContext } from '@mastra/core/agent-controller';\nimport type { GatewayLanguageModel, MastraModelGatewayInterface } from '@mastra/core/llm';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport {\n loadSettings,\n resolveDefaultThinkingLevel,\n stripMastraCodeCustomProviderPrefix,\n} from '../onboarding/settings.js';\nimport { AMAZON_BEDROCK_GATEWAY_ID, createAmazonBedrockGateway } from '../providers/amazon-bedrock-gateway.js';\nimport { isThinkingLevelSetting } from '../thinking.js';\nimport type { ThinkingLevelSetting } from '../thinking.js';\nimport { resolveCredentialStore } from './credential-resolver.js';\nimport { resolveCustomProviders } from './custom-provider-source.js';\nimport {\n MASTRA_GATEWAY_PREFIX,\n MASTRACODE_GATEWAY_ID,\n MastraCodeGateway,\n reloadAuthStorage,\n stripMastraGatewayPrefix,\n} from './mastracode-gateway.js';\nimport type { MastraCodeGatewayOptions } from './mastracode-gateway.js';\n\nexport {\n getAnthropicApiKey,\n getOpenAIApiKey,\n MASTRACODE_GATEWAY_ID,\n MastraCodeGateway,\n remapOpenAIModelForCodexOAuth,\n resolveAuth,\n} from './mastracode-gateway.js';\nexport type { MastraCodeCustomProvider, MastraCodeGatewayOptions } from './mastracode-gateway.js';\nexport {\n setCredentialStoreProvider,\n hasCredentialStoreProvider,\n resolveTenantFromRequestContext,\n} from './credential-resolver.js';\nexport type { CredentialTenant, CredentialStoreProvider } from './credential-resolver.js';\nexport {\n setCustomProvidersSource,\n hasCustomProvidersSource,\n resolveCustomProviders,\n} from './custom-provider-source.js';\nexport type { CustomProvidersSource } from './custom-provider-source.js';\n\ntype ResolvedModel = GatewayLanguageModel;\ntype ModelRequestHeaders = Record<string, string>;\n\nfunction getAgentControllerHeaders(requestContext?: RequestContext): ModelRequestHeaders | undefined {\n const agentControllerContext = requestContext?.get('controller') as AgentControllerRequestContext<any> | undefined;\n const headers = {\n ...(agentControllerContext?.threadId ? { 'x-thread-id': agentControllerContext.threadId } : {}),\n ...(agentControllerContext?.resourceId ? { 'x-resource-id': agentControllerContext.resourceId } : {}),\n };\n\n return Object.keys(headers).length > 0 ? headers : undefined;\n}\n\nexport function createMastraCodeGateway(options: MastraCodeGatewayOptions): MastraCodeGateway {\n return new MastraCodeGateway(options);\n}\n\nexport function createMastraCodeModelCatalogProvider(gateway: MastraModelGatewayInterface) {\n return gateway instanceof MastraCodeGateway\n ? gateway.createModelCatalogProvider()\n : MastraCodeGateway.createModelCatalogProvider(gateway);\n}\n\n/**\n * Placeholder for future model ID normalization.\n * Currently returns the input unchanged, but exists as a seam\n * for aliasing, casing fixes, or validation in the future.\n */\nexport function resolveModelId(modelId: string): string {\n return modelId;\n}\n\n/**\n * Resolve a model ID to the correct provider instance.\n * Shared by the main agent, observer, and reflector.\n *\n * - For anthropic/* models: Uses stored OAuth credentials when present, otherwise direct API key\n * - For openai/* models: Uses OAuth when configured, otherwise direct API key from AuthStorage\n * - For moonshotai/* models: Uses Moonshot AI Anthropic-compatible endpoint\n * - For all other providers: Uses Mastra's model router (models.dev gateway)\n */\nexport function resolveModel(\n modelId: string,\n options?: { thinkingLevel?: ThinkingLevelSetting; remapForCodexOAuth?: boolean; requestContext?: RequestContext },\n): GatewayLanguageModel {\n reloadAuthStorage();\n const headers = getAgentControllerHeaders(options?.requestContext);\n const settings = loadSettings();\n // Bedrock was previously cataloged under the MastraCode gateway namespace\n // (`mastracode/amazon-bedrock/<model>`). Normalize any legacy saved ids to the\n // standalone `amazon-bedrock/<model>` form so they resolve through the\n // dedicated Bedrock gateway.\n const bedrockLegacyPrefix = `${MASTRACODE_GATEWAY_ID}/amazon-bedrock/`;\n const bedrockNormalizedInput = modelId.startsWith(bedrockLegacyPrefix)\n ? modelId.slice(MASTRACODE_GATEWAY_ID.length + 1)\n : modelId;\n // Deployed web registers a custom providers source (DB-backed, tenant\n // scoped); when registered it is authoritative and settings.json custom\n // providers are ignored. Undefined = local settings-based behavior.\n const customProviders = resolveCustomProviders(options?.requestContext) ?? settings.customProviders;\n // Ids selected from the shared /models catalog were previously persisted in\n // the gateway-qualified `mastracode/<customProviderId>/<model>` form, which\n // parses the provider as `mastracode` and breaks provider config lookup.\n // Normalize at resolution time (in addition to stripping at selection time)\n // so already-saved ids and any surface that persists the raw catalog id\n // still resolve to the custom provider.\n const normalizedInput = stripMastraCodeCustomProviderPrefix(bedrockNormalizedInput, customProviders);\n const isMastraGatewayModel = normalizedInput.startsWith(MASTRA_GATEWAY_PREFIX);\n const normalizedModelId = stripMastraGatewayPrefix(normalizedInput);\n const [providerId, ...modelParts] = normalizedModelId.split('/');\n const bareModelId = modelParts.join('/');\n if (!providerId || !bareModelId) {\n throw new Error(`Invalid model id: ${modelId}`);\n }\n\n if (providerId === AMAZON_BEDROCK_GATEWAY_ID) {\n const bedrockGateway = createAmazonBedrockGateway();\n const routerId = `${AMAZON_BEDROCK_GATEWAY_ID}/${bareModelId}`;\n const auth = bedrockGateway.resolveAuth({\n gatewayId: AMAZON_BEDROCK_GATEWAY_ID,\n providerId: AMAZON_BEDROCK_GATEWAY_ID,\n modelId: bareModelId,\n routerId,\n });\n return bedrockGateway.resolveLanguageModel({\n providerId: AMAZON_BEDROCK_GATEWAY_ID,\n modelId: bareModelId,\n apiKey: auth?.apiKey ?? '',\n headers,\n });\n }\n\n const routerId = `${MASTRACODE_GATEWAY_ID}/${normalizedModelId}`;\n\n const mgApiKey = MastraCodeGateway.getMastraGatewayApiKey();\n const rawGatewayBase =\n settings.memoryGateway?.baseUrl ?? process.env['MASTRA_GATEWAY_URL'] ?? 'https://gateway-api.mastra.ai';\n // Deployed web registers a per-tenant credential store provider; when the\n // request carries an authenticated tenant, resolve credentials through the\n // caller's own store (user > org > env). Undefined = global AuthStorage.\n const credentialStore = resolveCredentialStore(options?.requestContext);\n const gateway = createMastraCodeGateway({\n mastraGatewayBaseUrl: rawGatewayBase.replace(/\\/+$/, '').replace(/\\/v1$/, ''),\n mastraGatewayApiKey: mgApiKey,\n routeThroughMastraGateway: Boolean(mgApiKey && isMastraGatewayModel),\n thinkingLevel: options?.thinkingLevel,\n customProviders,\n credentialStore,\n });\n\n const auth = gateway.resolveAuth({\n gatewayId: MASTRACODE_GATEWAY_ID,\n providerId,\n modelId: bareModelId,\n routerId,\n });\n\n return gateway.resolveLanguageModel({\n providerId,\n modelId: bareModelId,\n apiKey: auth?.apiKey ?? '',\n headers,\n });\n}\n\nexport interface ThinkingRequestContext {\n state?: { thinkingLevel?: unknown };\n session?: { modeId?: string };\n}\n/**\n * Resolve the effective thinking level for the current request.\n *\n * Precedence:\n * 1. Session override (`state.thinkingLevel`, set via /think or the session\n * settings panel).\n * 2. Per-mode default from settings (`models.modeThinkingDefaults[mode]`).\n * 3. Global default (`preferences.thinkingLevel`).\n *\n * Resolved per-request (not seeded at session start) so configuration changes\n * apply to the next request of every session — including automated\n * (rule-driven) Factory runs that nobody ever opens interactively.\n */\n\nexport function resolveRequestThinkingLevel(\n agentControllerContext: ThinkingRequestContext | undefined,\n settingsPath?: string,\n): ThinkingLevelSetting {\n const override = agentControllerContext?.state?.thinkingLevel;\n if (isThinkingLevelSetting(override)) return override;\n const modeId = agentControllerContext?.session?.modeId;\n return resolveDefaultThinkingLevel(loadSettings(settingsPath), modeId).level;\n}\n\n/**\n * Dynamic model function that reads the current model from controller state.\n * This allows runtime model switching via the /models picker.\n */\nexport function getDynamicModel(\n { requestContext }: { requestContext: RequestContext },\n settingsPath?: string,\n): ResolvedModel {\n const agentControllerContext = requestContext.get('controller') as AgentControllerRequestContext<any> | undefined;\n\n const modelId = agentControllerContext?.session?.modelId;\n if (!modelId) {\n // A missing controller context means the run was started without session\n // request context at all (e.g. a signal delivered to an idle thread) —\n // \"use /models\" would mislead there, the user's selection was never the\n // problem.\n if (!agentControllerContext) {\n throw new Error(\n 'No model available: this run started without a controller session context, so no model selection could be resolved.',\n );\n }\n throw new Error('No model selected. Use /models to select a model first.');\n }\n\n const thinkingLevel = resolveRequestThinkingLevel(agentControllerContext, settingsPath);\n\n return resolveModel(modelId, { thinkingLevel, remapForCodexOAuth: true, requestContext });\n}\n\n/**\n * Goal judge model resolver for the agent's `goal.judge` config. Resolves the\n * configured goal judge model through mastracode's gateway so provider\n * credentials (stored in auth storage, not just env) are injected — a bare model\n * id handed to core's default model router would fail to find the API key.\n *\n * Returns `undefined` when no judge model is configured, which keeps the goal\n * step a complete no-op (the goal mechanism requires a judge to do anything).\n *\n * `settingsPath` must be the same source `createMastraCode()` reads from so the\n * judge model and the goal budget (`goalMaxTurns`) come from one config — with a\n * custom `settingsPath` a bare `loadSettings()` here could read a different file\n * and silently turn the goal step into a no-op.\n */\nexport function getGoalJudgeModel(\n { requestContext }: { requestContext: RequestContext },\n settingsPath?: string,\n): ResolvedModel | undefined {\n const judgeModelId = loadSettings(settingsPath).models.goalJudgeModel;\n if (!judgeModelId) return undefined;\n return resolveModel(judgeModelId, { remapForCodexOAuth: true, requestContext });\n}\n"],"mappings":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;;;;;;;;;;;AAgBA,SAAgB,kBACd,EAAE,kBACF,cAC2B;CAC3B,MAAM,eAAe,aAAa,YAAY,CAAC,CAAC,OAAO;CACvD,IAAI,CAAC,cAAc,OAAO,KAAA;CAC1B,OAAO,aAAa,cAAc;EAAE,oBAAoB;EAAM;CAAe,CAAC;AAChF"}
|
|
1
|
+
{"version":3,"file":"model.js","names":[],"sources":["../../src/agents/model.ts"],"sourcesContent":["import type { AgentControllerRequestContext } from '@mastra/core/agent-controller';\nimport type { GatewayLanguageModel, MastraModelGatewayInterface } from '@mastra/core/llm';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport {\n loadSettings,\n resolveDefaultThinkingLevel,\n stripMastraCodeCustomProviderPrefix,\n} from '../onboarding/settings.js';\nimport { AMAZON_BEDROCK_GATEWAY_ID, createAmazonBedrockGateway } from '../providers/amazon-bedrock-gateway.js';\nimport { isThinkingLevelSetting } from '../thinking.js';\nimport type { ThinkingLevelSetting } from '../thinking.js';\nimport { resolveCredentialStore } from './credential-resolver.js';\nimport { resolveCustomProviders } from './custom-provider-source.js';\nimport {\n MASTRA_GATEWAY_PREFIX,\n MASTRACODE_GATEWAY_ID,\n MastraCodeGateway,\n reloadAuthStorage,\n stripMastraGatewayPrefix,\n} from './mastracode-gateway.js';\nimport type { MastraCodeGatewayOptions } from './mastracode-gateway.js';\n\nexport {\n getAnthropicApiKey,\n getOpenAIApiKey,\n MASTRACODE_GATEWAY_ID,\n MastraCodeGateway,\n remapOpenAIModelForCodexOAuth,\n resolveAuth,\n} from './mastracode-gateway.js';\nexport type { MastraCodeCustomProvider, MastraCodeGatewayOptions } from './mastracode-gateway.js';\nexport {\n setCredentialStoreProvider,\n hasCredentialStoreProvider,\n resolveTenantFromRequestContext,\n} from './credential-resolver.js';\nexport type { CredentialTenant, CredentialStoreProvider } from './credential-resolver.js';\nexport {\n setCustomProvidersSource,\n hasCustomProvidersSource,\n resolveCustomProviders,\n} from './custom-provider-source.js';\nexport type { CustomProvidersSource } from './custom-provider-source.js';\n\ntype ResolvedModel = GatewayLanguageModel;\ntype ModelRequestHeaders = Record<string, string>;\n\nfunction getAgentControllerHeaders(requestContext?: RequestContext): ModelRequestHeaders | undefined {\n const agentControllerContext = requestContext?.get('controller') as AgentControllerRequestContext<any> | undefined;\n const headers = {\n ...(agentControllerContext?.threadId ? { 'x-thread-id': agentControllerContext.threadId } : {}),\n ...(agentControllerContext?.resourceId ? { 'x-resource-id': agentControllerContext.resourceId } : {}),\n };\n\n return Object.keys(headers).length > 0 ? headers : undefined;\n}\n\nexport function createMastraCodeGateway(options: MastraCodeGatewayOptions): MastraCodeGateway {\n return new MastraCodeGateway(options);\n}\n\nexport function createMastraCodeModelCatalogProvider(gateway: MastraModelGatewayInterface) {\n return gateway instanceof MastraCodeGateway\n ? gateway.createModelCatalogProvider()\n : MastraCodeGateway.createModelCatalogProvider(gateway);\n}\n\n/**\n * Placeholder for future model ID normalization.\n * Currently returns the input unchanged, but exists as a seam\n * for aliasing, casing fixes, or validation in the future.\n */\nexport function resolveModelId(modelId: string): string {\n return modelId;\n}\n\n/**\n * Resolve a model ID to the correct provider instance.\n * Shared by the main agent, observer, and reflector.\n *\n * - For anthropic/* models: Uses stored OAuth credentials when present, otherwise direct API key\n * - For openai/* models: Uses OAuth when configured, otherwise direct API key from AuthStorage\n * - For moonshotai/* models: Uses Moonshot AI Anthropic-compatible endpoint\n * - For all other providers: Uses Mastra's model router (models.dev gateway)\n */\nexport function resolveModel(\n modelId: string,\n options?: { thinkingLevel?: ThinkingLevelSetting; remapForCodexOAuth?: boolean; requestContext?: RequestContext },\n): GatewayLanguageModel {\n reloadAuthStorage();\n const headers = getAgentControllerHeaders(options?.requestContext);\n const settings = loadSettings();\n // Bedrock was previously cataloged under the MastraCode gateway namespace\n // (`mastracode/amazon-bedrock/<model>`). Normalize any legacy saved ids to the\n // standalone `amazon-bedrock/<model>` form so they resolve through the\n // dedicated Bedrock gateway.\n const bedrockLegacyPrefix = `${MASTRACODE_GATEWAY_ID}/amazon-bedrock/`;\n const bedrockNormalizedInput = modelId.startsWith(bedrockLegacyPrefix)\n ? modelId.slice(MASTRACODE_GATEWAY_ID.length + 1)\n : modelId;\n // Deployed web registers a custom providers source (DB-backed, tenant\n // scoped); when registered it is authoritative and settings.json custom\n // providers are ignored. Undefined = local settings-based behavior.\n const customProviders = resolveCustomProviders(options?.requestContext) ?? settings.customProviders;\n // Ids selected from the shared /models catalog were previously persisted in\n // the gateway-qualified `mastracode/<customProviderId>/<model>` form, which\n // parses the provider as `mastracode` and breaks provider config lookup.\n // Normalize at resolution time (in addition to stripping at selection time)\n // so already-saved ids and any surface that persists the raw catalog id\n // still resolve to the custom provider.\n const normalizedInput = stripMastraCodeCustomProviderPrefix(bedrockNormalizedInput, customProviders);\n const isMastraGatewayModel = normalizedInput.startsWith(MASTRA_GATEWAY_PREFIX);\n const normalizedModelId = stripMastraGatewayPrefix(normalizedInput);\n const [providerId, ...modelParts] = normalizedModelId.split('/');\n const bareModelId = modelParts.join('/');\n if (!providerId || !bareModelId) {\n throw new Error(`Invalid model id: ${modelId}`);\n }\n\n if (providerId === AMAZON_BEDROCK_GATEWAY_ID) {\n const bedrockGateway = createAmazonBedrockGateway();\n const routerId = `${AMAZON_BEDROCK_GATEWAY_ID}/${bareModelId}`;\n const auth = bedrockGateway.resolveAuth({\n gatewayId: AMAZON_BEDROCK_GATEWAY_ID,\n providerId: AMAZON_BEDROCK_GATEWAY_ID,\n modelId: bareModelId,\n routerId,\n });\n return bedrockGateway.resolveLanguageModel({\n providerId: AMAZON_BEDROCK_GATEWAY_ID,\n modelId: bareModelId,\n apiKey: auth?.apiKey ?? '',\n headers,\n });\n }\n\n const routerId = `${MASTRACODE_GATEWAY_ID}/${normalizedModelId}`;\n\n const mgApiKey = MastraCodeGateway.getMastraGatewayApiKey();\n const rawGatewayBase =\n settings.memoryGateway?.baseUrl ?? process.env['MASTRA_GATEWAY_URL'] ?? 'https://gateway-api.mastra.ai';\n // Deployed web registers a per-tenant credential store provider; when the\n // request carries an authenticated tenant, resolve credentials through the\n // caller's own store (user > org > env). Undefined = global AuthStorage.\n const credentialStore = resolveCredentialStore(options?.requestContext);\n const gateway = createMastraCodeGateway({\n mastraGatewayBaseUrl: rawGatewayBase.replace(/\\/+$/, '').replace(/\\/v1$/, ''),\n mastraGatewayApiKey: mgApiKey,\n routeThroughMastraGateway: Boolean(mgApiKey && isMastraGatewayModel),\n thinkingLevel: options?.thinkingLevel,\n customProviders,\n credentialStore,\n });\n\n const auth = gateway.resolveAuth({\n gatewayId: MASTRACODE_GATEWAY_ID,\n providerId,\n modelId: bareModelId,\n routerId,\n });\n\n if (!auth && credentialStore?.allowEnvironmentFallback === false) {\n throw new Error(\n `No usable ${providerId} credential is configured for this signed-in Factory account. Connect the provider or add an organization credential, then try again.`,\n );\n }\n\n return gateway.resolveLanguageModel({\n providerId,\n modelId: bareModelId,\n apiKey: auth?.apiKey ?? '',\n headers,\n });\n}\n\nexport interface ThinkingRequestContext {\n state?: { thinkingLevel?: unknown };\n session?: { modeId?: string };\n}\n/**\n * Resolve the effective thinking level for the current request.\n *\n * Precedence:\n * 1. Session override (`state.thinkingLevel`, set via /think or the session\n * settings panel).\n * 2. Per-mode default from settings (`models.modeThinkingDefaults[mode]`).\n * 3. Global default (`preferences.thinkingLevel`).\n *\n * Resolved per-request (not seeded at session start) so configuration changes\n * apply to the next request of every session — including automated\n * (rule-driven) Factory runs that nobody ever opens interactively.\n */\n\nexport function resolveRequestThinkingLevel(\n agentControllerContext: ThinkingRequestContext | undefined,\n settingsPath?: string,\n): ThinkingLevelSetting {\n const override = agentControllerContext?.state?.thinkingLevel;\n if (isThinkingLevelSetting(override)) return override;\n const modeId = agentControllerContext?.session?.modeId;\n return resolveDefaultThinkingLevel(loadSettings(settingsPath), modeId).level;\n}\n\n/**\n * Dynamic model function that reads the current model from controller state.\n * This allows runtime model switching via the /models picker.\n */\nexport function getDynamicModel(\n { requestContext }: { requestContext: RequestContext },\n settingsPath?: string,\n): ResolvedModel {\n const agentControllerContext = requestContext.get('controller') as AgentControllerRequestContext<any> | undefined;\n\n const modelId = agentControllerContext?.session?.modelId;\n if (!modelId) {\n // A missing controller context means the run was started without session\n // request context at all (e.g. a signal delivered to an idle thread) —\n // \"use /models\" would mislead there, the user's selection was never the\n // problem.\n if (!agentControllerContext) {\n throw new Error(\n 'No model available: this run started without a controller session context, so no model selection could be resolved.',\n );\n }\n throw new Error('No model selected. Use /models to select a model first.');\n }\n\n const thinkingLevel = resolveRequestThinkingLevel(agentControllerContext, settingsPath);\n\n return resolveModel(modelId, { thinkingLevel, remapForCodexOAuth: true, requestContext });\n}\n\n/**\n * Goal judge model resolver for the agent's `goal.judge` config. Resolves the\n * configured goal judge model through mastracode's gateway so provider\n * credentials (stored in auth storage, not just env) are injected — a bare model\n * id handed to core's default model router would fail to find the API key.\n *\n * Returns `undefined` when no judge model is configured, which keeps the goal\n * step a complete no-op (the goal mechanism requires a judge to do anything).\n *\n * `settingsPath` must be the same source `createMastraCode()` reads from so the\n * judge model and the goal budget (`goalMaxTurns`) come from one config — with a\n * custom `settingsPath` a bare `loadSettings()` here could read a different file\n * and silently turn the goal step into a no-op.\n */\nexport function getGoalJudgeModel(\n { requestContext }: { requestContext: RequestContext },\n settingsPath?: string,\n): ResolvedModel | undefined {\n const judgeModelId = loadSettings(settingsPath).models.goalJudgeModel;\n if (!judgeModelId) return undefined;\n return resolveModel(judgeModelId, { remapForCodexOAuth: true, requestContext });\n}\n"],"mappings":";;;;;;;AA+CA,SAAS,0BAA0B,gBAAkE;CACnG,MAAM,yBAAyB,gBAAgB,IAAI,YAAY;CAC/D,MAAM,UAAU;EACd,GAAI,wBAAwB,WAAW,EAAE,eAAe,uBAAuB,SAAS,IAAI,CAAC;EAC7F,GAAI,wBAAwB,aAAa,EAAE,iBAAiB,uBAAuB,WAAW,IAAI,CAAC;CACrG;CAEA,OAAO,OAAO,KAAK,OAAO,CAAC,CAAC,SAAS,IAAI,UAAU,KAAA;AACrD;AA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 -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mastra/code-sdk",
|
|
3
|
-
"version": "1.6.0-alpha.
|
|
3
|
+
"version": "1.6.0-alpha.3",
|
|
4
4
|
"description": "Mastra Code SDK: the agent core behind Mastra Code (everything except the TUI) — build your own UIs and surfaces on top of it",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"publishConfig": {
|
|
@@ -58,19 +58,19 @@
|
|
|
58
58
|
"yaml": "^2.7.1",
|
|
59
59
|
"zod": "^4.3.6",
|
|
60
60
|
"@mastra/agent-browser": "0.5.1",
|
|
61
|
-
"@mastra/duckdb": "1.6.3",
|
|
62
61
|
"@mastra/core": "1.63.3-alpha.1",
|
|
62
|
+
"@mastra/fastembed": "1.3.0",
|
|
63
|
+
"@mastra/duckdb": "1.6.3",
|
|
64
|
+
"@mastra/mcp": "1.17.2",
|
|
63
65
|
"@mastra/libsql": "1.22.2",
|
|
64
66
|
"@mastra/github-signals": "0.4.0-alpha.0",
|
|
65
|
-
"@mastra/mcp": "1.17.2",
|
|
66
67
|
"@mastra/observability": "1.17.4",
|
|
67
|
-
"@mastra/memory": "1.28.2-alpha.0",
|
|
68
68
|
"@mastra/parallel": "0.1.0",
|
|
69
|
-
"@mastra/schema-compat": "1.3.7",
|
|
70
69
|
"@mastra/pg": "1.22.2",
|
|
71
70
|
"@mastra/stagehand": "0.3.3",
|
|
72
71
|
"@mastra/tavily": "1.1.1",
|
|
73
|
-
"@mastra/
|
|
72
|
+
"@mastra/schema-compat": "1.3.7",
|
|
73
|
+
"@mastra/memory": "1.28.2-alpha.0"
|
|
74
74
|
},
|
|
75
75
|
"devDependencies": {
|
|
76
76
|
"@libsql/client": "^0.17.4",
|