@mastra/code-sdk 1.19.0-alpha.0 → 1.19.0-alpha.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agents/mastracode-gateway.d.ts +1 -0
- package/dist/agents/mastracode-gateway.d.ts.map +1 -1
- package/dist/agents/mastracode-gateway.js +7 -3
- package/dist/agents/mastracode-gateway.js.map +1 -1
- package/dist/voice/stt-registry.d.ts +6 -3
- package/dist/voice/stt-registry.d.ts.map +1 -1
- package/dist/voice/stt-registry.js +13 -10
- package/dist/voice/stt-registry.js.map +1 -1
- package/dist/voice/transcribe.d.ts +10 -0
- package/dist/voice/transcribe.d.ts.map +1 -0
- package/dist/voice/transcribe.js +77 -0
- package/dist/voice/transcribe.js.map +1 -0
- package/package.json +11 -8
|
@@ -42,6 +42,7 @@ export declare function getAnthropicApiKey(credentials?: CredentialStore): strin
|
|
|
42
42
|
*/
|
|
43
43
|
export declare function getOpenAIApiKey(credentials?: CredentialStore): string | undefined;
|
|
44
44
|
export declare function resolveAuth(request: GatewayAuthRequest, mastraGatewayApiKey?: string): GatewayAuthResult | undefined;
|
|
45
|
+
export declare function providerApiKeyEnvVar(providerId: string): string | undefined;
|
|
45
46
|
/**
|
|
46
47
|
* Whether the process environment has a key for a models.dev provider. Checks every
|
|
47
48
|
* env var the registry lists, as the models.dev gateway does when `resolveModel`
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mastracode-gateway.d.ts","sourceRoot":"","sources":["../../src/agents/mastracode-gateway.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAwB,0BAA0B,EAAE,MAAM,+BAA+B,CAAC;AACtG,OAAO,EAGL,kBAAkB,EAGnB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,KAAK,EACV,kBAAkB,EAClB,iBAAiB,EACjB,oBAAoB,EACpB,2BAA2B,EAC3B,cAAc,EACf,MAAM,kBAAkB,CAAC;AAE1B,OAAO,EAAE,WAAW,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kB,EAC3B,mBAAmB,CAAC,EAAE,MAAM,EAC5B,WAAW,GAAE,eAAwC,GACpD,iBAAiB,GAAG,SAAS,CAa/B;IAED,MAAM,CAAC,0BAA0B,CAAC,OAAO,EAAE,2BAA2B,GAAG,0BAA0B,CA6BlG;IAED,0BAA0B,IAAI,0BAA0B,CAEvD;IASK,cAAc,IAAI,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,cAAc,CAAC,CAAC,CAwB9D;IAED,QAAQ,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,GAAG,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAE1E;IAEK,SAAS,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAIhD;IAED,WAAW,CAAC,OAAO,EAAE,kBAAkB,GAAG,iBAAiB,GAAG,SAAS,CAatE;IAED,oBAAoB,CAAC,IAAI,EAAE;QACzB,OAAO,EAAE,MAAM,CAAC;QAChB,UAAU,EAAE,MAAM,CAAC;QACnB,MAAM,EAAE,MAAM,CAAC;QACf,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;QACjC,SAAS,CAAC,EAAE,GAAG,CAAC;QAChB,kBAAkB,CAAC,EAAE,GAAG,CAAC;KAC1B,GAAG,oBAAoB,CAiFvB;CAyJF"}
|
|
@@ -16,6 +16,7 @@ import { wrapLanguageModel } from "ai";
|
|
|
16
16
|
import { createAnthropic } from "@ai-sdk/anthropic";
|
|
17
17
|
import { createOpenAICompatible } from "@ai-sdk/openai-compatible";
|
|
18
18
|
// src/agents/mastracode-gateway.ts
|
|
19
|
+
const PROVIDERS = PROVIDER_REGISTRY;
|
|
19
20
|
const MASTRACODE_GATEWAY_ID = "mastracode";
|
|
20
21
|
/**
|
|
21
22
|
* Global file-backed credential store for local (TUI) model resolution.
|
|
@@ -138,7 +139,7 @@ async function resolveGatewayProviderAuth(gateway, routerId) {
|
|
|
138
139
|
}
|
|
139
140
|
}
|
|
140
141
|
async function getMastraCodeProviderConfigs(gateway) {
|
|
141
|
-
const providers = { ...
|
|
142
|
+
const providers = { ...PROVIDERS };
|
|
142
143
|
try {
|
|
143
144
|
const gatewayProviders = await gateway.fetchProviders();
|
|
144
145
|
for (const [providerId, config] of Object.entries(gatewayProviders)) providers[getGatewayProviderKey(gateway.id, providerId)] = {
|
|
@@ -154,13 +155,16 @@ function getApiKeyEnvVar(providerConfig) {
|
|
|
154
155
|
const envVars = providerConfig?.apiKeyEnvVar;
|
|
155
156
|
return Array.isArray(envVars) ? envVars[0] : envVars;
|
|
156
157
|
}
|
|
158
|
+
function providerApiKeyEnvVar(providerId) {
|
|
159
|
+
return getApiKeyEnvVar(PROVIDERS[providerId]);
|
|
160
|
+
}
|
|
157
161
|
/**
|
|
158
162
|
* Whether the process environment has a key for a models.dev provider. Checks every
|
|
159
163
|
* env var the registry lists, as the models.dev gateway does when `resolveModel`
|
|
160
164
|
* gets no gateway credential (e.g. `GOOGLE_API_KEY` or `GOOGLE_GENERATIVE_AI_API_KEY`).
|
|
161
165
|
*/
|
|
162
166
|
function hasProviderEnvironmentKey(providerId) {
|
|
163
|
-
const envVars =
|
|
167
|
+
const envVars = PROVIDERS[providerId]?.apiKeyEnvVar;
|
|
164
168
|
if (!envVars) return false;
|
|
165
169
|
return (Array.isArray(envVars) ? envVars : [envVars]).some((envVar) => Boolean(process.env[envVar]?.trim()));
|
|
166
170
|
}
|
|
@@ -448,6 +452,6 @@ var MastraCodeGateway = class MastraCodeGateway extends MastraModelGateway {
|
|
|
448
452
|
});
|
|
449
453
|
}
|
|
450
454
|
};
|
|
451
|
-
export { MASTRACODE_GATEWAY_ID, MASTRA_GATEWAY_PREFIX, MastraCodeGateway, OPENAI_PREFIX, getAnthropicApiKey, getGlobalAuthStorage, getOpenAIApiKey, hasProviderEnvironmentKey, reloadAuthStorage, remapOpenAIModelForCodexOAuth, resolveAuth, stripMastraGatewayPrefix };
|
|
455
|
+
export { MASTRACODE_GATEWAY_ID, MASTRA_GATEWAY_PREFIX, MastraCodeGateway, OPENAI_PREFIX, getAnthropicApiKey, getGlobalAuthStorage, getOpenAIApiKey, hasProviderEnvironmentKey, providerApiKeyEnvVar, reloadAuthStorage, remapOpenAIModelForCodexOAuth, resolveAuth, stripMastraGatewayPrefix };
|
|
452
456
|
|
|
453
457
|
//# sourceMappingURL=mastracode-gateway.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mastracode-gateway.js","names":[],"sources":["../../src/agents/mastracode-gateway.ts"],"sourcesContent":["import { createAnthropic } from '@ai-sdk/anthropic';\nimport { createOpenAI } from '@ai-sdk/openai';\nimport { createOpenAICompatible } from '@ai-sdk/openai-compatible';\nimport type { CustomAvailableModel, CustomModelCatalogProvider } from '@mastra/core/agent-controller';\nimport {\n GATEWAY_AUTH_HEADER,\n MastraGateway,\n MastraModelGateway,\n ModelRouterLanguageModel,\n PROVIDER_REGISTRY,\n} from '@mastra/core/llm';\nimport type {\n GatewayAuthRequest,\n GatewayAuthResult,\n GatewayLanguageModel,\n MastraModelGatewayInterface,\n ProviderConfig,\n} from '@mastra/core/llm';\nimport { wrapLanguageModel } from 'ai';\nimport { AuthStorage } from '../auth/storage.js';\nimport type { CredentialStore } from '../auth/types.js';\nimport { getCustomProviderId, loadSettings, MASTRA_GATEWAY_PROVIDER } from '../onboarding/settings.js';\nimport type { AnthropicPromptCacheScope } from '../providers/anthropic-prompt-cache.js';\nimport {\n buildAnthropicOAuthFetch,\n claudeCodeMiddleware,\n createAnthropicThinkingMiddleware,\n createPromptCacheMiddleware,\n opencodeClaudeMaxProvider,\n} from '../providers/claude-max.js';\nimport { githubCopilotProvider } from '../providers/github-copilot.js';\nimport { createGoogleThinkingMiddleware } from '../providers/google-thinking.js';\nimport { kimiCodingProvider } from '../providers/kimi-coding.js';\nimport {\n getCredentialProviderId,\n KIMI_CODING_CREDENTIAL_ID,\n KIMI_CODING_PROVIDER_ID,\n normalizeAnthropicModelId,\n OPENAI_PREFIX,\n remapOpenAIModelForCodexOAuth,\n stripMastraGatewayPrefix,\n} from '../providers/model-ids.js';\nimport {\n buildOpenAICodexOAuthFetch,\n createCodexMiddleware,\n createPromptCacheKeyMiddleware,\n createReasoningEffortMiddleware,\n getEffectiveThinkingLevel,\n getRequestThreadId,\n openaiCodexProvider,\n THINKING_LEVEL_TO_REASONING_EFFORT,\n} from '../providers/openai-codex.js';\nimport type { ThinkingLevel } from '../providers/openai-codex.js';\nimport {\n ModelRouterLanguageModelWithThinking,\n providerThinkingOptions,\n withThinkingOptionsModel,\n} from '../providers/provider-thinking.js';\nimport { xaiProvider } from '../providers/xai.js';\nimport { getAppDataDir } from '../utils/project.js';\nimport { resolveCustomProviders } from './custom-provider-source.js';\n\nexport {\n MASTRA_GATEWAY_PREFIX,\n OPENAI_PREFIX,\n remapOpenAIModelForCodexOAuth,\n stripMastraGatewayPrefix,\n} from '../providers/model-ids.js';\n\nexport const MASTRACODE_GATEWAY_ID = 'mastracode';\n\ntype ModelRequestHeaders = Record<string, string>;\n\nexport type MastraCodeCustomProvider = { name: string; url: string; apiKey?: string; models?: string[] };\n\nexport type MastraCodeGatewayOptions = {\n mastraGatewayBaseUrl: string;\n mastraGatewayApiKey?: string;\n routeThroughMastraGateway: boolean;\n thinkingLevel?: ThinkingLevel;\n /** Anthropic prompt-cache breakpoints to write. Defaults to `conversation`. */\n anthropicPromptCacheScope?: AnthropicPromptCacheScope;\n customProviders?: MastraCodeCustomProvider[];\n settingsPath?: string;\n /**\n * Per-tenant credential source for this gateway instance. Defaults to the\n * server-global file-backed `AuthStorage`; deployed web passes the calling\n * tenant's store so model calls use the caller's own credentials.\n */\n credentialStore?: CredentialStore;\n};\n\n/**\n * Global file-backed credential store for local (TUI) model resolution.\n *\n * Constructed lazily, NOT at module scope: `AuthStorage`'s default path is\n * resolved from `MASTRA_APP_DATA_DIR` at construction, and this module is\n * routinely imported before test harnesses / embedders point that variable at\n * an isolated directory — an import-time construction would permanently pin\n * the developer's real app-data dir for every credential read.\n */\nlet authStorageSingleton: AuthStorage | undefined;\nlet authStorageSingletonDir: string | undefined;\n\nexport function getGlobalAuthStorage(): AuthStorage {\n // Keyed by the resolved app-data dir: in-process harnesses re-point\n // MASTRA_APP_DATA_DIR per run inside one long-lived worker, so a store\n // pinned to a previous dir must be discarded, not reused.\n const dir = getAppDataDir();\n if (!authStorageSingleton || authStorageSingletonDir !== dir) {\n authStorageSingleton = new AuthStorage();\n authStorageSingletonDir = dir;\n }\n return authStorageSingleton;\n}\n\nexport function reloadAuthStorage() {\n getGlobalAuthStorage().reload();\n}\n\n/**\n * Resolve the Anthropic API key.\n * Main slot → dedicated apikey: slot → env var.\n */\nexport function getAnthropicApiKey(credentials: CredentialStore = getGlobalAuthStorage()): string | undefined {\n const storedCred = credentials.get('anthropic');\n if (storedCred?.type === 'api_key' && storedCred.key.trim().length > 0) {\n return storedCred.key.trim();\n }\n const dedicatedKey = credentials.getStoredApiKey('anthropic')?.trim();\n if (dedicatedKey) return dedicatedKey;\n return credentials.allowEnvironmentFallback === false\n ? undefined\n : process.env.ANTHROPIC_API_KEY?.trim() || undefined;\n}\n\n/**\n * Resolve the OpenAI API key.\n * Main slot → dedicated apikey: slot → env var.\n */\nexport function getOpenAIApiKey(credentials: CredentialStore = getGlobalAuthStorage()): string | undefined {\n const storedCred = credentials.get('openai-codex');\n if (storedCred?.type === 'api_key' && storedCred.key.trim().length > 0) {\n return storedCred.key.trim();\n }\n const dedicatedKey = credentials.getStoredApiKey('openai-codex')?.trim();\n if (dedicatedKey) return dedicatedKey;\n return credentials.allowEnvironmentFallback === false ? undefined : process.env.OPENAI_API_KEY?.trim() || undefined;\n}\n\nfunction anthropicApiKeyProvider(\n modelId: string,\n apiKey: string,\n headers: ModelRequestHeaders | undefined,\n thinkingLevel: ThinkingLevel | undefined,\n promptCacheScope: AnthropicPromptCacheScope,\n) {\n const anthropic = createAnthropic({ apiKey, headers });\n const thinkingMiddleware = createAnthropicThinkingMiddleware(modelId, thinkingLevel);\n return wrapLanguageModel({\n model: anthropic(modelId),\n middleware: [createPromptCacheMiddleware(promptCacheScope), ...(thinkingMiddleware ? [thinkingMiddleware] : [])],\n });\n}\n\nfunction openaiApiKeyProvider(\n modelId: string,\n apiKey: string,\n headers?: ModelRequestHeaders,\n thinkingLevel?: ThinkingLevel,\n) {\n const openai = createOpenAI({ apiKey, baseURL: process.env.OPENAI_BASE_URL, headers });\n const middleware =\n thinkingLevel && thinkingLevel !== 'off'\n ? createReasoningEffortMiddleware(\n 'openai',\n THINKING_LEVEL_TO_REASONING_EFFORT[getEffectiveThinkingLevel(modelId, thinkingLevel)],\n )\n : undefined;\n const promptCacheKeyMiddleware = createPromptCacheKeyMiddleware(getRequestThreadId(headers));\n return wrapLanguageModel({\n model: openai.responses(modelId),\n middleware: [...(middleware ? [middleware] : []), ...(promptCacheKeyMiddleware ? [promptCacheKeyMiddleware] : [])],\n });\n}\n\nfunction getProviderAuthKey(\n providerId: string,\n credentials: CredentialStore = getGlobalAuthStorage(),\n): string | undefined {\n const authProviderId = getCredentialProviderId(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 // `/api-keys` stores keys under the catalog provider id (`kimi-code-plan-cn`),\n // which can differ from the credential id.\n const catalogKey = authProviderId !== providerId ? credentials.getStoredApiKey(providerId)?.trim() : undefined;\n if (catalogKey) return catalogKey;\n if (credentials.allowEnvironmentFallback === false) return undefined;\n return authProviderId === KIMI_CODING_CREDENTIAL_ID ? 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\n/**\n * Whether the process environment has a key for a models.dev provider. Checks every\n * env var the registry lists, as the models.dev gateway does when `resolveModel`\n * gets no gateway credential (e.g. `GOOGLE_API_KEY` or `GOOGLE_GENERATIVE_AI_API_KEY`).\n */\nexport function hasProviderEnvironmentKey(providerId: string): boolean {\n const envVars = (PROVIDER_REGISTRY as Record<string, ProviderConfig>)[providerId]?.apiKeyEnvVar;\n if (!envVars) return false;\n return (Array.isArray(envVars) ? envVars : [envVars]).some(envVar => Boolean(process.env[envVar]?.trim()));\n}\n\nexport class MastraCodeGateway extends MastraModelGateway {\n readonly id = MASTRACODE_GATEWAY_ID;\n readonly name = 'MastraCode Gateway';\n\n readonly #mastraGateway: MastraGateway;\n readonly #mastraGatewayBaseUrl: string;\n readonly #mastraGatewayApiKey?: string;\n readonly #routeThroughMastraGateway: boolean;\n readonly #thinkingLevel?: ThinkingLevel;\n readonly #anthropicPromptCacheScope: AnthropicPromptCacheScope;\n readonly #customProviders?: MastraCodeCustomProvider[];\n readonly #settingsPath?: string;\n readonly #credentials: CredentialStore;\n\n constructor({\n mastraGatewayBaseUrl,\n mastraGatewayApiKey,\n routeThroughMastraGateway,\n thinkingLevel,\n anthropicPromptCacheScope,\n customProviders,\n settingsPath,\n credentialStore,\n }: MastraCodeGatewayOptions) {\n super();\n this.#mastraGateway = new MastraGateway({ baseUrl: mastraGatewayBaseUrl });\n this.#mastraGatewayBaseUrl = mastraGatewayBaseUrl;\n this.#mastraGatewayApiKey = mastraGatewayApiKey;\n this.#routeThroughMastraGateway = routeThroughMastraGateway;\n this.#thinkingLevel = thinkingLevel;\n this.#anthropicPromptCacheScope = anthropicPromptCacheScope ?? 'conversation';\n this.#customProviders = customProviders;\n this.#settingsPath = settingsPath;\n this.#credentials = credentialStore ?? getGlobalAuthStorage();\n }\n\n static getMastraGatewayApiKey(): string | undefined {\n return getGlobalAuthStorage().getStoredApiKey(MASTRA_GATEWAY_PROVIDER) ?? process.env['MASTRA_GATEWAY_API_KEY'];\n }\n\n /** @deprecated Renamed to {@link MastraCodeGateway.getMastraGatewayApiKey}. */\n static getMemoryGatewayApiKey(): string | undefined {\n return MastraCodeGateway.getMastraGatewayApiKey();\n }\n\n /**\n * Claim an unprefixed model id (e.g. a bare `anthropic/...`) when this gateway\n * can authenticate it via OAuth or a stored/env credential. This lets the\n * shared gateway router select MastraCode for auth resolution, so the status\n * bar and `/api-keys` reflect OAuth logins instead of only checking env vars.\n */\n handlesModel(modelId: string): boolean {\n const parsed = parseGatewayRouterId(modelId, this);\n if (!parsed.providerId || !parsed.modelId) return false;\n if (this.#routeThroughMastraGateway && this.#mastraGatewayApiKey) return true;\n const customProvider = this.#getCustomProviders().find(\n provider => parsed.providerId === getCustomProviderId(provider.name),\n );\n if (customProvider?.apiKey) return true;\n return hasResolvedAuth(\n MastraCodeGateway.resolveProviderAuth(\n {\n gatewayId: this.id,\n providerId: parsed.providerId,\n modelId: parsed.modelId,\n routerId: modelId,\n },\n undefined,\n this.#credentials,\n ),\n );\n }\n\n static resolveProviderAuth(\n request: GatewayAuthRequest,\n mastraGatewayApiKey?: string,\n credentials: CredentialStore = getGlobalAuthStorage(),\n ): GatewayAuthResult | undefined {\n if (request.gatewayId === 'mastra' && mastraGatewayApiKey) {\n return { apiKey: mastraGatewayApiKey, source: 'gateway' };\n }\n\n const authProviderId = getCredentialProviderId(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 // Catalog auth (`handlesModel`, `resolveAuth`) reads this store, while\n // `/api-keys` and logins write through other AuthStorage instances. Pick\n // up their changes on every catalog refresh.\n this.#credentials.reload();\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 // Subscription providers are not listed here: catalog ids from this gateway\n // are namespaced (`mastracode/<provider>/...`). Kimi augments the models.dev\n // `kimi-code-plan-cn` provider (claimed via `handlesModel`), and Copilot,\n // which models.dev excludes, has its own `github-copilot` gateway.\n return providers;\n }\n\n buildUrl(modelId: string): string | undefined | Promise<string | undefined> {\n return this.#routeThroughMastraGateway ? this.#mastraGateway.buildUrl(modelId) : modelId;\n }\n\n async getApiKey(modelId: string): Promise<string> {\n const providerId = stripMastraGatewayPrefix(modelId).split('/', 1)[0];\n if (this.#routeThroughMastraGateway) return this.#mastraGatewayApiKey ?? '';\n return providerId ? (getProviderAuthKey(providerId, this.#credentials) ?? '') : '';\n }\n\n resolveAuth(request: GatewayAuthRequest): GatewayAuthResult | undefined {\n if (this.#routeThroughMastraGateway && this.#mastraGatewayApiKey) {\n return { apiKey: this.#mastraGatewayApiKey, source: 'gateway' };\n }\n\n const customProvider = this.#getCustomProviders().find(\n provider => request.providerId === getCustomProviderId(provider.name),\n );\n if (customProvider?.apiKey) {\n return { apiKey: customProvider.apiKey, source: 'gateway' };\n }\n\n return MastraCodeGateway.resolveProviderAuth(request, undefined, this.#credentials);\n }\n\n resolveLanguageModel(args: {\n modelId: string;\n providerId: string;\n apiKey: string;\n headers?: Record<string, string>;\n transport?: any;\n responsesWebSocket?: any;\n }): GatewayLanguageModel {\n const customProvider = this.#getCustomProviders().find(\n provider => args.providerId === getCustomProviderId(provider.name),\n );\n if (customProvider) {\n const provider = createOpenAICompatible({\n name: args.providerId,\n baseURL: customProvider.url,\n apiKey: args.apiKey,\n headers: args.headers,\n });\n const reasoningEffort = this.#thinkingLevel ? THINKING_LEVEL_TO_REASONING_EFFORT[this.#thinkingLevel] : undefined;\n const middleware = createReasoningEffortMiddleware(args.providerId, reasoningEffort);\n if (!middleware) {\n return provider.chatModel(args.modelId);\n }\n return wrapLanguageModel({\n model: provider.chatModel(args.modelId),\n middleware: [middleware],\n });\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);\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 withThinkingOptionsModel(\n xaiProvider(args.modelId, { headers: args.headers, authStorage: this.#credentials }),\n providerThinkingOptions(`xai/${args.modelId}`, this.#thinkingLevel),\n );\n }\n\n if (this.#routeThroughMastraGateway) return this.#mastraGateway.resolveLanguageModel(args);\n\n if (args.providerId === 'google') {\n return this.#resolveGoogleModel(args);\n }\n\n if (args.providerId === KIMI_CODING_PROVIDER_ID || args.providerId === KIMI_CODING_CREDENTIAL_ID) {\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 const routedModelId: `${string}/${string}` = `${args.providerId}/${args.modelId}`;\n return new ModelRouterLanguageModelWithThinking(\n { id: routedModelId, apiKey: args.apiKey, headers: args.headers },\n providerThinkingOptions(routedModelId, this.#thinkingLevel),\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 }),\n });\n\n return wrapLanguageModel({\n model: anthropic(bareModelId),\n middleware: [\n claudeCodeMiddleware,\n createPromptCacheMiddleware(this.#anthropicPromptCacheScope),\n ...(thinkingMiddleware ? [thinkingMiddleware] : []),\n ],\n });\n }\n\n return this.#mastraGateway.resolveLanguageModel({ ...args, modelId: bareModelId });\n }\n\n if (storedCred?.type === 'oauth') {\n return opencodeClaudeMaxProvider(bareModelId, {\n headers: args.headers,\n authStorage: this.#credentials,\n thinkingLevel: this.#thinkingLevel,\n promptCacheScope: this.#anthropicPromptCacheScope,\n }) as unknown as GatewayLanguageModel;\n }\n\n if (storedCred?.type === 'api_key' && storedCred.key.trim().length > 0) {\n return anthropicApiKeyProvider(\n bareModelId,\n storedCred.key.trim(),\n args.headers,\n this.#thinkingLevel,\n this.#anthropicPromptCacheScope,\n );\n }\n\n const apiKey = getAnthropicApiKey(this.#credentials);\n if (apiKey) {\n return anthropicApiKeyProvider(\n bareModelId,\n apiKey,\n args.headers,\n this.#thinkingLevel,\n this.#anthropicPromptCacheScope,\n );\n }\n\n // No stored credentials: use the OAuth-backed provider so the first request can trigger login.\n return opencodeClaudeMaxProvider(bareModelId, {\n headers: args.headers,\n authStorage: this.#credentials,\n thinkingLevel: this.#thinkingLevel,\n promptCacheScope: this.#anthropicPromptCacheScope,\n }) as unknown as GatewayLanguageModel;\n }\n\n #resolveOpenAIModel(args: {\n modelId: string;\n providerId: string;\n apiKey: string;\n headers?: Record<string, string>;\n transport?: any;\n responsesWebSocket?: any;\n }): GatewayLanguageModel | undefined {\n const storedCred = this.#credentials.get('openai-codex');\n\n if (this.#routeThroughMastraGateway) {\n if (storedCred?.type === 'oauth') {\n const resolvedModelId = remapOpenAIModelForCodexOAuth(`openai/${args.modelId}`);\n const resolvedBareModelId = resolvedModelId.substring(OPENAI_PREFIX.length);\n const effectiveLevel = getEffectiveThinkingLevel(args.modelId, this.#thinkingLevel ?? 'medium');\n const reasoningEffort = THINKING_LEVEL_TO_REASONING_EFFORT[effectiveLevel];\n const middleware = createCodexMiddleware(reasoningEffort);\n const promptCacheKeyMiddleware = createPromptCacheKeyMiddleware(getRequestThreadId(args.headers));\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 }),\n });\n\n return wrapLanguageModel({\n model: openai.responses(resolvedBareModelId),\n middleware: [middleware, ...(promptCacheKeyMiddleware ? [promptCacheKeyMiddleware] : [])],\n });\n }\n\n return this.#mastraGateway.resolveLanguageModel(args);\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 && getEffectiveThinkingLevel(args.modelId, 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, this.#thinkingLevel);\n }\n\n return undefined;\n }\n\n #resolveGoogleModel(args: {\n modelId: string;\n providerId: string;\n apiKey: string;\n headers?: Record<string, string>;\n transport?: any;\n responsesWebSocket?: any;\n }): GatewayLanguageModel {\n const routerModel = new ModelRouterLanguageModel({\n id: `${args.providerId}/${args.modelId}`,\n apiKey: args.apiKey,\n headers: args.headers,\n }) as unknown as GatewayLanguageModel;\n const thinkingMiddleware = createGoogleThinkingMiddleware(args.modelId, this.#thinkingLevel);\n if (!thinkingMiddleware) return routerModel;\n\n return wrapLanguageModel({\n model: routerModel as any,\n middleware: [thinkingMiddleware],\n });\n }\n}\n"],"mappings":";;;;;;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AQ,KAAK,SAAS,KAAK,cAAc;CAIvF;CAEA,oBAAoB,MAOK;EACvB,MAAM,cAAc,IAAI,yBAAyB;GAC/C,IAAI,GAAG,KAAK,WAAW,GAAG,KAAK;GAC/B,QAAQ,KAAK;GACb,SAAS,KAAK;EAChB,CAAC;EACD,MAAM,qBAAqB,+BAA+B,KAAK,SAAS,KAAK,cAAc;EAC3F,IAAI,CAAC,oBAAoB,OAAO;EAEhC,OAAO,kBAAkB;GACvB,OAAO;GACP,YAAY,CAAC,kBAAkB;EACjC,CAAC;CACH;AACF"}
|
|
1
|
+
{"version":3,"file":"mastracode-gateway.js","names":[],"sources":["../../src/agents/mastracode-gateway.ts"],"sourcesContent":["import { createAnthropic } from '@ai-sdk/anthropic';\nimport { createOpenAI } from '@ai-sdk/openai';\nimport { createOpenAICompatible } from '@ai-sdk/openai-compatible';\nimport type { CustomAvailableModel, CustomModelCatalogProvider } from '@mastra/core/agent-controller';\nimport {\n GATEWAY_AUTH_HEADER,\n MastraGateway,\n MastraModelGateway,\n ModelRouterLanguageModel,\n PROVIDER_REGISTRY,\n} from '@mastra/core/llm';\nimport type {\n GatewayAuthRequest,\n GatewayAuthResult,\n GatewayLanguageModel,\n MastraModelGatewayInterface,\n ProviderConfig,\n} from '@mastra/core/llm';\nimport { wrapLanguageModel } from 'ai';\nimport { AuthStorage } from '../auth/storage.js';\nimport type { CredentialStore } from '../auth/types.js';\nimport { getCustomProviderId, loadSettings, MASTRA_GATEWAY_PROVIDER } from '../onboarding/settings.js';\nimport type { AnthropicPromptCacheScope } from '../providers/anthropic-prompt-cache.js';\nimport {\n buildAnthropicOAuthFetch,\n claudeCodeMiddleware,\n createAnthropicThinkingMiddleware,\n createPromptCacheMiddleware,\n opencodeClaudeMaxProvider,\n} from '../providers/claude-max.js';\nimport { githubCopilotProvider } from '../providers/github-copilot.js';\nimport { createGoogleThinkingMiddleware } from '../providers/google-thinking.js';\nimport { kimiCodingProvider } from '../providers/kimi-coding.js';\nimport {\n getCredentialProviderId,\n KIMI_CODING_CREDENTIAL_ID,\n KIMI_CODING_PROVIDER_ID,\n normalizeAnthropicModelId,\n OPENAI_PREFIX,\n remapOpenAIModelForCodexOAuth,\n stripMastraGatewayPrefix,\n} from '../providers/model-ids.js';\nimport {\n buildOpenAICodexOAuthFetch,\n createCodexMiddleware,\n createPromptCacheKeyMiddleware,\n createReasoningEffortMiddleware,\n getEffectiveThinkingLevel,\n getRequestThreadId,\n openaiCodexProvider,\n THINKING_LEVEL_TO_REASONING_EFFORT,\n} from '../providers/openai-codex.js';\nimport type { ThinkingLevel } from '../providers/openai-codex.js';\nimport {\n ModelRouterLanguageModelWithThinking,\n providerThinkingOptions,\n withThinkingOptionsModel,\n} from '../providers/provider-thinking.js';\nimport { xaiProvider } from '../providers/xai.js';\nimport { getAppDataDir } from '../utils/project.js';\nimport { resolveCustomProviders } from './custom-provider-source.js';\n\nconst PROVIDERS: Record<string, ProviderConfig> = PROVIDER_REGISTRY;\n\nexport {\n MASTRA_GATEWAY_PREFIX,\n OPENAI_PREFIX,\n remapOpenAIModelForCodexOAuth,\n stripMastraGatewayPrefix,\n} from '../providers/model-ids.js';\n\nexport const MASTRACODE_GATEWAY_ID = 'mastracode';\n\ntype ModelRequestHeaders = Record<string, string>;\n\nexport type MastraCodeCustomProvider = { name: string; url: string; apiKey?: string; models?: string[] };\n\nexport type MastraCodeGatewayOptions = {\n mastraGatewayBaseUrl: string;\n mastraGatewayApiKey?: string;\n routeThroughMastraGateway: boolean;\n thinkingLevel?: ThinkingLevel;\n /** Anthropic prompt-cache breakpoints to write. Defaults to `conversation`. */\n anthropicPromptCacheScope?: AnthropicPromptCacheScope;\n customProviders?: MastraCodeCustomProvider[];\n settingsPath?: string;\n /**\n * Per-tenant credential source for this gateway instance. Defaults to the\n * server-global file-backed `AuthStorage`; deployed web passes the calling\n * tenant's store so model calls use the caller's own credentials.\n */\n credentialStore?: CredentialStore;\n};\n\n/**\n * Global file-backed credential store for local (TUI) model resolution.\n *\n * Constructed lazily, NOT at module scope: `AuthStorage`'s default path is\n * resolved from `MASTRA_APP_DATA_DIR` at construction, and this module is\n * routinely imported before test harnesses / embedders point that variable at\n * an isolated directory — an import-time construction would permanently pin\n * the developer's real app-data dir for every credential read.\n */\nlet authStorageSingleton: AuthStorage | undefined;\nlet authStorageSingletonDir: string | undefined;\n\nexport function getGlobalAuthStorage(): AuthStorage {\n // Keyed by the resolved app-data dir: in-process harnesses re-point\n // MASTRA_APP_DATA_DIR per run inside one long-lived worker, so a store\n // pinned to a previous dir must be discarded, not reused.\n const dir = getAppDataDir();\n if (!authStorageSingleton || authStorageSingletonDir !== dir) {\n authStorageSingleton = new AuthStorage();\n authStorageSingletonDir = dir;\n }\n return authStorageSingleton;\n}\n\nexport function reloadAuthStorage() {\n getGlobalAuthStorage().reload();\n}\n\n/**\n * Resolve the Anthropic API key.\n * Main slot → dedicated apikey: slot → env var.\n */\nexport function getAnthropicApiKey(credentials: CredentialStore = getGlobalAuthStorage()): string | undefined {\n const storedCred = credentials.get('anthropic');\n if (storedCred?.type === 'api_key' && storedCred.key.trim().length > 0) {\n return storedCred.key.trim();\n }\n const dedicatedKey = credentials.getStoredApiKey('anthropic')?.trim();\n if (dedicatedKey) return dedicatedKey;\n return credentials.allowEnvironmentFallback === false\n ? undefined\n : process.env.ANTHROPIC_API_KEY?.trim() || undefined;\n}\n\n/**\n * Resolve the OpenAI API key.\n * Main slot → dedicated apikey: slot → env var.\n */\nexport function getOpenAIApiKey(credentials: CredentialStore = getGlobalAuthStorage()): string | undefined {\n const storedCred = credentials.get('openai-codex');\n if (storedCred?.type === 'api_key' && storedCred.key.trim().length > 0) {\n return storedCred.key.trim();\n }\n const dedicatedKey = credentials.getStoredApiKey('openai-codex')?.trim();\n if (dedicatedKey) return dedicatedKey;\n return credentials.allowEnvironmentFallback === false ? undefined : process.env.OPENAI_API_KEY?.trim() || undefined;\n}\n\nfunction anthropicApiKeyProvider(\n modelId: string,\n apiKey: string,\n headers: ModelRequestHeaders | undefined,\n thinkingLevel: ThinkingLevel | undefined,\n promptCacheScope: AnthropicPromptCacheScope,\n) {\n const anthropic = createAnthropic({ apiKey, headers });\n const thinkingMiddleware = createAnthropicThinkingMiddleware(modelId, thinkingLevel);\n return wrapLanguageModel({\n model: anthropic(modelId),\n middleware: [createPromptCacheMiddleware(promptCacheScope), ...(thinkingMiddleware ? [thinkingMiddleware] : [])],\n });\n}\n\nfunction openaiApiKeyProvider(\n modelId: string,\n apiKey: string,\n headers?: ModelRequestHeaders,\n thinkingLevel?: ThinkingLevel,\n) {\n const openai = createOpenAI({ apiKey, baseURL: process.env.OPENAI_BASE_URL, headers });\n const middleware =\n thinkingLevel && thinkingLevel !== 'off'\n ? createReasoningEffortMiddleware(\n 'openai',\n THINKING_LEVEL_TO_REASONING_EFFORT[getEffectiveThinkingLevel(modelId, thinkingLevel)],\n )\n : undefined;\n const promptCacheKeyMiddleware = createPromptCacheKeyMiddleware(getRequestThreadId(headers));\n return wrapLanguageModel({\n model: openai.responses(modelId),\n middleware: [...(middleware ? [middleware] : []), ...(promptCacheKeyMiddleware ? [promptCacheKeyMiddleware] : [])],\n });\n}\n\nfunction getProviderAuthKey(\n providerId: string,\n credentials: CredentialStore = getGlobalAuthStorage(),\n): string | undefined {\n const authProviderId = getCredentialProviderId(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 // `/api-keys` stores keys under the catalog provider id (`kimi-code-plan-cn`),\n // which can differ from the credential id.\n const catalogKey = authProviderId !== providerId ? credentials.getStoredApiKey(providerId)?.trim() : undefined;\n if (catalogKey) return catalogKey;\n if (credentials.allowEnvironmentFallback === false) return undefined;\n return authProviderId === KIMI_CODING_CREDENTIAL_ID ? 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> = { ...PROVIDERS };\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 function providerApiKeyEnvVar(providerId: string): string | undefined {\n return getApiKeyEnvVar(PROVIDERS[providerId]);\n}\n\n/**\n * Whether the process environment has a key for a models.dev provider. Checks every\n * env var the registry lists, as the models.dev gateway does when `resolveModel`\n * gets no gateway credential (e.g. `GOOGLE_API_KEY` or `GOOGLE_GENERATIVE_AI_API_KEY`).\n */\nexport function hasProviderEnvironmentKey(providerId: string): boolean {\n const envVars = PROVIDERS[providerId]?.apiKeyEnvVar;\n if (!envVars) return false;\n return (Array.isArray(envVars) ? envVars : [envVars]).some(envVar => Boolean(process.env[envVar]?.trim()));\n}\n\nexport class MastraCodeGateway extends MastraModelGateway {\n readonly id = MASTRACODE_GATEWAY_ID;\n readonly name = 'MastraCode Gateway';\n\n readonly #mastraGateway: MastraGateway;\n readonly #mastraGatewayBaseUrl: string;\n readonly #mastraGatewayApiKey?: string;\n readonly #routeThroughMastraGateway: boolean;\n readonly #thinkingLevel?: ThinkingLevel;\n readonly #anthropicPromptCacheScope: AnthropicPromptCacheScope;\n readonly #customProviders?: MastraCodeCustomProvider[];\n readonly #settingsPath?: string;\n readonly #credentials: CredentialStore;\n\n constructor({\n mastraGatewayBaseUrl,\n mastraGatewayApiKey,\n routeThroughMastraGateway,\n thinkingLevel,\n anthropicPromptCacheScope,\n customProviders,\n settingsPath,\n credentialStore,\n }: MastraCodeGatewayOptions) {\n super();\n this.#mastraGateway = new MastraGateway({ baseUrl: mastraGatewayBaseUrl });\n this.#mastraGatewayBaseUrl = mastraGatewayBaseUrl;\n this.#mastraGatewayApiKey = mastraGatewayApiKey;\n this.#routeThroughMastraGateway = routeThroughMastraGateway;\n this.#thinkingLevel = thinkingLevel;\n this.#anthropicPromptCacheScope = anthropicPromptCacheScope ?? 'conversation';\n this.#customProviders = customProviders;\n this.#settingsPath = settingsPath;\n this.#credentials = credentialStore ?? getGlobalAuthStorage();\n }\n\n static getMastraGatewayApiKey(): string | undefined {\n return getGlobalAuthStorage().getStoredApiKey(MASTRA_GATEWAY_PROVIDER) ?? process.env['MASTRA_GATEWAY_API_KEY'];\n }\n\n /** @deprecated Renamed to {@link MastraCodeGateway.getMastraGatewayApiKey}. */\n static getMemoryGatewayApiKey(): string | undefined {\n return MastraCodeGateway.getMastraGatewayApiKey();\n }\n\n /**\n * Claim an unprefixed model id (e.g. a bare `anthropic/...`) when this gateway\n * can authenticate it via OAuth or a stored/env credential. This lets the\n * shared gateway router select MastraCode for auth resolution, so the status\n * bar and `/api-keys` reflect OAuth logins instead of only checking env vars.\n */\n handlesModel(modelId: string): boolean {\n const parsed = parseGatewayRouterId(modelId, this);\n if (!parsed.providerId || !parsed.modelId) return false;\n if (this.#routeThroughMastraGateway && this.#mastraGatewayApiKey) return true;\n const customProvider = this.#getCustomProviders().find(\n provider => parsed.providerId === getCustomProviderId(provider.name),\n );\n if (customProvider?.apiKey) return true;\n return hasResolvedAuth(\n MastraCodeGateway.resolveProviderAuth(\n {\n gatewayId: this.id,\n providerId: parsed.providerId,\n modelId: parsed.modelId,\n routerId: modelId,\n },\n undefined,\n this.#credentials,\n ),\n );\n }\n\n static resolveProviderAuth(\n request: GatewayAuthRequest,\n mastraGatewayApiKey?: string,\n credentials: CredentialStore = getGlobalAuthStorage(),\n ): GatewayAuthResult | undefined {\n if (request.gatewayId === 'mastra' && mastraGatewayApiKey) {\n return { apiKey: mastraGatewayApiKey, source: 'gateway' };\n }\n\n const authProviderId = getCredentialProviderId(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 // Catalog auth (`handlesModel`, `resolveAuth`) reads this store, while\n // `/api-keys` and logins write through other AuthStorage instances. Pick\n // up their changes on every catalog refresh.\n this.#credentials.reload();\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 // Subscription providers are not listed here: catalog ids from this gateway\n // are namespaced (`mastracode/<provider>/...`). Kimi augments the models.dev\n // `kimi-code-plan-cn` provider (claimed via `handlesModel`), and Copilot,\n // which models.dev excludes, has its own `github-copilot` gateway.\n return providers;\n }\n\n buildUrl(modelId: string): string | undefined | Promise<string | undefined> {\n return this.#routeThroughMastraGateway ? this.#mastraGateway.buildUrl(modelId) : modelId;\n }\n\n async getApiKey(modelId: string): Promise<string> {\n const providerId = stripMastraGatewayPrefix(modelId).split('/', 1)[0];\n if (this.#routeThroughMastraGateway) return this.#mastraGatewayApiKey ?? '';\n return providerId ? (getProviderAuthKey(providerId, this.#credentials) ?? '') : '';\n }\n\n resolveAuth(request: GatewayAuthRequest): GatewayAuthResult | undefined {\n if (this.#routeThroughMastraGateway && this.#mastraGatewayApiKey) {\n return { apiKey: this.#mastraGatewayApiKey, source: 'gateway' };\n }\n\n const customProvider = this.#getCustomProviders().find(\n provider => request.providerId === getCustomProviderId(provider.name),\n );\n if (customProvider?.apiKey) {\n return { apiKey: customProvider.apiKey, source: 'gateway' };\n }\n\n return MastraCodeGateway.resolveProviderAuth(request, undefined, this.#credentials);\n }\n\n resolveLanguageModel(args: {\n modelId: string;\n providerId: string;\n apiKey: string;\n headers?: Record<string, string>;\n transport?: any;\n responsesWebSocket?: any;\n }): GatewayLanguageModel {\n const customProvider = this.#getCustomProviders().find(\n provider => args.providerId === getCustomProviderId(provider.name),\n );\n if (customProvider) {\n const provider = createOpenAICompatible({\n name: args.providerId,\n baseURL: customProvider.url,\n apiKey: args.apiKey,\n headers: args.headers,\n });\n const reasoningEffort = this.#thinkingLevel ? THINKING_LEVEL_TO_REASONING_EFFORT[this.#thinkingLevel] : undefined;\n const middleware = createReasoningEffortMiddleware(args.providerId, reasoningEffort);\n if (!middleware) {\n return provider.chatModel(args.modelId);\n }\n return wrapLanguageModel({\n model: provider.chatModel(args.modelId),\n middleware: [middleware],\n });\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);\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 withThinkingOptionsModel(\n xaiProvider(args.modelId, { headers: args.headers, authStorage: this.#credentials }),\n providerThinkingOptions(`xai/${args.modelId}`, this.#thinkingLevel),\n );\n }\n\n if (this.#routeThroughMastraGateway) return this.#mastraGateway.resolveLanguageModel(args);\n\n if (args.providerId === 'google') {\n return this.#resolveGoogleModel(args);\n }\n\n if (args.providerId === KIMI_CODING_PROVIDER_ID || args.providerId === KIMI_CODING_CREDENTIAL_ID) {\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 const routedModelId: `${string}/${string}` = `${args.providerId}/${args.modelId}`;\n return new ModelRouterLanguageModelWithThinking(\n { id: routedModelId, apiKey: args.apiKey, headers: args.headers },\n providerThinkingOptions(routedModelId, this.#thinkingLevel),\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 }),\n });\n\n return wrapLanguageModel({\n model: anthropic(bareModelId),\n middleware: [\n claudeCodeMiddleware,\n createPromptCacheMiddleware(this.#anthropicPromptCacheScope),\n ...(thinkingMiddleware ? [thinkingMiddleware] : []),\n ],\n });\n }\n\n return this.#mastraGateway.resolveLanguageModel({ ...args, modelId: bareModelId });\n }\n\n if (storedCred?.type === 'oauth') {\n return opencodeClaudeMaxProvider(bareModelId, {\n headers: args.headers,\n authStorage: this.#credentials,\n thinkingLevel: this.#thinkingLevel,\n promptCacheScope: this.#anthropicPromptCacheScope,\n }) as unknown as GatewayLanguageModel;\n }\n\n if (storedCred?.type === 'api_key' && storedCred.key.trim().length > 0) {\n return anthropicApiKeyProvider(\n bareModelId,\n storedCred.key.trim(),\n args.headers,\n this.#thinkingLevel,\n this.#anthropicPromptCacheScope,\n );\n }\n\n const apiKey = getAnthropicApiKey(this.#credentials);\n if (apiKey) {\n return anthropicApiKeyProvider(\n bareModelId,\n apiKey,\n args.headers,\n this.#thinkingLevel,\n this.#anthropicPromptCacheScope,\n );\n }\n\n // No stored credentials: use the OAuth-backed provider so the first request can trigger login.\n return opencodeClaudeMaxProvider(bareModelId, {\n headers: args.headers,\n authStorage: this.#credentials,\n thinkingLevel: this.#thinkingLevel,\n promptCacheScope: this.#anthropicPromptCacheScope,\n }) as unknown as GatewayLanguageModel;\n }\n\n #resolveOpenAIModel(args: {\n modelId: string;\n providerId: string;\n apiKey: string;\n headers?: Record<string, string>;\n transport?: any;\n responsesWebSocket?: any;\n }): GatewayLanguageModel | undefined {\n const storedCred = this.#credentials.get('openai-codex');\n\n if (this.#routeThroughMastraGateway) {\n if (storedCred?.type === 'oauth') {\n const resolvedModelId = remapOpenAIModelForCodexOAuth(`openai/${args.modelId}`);\n const resolvedBareModelId = resolvedModelId.substring(OPENAI_PREFIX.length);\n const effectiveLevel = getEffectiveThinkingLevel(args.modelId, this.#thinkingLevel ?? 'medium');\n const reasoningEffort = THINKING_LEVEL_TO_REASONING_EFFORT[effectiveLevel];\n const middleware = createCodexMiddleware(reasoningEffort);\n const promptCacheKeyMiddleware = createPromptCacheKeyMiddleware(getRequestThreadId(args.headers));\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 }),\n });\n\n return wrapLanguageModel({\n model: openai.responses(resolvedBareModelId),\n middleware: [middleware, ...(promptCacheKeyMiddleware ? [promptCacheKeyMiddleware] : [])],\n });\n }\n\n return this.#mastraGateway.resolveLanguageModel(args);\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 && getEffectiveThinkingLevel(args.modelId, 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, this.#thinkingLevel);\n }\n\n return undefined;\n }\n\n #resolveGoogleModel(args: {\n modelId: string;\n providerId: string;\n apiKey: string;\n headers?: Record<string, string>;\n transport?: any;\n responsesWebSocket?: any;\n }): GatewayLanguageModel {\n const routerModel = new ModelRouterLanguageModel({\n id: `${args.providerId}/${args.modelId}`,\n apiKey: args.apiKey,\n headers: args.headers,\n }) as unknown as GatewayLanguageModel;\n const thinkingMiddleware = createGoogleThinkingMiddleware(args.modelId, this.#thinkingLevel);\n if (!thinkingMiddleware) return routerModel;\n\n return wrapLanguageModel({\n model: routerModel as any,\n middleware: [thinkingMiddleware],\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA8DA,MAAM,YAA4C;AASlD,MAAa,wBAAwB;;;;;;;;;;AAgCrC,IAAI;AACJ,IAAI;AAEJ,SAAgB,uBAAoC;CAIlD,MAAM,MAAM,cAAc;CAC1B,IAAI,CAAC,wBAAwB,4BAA4B,KAAK;EAC5D,uBAAuB,IAAI,YAAY;EACvC,0BAA0B;CAC5B;CACA,OAAO;AACT;AAEA,SAAgB,oBAAoB;CAClC,qBAAqB,CAAC,CAAC,OAAO;AAChC;;;;;AAMA,SAAgB,mBAAmB,cAA+B,qBAAqB,GAAuB;CAC5G,MAAM,aAAa,YAAY,IAAI,WAAW;CAC9C,IAAI,YAAY,SAAS,aAAa,WAAW,IAAI,KAAK,CAAC,CAAC,SAAS,GACnE,OAAO,WAAW,IAAI,KAAK;CAE7B,MAAM,eAAe,YAAY,gBAAgB,WAAW,CAAC,EAAE,KAAK;CACpE,IAAI,cAAc,OAAO;CACzB,OAAO,YAAY,6BAA6B,QAC5C,KAAA,IACA,QAAQ,IAAI,mBAAmB,KAAK,KAAK,KAAA;AAC/C;;;;;AAMA,SAAgB,gBAAgB,cAA+B,qBAAqB,GAAuB;CACzG,MAAM,aAAa,YAAY,IAAI,cAAc;CACjD,IAAI,YAAY,SAAS,aAAa,WAAW,IAAI,KAAK,CAAC,CAAC,SAAS,GACnE,OAAO,WAAW,IAAI,KAAK;CAE7B,MAAM,eAAe,YAAY,gBAAgB,cAAc,CAAC,EAAE,KAAK;CACvE,IAAI,cAAc,OAAO;CACzB,OAAO,YAAY,6BAA6B,QAAQ,KAAA,IAAY,QAAQ,IAAI,gBAAgB,KAAK,KAAK,KAAA;AAC5G;AAEA,SAAS,wBACP,SACA,QACA,SACA,eACA,kBACA;CACA,MAAM,Y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O,oBAAoB,gBAAgB,UAAU,cAAc,MAAM,GAAG;IAC1E,eAAe,KAAK,kBAAkB,0BAA0B,KAAK,SAAS,KAAK,cAAc;IACjG,SAAS,KAAK;IACd,aAAa,KAAK;GACpB,CAAC;EACH;EAEA,MAAM,SAAS,gBAAgB,KAAK,YAAY;EAChD,IAAI,QACF,OAAO,qBAAqB,KAAK,SAAS,QAAQ,KAAK,SAAS,KAAK,cAAc;CAIvF;CAEA,oBAAoB,MAOK;EACvB,MAAM,cAAc,IAAI,yBAAyB;GAC/C,IAAI,GAAG,KAAK,WAAW,GAAG,KAAK;GAC/B,QAAQ,KAAK;GACb,SAAS,KAAK;EAChB,CAAC;EACD,MAAM,qBAAqB,+BAA+B,KAAK,SAAS,KAAK,cAAc;EAC3F,IAAI,CAAC,oBAAoB,OAAO;EAEhC,OAAO,kBAAkB;GACvB,OAAO;GACP,YAAY,CAAC,kBAAkB;EACjC,CAAC;CACH;AACF"}
|
|
@@ -11,8 +11,8 @@
|
|
|
11
11
|
* built on the OpenAI client — `openai` uses the default endpoint, every other
|
|
12
12
|
* OpenAI-compatible host supplies its `baseURL`. Deepgram is the exception: it
|
|
13
13
|
* is not OpenAI-compatible, so it resolves through `@mastra/voice-deepgram`
|
|
14
|
-
* (`DeepgramVoice`)
|
|
15
|
-
*
|
|
14
|
+
* (`DeepgramVoice`), and Mistral through `@mastra/voice-mistral`. Neither is
|
|
15
|
+
* in the models.dev STT snapshot, so both are added by hand.
|
|
16
16
|
*
|
|
17
17
|
* The accompanying snapshot test (`__tests__/stt-registry.test.ts`) re-derives
|
|
18
18
|
* the models.dev-backed entries from a checked-in snapshot so this list stays
|
|
@@ -25,8 +25,9 @@
|
|
|
25
25
|
* (its `/audio/transcriptions` endpoint follows the OpenAI shape).
|
|
26
26
|
* - `deepgram`: `DeepgramVoice` from `@mastra/voice-deepgram` (not
|
|
27
27
|
* OpenAI-compatible; uses the Deepgram SDK).
|
|
28
|
+
* - `mistral`: `MistralVoice` from `@mastra/voice-mistral`.
|
|
28
29
|
*/
|
|
29
|
-
export type STTResolver = 'openai' | 'openai-compatible' | 'deepgram';
|
|
30
|
+
export type STTResolver = 'openai' | 'openai-compatible' | 'deepgram' | 'mistral';
|
|
30
31
|
export interface STTModel {
|
|
31
32
|
/** models.dev provider id (also the AuthStorage key for the API key). */
|
|
32
33
|
provider: string;
|
|
@@ -38,6 +39,7 @@ export interface STTModel {
|
|
|
38
39
|
resolver: STTResolver;
|
|
39
40
|
/** Base URL for `openai-compatible` providers (from models.dev `api`). */
|
|
40
41
|
baseURL?: string;
|
|
42
|
+
realtimeModel?: string;
|
|
41
43
|
}
|
|
42
44
|
/**
|
|
43
45
|
* The curated STT catalog. Order matters: the first entry for a provider is its
|
|
@@ -55,6 +57,7 @@ export declare function sttProviders(): string[];
|
|
|
55
57
|
export declare function sttModelsForProvider(provider: string): STTModel[];
|
|
56
58
|
/** The default (first) model for a provider, or undefined if unknown. */
|
|
57
59
|
export declare function defaultModelForProvider(provider: string): STTModel | undefined;
|
|
60
|
+
export declare function findSTTModel(provider: string, model: string): STTModel | undefined;
|
|
58
61
|
/**
|
|
59
62
|
* Resolve a provider/model pair to a concrete registry entry.
|
|
60
63
|
* Falls back to the provider default (then the global default) so callers
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"stt-registry.d.ts","sourceRoot":"","sources":["../../src/voice/stt-registry.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAEH
|
|
1
|
+
{"version":3,"file":"stt-registry.d.ts","sourceRoot":"","sources":["../../src/voice/stt-registry.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAEH;;;;;;;;GAQG;AACH,MAAM,MAAM,WAAW,GAAG,QAAQ,GAAG,mBAAmB,GAAG,UAAU,GAAG,SAAS,CAAC;AAElF,MAAM,WAAW,QAAQ;IACvB,yEAAyE;IACzE,QAAQ,EAAE,MAAM,CAAC;IACjB,oEAAoE;IACpE,KAAK,EAAE,MAAM,CAAC;IACd,2CAA2C;IAC3C,KAAK,EAAE,MAAM,CAAC;IACd,4CAA4C;IAC5C,QAAQ,EAAE,WAAW,CAAC;IACtB,0EAA0E;IAC1E,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,aAAa,CAAC,EAAE,MAAM,CAAC;CACxB;AAED;;;;GAIG;AACH,eAAO,MAAM,UAAU,EAAE,SAAS,QAAQ,EA4FhC,CAAC;AAEX,2DAA2D;AAC3D,eAAO,MAAM,iBAAiB,EAAE,QAAyB,CAAC;AAE1D,wDAAwD;AACxD,eAAO,MAAM,oBAAoB,QAA6B,CAAC;AAE/D,6CAA6C;AAC7C,wBAAgB,YAAY,IAAI,MAAM,EAAE,CAUvC;AAED,4DAA4D;AAC5D,wBAAgB,oBAAoB,CAAC,QAAQ,EAAE,MAAM,GAAG,QAAQ,EAAE,CAEjE;AAED,yEAAyE;AACzE,wBAAgB,uBAAuB,CAAC,QAAQ,EAAE,MAAM,GAAG,QAAQ,GAAG,SAAS,CAE9E;AAED,wBAAgB,YAAY,CAAC,QAAQ,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,QAAQ,GAAG,SAAS,CAElF;AAED;;;;GAIG;AACH,wBAAgB,eAAe,CAAC,QAAQ,CAAC,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,MAAM,GAAG,QAAQ,CAG3E"}
|
|
@@ -43,6 +43,13 @@ const STT_MODELS = [
|
|
|
43
43
|
label: "Deepgram Nova-3",
|
|
44
44
|
resolver: "deepgram"
|
|
45
45
|
},
|
|
46
|
+
{
|
|
47
|
+
provider: "mistral",
|
|
48
|
+
model: "voxtral-mini-latest",
|
|
49
|
+
label: "Mistral Voxtral Mini",
|
|
50
|
+
resolver: "mistral",
|
|
51
|
+
realtimeModel: "voxtral-mini-transcribe-realtime-3"
|
|
52
|
+
},
|
|
46
53
|
{
|
|
47
54
|
provider: "alibaba",
|
|
48
55
|
model: "qwen3-asr-flash",
|
|
@@ -122,22 +129,18 @@ function sttModelsForProvider(provider) {
|
|
|
122
129
|
function defaultModelForProvider(provider) {
|
|
123
130
|
return STT_MODELS.find((m) => m.provider === provider);
|
|
124
131
|
}
|
|
132
|
+
function findSTTModel(provider, model) {
|
|
133
|
+
return STT_MODELS.find((m) => m.provider === provider && m.model === model);
|
|
134
|
+
}
|
|
125
135
|
/**
|
|
126
136
|
* Resolve a provider/model pair to a concrete registry entry.
|
|
127
137
|
* Falls back to the provider default (then the global default) so callers
|
|
128
138
|
* always get a usable entry even if settings name an unknown model.
|
|
129
139
|
*/
|
|
130
140
|
function resolveSTTModel(provider, model) {
|
|
131
|
-
if (provider)
|
|
132
|
-
|
|
133
|
-
const exact = STT_MODELS.find((m) => m.provider === provider && m.model === model);
|
|
134
|
-
if (exact) return exact;
|
|
135
|
-
}
|
|
136
|
-
const providerDefault = defaultModelForProvider(provider);
|
|
137
|
-
if (providerDefault) return providerDefault;
|
|
138
|
-
}
|
|
139
|
-
return DEFAULT_STT_MODEL;
|
|
141
|
+
if (!provider) return DEFAULT_STT_MODEL;
|
|
142
|
+
return (model ? findSTTModel(provider, model) : void 0) ?? defaultModelForProvider(provider) ?? DEFAULT_STT_MODEL;
|
|
140
143
|
}
|
|
141
|
-
export { DEFAULT_STT_MODEL, DEFAULT_STT_PROVIDER, STT_MODELS, defaultModelForProvider, resolveSTTModel, sttModelsForProvider, sttProviders };
|
|
144
|
+
export { DEFAULT_STT_MODEL, DEFAULT_STT_PROVIDER, STT_MODELS, defaultModelForProvider, findSTTModel, resolveSTTModel, sttModelsForProvider, sttProviders };
|
|
142
145
|
|
|
143
146
|
//# sourceMappingURL=stt-registry.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"stt-registry.js","names":[],"sources":["../../src/voice/stt-registry.ts"],"sourcesContent":["/**\n * Speech-to-text (STT) model registry for push-to-talk voice input.\n *\n * This is the single source of truth shared by the `/voice` settings picker,\n * settings validation, and the cloud transcription resolver. Entries are\n * derived from models.dev (https://models.dev/api.json): a model is treated as\n * STT when its modalities are audio-in / text-out with no text input.\n *\n * Most cloud providers here speak the OpenAI `/audio/transcriptions` shape, so\n * the cloud engine resolves them through Mastra's `OpenAIVoice` (`MastraVoice`)\n * built on the OpenAI client — `openai` uses the default endpoint, every other\n * OpenAI-compatible host supplies its `baseURL`. Deepgram is the exception: it\n * is not OpenAI-compatible, so it resolves through `@mastra/voice-deepgram`\n * (`DeepgramVoice`)
|
|
1
|
+
{"version":3,"file":"stt-registry.js","names":[],"sources":["../../src/voice/stt-registry.ts"],"sourcesContent":["/**\n * Speech-to-text (STT) model registry for push-to-talk voice input.\n *\n * This is the single source of truth shared by the `/voice` settings picker,\n * settings validation, and the cloud transcription resolver. Entries are\n * derived from models.dev (https://models.dev/api.json): a model is treated as\n * STT when its modalities are audio-in / text-out with no text input.\n *\n * Most cloud providers here speak the OpenAI `/audio/transcriptions` shape, so\n * the cloud engine resolves them through Mastra's `OpenAIVoice` (`MastraVoice`)\n * built on the OpenAI client — `openai` uses the default endpoint, every other\n * OpenAI-compatible host supplies its `baseURL`. Deepgram is the exception: it\n * is not OpenAI-compatible, so it resolves through `@mastra/voice-deepgram`\n * (`DeepgramVoice`), and Mistral through `@mastra/voice-mistral`. Neither is\n * in the models.dev STT snapshot, so both are added by hand.\n *\n * The accompanying snapshot test (`__tests__/stt-registry.test.ts`) re-derives\n * the models.dev-backed entries from a checked-in snapshot so this list stays\n * honest and can be refreshed deliberately rather than drifting by hand.\n */\n\n/**\n * How a provider's transcription model is constructed.\n * - `openai`: `OpenAIVoice` with the default OpenAI endpoint.\n * - `openai-compatible`: `OpenAIVoice` pointed at the host's `baseURL`\n * (its `/audio/transcriptions` endpoint follows the OpenAI shape).\n * - `deepgram`: `DeepgramVoice` from `@mastra/voice-deepgram` (not\n * OpenAI-compatible; uses the Deepgram SDK).\n * - `mistral`: `MistralVoice` from `@mastra/voice-mistral`.\n */\nexport type STTResolver = 'openai' | 'openai-compatible' | 'deepgram' | 'mistral';\n\nexport interface STTModel {\n /** models.dev provider id (also the AuthStorage key for the API key). */\n provider: string;\n /** Bare model id passed to the provider's transcription factory. */\n model: string;\n /** Human-friendly label for the picker. */\n label: string;\n /** How to build the transcription model. */\n resolver: STTResolver;\n /** Base URL for `openai-compatible` providers (from models.dev `api`). */\n baseURL?: string;\n realtimeModel?: string;\n}\n\n/**\n * The curated STT catalog. Order matters: the first entry for a provider is its\n * default model, and the first overall entry (`openai`/`whisper-1`) is the\n * global default.\n */\nexport const STT_MODELS: readonly STTModel[] = [\n // OpenAI — default provider.\n { provider: 'openai', model: 'whisper-1', label: 'OpenAI Whisper', resolver: 'openai' },\n { provider: 'openai', model: 'gpt-4o-transcribe', label: 'OpenAI GPT-4o Transcribe', resolver: 'openai' },\n {\n provider: 'openai',\n model: 'gpt-4o-mini-transcribe',\n label: 'OpenAI GPT-4o mini Transcribe',\n resolver: 'openai',\n },\n // Groq — fast, cheap whisper hosting via its OpenAI-compatible endpoint.\n {\n provider: 'groq',\n model: 'whisper-large-v3-turbo',\n label: 'Groq Whisper Large v3 Turbo',\n resolver: 'openai-compatible',\n baseURL: 'https://api.groq.com/openai/v1',\n },\n {\n provider: 'groq',\n model: 'whisper-large-v3',\n label: 'Groq Whisper Large v3',\n resolver: 'openai-compatible',\n baseURL: 'https://api.groq.com/openai/v1',\n },\n // Deepgram — dedicated STT provider (not OpenAI-compatible); via @mastra/voice-deepgram.\n { provider: 'deepgram', model: 'nova-3', label: 'Deepgram Nova-3', resolver: 'deepgram' },\n {\n provider: 'mistral',\n model: 'voxtral-mini-latest',\n label: 'Mistral Voxtral Mini',\n resolver: 'mistral',\n realtimeModel: 'voxtral-mini-transcribe-realtime-3',\n },\n // Alibaba Qwen ASR (OpenAI-compatible endpoints).\n {\n provider: 'alibaba',\n model: 'qwen3-asr-flash',\n label: 'Alibaba Qwen3 ASR Flash',\n resolver: 'openai-compatible',\n baseURL: 'https://dashscope-intl.aliyuncs.com/compatible-mode/v1',\n },\n {\n provider: 'alibaba-cn',\n model: 'qwen3-asr-flash',\n label: 'Alibaba Qwen3 ASR Flash (China)',\n resolver: 'openai-compatible',\n baseURL: 'https://dashscope.aliyuncs.com/compatible-mode/v1',\n },\n // Whisper hosts (OpenAI-compatible endpoints).\n {\n provider: 'scaleway',\n model: 'whisper-large-v3',\n label: 'Scaleway Whisper Large v3',\n resolver: 'openai-compatible',\n baseURL: 'https://api.scaleway.ai/v1',\n },\n {\n provider: 'nvidia',\n model: 'openai/whisper-large-v3',\n label: 'Nvidia Whisper Large v3',\n resolver: 'openai-compatible',\n baseURL: 'https://integrate.api.nvidia.com/v1',\n },\n {\n provider: 'nearai',\n model: 'openai/whisper-large-v3',\n label: 'NEAR AI Whisper Large v3',\n resolver: 'openai-compatible',\n baseURL: 'https://cloud-api.near.ai/v1',\n },\n {\n provider: 'evroc',\n model: 'openai/whisper-large-v3-turbo',\n label: 'evroc Whisper Large v3 Turbo',\n resolver: 'openai-compatible',\n baseURL: 'https://models.think.evroc.com/v1',\n },\n {\n provider: 'evroc',\n model: 'openai/whisper-large-v3',\n label: 'evroc Whisper Large v3',\n resolver: 'openai-compatible',\n baseURL: 'https://models.think.evroc.com/v1',\n },\n {\n provider: 'evroc',\n model: 'KBLab/kb-whisper-large',\n label: 'evroc KB-Whisper Large',\n resolver: 'openai-compatible',\n baseURL: 'https://models.think.evroc.com/v1',\n },\n] as const;\n\n/** The global default STT model (first registry entry). */\nexport const DEFAULT_STT_MODEL: STTModel = STT_MODELS[0]!;\n\n/** The default STT provider when none is configured. */\nexport const DEFAULT_STT_PROVIDER = DEFAULT_STT_MODEL.provider;\n\n/** Unique provider ids in registry order. */\nexport function sttProviders(): string[] {\n const seen = new Set<string>();\n const out: string[] = [];\n for (const m of STT_MODELS) {\n if (!seen.has(m.provider)) {\n seen.add(m.provider);\n out.push(m.provider);\n }\n }\n return out;\n}\n\n/** All models offered for a provider, in registry order. */\nexport function sttModelsForProvider(provider: string): STTModel[] {\n return STT_MODELS.filter(m => m.provider === provider);\n}\n\n/** The default (first) model for a provider, or undefined if unknown. */\nexport function defaultModelForProvider(provider: string): STTModel | undefined {\n return STT_MODELS.find(m => m.provider === provider);\n}\n\nexport function findSTTModel(provider: string, model: string): STTModel | undefined {\n return STT_MODELS.find(m => m.provider === provider && m.model === model);\n}\n\n/**\n * Resolve a provider/model pair to a concrete registry entry.\n * Falls back to the provider default (then the global default) so callers\n * always get a usable entry even if settings name an unknown model.\n */\nexport function resolveSTTModel(provider?: string, model?: string): STTModel {\n if (!provider) return DEFAULT_STT_MODEL;\n return (model ? findSTTModel(provider, model) : undefined) ?? defaultModelForProvider(provider) ?? DEFAULT_STT_MODEL;\n}\n"],"mappings":";;;;;;AAmDA,MAAa,aAAkC;CAE7C;EAAE,UAAU;EAAU,OAAO;EAAa,OAAO;EAAkB,UAAU;CAAS;CACtF;EAAE,UAAU;EAAU,OAAO;EAAqB,OAAO;EAA4B,UAAU;CAAS;CACxG;EACE,UAAU;EACV,OAAO;EACP,OAAO;EACP,UAAU;CACZ;CAEA;EACE,UAAU;EACV,OAAO;EACP,OAAO;EACP,UAAU;EACV,SAAS;CACX;CACA;EACE,UAAU;EACV,OAAO;EACP,OAAO;EACP,UAAU;EACV,SAAS;CACX;CAEA;EAAE,UAAU;EAAY,OAAO;EAAU,OAAO;EAAmB,UAAU;CAAW;CACxF;EACE,UAAU;EACV,OAAO;EACP,OAAO;EACP,UAAU;EACV,eAAe;CACjB;CAEA;EACE,UAAU;EACV,OAAO;EACP,OAAO;EACP,UAAU;EACV,SAAS;CACX;CACA;EACE,UAAU;EACV,OAAO;EACP,OAAO;EACP,UAAU;EACV,SAAS;CACX;CAEA;EACE,UAAU;EACV,OAAO;EACP,OAAO;EACP,UAAU;EACV,SAAS;CACX;CACA;EACE,UAAU;EACV,OAAO;EACP,OAAO;EACP,UAAU;EACV,SAAS;CACX;CACA;EACE,UAAU;EACV,OAAO;EACP,OAAO;EACP,UAAU;EACV,SAAS;CACX;CACA;EACE,UAAU;EACV,OAAO;EACP,OAAO;EACP,UAAU;EACV,SAAS;CACX;CACA;EACE,UAAU;EACV,OAAO;EACP,OAAO;EACP,UAAU;EACV,SAAS;CACX;CACA;EACE,UAAU;EACV,OAAO;EACP,OAAO;EACP,UAAU;EACV,SAAS;CACX;AACF;;AAGA,MAAa,oBAA8B,WAAW;;AAGtD,MAAa,uBAAuB,kBAAkB;;AAGtD,SAAgB,eAAyB;CACvC,MAAM,uBAAO,IAAI,IAAY;CAC7B,MAAM,MAAgB,CAAC;CACvB,KAAK,MAAM,KAAK,YACd,IAAI,CAAC,KAAK,IAAI,EAAE,QAAQ,GAAG;EACzB,KAAK,IAAI,EAAE,QAAQ;EACnB,IAAI,KAAK,EAAE,QAAQ;CACrB;CAEF,OAAO;AACT;;AAGA,SAAgB,qBAAqB,UAA8B;CACjE,OAAO,WAAW,QAAO,MAAK,EAAE,aAAa,QAAQ;AACvD;;AAGA,SAAgB,wBAAwB,UAAwC;CAC9E,OAAO,WAAW,MAAK,MAAK,EAAE,aAAa,QAAQ;AACrD;AAEA,SAAgB,aAAa,UAAkB,OAAqC;CAClF,OAAO,WAAW,MAAK,MAAK,EAAE,aAAa,YAAY,EAAE,UAAU,KAAK;AAC1E;;;;;;AAOA,SAAgB,gBAAgB,UAAmB,OAA0B;CAC3E,IAAI,CAAC,UAAU,OAAO;CACtB,QAAQ,QAAQ,aAAa,UAAU,KAAK,IAAI,KAAA,MAAc,wBAAwB,QAAQ,KAAK;AACrG"}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { AuthStorage } from '../auth/storage.js';
|
|
2
|
+
import type { STTModel } from './stt-registry.js';
|
|
3
|
+
export declare function sttApiKeyEnvVar(provider: string): string | undefined;
|
|
4
|
+
export declare function resolveSTTApiKey(provider: string, authStorage?: AuthStorage): string | undefined;
|
|
5
|
+
export interface STTTranscriber {
|
|
6
|
+
/** `filetype` is the extension the provider reads the format from (`wav`, `webm`, `m4a`…). */
|
|
7
|
+
transcribe(audio: Buffer, filetype: string): Promise<string>;
|
|
8
|
+
}
|
|
9
|
+
export declare function createSTTTranscriber(entry: STTModel, apiKey: string): Promise<STTTranscriber>;
|
|
10
|
+
//# sourceMappingURL=transcribe.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"transcribe.d.ts","sourceRoot":"","sources":["../../src/voice/transcribe.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AACtD,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAQlD,wBAAgB,eAAe,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAEpE;AAED,wBAAgB,gBAAgB,CAAC,QAAQ,EAAE,MAAM,EAAE,WAAW,CAAC,EAAE,WAAW,GAAG,MAAM,GAAG,SAAS,CAIhG;AA0DD,MAAM,WAAW,cAAc;IAC7B,8FAA8F;IAC9F,UAAU,CAAC,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;CAC9D;AAED,wBAAsB,oBAAoB,CAAC,KAAK,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,cAAc,CAAC,CAgBnG"}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { providerApiKeyEnvVar } from "../agents/mastracode-gateway.js";
|
|
2
|
+
import { Readable } from "stream";
|
|
3
|
+
// src/voice/transcribe.ts
|
|
4
|
+
const STT_ONLY_API_KEY_ENV_VARS = { deepgram: "DEEPGRAM_API_KEY" };
|
|
5
|
+
const STT_TIMEOUT_MS = 6e4;
|
|
6
|
+
const STT_MAX_RETRIES = 1;
|
|
7
|
+
function sttApiKeyEnvVar(provider) {
|
|
8
|
+
return STT_ONLY_API_KEY_ENV_VARS[provider] ?? providerApiKeyEnvVar(provider);
|
|
9
|
+
}
|
|
10
|
+
function resolveSTTApiKey(provider, authStorage) {
|
|
11
|
+
const envVar = sttApiKeyEnvVar(provider);
|
|
12
|
+
return (envVar ? process.env[envVar]?.trim() : void 0) || authStorage?.getStoredApiKey(provider);
|
|
13
|
+
}
|
|
14
|
+
function listenWithFiletype(voice) {
|
|
15
|
+
return (audio, filetype) => voice.listen(Readable.from(audio), { filetype });
|
|
16
|
+
}
|
|
17
|
+
function openAIClientOptions(entry, apiKey) {
|
|
18
|
+
return {
|
|
19
|
+
timeout: STT_TIMEOUT_MS,
|
|
20
|
+
maxRetries: STT_MAX_RETRIES,
|
|
21
|
+
...apiKey === process.env.OPENAI_API_KEY?.trim() ? {} : {
|
|
22
|
+
organization: null,
|
|
23
|
+
project: null
|
|
24
|
+
},
|
|
25
|
+
...entry.resolver === "openai-compatible" && entry.baseURL ? { baseURL: entry.baseURL } : {}
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
async function buildListen(entry, apiKey) {
|
|
29
|
+
if (entry.resolver === "deepgram") {
|
|
30
|
+
const { DeepgramVoice } = await import("@mastra/voice-deepgram");
|
|
31
|
+
const voice = new DeepgramVoice({ listeningModel: {
|
|
32
|
+
name: entry.model,
|
|
33
|
+
apiKey
|
|
34
|
+
} });
|
|
35
|
+
return (audio) => voice.listen(Readable.from(audio));
|
|
36
|
+
}
|
|
37
|
+
const speechModel = { apiKey };
|
|
38
|
+
if (entry.resolver === "mistral") {
|
|
39
|
+
const { MistralVoice } = await import("@mastra/voice-mistral");
|
|
40
|
+
return listenWithFiletype(new MistralVoice({
|
|
41
|
+
speechModel,
|
|
42
|
+
listeningModel: {
|
|
43
|
+
name: entry.model,
|
|
44
|
+
apiKey
|
|
45
|
+
}
|
|
46
|
+
}));
|
|
47
|
+
}
|
|
48
|
+
const { OpenAIVoice } = await import("@mastra/voice-openai");
|
|
49
|
+
return listenWithFiletype(new OpenAIVoice({
|
|
50
|
+
speechModel,
|
|
51
|
+
listeningModel: {
|
|
52
|
+
name: entry.model,
|
|
53
|
+
apiKey,
|
|
54
|
+
options: openAIClientOptions(entry, apiKey)
|
|
55
|
+
}
|
|
56
|
+
}));
|
|
57
|
+
}
|
|
58
|
+
function normalizeTranscript(result) {
|
|
59
|
+
return (typeof result === "string" ? result : result.transcript ?? "").trim();
|
|
60
|
+
}
|
|
61
|
+
async function createSTTTranscriber(entry, apiKey) {
|
|
62
|
+
const listen = await buildListen(entry, apiKey);
|
|
63
|
+
return { async transcribe(audio, filetype) {
|
|
64
|
+
let timer;
|
|
65
|
+
const timeout = new Promise((_, reject) => {
|
|
66
|
+
timer = setTimeout(() => reject(/* @__PURE__ */ new Error("Speech-to-text timed out after 1 minute.")), STT_TIMEOUT_MS);
|
|
67
|
+
});
|
|
68
|
+
try {
|
|
69
|
+
return normalizeTranscript(await Promise.race([listen(audio, filetype), timeout]));
|
|
70
|
+
} finally {
|
|
71
|
+
clearTimeout(timer);
|
|
72
|
+
}
|
|
73
|
+
} };
|
|
74
|
+
}
|
|
75
|
+
export { createSTTTranscriber, resolveSTTApiKey, sttApiKeyEnvVar };
|
|
76
|
+
|
|
77
|
+
//# sourceMappingURL=transcribe.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"transcribe.js","names":[],"sources":["../../src/voice/transcribe.ts"],"sourcesContent":["// OAuth (Codex) tokens cannot call the transcription endpoints, so callers pass a real provider API key.\n\nimport { Readable } from 'node:stream';\n\nimport type { DeepgramModel } from '@mastra/voice-deepgram';\nimport type { OpenAIConfig } from '@mastra/voice-openai';\n\nimport { providerApiKeyEnvVar } from '../agents/mastracode-gateway.js';\nimport type { AuthStorage } from '../auth/storage.js';\nimport type { STTModel } from './stt-registry.js';\n\nconst STT_ONLY_API_KEY_ENV_VARS: Record<string, string> = { deepgram: 'DEEPGRAM_API_KEY' };\n\nconst STT_TIMEOUT_MS = 60_000;\n\nconst STT_MAX_RETRIES = 1;\n\nexport function sttApiKeyEnvVar(provider: string): string | undefined {\n return STT_ONLY_API_KEY_ENV_VARS[provider] ?? providerApiKeyEnvVar(provider);\n}\n\nexport function resolveSTTApiKey(provider: string, authStorage?: AuthStorage): string | undefined {\n const envVar = sttApiKeyEnvVar(provider);\n const fromEnv = envVar ? process.env[envVar]?.trim() : undefined;\n return fromEnv || authStorage?.getStoredApiKey(provider);\n}\n\n/** Structural, because each `@mastra/voice-*` package extends its own bundled `MastraVoice`. */\ninterface VoiceListener {\n listen(\n audioStream: NodeJS.ReadableStream,\n options?: Record<string, unknown>,\n ): Promise<string | { transcript?: string }>;\n}\n\ntype Listen = (audio: Buffer, filetype: string) => Promise<string | { transcript?: string }>;\n\nfunction listenWithFiletype(voice: VoiceListener): Listen {\n return (audio, filetype) => voice.listen(Readable.from(audio), { filetype });\n}\n\n// The OpenAI SDK reads OPENAI_ORG_ID and OPENAI_PROJECT_ID, which belong to the OPENAI_API_KEY account only.\nfunction openAIClientOptions(entry: STTModel, apiKey: string): OpenAIConfig['options'] {\n return {\n timeout: STT_TIMEOUT_MS,\n maxRetries: STT_MAX_RETRIES,\n ...(apiKey === process.env.OPENAI_API_KEY?.trim() ? {} : { organization: null, project: null }),\n ...(entry.resolver === 'openai-compatible' && entry.baseURL ? { baseURL: entry.baseURL } : {}),\n };\n}\n\n// Each voice SDK loads on first dictation, not with every session.\nasync function buildListen(entry: STTModel, apiKey: string): Promise<Listen> {\n if (entry.resolver === 'deepgram') {\n const { DeepgramVoice } = await import('@mastra/voice-deepgram');\n // `name` is typed for Deepgram's own ids; the registry's model string is passed verbatim.\n const voice = new DeepgramVoice({ listeningModel: { name: entry.model as DeepgramModel, apiKey } });\n return audio => voice.listen(Readable.from(audio));\n }\n // The OpenAI and Mistral constructors also build a TTS client and throw without its key.\n const speechModel = { apiKey };\n if (entry.resolver === 'mistral') {\n const { MistralVoice } = await import('@mastra/voice-mistral');\n return listenWithFiletype(new MistralVoice({ speechModel, listeningModel: { name: entry.model, apiKey } }));\n }\n const { OpenAIVoice } = await import('@mastra/voice-openai');\n return listenWithFiletype(\n new OpenAIVoice({\n speechModel,\n listeningModel: {\n // Typed for OpenAI's own ids; the client accepts any model string and baseURL.\n name: entry.model as OpenAIConfig['name'],\n apiKey,\n options: openAIClientOptions(entry, apiKey),\n },\n }),\n );\n}\n\nfunction normalizeTranscript(result: string | { transcript?: string }): string {\n return (typeof result === 'string' ? result : (result.transcript ?? '')).trim();\n}\n\nexport interface STTTranscriber {\n /** `filetype` is the extension the provider reads the format from (`wav`, `webm`, `m4a`…). */\n transcribe(audio: Buffer, filetype: string): Promise<string>;\n}\n\nexport async function createSTTTranscriber(entry: STTModel, apiKey: string): Promise<STTTranscriber> {\n const listen = await buildListen(entry, apiKey);\n return {\n async transcribe(audio, filetype) {\n let timer: NodeJS.Timeout | undefined;\n // Only the OpenAI client takes a timeout; Mistral and Deepgram calls, and an OpenAI retry after a slow attempt, are abandoned here, not cancelled.\n const timeout = new Promise<never>((_, reject) => {\n timer = setTimeout(() => reject(new Error('Speech-to-text timed out after 1 minute.')), STT_TIMEOUT_MS);\n });\n try {\n return normalizeTranscript(await Promise.race([listen(audio, filetype), timeout]));\n } finally {\n clearTimeout(timer);\n }\n },\n };\n}\n"],"mappings":";;;AAWA,MAAM,4BAAoD,EAAE,UAAU,mBAAmB;AAEzF,MAAM,iBAAiB;AAEvB,MAAM,kBAAkB;AAExB,SAAgB,gBAAgB,UAAsC;CACpE,OAAO,0BAA0B,aAAa,qBAAqB,QAAQ;AAC7E;AAEA,SAAgB,iBAAiB,UAAkB,aAA+C;CAChG,MAAM,SAAS,gBAAgB,QAAQ;CAEvC,QADgB,SAAS,QAAQ,IAAI,OAAO,EAAE,KAAK,IAAI,KAAA,MACrC,aAAa,gBAAgB,QAAQ;AACzD;AAYA,SAAS,mBAAmB,OAA8B;CACxD,QAAQ,OAAO,aAAa,MAAM,OAAO,SAAS,KAAK,KAAK,GAAG,EAAE,SAAS,CAAC;AAC7E;AAGA,SAAS,oBAAoB,OAAiB,QAAyC;CACrF,OAAO;EACL,SAAS;EACT,YAAY;EACZ,GAAI,WAAW,QAAQ,IAAI,gBA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C,CAAC;EACnF,UAAU;GACR,aAAa,KAAK;EACpB;CACF,EACF;AACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mastra/code-sdk",
|
|
3
|
-
"version": "1.19.0-alpha.
|
|
3
|
+
"version": "1.19.0-alpha.2",
|
|
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": {
|
|
@@ -64,19 +64,22 @@
|
|
|
64
64
|
"yaml": "^2.9.1",
|
|
65
65
|
"zod": "^4.6.7",
|
|
66
66
|
"@mastra/agent-browser": "0.6.0",
|
|
67
|
-
"@mastra/client-js": "1.60.0-alpha.
|
|
68
|
-
"@mastra/duckdb": "1.19.0-alpha.
|
|
67
|
+
"@mastra/client-js": "1.60.0-alpha.2",
|
|
68
|
+
"@mastra/duckdb": "1.19.0-alpha.1",
|
|
69
69
|
"@mastra/fastembed": "1.3.6",
|
|
70
70
|
"@mastra/github-signals": "0.5.2",
|
|
71
71
|
"@mastra/libsql": "1.30.0-alpha.0",
|
|
72
|
-
"@mastra/mcp": "2.9.0-alpha.
|
|
72
|
+
"@mastra/mcp": "2.9.0-alpha.1",
|
|
73
73
|
"@mastra/memory": "1.41.1-alpha.0",
|
|
74
|
-
"@mastra/observability": "1.23.2-alpha.
|
|
74
|
+
"@mastra/observability": "1.23.2-alpha.1",
|
|
75
75
|
"@mastra/parallel": "0.1.5",
|
|
76
|
-
"@mastra/pg": "1.36.0-alpha.
|
|
76
|
+
"@mastra/pg": "1.36.0-alpha.1",
|
|
77
77
|
"@mastra/schema-compat": "1.3.17",
|
|
78
78
|
"@mastra/stagehand": "0.4.0",
|
|
79
|
-
"@mastra/tavily": "1.1.3"
|
|
79
|
+
"@mastra/tavily": "1.1.3",
|
|
80
|
+
"@mastra/voice-deepgram": "0.13.4-alpha.0",
|
|
81
|
+
"@mastra/voice-mistral": "0.1.3",
|
|
82
|
+
"@mastra/voice-openai": "0.13.4"
|
|
80
83
|
},
|
|
81
84
|
"devDependencies": {
|
|
82
85
|
"@ai-sdk/provider": "^4.0.35",
|
|
@@ -91,7 +94,7 @@
|
|
|
91
94
|
"@internal/lint": "0.0.148",
|
|
92
95
|
"@internal/types-builder": "0.0.123",
|
|
93
96
|
"@internal/workspace-test-utils": "0.0.92",
|
|
94
|
-
"@mastra/core": "1.83.0-alpha.
|
|
97
|
+
"@mastra/core": "1.83.0-alpha.2"
|
|
95
98
|
},
|
|
96
99
|
"peerDependencies": {
|
|
97
100
|
"@mastra/core": ">=1.83.0-0 <2.0.0-0"
|