chat-js 1.0.0-alpha.5 → 1.0.0-alpha.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.
Files changed (44) hide show
  1. package/README.md +3 -3
  2. package/dist/index.js +21864 -21965
  3. package/package.json +1 -2
  4. package/templates/chat-app/app/(chat)/layout.tsx +8 -20
  5. package/templates/chat-app/chatjs/core/gateway/defaults.ts +43 -0
  6. package/templates/chat-app/chatjs/core/gateway/gateway-provider.ts +23 -0
  7. package/templates/chat-app/chatjs/core/gateway/models.test.ts +39 -0
  8. package/templates/chat-app/chatjs/core/gateway/models.ts +67 -0
  9. package/templates/chat-app/chatjs/core/gateway/provider-types.ts +11 -0
  10. package/templates/chat-app/chatjs/core/gateway/runtime.test.ts +30 -0
  11. package/templates/chat-app/chatjs/core/gateway/runtime.ts +62 -0
  12. package/templates/chat-app/chatjs/plugins/guest-chat/guest-policy.ts +1 -0
  13. package/templates/chat-app/chatjs/plugins/guest-chat/signed-out.tsx +14 -2
  14. package/templates/chat-app/chatjs/plugins/mcp/routes/oauth-callback.ts +27 -26
  15. package/templates/chat-app/chatjs/plugins/model-preferences/settings-link.tsx +1 -2
  16. package/templates/chat-app/chatjs/providers/gateway-defaults.ts +1 -1
  17. package/templates/chat-app/chatjs/providers/gateway.ts +47 -26
  18. package/templates/chat-app/chatjs/tools/attach-workspace-file/schemas.ts +13 -2
  19. package/templates/chat-app/components/eve/eve-model-picker.tsx +3 -0
  20. package/templates/chat-app/components/model-selector-view.tsx +8 -15
  21. package/templates/chat-app/components/model-selector.tsx +1 -0
  22. package/templates/chat-app/integrations/chat/model-options.ts +75 -0
  23. package/templates/chat-app/integrations/chat/models.ts +3 -8
  24. package/templates/chat-app/lib/ai/app-models.test.ts +41 -46
  25. package/templates/chat-app/lib/ai/app-models.ts +4 -154
  26. package/templates/chat-app/lib/ai/gateways/fallback-models.ts +1 -1
  27. package/templates/chat-app/lib/ai/gateways/registry.ts +2 -2
  28. package/templates/chat-app/lib/ai/models.generated.ts +1 -1
  29. package/templates/chat-app/lib/ai/models.ts +1 -1
  30. package/templates/chat-app/lib/ai/to-model-data.test.ts +1 -1
  31. package/templates/chat-app/lib/ai/to-model-data.ts +1 -1
  32. package/templates/chat-app/lib/ai/web-chat-models.ts +70 -0
  33. package/templates/chat-app/lib/config-schema.ts +1 -1
  34. package/templates/chat-app/lib/eve/application-model.ts +17 -5
  35. package/templates/chat-app/lib/eve/model-selection.test.ts +6 -0
  36. package/templates/chat-app/lib/eve/model-selection.ts +41 -7
  37. package/templates/chat-app/lib/eve/tool-cost.ts +1 -1
  38. package/templates/chat-app/next.config.ts +0 -1
  39. package/templates/chat-app/package.json +1 -2
  40. package/templates/chat-app/providers/chat-models-provider.tsx +1 -2
  41. package/templates/chat-app/scripts/fetch-models.ts +1 -1
  42. package/templates/electron/src/config.ts +7 -23
  43. package/templates/electron/src/lib/auth-client.ts +3 -4
  44. package/templates/electron/src/startup-config.test.ts +133 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "chat-js",
3
- "version": "1.0.0-alpha.5",
3
+ "version": "1.0.0-alpha.7",
4
4
  "private": false,
5
5
  "description": "CLI for creating and extending ChatJS apps",
6
6
  "keywords": [
@@ -51,7 +51,6 @@
51
51
  "test:native-agent": "bun test/native-agent-acceptance.ts"
52
52
  },
