@mastra/code-sdk 1.11.1-alpha.0 → 1.12.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/dist/acp/agent.d.ts.map +1 -1
  2. package/dist/acp/agent.js +6 -9
  3. package/dist/acp/agent.js.map +1 -1
  4. package/dist/acp/runtime.d.ts.map +1 -1
  5. package/dist/acp/runtime.js +3 -0
  6. package/dist/acp/runtime.js.map +1 -1
  7. package/dist/agent-connections/ownership.d.ts.map +1 -1
  8. package/dist/agent-connections/ownership.js +1 -1
  9. package/dist/agent-connections/ownership.js.map +1 -1
  10. package/dist/agent-connections/tools.d.ts.map +1 -1
  11. package/dist/agent-connections/tools.js +14 -1
  12. package/dist/agent-connections/tools.js.map +1 -1
  13. package/dist/agents/mastracode-gateway.d.ts.map +1 -1
  14. package/dist/agents/mastracode-gateway.js +3 -3
  15. package/dist/agents/mastracode-gateway.js.map +1 -1
  16. package/dist/auth/account-rotation-processor.d.ts +4 -3
  17. package/dist/auth/account-rotation-processor.d.ts.map +1 -1
  18. package/dist/auth/account-rotation-processor.js +10 -29
  19. package/dist/auth/account-rotation-processor.js.map +1 -1
  20. package/dist/headless/cli.d.ts.map +1 -1
  21. package/dist/headless/cli.js +3 -0
  22. package/dist/headless/cli.js.map +1 -1
  23. package/dist/index.d.ts +14 -0
  24. package/dist/index.d.ts.map +1 -1
  25. package/dist/index.js +13 -1
  26. package/dist/index.js.map +1 -1
  27. package/dist/providers/anthropic-thinking.d.ts +5 -0
  28. package/dist/providers/anthropic-thinking.d.ts.map +1 -0
  29. package/dist/providers/anthropic-thinking.js +25 -0
  30. package/dist/providers/anthropic-thinking.js.map +1 -0
  31. package/dist/providers/claude-max.d.ts +1 -1
  32. package/dist/providers/claude-max.d.ts.map +1 -1
  33. package/dist/providers/claude-max.js +8 -34
  34. package/dist/providers/claude-max.js.map +1 -1
  35. package/dist/providers/google-thinking.d.ts +4 -2
  36. package/dist/providers/google-thinking.d.ts.map +1 -1
  37. package/dist/providers/google-thinking.js +23 -7
  38. package/dist/providers/google-thinking.js.map +1 -1
  39. package/dist/providers/openai-codex.d.ts.map +1 -1
  40. package/dist/providers/openai-codex.js +3 -3
  41. package/dist/providers/openai-codex.js.map +1 -1
  42. package/dist/thinking-catalog.d.ts +4 -0
  43. package/dist/thinking-catalog.d.ts.map +1 -0
  44. package/dist/thinking-catalog.js +13 -0
  45. package/dist/thinking-catalog.js.map +1 -0
  46. package/dist/thinking.d.ts +4 -1
  47. package/dist/thinking.d.ts.map +1 -1
  48. package/dist/thinking.js +65 -4
  49. package/dist/thinking.js.map +1 -1
  50. package/package.json +12 -12
