@vite-hub/gateways 0.0.0 → 0.3.0

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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,248 @@
1
+ # @vite-hub/gateways
2
+
3
+ An AI gateway is one object that knows where AI requests go and how to sign them. A gateway has three capabilities:
4
+
5
+ - **Driver routes.** It routes Codex and Claude Code model requests, for example through Vercel AI Gateway or CLIProxyAPI.
6
+ - **AI SDK models.** `languageModel(gateway, modelId)` from `@vite-hub/gateways/ai-sdk` returns an [AI SDK](https://ai-sdk.dev) model that sends its requests through the gateway.
7
+ - **`gateway.ask()`.** It answers typed [TypeSafe Jev](https://typesafe.ai) questions, such as "which category fits this transaction". Only gateways that can reach Jev have `ask()`.
8
+
9
+ `ask(prompt, { model, schema })` sends one model request and returns typed data that a schema checked. Without `schema`, it returns the answer text.
10
+
11
+ The package has no Agent, Vite, or Nitro code. It works in a plain Node script, a Worker, or another framework, and its only dependency is `nostics`. ViteHub applications import it as `vite-hub/gateways`. User docs: [AI Gateways](https://vitehub.dev/docs/gateways).
12
+
13
+ ## Install
14
+
15
+ `languageModel()`, `ask()`, and `gateway.ask()` load optional peer dependencies only when you use them. `gateway.ask()` needs `advocaat`, the TypeSafe client. `languageModel()` needs the AI SDK provider package of its model API, usually `@ai-sdk/openai-compatible`, and `ask(prompt, { model, schema })` needs `ai`:
16
+
17
+ ```sh
18
+ pnpm add @vite-hub/gateways advocaat
19
+ pnpm add @vite-hub/gateways ai @ai-sdk/openai-compatible
20
+ ```
21
+
22
+ ## Use a model with the AI SDK
23
+
24
+ ```ts
25
+ import { generateText } from 'ai'
26
+ import { openrouter } from '@vite-hub/gateways'
27
+ import { languageModel } from '@vite-hub/gateways/ai-sdk'
28
+
29
+ // Reads OPENROUTER_API_KEY when it sends the request.
30
+ const model = languageModel(openrouter(), 'google/gemini-3-flash')
31
+
32
+ const { text } = await generateText({ model, prompt: 'What is a Server Primitive?' })
33
+ ```
34
+
35
+ Change the preset to change the provider. The model ID is the ID that the gateway uses. The `api` option selects the model API, and the type accepts only the APIs that the gateway serves:
36
+
37
+ | `api` | Request | URL | Package |
38
+ | --- | --- | --- | --- |
39
+ | `'chat'` | OpenAI Chat Completions | `openai-compatible` | `@ai-sdk/openai-compatible` |
40
+ | `'responses'` | OpenAI Responses | `openai-compatible`, else `codex` | `@ai-sdk/openai` |
41
+ | `'messages'` | Anthropic Messages | `claude-code` | `@ai-sdk/anthropic` |
42
+
43
+ The default is `'chat'` when the gateway has an `openai-compatible` URL, else `'messages'`, else `'responses'`. Use `api: 'responses'` for OpenAI reasoning models that call tools. The gateway resolves its URL, key, and headers for each request from the values that you passed or from `process.env`. Pass `fetch` to use a custom fetch implementation. `providerOptions` for `'chat'` go under the gateway name, such as `{ openrouter: { ... } }`; `'responses'` reads `openai` and `'messages'` reads `anthropic`.
44
+
45
+ ## Get typed data from one call
46
+
47
+ `ask(prompt, { model, schema })` sends one request to an AI SDK model and returns the answer that the schema validated, as `[error, data]`. It needs the `ai` package. Use `languageModel(gateway, modelId)` to send it through any gateway:
48
+
49
+ ```ts
50
+ import { z } from 'zod'
51
+ import { ask, openrouter } from '@vite-hub/gateways'
52
+ import { languageModel } from '@vite-hub/gateways/ai-sdk'
53
+
54
+ const [error, receipt] = await ask('MERCADONA 23.10 -34.90 EUR', {
55
+ model: languageModel(openrouter(), 'google/gemini-3-flash'),
56
+ schema: z.object({ merchant: z.string(), amount: z.number() }),
57
+ })
58
+ if (error) throw error
59
+
60
+ receipt.merchant // string
61
+ ```
62
+
63
+ `schema` is a [Standard Schema](https://standardschema.dev) that converts to JSON Schema: Zod 4, ArkType, or Valibot wrapped with `toStandardJsonSchema()` from `@valibot/to-json-schema`. Leave out `schema` to get the answer as a string: `const [error, summary] = await ask(log, { model })`. Options: `instructions` (system instructions), `signal`, and `onUsage`. `error` is `GATEWAYS_ASK_MODEL_FAILED` when the request fails and `GATEWAYS_ASK_OUTPUT_INVALID` when the answer does not match the schema or has no text. Setup errors, such as a missing key or a schema without JSON Schema, throw. Use an Agent when the model must call tools or keep a conversation.
64
+
65
+ ## Ask your first question
66
+
67
+ ```ts
68
+ import { ask, typesafe } from '@vite-hub/gateways'
69
+
70
+ // Reads TYPESAFE_API_KEY.
71
+ const gateway = typesafe()
72
+
73
+ const answers = await gateway.ask('MERCADONA 23.10 -34.90 EUR', {
74
+ category: ask.choice('Which category fits this bank transaction?', {
75
+ groceries: 'Food and household shopping.',
76
+ eatingOut: 'Restaurants and cafes.',
77
+ }),
78
+ recurring: ask.if('Is it a recurring payment?'),
79
+ })
80
+
81
+ answers.category.choice // 'groceries' | 'eatingOut'
82
+ answers.category.confidence // 0 to 1
83
+ answers.recurring // boolean
84
+ ```
85
+
86
+ The answer types come from the questions:
87
+
88
+ | Builder | Answer |
89
+ | --- | --- |
90
+ | `ask.choice(instructions, criteria)` | `{ choice, confidence, probabilities }`. `criteria` maps labels to descriptions, or is a list of 2 to 255 labels. |
91
+ | `ask.switch(instructions, criteria)` | The selected label only. |
92
+ | `ask.score(instructions, levels)` | `{ score, ratio, confidence, legend, probabilities }` for 2 to 10 ordered levels. |
93
+ | `ask.chance(instructions, criteria?)` | `{ chance }`, the probability of yes. |
94
+ | `ask.if(instructions, { threshold? })` | `true` when the probability of yes is above `threshold`, between `0` and `1`. The default is `0.5`. |
95
+ | `ask.each(items, { key, question })` | One question for each item, under the key that `key(item)` returns. |
96
+
97
+ `gateway.ask(state, questions, { signal, onUsage })` sends the questions in sequential bounded requests. The shared state plus each question must fit below 30,000 bytes. It retries up to two times when the provider answers 408, 429, 500, 502, 503, or 504, or when the network fails. `onUsage` receives the `model`, `provider`, and token `usage` of each request.
98
+
99
+ ### Ask with any model
100
+
101
+ `askWithModel(model)` answers the same questions with any [AI SDK](https://ai-sdk.dev) model, in one structured output request. Use it where a gateway with `ask()` goes. It needs the `ai` package:
102
+
103
+ ```ts [label.ts]
104
+ import { ask, askWithModel } from '@vite-hub/gateways'
105
+ import { openai } from '@ai-sdk/openai'
106
+
107
+ const answers = await askWithModel(openai('gpt-5.1-mini')).ask('MERCADONA 23.10 -34.90 EUR', {
108
+ category: ask.choice('Which category fits this bank transaction?', ['groceries', 'eatingOut']),
109
+ })
110
+ ```
111
+
112
+ A chat model gives one answer and how sure it is. `probabilities` put that number on the answer and share the rest between the other options. Jev gives a real probability for every option, so prefer it when you compare or rank options.
113
+
114
+ ## Presets
115
+
116
+ | Preset | Codex | Claude Code | OpenAI-compatible | `ask()` | Variables |
117
+ | --- | --- | --- | --- | --- | --- |
118
+ | `vercel()` | `https://ai-gateway.vercel.sh/codex/v1` | `https://ai-gateway.vercel.sh/claude-code` | `https://ai-gateway.vercel.sh/v1` | `typesafe-ai/jev` at `https://ai-gateway.vercel.sh/v4/ai` | `AI_GATEWAY_API_KEY`, then `VERCEL_OIDC_TOKEN` |
119
+ | `cloudflare()` | | | `.../<account>/<gateway>/compat` | `jev-latest` through a [custom provider](#typesafe-through-cloudflare-ai-gateway) | `CLOUDFLARE_ACCOUNT_ID`, `CLOUDFLARE_AI_GATEWAY_ID`, `CLOUDFLARE_AI_GATEWAY_TOKEN`, `CLOUDFLARE_AI_GATEWAY_API_KEY`, `TYPESAFE_API_KEY`, `CLOUDFLARE_AI_GATEWAY_SLUG` (see [Cloudflare AI Gateway](#cloudflare-ai-gateway)) |
120
+ | `openrouter()` | `https://openrouter.ai/api/v1` | `https://openrouter.ai/api` | `https://openrouter.ai/api/v1` | | `OPENROUTER_API_KEY` |
121
+ | `litellm()` | `<url>/v1` | `<url>` | `<url>/v1` | | `LITELLM_URL`, `LITELLM_API_KEY` |
122
+ | `cliproxy()` | `<url>/v1` | `<url>` | `<url>/v1` | | `CLIPROXY_URL`, `CLIPROXY_API_KEY` |
123
+ | `ollama()` | `<url>/v1` | `<url>` | `<url>/v1` | | `OLLAMA_URL` (default `http://localhost:11434`), `OLLAMA_API_KEY` (default `ollama`) |
124
+ | `openai()` | `https://api.openai.com/v1` | | `https://api.openai.com/v1` | | `OPENAI_API_KEY` |
125
+ | `chatgpt()` | `https://api.openai.com/v1` through a ChatGPT Connection | | | | None |
126
+ | `anthropic()` | | `https://api.anthropic.com` | | | `ANTHROPIC_API_KEY` |
127
+ | `typesafe()` | | | | `jev-latest` at `https://api.typesafe.ai` | `TYPESAFE_API_KEY`, `TYPESAFE_DEFAULT_MODEL` |
128
+
129
+ The type of a preset lists the model APIs that it serves: `AiGateway<{ routes: "codex" }>` accepts only gateways with a Codex URL, so a ViteHub Codex Driver with `anthropic()` and `languageModel(typesafe(), ...)` are type errors. `vercel()`, `typesafe()`, and `cloudflare()` return `AiGateway<{ ask: true }>`. `chatgpt()` returns a `ChatGPTGateway` descriptor for the Agent runtime. The other presets have no `ask()`, so `ask()` on them is a type error. CLIProxyAPI, LiteLLM, Ollama, OpenRouter, OpenAI, Anthropic, and the Cloudflare OpenAI-compatible endpoint forward model APIs only, not TypeSafe's `/v1/systemone`.
130
+
131
+ `cloudflareAccess()` returns the `CF-Access-Client-Id` and `CF-Access-Client-Secret` headers for a gateway behind Cloudflare Access, from `CF_ACCESS_CLIENT_ID` and `CF_ACCESS_CLIENT_SECRET`. Pass it as `headers`, for example `cliproxy({ headers: cloudflareAccess() })`.
132
+
133
+ `aiGatewayEnv` lists the variables that each preset reads.
134
+
135
+ ## Credentials
136
+
137
+ `chatgpt({ connection?: string })` is a credential-free descriptor for a ViteHub Codex Driver or a model-backed Driver (`driver: { model, gateway: chatgpt() }`). It defaults to the `chatgpt` Connection. The Agent runtime applies the Connection's read policy and resolves a fresh plan token. This descriptor has no `apiKey` callback or `ask()` method. Configure `chatgpt({ appName })` from `@vite-hub/connections/chatgpt` on the Connection and sign in with `vitehub connections connect chatgpt`. See [ChatGPT plan usage](https://vitehub.dev/docs/connections/chatgpt).
138
+
139
+ A preset reads each value that you do not pass when it sends a request. Direct `gateway.ask()` calls, including imports from `vite-hub/gateways`, read `process.env`: `VITEHUB_<PRESET>_<FIELD>` first, such as `VITEHUB_TYPESAFE_API_KEY`, then the vendor variable in the table. Provider Drivers and ask Drivers supply Server Env, with the Cloudflare bindings of the request. `languageModel()` reads `process.env`, also in an AI SDK model Driver. For a direct call with provider-backed Server Env or request bindings, load the values in your application and pass them to the preset.
140
+
141
+ Vercel keeps its credentials in separate Server Env fields: `vercel.apiKey` reads `AI_GATEWAY_API_KEY`, and `vercel.oidcToken` reads `VERCEL_OIDC_TOKEN`. The API key takes precedence; a token uses OIDC authentication even when an Env provider supplies it.
142
+
143
+ A value that you pass replaces its variable. Pass the values when the application stores the credentials, for example one key for each tenant:
144
+
145
+ ```ts fragment
146
+ import { cloudflare, typesafe, vercel } from '@vite-hub/gateways'
147
+
148
+ typesafe({ apiKey: tenant.typesafeKey })
149
+ vercel({ apiKey: tenant.aiGatewayKey })
150
+ cloudflare({ accountId, gatewayId, token: tenant.gatewayToken, typesafeApiKey: tenant.typesafeKey, slug })
151
+ ```
152
+
153
+ An `apiKey` or header value can also be a function that returns the value for each request. `undefined` fails the request; it does not fall back to the variable. `cloudflare()` reads two keys, `typesafeApiKey` for `ask()` and an optional `providerApiKey` for models. `typesafe()`, `vercel()`, and `cloudflare()` also take `model` and `fetch` for `ask()`.
154
+
155
+ ## Cloudflare AI Gateway
156
+
157
+ `cloudflare()` sends AI SDK model requests to the [OpenAI-compatible endpoint](https://developers.cloudflare.com/ai-gateway/usage/chat-completion/) of a Cloudflare AI Gateway: `https://gateway.ai.cloudflare.com/v1/<account>/<gateway>/compat/chat/completions`. This endpoint supports only `api: 'chat'`; `api: 'responses'` is rejected. Model IDs are `{provider}/{model}`, such as `openai/gpt-5` or `workers-ai/@cf/meta/llama-3.3-70b-instruct-fp8-fast`.
158
+
159
+ Each request needs a gateway token, a provider key, or both:
160
+
161
+ | Setup | Variables | Headers |
162
+ | --- | --- | --- |
163
+ | The gateway stores the provider keys, or uses Unified Billing | `CLOUDFLARE_AI_GATEWAY_TOKEN` | `cf-aig-authorization` |
164
+ | Open gateway, provider key in the request | `CLOUDFLARE_AI_GATEWAY_API_KEY` (or `providerApiKey`) | `Authorization` |
165
+ | Authenticated gateway, provider key in the request | Both | Both |
166
+
167
+ `CLOUDFLARE_ACCOUNT_ID` and `CLOUDFLARE_AI_GATEWAY_ID` are always required. A request without a token and without a provider key fails with `GATEWAYS_R0002` before it is sent. The two keys never mix: `ask()` sends only the TypeSafe key, and model requests send only the provider key. `cloudflare({ apiKey })` throws and names both options. `cloudflare()` does not route Drivers: Codex and Claude Code need the vendor endpoints of the gateway, each with that vendor's key. To route a Driver through Cloudflare, define a gateway for it.
168
+
169
+ ### TypeSafe through Cloudflare AI Gateway
170
+
171
+ Cloudflare AI Gateway has no TypeSafe provider. `cloudflare().ask()` reaches TypeSafe through a [custom provider](https://developers.cloudflare.com/ai-gateway/configuration/custom-providers/) that you create once per Cloudflare account. It reads `TYPESAFE_API_KEY`, or `typesafeApiKey` when you pass it. The gateway then logs each request, and its caching and rate limits apply.
172
+
173
+ 1. In the Cloudflare dashboard, go to **Compute & AI** > **AI Gateway** and create a gateway. Its name is the gateway ID.
174
+ 2. Go to **Custom Providers** and select **Add Custom Provider**. Set the slug to `typesafe` and the base URL to `https://api.typesafe.ai`. Or use the Cloudflare API:
175
+
176
+ ```sh
177
+ curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai-gateway/custom-providers \
178
+ -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
179
+ -H "Content-Type: application/json" \
180
+ -d '{"name":"TypeSafe","slug":"typesafe","base_url":"https://api.typesafe.ai","enable":true}'
181
+ ```
182
+
183
+ 3. If the gateway is authenticated, create a gateway token in the gateway settings.
184
+ 4. Set the variables:
185
+
186
+ ```sh
187
+ TYPESAFE_API_KEY=...
188
+ CLOUDFLARE_ACCOUNT_ID=...
189
+ CLOUDFLARE_AI_GATEWAY_ID=...
190
+ # Only for an authenticated gateway.
191
+ CLOUDFLARE_AI_GATEWAY_TOKEN=...
192
+ # Only when the custom provider slug is not typesafe.
193
+ CLOUDFLARE_AI_GATEWAY_SLUG=...
194
+ ```
195
+
196
+ `cloudflare().ask()` sends `POST https://gateway.ai.cloudflare.com/v1/<account>/<gateway>/custom-<slug>/v1/systemone` with the TypeSafe key as `Authorization` and the gateway token as `cf-aig-authorization`. TypeSafe still bills the requests.
197
+
198
+ ## Custom gateways
199
+
200
+ Use `defineAiGateway()` for an endpoint without a preset. It routes model requests and has no `ask()`. Its type lists the keys of `baseURL`:
201
+
202
+ ```ts
203
+ import { defineAiGateway } from '@vite-hub/gateways'
204
+
205
+ // Codex through Cloudflare AI Gateway's OpenAI endpoint.
206
+ export const codexThroughCloudflare = defineAiGateway({
207
+ name: 'cloudflare-openai',
208
+ baseURL: {
209
+ codex: () => `https://gateway.ai.cloudflare.com/v1/${process.env.CLOUDFLARE_ACCOUNT_ID}/${process.env.CLOUDFLARE_AI_GATEWAY_ID}/openai`,
210
+ },
211
+ apiKeyEnv: ['OPENAI_API_KEY'],
212
+ headers: { 'cf-aig-authorization': () => `Bearer ${process.env.CLOUDFLARE_AI_GATEWAY_TOKEN}` },
213
+ })
214
+ ```
215
+
216
+ | Option | Description |
217
+ | --- | --- |
218
+ | `name` | Shown in inspection and diagnostics. |
219
+ | `baseURL` | One URL for each model API: `codex` (OpenAI Responses at `<url>/responses`, for the Codex Driver), `claude-code` (Anthropic Messages at `<url>/v1/messages`, for the Claude Code Driver and `api: 'messages'`), and `openai-compatible` (OpenAI Chat Completions at `<url>/chat/completions` and Responses at `<url>/responses`, for AI SDK models). A function runs for each request. |
220
+ | `apiKey` | A string or a function. |
221
+ | `apiKeyEnv` | Host variables that supply the key, in order. |
222
+ | `auth` | `'bearer'` (default) sends `Authorization: Bearer <key>`. `'x-api-key'` sends `x-api-key: <key>`. |
223
+ | `headers` | Extra headers. Each value is a secret, like `apiKey`. |
224
+
225
+ ## Use with ViteHub Agents
226
+
227
+ In a ViteHub application, set a gateway as `driver.gateway` to route an Agent's model requests, pass `languageModel(gateway, modelId)` from `vite-hub/gateways/ai-sdk` as an AI SDK Driver `model`, or pass a gateway with `ask()` to an ask Driver. ViteHub declares the variables of each preset that a server file imports in Server Env. See [Use with Agents](https://vitehub.dev/docs/gateways/agents) in the ViteHub docs.
228
+
229
+ `@vite-hub/gateways/internal` is for ViteHub packages: model API route resolution and `ask()` with trace observers.
230
+
231
+ ## Errors
232
+
233
+ Every error has a `code`, a `why`, and a `fix`. Errors from `ask()` keep the provider error as `cause`.
234
+
235
+ | Code | When |
236
+ | --- | --- |
237
+ | `GATEWAYS_R0001` | A gateway definition is not valid, such as an unknown option or a URL that is not http or https. It throws when you call the preset. |
238
+ | `GATEWAYS_R0002` | A key is missing or empty. The message names the variable to set, or `apiKey` when you passed it. |
239
+ | `GATEWAYS_R0003` | A header value is missing, empty, or has a line break. |
240
+ | `GATEWAYS_R0004` | A URL, a Cloudflare account ID, or an AI Gateway ID is missing or not valid, or the gateway does not serve the Driver or model API. |
241
+ | `GATEWAYS_R0005` | `ask()` on a gateway that only routes model requests. |
242
+ | `GATEWAYS_R0006` | `ask()` without the `advocaat` package. Install it with `pnpm add advocaat`. |
243
+ | `GATEWAYS_R0007` | A Jev question that the `ask` builders do not make, or a question that is too large. |
244
+ | `GATEWAYS_R0008` | The provider rejected the key with 401 or 403. `status` is 503, and the error has `providerStatus` and `requestId`. The `fix` names the variable to rotate. |
245
+ | `GATEWAYS_R0009` | The provider still failed after three attempts. `status` is 502, and the error has `providerStatus` and `requestId`. |
246
+ | `GATEWAYS_R0010` | `languageModel()` without the AI SDK provider package of its model API. The message names the package to install. |
247
+ | `GATEWAYS_R0011` | `askWithModel()` without the `ai` package. Install it with `pnpm add ai`. |
248
+ | `GATEWAYS_R0012` | The model of `askWithModel()` answered a question with a value that is not one of its options. |
@@ -0,0 +1,36 @@
1
+ import { c as AiGatewayRoute, i as AiGatewayCapabilities, t as AiGateway } from "./types-D0loH5yz.js";
2
+ import { LanguageModelV4 } from "@ai-sdk/provider";
3
+ //#region src/ai-sdk.d.ts
4
+ /**
5
+ * The model APIs that `languageModel()` can call, for the routes of a gateway:
6
+ * - `chat`: OpenAI Chat Completions at the `openai-compatible` URL, with `@ai-sdk/openai-compatible`.
7
+ * - `responses`: OpenAI Responses at the `openai-compatible` URL, else at the `codex` URL, with `@ai-sdk/openai`.
8
+ * - `messages`: Anthropic Messages at the `claude-code` URL, with `@ai-sdk/anthropic`.
9
+ */
10
+ export type AiGatewayModelApi<TRoutes extends AiGatewayRoute = AiGatewayRoute> = ("openai-compatible" extends TRoutes ? "chat" | "responses" : never) | ("codex" extends TRoutes ? "responses" : never) | ("claude-code" extends TRoutes ? "messages" : never);
11
+ export interface AiGatewayLanguageModelOptions<TApi extends AiGatewayModelApi = AiGatewayModelApi> {
12
+ /** The model API to call. Default: `chat` when the gateway has an `openai-compatible` URL, else `messages`, else `responses`. */
13
+ api?: TApi;
14
+ /** Custom fetch implementation for model requests. Default: `globalThis.fetch`. */
15
+ fetch?: typeof globalThis.fetch;
16
+ }
17
+ /** Rejects a gateway that serves no model API, such as `typesafe()`, with a readable type error. */
18
+ type ServesModels<TRoutes extends AiGatewayRoute> = [AiGatewayModelApi<TRoutes>] extends [never] ? {
19
+ readonly "This gateway serves no model API. Use a gateway with an openai-compatible, claude-code, or codex baseURL.": never;
20
+ } : unknown;
21
+ /**
22
+ * An AI SDK language model that sends its requests through the gateway. The gateway resolves its URL, key, and headers
23
+ * for each request, from the values that you passed to the preset or from `process.env`.
24
+ *
25
+ * @example
26
+ * import { generateText } from 'ai'
27
+ * import { openrouter } from '@vite-hub/gateways'
28
+ * import { languageModel } from '@vite-hub/gateways/ai-sdk'
29
+ *
30
+ * await generateText({ model: languageModel(openrouter(), 'google/gemini-3-flash'), prompt: 'Hello' })
31
+ */
32
+ export declare function languageModel<const TRoutes extends AiGatewayRoute, const TApis extends AiGatewayCapabilities["apis"] = AiGatewayCapabilities["apis"]>(gateway: AiGateway<{
33
+ apis: TApis;
34
+ routes: TRoutes;
35
+ }> & ServesModels<TRoutes>, modelId: string, options?: AiGatewayLanguageModelOptions<Extract<AiGatewayModelApi<TRoutes>, NoInfer<TApis>>>): LanguageModelV4;
36
+ //#endregion
package/dist/ai-sdk.js ADDED
@@ -0,0 +1,113 @@
1
+ import { i as aiGatewaySupports, s as resolveAiGatewayModelRoute, u as gatewayDiagnostics } from "./definition-BVc8HZWs.js";
2
+ //#region src/ai-sdk.ts
3
+ const packages = {
4
+ "chat": "@ai-sdk/openai-compatible",
5
+ "messages": "@ai-sdk/anthropic",
6
+ "responses": "@ai-sdk/openai"
7
+ };
8
+ function defaultApi(gateway) {
9
+ if (aiGatewaySupports(gateway, "openai-compatible")) return "chat";
10
+ if (aiGatewaySupports(gateway, "claude-code")) return "messages";
11
+ return "responses";
12
+ }
13
+ function routeOf(gateway, api) {
14
+ if (api === "messages") return "claude-code";
15
+ if (api === "responses" && !aiGatewaySupports(gateway, "openai-compatible")) return "codex";
16
+ return "openai-compatible";
17
+ }
18
+ async function load(api, importer) {
19
+ try {
20
+ return await importer();
21
+ } catch (error) {
22
+ throw gatewayDiagnostics.GATEWAYS_R0010({
23
+ message: `[vitehub] The "${api}" model API needs the ${packages[api]} package. Install it with: pnpm add ${packages[api]}`,
24
+ cause: error
25
+ });
26
+ }
27
+ }
28
+ function headerRecord(route) {
29
+ return Object.fromEntries([...route.headers, ...route.auth === "x-api-key" && route.apiKey ? [["x-api-key", route.apiKey]] : []]);
30
+ }
31
+ async function createModel(name, modelId, api, route, fetch) {
32
+ const shared = {
33
+ headers: headerRecord(route),
34
+ name,
35
+ ...fetch ? { fetch } : {}
36
+ };
37
+ if (api === "chat") {
38
+ const { createOpenAICompatible } = await load(api, async () => await import("@ai-sdk/openai-compatible"));
39
+ return createOpenAICompatible({
40
+ ...shared,
41
+ baseURL: route.baseURL,
42
+ includeUsage: true,
43
+ ...route.apiKey && route.auth === "bearer" ? { apiKey: route.apiKey } : {}
44
+ }).chatModel(modelId);
45
+ }
46
+ const apiKey = route.apiKey;
47
+ if (!apiKey) throw gatewayDiagnostics.GATEWAYS_R0002({ message: `[vitehub] Gateway "${name}" needs an API key for the "${api}" model API. Pass apiKey, or use api: "chat".` });
48
+ if (api === "responses") {
49
+ const { createOpenAI } = await load(api, async () => await import("@ai-sdk/openai"));
50
+ return createOpenAI({
51
+ ...shared,
52
+ apiKey,
53
+ baseURL: route.baseURL,
54
+ fetch: route.auth === "x-api-key" ? async (input, init) => {
55
+ const headers = new Headers(init?.headers);
56
+ headers.delete("authorization");
57
+ headers.set("x-api-key", apiKey);
58
+ return await (fetch ?? globalThis.fetch)(input, {
59
+ ...init,
60
+ headers
61
+ });
62
+ } : fetch
63
+ }).responses(modelId);
64
+ }
65
+ const { createAnthropic } = await load(api, async () => await import("@ai-sdk/anthropic"));
66
+ return createAnthropic({
67
+ ...shared,
68
+ baseURL: `${route.baseURL}/v1`,
69
+ ...route.auth === "x-api-key" ? { apiKey } : { authToken: apiKey }
70
+ }).languageModel(modelId);
71
+ }
72
+ /**
73
+ * An AI SDK language model that sends its requests through the gateway. The gateway resolves its URL, key, and headers
74
+ * for each request, from the values that you passed to the preset or from `process.env`.
75
+ *
76
+ * @example
77
+ * import { generateText } from 'ai'
78
+ * import { openrouter } from '@vite-hub/gateways'
79
+ * import { languageModel } from '@vite-hub/gateways/ai-sdk'
80
+ *
81
+ * await generateText({ model: languageModel(openrouter(), 'google/gemini-3-flash'), prompt: 'Hello' })
82
+ */
83
+ function languageModel(gateway, modelId, options = {}) {
84
+ if (typeof gateway !== "object" || gateway === null || typeof gateway.baseURL !== "object" || gateway.baseURL === null) throw gatewayDiagnostics.GATEWAYS_R0001({ message: "[vitehub] languageModel(gateway, modelId) needs a gateway from a preset or defineAiGateway(). For chatgpt(), set driver: { model, gateway: chatgpt() } on an Agent." });
85
+ if (typeof modelId !== "string" || !modelId.trim()) throw gatewayDiagnostics.GATEWAYS_R0001({ message: "[vitehub] languageModel(gateway, modelId) needs a non-empty model ID." });
86
+ const api = options.api ?? defaultApi(gateway);
87
+ if (!packages[api]) throw gatewayDiagnostics.GATEWAYS_R0001({ message: `[vitehub] languageModel() api must be "chat", "responses", or "messages".` });
88
+ const route = routeOf(gateway, api);
89
+ if (gateway.modelApis && !gateway.modelApis.some((supported) => supported === api)) throw gatewayDiagnostics.GATEWAYS_R0004({ message: `[vitehub] Gateway "${gateway.name}" does not serve the "${api}" model API. Choose api: ${gateway.modelApis.map((supported) => `"${supported}"`).join(" or ")}.` });
90
+ if (!aiGatewaySupports(gateway, route)) throw gatewayDiagnostics.GATEWAYS_R0004({ message: `[vitehub] Gateway "${gateway.name}" does not serve the "${api}" model API. Set baseURL["${route}"] or choose another api.` });
91
+ const id = modelId.trim();
92
+ const model = async (abortSignal) => {
93
+ const resolved = await resolveAiGatewayModelRoute(gateway, route, abortSignal ? { abortSignal } : {});
94
+ return await createModel(gateway.name, id, api, resolved, options.fetch);
95
+ };
96
+ return {
97
+ specificationVersion: "v4",
98
+ provider: `${gateway.name}.${api}`,
99
+ modelId: id,
100
+ get supportedUrls() {
101
+ return createModel(gateway.name, id, api, {
102
+ apiKey: "unused",
103
+ auth: "bearer",
104
+ baseURL: "https://gateway.invalid",
105
+ headers: []
106
+ }).then((resolved) => resolved.supportedUrls);
107
+ },
108
+ doGenerate: async (callOptions) => await (await model(callOptions.abortSignal)).doGenerate(callOptions),
109
+ doStream: async (callOptions) => await (await model(callOptions.abortSignal)).doStream(callOptions)
110
+ };
111
+ }
112
+ //#endregion
113
+ export { languageModel };