53
53
  "dependencies": {
54
- "@chat-js/gateways": "0.2.2",
55
54
  "@clack/prompts": "^1.0.1",
56
55
  "commander": "^14.0.0",
57
56
  "files-sdk": "2.5.0",
@@ -1,4 +1,3 @@
1
- import { webModels } from "@/integrations/chat/models";
2
1
  import { cookies, headers } from "next/headers";
3
2
  import React, { Suspense } from "react";
4
3
 
@@ -12,8 +11,10 @@ import {
12
11
  ChatWorkspace,
13
12
  ChatWorkspaceContent,
14
13
  } from "@/components/chat/chat-workspace";
15
- import type { AppModelId } from "@/lib/ai/app-model-id";
16
- import { config } from "@/lib/config";
14
+ import {
15
+ getConfiguredWebChatModel,
16
+ getDefaultWebChatModelId,
17
+ } from "@/lib/ai/web-chat-models";
17
18
  import { isPlaywrightTestEnvironment } from "@/lib/constants";
18
19
  import { resolveEvePrincipal } from "@/lib/eve/principal";
19
20
  import type { ReadonlyReactNode } from "@/lib/readonly-react-node";
@@ -26,22 +27,6 @@ import { HydrateClient } from "@/trpc/server";
26
27
 
27
28
  import { auth } from "@/lib/auth";
28
29
 
29
- const resolveDefaultModel = (
30
- cookieModel: string | undefined,
31
- chatModels: readonly { readonly id: string }[]
32
- ): AppModelId => {
33
- const configuredModel = webModels.model ?? config.ai.workflows.chat;
34
- let defaultModel: AppModelId = cookieModel ?? configuredModel;
35
-
36
- if (typeof cookieModel === "string" && cookieModel !== "") {
37
- const modelExists = chatModels.some((model) => model.id === cookieModel);
38
- if (!modelExists) {
39
- defaultModel = configuredModel;
40
- }
41
- }
42
- return defaultModel;
43
- };
44
-
45
30
  const ChatLayoutDynamic = async ({
46
31
  children,
47
32
  }: {
@@ -61,7 +46,10 @@ const ChatLayoutDynamic = async ({
61
46
 
62
47
  const cookieModel = cookieStore.get("chat-model")?.value;
63
48
 
64
- const defaultModel = resolveDefaultModel(cookieModel, chatModels);
49
+ const defaultModel =
50
+ chatModels.find((model) => model.id === cookieModel)?.id ??
51
+ getDefaultWebChatModelId(chatModels) ??
52
+ getConfiguredWebChatModel();
65
53
 
66
54
  return (
67
55
  <HydrateClient>
@@ -0,0 +1,43 @@
1
+ import type { ConfigMediaModelId } from "./provider-types.ts";
2
+ import type { GatewayProvider } from "./gateway-provider.ts";
3
+
4
+ const MODEL_ID_PARAMETER_INDEX = 0;
5
+
6
+ interface GatewayModelDefaults<TGateway extends GatewayProvider> {
7
+ curatedDefaults: Parameters<
8
+ TGateway["createLanguageModel"]
9
+ >[typeof MODEL_ID_PARAMETER_INDEX][];
10
+ disabledModels: Parameters<
11
+ TGateway["createLanguageModel"]
12
+ >[typeof MODEL_ID_PARAMETER_INDEX][];
13
+ providerOrder: string[];
14
+ roles: {
15
+ fast: Parameters<
16
+ TGateway["createLanguageModel"]
17
+ >[typeof MODEL_ID_PARAMETER_INDEX];
18
+ balanced: Parameters<
19
+ TGateway["createLanguageModel"]
20
+ >[typeof MODEL_ID_PARAMETER_INDEX];
21
+ smart: Parameters<
22
+ TGateway["createLanguageModel"]
23
+ >[typeof MODEL_ID_PARAMETER_INDEX];
24
+ image?: ConfigMediaModelId<TGateway["createImageModel"]>;
25
+ video?: ConfigMediaModelId<TGateway["createVideoModel"]>;
26
+ };
27
+ workflows: {
28
+ chat: Parameters<
29
+ TGateway["createLanguageModel"]
30
+ >[typeof MODEL_ID_PARAMETER_INDEX];
31
+ title: Parameters<
32
+ TGateway["createLanguageModel"]
33
+ >[typeof MODEL_ID_PARAMETER_INDEX];
34
+ pdf: Parameters<
35
+ TGateway["createLanguageModel"]
36
+ >[typeof MODEL_ID_PARAMETER_INDEX];
37
+ chatImageCompatible: Parameters<
38
+ TGateway["createLanguageModel"]
39
+ >[typeof MODEL_ID_PARAMETER_INDEX];
40
+ };
41
+ }
42
+
43
+ export type { GatewayModelDefaults };
@@ -0,0 +1,23 @@
1
+ import type {
2
+ Experimental_VideoModelV4,
3
+ LanguageModelV4,
4
+ } from "@ai-sdk/provider";
5
+ import type { AiGatewayModel } from "./models.ts";
6
+ import type { ImageModel } from "ai";
7
+
8
+ interface GatewayProvider<TGateway extends string = string> {
9
+ /** Dedicated image model factory; null when this capability is unsupported. */
10
+ createImageModel: ((modelId: string) => ImageModel) | null;
11
+
12
+ /** Create a language model instance from a model ID like "openai/gpt-5-nano" */
13
+ createLanguageModel: (modelId: string) => LanguageModelV4;
14
+
15
+ /** Video model factory; null when this capability is unsupported. */
16
+ createVideoModel: ((modelId: string) => Experimental_VideoModelV4) | null;
17
+
18
+ /** Fetch the list of available models from the gateway's API */
19
+ fetchModels: () => Promise<AiGatewayModel[]>;
20
+ readonly type: TGateway;
21
+ }
22
+
23
+ export type { GatewayProvider };
@@ -0,0 +1,39 @@
1
+ import { describe, expect, expectTypeOf, it } from "vitest";
2
+
3
+ import type { AiGatewayModel } from "./models";
4
+ import { aiGatewayModelSchema } from "./models";
5
+
6
+ const tagsSchema = aiGatewayModelSchema.shape.tags;
7
+
8
+ describe("gateway model tags", () => {
9
+ it("accepts known and future provider tags without changing their values", () => {
10
+ const tags: NonNullable<AiGatewayModel["tags"]> = [
11
+ "reasoning",
12
+ "tool-use",
13
+ "vision",
14
+ "file-input",
15
+ "image-generation",
16
+ "implicit-caching",
17
+ "future-provider-tag",
18
+ "",
19
+ ];
20
+
21
+ expect(tagsSchema.parse(tags)).toEqual(tags);
22
+ expectTypeOf<string>().toExtend<
23
+ NonNullable<AiGatewayModel["tags"]>[number]
24
+ >();
25
+ expectTypeOf(tagsSchema.parse(tags)).toExtend<string[] | undefined>();
26
+ });
27
+
28
+ it("keeps tags optional and accepts an empty list", () => {
29
+ expect(aiGatewayModelSchema.pick({ tags: true }).parse({})).toEqual({});
30
+ expect(tagsSchema.parse([])).toEqual([]);
31
+ });
32
+
33
+ it.each([{ tag: true }, { tag: {} }, { tag: [] }])(
34
+ "rejects non-string tags: $tag",
35
+ ({ tag }: { readonly tag: unknown }) => {
36
+ expect(tagsSchema.safeParse([tag]).success).toBe(false);
37
+ }
38
+ );
39
+ });
@@ -0,0 +1,67 @@
1
+ import { z } from "zod";
2
+
3
+ // Known tags provide IDE hints; providers may introduce other string tags.
4
+ type KnownTag =
5
+ | "reasoning"
6
+ | "tool-use"
7
+ | "vision"
8
+ | "file-input"
9
+ | "image-generation"
10
+ | "implicit-caching";
11
+
12
+ type ModelTag = KnownTag | (string & Record<never, never>);
13
+
14
+ const tagSchema: z.ZodType<ModelTag> = z.string();
15
+
16
+ const supportedAiGatewayModelTypes = [
17
+ "language",
18
+ "embedding",
19
+ "image",
20
+ "video",
21
+ ] as const;
22
+
23
+ type AiGatewayModelType = (typeof supportedAiGatewayModelTypes)[number];
24
+
25
+ const aiGatewayModelTypeSchema = z.enum(supportedAiGatewayModelTypes);
26
+
27
+ const MIN_PRICING_TIER_BOUND = 0;
28
+
29
+ const pricingTierSchema = z.object({
30
+ cost: z.string(),
31
+ max: z.number().optional(),
32
+ min: z.number().default(MIN_PRICING_TIER_BOUND),
33
+ });
34
+
35
+ // Model catalog record returned by gateway adapters.
36
+ const aiGatewayModelSchema = z.object({
37
+ context_window: z.number(),
38
+ created: z.number(),
39
+ description: z.string(),
40
+ id: z.string(),
41
+ max_tokens: z.number(),
42
+ name: z.string(),
43
+ object: z.literal("model"),
44
+ owned_by: z.string(),
45
+ pricing: z.object({
46
+ image: z.string().optional(),
47
+ input: z.string().optional(),
48
+ input_cache_read: z.string().optional(),
49
+ input_cache_read_tiers: z.array(pricingTierSchema).optional(),
50
+ input_cache_write: z.string().optional(),
51
+ input_tiers: z.array(pricingTierSchema).optional(),
52
+ output: z.string().optional(),
53
+ output_tiers: z.array(pricingTierSchema).optional(),
54
+ web_search: z.string().optional(),
55
+ }),
56
+ tags: z.array(tagSchema).optional(),
57
+ type: aiGatewayModelTypeSchema,
58
+ });
59
+
60
+ type AiGatewayModel = z.infer<typeof aiGatewayModelSchema>;
61
+
62
+ const isAiGatewayModelType = (type: string): type is AiGatewayModelType =>
63
+ supportedAiGatewayModelTypes.some((supportedType) => supportedType === type);
64
+
65
+ export { aiGatewayModelSchema, isAiGatewayModelType };
66
+
67
+ export type { AiGatewayModelType, AiGatewayModel };
@@ -0,0 +1,11 @@
1
+ type StrictLiterals<TValue> = TValue extends string
2
+ ? string extends TValue
3
+ ? never
4
+ : TValue
5
+ : TValue;
6
+
7
+ // Null capabilities have no configurable IDs; supported factories retain SDK suggestions.
8
+ type ConfigMediaModelId<Factory extends ((modelId: string) => unknown) | null> =
9
+ Parameters<NonNullable<Factory>>[0];
10
+
11
+ export type { ConfigMediaModelId, StrictLiterals };
@@ -0,0 +1,30 @@
1
+ import { afterEach, expect, test, vi } from "vitest";
2
+ import { GatewayRuntime } from "./runtime";
3
+
4
+ class RuntimeProbe extends GatewayRuntime {
5
+ public get request(): typeof fetch {
6
+ return this.fetch;
7
+ }
8
+ }
9
+
10
+ afterEach(() => {
11
+ vi.unstubAllGlobals();
12
+ });
13
+
14
+ test("default fetch reads the current global and forwards arguments, results and failures", async () => {
15
+ const runtime = new RuntimeProbe();
16
+ const response = Promise.resolve(new Response("ok"));
17
+ const request = new Request("https://example.com");
18
+ const options = { headers: { "x-test": "forwarded" } };
19
+ const fetchMock = vi.fn<typeof fetch>().mockReturnValue(response);
20
+ vi.stubGlobal("fetch", fetchMock);
21
+ await expect(runtime.request(request, options)).resolves.toBe(await response);
22
+ expect(fetchMock.mock.calls[0]?.[0]).toBe(request);
23
+ expect(fetchMock.mock.calls[0]?.[1]).toBe(options);
24
+
25
+ const failure = new Error("custom fetch validation");
26
+ fetchMock.mockImplementation(() => {
27
+ throw failure;
28
+ });
29
+ await expect(runtime.request(request)).rejects.toBe(failure);
30
+ });
@@ -0,0 +1,62 @@
1
+ import type { AiGatewayModel } from "./models.ts";
2
+
3
+ interface GatewayLogger {
4
+ debug: (data: unknown, message?: string) => void;
5
+ info: (data: unknown, message?: string) => void;
6
+ warn: (data: unknown, message?: string) => void;
7
+ error: (data: unknown, message?: string) => void;
8
+ }
9
+
10
+ interface GatewayOptions {
11
+ env?: Record<string, string | undefined>;
12
+ fetch?: (
13
+ ...args: Parameters<typeof globalThis.fetch>
14
+ ) => ReturnType<typeof globalThis.fetch>;
15
+ getFallbackModels?: (gateway: string) => readonly AiGatewayModel[];
16
+ logger?: GatewayLogger;
17
+ }
18
+
19
+ type GatewayReaderOptions = Readonly<Omit<GatewayOptions, "env" | "logger">> & {
20
+ readonly env?: Readonly<NonNullable<GatewayOptions["env"]>>;
21
+ readonly logger?: Readonly<GatewayLogger>;
22
+ };
23
+
24
+ const silentLogger: GatewayLogger = {
25
+ debug: (): void => {
26
+ /* Intentionally silent when no logger is provided. */
27
+ },
28
+ error: (): void => {
29
+ /* Intentionally silent when no logger is provided. */
30
+ },
31
+ info: (): void => {
32
+ /* Intentionally silent when no logger is provided. */
33
+ },
34
+ warn: (): void => {
35
+ /* Intentionally silent when no logger is provided. */
36
+ },
37
+ };
38
+
39
+ class GatewayRuntime {
40
+ protected readonly env: NonNullable<GatewayOptions["env"]>;
41
+ protected readonly fetch: NonNullable<GatewayOptions["fetch"]>;
42
+ protected readonly getFallbackModels: NonNullable<
43
+ GatewayOptions["getFallbackModels"]
44
+ >;
45
+ protected readonly log: GatewayLogger;
46
+
47
+ public constructor(options: GatewayReaderOptions = {}) {
48
+ this.env = options.env ?? process.env;
49
+ this.fetch =
50
+ options.fetch ??
51
+ (async (
52
+ ...args: Parameters<typeof globalThis.fetch>
53
+ ): ReturnType<typeof globalThis.fetch> =>
54
+ await globalThis.fetch(...args));
55
+ this.getFallbackModels = options.getFallbackModels ?? ((): never[] => []);
56
+ this.log = options.logger ?? silentLogger;
57
+ }
58
+ }
59
+
60
+ export { GatewayRuntime };
61
+
62
+ export type { GatewayOptions };
@@ -7,6 +7,7 @@ export const guestModelIdForGateway = (gateway: string): string =>
7
7
  export const GUEST_POLICY = {
8
8
  version: "1",
9
9
  modelId: guestModelIdForGateway(config.ai.gateway),
10
+ modelName: "GPT-5 nano",
10
11
  requestsPerMinute: 5,
11
12
  sessionsPerHour: 5,
12
13
  credentialDurationMs: 3_600_000,
@@ -133,7 +133,13 @@ const GuestConversationView = ({
133
133
  <EveComposer
134
134
  autoFocus
135
135
 
136
- modelPicker={<EveModelPicker disabled modelId={modelId} />}
136
+ modelPicker={
137
+ <EveModelPicker
138
+ disabled
139
+ modelId={modelId}
140
+ fallbackModelName={GUEST_POLICY.modelName}
141
+ />
142
+ }
137
143
  status={busy ? "streaming" : "ready"}
138
144
  disabled={busy || expired}
139
145
  draft={draft}
@@ -293,7 +299,13 @@ const GuestWelcomeView = ({
293
299
  )}
294
300
  <EveComposer
295
301
  autoFocus
296
- modelPicker={<EveModelPicker disabled modelId={modelId} />}
302
+ modelPicker={
303
+ <EveModelPicker
304
+ disabled
305
+ modelId={modelId}
306
+ fallbackModelName={GUEST_POLICY.modelName}
307
+ />
308
+ }
297
309
  status={busy ? "submitted" : "ready"}
298
310
  disabled={busy || !modelId}
299
311
  draft={draft}
@@ -21,34 +21,35 @@ const hasNonEmptyValue = (value: string | null | undefined): value is string =>
21
21
  typeof value === "string" && value !== "";
22
22
 
23
23
  const log = createModuleLogger("mcp-oauth-callback");
24
-
25
- const redirectToConnector = (
26
- request: ReadonlyNativeSurface<Pick<NextRequest, "nextUrl">>,
27
- {
28
- connectorId,
29
- connected,
30
- errorMessage,
31
- }: {
32
- readonly connectorId?: string;
33
- readonly connected?: boolean;
34
- readonly errorMessage?: string;
35
- }
36
- ): NextResponse => {
24
+ const TEMPORARY_REDIRECT = 307;
25
+
26
+ const redirectToConnector = ({
27
+ connectorId,
28
+ connected,
29
+ errorMessage,
30
+ }: {
31
+ readonly connectorId?: string;
32
+ readonly connected?: boolean;
33
+ readonly errorMessage?: string;
34
+ }): NextResponse => {
37
35
  const path = hasNonEmptyValue(connectorId)
38
36
  ? `/settings/connectors/${connectorId}`
39
37
  : "/settings/connectors";
40
- const url = new URL(path, request.nextUrl.origin);
38
+ const searchParams = new URLSearchParams();
41
39
  if (connected === true) {
42
- url.searchParams.set("connected", "1");
40
+ searchParams.set("connected", "1");
43
41
  }
44
42
  if (hasNonEmptyValue(errorMessage)) {
45
- url.searchParams.set("error", errorMessage);
43
+ searchParams.set("error", errorMessage);
46
44
  }
47
- return NextResponse.redirect(url);
45
+ // Keep the browser on the callback origin when a proxy supplies a different host to Next.
46
+ return new NextResponse(null, {
47
+ headers: { Location: `${path}?${searchParams}` },
48
+ status: TEMPORARY_REDIRECT,
49
+ });
48
50
  };
49
51
 
50
52
  const oauthFailureResponse = (
51
- request: ReadonlyNativeSurface<Pick<NextRequest, "nextUrl">>,
52
53
  connector: Readonly<
53
54
  Pick<NonNullable<Awaited<ReturnType<typeof getMcpConnectorById>>>, "id">
54
55
  >,
@@ -66,7 +67,7 @@ const oauthFailureResponse = (
66
67
  "OAuth token exchange failed"
67
68
  );
68
69
 
69
- return redirectToConnector(request, {
70
+ return redirectToConnector({
70
71
  connectorId: connector.id,
71
72
  errorMessage:
72
73
  "Could not complete connector authorization. Please try again.",
@@ -92,7 +93,7 @@ export const GET = async (
92
93
  requireMcpCredentials();
93
94
  } catch (setupError) {
94
95
  if (setupError instanceof MissingCredentialsError) {
95
- return redirectToConnector(request, { errorMessage: setupError.message });
96
+ return redirectToConnector({ errorMessage: setupError.message });
96
97
  }
97
98
  throw setupError;
98
99
  }
@@ -109,7 +110,7 @@ export const GET = async (
109
110
  invalidateAllMcpCaches(deleted.mcpConnectorId);
110
111
  }
111
112
  }
112
- return redirectToConnector(request, {
113
+ return redirectToConnector({
113
114
  connectorId: pending?.mcpConnectorId,
114
115
  errorMessage:
115
116
  "Authorization was not completed. Please try connecting again.",
@@ -120,7 +121,7 @@ export const GET = async (
120
121
  { code: Boolean(code), state: Boolean(state) },
121
122
  "Missing code or state"
122
123
  );
123
- return redirectToConnector(request, {
124
+ return redirectToConnector({
124
125
  errorMessage: "Missing authorization code or state parameter",
125
126
  });
126
127
  }
@@ -130,7 +131,7 @@ export const GET = async (
130
131
 
131
132
  if (!session) {
132
133
  log.error({ state }, "Session not found for state");
133
- return redirectToConnector(request, {
134
+ return redirectToConnector({
134
135
  errorMessage: "Invalid or expired session. Please try again.",
135
136
  });
136
137
  }
@@ -139,7 +140,7 @@ export const GET = async (
139
140
  const connector = await getMcpConnectorById({ id: session.mcpConnectorId });
140
141
  if (!connector) {
141
142
  log.error({ connectorId: session.mcpConnectorId }, "Connector not found");
142
- return redirectToConnector(request, {
143
+ return redirectToConnector({
143
144
  errorMessage: "MCP connector not found",
144
145
  });
145
146
  }
@@ -170,11 +171,11 @@ export const GET = async (
170
171
  // cached clients may still keep an authorization URL in memory.
171
172
  await removeMcpClient(connector.id);
172
173
 
173
- return redirectToConnector(request, {
174
+ return redirectToConnector({
174
175
  connected: true,
175
176
  connectorId: connector.id,
176
177
  });
177
178
  } catch (oauthError) {
178
- return oauthFailureResponse(request, connector, oauthError);
179
+ return oauthFailureResponse(connector, oauthError);
179
180
  }
180
181
  };
@@ -36,7 +36,6 @@ export const ModelPreferencesLink = ({
36
36
  return (
37
37
  <div className="border-t p-2">
38
38
  <InternalLink
39
- aria-label="Add Models"
40
39
  href="/settings/models"
41
40
  className={buttonVariants({
42
41
  className: "w-full justify-between",
@@ -44,7 +43,7 @@ export const ModelPreferencesLink = ({
44
43
  variant: "ghost",
45
44
  })}
46
45
  >
47
- Add Models
46
+ Manage models
48
47
  <ChevronRightIcon className="h-4 w-4" />
49
48
  </InternalLink>
50
49
  </div>
@@ -1,4 +1,4 @@
1
- import type { GatewayModelDefaults } from "@chat-js/gateways/defaults";
1
+ import type { GatewayModelDefaults } from "@/chatjs/core/gateway/defaults";
2
2
  import type { Gateway } from "@/chatjs/providers/gateway";
3
3
 
4
4
  const gatewayType = "vercel" satisfies InstanceType<typeof Gateway>["type"];
@@ -3,18 +3,18 @@ import type {
3
3
  LanguageModelV4,
4
4
  } from "@ai-sdk/provider";
5
5
  import {
6
- aiGatewayModelDiscriminatorSchema,
7
6
  aiGatewayModelSchema,
8
- aiGatewayModelsEnvelopeSchema,
9
7
  isAiGatewayModelType,
10
- } from "@chat-js/gateways/models";
11
- import type { AiGatewayModel } from "@chat-js/gateways/models";
12
- import type { GatewayProvider } from "@chat-js/gateways/gateway-provider";
13
- import { GatewayRuntime } from "@chat-js/gateways/runtime";
8
+ } from "@/chatjs/core/gateway/models";
9
+ import type { AiGatewayModel } from "@/chatjs/core/gateway/models";
10
+ import type { GatewayProvider } from "@/chatjs/core/gateway/gateway-provider";
11
+ import { GatewayRuntime } from "@/chatjs/core/gateway/runtime";
14
12
  import type { ImageModel } from "ai";
15
13
 
16
14
  import { createGateway } from "@ai-sdk/gateway";
17
15
  import type { gateway } from "@ai-sdk/gateway";
16
+ import { getVercelOidcToken } from "@vercel/oidc";
17
+ import { z } from "zod";
18
18
 
19
19
  const MODEL_ID_PARAMETER_INDEX = 0;
20
20
  type VercelImageModelId = Parameters<
@@ -25,6 +25,19 @@ type VercelVideoModelId = Parameters<
25
25
  >[typeof MODEL_ID_PARAMETER_INDEX];
26
26
 
27
27
  const EMPTY_MODEL_TYPE_COUNT = 0;
28
+ const modelDiscriminatorSchema = z.object({ type: z.string() });
29
+ const modelsEnvelopeSchema = z.object({
30
+ data: z.array(z.unknown()),
31
+ object: z.literal("list"),
32
+ });
33
+ const modelAvailability = z.object({
34
+ model_eligibility: z
35
+ .object({
36
+ status: z.string(),
37
+ category: z.string().optional(),
38
+ })
39
+ .optional(),
40
+ });
28
41
 
29
42
  class VercelGateway
30
43
  extends GatewayRuntime
@@ -57,33 +70,33 @@ class VercelGateway
57
70
  return this.provider;
58
71
  }
59
72
 
60
- private getApiKey(): string | undefined {
73
+ private async getApiKey(): Promise<string | null> {
61
74
  const apiKey = this.env.AI_GATEWAY_API_KEY;
62
75
 
63
76
  if (typeof apiKey === "string" && apiKey !== "") {
64
77
  return apiKey;
65
78
  }
66
- return this.env.VERCEL_OIDC_TOKEN;
79
+ const oidcToken = this.env.VERCEL_OIDC_TOKEN;
80
+ if (typeof oidcToken === "string" && oidcToken !== "") {
81
+ return oidcToken;
82
+ }
83
+ return await getVercelOidcToken().catch(() => null);
67
84
  }
68
85
 
69
86
  public async fetchModels(): Promise<AiGatewayModel[]> {
70
- const apiKey = this.getApiKey();
71
-
72
- if (!(typeof apiKey === "string" && apiKey !== "")) {
73
- this.log.warn("No AI gateway API key found, using fallback models");
74
- return [...this.getFallbackModels(this.type)];
75
- }
76
-
77
- const url = "https://ai-gateway.vercel.sh/v1/models";
87
+ const apiKey = await this.getApiKey();
88
+ const catalogUrl = "https://ai-gateway.vercel.sh/v1/models";
89
+ const url =
90
+ apiKey === null ? catalogUrl : `${catalogUrl}?include_availability`;
78
91
  this.log.debug({ url }, "Fetching models from Vercel AI Gateway");
79
92
 
80
93
  try {
81
- const response = await this.fetch(url, {
82
- headers: {
83
- Authorization: `Bearer ${apiKey}`,
84
- "Content-Type": "application/json",
85
- },
86
- });
94
+ const response = await this.fetch(
95
+ url,
96
+ apiKey === null
97
+ ? undefined
98
+ : { headers: { Authorization: `Bearer ${apiKey}` } }
99
+ );
87
100
 
88
101
  if (!response.ok) {
89
102
  this.log.error(
@@ -94,15 +107,23 @@ class VercelGateway
94
107
  }
95
108
 
96
109
  const bodyRaw: unknown = await response.json();
97
- const body = aiGatewayModelsEnvelopeSchema.parse(bodyRaw);
110
+ const body = modelsEnvelopeSchema.parse(bodyRaw);
98
111
  const unsupportedTypes = new Set<string>();
99
112
  const models: AiGatewayModel[] = [];
100
113
 
101
114
  for (const candidate of body.data) {
102
- const { type } = aiGatewayModelDiscriminatorSchema.parse(candidate);
115
+ const { type } = modelDiscriminatorSchema.parse(candidate);
103
116
  if (isAiGatewayModelType(type)) {
104
- const model = aiGatewayModelSchema.parse(candidate);
105
- models.push({ ...model, type });
117
+ const availability = modelAvailability.safeParse(candidate);
118
+ const eligibility = availability.data?.model_eligibility;
119
+ if (
120
+ eligibility?.status === "ineligible" &&
121
+ (eligibility.category === "policy" ||
122
+ eligibility.category === "configuration")
123
+ ) {
124
+ continue;
125
+ }
126
+ models.push(aiGatewayModelSchema.parse(candidate));
106
127
  } else {
107
128
  unsupportedTypes.add(type);
108
129
  }