@@ -1 +1 @@
1
- {"version":3,"file":"mastracode-gateway.js","names":["#mastraGateway","#mastraGatewayBaseUrl","#mastraGatewayApiKey","#routeThroughMastraGateway","#thinkingLevel","#anthropicPromptCacheScope","#customProviders","#settingsPath","#credentials","#getCustomProviders","#resolveAnthropicModel","#resolveOpenAIModel","#resolveGoogleModel"],"sources":["../../src/agents/mastracode-gateway.ts"],"sourcesContent":["import { createAnthropic } from '@ai-sdk/anthropic';\nimport { createOpenAI } from '@ai-sdk/openai';\nimport { createOpenAICompatible } from '@ai-sdk/openai-compatible';\nimport type { CustomAvailableModel, CustomModelCatalogProvider } from '@mastra/core/agent-controller';\nimport {\n GATEWAY_AUTH_HEADER,\n MastraGateway,\n MastraModelGateway,\n ModelRouterLanguageModel,\n PROVIDER_REGISTRY,\n} from '@mastra/core/llm';\nimport type {\n GatewayAuthRequest,\n GatewayAuthResult,\n GatewayLanguageModel,\n MastraModelGatewayInterface,\n ProviderConfig,\n} from '@mastra/core/llm';\nimport { wrapLanguageModel } from 'ai';\nimport { AuthStorage } from '../auth/storage.js';\nimport type { CredentialStore } from '../auth/types.js';\nimport { getCustomProviderId, loadSettings, MASTRA_GATEWAY_PROVIDER } from '../onboarding/settings.js';\nimport type { AnthropicPromptCacheScope } from '../providers/anthropic-prompt-cache.js';\nimport {\n buildAnthropicOAuthFetch,\n claudeCodeMiddleware,\n createAnthropicThinkingMiddleware,\n createPromptCacheMiddleware,\n opencodeClaudeMaxProvider,\n} from '../providers/claude-max.js';\nimport { getCopilotModelCatalog, githubCopilotProvider } from '../providers/github-copilot.js';\nimport { createGoogleThinkingMiddleware } from '../providers/google-thinking.js';\nimport { KIMI_CODING_MODELS, kimiCodingProvider } from '../providers/kimi-coding.js';\nimport {\n normalizeAnthropicModelId,\n OPENAI_PREFIX,\n remapOpenAIModelForCodexOAuth,\n stripMastraGatewayPrefix,\n} from '../providers/model-ids.js';\nimport {\n buildOpenAICodexOAuthFetch,\n createCodexMiddleware,\n createReasoningEffortMiddleware,\n getEffectiveThinkingLevel,\n openaiCodexProvider,\n THINKING_LEVEL_TO_REASONING_EFFORT,\n} from '../providers/openai-codex.js';\nimport type { ThinkingLevel } from '../providers/openai-codex.js';\nimport { xaiProvider } from '../providers/xai.js';\nimport { getAppDataDir } from '../utils/project.js';\nimport { resolveCustomProviders } from './custom-provider-source.js';\n\nexport {\n MASTRA_GATEWAY_PREFIX,\n OPENAI_PREFIX,\n remapOpenAIModelForCodexOAuth,\n stripMastraGatewayPrefix,\n} from '../providers/model-ids.js';\n\nexport const MASTRACODE_GATEWAY_ID = 'mastracode';\n\ntype ModelRequestHeaders = Record<string, string>;\n\nexport type MastraCodeCustomProvider = { name: string; url: string; apiKey?: string; models?: string[] };\n\nexport type MastraCodeGatewayOptions = {\n mastraGatewayBaseUrl: string;\n mastraGatewayApiKey?: string;\n routeThroughMastraGateway: boolean;\n thinkingLevel?: ThinkingLevel;\n /** Anthropic prompt-cache breakpoints to write. Defaults to `conversation`. */\n anthropicPromptCacheScope?: AnthropicPromptCacheScope;\n customProviders?: MastraCodeCustomProvider[];\n settingsPath?: string;\n /**\n * Per-tenant credential source for this gateway instance. Defaults to the\n * server-global file-backed `AuthStorage`; deployed web passes the calling\n * tenant's store so model calls use the caller's own credentials.\n */\n credentialStore?: CredentialStore;\n};\n\n/**\n * Global file-backed credential store for local (TUI) model resolution.\n *\n * Constructed lazily, NOT at module scope: `AuthStorage`'s default path is\n * resolved from `MASTRA_APP_DATA_DIR` at construction, and this module is\n * routinely imported before test harnesses / embedders point that variable at\n * an isolated directory — an import-time construction would permanently pin\n * the developer's real app-data dir for every credential read.\n */\nlet authStorageSingleton: AuthStorage | undefined;\nlet authStorageSingletonDir: string | undefined;\n\nexport function getGlobalAuthStorage(): AuthStorage {\n // Keyed by the resolved app-data dir: in-process harnesses re-point\n // MASTRA_APP_DATA_DIR per run inside one long-lived worker, so a store\n // pinned to a previous dir must be discarded, not reused.\n const dir = getAppDataDir();\n if (!authStorageSingleton || authStorageSingletonDir !== dir) {\n authStorageSingleton = new AuthStorage();\n authStorageSingletonDir = dir;\n }\n return authStorageSingleton;\n}\n\nexport function reloadAuthStorage() {\n getGlobalAuthStorage().reload();\n}\n\n/**\n * Resolve the Anthropic API key.\n * Main slot → dedicated apikey: slot → env var.\n */\nexport function getAnthropicApiKey(credentials: CredentialStore = getGlobalAuthStorage()): string | undefined {\n const storedCred = credentials.get('anthropic');\n if (storedCred?.type === 'api_key' && storedCred.key.trim().length > 0) {\n return storedCred.key.trim();\n }\n const dedicatedKey = credentials.getStoredApiKey('anthropic')?.trim();\n if (dedicatedKey) return dedicatedKey;\n return credentials.allowEnvironmentFallback === false\n ? undefined\n : process.env.ANTHROPIC_API_KEY?.trim() || undefined;\n}\n\n/**\n * Resolve the OpenAI API key.\n * Main slot → dedicated apikey: slot → env var.\n */\nexport function getOpenAIApiKey(credentials: CredentialStore = getGlobalAuthStorage()): string | undefined {\n const storedCred = credentials.get('openai-codex');\n if (storedCred?.type === 'api_key' && storedCred.key.trim().length > 0) {\n return storedCred.key.trim();\n }\n const dedicatedKey = credentials.getStoredApiKey('openai-codex')?.trim();\n if (dedicatedKey) return dedicatedKey;\n return credentials.allowEnvironmentFallback === false ? undefined : process.env.OPENAI_API_KEY?.trim() || undefined;\n}\n\nfunction anthropicApiKeyProvider(\n modelId: string,\n apiKey: string,\n headers: ModelRequestHeaders | undefined,\n thinkingLevel: ThinkingLevel | undefined,\n promptCacheScope: AnthropicPromptCacheScope,\n) {\n const anthropic = createAnthropic({ apiKey, headers });\n const thinkingMiddleware = createAnthropicThinkingMiddleware(modelId, thinkingLevel);\n return wrapLanguageModel({\n model: anthropic(modelId),\n middleware: [createPromptCacheMiddleware(promptCacheScope), ...(thinkingMiddleware ? [thinkingMiddleware] : [])],\n });\n}\n\nfunction openaiApiKeyProvider(\n modelId: string,\n apiKey: string,\n headers?: ModelRequestHeaders,\n thinkingLevel?: ThinkingLevel,\n) {\n const openai = createOpenAI({ apiKey, baseURL: process.env.OPENAI_BASE_URL, headers });\n const middleware =\n thinkingLevel && thinkingLevel !== 'off'\n ? createReasoningEffortMiddleware(\n 'openai',\n THINKING_LEVEL_TO_REASONING_EFFORT[getEffectiveThinkingLevel(modelId, thinkingLevel)],\n )\n : undefined;\n return wrapLanguageModel({\n model: openai.responses(modelId),\n middleware: middleware ? [middleware] : [],\n });\n}\n\nfunction getAuthProviderId(providerId: string): string {\n return providerId === 'openai' ? 'openai-codex' : providerId;\n}\n\nfunction getProviderAuthKey(\n providerId: string,\n credentials: CredentialStore = getGlobalAuthStorage(),\n): string | undefined {\n const authProviderId = getAuthProviderId(providerId);\n const storedCred = credentials.get(authProviderId);\n if (storedCred?.type === 'api_key' && storedCred.key.trim().length > 0) {\n return storedCred.key.trim();\n }\n const dedicatedKey = credentials.getStoredApiKey(authProviderId)?.trim();\n if (dedicatedKey) return dedicatedKey;\n if (credentials.allowEnvironmentFallback === false) return undefined;\n return authProviderId === 'kimi-for-coding' ? process.env.KIMI_API_KEY?.trim() || undefined : undefined;\n}\n\nexport function resolveAuth(request: GatewayAuthRequest, mastraGatewayApiKey?: string): GatewayAuthResult | undefined {\n return MastraCodeGateway.resolveProviderAuth(request, mastraGatewayApiKey);\n}\n\nfunction getGatewayProviderKey(gatewayId: string, providerId: string): string {\n if (gatewayId === 'models.dev') return providerId;\n return providerId === gatewayId ? gatewayId : `${gatewayId}/${providerId}`;\n}\n\nfunction parseGatewayRouterId(\n routerId: string,\n gateway: MastraModelGatewayInterface,\n): { gatewayId: string; providerId: string; modelId: string } {\n const [firstPart = '', secondPart = '', ...restParts] = routerId.split('/');\n const gatewayId = gateway.id;\n\n if (firstPart === gatewayId && secondPart) {\n return {\n gatewayId,\n providerId: secondPart,\n modelId: restParts.join('/'),\n };\n }\n\n return {\n gatewayId,\n providerId: firstPart,\n modelId: [secondPart, ...restParts].filter(Boolean).join('/'),\n };\n}\n\nfunction hasResolvedAuth(auth: GatewayAuthResult | undefined): boolean {\n if (!auth) return false;\n if (auth.apiKey || auth.bearerToken) return true;\n return auth.headers ? Object.keys(auth.headers).length > 0 : false;\n}\n\nasync function resolveGatewayProviderAuth(\n gateway: MastraModelGatewayInterface,\n routerId: string,\n): Promise<GatewayAuthResult | undefined> {\n if (!gateway.resolveAuth) return undefined;\n\n const parsed = parseGatewayRouterId(routerId, gateway);\n try {\n const result = await gateway.resolveAuth({\n gatewayId: parsed.gatewayId,\n providerId: parsed.providerId,\n modelId: parsed.modelId,\n routerId,\n });\n return hasResolvedAuth(result) ? result : undefined;\n } catch {\n return undefined;\n }\n}\n\nasync function getMastraCodeProviderConfigs(\n gateway: MastraModelGatewayInterface,\n): Promise<Record<string, ProviderConfig>> {\n const providers: Record<string, ProviderConfig> = { ...(PROVIDER_REGISTRY as Record<string, ProviderConfig>) };\n\n try {\n const gatewayProviders = await gateway.fetchProviders();\n for (const [providerId, config] of Object.entries(gatewayProviders)) {\n providers[getGatewayProviderKey(gateway.id, providerId)] = {\n ...config,\n gateway: gateway.id,\n };\n }\n } catch (error) {\n console.warn(`Failed to load providers from gateway ${gateway.id}:`, error);\n }\n\n return providers;\n}\n\nfunction getApiKeyEnvVar(providerConfig: Pick<ProviderConfig, 'apiKeyEnvVar'> | undefined): string | undefined {\n const envVars = providerConfig?.apiKeyEnvVar;\n return Array.isArray(envVars) ? envVars[0] : envVars;\n}\n\nexport class MastraCodeGateway extends MastraModelGateway {\n readonly id = MASTRACODE_GATEWAY_ID;\n readonly name = 'MastraCode Gateway';\n\n readonly #mastraGateway: MastraGateway;\n readonly #mastraGatewayBaseUrl: string;\n readonly #mastraGatewayApiKey?: string;\n readonly #routeThroughMastraGateway: boolean;\n readonly #thinkingLevel?: ThinkingLevel;\n readonly #anthropicPromptCacheScope: AnthropicPromptCacheScope;\n readonly #customProviders?: MastraCodeCustomProvider[];\n readonly #settingsPath?: string;\n readonly #credentials: CredentialStore;\n\n constructor({\n mastraGatewayBaseUrl,\n mastraGatewayApiKey,\n routeThroughMastraGateway,\n thinkingLevel,\n anthropicPromptCacheScope,\n customProviders,\n settingsPath,\n credentialStore,\n }: MastraCodeGatewayOptions) {\n super();\n this.#mastraGateway = new MastraGateway({ baseUrl: mastraGatewayBaseUrl });\n this.#mastraGatewayBaseUrl = mastraGatewayBaseUrl;\n this.#mastraGatewayApiKey = mastraGatewayApiKey;\n this.#routeThroughMastraGateway = routeThroughMastraGateway;\n this.#thinkingLevel = thinkingLevel;\n this.#anthropicPromptCacheScope = anthropicPromptCacheScope ?? 'conversation';\n this.#customProviders = customProviders;\n this.#settingsPath = settingsPath;\n this.#credentials = credentialStore ?? getGlobalAuthStorage();\n }\n\n static getMastraGatewayApiKey(): string | undefined {\n return getGlobalAuthStorage().getStoredApiKey(MASTRA_GATEWAY_PROVIDER) ?? process.env['MASTRA_GATEWAY_API_KEY'];\n }\n\n /** @deprecated Renamed to {@link MastraCodeGateway.getMastraGatewayApiKey}. */\n static getMemoryGatewayApiKey(): string | undefined {\n return MastraCodeGateway.getMastraGatewayApiKey();\n }\n\n /**\n * Claim an unprefixed model id (e.g. a bare `anthropic/...`) when this gateway\n * can authenticate it via OAuth or a stored/env credential. This lets the\n * shared gateway router select MastraCode for auth resolution, so the status\n * bar and `/api-keys` reflect OAuth logins instead of only checking env vars.\n */\n handlesModel(modelId: string): boolean {\n const parsed = parseGatewayRouterId(modelId, this);\n if (!parsed.providerId || !parsed.modelId) return false;\n if (this.#routeThroughMastraGateway && this.#mastraGatewayApiKey) return true;\n const customProvider = this.#getCustomProviders().find(\n provider => parsed.providerId === getCustomProviderId(provider.name),\n );\n if (customProvider?.apiKey) return true;\n return hasResolvedAuth(\n MastraCodeGateway.resolveProviderAuth(\n {\n gatewayId: this.id,\n providerId: parsed.providerId,\n modelId: parsed.modelId,\n routerId: modelId,\n },\n undefined,\n this.#credentials,\n ),\n );\n }\n\n static resolveProviderAuth(\n request: GatewayAuthRequest,\n mastraGatewayApiKey?: string,\n credentials: CredentialStore = getGlobalAuthStorage(),\n ): GatewayAuthResult | undefined {\n if (request.gatewayId === 'mastra' && mastraGatewayApiKey) {\n return { apiKey: mastraGatewayApiKey, source: 'gateway' };\n }\n\n const authProviderId = getAuthProviderId(request.providerId);\n const storedCred = credentials.get(authProviderId);\n if (storedCred?.type === 'oauth') {\n return { bearerToken: 'oauth', source: 'gateway' };\n }\n\n const apiKey = getProviderAuthKey(request.providerId, credentials);\n return apiKey ? { apiKey, source: 'gateway' } : undefined;\n }\n\n static createModelCatalogProvider(gateway: MastraModelGatewayInterface): CustomModelCatalogProvider {\n return async () => {\n const registry = await getMastraCodeProviderConfigs(gateway);\n const models: CustomAvailableModel[] = [];\n\n for (const [provider, providerConfig] of Object.entries(registry)) {\n const apiKeyEnvVar = getApiKeyEnvVar(providerConfig);\n const hasEnvKey = apiKeyEnvVar ? Boolean(process.env[apiKeyEnvVar]) : false;\n const modelNames = providerConfig.models;\n if (!Array.isArray(modelNames)) continue;\n\n const gatewayAuth = modelNames[0]\n ? await resolveGatewayProviderAuth(gateway, `${provider}/${modelNames[0]}`)\n : undefined;\n\n for (const modelName of modelNames) {\n const id = `${provider}/${modelName}`;\n models.push({\n id,\n provider,\n modelName,\n hasApiKey: hasEnvKey || Boolean(gatewayAuth),\n apiKeyEnvVar: apiKeyEnvVar || undefined,\n });\n }\n }\n\n return models;\n };\n }\n\n createModelCatalogProvider(): CustomModelCatalogProvider {\n return MastraCodeGateway.createModelCatalogProvider(this);\n }\n\n #getCustomProviders(): MastraCodeCustomProvider[] {\n // Explicit constructor list wins; then a registered source (deployed web,\n // DB-backed — authoritative, so settings.json is never consulted); then\n // the local file-backed settings.\n return this.#customProviders ?? resolveCustomProviders() ?? loadSettings(this.#settingsPath).customProviders;\n }\n\n async fetchProviders(): Promise<Record<string, ProviderConfig>> {\n const providers: Record<string, ProviderConfig> = {};\n for (const provider of this.#getCustomProviders()) {\n const models = provider.models ?? [];\n if (!models.length) continue;\n providers[getCustomProviderId(provider.name)] = {\n name: provider.name,\n url: provider.url,\n apiKeyEnvVar: '',\n apiKeyHeader: 'Authorization',\n gateway: this.id,\n models,\n };\n }\n\n providers['kimi-for-coding'] = {\n name: 'Kimi For Coding',\n apiKeyEnvVar: 'KIMI_API_KEY',\n apiKeyHeader: 'Authorization',\n gateway: this.id,\n models: [...KIMI_CODING_MODELS],\n };\n\n try {\n const copilotModels = await getCopilotModelCatalog({ authStorage: this.#credentials });\n providers['github-copilot'] = {\n name: 'GitHub Copilot',\n apiKeyEnvVar: '',\n apiKeyHeader: 'Authorization',\n gateway: this.id,\n models: copilotModels.map(model => model.id),\n };\n } catch (error) {\n console.warn('Failed to load GitHub Copilot model catalog:', error);\n }\n\n return providers;\n }\n\n buildUrl(modelId: string): string | undefined | Promise<string | undefined> {\n return this.#routeThroughMastraGateway ? this.#mastraGateway.buildUrl(modelId) : modelId;\n }\n\n async getApiKey(modelId: string): Promise<string> {\n const providerId = stripMastraGatewayPrefix(modelId).split('/', 1)[0];\n if (this.#routeThroughMastraGateway) return this.#mastraGatewayApiKey ?? '';\n return providerId ? (getProviderAuthKey(providerId, this.#credentials) ?? '') : '';\n }\n\n resolveAuth(request: GatewayAuthRequest): GatewayAuthResult | undefined {\n if (this.#routeThroughMastraGateway && this.#mastraGatewayApiKey) {\n return { apiKey: this.#mastraGatewayApiKey, source: 'gateway' };\n }\n\n const customProvider = this.#getCustomProviders().find(\n provider => request.providerId === getCustomProviderId(provider.name),\n );\n if (customProvider?.apiKey) {\n return { apiKey: customProvider.apiKey, source: 'gateway' };\n }\n\n return MastraCodeGateway.resolveProviderAuth(request, undefined, this.#credentials);\n }\n\n resolveLanguageModel(args: {\n modelId: string;\n providerId: string;\n apiKey: string;\n headers?: Record<string, string>;\n transport?: any;\n responsesWebSocket?: any;\n }): GatewayLanguageModel {\n const customProvider = this.#getCustomProviders().find(\n provider => args.providerId === getCustomProviderId(provider.name),\n );\n if (customProvider) {\n const provider = createOpenAICompatible({\n name: args.providerId,\n baseURL: customProvider.url,\n apiKey: args.apiKey,\n headers: args.headers,\n });\n const reasoningEffort = this.#thinkingLevel ? THINKING_LEVEL_TO_REASONING_EFFORT[this.#thinkingLevel] : undefined;\n const middleware = createReasoningEffortMiddleware(args.providerId, reasoningEffort);\n if (!middleware) {\n return provider.chatModel(args.modelId) as unknown as GatewayLanguageModel;\n }\n return wrapLanguageModel({\n model: provider.chatModel(args.modelId),\n middleware: [middleware],\n }) as unknown as GatewayLanguageModel;\n }\n\n if (args.providerId === 'github-copilot') {\n return githubCopilotProvider(args.modelId, {\n headers: args.headers,\n authStorage: this.#credentials,\n }) as unknown as GatewayLanguageModel;\n }\n\n if (args.providerId === 'moonshotai') {\n // Prefer the gateway-resolved key (stored credentials), then the canonical\n // registry env var. Keep the legacy typo name as a fallback for anyone who\n // set it because of the previous error message.\n const apiKey =\n args.apiKey?.trim() || process.env.MOONSHOT_API_KEY?.trim() || process.env.MOONSHOT_AI_API_KEY?.trim();\n if (!apiKey) {\n throw new Error('Need MOONSHOT_API_KEY');\n }\n return createAnthropic({\n apiKey,\n baseURL: 'https://api.moonshot.ai/anthropic/v1',\n name: 'moonshotai.anthropicv1',\n headers: args.headers,\n })(args.modelId) as unknown as GatewayLanguageModel;\n }\n\n if (args.providerId === 'anthropic') {\n return this.#resolveAnthropicModel(args);\n }\n\n if (args.providerId === 'openai') {\n const openaiModel = this.#resolveOpenAIModel(args);\n if (openaiModel) return openaiModel;\n }\n\n if (args.providerId === 'xai' && this.#credentials.get('xai')?.type === 'oauth') {\n return xaiProvider(args.modelId, {\n headers: args.headers,\n authStorage: this.#credentials,\n }) as unknown as GatewayLanguageModel;\n }\n\n if (args.providerId === 'google') {\n return this.#resolveGoogleModel(args);\n }\n\n if (this.#routeThroughMastraGateway) {\n return this.#mastraGateway.resolveLanguageModel(args) as GatewayLanguageModel;\n }\n\n if (args.providerId === 'kimi-for-coding') {\n return kimiCodingProvider(args.modelId, {\n apiKey: args.apiKey,\n headers: args.headers,\n credentialStore: this.#credentials,\n }) as unknown as GatewayLanguageModel;\n }\n\n return new ModelRouterLanguageModel({\n id: `${args.providerId}/${args.modelId}` as `${string}/${string}`,\n apiKey: args.apiKey,\n headers: args.headers,\n }) as unknown as GatewayLanguageModel;\n }\n\n #resolveAnthropicModel(args: {\n modelId: string;\n providerId: string;\n apiKey: string;\n headers?: Record<string, string>;\n transport?: any;\n responsesWebSocket?: any;\n }): GatewayLanguageModel {\n const bareModelId = normalizeAnthropicModelId(args.modelId);\n const storedCred = this.#credentials.get('anthropic');\n const thinkingMiddleware = createAnthropicThinkingMiddleware(bareModelId, this.#thinkingLevel);\n\n if (this.#routeThroughMastraGateway) {\n if (storedCred?.type === 'oauth') {\n const anthropic = createAnthropic({\n apiKey: 'oauth-gateway-placeholder',\n baseURL: `${this.#mastraGatewayBaseUrl}/v1`,\n headers: {\n [GATEWAY_AUTH_HEADER]: `Bearer ${args.apiKey}`,\n ...args.headers,\n },\n fetch: buildAnthropicOAuthFetch({ authStorage: this.#credentials }) as any,\n });\n\n return wrapLanguageModel({\n model: anthropic(bareModelId),\n middleware: [\n claudeCodeMiddleware,\n createPromptCacheMiddleware(this.#anthropicPromptCacheScope),\n ...(thinkingMiddleware ? [thinkingMiddleware] : []),\n ],\n }) as unknown as GatewayLanguageModel;\n }\n\n const gatewayModel = this.#mastraGateway.resolveLanguageModel({\n ...args,\n modelId: bareModelId,\n }) as GatewayLanguageModel;\n if (!thinkingMiddleware) return gatewayModel;\n return wrapLanguageModel({\n model: gatewayModel as any,\n middleware: [thinkingMiddleware],\n }) as unknown as GatewayLanguageModel;\n }\n\n if (storedCred?.type === 'oauth') {\n return opencodeClaudeMaxProvider(bareModelId, {\n headers: args.headers,\n authStorage: this.#credentials,\n thinkingLevel: this.#thinkingLevel,\n promptCacheScope: this.#anthropicPromptCacheScope,\n }) as unknown as GatewayLanguageModel;\n }\n\n if (storedCred?.type === 'api_key' && storedCred.key.trim().length > 0) {\n return anthropicApiKeyProvider(\n bareModelId,\n storedCred.key.trim(),\n args.headers,\n this.#thinkingLevel,\n this.#anthropicPromptCacheScope,\n ) as unknown as GatewayLanguageModel;\n }\n\n const apiKey = getAnthropicApiKey(this.#credentials);\n if (apiKey) {\n return anthropicApiKeyProvider(\n bareModelId,\n apiKey,\n args.headers,\n this.#thinkingLevel,\n this.#anthropicPromptCacheScope,\n ) as unknown as GatewayLanguageModel;\n }\n\n // No stored credentials: use the OAuth-backed provider so the first request can trigger login.\n return opencodeClaudeMaxProvider(bareModelId, {\n headers: args.headers,\n authStorage: this.#credentials,\n thinkingLevel: this.#thinkingLevel,\n promptCacheScope: this.#anthropicPromptCacheScope,\n }) as unknown as GatewayLanguageModel;\n }\n\n #resolveOpenAIModel(args: {\n modelId: string;\n providerId: string;\n apiKey: string;\n headers?: Record<string, string>;\n transport?: any;\n responsesWebSocket?: any;\n }): GatewayLanguageModel | undefined {\n const storedCred = this.#credentials.get('openai-codex');\n\n if (this.#routeThroughMastraGateway) {\n if (storedCred?.type === 'oauth') {\n const resolvedModelId = remapOpenAIModelForCodexOAuth(`openai/${args.modelId}`);\n const resolvedBareModelId = resolvedModelId.substring(OPENAI_PREFIX.length);\n const requestedLevel: ThinkingLevel = this.#thinkingLevel ?? 'medium';\n const effectiveLevel = getEffectiveThinkingLevel(resolvedBareModelId, requestedLevel);\n const reasoningEffort = THINKING_LEVEL_TO_REASONING_EFFORT[effectiveLevel];\n const middleware = createCodexMiddleware(reasoningEffort);\n const openai = createOpenAI({\n apiKey: 'oauth-gateway-placeholder',\n baseURL: `${this.#mastraGatewayBaseUrl}/v1`,\n headers: {\n [GATEWAY_AUTH_HEADER]: `Bearer ${args.apiKey}`,\n ...args.headers,\n },\n fetch: buildOpenAICodexOAuthFetch({ authStorage: this.#credentials, rewriteUrl: false }) as any,\n });\n\n return wrapLanguageModel({\n model: openai.responses(resolvedBareModelId),\n middleware: [middleware],\n }) as unknown as GatewayLanguageModel;\n }\n\n return this.#mastraGateway.resolveLanguageModel(args) as GatewayLanguageModel;\n }\n\n if (storedCred?.type === 'oauth') {\n const resolvedModelId = remapOpenAIModelForCodexOAuth(`openai/${args.modelId}`);\n return openaiCodexProvider(resolvedModelId.substring(OPENAI_PREFIX.length), {\n thinkingLevel: this.#thinkingLevel,\n headers: args.headers,\n authStorage: this.#credentials,\n }) as unknown as GatewayLanguageModel;\n }\n\n const apiKey = getOpenAIApiKey(this.#credentials);\n if (apiKey) {\n return openaiApiKeyProvider(\n args.modelId,\n apiKey,\n args.headers,\n this.#thinkingLevel,\n ) as unknown as GatewayLanguageModel;\n }\n\n return undefined;\n }\n\n #resolveGoogleModel(args: {\n modelId: string;\n providerId: string;\n apiKey: string;\n headers?: Record<string, string>;\n transport?: any;\n responsesWebSocket?: any;\n }): GatewayLanguageModel {\n const baseModel = this.#routeThroughMastraGateway\n ? (this.#mastraGateway.resolveLanguageModel(args) as GatewayLanguageModel)\n : (new ModelRouterLanguageModel({\n id: `${args.providerId}/${args.modelId}` as `${string}/${string}`,\n apiKey: args.apiKey,\n headers: args.headers,\n }) as unknown as GatewayLanguageModel);\n\n const thinkingMiddleware = createGoogleThinkingMiddleware(args.modelId, this.#thinkingLevel);\n if (!thinkingMiddleware) return baseModel;\n\n return wrapLanguageModel({\n model: baseModel as any,\n middleware: [thinkingMiddleware],\n }) as unknown as GatewayLanguageModel;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AA2DA,MAAa,wBA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S,KAAKI,cAAc;EAC3F,IAAI,CAAC,oBAAoB,OAAO;EAEhC,OAAO,kBAAkB;GACvB,OAAO;GACP,YAAY,CAAC,kBAAkB;EACjC,CAAC;CACH;AACF"}
1
+ {"version":3,"file":"mastracode-gateway.js","names":["#mastraGateway","#mastraGatewayBaseUrl","#mastraGatewayApiKey","#routeThroughMastraGateway","#thinkingLevel","#anthropicPromptCacheScope","#customProviders","#settingsPath","#credentials","#getCustomProviders","#resolveAnthropicModel","#resolveOpenAIModel","#resolveGoogleModel"],"sources":["../../src/agents/mastracode-gateway.ts"],"sourcesContent":["import { createAnthropic } from '@ai-sdk/anthropic';\nimport { createOpenAI } from '@ai-sdk/openai';\nimport { createOpenAICompatible } from '@ai-sdk/openai-compatible';\nimport type { CustomAvailableModel, CustomModelCatalogProvider } from '@mastra/core/agent-controller';\nimport {\n GATEWAY_AUTH_HEADER,\n MastraGateway,\n MastraModelGateway,\n ModelRouterLanguageModel,\n PROVIDER_REGISTRY,\n} from '@mastra/core/llm';\nimport type {\n GatewayAuthRequest,\n GatewayAuthResult,\n GatewayLanguageModel,\n MastraModelGatewayInterface,\n ProviderConfig,\n} from '@mastra/core/llm';\nimport { wrapLanguageModel } from 'ai';\nimport { AuthStorage } from '../auth/storage.js';\nimport type { CredentialStore } from '../auth/types.js';\nimport { getCustomProviderId, loadSettings, MASTRA_GATEWAY_PROVIDER } from '../onboarding/settings.js';\nimport type { AnthropicPromptCacheScope } from '../providers/anthropic-prompt-cache.js';\nimport {\n buildAnthropicOAuthFetch,\n claudeCodeMiddleware,\n createAnthropicThinkingMiddleware,\n createPromptCacheMiddleware,\n opencodeClaudeMaxProvider,\n} from '../providers/claude-max.js';\nimport { getCopilotModelCatalog, githubCopilotProvider } from '../providers/github-copilot.js';\nimport { createGoogleThinkingMiddleware } from '../providers/google-thinking.js';\nimport { KIMI_CODING_MODELS, kimiCodingProvider } from '../providers/kimi-coding.js';\nimport {\n normalizeAnthropicModelId,\n OPENAI_PREFIX,\n remapOpenAIModelForCodexOAuth,\n stripMastraGatewayPrefix,\n} from '../providers/model-ids.js';\nimport {\n buildOpenAICodexOAuthFetch,\n createCodexMiddleware,\n createReasoningEffortMiddleware,\n getEffectiveThinkingLevel,\n openaiCodexProvider,\n THINKING_LEVEL_TO_REASONING_EFFORT,\n} from '../providers/openai-codex.js';\nimport type { ThinkingLevel } from '../providers/openai-codex.js';\nimport { xaiProvider } from '../providers/xai.js';\nimport { getAppDataDir } from '../utils/project.js';\nimport { resolveCustomProviders } from './custom-provider-source.js';\n\nexport {\n MASTRA_GATEWAY_PREFIX,\n OPENAI_PREFIX,\n remapOpenAIModelForCodexOAuth,\n stripMastraGatewayPrefix,\n} from '../providers/model-ids.js';\n\nexport const MASTRACODE_GATEWAY_ID = 'mastracode';\n\ntype ModelRequestHeaders = Record<string, string>;\n\nexport type MastraCodeCustomProvider = { name: string; url: string; apiKey?: string; models?: string[] };\n\nexport type MastraCodeGatewayOptions = {\n mastraGatewayBaseUrl: string;\n mastraGatewayApiKey?: string;\n routeThroughMastraGateway: boolean;\n thinkingLevel?: ThinkingLevel;\n /** Anthropic prompt-cache breakpoints to write. Defaults to `conversation`. */\n anthropicPromptCacheScope?: AnthropicPromptCacheScope;\n customProviders?: MastraCodeCustomProvider[];\n settingsPath?: string;\n /**\n * Per-tenant credential source for this gateway instance. Defaults to the\n * server-global file-backed `AuthStorage`; deployed web passes the calling\n * tenant's store so model calls use the caller's own credentials.\n */\n credentialStore?: CredentialStore;\n};\n\n/**\n * Global file-backed credential store for local (TUI) model resolution.\n *\n * Constructed lazily, NOT at module scope: `AuthStorage`'s default path is\n * resolved from `MASTRA_APP_DATA_DIR` at construction, and this module is\n * routinely imported before test harnesses / embedders point that variable at\n * an isolated directory — an import-time construction would permanently pin\n * the developer's real app-data dir for every credential read.\n */\nlet authStorageSingleton: AuthStorage | undefined;\nlet authStorageSingletonDir: string | undefined;\n\nexport function getGlobalAuthStorage(): AuthStorage {\n // Keyed by the resolved app-data dir: in-process harnesses re-point\n // MASTRA_APP_DATA_DIR per run inside one long-lived worker, so a store\n // pinned to a previous dir must be discarded, not reused.\n const dir = getAppDataDir();\n if (!authStorageSingleton || authStorageSingletonDir !== dir) {\n authStorageSingleton = new AuthStorage();\n authStorageSingletonDir = dir;\n }\n return authStorageSingleton;\n}\n\nexport function reloadAuthStorage() {\n getGlobalAuthStorage().reload();\n}\n\n/**\n * Resolve the Anthropic API key.\n * Main slot → dedicated apikey: slot → env var.\n */\nexport function getAnthropicApiKey(credentials: CredentialStore = getGlobalAuthStorage()): string | undefined {\n const storedCred = credentials.get('anthropic');\n if (storedCred?.type === 'api_key' && storedCred.key.trim().length > 0) {\n return storedCred.key.trim();\n }\n const dedicatedKey = credentials.getStoredApiKey('anthropic')?.trim();\n if (dedicatedKey) return dedicatedKey;\n return credentials.allowEnvironmentFallback === false\n ? undefined\n : process.env.ANTHROPIC_API_KEY?.trim() || undefined;\n}\n\n/**\n * Resolve the OpenAI API key.\n * Main slot → dedicated apikey: slot → env var.\n */\nexport function getOpenAIApiKey(credentials: CredentialStore = getGlobalAuthStorage()): string | undefined {\n const storedCred = credentials.get('openai-codex');\n if (storedCred?.type === 'api_key' && storedCred.key.trim().length > 0) {\n return storedCred.key.trim();\n }\n const dedicatedKey = credentials.getStoredApiKey('openai-codex')?.trim();\n if (dedicatedKey) return dedicatedKey;\n return credentials.allowEnvironmentFallback === false ? undefined : process.env.OPENAI_API_KEY?.trim() || undefined;\n}\n\nfunction anthropicApiKeyProvider(\n modelId: string,\n apiKey: string,\n headers: ModelRequestHeaders | undefined,\n thinkingLevel: ThinkingLevel | undefined,\n promptCacheScope: AnthropicPromptCacheScope,\n) {\n const anthropic = createAnthropic({ apiKey, headers });\n const thinkingMiddleware = createAnthropicThinkingMiddleware(modelId, thinkingLevel);\n return wrapLanguageModel({\n model: anthropic(modelId),\n middleware: [createPromptCacheMiddleware(promptCacheScope), ...(thinkingMiddleware ? [thinkingMiddleware] : [])],\n });\n}\n\nfunction openaiApiKeyProvider(\n modelId: string,\n apiKey: string,\n headers?: ModelRequestHeaders,\n thinkingLevel?: ThinkingLevel,\n) {\n const openai = createOpenAI({ apiKey, baseURL: process.env.OPENAI_BASE_URL, headers });\n const middleware =\n thinkingLevel && thinkingLevel !== 'off'\n ? createReasoningEffortMiddleware(\n 'openai',\n THINKING_LEVEL_TO_REASONING_EFFORT[getEffectiveThinkingLevel(modelId, thinkingLevel)],\n )\n : undefined;\n return wrapLanguageModel({\n model: openai.responses(modelId),\n middleware: middleware ? [middleware] : [],\n });\n}\n\nfunction getAuthProviderId(providerId: string): string {\n return providerId === 'openai' ? 'openai-codex' : providerId;\n}\n\nfunction getProviderAuthKey(\n providerId: string,\n credentials: CredentialStore = getGlobalAuthStorage(),\n): string | undefined {\n const authProviderId = getAuthProviderId(providerId);\n const storedCred = credentials.get(authProviderId);\n if (storedCred?.type === 'api_key' && storedCred.key.trim().length > 0) {\n return storedCred.key.trim();\n }\n const dedicatedKey = credentials.getStoredApiKey(authProviderId)?.trim();\n if (dedicatedKey) return dedicatedKey;\n if (credentials.allowEnvironmentFallback === false) return undefined;\n return authProviderId === 'kimi-for-coding' ? process.env.KIMI_API_KEY?.trim() || undefined : undefined;\n}\n\nexport function resolveAuth(request: GatewayAuthRequest, mastraGatewayApiKey?: string): GatewayAuthResult | undefined {\n return MastraCodeGateway.resolveProviderAuth(request, mastraGatewayApiKey);\n}\n\nfunction getGatewayProviderKey(gatewayId: string, providerId: string): string {\n if (gatewayId === 'models.dev') return providerId;\n return providerId === gatewayId ? gatewayId : `${gatewayId}/${providerId}`;\n}\n\nfunction parseGatewayRouterId(\n routerId: string,\n gateway: MastraModelGatewayInterface,\n): { gatewayId: string; providerId: string; modelId: string } {\n const [firstPart = '', secondPart = '', ...restParts] = routerId.split('/');\n const gatewayId = gateway.id;\n\n if (firstPart === gatewayId && secondPart) {\n return {\n gatewayId,\n providerId: secondPart,\n modelId: restParts.join('/'),\n };\n }\n\n return {\n gatewayId,\n providerId: firstPart,\n modelId: [secondPart, ...restParts].filter(Boolean).join('/'),\n };\n}\n\nfunction hasResolvedAuth(auth: GatewayAuthResult | undefined): boolean {\n if (!auth) return false;\n if (auth.apiKey || auth.bearerToken) return true;\n return auth.headers ? Object.keys(auth.headers).length > 0 : false;\n}\n\nasync function resolveGatewayProviderAuth(\n gateway: MastraModelGatewayInterface,\n routerId: string,\n): Promise<GatewayAuthResult | undefined> {\n if (!gateway.resolveAuth) return undefined;\n\n const parsed = parseGatewayRouterId(routerId, gateway);\n try {\n const result = await gateway.resolveAuth({\n gatewayId: parsed.gatewayId,\n providerId: parsed.providerId,\n modelId: parsed.modelId,\n routerId,\n });\n return hasResolvedAuth(result) ? result : undefined;\n } catch {\n return undefined;\n }\n}\n\nasync function getMastraCodeProviderConfigs(\n gateway: MastraModelGatewayInterface,\n): Promise<Record<string, ProviderConfig>> {\n const providers: Record<string, ProviderConfig> = { ...(PROVIDER_REGISTRY as Record<string, ProviderConfig>) };\n\n try {\n const gatewayProviders = await gateway.fetchProviders();\n for (const [providerId, config] of Object.entries(gatewayProviders)) {\n providers[getGatewayProviderKey(gateway.id, providerId)] = {\n ...config,\n gateway: gateway.id,\n };\n }\n } catch (error) {\n console.warn(`Failed to load providers from gateway ${gateway.id}:`, error);\n }\n\n return providers;\n}\n\nfunction getApiKeyEnvVar(providerConfig: Pick<ProviderConfig, 'apiKeyEnvVar'> | undefined): string | undefined {\n const envVars = providerConfig?.apiKeyEnvVar;\n return Array.isArray(envVars) ? envVars[0] : envVars;\n}\n\nexport class MastraCodeGateway extends MastraModelGateway {\n readonly id = MASTRACODE_GATEWAY_ID;\n readonly name = 'MastraCode Gateway';\n\n readonly #mastraGateway: MastraGateway;\n readonly #mastraGatewayBaseUrl: string;\n readonly #mastraGatewayApiKey?: string;\n readonly #routeThroughMastraGateway: boolean;\n readonly #thinkingLevel?: ThinkingLevel;\n readonly #anthropicPromptCacheScope: AnthropicPromptCacheScope;\n readonly #customProviders?: MastraCodeCustomProvider[];\n readonly #settingsPath?: string;\n readonly #credentials: CredentialStore;\n\n constructor({\n mastraGatewayBaseUrl,\n mastraGatewayApiKey,\n routeThroughMastraGateway,\n thinkingLevel,\n anthropicPromptCacheScope,\n customProviders,\n settingsPath,\n credentialStore,\n }: MastraCodeGatewayOptions) {\n super();\n this.#mastraGateway = new MastraGateway({ baseUrl: mastraGatewayBaseUrl });\n this.#mastraGatewayBaseUrl = mastraGatewayBaseUrl;\n this.#mastraGatewayApiKey = mastraGatewayApiKey;\n this.#routeThroughMastraGateway = routeThroughMastraGateway;\n this.#thinkingLevel = thinkingLevel;\n this.#anthropicPromptCacheScope = anthropicPromptCacheScope ?? 'conversation';\n this.#customProviders = customProviders;\n this.#settingsPath = settingsPath;\n this.#credentials = credentialStore ?? getGlobalAuthStorage();\n }\n\n static getMastraGatewayApiKey(): string | undefined {\n return getGlobalAuthStorage().getStoredApiKey(MASTRA_GATEWAY_PROVIDER) ?? process.env['MASTRA_GATEWAY_API_KEY'];\n }\n\n /** @deprecated Renamed to {@link MastraCodeGateway.getMastraGatewayApiKey}. */\n static getMemoryGatewayApiKey(): string | undefined {\n return MastraCodeGateway.getMastraGatewayApiKey();\n }\n\n /**\n * Claim an unprefixed model id (e.g. a bare `anthropic/...`) when this gateway\n * can authenticate it via OAuth or a stored/env credential. This lets the\n * shared gateway router select MastraCode for auth resolution, so the status\n * bar and `/api-keys` reflect OAuth logins instead of only checking env vars.\n */\n handlesModel(modelId: string): boolean {\n const parsed = parseGatewayRouterId(modelId, this);\n if (!parsed.providerId || !parsed.modelId) return false;\n if (this.#routeThroughMastraGateway && this.#mastraGatewayApiKey) return true;\n const customProvider = this.#getCustomProviders().find(\n provider => parsed.providerId === getCustomProviderId(provider.name),\n );\n if (customProvider?.apiKey) return true;\n return hasResolvedAuth(\n MastraCodeGateway.resolveProviderAuth(\n {\n gatewayId: this.id,\n providerId: parsed.providerId,\n modelId: parsed.modelId,\n routerId: modelId,\n },\n undefined,\n this.#credentials,\n ),\n );\n }\n\n static resolveProviderAuth(\n request: GatewayAuthRequest,\n mastraGatewayApiKey?: string,\n credentials: CredentialStore = getGlobalAuthStorage(),\n ): GatewayAuthResult | undefined {\n if (request.gatewayId === 'mastra' && mastraGatewayApiKey) {\n return { apiKey: mastraGatewayApiKey, source: 'gateway' };\n }\n\n const authProviderId = getAuthProviderId(request.providerId);\n const storedCred = credentials.get(authProviderId);\n if (storedCred?.type === 'oauth') {\n return { bearerToken: 'oauth', source: 'gateway' };\n }\n\n const apiKey = getProviderAuthKey(request.providerId, credentials);\n return apiKey ? { apiKey, source: 'gateway' } : undefined;\n }\n\n static createModelCatalogProvider(gateway: MastraModelGatewayInterface): CustomModelCatalogProvider {\n return async () => {\n const registry = await getMastraCodeProviderConfigs(gateway);\n const models: CustomAvailableModel[] = [];\n\n for (const [provider, providerConfig] of Object.entries(registry)) {\n const apiKeyEnvVar = getApiKeyEnvVar(providerConfig);\n const hasEnvKey = apiKeyEnvVar ? Boolean(process.env[apiKeyEnvVar]) : false;\n const modelNames = providerConfig.models;\n if (!Array.isArray(modelNames)) continue;\n\n const gatewayAuth = modelNames[0]\n ? await resolveGatewayProviderAuth(gateway, `${provider}/${modelNames[0]}`)\n : undefined;\n\n for (const modelName of modelNames) {\n const id = `${provider}/${modelName}`;\n models.push({\n id,\n provider,\n modelName,\n hasApiKey: hasEnvKey || Boolean(gatewayAuth),\n apiKeyEnvVar: apiKeyEnvVar || undefined,\n });\n }\n }\n\n return models;\n };\n }\n\n createModelCatalogProvider(): CustomModelCatalogProvider {\n return MastraCodeGateway.createModelCatalogProvider(this);\n }\n\n #getCustomProviders(): MastraCodeCustomProvider[] {\n // Explicit constructor list wins; then a registered source (deployed web,\n // DB-backed — authoritative, so settings.json is never consulted); then\n // the local file-backed settings.\n return this.#customProviders ?? resolveCustomProviders() ?? loadSettings(this.#settingsPath).customProviders;\n }\n\n async fetchProviders(): Promise<Record<string, ProviderConfig>> {\n const providers: Record<string, ProviderConfig> = {};\n for (const provider of this.#getCustomProviders()) {\n const models = provider.models ?? [];\n if (!models.length) continue;\n providers[getCustomProviderId(provider.name)] = {\n name: provider.name,\n url: provider.url,\n apiKeyEnvVar: '',\n apiKeyHeader: 'Authorization',\n gateway: this.id,\n models,\n };\n }\n\n providers['kimi-for-coding'] = {\n name: 'Kimi For Coding',\n apiKeyEnvVar: 'KIMI_API_KEY',\n apiKeyHeader: 'Authorization',\n gateway: this.id,\n models: [...KIMI_CODING_MODELS],\n };\n\n try {\n const copilotModels = await getCopilotModelCatalog({ authStorage: this.#credentials });\n providers['github-copilot'] = {\n name: 'GitHub Copilot',\n apiKeyEnvVar: '',\n apiKeyHeader: 'Authorization',\n gateway: this.id,\n models: copilotModels.map(model => model.id),\n };\n } catch (error) {\n console.warn('Failed to load GitHub Copilot model catalog:', error);\n }\n\n return providers;\n }\n\n buildUrl(modelId: string): string | undefined | Promise<string | undefined> {\n return this.#routeThroughMastraGateway ? this.#mastraGateway.buildUrl(modelId) : modelId;\n }\n\n async getApiKey(modelId: string): Promise<string> {\n const providerId = stripMastraGatewayPrefix(modelId).split('/', 1)[0];\n if (this.#routeThroughMastraGateway) return this.#mastraGatewayApiKey ?? '';\n return providerId ? (getProviderAuthKey(providerId, this.#credentials) ?? '') : '';\n }\n\n resolveAuth(request: GatewayAuthRequest): GatewayAuthResult | undefined {\n if (this.#routeThroughMastraGateway && this.#mastraGatewayApiKey) {\n return { apiKey: this.#mastraGatewayApiKey, source: 'gateway' };\n }\n\n const customProvider = this.#getCustomProviders().find(\n provider => request.providerId === getCustomProviderId(provider.name),\n );\n if (customProvider?.apiKey) {\n return { apiKey: customProvider.apiKey, source: 'gateway' };\n }\n\n return MastraCodeGateway.resolveProviderAuth(request, undefined, this.#credentials);\n }\n\n resolveLanguageModel(args: {\n modelId: string;\n providerId: string;\n apiKey: string;\n headers?: Record<string, string>;\n transport?: any;\n responsesWebSocket?: any;\n }): GatewayLanguageModel {\n const customProvider = this.#getCustomProviders().find(\n provider => args.providerId === getCustomProviderId(provider.name),\n );\n if (customProvider) {\n const provider = createOpenAICompatible({\n name: args.providerId,\n baseURL: customProvider.url,\n apiKey: args.apiKey,\n headers: args.headers,\n });\n const reasoningEffort = this.#thinkingLevel ? THINKING_LEVEL_TO_REASONING_EFFORT[this.#thinkingLevel] : undefined;\n const middleware = createReasoningEffortMiddleware(args.providerId, reasoningEffort);\n if (!middleware) {\n return provider.chatModel(args.modelId) as unknown as GatewayLanguageModel;\n }\n return wrapLanguageModel({\n model: provider.chatModel(args.modelId),\n middleware: [middleware],\n }) as unknown as GatewayLanguageModel;\n }\n\n if (args.providerId === 'github-copilot') {\n return githubCopilotProvider(args.modelId, {\n headers: args.headers,\n authStorage: this.#credentials,\n }) as unknown as GatewayLanguageModel;\n }\n\n if (args.providerId === 'moonshotai') {\n // Prefer the gateway-resolved key (stored credentials), then the canonical\n // registry env var. Keep the legacy typo name as a fallback for anyone who\n // set it because of the previous error message.\n const apiKey =\n args.apiKey?.trim() || process.env.MOONSHOT_API_KEY?.trim() || process.env.MOONSHOT_AI_API_KEY?.trim();\n if (!apiKey) {\n throw new Error('Need MOONSHOT_API_KEY');\n }\n return createAnthropic({\n apiKey,\n baseURL: 'https://api.moonshot.ai/anthropic/v1',\n name: 'moonshotai.anthropicv1',\n headers: args.headers,\n })(args.modelId) as unknown as GatewayLanguageModel;\n }\n\n if (args.providerId === 'anthropic') {\n return this.#resolveAnthropicModel(args);\n }\n\n if (args.providerId === 'openai') {\n const openaiModel = this.#resolveOpenAIModel(args);\n if (openaiModel) return openaiModel;\n }\n\n if (args.providerId === 'xai' && this.#credentials.get('xai')?.type === 'oauth') {\n return xaiProvider(args.modelId, {\n headers: args.headers,\n authStorage: this.#credentials,\n }) as unknown as GatewayLanguageModel;\n }\n\n if (args.providerId === 'google') {\n return this.#resolveGoogleModel(args);\n }\n\n if (this.#routeThroughMastraGateway) {\n return this.#mastraGateway.resolveLanguageModel(args) as GatewayLanguageModel;\n }\n\n if (args.providerId === 'kimi-for-coding') {\n return kimiCodingProvider(args.modelId, {\n apiKey: args.apiKey,\n headers: args.headers,\n credentialStore: this.#credentials,\n }) as unknown as GatewayLanguageModel;\n }\n\n return new ModelRouterLanguageModel({\n id: `${args.providerId}/${args.modelId}` as `${string}/${string}`,\n apiKey: args.apiKey,\n headers: args.headers,\n }) as unknown as GatewayLanguageModel;\n }\n\n #resolveAnthropicModel(args: {\n modelId: string;\n providerId: string;\n apiKey: string;\n headers?: Record<string, string>;\n transport?: any;\n responsesWebSocket?: any;\n }): GatewayLanguageModel {\n const bareModelId = normalizeAnthropicModelId(args.modelId);\n const storedCred = this.#credentials.get('anthropic');\n const thinkingMiddleware = createAnthropicThinkingMiddleware(bareModelId, this.#thinkingLevel);\n\n if (this.#routeThroughMastraGateway) {\n if (storedCred?.type === 'oauth') {\n const anthropic = createAnthropic({\n apiKey: 'oauth-gateway-placeholder',\n baseURL: `${this.#mastraGatewayBaseUrl}/v1`,\n headers: {\n [GATEWAY_AUTH_HEADER]: `Bearer ${args.apiKey}`,\n ...args.headers,\n },\n fetch: buildAnthropicOAuthFetch({ authStorage: this.#credentials }) as any,\n });\n\n return wrapLanguageModel({\n model: anthropic(bareModelId),\n middleware: [\n claudeCodeMiddleware,\n createPromptCacheMiddleware(this.#anthropicPromptCacheScope),\n ...(thinkingMiddleware ? [thinkingMiddleware] : []),\n ],\n }) as unknown as GatewayLanguageModel;\n }\n\n const gatewayModel = this.#mastraGateway.resolveLanguageModel({\n ...args,\n modelId: bareModelId,\n }) as GatewayLanguageModel;\n if (!thinkingMiddleware) return gatewayModel;\n return wrapLanguageModel({\n model: gatewayModel as any,\n middleware: [thinkingMiddleware],\n }) as unknown as GatewayLanguageModel;\n }\n\n if (storedCred?.type === 'oauth') {\n return opencodeClaudeMaxProvider(bareModelId, {\n headers: args.headers,\n authStorage: this.#credentials,\n thinkingLevel: this.#thinkingLevel,\n promptCacheScope: this.#anthropicPromptCacheScope,\n }) as unknown as GatewayLanguageModel;\n }\n\n if (storedCred?.type === 'api_key' && storedCred.key.trim().length > 0) {\n return anthropicApiKeyProvider(\n bareModelId,\n storedCred.key.trim(),\n args.headers,\n this.#thinkingLevel,\n this.#anthropicPromptCacheScope,\n ) as unknown as GatewayLanguageModel;\n }\n\n const apiKey = getAnthropicApiKey(this.#credentials);\n if (apiKey) {\n return anthropicApiKeyProvider(\n bareModelId,\n apiKey,\n args.headers,\n this.#thinkingLevel,\n this.#anthropicPromptCacheScope,\n ) as unknown as GatewayLanguageModel;\n }\n\n // No stored credentials: use the OAuth-backed provider so the first request can trigger login.\n return opencodeClaudeMaxProvider(bareModelId, {\n headers: args.headers,\n authStorage: this.#credentials,\n thinkingLevel: this.#thinkingLevel,\n promptCacheScope: this.#anthropicPromptCacheScope,\n }) as unknown as GatewayLanguageModel;\n }\n\n #resolveOpenAIModel(args: {\n modelId: string;\n providerId: string;\n apiKey: string;\n headers?: Record<string, string>;\n transport?: any;\n responsesWebSocket?: any;\n }): GatewayLanguageModel | undefined {\n const storedCred = this.#credentials.get('openai-codex');\n\n if (this.#routeThroughMastraGateway) {\n if (storedCred?.type === 'oauth') {\n const resolvedModelId = remapOpenAIModelForCodexOAuth(`openai/${args.modelId}`);\n const resolvedBareModelId = resolvedModelId.substring(OPENAI_PREFIX.length);\n const effectiveLevel = getEffectiveThinkingLevel(args.modelId, this.#thinkingLevel ?? 'medium');\n const reasoningEffort = THINKING_LEVEL_TO_REASONING_EFFORT[effectiveLevel];\n const middleware = createCodexMiddleware(reasoningEffort);\n const openai = createOpenAI({\n apiKey: 'oauth-gateway-placeholder',\n baseURL: `${this.#mastraGatewayBaseUrl}/v1`,\n headers: {\n [GATEWAY_AUTH_HEADER]: `Bearer ${args.apiKey}`,\n ...args.headers,\n },\n fetch: buildOpenAICodexOAuthFetch({ authStorage: this.#credentials, rewriteUrl: false }) as any,\n });\n\n return wrapLanguageModel({\n model: openai.responses(resolvedBareModelId),\n middleware: [middleware],\n }) as unknown as GatewayLanguageModel;\n }\n\n return this.#mastraGateway.resolveLanguageModel(args) as GatewayLanguageModel;\n }\n\n if (storedCred?.type === 'oauth') {\n const resolvedModelId = remapOpenAIModelForCodexOAuth(`openai/${args.modelId}`);\n return openaiCodexProvider(resolvedModelId.substring(OPENAI_PREFIX.length), {\n thinkingLevel: this.#thinkingLevel && 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(\n args.modelId,\n apiKey,\n args.headers,\n this.#thinkingLevel,\n ) as unknown as GatewayLanguageModel;\n }\n\n return undefined;\n }\n\n #resolveGoogleModel(args: {\n modelId: string;\n providerId: string;\n apiKey: string;\n headers?: Record<string, string>;\n transport?: any;\n responsesWebSocket?: any;\n }): GatewayLanguageModel {\n const baseModel = this.#routeThroughMastraGateway\n ? (this.#mastraGateway.resolveLanguageModel(args) as GatewayLanguageModel)\n : (new ModelRouterLanguageModel({\n id: `${args.providerId}/${args.modelId}` as `${string}/${string}`,\n apiKey: args.apiKey,\n headers: args.headers,\n }) as unknown as GatewayLanguageModel);\n\n const thinkingMiddleware = createGoogleThinkingMiddleware(args.modelId, this.#thinkingLevel);\n if (!thinkingMiddleware) return baseModel;\n\n return wrapLanguageModel({\n model: baseModel as any,\n middleware: [thinkingMiddleware],\n }) as unknown as GatewayLanguageModel;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AA2DA,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;CAC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KAAK,SAAS,KAAKC,kBAAkB,QACd;IACxE,MAAM,aAAa,sBAAsB,eAAe;IAWxD,OAAO,kBAAkB;KACvB,OAXa,aAAa;MAC1B,QAAQ;MACR,SAAS,GAAG,KAAKH,sBAAsB;MACvC,SAAS;QACN,sBAAsB,UAAU,KAAK;OACtC,GAAG,KAAK;MACV;MACA,OAAO,2BAA2B;OAAE,aAAa,KAAKO;OAAc,YAAY;MAAM,CAAC;KACzF,CAGc,CAAC,CAAC,UAAU,mBAAmB;KAC3C,YAAY,CAAC,UAAU;IACzB,CAAC;GACH;GAEA,OAAO,KAAKR,eAAe,qBAAqB,IAAI;EACtD;EAEA,IAAI,YAAY,SAAS,SAEvB,OAAO,oBADiB,8BAA8B,UAAU,KAAK,SAC5B,CAAC,CAAC,UAAU,cAAc,MAAM,GAAG;GAC1E,eAAe,KAAKI,kBAAkB,0BAA0B,KAAK,SAAS,KAAKA,cAAc;GACjG,SAAS,KAAK;GACd,aAAa,KAAKI;EACpB,CAAC;EAGH,MAAM,SAAS,gBAAgB,KAAKA,YAAY;EAChD,IAAI,QACF,OAAO,qBACL,KAAK,SACL,QACA,KAAK,SACL,KAAKJ,cACP;CAIJ;CAEA,oBAAoB,MAOK;EACvB,MAAM,YAAY,KAAKD,6BAClB,KAAKH,eAAe,qBAAqB,IAAI,IAC7C,IAAI,yBAAyB;GAC5B,IAAI,GAAG,KAAK,WAAW,GAAG,KAAK;GAC/B,QAAQ,KAAK;GACb,SAAS,KAAK;EAChB,CAAC;EAEL,MAAM,qBAAqB,+BAA+B,KAAK,SAAS,KAAKI,cAAc;EAC3F,IAAI,CAAC,oBAAoB,OAAO;EAEhC,OAAO,kBAAkB;GACvB,OAAO;GACP,YAAY,CAAC,kBAAkB;EACjC,CAAC;CACH;AACF"}
@@ -12,7 +12,7 @@ export interface AccountSwitchPartData {
12
12
  id: string;
13
13
  label: string;
14
14
  } | null;
15
- reason: 'rate-limit' | 'quota-exhausted' | 'auth-failed' | 'pool-exhausted' | 'persistent-outage' | 'preferred-routing' | 'starting-on-account';
15
+ reason: 'rate-limit' | 'quota-exhausted' | 'auth-failed' | 'pool-exhausted' | 'persistent-outage' | 'preferred-routing';
16
16
  at: string;
17
17
  /**
18
18
  * Set on a `to: null` part when a route pinned to a single account reported
@@ -160,8 +160,9 @@ export declare class AccountRotationProcessor implements Processor {
160
160
  private declarePoolUnavailable;
161
161
  }
162
162
  /**
163
- * Emits the "starting on a non-default account" notice (Q19) once per
164
- * request when the active registry account is not the first entry.
163
+ * Applies the pack's preferred account route once per request, before the
164
+ * first model call. Without a route it only reloads the credential store so
165
+ * the request sees accounts changed by other processes.
165
166
  *
166
167
  * TYPE CONSTRAINT: this class must NEVER implement `processAPIError`. It
167
168
  * lives in `inputProcessors`; the runner walks input processors first when
@@ -1 +1 @@
1
- {"version":3,"file":"account-rotation-processor.d.ts","sourceRoot":"","sources":["../../src/auth/account-rotation-processor.ts"],"names":[],"mappings":"AAsBA,OAAO,KAAK,EAAE,mBAAmB,EAAE,gBAAgB,EAAE,kBAAkB,EAAE,SAAS,EAAE,MAAM,yBAAyB,CAAC;AAYpH,OAAO,KAAK,EAAE,eAAe,EAAsB,MAAM,YAAY,CAAC;AAEtE,eAAO,MAAM,wBAAwB,mCAAmC,CAAC;AAEzE,yEAAyE;AACzE,MAAM,WAAW,qBAAqB;IACpC,QAAQ,EAAE,MAAM,CAAC;IACjB,IAAI,EAAE;QAAE,EAAE,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,GAAG,IAAI,CAAC;IAC3C,EAAE,EAAE;QAAE,EAAE,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,GAAG,IAAI,CAAC;IACzC,MAAM,EACF,YAAY,GACZ,iBAAiB,GACjB,aAAa,GACb,gBAAgB,GAChB,mBAAmB,GACnB,mBAAmB,GACnB,qBAAqB,CAAC;IAC1B,EAAE,EAAE,MAAM,CAAC;IACX;;;;;OAKG;IACH,SAAS,C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EXT = {
222
222
  };
223
223
  /** Validates untrusted `reason` values (e.g. persisted message parts). */
224
224
  function isAccountSwitchReason(value) {
225
- return value === "starting-on-account" || typeof value === "string" && Object.prototype.hasOwnProperty.call(REASON_TEXT, value);
225
+ return typeof value === "string" && Object.prototype.hasOwnProperty.call(REASON_TEXT, value);
226
226
  }
227
227
  /**
228
228
  * One-line transcript copy for a switch part. Shared by the live `info`
@@ -232,8 +232,7 @@ function isAccountSwitchReason(value) {
232
232
  */
233
233
  function accountSwitchNoticeText(data) {
234
234
  const provider = PROVIDER_DISPLAY_NAMES[data.provider] ?? data.provider;
235
- if (data.reason === "starting-on-account" && data.to) return `Starting on ${provider} account: ${data.to.label}`;
236
- const reason = data.reason === "starting-on-account" ? data.reason : REASON_TEXT[data.reason];
235
+ const reason = REASON_TEXT[data.reason];
237
236
  if (data.to === null) {
238
237
  if (data.exclusive) return `Pinned ${provider} account unavailable (${reason})`;
239
238
  return `All ${provider} accounts unavailable (${reason})`;
@@ -576,8 +575,9 @@ var AccountRotationProcessor = class {
576
575
  }
577
576
  };
578
577
  /**
579
- * Emits the "starting on a non-default account" notice (Q19) once per
580
- * request when the active registry account is not the first entry.
578
+ * Applies the pack's preferred account route once per request, before the
579
+ * first model call. Without a route it only reloads the credential store so
580
+ * the request sees accounts changed by other processes.
581
581
  *
582
582
  * TYPE CONSTRAINT: this class must NEVER implement `processAPIError`. It
583
583
  * lives in `inputProcessors`; the runner walks input processors first when
@@ -594,30 +594,11 @@ var AccountStartNoticeProcessor = class {
594
594
  if (args.state.startNoticeEmitted) return args.messageList;
595
595
  const store = resolveCredentialStore(args.requestContext) ?? this.options.credentialStore;
596
596
  const route = resolveAccountRoute(args);
597
- if (route) {
598
- if (await applyPreferredAccountRoute(args, store, route) || getRouteTargetAccountId(route) !== void 0) {
599
- args.state.startNoticeEmitted = true;
600
- return args.messageList;
601
- }
602
- } else store.reload();
603
- const providerId = route?.providerId ?? providerFromSession(args);
604
- if (!providerId) return args.messageList;
605
- const accounts = store.listAccounts?.(providerId) ?? [];
606
- if (accounts.length < 2) return args.messageList;
607
- const active = store.getActiveAccount?.(providerId);
608
- const first = accounts[0];
609
- if (!active || !first || active.id === first.id) return args.messageList;
610
- args.state.startNoticeEmitted = true;
611
- await emitAccountSwitchPart(args, {
612
- provider: providerId,
613
- from: null,
614
- to: {
615
- id: active.id,
616
- label: active.label
617
- },
618
- reason: "starting-on-account",
619
- at: (/* @__PURE__ */ new Date()).toISOString()
620
- });
597
+ if (!route) {
598
+ store.reload();
599
+ return args.messageList;
600
+ }
601
+ if (await applyPreferredAccountRoute(args, store, route) || getRouteTargetAccountId(route) !== void 0) args.state.startNoticeEmitted = true;
621
602
  return args.messageList;
