@mastra/code-sdk 1.14.0-alpha.7 → 1.14.0-alpha.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/auth/index.js +2 -2
- package/dist/auth/provider-auth-error.d.ts +10 -0
- package/dist/auth/provider-auth-error.d.ts.map +1 -1
- package/dist/auth/provider-auth-error.js +26 -1
- package/dist/auth/provider-auth-error.js.map +1 -1
- package/dist/providers/claude-max.d.ts.map +1 -1
- package/dist/providers/claude-max.js +7 -3
- package/dist/providers/claude-max.js.map +1 -1
- package/dist/providers/github-copilot.d.ts.map +1 -1
- package/dist/providers/github-copilot.js +5 -2
- package/dist/providers/github-copilot.js.map +1 -1
- package/dist/providers/kimi-coding.d.ts.map +1 -1
- package/dist/providers/kimi-coding.js +5 -2
- package/dist/providers/kimi-coding.js.map +1 -1
- package/dist/providers/openai-codex.d.ts.map +1 -1
- package/dist/providers/openai-codex.js +5 -2
- package/dist/providers/openai-codex.js.map +1 -1
- package/dist/providers/xai.d.ts.map +1 -1
- package/dist/providers/xai.js +5 -2
- package/dist/providers/xai.js.map +1 -1
- package/package.json +9 -9
package/dist/auth/index.js
CHANGED
|
@@ -4,6 +4,6 @@ import { kimiCodingOAuthProvider } from "./providers/kimi-coding.js";
|
|
|
4
4
|
import { openaiCodexOAuthProvider } from "./providers/openai-codex.js";
|
|
5
5
|
import { xaiOAuthProvider } from "./providers/xai.js";
|
|
6
6
|
import { AuthStorage, PROVIDER_DEFAULT_MODELS, getOAuthProvider, getOAuthProviders } from "./storage.js";
|
|
7
|
-
import { PROVIDER_AUTH_REQUIRED_ERROR, ProviderAuthRequiredError } from "./provider-auth-error.js";
|
|
7
|
+
import { PROVIDER_AUTH_REQUIRED_ERROR, ProviderAuthRequiredError, rejectUnauthorizedResponse } from "./provider-auth-error.js";
|
|
8
8
|
import { ACCOUNT_SWITCH_PART_TYPE, AccountRotationProcessor, AccountStartNoticeProcessor, MODEL_FALLBACK_PART_TYPE, MODEL_FALLBACK_STATE_KEY, PROVIDER_DISPLAY_NAMES, accountSwitchNoticeText, classifyRotationError, isAccountSwitchReason, isModelFallbackReason, modelFallbackNoticeText, providerFromError, providerFromModelId } from "./account-rotation-processor.js";
|
|
9
|
-
export { ACCOUNT_SWITCH_PART_TYPE, AccountRotationProcessor, AccountStartNoticeProcessor, AuthStorage, MODEL_FALLBACK_PART_TYPE, MODEL_FALLBACK_STATE_KEY, PROVIDER_AUTH_REQUIRED_ERROR, PROVIDER_DEFAULT_MODELS, PROVIDER_DISPLAY_NAMES, ProviderAuthRequiredError, accountSwitchNoticeText, anthropicOAuthProvider, classifyRotationError, getOAuthProvider, getOAuthProviders, githubCopilotOAuthProvider, isAccountSwitchReason, isModelFallbackReason, kimiCodingOAuthProvider, modelFallbackNoticeText, openaiCodexOAuthProvider, providerFromError, providerFromModelId, xaiOAuthProvider };
|
|
9
|
+
export { ACCOUNT_SWITCH_PART_TYPE, AccountRotationProcessor, AccountStartNoticeProcessor, AuthStorage, MODEL_FALLBACK_PART_TYPE, MODEL_FALLBACK_STATE_KEY, PROVIDER_AUTH_REQUIRED_ERROR, PROVIDER_DEFAULT_MODELS, PROVIDER_DISPLAY_NAMES, ProviderAuthRequiredError, accountSwitchNoticeText, anthropicOAuthProvider, classifyRotationError, getOAuthProvider, getOAuthProviders, githubCopilotOAuthProvider, isAccountSwitchReason, isModelFallbackReason, kimiCodingOAuthProvider, modelFallbackNoticeText, openaiCodexOAuthProvider, providerFromError, providerFromModelId, rejectUnauthorizedResponse, xaiOAuthProvider };
|
|
@@ -9,4 +9,14 @@ export declare const PROVIDER_AUTH_REQUIRED_ERROR = "ProviderAuthRequiredError";
|
|
|
9
9
|
export declare class ProviderAuthRequiredError extends Error {
|
|
10
10
|
readonly name = "ProviderAuthRequiredError";
|
|
11
11
|
}
|
|
12
|
+
/**
|
|
13
|
+
* A stored OAuth token the provider rejects (revoked, signed out elsewhere) is
|
|
14
|
+
* the same user-facing state as a missing one, so a 401 becomes
|
|
15
|
+
* `ProviderAuthRequiredError`. `status` and `requestUrl` stay on the error:
|
|
16
|
+
* account rotation reads them to force a refresh and attribute the provider.
|
|
17
|
+
*/
|
|
18
|
+
export declare function rejectUnauthorizedResponse(response: Response, { providerName, requestUrl }: {
|
|
19
|
+
providerName: string;
|
|
20
|
+
requestUrl: string;
|
|
21
|
+
}): Promise<Response>;
|
|
12
22
|
//# sourceMappingURL=provider-auth-error.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"provider-auth-error.d.ts","sourceRoot":"","sources":["../../src/auth/provider-auth-error.ts"],"names":[],"mappings":"AAAA,2GAA2G;AAC3G,eAAO,MAAM,4BAA4B,8BAA8B,CAAC;AAExE;;;;;GAKG;AACH,qBAAa,yBAA0B,SAAQ,KAAK;IAClD,QAAQ,CAAC,IAAI,+BAAgC;CAC9C"}
|
|
1
|
+
{"version":3,"file":"provider-auth-error.d.ts","sourceRoot":"","sources":["../../src/auth/provider-auth-error.ts"],"names":[],"mappings":"AAAA,2GAA2G;AAC3G,eAAO,MAAM,4BAA4B,8BAA8B,CAAC;AAExE;;;;;GAKG;AACH,qBAAa,yBAA0B,SAAQ,KAAK;IAClD,QAAQ,CAAC,IAAI,+BAAgC;CAC9C;AAiBD;;;;;GAKG;AACH,wBAAsB,0BAA0B,CAC9C,QAAQ,EAAE,QAAQ,EAClB,EAAE,YAAY,EAAE,UAAU,EAAE,EAAE;IAAE,YAAY,EAAE,MAAM,CAAC;IAAC,UAAU,EAAE,MAAM,CAAA;CAAE,GACzE,OAAO,CAAC,QAAQ,CAAC,CAKnB"}
|
|
@@ -10,7 +10,32 @@ const PROVIDER_AUTH_REQUIRED_ERROR = "ProviderAuthRequiredError";
|
|
|
10
10
|
var ProviderAuthRequiredError = class extends Error {
|
|
11
11
|
name = PROVIDER_AUTH_REQUIRED_ERROR;
|
|
12
12
|
};
|
|
13
|
+
function providerErrorMessage(body) {
|
|
14
|
+
try {
|
|
15
|
+
const parsed = JSON.parse(body);
|
|
16
|
+
const error = parsed.error;
|
|
17
|
+
if (typeof error === "object" && error !== null && "message" in error && typeof error.message === "string") return error.message;
|
|
18
|
+
if (typeof error === "string") return error;
|
|
19
|
+
if (typeof parsed.message === "string") return parsed.message;
|
|
20
|
+
} catch {}
|
|
21
|
+
return body.trim() || void 0;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* A stored OAuth token the provider rejects (revoked, signed out elsewhere) is
|
|
25
|
+
* the same user-facing state as a missing one, so a 401 becomes
|
|
26
|
+
* `ProviderAuthRequiredError`. `status` and `requestUrl` stay on the error:
|
|
27
|
+
* account rotation reads them to force a refresh and attribute the provider.
|
|
28
|
+
*/
|
|
29
|
+
async function rejectUnauthorizedResponse(response, { providerName, requestUrl }) {
|
|
30
|
+
if (response.status !== 401) return response;
|
|
31
|
+
const detail = providerErrorMessage(await response.text().catch(() => ""));
|
|
32
|
+
const message = `${providerName} rejected the stored sign-in${detail ? `: ${detail}` : "."}`;
|
|
33
|
+
throw Object.assign(new ProviderAuthRequiredError(message), {
|
|
34
|
+
status: 401,
|
|
35
|
+
requestUrl
|
|
36
|
+
});
|
|
37
|
+
}
|
|
13
38
|
//#endregion
|
|
14
|
-
export { PROVIDER_AUTH_REQUIRED_ERROR, ProviderAuthRequiredError };
|
|
39
|
+
export { PROVIDER_AUTH_REQUIRED_ERROR, ProviderAuthRequiredError, rejectUnauthorizedResponse };
|
|
15
40
|
|
|
16
41
|
//# sourceMappingURL=provider-auth-error.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"provider-auth-error.js","names":[],"sources":["../../src/auth/provider-auth-error.ts"],"sourcesContent":["/** Wire-stable `Error.name`: the server flattens errors to `{ name, message }`, so hosts match on this. */\nexport const PROVIDER_AUTH_REQUIRED_ERROR = 'ProviderAuthRequiredError';\n\n/**\n * A provider credential is missing or no longer usable. The message states the\n * fact only — how the user re-authenticates is the host's call (`/login` in the\n * TUI, Settings → Models in the factory web UI), so no host advertises a\n * command another host doesn't have.\n */\nexport class ProviderAuthRequiredError extends Error {\n readonly name = PROVIDER_AUTH_REQUIRED_ERROR;\n}\n"],"mappings":";;AACA,MAAa,+BAA+B;;;;;;;AAQ5C,IAAa,4BAAb,cAA+C,MAAM;CACnD,OAAgB;AAClB"}
|
|
1
|
+
{"version":3,"file":"provider-auth-error.js","names":[],"sources":["../../src/auth/provider-auth-error.ts"],"sourcesContent":["/** Wire-stable `Error.name`: the server flattens errors to `{ name, message }`, so hosts match on this. */\nexport const PROVIDER_AUTH_REQUIRED_ERROR = 'ProviderAuthRequiredError';\n\n/**\n * A provider credential is missing or no longer usable. The message states the\n * fact only — how the user re-authenticates is the host's call (`/login` in the\n * TUI, Settings → Models in the factory web UI), so no host advertises a\n * command another host doesn't have.\n */\nexport class ProviderAuthRequiredError extends Error {\n readonly name = PROVIDER_AUTH_REQUIRED_ERROR;\n}\n\nfunction providerErrorMessage(body: string): string | undefined {\n try {\n const parsed = JSON.parse(body) as { message?: unknown; error?: unknown };\n const error = parsed.error;\n if (typeof error === 'object' && error !== null && 'message' in error && typeof error.message === 'string') {\n return error.message;\n }\n if (typeof error === 'string') return error;\n if (typeof parsed.message === 'string') return parsed.message;\n } catch {\n // Not JSON — fall through to the raw text.\n }\n return body.trim() || undefined;\n}\n\n/**\n * A stored OAuth token the provider rejects (revoked, signed out elsewhere) is\n * the same user-facing state as a missing one, so a 401 becomes\n * `ProviderAuthRequiredError`. `status` and `requestUrl` stay on the error:\n * account rotation reads them to force a refresh and attribute the provider.\n */\nexport async function rejectUnauthorizedResponse(\n response: Response,\n { providerName, requestUrl }: { providerName: string; requestUrl: string },\n): Promise<Response> {\n if (response.status !== 401) return response;\n const detail = providerErrorMessage(await response.text().catch(() => ''));\n const message = `${providerName} rejected the stored sign-in${detail ? `: ${detail}` : '.'}`;\n throw Object.assign(new ProviderAuthRequiredError(message), { status: 401, requestUrl });\n}\n"],"mappings":";;AACA,MAAa,+BAA+B;;;;;;;AA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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,CAyCnG;AAED;;;GAGG;AACH,wBAAgB,yBAAyB,CACvC,OAAO,GAAE,MAAmC,EAC5C,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"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { AuthStorage } from "../auth/storage.js";
|
|
2
2
|
import { ANTHROPIC_THINKING_BUDGET_TOKENS, getAnthropicThinkingCapability } from "./anthropic-thinking.js";
|
|
3
3
|
import { runCatalogThinkingLevel } from "../thinking-catalog.js";
|
|
4
|
-
import { ProviderAuthRequiredError } from "../auth/provider-auth-error.js";
|
|
4
|
+
import { ProviderAuthRequiredError, rejectUnauthorizedResponse } from "../auth/provider-auth-error.js";
|
|
5
5
|
import "./anthropic-prompt-cache.js";
|
|
6
6
|
import { wrapLanguageModel } from "ai";
|
|
7
7
|
import { createAnthropic } from "@ai-sdk/anthropic";
|
|
@@ -181,13 +181,17 @@ function buildAnthropicOAuthFetch(opts = {}) {
|
|
|
181
181
|
const requestBetas = (headers.get("anthropic-beta") ?? "").split(",").map((beta) => beta.trim()).filter(Boolean);
|
|
182
182
|
headers.set("anthropic-beta", Array.from(/* @__PURE__ */ new Set([...OAUTH_REQUIRED_BETAS, ...requestBetas])).join(","));
|
|
183
183
|
headers.set("anthropic-version", "2023-06-01");
|
|
184
|
+
const requestUrl = url instanceof URL ? url.toString() : typeof url === "string" ? url : url.url;
|
|
184
185
|
try {
|
|
185
|
-
return await fetch(url, {
|
|
186
|
+
return await rejectUnauthorizedResponse(await fetch(url, {
|
|
186
187
|
...init,
|
|
187
188
|
headers
|
|
189
|
+
}), {
|
|
190
|
+
providerName: "Anthropic",
|
|
191
|
+
requestUrl
|
|
188
192
|
});
|
|
189
193
|
} catch (error) {
|
|
190
|
-
if (error && typeof error === "object") Object.assign(error, { requestUrl
|
|
194
|
+
if (error && typeof error === "object") Object.assign(error, { requestUrl });
|
|
191
195
|
throw error;
|
|
192
196
|
}
|
|
193
197
|
});
|
|
@@ -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 } 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 try {\n return await fetch(url, { ...init, headers });\n } catch (error) {\n if (error && typeof error === 'object') {\n Object.assign(error as Record<string, unknown>, {\n requestUrl: url instanceof URL ? url.toString() : typeof url === 'string' ? url : url.url,\n });\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-4-20250514',\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,M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
+
{"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-4-20250514',\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;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E,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,6 +1,6 @@
|
|
|
1
1
|
import { COPILOT_HEADERS, fetchCopilotModels, getGitHubCopilotBaseUrl } from "../auth/providers/github-copilot.js";
|
|
2
2
|
import { AuthStorage } from "../auth/storage.js";
|
|
3
|
-
import { ProviderAuthRequiredError } from "../auth/provider-auth-error.js";
|
|
3
|
+
import { ProviderAuthRequiredError, rejectUnauthorizedResponse } from "../auth/provider-auth-error.js";
|
|
4
4
|
import { wrapLanguageModel } from "ai";
|
|
5
5
|
import { createOpenAICompatible } from "@ai-sdk/openai-compatible";
|
|
6
6
|
import { GoogleSchemaCompatLayer, applyCompatLayer } from "@mastra/schema-compat";
|
|
@@ -127,7 +127,10 @@ function buildGitHubCopilotOAuthFetch(opts = {}) {
|
|
|
127
127
|
...body ? { duplex: "half" } : {}
|
|
128
128
|
});
|
|
129
129
|
try {
|
|
130
|
-
return await fetch(finalRequest)
|
|
130
|
+
return await rejectUnauthorizedResponse(await fetch(finalRequest), {
|
|
131
|
+
providerName: "GitHub Copilot",
|
|
132
|
+
requestUrl: finalUrl.toString()
|
|
133
|
+
});
|
|
131
134
|
} catch (error) {
|
|
132
135
|
if (error && typeof error === "object") Object.assign(error, { requestUrl: finalUrl.toString() });
|
|
133
136
|
throw error;
|
|
@@ -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 } 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 fetch(finalRequest);\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;AAG5B,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;EACxC,IAAI,MAAM,QAAQ,KAAK,SAAS,QAAQ,OAAO;EAC/C,IAAI,MAAM,QAAQ,MAAM,OAAO,GAEP;OAAA,KAAK,QAAQ,MAChC,SAAkB,QAAQ,OA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,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';\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,MAAM,sBAAsB;AAG5B,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;EACxC,IAAI,MAAM,QAAQ,KAAK,SAAS,QAAQ,OAAO;EAC/C,IAAI,MAAM,QAAQ,MAAM,OAAO,GAEP;OAAA,KAAK,QAAQ,MAChC,SAAkB,QAAQ,OAAO,SAAS,YAAa,KAA2B,SAAS,aAE9E,GAAG,OAAO;EAAA;CAE9B;CAEA,MAAM,QAAQ,IAAI;CAClB,IAAI,MAAM,QAAQ,KAAK,KAAK,MAAM,SAAS,GAAG;EAC5C,MAAM,OAAO,MAAM,MAAM,SAAS;EAClC,IAAI,MAAM,QAAQ,KAAK,SAAS,QAAQ,OAAO;CACjD;CAEA,OAAO;AACT;;AAGA,SAAS,eAAe,MAAwB;CAC9C,IAAI,CAAC,QAAQ,OAAO,SAAS,UAAU,OAAO;CAC9C,MAAM,MAAM;CAEZ,MAAM,aAAa,SAA2B;EAC5C,IAAI,CAAC,QAAQ,OAAO,SAAS,UAAU,OAAO;EAC9C,MAAM,IAAK,KAA2B;EACtC,OAAO,MAAM,WAAW,MAAM,eAAe,MAAM;CACrD;CAEA,MAAM,WAAW,IAAI;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"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,
|
|
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,6 +1,6 @@
|
|
|
1
1
|
import { getKimiCodingDeviceHeaders, isKimiCodingDeviceId } from "../auth/providers/kimi-coding.js";
|
|
2
2
|
import { AuthStorage } from "../auth/storage.js";
|
|
3
|
-
import { ProviderAuthRequiredError } from "../auth/provider-auth-error.js";
|
|
3
|
+
import { ProviderAuthRequiredError, rejectUnauthorizedResponse } from "../auth/provider-auth-error.js";
|
|
4
4
|
import { createAnthropic } from "@ai-sdk/anthropic";
|
|
5
5
|
//#region src/providers/kimi-coding.ts
|
|
6
6
|
const PROVIDER_ID = "kimi-for-coding";
|
|
@@ -43,9 +43,12 @@ function buildKimiCodingOAuthFetch(options = {}) {
|
|
|
43
43
|
headers.delete("authorization");
|
|
44
44
|
headers.delete("x-api-key");
|
|
45
45
|
headers.set("Authorization", `Bearer ${token}`);
|
|
46
|
-
return fetch(input, {
|
|
46
|
+
return rejectUnauthorizedResponse(await fetch(input, {
|
|
47
47
|
...init,
|
|
48
48
|
headers
|
|
49
|
+
}), {
|
|
50
|
+
providerName: "Kimi For Coding",
|
|
51
|
+
requestUrl: input instanceof URL ? input.toString() : typeof input === "string" ? input : input.url
|
|
49
52
|
});
|
|
50
53
|
});
|
|
51
54
|
}
|
|
@@ -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 } 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 fetch(input, { ...init, headers });\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,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,IAAI,CAAC,OAAO,MAAM,IAAI,0BAA0B,8CAA8C;EAC9F,IAAI,CAAC,oBAAoB,CAAC,qBAAqB,iBAAiB,QAAQ,GACtE,MAAM,IAAI,0BAA0B,wEAAwE;EAE9G,MAAM,gBAAgB,2BAA2B,iBAAiB,QAAQ;EAE1E,MAAM,UAAU,IAAI,QAAQ,iBAAiB,UAAU,MAAM,UAAU,KAAA,CAAS;EAChF,IAAI,MAAM,SAAS,IAAI,QAAQ,KAAK,OAAO,CAAC,CAAC,SAAS,OAAO,QAAQ,QAAQ,IAAI,KAAK,KAAK,CAAC;EAC5F,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,aAAa,GAAG,QAAQ,IAAI,KAAK,KAAK;EAChF,QAAQ,OAAO,eAAe;EAC9B,QAAQ,OAAO,WAAW;EAC1B,QAAQ,IAAI,iBAAiB,UAAU,OAAO;EAC9C,OAAO,MAAM,OAAO;GAAE,GAAG;GAAM;EAAQ,CAAC;
|
|
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,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qB,CAAC,eAAe,CAAC,EAAE,MAAM,GAAG,uBAAuB,CA4BvF;AAED;;;;;;;;;GASG;AACH,wBAAgB,+BAA+B,CAC7C,WAAW,EAAE,MAAM,EACnB,eAAe,CAAC,EAAE,MAAM,GACvB,uBAAuB,GAAG,SAAS,CAgBrC;AA2CD;;;;;;GAMG;AACH,wBAAgB,0BAA0B,CACxC,IAAI,GAAE;IAAE,WAAW,CAAC,EAAE,eAAe,CAAC;IAAC,UAAU,CAAC,EAAE,OAAO,CAAA;CAAO,GACjE,OAAO,KAAK,CAqDd;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,CAmCnB"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { AuthStorage } from "../auth/storage.js";
|
|
2
2
|
import { supportsMaxReasoningEffort } from "../thinking.js";
|
|
3
3
|
import { runCatalogThinkingLevel } from "../thinking-catalog.js";
|
|
4
|
-
import { ProviderAuthRequiredError } from "../auth/provider-auth-error.js";
|
|
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
7
|
//#region src/providers/openai-codex.ts
|
|
@@ -162,7 +162,10 @@ function buildOpenAICodexOAuthFetch(opts = {}) {
|
|
|
162
162
|
...body ? { duplex: "half" } : {}
|
|
163
163
|
});
|
|
164
164
|
try {
|
|
165
|
-
return await fetch(finalRequest)
|
|
165
|
+
return await rejectUnauthorizedResponse(await fetch(finalRequest), {
|
|
166
|
+
providerName: "OpenAI Codex",
|
|
167
|
+
requestUrl: finalUrl.toString()
|
|
168
|
+
});
|
|
166
169
|
} catch (error) {
|
|
167
170
|
if (error && typeof error === "object") Object.assign(error, { requestUrl: finalUrl.toString() });
|
|
168
171
|
throw error;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"openai-codex.js","names":[],"sources":["../../src/providers/openai-codex.ts"],"sourcesContent":["/**\n * OpenAI Codex OAuth Provider\n *\n * Uses OAuth tokens from AuthStorage to authenticate with ChatGPT Plus/Pro subscription.\n * This allows access to OpenAI models through the ChatGPT OAuth flow.\n *\n * Inspired by opencode's Codex plugin implementation:\n * https://github.com/sst/opencode/blob/main/packages/opencode/src/plugin/codex.ts\n */\n\nimport { createOpenAI } from '@ai-sdk/openai';\nimport type { MastraModelConfig } from '@mastra/core/llm';\nimport { wrapLanguageModel } from 'ai';\nimport type { LanguageModelMiddleware } from 'ai';\nimport { ProviderAuthRequiredError } 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 type { ThinkingLevelSetting } from '../thinking.js';\nexport { supportsMaxReasoningEffort } from '../thinking.js';\n\n// Codex API endpoint (not standard OpenAI API)\nconst CODEX_API_ENDPOINT = 'https://chatgpt.com/backend-api/codex/responses';\nconst CODEX_ORIGINATOR = 'mastracode';\nconst CODEX_USER_AGENT = 'mastracode';\n\n// Singleton auth storage instance (shared with claude-max.ts)\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// Default instructions for Codex API (required)\nconst CODEX_INSTRUCTIONS = `You are an interactive CLI tool that helps users with software engineering tasks. Use the instructions below and the tools available to you to assist the user.\n\nIMPORTANT: You should be concise, direct, and helpful. Focus on solving the user's problem efficiently.`;\n\nexport type ThinkingLevel = ThinkingLevelSetting;\n\nconst GPT5_MODEL_RE = /^gpt-5(?:\\.|-|$)/;\n\nexport function getEffectiveThinkingLevel(modelId: string, level: ThinkingLevel): ThinkingLevel {\n // GPT-5.* models on Codex require at least low reasoning.\n const requestedLevel = GPT5_MODEL_RE.test(modelId) && level === 'off' ? 'low' : level;\n return runCatalogThinkingLevel(`openai/${modelId}`, requestedLevel);\n}\n\n// Map thinkingLevel state values to OpenAI reasoningEffort values.\n// undefined means omit the parameter (no reasoning). Model-dependent fitting\n// happens in getEffectiveThinkingLevel before this lookup.\nexport const THINKING_LEVEL_TO_REASONING_EFFORT: Record<ThinkingLevel, string | undefined> = {\n off: undefined,\n low: 'low',\n medium: 'medium',\n high: 'high',\n xhigh: 'xhigh',\n max: 'max',\n};\n\n/**\n * Create Codex middleware with the given reasoning effort level.\n */\nexport function createCodexMiddleware(reasoningEffort?: string): LanguageModelMiddleware {\n return {\n specificationVersion: 'v3',\n transformParams: async ({ params }) => {\n // Remove topP if temperature is set (OpenAI doesn't like both)\n if (params.temperature !== undefined && params.temperature !== null) {\n delete params.topP;\n }\n\n // Codex API requires specific settings via providerOptions\n // Use type assertion to satisfy JSONValue constraints\n params.providerOptions = {\n ...params.providerOptions,\n openai: {\n ...(params.providerOptions?.openai ?? {}),\n instructions: CODEX_INSTRUCTIONS,\n // Codex API requires store to be false\n store: false,\n // Enable reasoning for Codex models — without this, the model\n // skips the reasoning/action phase and goes straight to final_answer,\n // resulting in narration instead of tool calls.\n ...(reasoningEffort ? { reasoningEffort } : {}),\n },\n } as typeof params.providerOptions;\n\n return params;\n },\n };\n}\n\n/**\n * Create middleware that forwards a resolved reasoning effort to an\n * OpenAI-compatible provider as `providerOptions[providerKey].reasoningEffort`.\n *\n * Returns `undefined` when `reasoningEffort` is unset so callers wrap nothing\n * (e.g. thinking level `off`), leaving the wire request without a\n * `reasoning_effort` field. Unlike {@link createCodexMiddleware}, it does not\n * inject Codex-only options (instructions/store); it only sets reasoning\n * effort, keyed by the caller-supplied provider id.\n */\nexport function createReasoningEffortMiddleware(\n providerKey: string,\n reasoningEffort?: string,\n): LanguageModelMiddleware | undefined {\n if (!reasoningEffort) return undefined;\n return {\n specificationVersion: 'v3',\n transformParams: async ({ params }) => {\n params.providerOptions = {\n ...params.providerOptions,\n [providerKey]: {\n ...(params.providerOptions?.[providerKey] ?? {}),\n reasoningEffort,\n },\n } as typeof params.providerOptions;\n\n return params;\n },\n };\n}\n\n/**\n * Get a live OAuth bearer token for the Codex OAuth credential.\n *\n * Refreshes the token if it's expired, and returns the credential's\n * accountId alongside the access token. Throws if the user isn't logged in\n * or if the refresh fails.\n *\n * This is the only piece of Codex auth that is genuinely shared between\n * the main agent's fetch (`buildOpenAICodexOAuthFetch`) and the Stagehand\n * fetch (`buildCodexStagehandFetch`).\n */\nasync function getCodexBearer(\n authStorage?: CredentialStore,\n): Promise<{ accessToken: string; accountId: string | undefined }> {\n const storage = authStorage ?? getAuthStorage();\n storage.reload();\n\n let cred = storage.get('openai-codex');\n if (!cred || cred.type !== 'oauth') {\n throw new ProviderAuthRequiredError('Not logged in to OpenAI Codex.');\n }\n\n if (storage.getOAuthCredential) {\n cred = await storage.getOAuthCredential('openai-codex');\n if (!cred) throw new ProviderAuthRequiredError('Failed to refresh the OpenAI Codex token.');\n } else if (Date.now() >= cred.expires) {\n const refreshedToken = await storage.getApiKey('openai-codex');\n if (!refreshedToken) {\n throw new ProviderAuthRequiredError('Failed to refresh the OpenAI Codex token.');\n }\n storage.reload();\n const reloaded = storage.get('openai-codex');\n if (!reloaded || reloaded.type !== 'oauth') {\n throw new ProviderAuthRequiredError('Not logged in to OpenAI Codex.');\n }\n cred = { ...reloaded, access: refreshedToken };\n }\n\n return { accessToken: cred.access, accountId: (cred as any).accountId as string | undefined };\n}\n\n/**\n * Build a fetch function that handles OpenAI Codex OAuth.\n * Preserves non-authorization headers from init.\n * When rewriteUrl is true (default), rewrites /v1/responses and /chat/completions\n * to the Codex API endpoint. Set rewriteUrl: false for gateway usage where the\n * SDK already targets the correct URL.\n */\nexport function buildOpenAICodexOAuthFetch(\n opts: { authStorage?: CredentialStore; rewriteUrl?: boolean } = {},\n): typeof fetch {\n return (async (url: string | URL | Request, init?: Parameters<typeof fetch>[1]) => {\n const { accessToken, accountId } = await getCodexBearer(opts.authStorage);\n const { headers: initHeaders, ...requestInit } = init ?? {};\n const request = new Request(url, requestInit);\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 (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 if (!headers.has('originator')) {\n headers.set('originator', CODEX_ORIGINATOR);\n }\n if (!headers.has('User-Agent')) {\n headers.set('User-Agent', CODEX_USER_AGENT);\n }\n if (accountId) {\n headers.set('ChatGPT-Account-ID', accountId);\n }\n\n // URL rewriting — only when rewriteUrl !== false\n const parsed = new URL(request.url);\n const shouldRewrite =\n opts.rewriteUrl !== false &&\n (parsed.pathname.includes('/v1/responses') || parsed.pathname.includes('/chat/completions'));\n const finalUrl = shouldRewrite ? new URL(CODEX_API_ENDPOINT) : parsed;\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 fetch(finalRequest);\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\n/**\n * Build a fetch function for Stagehand-on-Codex.\n *\n * The Codex backend has two requirements that AI SDK's non-streaming\n * `generateText` path doesn't naturally satisfy:\n *\n * 1. `stream: true` must be set on every request body.\n * 2. The response is delivered as Server-Sent Events; AI SDK's\n * non-streaming code path expects a single JSON body.\n *\n * This fetch forces streaming on the outgoing request, collects the SSE\n * events, and synthesizes the non-streaming JSON shape that\n * `@ai-sdk/openai`'s Responses API parser expects.\n *\n * Headers, OAuth refresh, and URL targeting are handled by the caller via\n * `baseURL` / `headers` on the AI SDK provider; this fetch only injects the\n * live OAuth bearer per call.\n */\nexport function buildCodexStagehandFetch(authStorage: AuthStorage): typeof fetch {\n return (async (url: string | URL | Request, init?: Parameters<typeof fetch>[1]) => {\n // Refresh + inject the OAuth bearer per call.\n const { accessToken } = await getCodexBearer(authStorage);\n const { headers: initHeaders, ...requestInit } = init ?? {};\n const request = new Request(url, requestInit);\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('Accept', 'text/event-stream');\n\n // Stagehand sends JSON; force stream: true while preserving Request bodies.\n let body = await request.clone().text();\n try {\n const parsed = JSON.parse(body) as Record<string, unknown>;\n parsed.stream = true;\n body = JSON.stringify(parsed);\n if (!headers.has('content-type')) headers.set('content-type', 'application/json');\n } catch {\n // Not JSON; leave as-is.\n }\n\n const upstream = await fetch(\n new Request(request, {\n headers,\n ...(request.method === 'GET' || request.method === 'HEAD' ? {} : { body }),\n }),\n );\n if (!upstream.ok) return upstream;\n\n // Aggregate SSE -> synthesized non-streaming Response\n const aggregated = await aggregateCodexStream(upstream);\n return new Response(aggregated, {\n status: 200,\n headers: { 'content-type': 'application/json' },\n });\n }) as typeof fetch;\n}\n\n/**\n * Read an SSE Response and reduce it to a single JSON string matching the\n * non-streaming OpenAI Responses-API shape.\n *\n * Event vocabulary we care about (per OpenAI Responses API streaming):\n * - response.created → carries `response` object (id, model, usage stub)\n * - response.output_item.added/done → output items (message, reasoning, etc.)\n * - response.output_text.delta → text chunks\n * - response.completed → final `response` snapshot incl. usage\n * - response.error / error → bubble up as a thrown body\n *\n * Reasoning events (`response.reasoning_summary.*`) are intentionally ignored\n * for the non-streaming text response.\n */\nasync function aggregateCodexStream(response: Response): Promise<string> {\n if (!response.body) {\n throw new Error('Codex streaming response had no body');\n }\n\n const reader = response.body.getReader();\n const decoder = new TextDecoder('utf-8');\n let buffer = '';\n\n let finalResponse: any = null;\n let createdResponse: any = null;\n // Track output_items by index so we can rebuild the final array\n const items = new Map<number, any>();\n // Accumulate output_text deltas keyed by item_index + content_index\n const textBuffers = new Map<string, string>();\n\n const handleEvent = (event: { event?: string; data?: string }) => {\n if (!event.data || event.data === '[DONE]') return;\n let payload: any;\n try {\n payload = JSON.parse(event.data);\n } catch {\n return;\n }\n const type: string = payload.type ?? event.event ?? '';\n\n switch (type) {\n case 'response.created': {\n createdResponse = payload.response ?? createdResponse;\n break;\n }\n case 'response.output_item.added': {\n if (typeof payload.output_index === 'number' && payload.item) {\n items.set(payload.output_index, payload.item);\n }\n break;\n }\n case 'response.output_item.done': {\n if (typeof payload.output_index === 'number' && payload.item) {\n items.set(payload.output_index, payload.item);\n }\n break;\n }\n case 'response.output_text.delta': {\n const key = `${payload.output_index}:${payload.content_index ?? 0}`;\n textBuffers.set(key, (textBuffers.get(key) ?? '') + (payload.delta ?? ''));\n break;\n }\n case 'response.completed': {\n finalResponse = payload.response ?? finalResponse;\n break;\n }\n case 'response.error':\n case 'error': {\n throw new Error(`Codex stream error: ${JSON.stringify(payload.error ?? payload)}`);\n }\n default:\n // Ignore reasoning / unknown events\n break;\n }\n };\n\n // SSE parser: events separated by blank line; lines like \"event: x\" / \"data: y\"\n // Normalize CRLF→LF so \\r\\n\\r\\n event boundaries parse correctly (SSE spec allows CRLF).\n const processChunk = (chunk: string) => {\n buffer += chunk.replace(/\\r\\n/g, '\\n');\n let sepIdx: number;\n while ((sepIdx = buffer.indexOf('\\n\\n')) !== -1) {\n const raw = buffer.slice(0, sepIdx);\n buffer = buffer.slice(sepIdx + 2);\n const event: { event?: string; data?: string } = {};\n const dataLines: string[] = [];\n for (const line of raw.split('\\n')) {\n if (line.startsWith('event:')) {\n event.event = line.slice(6).trim();\n } else if (line.startsWith('data:')) {\n dataLines.push(line.slice(5).trimStart());\n }\n }\n if (dataLines.length > 0) {\n event.data = dataLines.join('\\n');\n }\n handleEvent(event);\n }\n };\n\n try {\n while (true) {\n const { value, done } = await reader.read();\n if (done) break;\n processChunk(decoder.decode(value, { stream: true }));\n }\n processChunk(decoder.decode());\n } finally {\n reader.releaseLock();\n }\n\n // Stitch accumulated text deltas back into their items\n const base = finalResponse ?? createdResponse ?? { output: [] };\n const finalItems = Array.from(items.entries())\n .sort(([a], [b]) => a - b)\n .map(([index, item]) => {\n // Patch message-type items' content text using buffered deltas\n if (item?.type === 'message' && Array.isArray(item.content)) {\n item.content = item.content.map((c: any, ci: number) => {\n const key = `${index}:${ci}`;\n if (textBuffers.has(key)) {\n return { ...c, text: textBuffers.get(key) };\n }\n return c;\n });\n }\n return item;\n });\n\n base.output = finalItems.length > 0 ? finalItems : (base.output ?? []);\n\n return JSON.stringify(base);\n}\n\n/**\n * Creates an OpenAI model using ChatGPT OAuth authentication\n * Uses OAuth tokens from AuthStorage (auto-refreshes when needed)\n *\n * IMPORTANT: This uses the Codex API endpoint, not the standard OpenAI API.\n * URLs are rewritten from /v1/responses or /chat/completions to the Codex endpoint.\n */\nexport function openaiCodexProvider(\n modelId: string = 'codex-mini-latest',\n options?: { thinkingLevel?: ThinkingLevel; headers?: Record<string, string>; authStorage?: CredentialStore },\n): MastraModelConfig {\n const requestedLevel: ThinkingLevel = options?.thinkingLevel ?? 'medium';\n const effectiveLevel = getEffectiveThinkingLevel(modelId, requestedLevel);\n const reasoningEffort = THINKING_LEVEL_TO_REASONING_EFFORT[effectiveLevel];\n const middleware = createCodexMiddleware(reasoningEffort);\n const headers = options?.headers;\n\n const baseURL = process.env.OPENAI_BASE_URL;\n\n // Test environment: use API key\n if (process.env.NODE_ENV === 'test' || process.env.VITEST) {\n const openai = createOpenAI({\n apiKey: 'test-api-key',\n baseURL,\n headers,\n });\n return wrapLanguageModel({\n model: openai.responses(modelId),\n middleware: [middleware],\n });\n }\n\n const openai = createOpenAI({\n apiKey: 'oauth-dummy-key',\n baseURL,\n headers,\n fetch: buildOpenAICodexOAuthFetch({ authStorage: options?.authStorage }) as any,\n });\n\n // Use the responses API for Codex models\n // Wrap with middleware\n return wrapLanguageModel({\n model: openai.responses(modelId),\n middleware: [middleware],\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAsBA,MAAM,qBAAqB;AAC3B,MAAM,mBAAmB;AACzB,MAAM,mBAAmB;AAGzB,IAAI,sBAA0C;;;;AAK9C,SAAgB,iBAA8B;CAC5C,IAAI,CAAC,qBACH,sBAAsB,IAAI,YAAY;CAExC,OAAO;AACT;;;;AAKA,SAAgB,eAAe,SAAwC;CACrE,sBAAsB,WAAW;AACnC;AAGA,MAAM,qBAAqB;;;AAM3B,MAAM,gBAAgB;AAEtB,SAAgB,0BAA0B,SAAiB,OAAqC;CAE9F,MAAM,iBAAiB,cAAc,KAAK,OAAO,KAAK,UAAU,QAAQ,QAAQ;CAChF,OAAO,wBAAwB,UAAU,WAAW,cAAc;AACpE;AAKA,MAAa,qCAAgF;CAC3F,KAAK,KAAA;CACL,KAAK;CACL,QAAQ;CACR,MAAM;CACN,OAAO;CACP,KAAK;AACP;;;;AAKA,SAAgB,sBAAsB,iBAAmD;CACvF,OAAO;EACL,sBAAsB;EACtB,iBAAiB,OAAO,EAAE,aAAa;GAErC,IAAI,OAAO,gBAAgB,KAAA,KAAa,OAAO,gBAAgB,MAC7D,OAAO,OAAO;GAKhB,OAAO,kBAAkB;IACvB,GAAG,OAAO;IACV,QAAQ;KACN,GAAI,OAAO,iBA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D,MAAM,UAAU,SAAS;CAEzB,MAAM,UAAU,QAAQ,IAAI;CAG5B,IAAI,QAAQ,IAAI,aAAa,UAAU,QAAQ,IAAI,QAMjD,OAAO,kBAAkB;EACvB,OANa,aAAa;GAC1B,QAAQ;GACR;GACA;EACF,CAEc,CAAC,CAAC,UAAU,OAAO;EAC/B,YAAY,CAAC,UAAU;CACzB,CAAC;CAYH,OAAO,kBAAkB;EACvB,OAVa,aAAa;GAC1B,QAAQ;GACR;GACA;GACA,OAAO,2BAA2B,EAAE,aAAa,SAAS,YAAY,CAAC;EACzE,CAKc,CAAC,CAAC,UAAU,OAAO;EAC/B,YAAY,CAAC,UAAU;CACzB,CAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"openai-codex.js","names":[],"sources":["../../src/providers/openai-codex.ts"],"sourcesContent":["/**\n * OpenAI Codex OAuth Provider\n *\n * Uses OAuth tokens from AuthStorage to authenticate with ChatGPT Plus/Pro subscription.\n * This allows access to OpenAI models through the ChatGPT OAuth flow.\n *\n * Inspired by opencode's Codex plugin implementation:\n * https://github.com/sst/opencode/blob/main/packages/opencode/src/plugin/codex.ts\n */\n\nimport { createOpenAI } from '@ai-sdk/openai';\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 type { ThinkingLevelSetting } from '../thinking.js';\nexport { supportsMaxReasoningEffort } from '../thinking.js';\n\n// Codex API endpoint (not standard OpenAI API)\nconst CODEX_API_ENDPOINT = 'https://chatgpt.com/backend-api/codex/responses';\nconst CODEX_ORIGINATOR = 'mastracode';\nconst CODEX_USER_AGENT = 'mastracode';\n\n// Singleton auth storage instance (shared with claude-max.ts)\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// Default instructions for Codex API (required)\nconst CODEX_INSTRUCTIONS = `You are an interactive CLI tool that helps users with software engineering tasks. Use the instructions below and the tools available to you to assist the user.\n\nIMPORTANT: You should be concise, direct, and helpful. Focus on solving the user's problem efficiently.`;\n\nexport type ThinkingLevel = ThinkingLevelSetting;\n\nconst GPT5_MODEL_RE = /^gpt-5(?:\\.|-|$)/;\n\nexport function getEffectiveThinkingLevel(modelId: string, level: ThinkingLevel): ThinkingLevel {\n // GPT-5.* models on Codex require at least low reasoning.\n const requestedLevel = GPT5_MODEL_RE.test(modelId) && level === 'off' ? 'low' : level;\n return runCatalogThinkingLevel(`openai/${modelId}`, requestedLevel);\n}\n\n// Map thinkingLevel state values to OpenAI reasoningEffort values.\n// undefined means omit the parameter (no reasoning). Model-dependent fitting\n// happens in getEffectiveThinkingLevel before this lookup.\nexport const THINKING_LEVEL_TO_REASONING_EFFORT: Record<ThinkingLevel, string | undefined> = {\n off: undefined,\n low: 'low',\n medium: 'medium',\n high: 'high',\n xhigh: 'xhigh',\n max: 'max',\n};\n\n/**\n * Create Codex middleware with the given reasoning effort level.\n */\nexport function createCodexMiddleware(reasoningEffort?: string): LanguageModelMiddleware {\n return {\n specificationVersion: 'v3',\n transformParams: async ({ params }) => {\n // Remove topP if temperature is set (OpenAI doesn't like both)\n if (params.temperature !== undefined && params.temperature !== null) {\n delete params.topP;\n }\n\n // Codex API requires specific settings via providerOptions\n // Use type assertion to satisfy JSONValue constraints\n params.providerOptions = {\n ...params.providerOptions,\n openai: {\n ...(params.providerOptions?.openai ?? {}),\n instructions: CODEX_INSTRUCTIONS,\n // Codex API requires store to be false\n store: false,\n // Enable reasoning for Codex models — without this, the model\n // skips the reasoning/action phase and goes straight to final_answer,\n // resulting in narration instead of tool calls.\n ...(reasoningEffort ? { reasoningEffort } : {}),\n },\n } as typeof params.providerOptions;\n\n return params;\n },\n };\n}\n\n/**\n * Create middleware that forwards a resolved reasoning effort to an\n * OpenAI-compatible provider as `providerOptions[providerKey].reasoningEffort`.\n *\n * Returns `undefined` when `reasoningEffort` is unset so callers wrap nothing\n * (e.g. thinking level `off`), leaving the wire request without a\n * `reasoning_effort` field. Unlike {@link createCodexMiddleware}, it does not\n * inject Codex-only options (instructions/store); it only sets reasoning\n * effort, keyed by the caller-supplied provider id.\n */\nexport function createReasoningEffortMiddleware(\n providerKey: string,\n reasoningEffort?: string,\n): LanguageModelMiddleware | undefined {\n if (!reasoningEffort) return undefined;\n return {\n specificationVersion: 'v3',\n transformParams: async ({ params }) => {\n params.providerOptions = {\n ...params.providerOptions,\n [providerKey]: {\n ...(params.providerOptions?.[providerKey] ?? {}),\n reasoningEffort,\n },\n } as typeof params.providerOptions;\n\n return params;\n },\n };\n}\n\n/**\n * Get a live OAuth bearer token for the Codex OAuth credential.\n *\n * Refreshes the token if it's expired, and returns the credential's\n * accountId alongside the access token. Throws if the user isn't logged in\n * or if the refresh fails.\n *\n * This is the only piece of Codex auth that is genuinely shared between\n * the main agent's fetch (`buildOpenAICodexOAuthFetch`) and the Stagehand\n * fetch (`buildCodexStagehandFetch`).\n */\nasync function getCodexBearer(\n authStorage?: CredentialStore,\n): Promise<{ accessToken: string; accountId: string | undefined }> {\n const storage = authStorage ?? getAuthStorage();\n storage.reload();\n\n let cred = storage.get('openai-codex');\n if (!cred || cred.type !== 'oauth') {\n throw new ProviderAuthRequiredError('Not logged in to OpenAI Codex.');\n }\n\n if (storage.getOAuthCredential) {\n cred = await storage.getOAuthCredential('openai-codex');\n if (!cred) throw new ProviderAuthRequiredError('Failed to refresh the OpenAI Codex token.');\n } else if (Date.now() >= cred.expires) {\n const refreshedToken = await storage.getApiKey('openai-codex');\n if (!refreshedToken) {\n throw new ProviderAuthRequiredError('Failed to refresh the OpenAI Codex token.');\n }\n storage.reload();\n const reloaded = storage.get('openai-codex');\n if (!reloaded || reloaded.type !== 'oauth') {\n throw new ProviderAuthRequiredError('Not logged in to OpenAI Codex.');\n }\n cred = { ...reloaded, access: refreshedToken };\n }\n\n return { accessToken: cred.access, accountId: (cred as any).accountId as string | undefined };\n}\n\n/**\n * Build a fetch function that handles OpenAI Codex OAuth.\n * Preserves non-authorization headers from init.\n * When rewriteUrl is true (default), rewrites /v1/responses and /chat/completions\n * to the Codex API endpoint. Set rewriteUrl: false for gateway usage where the\n * SDK already targets the correct URL.\n */\nexport function buildOpenAICodexOAuthFetch(\n opts: { authStorage?: CredentialStore; rewriteUrl?: boolean } = {},\n): typeof fetch {\n return (async (url: string | URL | Request, init?: Parameters<typeof fetch>[1]) => {\n const { accessToken, accountId } = await getCodexBearer(opts.authStorage);\n const { headers: initHeaders, ...requestInit } = init ?? {};\n const request = new Request(url, requestInit);\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 (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 if (!headers.has('originator')) {\n headers.set('originator', CODEX_ORIGINATOR);\n }\n if (!headers.has('User-Agent')) {\n headers.set('User-Agent', CODEX_USER_AGENT);\n }\n if (accountId) {\n headers.set('ChatGPT-Account-ID', accountId);\n }\n\n // URL rewriting — only when rewriteUrl !== false\n const parsed = new URL(request.url);\n const shouldRewrite =\n opts.rewriteUrl !== false &&\n (parsed.pathname.includes('/v1/responses') || parsed.pathname.includes('/chat/completions'));\n const finalUrl = shouldRewrite ? new URL(CODEX_API_ENDPOINT) : parsed;\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: 'OpenAI Codex',\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\n/**\n * Build a fetch function for Stagehand-on-Codex.\n *\n * The Codex backend has two requirements that AI SDK's non-streaming\n * `generateText` path doesn't naturally satisfy:\n *\n * 1. `stream: true` must be set on every request body.\n * 2. The response is delivered as Server-Sent Events; AI SDK's\n * non-streaming code path expects a single JSON body.\n *\n * This fetch forces streaming on the outgoing request, collects the SSE\n * events, and synthesizes the non-streaming JSON shape that\n * `@ai-sdk/openai`'s Responses API parser expects.\n *\n * Headers, OAuth refresh, and URL targeting are handled by the caller via\n * `baseURL` / `headers` on the AI SDK provider; this fetch only injects the\n * live OAuth bearer per call.\n */\nexport function buildCodexStagehandFetch(authStorage: AuthStorage): typeof fetch {\n return (async (url: string | URL | Request, init?: Parameters<typeof fetch>[1]) => {\n // Refresh + inject the OAuth bearer per call.\n const { accessToken } = await getCodexBearer(authStorage);\n const { headers: initHeaders, ...requestInit } = init ?? {};\n const request = new Request(url, requestInit);\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('Accept', 'text/event-stream');\n\n // Stagehand sends JSON; force stream: true while preserving Request bodies.\n let body = await request.clone().text();\n try {\n const parsed = JSON.parse(body) as Record<string, unknown>;\n parsed.stream = true;\n body = JSON.stringify(parsed);\n if (!headers.has('content-type')) headers.set('content-type', 'application/json');\n } catch {\n // Not JSON; leave as-is.\n }\n\n const upstream = await fetch(\n new Request(request, {\n headers,\n ...(request.method === 'GET' || request.method === 'HEAD' ? {} : { body }),\n }),\n );\n if (!upstream.ok) return upstream;\n\n // Aggregate SSE -> synthesized non-streaming Response\n const aggregated = await aggregateCodexStream(upstream);\n return new Response(aggregated, {\n status: 200,\n headers: { 'content-type': 'application/json' },\n });\n }) as typeof fetch;\n}\n\n/**\n * Read an SSE Response and reduce it to a single JSON string matching the\n * non-streaming OpenAI Responses-API shape.\n *\n * Event vocabulary we care about (per OpenAI Responses API streaming):\n * - response.created → carries `response` object (id, model, usage stub)\n * - response.output_item.added/done → output items (message, reasoning, etc.)\n * - response.output_text.delta → text chunks\n * - response.completed → final `response` snapshot incl. usage\n * - response.error / error → bubble up as a thrown body\n *\n * Reasoning events (`response.reasoning_summary.*`) are intentionally ignored\n * for the non-streaming text response.\n */\nasync function aggregateCodexStream(response: Response): Promise<string> {\n if (!response.body) {\n throw new Error('Codex streaming response had no body');\n }\n\n const reader = response.body.getReader();\n const decoder = new TextDecoder('utf-8');\n let buffer = '';\n\n let finalResponse: any = null;\n let createdResponse: any = null;\n // Track output_items by index so we can rebuild the final array\n const items = new Map<number, any>();\n // Accumulate output_text deltas keyed by item_index + content_index\n const textBuffers = new Map<string, string>();\n\n const handleEvent = (event: { event?: string; data?: string }) => {\n if (!event.data || event.data === '[DONE]') return;\n let payload: any;\n try {\n payload = JSON.parse(event.data);\n } catch {\n return;\n }\n const type: string = payload.type ?? event.event ?? '';\n\n switch (type) {\n case 'response.created': {\n createdResponse = payload.response ?? createdResponse;\n break;\n }\n case 'response.output_item.added': {\n if (typeof payload.output_index === 'number' && payload.item) {\n items.set(payload.output_index, payload.item);\n }\n break;\n }\n case 'response.output_item.done': {\n if (typeof payload.output_index === 'number' && payload.item) {\n items.set(payload.output_index, payload.item);\n }\n break;\n }\n case 'response.output_text.delta': {\n const key = `${payload.output_index}:${payload.content_index ?? 0}`;\n textBuffers.set(key, (textBuffers.get(key) ?? '') + (payload.delta ?? ''));\n break;\n }\n case 'response.completed': {\n finalResponse = payload.response ?? finalResponse;\n break;\n }\n case 'response.error':\n case 'error': {\n throw new Error(`Codex stream error: ${JSON.stringify(payload.error ?? payload)}`);\n }\n default:\n // Ignore reasoning / unknown events\n break;\n }\n };\n\n // SSE parser: events separated by blank line; lines like \"event: x\" / \"data: y\"\n // Normalize CRLF→LF so \\r\\n\\r\\n event boundaries parse correctly (SSE spec allows CRLF).\n const processChunk = (chunk: string) => {\n buffer += chunk.replace(/\\r\\n/g, '\\n');\n let sepIdx: number;\n while ((sepIdx = buffer.indexOf('\\n\\n')) !== -1) {\n const raw = buffer.slice(0, sepIdx);\n buffer = buffer.slice(sepIdx + 2);\n const event: { event?: string; data?: string } = {};\n const dataLines: string[] = [];\n for (const line of raw.split('\\n')) {\n if (line.startsWith('event:')) {\n event.event = line.slice(6).trim();\n } else if (line.startsWith('data:')) {\n dataLines.push(line.slice(5).trimStart());\n }\n }\n if (dataLines.length > 0) {\n event.data = dataLines.join('\\n');\n }\n handleEvent(event);\n }\n };\n\n try {\n while (true) {\n const { value, done } = await reader.read();\n if (done) break;\n processChunk(decoder.decode(value, { stream: true }));\n }\n processChunk(decoder.decode());\n } finally {\n reader.releaseLock();\n }\n\n // Stitch accumulated text deltas back into their items\n const base = finalResponse ?? createdResponse ?? { output: [] };\n const finalItems = Array.from(items.entries())\n .sort(([a], [b]) => a - b)\n .map(([index, item]) => {\n // Patch message-type items' content text using buffered deltas\n if (item?.type === 'message' && Array.isArray(item.content)) {\n item.content = item.content.map((c: any, ci: number) => {\n const key = `${index}:${ci}`;\n if (textBuffers.has(key)) {\n return { ...c, text: textBuffers.get(key) };\n }\n return c;\n });\n }\n return item;\n });\n\n base.output = finalItems.length > 0 ? finalItems : (base.output ?? []);\n\n return JSON.stringify(base);\n}\n\n/**\n * Creates an OpenAI model using ChatGPT OAuth authentication\n * Uses OAuth tokens from AuthStorage (auto-refreshes when needed)\n *\n * IMPORTANT: This uses the Codex API endpoint, not the standard OpenAI API.\n * URLs are rewritten from /v1/responses or /chat/completions to the Codex endpoint.\n */\nexport function openaiCodexProvider(\n modelId: string = 'codex-mini-latest',\n options?: { thinkingLevel?: ThinkingLevel; headers?: Record<string, string>; authStorage?: CredentialStore },\n): MastraModelConfig {\n const requestedLevel: ThinkingLevel = options?.thinkingLevel ?? 'medium';\n const effectiveLevel = getEffectiveThinkingLevel(modelId, requestedLevel);\n const reasoningEffort = THINKING_LEVEL_TO_REASONING_EFFORT[effectiveLevel];\n const middleware = createCodexMiddleware(reasoningEffort);\n const headers = options?.headers;\n\n const baseURL = process.env.OPENAI_BASE_URL;\n\n // Test environment: use API key\n if (process.env.NODE_ENV === 'test' || process.env.VITEST) {\n const openai = createOpenAI({\n apiKey: 'test-api-key',\n baseURL,\n headers,\n });\n return wrapLanguageModel({\n model: openai.responses(modelId),\n middleware: [middleware],\n });\n }\n\n const openai = createOpenAI({\n apiKey: 'oauth-dummy-key',\n baseURL,\n headers,\n fetch: buildOpenAICodexOAuthFetch({ authStorage: options?.authStorage }) as any,\n });\n\n // Use the responses API for Codex models\n // Wrap with middleware\n return wrapLanguageModel({\n model: openai.responses(modelId),\n middleware: [middleware],\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAsBA,MAAM,qBAAqB;AAC3B,MAAM,mBAAmB;AACzB,MAAM,mBAAmB;AAGzB,IAAI,sBAA0C;;;;AAK9C,SAAgB,iBAA8B;CAC5C,IAAI,CAAC,qBACH,sBAAsB,IAAI,YAAY;CAExC,OAAO;AACT;;;;AAKA,SAAgB,eAAe,SAAwC;CACrE,sBAAsB,WAAW;AACnC;AAGA,MAAM,qBAAqB;;;AAM3B,MAAM,gBAAgB;AAEtB,SAAgB,0BAA0B,SAAiB,OAAqC;CAE9F,MAAM,iBAAiB,cAAc,KAAK,OAAO,KAAK,UAAU,QAAQ,QAAQ;CAChF,OAAO,wBAAwB,UAAU,WAAW,cAAc;AACpE;AAKA,MAAa,qCAAgF;CAC3F,KAAK,KAAA;CACL,KAAK;CACL,QAAQ;CACR,MAA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CAAC,IAAI,GAAE;IAAE,WAAW,CAAC,EAAE,eAAe,CAAA;CAAO,GAAG,OAAO,KAAK,
|
|
1
|
+
{"version":3,"file":"xai.d.ts","sourceRoot":"","sources":["../../src/providers/xai.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAGH,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,2BAA2B,CAAC;AAE1E,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AACjD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAQxD,qDAAqD;AACrD,wBAAgB,cAAc,IAAI,WAAW,CAK5C;AAED,8EAA8E;AAC9E,wBAAgB,cAAc,CAAC,OAAO,EAAE,WAAW,GAAG,SAAS,GAAG,IAAI,CAErE;AAED;;;;GAIG;AACH,wBAAgB,kBAAkB,CAAC,IAAI,GAAE;IAAE,WAAW,CAAC,EAAE,eAAe,CAAA;CAAO,GAAG,OAAO,KAAK,CAyC7F;AAED;;;GAGG;AACH,wBAAgB,WAAW,CACzB,OAAO,EAAE,MAAM,EACf,OAAO,CAAC,EAAE;IAAE,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAAC,WAAW,CAAC,EAAE,eAAe,CAAA;CAAE,GAC5E,UAAU,CAAC,wBAAwB,CAAC,WAAW,CAAC,CAAC,CASnD"}
|
package/dist/providers/xai.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { AuthStorage } from "../auth/storage.js";
|
|
2
|
-
import { ProviderAuthRequiredError } from "../auth/provider-auth-error.js";
|
|
2
|
+
import { ProviderAuthRequiredError, rejectUnauthorizedResponse } from "../auth/provider-auth-error.js";
|
|
3
3
|
import { createOpenAICompatible } from "@ai-sdk/openai-compatible";
|
|
4
4
|
//#region src/providers/xai.ts
|
|
5
5
|
/**
|
|
@@ -42,9 +42,12 @@ function buildXAIOAuthFetch(opts = {}) {
|
|
|
42
42
|
headers.delete("x-api-key");
|
|
43
43
|
headers.set("Authorization", `Bearer ${accessToken}`);
|
|
44
44
|
try {
|
|
45
|
-
return await fetch(url, {
|
|
45
|
+
return await rejectUnauthorizedResponse(await fetch(url, {
|
|
46
46
|
...init,
|
|
47
47
|
headers
|
|
48
|
+
}), {
|
|
49
|
+
providerName: "xAI",
|
|
50
|
+
requestUrl: url instanceof URL ? url.toString() : typeof url === "string" ? url : url.url
|
|
48
51
|
});
|
|
49
52
|
} catch (error) {
|
|
50
53
|
if (error && typeof error === "object") Object.assign(error, { requestUrl: url instanceof URL ? url.toString() : typeof url === "string" ? url : url.url });
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"xai.js","names":[],"sources":["../../src/providers/xai.ts"],"sourcesContent":["/**\n * xAI (Grok) OAuth Provider\n *\n * Uses OAuth tokens from AuthStorage to authenticate with the xAI API.\n * The xAI API speaks an OpenAI-compatible chat format, and the OAuth access\n * token is accepted as a bearer API key, so we plug `@ai-sdk/openai-compatible`\n * into `https://api.x.ai/v1` with a custom fetch that injects the (auto-refreshed)\n * access token.\n */\n\nimport { createOpenAICompatible } from '@ai-sdk/openai-compatible';\nimport type { OpenAICompatibleProvider } from '@ai-sdk/openai-compatible';\nimport { ProviderAuthRequiredError } from '../auth/provider-auth-error.js';\nimport { AuthStorage } from '../auth/storage.js';\nimport type { CredentialStore } from '../auth/types.js';\n\nconst XAI_PROVIDER_ID = 'xai';\nconst XAI_BASE_URL = 'https://api.x.ai/v1';\n\n// Singleton auth storage instance (shared with claude-max.ts / github-copilot.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 * Build a fetch wrapper that authenticates with xAI OAuth.\n * Injects the access token (auto-refreshed by AuthStorage) as a bearer token,\n * preserving non-auth headers from the caller.\n */\nexport function buildXAIOAuthFetch(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 cred = storage.get(XAI_PROVIDER_ID);\n if (!cred || cred.type !== 'oauth') {\n throw new ProviderAuthRequiredError('Not logged in to xAI.');\n }\n\n // getApiKey() refreshes the access token if it has expired.\n const accessToken = await storage.getApiKey(XAI_PROVIDER_ID);\n if (!accessToken) {\n throw new ProviderAuthRequiredError('Failed to refresh the xAI token.');\n }\n\n // Preserve existing headers, strip auth-related ones. Explicit init\n // headers override headers carried by an incoming Request.\n const headers = new Headers(url instanceof Request ? url.headers : undefined);\n if (init?.headers) {\n new Headers(init.headers).forEach((value, key) => headers.set(key, value));\n }\n headers.delete('authorization');\n headers.delete('x-api-key');\n\n headers.set('Authorization', `Bearer ${accessToken}`);\n\n try {\n return await fetch(url, { ...init, headers });\n } catch (error) {\n if (error && typeof error === 'object') {\n Object.assign(error as Record<string, unknown>, {\n requestUrl: url instanceof URL ? url.toString() : typeof url === 'string' ? url : (url as Request).url,\n });\n }\n throw error;\n }\n }) as typeof fetch;\n}\n\n/**\n * Creates an xAI model using OAuth authentication.\n * Uses OAuth tokens from AuthStorage (auto-refreshes when needed).\n */\nexport function xaiProvider(\n modelId: string,\n options?: { headers?: Record<string, string>; authStorage?: CredentialStore },\n): ReturnType<OpenAICompatibleProvider['chatModel']> {\n const provider = createOpenAICompatible({\n name: XAI_PROVIDER_ID,\n baseURL: XAI_BASE_URL,\n apiKey: 'oauth-placeholder', // real auth injected by the custom fetch\n headers: options?.headers,\n fetch: buildXAIOAuthFetch({ authStorage: options?.authStorage }),\n });\n return provider.chatModel(modelId);\n}\n"],"mappings":";;;;;;;;;;;;;AAgBA,MAAM,kBAAkB;AACxB,MAAM,eAAe;AAGrB,IAAI,sBAA0C;;AAG9C,SAAgB,iBAA8B;CAC5C,IAAI,CAAC,qBACH,sBAAsB,IAAI,YAAY;CAExC,OAAO;AACT;;AAGA,SAAgB,eAAe,SAAwC;CACrE,sBAAsB,WAAW;AACnC;;;;;;AAOA,SAAgB,mBAAmB,OAA0C,CAAC,GAAiB;CAC7F,QAAQ,OAAO,KAA6B,SAAuC;EACjF,MAAM,UAAU,KAAK,eAAe,eAAe;EACnD,QAAQ,OAAO;EAEf,MAAM,OAAO,QAAQ,IAAI,eAAe;EACxC,IAAI,CAAC,QAAQ,KAAK,SAAS,SACzB,MAAM,IAAI,0BAA0B,uBAAuB;EAI7D,MAAM,cAAc,MAAM,QAAQ,UAAU,eAAe;EAC3D,IAAI,CAAC,aACH,MAAM,IAAI,0BAA0B,kCAAkC;EAKxE,MAAM,UAAU,IAAI,QAAQ,eAAe,UAAU,IAAI,UAAU,KAAA,CAAS;EAC5E,IAAI,MAAM,SACR,IAAI,QAAQ,KAAK,OAAO,CAAC,CAAC,SAAS,OAAO,QAAQ,QAAQ,IAAI,KAAK,KAAK,CAAC;EAE3E,QAAQ,OAAO,eAAe;EAC9B,QAAQ,OAAO,WAAW;EAE1B,QAAQ,IAAI,iBAAiB,UAAU,aAAa;EAEpD,IAAI;GACF,OAAO,MAAM,MAAM,KAAK;IAAE,GAAG;IAAM;GAAQ,CAAC;
|
|
1
|
+
{"version":3,"file":"xai.js","names":[],"sources":["../../src/providers/xai.ts"],"sourcesContent":["/**\n * xAI (Grok) OAuth Provider\n *\n * Uses OAuth tokens from AuthStorage to authenticate with the xAI API.\n * The xAI API speaks an OpenAI-compatible chat format, and the OAuth access\n * token is accepted as a bearer API key, so we plug `@ai-sdk/openai-compatible`\n * into `https://api.x.ai/v1` with a custom fetch that injects the (auto-refreshed)\n * access token.\n */\n\nimport { createOpenAICompatible } from '@ai-sdk/openai-compatible';\nimport type { OpenAICompatibleProvider } from '@ai-sdk/openai-compatible';\nimport { ProviderAuthRequiredError, rejectUnauthorizedResponse } from '../auth/provider-auth-error.js';\nimport { AuthStorage } from '../auth/storage.js';\nimport type { CredentialStore } from '../auth/types.js';\n\nconst XAI_PROVIDER_ID = 'xai';\nconst XAI_BASE_URL = 'https://api.x.ai/v1';\n\n// Singleton auth storage instance (shared with claude-max.ts / github-copilot.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 * Build a fetch wrapper that authenticates with xAI OAuth.\n * Injects the access token (auto-refreshed by AuthStorage) as a bearer token,\n * preserving non-auth headers from the caller.\n */\nexport function buildXAIOAuthFetch(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 cred = storage.get(XAI_PROVIDER_ID);\n if (!cred || cred.type !== 'oauth') {\n throw new ProviderAuthRequiredError('Not logged in to xAI.');\n }\n\n // getApiKey() refreshes the access token if it has expired.\n const accessToken = await storage.getApiKey(XAI_PROVIDER_ID);\n if (!accessToken) {\n throw new ProviderAuthRequiredError('Failed to refresh the xAI token.');\n }\n\n // Preserve existing headers, strip auth-related ones. Explicit init\n // headers override headers carried by an incoming Request.\n const headers = new Headers(url instanceof Request ? url.headers : undefined);\n if (init?.headers) {\n new Headers(init.headers).forEach((value, key) => headers.set(key, value));\n }\n headers.delete('authorization');\n headers.delete('x-api-key');\n\n headers.set('Authorization', `Bearer ${accessToken}`);\n\n try {\n return await rejectUnauthorizedResponse(await fetch(url, { ...init, headers }), {\n providerName: 'xAI',\n requestUrl: url instanceof URL ? url.toString() : typeof url === 'string' ? url : (url as Request).url,\n });\n } catch (error) {\n if (error && typeof error === 'object') {\n Object.assign(error as Record<string, unknown>, {\n requestUrl: url instanceof URL ? url.toString() : typeof url === 'string' ? url : (url as Request).url,\n });\n }\n throw error;\n }\n }) as typeof fetch;\n}\n\n/**\n * Creates an xAI model using OAuth authentication.\n * Uses OAuth tokens from AuthStorage (auto-refreshes when needed).\n */\nexport function xaiProvider(\n modelId: string,\n options?: { headers?: Record<string, string>; authStorage?: CredentialStore },\n): ReturnType<OpenAICompatibleProvider['chatModel']> {\n const provider = createOpenAICompatible({\n name: XAI_PROVIDER_ID,\n baseURL: XAI_BASE_URL,\n apiKey: 'oauth-placeholder', // real auth injected by the custom fetch\n headers: options?.headers,\n fetch: buildXAIOAuthFetch({ authStorage: options?.authStorage }),\n });\n return provider.chatModel(modelId);\n}\n"],"mappings":";;;;;;;;;;;;;AAgBA,MAAM,kBAAkB;AACxB,MAAM,eAAe;AAGrB,IAAI,sBAA0C;;AAG9C,SAAgB,iBAA8B;CAC5C,IAAI,CAAC,qBACH,sBAAsB,IAAI,YAAY;CAExC,OAAO;AACT;;AAGA,SAAgB,eAAe,SAAwC;CACrE,sBAAsB,WAAW;AACnC;;;;;;AAOA,SAAgB,mBAAmB,OAA0C,CAAC,GAAiB;CAC7F,QAAQ,OAAO,KAA6B,SAAuC;EACjF,MAAM,UAAU,KAAK,eAAe,eAAe;EACnD,QAAQ,OAAO;EAEf,MAAM,OAAO,QAAQ,IAAI,eAAe;EACxC,IAAI,CAAC,QAAQ,KAAK,SAAS,SACzB,MAAM,IAAI,0BAA0B,uBAAuB;EAI7D,MAAM,cAAc,MAAM,QAAQ,UAAU,eAAe;EAC3D,IAAI,CAAC,aACH,MAAM,IAAI,0BAA0B,kCAAkC;EAKxE,MAAM,UAAU,IAAI,QAAQ,eAAe,UAAU,IAAI,UAAU,KAAA,CAAS;EAC5E,IAAI,MAAM,SACR,IAAI,QAAQ,KAAK,OAAO,CAAC,CAAC,SAAS,OAAO,QAAQ,QAAQ,IAAI,KAAK,KAAK,CAAC;EAE3E,QAAQ,OAAO,eAAe;EAC9B,QAAQ,OAAO,WAAW;EAE1B,QAAQ,IAAI,iBAAiB,UAAU,aAAa;EAEpD,IAAI;GACF,OAAO,MAAM,2BAA2B,MAAM,MAAM,KAAK;IAAE,GAAG;IAAM;GAAQ,CAAC,GAAG;IAC9E,cAAc;IACd,YAAY,eAAe,MAAM,IAAI,SAAS,IAAI,OAAO,QAAQ,WAAW,MAAO,IAAgB;GACrG,CAAC;EACH,SAAS,OAAO;GACd,IAAI,SAAS,OAAO,UAAU,UAC5B,OAAO,OAAO,OAAkC,EAC9C,YAAY,eAAe,MAAM,IAAI,SAAS,IAAI,OAAO,QAAQ,WAAW,MAAO,IAAgB,IACrG,CAAC;GAEH,MAAM;EACR;CACF;AACF;;;;;AAMA,SAAgB,YACd,SACA,SACmD;CAQnD,OAPiB,uBAAuB;EACtC,MAAM;EACN,SAAS;EACT,QAAQ;EACR,SAAS,SAAS;EAClB,OAAO,mBAAmB,EAAE,aAAa,SAAS,YAAY,CAAC;CACjE,CACc,CAAC,CAAC,UAAU,OAAO;AACnC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mastra/code-sdk",
|
|
3
|
-
"version": "1.14.0-alpha.
|
|
3
|
+
"version": "1.14.0-alpha.9",
|
|
4
4
|
"description": "Mastra Code SDK: the agent core behind Mastra Code (everything except the TUI) — build your own UIs and surfaces on top of it",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"publishConfig": {
|
|
@@ -63,19 +63,19 @@
|
|
|
63
63
|
"yaml": "^2.7.1",
|
|
64
64
|
"zod": "^4.6.4",
|
|
65
65
|
"@mastra/agent-browser": "0.5.3",
|
|
66
|
-
"@mastra/core": "1.78.0-alpha.
|
|
66
|
+
"@mastra/core": "1.78.0-alpha.9",
|
|
67
|
+
"@mastra/fastembed": "1.3.3",
|
|
67
68
|
"@mastra/duckdb": "1.14.1-alpha.0",
|
|
68
69
|
"@mastra/github-signals": "0.5.1",
|
|
69
|
-
"@mastra/fastembed": "1.3.3",
|
|
70
|
-
"@mastra/memory": "1.38.0-alpha.0",
|
|
71
70
|
"@mastra/mcp": "2.4.1-alpha.1",
|
|
72
71
|
"@mastra/libsql": "1.26.2-alpha.0",
|
|
73
72
|
"@mastra/observability": "1.20.1-alpha.1",
|
|
74
73
|
"@mastra/parallel": "0.1.2",
|
|
75
|
-
"@mastra/schema-compat": "1.3.15-alpha.0",
|
|
76
74
|
"@mastra/pg": "1.31.2-alpha.1",
|
|
77
|
-
"@mastra/
|
|
78
|
-
"@mastra/tavily": "1.1.2"
|
|
75
|
+
"@mastra/schema-compat": "1.3.15-alpha.0",
|
|
76
|
+
"@mastra/tavily": "1.1.2",
|
|
77
|
+
"@mastra/memory": "1.38.0-alpha.0",
|
|
78
|
+
"@mastra/stagehand": "0.3.5"
|
|
79
79
|
},
|
|
80
80
|
"devDependencies": {
|
|
81
81
|
"@libsql/client": "^0.18.0",
|
|
@@ -87,8 +87,8 @@
|
|
|
87
87
|
"typescript-eslint": "^8.57.0",
|
|
88
88
|
"vitest": "4.1.11",
|
|
89
89
|
"@internal/lint": "0.0.143",
|
|
90
|
-
"@internal/
|
|
91
|
-
"@internal/
|
|
90
|
+
"@internal/types-builder": "0.0.118",
|
|
91
|
+
"@internal/workspace-test-utils": "0.0.87"
|
|
92
92
|
},
|
|
93
93
|
"engines": {
|
|
94
94
|
"node": ">=22.19.0"
|