@chat-js/registry 0.2.0-beta.5 → 0.2.0-beta.7
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/README.md +1 -1
- package/dist/r/attach-workspace-file.json +1 -1
- package/dist/r/base/attach-workspace-file.json +1 -1
- package/dist/r/base/default-sandbox.json +1 -1
- package/dist/r/base/docker-sandbox.json +1 -1
- package/dist/r/base/generate-image.json +1 -1
- package/dist/r/base/generate-video.json +1 -1
- package/dist/r/base/guest-chat.json +1 -1
- package/dist/r/base/just-bash-sandbox.json +1 -1
- package/dist/r/base/litellm-gateway.json +2 -3
- package/dist/r/base/mcp.json +2 -2
- package/dist/r/base/openai-compatible-gateway.json +2 -3
- package/dist/r/base/openai-gateway.json +2 -3
- package/dist/r/base/openrouter-gateway.json +1 -2
- package/dist/r/base/registry.json +14 -18
- package/dist/r/base/vercel-gateway.json +3 -3
- package/dist/r/base/vercel-sandbox.json +1 -1
- package/dist/r/default-sandbox.json +1 -1
- package/dist/r/docker-sandbox.json +1 -1
- package/dist/r/eve/deep-research.json +1 -1
- package/dist/r/eve/registry.json +1 -1
- package/dist/r/generate-image.json +1 -1
- package/dist/r/generate-video.json +1 -1
- package/dist/r/guest-chat.json +1 -1
- package/dist/r/just-bash-sandbox.json +1 -1
- package/dist/r/litellm-gateway.json +2 -3
- package/dist/r/mcp.json +2 -2
- package/dist/r/openai-compatible-gateway.json +2 -3
- package/dist/r/openai-gateway.json +2 -3
- package/dist/r/openrouter-gateway.json +1 -2
- package/dist/r/radix/attach-workspace-file.json +1 -1
- package/dist/r/radix/default-sandbox.json +1 -1
- package/dist/r/radix/docker-sandbox.json +1 -1
- package/dist/r/radix/generate-image.json +1 -1
- package/dist/r/radix/generate-video.json +1 -1
- package/dist/r/radix/guest-chat.json +1 -1
- package/dist/r/radix/just-bash-sandbox.json +1 -1
- package/dist/r/radix/litellm-gateway.json +2 -3
- package/dist/r/radix/mcp.json +2 -2
- package/dist/r/radix/openai-compatible-gateway.json +2 -3
- package/dist/r/radix/openai-gateway.json +2 -3
- package/dist/r/radix/openrouter-gateway.json +1 -2
- package/dist/r/radix/registry.json +14 -18
- package/dist/r/radix/vercel-gateway.json +3 -3
- package/dist/r/radix/vercel-sandbox.json +1 -1
- package/dist/r/registry.json +14 -18
- package/dist/r/vercel-gateway.json +3 -3
- package/dist/r/vercel-sandbox.json +1 -1
- package/package.json +11 -12
|
@@ -3,13 +3,12 @@
|
|
|
3
3
|
"name": "litellm-gateway",
|
|
4
4
|
"title": "LiteLLM",
|
|
5
5
|
"dependencies": [
|
|
6
|
-
"@
|
|
7
|
-
"@ai-sdk/openai-compatible@3.0.44"
|
|
6
|
+
"@ai-sdk/openai-compatible@3.0.92"
|
|
8
7
|
],
|
|
9
8
|
"files": [
|
|
10
9
|
{
|
|
11
10
|
"path": "src/gateways/litellm/gateway.ts",
|
|
12
|
-
"content": "import type { LanguageModelV4 } from \"@ai-sdk/provider\";\n\nimport type { AiGatewayModel } from \"
|
|
11
|
+
"content": "import type { LanguageModelV4 } from \"@ai-sdk/provider\";\n\nimport type { AiGatewayModel } from \"@/chatjs/core/gateway/models\";\n\nimport type { GatewayProvider } from \"@/chatjs/core/gateway/gateway-provider\";\n\nimport { GatewayRuntime } from \"@/chatjs/core/gateway/runtime\";\n\nimport type { ImageModel } from \"ai\";\nimport { createOpenAICompatible } from \"@ai-sdk/openai-compatible\";\nimport { z } from \"zod\";\n\nconst MODEL_DISCOVERY_TIMEOUT_MS = 10_000;\nconst TRAILING_SLASHES_REGEX = /\\/+$/u;\n\nconst litellmModelSchema = z.object({\n created: z.number().optional(),\n id: z.string(),\n object: z.string().optional(),\n owned_by: z.string().optional(),\n});\nconst litellmModelsResponseSchema = z.object({\n data: z.array(litellmModelSchema),\n});\n\ntype LiteLLMModelResponse = z.infer<\n typeof litellmModelsResponseSchema\n>[\"data\"][number];\n\nconst getModelsUrl = (baseURL: string): string => {\n const normalizedBaseURL = baseURL.replace(TRAILING_SLASHES_REGEX, \"\");\n if (normalizedBaseURL.endsWith(\"/v1\")) {\n return `${normalizedBaseURL}/models`;\n }\n return `${normalizedBaseURL}/v1/models`;\n};\n\nconst UNKNOWN_MODEL_LIMIT = 0;\nconst toAiGatewayModel = (model: LiteLLMModelResponse): AiGatewayModel => ({\n context_window: UNKNOWN_MODEL_LIMIT,\n created: model.created ?? UNKNOWN_MODEL_LIMIT,\n description: \"\",\n id: model.id,\n max_tokens: UNKNOWN_MODEL_LIMIT,\n name: model.id,\n object: \"model\",\n owned_by: model.owned_by ?? \"litellm\",\n pricing: {},\n type: \"language\",\n});\n\nclass LiteLLMGateway\n extends GatewayRuntime\n implements GatewayProvider<\"litellm\">\n{\n public readonly type = \"litellm\" as const;\n\n private getProvider(): ReturnType<typeof createOpenAICompatible> {\n const apiKey = this.getApiKey();\n const baseURL = this.getBaseURL();\n if (!(typeof baseURL === \"string\" && baseURL !== \"\")) {\n throw new Error(\"LITELLM_BASE_URL is not configured\");\n }\n return createOpenAICompatible({\n apiKey,\n baseURL,\n name: \"litellm\",\n });\n }\n\n public createLanguageModel(modelId: string): LanguageModelV4 {\n const provider = this.getProvider();\n return provider(modelId);\n }\n\n public createImageModel(modelId: string): ImageModel {\n const provider = this.getProvider();\n return provider.imageModel(modelId);\n }\n\n public readonly createVideoModel = null;\n\n private getApiKey(): string | undefined {\n return this.env.LITELLM_API_KEY;\n }\n\n private getBaseURL(): string | undefined {\n const baseURL = this.env.LITELLM_BASE_URL;\n if (baseURL === undefined || baseURL === \"\") {\n return undefined;\n }\n return z.url().parse(baseURL);\n }\n\n public async fetchModels(): Promise<AiGatewayModel[]> {\n const apiKey = this.getApiKey();\n const baseURL = this.getBaseURL();\n\n if (!(typeof baseURL === \"string\" && baseURL !== \"\")) {\n this.log.warn(\"No LITELLM_BASE_URL found, using fallback models\");\n return [...this.getFallbackModels(this.type)];\n }\n\n const url = getModelsUrl(baseURL);\n this.log.debug({ url }, \"Fetching models from LiteLLM proxy\");\n\n try {\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n };\n if (typeof apiKey === \"string\" && apiKey !== \"\") {\n headers.Authorization = `Bearer ${apiKey}`;\n }\n\n const response = await this.fetch(url, {\n headers,\n signal: AbortSignal.timeout(MODEL_DISCOVERY_TIMEOUT_MS),\n });\n\n if (!response.ok) {\n this.log.error(\n { status: response.status, statusText: response.statusText, url },\n \"LiteLLM proxy returned non-OK response\"\n );\n throw new Error(`Failed to fetch models: ${response.statusText}`);\n }\n\n const body = litellmModelsResponseSchema.parse(await response.json());\n const models = body.data;\n const result = models.map((model) => toAiGatewayModel(model));\n\n this.log.info(\n { modelCount: result.length },\n \"Successfully fetched models from LiteLLM proxy\"\n );\n return result;\n } catch (error) {\n this.log.error(\n { err: error, url },\n \"Error fetching models from LiteLLM proxy, falling back to generated models\"\n );\n return [...this.getFallbackModels(this.type)];\n }\n }\n}\nexport { LiteLLMGateway as Gateway, LiteLLMGateway };\n",
|
|
13
12
|
"type": "registry:file",
|
|
14
13
|
"target": "~/chatjs/providers/gateway.ts"
|
|
15
14
|
}
|
package/dist/r/mcp.json
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"name": "mcp",
|
|
4
4
|
"description": "MCP connectors, management pages, OAuth and composer control",
|
|
5
5
|
"dependencies": [
|
|
6
|
-
"@ai-sdk/mcp@2.0.
|
|
6
|
+
"@ai-sdk/mcp@2.0.99",
|
|
7
7
|
"@hookform/resolvers@^5.2.1",
|
|
8
8
|
"@modelcontextprotocol/sdk@^1.24.3",
|
|
9
9
|
"@tanstack/react-query@^5.104.1",
|
|
@@ -175,7 +175,7 @@
|
|
|
175
175
|
},
|
|
176
176
|
{
|
|
177
177
|
"path": "src/plugins/mcp/src/oauth/mcp-client.ts",
|
|
178
|
-
"content": "import type {\n ListPromptsResult,\n ListResourcesResult,\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport {\n auth,\n experimental_createMCPClient as createMCPClient,\n} from \"@ai-sdk/mcp\";\nimport { McpOAuthClientProvider } from \"@/chatjs/plugins/mcp/oauth/mcp-oauth-provider\";\nimport { OAuthAuthorizationRequiredError } from \"@/chatjs/plugins/mcp/oauth/oauth-authorization-required-error\";\nimport type { ReadonlyNativeSurface } from \"@/lib/readonly-native-surface\";\nimport type { Tool } from \"ai\";\nimport { config } from \"@/lib/config\";\nimport { createModuleLogger } from \"@/lib/logger\";\nimport { getBaseUrl } from \"@/lib/url\";\n\nconst log = createModuleLogger(\"mcp-client\");\n\nconst INITIAL_CONNECTION_GENERATION = 0;\nconst MCP_CONNECTION_TIMEOUT_MS = 30_000;\n\nconst getMcpErrorMessage = (error: unknown): string => {\n if (error instanceof Error) {\n return error.message;\n }\n return String(error);\n};\n\ntype McpPreconnect = (\n url: string | URL,\n options?: {\n readonly dns?: boolean;\n readonly http?: boolean;\n readonly https?: boolean;\n readonly tcp?: boolean;\n }\n) => void;\n\nconst isMcpPreconnect = (value: unknown): value is McpPreconnect =>\n typeof value === \"function\";\n\n// Bun's fetch type requires preconnect. Node's does not. Delegate when the\n// runtime provides it so one fetch value satisfies both FetchFunction types.\nconst mcpPreconnect: McpPreconnect = (url, options): void => {\n const candidate: object = globalThis.fetch;\n if (!(\"preconnect\" in candidate)) {\n return;\n }\n const method: unknown = candidate.preconnect;\n if (!isMcpPreconnect(method)) {\n return;\n }\n method(url, options);\n};\n\nconst toMcpSdkFetch = (\n fetchImpl: (\n ...args: Parameters<typeof globalThis.fetch>\n ) => ReturnType<typeof globalThis.fetch>\n): typeof globalThis.fetch =>\n Object.assign(fetchImpl, { preconnect: mcpPreconnect });\n\ntype McpClientInstance = Awaited<ReturnType<typeof createMCPClient>>;\n\ntype McpClientStatus =\n | \"disconnected\"\n | \"connecting\"\n | \"connected\"\n | \"authorizing\"\n | \"incompatible\";\n\n/**\n * MCP Client wrapper with OAuth support.\n * Uses @ai-sdk/mcp's createMCPClient with authProvider for OAuth flow.\n */\nexport class MCPClient {\n private client?: McpClientInstance;\n private generation = INITIAL_CONNECTION_GENERATION;\n private connectionAbort?: AbortController;\n private connectPromise?: Promise<void>;\n private readonly invalidateCache?: () => void;\n private oauthProvider: McpOAuthClientProvider;\n private authorizationUrl?: URL;\n private connectionStatus: McpClientStatus = \"disconnected\";\n\n private readonly id: string;\n private readonly name: string;\n private readonly serverConfig: {\n url: string;\n type: \"http\" | \"sse\";\n headers?: Record<string, string>;\n oauthClientId?: string | null;\n oauthClientSecret?: string | null;\n };\n\n public constructor(\n id: string,\n name: string,\n serverConfig: {\n readonly url: string;\n readonly type: \"http\" | \"sse\";\n readonly headers?: Readonly<Record<string, string>>;\n readonly oauthClientId?: string | null;\n readonly oauthClientSecret?: string | null;\n },\n invalidateCache?: () => void\n ) {\n this.invalidateCache = invalidateCache;\n this.id = id;\n this.name = name;\n this.serverConfig = serverConfig;\n this.oauthProvider = this.createOAuthProvider();\n }\n\n private createOAuthProvider(): McpOAuthClientProvider {\n const { generation } = this;\n const baseUrl = getBaseUrl();\n\n return new McpOAuthClientProvider({\n clientMetadata: {\n client_name: `${config.appPrefix}-${this.name}`,\n grant_types: [\"authorization_code\", \"refresh_token\"],\n redirect_uris: [`${baseUrl}/api/mcp/oauth/callback`],\n response_types: [\"code\"],\n scope: \"mcp:tools\",\n software_id: config.appPrefix,\n software_version: \"1.0.0\",\n token_endpoint_auth_method:\n typeof this.serverConfig.oauthClientId === \"string\" &&\n this.serverConfig.oauthClientId !== \"\" &&\n typeof this.serverConfig.oauthClientSecret === \"string\" &&\n this.serverConfig.oauthClientSecret !== \"\"\n ? \"client_secret_basic\"\n : \"none\",\n },\n mcpConnectorId: this.id,\n oauthClientId: this.serverConfig.oauthClientId,\n oauthClientSecret: this.serverConfig.oauthClientSecret,\n onRedirectToAuthorization: (\n authorizationUrl: ReadonlyNativeSurface<URL>\n ): never => {\n if (generation !== this.generation) {\n throw new Error(\"MCP connection was closed\");\n }\n this.authorizationUrl = authorizationUrl;\n throw new OAuthAuthorizationRequiredError(authorizationUrl);\n },\n serverUrl: this.serverConfig.url,\n });\n }\n\n public get status(): McpClientStatus {\n if (this.authorizationUrl) {\n return \"authorizing\";\n }\n if (this.client) {\n return \"connected\";\n }\n return this.connectionStatus;\n }\n\n public getAuthorizationUrl(): URL | undefined {\n return this.authorizationUrl;\n }\n\n public get serverInfo(): McpClientInstance[\"serverInfo\"] | undefined {\n const { client } = this;\n return client && client.serverInfo;\n }\n\n public async connect({\n oauthState,\n abortSignal,\n }: {\n readonly oauthState?: string;\n readonly abortSignal?: Readonly<\n Pick<\n AbortSignal,\n | \"throwIfAborted\"\n | \"reason\"\n | \"addEventListener\"\n | \"removeEventListener\"\n | \"aborted\"\n >\n >;\n } = {}): Promise<void> {\n if (abortSignal) {\n abortSignal.throwIfAborted();\n }\n if (!this.connectPromise) {\n const { generation } = this;\n this.connectPromise = (async (): Promise<void> => {\n try {\n await this.connectOnce(oauthState);\n } finally {\n // Only close() can retire a pending attempt and allow a replacement.\n if (this.generation === generation) {\n this.connectPromise = undefined;\n }\n }\n })();\n }\n if (!abortSignal) {\n await this.connectPromise;\n return;\n }\n const aborted = Promise.withResolvers<never>();\n const cancel = (): void => {\n aborted.reject(abortSignal.reason);\n };\n abortSignal.addEventListener(\"abort\", cancel, { once: true });\n if (abortSignal.aborted) {\n cancel();\n }\n try {\n await Promise.race([this.connectPromise, aborted.promise]);\n } finally {\n abortSignal.removeEventListener(\"abort\", cancel);\n }\n }\n private async connectOnce(oauthState?: string): Promise<void> {\n if (this.status === \"connected\" && this.client) {\n return;\n }\n\n const { generation, oauthProvider } = this;\n this.connectionAbort = new AbortController();\n const signal = AbortSignal.any([\n this.connectionAbort.signal,\n AbortSignal.timeout(MCP_CONNECTION_TIMEOUT_MS),\n ]);\n this.connectionStatus = \"connecting\";\n\n try {\n // Adopt state if provided (for callback reconciliation).\n if (typeof oauthState === \"string\" && oauthState !== \"\") {\n await oauthProvider.adoptState(oauthState);\n }\n signal.throwIfAborted();\n // AI SDK handles 401 internally and calls auth() with the provider\n const client = await createMCPClient({\n initializationOptions: { signal },\n transport: {\n authProvider: oauthProvider,\n fetch: toMcpSdkFetch(oauthProvider.fetch),\n headers: this.serverConfig.headers,\n type: this.serverConfig.type,\n url: this.serverConfig.url,\n },\n });\n\n if (generation !== this.generation || signal.aborted) {\n await client.close();\n signal.throwIfAborted();\n throw new Error(\"MCP connection was closed\");\n }\n this.client = client;\n this.authorizationUrl = undefined;\n this.connectionStatus = \"connected\";\n } catch (error) {\n if (generation !== this.generation || signal.aborted) {\n if (generation === this.generation) {\n this.authorizationUrl = undefined;\n this.connectionStatus = \"disconnected\";\n }\n throw error;\n }\n // If OAuth required error, status becomes \"authorizing\"\n if (error instanceof OAuthAuthorizationRequiredError) {\n this.connectionStatus = \"authorizing\";\n log.info(\n { authUrl: error.authorizationUrl.toString(), connectorId: this.id },\n \"OAuth authorization required\"\n );\n return;\n }\n\n this.connectionStatus = \"disconnected\";\n throw error;\n }\n }\n /**\n * Lightweight connection test - just checks if we can connect without full discovery.\n * Returns connection status without fetching tools/resources/prompts.\n * @param {Readonly<Pick<AbortSignal, \"throwIfAborted\" | \"reason\" | \"addEventListener\" | \"removeEventListener\" | \"aborted\">> | undefined} abortSignal - Cancels this caller while shared initialization continues.\n * @returns {Promise<{ status: McpClientStatus; needsAuth: boolean; error?: string; }>} The connection or authorization status.\n */\n public async attemptConnection(\n abortSignal?: Readonly<\n Pick<\n AbortSignal,\n | \"throwIfAborted\"\n | \"reason\"\n | \"addEventListener\"\n | \"removeEventListener\"\n | \"aborted\"\n >\n >\n ): Promise<{\n status: McpClientStatus;\n needsAuth: boolean;\n error?: string;\n }> {\n // If already connected, return current status\n if (this.status === \"connected\" && this.client) {\n return { needsAuth: false, status: \"connected\" };\n }\n\n // If already in authorizing state, return that\n if (this.authorizationUrl) {\n return { needsAuth: true, status: \"authorizing\" };\n }\n\n try {\n await this.connect({ abortSignal });\n // Check if OAuth is required (authorizationUrl gets set during connect)\n if (this.authorizationUrl !== undefined) {\n return { needsAuth: true, status: \"authorizing\" };\n }\n return {\n needsAuth: false,\n status: this.client ? \"connected\" : \"disconnected\",\n };\n } catch (error) {\n const errorMessage = getMcpErrorMessage(error);\n log.error(\n {\n connectorId: this.id,\n errorMessage,\n errorStack: error instanceof Error ? error.stack : undefined,\n },\n \"attemptConnection failed\"\n );\n\n // Detect incompatible server errors\n if (\n errorMessage.includes(\"does not support dynamic client registration\")\n ) {\n this.connectionStatus = \"incompatible\";\n return {\n error:\n \"Server requires pre-configured OAuth credentials (does not support dynamic client registration)\",\n needsAuth: false,\n status: \"incompatible\",\n };\n }\n\n return { error: errorMessage, needsAuth: false, status: \"disconnected\" };\n }\n }\n /**\n * Called after callback receives code to complete the OAuth flow.\n * @param {string} code - Authorization code received by the callback.\n * @param {string} state - State used to restore the verifier session.\n */\n public async finishAuth(code: string, state: string): Promise<void> {\n const { generation, oauthProvider } = this;\n // Always adopt the state from the callback to load the session with code verifier\n await oauthProvider.adoptState(state);\n\n // Use the auth function from @ai-sdk/mcp to complete the OAuth flow\n await auth(oauthProvider, {\n authorizationCode: code,\n fetchFn: toMcpSdkFetch(oauthProvider.fetch),\n serverUrl: this.serverConfig.url,\n });\n\n if (generation !== this.generation) {\n throw new Error(\"MCP connection was closed\");\n }\n this.authorizationUrl = undefined;\n // Don't set to connected - tokens are saved, next connect() will use them\n }\n /**\n * Get tools from the MCP server, already in AI SDK format.\n * @param {Parameters<McpClientInstance[\"tools\"]>} args - Native SDK schema options.\n * @returns {Promise<Record<string, Tool>>} The discovered SDK tools.\n */\n public async tools(\n ...args: Parameters<NonNullable<McpClientInstance>[\"tools\"]>\n ): Promise<Record<string, Tool>> {\n const { client } = this;\n if (!client) {\n throw new Error(\"Client not connected\");\n }\n try {\n return await client.tools(...args);\n } catch (error) {\n await this.handlePotentialAuthError(error, client);\n throw error;\n }\n }\n /**\n * List resources from the MCP server.\n * @returns {Promise<ListResourcesResult>} The native MCP resource result.\n */\n public async listResources(): Promise<ListResourcesResult> {\n const { client } = this;\n if (!client) {\n throw new Error(\"Client not connected\");\n }\n try {\n return await client.listResources();\n } catch (error) {\n await this.handlePotentialAuthError(error, client);\n throw error;\n }\n }\n /**\n * List prompts from the MCP server.\n * @returns {Promise<ListPromptsResult>} The native MCP prompt result.\n */\n public async listPrompts(): Promise<ListPromptsResult> {\n const { client } = this;\n if (!client) {\n throw new Error(\"Client not connected\");\n }\n try {\n return await client.experimental_listPrompts();\n } catch (error) {\n await this.handlePotentialAuthError(error, client);\n throw error;\n }\n }\n /**\n * Close the connection to the MCP server.\n */\n public async close(): Promise<void> {\n this.generation += 1;\n const { connectionAbort } = this;\n if (connectionAbort) {\n connectionAbort.abort(new Error(\"MCP connection was closed\"));\n }\n this.connectPromise = undefined;\n this.oauthProvider = this.createOAuthProvider();\n const { client } = this;\n this.client = undefined;\n this.authorizationUrl = undefined;\n this.connectionStatus = \"disconnected\";\n try {\n // Await even without a client to preserve cache-invalidation timing.\n await (client && client.close());\n } catch (error) {\n log.error({ connectorId: this.id, error }, \"Error closing MCP client\");\n }\n if (this.invalidateCache) {\n this.invalidateCache();\n }\n }\n /**\n * Check if an error is an auth error (401/403) and invalidate caches if so.\n * @param {unknown} error - Failure from a connected SDK operation.\n * @param {unknown} origin - Client whose failure is being handled.\n */\n private async handlePotentialAuthError(\n error: unknown,\n origin: unknown\n ): Promise<void> {\n if (this.client !== origin) {\n return;\n }\n const errorMessage = getMcpErrorMessage(error);\n const isAuthError =\n errorMessage.includes(\"401\") ||\n errorMessage.includes(\"403\") ||\n errorMessage.includes(\"Unauthorized\") ||\n errorMessage.includes(\"Forbidden\");\n\n if (isAuthError) {\n log.warn(\n { connectorId: this.id, errorMessage },\n \"Auth error detected, invalidating caches\"\n );\n await this.close();\n }\n }\n}\n",
|
|
178
|
+
"content": "import type {\n ListPromptsResult,\n ListResourcesResult,\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport {\n auth,\n experimental_createMCPClient as createMCPClient,\n} from \"@ai-sdk/mcp\";\nimport { McpOAuthClientProvider } from \"@/chatjs/plugins/mcp/oauth/mcp-oauth-provider\";\nimport { OAuthAuthorizationRequiredError } from \"@/chatjs/plugins/mcp/oauth/oauth-authorization-required-error\";\nimport type { ReadonlyNativeSurface } from \"@/lib/readonly-native-surface\";\nimport type { Tool } from \"ai\";\nimport { config } from \"@/lib/config\";\nimport { createModuleLogger } from \"@/lib/logger\";\nimport { getBaseUrl } from \"@/lib/url\";\n\nconst log = createModuleLogger(\"mcp-client\");\n\nconst INITIAL_CONNECTION_GENERATION = 0;\nconst MCP_CONNECTION_TIMEOUT_MS = 30_000;\n\nconst getMcpErrorMessage = (error: unknown): string => {\n if (error instanceof Error) {\n return error.message;\n }\n return String(error);\n};\n\ntype McpPreconnect = (\n url: string | URL,\n options?: {\n readonly dns?: boolean;\n readonly http?: boolean;\n readonly https?: boolean;\n readonly tcp?: boolean;\n }\n) => void;\n\nconst isMcpPreconnect = (value: unknown): value is McpPreconnect =>\n typeof value === \"function\";\n\n// Bun's fetch type requires preconnect. Node's does not. Delegate when the\n// runtime provides it so one fetch value satisfies both FetchFunction types.\nconst mcpPreconnect: McpPreconnect = (url, options): void => {\n const candidate: object = globalThis.fetch;\n if (!(\"preconnect\" in candidate)) {\n return;\n }\n const method: unknown = candidate.preconnect;\n if (!isMcpPreconnect(method)) {\n return;\n }\n method(url, options);\n};\n\nconst toMcpSdkFetch = (\n fetchImpl: (\n ...args: Parameters<typeof globalThis.fetch>\n ) => ReturnType<typeof globalThis.fetch>\n): typeof globalThis.fetch =>\n Object.assign(fetchImpl, { preconnect: mcpPreconnect });\n\ntype McpClientInstance = Awaited<ReturnType<typeof createMCPClient>>;\n\ntype McpClientStatus =\n | \"disconnected\"\n | \"connecting\"\n | \"connected\"\n | \"authorizing\"\n | \"incompatible\";\n\n/**\n * MCP Client wrapper with OAuth support.\n * Uses @ai-sdk/mcp's createMCPClient with authProvider for OAuth flow.\n */\nexport class MCPClient {\n private client?: McpClientInstance;\n private generation = INITIAL_CONNECTION_GENERATION;\n private connectionAbort?: AbortController;\n private connectPromise?: Promise<void>;\n private readonly invalidateCache?: () => void;\n private oauthProvider: McpOAuthClientProvider;\n private authorizationUrl?: URL;\n private connectionStatus: McpClientStatus = \"disconnected\";\n\n private readonly id: string;\n private readonly name: string;\n private readonly serverConfig: {\n url: string;\n type: \"http\" | \"sse\";\n headers?: Record<string, string>;\n oauthClientId?: string | null;\n oauthClientSecret?: string | null;\n };\n\n public constructor(\n id: string,\n name: string,\n serverConfig: {\n readonly url: string;\n readonly type: \"http\" | \"sse\";\n readonly headers?: Readonly<Record<string, string>>;\n readonly oauthClientId?: string | null;\n readonly oauthClientSecret?: string | null;\n },\n invalidateCache?: () => void\n ) {\n this.invalidateCache = invalidateCache;\n this.id = id;\n this.name = name;\n this.serverConfig = serverConfig;\n this.oauthProvider = this.createOAuthProvider();\n }\n\n private createOAuthProvider(): McpOAuthClientProvider {\n const { generation } = this;\n const baseUrl = getBaseUrl();\n\n return new McpOAuthClientProvider({\n clientMetadata: {\n client_name: `${config.appPrefix}-${this.name}`,\n grant_types: [\"authorization_code\", \"refresh_token\"],\n redirect_uris: [`${baseUrl}/api/mcp/oauth/callback`],\n response_types: [\"code\"],\n scope: \"mcp:tools\",\n software_id: config.appPrefix,\n software_version: \"1.0.0\",\n token_endpoint_auth_method:\n typeof this.serverConfig.oauthClientId === \"string\" &&\n this.serverConfig.oauthClientId !== \"\" &&\n typeof this.serverConfig.oauthClientSecret === \"string\" &&\n this.serverConfig.oauthClientSecret !== \"\"\n ? \"client_secret_basic\"\n : \"none\",\n },\n mcpConnectorId: this.id,\n oauthClientId: this.serverConfig.oauthClientId,\n oauthClientSecret: this.serverConfig.oauthClientSecret,\n onRedirectToAuthorization: (\n authorizationUrl: ReadonlyNativeSurface<URL>\n ): never => {\n if (generation !== this.generation) {\n throw new Error(\"MCP connection was closed\");\n }\n this.authorizationUrl = authorizationUrl;\n throw new OAuthAuthorizationRequiredError(authorizationUrl);\n },\n serverUrl: this.serverConfig.url,\n });\n }\n\n public get status(): McpClientStatus {\n if (this.authorizationUrl) {\n return \"authorizing\";\n }\n if (this.client) {\n return \"connected\";\n }\n return this.connectionStatus;\n }\n\n public getAuthorizationUrl(): URL | undefined {\n return this.authorizationUrl;\n }\n\n public get serverInfo(): McpClientInstance[\"serverInfo\"] | undefined {\n const { client } = this;\n return client && client.serverInfo;\n }\n\n public async connect({\n oauthState,\n abortSignal,\n }: {\n readonly oauthState?: string;\n readonly abortSignal?: Readonly<\n Pick<\n AbortSignal,\n | \"throwIfAborted\"\n | \"reason\"\n | \"addEventListener\"\n | \"removeEventListener\"\n | \"aborted\"\n >\n >;\n } = {}): Promise<void> {\n if (abortSignal) {\n abortSignal.throwIfAborted();\n }\n if (!this.connectPromise) {\n const { generation } = this;\n this.connectPromise = (async (): Promise<void> => {\n try {\n await this.connectOnce(oauthState);\n } finally {\n // Only close() can retire a pending attempt and allow a replacement.\n if (this.generation === generation) {\n this.connectPromise = undefined;\n }\n }\n })();\n }\n if (!abortSignal) {\n await this.connectPromise;\n return;\n }\n const aborted = Promise.withResolvers<never>();\n const cancel = (): void => {\n aborted.reject(abortSignal.reason);\n };\n abortSignal.addEventListener(\"abort\", cancel, { once: true });\n if (abortSignal.aborted) {\n cancel();\n }\n try {\n await Promise.race([this.connectPromise, aborted.promise]);\n } finally {\n abortSignal.removeEventListener(\"abort\", cancel);\n }\n }\n private async connectOnce(oauthState?: string): Promise<void> {\n if (this.status === \"connected\" && this.client) {\n return;\n }\n\n const { generation, oauthProvider } = this;\n this.connectionAbort = new AbortController();\n const signal = AbortSignal.any([\n this.connectionAbort.signal,\n AbortSignal.timeout(MCP_CONNECTION_TIMEOUT_MS),\n ]);\n this.connectionStatus = \"connecting\";\n\n try {\n // Adopt state if provided (for callback reconciliation).\n if (typeof oauthState === \"string\" && oauthState !== \"\") {\n await oauthProvider.adoptState(oauthState);\n }\n signal.throwIfAborted();\n // AI SDK handles 401 internally and calls auth() with the provider\n const client = await createMCPClient({\n initializationOptions: { signal },\n transport: {\n authProvider: oauthProvider,\n fetch: toMcpSdkFetch(oauthProvider.fetch),\n headers: this.serverConfig.headers,\n type: this.serverConfig.type,\n url: this.serverConfig.url,\n },\n });\n\n if (generation !== this.generation || signal.aborted) {\n await client.close();\n signal.throwIfAborted();\n throw new Error(\"MCP connection was closed\");\n }\n this.client = client;\n this.authorizationUrl = undefined;\n this.connectionStatus = \"connected\";\n } catch (error) {\n if (generation !== this.generation || signal.aborted) {\n if (generation === this.generation) {\n this.authorizationUrl = undefined;\n this.connectionStatus = \"disconnected\";\n }\n throw error;\n }\n // If OAuth required error, status becomes \"authorizing\"\n if (error instanceof OAuthAuthorizationRequiredError) {\n this.connectionStatus = \"authorizing\";\n log.info(\n { authUrl: error.authorizationUrl.toString(), connectorId: this.id },\n \"OAuth authorization required\"\n );\n return;\n }\n\n this.connectionStatus = \"disconnected\";\n throw error;\n }\n }\n /**\n * Lightweight connection test - just checks if we can connect without full discovery.\n * Returns connection status without fetching tools/resources/prompts.\n * @param {Readonly<Pick<AbortSignal, \"throwIfAborted\" | \"reason\" | \"addEventListener\" | \"removeEventListener\" | \"aborted\">> | undefined} abortSignal - Cancels this caller while shared initialization continues.\n * @returns {Promise<{ status: McpClientStatus; needsAuth: boolean; error?: string; }>} The connection or authorization status.\n */\n public async attemptConnection(\n abortSignal?: Readonly<\n Pick<\n AbortSignal,\n | \"throwIfAborted\"\n | \"reason\"\n | \"addEventListener\"\n | \"removeEventListener\"\n | \"aborted\"\n >\n >\n ): Promise<{\n status: McpClientStatus;\n needsAuth: boolean;\n error?: string;\n }> {\n // If already connected, return current status\n if (this.status === \"connected\" && this.client) {\n return { needsAuth: false, status: \"connected\" };\n }\n\n // If already in authorizing state, return that\n if (this.authorizationUrl) {\n return { needsAuth: true, status: \"authorizing\" };\n }\n\n try {\n await this.connect({ abortSignal });\n // Check if OAuth is required (authorizationUrl gets set during connect)\n if (this.authorizationUrl !== undefined) {\n return { needsAuth: true, status: \"authorizing\" };\n }\n return {\n needsAuth: false,\n status: this.client ? \"connected\" : \"disconnected\",\n };\n } catch (error) {\n const errorMessage = getMcpErrorMessage(error);\n log.error(\n {\n connectorId: this.id,\n errorMessage,\n errorStack: error instanceof Error ? error.stack : undefined,\n },\n \"attemptConnection failed\"\n );\n\n // Detect incompatible server errors\n if (\n errorMessage.includes(\"does not support dynamic client registration\")\n ) {\n this.connectionStatus = \"incompatible\";\n return {\n error:\n \"Server requires pre-configured OAuth credentials (does not support dynamic client registration)\",\n needsAuth: false,\n status: \"incompatible\",\n };\n }\n\n return { error: errorMessage, needsAuth: false, status: \"disconnected\" };\n }\n }\n /**\n * Called after callback receives code to complete the OAuth flow.\n * @param {string} code - Authorization code received by the callback.\n * @param {string} state - State used to restore the verifier session.\n */\n public async finishAuth(code: string, state: string): Promise<void> {\n const { generation, oauthProvider } = this;\n // Always adopt the state from the callback to load the session with code verifier\n await oauthProvider.adoptState(state);\n\n // Use the auth function from @ai-sdk/mcp to complete the OAuth flow\n await auth(oauthProvider, {\n authorizationCode: code,\n fetchFn: toMcpSdkFetch(oauthProvider.fetch),\n serverUrl: this.serverConfig.url,\n });\n\n if (generation !== this.generation) {\n throw new Error(\"MCP connection was closed\");\n }\n this.authorizationUrl = undefined;\n // Don't set to connected - tokens are saved, next connect() will use them\n }\n /**\n * Get tools from the MCP server, already in AI SDK format.\n * @param {Parameters<McpClientInstance[\"tools\"]>} args - Native SDK schema options.\n * @returns {Promise<Record<string, Tool>>} The discovered SDK tools.\n */\n public async tools(\n ...args: Parameters<NonNullable<McpClientInstance>[\"tools\"]>\n ): Promise<Record<string, Tool>> {\n const { client } = this;\n if (!client) {\n throw new Error(\"Client not connected\");\n }\n try {\n return await client.tools(...args);\n } catch (error) {\n await this.handlePotentialAuthError(error, client);\n throw error;\n }\n }\n /**\n * List resources from the MCP server.\n * @returns {Promise<ListResourcesResult>} The native MCP resource result.\n */\n public async listResources(): Promise<ListResourcesResult> {\n const { client } = this;\n if (!client) {\n throw new Error(\"Client not connected\");\n }\n try {\n return await client.listResources();\n } catch (error) {\n await this.handlePotentialAuthError(error, client);\n throw error;\n }\n }\n /**\n * List prompts from the MCP server.\n * @returns {Promise<ListPromptsResult>} The native MCP prompt result.\n */\n public async listPrompts(): Promise<ListPromptsResult> {\n const { client } = this;\n if (!client) {\n throw new Error(\"Client not connected\");\n }\n try {\n return await client.listPrompts();\n } catch (error) {\n await this.handlePotentialAuthError(error, client);\n throw error;\n }\n }\n /**\n * Close the connection to the MCP server.\n */\n public async close(): Promise<void> {\n this.generation += 1;\n const { connectionAbort } = this;\n if (connectionAbort) {\n connectionAbort.abort(new Error(\"MCP connection was closed\"));\n }\n this.connectPromise = undefined;\n this.oauthProvider = this.createOAuthProvider();\n const { client } = this;\n this.client = undefined;\n this.authorizationUrl = undefined;\n this.connectionStatus = \"disconnected\";\n try {\n // Await even without a client to preserve cache-invalidation timing.\n await (client && client.close());\n } catch (error) {\n log.error({ connectorId: this.id, error }, \"Error closing MCP client\");\n }\n if (this.invalidateCache) {\n this.invalidateCache();\n }\n }\n /**\n * Check if an error is an auth error (401/403) and invalidate caches if so.\n * @param {unknown} error - Failure from a connected SDK operation.\n * @param {unknown} origin - Client whose failure is being handled.\n */\n private async handlePotentialAuthError(\n error: unknown,\n origin: unknown\n ): Promise<void> {\n if (this.client !== origin) {\n return;\n }\n const errorMessage = getMcpErrorMessage(error);\n const isAuthError =\n errorMessage.includes(\"401\") ||\n errorMessage.includes(\"403\") ||\n errorMessage.includes(\"Unauthorized\") ||\n errorMessage.includes(\"Forbidden\");\n\n if (isAuthError) {\n log.warn(\n { connectorId: this.id, errorMessage },\n \"Auth error detected, invalidating caches\"\n );\n await this.close();\n }\n }\n}\n",
|
|
179
179
|
"type": "registry:file",
|
|
180
180
|
"target": "~/chatjs/plugins/mcp/oauth/mcp-client.ts"
|
|
181
181
|
},
|
|
@@ -3,14 +3,13 @@
|
|
|
3
3
|
"name": "openai-compatible-gateway",
|
|
4
4
|
"title": "OpenAI Compatible",
|
|
5
5
|
"dependencies": [
|
|
6
|
-
"@
|
|
7
|
-
"@ai-sdk/openai-compatible@3.0.44",
|
|
6
|
+
"@ai-sdk/openai-compatible@3.0.92",
|
|
8
7
|
"zod@4.5.4"
|
|
9
8
|
],
|
|
10
9
|
"files": [
|
|
11
10
|
{
|
|
12
11
|
"path": "src/gateways/openai-compatible/gateway.ts",
|
|
13
|
-
"content": "import type { LanguageModelV4 } from \"@ai-sdk/provider\";\n\nimport type { AiGatewayModel } from \"
|
|
12
|
+
"content": "import type { LanguageModelV4 } from \"@ai-sdk/provider\";\n\nimport type { AiGatewayModel } from \"@/chatjs/core/gateway/models\";\n\nimport type { GatewayProvider } from \"@/chatjs/core/gateway/gateway-provider\";\n\nimport { GatewayRuntime } from \"@/chatjs/core/gateway/runtime\";\n\nimport type { ImageModel } from \"ai\";\nimport { createOpenAICompatible } from \"@ai-sdk/openai-compatible\";\nimport { z } from \"zod\";\n\nconst providerModelSchema = z.object({\n created: z.number().nullish(),\n id: z.string(),\n owned_by: z.string().nullish(),\n});\ntype OpenAICompatibleModelResponse = z.output<typeof providerModelSchema>;\nconst providerModelListSchema = z.object({\n data: z.array(z.unknown()),\n});\n\nconst EMPTY_MODEL_COUNT = 0;\nconst UNKNOWN_MODEL_LIMIT = 0;\nconst UNKNOWN_MODEL_TIMESTAMP = 0;\nconst toAiGatewayModel = (\n model: Readonly<OpenAICompatibleModelResponse>\n): AiGatewayModel => ({\n context_window: UNKNOWN_MODEL_LIMIT,\n created: model.created ?? UNKNOWN_MODEL_TIMESTAMP,\n description: \"\",\n id: model.id,\n max_tokens: UNKNOWN_MODEL_LIMIT,\n name: model.id,\n object: \"model\",\n owned_by: model.owned_by ?? \"unknown\",\n pricing: {},\n type: \"language\",\n});\n\n// Validate the wire envelope separately from each model so valid neighbors survive.\nconst parseProviderModels = (value: unknown): AiGatewayModel[] => {\n const body = providerModelListSchema.parse(value);\n const result = body.data.flatMap((entry): AiGatewayModel[] => {\n const model = providerModelSchema.safeParse(entry);\n if (!model.success) {\n return [];\n }\n return [toAiGatewayModel(model.data)];\n });\n // A genuinely empty catalog is valid; a nonempty unparseable catalog is not.\n if (\n body.data.length > EMPTY_MODEL_COUNT &&\n result.length === EMPTY_MODEL_COUNT\n ) {\n throw new Error(\"Provider catalog contains no valid models.\");\n }\n return result;\n};\n\nclass OpenAICompatibleGateway\n extends GatewayRuntime\n implements GatewayProvider<\"openai-compatible\">\n{\n public readonly type = \"openai-compatible\" as const;\n\n private getProvider(): ReturnType<typeof createOpenAICompatible> {\n const apiKey = this.getApiKey();\n const baseURL = this.getBaseURL();\n if (!(typeof baseURL === \"string\" && baseURL !== \"\")) {\n throw new Error(\"OPENAI_COMPATIBLE_BASE_URL is not configured\");\n }\n return createOpenAICompatible({\n apiKey,\n baseURL,\n name: \"openai-compatible\",\n });\n }\n\n public createLanguageModel(modelId: string): LanguageModelV4 {\n const provider = this.getProvider();\n return provider(modelId);\n }\n\n public createImageModel(modelId: string): ImageModel {\n const provider = this.getProvider();\n return provider.imageModel(modelId);\n }\n\n public readonly createVideoModel = null;\n\n private getApiKey(): string | undefined {\n return this.env.OPENAI_COMPATIBLE_API_KEY;\n }\n\n private getBaseURL(): string | undefined {\n const baseURL = this.env.OPENAI_COMPATIBLE_BASE_URL;\n if (baseURL === undefined || baseURL === \"\") {\n return undefined;\n }\n return z.url().parse(baseURL);\n }\n\n public async fetchModels(): Promise<AiGatewayModel[]> {\n const apiKey = this.getApiKey();\n const baseURL = this.getBaseURL();\n\n if (!(typeof baseURL === \"string\" && baseURL !== \"\")) {\n this.log.warn(\n \"No OPENAI_COMPATIBLE_BASE_URL found, using fallback models\"\n );\n return [...this.getFallbackModels(this.type)];\n }\n\n const url = `${baseURL}/models`;\n this.log.debug({ url }, \"Fetching models from OpenAI-compatible provider\");\n\n try {\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n };\n if (typeof apiKey === \"string\" && apiKey !== \"\") {\n headers.Authorization = `Bearer ${apiKey}`;\n }\n\n const response = await this.fetch(url, {\n headers,\n });\n\n if (!response.ok) {\n this.log.error(\n { status: response.status, statusText: response.statusText, url },\n \"OpenAI-compatible provider returned non-OK response\"\n );\n throw new Error(`Failed to fetch models: ${response.statusText}`);\n }\n\n const result = parseProviderModels(await response.json());\n\n this.log.info(\n { modelCount: result.length },\n \"Successfully fetched models from OpenAI-compatible provider\"\n );\n return result;\n } catch (error) {\n this.log.error(\n { err: error, url },\n \"Error fetching models from OpenAI-compatible provider, falling back to generated models\"\n );\n return [...this.getFallbackModels(this.type)];\n }\n }\n}\nexport { OpenAICompatibleGateway as Gateway, OpenAICompatibleGateway };\n",
|
|
14
13
|
"type": "registry:file",
|
|
15
14
|
"target": "~/chatjs/providers/gateway.ts"
|
|
16
15
|
}
|
|
@@ -3,14 +3,13 @@
|
|
|
3
3
|
"name": "openai-gateway",
|
|
4
4
|
"title": "OpenAI",
|
|
5
5
|
"dependencies": [
|
|
6
|
-
"@
|
|
7
|
-
"@ai-sdk/openai@4.0.59",
|
|
6
|
+
"@ai-sdk/openai@4.0.117",
|
|
8
7
|
"zod@4.5.4"
|
|
9
8
|
],
|
|
10
9
|
"files": [
|
|
11
10
|
{
|
|
12
11
|
"path": "src/gateways/openai/gateway.ts",
|
|
13
|
-
"content": "import type { LanguageModelV4 } from \"@ai-sdk/provider\";\n\nimport type {
|
|
12
|
+
"content": "import type { LanguageModelV4 } from \"@ai-sdk/provider\";\n\nimport type { AiGatewayModel } from \"@/chatjs/core/gateway/models\";\n\nimport type { GatewayProvider } from \"@/chatjs/core/gateway/gateway-provider\";\n\nimport { GatewayRuntime } from \"@/chatjs/core/gateway/runtime\";\n\nimport type { ImageModel } from \"ai\";\nimport { createOpenAI } from \"@ai-sdk/openai\";\nimport { z } from \"zod\";\n\nconst MODEL_ID_PARAMETER_INDEX = 0;\ntype OpenAiLanguageModelId = Parameters<\n ReturnType<typeof createOpenAI>[\"languageModel\"]\n>[typeof MODEL_ID_PARAMETER_INDEX];\ntype OpenAiImageModelId = Parameters<\n ReturnType<typeof createOpenAI>[\"image\"]\n>[typeof MODEL_ID_PARAMETER_INDEX];\n\nconst providerModelSchema = z.object({\n created: z.number().nullish(),\n id: z.string(),\n owned_by: z.string().nullish(),\n});\ntype OpenAIModelResponse = z.output<typeof providerModelSchema>;\nconst providerModelListSchema = z.object({\n data: z.array(z.unknown()),\n});\n\nconst EMPTY_MODEL_COUNT = 0;\nconst UNKNOWN_MODEL_LIMIT = 0;\nconst UNKNOWN_MODEL_TIMESTAMP = 0;\nconst toAiGatewayModel = (\n model: Readonly<OpenAIModelResponse>\n): AiGatewayModel => ({\n context_window: UNKNOWN_MODEL_LIMIT,\n created: model.created ?? UNKNOWN_MODEL_TIMESTAMP,\n description: \"\",\n id: model.id,\n max_tokens: UNKNOWN_MODEL_LIMIT,\n name: model.id,\n object: \"model\",\n owned_by:\n (model.owned_by === \"system\" ? \"openai\" : model.owned_by) ?? \"openai\",\n pricing: {},\n type: \"language\",\n});\n\n// Validate the wire envelope separately from each model so valid neighbors survive.\nconst parseProviderModels = (value: unknown): AiGatewayModel[] => {\n const body = providerModelListSchema.parse(value);\n const result = body.data.flatMap((entry): AiGatewayModel[] => {\n const model = providerModelSchema.safeParse(entry);\n if (!model.success) {\n return [];\n }\n return [toAiGatewayModel(model.data)];\n });\n // A genuinely empty catalog is valid; a nonempty unparseable catalog is not.\n if (\n body.data.length > EMPTY_MODEL_COUNT &&\n result.length === EMPTY_MODEL_COUNT\n ) {\n throw new Error(\"Provider catalog contains no valid models.\");\n }\n return result;\n};\n\nclass OpenAIGateway\n extends GatewayRuntime\n implements GatewayProvider<\"openai\">\n{\n public readonly type = \"openai\" as const;\n\n private getProvider(): ReturnType<typeof createOpenAI> {\n const apiKey = this.getApiKey();\n if (!(typeof apiKey === \"string\" && apiKey !== \"\")) {\n throw new Error(\"OPENAI_API_KEY is not configured\");\n }\n return createOpenAI({ apiKey });\n }\n\n public createLanguageModel(modelId: OpenAiLanguageModelId): LanguageModelV4 {\n const provider = this.getProvider();\n return provider(modelId);\n }\n\n public createImageModel(modelId: OpenAiImageModelId): ImageModel {\n const provider = this.getProvider();\n return provider.image(modelId);\n }\n\n public readonly createVideoModel = null;\n\n private getApiKey(): string | undefined {\n return this.env.OPENAI_API_KEY;\n }\n\n public async fetchModels(): Promise<AiGatewayModel[]> {\n const apiKey = this.getApiKey();\n\n if (!(typeof apiKey === \"string\" && apiKey !== \"\")) {\n this.log.warn(\"No OPENAI_API_KEY found, using fallback models\");\n return [...this.getFallbackModels(this.type)];\n }\n\n const url = \"https://api.openai.com/v1/models\";\n this.log.debug({ url }, \"Fetching models from OpenAI\");\n\n try {\n const response = await this.fetch(url, {\n headers: {\n Authorization: `Bearer ${apiKey}`,\n \"Content-Type\": \"application/json\",\n },\n });\n\n if (!response.ok) {\n this.log.error(\n { status: response.status, statusText: response.statusText, url },\n \"OpenAI returned non-OK response\"\n );\n throw new Error(`Failed to fetch models: ${response.statusText}`);\n }\n\n const result = parseProviderModels(await response.json());\n\n this.log.info(\n { modelCount: result.length },\n \"Successfully fetched models from OpenAI\"\n );\n return result;\n } catch (error) {\n this.log.error(\n { err: error, url },\n \"Error fetching models from OpenAI, falling back to generated models\"\n );\n return [...this.getFallbackModels(this.type)];\n }\n }\n}\nexport { OpenAIGateway as Gateway, OpenAIGateway };\n",
|
|
14
13
|
"type": "registry:file",
|
|
15
14
|
"target": "~/chatjs/providers/gateway.ts"
|
|
16
15
|
}
|
|
@@ -3,14 +3,13 @@
|
|
|
3
3
|
"name": "openrouter-gateway",
|
|
4
4
|
"title": "OpenRouter",
|
|
5
5
|
"dependencies": [
|
|
6
|
-
"@chat-js/gateways@0.2.1",
|
|
7
6
|
"@openrouter/ai-sdk-provider@3.0.0",
|
|
8
7
|
"zod@4.5.4"
|
|
9
8
|
],
|
|
10
9
|
"files": [
|
|
11
10
|
{
|
|
12
11
|
"path": "src/gateways/openrouter/gateway.ts",
|
|
13
|
-
"content": "import type { LanguageModelV4 } from \"@ai-sdk/provider\";\nimport type { AiGatewayModel } from \"
|
|
12
|
+
"content": "import type { LanguageModelV4 } from \"@ai-sdk/provider\";\nimport type { AiGatewayModel } from \"@/chatjs/core/gateway/models\";\n\nimport type { GatewayProvider } from \"@/chatjs/core/gateway/gateway-provider\";\n\nimport { GatewayRuntime } from \"@/chatjs/core/gateway/runtime\";\n\nimport { createOpenRouter } from \"@openrouter/ai-sdk-provider\";\n\nimport { z } from \"zod\";\n\nconst MODEL_OWNER_SEGMENT_INDEX = 0;\nconst EMPTY_TAG_COUNT = 0;\nconst OPENROUTER_MODELS_URL = \"https://openrouter.ai/api/v1/models\";\n\nconst modalitiesSchema = z.array(z.string()).nullish();\nconst providerModelSchema = z.object({\n architecture: z\n .object({\n input_modalities: modalitiesSchema,\n output_modalities: modalitiesSchema,\n })\n .nullish(),\n context_length: z.number().nullish(),\n created: z.number().nullish(),\n description: z.string().nullish(),\n id: z.string(),\n name: z.string().nullish(),\n pricing: z\n .object({\n completion: z.string().optional(),\n image: z.string().optional(),\n input_cache_read: z.string().optional(),\n input_cache_write: z.string().optional(),\n prompt: z.string().optional(),\n web_search: z.string().optional(),\n })\n .nullish(),\n supported_parameters: z.array(z.string()).nullish(),\n top_provider: z\n .object({ max_completion_tokens: z.number().nullish() })\n .nullish(),\n});\ntype OpenRouterModelResponse = Omit<\n z.output<typeof providerModelSchema>,\n \"architecture\" | \"pricing\" | \"top_provider\" | \"supported_parameters\"\n> & {\n architecture?: {\n readonly input_modalities?: readonly string[] | null;\n readonly output_modalities?: readonly string[] | null;\n } | null;\n pricing?: Readonly<z.output<typeof providerModelSchema>[\"pricing\"]>;\n top_provider?: Readonly<z.output<typeof providerModelSchema>[\"top_provider\"]>;\n supported_parameters?: readonly string[] | null;\n};\nconst providerModelListSchema = z.object({\n data: z.array(z.unknown()),\n});\n\nconst deriveTags = (model: Readonly<OpenRouterModelResponse>): string[] => {\n const inputMods = (model.architecture ?? {}).input_modalities ?? [\"text\"];\n const outputMods = (model.architecture ?? {}).output_modalities ?? [\"text\"];\n const supportedParams = model.supported_parameters ?? [];\n\n const capabilities: readonly (readonly [boolean, string])[] = [\n [inputMods.includes(\"image\"), \"vision\"],\n [inputMods.includes(\"file\"), \"file-input\"],\n [outputMods.includes(\"image\"), \"image-generation\"],\n [\n supportedParams.includes(\"reasoning\") ||\n supportedParams.includes(\"include_reasoning\"),\n \"reasoning\",\n ],\n [supportedParams.includes(\"tools\"), \"tool-use\"],\n ];\n return capabilities.filter(([supported]) => supported).map(([, tag]) => tag);\n};\n\nconst EMPTY_MODEL_COUNT = 0;\nconst UNKNOWN_MODEL_LIMIT = 0;\nconst UNKNOWN_MODEL_TIMESTAMP = 0;\nconst toAiGatewayModel = (\n model: Readonly<OpenRouterModelResponse>\n): AiGatewayModel => {\n const tags = deriveTags(model);\n const outputMods = (model.architecture ?? {}).output_modalities ?? [\"text\"];\n\n let type: \"language\" | \"embedding\" | \"image\" = \"language\";\n if (!outputMods.includes(\"text\") && outputMods.includes(\"image\")) {\n type = \"image\";\n }\n\n const owned_by =\n model.id.split(\"/\").at(MODEL_OWNER_SEGMENT_INDEX) ?? \"unknown\";\n\n return {\n context_window: model.context_length ?? UNKNOWN_MODEL_LIMIT,\n created: model.created ?? UNKNOWN_MODEL_TIMESTAMP,\n description: model.description ?? \"\",\n id: model.id,\n max_tokens:\n (model.top_provider ?? {}).max_completion_tokens ?? UNKNOWN_MODEL_LIMIT,\n name: model.name ?? model.id,\n object: \"model\",\n owned_by,\n pricing: {\n image: (model.pricing ?? {}).image,\n input: (model.pricing ?? {}).prompt,\n input_cache_read: (model.pricing ?? {}).input_cache_read,\n input_cache_write: (model.pricing ?? {}).input_cache_write,\n output: (model.pricing ?? {}).completion,\n web_search: (model.pricing ?? {}).web_search,\n },\n tags: tags.length > EMPTY_TAG_COUNT ? tags : undefined,\n type,\n };\n};\n\n// Validate the wire envelope separately from each model so valid neighbors survive.\nconst parseProviderModels = (value: unknown): AiGatewayModel[] => {\n const body = providerModelListSchema.parse(value);\n const result = body.data.flatMap((entry): AiGatewayModel[] => {\n const model = providerModelSchema.safeParse(entry);\n if (!model.success) {\n return [];\n }\n return [toAiGatewayModel(model.data)];\n });\n // A genuinely empty catalog is valid; a nonempty unparseable catalog is not.\n if (\n body.data.length > EMPTY_MODEL_COUNT &&\n result.length === EMPTY_MODEL_COUNT\n ) {\n throw new Error(\"Provider catalog contains no valid models.\");\n }\n return result;\n};\n\nclass OpenRouterGateway\n extends GatewayRuntime\n implements GatewayProvider<\"openrouter\">\n{\n public readonly type = \"openrouter\" as const;\n\n private getProvider(): ReturnType<typeof createOpenRouter> {\n const apiKey = this.getApiKey();\n if (!(typeof apiKey === \"string\" && apiKey !== \"\")) {\n throw new Error(\"OPENROUTER_API_KEY is not configured\");\n }\n return createOpenRouter({ apiKey });\n }\n\n public createLanguageModel(modelId: string): LanguageModelV4 {\n const provider = this.getProvider();\n return provider.chat(modelId);\n }\n\n // OpenRouter generates images through multimodal language models.\n public readonly createImageModel = null;\n\n public readonly createVideoModel = null;\n\n private getApiKey(): string | undefined {\n return this.env.OPENROUTER_API_KEY;\n }\n\n public async fetchModels(): Promise<AiGatewayModel[]> {\n const apiKey = this.getApiKey();\n\n if (!(typeof apiKey === \"string\" && apiKey !== \"\")) {\n this.log.warn(\"No OPENROUTER_API_KEY found, using fallback models\");\n return [...this.getFallbackModels(this.type)];\n }\n\n const url = OPENROUTER_MODELS_URL;\n this.log.debug({ url }, \"Fetching models from OpenRouter\");\n\n try {\n const response = await this.fetch(url, {\n headers: {\n Authorization: `Bearer ${apiKey}`,\n \"Content-Type\": \"application/json\",\n },\n });\n\n if (!response.ok) {\n this.log.error(\n { status: response.status, statusText: response.statusText, url },\n \"OpenRouter returned non-OK response\"\n );\n throw new Error(`Failed to fetch models: ${response.statusText}`);\n }\n\n const result = parseProviderModels(await response.json());\n\n this.log.info(\n { modelCount: result.length },\n \"Successfully fetched models from OpenRouter\"\n );\n return result;\n } catch (error) {\n this.log.error(\n { err: error, url },\n \"Error fetching models from OpenRouter, falling back to generated models\"\n );\n return [...this.getFallbackModels(this.type)];\n }\n }\n}\nexport { OpenRouterGateway as Gateway, OpenRouterGateway };\n",
|
|
14
13
|
"type": "registry:file",
|
|
15
14
|
"target": "~/chatjs/providers/gateway.ts"
|
|
16
15
|
}
|
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"name": "attach-workspace-file",
|
|
4
4
|
"description": "Attach workspace files to the conversation as downloads, or import earlier files into the workspace for revision.",
|
|
5
5
|
"dependencies": [
|
|
6
|
-
"eve@npm:@chat-js/eve@1.
|
|
6
|
+
"eve@npm:@chat-js/eve@1.1.1-chatjs.0",
|
|
7
7
|
"zod@4.5.4",
|
|
8
8
|
"lucide-react@0.553.0"
|
|
9
9
|
],
|
|
@@ -3,13 +3,12 @@
|
|
|
3
3
|
"name": "litellm-gateway",
|
|
4
4
|
"title": "LiteLLM",
|
|
5
5
|
"dependencies": [
|
|
6
|
-
"@
|
|
7
|
-
"@ai-sdk/openai-compatible@3.0.44"
|
|
6
|
+
"@ai-sdk/openai-compatible@3.0.92"
|
|
8
7
|
],
|
|
9
8
|
"files": [
|
|
10
9
|
{
|
|
11
10
|
"path": "src/gateways/litellm/gateway.ts",
|
|
12
|
-
"content": "import type { LanguageModelV4 } from \"@ai-sdk/provider\";\n\nimport type { AiGatewayModel } from \"
|
|
11
|
+
"content": "import type { LanguageModelV4 } from \"@ai-sdk/provider\";\n\nimport type { AiGatewayModel } from \"@/chatjs/core/gateway/models\";\n\nimport type { GatewayProvider } from \"@/chatjs/core/gateway/gateway-provider\";\n\nimport { GatewayRuntime } from \"@/chatjs/core/gateway/runtime\";\n\nimport type { ImageModel } from \"ai\";\nimport { createOpenAICompatible } from \"@ai-sdk/openai-compatible\";\nimport { z } from \"zod\";\n\nconst MODEL_DISCOVERY_TIMEOUT_MS = 10_000;\nconst TRAILING_SLASHES_REGEX = /\\/+$/u;\n\nconst litellmModelSchema = z.object({\n created: z.number().optional(),\n id: z.string(),\n object: z.string().optional(),\n owned_by: z.string().optional(),\n});\nconst litellmModelsResponseSchema = z.object({\n data: z.array(litellmModelSchema),\n});\n\ntype LiteLLMModelResponse = z.infer<\n typeof litellmModelsResponseSchema\n>[\"data\"][number];\n\nconst getModelsUrl = (baseURL: string): string => {\n const normalizedBaseURL = baseURL.replace(TRAILING_SLASHES_REGEX, \"\");\n if (normalizedBaseURL.endsWith(\"/v1\")) {\n return `${normalizedBaseURL}/models`;\n }\n return `${normalizedBaseURL}/v1/models`;\n};\n\nconst UNKNOWN_MODEL_LIMIT = 0;\nconst toAiGatewayModel = (model: LiteLLMModelResponse): AiGatewayModel => ({\n context_window: UNKNOWN_MODEL_LIMIT,\n created: model.created ?? UNKNOWN_MODEL_LIMIT,\n description: \"\",\n id: model.id,\n max_tokens: UNKNOWN_MODEL_LIMIT,\n name: model.id,\n object: \"model\",\n owned_by: model.owned_by ?? \"litellm\",\n pricing: {},\n type: \"language\",\n});\n\nclass LiteLLMGateway\n extends GatewayRuntime\n implements GatewayProvider<\"litellm\">\n{\n public readonly type = \"litellm\" as const;\n\n private getProvider(): ReturnType<typeof createOpenAICompatible> {\n const apiKey = this.getApiKey();\n const baseURL = this.getBaseURL();\n if (!(typeof baseURL === \"string\" && baseURL !== \"\")) {\n throw new Error(\"LITELLM_BASE_URL is not configured\");\n }\n return createOpenAICompatible({\n apiKey,\n baseURL,\n name: \"litellm\",\n });\n }\n\n public createLanguageModel(modelId: string): LanguageModelV4 {\n const provider = this.getProvider();\n return provider(modelId);\n }\n\n public createImageModel(modelId: string): ImageModel {\n const provider = this.getProvider();\n return provider.imageModel(modelId);\n }\n\n public readonly createVideoModel = null;\n\n private getApiKey(): string | undefined {\n return this.env.LITELLM_API_KEY;\n }\n\n private getBaseURL(): string | undefined {\n const baseURL = this.env.LITELLM_BASE_URL;\n if (baseURL === undefined || baseURL === \"\") {\n return undefined;\n }\n return z.url().parse(baseURL);\n }\n\n public async fetchModels(): Promise<AiGatewayModel[]> {\n const apiKey = this.getApiKey();\n const baseURL = this.getBaseURL();\n\n if (!(typeof baseURL === \"string\" && baseURL !== \"\")) {\n this.log.warn(\"No LITELLM_BASE_URL found, using fallback models\");\n return [...this.getFallbackModels(this.type)];\n }\n\n const url = getModelsUrl(baseURL);\n this.log.debug({ url }, \"Fetching models from LiteLLM proxy\");\n\n try {\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n };\n if (typeof apiKey === \"string\" && apiKey !== \"\") {\n headers.Authorization = `Bearer ${apiKey}`;\n }\n\n const response = await this.fetch(url, {\n headers,\n signal: AbortSignal.timeout(MODEL_DISCOVERY_TIMEOUT_MS),\n });\n\n if (!response.ok) {\n this.log.error(\n { status: response.status, statusText: response.statusText, url },\n \"LiteLLM proxy returned non-OK response\"\n );\n throw new Error(`Failed to fetch models: ${response.statusText}`);\n }\n\n const body = litellmModelsResponseSchema.parse(await response.json());\n const models = body.data;\n const result = models.map((model) => toAiGatewayModel(model));\n\n this.log.info(\n { modelCount: result.length },\n \"Successfully fetched models from LiteLLM proxy\"\n );\n return result;\n } catch (error) {\n this.log.error(\n { err: error, url },\n \"Error fetching models from LiteLLM proxy, falling back to generated models\"\n );\n return [...this.getFallbackModels(this.type)];\n }\n }\n}\nexport { LiteLLMGateway as Gateway, LiteLLMGateway };\n",
|
|
13
12
|
"type": "registry:file",
|
|
14
13
|
"target": "~/chatjs/providers/gateway.ts"
|
|
15
14
|
}
|
package/dist/r/radix/mcp.json
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"name": "mcp",
|
|
4
4
|
"description": "MCP connectors, management pages, OAuth and composer control",
|
|
5
5
|
"dependencies": [
|
|
6
|
-
"@ai-sdk/mcp@2.0.
|
|
6
|
+
"@ai-sdk/mcp@2.0.99",
|
|
7
7
|
"@hookform/resolvers@^5.2.1",
|
|
8
8
|
"@modelcontextprotocol/sdk@^1.24.3",
|
|
9
9
|
"@tanstack/react-query@^5.104.1",
|
|
@@ -175,7 +175,7 @@
|
|
|
175
175
|
},
|
|
176
176
|
{
|
|
177
177
|
"path": "src/plugins/mcp/src/oauth/mcp-client.ts",
|
|
178
|
-
"content": "import type {\n ListPromptsResult,\n ListResourcesResult,\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport {\n auth,\n experimental_createMCPClient as createMCPClient,\n} from \"@ai-sdk/mcp\";\nimport { McpOAuthClientProvider } from \"@/chatjs/plugins/mcp/oauth/mcp-oauth-provider\";\nimport { OAuthAuthorizationRequiredError } from \"@/chatjs/plugins/mcp/oauth/oauth-authorization-required-error\";\nimport type { ReadonlyNativeSurface } from \"@/lib/readonly-native-surface\";\nimport type { Tool } from \"ai\";\nimport { config } from \"@/lib/config\";\nimport { createModuleLogger } from \"@/lib/logger\";\nimport { getBaseUrl } from \"@/lib/url\";\n\nconst log = createModuleLogger(\"mcp-client\");\n\nconst INITIAL_CONNECTION_GENERATION = 0;\nconst MCP_CONNECTION_TIMEOUT_MS = 30_000;\n\nconst getMcpErrorMessage = (error: unknown): string => {\n if (error instanceof Error) {\n return error.message;\n }\n return String(error);\n};\n\ntype McpPreconnect = (\n url: string | URL,\n options?: {\n readonly dns?: boolean;\n readonly http?: boolean;\n readonly https?: boolean;\n readonly tcp?: boolean;\n }\n) => void;\n\nconst isMcpPreconnect = (value: unknown): value is McpPreconnect =>\n typeof value === \"function\";\n\n// Bun's fetch type requires preconnect. Node's does not. Delegate when the\n// runtime provides it so one fetch value satisfies both FetchFunction types.\nconst mcpPreconnect: McpPreconnect = (url, options): void => {\n const candidate: object = globalThis.fetch;\n if (!(\"preconnect\" in candidate)) {\n return;\n }\n const method: unknown = candidate.preconnect;\n if (!isMcpPreconnect(method)) {\n return;\n }\n method(url, options);\n};\n\nconst toMcpSdkFetch = (\n fetchImpl: (\n ...args: Parameters<typeof globalThis.fetch>\n ) => ReturnType<typeof globalThis.fetch>\n): typeof globalThis.fetch =>\n Object.assign(fetchImpl, { preconnect: mcpPreconnect });\n\ntype McpClientInstance = Awaited<ReturnType<typeof createMCPClient>>;\n\ntype McpClientStatus =\n | \"disconnected\"\n | \"connecting\"\n | \"connected\"\n | \"authorizing\"\n | \"incompatible\";\n\n/**\n * MCP Client wrapper with OAuth support.\n * Uses @ai-sdk/mcp's createMCPClient with authProvider for OAuth flow.\n */\nexport class MCPClient {\n private client?: McpClientInstance;\n private generation = INITIAL_CONNECTION_GENERATION;\n private connectionAbort?: AbortController;\n private connectPromise?: Promise<void>;\n private readonly invalidateCache?: () => void;\n private oauthProvider: McpOAuthClientProvider;\n private authorizationUrl?: URL;\n private connectionStatus: McpClientStatus = \"disconnected\";\n\n private readonly id: string;\n private readonly name: string;\n private readonly serverConfig: {\n url: string;\n type: \"http\" | \"sse\";\n headers?: Record<string, string>;\n oauthClientId?: string | null;\n oauthClientSecret?: string | null;\n };\n\n public constructor(\n id: string,\n name: string,\n serverConfig: {\n readonly url: string;\n readonly type: \"http\" | \"sse\";\n readonly headers?: Readonly<Record<string, string>>;\n readonly oauthClientId?: string | null;\n readonly oauthClientSecret?: string | null;\n },\n invalidateCache?: () => void\n ) {\n this.invalidateCache = invalidateCache;\n this.id = id;\n this.name = name;\n this.serverConfig = serverConfig;\n this.oauthProvider = this.createOAuthProvider();\n }\n\n private createOAuthProvider(): McpOAuthClientProvider {\n const { generation } = this;\n const baseUrl = getBaseUrl();\n\n return new McpOAuthClientProvider({\n clientMetadata: {\n client_name: `${config.appPrefix}-${this.name}`,\n grant_types: [\"authorization_code\", \"refresh_token\"],\n redirect_uris: [`${baseUrl}/api/mcp/oauth/callback`],\n response_types: [\"code\"],\n scope: \"mcp:tools\",\n software_id: config.appPrefix,\n software_version: \"1.0.0\",\n token_endpoint_auth_method:\n typeof this.serverConfig.oauthClientId === \"string\" &&\n this.serverConfig.oauthClientId !== \"\" &&\n typeof this.serverConfig.oauthClientSecret === \"string\" &&\n this.serverConfig.oauthClientSecret !== \"\"\n ? \"client_secret_basic\"\n : \"none\",\n },\n mcpConnectorId: this.id,\n oauthClientId: this.serverConfig.oauthClientId,\n oauthClientSecret: this.serverConfig.oauthClientSecret,\n onRedirectToAuthorization: (\n authorizationUrl: ReadonlyNativeSurface<URL>\n ): never => {\n if (generation !== this.generation) {\n throw new Error(\"MCP connection was closed\");\n }\n this.authorizationUrl = authorizationUrl;\n throw new OAuthAuthorizationRequiredError(authorizationUrl);\n },\n serverUrl: this.serverConfig.url,\n });\n }\n\n public get status(): McpClientStatus {\n if (this.authorizationUrl) {\n return \"authorizing\";\n }\n if (this.client) {\n return \"connected\";\n }\n return this.connectionStatus;\n }\n\n public getAuthorizationUrl(): URL | undefined {\n return this.authorizationUrl;\n }\n\n public get serverInfo(): McpClientInstance[\"serverInfo\"] | undefined {\n const { client } = this;\n return client && client.serverInfo;\n }\n\n public async connect({\n oauthState,\n abortSignal,\n }: {\n readonly oauthState?: string;\n readonly abortSignal?: Readonly<\n Pick<\n AbortSignal,\n | \"throwIfAborted\"\n | \"reason\"\n | \"addEventListener\"\n | \"removeEventListener\"\n | \"aborted\"\n >\n >;\n } = {}): Promise<void> {\n if (abortSignal) {\n abortSignal.throwIfAborted();\n }\n if (!this.connectPromise) {\n const { generation } = this;\n this.connectPromise = (async (): Promise<void> => {\n try {\n await this.connectOnce(oauthState);\n } finally {\n // Only close() can retire a pending attempt and allow a replacement.\n if (this.generation === generation) {\n this.connectPromise = undefined;\n }\n }\n })();\n }\n if (!abortSignal) {\n await this.connectPromise;\n return;\n }\n const aborted = Promise.withResolvers<never>();\n const cancel = (): void => {\n aborted.reject(abortSignal.reason);\n };\n abortSignal.addEventListener(\"abort\", cancel, { once: true });\n if (abortSignal.aborted) {\n cancel();\n }\n try {\n await Promise.race([this.connectPromise, aborted.promise]);\n } finally {\n abortSignal.removeEventListener(\"abort\", cancel);\n }\n }\n private async connectOnce(oauthState?: string): Promise<void> {\n if (this.status === \"connected\" && this.client) {\n return;\n }\n\n const { generation, oauthProvider } = this;\n this.connectionAbort = new AbortController();\n const signal = AbortSignal.any([\n this.connectionAbort.signal,\n AbortSignal.timeout(MCP_CONNECTION_TIMEOUT_MS),\n ]);\n this.connectionStatus = \"connecting\";\n\n try {\n // Adopt state if provided (for callback reconciliation).\n if (typeof oauthState === \"string\" && oauthState !== \"\") {\n await oauthProvider.adoptState(oauthState);\n }\n signal.throwIfAborted();\n // AI SDK handles 401 internally and calls auth() with the provider\n const client = await createMCPClient({\n initializationOptions: { signal },\n transport: {\n authProvider: oauthProvider,\n fetch: toMcpSdkFetch(oauthProvider.fetch),\n headers: this.serverConfig.headers,\n type: this.serverConfig.type,\n url: this.serverConfig.url,\n },\n });\n\n if (generation !== this.generation || signal.aborted) {\n await client.close();\n signal.throwIfAborted();\n throw new Error(\"MCP connection was closed\");\n }\n this.client = client;\n this.authorizationUrl = undefined;\n this.connectionStatus = \"connected\";\n } catch (error) {\n if (generation !== this.generation || signal.aborted) {\n if (generation === this.generation) {\n this.authorizationUrl = undefined;\n this.connectionStatus = \"disconnected\";\n }\n throw error;\n }\n // If OAuth required error, status becomes \"authorizing\"\n if (error instanceof OAuthAuthorizationRequiredError) {\n this.connectionStatus = \"authorizing\";\n log.info(\n { authUrl: error.authorizationUrl.toString(), connectorId: this.id },\n \"OAuth authorization required\"\n );\n return;\n }\n\n this.connectionStatus = \"disconnected\";\n throw error;\n }\n }\n /**\n * Lightweight connection test - just checks if we can connect without full discovery.\n * Returns connection status without fetching tools/resources/prompts.\n * @param {Readonly<Pick<AbortSignal, \"throwIfAborted\" | \"reason\" | \"addEventListener\" | \"removeEventListener\" | \"aborted\">> | undefined} abortSignal - Cancels this caller while shared initialization continues.\n * @returns {Promise<{ status: McpClientStatus; needsAuth: boolean; error?: string; }>} The connection or authorization status.\n */\n public async attemptConnection(\n abortSignal?: Readonly<\n Pick<\n AbortSignal,\n | \"throwIfAborted\"\n | \"reason\"\n | \"addEventListener\"\n | \"removeEventListener\"\n | \"aborted\"\n >\n >\n ): Promise<{\n status: McpClientStatus;\n needsAuth: boolean;\n error?: string;\n }> {\n // If already connected, return current status\n if (this.status === \"connected\" && this.client) {\n return { needsAuth: false, status: \"connected\" };\n }\n\n // If already in authorizing state, return that\n if (this.authorizationUrl) {\n return { needsAuth: true, status: \"authorizing\" };\n }\n\n try {\n await this.connect({ abortSignal });\n // Check if OAuth is required (authorizationUrl gets set during connect)\n if (this.authorizationUrl !== undefined) {\n return { needsAuth: true, status: \"authorizing\" };\n }\n return {\n needsAuth: false,\n status: this.client ? \"connected\" : \"disconnected\",\n };\n } catch (error) {\n const errorMessage = getMcpErrorMessage(error);\n log.error(\n {\n connectorId: this.id,\n errorMessage,\n errorStack: error instanceof Error ? error.stack : undefined,\n },\n \"attemptConnection failed\"\n );\n\n // Detect incompatible server errors\n if (\n errorMessage.includes(\"does not support dynamic client registration\")\n ) {\n this.connectionStatus = \"incompatible\";\n return {\n error:\n \"Server requires pre-configured OAuth credentials (does not support dynamic client registration)\",\n needsAuth: false,\n status: \"incompatible\",\n };\n }\n\n return { error: errorMessage, needsAuth: false, status: \"disconnected\" };\n }\n }\n /**\n * Called after callback receives code to complete the OAuth flow.\n * @param {string} code - Authorization code received by the callback.\n * @param {string} state - State used to restore the verifier session.\n */\n public async finishAuth(code: string, state: string): Promise<void> {\n const { generation, oauthProvider } = this;\n // Always adopt the state from the callback to load the session with code verifier\n await oauthProvider.adoptState(state);\n\n // Use the auth function from @ai-sdk/mcp to complete the OAuth flow\n await auth(oauthProvider, {\n authorizationCode: code,\n fetchFn: toMcpSdkFetch(oauthProvider.fetch),\n serverUrl: this.serverConfig.url,\n });\n\n if (generation !== this.generation) {\n throw new Error(\"MCP connection was closed\");\n }\n this.authorizationUrl = undefined;\n // Don't set to connected - tokens are saved, next connect() will use them\n }\n /**\n * Get tools from the MCP server, already in AI SDK format.\n * @param {Parameters<McpClientInstance[\"tools\"]>} args - Native SDK schema options.\n * @returns {Promise<Record<string, Tool>>} The discovered SDK tools.\n */\n public async tools(\n ...args: Parameters<NonNullable<McpClientInstance>[\"tools\"]>\n ): Promise<Record<string, Tool>> {\n const { client } = this;\n if (!client) {\n throw new Error(\"Client not connected\");\n }\n try {\n return await client.tools(...args);\n } catch (error) {\n await this.handlePotentialAuthError(error, client);\n throw error;\n }\n }\n /**\n * List resources from the MCP server.\n * @returns {Promise<ListResourcesResult>} The native MCP resource result.\n */\n public async listResources(): Promise<ListResourcesResult> {\n const { client } = this;\n if (!client) {\n throw new Error(\"Client not connected\");\n }\n try {\n return await client.listResources();\n } catch (error) {\n await this.handlePotentialAuthError(error, client);\n throw error;\n }\n }\n /**\n * List prompts from the MCP server.\n * @returns {Promise<ListPromptsResult>} The native MCP prompt result.\n */\n public async listPrompts(): Promise<ListPromptsResult> {\n const { client } = this;\n if (!client) {\n throw new Error(\"Client not connected\");\n }\n try {\n return await client.experimental_listPrompts();\n } catch (error) {\n await this.handlePotentialAuthError(error, client);\n throw error;\n }\n }\n /**\n * Close the connection to the MCP server.\n */\n public async close(): Promise<void> {\n this.generation += 1;\n const { connectionAbort } = this;\n if (connectionAbort) {\n connectionAbort.abort(new Error(\"MCP connection was closed\"));\n }\n this.connectPromise = undefined;\n this.oauthProvider = this.createOAuthProvider();\n const { client } = this;\n this.client = undefined;\n this.authorizationUrl = undefined;\n this.connectionStatus = \"disconnected\";\n try {\n // Await even without a client to preserve cache-invalidation timing.\n await (client && client.close());\n } catch (error) {\n log.error({ connectorId: this.id, error }, \"Error closing MCP client\");\n }\n if (this.invalidateCache) {\n this.invalidateCache();\n }\n }\n /**\n * Check if an error is an auth error (401/403) and invalidate caches if so.\n * @param {unknown} error - Failure from a connected SDK operation.\n * @param {unknown} origin - Client whose failure is being handled.\n */\n private async handlePotentialAuthError(\n error: unknown,\n origin: unknown\n ): Promise<void> {\n if (this.client !== origin) {\n return;\n }\n const errorMessage = getMcpErrorMessage(error);\n const isAuthError =\n errorMessage.includes(\"401\") ||\n errorMessage.includes(\"403\") ||\n errorMessage.includes(\"Unauthorized\") ||\n errorMessage.includes(\"Forbidden\");\n\n if (isAuthError) {\n log.warn(\n { connectorId: this.id, errorMessage },\n \"Auth error detected, invalidating caches\"\n );\n await this.close();\n }\n }\n}\n",
|
|
178
|
+
"content": "import type {\n ListPromptsResult,\n ListResourcesResult,\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport {\n auth,\n experimental_createMCPClient as createMCPClient,\n} from \"@ai-sdk/mcp\";\nimport { McpOAuthClientProvider } from \"@/chatjs/plugins/mcp/oauth/mcp-oauth-provider\";\nimport { OAuthAuthorizationRequiredError } from \"@/chatjs/plugins/mcp/oauth/oauth-authorization-required-error\";\nimport type { ReadonlyNativeSurface } from \"@/lib/readonly-native-surface\";\nimport type { Tool } from \"ai\";\nimport { config } from \"@/lib/config\";\nimport { createModuleLogger } from \"@/lib/logger\";\nimport { getBaseUrl } from \"@/lib/url\";\n\nconst log = createModuleLogger(\"mcp-client\");\n\nconst INITIAL_CONNECTION_GENERATION = 0;\nconst MCP_CONNECTION_TIMEOUT_MS = 30_000;\n\nconst getMcpErrorMessage = (error: unknown): string => {\n if (error instanceof Error) {\n return error.message;\n }\n return String(error);\n};\n\ntype McpPreconnect = (\n url: string | URL,\n options?: {\n readonly dns?: boolean;\n readonly http?: boolean;\n readonly https?: boolean;\n readonly tcp?: boolean;\n }\n) => void;\n\nconst isMcpPreconnect = (value: unknown): value is McpPreconnect =>\n typeof value === \"function\";\n\n// Bun's fetch type requires preconnect. Node's does not. Delegate when the\n// runtime provides it so one fetch value satisfies both FetchFunction types.\nconst mcpPreconnect: McpPreconnect = (url, options): void => {\n const candidate: object = globalThis.fetch;\n if (!(\"preconnect\" in candidate)) {\n return;\n }\n const method: unknown = candidate.preconnect;\n if (!isMcpPreconnect(method)) {\n return;\n }\n method(url, options);\n};\n\nconst toMcpSdkFetch = (\n fetchImpl: (\n ...args: Parameters<typeof globalThis.fetch>\n ) => ReturnType<typeof globalThis.fetch>\n): typeof globalThis.fetch =>\n Object.assign(fetchImpl, { preconnect: mcpPreconnect });\n\ntype McpClientInstance = Awaited<ReturnType<typeof createMCPClient>>;\n\ntype McpClientStatus =\n | \"disconnected\"\n | \"connecting\"\n | \"connected\"\n | \"authorizing\"\n | \"incompatible\";\n\n/**\n * MCP Client wrapper with OAuth support.\n * Uses @ai-sdk/mcp's createMCPClient with authProvider for OAuth flow.\n */\nexport class MCPClient {\n private client?: McpClientInstance;\n private generation = INITIAL_CONNECTION_GENERATION;\n private connectionAbort?: AbortController;\n private connectPromise?: Promise<void>;\n private readonly invalidateCache?: () => void;\n private oauthProvider: McpOAuthClientProvider;\n private authorizationUrl?: URL;\n private connectionStatus: McpClientStatus = \"disconnected\";\n\n private readonly id: string;\n private readonly name: string;\n private readonly serverConfig: {\n url: string;\n type: \"http\" | \"sse\";\n headers?: Record<string, string>;\n oauthClientId?: string | null;\n oauthClientSecret?: string | null;\n };\n\n public constructor(\n id: string,\n name: string,\n serverConfig: {\n readonly url: string;\n readonly type: \"http\" | \"sse\";\n readonly headers?: Readonly<Record<string, string>>;\n readonly oauthClientId?: string | null;\n readonly oauthClientSecret?: string | null;\n },\n invalidateCache?: () => void\n ) {\n this.invalidateCache = invalidateCache;\n this.id = id;\n this.name = name;\n this.serverConfig = serverConfig;\n this.oauthProvider = this.createOAuthProvider();\n }\n\n private createOAuthProvider(): McpOAuthClientProvider {\n const { generation } = this;\n const baseUrl = getBaseUrl();\n\n return new McpOAuthClientProvider({\n clientMetadata: {\n client_name: `${config.appPrefix}-${this.name}`,\n grant_types: [\"authorization_code\", \"refresh_token\"],\n redirect_uris: [`${baseUrl}/api/mcp/oauth/callback`],\n response_types: [\"code\"],\n scope: \"mcp:tools\",\n software_id: config.appPrefix,\n software_version: \"1.0.0\",\n token_endpoint_auth_method:\n typeof this.serverConfig.oauthClientId === \"string\" &&\n this.serverConfig.oauthClientId !== \"\" &&\n typeof this.serverConfig.oauthClientSecret === \"string\" &&\n this.serverConfig.oauthClientSecret !== \"\"\n ? \"client_secret_basic\"\n : \"none\",\n },\n mcpConnectorId: this.id,\n oauthClientId: this.serverConfig.oauthClientId,\n oauthClientSecret: this.serverConfig.oauthClientSecret,\n onRedirectToAuthorization: (\n authorizationUrl: ReadonlyNativeSurface<URL>\n ): never => {\n if (generation !== this.generation) {\n throw new Error(\"MCP connection was closed\");\n }\n this.authorizationUrl = authorizationUrl;\n throw new OAuthAuthorizationRequiredError(authorizationUrl);\n },\n serverUrl: this.serverConfig.url,\n });\n }\n\n public get status(): McpClientStatus {\n if (this.authorizationUrl) {\n return \"authorizing\";\n }\n if (this.client) {\n return \"connected\";\n }\n return this.connectionStatus;\n }\n\n public getAuthorizationUrl(): URL | undefined {\n return this.authorizationUrl;\n }\n\n public get serverInfo(): McpClientInstance[\"serverInfo\"] | undefined {\n const { client } = this;\n return client && client.serverInfo;\n }\n\n public async connect({\n oauthState,\n abortSignal,\n }: {\n readonly oauthState?: string;\n readonly abortSignal?: Readonly<\n Pick<\n AbortSignal,\n | \"throwIfAborted\"\n | \"reason\"\n | \"addEventListener\"\n | \"removeEventListener\"\n | \"aborted\"\n >\n >;\n } = {}): Promise<void> {\n if (abortSignal) {\n abortSignal.throwIfAborted();\n }\n if (!this.connectPromise) {\n const { generation } = this;\n this.connectPromise = (async (): Promise<void> => {\n try {\n await this.connectOnce(oauthState);\n } finally {\n // Only close() can retire a pending attempt and allow a replacement.\n if (this.generation === generation) {\n this.connectPromise = undefined;\n }\n }\n })();\n }\n if (!abortSignal) {\n await this.connectPromise;\n return;\n }\n const aborted = Promise.withResolvers<never>();\n const cancel = (): void => {\n aborted.reject(abortSignal.reason);\n };\n abortSignal.addEventListener(\"abort\", cancel, { once: true });\n if (abortSignal.aborted) {\n cancel();\n }\n try {\n await Promise.race([this.connectPromise, aborted.promise]);\n } finally {\n abortSignal.removeEventListener(\"abort\", cancel);\n }\n }\n private async connectOnce(oauthState?: string): Promise<void> {\n if (this.status === \"connected\" && this.client) {\n return;\n }\n\n const { generation, oauthProvider } = this;\n this.connectionAbort = new AbortController();\n const signal = AbortSignal.any([\n this.connectionAbort.signal,\n AbortSignal.timeout(MCP_CONNECTION_TIMEOUT_MS),\n ]);\n this.connectionStatus = \"connecting\";\n\n try {\n // Adopt state if provided (for callback reconciliation).\n if (typeof oauthState === \"string\" && oauthState !== \"\") {\n await oauthProvider.adoptState(oauthState);\n }\n signal.throwIfAborted();\n // AI SDK handles 401 internally and calls auth() with the provider\n const client = await createMCPClient({\n initializationOptions: { signal },\n transport: {\n authProvider: oauthProvider,\n fetch: toMcpSdkFetch(oauthProvider.fetch),\n headers: this.serverConfig.headers,\n type: this.serverConfig.type,\n url: this.serverConfig.url,\n },\n });\n\n if (generation !== this.generation || signal.aborted) {\n await client.close();\n signal.throwIfAborted();\n throw new Error(\"MCP connection was closed\");\n }\n this.client = client;\n this.authorizationUrl = undefined;\n this.connectionStatus = \"connected\";\n } catch (error) {\n if (generation !== this.generation || signal.aborted) {\n if (generation === this.generation) {\n this.authorizationUrl = undefined;\n this.connectionStatus = \"disconnected\";\n }\n throw error;\n }\n // If OAuth required error, status becomes \"authorizing\"\n if (error instanceof OAuthAuthorizationRequiredError) {\n this.connectionStatus = \"authorizing\";\n log.info(\n { authUrl: error.authorizationUrl.toString(), connectorId: this.id },\n \"OAuth authorization required\"\n );\n return;\n }\n\n this.connectionStatus = \"disconnected\";\n throw error;\n }\n }\n /**\n * Lightweight connection test - just checks if we can connect without full discovery.\n * Returns connection status without fetching tools/resources/prompts.\n * @param {Readonly<Pick<AbortSignal, \"throwIfAborted\" | \"reason\" | \"addEventListener\" | \"removeEventListener\" | \"aborted\">> | undefined} abortSignal - Cancels this caller while shared initialization continues.\n * @returns {Promise<{ status: McpClientStatus; needsAuth: boolean; error?: string; }>} The connection or authorization status.\n */\n public async attemptConnection(\n abortSignal?: Readonly<\n Pick<\n AbortSignal,\n | \"throwIfAborted\"\n | \"reason\"\n | \"addEventListener\"\n | \"removeEventListener\"\n | \"aborted\"\n >\n >\n ): Promise<{\n status: McpClientStatus;\n needsAuth: boolean;\n error?: string;\n }> {\n // If already connected, return current status\n if (this.status === \"connected\" && this.client) {\n return { needsAuth: false, status: \"connected\" };\n }\n\n // If already in authorizing state, return that\n if (this.authorizationUrl) {\n return { needsAuth: true, status: \"authorizing\" };\n }\n\n try {\n await this.connect({ abortSignal });\n // Check if OAuth is required (authorizationUrl gets set during connect)\n if (this.authorizationUrl !== undefined) {\n return { needsAuth: true, status: \"authorizing\" };\n }\n return {\n needsAuth: false,\n status: this.client ? \"connected\" : \"disconnected\",\n };\n } catch (error) {\n const errorMessage = getMcpErrorMessage(error);\n log.error(\n {\n connectorId: this.id,\n errorMessage,\n errorStack: error instanceof Error ? error.stack : undefined,\n },\n \"attemptConnection failed\"\n );\n\n // Detect incompatible server errors\n if (\n errorMessage.includes(\"does not support dynamic client registration\")\n ) {\n this.connectionStatus = \"incompatible\";\n return {\n error:\n \"Server requires pre-configured OAuth credentials (does not support dynamic client registration)\",\n needsAuth: false,\n status: \"incompatible\",\n };\n }\n\n return { error: errorMessage, needsAuth: false, status: \"disconnected\" };\n }\n }\n /**\n * Called after callback receives code to complete the OAuth flow.\n * @param {string} code - Authorization code received by the callback.\n * @param {string} state - State used to restore the verifier session.\n */\n public async finishAuth(code: string, state: string): Promise<void> {\n const { generation, oauthProvider } = this;\n // Always adopt the state from the callback to load the session with code verifier\n await oauthProvider.adoptState(state);\n\n // Use the auth function from @ai-sdk/mcp to complete the OAuth flow\n await auth(oauthProvider, {\n authorizationCode: code,\n fetchFn: toMcpSdkFetch(oauthProvider.fetch),\n serverUrl: this.serverConfig.url,\n });\n\n if (generation !== this.generation) {\n throw new Error(\"MCP connection was closed\");\n }\n this.authorizationUrl = undefined;\n // Don't set to connected - tokens are saved, next connect() will use them\n }\n /**\n * Get tools from the MCP server, already in AI SDK format.\n * @param {Parameters<McpClientInstance[\"tools\"]>} args - Native SDK schema options.\n * @returns {Promise<Record<string, Tool>>} The discovered SDK tools.\n */\n public async tools(\n ...args: Parameters<NonNullable<McpClientInstance>[\"tools\"]>\n ): Promise<Record<string, Tool>> {\n const { client } = this;\n if (!client) {\n throw new Error(\"Client not connected\");\n }\n try {\n return await client.tools(...args);\n } catch (error) {\n await this.handlePotentialAuthError(error, client);\n throw error;\n }\n }\n /**\n * List resources from the MCP server.\n * @returns {Promise<ListResourcesResult>} The native MCP resource result.\n */\n public async listResources(): Promise<ListResourcesResult> {\n const { client } = this;\n if (!client) {\n throw new Error(\"Client not connected\");\n }\n try {\n return await client.listResources();\n } catch (error) {\n await this.handlePotentialAuthError(error, client);\n throw error;\n }\n }\n /**\n * List prompts from the MCP server.\n * @returns {Promise<ListPromptsResult>} The native MCP prompt result.\n */\n public async listPrompts(): Promise<ListPromptsResult> {\n const { client } = this;\n if (!client) {\n throw new Error(\"Client not connected\");\n }\n try {\n return await client.listPrompts();\n } catch (error) {\n await this.handlePotentialAuthError(error, client);\n throw error;\n }\n }\n /**\n * Close the connection to the MCP server.\n */\n public async close(): Promise<void> {\n this.generation += 1;\n const { connectionAbort } = this;\n if (connectionAbort) {\n connectionAbort.abort(new Error(\"MCP connection was closed\"));\n }\n this.connectPromise = undefined;\n this.oauthProvider = this.createOAuthProvider();\n const { client } = this;\n this.client = undefined;\n this.authorizationUrl = undefined;\n this.connectionStatus = \"disconnected\";\n try {\n // Await even without a client to preserve cache-invalidation timing.\n await (client && client.close());\n } catch (error) {\n log.error({ connectorId: this.id, error }, \"Error closing MCP client\");\n }\n if (this.invalidateCache) {\n this.invalidateCache();\n }\n }\n /**\n * Check if an error is an auth error (401/403) and invalidate caches if so.\n * @param {unknown} error - Failure from a connected SDK operation.\n * @param {unknown} origin - Client whose failure is being handled.\n */\n private async handlePotentialAuthError(\n error: unknown,\n origin: unknown\n ): Promise<void> {\n if (this.client !== origin) {\n return;\n }\n const errorMessage = getMcpErrorMessage(error);\n const isAuthError =\n errorMessage.includes(\"401\") ||\n errorMessage.includes(\"403\") ||\n errorMessage.includes(\"Unauthorized\") ||\n errorMessage.includes(\"Forbidden\");\n\n if (isAuthError) {\n log.warn(\n { connectorId: this.id, errorMessage },\n \"Auth error detected, invalidating caches\"\n );\n await this.close();\n }\n }\n}\n",
|
|
179
179
|
"type": "registry:file",
|
|
180
180
|
"target": "~/chatjs/plugins/mcp/oauth/mcp-client.ts"
|
|
181
181
|
},
|
|
@@ -3,14 +3,13 @@
|
|
|
3
3
|
"name": "openai-compatible-gateway",
|
|
4
4
|
"title": "OpenAI Compatible",
|
|
5
5
|
"dependencies": [
|
|
6
|
-
"@
|
|
7
|
-
"@ai-sdk/openai-compatible@3.0.44",
|
|
6
|
+
"@ai-sdk/openai-compatible@3.0.92",
|
|
8
7
|
"zod@4.5.4"
|
|
9
8
|
],
|
|
10
9
|
"files": [
|
|
11
10
|
{
|
|
12
11
|
"path": "src/gateways/openai-compatible/gateway.ts",
|
|
13
|
-
"content": "import type { LanguageModelV4 } from \"@ai-sdk/provider\";\n\nimport type { AiGatewayModel } from \"
|
|
12
|
+
"content": "import type { LanguageModelV4 } from \"@ai-sdk/provider\";\n\nimport type { AiGatewayModel } from \"@/chatjs/core/gateway/models\";\n\nimport type { GatewayProvider } from \"@/chatjs/core/gateway/gateway-provider\";\n\nimport { GatewayRuntime } from \"@/chatjs/core/gateway/runtime\";\n\nimport type { ImageModel } from \"ai\";\nimport { createOpenAICompatible } from \"@ai-sdk/openai-compatible\";\nimport { z } from \"zod\";\n\nconst providerModelSchema = z.object({\n created: z.number().nullish(),\n id: z.string(),\n owned_by: z.string().nullish(),\n});\ntype OpenAICompatibleModelResponse = z.output<typeof providerModelSchema>;\nconst providerModelListSchema = z.object({\n data: z.array(z.unknown()),\n});\n\nconst EMPTY_MODEL_COUNT = 0;\nconst UNKNOWN_MODEL_LIMIT = 0;\nconst UNKNOWN_MODEL_TIMESTAMP = 0;\nconst toAiGatewayModel = (\n model: Readonly<OpenAICompatibleModelResponse>\n): AiGatewayModel => ({\n context_window: UNKNOWN_MODEL_LIMIT,\n created: model.created ?? UNKNOWN_MODEL_TIMESTAMP,\n description: \"\",\n id: model.id,\n max_tokens: UNKNOWN_MODEL_LIMIT,\n name: model.id,\n object: \"model\",\n owned_by: model.owned_by ?? \"unknown\",\n pricing: {},\n type: \"language\",\n});\n\n// Validate the wire envelope separately from each model so valid neighbors survive.\nconst parseProviderModels = (value: unknown): AiGatewayModel[] => {\n const body = providerModelListSchema.parse(value);\n const result = body.data.flatMap((entry): AiGatewayModel[] => {\n const model = providerModelSchema.safeParse(entry);\n if (!model.success) {\n return [];\n }\n return [toAiGatewayModel(model.data)];\n });\n // A genuinely empty catalog is valid; a nonempty unparseable catalog is not.\n if (\n body.data.length > EMPTY_MODEL_COUNT &&\n result.length === EMPTY_MODEL_COUNT\n ) {\n throw new Error(\"Provider catalog contains no valid models.\");\n }\n return result;\n};\n\nclass OpenAICompatibleGateway\n extends GatewayRuntime\n implements GatewayProvider<\"openai-compatible\">\n{\n public readonly type = \"openai-compatible\" as const;\n\n private getProvider(): ReturnType<typeof createOpenAICompatible> {\n const apiKey = this.getApiKey();\n const baseURL = this.getBaseURL();\n if (!(typeof baseURL === \"string\" && baseURL !== \"\")) {\n throw new Error(\"OPENAI_COMPATIBLE_BASE_URL is not configured\");\n }\n return createOpenAICompatible({\n apiKey,\n baseURL,\n name: \"openai-compatible\",\n });\n }\n\n public createLanguageModel(modelId: string): LanguageModelV4 {\n const provider = this.getProvider();\n return provider(modelId);\n }\n\n public createImageModel(modelId: string): ImageModel {\n const provider = this.getProvider();\n return provider.imageModel(modelId);\n }\n\n public readonly createVideoModel = null;\n\n private getApiKey(): string | undefined {\n return this.env.OPENAI_COMPATIBLE_API_KEY;\n }\n\n private getBaseURL(): string | undefined {\n const baseURL = this.env.OPENAI_COMPATIBLE_BASE_URL;\n if (baseURL === undefined || baseURL === \"\") {\n return undefined;\n }\n return z.url().parse(baseURL);\n }\n\n public async fetchModels(): Promise<AiGatewayModel[]> {\n const apiKey = this.getApiKey();\n const baseURL = this.getBaseURL();\n\n if (!(typeof baseURL === \"string\" && baseURL !== \"\")) {\n this.log.warn(\n \"No OPENAI_COMPATIBLE_BASE_URL found, using fallback models\"\n );\n return [...this.getFallbackModels(this.type)];\n }\n\n const url = `${baseURL}/models`;\n this.log.debug({ url }, \"Fetching models from OpenAI-compatible provider\");\n\n try {\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n };\n if (typeof apiKey === \"string\" && apiKey !== \"\") {\n headers.Authorization = `Bearer ${apiKey}`;\n }\n\n const response = await this.fetch(url, {\n headers,\n });\n\n if (!response.ok) {\n this.log.error(\n { status: response.status, statusText: response.statusText, url },\n \"OpenAI-compatible provider returned non-OK response\"\n );\n throw new Error(`Failed to fetch models: ${response.statusText}`);\n }\n\n const result = parseProviderModels(await response.json());\n\n this.log.info(\n { modelCount: result.length },\n \"Successfully fetched models from OpenAI-compatible provider\"\n );\n return result;\n } catch (error) {\n this.log.error(\n { err: error, url },\n \"Error fetching models from OpenAI-compatible provider, falling back to generated models\"\n );\n return [...this.getFallbackModels(this.type)];\n }\n }\n}\nexport { OpenAICompatibleGateway as Gateway, OpenAICompatibleGateway };\n",
|
|
14
13
|
"type": "registry:file",
|
|
15
14
|
"target": "~/chatjs/providers/gateway.ts"
|
|
16
15
|
}
|
|
@@ -3,14 +3,13 @@
|
|
|
3
3
|
"name": "openai-gateway",
|
|
4
4
|
"title": "OpenAI",
|
|
5
5
|
"dependencies": [
|
|
6
|
-
"@
|
|
7
|
-
"@ai-sdk/openai@4.0.59",
|
|
6
|
+
"@ai-sdk/openai@4.0.117",
|
|
8
7
|
"zod@4.5.4"
|
|
9
8
|
],
|
|
10
9
|
"files": [
|
|
11
10
|
{
|
|
12
11
|
"path": "src/gateways/openai/gateway.ts",
|
|
13
|
-
"content": "import type { LanguageModelV4 } from \"@ai-sdk/provider\";\n\nimport type {
|
|
12
|
+
"content": "import type { LanguageModelV4 } from \"@ai-sdk/provider\";\n\nimport type { AiGatewayModel } from \"@/chatjs/core/gateway/models\";\n\nimport type { GatewayProvider } from \"@/chatjs/core/gateway/gateway-provider\";\n\nimport { GatewayRuntime } from \"@/chatjs/core/gateway/runtime\";\n\nimport type { ImageModel } from \"ai\";\nimport { createOpenAI } from \"@ai-sdk/openai\";\nimport { z } from \"zod\";\n\nconst MODEL_ID_PARAMETER_INDEX = 0;\ntype OpenAiLanguageModelId = Parameters<\n ReturnType<typeof createOpenAI>[\"languageModel\"]\n>[typeof MODEL_ID_PARAMETER_INDEX];\ntype OpenAiImageModelId = Parameters<\n ReturnType<typeof createOpenAI>[\"image\"]\n>[typeof MODEL_ID_PARAMETER_INDEX];\n\nconst providerModelSchema = z.object({\n created: z.number().nullish(),\n id: z.string(),\n owned_by: z.string().nullish(),\n});\ntype OpenAIModelResponse = z.output<typeof providerModelSchema>;\nconst providerModelListSchema = z.object({\n data: z.array(z.unknown()),\n});\n\nconst EMPTY_MODEL_COUNT = 0;\nconst UNKNOWN_MODEL_LIMIT = 0;\nconst UNKNOWN_MODEL_TIMESTAMP = 0;\nconst toAiGatewayModel = (\n model: Readonly<OpenAIModelResponse>\n): AiGatewayModel => ({\n context_window: UNKNOWN_MODEL_LIMIT,\n created: model.created ?? UNKNOWN_MODEL_TIMESTAMP,\n description: \"\",\n id: model.id,\n max_tokens: UNKNOWN_MODEL_LIMIT,\n name: model.id,\n object: \"model\",\n owned_by:\n (model.owned_by === \"system\" ? \"openai\" : model.owned_by) ?? \"openai\",\n pricing: {},\n type: \"language\",\n});\n\n// Validate the wire envelope separately from each model so valid neighbors survive.\nconst parseProviderModels = (value: unknown): AiGatewayModel[] => {\n const body = providerModelListSchema.parse(value);\n const result = body.data.flatMap((entry): AiGatewayModel[] => {\n const model = providerModelSchema.safeParse(entry);\n if (!model.success) {\n return [];\n }\n return [toAiGatewayModel(model.data)];\n });\n // A genuinely empty catalog is valid; a nonempty unparseable catalog is not.\n if (\n body.data.length > EMPTY_MODEL_COUNT &&\n result.length === EMPTY_MODEL_COUNT\n ) {\n throw new Error(\"Provider catalog contains no valid models.\");\n }\n return result;\n};\n\nclass OpenAIGateway\n extends GatewayRuntime\n implements GatewayProvider<\"openai\">\n{\n public readonly type = \"openai\" as const;\n\n private getProvider(): ReturnType<typeof createOpenAI> {\n const apiKey = this.getApiKey();\n if (!(typeof apiKey === \"string\" && apiKey !== \"\")) {\n throw new Error(\"OPENAI_API_KEY is not configured\");\n }\n return createOpenAI({ apiKey });\n }\n\n public createLanguageModel(modelId: OpenAiLanguageModelId): LanguageModelV4 {\n const provider = this.getProvider();\n return provider(modelId);\n }\n\n public createImageModel(modelId: OpenAiImageModelId): ImageModel {\n const provider = this.getProvider();\n return provider.image(modelId);\n }\n\n public readonly createVideoModel = null;\n\n private getApiKey(): string | undefined {\n return this.env.OPENAI_API_KEY;\n }\n\n public async fetchModels(): Promise<AiGatewayModel[]> {\n const apiKey = this.getApiKey();\n\n if (!(typeof apiKey === \"string\" && apiKey !== \"\")) {\n this.log.warn(\"No OPENAI_API_KEY found, using fallback models\");\n return [...this.getFallbackModels(this.type)];\n }\n\n const url = \"https://api.openai.com/v1/models\";\n this.log.debug({ url }, \"Fetching models from OpenAI\");\n\n try {\n const response = await this.fetch(url, {\n headers: {\n Authorization: `Bearer ${apiKey}`,\n \"Content-Type\": \"application/json\",\n },\n });\n\n if (!response.ok) {\n this.log.error(\n { status: response.status, statusText: response.statusText, url },\n \"OpenAI returned non-OK response\"\n );\n throw new Error(`Failed to fetch models: ${response.statusText}`);\n }\n\n const result = parseProviderModels(await response.json());\n\n this.log.info(\n { modelCount: result.length },\n \"Successfully fetched models from OpenAI\"\n );\n return result;\n } catch (error) {\n this.log.error(\n { err: error, url },\n \"Error fetching models from OpenAI, falling back to generated models\"\n );\n return [...this.getFallbackModels(this.type)];\n }\n }\n}\nexport { OpenAIGateway as Gateway, OpenAIGateway };\n",
|
|
14
13
|
"type": "registry:file",
|
|
15
14
|
"target": "~/chatjs/providers/gateway.ts"
|
|
16
15
|
}
|