622
603
  }
623
604
  };
@@ -1 +1 @@
1
- {"version":3,"file":"account-rotation-processor.js","names":[],"sources":["../../src/auth/account-rotation-processor.ts"],"sourcesContent":["/**\n * Error-driven rotation across a provider's OAuth account registry.\n *\n * When the active account cannot serve a request (rate limit, quota\n * exhaustion, dead token, persistent outage), the next account in insertion\n * order is selected for the request and the request retried. OAuth fetch\n * wrappers read that request-scoped selection on every HTTP attempt, so\n * concurrent runs can't swap each other's credentials. Every switch is\n * persisted as a non-transient `data-mastracode-account-switch` part so it\n * shows in the transcript and survives history reload.\n *\n * Two classes, two lanes — the split is load-bearing. The processor runner\n * walks `[...inputProcessors, ...outputProcessors, ...errorProcessors]` when\n * running `processAPIError`, so a processor registered in the input lane that\n * also implemented `processAPIError` would run BEFORE\n * `StreamErrorRetryProcessor` and hop on 5xx errors before transient retries\n * had a chance. `AccountRotationProcessor` therefore implements\n * `processAPIError` only and is registered in `errorProcessors` after\n * `StreamErrorRetryProcessor`; `AccountStartNoticeProcessor` implements\n * `processInput` only and is registered in `inputProcessors`.\n */\nimport { TripWire } from '@mastra/core/agent';\nimport type { ProcessAPIErrorArgs, ProcessInputArgs, ProcessInputResult, Processor } from '@mastra/core/processors';\n\nimport { resolveCredentialStore } from '../agents/credential-resolver.js';\nimport { resolveModel, resolveRequestThinkingLevel } from '../agents/model.js';\nimport {\n getRequestAccountSelection,\n isRequestAccountRoutingExhausted,\n markRequestAccountRoutingExhausted,\n setRequestAccountSelection,\n} from './account-routing-context.js';\nimport { ProviderAuthRequiredError, PROVIDER_AUTH_REQUIRED_ERROR } from './provider-auth-error.js';\nimport { getOAuthProviders } from './storage.js';\nimport type { CredentialStore, OAuthAccountRecord } from './types.js';\n\nexport const ACCOUNT_SWITCH_PART_TYPE = 'data-mastracode-account-switch';\n\n/** Labels and instance ids only — never token material (do-not list). */\nexport interface AccountSwitchPartData {\n provider: string;\n from: { id: string; label: string } | null;\n to: { id: string; label: string } | null;\n reason:\n | 'rate-limit'\n | 'quota-exhausted'\n | 'auth-failed'\n | 'pool-exhausted'\n | 'persistent-outage'\n | 'preferred-routing'\n | 'starting-on-account';\n at: string;\n /**\n * Set on a `to: null` part when a route pinned to a single account reported\n * that account unusable. The provider's other subscriptions were never\n * consulted (A12), so \"all accounts unavailable\" would misreport what\n * happened.\n */\n exclusive?: boolean;\n}\n\n/** The store surface rotation needs; `AuthStorage` satisfies it structurally. */\nexport type RotationCredentialStore = CredentialStore & {\n /**\n * Force one refresh of the active account's tokens regardless of expiry\n * (401/403 path — a rejected-but-unexpired token usually means clock skew\n * or a refresh race). `AuthStorage` provides it; deployed per-tenant stores\n * don't, and the auth path degrades to plain rotation (which itself no-ops\n * without registry methods).\n */\n forceRefreshActiveAccount?(providerId: string, accountInstanceId?: string): Promise<string | undefined>;\n};\n\n/** Rotatable providers = the OAuth provider registry; API-key-only providers never rotate. */\nconst KNOWN_PROVIDER_IDS = new Set(getOAuthProviders().map(provider => provider.id));\n\n/** Hostname suffixes → provider ids, for `APICallError.url`. */\nconst PROVIDER_HOST_PATTERNS: Array<[RegExp, string]> = [\n [/(^|\\.)api\\.anthropic\\.com$/i, 'anthropic'],\n [/(^|\\.)api\\.kimi\\.com$/i, 'kimi-for-coding'],\n [/(^|\\.)api\\.x\\.ai$/i, 'xai'],\n [/(^|\\.)chatgpt\\.com$/i, 'openai-codex'],\n [/(^|\\.)backend-api\\.codex\\.ai$/i, 'openai-codex'],\n [/(^|\\.)githubcopilot\\.com$/i, 'github-copilot'],\n [/(^|\\.)api\\.github\\.com$/i, 'github-copilot'],\n];\n\n/**\n * Provider usage/quota-limit wording (locked Q7 bucket 1). Statuses 429/402\n * are matched before this; some providers deliver quota errors as plain 400s,\n * which only the message reveals. Deliberately restricted to unambiguous\n * quota phrases — a generic \"exceeded your … limit\" can appear on non-quota\n * client errors (request size, context length) that must never rotate.\n */\nconst USAGE_LIMIT_MESSAGE_PATTERN =\n /usage (?:limit|cap)|insufficient[_ ]quota|quota (?:exceeded|exhausted|reached)|exceeded (?:your )?current quota|insufficient (?:balance|credits?)|credits? exhausted|rate limit (?:exceeded|reached)|weekly limit|monthly limit/i;\n\nconst NETWORK_ERROR_CODES = new Set([\n 'ECONNRESET',\n 'EPIPE',\n 'ECONNREFUSED',\n 'ENOTFOUND',\n 'ETIMEDOUT',\n 'EAI_AGAIN',\n 'UND_ERR_CONNECT_TIMEOUT',\n 'UND_ERR_SOCKET',\n]);\n\nconst NETWORK_MESSAGE_PATTERN =\n /fetch failed|network error|socket hang up|getaddrinfo|econnrefused|enotfound|etimedout|connection (?:refused|reset|closed|timed out)|other side closed|write epipe/i;\n\nconst MAX_CAUSE_DEPTH = 4;\n\n/** Persisted data-part type for a model-route hop. */\nexport const MODEL_FALLBACK_PART_TYPE = 'data-mastracode-model-fallback' as const;\n\n/** Non-secret transcript payload for a model-route hop. */\nexport interface ModelFallbackPartData {\n from: { entryId: string; label: string };\n to: { entryId: string; label: string };\n reason: 'pool-exhausted' | 'persistent-outage';\n at: string;\n}\n\n/** Session-state key set when account rotation advances the model route. */\nexport const MODEL_FALLBACK_STATE_KEY = 'mastracodePendingModelFallback' as const;\n\n/** Payload written to session state under MODEL_FALLBACK_STATE_KEY. */\nexport interface PendingModelFallback {\n fromEntryId: string;\n toEntryId: string;\n toModelId: string;\n threadId?: string;\n reason: 'pool-exhausted' | 'persistent-outage';\n at: string;\n}\n\nexport type RotationClassification =\n | { kind: 'rotate'; reason: 'rate-limit' | 'quota-exhausted' | 'auth-failed' }\n | { kind: 'hop' }\n | { kind: 'never' };\n\nfunction isErrorWithCode(error: unknown): error is { code?: unknown } {\n return typeof error === 'object' && error !== null && 'code' in error;\n}\n\nfunction readErrorStatus(error: unknown): number | undefined {\n let current: unknown = error;\n for (let depth = 0; current && depth < MAX_CAUSE_DEPTH; depth++) {\n if (typeof current !== 'object') break;\n const { statusCode, status } = current as { statusCode?: unknown; status?: unknown };\n if (typeof statusCode === 'number') return statusCode;\n if (typeof status === 'number') return status;\n current = (current as { cause?: unknown }).cause;\n }\n return undefined;\n}\n\nfunction isProviderAuthRequiredError(error: unknown): boolean {\n let current: unknown = error;\n for (let depth = 0; current && depth < MAX_CAUSE_DEPTH; depth++) {\n if (\n current instanceof ProviderAuthRequiredError ||\n (current instanceof Error && current.name === PROVIDER_AUTH_REQUIRED_ERROR)\n ) {\n return true;\n }\n if (typeof current !== 'object') break;\n current = (current as { cause?: unknown }).cause;\n }\n return false;\n}\n\n/** Concatenate the error's message with its cause chain (bounded). */\nfunction collectErrorText(error: unknown): string {\n const parts: string[] = [];\n let current: unknown = error;\n for (let depth = 0; current && depth < MAX_CAUSE_DEPTH; depth++) {\n if (current instanceof Error) {\n parts.push(current.message);\n current = current.cause;\n } else if (typeof current === 'object' && 'message' in current) {\n const message = (current as { message?: unknown }).message;\n if (typeof message === 'string') parts.push(message);\n current = (current as { cause?: unknown }).cause;\n } else {\n break;\n }\n }\n return parts.join(' | ');\n}\n\nfunction isNetworkErrorLike(error: unknown): boolean {\n let current: unknown = error;\n for (let depth = 0; current && depth < MAX_CAUSE_DEPTH; depth++) {\n if (\n isErrorWithCode(current) &&\n typeof current.code === 'string' &&\n NETWORK_ERROR_CODES.has(current.code.toUpperCase())\n ) {\n return true;\n }\n if (current instanceof Error) {\n if (NETWORK_MESSAGE_PATTERN.test(current.message)) return true;\n current = current.cause;\n } else if (typeof current === 'object') {\n current = (current as { cause?: unknown }).cause;\n } else {\n break;\n }\n }\n return false;\n}\n\n/**\n * The locked Q7 taxonomy. 429/402/usage-limit rotate immediately (429 is not\n * covered by any transient matcher, so it arrives here on first occurrence);\n * 401/403 and `ProviderAuthRequiredError` rotate after one forced refresh;\n * 5xx/network hop only when the transient retry budget is already spent (they\n * reach this processor because `StreamErrorRetryProcessor` declined); 400 and\n * everything unknown never touch the registry.\n */\nexport function classifyRotationError(error: unknown): RotationClassification {\n if (isProviderAuthRequiredError(error)) {\n return { kind: 'rotate', reason: 'auth-failed' };\n }\n\n const status = readErrorStatus(error);\n\n if (status === 429) return { kind: 'rotate', reason: 'rate-limit' };\n if (status === 402) return { kind: 'rotate', reason: 'quota-exhausted' };\n if (status === 401 || status === 403) return { kind: 'rotate', reason: 'auth-failed' };\n if (status !== undefined && status >= 500 && status < 600) return { kind: 'hop' };\n\n // Quota wording only rotates when it co-occurs with a statusless or 400\n // error — the shapes providers actually use for message-only quota\n // failures. Any other status keeps its own classification above (401/403\n // auth, 5xx outage hop, 404/422 never), so limit-ish text riding a\n // non-quota client error can no longer burn the whole pool.\n if (status === undefined || status === 400) {\n if (USAGE_LIMIT_MESSAGE_PATTERN.test(collectErrorText(error))) {\n return { kind: 'rotate', reason: 'quota-exhausted' };\n }\n }\n if (isNetworkErrorLike(error)) return { kind: 'hop' };\n\n return { kind: 'never' };\n}\n\n/** Provider id off a router model id: `mastracode/<provider>/<model>` or `<provider>/<model>`. */\nexport function providerFromModelId(modelId: string): string | undefined {\n const segments = modelId.replace(/^mastracode\\//, '').split('/');\n const providerId = segments[0];\n if (providerId === 'openai') return 'openai-codex';\n return providerId && KNOWN_PROVIDER_IDS.has(providerId) ? providerId : undefined;\n}\n\nfunction providerFromHost(hostname: string): string | undefined {\n for (const [pattern, providerId] of PROVIDER_HOST_PATTERNS) {\n if (pattern.test(hostname)) return providerId;\n }\n return undefined;\n}\n\n/**\n * Identify the provider an error came from: the request URL's hostname\n * (`APICallError.url`, cause chain included), falling back to the router\n * model id. Unknown → undefined (caller treats as never-rotate).\n */\nexport function providerFromError(error: unknown): string | undefined {\n const causeChain: object[] = [];\n let current: unknown = error;\n for (let depth = 0; current && depth < MAX_CAUSE_DEPTH; depth++) {\n if (typeof current !== 'object') break;\n causeChain.push(current);\n current = (current as { cause?: unknown }).cause;\n }\n\n // A request URL identifies the provider that actually handled the failed\n // call. Check every supported URL field throughout the cause chain before\n // falling back to router model metadata, which may describe the original\n // session model rather than the active cascade entry.\n for (const item of causeChain) {\n const urls = [\n (item as { url?: unknown }).url,\n (item as { requestURL?: unknown }).requestURL,\n (item as { requestUrl?: unknown }).requestUrl,\n ];\n for (const url of urls) {\n if (typeof url !== 'string') continue;\n try {\n const providerId = providerFromHost(new URL(url).hostname);\n if (providerId) return providerId;\n } catch {\n // Not a parseable URL — try the other fields and causes.\n }\n }\n }\n\n for (const item of causeChain) {\n const modelId = (item as { modelId?: unknown }).modelId;\n if (typeof modelId !== 'string') continue;\n const providerId = providerFromModelId(modelId);\n if (providerId) return providerId;\n }\n return undefined;\n}\n\nfunction getTriedInstances(state: Record<string, unknown>): Set<string> {\n const existing = state.triedInstances;\n if (existing instanceof Set) return existing;\n const created = new Set<string>();\n state.triedInstances = created;\n return created;\n}\n\nfunction getForcedRefreshInstances(state: Record<string, unknown>): Set<string> {\n const existing = state.forcedAuthRefresh;\n if (existing instanceof Set) return existing;\n const created = new Set<string>();\n state.forcedAuthRefresh = created;\n return created;\n}\n\n/** Friendly names for the part/notice copy (display only — never auth data). */\nexport const PROVIDER_DISPLAY_NAMES: Record<string, string> = {\n anthropic: 'Anthropic',\n 'kimi-for-coding': 'Kimi',\n 'openai-codex': 'Codex',\n 'github-copilot': 'GitHub Copilot',\n xai: 'xAI',\n};\n\nconst REASON_TEXT: Record<Exclude<AccountSwitchPartData['reason'], 'starting-on-account'>, string> = {\n 'rate-limit': 'rate limit',\n 'quota-exhausted': 'quota exhausted',\n 'auth-failed': 'auth failed',\n 'pool-exhausted': 'pool exhausted',\n 'persistent-outage': 'persistent outage',\n 'preferred-routing': 'subscription routing',\n};\n\n/** Validates untrusted `reason` values (e.g. persisted message parts). */\nexport function isAccountSwitchReason(value: unknown): value is AccountSwitchPartData['reason'] {\n return (\n value === 'starting-on-account' ||\n // Own-property check: `in` would accept prototype names like 'toString',\n // which would then interpolate the inherited function into the notice text.\n (typeof value === 'string' && Object.prototype.hasOwnProperty.call(REASON_TEXT, value))\n );\n}\n\n/**\n * One-line transcript copy for a switch part. Shared by the live `info`\n * controller event (the TUI shows controller `info` events as transcript\n * lines, and no message event carries data parts mid-run) and by the TUI's\n * history rendering of the persisted part — one formatter, identical text.\n */\nexport function accountSwitchNoticeText(data: AccountSwitchPartData): string {\n const provider = PROVIDER_DISPLAY_NAMES[data.provider] ?? data.provider;\n if (data.reason === 'starting-on-account' && data.to) {\n return `Starting on ${provider} account: ${data.to.label}`;\n }\n const reason = data.reason === 'starting-on-account' ? data.reason : REASON_TEXT[data.reason];\n if (data.to === null) {\n // A12: a targeted route reports *its* account, not the pool — the other\n // subscriptions were never tried, so \"all accounts unavailable\" would be\n // wrong and would read as if the pool had been walked.\n if (data.exclusive) {\n return `Pinned ${provider} account unavailable (${reason})`;\n }\n return `All ${provider} accounts unavailable (${reason})`;\n }\n const from = data.from?.label ?? 'unknown';\n return `Switched ${provider} account: ${from} → ${data.to.label} (${reason})`;\n}\n\n/** Transcript line for a model-route hop; shared by the live info event and the TUI's history render. */\nexport function modelFallbackNoticeText(data: ModelFallbackPartData): string {\n const reason = REASON_TEXT[data.reason] ?? data.reason;\n return `Switched model route: ${data.from.label} → ${data.to.label} (${reason})`;\n}\n\n/**\n * Whether a persisted model-fallback reason is one this build understands.\n * `REASON_TEXT` also covers the account-switch reasons, so the notice text\n * alone would happily render a foreign value such as `rate-limit` as a\n * model-fallback reason; history parsed from another build's part must be\n * rejected instead.\n */\nexport function isModelFallbackReason(value: unknown): value is ModelFallbackPartData['reason'] {\n return value === 'pool-exhausted' || value === 'persistent-outage';\n}\n\nasync function emitAccountSwitchPart(\n args: Pick<ProcessAPIErrorArgs, 'writer' | 'requestContext'> | Pick<ProcessInputArgs, 'writer' | 'requestContext'>,\n data: AccountSwitchPartData,\n): Promise<void> {\n // Non-transient on purpose (contrast the transient tool-progress parts):\n // switches must persist into the assistant message and render from history.\n await args.writer?.custom({\n type: ACCOUNT_SWITCH_PART_TYPE,\n data,\n });\n // Data parts surface in the TUI only on history reload; emit the same line\n // as a controller `info` event so the switch is visible live (precedent:\n // emitTransientRetry emits controller events from the retry matcher).\n const controllerContext = args.requestContext?.get('controller') as\n | { emitEvent?: (event: { type: 'info'; message: string }) => void }\n | undefined;\n controllerContext?.emitEvent?.({ type: 'info', message: accountSwitchNoticeText(data) });\n}\n\n/**\n * Provider of the model the controller session is currently running — the\n * fallback identification path for errors that carry neither a request URL\n * nor a model id (e.g. `ProviderAuthRequiredError` thrown by a fetch wrapper\n * before any HTTP request exists).\n */\nfunction providerFromSession(\n args: Pick<ProcessAPIErrorArgs, 'requestContext'> | Pick<ProcessInputArgs, 'requestContext'>,\n): string | undefined {\n const controller = args.requestContext?.get('controller') as { session?: { modelId?: unknown } } | undefined;\n const modelId = controller?.session?.modelId;\n return typeof modelId === 'string' ? providerFromModelId(modelId) : undefined;\n}\n\n/**\n * Rotates the active OAuth account on classified API errors.\n *\n * Registered in `errorProcessors` AFTER `StreamErrorRetryProcessor` — a\n * transient error reaching this processor means the transient budget is\n * spent, which is exactly the hop condition. Implements `processAPIError`\n * ONLY (see the file header for the runner-order rationale).\n */\n/** Cached per-request model route cascade. */\ninterface ModelRouteCascade {\n entries: Array<{ id: string; label: string; modelId: string; accountId?: string }>;\n position: number;\n}\n\ninterface AccountRoute {\n entryId: string;\n modelId: string;\n providerId: string;\n accountId?: string;\n}\n\ntype RoutingProcessorArgs = Pick<ProcessAPIErrorArgs, 'requestContext' | 'state' | 'writer'> | ProcessInputArgs;\n\nexport type RoutingControllerContext = {\n session?: { modelId?: unknown; modeId?: unknown };\n threadId?: unknown;\n getState?: () => Record<string, unknown>;\n setState?: (updates: Record<string, unknown>) => Promise<void>;\n getThreadSetting?: (key: string) => Promise<unknown>;\n setThreadSetting?: (setting: { key: string; value: unknown }) => Promise<void>;\n isThreadActive?: () => boolean;\n};\n\nfunction getRoutingController(\n args: Pick<RoutingProcessorArgs, 'requestContext'>,\n): RoutingControllerContext | undefined {\n return args.requestContext?.get('controller') as RoutingControllerContext | undefined;\n}\n\n/** A targeted route is exclusive; an entry without accountId uses automatic pool rotation. */\nfunction getRouteTargetAccountId(route: AccountRoute | null): string | undefined {\n return route?.accountId;\n}\n\nfunction getRequestActiveAccount(\n args: Pick<RoutingProcessorArgs, 'requestContext'>,\n store: CredentialStore,\n providerId: string,\n) {\n if (isRequestAccountRoutingExhausted(args.requestContext, providerId)) return undefined;\n const selectedId = getRequestAccountSelection(args.requestContext, providerId);\n if (selectedId) return store.listAccounts?.(providerId).find(account => account.id === selectedId);\n return store.getActiveAccount?.(providerId) ?? store.listAccounts?.(providerId).find(account => account.active);\n}\n\nfunction resolveAccountRoute(\n args: Pick<RoutingProcessorArgs, 'requestContext'>,\n explicit?: { id: string; modelId: string; accountId?: string },\n): AccountRoute | null {\n const controller = getRoutingController(args);\n const state = controller?.getState?.();\n const pending = state?.mastracodePendingModelFallback as\n | { toEntryId?: unknown; toModelId?: unknown; threadId?: unknown }\n | null\n | undefined;\n const pendingMatchesThread =\n pending &&\n typeof pending.toEntryId === 'string' &&\n typeof pending.toModelId === 'string' &&\n (pending.threadId === undefined || pending.threadId === controller?.threadId);\n const routeEntries = Array.isArray((state?.modelRoute as { entries?: unknown } | undefined)?.entries)\n ? ((state?.modelRoute as { entries: Array<{ id?: unknown; modelId?: unknown; accountId?: unknown }> }).entries ??\n [])\n : [];\n const entry = explicit\n ? explicit\n : pendingMatchesThread\n ? routeEntries.find(candidate => candidate.id === pending.toEntryId && candidate.modelId === pending.toModelId)\n : routeEntries.find(candidate => candidate.modelId === controller?.session?.modelId);\n if (!entry || typeof entry.id !== 'string' || typeof entry.modelId !== 'string') return null;\n const providerId = providerFromModelId(entry.modelId);\n if (!providerId) return null;\n return {\n entryId: entry.id,\n modelId: entry.modelId,\n providerId,\n ...(typeof entry.accountId === 'string' ? { accountId: entry.accountId } : {}),\n };\n}\n\n/**\n * A14: `Automatic` rotation starts *at* the persisted active account and walks\n * insertion order from there, wrapping once. The active account is the cursor\n * rotation last left at, so a turn that starts at index 0 regardless would\n * re-activate and re-try an account the previous turn already moved past —\n * which is the whole job the removed sticky-exclusion set was doing badly.\n * With no persisted active account the order is plain insertion order.\n */\nfunction orderAccountsFromActive(accounts: OAuthAccountRecord[], activeId: string | undefined) {\n const index = activeId === undefined ? -1 : accounts.findIndex(account => account.id === activeId);\n if (index <= 0) return accounts;\n return [...accounts.slice(index), ...accounts.slice(0, index)];\n}\n\nasync function applyPreferredAccountRoute(\n args: RoutingProcessorArgs,\n store: CredentialStore,\n route: AccountRoute,\n): Promise<boolean> {\n store.reload();\n const preferredId = getRouteTargetAccountId(route);\n const accounts = store.listAccounts?.(route.providerId) ?? [];\n if (accounts.length === 0 && preferredId === undefined) return false;\n const tried = getTriedInstances(args.state);\n const unavailable = new Set(accounts.filter(account => tried.has(account.id)).map(account => account.id));\n const active = getRequestActiveAccount(args, store, route.providerId) ?? store.getActiveAccount?.(route.providerId);\n const selected = // A12: a targeted route may use only the account it names. `Automatic`\n // keeps insertion order with full pool rotation (A10), starting from the\n // account the cursor already points at (A14).\n (\n preferredId\n ? accounts.filter(account => account.id === preferredId)\n : orderAccountsFromActive(accounts, active?.id)\n ).find(account => !unavailable.has(account.id));\n\n for (const accountId of unavailable) tried.add(accountId);\n if (!selected) {\n markRequestAccountRoutingExhausted(args.requestContext, route.providerId);\n return false;\n }\n\n if (active?.id === selected.id) {\n setRequestAccountSelection(args.requestContext, route.providerId, selected.id);\n return false;\n }\n // Activate before recording the request-scoped selection: a failed\n // activation must not leave the selection claiming an account that never\n // became the provider's active credential.\n const activated = store.activateAccount ? store.activateAccount(route.providerId, selected.id) : selected;\n if (!activated) {\n // Only a targeted route is out of options here. The exhausted marker is\n // request-wide and fails every credential read closed, so setting it for\n // `Automatic` would stop error recovery from retrying on a survivor.\n if (preferredId !== undefined) markRequestAccountRoutingExhausted(args.requestContext, route.providerId);\n return false;\n }\n setRequestAccountSelection(args.requestContext, route.providerId, activated.id);\n\n // Applying an explicit account choice is routine, not a failover notice.\n if (preferredId === undefined) {\n await emitAccountSwitchPart(args, {\n provider: route.providerId,\n from: active ? { id: active.id, label: active.label } : null,\n to: { id: activated.id, label: activated.label },\n reason: 'preferred-routing',\n at: new Date().toISOString(),\n });\n }\n return true;\n}\n\nexport class AccountRotationProcessor implements Processor {\n readonly id = 'mastracode-account-rotation' as const;\n\n constructor(\n private readonly options: {\n credentialStore: RotationCredentialStore;\n maxProcessorRetries: number;\n settingsPath?: string;\n },\n ) {}\n\n async processAPIError(args: ProcessAPIErrorArgs): Promise<{ retry: boolean }> {\n const { error, state } = args;\n\n // Core runs error processors even after the shared retry budget is spent\n // and silently discards `retry: true` then (llm-execution-step.ts\n // canRetryError) — rotating the cursor or emitting a switch part for a\n // retry that will never run would lie to both auth.json and the\n // transcript. With a fallback chain configured, a bare `retry: false`\n // here would silently advance the route for an error we never classified, so the\n // chain gate surfaces the error instead.\n if (args.retryCount >= this.options.maxProcessorRetries) {\n await this.gateChainHop(args, error);\n return { retry: false };\n }\n\n // Classify before attributing: an error from a provider outside the OAuth\n // registry (API-key/router providers are valid route entries) still hops on\n // rotate/hop classes — there is just no account cursor to advance.\n const classification = classifyRotationError(error);\n // Q14: 400/unknown errors never rotate and never advance routes. With a chain\n // active, core's fallback array would still advance on a bare\n // `retry: false` (it advances on any thrown non-TripWire error), so the\n // gate converts that into a surfaced error instead of a silent hop.\n if (classification.kind === 'never') {\n await this.gateChainHop(args, error);\n return { retry: false };\n }\n\n const cascade = await this.getModelRouteCascade(args);\n const currentEntry = cascade?.entries[cascade.position];\n const providerId =\n providerFromError(error) ??\n (currentEntry ? providerFromModelId(currentEntry.modelId) : undefined) ??\n (cascade ? undefined : providerFromSession(args));\n if (!providerId) {\n await this.emitModelFallbackPart(args, classification.kind === 'hop' ? 'persistent-outage' : 'pool-exhausted');\n return { retry: false };\n }\n\n // Deployed requests resolve the tenant-scoped store; local mode keeps the\n // host storage. Reading the host registry here would rotate or announce\n // host accounts for a tenant request. Annotated as the rotation surface:\n // `resolveCredentialStore` returns a plain CredentialStore, and the 401\n // path below uses the optional `forceRefreshActiveAccount` when the host\n // provides it.\n const store: RotationCredentialStore = resolveCredentialStore(args.requestContext) ?? this.options.credentialStore;\n store.reload();\n const accounts = store.listAccounts?.(providerId) ?? [];\n const active = getRequestActiveAccount(args, store, providerId);\n const route = currentEntry ? resolveAccountRoute(args, currentEntry) : resolveAccountRoute(args);\n\n // Q7 bucket 2: force one refresh of the active instance before rotating.\n // A 401 usually means a fresh-but-rejected token; the forced refresh\n // covers server-side clock skew and refresh-token races. Success retries\n // the same account — no rotation, no part. With no active account (e.g.\n // `ProviderAuthRequiredError` from an empty registry) a refresh can never\n // succeed, so skip it and fall through to the retry:false surface below,\n // which rethrows the original auth error instead of a generic pool\n // exhaustion message.\n if (classification.kind === 'rotate' && classification.reason === 'auth-failed' && active) {\n const forced = getForcedRefreshInstances(state);\n const refreshKey = `${providerId}:${active?.id ?? 'active'}`;\n if (!forced.has(refreshKey) && typeof store.forceRefreshActiveAccount === 'function') {\n forced.add(refreshKey);\n const token = await store.forceRefreshActiveAccount(providerId, active?.id);\n if (token !== undefined) {\n return { retry: true };\n }\n }\n }\n\n // A12: only a pin on the provider that actually failed makes this failure\n // exclusive. `route.providerId` is derived from the route's model while\n // `providerId` comes from the failed request's URL, which during a cascade\n // can still describe the session model rather than the entry being retried;\n // when they differ the pin belongs to an unrelated route, so the provider\n // that failed keeps its normal pool handling.\n const targetAccountId = route?.providerId === providerId ? getRouteTargetAccountId(route) : undefined;\n\n if (classification.kind === 'hop') {\n return this.declarePoolUnavailable(args, providerId, 'persistent-outage', targetAccountId !== undefined);\n }\n\n // A12: a targeted route never activates a sibling subscription. A\n // rotate-classified failure on the account the route selected proceeds to\n // the model route instead — the request hops, it does not spill\n // onto another subscription's quota. A targeted route has nothing to\n // rotate to at any pool size. A stale id for an account the user removed\n // reads the same way: fail closed rather than silently land on a sibling.\n if (targetAccountId !== undefined) {\n return this.declarePoolUnavailable(args, providerId, 'pool-exhausted', true);\n }\n\n // Count only this provider's instances: `tried` spans the whole request\n // (a cascade can visit several providers), so comparing its raw size to\n // this provider's account count would falsely report exhaustion when an\n // earlier provider in the same request already used up accounts.\n const tried = getTriedInstances(state);\n if (active) tried.add(active.id);\n // The tried-set is request-global and shared across providers after a\n // route hop, so exhaustion must count only this provider's ids.\n const triedForProvider = accounts.filter(account => tried.has(account.id)).length;\n if (triedForProvider >= accounts.length) {\n return this.declarePoolUnavailable(args, providerId, 'pool-exhausted');\n }\n\n // If the selected account was removed elsewhere, even a single survivor\n // is still untried. Resume from the freshly loaded global cursor.\n const candidates = active ? accounts : orderAccountsFromActive(accounts, store.getActiveAccount?.(providerId)?.id);\n const nextCandidate = candidates.find(account => !tried.has(account.id));\n\n const next = nextCandidate ? store.activateAccount?.(providerId, nextCandidate.id) : undefined;\n if (!next) {\n return this.declarePoolUnavailable(args, providerId, 'pool-exhausted');\n }\n setRequestAccountSelection(args.requestContext, providerId, next.id);\n tried.add(next.id);\n\n // The retry replays the request from scratch (Q10): rotate the assistant\n // message id so the retried response starts a fresh message instead of\n // appending to the partially streamed one.\n args.rotateResponseMessageId?.();\n\n await emitAccountSwitchPart(args, {\n provider: providerId,\n from: active ? { id: active.id, label: active.label } : null,\n to: { id: next.id, label: next.label },\n reason: classification.reason,\n at: new Date().toISOString(),\n });\n\n return { retry: true };\n }\n\n /**\n * Resolve the request's host-supplied model route once and cache the reachable\n * prefix in processor state. Resolution mirrors getDynamicModel so a hop is\n * never announced for an entry core cannot reach.\n */\n private async getModelRouteCascade(args: ProcessAPIErrorArgs): Promise<ModelRouteCascade | null> {\n if (args.state.modelRouteCascade !== undefined) {\n return (args.state.modelRouteCascade as ModelRouteCascade | null) ?? null;\n }\n const controller = getRoutingController(args);\n const state = controller?.getState?.();\n const route = (\n state?.modelRoute as\n | { entries?: Array<{ id?: unknown; label?: unknown; modelId?: unknown; accountId?: unknown }> }\n | undefined\n )?.entries;\n const pending = state?.mastracodePendingModelFallback as\n | { toEntryId?: unknown; threadId?: unknown }\n | null\n | undefined;\n const pendingMatchesThread =\n pending &&\n typeof pending.toEntryId === 'string' &&\n (pending.threadId === undefined || pending.threadId === controller?.threadId);\n const startIndex = pendingMatchesThread\n ? route?.findIndex(entry => entry.id === pending.toEntryId)\n : route?.findIndex(entry => entry.modelId === controller?.session?.modelId);\n if (!route || startIndex === undefined || startIndex < 0 || route.length - startIndex < 2) {\n args.state.modelRouteCascade = null;\n return null;\n }\n\n const thinkingLevel = resolveRequestThinkingLevel(\n {\n state: { thinkingLevel: state?.thinkingLevel },\n session: { modeId: typeof controller?.session?.modeId === 'string' ? controller.session.modeId : 'build' },\n },\n this.options.settingsPath,\n );\n const entries: ModelRouteCascade['entries'] = [];\n for (const entry of route.slice(startIndex)) {\n if (\n typeof entry.id !== 'string' ||\n entry.id.length === 0 ||\n typeof entry.modelId !== 'string' ||\n entry.modelId.length === 0\n ) {\n break;\n }\n if (entries.length > 0) {\n try {\n resolveModel(entry.modelId, {\n thinkingLevel,\n remapForCodexOAuth: true,\n requestContext: args.requestContext,\n });\n } catch {\n break;\n }\n }\n entries.push({\n id: entry.id,\n label: typeof entry.label === 'string' && entry.label.length > 0 ? entry.label : entry.id,\n modelId: entry.modelId,\n ...(typeof entry.accountId === 'string' ? { accountId: entry.accountId } : {}),\n });\n }\n if (entries.length < 2) {\n args.state.modelRouteCascade = null;\n return null;\n }\n const cascade: ModelRouteCascade = { entries, position: 0 };\n args.state.modelRouteCascade = cascade;\n return cascade;\n }\n\n /**\n * Q14 gate: 400/unknown/unattributable errors never advance routes. Core's\n * fallback array advances on ANY thrown error except TripWire\n * (llm-execution-step.ts), so when the session route has another entry and the\n * current entry is non-last, a bare `retry: false` would silently hop on an\n * error class the user excluded from hop triggers. TripWire is the only\n * no-advance escape: the runner rethrows it and the fallback loop declines\n * to advance. No chain (or already on the last entry) → return and let the\n * plain `retry: false` surface the error exactly as before.\n */\n private async gateChainHop(args: ProcessAPIErrorArgs, error: unknown): Promise<void> {\n const cascade = await this.getModelRouteCascade(args);\n if (!cascade) return;\n if (cascade.position >= cascade.entries.length - 1) return;\n const reason = error instanceof Error ? error.message : String(error);\n throw new TripWire(reason, {}, this.id);\n }\n\n /** Announce and persist the next model-route hop before core advances. */\n private async emitModelFallbackPart(\n args: ProcessAPIErrorArgs,\n reason: 'pool-exhausted' | 'persistent-outage',\n ): Promise<void> {\n const cascade = await this.getModelRouteCascade(args);\n if (!cascade) return;\n\n const from = cascade.entries[cascade.position];\n const to = cascade.entries[cascade.position + 1];\n if (!from || !to) return;\n\n const controller = args.requestContext?.get('controller') as\n | {\n threadId?: unknown;\n setState?: (updates: Record<string, unknown>) => Promise<void>;\n setThreadSetting?: (setting: { key: string; value: unknown }) => Promise<void>;\n emitEvent?: (event: { type: 'info'; message: string }) => void;\n }\n | undefined;\n const at = new Date().toISOString();\n const threadId = typeof controller?.threadId === 'string' ? controller.threadId : undefined;\n const pending = {\n fromEntryId: from.id,\n toEntryId: to.id,\n toModelId: to.modelId,\n ...(threadId ? { threadId } : {}),\n reason,\n at,\n } satisfies PendingModelFallback;\n await controller?.setThreadSetting?.({ key: MODEL_FALLBACK_STATE_KEY, value: pending });\n const data: ModelFallbackPartData = {\n from: { entryId: from.id, label: from.label },\n to: { entryId: to.id, label: to.label },\n reason,\n at,\n };\n try {\n await args.writer?.custom({ type: MODEL_FALLBACK_PART_TYPE, data });\n } catch (error) {\n await controller?.setThreadSetting?.({ key: MODEL_FALLBACK_STATE_KEY, value: undefined });\n throw error;\n }\n await controller?.setState?.({ [MODEL_FALLBACK_STATE_KEY]: pending });\n args.state.startNoticeEmitted = false;\n const targetRoute = resolveAccountRoute(args, to);\n if (targetRoute) {\n const store = resolveCredentialStore(args.requestContext) ?? this.options.credentialStore;\n await applyPreferredAccountRoute(args, store, targetRoute).catch(() => undefined);\n }\n controller?.emitEvent?.({ type: 'info', message: modelFallbackNoticeText(data) });\n cascade.position++;\n }\n\n /**\n * Pool done for this request: every instance recorded in the tried-set and\n * a `to: null` part emitted. Returns `retry: false` so core's fallback\n * array can hop to the next route entry (announced by `emitModelFallbackPart`).\n * Silent on the account part when the provider has no registry at all —\n * there are no accounts to declare unavailable, but the hop still applies.\n */\n private async declarePoolUnavailable(\n args: ProcessAPIErrorArgs,\n providerId: string,\n reason: 'pool-exhausted' | 'persistent-outage',\n exclusive = false,\n ): Promise<{ retry: boolean }> {\n const store = resolveCredentialStore(args.requestContext) ?? this.options.credentialStore;\n const accounts = store.listAccounts?.(providerId) ?? [];\n if (accounts.length === 0) {\n // No account registry (API-key-only provider): nothing rotated, but the\n // hop still happens — announce the model fallback before core advances.\n await this.emitModelFallbackPart(args, reason);\n return { retry: false };\n }\n\n const tried = getTriedInstances(args.state);\n for (const account of accounts) tried.add(account.id);\n\n const active = getRequestActiveAccount(args, store, providerId);\n\n await emitAccountSwitchPart(args, {\n provider: providerId,\n from: active ? { id: active.id, label: active.label } : null,\n to: null,\n reason,\n at: new Date().toISOString(),\n ...(exclusive ? { exclusive: true } : {}),\n });\n\n await this.emitModelFallbackPart(args, reason);\n\n return { retry: false };\n }\n}\n\n/**\n * Emits the \"starting on a non-default account\" notice (Q19) once per\n * request when the active registry account is not the first entry.\n *\n * TYPE CONSTRAINT: this class must NEVER implement `processAPIError`. It\n * lives in `inputProcessors`; the runner walks input processors first when\n * running `processAPIError`, so adding the method here would classify and\n * rotate errors BEFORE `StreamErrorRetryProcessor`'s transient retries run.\n */\nexport class AccountStartNoticeProcessor implements Processor {\n readonly id = 'mastracode-account-start-notice' as const;\n\n constructor(private readonly options: { credentialStore: CredentialStore }) {}\n\n async processInput(args: ProcessInputArgs): Promise<ProcessInputResult> {\n if (args.state.startNoticeEmitted) return args.messageList;\n\n // Deployed requests resolve the tenant-scoped store so host accounts are\n // never listed, activated, or announced for a tenant run. Local mode keeps\n // the constructor's storage.\n const store = resolveCredentialStore(args.requestContext) ?? this.options.credentialStore;\n\n const route = resolveAccountRoute(args);\n if (route) {\n const switched = await applyPreferredAccountRoute(args, store, route);\n if (switched || getRouteTargetAccountId(route) !== undefined) {\n args.state.startNoticeEmitted = true;\n return args.messageList;\n }\n } else {\n store.reload();\n }\n\n // A14: a route whose accounts are all unavailable is not a pre-emptive\n // abort. `applyPreferredAccountRoute` marks the provider on the request so\n // credential reads fail closed rather than falling through to the active\n // account, and the request then runs and fails at the provider — which is\n // what lets the error lane classify it and hand the turn to the route's\n // configured fallback chain. The removed persisted set threw here instead,\n // before any socket opened, so the chain was never reached.\n const providerId = route?.providerId ?? providerFromSession(args);\n if (!providerId) return args.messageList;\n\n const accounts = store.listAccounts?.(providerId) ?? [];\n if (accounts.length < 2) return args.messageList;\n\n const active = store.getActiveAccount?.(providerId);\n const first = accounts[0];\n if (!active || !first || active.id === first.id) return args.messageList;\n\n args.state.startNoticeEmitted = true;\n\n await emitAccountSwitchPart(args, {\n provider: providerId,\n from: null,\n to: { id: active.id, label: active.label },\n reason: 'starting-on-account',\n at: new Date().toISOString(),\n });\n\n return args.messageList;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCA,MAAa,2BAA2B;;AAsCxC,MAAM,qBAAqB,IAAI,IAAI,kBAAkB,CAAC,CAAC,KAAI,aAAY,SAAS,EAAE,CAAC;;AAGnF,MAAM,yBAAkD;CACtD,CAAC,+BAA+B,WAAW;CAC3C,CAAC,0BAA0B,iBAAiB;CAC5C,CAAC,sBAAsB,KAAK;CAC5B,CAAC,wBAAwB,cAAc;CACvC,CAAC,kCAAkC,cAAc;CACjD,CAAC,8BAA8B,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AACF"}
1
+ {"version":3,"file":"account-rotation-processor.js","names":[],"sources":["../../src/auth/account-rotation-processor.ts"],"sourcesContent":["/**\n * Error-driven rotation across a provider's OAuth account registry.\n *\n * When the active account cannot serve a request (rate limit, quota\n * exhaustion, dead token, persistent outage), the next account in insertion\n * order is selected for the request and the request retried. OAuth fetch\n * wrappers read that request-scoped selection on every HTTP attempt, so\n * concurrent runs can't swap each other's credentials. Every switch is\n * persisted as a non-transient `data-mastracode-account-switch` part so it\n * shows in the transcript and survives history reload.\n *\n * Two classes, two lanes — the split is load-bearing. The processor runner\n * walks `[...inputProcessors, ...outputProcessors, ...errorProcessors]` when\n * running `processAPIError`, so a processor registered in the input lane that\n * also implemented `processAPIError` would run BEFORE\n * `StreamErrorRetryProcessor` and hop on 5xx errors before transient retries\n * had a chance. `AccountRotationProcessor` therefore implements\n * `processAPIError` only and is registered in `errorProcessors` after\n * `StreamErrorRetryProcessor`; `AccountStartNoticeProcessor` implements\n * `processInput` only and is registered in `inputProcessors`.\n */\nimport { TripWire } from '@mastra/core/agent';\nimport type { ProcessAPIErrorArgs, ProcessInputArgs, ProcessInputResult, Processor } from '@mastra/core/processors';\n\nimport { resolveCredentialStore } from '../agents/credential-resolver.js';\nimport { resolveModel, resolveRequestThinkingLevel } from '../agents/model.js';\nimport {\n getRequestAccountSelection,\n isRequestAccountRoutingExhausted,\n markRequestAccountRoutingExhausted,\n setRequestAccountSelection,\n} from './account-routing-context.js';\nimport { ProviderAuthRequiredError, PROVIDER_AUTH_REQUIRED_ERROR } from './provider-auth-error.js';\nimport { getOAuthProviders } from './storage.js';\nimport type { CredentialStore, OAuthAccountRecord } from './types.js';\n\nexport const ACCOUNT_SWITCH_PART_TYPE = 'data-mastracode-account-switch';\n\n/** Labels and instance ids only — never token material (do-not list). */\nexport interface AccountSwitchPartData {\n provider: string;\n from: { id: string; label: string } | null;\n to: { id: string; label: string } | null;\n reason:\n | 'rate-limit'\n | 'quota-exhausted'\n | 'auth-failed'\n | 'pool-exhausted'\n | 'persistent-outage'\n | 'preferred-routing';\n at: string;\n /**\n * Set on a `to: null` part when a route pinned to a single account reported\n * that account unusable. The provider's other subscriptions were never\n * consulted (A12), so \"all accounts unavailable\" would misreport what\n * happened.\n */\n exclusive?: boolean;\n}\n\n/** The store surface rotation needs; `AuthStorage` satisfies it structurally. */\nexport type RotationCredentialStore = CredentialStore & {\n /**\n * Force one refresh of the active account's tokens regardless of expiry\n * (401/403 path — a rejected-but-unexpired token usually means clock skew\n * or a refresh race). `AuthStorage` provides it; deployed per-tenant stores\n * don't, and the auth path degrades to plain rotation (which itself no-ops\n * without registry methods).\n */\n forceRefreshActiveAccount?(providerId: string, accountInstanceId?: string): Promise<string | undefined>;\n};\n\n/** Rotatable providers = the OAuth provider registry; API-key-only providers never rotate. */\nconst KNOWN_PROVIDER_IDS = new Set(getOAuthProviders().map(provider => provider.id));\n\n/** Hostname suffixes → provider ids, for `APICallError.url`. */\nconst PROVIDER_HOST_PATTERNS: Array<[RegExp, string]> = [\n [/(^|\\.)api\\.anthropic\\.com$/i, 'anthropic'],\n [/(^|\\.)api\\.kimi\\.com$/i, 'kimi-for-coding'],\n [/(^|\\.)api\\.x\\.ai$/i, 'xai'],\n [/(^|\\.)chatgpt\\.com$/i, 'openai-codex'],\n [/(^|\\.)backend-api\\.codex\\.ai$/i, 'openai-codex'],\n [/(^|\\.)githubcopilot\\.com$/i, 'github-copilot'],\n [/(^|\\.)api\\.github\\.com$/i, 'github-copilot'],\n];\n\n/**\n * Provider usage/quota-limit wording (locked Q7 bucket 1). Statuses 429/402\n * are matched before this; some providers deliver quota errors as plain 400s,\n * which only the message reveals. Deliberately restricted to unambiguous\n * quota phrases — a generic \"exceeded your … limit\" can appear on non-quota\n * client errors (request size, context length) that must never rotate.\n */\nconst USAGE_LIMIT_MESSAGE_PATTERN =\n /usage (?:limit|cap)|insufficient[_ ]quota|quota (?:exceeded|exhausted|reached)|exceeded (?:your )?current quota|insufficient (?:balance|credits?)|credits? exhausted|rate limit (?:exceeded|reached)|weekly limit|monthly limit/i;\n\nconst NETWORK_ERROR_CODES = new Set([\n 'ECONNRESET',\n 'EPIPE',\n 'ECONNREFUSED',\n 'ENOTFOUND',\n 'ETIMEDOUT',\n 'EAI_AGAIN',\n 'UND_ERR_CONNECT_TIMEOUT',\n 'UND_ERR_SOCKET',\n]);\n\nconst NETWORK_MESSAGE_PATTERN =\n /fetch failed|network error|socket hang up|getaddrinfo|econnrefused|enotfound|etimedout|connection (?:refused|reset|closed|timed out)|other side closed|write epipe/i;\n\nconst MAX_CAUSE_DEPTH = 4;\n\n/** Persisted data-part type for a model-route hop. */\nexport const MODEL_FALLBACK_PART_TYPE = 'data-mastracode-model-fallback' as const;\n\n/** Non-secret transcript payload for a model-route hop. */\nexport interface ModelFallbackPartData {\n from: { entryId: string; label: string };\n to: { entryId: string; label: string };\n reason: 'pool-exhausted' | 'persistent-outage';\n at: string;\n}\n\n/** Session-state key set when account rotation advances the model route. */\nexport const MODEL_FALLBACK_STATE_KEY = 'mastracodePendingModelFallback' as const;\n\n/** Payload written to session state under MODEL_FALLBACK_STATE_KEY. */\nexport interface PendingModelFallback {\n fromEntryId: string;\n toEntryId: string;\n toModelId: string;\n threadId?: string;\n reason: 'pool-exhausted' | 'persistent-outage';\n at: string;\n}\n\nexport type RotationClassification =\n | { kind: 'rotate'; reason: 'rate-limit' | 'quota-exhausted' | 'auth-failed' }\n | { kind: 'hop' }\n | { kind: 'never' };\n\nfunction isErrorWithCode(error: unknown): error is { code?: unknown } {\n return typeof error === 'object' && error !== null && 'code' in error;\n}\n\nfunction readErrorStatus(error: unknown): number | undefined {\n let current: unknown = error;\n for (let depth = 0; current && depth < MAX_CAUSE_DEPTH; depth++) {\n if (typeof current !== 'object') break;\n const { statusCode, status } = current as { statusCode?: unknown; status?: unknown };\n if (typeof statusCode === 'number') return statusCode;\n if (typeof status === 'number') return status;\n current = (current as { cause?: unknown }).cause;\n }\n return undefined;\n}\n\nfunction isProviderAuthRequiredError(error: unknown): boolean {\n let current: unknown = error;\n for (let depth = 0; current && depth < MAX_CAUSE_DEPTH; depth++) {\n if (\n current instanceof ProviderAuthRequiredError ||\n (current instanceof Error && current.name === PROVIDER_AUTH_REQUIRED_ERROR)\n ) {\n return true;\n }\n if (typeof current !== 'object') break;\n current = (current as { cause?: unknown }).cause;\n }\n return false;\n}\n\n/** Concatenate the error's message with its cause chain (bounded). */\nfunction collectErrorText(error: unknown): string {\n const parts: string[] = [];\n let current: unknown = error;\n for (let depth = 0; current && depth < MAX_CAUSE_DEPTH; depth++) {\n if (current instanceof Error) {\n parts.push(current.message);\n current = current.cause;\n } else if (typeof current === 'object' && 'message' in current) {\n const message = (current as { message?: unknown }).message;\n if (typeof message === 'string') parts.push(message);\n current = (current as { cause?: unknown }).cause;\n } else {\n break;\n }\n }\n return parts.join(' | ');\n}\n\nfunction isNetworkErrorLike(error: unknown): boolean {\n let current: unknown = error;\n for (let depth = 0; current && depth < MAX_CAUSE_DEPTH; depth++) {\n if (\n isErrorWithCode(current) &&\n typeof current.code === 'string' &&\n NETWORK_ERROR_CODES.has(current.code.toUpperCase())\n ) {\n return true;\n }\n if (current instanceof Error) {\n if (NETWORK_MESSAGE_PATTERN.test(current.message)) return true;\n current = current.cause;\n } else if (typeof current === 'object') {\n current = (current as { cause?: unknown }).cause;\n } else {\n break;\n }\n }\n return false;\n}\n\n/**\n * The locked Q7 taxonomy. 429/402/usage-limit rotate immediately (429 is not\n * covered by any transient matcher, so it arrives here on first occurrence);\n * 401/403 and `ProviderAuthRequiredError` rotate after one forced refresh;\n * 5xx/network hop only when the transient retry budget is already spent (they\n * reach this processor because `StreamErrorRetryProcessor` declined); 400 and\n * everything unknown never touch the registry.\n */\nexport function classifyRotationError(error: unknown): RotationClassification {\n if (isProviderAuthRequiredError(error)) {\n return { kind: 'rotate', reason: 'auth-failed' };\n }\n\n const status = readErrorStatus(error);\n\n if (status === 429) return { kind: 'rotate', reason: 'rate-limit' };\n if (status === 402) return { kind: 'rotate', reason: 'quota-exhausted' };\n if (status === 401 || status === 403) return { kind: 'rotate', reason: 'auth-failed' };\n if (status !== undefined && status >= 500 && status < 600) return { kind: 'hop' };\n\n // Quota wording only rotates when it co-occurs with a statusless or 400\n // error — the shapes providers actually use for message-only quota\n // failures. Any other status keeps its own classification above (401/403\n // auth, 5xx outage hop, 404/422 never), so limit-ish text riding a\n // non-quota client error can no longer burn the whole pool.\n if (status === undefined || status === 400) {\n if (USAGE_LIMIT_MESSAGE_PATTERN.test(collectErrorText(error))) {\n return { kind: 'rotate', reason: 'quota-exhausted' };\n }\n }\n if (isNetworkErrorLike(error)) return { kind: 'hop' };\n\n return { kind: 'never' };\n}\n\n/** Provider id off a router model id: `mastracode/<provider>/<model>` or `<provider>/<model>`. */\nexport function providerFromModelId(modelId: string): string | undefined {\n const segments = modelId.replace(/^mastracode\\//, '').split('/');\n const providerId = segments[0];\n if (providerId === 'openai') return 'openai-codex';\n return providerId && KNOWN_PROVIDER_IDS.has(providerId) ? providerId : undefined;\n}\n\nfunction providerFromHost(hostname: string): string | undefined {\n for (const [pattern, providerId] of PROVIDER_HOST_PATTERNS) {\n if (pattern.test(hostname)) return providerId;\n }\n return undefined;\n}\n\n/**\n * Identify the provider an error came from: the request URL's hostname\n * (`APICallError.url`, cause chain included), falling back to the router\n * model id. Unknown → undefined (caller treats as never-rotate).\n */\nexport function providerFromError(error: unknown): string | undefined {\n const causeChain: object[] = [];\n let current: unknown = error;\n for (let depth = 0; current && depth < MAX_CAUSE_DEPTH; depth++) {\n if (typeof current !== 'object') break;\n causeChain.push(current);\n current = (current as { cause?: unknown }).cause;\n }\n\n // A request URL identifies the provider that actually handled the failed\n // call. Check every supported URL field throughout the cause chain before\n // falling back to router model metadata, which may describe the original\n // session model rather than the active cascade entry.\n for (const item of causeChain) {\n const urls = [\n (item as { url?: unknown }).url,\n (item as { requestURL?: unknown }).requestURL,\n (item as { requestUrl?: unknown }).requestUrl,\n ];\n for (const url of urls) {\n if (typeof url !== 'string') continue;\n try {\n const providerId = providerFromHost(new URL(url).hostname);\n if (providerId) return providerId;\n } catch {\n // Not a parseable URL — try the other fields and causes.\n }\n }\n }\n\n for (const item of causeChain) {\n const modelId = (item as { modelId?: unknown }).modelId;\n if (typeof modelId !== 'string') continue;\n const providerId = providerFromModelId(modelId);\n if (providerId) return providerId;\n }\n return undefined;\n}\n\nfunction getTriedInstances(state: Record<string, unknown>): Set<string> {\n const existing = state.triedInstances;\n if (existing instanceof Set) return existing;\n const created = new Set<string>();\n state.triedInstances = created;\n return created;\n}\n\nfunction getForcedRefreshInstances(state: Record<string, unknown>): Set<string> {\n const existing = state.forcedAuthRefresh;\n if (existing instanceof Set) return existing;\n const created = new Set<string>();\n state.forcedAuthRefresh = created;\n return created;\n}\n\n/** Friendly names for the part/notice copy (display only — never auth data). */\nexport const PROVIDER_DISPLAY_NAMES: Record<string, string> = {\n anthropic: 'Anthropic',\n 'kimi-for-coding': 'Kimi',\n 'openai-codex': 'Codex',\n 'github-copilot': 'GitHub Copilot',\n xai: 'xAI',\n};\n\nconst REASON_TEXT: Record<AccountSwitchPartData['reason'], string> = {\n 'rate-limit': 'rate limit',\n 'quota-exhausted': 'quota exhausted',\n 'auth-failed': 'auth failed',\n 'pool-exhausted': 'pool exhausted',\n 'persistent-outage': 'persistent outage',\n 'preferred-routing': 'subscription routing',\n};\n\n/** Validates untrusted `reason` values (e.g. persisted message parts). */\nexport function isAccountSwitchReason(value: unknown): value is AccountSwitchPartData['reason'] {\n // Own-property check: `in` would accept prototype names like 'toString',\n // which would then interpolate the inherited function into the notice text.\n return typeof value === 'string' && Object.prototype.hasOwnProperty.call(REASON_TEXT, value);\n}\n\n/**\n * One-line transcript copy for a switch part. Shared by the live `info`\n * controller event (the TUI shows controller `info` events as transcript\n * lines, and no message event carries data parts mid-run) and by the TUI's\n * history rendering of the persisted part — one formatter, identical text.\n */\nexport function accountSwitchNoticeText(data: AccountSwitchPartData): string {\n const provider = PROVIDER_DISPLAY_NAMES[data.provider] ?? data.provider;\n const reason = REASON_TEXT[data.reason];\n if (data.to === null) {\n // A12: a targeted route reports *its* account, not the pool — the other\n // subscriptions were never tried, so \"all accounts unavailable\" would be\n // wrong and would read as if the pool had been walked.\n if (data.exclusive) {\n return `Pinned ${provider} account unavailable (${reason})`;\n }\n return `All ${provider} accounts unavailable (${reason})`;\n }\n const from = data.from?.label ?? 'unknown';\n return `Switched ${provider} account: ${from} → ${data.to.label} (${reason})`;\n}\n\n/** Transcript line for a model-route hop; shared by the live info event and the TUI's history render. */\nexport function modelFallbackNoticeText(data: ModelFallbackPartData): string {\n const reason = REASON_TEXT[data.reason] ?? data.reason;\n return `Switched model route: ${data.from.label} → ${data.to.label} (${reason})`;\n}\n\n/**\n * Whether a persisted model-fallback reason is one this build understands.\n * `REASON_TEXT` also covers the account-switch reasons, so the notice text\n * alone would happily render a foreign value such as `rate-limit` as a\n * model-fallback reason; history parsed from another build's part must be\n * rejected instead.\n */\nexport function isModelFallbackReason(value: unknown): value is ModelFallbackPartData['reason'] {\n return value === 'pool-exhausted' || value === 'persistent-outage';\n}\n\nasync function emitAccountSwitchPart(\n args: Pick<ProcessAPIErrorArgs, 'writer' | 'requestContext'> | Pick<ProcessInputArgs, 'writer' | 'requestContext'>,\n data: AccountSwitchPartData,\n): Promise<void> {\n // Non-transient on purpose (contrast the transient tool-progress parts):\n // switches must persist into the assistant message and render from history.\n await args.writer?.custom({\n type: ACCOUNT_SWITCH_PART_TYPE,\n data,\n });\n // Data parts surface in the TUI only on history reload; emit the same line\n // as a controller `info` event so the switch is visible live (precedent:\n // emitTransientRetry emits controller events from the retry matcher).\n const controllerContext = args.requestContext?.get('controller') as\n | { emitEvent?: (event: { type: 'info'; message: string }) => void }\n | undefined;\n controllerContext?.emitEvent?.({ type: 'info', message: accountSwitchNoticeText(data) });\n}\n\n/**\n * Provider of the model the controller session is currently running — the\n * fallback identification path for errors that carry neither a request URL\n * nor a model id (e.g. `ProviderAuthRequiredError` thrown by a fetch wrapper\n * before any HTTP request exists).\n */\nfunction providerFromSession(\n args: Pick<ProcessAPIErrorArgs, 'requestContext'> | Pick<ProcessInputArgs, 'requestContext'>,\n): string | undefined {\n const controller = args.requestContext?.get('controller') as { session?: { modelId?: unknown } } | undefined;\n const modelId = controller?.session?.modelId;\n return typeof modelId === 'string' ? providerFromModelId(modelId) : undefined;\n}\n\n/**\n * Rotates the active OAuth account on classified API errors.\n *\n * Registered in `errorProcessors` AFTER `StreamErrorRetryProcessor` — a\n * transient error reaching this processor means the transient budget is\n * spent, which is exactly the hop condition. Implements `processAPIError`\n * ONLY (see the file header for the runner-order rationale).\n */\n/** Cached per-request model route cascade. */\ninterface ModelRouteCascade {\n entries: Array<{ id: string; label: string; modelId: string; accountId?: string }>;\n position: number;\n}\n\ninterface AccountRoute {\n entryId: string;\n modelId: string;\n providerId: string;\n accountId?: string;\n}\n\ntype RoutingProcessorArgs = Pick<ProcessAPIErrorArgs, 'requestContext' | 'state' | 'writer'> | ProcessInputArgs;\n\nexport type RoutingControllerContext = {\n session?: { modelId?: unknown; modeId?: unknown };\n threadId?: unknown;\n getState?: () => Record<string, unknown>;\n setState?: (updates: Record<string, unknown>) => Promise<void>;\n getThreadSetting?: (key: string) => Promise<unknown>;\n setThreadSetting?: (setting: { key: string; value: unknown }) => Promise<void>;\n isThreadActive?: () => boolean;\n};\n\nfunction getRoutingController(\n args: Pick<RoutingProcessorArgs, 'requestContext'>,\n): RoutingControllerContext | undefined {\n return args.requestContext?.get('controller') as RoutingControllerContext | undefined;\n}\n\n/** A targeted route is exclusive; an entry without accountId uses automatic pool rotation. */\nfunction getRouteTargetAccountId(route: AccountRoute | null): string | undefined {\n return route?.accountId;\n}\n\nfunction getRequestActiveAccount(\n args: Pick<RoutingProcessorArgs, 'requestContext'>,\n store: CredentialStore,\n providerId: string,\n) {\n if (isRequestAccountRoutingExhausted(args.requestContext, providerId)) return undefined;\n const selectedId = getRequestAccountSelection(args.requestContext, providerId);\n if (selectedId) return store.listAccounts?.(providerId).find(account => account.id === selectedId);\n return store.getActiveAccount?.(providerId) ?? store.listAccounts?.(providerId).find(account => account.active);\n}\n\nfunction resolveAccountRoute(\n args: Pick<RoutingProcessorArgs, 'requestContext'>,\n explicit?: { id: string; modelId: string; accountId?: string },\n): AccountRoute | null {\n const controller = getRoutingController(args);\n const state = controller?.getState?.();\n const pending = state?.mastracodePendingModelFallback as\n | { toEntryId?: unknown; toModelId?: unknown; threadId?: unknown }\n | null\n | undefined;\n const pendingMatchesThread =\n pending &&\n typeof pending.toEntryId === 'string' &&\n typeof pending.toModelId === 'string' &&\n (pending.threadId === undefined || pending.threadId === controller?.threadId);\n const routeEntries = Array.isArray((state?.modelRoute as { entries?: unknown } | undefined)?.entries)\n ? ((state?.modelRoute as { entries: Array<{ id?: unknown; modelId?: unknown; accountId?: unknown }> }).entries ??\n [])\n : [];\n const entry = explicit\n ? explicit\n : pendingMatchesThread\n ? routeEntries.find(candidate => candidate.id === pending.toEntryId && candidate.modelId === pending.toModelId)\n : routeEntries.find(candidate => candidate.modelId === controller?.session?.modelId);\n if (!entry || typeof entry.id !== 'string' || typeof entry.modelId !== 'string') return null;\n const providerId = providerFromModelId(entry.modelId);\n if (!providerId) return null;\n return {\n entryId: entry.id,\n modelId: entry.modelId,\n providerId,\n ...(typeof entry.accountId === 'string' ? { accountId: entry.accountId } : {}),\n };\n}\n\n/**\n * A14: `Automatic` rotation starts *at* the persisted active account and walks\n * insertion order from there, wrapping once. The active account is the cursor\n * rotation last left at, so a turn that starts at index 0 regardless would\n * re-activate and re-try an account the previous turn already moved past —\n * which is the whole job the removed sticky-exclusion set was doing badly.\n * With no persisted active account the order is plain insertion order.\n */\nfunction orderAccountsFromActive(accounts: OAuthAccountRecord[], activeId: string | undefined) {\n const index = activeId === undefined ? -1 : accounts.findIndex(account => account.id === activeId);\n if (index <= 0) return accounts;\n return [...accounts.slice(index), ...accounts.slice(0, index)];\n}\n\nasync function applyPreferredAccountRoute(\n args: RoutingProcessorArgs,\n store: CredentialStore,\n route: AccountRoute,\n): Promise<boolean> {\n store.reload();\n const preferredId = getRouteTargetAccountId(route);\n const accounts = store.listAccounts?.(route.providerId) ?? [];\n if (accounts.length === 0 && preferredId === undefined) return false;\n const tried = getTriedInstances(args.state);\n const unavailable = new Set(accounts.filter(account => tried.has(account.id)).map(account => account.id));\n const active = getRequestActiveAccount(args, store, route.providerId) ?? store.getActiveAccount?.(route.providerId);\n const selected = // A12: a targeted route may use only the account it names. `Automatic`\n // keeps insertion order with full pool rotation (A10), starting from the\n // account the cursor already points at (A14).\n (\n preferredId\n ? accounts.filter(account => account.id === preferredId)\n : orderAccountsFromActive(accounts, active?.id)\n ).find(account => !unavailable.has(account.id));\n\n for (const accountId of unavailable) tried.add(accountId);\n if (!selected) {\n markRequestAccountRoutingExhausted(args.requestContext, route.providerId);\n return false;\n }\n\n if (active?.id === selected.id) {\n setRequestAccountSelection(args.requestContext, route.providerId, selected.id);\n return false;\n }\n // Activate before recording the request-scoped selection: a failed\n // activation must not leave the selection claiming an account that never\n // became the provider's active credential.\n const activated = store.activateAccount ? store.activateAccount(route.providerId, selected.id) : selected;\n if (!activated) {\n // Only a targeted route is out of options here. The exhausted marker is\n // request-wide and fails every credential read closed, so setting it for\n // `Automatic` would stop error recovery from retrying on a survivor.\n if (preferredId !== undefined) markRequestAccountRoutingExhausted(args.requestContext, route.providerId);\n return false;\n }\n setRequestAccountSelection(args.requestContext, route.providerId, activated.id);\n\n // Applying an explicit account choice is routine, not a failover notice.\n if (preferredId === undefined) {\n await emitAccountSwitchPart(args, {\n provider: route.providerId,\n from: active ? { id: active.id, label: active.label } : null,\n to: { id: activated.id, label: activated.label },\n reason: 'preferred-routing',\n at: new Date().toISOString(),\n });\n }\n return true;\n}\n\nexport class AccountRotationProcessor implements Processor {\n readonly id = 'mastracode-account-rotation' as const;\n\n constructor(\n private readonly options: {\n credentialStore: RotationCredentialStore;\n maxProcessorRetries: number;\n settingsPath?: string;\n },\n ) {}\n\n async processAPIError(args: ProcessAPIErrorArgs): Promise<{ retry: boolean }> {\n const { error, state } = args;\n\n // Core runs error processors even after the shared retry budget is spent\n // and silently discards `retry: true` then (llm-execution-step.ts\n // canRetryError) — rotating the cursor or emitting a switch part for a\n // retry that will never run would lie to both auth.json and the\n // transcript. With a fallback chain configured, a bare `retry: false`\n // here would silently advance the route for an error we never classified, so the\n // chain gate surfaces the error instead.\n if (args.retryCount >= this.options.maxProcessorRetries) {\n await this.gateChainHop(args, error);\n return { retry: false };\n }\n\n // Classify before attributing: an error from a provider outside the OAuth\n // registry (API-key/router providers are valid route entries) still hops on\n // rotate/hop classes — there is just no account cursor to advance.\n const classification = classifyRotationError(error);\n // Q14: 400/unknown errors never rotate and never advance routes. With a chain\n // active, core's fallback array would still advance on a bare\n // `retry: false` (it advances on any thrown non-TripWire error), so the\n // gate converts that into a surfaced error instead of a silent hop.\n if (classification.kind === 'never') {\n await this.gateChainHop(args, error);\n return { retry: false };\n }\n\n const cascade = await this.getModelRouteCascade(args);\n const currentEntry = cascade?.entries[cascade.position];\n const providerId =\n providerFromError(error) ??\n (currentEntry ? providerFromModelId(currentEntry.modelId) : undefined) ??\n (cascade ? undefined : providerFromSession(args));\n if (!providerId) {\n await this.emitModelFallbackPart(args, classification.kind === 'hop' ? 'persistent-outage' : 'pool-exhausted');\n return { retry: false };\n }\n\n // Deployed requests resolve the tenant-scoped store; local mode keeps the\n // host storage. Reading the host registry here would rotate or announce\n // host accounts for a tenant request. Annotated as the rotation surface:\n // `resolveCredentialStore` returns a plain CredentialStore, and the 401\n // path below uses the optional `forceRefreshActiveAccount` when the host\n // provides it.\n const store: RotationCredentialStore = resolveCredentialStore(args.requestContext) ?? this.options.credentialStore;\n store.reload();\n const accounts = store.listAccounts?.(providerId) ?? [];\n const active = getRequestActiveAccount(args, store, providerId);\n const route = currentEntry ? resolveAccountRoute(args, currentEntry) : resolveAccountRoute(args);\n\n // Q7 bucket 2: force one refresh of the active instance before rotating.\n // A 401 usually means a fresh-but-rejected token; the forced refresh\n // covers server-side clock skew and refresh-token races. Success retries\n // the same account — no rotation, no part. With no active account (e.g.\n // `ProviderAuthRequiredError` from an empty registry) a refresh can never\n // succeed, so skip it and fall through to the retry:false surface below,\n // which rethrows the original auth error instead of a generic pool\n // exhaustion message.\n if (classification.kind === 'rotate' && classification.reason === 'auth-failed' && active) {\n const forced = getForcedRefreshInstances(state);\n const refreshKey = `${providerId}:${active?.id ?? 'active'}`;\n if (!forced.has(refreshKey) && typeof store.forceRefreshActiveAccount === 'function') {\n forced.add(refreshKey);\n const token = await store.forceRefreshActiveAccount(providerId, active?.id);\n if (token !== undefined) {\n return { retry: true };\n }\n }\n }\n\n // A12: only a pin on the provider that actually failed makes this failure\n // exclusive. `route.providerId` is derived from the route's model while\n // `providerId` comes from the failed request's URL, which during a cascade\n // can still describe the session model rather than the entry being retried;\n // when they differ the pin belongs to an unrelated route, so the provider\n // that failed keeps its normal pool handling.\n const targetAccountId = route?.providerId === providerId ? getRouteTargetAccountId(route) : undefined;\n\n if (classification.kind === 'hop') {\n return this.declarePoolUnavailable(args, providerId, 'persistent-outage', targetAccountId !== undefined);\n }\n\n // A12: a targeted route never activates a sibling subscription. A\n // rotate-classified failure on the account the route selected proceeds to\n // the model route instead — the request hops, it does not spill\n // onto another subscription's quota. A targeted route has nothing to\n // rotate to at any pool size. A stale id for an account the user removed\n // reads the same way: fail closed rather than silently land on a sibling.\n if (targetAccountId !== undefined) {\n return this.declarePoolUnavailable(args, providerId, 'pool-exhausted', true);\n }\n\n // Count only this provider's instances: `tried` spans the whole request\n // (a cascade can visit several providers), so comparing its raw size to\n // this provider's account count would falsely report exhaustion when an\n // earlier provider in the same request already used up accounts.\n const tried = getTriedInstances(state);\n if (active) tried.add(active.id);\n // The tried-set is request-global and shared across providers after a\n // route hop, so exhaustion must count only this provider's ids.\n const triedForProvider = accounts.filter(account => tried.has(account.id)).length;\n if (triedForProvider >= accounts.length) {\n return this.declarePoolUnavailable(args, providerId, 'pool-exhausted');\n }\n\n // If the selected account was removed elsewhere, even a single survivor\n // is still untried. Resume from the freshly loaded global cursor.\n const candidates = active ? accounts : orderAccountsFromActive(accounts, store.getActiveAccount?.(providerId)?.id);\n const nextCandidate = candidates.find(account => !tried.has(account.id));\n\n const next = nextCandidate ? store.activateAccount?.(providerId, nextCandidate.id) : undefined;\n if (!next) {\n return this.declarePoolUnavailable(args, providerId, 'pool-exhausted');\n }\n setRequestAccountSelection(args.requestContext, providerId, next.id);\n tried.add(next.id);\n\n // The retry replays the request from scratch (Q10): rotate the assistant\n // message id so the retried response starts a fresh message instead of\n // appending to the partially streamed one.\n args.rotateResponseMessageId?.();\n\n await emitAccountSwitchPart(args, {\n provider: providerId,\n from: active ? { id: active.id, label: active.label } : null,\n to: { id: next.id, label: next.label },\n reason: classification.reason,\n at: new Date().toISOString(),\n });\n\n return { retry: true };\n }\n\n /**\n * Resolve the request's host-supplied model route once and cache the reachable\n * prefix in processor state. Resolution mirrors getDynamicModel so a hop is\n * never announced for an entry core cannot reach.\n */\n private async getModelRouteCascade(args: ProcessAPIErrorArgs): Promise<ModelRouteCascade | null> {\n if (args.state.modelRouteCascade !== undefined) {\n return (args.state.modelRouteCascade as ModelRouteCascade | null) ?? null;\n }\n const controller = getRoutingController(args);\n const state = controller?.getState?.();\n const route = (\n state?.modelRoute as\n | { entries?: Array<{ id?: unknown; label?: unknown; modelId?: unknown; accountId?: unknown }> }\n | undefined\n )?.entries;\n const pending = state?.mastracodePendingModelFallback as\n | { toEntryId?: unknown; threadId?: unknown }\n | null\n | undefined;\n const pendingMatchesThread =\n pending &&\n typeof pending.toEntryId === 'string' &&\n (pending.threadId === undefined || pending.threadId === controller?.threadId);\n const startIndex = pendingMatchesThread\n ? route?.findIndex(entry => entry.id === pending.toEntryId)\n : route?.findIndex(entry => entry.modelId === controller?.session?.modelId);\n if (!route || startIndex === undefined || startIndex < 0 || route.length - startIndex < 2) {\n args.state.modelRouteCascade = null;\n return null;\n }\n\n const thinkingLevel = resolveRequestThinkingLevel(\n {\n state: { thinkingLevel: state?.thinkingLevel },\n session: { modeId: typeof controller?.session?.modeId === 'string' ? controller.session.modeId : 'build' },\n },\n this.options.settingsPath,\n );\n const entries: ModelRouteCascade['entries'] = [];\n for (const entry of route.slice(startIndex)) {\n if (\n typeof entry.id !== 'string' ||\n entry.id.length === 0 ||\n typeof entry.modelId !== 'string' ||\n entry.modelId.length === 0\n ) {\n break;\n }\n if (entries.length > 0) {\n try {\n resolveModel(entry.modelId, {\n thinkingLevel,\n remapForCodexOAuth: true,\n requestContext: args.requestContext,\n });\n } catch {\n break;\n }\n }\n entries.push({\n id: entry.id,\n label: typeof entry.label === 'string' && entry.label.length > 0 ? entry.label : entry.id,\n modelId: entry.modelId,\n ...(typeof entry.accountId === 'string' ? { accountId: entry.accountId } : {}),\n });\n }\n if (entries.length < 2) {\n args.state.modelRouteCascade = null;\n return null;\n }\n const cascade: ModelRouteCascade = { entries, position: 0 };\n args.state.modelRouteCascade = cascade;\n return cascade;\n }\n\n /**\n * Q14 gate: 400/unknown/unattributable errors never advance routes. Core's\n * fallback array advances on ANY thrown error except TripWire\n * (llm-execution-step.ts), so when the session route has another entry and the\n * current entry is non-last, a bare `retry: false` would silently hop on an\n * error class the user excluded from hop triggers. TripWire is the only\n * no-advance escape: the runner rethrows it and the fallback loop declines\n * to advance. No chain (or already on the last entry) → return and let the\n * plain `retry: false` surface the error exactly as before.\n */\n private async gateChainHop(args: ProcessAPIErrorArgs, error: unknown): Promise<void> {\n const cascade = await this.getModelRouteCascade(args);\n if (!cascade) return;\n if (cascade.position >= cascade.entries.length - 1) return;\n const reason = error instanceof Error ? error.message : String(error);\n throw new TripWire(reason, {}, this.id);\n }\n\n /** Announce and persist the next model-route hop before core advances. */\n private async emitModelFallbackPart(\n args: ProcessAPIErrorArgs,\n reason: 'pool-exhausted' | 'persistent-outage',\n ): Promise<void> {\n const cascade = await this.getModelRouteCascade(args);\n if (!cascade) return;\n\n const from = cascade.entries[cascade.position];\n const to = cascade.entries[cascade.position + 1];\n if (!from || !to) return;\n\n const controller = args.requestContext?.get('controller') as\n | {\n threadId?: unknown;\n setState?: (updates: Record<string, unknown>) => Promise<void>;\n setThreadSetting?: (setting: { key: string; value: unknown }) => Promise<void>;\n emitEvent?: (event: { type: 'info'; message: string }) => void;\n }\n | undefined;\n const at = new Date().toISOString();\n const threadId = typeof controller?.threadId === 'string' ? controller.threadId : undefined;\n const pending = {\n fromEntryId: from.id,\n toEntryId: to.id,\n toModelId: to.modelId,\n ...(threadId ? { threadId } : {}),\n reason,\n at,\n } satisfies PendingModelFallback;\n await controller?.setThreadSetting?.({ key: MODEL_FALLBACK_STATE_KEY, value: pending });\n const data: ModelFallbackPartData = {\n from: { entryId: from.id, label: from.label },\n to: { entryId: to.id, label: to.label },\n reason,\n at,\n };\n try {\n await args.writer?.custom({ type: MODEL_FALLBACK_PART_TYPE, data });\n } catch (error) {\n await controller?.setThreadSetting?.({ key: MODEL_FALLBACK_STATE_KEY, value: undefined });\n throw error;\n }\n await controller?.setState?.({ [MODEL_FALLBACK_STATE_KEY]: pending });\n args.state.startNoticeEmitted = false;\n const targetRoute = resolveAccountRoute(args, to);\n if (targetRoute) {\n const store = resolveCredentialStore(args.requestContext) ?? this.options.credentialStore;\n await applyPreferredAccountRoute(args, store, targetRoute).catch(() => undefined);\n }\n controller?.emitEvent?.({ type: 'info', message: modelFallbackNoticeText(data) });\n cascade.position++;\n }\n\n /**\n * Pool done for this request: every instance recorded in the tried-set and\n * a `to: null` part emitted. Returns `retry: false` so core's fallback\n * array can hop to the next route entry (announced by `emitModelFallbackPart`).\n * Silent on the account part when the provider has no registry at all —\n * there are no accounts to declare unavailable, but the hop still applies.\n */\n private async declarePoolUnavailable(\n args: ProcessAPIErrorArgs,\n providerId: string,\n reason: 'pool-exhausted' | 'persistent-outage',\n exclusive = false,\n ): Promise<{ retry: boolean }> {\n const store = resolveCredentialStore(args.requestContext) ?? this.options.credentialStore;\n const accounts = store.listAccounts?.(providerId) ?? [];\n if (accounts.length === 0) {\n // No account registry (API-key-only provider): nothing rotated, but the\n // hop still happens — announce the model fallback before core advances.\n await this.emitModelFallbackPart(args, reason);\n return { retry: false };\n }\n\n const tried = getTriedInstances(args.state);\n for (const account of accounts) tried.add(account.id);\n\n const active = getRequestActiveAccount(args, store, providerId);\n\n await emitAccountSwitchPart(args, {\n provider: providerId,\n from: active ? { id: active.id, label: active.label } : null,\n to: null,\n reason,\n at: new Date().toISOString(),\n ...(exclusive ? { exclusive: true } : {}),\n });\n\n await this.emitModelFallbackPart(args, reason);\n\n return { retry: false };\n }\n}\n\n/**\n * Applies the pack's preferred account route once per request, before the\n * first model call. Without a route it only reloads the credential store so\n * the request sees accounts changed by other processes.\n *\n * TYPE CONSTRAINT: this class must NEVER implement `processAPIError`. It\n * lives in `inputProcessors`; the runner walks input processors first when\n * running `processAPIError`, so adding the method here would classify and\n * rotate errors BEFORE `StreamErrorRetryProcessor`'s transient retries run.\n */\nexport class AccountStartNoticeProcessor implements Processor {\n readonly id = 'mastracode-account-start-notice' as const;\n\n constructor(private readonly options: { credentialStore: CredentialStore }) {}\n\n async processInput(args: ProcessInputArgs): Promise<ProcessInputResult> {\n if (args.state.startNoticeEmitted) return args.messageList;\n\n // Deployed requests resolve the tenant-scoped store so host accounts are\n // never listed, activated, or announced for a tenant run. Local mode keeps\n // the constructor's storage.\n const store = resolveCredentialStore(args.requestContext) ?? this.options.credentialStore;\n\n const route = resolveAccountRoute(args);\n if (!route) {\n store.reload();\n return args.messageList;\n }\n\n // A14: a route whose accounts are all unavailable is not a pre-emptive\n // abort. `applyPreferredAccountRoute` marks the provider on the request so\n // credential reads fail closed rather than falling through to the active\n // account, and the request then runs and fails at the provider — which is\n // what lets the error lane classify it and hand the turn to the route's\n // configured fallback chain. The removed persisted set threw here instead,\n // before any socket opened, so the chain was never reached.\n const switched = await applyPreferredAccountRoute(args, store, route);\n if (switched || getRouteTargetAccountId(route) !== undefined) {\n args.state.startNoticeEmitted = true;\n }\n return args.messageList;\n }\n}\n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D,MAAM,WAAW,YAAY;IAC3B,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,wEAAwE;IACxE,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,MAAM,EAAE,UAAU,CAAC;IACnB,SAAS,EAAE,OAAO,CAAC;IACnB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,IAAI,CAAC,EAAE,OAAO,CAAC;IACf,aAAa,CAAC,EAAE,aAAa,CAAC;IAC9B,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,WAAW,EAAE,OAAO,CAAC;IACrB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,gEAAgE;IAChE,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,gFAAgF;IAChF,cAAc,CAAC,EAAE,cAAc,CAAC;CACjC;AAKD;;;;;GAKG;AACH,wBAAgB,eAAe,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,OAAO,CAcvD;AAED;;;;GAIG;AACH,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,YAAY,CAsC9D;AAED,wBAAgB,kBAAkB,IAAI,IAAI,CA+BzC;AAED;;;GAGG;AACH,wBAAsB,QAAQ,CAC5B,eAAe,CAAC,EAAE,MAAM,GAAG,IAAI,EAC/B,OAAO,CAAC,EAAE;IAAE,QAAQ,CAAC,EAAE;QAAE,IAAI,CAAC,EAAE,MAAM,CAAC;QAAC,KAAK,CAAC,EAAE,MAAM,CAAA;KAAE,CAAA;CAAE,GACzD,OAAO,CAAC,KAAK,CAAC,CAoJhB"}
@@ -192,6 +192,9 @@ async function runMCCli(predrainedInput, options) {
192
192
  } finally {
193
193
  releaseAllThreadLocks();
194
194
  if (boot) {
195
+ try {
196
+ boot.releaseThreadClaims();
197
+ } catch {}
195
198
  try {
196
199
  boot.stopPluginSignalProviders();
197
200
  } catch {}