@mastra/code-sdk 1.5.2-alpha.0 → 1.5.2-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/LICENSE.md +6 -4
  3. package/dist/agents/mastracode-gateway.d.ts.map +1 -1
  4. package/dist/agents/mastracode-gateway.js +19 -2
  5. package/dist/agents/mastracode-gateway.js.map +1 -1
  6. package/dist/agents/memory.d.ts +6 -0
  7. package/dist/agents/memory.d.ts.map +1 -1
  8. package/dist/agents/memory.js +28 -5
  9. package/dist/agents/memory.js.map +1 -1
  10. package/dist/agents/workspace.js +1 -1
  11. package/dist/auth/index.d.ts +1 -0
  12. package/dist/auth/index.d.ts.map +1 -1
  13. package/dist/auth/index.js +2 -1
  14. package/dist/auth/providers/kimi-coding.d.ts +38 -0
  15. package/dist/auth/providers/kimi-coding.d.ts.map +1 -0
  16. package/dist/auth/providers/kimi-coding.js +232 -0
  17. package/dist/auth/providers/kimi-coding.js.map +1 -0
  18. package/dist/auth/storage.d.ts +1 -0
  19. package/dist/auth/storage.d.ts.map +1 -1
  20. package/dist/auth/storage.js +23 -9
  21. package/dist/auth/storage.js.map +1 -1
  22. package/dist/index.d.ts.map +1 -1
  23. package/dist/index.js +7 -2
  24. package/dist/index.js.map +1 -1
  25. package/dist/onboarding/packs.d.ts +3 -0
  26. package/dist/onboarding/packs.d.ts.map +1 -1
  27. package/dist/onboarding/packs.js +48 -26
  28. package/dist/onboarding/packs.js.map +1 -1
  29. package/dist/onboarding/settings.d.ts +9 -3
  30. package/dist/onboarding/settings.d.ts.map +1 -1
  31. package/dist/onboarding/settings.js +24 -3
  32. package/dist/onboarding/settings.js.map +1 -1
  33. package/dist/process-memory-diagnostics.js +4 -4
  34. package/dist/process-memory-diagnostics.js.map +1 -1
  35. package/dist/providers/kimi-coding.d.ts +15 -0
  36. package/dist/providers/kimi-coding.d.ts.map +1 -0
  37. package/dist/providers/kimi-coding.js +69 -0
  38. package/dist/providers/kimi-coding.js.map +1 -0
  39. package/dist/schema.d.ts +7 -0
  40. package/dist/schema.d.ts.map +1 -1
  41. package/dist/schema.js +1 -0
  42. package/dist/schema.js.map +1 -1
  43. package/package.json +10 -10
package/CHANGELOG.md CHANGED
@@ -1,5 +1,39 @@
1
1
  # @mastra/code-sdk
2
2
 
