@vite-hub/gateways 0.1.0 → 0.3.1

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.
@@ -1,38 +1,6 @@
1
- import { defineDiagnostics } from "nostics";
2
- //#region src/diagnostics.ts
3
- const dynamicError = { why: ({ message }) => message === void 0 ? "" : String(message) };
4
- const gatewayDiagnostics = /*#__PURE__*/ defineDiagnostics({
5
- docsBase: () => "https://vitehub.dev/docs/agents/ai-gateways#errors",
6
- codes: {
7
- /** An AI gateway definition is invalid. */
8
- GATEWAYS_R0001: dynamicError,
9
- /** A gateway API key is missing or resolves to an empty value. */
10
- GATEWAYS_R0002: dynamicError,
11
- /** A gateway header value is missing, empty, or has a line break. */
12
- GATEWAYS_R0003: dynamicError,
13
- /** A gateway URL, Cloudflare account ID, or AI Gateway ID is missing or invalid. */
14
- GATEWAYS_R0004: dynamicError,
15
- /** `ask()` was called on a gateway that only routes Driver model requests. */
16
- GATEWAYS_R0005: dynamicError,
17
- /** `ask()` needs the optional `advocaat` package. */
18
- GATEWAYS_R0006: dynamicError,
19
- /** A Jev question is not a question that the `ask` builders make, or it is too large. */
20
- GATEWAYS_R0007: dynamicError,
21
- /** The provider rejected the key with 401 or 403. */
22
- GATEWAYS_R0008: {
23
- why: ({ provider, status }) => `[vitehub] The ${provider} Jev provider rejected the API key with HTTP ${status}. The key is missing, expired, or not allowed to call Jev.`,
24
- fix: ({ env }) => env ? `Set or rotate ${env}.` : "Pass a valid apiKey to the gateway, or rotate the key."
25
- },
26
- /** The provider still failed after three attempts. */
27
- GATEWAYS_R0009: {
28
- why: ({ provider, status, attempts }) => `[vitehub] The ${provider} Jev provider failed${status === void 0 ? " to respond" : ` with HTTP ${status}`} after ${attempts} attempts.`,
29
- fix: "This is usually temporary. Retry later. The cause has the provider response."
30
- }
31
- }
32
- });
33
- //#endregion
1
+ import { a as isRecord, l as resolveAiGatewaySecret, n as aiGatewayModelCredentials, o as normalizeAiGateway, r as aiGatewayOptionalCredentials, t as aiGatewayAsks, u as gatewayDiagnostics } from "./definition-BVc8HZWs.js";
34
2
  //#region src/chatgpt.ts
