@mastra/code-sdk 1.15.1-alpha.4 → 1.16.0-alpha.6

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 (222) hide show
  1. package/dist/acp/agent.js +1 -2
  2. package/dist/acp/errors.js +1 -2
  3. package/dist/acp/event-mapper.js +1 -2
  4. package/dist/acp/index.js +1 -2
  5. package/dist/acp/runtime.d.ts.map +1 -1
  6. package/dist/acp/runtime.js +5 -4
  7. package/dist/acp/runtime.js.map +1 -1
  8. package/dist/acp/server.js +1 -2
  9. package/dist/acp/skills.js +1 -2
  10. package/dist/agent-connections/messaging-processor.js +1 -2
  11. package/dist/agent-connections/ownership.js +1 -2
  12. package/dist/agent-connections/registry.js +1 -2
  13. package/dist/agent-connections/session-advertisement.js +1 -2
  14. package/dist/agent-connections/signal-provider.js +1 -2
  15. package/dist/agent-connections/state-processor.js +1 -2
  16. package/dist/agent-connections/thread-state.js +1 -2
  17. package/dist/agent-connections/tools.js +1 -2
  18. package/dist/agent-connections/types.js +1 -2
  19. package/dist/agent-connections/untrusted-text.js +1 -2
  20. package/dist/agents/background-completion-events.js +1 -2
  21. package/dist/agents/background-completion.js +1 -2
  22. package/dist/agents/context-audit.js +1 -2
  23. package/dist/agents/credential-resolver.js +1 -2
  24. package/dist/agents/custom-provider-source.js +1 -2
  25. package/dist/agents/instructions.js +1 -2
  26. package/dist/agents/mastracode-gateway.js +1 -2
  27. package/dist/agents/memory.js +1 -2
  28. package/dist/agents/model.js +1 -2
  29. package/dist/agents/modes/build.js +1 -2
  30. package/dist/agents/modes/explore.js +1 -2
  31. package/dist/agents/modes/plan.js +1 -2
  32. package/dist/agents/prompts/agent-instructions.js +1 -2
  33. package/dist/agents/prompts/build.js +1 -2
  34. package/dist/agents/prompts/fast.js +1 -2
  35. package/dist/agents/prompts/index.js +1 -2
  36. package/dist/agents/prompts/model.js +1 -2
  37. package/dist/agents/prompts/plan.js +1 -2
  38. package/dist/agents/prompts/tool-guidance.js +1 -2
  39. package/dist/agents/sandbox-filesystem.d.ts.map +1 -1
  40. package/dist/agents/sandbox-filesystem.js +9 -7
  41. package/dist/agents/sandbox-filesystem.js.map +1 -1
  42. package/dist/agents/subagents/execute.js +1 -2
  43. package/dist/agents/subagents/explore.js +1 -2
  44. package/dist/agents/subagents/index.d.ts +6 -0
  45. package/dist/agents/subagents/index.d.ts.map +1 -0
  46. package/dist/agents/subagents/index.js +17 -0
  47. package/dist/agents/subagents/index.js.map +1 -0
  48. package/dist/agents/subagents/plan.js +1 -2
  49. package/dist/agents/thread-caveman-state.js +1 -2
  50. package/dist/agents/tool-availability.js +1 -2
  51. package/dist/agents/tools.js +1 -2
  52. package/dist/agents/workflow-builder-agent.js +1 -2
  53. package/dist/agents/workspace.js +1 -2
  54. package/dist/analytics.js +1 -2
  55. package/dist/auth/account-rotation-processor.d.ts +6 -6
  56. package/dist/auth/account-rotation-processor.d.ts.map +1 -1
  57. package/dist/auth/account-rotation-processor.js +41 -51
  58. package/dist/auth/account-rotation-processor.js.map +1 -1
  59. package/dist/auth/account-routing-context.js +1 -2
  60. package/dist/auth/authorization-input.js +1 -2
  61. package/dist/auth/device-code.js +1 -2
  62. package/dist/auth/pkce.js +1 -2
  63. package/dist/auth/provider-auth-error.d.ts +2 -0
  64. package/dist/auth/provider-auth-error.d.ts.map +1 -1
  65. package/dist/auth/provider-auth-error.js +8 -3
  66. package/dist/auth/provider-auth-error.js.map +1 -1
  67. package/dist/auth/providers/anthropic.js +1 -2
  68. package/dist/auth/providers/github-copilot.js +1 -2
  69. package/dist/auth/providers/kimi-coding.js +1 -2
  70. package/dist/auth/providers/openai-codex.js +1 -2
  71. package/dist/auth/providers/xai.js +1 -2
  72. package/dist/auth/storage.js +1 -2
  73. package/dist/clipboard/index.js +1 -2
  74. package/dist/constants.js +1 -2
  75. package/dist/error-classification.js +1 -2
  76. package/dist/evals/context-builder.js +1 -2
  77. package/dist/evals/scorers/classify-command.d.ts +1 -2
  78. package/dist/evals/scorers/classify-command.d.ts.map +1 -1
  79. package/dist/evals/scorers/classify-command.js +7 -17
  80. package/dist/evals/scorers/classify-command.js.map +1 -1
  81. package/dist/evals/scorers/efficiency.js +1 -2
  82. package/dist/evals/scorers/extract-tools.js +1 -2
  83. package/dist/evals/scorers/outcome.d.ts.map +1 -1
  84. package/dist/evals/scorers/outcome.js +36 -22
  85. package/dist/evals/scorers/outcome.js.map +1 -1
  86. package/dist/experimental-agent.js +1 -2
  87. package/dist/factory/client.js +1 -2
  88. package/dist/factory/remote-controller.js +1 -2
  89. package/dist/factory/remote-session.js +1 -2
  90. package/dist/goal-manager.js +1 -2
  91. package/dist/goal-signal.js +1 -2
  92. package/dist/headless/cli.d.ts.map +1 -1
  93. package/dist/headless/cli.js +4 -3
  94. package/dist/headless/cli.js.map +1 -1
  95. package/dist/headless/flags.js +1 -2
  96. package/dist/headless/format.js +1 -2
  97. package/dist/headless/policy.js +1 -2
  98. package/dist/headless/run-mc.js +1 -2
  99. package/dist/headless/types.js +1 -2
  100. package/dist/hooks/config.js +1 -2
  101. package/dist/hooks/executor.js +1 -2
  102. package/dist/hooks/manager.js +1 -2
  103. package/dist/hooks/types.js +1 -2
  104. package/dist/index.d.ts +7 -3
  105. package/dist/index.d.ts.map +1 -1
  106. package/dist/index.js +9 -15
  107. package/dist/index.js.map +1 -1
  108. package/dist/ipc/ipc-reporter.js +1 -2
  109. package/dist/knowledge-inspector.js +1 -2
  110. package/dist/knowledge-scope.js +1 -2
  111. package/dist/lsp/client.d.ts.map +1 -1
  112. package/dist/lsp/client.js +1 -2
  113. package/dist/lsp/client.js.map +1 -1
  114. package/dist/lsp/language.js +1 -2
  115. package/dist/lsp/manager.js +1 -2
  116. package/dist/lsp/server.js +1 -2
  117. package/dist/lsp/workspace.js +1 -2
  118. package/dist/mcp/config.js +1 -2
  119. package/dist/mcp/manager.js +1 -2
  120. package/dist/mcp/state.js +1 -2
  121. package/dist/onboarding/custom-packs.js +1 -2
  122. package/dist/onboarding/custom-providers.js +1 -2
  123. package/dist/onboarding/om-settings.js +1 -2
  124. package/dist/onboarding/pack-activation.js +1 -2
  125. package/dist/onboarding/packs.js +1 -2
  126. package/dist/onboarding/settings.js +1 -2
  127. package/dist/permissions.js +1 -2
  128. package/dist/platform/index.js +1 -2
  129. package/dist/plugin.js +1 -2
  130. package/dist/plugins/dependencies.js +1 -2
  131. package/dist/plugins/install.js +1 -2
  132. package/dist/plugins/loader.js +1 -2
  133. package/dist/plugins/manager.js +1 -2
  134. package/dist/plugins/manifest.js +1 -2
  135. package/dist/plugins/package-link.js +1 -2
  136. package/dist/plugins/paths.js +1 -2
  137. package/dist/plugins/registry.js +1 -2
  138. package/dist/plugins/scaffold.js +1 -2
  139. package/dist/plugins/signal-lane.js +1 -2
  140. package/dist/process-memory-diagnostics.js +1 -2
  141. package/dist/processors/plan-rejection-abort.js +1 -2
  142. package/dist/providers/amazon-bedrock-gateway.js +1 -2
  143. package/dist/providers/amazon-bedrock.js +1 -2
  144. package/dist/providers/anthropic-prompt-cache.js +1 -2
  145. package/dist/providers/anthropic-thinking.js +1 -2
  146. package/dist/providers/claude-max.d.ts.map +1 -1
  147. package/dist/providers/claude-max.js +4 -4
  148. package/dist/providers/claude-max.js.map +1 -1
  149. package/dist/providers/github-copilot-gateway.js +1 -2
  150. package/dist/providers/github-copilot.d.ts.map +1 -1
  151. package/dist/providers/github-copilot.js +5 -5
  152. package/dist/providers/github-copilot.js.map +1 -1
  153. package/dist/providers/google-thinking.js +1 -2
  154. package/dist/providers/kimi-coding.d.ts.map +1 -1
  155. package/dist/providers/kimi-coding.js +8 -7
  156. package/dist/providers/kimi-coding.js.map +1 -1
  157. package/dist/providers/model-ids.js +1 -2
  158. package/dist/providers/openai-codex.d.ts.map +1 -1
  159. package/dist/providers/openai-codex.js +7 -7
  160. package/dist/providers/openai-codex.js.map +1 -1
  161. package/dist/providers/provider-thinking.js +1 -2
  162. package/dist/providers/thinking-request.js +1 -2
  163. package/dist/providers/xai.d.ts.map +1 -1
  164. package/dist/providers/xai.js +5 -5
  165. package/dist/providers/xai.js.map +1 -1
  166. package/dist/schedules/interval.js +1 -2
  167. package/dist/schedules/prompt.js +1 -2
  168. package/dist/schedules/run-script.js +1 -2
  169. package/dist/schedules/scheduler.js +1 -2
  170. package/dist/schedules/tools.js +1 -2
  171. package/dist/schema.js +1 -2
  172. package/dist/theme-palette.js +1 -2
  173. package/dist/thinking-catalog.js +1 -2
  174. package/dist/thinking.js +1 -2
  175. package/dist/tool-names.js +1 -2
  176. package/dist/tools/request-sandbox-access.js +1 -2
  177. package/dist/tools/utils.js +1 -2
  178. package/dist/tools/web-search.js +1 -2
  179. package/dist/tools/workflows/create-workflow.js +1 -2
  180. package/dist/tools/workflows/delete-workflow.js +1 -2
  181. package/dist/tools/workflows/ephemeral-memory.js +1 -2
  182. package/dist/tools/workflows/extract-json-schema.js +1 -2
  183. package/dist/tools/workflows/get-workflow.js +1 -2
  184. package/dist/tools/workflows/list-available-agents.js +1 -2
  185. package/dist/tools/workflows/list-available-classifiers.js +1 -2
  186. package/dist/tools/workflows/list-available-tools.js +1 -2
  187. package/dist/tools/workflows/list-available-workflows.js +1 -2
  188. package/dist/tools/workflows/list-workflows.js +1 -2
  189. package/dist/tools/workflows/run-workflow.js +1 -2
  190. package/dist/tools/workflows/save-workflow.js +1 -2
  191. package/dist/tools/workflows/tool-ids.js +1 -2
  192. package/dist/utils/binaries.js +1 -2
  193. package/dist/utils/debug-log.js +1 -2
  194. package/dist/utils/discarding-scores-storage.js +1 -2
  195. package/dist/utils/errors.d.ts +1 -1
  196. package/dist/utils/errors.d.ts.map +1 -1
  197. package/dist/utils/errors.js +99 -80
  198. package/dist/utils/errors.js.map +1 -1
  199. package/dist/utils/gateway-sync.js +1 -2
  200. package/dist/utils/local-observability.js +1 -2
  201. package/dist/utils/maintenance-lock.js +1 -2
  202. package/dist/utils/notification-dispatch.js +1 -2
  203. package/dist/utils/open-url.js +1 -2
  204. package/dist/utils/path-security.js +1 -2
  205. package/dist/utils/plan-diff.js +1 -2
  206. package/dist/utils/plans.js +1 -2
  207. package/dist/utils/project.js +1 -2
  208. package/dist/utils/prune-cli.js +1 -2
  209. package/dist/utils/signals-pubsub.js +1 -2
  210. package/dist/utils/slash-command-loader.js +1 -2
  211. package/dist/utils/slash-command-processor.js +1 -2
  212. package/dist/utils/stdin-pipe.js +1 -2
  213. package/dist/utils/storage-factory.js +1 -2
  214. package/dist/utils/storage-maintenance.js +1 -2
  215. package/dist/utils/thread-lock.js +1 -2
  216. package/dist/utils/token-estimator.js +1 -2
  217. package/dist/utils/update-check.js +1 -2
  218. package/dist/utils/wake-session.js +1 -2
  219. package/dist/voice/stt-registry.js +1 -2
  220. package/dist/workflows/register-primitives.js +1 -2
  221. package/dist/workflows/service.js +1 -2
  222. package/package.json +35 -31
@@ -4,7 +4,7 @@ import { existsSync } from "fs";
4
4
  import { MastraModelGateway } from "@mastra/core/llm";
5
5
  import { createAmazonBedrock } from "@ai-sdk/amazon-bedrock";
6
6
  import { fromNodeProviderChain } from "@aws-sdk/credential-providers";
7
- //#region src/providers/amazon-bedrock-gateway.ts
7
+ // src/providers/amazon-bedrock-gateway.ts
8
8
  const CLAUDE_3_CACHEABLE = /claude-3-7-sonnet|claude-3-5-sonnet-20241022|claude-3-5-haiku/;