3
+ ## 1.5.2-alpha.2
4
+
5
+ ### Patch Changes
6
+
7
+ - Added Kimi For Coding account authentication, API key authentication, token refresh, and model routing. ([#22428](https://github.com/mastra-ai/mastra/pull/22428))
8
+
9
+ ```text
10
+ /connect
11
+ ```
12
+
13
+ - Updated dependencies [[`0885364`](https://github.com/mastra-ai/mastra/commit/0885364c2fc7fa31febcfc444fc1ba5231ac1257)]:
14
+ - @mastra/core@1.63.1-alpha.2
15
+ - @mastra/memory@1.28.1-alpha.1
16
+ - @mastra/libsql@1.22.1-alpha.0
17
+ - @mastra/pg@1.22.1-alpha.0
18
+
19
+ ## 1.5.2-alpha.1
20
+
21
+ ### Patch Changes
22
+
23
+ - Fix knowledge captured in factory sessions being stored in the wrong tenant. ([#21823](https://github.com/mastra-ai/mastra/pull/21823))
24
+
25
+ Knowledge captured during a factory session is now always stored under the organization
26
+ that owns the session, so it is visible in that organization's knowledge graph. A session
27
+ whose organization cannot be determined no longer stores knowledge somewhere it could
28
+ never be read back from; it stops capturing and reports why. Local (TUI/studio) use is
29
+ unaffected and captures under a dedicated local scope.
30
+
31
+ - Updated dependencies [[`295e506`](https://github.com/mastra-ai/mastra/commit/295e506b9e6cec99e7181c5f712648888cd9486f), [`8c3be07`](https://github.com/mastra-ai/mastra/commit/8c3be0761a862c5c035ed6e5d633de87cbba20e7), [`078affd`](https://github.com/mastra-ai/mastra/commit/078affdaea57ac5e95a77e9e7b197d1878190684), [`a87ff53`](https://github.com/mastra-ai/mastra/commit/a87ff53cef9318bea80c38c3bf3d9d9d507ac3c1), [`9e3403e`](https://github.com/mastra-ai/mastra/commit/9e3403e9868240cb18841898e84cf008ebd7a87e), [`791bf5e`](https://github.com/mastra-ai/mastra/commit/791bf5e81cd27e2e1cff66122f1380ab8a3dda41)]:
32
+ - @mastra/memory@1.28.1-alpha.0
33
+ - @mastra/core@1.63.1-alpha.1
34
+ - @mastra/observability@1.17.4-alpha.0
35
+ - @mastra/mcp@1.17.2
36
+
3
37
  ## 1.5.2-alpha.0
4
38
 
5
39
  ### Patch Changes
package/LICENSE.md CHANGED
@@ -1,10 +1,12 @@
1
1
  Portions of this software are licensed as follows:
2
2
 
3
- - All content that resides under any directory named "ee/" within this
3
+ - All content that resides under any directory named `ee/` within this
4
4
  repository, including but not limited to:
5
- - `packages/core/src/auth/ee/`
6
- - `packages/server/src/server/auth/ee/`
7
- is licensed under the license defined in `ee/LICENSE`.
5
+ - `@mastra/core/auth/ee`
6
+ - `@mastra/core/agent-builder/ee`
7
+ - `@mastra/editor/ee`
8
+
9
+ is licensed under the license defined in [`ee/LICENSE`](https://github.com/mastra-ai/mastra/blob/main/ee/LICENSE).
8
10
 
9
11
  - All third-party components incorporated into the Mastra Software are
10
12
  licensed under the original license provided by the owner of the
@@ -1 +1 @@
1
- {"version":3,"file":"mastracode-gateway.d.ts","sourceRoot":"","sources":["../../src/agents/mastracode-gateway.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAwB,0BAA0B,EAAE,MAAM,+BAA+B,CAAC;AACtG,OAAO,EAGL,kBAAkB,EAGnB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,KAAK,EACV,kBAAkB,EAClB,iBAAiB,EACjB,oBAAoB,EACpB,2BAA2B,EAC3B,cAAc,EACf,MAAM,kBAAkB,CAAC;AAG1B,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAiBxD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,8BAA8B,CAAC;AAIlE,eAAO,MAAM,aAAa,YAAY,CAAC;AACvC,eAAO,MAAM,qBAAqB,YAAY,CAAC;AAC/C,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AE,GAAG,CAAC;QAChB,kBAAkB,CAAC,EAAE,GAAG,CAAC;KAC1B,GAAG,oBAAoB;CA8MzB"}
@@ -4,6 +4,7 @@ import { getCustomProviderId, loadSettings } from "../onboarding/settings.js";
4
4
  import { resolveCustomProviders } from "./custom-provider-source.js";
5
5
  import { buildAnthropicOAuthFetch, claudeCodeMiddleware, createAnthropicThinkingMiddleware, opencodeClaudeMaxProvider, promptCacheMiddleware } from "../providers/claude-max.js";
6
6
  import { getCopilotModelCatalog, githubCopilotProvider } from "../providers/github-copilot.js";
7
+ import { KIMI_CODING_MODELS, kimiCodingProvider } from "../providers/kimi-coding.js";
7
8
  import { xaiProvider } from "../providers/xai.js";
8
9
  import { createOpenAI } from "@ai-sdk/openai";
9
10
  import { wrapLanguageModel } from "ai";
@@ -91,7 +92,10 @@ function getProviderAuthKey(providerId, credentials = authStorage) {
91
92
  const authProviderId = getAuthProviderId(providerId);
92
93
  const storedCred = credentials.get(authProviderId);
93
94
  if (storedCred?.type === "api_key" && storedCred.key.trim().length > 0) return storedCred.key.trim();
94
- return credentials.getStoredApiKey(authProviderId)?.trim() || void 0;
95
+ const dedicatedKey = credentials.getStoredApiKey(authProviderId)?.trim();
96
+ if (dedicatedKey) return dedicatedKey;
97
+ if (credentials.allowEnvironmentFallback === false) return void 0;
98
+ return authProviderId === "kimi-for-coding" ? process.env.KIMI_API_KEY?.trim() || void 0 : void 0;
95
99
  }
96
100
  function resolveAuth(request, mastraGatewayApiKey) {
97
101
  return MastraCodeGateway.resolveProviderAuth(request, mastraGatewayApiKey);
@@ -203,7 +207,8 @@ var MastraCodeGateway = class MastraCodeGateway extends MastraModelGateway {
203
207
  apiKey: mastraGatewayApiKey,
204
208
  source: "gateway"
205
209
  };
206
- if (credentials.get(getAuthProviderId(request.providerId))?.type === "oauth") return {
210
+ const authProviderId = getAuthProviderId(request.providerId);
211
+ if (credentials.get(authProviderId)?.type === "oauth") return {
207
212
  bearerToken: "oauth",
208
213
  source: "gateway"
209
214
  };
@@ -257,6 +262,13 @@ var MastraCodeGateway = class MastraCodeGateway extends MastraModelGateway {
257
262
  models
258
263
  };
259
264
  }
265
+ providers["kimi-for-coding"] = {
266
+ name: "Kimi For Coding",
267
+ apiKeyEnvVar: "KIMI_API_KEY",
268
+ apiKeyHeader: "Authorization",
269
+ gateway: this.id,
270
+ models: [...KIMI_CODING_MODELS]
271
+ };
260
272
  try {
261
273
  const copilotModels = await getCopilotModelCatalog({ authStorage });
262
274
  providers["github-copilot"] = {
@@ -323,6 +335,11 @@ var MastraCodeGateway = class MastraCodeGateway extends MastraModelGateway {
323
335
  authStorage: this.#credentials
324
336
  });
325
337
  if (this.#routeThroughMastraGateway) return this.#mastraGateway.resolveLanguageModel(args);
338
+ if (args.providerId === "kimi-for-coding") return kimiCodingProvider(args.modelId, {
339
+ apiKey: args.apiKey,
340
+ headers: args.headers,
341
+ credentialStore: this.#credentials
342
+ });
326
343
  return new ModelRouterLanguageModel({
327
344
  id: `${args.providerId}/${args.modelId}`,
328
345
  apiKey: args.apiKey,
@@ -1 +1 @@
1
- {"version":3,"file":"mastracode-gateway.js","names":["#mastraGateway","#mastraGatewayBaseUrl","#mastraGatewayApiKey","#routeThroughMastraGateway","#thinkingLevel","#customProviders","#settingsPath","#credentials","#getCustomProviders","#resolveAnthropicModel","#resolveOpenAIModel"],"sources":["../../src/agents/mastracode-gateway.ts"],"sourcesContent":["import { createAnthropic } from '@ai-sdk/anthropic';\nimport { createOpenAI } from '@ai-sdk/openai';\nimport { createOpenAICompatible } from '@ai-sdk/openai-compatible';\nimport type { CustomAvailableModel, CustomModelCatalogProvider } from '@mastra/core/agent-controller';\nimport {\n GATEWAY_AUTH_HEADER,\n MastraGateway,\n MastraModelGateway,\n ModelRouterLanguageModel,\n PROVIDER_REGISTRY,\n} from '@mastra/core/llm';\nimport type {\n GatewayAuthRequest,\n GatewayAuthResult,\n GatewayLanguageModel,\n MastraModelGatewayInterface,\n ProviderConfig,\n} from '@mastra/core/llm';\nimport { wrapLanguageModel } from 'ai';\nimport { AuthStorage } from '../auth/storage.js';\nimport type { CredentialStore } from '../auth/types.js';\nimport { getCustomProviderId, loadSettings, MASTRA_GATEWAY_PROVIDER } from '../onboarding/settings.js';\nimport {\n buildAnthropicOAuthFetch,\n claudeCodeMiddleware,\n createAnthropicThinkingMiddleware,\n opencodeClaudeMaxProvider,\n promptCacheMiddleware,\n} from '../providers/claude-max.js';\nimport { getCopilotModelCatalog, githubCopilotProvider } from '../providers/github-copilot.js';\nimport {\n buildOpenAICodexOAuthFetch,\n createCodexMiddleware,\n getEffectiveThinkingLevel,\n openaiCodexProvider,\n THINKING_LEVEL_TO_REASONING_EFFORT,\n} from '../providers/openai-codex.js';\nimport type { ThinkingLevel } from '../providers/openai-codex.js';\nimport { xaiProvider } from '../providers/xai.js';\nimport { resolveCustomProviders } from './custom-provider-source.js';\n\nexport const OPENAI_PREFIX = 'openai/';\nexport const MASTRA_GATEWAY_PREFIX = 'mastra/';\nexport const MASTRACODE_GATEWAY_ID = 'mastracode';\n\nconst CODEX_OPENAI_MODEL_REMAPS: Record<string, string> = {\n 'gpt-5.3': 'gpt-5.3-codex',\n 'gpt-5.2': 'gpt-5.2-codex',\n 'gpt-5.1': 'gpt-5.1-codex',\n 'gpt-5.1-mini': 'gpt-5.1-codex-mini',\n 'gpt-5': 'gpt-5-codex',\n};\n\ntype ModelRequestHeaders = Record<string, string>;\n\nexport type MastraCodeCustomProvider = { name: string; url: string; apiKey?: string; models?: string[] };\n\nexport type MastraCodeGatewayOptions = {\n mastraGatewayBaseUrl: string;\n mastraGatewayApiKey?: string;\n routeThroughMastraGateway: boolean;\n thinkingLevel?: ThinkingLevel;\n customProviders?: MastraCodeCustomProvider[];\n settingsPath?: string;\n /**\n * Per-tenant credential source for this gateway instance. Defaults to the\n * server-global file-backed `AuthStorage`; deployed web passes the calling\n * tenant's store so model calls use the caller's own credentials.\n */\n credentialStore?: CredentialStore;\n};\n\nconst authStorage = new AuthStorage();\n\nexport function reloadAuthStorage() {\n authStorage.reload();\n}\n\nexport function stripMastraGatewayPrefix(modelId: string): string {\n return modelId.startsWith(MASTRA_GATEWAY_PREFIX) ? modelId.substring(MASTRA_GATEWAY_PREFIX.length) : modelId;\n}\n\nfunction normalizeAnthropicModelId(modelId: string): string {\n return modelId.replace(/\\.(?=\\d)/g, '-');\n}\n\nexport function remapOpenAIModelForCodexOAuth(modelId: string): string {\n const normalizedModelId = stripMastraGatewayPrefix(modelId);\n\n if (!normalizedModelId.startsWith(OPENAI_PREFIX)) {\n return modelId;\n }\n\n const openaiModelId = normalizedModelId.substring(OPENAI_PREFIX.length);\n\n if (openaiModelId.includes('-codex')) {\n return modelId;\n }\n\n const codexModelId = CODEX_OPENAI_MODEL_REMAPS[openaiModelId];\n if (!codexModelId) {\n return modelId;\n }\n\n const remappedModelId = `${OPENAI_PREFIX}${codexModelId}`;\n return modelId.startsWith(MASTRA_GATEWAY_PREFIX) ? `${MASTRA_GATEWAY_PREFIX}${remappedModelId}` : remappedModelId;\n}\n\n/**\n * Resolve the Anthropic API key.\n * Main slot → dedicated apikey: slot → env var.\n */\nexport function getAnthropicApiKey(credentials: CredentialStore = authStorage): string | undefined {\n const storedCred = credentials.get('anthropic');\n if (storedCred?.type === 'api_key' && storedCred.key.trim().length > 0) {\n return storedCred.key.trim();\n }\n const dedicatedKey = credentials.getStoredApiKey('anthropic')?.trim();\n if (dedicatedKey) return dedicatedKey;\n return credentials.allowEnvironmentFallback === false\n ? undefined\n : process.env.ANTHROPIC_API_KEY?.trim() || undefined;\n}\n\n/**\n * Resolve the OpenAI API key.\n * Main slot → dedicated apikey: slot → env var.\n */\nexport function getOpenAIApiKey(credentials: CredentialStore = authStorage): string | undefined {\n const storedCred = credentials.get('openai-codex');\n if (storedCred?.type === 'api_key' && storedCred.key.trim().length > 0) {\n return storedCred.key.trim();\n }\n const dedicatedKey = credentials.getStoredApiKey('openai-codex')?.trim();\n if (dedicatedKey) return dedicatedKey;\n return credentials.allowEnvironmentFallback === false ? undefined : process.env.OPENAI_API_KEY?.trim() || undefined;\n}\n\nfunction anthropicApiKeyProvider(\n modelId: string,\n apiKey: string,\n headers?: ModelRequestHeaders,\n thinkingLevel?: ThinkingLevel,\n) {\n const anthropic = createAnthropic({ apiKey, headers });\n const thinkingMiddleware = createAnthropicThinkingMiddleware(modelId, thinkingLevel);\n return wrapLanguageModel({\n model: anthropic(modelId),\n middleware: [promptCacheMiddleware, ...(thinkingMiddleware ? [thinkingMiddleware] : [])],\n });\n}\n\nfunction openaiApiKeyProvider(modelId: string, apiKey: string, headers?: ModelRequestHeaders) {\n const openai = createOpenAI({ apiKey, baseURL: process.env.OPENAI_BASE_URL, headers });\n return wrapLanguageModel({\n model: openai.responses(modelId),\n middleware: [],\n });\n}\n\nfunction getAuthProviderId(providerId: string): string {\n return providerId === 'openai' ? 'openai-codex' : providerId;\n}\n\nfunction getProviderAuthKey(providerId: string, credentials: CredentialStore = authStorage): string | undefined {\n const authProviderId = getAuthProviderId(providerId);\n const storedCred = credentials.get(authProviderId);\n if (storedCred?.type === 'api_key' && storedCred.key.trim().length > 0) {\n return storedCred.key.trim();\n }\n return credentials.getStoredApiKey(authProviderId)?.trim() || undefined;\n}\n\nexport function resolveAuth(request: GatewayAuthRequest, mastraGatewayApiKey?: string): GatewayAuthResult | undefined {\n return MastraCodeGateway.resolveProviderAuth(request, mastraGatewayApiKey);\n}\n\nfunction getGatewayProviderKey(gatewayId: string, providerId: string): string {\n if (gatewayId === 'models.dev') return providerId;\n return providerId === gatewayId ? gatewayId : `${gatewayId}/${providerId}`;\n}\n\nfunction parseGatewayRouterId(\n routerId: string,\n gateway: MastraModelGatewayInterface,\n): { gatewayId: string; providerId: string; modelId: string } {\n const [firstPart = '', secondPart = '', ...restParts] = routerId.split('/');\n const gatewayId = gateway.id;\n\n if (firstPart === gatewayId && secondPart) {\n return {\n gatewayId,\n providerId: secondPart,\n modelId: restParts.join('/'),\n };\n }\n\n return {\n gatewayId,\n providerId: firstPart,\n modelId: [secondPart, ...restParts].filter(Boolean).join('/'),\n };\n}\n\nfunction hasResolvedAuth(auth: GatewayAuthResult | undefined): boolean {\n if (!auth) return false;\n if (auth.apiKey || auth.bearerToken) return true;\n return auth.headers ? Object.keys(auth.headers).length > 0 : false;\n}\n\nasync function resolveGatewayProviderAuth(\n gateway: MastraModelGatewayInterface,\n routerId: string,\n): Promise<GatewayAuthResult | undefined> {\n if (!gateway.resolveAuth) return undefined;\n\n const parsed = parseGatewayRouterId(routerId, gateway);\n try {\n const result = await gateway.resolveAuth({\n gatewayId: parsed.gatewayId,\n providerId: parsed.providerId,\n modelId: parsed.modelId,\n routerId,\n });\n return hasResolvedAuth(result) ? result : undefined;\n } catch {\n return undefined;\n }\n}\n\nasync function getMastraCodeProviderConfigs(\n gateway: MastraModelGatewayInterface,\n): Promise<Record<string, ProviderConfig>> {\n const providers: Record<string, ProviderConfig> = { ...(PROVIDER_REGISTRY as Record<string, ProviderConfig>) };\n\n try {\n const gatewayProviders = await gateway.fetchProviders();\n for (const [providerId, config] of Object.entries(gatewayProviders)) {\n providers[getGatewayProviderKey(gateway.id, providerId)] = {\n ...config,\n gateway: gateway.id,\n };\n }\n } catch (error) {\n console.warn(`Failed to load providers from gateway ${gateway.id}:`, error);\n }\n\n return providers;\n}\n\nfunction getApiKeyEnvVar(providerConfig: Pick<ProviderConfig, 'apiKeyEnvVar'> | undefined): string | undefined {\n const envVars = providerConfig?.apiKeyEnvVar;\n return Array.isArray(envVars) ? envVars[0] : envVars;\n}\n\nexport class MastraCodeGateway extends MastraModelGateway {\n readonly id = MASTRACODE_GATEWAY_ID;\n readonly name = 'MastraCode Gateway';\n\n readonly #mastraGateway: MastraGateway;\n readonly #mastraGatewayBaseUrl: string;\n readonly #mastraGatewayApiKey?: string;\n readonly #routeThroughMastraGateway: boolean;\n readonly #thinkingLevel?: ThinkingLevel;\n readonly #customProviders?: MastraCodeCustomProvider[];\n readonly #settingsPath?: string;\n readonly #credentials: CredentialStore;\n\n constructor({\n mastraGatewayBaseUrl,\n mastraGatewayApiKey,\n routeThroughMastraGateway,\n thinkingLevel,\n customProviders,\n settingsPath,\n credentialStore,\n }: MastraCodeGatewayOptions) {\n super();\n this.#mastraGateway = new MastraGateway({ baseUrl: mastraGatewayBaseUrl });\n this.#mastraGatewayBaseUrl = mastraGatewayBaseUrl;\n this.#mastraGatewayApiKey = mastraGatewayApiKey;\n this.#routeThroughMastraGateway = routeThroughMastraGateway;\n this.#thinkingLevel = thinkingLevel;\n this.#customProviders = customProviders;\n this.#settingsPath = settingsPath;\n this.#credentials = credentialStore ?? authStorage;\n }\n\n static getMastraGatewayApiKey(): string | undefined {\n return authStorage.getStoredApiKey(MASTRA_GATEWAY_PROVIDER) ?? process.env['MASTRA_GATEWAY_API_KEY'];\n }\n\n /** @deprecated Renamed to {@link MastraCodeGateway.getMastraGatewayApiKey}. */\n static getMemoryGatewayApiKey(): string | undefined {\n return MastraCodeGateway.getMastraGatewayApiKey();\n }\n\n /**\n * Claim an unprefixed model id (e.g. a bare `anthropic/...`) when this gateway\n * can authenticate it via OAuth or a stored/env credential. This lets the\n * shared gateway router select MastraCode for auth resolution, so the status\n * bar and `/api-keys` reflect OAuth logins instead of only checking env vars.\n */\n handlesModel(modelId: string): boolean {\n const parsed = parseGatewayRouterId(modelId, this);\n if (!parsed.providerId || !parsed.modelId) return false;\n if (this.#routeThroughMastraGateway && this.#mastraGatewayApiKey) return true;\n const customProvider = this.#getCustomProviders().find(\n provider => parsed.providerId === getCustomProviderId(provider.name),\n );\n if (customProvider?.apiKey) return true;\n return hasResolvedAuth(\n MastraCodeGateway.resolveProviderAuth(\n {\n gatewayId: this.id,\n providerId: parsed.providerId,\n modelId: parsed.modelId,\n routerId: modelId,\n },\n undefined,\n this.#credentials,\n ),\n );\n }\n\n static resolveProviderAuth(\n request: GatewayAuthRequest,\n mastraGatewayApiKey?: string,\n credentials: CredentialStore = authStorage,\n ): GatewayAuthResult | undefined {\n if (request.gatewayId === 'mastra' && mastraGatewayApiKey) {\n return { apiKey: mastraGatewayApiKey, source: 'gateway' };\n }\n\n const storedCred = credentials.get(getAuthProviderId(request.providerId));\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 try {\n const copilotModels = await getCopilotModelCatalog({ authStorage });\n providers['github-copilot'] = {\n name: 'GitHub Copilot',\n apiKeyEnvVar: '',\n apiKeyHeader: 'Authorization',\n gateway: this.id,\n models: copilotModels.map(model => model.id),\n };\n } catch (error) {\n console.warn('Failed to load GitHub Copilot model catalog:', error);\n }\n\n return providers;\n }\n\n buildUrl(modelId: string): string | undefined | Promise<string | undefined> {\n return this.#routeThroughMastraGateway ? this.#mastraGateway.buildUrl(modelId) : modelId;\n }\n\n async getApiKey(modelId: string): Promise<string> {\n const providerId = stripMastraGatewayPrefix(modelId).split('/', 1)[0];\n if (this.#routeThroughMastraGateway) return this.#mastraGatewayApiKey ?? '';\n return providerId ? (getProviderAuthKey(providerId, this.#credentials) ?? '') : '';\n }\n\n resolveAuth(request: GatewayAuthRequest): GatewayAuthResult | undefined {\n if (this.#routeThroughMastraGateway && this.#mastraGatewayApiKey) {\n return { apiKey: this.#mastraGatewayApiKey, source: 'gateway' };\n }\n\n const customProvider = this.#getCustomProviders().find(\n provider => request.providerId === getCustomProviderId(provider.name),\n );\n if (customProvider?.apiKey) {\n return { apiKey: customProvider.apiKey, source: 'gateway' };\n }\n\n return MastraCodeGateway.resolveProviderAuth(request, undefined, this.#credentials);\n }\n\n resolveLanguageModel(args: {\n modelId: string;\n providerId: string;\n apiKey: string;\n headers?: Record<string, string>;\n transport?: any;\n responsesWebSocket?: any;\n }): GatewayLanguageModel {\n const customProvider = this.#getCustomProviders().find(\n provider => args.providerId === getCustomProviderId(provider.name),\n );\n if (customProvider) {\n const provider = createOpenAICompatible({\n name: args.providerId,\n baseURL: customProvider.url,\n apiKey: args.apiKey,\n headers: args.headers,\n });\n return provider.chatModel(args.modelId) as unknown as GatewayLanguageModel;\n }\n\n if (args.providerId === 'github-copilot') {\n return githubCopilotProvider(args.modelId, {\n headers: args.headers,\n authStorage: this.#credentials,\n }) as unknown as GatewayLanguageModel;\n }\n\n if (args.providerId === 'moonshotai') {\n // Prefer the gateway-resolved key (stored credentials), then the canonical\n // registry env var. Keep the legacy typo name as a fallback for anyone who\n // set it because of the previous error message.\n const apiKey =\n args.apiKey?.trim() || process.env.MOONSHOT_API_KEY?.trim() || process.env.MOONSHOT_AI_API_KEY?.trim();\n if (!apiKey) {\n throw new Error('Need MOONSHOT_API_KEY');\n }\n return createAnthropic({\n apiKey,\n baseURL: 'https://api.moonshot.ai/anthropic/v1',\n name: 'moonshotai.anthropicv1',\n headers: args.headers,\n })(args.modelId) as unknown as GatewayLanguageModel;\n }\n\n if (args.providerId === 'anthropic') {\n return this.#resolveAnthropicModel(args);\n }\n\n if (args.providerId === 'openai') {\n const openaiModel = this.#resolveOpenAIModel(args);\n if (openaiModel) return openaiModel;\n }\n\n if (args.providerId === 'xai' && this.#credentials.get('xai')?.type === 'oauth') {\n return xaiProvider(args.modelId, {\n headers: args.headers,\n authStorage: this.#credentials,\n }) as unknown as GatewayLanguageModel;\n }\n\n if (this.#routeThroughMastraGateway) {\n return this.#mastraGateway.resolveLanguageModel(args) as GatewayLanguageModel;\n }\n\n return new ModelRouterLanguageModel({\n id: `${args.providerId}/${args.modelId}` as `${string}/${string}`,\n apiKey: args.apiKey,\n headers: args.headers,\n }) as unknown as GatewayLanguageModel;\n }\n\n #resolveAnthropicModel(args: {\n modelId: string;\n providerId: string;\n apiKey: string;\n headers?: Record<string, string>;\n transport?: any;\n responsesWebSocket?: any;\n }): GatewayLanguageModel {\n const bareModelId = normalizeAnthropicModelId(args.modelId);\n const storedCred = this.#credentials.get('anthropic');\n const thinkingMiddleware = createAnthropicThinkingMiddleware(bareModelId, this.#thinkingLevel);\n\n if (this.#routeThroughMastraGateway) {\n if (storedCred?.type === 'oauth') {\n const anthropic = createAnthropic({\n apiKey: 'oauth-gateway-placeholder',\n baseURL: `${this.#mastraGatewayBaseUrl}/v1`,\n headers: {\n [GATEWAY_AUTH_HEADER]: `Bearer ${args.apiKey}`,\n ...args.headers,\n },\n fetch: buildAnthropicOAuthFetch({ authStorage: this.#credentials }) as any,\n });\n\n return wrapLanguageModel({\n model: anthropic(bareModelId),\n middleware: [\n claudeCodeMiddleware,\n promptCacheMiddleware,\n ...(thinkingMiddleware ? [thinkingMiddleware] : []),\n ],\n }) as unknown as GatewayLanguageModel;\n }\n\n const gatewayModel = this.#mastraGateway.resolveLanguageModel({\n ...args,\n modelId: bareModelId,\n }) as GatewayLanguageModel;\n if (!thinkingMiddleware) return gatewayModel;\n return wrapLanguageModel({\n model: gatewayModel as any,\n middleware: [thinkingMiddleware],\n }) as unknown as GatewayLanguageModel;\n }\n\n if (storedCred?.type === 'oauth') {\n return opencodeClaudeMaxProvider(bareModelId, {\n headers: args.headers,\n authStorage: this.#credentials,\n thinkingLevel: this.#thinkingLevel,\n }) as unknown as GatewayLanguageModel;\n }\n\n if (storedCred?.type === 'api_key' && storedCred.key.trim().length > 0) {\n return anthropicApiKeyProvider(\n bareModelId,\n storedCred.key.trim(),\n args.headers,\n this.#thinkingLevel,\n ) as unknown as GatewayLanguageModel;\n }\n\n const apiKey = getAnthropicApiKey(this.#credentials);\n if (apiKey) {\n return anthropicApiKeyProvider(\n bareModelId,\n apiKey,\n args.headers,\n this.#thinkingLevel,\n ) as unknown as GatewayLanguageModel;\n }\n\n // No stored credentials: use the OAuth-backed provider so the first request can trigger login.\n return opencodeClaudeMaxProvider(bareModelId, {\n headers: args.headers,\n authStorage: this.#credentials,\n thinkingLevel: this.#thinkingLevel,\n }) as unknown as GatewayLanguageModel;\n }\n\n #resolveOpenAIModel(args: {\n modelId: string;\n providerId: string;\n apiKey: string;\n headers?: Record<string, string>;\n transport?: any;\n responsesWebSocket?: any;\n }): GatewayLanguageModel | undefined {\n const storedCred = this.#credentials.get('openai-codex');\n\n if (this.#routeThroughMastraGateway) {\n if (storedCred?.type === 'oauth') {\n const resolvedModelId = remapOpenAIModelForCodexOAuth(`openai/${args.modelId}`);\n const resolvedBareModelId = resolvedModelId.substring(OPENAI_PREFIX.length);\n const requestedLevel: ThinkingLevel = this.#thinkingLevel ?? 'medium';\n const effectiveLevel = getEffectiveThinkingLevel(resolvedBareModelId, requestedLevel);\n const reasoningEffort = THINKING_LEVEL_TO_REASONING_EFFORT[effectiveLevel];\n const middleware = createCodexMiddleware(reasoningEffort);\n const openai = createOpenAI({\n apiKey: 'oauth-gateway-placeholder',\n baseURL: `${this.#mastraGatewayBaseUrl}/v1`,\n headers: {\n [GATEWAY_AUTH_HEADER]: `Bearer ${args.apiKey}`,\n ...args.headers,\n },\n fetch: buildOpenAICodexOAuthFetch({ authStorage: this.#credentials, rewriteUrl: false }) as any,\n });\n\n return wrapLanguageModel({\n model: openai.responses(resolvedBareModelId),\n middleware: [middleware],\n }) as unknown as GatewayLanguageModel;\n }\n\n return this.#mastraGateway.resolveLanguageModel(args) as GatewayLanguageModel;\n }\n\n if (storedCred?.type === 'oauth') {\n const resolvedModelId = remapOpenAIModelForCodexOAuth(`openai/${args.modelId}`);\n return openaiCodexProvider(resolvedModelId.substring(OPENAI_PREFIX.length), {\n thinkingLevel: this.#thinkingLevel,\n headers: args.headers,\n authStorage: this.#credentials,\n }) as unknown as GatewayLanguageModel;\n }\n\n const apiKey = getOpenAIApiKey(this.#credentials);\n if (apiKey) {\n return openaiApiKeyProvider(args.modelId, apiKey, args.headers) as unknown as GatewayLanguageModel;\n }\n\n return undefined;\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAyCA,MAAa,gBAAgB;AAC7B,MAAa,wBAAwB;AACrC,MAAa,wBAAwB;AAErC,MAAM,4BAAoD;CACxD,WAAW;CACX,WAAW;CACX,WAAW;CACX,gBAAgB;CAChB,SAAS;AACX;AAqBA,MAAM,cAAc,IAAI,YAAY;AAEpC,SAAgB,oBAAoB;CAClC,YAAY,OAAO;AACrB;AAEA,SAAgB,yBAAyB,SAAyB;CAChE,OAAO,QAAQ,WAAA,SAAgC,IAAI,QAAQ,UAAU,CAA4B,IAAI;AACvG;AAEA,SAAS,0BAA0B,SAAyB;CAC1D,OAAO,QAAQ,QAAQ,aAAa,GAAG;AACzC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K,SAAS,QAAQ,KAAK,OAAO;CAIlE;AACF"}
1
+ {"version":3,"file":"mastracode-gateway.js","names":["#mastraGateway","#mastraGatewayBaseUrl","#mastraGatewayApiKey","#routeThroughMastraGateway","#thinkingLevel","#customProviders","#settingsPath","#credentials","#getCustomProviders","#resolveAnthropicModel","#resolveOpenAIModel"],"sources":["../../src/agents/mastracode-gateway.ts"],"sourcesContent":["import { createAnthropic } from '@ai-sdk/anthropic';\nimport { createOpenAI } from '@ai-sdk/openai';\nimport { createOpenAICompatible } from '@ai-sdk/openai-compatible';\nimport type { CustomAvailableModel, CustomModelCatalogProvider } from '@mastra/core/agent-controller';\nimport {\n GATEWAY_AUTH_HEADER,\n MastraGateway,\n MastraModelGateway,\n ModelRouterLanguageModel,\n PROVIDER_REGISTRY,\n} from '@mastra/core/llm';\nimport type {\n GatewayAuthRequest,\n GatewayAuthResult,\n GatewayLanguageModel,\n MastraModelGatewayInterface,\n ProviderConfig,\n} from '@mastra/core/llm';\nimport { wrapLanguageModel } from 'ai';\nimport { AuthStorage } from '../auth/storage.js';\nimport type { CredentialStore } from '../auth/types.js';\nimport { getCustomProviderId, loadSettings, MASTRA_GATEWAY_PROVIDER } from '../onboarding/settings.js';\nimport {\n buildAnthropicOAuthFetch,\n claudeCodeMiddleware,\n createAnthropicThinkingMiddleware,\n opencodeClaudeMaxProvider,\n promptCacheMiddleware,\n} from '../providers/claude-max.js';\nimport { getCopilotModelCatalog, githubCopilotProvider } from '../providers/github-copilot.js';\nimport { KIMI_CODING_MODELS, kimiCodingProvider } from '../providers/kimi-coding.js';\nimport {\n buildOpenAICodexOAuthFetch,\n createCodexMiddleware,\n getEffectiveThinkingLevel,\n openaiCodexProvider,\n THINKING_LEVEL_TO_REASONING_EFFORT,\n} from '../providers/openai-codex.js';\nimport type { ThinkingLevel } from '../providers/openai-codex.js';\nimport { xaiProvider } from '../providers/xai.js';\nimport { resolveCustomProviders } from './custom-provider-source.js';\n\nexport const OPENAI_PREFIX = 'openai/';\nexport const MASTRA_GATEWAY_PREFIX = 'mastra/';\nexport const MASTRACODE_GATEWAY_ID = 'mastracode';\n\nconst CODEX_OPENAI_MODEL_REMAPS: Record<string, string> = {\n 'gpt-5.3': 'gpt-5.3-codex',\n 'gpt-5.2': 'gpt-5.2-codex',\n 'gpt-5.1': 'gpt-5.1-codex',\n 'gpt-5.1-mini': 'gpt-5.1-codex-mini',\n 'gpt-5': 'gpt-5-codex',\n};\n\ntype ModelRequestHeaders = Record<string, string>;\n\nexport type MastraCodeCustomProvider = { name: string; url: string; apiKey?: string; models?: string[] };\n\nexport type MastraCodeGatewayOptions = {\n mastraGatewayBaseUrl: string;\n mastraGatewayApiKey?: string;\n routeThroughMastraGateway: boolean;\n thinkingLevel?: ThinkingLevel;\n customProviders?: MastraCodeCustomProvider[];\n settingsPath?: string;\n /**\n * Per-tenant credential source for this gateway instance. Defaults to the\n * server-global file-backed `AuthStorage`; deployed web passes the calling\n * tenant's store so model calls use the caller's own credentials.\n */\n credentialStore?: CredentialStore;\n};\n\nconst authStorage = new AuthStorage();\n\nexport function reloadAuthStorage() {\n authStorage.reload();\n}\n\nexport function stripMastraGatewayPrefix(modelId: string): string {\n return modelId.startsWith(MASTRA_GATEWAY_PREFIX) ? modelId.substring(MASTRA_GATEWAY_PREFIX.length) : modelId;\n}\n\nfunction normalizeAnthropicModelId(modelId: string): string {\n return modelId.replace(/\\.(?=\\d)/g, '-');\n}\n\nexport function remapOpenAIModelForCodexOAuth(modelId: string): string {\n const normalizedModelId = stripMastraGatewayPrefix(modelId);\n\n if (!normalizedModelId.startsWith(OPENAI_PREFIX)) {\n return modelId;\n }\n\n const openaiModelId = normalizedModelId.substring(OPENAI_PREFIX.length);\n\n if (openaiModelId.includes('-codex')) {\n return modelId;\n }\n\n const codexModelId = CODEX_OPENAI_MODEL_REMAPS[openaiModelId];\n if (!codexModelId) {\n return modelId;\n }\n\n const remappedModelId = `${OPENAI_PREFIX}${codexModelId}`;\n return modelId.startsWith(MASTRA_GATEWAY_PREFIX) ? `${MASTRA_GATEWAY_PREFIX}${remappedModelId}` : remappedModelId;\n}\n\n/**\n * Resolve the Anthropic API key.\n * Main slot → dedicated apikey: slot → env var.\n */\nexport function getAnthropicApiKey(credentials: CredentialStore = authStorage): string | undefined {\n const storedCred = credentials.get('anthropic');\n if (storedCred?.type === 'api_key' && storedCred.key.trim().length > 0) {\n return storedCred.key.trim();\n }\n const dedicatedKey = credentials.getStoredApiKey('anthropic')?.trim();\n if (dedicatedKey) return dedicatedKey;\n return credentials.allowEnvironmentFallback === false\n ? undefined\n : process.env.ANTHROPIC_API_KEY?.trim() || undefined;\n}\n\n/**\n * Resolve the OpenAI API key.\n * Main slot → dedicated apikey: slot → env var.\n */\nexport function getOpenAIApiKey(credentials: CredentialStore = authStorage): string | undefined {\n const storedCred = credentials.get('openai-codex');\n if (storedCred?.type === 'api_key' && storedCred.key.trim().length > 0) {\n return storedCred.key.trim();\n }\n const dedicatedKey = credentials.getStoredApiKey('openai-codex')?.trim();\n if (dedicatedKey) return dedicatedKey;\n return credentials.allowEnvironmentFallback === false ? undefined : process.env.OPENAI_API_KEY?.trim() || undefined;\n}\n\nfunction anthropicApiKeyProvider(\n modelId: string,\n apiKey: string,\n headers?: ModelRequestHeaders,\n thinkingLevel?: ThinkingLevel,\n) {\n const anthropic = createAnthropic({ apiKey, headers });\n const thinkingMiddleware = createAnthropicThinkingMiddleware(modelId, thinkingLevel);\n return wrapLanguageModel({\n model: anthropic(modelId),\n middleware: [promptCacheMiddleware, ...(thinkingMiddleware ? [thinkingMiddleware] : [])],\n });\n}\n\nfunction openaiApiKeyProvider(modelId: string, apiKey: string, headers?: ModelRequestHeaders) {\n const openai = createOpenAI({ apiKey, baseURL: process.env.OPENAI_BASE_URL, headers });\n return wrapLanguageModel({\n model: openai.responses(modelId),\n middleware: [],\n });\n}\n\nfunction getAuthProviderId(providerId: string): string {\n return providerId === 'openai' ? 'openai-codex' : providerId;\n}\n\nfunction getProviderAuthKey(providerId: string, credentials: CredentialStore = authStorage): string | undefined {\n const authProviderId = getAuthProviderId(providerId);\n const storedCred = credentials.get(authProviderId);\n if (storedCred?.type === 'api_key' && storedCred.key.trim().length > 0) {\n return storedCred.key.trim();\n }\n const dedicatedKey = credentials.getStoredApiKey(authProviderId)?.trim();\n if (dedicatedKey) return dedicatedKey;\n if (credentials.allowEnvironmentFallback === false) return undefined;\n return authProviderId === 'kimi-for-coding' ? process.env.KIMI_API_KEY?.trim() || undefined : undefined;\n}\n\nexport function resolveAuth(request: GatewayAuthRequest, mastraGatewayApiKey?: string): GatewayAuthResult | undefined {\n return MastraCodeGateway.resolveProviderAuth(request, mastraGatewayApiKey);\n}\n\nfunction getGatewayProviderKey(gatewayId: string, providerId: string): string {\n if (gatewayId === 'models.dev') return providerId;\n return providerId === gatewayId ? gatewayId : `${gatewayId}/${providerId}`;\n}\n\nfunction parseGatewayRouterId(\n routerId: string,\n gateway: MastraModelGatewayInterface,\n): { gatewayId: string; providerId: string; modelId: string } {\n const [firstPart = '', secondPart = '', ...restParts] = routerId.split('/');\n const gatewayId = gateway.id;\n\n if (firstPart === gatewayId && secondPart) {\n return {\n gatewayId,\n providerId: secondPart,\n modelId: restParts.join('/'),\n };\n }\n\n return {\n gatewayId,\n providerId: firstPart,\n modelId: [secondPart, ...restParts].filter(Boolean).join('/'),\n };\n}\n\nfunction hasResolvedAuth(auth: GatewayAuthResult | undefined): boolean {\n if (!auth) return false;\n if (auth.apiKey || auth.bearerToken) return true;\n return auth.headers ? Object.keys(auth.headers).length > 0 : false;\n}\n\nasync function resolveGatewayProviderAuth(\n gateway: MastraModelGatewayInterface,\n routerId: string,\n): Promise<GatewayAuthResult | undefined> {\n if (!gateway.resolveAuth) return undefined;\n\n const parsed = parseGatewayRouterId(routerId, gateway);\n try {\n const result = await gateway.resolveAuth({\n gatewayId: parsed.gatewayId,\n providerId: parsed.providerId,\n modelId: parsed.modelId,\n routerId,\n });\n return hasResolvedAuth(result) ? result : undefined;\n } catch {\n return undefined;\n }\n}\n\nasync function getMastraCodeProviderConfigs(\n gateway: MastraModelGatewayInterface,\n): Promise<Record<string, ProviderConfig>> {\n const providers: Record<string, ProviderConfig> = { ...(PROVIDER_REGISTRY as Record<string, ProviderConfig>) };\n\n try {\n const gatewayProviders = await gateway.fetchProviders();\n for (const [providerId, config] of Object.entries(gatewayProviders)) {\n providers[getGatewayProviderKey(gateway.id, providerId)] = {\n ...config,\n gateway: gateway.id,\n };\n }\n } catch (error) {\n console.warn(`Failed to load providers from gateway ${gateway.id}:`, error);\n }\n\n return providers;\n}\n\nfunction getApiKeyEnvVar(providerConfig: Pick<ProviderConfig, 'apiKeyEnvVar'> | undefined): string | undefined {\n const envVars = providerConfig?.apiKeyEnvVar;\n return Array.isArray(envVars) ? envVars[0] : envVars;\n}\n\nexport class MastraCodeGateway extends MastraModelGateway {\n readonly id = MASTRACODE_GATEWAY_ID;\n readonly name = 'MastraCode Gateway';\n\n readonly #mastraGateway: MastraGateway;\n readonly #mastraGatewayBaseUrl: string;\n readonly #mastraGatewayApiKey?: string;\n readonly #routeThroughMastraGateway: boolean;\n readonly #thinkingLevel?: ThinkingLevel;\n readonly #customProviders?: MastraCodeCustomProvider[];\n readonly #settingsPath?: string;\n readonly #credentials: CredentialStore;\n\n constructor({\n mastraGatewayBaseUrl,\n mastraGatewayApiKey,\n routeThroughMastraGateway,\n thinkingLevel,\n customProviders,\n settingsPath,\n credentialStore,\n }: MastraCodeGatewayOptions) {\n super();\n this.#mastraGateway = new MastraGateway({ baseUrl: mastraGatewayBaseUrl });\n this.#mastraGatewayBaseUrl = mastraGatewayBaseUrl;\n this.#mastraGatewayApiKey = mastraGatewayApiKey;\n this.#routeThroughMastraGateway = routeThroughMastraGateway;\n this.#thinkingLevel = thinkingLevel;\n this.#customProviders = customProviders;\n this.#settingsPath = settingsPath;\n this.#credentials = credentialStore ?? authStorage;\n }\n\n static getMastraGatewayApiKey(): string | undefined {\n return authStorage.getStoredApiKey(MASTRA_GATEWAY_PROVIDER) ?? process.env['MASTRA_GATEWAY_API_KEY'];\n }\n\n /** @deprecated Renamed to {@link MastraCodeGateway.getMastraGatewayApiKey}. */\n static getMemoryGatewayApiKey(): string | undefined {\n return MastraCodeGateway.getMastraGatewayApiKey();\n }\n\n /**\n * Claim an unprefixed model id (e.g. a bare `anthropic/...`) when this gateway\n * can authenticate it via OAuth or a stored/env credential. This lets the\n * shared gateway router select MastraCode for auth resolution, so the status\n * bar and `/api-keys` reflect OAuth logins instead of only checking env vars.\n */\n handlesModel(modelId: string): boolean {\n const parsed = parseGatewayRouterId(modelId, this);\n if (!parsed.providerId || !parsed.modelId) return false;\n if (this.#routeThroughMastraGateway && this.#mastraGatewayApiKey) return true;\n const customProvider = this.#getCustomProviders().find(\n provider => parsed.providerId === getCustomProviderId(provider.name),\n );\n if (customProvider?.apiKey) return true;\n return hasResolvedAuth(\n MastraCodeGateway.resolveProviderAuth(\n {\n gatewayId: this.id,\n providerId: parsed.providerId,\n modelId: parsed.modelId,\n routerId: modelId,\n },\n undefined,\n this.#credentials,\n ),\n );\n }\n\n static resolveProviderAuth(\n request: GatewayAuthRequest,\n mastraGatewayApiKey?: string,\n credentials: CredentialStore = authStorage,\n ): GatewayAuthResult | undefined {\n if (request.gatewayId === 'mastra' && mastraGatewayApiKey) {\n return { apiKey: mastraGatewayApiKey, source: 'gateway' };\n }\n\n const authProviderId = getAuthProviderId(request.providerId);\n const storedCred = credentials.get(authProviderId);\n if (storedCred?.type === 'oauth') {\n return { bearerToken: 'oauth', source: 'gateway' };\n }\n\n const apiKey = getProviderAuthKey(request.providerId, credentials);\n return apiKey ? { apiKey, source: 'gateway' } : undefined;\n }\n\n static createModelCatalogProvider(gateway: MastraModelGatewayInterface): CustomModelCatalogProvider {\n return async () => {\n const registry = await getMastraCodeProviderConfigs(gateway);\n const models: CustomAvailableModel[] = [];\n\n for (const [provider, providerConfig] of Object.entries(registry)) {\n const apiKeyEnvVar = getApiKeyEnvVar(providerConfig);\n const hasEnvKey = apiKeyEnvVar ? Boolean(process.env[apiKeyEnvVar]) : false;\n const modelNames = providerConfig.models;\n if (!Array.isArray(modelNames)) continue;\n\n const gatewayAuth = modelNames[0]\n ? await resolveGatewayProviderAuth(gateway, `${provider}/${modelNames[0]}`)\n : undefined;\n\n for (const modelName of modelNames) {\n const id = `${provider}/${modelName}`;\n models.push({\n id,\n provider,\n modelName,\n hasApiKey: hasEnvKey || Boolean(gatewayAuth),\n apiKeyEnvVar: apiKeyEnvVar || undefined,\n });\n }\n }\n\n return models;\n };\n }\n\n createModelCatalogProvider(): CustomModelCatalogProvider {\n return MastraCodeGateway.createModelCatalogProvider(this);\n }\n\n #getCustomProviders(): MastraCodeCustomProvider[] {\n // Explicit constructor list wins; then a registered source (deployed web,\n // DB-backed — authoritative, so settings.json is never consulted); then\n // the local file-backed settings.\n return this.#customProviders ?? resolveCustomProviders() ?? loadSettings(this.#settingsPath).customProviders;\n }\n\n async fetchProviders(): Promise<Record<string, ProviderConfig>> {\n const providers: Record<string, ProviderConfig> = {};\n for (const provider of this.#getCustomProviders()) {\n const models = provider.models ?? [];\n if (!models.length) continue;\n providers[getCustomProviderId(provider.name)] = {\n name: provider.name,\n url: provider.url,\n apiKeyEnvVar: '',\n apiKeyHeader: 'Authorization',\n gateway: this.id,\n models,\n };\n }\n\n providers['kimi-for-coding'] = {\n name: 'Kimi For Coding',\n apiKeyEnvVar: 'KIMI_API_KEY',\n apiKeyHeader: 'Authorization',\n gateway: this.id,\n models: [...KIMI_CODING_MODELS],\n };\n\n try {\n const copilotModels = await getCopilotModelCatalog({ authStorage });\n providers['github-copilot'] = {\n name: 'GitHub Copilot',\n apiKeyEnvVar: '',\n apiKeyHeader: 'Authorization',\n gateway: this.id,\n models: copilotModels.map(model => model.id),\n };\n } catch (error) {\n console.warn('Failed to load GitHub Copilot model catalog:', error);\n }\n\n return providers;\n }\n\n buildUrl(modelId: string): string | undefined | Promise<string | undefined> {\n return this.#routeThroughMastraGateway ? this.#mastraGateway.buildUrl(modelId) : modelId;\n }\n\n async getApiKey(modelId: string): Promise<string> {\n const providerId = stripMastraGatewayPrefix(modelId).split('/', 1)[0];\n if (this.#routeThroughMastraGateway) return this.#mastraGatewayApiKey ?? '';\n return providerId ? (getProviderAuthKey(providerId, this.#credentials) ?? '') : '';\n }\n\n resolveAuth(request: GatewayAuthRequest): GatewayAuthResult | undefined {\n if (this.#routeThroughMastraGateway && this.#mastraGatewayApiKey) {\n return { apiKey: this.#mastraGatewayApiKey, source: 'gateway' };\n }\n\n const customProvider = this.#getCustomProviders().find(\n provider => request.providerId === getCustomProviderId(provider.name),\n );\n if (customProvider?.apiKey) {\n return { apiKey: customProvider.apiKey, source: 'gateway' };\n }\n\n return MastraCodeGateway.resolveProviderAuth(request, undefined, this.#credentials);\n }\n\n resolveLanguageModel(args: {\n modelId: string;\n providerId: string;\n apiKey: string;\n headers?: Record<string, string>;\n transport?: any;\n responsesWebSocket?: any;\n }): GatewayLanguageModel {\n const customProvider = this.#getCustomProviders().find(\n provider => args.providerId === getCustomProviderId(provider.name),\n );\n if (customProvider) {\n const provider = createOpenAICompatible({\n name: args.providerId,\n baseURL: customProvider.url,\n apiKey: args.apiKey,\n headers: args.headers,\n });\n return provider.chatModel(args.modelId) as unknown as GatewayLanguageModel;\n }\n\n if (args.providerId === 'github-copilot') {\n return githubCopilotProvider(args.modelId, {\n headers: args.headers,\n authStorage: this.#credentials,\n }) as unknown as GatewayLanguageModel;\n }\n\n if (args.providerId === 'moonshotai') {\n // Prefer the gateway-resolved key (stored credentials), then the canonical\n // registry env var. Keep the legacy typo name as a fallback for anyone who\n // set it because of the previous error message.\n const apiKey =\n args.apiKey?.trim() || process.env.MOONSHOT_API_KEY?.trim() || process.env.MOONSHOT_AI_API_KEY?.trim();\n if (!apiKey) {\n throw new Error('Need MOONSHOT_API_KEY');\n }\n return createAnthropic({\n apiKey,\n baseURL: 'https://api.moonshot.ai/anthropic/v1',\n name: 'moonshotai.anthropicv1',\n headers: args.headers,\n })(args.modelId) as unknown as GatewayLanguageModel;\n }\n\n if (args.providerId === 'anthropic') {\n return this.#resolveAnthropicModel(args);\n }\n\n if (args.providerId === 'openai') {\n const openaiModel = this.#resolveOpenAIModel(args);\n if (openaiModel) return openaiModel;\n }\n\n if (args.providerId === 'xai' && this.#credentials.get('xai')?.type === 'oauth') {\n return xaiProvider(args.modelId, {\n headers: args.headers,\n authStorage: this.#credentials,\n }) as unknown as GatewayLanguageModel;\n }\n\n if (this.#routeThroughMastraGateway) {\n return this.#mastraGateway.resolveLanguageModel(args) as GatewayLanguageModel;\n }\n\n if (args.providerId === 'kimi-for-coding') {\n return kimiCodingProvider(args.modelId, {\n apiKey: args.apiKey,\n headers: args.headers,\n credentialStore: this.#credentials,\n }) as unknown as GatewayLanguageModel;\n }\n\n return new ModelRouterLanguageModel({\n id: `${args.providerId}/${args.modelId}` as `${string}/${string}`,\n apiKey: args.apiKey,\n headers: args.headers,\n }) as unknown as GatewayLanguageModel;\n }\n\n #resolveAnthropicModel(args: {\n modelId: string;\n providerId: string;\n apiKey: string;\n headers?: Record<string, string>;\n transport?: any;\n responsesWebSocket?: any;\n }): GatewayLanguageModel {\n const bareModelId = normalizeAnthropicModelId(args.modelId);\n const storedCred = this.#credentials.get('anthropic');\n const thinkingMiddleware = createAnthropicThinkingMiddleware(bareModelId, this.#thinkingLevel);\n\n if (this.#routeThroughMastraGateway) {\n if (storedCred?.type === 'oauth') {\n const anthropic = createAnthropic({\n apiKey: 'oauth-gateway-placeholder',\n baseURL: `${this.#mastraGatewayBaseUrl}/v1`,\n headers: {\n [GATEWAY_AUTH_HEADER]: `Bearer ${args.apiKey}`,\n ...args.headers,\n },\n fetch: buildAnthropicOAuthFetch({ authStorage: this.#credentials }) as any,\n });\n\n return wrapLanguageModel({\n model: anthropic(bareModelId),\n middleware: [\n claudeCodeMiddleware,\n promptCacheMiddleware,\n ...(thinkingMiddleware ? [thinkingMiddleware] : []),\n ],\n }) as unknown as GatewayLanguageModel;\n }\n\n const gatewayModel = this.#mastraGateway.resolveLanguageModel({\n ...args,\n modelId: bareModelId,\n }) as GatewayLanguageModel;\n if (!thinkingMiddleware) return gatewayModel;\n return wrapLanguageModel({\n model: gatewayModel as any,\n middleware: [thinkingMiddleware],\n }) as unknown as GatewayLanguageModel;\n }\n\n if (storedCred?.type === 'oauth') {\n return opencodeClaudeMaxProvider(bareModelId, {\n headers: args.headers,\n authStorage: this.#credentials,\n thinkingLevel: this.#thinkingLevel,\n }) as unknown as GatewayLanguageModel;\n }\n\n if (storedCred?.type === 'api_key' && storedCred.key.trim().length > 0) {\n return anthropicApiKeyProvider(\n bareModelId,\n storedCred.key.trim(),\n args.headers,\n this.#thinkingLevel,\n ) as unknown as GatewayLanguageModel;\n }\n\n const apiKey = getAnthropicApiKey(this.#credentials);\n if (apiKey) {\n return anthropicApiKeyProvider(\n bareModelId,\n apiKey,\n args.headers,\n this.#thinkingLevel,\n ) as unknown as GatewayLanguageModel;\n }\n\n // No stored credentials: use the OAuth-backed provider so the first request can trigger login.\n return opencodeClaudeMaxProvider(bareModelId, {\n headers: args.headers,\n authStorage: this.#credentials,\n thinkingLevel: this.#thinkingLevel,\n }) as unknown as GatewayLanguageModel;\n }\n\n #resolveOpenAIModel(args: {\n modelId: string;\n providerId: string;\n apiKey: string;\n headers?: Record<string, string>;\n transport?: any;\n responsesWebSocket?: any;\n }): GatewayLanguageModel | undefined {\n const storedCred = this.#credentials.get('openai-codex');\n\n if (this.#routeThroughMastraGateway) {\n if (storedCred?.type === 'oauth') {\n const resolvedModelId = remapOpenAIModelForCodexOAuth(`openai/${args.modelId}`);\n const resolvedBareModelId = resolvedModelId.substring(OPENAI_PREFIX.length);\n const requestedLevel: ThinkingLevel = this.#thinkingLevel ?? 'medium';\n const effectiveLevel = getEffectiveThinkingLevel(resolvedBareModelId, requestedLevel);\n const reasoningEffort = THINKING_LEVEL_TO_REASONING_EFFORT[effectiveLevel];\n const middleware = createCodexMiddleware(reasoningEffort);\n const openai = createOpenAI({\n apiKey: 'oauth-gateway-placeholder',\n baseURL: `${this.#mastraGatewayBaseUrl}/v1`,\n headers: {\n [GATEWAY_AUTH_HEADER]: `Bearer ${args.apiKey}`,\n ...args.headers,\n },\n fetch: buildOpenAICodexOAuthFetch({ authStorage: this.#credentials, rewriteUrl: false }) as any,\n });\n\n return wrapLanguageModel({\n model: openai.responses(resolvedBareModelId),\n middleware: [middleware],\n }) as unknown as GatewayLanguageModel;\n }\n\n return this.#mastraGateway.resolveLanguageModel(args) as GatewayLanguageModel;\n }\n\n if (storedCred?.type === 'oauth') {\n const resolvedModelId = remapOpenAIModelForCodexOAuth(`openai/${args.modelId}`);\n return openaiCodexProvider(resolvedModelId.substring(OPENAI_PREFIX.length), {\n thinkingLevel: this.#thinkingLevel,\n headers: args.headers,\n authStorage: this.#credentials,\n }) as unknown as GatewayLanguageModel;\n }\n\n const apiKey = getOpenAIApiKey(this.#credentials);\n if (apiKey) {\n return openaiApiKeyProvider(args.modelId, apiKey, args.headers) as unknown as GatewayLanguageModel;\n }\n\n return undefined;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AA0CA,MAAa,gBAAgB;AAC7B,MAAa,wBAAwB;AACrC,MAAa,wBAAwB;AAErC,MAAM,4BAAoD;CACxD,WAAW;CACX,WAAW;CACX,WAAW;CACX,gBAAgB;CAChB,SAAS;AACX;AAqBA,MAAM,cAAc,IAAI,YAAY;AAEpC,SAAgB,oBAAoB;CAClC,YAAY,OAAO;AACrB;AAEA,SAAgB,yBAAyB,SAAyB;CAChE,OAAO,QAAQ,WAAA,SAAgC,IAAI,QAAQ,UAAU,CAA4B,IAAI;AACvG;AAEA,SAAS,0BAA0B,SAAyB;CAC1D,OAAO,QAAQ,QAAQ,aAAa,GAAG;AACzC;AAEA,SAAgB,8BAA8B,SAAyB;CACrE,MAAM,oBAAoB,yBAAyB,OAAO;CAE1D,IAAI,CAAC,kBAAkB,WAAA,SAAwB,GAC7C,OAAO;CAGT,MAAM,gBAAgB,kBAAkB,UAAU,CAAoB;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AI,YAAY,SAAS,SAEvB,OAAO,oBADiB,8BAA8B,UAAU,KAAK,SAC5B,CAAC,CAAC,UAAU,CAAoB,GAAG;GAC1E,eAAe,KAAKI;GACpB,SAAS,KAAK;GACd,aAAa,KAAKG;EACpB,CAAC;EAGH,MAAM,SAAS,gBAAgB,KAAKA,YAAY;EAChD,IAAI,QACF,OAAO,qBAAqB,KAAK,SAAS,QAAQ,KAAK,OAAO;CAIlE;AACF"}
@@ -2,6 +2,12 @@ import type { RequestContext } from '@mastra/core/request-context';
2
2
  import type { MastraCompositeStore } from '@mastra/core/storage';
3
3
  import type { MastraVector } from '@mastra/core/vector';
4
4
  import { Memory } from '@mastra/memory';
5
+ /**
6
+ * The organization rung local (TUI/studio) knowledge is captured under. A fixed
7
+ * literal on purpose: deriving it from a hostname or path would fragment local
8
+ * knowledge per checkout into scopes nothing ever reads.
9
+ */
10
+ export declare const LOCAL_KNOWLEDGE_ORG_ID = "local";
5
11
  /**
6
12
  * Dynamic memory factory function.
7
13
  * Reads OM thresholds from controller state via requestContext.
@@ -1 +1 @@
1
- {"version":3,"file":"memory.d.ts","sourceRoot":"","sources":["../../src/agents/memory.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AACnE,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,sBAAsB,CAAC;AACjE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAExD,OAAO,EAAE,MAAM,EAAgB,MAAM,gBAAgB,CAAC;AAkEtD;;;;GAIG;AACH,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,oBAAoB,EAAE,MAAM,CAAC,EAAE,YAAY,IAM3E,oBAAoB;IAAE,cAAc,EAAE,cAAc,CAAA;CAAE,YAyG/D"}
1
+ {"version":3,"file":"memory.d.ts","sourceRoot":"","sources":["../../src/agents/memory.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AACnE,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,sBAAsB,CAAC;AACjE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAExD,OAAO,EAAE,MAAM,EAAgB,MAAM,gBAAgB,CAAC;AAkEtD;;;;GAIG;AACH,eAAO,MAAM,sBAAsB,UAAU,CAAC;AA6B9C;;;;GAIG;AACH,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,oBAAoB,EAAE,MAAM,CAAC,EAAE,YAAY,IAM3E,oBAAoB;IAAE,cAAc,EAAE,cAAc,CAAA;CAAE,YAmH/D"}
@@ -55,6 +55,24 @@ Don't say "Agent did x", say "did x". It will be assumed the agent did what was
55
55
 
56
56
  Drop caveman for: security warnings, irreversible action confirmations, multi-step sequences where fragment order risks misread, user asks to clarify or repeats question, and anything that requires remembering verbatim content. Resume caveman after clear part done`;
57
57
  /**
58
+ * The organization rung local (TUI/studio) knowledge is captured under. A fixed
59
+ * literal on purpose: deriving it from a hostname or path would fragment local
60
+ * knowledge per checkout into scopes nothing ever reads.
61
+ */
62
+ const LOCAL_KNOWLEDGE_ORG_ID = "local";
63
+ const REPORTED_ORG_UNRESOLVED_LIMIT = 500;
64
+ const reportedOrgUnresolved = /* @__PURE__ */ new Set();
65
+ function reportOrgUnresolved(controller, factoryProjectId) {
66
+ const sessionId = controller?.session?.id;
67
+ if (sessionId) {
68
+ if (reportedOrgUnresolved.has(sessionId)) return;
69
+ if (reportedOrgUnresolved.size >= REPORTED_ORG_UNRESOLVED_LIMIT) reportedOrgUnresolved.delete(reportedOrgUnresolved.values().next().value);
70
+ reportedOrgUnresolved.add(sessionId);
71
+ }
72
+ const session = controller?.session;
73
+ console.error(`[Subconscious] Knowledge capture disabled: no organization resolved for session ${session?.id ?? "unknown"} (project ${factoryProjectId ?? "none"}). Knowledge is not written rather than written where it cannot be read.`);
74
+ }
75
+ /**
58
76
  * Dynamic memory factory function.
59
77
  * Reads OM thresholds from controller state via requestContext.
60
78
  * Model functions also read from requestContext (no mutable bridge needed).
@@ -68,20 +86,25 @@ function getDynamicMemory(storage, vector) {
68
86
  const subconsciousEnabled = Boolean(vector) && process.env.MASTRACODE_EXPERIMENTAL_SUBCONSCIOUS === "1";
69
87
  const factoryProjectId = state?.factoryProjectId;
70
88
  const isFactory = typeof factoryProjectId === "string" && factoryProjectId.trim().length > 0;
89
+ let orgUnresolvedRefusal = false;
71
90
  if (subconsciousEnabled) {
72
91
  const factoryOrgId = state?.factoryOrgId;
73
- const ownerId = controller?.session.ownerId;
92
+ const factoryOwned = isFactory || state?.factoryOrgUnresolved === true;
74
93
  if (typeof factoryOrgId === "string" && factoryOrgId.trim()) requestContext.set("organizationId", factoryOrgId);
75
- else if (ownerId) requestContext.set("organizationId", ownerId);
94
+ else if (factoryOwned) {
95
+ orgUnresolvedRefusal = true;
96
+ reportOrgUnresolved(controller, factoryProjectId);
97
+ } else requestContext.set("organizationId", LOCAL_KNOWLEDGE_ORG_ID);
76
98
  if (isFactory) requestContext.set("knowledgeResourceId", factoryProjectId);
77
99
  }
100
+ const captureEnabled = subconsciousEnabled && !orgUnresolvedRefusal;
78
101
  const omScope = state?.omScope ?? getOmScope(state?.projectPath);
79
102
  const obsThreshold = state?.observationThreshold ?? 3e4;
80
103
  const refThreshold = state?.reflectionThreshold ?? 4e4;
81
104
  const caveman = state?.cavemanObservations ?? false;
82
105
  const observerPreviousObservationTokens = 1e3;
83
106
  const observeAttachments = state?.observeAttachments;
84
- const cacheKey = `${obsThreshold}:${refThreshold}:${omScope}:${observerPreviousObservationTokens}:${caveman ? 1 : 0}:${observeAttachments}:${isFactory ? 1 : 0}:${subconsciousEnabled ? 1 : 0}`;
107
+ const cacheKey = `${obsThreshold}:${refThreshold}:${omScope}:${observerPreviousObservationTokens}:${caveman ? 1 : 0}:${observeAttachments}:${isFactory ? 1 : 0}:${captureEnabled ? 1 : 0}`;
85
108
  if (cachedMemory && cachedMemoryKey === cacheKey) return cachedMemory;
86
109
  const isResourceScope = omScope === "resource";
87
110
  const observerInstruction = caveman ? `${DYNAMIC_AGENTS_MD_INSTRUCTION}\n\n${CAVEMAN_OM_INSTRUCTION}` : DYNAMIC_AGENTS_MD_INSTRUCTION;
@@ -96,7 +119,7 @@ function getDynamicMemory(storage, vector) {
96
119
  enabled: true,
97
120
  temporalMarkers: true,
98
121
  retrieval: vector ? { vector: true } : true,
99
- experimental_subconscious: subconsciousEnabled ? new Subconscious({
122
+ experimental_subconscious: captureEnabled ? new Subconscious({
100
123
  defaultScope: "resource",
101
124
  maxScope: "resource",
102
125
  pins: isFactory ? { capturePinning: true } : true,
@@ -132,6 +155,6 @@ function getDynamicMemory(storage, vector) {
132
155
  };
133
156
  }
134
157
  //#endregion
135
- export { getDynamicMemory };
158
+ export { LOCAL_KNOWLEDGE_ORG_ID, getDynamicMemory };
136
159
 
137
160
  //# sourceMappingURL=memory.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"memory.js","names":[],"sources":["../../src/agents/memory.ts"],"sourcesContent":["import type { AgentControllerRequestContext } from '@mastra/core/agent-controller';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport type { MastraCompositeStore } from '@mastra/core/storage';\nimport type { MastraVector } from '@mastra/core/vector';\nimport { fastembed } from '@mastra/fastembed';\nimport { Memory, Subconscious } from '@mastra/memory';\nimport { DEFAULT_OM_MODEL_ID, DEFAULT_OBS_THRESHOLD, DEFAULT_REF_THRESHOLD } from '../constants.js';\nimport type { MastraCodeState } from '../schema.js';\nimport { getOmScope } from '../utils/project.js';\nimport { resolveModel } from './model.js';\n\n/**\n * Read controller state from requestContext.\n * Used by both the memory factory and the OM model functions.\n */\nfunction getAgentControllerState(requestContext: RequestContext): MastraCodeState | undefined {\n const ctx = requestContext.get('controller') as AgentControllerRequestContext<MastraCodeState> | undefined;\n return ctx?.getState() as MastraCodeState | undefined;\n}\n\n/**\n * Observer model function — reads the current observer model ID from\n * controller state via requestContext (now propagated by OM's agent.generate).\n */\nfunction getObserverModel({ requestContext }: { requestContext: RequestContext }) {\n const state = getAgentControllerState(requestContext);\n return resolveModel(state?.observerModelId ?? DEFAULT_OM_MODEL_ID, {\n remapForCodexOAuth: true,\n requestContext,\n });\n}\n\n/**\n * Reflector model function — reads the current reflector model ID from\n * controller state via requestContext (now propagated by OM's agent.generate).\n */\nfunction getReflectorModel({ requestContext }: { requestContext: RequestContext }) {\n const state = getAgentControllerState(requestContext);\n return resolveModel(state?.reflectorModelId ?? DEFAULT_OM_MODEL_ID, {\n remapForCodexOAuth: true,\n requestContext,\n });\n}\n\nconst DYNAMIC_AGENTS_MD_INSTRUCTION =\n 'Messages wrapped in <system-reminder type=\"dynamic-agents-md\" ...>...</system-reminder> are ephemeral project-context instructions injected from files on disk. Do NOT observe or extract information from these messages — they are reloaded automatically when needed and should not be stored in memory.';\n\n// Derived from https://github.com/JuliusBrussee/caveman and adapted for OM use with fixed full-level compression.\nconst CAVEMAN_OM_INSTRUCTION = `Respond terse like smart caveman. All technical substance stay. Only fluff die.\n\nUse full caveman compression style.\n\nDrop: articles (a/an/the), filler (just/really/basically/actually/simply), pleasantries (sure/certainly/of course/happy to), hedging. Fragments OK. Short synonyms (big not extensive, fix not \"implement a solution for\"). Technical terms exact. Code blocks unchanged. Errors quoted exact. Leave out the words \"agent\" and \"assistant\" at the start of each observation line, it is assumed each line is referring to the assistant unless it specifically says it was about the user. Leave out parenthesis and other text characters like * that would not contribute to understanding the observations.\n\nPattern: \\`[thing] [action] [reason]. [next step]\\`\n\nNot: \"Sure! I'd be happy to help you with that. The issue you're experiencing is likely caused by...\"\nYes: \"Bug in auth middleware. Token expiry check use < not <=. Fix:\"\n\nExample 1\nšŸ”“ 14:31 user asks why React component rerenders\n🟔 14:32 saw inline object prop create new ref each render, cause rerender\nāœ… 14:34 fixed render issue by wrap object in useMemo\n\nExample 2\n🟔 15:10 explained pool reuse DB connections, skip repeat handshake overhead\n\nDon't say \"Agent did x\", say \"did x\". It will be assumed the agent did what was observed. The who should only be specified for the user or other third parties: \"user asked x\"\n\nDrop caveman for: security warnings, irreversible action confirmations, multi-step sequences where fragment order risks misread, user asks to clarify or repeats question, and anything that requires remembering verbatim content. Resume caveman after clear part done`;\n\n/**\n * Dynamic memory factory function.\n * Reads OM thresholds from controller state via requestContext.\n * Model functions also read from requestContext (no mutable bridge needed).\n */\nexport function getDynamicMemory(storage: MastraCompositeStore, vector?: MastraVector) {\n // Cache is scoped per storage instance (per getDynamicMemory call) so a\n // Memory bound to one storage is never reused after storage changes.\n let cachedMemory: Memory | null = null;\n let cachedMemoryKey: string | null = null;\n\n return ({ requestContext }: { requestContext: RequestContext }) => {\n const controller = requestContext.get('controller') as AgentControllerRequestContext<MastraCodeState> | undefined;\n const state = controller?.getState() as MastraCodeState | undefined;\n const subconsciousEnabled = Boolean(vector) && process.env.MASTRACODE_EXPERIMENTAL_SUBCONSCIOUS === '1';\n const factoryProjectId = state?.factoryProjectId;\n const isFactory = typeof factoryProjectId === 'string' && factoryProjectId.trim().length > 0;\n\n if (subconsciousEnabled) {\n // Factory seeds the authoritative org id into session state; prefer it.\n // The session owner is a USER id — mapping it into organizationId is only\n // the legacy fallback for clients (TUI/studio) that never set factoryOrgId.\n const factoryOrgId = state?.factoryOrgId;\n const ownerId = controller?.session.ownerId;\n if (typeof factoryOrgId === 'string' && factoryOrgId.trim()) {\n requestContext.set('organizationId', factoryOrgId);\n } else if (ownerId) {\n requestContext.set('organizationId', ownerId);\n }\n // Factory runs share one knowledge graph per project: anchor the\n // subconscious knowledge scope's resource rung on the project id.\n if (isFactory) {\n requestContext.set('knowledgeResourceId', factoryProjectId);\n }\n }\n\n const omScope = state?.omScope ?? getOmScope(state?.projectPath);\n\n const obsThreshold = state?.observationThreshold ?? DEFAULT_OBS_THRESHOLD;\n const refThreshold = state?.reflectionThreshold ?? DEFAULT_REF_THRESHOLD;\n const caveman = state?.cavemanObservations ?? false;\n\n const observerPreviousObservationTokens = 1000;\n const observeAttachments = state?.observeAttachments;\n // Factory sessions get a factory-only Subconscious config, so the cache key\n // carries a factory presence bit to keep the two configs from cross-serving.\n const cacheKey = `${obsThreshold}:${refThreshold}:${omScope}:${observerPreviousObservationTokens}:${caveman ? 1 : 0}:${observeAttachments}:${isFactory ? 1 : 0}:${subconsciousEnabled ? 1 : 0}`;\n if (cachedMemory && cachedMemoryKey === cacheKey) {\n return cachedMemory;\n }\n\n // Async buffering is not supported with resource scope — disable it\n const isResourceScope = omScope === 'resource';\n\n const observerInstruction = caveman\n ? `${DYNAMIC_AGENTS_MD_INSTRUCTION}\\n\\n${CAVEMAN_OM_INSTRUCTION}`\n : DYNAMIC_AGENTS_MD_INSTRUCTION;\n const reflectionInstruction = caveman ? CAVEMAN_OM_INSTRUCTION : undefined;\n\n cachedMemory = new Memory({\n storage,\n vector: vector || false,\n embedder: vector ? fastembed.small : undefined,\n options: {\n // The factory sidebar shows a session the moment it exists, so it needs a\n // name on the first turn. The TUI names its threads from OM's `threadTitle`\n // as they grow and would only pay for an extra call here.\n ...(isFactory ? { generateTitle: { model: getObserverModel } } : {}),\n observationalMemory: {\n enabled: true,\n temporalMarkers: true,\n retrieval: vector ? { vector: true } : true,\n experimental_subconscious: subconsciousEnabled\n ? new Subconscious({\n defaultScope: 'resource',\n maxScope: 'resource',\n // Capture-time pinning is a factory-only opinion; every other\n // client keeps plain curator-maintained pins.\n pins: isFactory ? { capturePinning: true } : true,\n // Factory sessions run the curator every 3 observation runs;\n // other clients leave the cadence trigger dormant.\n ...(isFactory ? { curationCadence: 3 } : {}),\n // Real curation over a factory worklist needs tool room: the\n // default 5-step budget exhausts mid-batch and the curator never\n // reaches its cursor acknowledgment (observed live 2026-08-13).\n ...(isFactory ? { maxSteps: 25 } : {}),\n })\n : undefined,\n scope: omScope,\n activateAfterIdle: 'auto',\n activateOnProviderChange: true,\n observation: {\n bufferTokens: isResourceScope ? false : 1 / 5,\n bufferActivation: isResourceScope ? undefined : 2000,\n model: getObserverModel,\n messageTokens: obsThreshold,\n blockAfter: 2,\n previousObserverTokens: observerPreviousObservationTokens,\n threadTitle: true,\n instruction: observerInstruction,\n observeAttachments,\n },\n reflection: {\n bufferActivation: isResourceScope ? undefined : 1 / 2,\n blockAfter: 1.1,\n model: getReflectorModel,\n observationTokens: refThreshold,\n instruction: reflectionInstruction,\n },\n },\n },\n });\n cachedMemoryKey = cacheKey;\n\n return cachedMemory;\n };\n}\n"],"mappings":";;;;;;;;;;AAeA,SAAS,wBAAwB,gBAA6D;CAE5F,OADY,eAAe,IAAI,YACtB,CAAC,EAAE,SAAS;AACvB;;;;;AAMA,SAAS,iBAAiB,EAAE,kBAAsD;CAEhF,OAAO,aADO,wBAAwB,cACd,CAAC,EAAE,mBAAmB,qBAAqB;EACjE,oBAAoB;EACpB;CACF,CAAC;AACH;;;;;AAMA,SAAS,kBAAkB,EAAE,kBAAsD;CAEjF,OAAO,aADO,wBAAwB,cACd,CAAC,EAAE,oBAAoB,qBAAqB;EAClE,oBAAoB;EACpB;CACF,CAAC;AACH;AAEA,MAAM,gCACJ;AAGF,MAAM,yBAAyB;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4B/B,SAAgB,iBAAiB,SAA+B,QAAuB;CAGrF,IAAI,eAA8B;CAClC,IAAI,kBAAiC;CAErC,QAAQ,EAAE,qBAAyD;EACjE,MAAM,aAAa,eAAe,IAAI,YAAY;EAClD,MAAM,QAAQ,YAAY,SAAS;EACnC,MAAM,sBAAsB,QAAQ,MAAM,KAAK,QAAQ,IAAI,yCAAyC;EACpG,MAAM,mBAAmB,OAAO;EAChC,MAAM,YAAY,OAAO,qBAAqB,YAAY,iBAAiB,KAAK,CAAC,CAAC,SAAS;EAE3F,IAAI,qBAAqB;GAIvB,MAAM,eAAe,OAAO;GAC5B,MAAM,UAAU,YAAY,QAAQ;GACpC,IAAI,OAAO,iBAAiB,YAAY,aAAa,KAAK,GACxD,eAAe,IAAI,kBAAkB,YAAY;QAC5C,IAAI,SACT,eAAe,IAAI,kBAAkB,OAAO;GAI9C,IAAI,WACF,eAA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Y;MACV,kBAAkB,kBAAkB,KAAA,IAAY,IAAI;MACpD,YAAY;MACZ,OAAO;MACP,mBAAmB;MACnB,aAAa;KACf;IACF;GACF;EACF,CAAC;EACD,kBAAkB;EAElB,OAAO;CACT;AACF"}
1
+ {"version":3,"file":"memory.js","names":[],"sources":["../../src/agents/memory.ts"],"sourcesContent":["import type { AgentControllerRequestContext } from '@mastra/core/agent-controller';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport type { MastraCompositeStore } from '@mastra/core/storage';\nimport type { MastraVector } from '@mastra/core/vector';\nimport { fastembed } from '@mastra/fastembed';\nimport { Memory, Subconscious } from '@mastra/memory';\nimport { DEFAULT_OM_MODEL_ID, DEFAULT_OBS_THRESHOLD, DEFAULT_REF_THRESHOLD } from '../constants.js';\nimport type { MastraCodeState } from '../schema.js';\nimport { getOmScope } from '../utils/project.js';\nimport { resolveModel } from './model.js';\n\n/**\n * Read controller state from requestContext.\n * Used by both the memory factory and the OM model functions.\n */\nfunction getAgentControllerState(requestContext: RequestContext): MastraCodeState | undefined {\n const ctx = requestContext.get('controller') as AgentControllerRequestContext<MastraCodeState> | undefined;\n return ctx?.getState() as MastraCodeState | undefined;\n}\n\n/**\n * Observer model function — reads the current observer model ID from\n * controller state via requestContext (now propagated by OM's agent.generate).\n */\nfunction getObserverModel({ requestContext }: { requestContext: RequestContext }) {\n const state = getAgentControllerState(requestContext);\n return resolveModel(state?.observerModelId ?? DEFAULT_OM_MODEL_ID, {\n remapForCodexOAuth: true,\n requestContext,\n });\n}\n\n/**\n * Reflector model function — reads the current reflector model ID from\n * controller state via requestContext (now propagated by OM's agent.generate).\n */\nfunction getReflectorModel({ requestContext }: { requestContext: RequestContext }) {\n const state = getAgentControllerState(requestContext);\n return resolveModel(state?.reflectorModelId ?? DEFAULT_OM_MODEL_ID, {\n remapForCodexOAuth: true,\n requestContext,\n });\n}\n\nconst DYNAMIC_AGENTS_MD_INSTRUCTION =\n 'Messages wrapped in <system-reminder type=\"dynamic-agents-md\" ...>...</system-reminder> are ephemeral project-context instructions injected from files on disk. Do NOT observe or extract information from these messages — they are reloaded automatically when needed and should not be stored in memory.';\n\n// Derived from https://github.com/JuliusBrussee/caveman and adapted for OM use with fixed full-level compression.\nconst CAVEMAN_OM_INSTRUCTION = `Respond terse like smart caveman. All technical substance stay. Only fluff die.\n\nUse full caveman compression style.\n\nDrop: articles (a/an/the), filler (just/really/basically/actually/simply), pleasantries (sure/certainly/of course/happy to), hedging. Fragments OK. Short synonyms (big not extensive, fix not \"implement a solution for\"). Technical terms exact. Code blocks unchanged. Errors quoted exact. Leave out the words \"agent\" and \"assistant\" at the start of each observation line, it is assumed each line is referring to the assistant unless it specifically says it was about the user. Leave out parenthesis and other text characters like * that would not contribute to understanding the observations.\n\nPattern: \\`[thing] [action] [reason]. [next step]\\`\n\nNot: \"Sure! I'd be happy to help you with that. The issue you're experiencing is likely caused by...\"\nYes: \"Bug in auth middleware. Token expiry check use < not <=. Fix:\"\n\nExample 1\nšŸ”“ 14:31 user asks why React component rerenders\n🟔 14:32 saw inline object prop create new ref each render, cause rerender\nāœ… 14:34 fixed render issue by wrap object in useMemo\n\nExample 2\n🟔 15:10 explained pool reuse DB connections, skip repeat handshake overhead\n\nDon't say \"Agent did x\", say \"did x\". It will be assumed the agent did what was observed. The who should only be specified for the user or other third parties: \"user asked x\"\n\nDrop caveman for: security warnings, irreversible action confirmations, multi-step sequences where fragment order risks misread, user asks to clarify or repeats question, and anything that requires remembering verbatim content. Resume caveman after clear part done`;\n\n/**\n * The organization rung local (TUI/studio) knowledge is captured under. A fixed\n * literal on purpose: deriving it from a hostname or path would fragment local\n * knowledge per checkout into scopes nothing ever reads.\n */\nexport const LOCAL_KNOWLEDGE_ORG_ID = 'local';\n\n// One error per session, not per memory resolution. Keyed on the session id\n// rather than the controller object: the controller is read off the request\n// context on every resolution, so it is a fresh object per request and would\n// dedupe nothing. Bounded so a long-running Factory process cannot grow this\n// without limit — refusing sessions are rare, and losing the oldest ids only\n// costs one extra log line.\nconst REPORTED_ORG_UNRESOLVED_LIMIT = 500;\nconst reportedOrgUnresolved = new Set<string>();\n\nfunction reportOrgUnresolved(\n controller: AgentControllerRequestContext<MastraCodeState> | undefined,\n factoryProjectId: string | undefined,\n) {\n const sessionId = controller?.session?.id;\n if (sessionId) {\n if (reportedOrgUnresolved.has(sessionId)) return;\n if (reportedOrgUnresolved.size >= REPORTED_ORG_UNRESOLVED_LIMIT) {\n reportedOrgUnresolved.delete(reportedOrgUnresolved.values().next().value as string);\n }\n reportedOrgUnresolved.add(sessionId);\n }\n const session = controller?.session;\n console.error(\n `[Subconscious] Knowledge capture disabled: no organization resolved for session ${session?.id ?? 'unknown'} (project ${factoryProjectId ?? 'none'}). Knowledge is not written rather than written where it cannot be read.`,\n );\n}\n\n/**\n * Dynamic memory factory function.\n * Reads OM thresholds from controller state via requestContext.\n * Model functions also read from requestContext (no mutable bridge needed).\n */\nexport function getDynamicMemory(storage: MastraCompositeStore, vector?: MastraVector) {\n // Cache is scoped per storage instance (per getDynamicMemory call) so a\n // Memory bound to one storage is never reused after storage changes.\n let cachedMemory: Memory | null = null;\n let cachedMemoryKey: string | null = null;\n\n return ({ requestContext }: { requestContext: RequestContext }) => {\n const controller = requestContext.get('controller') as AgentControllerRequestContext<MastraCodeState> | undefined;\n const state = controller?.getState() as MastraCodeState | undefined;\n const subconsciousEnabled = Boolean(vector) && process.env.MASTRACODE_EXPERIMENTAL_SUBCONSCIOUS === '1';\n const factoryProjectId = state?.factoryProjectId;\n const isFactory = typeof factoryProjectId === 'string' && factoryProjectId.trim().length > 0;\n\n // A Factory-owned session that could not resolve its org refuses to capture:\n // writing under a substituted identity produces knowledge the fail-closed\n // read path can never see.\n let orgUnresolvedRefusal = false;\n\n if (subconsciousEnabled) {\n // Factory seeds the authoritative org id into session state. There is no\n // fallback: a session owner is a USER id, never an organization.\n const factoryOrgId = state?.factoryOrgId;\n const factoryOwned = isFactory || state?.factoryOrgUnresolved === true;\n if (typeof factoryOrgId === 'string' && factoryOrgId.trim()) {\n requestContext.set('organizationId', factoryOrgId);\n } else if (factoryOwned) {\n orgUnresolvedRefusal = true;\n reportOrgUnresolved(controller, factoryProjectId);\n } else {\n // TUI/studio: an explicit, named scope rather than a cascaded identity.\n requestContext.set('organizationId', LOCAL_KNOWLEDGE_ORG_ID);\n }\n // Factory runs share one knowledge graph per project: anchor the\n // subconscious knowledge scope's resource rung on the project id.\n if (isFactory) {\n requestContext.set('knowledgeResourceId', factoryProjectId);\n }\n }\n\n const captureEnabled = subconsciousEnabled && !orgUnresolvedRefusal;\n\n const omScope = state?.omScope ?? getOmScope(state?.projectPath);\n\n const obsThreshold = state?.observationThreshold ?? DEFAULT_OBS_THRESHOLD;\n const refThreshold = state?.reflectionThreshold ?? DEFAULT_REF_THRESHOLD;\n const caveman = state?.cavemanObservations ?? false;\n\n const observerPreviousObservationTokens = 1000;\n const observeAttachments = state?.observeAttachments;\n // Factory sessions get a factory-only Subconscious config, so the cache key\n // carries a factory presence bit to keep the two configs from cross-serving.\n const cacheKey = `${obsThreshold}:${refThreshold}:${omScope}:${observerPreviousObservationTokens}:${caveman ? 1 : 0}:${observeAttachments}:${isFactory ? 1 : 0}:${captureEnabled ? 1 : 0}`;\n if (cachedMemory && cachedMemoryKey === cacheKey) {\n return cachedMemory;\n }\n\n // Async buffering is not supported with resource scope — disable it\n const isResourceScope = omScope === 'resource';\n\n const observerInstruction = caveman\n ? `${DYNAMIC_AGENTS_MD_INSTRUCTION}\\n\\n${CAVEMAN_OM_INSTRUCTION}`\n : DYNAMIC_AGENTS_MD_INSTRUCTION;\n const reflectionInstruction = caveman ? CAVEMAN_OM_INSTRUCTION : undefined;\n\n cachedMemory = new Memory({\n storage,\n vector: vector || false,\n embedder: vector ? fastembed.small : undefined,\n options: {\n // The factory sidebar shows a session the moment it exists, so it needs a\n // name on the first turn. The TUI names its threads from OM's `threadTitle`\n // as they grow and would only pay for an extra call here.\n ...(isFactory ? { generateTitle: { model: getObserverModel } } : {}),\n observationalMemory: {\n enabled: true,\n temporalMarkers: true,\n retrieval: vector ? { vector: true } : true,\n experimental_subconscious: captureEnabled\n ? new Subconscious({\n defaultScope: 'resource',\n maxScope: 'resource',\n // Capture-time pinning is a factory-only opinion; every other\n // client keeps plain curator-maintained pins.\n pins: isFactory ? { capturePinning: true } : true,\n // Factory sessions run the curator every 3 observation runs;\n // other clients leave the cadence trigger dormant.\n ...(isFactory ? { curationCadence: 3 } : {}),\n // Real curation over a factory worklist needs tool room: the\n // default 5-step budget exhausts mid-batch and the curator never\n // reaches its cursor acknowledgment (observed live 2026-08-13).\n ...(isFactory ? { maxSteps: 25 } : {}),\n })\n : undefined,\n scope: omScope,\n activateAfterIdle: 'auto',\n activateOnProviderChange: true,\n observation: {\n bufferTokens: isResourceScope ? false : 1 / 5,\n bufferActivation: isResourceScope ? undefined : 2000,\n model: getObserverModel,\n messageTokens: obsThreshold,\n blockAfter: 2,\n previousObserverTokens: observerPreviousObservationTokens,\n threadTitle: true,\n instruction: observerInstruction,\n observeAttachments,\n },\n reflection: {\n bufferActivation: isResourceScope ? undefined : 1 / 2,\n blockAfter: 1.1,\n model: getReflectorModel,\n observationTokens: refThreshold,\n instruction: reflectionInstruction,\n },\n },\n },\n });\n cachedMemoryKey = cacheKey;\n\n return cachedMemory;\n };\n}\n"],"mappings":";;;;;;;;;;AAeA,SAAS,wBAAwB,gBAA6D;CAE5F,OADY,eAAe,IAAI,YACtB,CAAC,EAAE,SAAS;AACvB;;;;;AAMA,SAAS,iBAAiB,EAAE,kBAAsD;CAEhF,OAAO,aADO,wBAAwB,cACd,CAAC,EAAE,mBAAmB,qBAAqB;EACjE,oBAAoB;EACpB;CACF,CAAC;AACH;;;;;AAMA,SAAS,kBAAkB,EAAE,kBAAsD;CAEjF,OAAO,aADO,wBAAwB,cACd,CAAC,EAAE,oBAAoB,qBAAqB;EAClE,oBAAoB;EACpB;CACF,CAAC;AACH;AAEA,MAAM,gCACJ;AAGF,MAAM,yBAAyB;;;;;;;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ACF;GACF;EACF,CAAC;EACD,kBAAkB;EAElB,OAAO;CACT;AACF"}
@@ -8,8 +8,8 @@ import { GOAL_JUDGE_READONLY_TOOLS, MASTRACODE_WORKSPACE_TOOLS } from "./tool-av
8
8
  import fs, { existsSync } from "fs";
9
9
  import os from "os";
10
10
  import path, { dirname, join } from "path";
11
- import { LocalFilesystem, LocalSandbox, Workspace, createWorkspaceTools } from "@mastra/core/workspace";
12
11
  import { fileURLToPath } from "url";
12
+ import { LocalFilesystem, LocalSandbox, Workspace, createWorkspaceTools } from "@mastra/core/workspace";
13
13
  //#region src/agents/workspace.ts
14
14
  function buildSandboxEnv() {
15
15
  return {
@@ -6,6 +6,7 @@ export * from './provider-auth-error.js';
6
6
  export * from './storage.js';
7
7
  export { anthropicOAuthProvider } from './providers/anthropic.js';
8
8
  export { githubCopilotOAuthProvider } from './providers/github-copilot.js';
9
+ export { kimiCodingOAuthProvider } from './providers/kimi-coding.js';
9
10
  export { openaiCodexOAuthProvider } from './providers/openai-codex.js';
10
11
  export { xaiOAuthProvider } from './providers/xai.js';
11
12
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/auth/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,cAAc,YAAY,CAAC;AAC3B,cAAc,0BAA0B,CAAC;AACzC,cAAc,cAAc,CAAC;AAC7B,OAAO,EAAE,sBAAsB,EAAE,MAAM,0BAA0B,CAAC;AAClE,OAAO,EAAE,0BAA0B,EAAE,MAAM,+BAA+B,CAAC;AAC3E,OAAO,EAAE,wBAAwB,EAAE,MAAM,6BAA6B,CAAC;AACvE,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/auth/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,cAAc,YAAY,CAAC;AAC3B,cAAc,0BAA0B,CAAC;AACzC,cAAc,cAAc,CAAC;AAC7B,OAAO,EAAE,sBAAsB,EAAE,MAAM,0BAA0B,CAAC;AAClE,OAAO,EAAE,0BAA0B,EAAE,MAAM,+BAA+B,CAAC;AAC3E,OAAO,EAAE,uBAAuB,EAAE,MAAM,4BAA4B,CAAC;AACrE,OAAO,EAAE,wBAAwB,EAAE,MAAM,6BAA6B,CAAC;AACvE,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC"}
@@ -1,7 +1,8 @@
1
1
  import { anthropicOAuthProvider } from "./providers/anthropic.js";
2
2
  import { githubCopilotOAuthProvider } from "./providers/github-copilot.js";
3
+ import { kimiCodingOAuthProvider } from "./providers/kimi-coding.js";
3
4
  import { openaiCodexOAuthProvider } from "./providers/openai-codex.js";
4
5
  import { xaiOAuthProvider } from "./providers/xai.js";
5
6
  import { AuthStorage, PROVIDER_DEFAULT_MODELS, getOAuthProvider, getOAuthProviders } from "./storage.js";
6
7
  import { PROVIDER_AUTH_REQUIRED_ERROR, ProviderAuthRequiredError } from "./provider-auth-error.js";
7
- export { AuthStorage, PROVIDER_AUTH_REQUIRED_ERROR, PROVIDER_DEFAULT_MODELS, ProviderAuthRequiredError, anthropicOAuthProvider, getOAuthProvider, getOAuthProviders, githubCopilotOAuthProvider, openaiCodexOAuthProvider, xaiOAuthProvider };
8
+ export { AuthStorage, PROVIDER_AUTH_REQUIRED_ERROR, PROVIDER_DEFAULT_MODELS, ProviderAuthRequiredError, anthropicOAuthProvider, getOAuthProvider, getOAuthProviders, githubCopilotOAuthProvider, kimiCodingOAuthProvider, openaiCodexOAuthProvider, xaiOAuthProvider };
@@ -0,0 +1,38 @@
1
+ import type { DeviceCodePollState } from '../device-code.js';
2
+ import type { OAuthCredentials, OAuthLoginCallbacks, OAuthProviderInterface } from '../types.js';
3
+ export declare function createKimiCodingDeviceId(): string;
4
+ export declare function isKimiCodingDeviceId(value: unknown): value is string;
5
+ export declare function getKimiCodingDeviceHeaders(deviceId: string): Record<string, string>;
6
+ export interface KimiCodingDeviceLoginPending {
7
+ clientId: string;
8
+ deviceId: string;
9
+ deviceCode: string;
10
+ userCode: string;
11
+ url: string;
12
+ instructions: string;
13
+ state: DeviceCodePollState;
14
+ }
15
+ export type KimiCodingDevicePollResult = {
16
+ status: 'complete';
17
+ credentials: OAuthCredentials;
18
+ } | {
19
+ status: 'pending';
20
+ nextPollMs: number;
21
+ pending: KimiCodingDeviceLoginPending;
22
+ } | {
23
+ status: 'failed';
24
+ error: string;
25
+ };
26
+ export declare function startKimiCodingDeviceLogin(options?: {
27
+ signal?: AbortSignal;
28
+ }): Promise<KimiCodingDeviceLoginPending>;
29
+ export declare function pollKimiCodingDeviceLogin(pending: KimiCodingDeviceLoginPending, options?: {
30
+ signal?: AbortSignal;
31
+ }): Promise<KimiCodingDevicePollResult>;
32
+ export declare function loginKimiCoding(callbacks: OAuthLoginCallbacks): Promise<OAuthCredentials>;
33
+ export declare function refreshKimiCodingToken(refreshToken: string, options: {
34
+ signal?: AbortSignal;
35
+ deviceId: string;
36
+ }): Promise<OAuthCredentials>;
37
+ export declare const kimiCodingOAuthProvider: OAuthProviderInterface;
38
+ //# sourceMappingURL=kimi-coding.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"kimi-coding.d.ts","sourceRoot":"","sources":["../../../src/auth/providers/kimi-coding.ts"],"names":[],"mappings":"AASA,OAAO,KAAK,EAAyB,mBAAmB,EAAE,MAAM,mBAAmB,CAAC;AACpF,OAAO,KAAK,EAAE,gBAAgB,EAAE,mBAAmB,EAAE,sBAAsB,EAAE,MAAM,aAAa,CAAC;AAuBjG,wBAAgB,wBAAwB,IAAI,MAAM,CAEjD;AAED,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,MAAM,CAEpE;AAED,wBAAgB,0BAA0B,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAKnF;AA6CD,MAAM,WAAW,4BAA4B;IAC3C,QA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