35
- /** Use a ChatGPT Connection with a Codex Driver. Defaults to the `chatgpt` Connection. */
3
+ /** Use a ChatGPT Connection with a Codex Driver or a model-backed Driver. Defaults to the `chatgpt` Connection. */
36
4
  function chatgpt(options = {}) {
37
5
  const connection = options.connection ?? "chatgpt";
38
6
  if (Object.keys(options).some((key) => key !== "connection") || typeof connection !== "string" || !connection.trim() || connection !== connection.trim()) throw gatewayDiagnostics.GATEWAYS_R0001({ message: "[vitehub] chatgpt() accepts only a non-empty Connection name: chatgpt({ connection: \"chatgpt\" })." });
@@ -65,15 +33,19 @@ const aiGatewayEnv = {
65
33
  },
66
34
  cloudflare: {
67
35
  accountId: { names: ["CLOUDFLARE_ACCOUNT_ID"] },
68
- apiKey: {
69
- names: ["TYPESAFE_API_KEY"],
36
+ gatewayId: { names: ["CLOUDFLARE_AI_GATEWAY_ID"] },
37
+ providerApiKey: {
38
+ names: ["CLOUDFLARE_AI_GATEWAY_API_KEY"],
70
39
  secret: true
71
40
  },
72
- gatewayId: { names: ["CLOUDFLARE_AI_GATEWAY_ID"] },
73
41
  slug: { names: ["CLOUDFLARE_AI_GATEWAY_SLUG"] },
74
42
  token: {
75
43
  names: ["CLOUDFLARE_AI_GATEWAY_TOKEN"],
76
44
  secret: true
45
+ },
46
+ typesafeApiKey: {
47
+ names: ["TYPESAFE_API_KEY"],
48
+ secret: true
77
49
  }
78
50
  },
79
51
  cloudflareAccess: {
@@ -313,6 +285,7 @@ async function requestJevWithRetry(advocaat, state, batch, options) {
313
285
  provider,
314
286
  status,
315
287
  env: options.keyEnv,
288
+ option: options.keyOption,
316
289
  cause: error
317
290
  }), {
318
291
  ...details,
@@ -497,13 +470,13 @@ function jevQuestionBatches(state, wire) {
497
470
  const sharedSize = jevInputSize(state) + 2048;
498
471
  const maxRequestSize = 6e4;
499
472
  const maxQuestionSize = 3e4;
500
- if (sharedSize >= maxQuestionSize) throw new RangeError("[vitehub] Jev shared state exceeds the safe per-question input budget.");
473
+ if (sharedSize >= maxQuestionSize) throw gatewayDiagnostics.GATEWAYS_JEV_INPUT_TOO_LARGE({});
501
474
  const batches = [];
502
475
  let batch = Object.create(null);
503
476
  let size = sharedSize;
504
477
  for (const [name, question] of Object.entries(wire)) {
505
478
  const questionSize = jevInputSize({ [name]: question }) + 128;
506
- if (sharedSize + questionSize > maxQuestionSize) throw new RangeError(`[vitehub] Jev question "${name}" exceeds the safe per-question input budget.`);
479
+ if (sharedSize + questionSize > maxQuestionSize) throw gatewayDiagnostics.GATEWAYS_JEV_INPUT_TOO_LARGE({ question: name });
507
480
  if (size + questionSize > maxRequestSize && Object.keys(batch).length) {
508
481
  batches.push(batch);
509
482
  batch = Object.create(null);
@@ -547,10 +520,16 @@ async function askJev(context, state, questions) {
547
520
  if (usage) context.recordUsage?.(usage);
548
521
  context.abortSignal?.throwIfAborted();
549
522
  for (const name of Object.keys(batch)) {
550
- if (!Object.hasOwn(response.answers, name)) throw new Error(`[vitehub] Jev response is missing answer "${name}".`);
523
+ if (!Object.hasOwn(response.answers, name)) throw gatewayDiagnostics.GATEWAYS_JEV_RESPONSE_INVALID({
524
+ name,
525
+ problem: "missing"
526
+ });
551
527
  const answer = response.answers[name];
552
528
  const question = questions[name];
553
- if (question.type === "choice" && !hasValidChoiceAnswer(question, answer)) throw new Error(`[vitehub] Jev choice answer "${name}" is missing a valid probability distribution.`);
529
+ if (question.type === "choice" && !hasValidChoiceAnswer(question, answer)) throw gatewayDiagnostics.GATEWAYS_JEV_RESPONSE_INVALID({
530
+ name,
531
+ problem: "choice"
532
+ });
554
533
  const scoreAnswer = isObject(answer) && answer.type === "score" ? answer : void 0;
555
534
  output[name] = question?.type === "score" && scoreAnswer ? {
556
535
  ...scoreAnswer,
@@ -566,142 +545,6 @@ async function askJev(context, state, questions) {
566
545
  return Object.fromEntries(Object.entries(output));
567
546
  }
568
547
  //#endregion
569
- //#region src/definition.ts
570
- const gatewayKeys = /* @__PURE__ */ new Set([
571
- "apiKey",
572
- "apiKeyEnv",
573
- "auth",
574
- "baseURL",
575
- "headers",
576
- "name"
577
- ]);
578
- const headerName = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
579
- const environmentName = /^[A-Za-z_][A-Za-z0-9_]*$/;
580
- /**
581
- * Marks an AI gateway that answers Jev questions. A symbol key, so key checks and copies skip it. Such a gateway may
582
- * have no Driver base URL.
583
- */
584
- const aiGatewayAsks = Symbol.for("vitehub.aiGateway.ask");
585
- function isRecord(value) {
586
- return typeof value === "object" && value !== null && !Array.isArray(value);
587
- }
588
- function isResolver(value) {
589
- return typeof value === "function" || isRecord(value) && typeof value.resolve === "function";
590
- }
591
- function invalid(message) {
592
- throw gatewayDiagnostics.GATEWAYS_R0001({ message: `[vitehub] ${message}` });
593
- }
594
- function validBaseURL(name, driver, url, fail) {
595
- if (typeof url !== "string" || !URL.canParse(url) || !/^https?:$/.test(new URL(url).protocol)) fail(`Gateway "${name}" baseURL.${driver} must be an http or https URL.`);
596
- return url.replace(/\/+$/, "");
597
- }
598
- function isSecretInput(value) {
599
- return typeof value === "string" || isResolver(value) || isRecord(value) && typeof value.unseal === "function";
600
- }
601
- const missingSecret = () => void 0;
602
- /** Validate a gateway definition and return a frozen copy with its Driver routes. */
603
- function normalizeAiGateway(value) {
604
- if (!isRecord(value)) invalid("A gateway must be an object.");
605
- const unknown = Object.keys(value).filter((key) => !gatewayKeys.has(key));
606
- if (unknown.length) invalid(`A gateway does not support: ${unknown.join(", ")}.`);
607
- if (typeof value.name !== "string" || !value.name.trim()) invalid("A gateway name must be a non-empty string.");
608
- const name = value.name.trim();
609
- if (!isRecord(value.baseURL)) invalid(`Gateway "${name}" baseURL must be an object keyed by Driver.`);
610
- const baseURL = {};
611
- for (const [driver, url] of Object.entries(value.baseURL)) {
612
- if (driver !== "codex" && driver !== "claude-code") invalid(`Gateway "${name}" baseURL has an unknown Driver "${driver}". Use "codex" or "claude-code".`);
613
- if (url === void 0) continue;
614
- if (isResolver(url)) {
615
- baseURL[driver] = url;
616
- continue;
617
- }
618
- baseURL[driver] = validBaseURL(name, driver, url, invalid);
619
- }
620
- if (!Object.keys(baseURL).length && Reflect.get(value, aiGatewayAsks) !== true) invalid(`Gateway "${name}" must set a baseURL for "codex" or "claude-code".`);
621
- if (value.auth !== void 0 && value.auth !== "bearer" && value.auth !== "x-api-key") invalid(`Gateway "${name}" auth must be "bearer" or "x-api-key".`);
622
- if (value.apiKey !== void 0 && !isSecretInput(value.apiKey)) invalid(`Gateway "${name}" apiKey must be a string, sealed secret, or resolver.`);
623
- if (value.apiKeyEnv !== void 0 && (!Array.isArray(value.apiKeyEnv) || !value.apiKeyEnv.every((item) => typeof item === "string" && environmentName.test(item)))) invalid(`Gateway "${name}" apiKeyEnv must be a list of environment variable names.`);
624
- const apiKey = Object.hasOwn(value, "apiKey") && value.apiKey === void 0 ? missingSecret : value.apiKey;
625
- const apiKeyEnv = Array.isArray(value.apiKeyEnv) ? value.apiKeyEnv.filter((item) => typeof item === "string") : void 0;
626
- if (apiKey === void 0 && !apiKeyEnv?.length) invalid(`Gateway "${name}" needs apiKey or apiKeyEnv.`);
627
- let headers;
628
- if (value.headers !== void 0) {
629
- if (!isRecord(value.headers)) invalid(`Gateway "${name}" headers must be an object.`);
630
- headers = {};
631
- for (const [header, item] of Object.entries(value.headers)) {
632
- if (!headerName.test(header)) invalid(`Gateway "${name}" header name "${header}" is not a valid HTTP header name.`);
633
- if (/^(?:authorization|x-api-key)$/i.test(header)) invalid(`Gateway "${name}" sets the API key with apiKey, not with the "${header}" header.`);
634
- if (item === void 0) {
635
- headers[header] = missingSecret;
636
- continue;
637
- }
638
- if (!isSecretInput(item)) invalid(`Gateway "${name}" header "${header}" must be a string, sealed secret, or resolver.`);
639
- headers[header] = item;
640
- }
641
- }
642
- return Object.freeze({
643
- name,
644
- baseURL: Object.freeze(baseURL),
645
- ...apiKey === void 0 ? {} : { apiKey },
646
- ...apiKeyEnv === void 0 ? {} : { apiKeyEnv: Object.freeze(apiKeyEnv) },
647
- ...value.auth === void 0 ? {} : { auth: value.auth },
648
- ...headers === void 0 ? {} : { headers: Object.freeze(headers) }
649
- });
650
- }
651
- /** A value or the result of its resolver. */
652
- async function resolveAiGatewayValue(value, context) {
653
- if (typeof value === "function") return await value(context);
654
- if (isRecord(value) && typeof value.resolve === "function") return await value.resolve(context);
655
- return value;
656
- }
657
- /** A secret as a trimmed string, or undefined when it is missing or empty. */
658
- async function resolveAiGatewaySecret(value, context) {
659
- const resolved = await resolveAiGatewayValue(value, context);
660
- const secret = isRecord(resolved) && typeof resolved.unseal === "function" ? Reflect.apply(resolved.unseal, resolved, []) : resolved;
661
- return typeof secret === "string" && secret.trim() ? secret.trim() : void 0;
662
- }
663
- /** Whether a gateway has a base URL for the Driver. */
664
- function aiGatewaySupports(gateway, driver) {
665
- return Boolean(gateway.baseURL[driver]);
666
- }
667
- async function resolveApiKey(gateway, context) {
668
- if (gateway.apiKey !== void 0) {
669
- const apiKey = await resolveAiGatewaySecret(gateway.apiKey, context);
670
- if (apiKey) return apiKey;
671
- throw gatewayDiagnostics.GATEWAYS_R0002({ message: `[vitehub] Gateway "${gateway.name}" apiKey resolved to an empty value.` });
672
- }
673
- for (const name of gateway.apiKeyEnv || []) {
674
- const value = globalThis.process?.env?.[name]?.trim();
675
- if (value) return value;
676
- }
677
- throw gatewayDiagnostics.GATEWAYS_R0002({ message: `[vitehub] Gateway "${gateway.name}" needs an API key. Set ${(gateway.apiKeyEnv || []).join(" or ")}, or pass apiKey.` });
678
- }
679
- async function resolveHeaders(gateway, context) {
680
- const headers = [];
681
- for (const [name, input] of Object.entries(gateway.headers || {})) {
682
- const value = await resolveAiGatewaySecret(input, context);
683
- if (!value) throw gatewayDiagnostics.GATEWAYS_R0003({ message: `[vitehub] Gateway "${gateway.name}" header "${name}" resolved to an empty value.` });
684
- if (/[\r\n]/.test(value)) throw gatewayDiagnostics.GATEWAYS_R0003({ message: `[vitehub] Gateway "${gateway.name}" header "${name}" must not contain line breaks.` });
685
- headers.push([name, value]);
686
- }
687
- return headers;
688
- }
689
- /** Resolve the base URL, key, and headers of one Driver route. The caller checks `aiGatewaySupports()` first. */
690
- async function resolveAiGatewayDriverRoute(gateway, driver, context) {
691
- const input = gateway.baseURL[driver];
692
- if (input === void 0) throw gatewayDiagnostics.GATEWAYS_R0004({ message: `[vitehub] Gateway "${gateway.name}" does not serve the ${driver} Driver.` });
693
- const baseURL = validBaseURL(gateway.name, driver, await resolveAiGatewayValue(input, context), (message) => {
694
- throw gatewayDiagnostics.GATEWAYS_R0004({ message: `[vitehub] ${message}` });
695
- });
696
- const [apiKey, headers] = await Promise.all([resolveApiKey(gateway, context), resolveHeaders(gateway, context)]);
697
- return {
698
- apiKey,
699
- auth: gateway.auth ?? "bearer",
700
- baseURL,
701
- headers
702
- };
703
- }
704
- //#endregion
705
548
  //#region src/presets.ts
706
549
  function origin(url, label) {
707
550
  if (typeof url !== "string" || !url.trim()) throw gatewayDiagnostics.GATEWAYS_R0001({ message: `[vitehub] ${label}({ url }) must be a non-empty URL.` });
@@ -728,7 +571,8 @@ function hostedBaseURL(gateway, url, fallback) {
728
571
  const root = origin(url ?? fallback, gateway);
729
572
  return {
730
573
  "codex": `${root}/v1`,
731
- "claude-code": root
574
+ "claude-code": root,
575
+ "openai-compatible": `${root}/v1`
732
576
  };
733
577
  }
734
578
  const read = requiredEnv(gateway, "url", (names) => {
@@ -736,7 +580,8 @@ function hostedBaseURL(gateway, url, fallback) {
736
580
  });
737
581
  return {
738
582
  "codex": async (context) => `${origin(await read(context), gateway)}/v1`,
739
- "claude-code": async (context) => origin(await read(context), gateway)
583
+ "claude-code": async (context) => origin(await read(context), gateway),
584
+ "openai-compatible": async (context) => `${origin(await read(context), gateway)}/v1`
740
585
  };
741
586
  }
742
587
  /** The route resolver of an ask gateway. ViteHub Agents call it with their Server Env context. */
@@ -765,6 +610,7 @@ function jevRoute(name, spec) {
765
610
  ...spec.fetch ? { fetch: spec.fetch } : {},
766
611
  ...Object.keys(headers).length ? { headers } : {},
767
612
  ...spec.keyEnv ? { keyEnv: spec.keyEnv } : {},
613
+ ...spec.keyOption ? { keyOption: spec.keyOption } : {},
768
614
  label: spec.label,
769
615
  model: typeof spec.model === "string" ? spec.model : await spec.model(context),
770
616
  name,
@@ -789,12 +635,18 @@ async function askAiGateway(gateway, state, questions, options = {}) {
789
635
  }
790
636
  function unsupportedAsk(name) {
791
637
  return async () => {
792
- throw gatewayDiagnostics.GATEWAYS_R0005({ message: `[vitehub] Gateway "${name}" routes Driver model requests and cannot answer Jev questions. Use typesafe(), vercel(), or cloudflare() for ask().` });
638
+ throw gatewayDiagnostics.GATEWAYS_R0005({ message: `[vitehub] Gateway "${name}" routes model requests and cannot answer Jev questions. Use typesafe(), vercel(), or cloudflare() for ask().` });
793
639
  };
794
640
  }
795
- function createAiGateway(definition, route) {
641
+ function createAiGateway(definition, route, optional, modelApis, modelCredentials) {
796
642
  const routes = normalizeAiGateway(route ? Object.defineProperty({ ...definition }, aiGatewayAsks, { value: true }) : definition);
797
643
  const gateway = { ...routes };
644
+ if (modelApis) Object.defineProperty(gateway, "modelApis", { value: Object.freeze([...modelApis]) });
645
+ if (optional) Object.defineProperty(gateway, aiGatewayOptionalCredentials, { value: Object.freeze({
646
+ ...optional,
647
+ headers: Object.freeze([...optional.headers])
648
+ }) });
649
+ if (modelCredentials) Object.defineProperty(gateway, aiGatewayModelCredentials, { value: modelCredentials });
798
650
  Object.defineProperty(gateway, "ask", { value: route ? (async (state, questions, options = {}) => await askAiGateway(gateway, state, questions, options)) : unsupportedAsk(routes.name) });
799
651
  if (route) Object.defineProperties(gateway, {
800
652
  [aiGatewayAsks]: { value: true },
@@ -813,12 +665,15 @@ function keyEnv(preset, options) {
813
665
  if (options && Object.hasOwn(options, "apiKey")) return void 0;
814
666
  return [...aiGatewayVendorNames(preset, "apiKey"), ...preset === "vercel" ? aiGatewayVendorNames(preset, "oidcToken") : []].join(" or ");
815
667
  }
668
+ function modelGateway(definition, optional) {
669
+ return createAiGateway(definition, void 0, optional);
670
+ }
816
671
  /**
817
- * Validate a custom gateway for an endpoint without a preset. It routes Driver model requests; only the `typesafe()`,
818
- * `vercel()`, and `cloudflare()` presets answer Jev questions.
672
+ * Validate a custom gateway for an endpoint without a preset. Its type lists the model APIs in `baseURL`. It routes
673
+ * model requests; only the `typesafe()`, `vercel()`, and `cloudflare()` presets answer Jev questions.
819
674
  */
820
675
  function defineAiGateway(gateway) {
821
- return createAiGateway(gateway);
676
+ return modelGateway(gateway);
822
677
  }
823
678
  /**
824
679
  * Cloudflare Access service-token headers for a gateway behind Access.
@@ -837,7 +692,7 @@ function cloudflareAccess(options = {}) {
837
692
  }
838
693
  /** [CLIProxyAPI](https://github.com/router-for-me/CLIProxyAPI). Serves Codex and Claude Code. Reads `CLIPROXY_URL` and `CLIPROXY_API_KEY`. */
839
694
  function cliproxy(options = {}) {
840
- return defineAiGateway(preset({
695
+ return modelGateway(preset({
841
696
  name: "cliproxy",
842
697
  baseURL: hostedBaseURL("cliproxy", options.url),
843
698
  apiKey: apiKeyFromEnv("cliproxy")
@@ -845,7 +700,7 @@ function cliproxy(options = {}) {
845
700
  }
846
701
  /** [LiteLLM Proxy](https://docs.litellm.ai/docs/simple_proxy). Serves Codex and Claude Code. Reads `LITELLM_URL` and `LITELLM_API_KEY`. */
847
702
  function litellm(options = {}) {
848
- return defineAiGateway(preset({
703
+ return modelGateway(preset({
849
704
  name: "litellm",
850
705
  baseURL: hostedBaseURL("litellm", options.url),
851
706
  apiKey: apiKeyFromEnv("litellm")
@@ -858,29 +713,32 @@ function ollama(options = {}) {
858
713
  return present(value) ? value : void 0;
859
714
  };
860
715
  const url = read("url");
861
- return defineAiGateway(preset({
716
+ const root = async (context) => origin(await url(context) ?? "http://localhost:11434", "ollama");
717
+ return modelGateway(preset({
862
718
  name: "ollama",
863
719
  baseURL: options.url !== void 0 ? hostedBaseURL("ollama", options.url) : {
864
- "codex": async (context) => `${origin(await url(context) ?? "http://localhost:11434", "ollama")}/v1`,
865
- "claude-code": async (context) => origin(await url(context) ?? "http://localhost:11434", "ollama")
720
+ "codex": async (context) => `${await root(context)}/v1`,
721
+ "claude-code": root,
722
+ "openai-compatible": async (context) => `${await root(context)}/v1`
866
723
  },
867
724
  apiKey: (async (context) => await read("apiKey")(context) ?? "ollama")
868
725
  }, options));
869
726
  }
870
727
  /** [OpenRouter](https://openrouter.ai/docs). Serves Codex and Claude Code. Reads `OPENROUTER_API_KEY`. */
871
728
  function openrouter(options) {
872
- return defineAiGateway(preset({
729
+ return modelGateway(preset({
873
730
  name: "openrouter",
874
731
  baseURL: {
875
732
  "codex": "https://openrouter.ai/api/v1",
876
- "claude-code": "https://openrouter.ai/api"
733
+ "claude-code": "https://openrouter.ai/api",
734
+ "openai-compatible": "https://openrouter.ai/api/v1"
877
735
  },
878
736
  apiKey: apiKeyFromEnv("openrouter")
879
737
  }, options));
880
738
  }
881
739
  /**
882
- * [Vercel AI Gateway](https://vercel.com/docs/ai-gateway). Serves Codex and Claude Code, and answers Jev questions as
883
- * `typesafe-ai/jev`. Reads `AI_GATEWAY_API_KEY`, then `VERCEL_OIDC_TOKEN`.
740
+ * [Vercel AI Gateway](https://vercel.com/docs/ai-gateway). Serves Codex, Claude Code, and AI SDK models, and answers
741
+ * Jev questions as `typesafe-ai/jev`. Reads `AI_GATEWAY_API_KEY`, then `VERCEL_OIDC_TOKEN`.
884
742
  */
885
743
  function vercel(options) {
886
744
  const envSecret = (field) => async (context) => {
@@ -893,10 +751,19 @@ function vercel(options) {
893
751
  name: "vercel",
894
752
  baseURL: {
895
753
  "codex": "https://ai-gateway.vercel.sh/codex/v1",
896
- "claude-code": "https://ai-gateway.vercel.sh/claude-code"
754
+ "claude-code": "https://ai-gateway.vercel.sh/claude-code",
755
+ "openai-compatible": "https://ai-gateway.vercel.sh/v1"
897
756
  },
898
757
  apiKey: async (context) => await resolveAiGatewaySecret(apiKey, context) ?? await resolveAiGatewaySecret(oidcToken, context)
899
758
  }, options);
759
+ const modelCredentials = async (context) => {
760
+ const resolvedKey = await resolveAiGatewaySecret(explicitKey ? definition.apiKey : apiKey, context);
761
+ const token = resolvedKey || explicitKey ? void 0 : await resolveAiGatewaySecret(oidcToken, context);
762
+ return {
763
+ apiKey: resolvedKey ?? token,
764
+ headers: [["ai-gateway-auth-method", token ? "oidc" : "api-key"]]
765
+ };
766
+ };
900
767
  return createAiGateway(definition, jevRoute("vercel", {
901
768
  apiKey: explicitKey ? definition.apiKey : apiKey,
902
769
  baseURL: async () => "https://ai-gateway.vercel.sh/v4/ai",
@@ -907,26 +774,29 @@ function vercel(options) {
907
774
  model: options?.model?.trim() || "typesafe-ai/jev",
908
775
  ...!explicitKey ? { oidcToken } : {},
909
776
  protocol: "vercel"
910
- }));
777
+ }), void 0, void 0, modelCredentials);
911
778
  }
912
- /** The OpenAI API with an API key. Serves Codex. Reads `OPENAI_API_KEY`. */
779
+ /** The OpenAI API with an API key. Serves Codex and AI SDK models. Reads `OPENAI_API_KEY`. */
913
780
  function openai(options) {
914
- return defineAiGateway(preset({
781
+ return modelGateway(preset({
915
782
  name: "openai",
916
- baseURL: { codex: "https://api.openai.com/v1" },
783
+ baseURL: {
784
+ "codex": "https://api.openai.com/v1",
785
+ "openai-compatible": "https://api.openai.com/v1"
786
+ },
917
787
  apiKey: apiKeyFromEnv("openai")
918
788
  }, options));
919
789
  }
920
- /** The Anthropic API with an API key. Serves Claude Code. Reads `ANTHROPIC_API_KEY`. */
790
+ /** The Anthropic API with an API key. Serves Claude Code and AI SDK models. Reads `ANTHROPIC_API_KEY`. */
921
791
  function anthropic(options) {
922
- return defineAiGateway(preset({
792
+ return modelGateway(preset({
923
793
  name: "anthropic",
924
794
  baseURL: { "claude-code": "https://api.anthropic.com" },
925
795
  apiKey: apiKeyFromEnv("anthropic"),
926
796
  auth: "x-api-key"
927
797
  }, options));
928
798
  }
929
- /** [TypeSafe](https://typesafe.ai). Answers Jev questions; it serves no Driver. Reads `TYPESAFE_API_KEY` and `TYPESAFE_DEFAULT_MODEL`. */
799
+ /** [TypeSafe](https://typesafe.ai). Answers Jev questions; it serves no model API. Reads `TYPESAFE_API_KEY` and `TYPESAFE_DEFAULT_MODEL`. */
930
800
  function typesafe(options) {
931
801
  const definition = preset({
932
802
  name: "typesafe",
@@ -947,47 +817,79 @@ function typesafe(options) {
947
817
  protocol: "typesafe"
948
818
  }));
949
819
  }
820
+ function cloudflareRoot(options, preset) {
821
+ const required = async (context, field) => {
822
+ const given = options[field];
823
+ const read = given !== void 0 ? given : await readAiGatewayEnv(context, preset, field);
824
+ const resolved = typeof read === "string" ? read.trim() : "";
825
+ if (resolved) return resolved;
826
+ const label = field === "accountId" ? "an account ID" : "a gateway ID";
827
+ throw gatewayDiagnostics.GATEWAYS_R0004({ message: `[vitehub] Gateway "${preset}" needs ${label}. Set ${aiGatewayVendorNames(preset, field).join(" or ")}, or pass ${field}.` });
828
+ };
829
+ return async (context) => ({
830
+ accountId: await required(context, "accountId"),
831
+ gatewayId: await required(context, "gatewayId")
832
+ });
833
+ }
834
+ /** A token that may be missing, read from `options.token` or Server Env, as a `cf-aig-authorization` value. */
835
+ function cloudflareToken(options, preset) {
836
+ const token = Object.hasOwn(options, "token") ? options.token : async (context) => await readAiGatewayEnv(context, preset, "token");
837
+ return async (context) => {
838
+ const resolved = await resolveAiGatewaySecret(token, context);
839
+ return resolved ? `Bearer ${resolved}` : void 0;
840
+ };
841
+ }
950
842
  /**
951
- * TypeSafe through a [Cloudflare AI Gateway](https://developers.cloudflare.com/ai-gateway/configuration/custom-providers/)
952
- * custom provider whose base URL is `https://api.typesafe.ai`. Answers Jev questions; it serves no Driver. Reads
953
- * `TYPESAFE_API_KEY`, `CLOUDFLARE_ACCOUNT_ID`, `CLOUDFLARE_AI_GATEWAY_ID`, `CLOUDFLARE_AI_GATEWAY_TOKEN`, and
954
- * `CLOUDFLARE_AI_GATEWAY_SLUG`.
843
+ * [Cloudflare AI Gateway](https://developers.cloudflare.com/ai-gateway/). Serves AI SDK models through its
844
+ * [OpenAI-compatible endpoint](https://developers.cloudflare.com/ai-gateway/usage/chat-completion/), with
845
+ * Chat Completions (`api: "chat"`) only, with `{provider}/{model}` model IDs such as `workers-ai/@cf/meta/llama-3.3-70b-instruct-fp8-fast`. Answers Jev questions
846
+ * through a TypeSafe [custom provider](https://developers.cloudflare.com/ai-gateway/configuration/custom-providers/).
847
+ * Each capability reads its own key: model requests need the gateway token, `CLOUDFLARE_AI_GATEWAY_API_KEY`, or both;
848
+ * `ask()` needs `TYPESAFE_API_KEY`. For Codex or Claude Code through Cloudflare, use `defineAiGateway()`.
955
849
  */
956
850
  function cloudflare(options = {}) {
957
- const definition = preset({
851
+ if (Object.hasOwn(options, "apiKey")) throw gatewayDiagnostics.GATEWAYS_R0001({ message: "[vitehub] cloudflare() reads two keys and has no apiKey. Pass typesafeApiKey for ask(), or providerApiKey for model requests." });
852
+ const root = cloudflareRoot(options, "cloudflare");
853
+ const token = cloudflareToken(options, "cloudflare");
854
+ const fromEnv = (field) => {
855
+ return async (context) => await readAiGatewayEnv(context, "cloudflare", field);
856
+ };
857
+ const definition = {
958
858
  name: "cloudflare",
959
- baseURL: {},
960
- apiKey: apiKeyFromEnv("cloudflare")
961
- }, options);
962
- const value = async (context, field, given) => {
963
- if (given !== void 0) return given.trim();
964
- const read = await readAiGatewayEnv(context, "cloudflare", field);
965
- return typeof read === "string" ? read.trim() : "";
859
+ baseURL: { "openai-compatible": async (context) => {
860
+ const { accountId, gatewayId } = await root(context);
861
+ return `https://gateway.ai.cloudflare.com/v1/${encodeURIComponent(accountId)}/${encodeURIComponent(gatewayId)}/compat`;
862
+ } },
863
+ apiKey: Object.hasOwn(options, "providerApiKey") ? options.providerApiKey : fromEnv("providerApiKey"),
864
+ headers: {
865
+ ...options.headers,
866
+ "cf-aig-authorization": token
867
+ }
966
868
  };
967
- const required = async (context, field, given) => {
968
- const resolved = await value(context, field, given);
969
- if (resolved) return resolved;
970
- const label = field === "accountId" ? "an account ID" : "a gateway ID";
971
- throw gatewayDiagnostics.GATEWAYS_R0004({ message: `[vitehub] Gateway "cloudflare" needs ${label}. Set ${aiGatewayVendorNames("cloudflare", field).join(" or ")}, or pass ${field}.` });
869
+ const slug = async (context) => {
870
+ const read = options.slug !== void 0 ? options.slug : await readAiGatewayEnv(context, "cloudflare", "slug");
871
+ return typeof read === "string" ? read.trim() : "";
972
872
  };
973
- const token = Object.hasOwn(options, "token") ? options.token : async (context) => await readAiGatewayEnv(context, "cloudflare", "token");
873
+ const explicitTypesafeKey = Object.hasOwn(options, "typesafeApiKey");
974
874
  return createAiGateway(definition, jevRoute("cloudflare", {
975
- apiKey: definition.apiKey,
875
+ apiKey: explicitTypesafeKey ? options.typesafeApiKey : fromEnv("typesafeApiKey"),
976
876
  baseURL: async (context) => cloudflareJevBaseURL({
977
- accountId: await required(context, "accountId", options.accountId),
978
- gatewayId: await required(context, "gatewayId", options.gatewayId),
979
- slug: await value(context, "slug", options.slug)
877
+ ...await root(context),
878
+ slug: await slug(context)
980
879
  }),
981
880
  ...options.fetch ? { fetch: options.fetch } : {},
982
- optionalHeaders: { "cf-aig-authorization": async (context) => {
983
- const resolved = await resolveAiGatewaySecret(token, context);
984
- return resolved ? `Bearer ${resolved}` : void 0;
985
- } },
986
- ...Object.hasOwn(options, "apiKey") ? {} : { keyEnv: "TYPESAFE_API_KEY or CLOUDFLARE_AI_GATEWAY_TOKEN" },
881
+ ...options.headers ? { headers: options.headers } : {},
882
+ optionalHeaders: { "cf-aig-authorization": token },
883
+ ...explicitTypesafeKey ? {} : { keyEnv: aiGatewayVendorNames("cloudflare", "typesafeApiKey").join(" or ") },
884
+ keyOption: "typesafeApiKey",
987
885
  label: "Cloudflare AI Gateway",
988
886
  model: options.model?.trim() || "jev-latest",
989
887
  protocol: "typesafe"
990
- }));
888
+ }), {
889
+ apiKey: true,
890
+ headers: ["cf-aig-authorization"],
891
+ missing: "Gateway \"cloudflare\" needs a gateway token or a provider key for model requests. Set CLOUDFLARE_AI_GATEWAY_TOKEN for stored provider keys or Unified Billing, or CLOUDFLARE_AI_GATEWAY_API_KEY, or pass token or providerApiKey."
892
+ }, ["chat"]);
991
893
  }
992
894
  //#endregion
993
- export { resolveAiGatewaySecret as _, cloudflareAccess as a, chatgpt as b, ollama as c, typesafe as d, vercel as f, resolveAiGatewayDriverRoute as g, normalizeAiGateway as h, cloudflare as i, openai as l, aiGatewaySupports as m, askAiGateway as n, defineAiGateway as o, aiGatewayAsks as p, cliproxy as r, litellm as s, anthropic as t, openrouter as u, aiGatewayEnv as v, isChatGPTGateway as x, aiGatewayEnvNames as y };
895
+ export { cloudflareAccess as a, ollama as c, typesafe as d, vercel as f, isChatGPTGateway as g, chatgpt as h, cloudflare as i, openai as l, aiGatewayEnvNames as m, askAiGateway as n, defineAiGateway as o, aiGatewayEnv as p, cliproxy as r, litellm as s, anthropic as t, openrouter as u };