9
9
  function supportsBedrockPromptCaching(modelId) {
10
10
  if (!modelId.includes("anthropic.claude")) return false;
@@ -139,7 +139,6 @@ var AmazonBedrockGateway = class extends MastraModelGateway {
139
139
  function createAmazonBedrockGateway() {
140
140
  return new AmazonBedrockGateway();
141
141
  }
142
- //#endregion
143
142
  export { AMAZON_BEDROCK_GATEWAY_ID, AmazonBedrockGateway, addBedrockCachePoints, createAmazonBedrockGateway, hasAwsCredentials, supportsBedrockPromptCaching, withBedrockCache };
144
143
 
145
144
  //# sourceMappingURL=amazon-bedrock-gateway.js.map
@@ -1,4 +1,4 @@
1
- //#region src/providers/amazon-bedrock.ts
1
+ // src/providers/amazon-bedrock.ts
2
2
  /**
3
3
  * Amazon Bedrock model catalog.
4
4
  *
@@ -96,7 +96,6 @@ async function getBedrockModelCatalog() {
96
96
  })();
97
97
  return inflightFetch;
98
98
  }
99
- //#endregion
100
99
  export { clearBedrockCatalogCache, getBedrockModelCatalog };
101
100
 
102
101
  //# sourceMappingURL=amazon-bedrock.js.map
@@ -1,11 +1,10 @@
1
- //#region src/providers/anthropic-prompt-cache.ts
1
+ // src/providers/anthropic-prompt-cache.ts
2
2
  /**
3
3
  * TTL for the main agent's Anthropic prompt-cache breakpoints.
4
4
  * Observational memory's idle activation for Anthropic is set to the same value,
5
5
  * so buffered observations don't activate while the cache is still warm.
6
6
  */
7
7
  const ANTHROPIC_PROMPT_CACHE_TTL = "1h";
8
- //#endregion
9
8
  export { ANTHROPIC_PROMPT_CACHE_TTL };
10
9
 
11
10
  //# sourceMappingURL=anthropic-prompt-cache.js.map
@@ -1,4 +1,4 @@
1
- //#region src/providers/anthropic-thinking.ts
1
+ // src/providers/anthropic-thinking.ts
2
2
  const ANTHROPIC_THINKING_BUDGET_TOKENS = {
3
3
  low: 4096,
4
4
  medium: 8192,
@@ -19,7 +19,6 @@ function getAnthropicThinkingCapability(modelId) {
19
19
  function supportsAnthropicXhighEffort(modelId) {
20
20
  return ANTHROPIC_XHIGH_EFFORT_RE.test(modelId);
21
21
  }
22
- //#endregion
23
22
  export { ANTHROPIC_THINKING_BUDGET_TOKENS, getAnthropicThinkingCapability, supportsAnthropicXhighEffort };
24
23
 
25
24
  //# sourceMappingURL=anthropic-thinking.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"claude-max.d.ts","sourceRoot":"","sources":["../../src/providers/claude-max.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAGH,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAE1D,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,IAAI,CAAC;AAElD,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AACj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O,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AACjD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAGxD,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,6BAA6B,CAAC;AAE7E,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAsBvD;;GAEG;AACH,wBAAgB,cAAc,IAAI,WAAW,CAK5C;AAED;;GAEG;AACH,wBAAgB,cAAc,CAAC,OAAO,EAAE,WAAW,GAAG,SAAS,GAAG,IAAI,CAErE;AAED;;;GAGG;AACH,eAAO,MAAM,oBAAoB,EAAE,uBAkBlC,CAAC;AAEF;;;;;;;;;;GAUG;AACH,eAAO,MAAM,2BAA2B,GAAI,OAAO,yBAAyB,KAAG,uBA8D7E,CAAC;AAMH;;;;;;;;;GASG;AACH,wBAAgB,iCAAiC,CAC/C,OAAO,EAAE,MAAM,EACf,aAAa,CAAC,EAAE,aAAa,GAC5B,uBAAuB,GAAG,SAAS,CAiCrC;AAED;;;;GAIG;AACH,wBAAgB,wBAAwB,CAAC,IAAI,GAAE;IAAE,WAAW,CAAC,EAAE,eAAe,CAAA;CAAO,GAAG,OAAO,KAAK,CA2CnG;AAED;;;GAGG;AACH,wBAAgB,yBAAyB,CACvC,OAAO,GAAE,MAA4B,EACrC,OAAO,CAAC,EAAE;IACR,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACjC,WAAW,CAAC,EAAE,eAAe,CAAC;IAC9B,aAAa,CAAC,EAAE,aAAa,CAAC;IAC9B,gBAAgB,CAAC,EAAE,yBAAyB,CAAC;CAC9C,GACA,iBAAiB,CAgCnB"}
@@ -5,13 +5,14 @@ import { ProviderAuthRequiredError, rejectUnauthorizedResponse } from "../auth/p
5
5
  import "./anthropic-prompt-cache.js";
6
6
  import { wrapLanguageModel } from "ai";
7
7
  import { createAnthropic } from "@ai-sdk/anthropic";
8
- //#region src/providers/claude-max.ts
8
+ // src/providers/claude-max.ts
9
9
  /**
10
10
  * Claude Max OAuth Provider
11
11
  *
12
12
  * Uses OAuth tokens from AuthStorage to authenticate with Claude Max plan.
13
13
  * The OAuth endpoint requires a specific system message to be present.
14
14
  */
15
+ const PROVIDER_NAME = "Anthropic";
15
16
  const claudeCodeIdentity = "You are Claude Code, Anthropic's official CLI for Claude.";
16
17
  const OAUTH_REQUIRED_BETAS = [
17
18
  "oauth-2025-04-20",
@@ -172,7 +173,7 @@ function buildAnthropicOAuthFetch(opts = {}) {
172
173
  storage.reload();
173
174
  if (storage.get("anthropic")?.type === "api_key") throw new Error("Anthropic API key credential is configured, but OAuth is required.");
174
175
  const accessToken = await storage.getApiKey("anthropic");
175
- if (!accessToken) throw new ProviderAuthRequiredError("Not logged in to Anthropic.");
176
+ if (!accessToken) throw storage.get("anthropic")?.type === "oauth" ? ProviderAuthRequiredError.signInExpired(PROVIDER_NAME) : ProviderAuthRequiredError.notSignedIn(PROVIDER_NAME);
176
177
  const headers = new Headers(url instanceof Request ? url.headers : void 0);
177
178
  if (init?.headers) new Headers(init.headers).forEach((value, key) => headers.set(key, value));
178
179
  headers.delete("authorization");
@@ -187,7 +188,7 @@ function buildAnthropicOAuthFetch(opts = {}) {
187
188
  ...init,
188
189
  headers
189
190
  }), {
190
- providerName: "Anthropic",
191
+ providerName: PROVIDER_NAME,
191
192
  requestUrl
192
193
  });
193
194
  } catch (error) {
@@ -228,7 +229,6 @@ function opencodeClaudeMaxProvider(modelId = "claude-sonnet-5-5", options) {
228
229
  middleware
229
230
  });
230
231
  }
231
- //#endregion
232
232
  export { buildAnthropicOAuthFetch, claudeCodeMiddleware, createAnthropicThinkingMiddleware, createPromptCacheMiddleware, getAuthStorage, opencodeClaudeMaxProvider, setAuthStorage };
233
233
 
234
234
  //# sourceMappingURL=claude-max.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"claude-max.js","names":[],"sources":["../../src/providers/claude-max.ts"],"sourcesContent":["/**\n * Claude Max OAuth Provider\n *\n * Uses OAuth tokens from AuthStorage to authenticate with Claude Max plan.\n * The OAuth endpoint requires a specific system message to be present.\n */\n\nimport { createAnthropic } from '@ai-sdk/anthropic';\nimport type { MastraModelConfig } from '@mastra/core/llm';\nimport { wrapLanguageModel } from 'ai';\nimport type { LanguageModelMiddleware } from 'ai';\nimport { ProviderAuthRequiredError, rejectUnauthorizedResponse } from '../auth/provider-auth-error.js';\nimport { AuthStorage } from '../auth/storage.js';\nimport type { CredentialStore } from '../auth/types.js';\nimport { runCatalogThinkingLevel } from '../thinking-catalog.js';\nimport { ANTHROPIC_PROMPT_CACHE_TTL } from './anthropic-prompt-cache.js';\nimport type { AnthropicPromptCacheScope } from './anthropic-prompt-cache.js';\nimport { ANTHROPIC_THINKING_BUDGET_TOKENS, getAnthropicThinkingCapability } from './anthropic-thinking.js';\nimport type { ThinkingLevel } from './openai-codex.js';\n\n// Required for Claude Max plan OAuth - the endpoint checks for this system message\nconst claudeCodeIdentity = \"You are Claude Code, Anthropic's official CLI for Claude.\";\n\n// Betas required for Claude Max plan OAuth. Merged with (not replacing) any\n// betas the AI SDK already set on the request — e.g. the SDK adds\n// `server-side-fallback-2026-06-01` when `providerOptions.anthropic.fallbacks`\n// is configured; dropping it makes the API reject the `fallbacks` body field\n// with \"Extra inputs are not permitted\".\nconst OAUTH_REQUIRED_BETAS = [\n 'oauth-2025-04-20',\n 'claude-code-20250219',\n 'interleaved-thinking-2025-05-14',\n 'fine-grained-tool-streaming-2025-05-14',\n];\n\n// Singleton auth storage instance\nlet authStorageInstance: AuthStorage | null = null;\n\n/**\n * Get or create the shared AuthStorage instance\n */\nexport function getAuthStorage(): AuthStorage {\n if (!authStorageInstance) {\n authStorageInstance = new AuthStorage();\n }\n return authStorageInstance;\n}\n\n/**\n * Set a custom AuthStorage instance (useful for TUI integration)\n */\nexport function setAuthStorage(storage: AuthStorage | undefined): void {\n authStorageInstance = storage ?? null;\n}\n\n/**\n * Middleware that injects the Claude Code identity system message\n * Required for Claude Max OAuth authentication\n */\nexport const claudeCodeMiddleware: LanguageModelMiddleware = {\n specificationVersion: 'v3',\n transformParams: async ({ params }) => {\n // Prepend the Claude Code identity as the first system message\n const systemMessage = {\n role: 'system' as const,\n content: claudeCodeIdentity,\n };\n\n if (params.temperature) {\n delete params.topP;\n }\n\n return {\n ...params,\n prompt: [systemMessage, ...params.prompt],\n };\n },\n};\n\n/**\n * Prompt caching middleware for Anthropic\n *\n * Adds cache breakpoints at strategic locations:\n * 1. Last system message (end of static instructions + dynamic memory)\n * 2. Most recent user/assistant message (conversation context), `conversation` scope only\n *\n * This allows Anthropic to cache:\n * - System prompts and instructions (rarely change)\n * - Conversation history up to the last message\n */\nexport const createPromptCacheMiddleware = (scope: AnthropicPromptCacheScope): LanguageModelMiddleware => ({\n specificationVersion: 'v3',\n transformParams: async ({ params }) => {\n const prompt = [...params.prompt];\n\n const cacheControl = {\n type: 'ephemeral' as const,\n ttl: scope === 'conversation' ? ANTHROPIC_PROMPT_CACHE_TTL : ('5m' as const),\n };\n\n // Helper to add cache control to a message's last content part\n const addCacheToMessage = (msg: any) => {\n // For system messages with string content\n if (typeof msg.content === 'string') {\n return {\n ...msg,\n providerOptions: {\n ...msg.providerOptions,\n anthropic: { ...msg.providerOptions?.anthropic, cacheControl },\n },\n };\n }\n\n // For messages with array content, add to last part\n if (Array.isArray(msg.content) && msg.content.length > 0) {\n const content = [...msg.content];\n const lastPart = content[content.length - 1];\n content[content.length - 1] = {\n ...lastPart,\n providerOptions: {\n ...lastPart.providerOptions,\n anthropic: { ...lastPart.providerOptions?.anthropic, cacheControl },\n },\n };\n return { ...msg, content };\n }\n\n return msg;\n };\n\n // Find the last system message index\n let lastSystemIdx = -1;\n for (let i = prompt.length - 1; i >= 0; i--) {\n if ((prompt[i] as any).role === 'system') {\n lastSystemIdx = i;\n break;\n }\n }\n\n // Add cache breakpoint to last system message\n if (lastSystemIdx >= 0) {\n prompt[lastSystemIdx] = addCacheToMessage(prompt[lastSystemIdx]);\n }\n\n // Add cache breakpoint to the most recent message (last in array)\n const lastIdx = prompt.length - 1;\n if (scope === 'conversation' && lastIdx >= 0 && lastIdx !== lastSystemIdx) {\n prompt[lastIdx] = addCacheToMessage(prompt[lastIdx]);\n }\n\n return { ...params, prompt };\n },\n});\n\nfunction runAnthropicRequestLevel(modelId: string, level: ThinkingLevel): ThinkingLevel {\n return runCatalogThinkingLevel(`anthropic/${modelId}`, level);\n}\n\n/**\n * Middleware that maps the session thinking level onto Anthropic extended\n * thinking. Returns `undefined` (no middleware) when the level is `off` or the\n * model doesn't support thinking, preserving the previous request shape.\n *\n * - Adaptive-era models (Sonnet 4.6+/Opus 4.6+): `thinking: adaptive` plus\n * `output_config.effort`, the closest effort the model accepts.\n * - Budget-era models (Claude 3.7 – Opus 4.5): `thinking: enabled` with a\n * `budget_tokens` value derived from the level.\n */\nexport function createAnthropicThinkingMiddleware(\n modelId: string,\n thinkingLevel?: ThinkingLevel,\n): LanguageModelMiddleware | undefined {\n if (!thinkingLevel || thinkingLevel === 'off') return undefined;\n const capability = getAnthropicThinkingCapability(modelId);\n const level = runAnthropicRequestLevel(modelId, thinkingLevel);\n if (level === 'off') return undefined;\n\n return {\n specificationVersion: 'v3',\n transformParams: async ({ params }) => {\n const anthropicOptions = (params.providerOptions?.anthropic ?? {}) as Record<string, unknown>;\n // Don't override explicit per-request thinking configuration.\n if (anthropicOptions.thinking !== undefined || anthropicOptions.effort !== undefined) {\n return params;\n }\n\n // Anthropic rejects sampling parameters when thinking is enabled.\n delete params.temperature;\n delete params.topP;\n delete params.topK;\n\n params.providerOptions = {\n ...params.providerOptions,\n anthropic: {\n ...anthropicOptions,\n ...(capability === 'adaptive'\n ? { thinking: { type: 'adaptive', display: 'summarized' }, effort: level }\n : { thinking: { type: 'enabled', budgetTokens: ANTHROPIC_THINKING_BUDGET_TOKENS[level] } }),\n },\n } as typeof params.providerOptions;\n\n return params;\n },\n };\n}\n\n/**\n * Build a fetch function that handles Anthropic OAuth.\n * Preserves non-auth headers from init (critical for gateway auth header to survive\n * when used with the gateway). Strips `authorization` and `x-api-key`.\n */\nexport function buildAnthropicOAuthFetch(opts: { authStorage?: CredentialStore } = {}): typeof fetch {\n return (async (url: string | URL | Request, init?: Parameters<typeof fetch>[1]) => {\n const storage = opts.authStorage ?? getAuthStorage();\n storage.reload();\n\n const storedCred = storage.get('anthropic');\n if (storedCred?.type === 'api_key') {\n throw new Error('Anthropic API key credential is configured, but OAuth is required.');\n }\n\n const accessToken = await storage.getApiKey('anthropic');\n if (!accessToken) {\n throw new ProviderAuthRequiredError('Not logged in to Anthropic.');\n }\n\n // Preserve Request headers and let explicit init headers override them.\n const headers = new Headers(url instanceof Request ? url.headers : undefined);\n if (init?.headers) new Headers(init.headers).forEach((value, key) => headers.set(key, value));\n headers.delete('authorization');\n headers.delete('x-api-key');\n headers.set('Authorization', `Bearer ${accessToken}`);\n const requestBetas = (headers.get('anthropic-beta') ?? '')\n .split(',')\n .map(beta => beta.trim())\n .filter(Boolean);\n headers.set('anthropic-beta', Array.from(new Set([...OAUTH_REQUIRED_BETAS, ...requestBetas])).join(','));\n headers.set('anthropic-version', '2023-06-01');\n\n const requestUrl = url instanceof URL ? url.toString() : typeof url === 'string' ? url : url.url;\n try {\n return await rejectUnauthorizedResponse(await fetch(url, { ...init, headers }), {\n providerName: 'Anthropic',\n requestUrl,\n });\n } catch (error) {\n if (error && typeof error === 'object') {\n Object.assign(error as Record<string, unknown>, { requestUrl });\n }\n throw error;\n }\n }) as typeof fetch;\n}\n\n/**\n * Creates an Anthropic model using Claude Max OAuth authentication\n * Uses OAuth tokens from AuthStorage (auto-refreshes when needed)\n */\nexport function opencodeClaudeMaxProvider(\n modelId: string = 'claude-sonnet-5-5',\n options?: {\n headers?: Record<string, string>;\n authStorage?: CredentialStore;\n thinkingLevel?: ThinkingLevel;\n promptCacheScope?: AnthropicPromptCacheScope;\n },\n): MastraModelConfig {\n const headers = options?.headers;\n const thinkingMiddleware = createAnthropicThinkingMiddleware(modelId, options?.thinkingLevel);\n const middleware = [\n claudeCodeMiddleware,\n createPromptCacheMiddleware(options?.promptCacheScope ?? 'conversation'),\n ...(thinkingMiddleware ? [thinkingMiddleware] : []),\n ];\n\n // Test environment: use API key\n if (process.env.NODE_ENV === 'test' || process.env.VITEST) {\n const anthropic = createAnthropic({\n apiKey: 'test-api-key',\n headers,\n });\n return wrapLanguageModel({\n model: anthropic(modelId),\n middleware,\n });\n }\n\n const anthropic = createAnthropic({\n apiKey: 'oauth-placeholder',\n headers,\n fetch: buildAnthropicOAuthFetch({ authStorage: options?.authStorage }) as any,\n });\n\n // Wrap with middleware to inject Claude Code identity and enable prompt caching\n return wrapLanguageModel({\n model: anthropic(modelId),\n middleware,\n });\n}\n"],"mappings":";;;;;;;;;;;;;;AAqBA,MAAM,qBAAqB;AAO3B,MAAM,uBAAuB;CAC3B;CACA;CACA;CACA;AACF;AAGA,IAAI,sBAA0C;;;;AAK9C,SAAgB,iBAA8B;CAC5C,IAAI,CAAC,qBACH,sBAAsB,IAAI,YAAY;CAExC,OAAO;AACT;;;;AAKA,SAAgB,eAAe,SAAwC;CACrE,sBAAsB,WAAW;AACnC;;;;;AAMA,MAAa,uBAAgD;CAC3D,sBAAsB;CACtB,iBAAiB,OAAO,EAAE,aAAa;EAErC,MAAM,gBAAgB;GACpB,MAAM;GACN,SAAS;EACX;EAEA,IAAI,OAAO,aACT,OAAO,OAAO;EAGhB,OAAO;GACL,GAAG;GACH,QAAQ,CAAC,eAAe,GAAG,OAAO,MAAM;EAC1C;CACF;AACF;;;;;;;;;;;;AAaA,MAAa,+BAA+B,WAA+D;CACzG,sBAAsB;CACtB,iBAAiB,OAAO,EAAE,aAAa;EACrC,MAAM,SAAS,CAAC,GAAG,OAAO,MAAM;EAEhC,MAAM,eAAe;GACnB,MAAM;GACN,KAAK,UAAU,iBAAA,OAA+C;EAChE;EAGA,MAAM,qBAAqB,QAAa;GAEtC,IAAI,OAAO,IAAI,YAAY,UACzB,OAAO;IACL,GA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AE7C,MAAM,aAAa,eAAe,MAAM,IAAI,SAAS,IAAI,OAAO,QAAQ,WAAW,MAAM,IAAI;EAC7F,IAAI;GACF,OAAO,MAAM,2BAA2B,MAAM,MAAM,KAAK;IAAE,GAAG;IAAM;GAAQ,CAAC,GAAG;IAC9E,cAAc;IACd;GACF,CAAC;EACH,SAAS,OAAO;GACd,IAAI,SAAS,OAAO,UAAU,UAC5B,OAAO,OAAO,OAAkC,EAAE,WAAW,CAAC;GAEhE,MAAM;EACR;CACF;AACF;;;;;AAMA,SAAgB,0BACd,UAAkB,qBAClB,SAMmB;CACnB,MAAM,UAAU,SAAS;CACzB,MAAM,qBAAqB,kCAAkC,SAAS,SAAS,aAAa;CAC5F,MAAM,aAAa;EACjB;EACA,4BAA4B,SAAS,oBAAoB,cAAc;EACvE,GAAI,qBAAqB,CAAC,kBAAkB,IAAI,CAAC;CACnD;CAGA,IAAI,QAAQ,IAAI,aAAa,UAAU,QAAQ,IAAI,QAAQ;EACzD,MAAM,YAAY,gBAAgB;GAChC,QAAQ;GACR;EACF,CAAC;EACD,OAAO,kBAAkB;GACvB,OAAO,UAAU,OAAO;GACxB;EACF,CAAC;CACH;CAEA,MAAM,YAAY,gBAAgB;EAChC,QAAQ;EACR;EACA,OAAO,yBAAyB,EAAE,aAAa,SAAS,YAAY,CAAC;CACvE,CAAC;CAGD,OAAO,kBAAkB;EACvB,OAAO,UAAU,OAAO;EACxB;CACF,CAAC;AACH"}
1
+ {"version":3,"file":"claude-max.js","names":[],"sources":["../../src/providers/claude-max.ts"],"sourcesContent":["/**\n * Claude Max OAuth Provider\n *\n * Uses OAuth tokens from AuthStorage to authenticate with Claude Max plan.\n * The OAuth endpoint requires a specific system message to be present.\n */\n\nimport { createAnthropic } from '@ai-sdk/anthropic';\nimport type { MastraModelConfig } from '@mastra/core/llm';\nimport { wrapLanguageModel } from 'ai';\nimport type { LanguageModelMiddleware } from 'ai';\nimport { ProviderAuthRequiredError, rejectUnauthorizedResponse } from '../auth/provider-auth-error.js';\nimport { AuthStorage } from '../auth/storage.js';\nimport type { CredentialStore } from '../auth/types.js';\nimport { runCatalogThinkingLevel } from '../thinking-catalog.js';\nimport { ANTHROPIC_PROMPT_CACHE_TTL } from './anthropic-prompt-cache.js';\nimport type { AnthropicPromptCacheScope } from './anthropic-prompt-cache.js';\nimport { ANTHROPIC_THINKING_BUDGET_TOKENS, getAnthropicThinkingCapability } from './anthropic-thinking.js';\nimport type { ThinkingLevel } from './openai-codex.js';\n\nconst PROVIDER_NAME = 'Anthropic';\n\n// Required for Claude Max plan OAuth - the endpoint checks for this system message\nconst claudeCodeIdentity = \"You are Claude Code, Anthropic's official CLI for Claude.\";\n\n// Betas required for Claude Max plan OAuth. Merged with (not replacing) any\n// betas the AI SDK already set on the request — e.g. the SDK adds\n// `server-side-fallback-2026-06-01` when `providerOptions.anthropic.fallbacks`\n// is configured; dropping it makes the API reject the `fallbacks` body field\n// with \"Extra inputs are not permitted\".\nconst OAUTH_REQUIRED_BETAS = [\n 'oauth-2025-04-20',\n 'claude-code-20250219',\n 'interleaved-thinking-2025-05-14',\n 'fine-grained-tool-streaming-2025-05-14',\n];\n\n// Singleton auth storage instance\nlet authStorageInstance: AuthStorage | null = null;\n\n/**\n * Get or create the shared AuthStorage instance\n */\nexport function getAuthStorage(): AuthStorage {\n if (!authStorageInstance) {\n authStorageInstance = new AuthStorage();\n }\n return authStorageInstance;\n}\n\n/**\n * Set a custom AuthStorage instance (useful for TUI integration)\n */\nexport function setAuthStorage(storage: AuthStorage | undefined): void {\n authStorageInstance = storage ?? null;\n}\n\n/**\n * Middleware that injects the Claude Code identity system message\n * Required for Claude Max OAuth authentication\n */\nexport const claudeCodeMiddleware: LanguageModelMiddleware = {\n specificationVersion: 'v3',\n transformParams: async ({ params }) => {\n // Prepend the Claude Code identity as the first system message\n const systemMessage = {\n role: 'system' as const,\n content: claudeCodeIdentity,\n };\n\n if (params.temperature) {\n delete params.topP;\n }\n\n return {\n ...params,\n prompt: [systemMessage, ...params.prompt],\n };\n },\n};\n\n/**\n * Prompt caching middleware for Anthropic\n *\n * Adds cache breakpoints at strategic locations:\n * 1. Last system message (end of static instructions + dynamic memory)\n * 2. Most recent user/assistant message (conversation context), `conversation` scope only\n *\n * This allows Anthropic to cache:\n * - System prompts and instructions (rarely change)\n * - Conversation history up to the last message\n */\nexport const createPromptCacheMiddleware = (scope: AnthropicPromptCacheScope): LanguageModelMiddleware => ({\n specificationVersion: 'v3',\n transformParams: async ({ params }) => {\n const prompt = [...params.prompt];\n\n const cacheControl = {\n type: 'ephemeral' as const,\n ttl: scope === 'conversation' ? ANTHROPIC_PROMPT_CACHE_TTL : ('5m' as const),\n };\n\n // Helper to add cache control to a message's last content part\n const addCacheToMessage = (msg: any) => {\n // For system messages with string content\n if (typeof msg.content === 'string') {\n return {\n ...msg,\n providerOptions: {\n ...msg.providerOptions,\n anthropic: { ...msg.providerOptions?.anthropic, cacheControl },\n },\n };\n }\n\n // For messages with array content, add to last part\n if (Array.isArray(msg.content) && msg.content.length > 0) {\n const content = [...msg.content];\n const lastPart = content[content.length - 1];\n content[content.length - 1] = {\n ...lastPart,\n providerOptions: {\n ...lastPart.providerOptions,\n anthropic: { ...lastPart.providerOptions?.anthropic, cacheControl },\n },\n };\n return { ...msg, content };\n }\n\n return msg;\n };\n\n // Find the last system message index\n let lastSystemIdx = -1;\n for (let i = prompt.length - 1; i >= 0; i--) {\n if ((prompt[i] as any).role === 'system') {\n lastSystemIdx = i;\n break;\n }\n }\n\n // Add cache breakpoint to last system message\n if (lastSystemIdx >= 0) {\n prompt[lastSystemIdx] = addCacheToMessage(prompt[lastSystemIdx]);\n }\n\n // Add cache breakpoint to the most recent message (last in array)\n const lastIdx = prompt.length - 1;\n if (scope === 'conversation' && lastIdx >= 0 && lastIdx !== lastSystemIdx) {\n prompt[lastIdx] = addCacheToMessage(prompt[lastIdx]);\n }\n\n return { ...params, prompt };\n },\n});\n\nfunction runAnthropicRequestLevel(modelId: string, level: ThinkingLevel): ThinkingLevel {\n return runCatalogThinkingLevel(`anthropic/${modelId}`, level);\n}\n\n/**\n * Middleware that maps the session thinking level onto Anthropic extended\n * thinking. Returns `undefined` (no middleware) when the level is `off` or the\n * model doesn't support thinking, preserving the previous request shape.\n *\n * - Adaptive-era models (Sonnet 4.6+/Opus 4.6+): `thinking: adaptive` plus\n * `output_config.effort`, the closest effort the model accepts.\n * - Budget-era models (Claude 3.7 – Opus 4.5): `thinking: enabled` with a\n * `budget_tokens` value derived from the level.\n */\nexport function createAnthropicThinkingMiddleware(\n modelId: string,\n thinkingLevel?: ThinkingLevel,\n): LanguageModelMiddleware | undefined {\n if (!thinkingLevel || thinkingLevel === 'off') return undefined;\n const capability = getAnthropicThinkingCapability(modelId);\n const level = runAnthropicRequestLevel(modelId, thinkingLevel);\n if (level === 'off') return undefined;\n\n return {\n specificationVersion: 'v3',\n transformParams: async ({ params }) => {\n const anthropicOptions = (params.providerOptions?.anthropic ?? {}) as Record<string, unknown>;\n // Don't override explicit per-request thinking configuration.\n if (anthropicOptions.thinking !== undefined || anthropicOptions.effort !== undefined) {\n return params;\n }\n\n // Anthropic rejects sampling parameters when thinking is enabled.\n delete params.temperature;\n delete params.topP;\n delete params.topK;\n\n params.providerOptions = {\n ...params.providerOptions,\n anthropic: {\n ...anthropicOptions,\n ...(capability === 'adaptive'\n ? { thinking: { type: 'adaptive', display: 'summarized' }, effort: level }\n : { thinking: { type: 'enabled', budgetTokens: ANTHROPIC_THINKING_BUDGET_TOKENS[level] } }),\n },\n } as typeof params.providerOptions;\n\n return params;\n },\n };\n}\n\n/**\n * Build a fetch function that handles Anthropic OAuth.\n * Preserves non-auth headers from init (critical for gateway auth header to survive\n * when used with the gateway). Strips `authorization` and `x-api-key`.\n */\nexport function buildAnthropicOAuthFetch(opts: { authStorage?: CredentialStore } = {}): typeof fetch {\n return (async (url: string | URL | Request, init?: Parameters<typeof fetch>[1]) => {\n const storage = opts.authStorage ?? getAuthStorage();\n storage.reload();\n\n const storedCred = storage.get('anthropic');\n if (storedCred?.type === 'api_key') {\n throw new Error('Anthropic API key credential is configured, but OAuth is required.');\n }\n\n const accessToken = await storage.getApiKey('anthropic');\n if (!accessToken) {\n throw storage.get('anthropic')?.type === 'oauth'\n ? ProviderAuthRequiredError.signInExpired(PROVIDER_NAME)\n : ProviderAuthRequiredError.notSignedIn(PROVIDER_NAME);\n }\n\n // Preserve Request headers and let explicit init headers override them.\n const headers = new Headers(url instanceof Request ? url.headers : undefined);\n if (init?.headers) new Headers(init.headers).forEach((value, key) => headers.set(key, value));\n headers.delete('authorization');\n headers.delete('x-api-key');\n headers.set('Authorization', `Bearer ${accessToken}`);\n const requestBetas = (headers.get('anthropic-beta') ?? '')\n .split(',')\n .map(beta => beta.trim())\n .filter(Boolean);\n headers.set('anthropic-beta', Array.from(new Set([...OAUTH_REQUIRED_BETAS, ...requestBetas])).join(','));\n headers.set('anthropic-version', '2023-06-01');\n\n const requestUrl = url instanceof URL ? url.toString() : typeof url === 'string' ? url : url.url;\n try {\n return await rejectUnauthorizedResponse(await fetch(url, { ...init, headers }), {\n providerName: PROVIDER_NAME,\n requestUrl,\n });\n } catch (error) {\n if (error && typeof error === 'object') {\n Object.assign(error as Record<string, unknown>, { requestUrl });\n }\n throw error;\n }\n }) as typeof fetch;\n}\n\n/**\n * Creates an Anthropic model using Claude Max OAuth authentication\n * Uses OAuth tokens from AuthStorage (auto-refreshes when needed)\n */\nexport function opencodeClaudeMaxProvider(\n modelId: string = 'claude-sonnet-5-5',\n options?: {\n headers?: Record<string, string>;\n authStorage?: CredentialStore;\n thinkingLevel?: ThinkingLevel;\n promptCacheScope?: AnthropicPromptCacheScope;\n },\n): MastraModelConfig {\n const headers = options?.headers;\n const thinkingMiddleware = createAnthropicThinkingMiddleware(modelId, options?.thinkingLevel);\n const middleware = [\n claudeCodeMiddleware,\n createPromptCacheMiddleware(options?.promptCacheScope ?? 'conversation'),\n ...(thinkingMiddleware ? [thinkingMiddleware] : []),\n ];\n\n // Test environment: use API key\n if (process.env.NODE_ENV === 'test' || process.env.VITEST) {\n const anthropic = createAnthropic({\n apiKey: 'test-api-key',\n headers,\n });\n return wrapLanguageModel({\n model: anthropic(modelId),\n middleware,\n });\n }\n\n const anthropic = createAnthropic({\n apiKey: 'oauth-placeholder',\n headers,\n fetch: buildAnthropicOAuthFetch({ authStorage: options?.authStorage }) as any,\n });\n\n // Wrap with middleware to inject Claude Code identity and enable prompt caching\n return wrapLanguageModel({\n model: anthropic(modelId),\n middleware,\n });\n}\n"],"mappings":";;;;;;;;;;;;;;AAoBA,MAAM,gBAAgB;AAGtB,MAAM,qBAAqB;AAO3B,MAAM,uBAAuB;CAC3B;CACA;CACA;CACA;AACF;AAGA,IAAI,sBAA0C;;;;AAK9C,SAAgB,iBAA8B;CAC5C,IAAI,CAAC,qBACH,sBAAsB,IAAI,YAAY;CAExC,OAAO;AACT;;;;AAKA,SAAgB,eAAe,SAAwC;CACrE,sBAAsB,WAAW;AACnC;;;;;AAMA,MAAa,uBAAgD;CAC3D,sBAAsB;CACtB,iBAAiB,OAAO,EAAE,aAAa;EAErC,MAAM,gBAAgB;GACpB,MAAM;GACN,SAAS;EACX;EAEA,IAAI,OAAO,aACT,OAAO,OAAO;EAGhB,OAAO;GACL,GAAG;GACH,QAAQ,CAAC,eAAe,GAAG,OAAO,MAAM;EAC1C;CACF;AACF;;;;;;;;;;;;AAaA,MAAa,+BAA+B,WAA+D;CACzG,sBAAsB;CACtB,iBAAiB,OAAO,EAAE,aAAa;EACrC,MAAM,SAAS,CAAC,GAAG,OAAO,MAAM;EAEhC,MAAM,eAAe;GACnB,MAAM;GACN,KAAK,UAAU,iBAAA,OAA+C;EAChE;EAGA,MAAM,qBAAqB,QAAa;GAEtC,IAAI,OAAO,IAAI,YAAY,UACzB,OAAO;IACL,GAAG;IACH,iBAAiB;KACf,GAAG,IAAI;KACP,WAAW;MAAE,GAAG,IAAI,iBAAiB;MAAW;KAAa;IAC/D;GACF;GAIF,IAAI,MAAM,QAAQ,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O,QAAQ,WAAW,MAAM,IAAI;EAC7F,IAAI;GACF,OAAO,MAAM,2BAA2B,MAAM,MAAM,KAAK;IAAE,GAAG;IAAM;GAAQ,CAAC,GAAG;IAC9E,cAAc;IACd;GACF,CAAC;EACH,SAAS,OAAO;GACd,IAAI,SAAS,OAAO,UAAU,UAC5B,OAAO,OAAO,OAAkC,EAAE,WAAW,CAAC;GAEhE,MAAM;EACR;CACF;AACF;;;;;AAMA,SAAgB,0BACd,UAAkB,qBAClB,SAMmB;CACnB,MAAM,UAAU,SAAS;CACzB,MAAM,qBAAqB,kCAAkC,SAAS,SAAS,aAAa;CAC5F,MAAM,aAAa;EACjB;EACA,4BAA4B,SAAS,oBAAoB,cAAc;EACvE,GAAI,qBAAqB,CAAC,kBAAkB,IAAI,CAAC;CACnD;CAGA,IAAI,QAAQ,IAAI,aAAa,UAAU,QAAQ,IAAI,QAAQ;EACzD,MAAM,YAAY,gBAAgB;GAChC,QAAQ;GACR;EACF,CAAC;EACD,OAAO,kBAAkB;GACvB,OAAO,UAAU,OAAO;GACxB;EACF,CAAC;CACH;CAEA,MAAM,YAAY,gBAAgB;EAChC,QAAQ;EACR;EACA,OAAO,yBAAyB,EAAE,aAAa,SAAS,YAAY,CAAC;CACvE,CAAC;CAGD,OAAO,kBAAkB;EACvB,OAAO,UAAU,OAAO;EACxB;CACF,CAAC;AACH"}
@@ -1,6 +1,6 @@
1
1
  import { getAuthStorage, getCopilotModelCatalog, githubCopilotProvider } from "./github-copilot.js";
2
2
  import { MastraModelGateway } from "@mastra/core/llm";
3
- //#region src/providers/github-copilot-gateway.ts
3
+ // src/providers/github-copilot-gateway.ts
4
4
  const GITHUB_COPILOT_GATEWAY_ID = "github-copilot";
5
5
  /**
6
6
  * Standalone GitHub Copilot gateway.
@@ -55,7 +55,6 @@ var GitHubCopilotGateway = class extends MastraModelGateway {
55
55
  function createGitHubCopilotGateway(options) {
56
56
  return new GitHubCopilotGateway(options);
57
57
  }
58
- //#endregion
59
58
  export { GITHUB_COPILOT_GATEWAY_ID, GitHubCopilotGateway, createGitHubCopilotGateway };
60
59
 
61
60
  //# sourceMappingURL=github-copilot-gateway.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"github-copilot.d.ts","sourceRoot":"","sources":["../../src/providers/github-copilot.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAGH,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAO1D,OAAO,KAAK,EAAE,iBAAiB,EAA4B,MAAM,qCAAqC,CAAC;AACvG,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AACjD,OAAO,KAAK,EAAE,eAAe,EAAmB,MAAM,kBAAkB,CAAC;AAOzE,qDAAqD;AACrD,wBAAgB,cAAc,IAAI,WAAW,CAK5C;AAED,8EAA8E;AAC9E,wBAAgB,cAAc,CAAC,OAAO,EAAE,WAAW,GAAG,SAAS,GAAG,IAAI,CAErE;AAqED;;;;;;GAMG;AACH,wBAAgB,4BAA4B,CAC1C,IAAI,GAAE;IAAE,WAAW,CAAC,EAAE,eAAe,CAAC;IAAC,UAAU,CAAC,EAAE,OAAO,CAAA;CAAO,GACjE,OAAO,KAAK,CAkFd;AAwED;;;;;;GAMG;AACH,wBAAgB,qBAAqB,CACnC,OAAO,GAAE,MAAkB,EAC3B,OAAO,CAAC,EAAE;IAAE,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAAC,WAAW,CAAC,EAAE,eAAe,CAAA;CAAE,GAC5E,iBAAiB,CAiBnB;AAsDD,wFAAwF;AACxF,wBAAgB,wBAAwB,IAAI,IAAI,CAG/C;AAED;;;;;;;;;;;GAWG;AACH,wBAAsB,sBAAsB,CAC1C,IAAI,GAAE;IAAE,WAAW,CAAC,EAAE,eAAe,CAAA;CAAO,GAC3C,OAAO,CAAC,iBAAiB,EAAE,CAAC,CA2F9B"}
1
+ {"version":3,"file":"github-copilot.d.ts","sourceRoot":"","sources":["../../src/providers/github-copilot.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAGH,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAO1D,OAAO,KAAK,EAAE,iBAAiB,EAA4B,MAAM,qCAAqC,CAAC;AACvG,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AACjD,OAAO,KAAK,EAAE,eAAe,EAAmB,MAAM,kBAAkB,CAAC;AAQzE,qDAAqD;AACrD,wBAAgB,cAAc,IAAI,WAAW,CAK5C;AAED,8EAA8E;AAC9E,wBAAgB,cAAc,CAAC,OAAO,EAAE,WAAW,GAAG,SAAS,GAAG,IAAI,CAErE;AAqED;;;;;;GAMG;AACH,wBAAgB,4BAA4B,CAC1C,IAAI,GAAE;IAAE,WAAW,CAAC,EAAE,eAAe,CAAC;IAAC,UAAU,CAAC,EAAE,OAAO,CAAA;CAAO,GACjE,OAAO,KAAK,CAgFd;AAwED;;;;;;GAMG;AACH,wBAAgB,qBAAqB,CACnC,OAAO,GAAE,MAAkB,EAC3B,OAAO,CAAC,EAAE;IAAE,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAAC,WAAW,CAAC,EAAE,eAAe,CAAA;CAAE,GAC5E,iBAAiB,CAiBnB;AAsDD,wFAAwF;AACxF,wBAAgB,wBAAwB,IAAI,IAAI,CAG/C;AAED;;;;;;;;;;;GAWG;AACH,wBAAsB,sBAAsB,CAC1C,IAAI,GAAE;IAAE,WAAW,CAAC,EAAE,eAAe,CAAA;CAAO,GAC3C,OAAO,CAAC,iBAAiB,EAAE,CAAC,CA2F9B"}
@@ -4,7 +4,7 @@ import { ProviderAuthRequiredError, rejectUnauthorizedResponse } from "../auth/p
4
4
  import { wrapLanguageModel } from "ai";
5
5
  import { createOpenAICompatible } from "@ai-sdk/openai-compatible";
6
6
  import { GoogleSchemaCompatLayer, applyCompatLayer } from "@mastra/schema-compat";
7
- //#region src/providers/github-copilot.ts
7
+ // src/providers/github-copilot.ts
8
8
  /**
9
9
  * GitHub Copilot OAuth Provider
10
10
  *
@@ -18,6 +18,7 @@ import { GoogleSchemaCompatLayer, applyCompatLayer } from "@mastra/schema-compat
18
18
  * - pi-mono: https://github.com/badlogic/pi-mono/blob/main/packages/ai/src/utils/oauth/github-copilot.ts
19
19
  */
20
20
  const COPILOT_PROVIDER_ID = "github-copilot";
21
+ const COPILOT_PROVIDER_NAME = "GitHub Copilot";
21
22
  let authStorageInstance = null;
22
23
  /** Get or create the shared AuthStorage instance. */
23
24
  function getAuthStorage() {
@@ -80,7 +81,7 @@ function buildGitHubCopilotOAuthFetch(opts = {}) {
80
81
  const storage = opts.authStorage ?? getAuthStorage();
81
82
  storage.reload();
82
83
  const cred = storage.get(COPILOT_PROVIDER_ID);
83
- if (!cred || cred.type !== "oauth") throw new ProviderAuthRequiredError("Not logged in to GitHub Copilot.");
84
+ if (!cred || cred.type !== "oauth") throw ProviderAuthRequiredError.notSignedIn(COPILOT_PROVIDER_NAME);
84
85
  let accessToken;
85
86
  let activeCred;
86
87
  if (storage.getOAuthCredential) {
@@ -95,7 +96,7 @@ function buildGitHubCopilotOAuthFetch(opts = {}) {
95
96
  access: accessToken ?? reloaded.access
96
97
  } : void 0;
97
98
  }
98
- if (!accessToken || !activeCred) throw new ProviderAuthRequiredError("Failed to refresh the GitHub Copilot token.");
99
+ if (!accessToken || !activeCred) throw ProviderAuthRequiredError.signInExpired(COPILOT_PROVIDER_NAME);
99
100
  const enterpriseUrl = activeCred.enterpriseUrl;
100
101
  let parsedBody;
101
102
  try {
@@ -128,7 +129,7 @@ function buildGitHubCopilotOAuthFetch(opts = {}) {
128
129
  });
129
130
  try {
130
131
  return await rejectUnauthorizedResponse(await fetch(finalRequest), {
131
- providerName: "GitHub Copilot",
132
+ providerName: COPILOT_PROVIDER_NAME,
132
133
  requestUrl: finalUrl.toString()
133
134
  });
134
135
  } catch (error) {
@@ -316,7 +317,6 @@ async function getCopilotModelCatalog(opts = {}) {
316
317
  if (dedupeKey !== void 0) inflightFetches.set(dedupeKey, fetchPromise);
317
318
  return fetchPromise;
318
319
  }
319
- //#endregion
320
320
  export { buildGitHubCopilotOAuthFetch, clearCopilotCatalogCache, getAuthStorage, getCopilotModelCatalog, githubCopilotProvider, setAuthStorage };
321
321
 
322
322
  //# sourceMappingURL=github-copilot.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"github-copilot.js","names":[],"sources":["../../src/providers/github-copilot.ts"],"sourcesContent":["/**\n * GitHub Copilot OAuth Provider\n *\n * Uses OAuth tokens from AuthStorage to authenticate with GitHub Copilot's chat API.\n * The Copilot API speaks an OpenAI-compatible chat format, so we plug\n * `@ai-sdk/openai-compatible` into Copilot's API URL and use a custom fetch to inject\n * the bearer token and Copilot-specific headers.\n *\n * Inspired by:\n * - opencode: https://github.com/anomalyco/opencode/blob/dev/packages/opencode/src/plugin/github-copilot/copilot.ts\n * - pi-mono: https://github.com/badlogic/pi-mono/blob/main/packages/ai/src/utils/oauth/github-copilot.ts\n */\n\nimport { createOpenAICompatible } from '@ai-sdk/openai-compatible';\nimport type { MastraModelConfig } from '@mastra/core/llm';\nimport type { JSONSchema7 } from '@mastra/schema-compat';\nimport { applyCompatLayer, GoogleSchemaCompatLayer } from '@mastra/schema-compat';\nimport { wrapLanguageModel } from 'ai';\nimport type { LanguageModelMiddleware } from 'ai';\nimport { ProviderAuthRequiredError, rejectUnauthorizedResponse } from '../auth/provider-auth-error.js';\nimport { COPILOT_HEADERS, fetchCopilotModels, getGitHubCopilotBaseUrl } from '../auth/providers/github-copilot.js';\nimport type { CopilotModelEntry, GitHubCopilotCredentials } from '../auth/providers/github-copilot.js';\nimport { AuthStorage } from '../auth/storage.js';\nimport type { CredentialStore, OAuthCredential } from '../auth/types.js';\n\nconst COPILOT_PROVIDER_ID = 'github-copilot';\n\n// Singleton auth storage instance (shared with claude-max.ts / openai-codex.ts when not overridden).\nlet authStorageInstance: AuthStorage | null = null;\n\n/** Get or create the shared AuthStorage instance. */\nexport function getAuthStorage(): AuthStorage {\n if (!authStorageInstance) {\n authStorageInstance = new AuthStorage();\n }\n return authStorageInstance;\n}\n\n/** Set a custom AuthStorage instance (useful for tests / TUI integration). */\nexport function setAuthStorage(storage: AuthStorage | undefined): void {\n authStorageInstance = storage ?? null;\n}\n\n/**\n * Heuristic: did this request come from the agent (e.g. tool result follow-ups) rather\n * than a fresh user turn? Mirrors opencode's `isAgent` logic — Copilot bills these\n * differently via the `x-initiator` header.\n */\nfunction detectIsAgent(body: unknown): boolean {\n if (!body || typeof body !== 'object') return false;\n const obj = body as Record<string, unknown>;\n\n const messages = obj.messages;\n if (Array.isArray(messages) && messages.length > 0) {\n const last = messages[messages.length - 1] as { role?: string; content?: unknown };\n if (last?.role && last.role !== 'user') return true;\n if (Array.isArray(last?.content)) {\n // If the last user turn carries any tool_result parts, treat it as an agent turn.\n const hasToolResult = last.content.some(\n (part: unknown) => part && typeof part === 'object' && (part as { type?: string }).type === 'tool_result',\n );\n if (hasToolResult) return true;\n }\n }\n\n const input = obj.input;\n if (Array.isArray(input) && input.length > 0) {\n const last = input[input.length - 1] as { role?: string };\n if (last?.role && last.role !== 'user') return true;\n }\n\n return false;\n}\n\n/** Detect image/vision content in a request body. */\nfunction detectIsVision(body: unknown): boolean {\n if (!body || typeof body !== 'object') return false;\n const obj = body as Record<string, unknown>;\n\n const matchPart = (part: unknown): boolean => {\n if (!part || typeof part !== 'object') return false;\n const t = (part as { type?: string }).type;\n return t === 'image' || t === 'image_url' || t === 'input_image';\n };\n\n const messages = obj.messages;\n if (Array.isArray(messages)) {\n return messages.some(\n (msg: unknown) =>\n msg &&\n typeof msg === 'object' &&\n Array.isArray((msg as { content?: unknown }).content) &&\n ((msg as { content: unknown[] }).content as unknown[]).some(matchPart),\n );\n }\n\n const input = obj.input;\n if (Array.isArray(input)) {\n return input.some(\n (item: unknown) =>\n item &&\n typeof item === 'object' &&\n Array.isArray((item as { content?: unknown }).content) &&\n ((item as { content: unknown[] }).content as unknown[]).some(matchPart),\n );\n }\n\n return false;\n}\n\n/**\n * Build a fetch wrapper that authenticates with GitHub Copilot OAuth.\n *\n * - Injects the short-lived Copilot bearer token (auto-refreshed by AuthStorage).\n * - Adds the VS Code-like Copilot headers required by the API.\n * - Rewrites the request URL onto the per-token API base when `rewriteUrl` is true.\n */\nexport function buildGitHubCopilotOAuthFetch(\n opts: { authStorage?: CredentialStore; rewriteUrl?: boolean } = {},\n): typeof fetch {\n return (async (url: string | URL | Request, init?: Parameters<typeof fetch>[1]) => {\n const { headers: initHeaders, ...requestInit } = init ?? {};\n const request = new Request(url, requestInit);\n const storage = opts.authStorage ?? getAuthStorage();\n storage.reload();\n\n const cred = storage.get(COPILOT_PROVIDER_ID);\n if (!cred || cred.type !== 'oauth') {\n throw new ProviderAuthRequiredError('Not logged in to GitHub Copilot.');\n }\n\n let accessToken: string | undefined;\n let activeCred: OAuthCredential | undefined;\n if (storage.getOAuthCredential) {\n activeCred = await storage.getOAuthCredential(COPILOT_PROVIDER_ID);\n accessToken = activeCred?.access;\n } else {\n accessToken = await storage.getApiKey(COPILOT_PROVIDER_ID);\n storage.reload();\n const reloaded = storage.get(COPILOT_PROVIDER_ID);\n activeCred = reloaded?.type === 'oauth' ? { ...reloaded, access: accessToken ?? reloaded.access } : undefined;\n }\n if (!accessToken || !activeCred) {\n throw new ProviderAuthRequiredError('Failed to refresh the GitHub Copilot token.');\n }\n const enterpriseUrl = (activeCred as GitHubCopilotCredentials).enterpriseUrl;\n\n let parsedBody: unknown;\n try {\n const body = await request.clone().text();\n parsedBody = body ? JSON.parse(body) : undefined;\n } catch {\n parsedBody = undefined;\n }\n const isAgent = detectIsAgent(parsedBody);\n const isVision = detectIsVision(parsedBody);\n\n const headers = new Headers(url instanceof Request ? url.headers : undefined);\n if (initHeaders) new Headers(initHeaders).forEach((value, key) => headers.set(key, value));\n headers.delete('authorization');\n headers.delete('x-api-key');\n headers.set('Authorization', `Bearer ${accessToken}`);\n headers.set('x-initiator', isAgent ? 'agent' : 'user');\n headers.set('Openai-Intent', 'conversation-edits');\n if (isVision) {\n headers.set('Copilot-Vision-Request', 'true');\n }\n for (const [key, value] of Object.entries(COPILOT_HEADERS)) {\n // Only set if caller didn't already provide it (allow overrides for tests).\n if (!headers.has(key)) {\n headers.set(key, value);\n }\n }\n\n const finalUrl =\n opts.rewriteUrl !== false ? rewriteToCopilotBase(request, accessToken, enterpriseUrl) : new URL(request.url);\n\n const body = request.method === 'GET' || request.method === 'HEAD' ? undefined : request.body;\n const finalRequest = new Request(finalUrl, {\n method: request.method,\n headers,\n body,\n signal: request.signal,\n redirect: request.redirect,\n integrity: request.integrity,\n ...(body ? ({ duplex: 'half' } as RequestInit) : {}),\n });\n try {\n return await rejectUnauthorizedResponse(await fetch(finalRequest), {\n providerName: 'GitHub Copilot',\n requestUrl: finalUrl.toString(),\n });\n } catch (error) {\n if (error && typeof error === 'object') {\n Object.assign(error as Record<string, unknown>, {\n requestUrl: finalUrl.toString(),\n });\n }\n throw error;\n }\n }) as typeof fetch;\n}\n\nfunction rewriteToCopilotBase(url: string | URL | Request, token: string, enterpriseDomain?: string): URL {\n const original = url instanceof URL ? url : new URL(typeof url === 'string' ? url : (url as Request).url);\n const base = new URL(getGitHubCopilotBaseUrl(token, enterpriseDomain));\n // Copilot's OpenAI-compatible API serves endpoints at the root of the base host\n // (`/chat/completions`, `/responses`, `/models`, ...) — not under a `/v1/` prefix\n // like api.openai.com does. The @ai-sdk/openai default baseURL is\n // `https://api.openai.com/v1`, so the SDK builds requests like\n // `https://api.openai.com/v1/chat/completions`. Strip the leading `/v1` segment\n // when rewriting onto the Copilot base or Copilot will return 404 Not Found.\n const pathname = original.pathname.replace(/^\\/v1(\\/|$)/, '/');\n return new URL(`${pathname}${original.search}`, base);\n}\n\nfunction isGeminiModel(modelId: string): boolean {\n return modelId.startsWith('gemini-');\n}\n\nfunction applyGeminiSchemaCompatToTools(modelId: string, tools: unknown): unknown {\n if (!Array.isArray(tools)) {\n return tools;\n }\n\n const compatLayer = new GoogleSchemaCompatLayer({\n provider: COPILOT_PROVIDER_ID,\n modelId,\n supportsStructuredOutputs: false,\n });\n\n return tools.map(tool => {\n if (!tool || typeof tool !== 'object' || (tool as { type?: unknown }).type !== 'function') {\n return tool;\n }\n\n const functionTool = tool as { inputSchema?: JSONSchema7 };\n if (!functionTool.inputSchema) {\n return tool;\n }\n\n return {\n ...functionTool,\n inputSchema: applyCompatLayer({\n schema: functionTool.inputSchema,\n compatLayers: [compatLayer],\n mode: 'aiSdkSchema',\n }).jsonSchema as JSONSchema7,\n };\n });\n}\n\n/** Middleware that prevents sending parameters Copilot's endpoint rejects. */\nfunction createCopilotMiddleware(modelId: string): LanguageModelMiddleware {\n return {\n specificationVersion: 'v3',\n transformParams: async ({ params }) => {\n if (params.temperature !== undefined && params.temperature !== null) {\n delete params.topP;\n }\n\n if (isGeminiModel(modelId)) {\n (params as { tools?: unknown }).tools = applyGeminiSchemaCompatToTools(\n modelId,\n (params as { tools?: unknown }).tools,\n );\n }\n\n return params;\n },\n };\n}\n\n/**\n * Creates a model that talks to GitHub Copilot using OAuth credentials.\n *\n * Copilot's `/chat/completions` endpoint is OpenAI-compatible, but GitHub Copilot\n * is not OpenAI. Use the generic OpenAI-compatible adapter with Copilot's base URL\n * instead of the OpenAI provider plus URL rewriting.\n */\nexport function githubCopilotProvider(\n modelId: string = 'gpt-4.1',\n options?: { headers?: Record<string, string>; authStorage?: CredentialStore },\n): MastraModelConfig {\n const headers = options?.headers;\n const copilot = createOpenAICompatible({\n name: COPILOT_PROVIDER_ID,\n baseURL: 'https://api.githubcopilot.com',\n apiKey: process.env.NODE_ENV === 'test' || process.env.VITEST ? 'test-api-key' : 'oauth-placeholder',\n headers,\n fetch:\n process.env.NODE_ENV === 'test' || process.env.VITEST\n ? undefined\n : (buildGitHubCopilotOAuthFetch({ rewriteUrl: false, authStorage: options?.authStorage }) as any),\n });\n\n return wrapLanguageModel({\n model: copilot.chatModel(modelId),\n middleware: [createCopilotMiddleware(modelId)],\n });\n}\n\n// ---------------------------------------------------------------------------\n// Live model catalog\n// ---------------------------------------------------------------------------\n\n/**\n * Hard-coded fallback advertised when the live `/models` request fails (network\n * down, expired token, etc.). Keep this conservative because the live catalog is\n * the source of truth for the user's currently-enabled Copilot models.\n *\n * Available across all paid Copilot tiers and free of premium-request charges.\n */\nconst COPILOT_FALLBACK_MODELS: CopilotModelEntry[] = [\n {\n id: 'gpt-4.1',\n name: 'GPT-4.1',\n vendor: 'OpenAI',\n supportedEndpoints: ['/chat/completions'],\n isAnthropicShaped: false,\n supportsVision: true,\n supportsToolCalls: true,\n },\n];\n\nconst CATALOG_TTL_MS = 10 * 60 * 1000;\nconst CATALOG_FAILURE_TTL_MS = 60 * 1000;\nconst CATALOG_FETCH_TIMEOUT_MS = 5_000;\n\ninterface CatalogCacheEntry {\n fetchedAt: number;\n ttl: number;\n models: CopilotModelEntry[];\n}\n\nconst catalogCache = new Map<string, CatalogCacheEntry>();\nconst inflightFetches = new Map<string, Promise<CopilotModelEntry[]>>();\n\n/**\n * Resolve the account identity for a credential read through `getApiKey`, which\n * may await a refresh with a rotation landing inside it. The registry is\n * consulted on both sides of that await, and only an id that survived it names\n * the account that produced the token: an id that moved describes whichever\n * account is active *now*, so trusting it would file this fetch's models under\n * the wrong account and serve them to it. Unidentified is the safe answer — the\n * caller then skips the TTL cache, exactly as it does when the store exposes no\n * registry at all. (`AuthStorage` never needs this: its snapshots name their\n * account.)\n */\nfunction readStableAccountId(storage: CredentialStore, idBeforeToken: string | undefined): string | undefined {\n const idAfterToken = storage.getActiveAccount?.(COPILOT_PROVIDER_ID)?.id;\n return idBeforeToken !== undefined && idBeforeToken === idAfterToken ? idAfterToken : undefined;\n}\n\n/** Reset the in-process Copilot catalog cache (test seam, also useful after logout). */\nexport function clearCopilotCatalogCache(): void {\n catalogCache.clear();\n inflightFetches.clear();\n}\n\n/**\n * Return the user's currently-available Copilot models.\n *\n * - Returns `[]` when the user is not logged in to GitHub Copilot.\n * - Returns the cached list when a recent fetch succeeded.\n * - On the cache-miss / expired path, fetches `/models` with a 5s timeout, filters\n * to picker-enabled and non-policy-disabled models, then caches for 10 minutes.\n * - On fetch failure, returns a small hard-coded fallback (so packs still work\n * offline) and caches that for 1 minute to avoid hammering the API.\n *\n * Concurrent calls during a fetch share the inflight promise.\n */\nexport async function getCopilotModelCatalog(\n opts: { authStorage?: CredentialStore } = {},\n): Promise<CopilotModelEntry[]> {\n const storage = opts.authStorage ?? getAuthStorage();\n\n // Resolve one coherent credential snapshot before consulting the cache so a\n // token can never be paired with another account's enterprise endpoint.\n // `getOAuthCredential` is optional (deployed stores have no local registry),\n // so fall back to the always-present `getApiKey`, taking any enterprise\n // endpoint from the same slot via `get()`.\n let accessToken: string | undefined;\n let accountInstanceId: string | undefined;\n let enterpriseUrl: string | undefined;\n if (storage.getOAuthCredential) {\n const credential = await storage.getOAuthCredential(COPILOT_PROVIDER_ID);\n if (!credential || credential.type !== 'oauth') return [];\n accessToken = credential.access;\n // A snapshot that names its account is coherent by construction — the store\n // read the identity and the token in the same breath. One that does not\n // cannot be attributed to a registry entry we then read afterwards, because\n // a rotation may have landed in between; leave it unnamed so the caller\n // skips the TTL cache instead of guessing. (`AuthStorage` always stamps.)\n accountInstanceId = credential.accountInstanceId;\n enterpriseUrl = (credential as GitHubCopilotCredentials).enterpriseUrl;\n } else {\n // This store republishes its registry but not the OAuth snapshot API, so the\n // identity has to come from the registry. `getApiKey` may await a refresh and\n // a rotation can land inside it, so bracket the fetch: only an id that held\n // still names the account that produced this token.\n const idBeforeToken = storage.getActiveAccount?.(COPILOT_PROVIDER_ID)?.id;\n accessToken = await storage.getApiKey(COPILOT_PROVIDER_ID);\n if (!accessToken) return [];\n accountInstanceId = readStableAccountId(storage, idBeforeToken);\n const stored = storage.get(COPILOT_PROVIDER_ID);\n if (stored?.type === 'oauth') {\n enterpriseUrl = (stored as GitHubCopilotCredentials).enterpriseUrl;\n }\n // The id is non-secret, and keying per account is what keeps entitlements\n // (per account, per `github-copilot-catalog.test.ts`) from leaking across a\n // rotation. Deriving the key from the token is what `cba11389e7` removed.\n }\n const baseUrl = getGitHubCopilotBaseUrl(accessToken, enterpriseUrl);\n // No identity means the store cannot name the account it just served, so the\n // TTL cache cannot be keyed per account — one entry would outlive the request\n // and serve those models to every other account of the store. The in-flight\n // map is no safer: two callers that resolved *different* accounts of an\n // unnamed store would otherwise collide on one key and share whichever\n // catalog was fetched first. So both caches are identified-only, and an\n // unnamed store pays one `/models` request per call.\n const credentialKey = accountInstanceId === undefined ? undefined : `${accountInstanceId}\\0${baseUrl}`;\n const dedupeKey = credentialKey;\n\n const now = Date.now();\n const cached = credentialKey ? catalogCache.get(credentialKey) : undefined;\n if (cached && now - cached.fetchedAt < cached.ttl) return cached.models;\n\n const existingFetch = dedupeKey === undefined ? undefined : inflightFetches.get(dedupeKey);\n if (existingFetch) return existingFetch;\n\n const fetchPromise = (async (): Promise<CopilotModelEntry[]> => {\n try {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), CATALOG_FETCH_TIMEOUT_MS);\n try {\n const models = await fetchCopilotModels({\n baseUrl,\n bearerToken: accessToken,\n signal: controller.signal,\n });\n if (credentialKey) catalogCache.set(credentialKey, { fetchedAt: Date.now(), ttl: CATALOG_TTL_MS, models });\n return models;\n } finally {\n clearTimeout(timer);\n }\n } catch (error) {\n if (credentialKey) {\n catalogCache.set(credentialKey, {\n fetchedAt: Date.now(),\n ttl: CATALOG_FAILURE_TTL_MS,\n models: COPILOT_FALLBACK_MODELS,\n });\n }\n console.warn(\n 'Failed to fetch live GitHub Copilot models, using fallback list:',\n error instanceof Error ? error.message : error,\n );\n return COPILOT_FALLBACK_MODELS;\n } finally {\n if (dedupeKey !== undefined) inflightFetches.delete(dedupeKey);\n }\n })();\n if (dedupeKey !== undefined) inflightFetches.set(dedupeKey, fetchPromise);\n return fetchPromise;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAyBA,MAA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,gBAAgB,sBAAsB,KAAA,IAAY,KAAA,IAAY,GAAG,kBAAkB,IAAI;CAC7F,MAAM,YAAY;CAElB,MAAM,MAAM,KAAK,IAAI;CACrB,MAAM,SAAS,gBAAgB,aAAa,IAAI,aAAa,IAAI,KAAA;CACjE,IAAI,UAAU,MAAM,OAAO,YAAY,OAAO,KAAK,OAAO,OAAO;CAEjE,MAAM,gBAAgB,cAAc,KAAA,IAAY,KAAA,IAAY,gBAAgB,IAAI,SAAS;CACzF,IAAI,eAAe,OAAO;CAE1B,MAAM,gBAAgB,YAA0C;EAC9D,IAAI;GACF,MAAM,aAAa,IAAI,gBAAgB;GACvC,MAAM,QAAQ,iBAAiB,WAAW,MAAM,GAAG,wBAAwB;GAC3E,IAAI;IACF,MAAM,SAAS,MAAM,mBAAmB;KACtC;KACA,aAAa;KACb,QAAQ,WAAW;IACrB,CAAC;IACD,IAAI,eAAe,aAAa,IAAI,eAAe;KAAE,WAAW,KAAK,IAAI;KAAG,KAAK;KAAgB;IAAO,CAAC;IACzG,OAAO;GACT,UAAU;IACR,aAAa,KAAK;GACpB;EACF,SAAS,OAAO;GACd,IAAI,eACF,aAAa,IAAI,eAAe;IAC9B,WAAW,KAAK,IAAI;IACpB,KAAK;IACL,QAAQ;GACV,CAAC;GAEH,QAAQ,KACN,oEACA,iBAAiB,QAAQ,MAAM,UAAU,KAC3C;GACA,OAAO;EACT,UAAU;GACR,IAAI,cAAc,KAAA,GAAW,gBAAgB,OAAO,SAAS;EAC/D;CACF,EAAA,CAAG;CACH,IAAI,cAAc,KAAA,GAAW,gBAAgB,IAAI,WAAW,YAAY;CACxE,OAAO;AACT"}
1
+ {"version":3,"file":"github-copilot.js","names":[],"sources":["../../src/providers/github-copilot.ts"],"sourcesContent":["/**\n * GitHub Copilot OAuth Provider\n *\n * Uses OAuth tokens from AuthStorage to authenticate with GitHub Copilot's chat API.\n * The Copilot API speaks an OpenAI-compatible chat format, so we plug\n * `@ai-sdk/openai-compatible` into Copilot's API URL and use a custom fetch to inject\n * the bearer token and Copilot-specific headers.\n *\n * Inspired by:\n * - opencode: https://github.com/anomalyco/opencode/blob/dev/packages/opencode/src/plugin/github-copilot/copilot.ts\n * - pi-mono: https://github.com/badlogic/pi-mono/blob/main/packages/ai/src/utils/oauth/github-copilot.ts\n */\n\nimport { createOpenAICompatible } from '@ai-sdk/openai-compatible';\nimport type { MastraModelConfig } from '@mastra/core/llm';\nimport type { JSONSchema7 } from '@mastra/schema-compat';\nimport { applyCompatLayer, GoogleSchemaCompatLayer } from '@mastra/schema-compat';\nimport { wrapLanguageModel } from 'ai';\nimport type { LanguageModelMiddleware } from 'ai';\nimport { ProviderAuthRequiredError, rejectUnauthorizedResponse } from '../auth/provider-auth-error.js';\nimport { COPILOT_HEADERS, fetchCopilotModels, getGitHubCopilotBaseUrl } from '../auth/providers/github-copilot.js';\nimport type { CopilotModelEntry, GitHubCopilotCredentials } from '../auth/providers/github-copilot.js';\nimport { AuthStorage } from '../auth/storage.js';\nimport type { CredentialStore, OAuthCredential } from '../auth/types.js';\n\nconst COPILOT_PROVIDER_ID = 'github-copilot';\nconst COPILOT_PROVIDER_NAME = 'GitHub Copilot';\n\n// Singleton auth storage instance (shared with claude-max.ts / openai-codex.ts when not overridden).\nlet authStorageInstance: AuthStorage | null = null;\n\n/** Get or create the shared AuthStorage instance. */\nexport function getAuthStorage(): AuthStorage {\n if (!authStorageInstance) {\n authStorageInstance = new AuthStorage();\n }\n return authStorageInstance;\n}\n\n/** Set a custom AuthStorage instance (useful for tests / TUI integration). */\nexport function setAuthStorage(storage: AuthStorage | undefined): void {\n authStorageInstance = storage ?? null;\n}\n\n/**\n * Heuristic: did this request come from the agent (e.g. tool result follow-ups) rather\n * than a fresh user turn? Mirrors opencode's `isAgent` logic — Copilot bills these\n * differently via the `x-initiator` header.\n */\nfunction detectIsAgent(body: unknown): boolean {\n if (!body || typeof body !== 'object') return false;\n const obj = body as Record<string, unknown>;\n\n const messages = obj.messages;\n if (Array.isArray(messages) && messages.length > 0) {\n const last = messages[messages.length - 1] as { role?: string; content?: unknown };\n if (last?.role && last.role !== 'user') return true;\n if (Array.isArray(last?.content)) {\n // If the last user turn carries any tool_result parts, treat it as an agent turn.\n const hasToolResult = last.content.some(\n (part: unknown) => part && typeof part === 'object' && (part as { type?: string }).type === 'tool_result',\n );\n if (hasToolResult) return true;\n }\n }\n\n const input = obj.input;\n if (Array.isArray(input) && input.length > 0) {\n const last = input[input.length - 1] as { role?: string };\n if (last?.role && last.role !== 'user') return true;\n }\n\n return false;\n}\n\n/** Detect image/vision content in a request body. */\nfunction detectIsVision(body: unknown): boolean {\n if (!body || typeof body !== 'object') return false;\n const obj = body as Record<string, unknown>;\n\n const matchPart = (part: unknown): boolean => {\n if (!part || typeof part !== 'object') return false;\n const t = (part as { type?: string }).type;\n return t === 'image' || t === 'image_url' || t === 'input_image';\n };\n\n const messages = obj.messages;\n if (Array.isArray(messages)) {\n return messages.some(\n (msg: unknown) =>\n msg &&\n typeof msg === 'object' &&\n Array.isArray((msg as { content?: unknown }).content) &&\n ((msg as { content: unknown[] }).content as unknown[]).some(matchPart),\n );\n }\n\n const input = obj.input;\n if (Array.isArray(input)) {\n return input.some(\n (item: unknown) =>\n item &&\n typeof item === 'object' &&\n Array.isArray((item as { content?: unknown }).content) &&\n ((item as { content: unknown[] }).content as unknown[]).some(matchPart),\n );\n }\n\n return false;\n}\n\n/**\n * Build a fetch wrapper that authenticates with GitHub Copilot OAuth.\n *\n * - Injects the short-lived Copilot bearer token (auto-refreshed by AuthStorage).\n * - Adds the VS Code-like Copilot headers required by the API.\n * - Rewrites the request URL onto the per-token API base when `rewriteUrl` is true.\n */\nexport function buildGitHubCopilotOAuthFetch(\n opts: { authStorage?: CredentialStore; rewriteUrl?: boolean } = {},\n): typeof fetch {\n return (async (url: string | URL | Request, init?: Parameters<typeof fetch>[1]) => {\n const { headers: initHeaders, ...requestInit } = init ?? {};\n const request = new Request(url, requestInit);\n const storage = opts.authStorage ?? getAuthStorage();\n storage.reload();\n\n const cred = storage.get(COPILOT_PROVIDER_ID);\n if (!cred || cred.type !== 'oauth') {\n throw ProviderAuthRequiredError.notSignedIn(COPILOT_PROVIDER_NAME);\n }\n\n let accessToken: string | undefined;\n let activeCred: OAuthCredential | undefined;\n if (storage.getOAuthCredential) {\n activeCred = await storage.getOAuthCredential(COPILOT_PROVIDER_ID);\n accessToken = activeCred?.access;\n } else {\n accessToken = await storage.getApiKey(COPILOT_PROVIDER_ID);\n storage.reload();\n const reloaded = storage.get(COPILOT_PROVIDER_ID);\n activeCred = reloaded?.type === 'oauth' ? { ...reloaded, access: accessToken ?? reloaded.access } : undefined;\n }\n if (!accessToken || !activeCred) throw ProviderAuthRequiredError.signInExpired(COPILOT_PROVIDER_NAME);\n const enterpriseUrl = (activeCred as GitHubCopilotCredentials).enterpriseUrl;\n\n let parsedBody: unknown;\n try {\n const body = await request.clone().text();\n parsedBody = body ? JSON.parse(body) : undefined;\n } catch {\n parsedBody = undefined;\n }\n const isAgent = detectIsAgent(parsedBody);\n const isVision = detectIsVision(parsedBody);\n\n const headers = new Headers(url instanceof Request ? url.headers : undefined);\n if (initHeaders) new Headers(initHeaders).forEach((value, key) => headers.set(key, value));\n headers.delete('authorization');\n headers.delete('x-api-key');\n headers.set('Authorization', `Bearer ${accessToken}`);\n headers.set('x-initiator', isAgent ? 'agent' : 'user');\n headers.set('Openai-Intent', 'conversation-edits');\n if (isVision) {\n headers.set('Copilot-Vision-Request', 'true');\n }\n for (const [key, value] of Object.entries(COPILOT_HEADERS)) {\n // Only set if caller didn't already provide it (allow overrides for tests).\n if (!headers.has(key)) {\n headers.set(key, value);\n }\n }\n\n const finalUrl =\n opts.rewriteUrl !== false ? rewriteToCopilotBase(request, accessToken, enterpriseUrl) : new URL(request.url);\n\n const body = request.method === 'GET' || request.method === 'HEAD' ? undefined : request.body;\n const finalRequest = new Request(finalUrl, {\n method: request.method,\n headers,\n body,\n signal: request.signal,\n redirect: request.redirect,\n integrity: request.integrity,\n ...(body ? ({ duplex: 'half' } as RequestInit) : {}),\n });\n try {\n return await rejectUnauthorizedResponse(await fetch(finalRequest), {\n providerName: COPILOT_PROVIDER_NAME,\n requestUrl: finalUrl.toString(),\n });\n } catch (error) {\n if (error && typeof error === 'object') {\n Object.assign(error as Record<string, unknown>, {\n requestUrl: finalUrl.toString(),\n });\n }\n throw error;\n }\n }) as typeof fetch;\n}\n\nfunction rewriteToCopilotBase(url: string | URL | Request, token: string, enterpriseDomain?: string): URL {\n const original = url instanceof URL ? url : new URL(typeof url === 'string' ? url : (url as Request).url);\n const base = new URL(getGitHubCopilotBaseUrl(token, enterpriseDomain));\n // Copilot's OpenAI-compatible API serves endpoints at the root of the base host\n // (`/chat/completions`, `/responses`, `/models`, ...) — not under a `/v1/` prefix\n // like api.openai.com does. The @ai-sdk/openai default baseURL is\n // `https://api.openai.com/v1`, so the SDK builds requests like\n // `https://api.openai.com/v1/chat/completions`. Strip the leading `/v1` segment\n // when rewriting onto the Copilot base or Copilot will return 404 Not Found.\n const pathname = original.pathname.replace(/^\\/v1(\\/|$)/, '/');\n return new URL(`${pathname}${original.search}`, base);\n}\n\nfunction isGeminiModel(modelId: string): boolean {\n return modelId.startsWith('gemini-');\n}\n\nfunction applyGeminiSchemaCompatToTools(modelId: string, tools: unknown): unknown {\n if (!Array.isArray(tools)) {\n return tools;\n }\n\n const compatLayer = new GoogleSchemaCompatLayer({\n provider: COPILOT_PROVIDER_ID,\n modelId,\n supportsStructuredOutputs: false,\n });\n\n return tools.map(tool => {\n if (!tool || typeof tool !== 'object' || (tool as { type?: unknown }).type !== 'function') {\n return tool;\n }\n\n const functionTool = tool as { inputSchema?: JSONSchema7 };\n if (!functionTool.inputSchema) {\n return tool;\n }\n\n return {\n ...functionTool,\n inputSchema: applyCompatLayer({\n schema: functionTool.inputSchema,\n compatLayers: [compatLayer],\n mode: 'aiSdkSchema',\n }).jsonSchema as JSONSchema7,\n };\n });\n}\n\n/** Middleware that prevents sending parameters Copilot's endpoint rejects. */\nfunction createCopilotMiddleware(modelId: string): LanguageModelMiddleware {\n return {\n specificationVersion: 'v3',\n transformParams: async ({ params }) => {\n if (params.temperature !== undefined && params.temperature !== null) {\n delete params.topP;\n }\n\n if (isGeminiModel(modelId)) {\n (params as { tools?: unknown }).tools = applyGeminiSchemaCompatToTools(\n modelId,\n (params as { tools?: unknown }).tools,\n );\n }\n\n return params;\n },\n };\n}\n\n/**\n * Creates a model that talks to GitHub Copilot using OAuth credentials.\n *\n * Copilot's `/chat/completions` endpoint is OpenAI-compatible, but GitHub Copilot\n * is not OpenAI. Use the generic OpenAI-compatible adapter with Copilot's base URL\n * instead of the OpenAI provider plus URL rewriting.\n */\nexport function githubCopilotProvider(\n modelId: string = 'gpt-4.1',\n options?: { headers?: Record<string, string>; authStorage?: CredentialStore },\n): MastraModelConfig {\n const headers = options?.headers;\n const copilot = createOpenAICompatible({\n name: COPILOT_PROVIDER_ID,\n baseURL: 'https://api.githubcopilot.com',\n apiKey: process.env.NODE_ENV === 'test' || process.env.VITEST ? 'test-api-key' : 'oauth-placeholder',\n headers,\n fetch:\n process.env.NODE_ENV === 'test' || process.env.VITEST\n ? undefined\n : (buildGitHubCopilotOAuthFetch({ rewriteUrl: false, authStorage: options?.authStorage }) as any),\n });\n\n return wrapLanguageModel({\n model: copilot.chatModel(modelId),\n middleware: [createCopilotMiddleware(modelId)],\n });\n}\n\n// ---------------------------------------------------------------------------\n// Live model catalog\n// ---------------------------------------------------------------------------\n\n/**\n * Hard-coded fallback advertised when the live `/models` request fails (network\n * down, expired token, etc.). Keep this conservative because the live catalog is\n * the source of truth for the user's currently-enabled Copilot models.\n *\n * Available across all paid Copilot tiers and free of premium-request charges.\n */\nconst COPILOT_FALLBACK_MODELS: CopilotModelEntry[] = [\n {\n id: 'gpt-4.1',\n name: 'GPT-4.1',\n vendor: 'OpenAI',\n supportedEndpoints: ['/chat/completions'],\n isAnthropicShaped: false,\n supportsVision: true,\n supportsToolCalls: true,\n },\n];\n\nconst CATALOG_TTL_MS = 10 * 60 * 1000;\nconst CATALOG_FAILURE_TTL_MS = 60 * 1000;\nconst CATALOG_FETCH_TIMEOUT_MS = 5_000;\n\ninterface CatalogCacheEntry {\n fetchedAt: number;\n ttl: number;\n models: CopilotModelEntry[];\n}\n\nconst catalogCache = new Map<string, CatalogCacheEntry>();\nconst inflightFetches = new Map<string, Promise<CopilotModelEntry[]>>();\n\n/**\n * Resolve the account identity for a credential read through `getApiKey`, which\n * may await a refresh with a rotation landing inside it. The registry is\n * consulted on both sides of that await, and only an id that survived it names\n * the account that produced the token: an id that moved describes whichever\n * account is active *now*, so trusting it would file this fetch's models under\n * the wrong account and serve them to it. Unidentified is the safe answer — the\n * caller then skips the TTL cache, exactly as it does when the store exposes no\n * registry at all. (`AuthStorage` never needs this: its snapshots name their\n * account.)\n */\nfunction readStableAccountId(storage: CredentialStore, idBeforeToken: string | undefined): string | undefined {\n const idAfterToken = storage.getActiveAccount?.(COPILOT_PROVIDER_ID)?.id;\n return idBeforeToken !== undefined && idBeforeToken === idAfterToken ? idAfterToken : undefined;\n}\n\n/** Reset the in-process Copilot catalog cache (test seam, also useful after logout). */\nexport function clearCopilotCatalogCache(): void {\n catalogCache.clear();\n inflightFetches.clear();\n}\n\n/**\n * Return the user's currently-available Copilot models.\n *\n * - Returns `[]` when the user is not logged in to GitHub Copilot.\n * - Returns the cached list when a recent fetch succeeded.\n * - On the cache-miss / expired path, fetches `/models` with a 5s timeout, filters\n * to picker-enabled and non-policy-disabled models, then caches for 10 minutes.\n * - On fetch failure, returns a small hard-coded fallback (so packs still work\n * offline) and caches that for 1 minute to avoid hammering the API.\n *\n * Concurrent calls during a fetch share the inflight promise.\n */\nexport async function getCopilotModelCatalog(\n opts: { authStorage?: CredentialStore } = {},\n): Promise<CopilotModelEntry[]> {\n const storage = opts.authStorage ?? getAuthStorage();\n\n // Resolve one coherent credential snapshot before consulting the cache so a\n // token can never be paired with another account's enterprise endpoint.\n // `getOAuthCredential` is optional (deployed stores have no local registry),\n // so fall back to the always-present `getApiKey`, taking any enterprise\n // endpoint from the same slot via `get()`.\n let accessToken: string | undefined;\n let accountInstanceId: string | undefined;\n let enterpriseUrl: string | undefined;\n if (storage.getOAuthCredential) {\n const credential = await storage.getOAuthCredential(COPILOT_PROVIDER_ID);\n if (!credential || credential.type !== 'oauth') return [];\n accessToken = credential.access;\n // A snapshot that names its account is coherent by construction — the store\n // read the identity and the token in the same breath. One that does not\n // cannot be attributed to a registry entry we then read afterwards, because\n // a rotation may have landed in between; leave it unnamed so the caller\n // skips the TTL cache instead of guessing. (`AuthStorage` always stamps.)\n accountInstanceId = credential.accountInstanceId;\n enterpriseUrl = (credential as GitHubCopilotCredentials).enterpriseUrl;\n } else {\n // This store republishes its registry but not the OAuth snapshot API, so the\n // identity has to come from the registry. `getApiKey` may await a refresh and\n // a rotation can land inside it, so bracket the fetch: only an id that held\n // still names the account that produced this token.\n const idBeforeToken = storage.getActiveAccount?.(COPILOT_PROVIDER_ID)?.id;\n accessToken = await storage.getApiKey(COPILOT_PROVIDER_ID);\n if (!accessToken) return [];\n accountInstanceId = readStableAccountId(storage, idBeforeToken);\n const stored = storage.get(COPILOT_PROVIDER_ID);\n if (stored?.type === 'oauth') {\n enterpriseUrl = (stored as GitHubCopilotCredentials).enterpriseUrl;\n }\n // The id is non-secret, and keying per account is what keeps entitlements\n // (per account, per `github-copilot-catalog.test.ts`) from leaking across a\n // rotation. Deriving the key from the token is what `cba11389e7` removed.\n }\n const baseUrl = getGitHubCopilotBaseUrl(accessToken, enterpriseUrl);\n // No identity means the store cannot name the account it just served, so the\n // TTL cache cannot be keyed per account — one entry would outlive the request\n // and serve those models to every other account of the store. The in-flight\n // map is no safer: two callers that resolved *different* accounts of an\n // unnamed store would otherwise collide on one key and share whichever\n // catalog was fetched first. So both caches are identified-only, and an\n // unnamed store pays one `/models` request per call.\n const credentialKey = accountInstanceId === undefined ? undefined : `${accountInstanceId}\\0${baseUrl}`;\n const dedupeKey = credentialKey;\n\n const now = Date.now();\n const cached = credentialKey ? catalogCache.get(credentialKey) : undefined;\n if (cached && now - cached.fetchedAt < cached.ttl) return cached.models;\n\n const existingFetch = dedupeKey === undefined ? undefined : inflightFetches.get(dedupeKey);\n if (existingFetch) return existingFetch;\n\n const fetchPromise = (async (): Promise<CopilotModelEntry[]> => {\n try {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), CATALOG_FETCH_TIMEOUT_MS);\n try {\n const models = await fetchCopilotModels({\n baseUrl,\n bearerToken: accessToken,\n signal: controller.signal,\n });\n if (credentialKey) catalogCache.set(credentialKey, { fetchedAt: Date.now(), ttl: CATALOG_TTL_MS, models });\n return models;\n } finally {\n clearTimeout(timer);\n }\n } catch (error) {\n if (credentialKey) {\n catalogCache.set(credentialKey, {\n fetchedAt: Date.now(),\n ttl: CATALOG_FAILURE_TTL_MS,\n models: COPILOT_FALLBACK_MODELS,\n });\n }\n console.warn(\n 'Failed to fetch live GitHub Copilot models, using fallback list:',\n error instanceof Error ? error.message : error,\n );\n return COPILOT_FALLBACK_MODELS;\n } finally {\n if (dedupeKey !== undefined) inflightFetches.delete(dedupeKey);\n }\n })();\n if (dedupeKey !== undefined) inflightFetches.set(dedupeKey, fetchPromise);\n return fetchPromise;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAyBA,MAAM,sBAAsB;AAC5B,MAAM,wBAAwB;AAG9B,IAAI,sBAA0C;;AAG9C,SAAgB,iBAA8B;CAC5C,IAAI,CAAC,qBACH,sBAAsB,IAAI,YAAY;CAExC,OAAO;AACT;;AAGA,SAAgB,eAAe,SAAwC;CACrE,sBAAsB,WAAW;AACnC;;;;;;AAOA,SAAS,cAAc,MAAwB;CAC7C,IAAI,CAAC,QAAQ,OAAO,SAAS,UAAU,OAAO;CAC9C,MAAM,MAAM;CAEZ,MAAM,WAAW,IAAI;CACrB,IAAI,MAAM,QAAQ,QAAQ,KAAK,SAAS,SAAS,GAAG;EAClD,MAAM,OAAO,SAAS,SAAS,SAAS;E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gB;GACvC,MAAM,QAAQ,iBAAiB,WAAW,MAAM,GAAG,wBAAwB;GAC3E,IAAI;IACF,MAAM,SAAS,MAAM,mBAAmB;KACtC;KACA,aAAa;KACb,QAAQ,WAAW;IACrB,CAAC;IACD,IAAI,eAAe,aAAa,IAAI,eAAe;KAAE,WAAW,KAAK,IAAI;KAAG,KAAK;KAAgB;IAAO,CAAC;IACzG,OAAO;GACT,UAAU;IACR,aAAa,KAAK;GACpB;EACF,SAAS,OAAO;GACd,IAAI,eACF,aAAa,IAAI,eAAe;IAC9B,WAAW,KAAK,IAAI;IACpB,KAAK;IACL,QAAQ;GACV,CAAC;GAEH,QAAQ,KACN,oEACA,iBAAiB,QAAQ,MAAM,UAAU,KAC3C;GACA,OAAO;EACT,UAAU;GACR,IAAI,cAAc,KAAA,GAAW,gBAAgB,OAAO,SAAS;EAC/D;CACF,EAAA,CAAG;CACH,IAAI,cAAc,KAAA,GAAW,gBAAgB,IAAI,WAAW,YAAY;CACxE,OAAO;AACT"}
@@ -1,4 +1,4 @@
1
- //#region src/providers/google-thinking.ts
1
+ // src/providers/google-thinking.ts
2
2
  const GEMINI_25_BUDGETS = {
3
3
  low: 1024,
4
4
  medium: 8192,
@@ -61,7 +61,6 @@ function createGoogleThinkingMiddleware(modelId, level) {
61
61
  }
62
62
  };
63
63
  }
64
- //#endregion
65
64
  export { createGoogleThinkingMiddleware, resolveGoogleThinkingConfig, runGeminiThinkingLevel };
66
65
 
67
66
  //# sourceMappingURL=google-thinking.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"kimi-coding.d.ts","sourceRoot":"","sources":["../../src/providers/kimi-coding.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAG1D,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AACjD,OAAO,KAAK,EAAE,eAAe,EAAmB,MAAM,kBAAkB,CAAC;AASzE,wBAAgB,cAAc,CAAC,OAAO,EAAE,WAAW,GAAG,SAAS,GAAG,IAAI,CAErE;AAOD,wBAAgB,yBAAyB,CAAC,OAAO,GAAE;IAAE,eAAe,CAAC,EAAE,eAAe,CAAA;CAAO,GAAG,OAAO,KAAK,CAuC3G;AAED,wBAAgB,0BAA0B,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,KAAK,CASvE;AAED,wBAAgB,kBAAkB,CAChC,OAAO,EAAE,MAAM,EACf,OAAO,EAAE;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAAC,eAAe,CAAC,EAAE,eAAe,CAAA;CAAE,GAC/F,iBAAiB,CAYnB"}
1
+ {"version":3,"file":"kimi-coding.d.ts","sourceRoot":"","sources":["../../src/providers/kimi-coding.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAG1D,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AACjD,OAAO,KAAK,EAAE,eAAe,EAAmB,MAAM,kBAAkB,CAAC;AAWzE,wBAAgB,cAAc,CAAC,OAAO,EAAE,WAAW,GAAG,SAAS,GAAG,IAAI,CAErE;AAOD,wBAAgB,yBAAyB,CAAC,OAAO,GAAE;IAAE,eAAe,CAAC,EAAE,eAAe,CAAA;CAAO,GAAG,OAAO,KAAK,CAuC3G;AAED,wBAAgB,0BAA0B,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,KAAK,CASvE;AAED,wBAAgB,kBAAkB,CAChC,OAAO,EAAE,MAAM,EACf,OAAO,EAAE;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAAC,eAAe,CAAC,EAAE,eAAe,CAAA;CAAE,GAC/F,iBAAiB,CAYnB"}
@@ -2,8 +2,10 @@ import { getKimiCodingDeviceHeaders, isKimiCodingDeviceId } from "../auth/provid
2
2
  import { AuthStorage } from "../auth/storage.js";
3
3
  import { ProviderAuthRequiredError, rejectUnauthorizedResponse } from "../auth/provider-auth-error.js";
4
4
  import { createAnthropic } from "@ai-sdk/anthropic";
5
- //#region src/providers/kimi-coding.ts
5
+ // src/providers/kimi-coding.ts
6
6
  const PROVIDER_ID = "kimi-for-coding";
7
+ const PROVIDER_NAME = "Kimi For Coding";
8
+ const INVALID_CREDENTIALS_MESSAGE = `${PROVIDER_NAME} credentials are invalid. Please reconnect the account.`;
7
9
  const BASE_URL = "https://api.kimi.com/coding/v1";
8
10
  let authStorageInstance = null;
9
11
  function setAuthStorage(storage) {
@@ -18,8 +20,8 @@ function buildKimiCodingOAuthFetch(options = {}) {
18
20
  const store = options.credentialStore ?? getAuthStorage();
19
21
  store.reload();
20
22
  const credential = store.get(PROVIDER_ID);
21
- if (!credential || credential.type !== "oauth") throw new ProviderAuthRequiredError("Not logged in to Kimi For Coding.");
22
- if (!isKimiCodingDeviceId(credential.deviceId)) throw new ProviderAuthRequiredError("Kimi For Coding credentials are invalid. Please reconnect the account.");
23
+ if (!credential || credential.type !== "oauth") throw ProviderAuthRequiredError.notSignedIn(PROVIDER_NAME);
24
+ if (!isKimiCodingDeviceId(credential.deviceId)) throw new ProviderAuthRequiredError(INVALID_CREDENTIALS_MESSAGE);
23
25
  let token;
24
26
  let activeCredential = credential;
25
27
  if (store.getOAuthCredential) {
@@ -34,8 +36,8 @@ function buildKimiCodingOAuthFetch(options = {}) {
34
36
  access: token ?? reloaded.access
35
37
  } : void 0;
36
38
  }
37
- if (!token) throw new ProviderAuthRequiredError("Failed to refresh the Kimi For Coding token.");
38
- if (!activeCredential || !isKimiCodingDeviceId(activeCredential.deviceId)) throw new ProviderAuthRequiredError("Kimi For Coding credentials are invalid. Please reconnect the account.");
39
+ if (!token) throw ProviderAuthRequiredError.signInExpired(PROVIDER_NAME);
40
+ if (!activeCredential || !isKimiCodingDeviceId(activeCredential.deviceId)) throw new ProviderAuthRequiredError(INVALID_CREDENTIALS_MESSAGE);
39
41
  const deviceHeaders = getKimiCodingDeviceHeaders(activeCredential.deviceId);
40
42
  const headers = new Headers(input instanceof Request ? input.headers : void 0);
41
43
  if (init?.headers) new Headers(init.headers).forEach((value, key) => headers.set(key, value));
@@ -47,7 +49,7 @@ function buildKimiCodingOAuthFetch(options = {}) {
47
49
  ...init,
48
50
  headers
49
51
  }), {
50
- providerName: "Kimi For Coding",
52
+ providerName: PROVIDER_NAME,
51
53
  requestUrl: input instanceof URL ? input.toString() : typeof input === "string" ? input : input.url
52
54
  });
53
55
  });
@@ -75,7 +77,6 @@ function kimiCodingProvider(modelId, options) {
75
77
  fetch: usesOAuth ? buildKimiCodingOAuthFetch({ credentialStore: options.credentialStore }) : buildKimiCodingApiKeyFetch(options.apiKey)
76
78
  })(modelId);
77
79
  }
78
- //#endregion
79
80
  export { buildKimiCodingApiKeyFetch, buildKimiCodingOAuthFetch, kimiCodingProvider, setAuthStorage };
80
81
 
81
82
  //# sourceMappingURL=kimi-coding.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"kimi-coding.js","names":[],"sources":["../../src/providers/kimi-coding.ts"],"sourcesContent":["import { createAnthropic } from '@ai-sdk/anthropic';\nimport type { MastraModelConfig } from '@mastra/core/llm';\nimport { ProviderAuthRequiredError, rejectUnauthorizedResponse } from '../auth/provider-auth-error.js';\nimport { getKimiCodingDeviceHeaders, isKimiCodingDeviceId } from '../auth/providers/kimi-coding.js';\nimport { AuthStorage } from '../auth/storage.js';\nimport type { CredentialStore, OAuthCredential } from '../auth/types.js';\n\nconst PROVIDER_ID = 'kimi-for-coding';\n// Pi's provider root is https://api.kimi.com/coding. The AI SDK expects the\n// versioned Anthropic base URL and appends /messages itself.\nconst BASE_URL = 'https://api.kimi.com/coding/v1';\n\nlet authStorageInstance: AuthStorage | null = null;\n\nexport function setAuthStorage(storage: AuthStorage | undefined): void {\n authStorageInstance = storage ?? null;\n}\n\nfunction getAuthStorage(): AuthStorage {\n if (!authStorageInstance) authStorageInstance = new AuthStorage();\n return authStorageInstance;\n}\n\nexport function buildKimiCodingOAuthFetch(options: { credentialStore?: CredentialStore } = {}): typeof fetch {\n return (async (input: string | URL | Request, init?: Parameters<typeof fetch>[1]) => {\n const store = options.credentialStore ?? getAuthStorage();\n store.reload();\n const credential = store.get(PROVIDER_ID);\n if (!credential || credential.type !== 'oauth') {\n throw new ProviderAuthRequiredError('Not logged in to Kimi For Coding.');\n }\n if (!isKimiCodingDeviceId(credential.deviceId)) {\n throw new ProviderAuthRequiredError('Kimi For Coding credentials are invalid. Please reconnect the account.');\n }\n let token: string | undefined;\n let activeCredential: OAuthCredential | undefined = credential;\n if (store.getOAuthCredential) {\n activeCredential = await store.getOAuthCredential(PROVIDER_ID);\n token = activeCredential?.access;\n } else {\n token = await store.getApiKey(PROVIDER_ID);\n store.reload();\n const reloaded = store.get(PROVIDER_ID);\n activeCredential = reloaded?.type === 'oauth' ? { ...reloaded, access: token ?? reloaded.access } : undefined;\n }\n if (!token) throw new ProviderAuthRequiredError('Failed to refresh the Kimi For Coding token.');\n if (!activeCredential || !isKimiCodingDeviceId(activeCredential.deviceId)) {\n throw new ProviderAuthRequiredError('Kimi For Coding credentials are invalid. Please reconnect the account.');\n }\n const deviceHeaders = getKimiCodingDeviceHeaders(activeCredential.deviceId);\n\n const headers = new Headers(input instanceof Request ? input.headers : undefined);\n if (init?.headers) new Headers(init.headers).forEach((value, key) => headers.set(key, value));\n for (const [key, value] of Object.entries(deviceHeaders)) headers.set(key, value);\n headers.delete('authorization');\n headers.delete('x-api-key');\n headers.set('Authorization', `Bearer ${token}`);\n return rejectUnauthorizedResponse(await fetch(input, { ...init, headers }), {\n providerName: 'Kimi For Coding',\n requestUrl: input instanceof URL ? input.toString() : typeof input === 'string' ? input : input.url,\n });\n }) as typeof fetch;\n}\n\nexport function buildKimiCodingApiKeyFetch(apiKey: string): typeof fetch {\n return (async (input: string | URL | Request, init?: Parameters<typeof fetch>[1]) => {\n const headers = new Headers(input instanceof Request ? input.headers : undefined);\n if (init?.headers) new Headers(init.headers).forEach((value, key) => headers.set(key, value));\n headers.delete('authorization');\n headers.delete('x-api-key');\n headers.set('Authorization', `Bearer ${apiKey}`);\n return fetch(input, { ...init, headers });\n }) as typeof fetch;\n}\n\nexport function kimiCodingProvider(\n modelId: string,\n options: { apiKey: string; headers?: Record<string, string>; credentialStore?: CredentialStore },\n): MastraModelConfig {\n const usesOAuth = options.credentialStore?.get(PROVIDER_ID)?.type === 'oauth';\n const provider = createAnthropic({\n name: PROVIDER_ID,\n apiKey: 'auth-placeholder',\n baseURL: BASE_URL,\n headers: options.headers,\n fetch: usesOAuth\n ? (buildKimiCodingOAuthFetch({ credentialStore: options.credentialStore }) as any)\n : (buildKimiCodingApiKeyFetch(options.apiKey) as any),\n });\n return provider(modelId) as unknown as MastraModelConfig;\n}\n"],"mappings":";;;;;AAOA,MAAM,cAAc;AAGpB,MAAM,WAAW;AAEjB,IAAI,sBAA0C;AAE9C,SAAgB,eAAe,SAAwC;CACrE,sBAAsB,WAAW;AACnC;AAEA,SAAS,iBAA8B;CACrC,IAAI,CAAC,qBAAqB,sBAAsB,IAAI,YAAY;CAChE,OAAO;AACT;AAEA,SAAgB,0BAA0B,UAAiD,CAAC,GAAiB;CAC3G,QAAQ,OAAO,OAA+B,SAAuC;EACnF,MAAM,QAAQ,QAAQ,mBAAmB,eAAe;EACxD,MAAM,OAAO;EACb,MAAM,aAAa,MAAM,IAAI,WAAW;EACxC,IAAI,CAAC,cAAc,WAAW,SAAS,SACrC,MAAM,IAAI,0BAA0B,mCAAmC;EAEzE,IAAI,CAAC,qBAAqB,WAAW,QAAQ,GAC3C,MAAM,IAAI,0BAA0B,wEAAwE;EAE9G,IAAI;EACJ,IAAI,mBAAgD;EACpD,IAAI,MAAM,oBAAoB;GAC5B,mBAAmB,MAAM,MAAM,mBAAmB,WAAW;GAC7D,QAAQ,kBAAkB;EAC5B,OAAO;GACL,QAAQ,MAAM,MAAM,UAAU,WA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C/C,OAAO,MAAM,OAAO;GAAE,GAAG;GAAM;EAAQ,CAAC;CAC1C;AACF;AAEA,SAAgB,mBACd,SACA,SACmB;CACnB,MAAM,YAAY,QAAQ,iBAAiB,IAAI,WAAW,CAAC,EAAE,SAAS;CAUtE,OATiB,gBAAgB;EAC/B,MAAM;EACN,QAAQ;EACR,SAAS;EACT,SAAS,QAAQ;EACjB,OAAO,YACF,0BAA0B,EAAE,iBAAiB,QAAQ,gBAAgB,CAAC,IACtE,2BAA2B,QAAQ,MAAM;CAChD,CACc,CAAC,CAAC,OAAO;AACzB"}
1
+ {"version":3,"file":"kimi-coding.js","names":[],"sources":["../../src/providers/kimi-coding.ts"],"sourcesContent":["import { createAnthropic } from '@ai-sdk/anthropic';\nimport type { MastraModelConfig } from '@mastra/core/llm';\nimport { ProviderAuthRequiredError, rejectUnauthorizedResponse } from '../auth/provider-auth-error.js';\nimport { getKimiCodingDeviceHeaders, isKimiCodingDeviceId } from '../auth/providers/kimi-coding.js';\nimport { AuthStorage } from '../auth/storage.js';\nimport type { CredentialStore, OAuthCredential } from '../auth/types.js';\n\nconst PROVIDER_ID = 'kimi-for-coding';\nconst PROVIDER_NAME = 'Kimi For Coding';\nconst INVALID_CREDENTIALS_MESSAGE = `${PROVIDER_NAME} credentials are invalid. Please reconnect the account.`;\n// Pi's provider root is https://api.kimi.com/coding. The AI SDK expects the\n// versioned Anthropic base URL and appends /messages itself.\nconst BASE_URL = 'https://api.kimi.com/coding/v1';\n\nlet authStorageInstance: AuthStorage | null = null;\n\nexport function setAuthStorage(storage: AuthStorage | undefined): void {\n authStorageInstance = storage ?? null;\n}\n\nfunction getAuthStorage(): AuthStorage {\n if (!authStorageInstance) authStorageInstance = new AuthStorage();\n return authStorageInstance;\n}\n\nexport function buildKimiCodingOAuthFetch(options: { credentialStore?: CredentialStore } = {}): typeof fetch {\n return (async (input: string | URL | Request, init?: Parameters<typeof fetch>[1]) => {\n const store = options.credentialStore ?? getAuthStorage();\n store.reload();\n const credential = store.get(PROVIDER_ID);\n if (!credential || credential.type !== 'oauth') {\n throw ProviderAuthRequiredError.notSignedIn(PROVIDER_NAME);\n }\n if (!isKimiCodingDeviceId(credential.deviceId)) {\n throw new ProviderAuthRequiredError(INVALID_CREDENTIALS_MESSAGE);\n }\n let token: string | undefined;\n let activeCredential: OAuthCredential | undefined = credential;\n if (store.getOAuthCredential) {\n activeCredential = await store.getOAuthCredential(PROVIDER_ID);\n token = activeCredential?.access;\n } else {\n token = await store.getApiKey(PROVIDER_ID);\n store.reload();\n const reloaded = store.get(PROVIDER_ID);\n activeCredential = reloaded?.type === 'oauth' ? { ...reloaded, access: token ?? reloaded.access } : undefined;\n }\n if (!token) throw ProviderAuthRequiredError.signInExpired(PROVIDER_NAME);\n if (!activeCredential || !isKimiCodingDeviceId(activeCredential.deviceId)) {\n throw new ProviderAuthRequiredError(INVALID_CREDENTIALS_MESSAGE);\n }\n const deviceHeaders = getKimiCodingDeviceHeaders(activeCredential.deviceId);\n\n const headers = new Headers(input instanceof Request ? input.headers : undefined);\n if (init?.headers) new Headers(init.headers).forEach((value, key) => headers.set(key, value));\n for (const [key, value] of Object.entries(deviceHeaders)) headers.set(key, value);\n headers.delete('authorization');\n headers.delete('x-api-key');\n headers.set('Authorization', `Bearer ${token}`);\n return rejectUnauthorizedResponse(await fetch(input, { ...init, headers }), {\n providerName: PROVIDER_NAME,\n requestUrl: input instanceof URL ? input.toString() : typeof input === 'string' ? input : input.url,\n });\n }) as typeof fetch;\n}\n\nexport function buildKimiCodingApiKeyFetch(apiKey: string): typeof fetch {\n return (async (input: string | URL | Request, init?: Parameters<typeof fetch>[1]) => {\n const headers = new Headers(input instanceof Request ? input.headers : undefined);\n if (init?.headers) new Headers(init.headers).forEach((value, key) => headers.set(key, value));\n headers.delete('authorization');\n headers.delete('x-api-key');\n headers.set('Authorization', `Bearer ${apiKey}`);\n return fetch(input, { ...init, headers });\n }) as typeof fetch;\n}\n\nexport function kimiCodingProvider(\n modelId: string,\n options: { apiKey: string; headers?: Record<string, string>; credentialStore?: CredentialStore },\n): MastraModelConfig {\n const usesOAuth = options.credentialStore?.get(PROVIDER_ID)?.type === 'oauth';\n const provider = createAnthropic({\n name: PROVIDER_ID,\n apiKey: 'auth-placeholder',\n baseURL: BASE_URL,\n headers: options.headers,\n fetch: usesOAuth\n ? (buildKimiCodingOAuthFetch({ credentialStore: options.credentialStore }) as any)\n : (buildKimiCodingApiKeyFetch(options.apiKey) as any),\n });\n return provider(modelId) as unknown as MastraModelConfig;\n}\n"],"mappings":";;;;;AAOA,MAAM,cAAc;AACpB,MAAM,gBAAgB;AACtB,MAAM,8BAA8B,GAAG,cAAc;AAGrD,MAAM,WAAW;AAEjB,IAAI,sBAA0C;AAE9C,SAAgB,eAAe,SAAwC;CACrE,sBAAsB,WAAW;AACnC;AAEA,SAAS,iBAA8B;CACrC,IAAI,CAAC,qBAAqB,sBAAsB,IAAI,YAAY;CAChE,OAAO;AACT;AAEA,SAAgB,0BAA0B,UAAiD,CAAC,GAAiB;CAC3G,QAAQ,OAAO,OAA+B,SAAuC;EACnF,MAAM,QAAQ,QAAQ,mBAAmB,eAAe;EACxD,MAAM,OAAO;EACb,MAAM,aAAa,MAAM,IAAI,WAAW;EACxC,IAAI,CAAC,cAAc,WAAW,SAAS,SACrC,MAAM,0BAA0B,YAAY,aAAa;EAE3D,IAAI,CAAC,qBAAqB,WAAW,QAAQ,GAC3C,MAAM,IAAI,0BAA0B,2BAA2B;EAEjE,IAAI;EACJ,IAAI,mBAAgD;EACpD,IAAI,MAAM,oBAAoB;GAC5B,mBAAmB,MAAM,MAAM,mBAAmB,WAAW;GAC7D,QAAQ,kBAAkB;EAC5B,OAAO;GACL,QAAQ,MAAM,MAAM,UAAU,WAAW;GACzC,MAAM,OAAO;GACb,MAAM,WAAW,MAAM,IAAI,WAAW;GACtC,mBAAmB,UAAU,SAAS,UAAU;IAAE,GAAG;IAAU,QAAQ,SAAS,SAAS;GAAO,IAAI,KAAA;EACtG;EACA,I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CAUtE,OATiB,gBAAgB;EAC/B,MAAM;EACN,QAAQ;EACR,SAAS;EACT,SAAS,QAAQ;EACjB,OAAO,YACF,0BAA0B,EAAE,iBAAiB,QAAQ,gBAAgB,CAAC,IACtE,2BAA2B,QAAQ,MAAM;CAChD,CACc,CAAC,CAAC,OAAO;AACzB"}
@@ -1,4 +1,4 @@
1
- //#region src/providers/model-ids.ts
1
+ // src/providers/model-ids.ts
2
2
  /**
3
3
  * Model-id helpers shared by the model gateway and the browser settings
4
4
  * module. Kept dependency-free so neither side has to import the other.
@@ -75,7 +75,6 @@ function remapOpenAIModelForCodexOAuth(modelId) {
75
75
  const remappedModelId = `${OPENAI_PREFIX}${codexModelId}`;
76
76
  return modelId.startsWith("mastra/") ? `${MASTRA_GATEWAY_PREFIX}${remappedModelId}` : remappedModelId;
77
77
  }
78
- //#endregion
79
78
  export { ANTHROPIC_PREFIX, KIMI_CODING_CREDENTIAL_ID, KIMI_CODING_PROVIDER_ID, MASTRA_GATEWAY_PREFIX, OPENAI_PREFIX, getCredentialProviderId, normalizeAnthropicModelId, normalizeLegacyModelId, normalizeLegacyProviderId, remapOpenAIModelForCodexOAuth, stripMastraGatewayPrefix };
80
79
 
81
80
  //# sourceMappingURL=model-ids.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"openai-codex.d.ts","sourceRoot":"","sources":["../../src/providers/openai-codex.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAGH,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAE1D,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,IAAI,CAAC;AAElD,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AACjD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAExD,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAC;AAC3D,OAAO,EAAE,0BAA0B,EAAE,MAAM,gBAAgB,CAAC;AAU5D;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;;GASG;AACH,wBAAgB,+BAA+B,CAC7C,WAAW,EAAE,MAAM,EACnB,eAAe,CAAC,EAAE,MAAM,GACvB,uBAAuB,GAAG,SAAS,CAgBrC;AAyCD;;;;;;GAMG;AACH,wBAAgB,0BAA0B,CACxC,IAAI,GAAE;IAAE,WAAW,CAAC,EAAE,eAAe,CAAC;IAAC,UAAU,CAAC,EAAE,OAAO,CAAA;CAAO,GACjE,OAAO,KAAK,CA2Dd;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,wBAAwB,CAAC,WAAW,EAAE,WAAW,GAAG,OAAO,KAAK,CAuC/E;AAwID;;;;;;GAMG;AACH,wBAAgB,mBAAmB,CACjC,OAAO,GAAE,MAA4B,EACrC,OAAO,CAAC,EAAE;IAAE,aAAa,CAAC,EAAE,aAAa,CAAC;IAAC,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAAC,WAAW,CAAC,EAAE,eAAe,CAAA;CAAE,GAC3G,iBAAiB,CAuCnB"}
@@ -4,7 +4,7 @@ import { runCatalogThinkingLevel } from "../thinking-catalog.js";
4
4
  import { ProviderAuthRequiredError, rejectUnauthorizedResponse } from "../auth/provider-auth-error.js";
5
5
  import { createOpenAI } from "@ai-sdk/openai";
6
6
  import { wrapLanguageModel } from "ai";
7
- //#region src/providers/openai-codex.ts
7
+ // src/providers/openai-codex.ts
8
8
  /**
9
9
  * OpenAI Codex OAuth Provider
10
10
  *
@@ -17,6 +17,7 @@ import { wrapLanguageModel } from "ai";
17
17
  const CODEX_API_ENDPOINT = "https://chatgpt.com/backend-api/codex/responses";
18
18
  const CODEX_ORIGINATOR = "mastracode";
19
19
  const CODEX_USER_AGENT = "mastracode";
20
+ const CODEX_PROVIDER_NAME = "OpenAI Codex";
20
21
  let authStorageInstance = null;
21
22
  /**
22
23
  * Get or create the shared AuthStorage instance
@@ -142,16 +143,16 @@ async function getCodexBearer(authStorage) {
142
143
  const storage = authStorage ?? getAuthStorage();
143
144
  storage.reload();
144
145
  let cred = storage.get("openai-codex");
145
- if (!cred || cred.type !== "oauth") throw new ProviderAuthRequiredError("Not logged in to OpenAI Codex.");
146
+ if (!cred || cred.type !== "oauth") throw ProviderAuthRequiredError.notSignedIn(CODEX_PROVIDER_NAME);
146
147
  if (storage.getOAuthCredential) {
147
148
  cred = await storage.getOAuthCredential("openai-codex");
148
- if (!cred) throw new ProviderAuthRequiredError("Failed to refresh the OpenAI Codex token.");
149
+ if (!cred) throw ProviderAuthRequiredError.signInExpired(CODEX_PROVIDER_NAME);
149
150
  } else if (Date.now() >= cred.expires) {
150
151
  const refreshedToken = await storage.getApiKey("openai-codex");
151
- if (!refreshedToken) throw new ProviderAuthRequiredError("Failed to refresh the OpenAI Codex token.");
152
+ if (!refreshedToken) throw ProviderAuthRequiredError.signInExpired(CODEX_PROVIDER_NAME);
152
153
  storage.reload();
153
154
  const reloaded = storage.get("openai-codex");
154
- if (!reloaded || reloaded.type !== "oauth") throw new ProviderAuthRequiredError("Not logged in to OpenAI Codex.");
155
+ if (!reloaded || reloaded.type !== "oauth") throw ProviderAuthRequiredError.notSignedIn(CODEX_PROVIDER_NAME);
155
156
  cred = {
156
157
  ...reloaded,
157
158
  access: refreshedToken
@@ -201,7 +202,7 @@ function buildOpenAICodexOAuthFetch(opts = {}) {
201
202
  });
202
203
  try {
203
204
  return await rejectUnauthorizedResponse(await fetch(finalRequest), {
204
- providerName: "OpenAI Codex",
205
+ providerName: CODEX_PROVIDER_NAME,
205
206
  requestUrl: finalUrl.toString()
206
207
  });
207
208
  } catch (error) {
@@ -386,7 +387,6 @@ function openaiCodexProvider(modelId = "codex-mini-latest", options) {
386
387
  middleware
387
388
  });
388
389
  }
389
- //#endregion
390
390
  export { THINKING_LEVEL_TO_REASONING_EFFORT, buildCodexStagehandFetch, buildOpenAICodexOAuthFetch, createCodexMiddleware, createPromptCacheKeyMiddleware, createReasoningEffortMiddleware, getAuthStorage, getEffectiveThinkingLevel, getRequestThreadId, openaiCodexProvider, setAuthStorage, supportsMaxReasoningEffort };
391
391
 
392
392
  //# sourceMappingURL=openai-codex.js.map