@vite-hub/gateways 0.0.0-stage → 0.1.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 +201 -0
- package/README.md +170 -2
- package/dist/index.d.ts +2 -0
- package/dist/index.js +79 -0
- package/dist/internal.d.ts +24 -0
- package/dist/internal.js +2 -0
- package/dist/presets-B2Xutktt.js +993 -0
- package/dist/presets-CY0KQOx8.d.ts +378 -0
- package/package.json +72 -3
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
CHANGED
|
@@ -1,3 +1,171 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @vite-hub/gateways
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
An AI gateway is one object that knows where AI requests go and how to sign them. A gateway has two capabilities:
|
|
4
|
+
|
|
5
|
+
- **Driver routes.** It routes Codex and Claude Code model requests, for example through Vercel AI Gateway or CLIProxyAPI.
|
|
6
|
+
- **`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()`.
|
|
7
|
+
|
|
8
|
+
The package has no Agent, Vite, or Nitro code. It works in a plain Node script or a Worker, and its only dependency is `nostics`. ViteHub applications import it as `vite-hub/gateways`.
|
|
9
|
+
|
|
10
|
+
## Install
|
|
11
|
+
|
|
12
|
+
`ask()` also needs `advocaat`, the TypeSafe client. It is an optional peer dependency, and only `ask()` loads it:
|
|
13
|
+
|
|
14
|
+
```sh
|
|
15
|
+
pnpm add @vite-hub/gateways advocaat
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
## Ask your first question
|
|
19
|
+
|
|
20
|
+
```ts
|
|
21
|
+
import { ask, typesafe } from '@vite-hub/gateways'
|
|
22
|
+
|
|
23
|
+
// Reads TYPESAFE_API_KEY.
|
|
24
|
+
const gateway = typesafe()
|
|
25
|
+
|
|
26
|
+
const answers = await gateway.ask('MERCADONA 23.10 -34.90 EUR', {
|
|
27
|
+
category: ask.choice('Which category fits this bank transaction?', {
|
|
28
|
+
groceries: 'Food and household shopping.',
|
|
29
|
+
eatingOut: 'Restaurants and cafes.',
|
|
30
|
+
}),
|
|
31
|
+
recurring: ask.if('Is it a recurring payment?'),
|
|
32
|
+
})
|
|
33
|
+
|
|
34
|
+
answers.category.choice // 'groceries' | 'eatingOut'
|
|
35
|
+
answers.category.confidence // 0 to 1
|
|
36
|
+
answers.recurring // boolean
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
The answer types come from the questions:
|
|
40
|
+
|
|
41
|
+
| Builder | Answer |
|
|
42
|
+
| --- | --- |
|
|
43
|
+
| `ask.choice(instructions, criteria)` | `{ choice, confidence, probabilities }`. `criteria` maps labels to descriptions, or is a list of 2 to 255 labels. |
|
|
44
|
+
| `ask.switch(instructions, criteria)` | The selected label only. |
|
|
45
|
+
| `ask.score(instructions, levels)` | `{ score, ratio, confidence, legend, probabilities }` for 2 to 10 ordered levels. |
|
|
46
|
+
| `ask.chance(instructions, criteria?)` | `{ chance }`, the probability of yes. |
|
|
47
|
+
| `ask.if(instructions, { threshold? })` | `true` when the probability of yes is above `threshold`, between `0` and `1`. The default is `0.5`. |
|
|
48
|
+
| `ask.each(items, { key, question })` | One question for each item, under the key that `key(item)` returns. |
|
|
49
|
+
|
|
50
|
+
`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.
|
|
51
|
+
|
|
52
|
+
## Presets
|
|
53
|
+
|
|
54
|
+
| Preset | Codex | Claude Code | `ask()` | Variables |
|
|
55
|
+
| --- | --- | --- | --- | --- |
|
|
56
|
+
| `typesafe()` | | | `jev-latest` at `https://api.typesafe.ai` | `TYPESAFE_API_KEY`, `TYPESAFE_DEFAULT_MODEL` |
|
|
57
|
+
| `vercel()` | `https://ai-gateway.vercel.sh/codex/v1` | `https://ai-gateway.vercel.sh/claude-code` | `typesafe-ai/jev` at `https://ai-gateway.vercel.sh/v4/ai` | `AI_GATEWAY_API_KEY`, then `VERCEL_OIDC_TOKEN` |
|
|
58
|
+
| `cloudflare()` | | | `jev-latest` through a [custom provider](#cloudflare-ai-gateway) | `TYPESAFE_API_KEY`, `CLOUDFLARE_ACCOUNT_ID`, `CLOUDFLARE_AI_GATEWAY_ID`, `CLOUDFLARE_AI_GATEWAY_TOKEN` (optional), `CLOUDFLARE_AI_GATEWAY_SLUG` (default `typesafe`) |
|
|
59
|
+
| `cliproxy()` | `<url>/v1` | `<url>` | | `CLIPROXY_URL`, `CLIPROXY_API_KEY` |
|
|
60
|
+
| `litellm()` | `<url>/v1` | `<url>` | | `LITELLM_URL`, `LITELLM_API_KEY` |
|
|
61
|
+
| `ollama()` | `<url>/v1` | `<url>` | | `OLLAMA_URL` (default `http://localhost:11434`), `OLLAMA_API_KEY` (default `ollama`) |
|
|
62
|
+
| `openrouter()` | `https://openrouter.ai/api/v1` | `https://openrouter.ai/api` | | `OPENROUTER_API_KEY` |
|
|
63
|
+
| `openai()` | `https://api.openai.com/v1` | | | `OPENAI_API_KEY` |
|
|
64
|
+
| `chatgpt()` | `https://api.openai.com/v1` through a ChatGPT Connection | | | None |
|
|
65
|
+
| `anthropic()` | | `https://api.anthropic.com` | | `ANTHROPIC_API_KEY` |
|
|
66
|
+
|
|
67
|
+
`typesafe()`, `vercel()`, and `cloudflare()` return `AiGateway<{ ask: true }>`. `chatgpt()` returns a `ChatGPTGateway` descriptor for the Agent runtime. The remaining presets return `AiGateway<{ ask: false }>`, so `ask()` on them is a type error. CLIProxyAPI, LiteLLM, Ollama, OpenRouter, OpenAI, and Anthropic forward model APIs only, not TypeSafe's `/v1/systemone`.
|
|
68
|
+
|
|
69
|
+
`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() })`.
|
|
70
|
+
|
|
71
|
+
`aiGatewayEnv` lists the variables that each preset reads.
|
|
72
|
+
|
|
73
|
+
## Credentials
|
|
74
|
+
|
|
75
|
+
`chatgpt({ connection?: string })` is a credential-free descriptor for a ViteHub Codex Driver. 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).
|
|
76
|
+
|
|
77
|
+
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. Agent Drivers, `llmGate()`, and `llmRoute()` supply Server Env, with the Cloudflare bindings of the request. For a direct call with provider-backed Server Env or request bindings, load the values in your application and pass them to the preset.
|
|
78
|
+
|
|
79
|
+
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.
|
|
80
|
+
|
|
81
|
+
A value that you pass replaces its variable. Pass the values when the application stores the credentials, for example one key for each tenant:
|
|
82
|
+
|
|
83
|
+
```ts
|
|
84
|
+
import { cloudflare, typesafe, vercel } from '@vite-hub/gateways'
|
|
85
|
+
|
|
86
|
+
typesafe({ apiKey: tenant.typesafeKey })
|
|
87
|
+
vercel({ apiKey: tenant.aiGatewayKey })
|
|
88
|
+
cloudflare({ apiKey: tenant.typesafeKey, accountId, gatewayId, token, slug })
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
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. `typesafe()`, `vercel()`, and `cloudflare()` also take `model` and `fetch`, a custom fetch implementation.
|
|
92
|
+
|
|
93
|
+
## Cloudflare AI Gateway
|
|
94
|
+
|
|
95
|
+
Cloudflare AI Gateway has no TypeSafe provider. `cloudflare()` reaches TypeSafe through a [custom provider](https://developers.cloudflare.com/ai-gateway/configuration/custom-providers/) that you create once per Cloudflare account. The gateway then logs each request, and its caching and rate limits apply.
|
|
96
|
+
|
|
97
|
+
1. In the Cloudflare dashboard, go to **Compute & AI** > **AI Gateway** and create a gateway. Its name is the gateway ID.
|
|
98
|
+
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:
|
|
99
|
+
|
|
100
|
+
```sh
|
|
101
|
+
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai-gateway/custom-providers \
|
|
102
|
+
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
|
|
103
|
+
-H "Content-Type: application/json" \
|
|
104
|
+
-d '{"name":"TypeSafe","slug":"typesafe","base_url":"https://api.typesafe.ai","enable":true}'
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
3. If the gateway is authenticated, create a gateway token in the gateway settings.
|
|
108
|
+
4. Set the variables:
|
|
109
|
+
|
|
110
|
+
```sh
|
|
111
|
+
TYPESAFE_API_KEY=...
|
|
112
|
+
CLOUDFLARE_ACCOUNT_ID=...
|
|
113
|
+
CLOUDFLARE_AI_GATEWAY_ID=...
|
|
114
|
+
# Only for an authenticated gateway.
|
|
115
|
+
CLOUDFLARE_AI_GATEWAY_TOKEN=...
|
|
116
|
+
# Only when the custom provider slug is not typesafe.
|
|
117
|
+
CLOUDFLARE_AI_GATEWAY_SLUG=...
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
`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.
|
|
121
|
+
|
|
122
|
+
`cloudflare()` does not route Drivers: Cloudflare's OpenAI and Anthropic endpoints each take that vendor's key. To route a Driver through Cloudflare, define a gateway for it.
|
|
123
|
+
|
|
124
|
+
## Custom gateways
|
|
125
|
+
|
|
126
|
+
Use `defineAiGateway()` for an endpoint without a preset. It routes Driver model requests and has no `ask()`:
|
|
127
|
+
|
|
128
|
+
```ts
|
|
129
|
+
import { defineAiGateway } from '@vite-hub/gateways'
|
|
130
|
+
|
|
131
|
+
// Codex through Cloudflare AI Gateway's OpenAI endpoint.
|
|
132
|
+
export const codexThroughCloudflare = defineAiGateway({
|
|
133
|
+
name: 'cloudflare-openai',
|
|
134
|
+
baseURL: {
|
|
135
|
+
codex: () => `https://gateway.ai.cloudflare.com/v1/${process.env.CLOUDFLARE_ACCOUNT_ID}/${process.env.CLOUDFLARE_AI_GATEWAY_ID}/openai`,
|
|
136
|
+
},
|
|
137
|
+
apiKeyEnv: ['OPENAI_API_KEY'],
|
|
138
|
+
headers: { 'cf-aig-authorization': () => `Bearer ${process.env.CLOUDFLARE_AI_GATEWAY_TOKEN}` },
|
|
139
|
+
})
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
| Option | Description |
|
|
143
|
+
| --- | --- |
|
|
144
|
+
| `name` | Shown in inspection and diagnostics. |
|
|
145
|
+
| `baseURL` | One URL for each Driver: `codex` (OpenAI Responses at `<url>/responses`) and `claude-code` (Anthropic Messages at `<url>/v1/messages`). A function runs for each request. |
|
|
146
|
+
| `apiKey` | A string or a function. |
|
|
147
|
+
| `apiKeyEnv` | Host variables that supply the key, in order. |
|
|
148
|
+
| `auth` | `'bearer'` (default) sends `Authorization: Bearer <key>`. `'x-api-key'` sends `x-api-key: <key>`. |
|
|
149
|
+
| `headers` | Extra headers. Each value is a secret, like `apiKey`. |
|
|
150
|
+
|
|
151
|
+
## Use with ViteHub Agents
|
|
152
|
+
|
|
153
|
+
In a ViteHub application, set a gateway as `driver.gateway` to route an Agent's model requests, or pass a gateway with `ask()` to an ask Driver, `llmGate()`, or `llmRoute()`. ViteHub then declares the preset's variables in Server Env. See [AI gateways](https://vitehub.dev/docs/agents/ai-gateways#use-with-agents) in the ViteHub docs.
|
|
154
|
+
|
|
155
|
+
`@vite-hub/gateways/internal` is for ViteHub packages: Driver route resolution and `ask()` with trace observers.
|
|
156
|
+
|
|
157
|
+
## Errors
|
|
158
|
+
|
|
159
|
+
Every error has a `code`, a `why`, and a `fix`. Errors from `ask()` keep the provider error as `cause`.
|
|
160
|
+
|
|
161
|
+
| Code | When |
|
|
162
|
+
| --- | --- |
|
|
163
|
+
| `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. |
|
|
164
|
+
| `GATEWAYS_R0002` | A key is missing or empty. The message names the variable to set, or `apiKey` when you passed it. |
|
|
165
|
+
| `GATEWAYS_R0003` | A header value is missing, empty, or has a line break. |
|
|
166
|
+
| `GATEWAYS_R0004` | A URL, a Cloudflare account ID, or an AI Gateway ID is missing or not valid. |
|
|
167
|
+
| `GATEWAYS_R0005` | `ask()` on a gateway that only routes Driver model requests. |
|
|
168
|
+
| `GATEWAYS_R0006` | `ask()` without the `advocaat` package. Install it with `pnpm add advocaat`. |
|
|
169
|
+
| `GATEWAYS_R0007` | A Jev question that the `ask` builders do not make, or a question that is too large. |
|
|
170
|
+
| `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. |
|
|
171
|
+
| `GATEWAYS_R0009` | The provider still failed after three attempts. `status` is 502, and the error has `providerStatus` and `requestId`. |
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { $ as AskScoreCriteria, A as AiGatewayContext, B as AskChanceAnswer, D as AiGatewayAsk, E as AiGateway, F as AiGatewayUsage, G as AskChoiceLabels, H as AskChanceQuestion, I as AiGatewayValue, J as AskIfQuestion, K as AskChoiceQuestion, L as AskAnswer, M as AiGatewayDriver, N as AiGatewaySealedSecret, O as AiGatewayAskOptions, P as AiGatewaySecret, Q as AskScoreAnswer, R as AskAnswerType, U as AskChoiceAnswer, V as AskChanceCriteria, W as AskChoiceCriteria, X as AskQuestion, Y as AskJson, Z as AskQuestions, _ as openrouter, a as CloudflareGatewayOptions, c as anthropic, d as cloudflare, et as AskScoreQuestion, f as cloudflareAccess, g as openai, h as ollama, i as CloudflareAccessOptions, it as chatgpt, j as AiGatewayDefinition, k as AiGatewayCapabilities, m as litellm, n as AiGatewayPresetOptions, nt as ask, o as TypesafeGatewayOptions, p as defineAiGateway, q as AskEntry, r as AiHostedGatewayOptions, rt as ChatGPTGateway, s as VercelGatewayOptions, t as AiAskGatewayOptions, tt as AskSwitchQuestion, u as cliproxy, v as typesafe, w as aiGatewayEnv, x as AiGatewayEnvField, y as vercel, z as AskAnswers } from "./presets-CY0KQOx8.js";
|
|
2
|
+
export { type AiAskGatewayOptions, type AiGateway, type AiGatewayAsk, type AiGatewayAskOptions, type AiGatewayCapabilities, type AiGatewayContext, type AiGatewayDefinition, type AiGatewayDriver, type AiGatewayEnvField, type AiGatewayPresetOptions, type AiGatewaySealedSecret, type AiGatewaySecret, type AiGatewayUsage, type AiGatewayValue, type AiHostedGatewayOptions, type AskAnswer, type AskAnswerType, type AskAnswers, type AskChanceAnswer, type AskChanceCriteria, type AskChanceQuestion, type AskChoiceAnswer, type AskChoiceCriteria, type AskChoiceLabels, type AskChoiceQuestion, type AskEntry, type AskIfQuestion, type AskJson, type AskQuestion, type AskQuestions, type AskScoreAnswer, type AskScoreCriteria, type AskScoreQuestion, type AskSwitchQuestion, type ChatGPTGateway, type CloudflareAccessOptions, type CloudflareGatewayOptions, type TypesafeGatewayOptions, type VercelGatewayOptions, aiGatewayEnv, anthropic, ask, chatgpt, cliproxy, cloudflare, cloudflareAccess, defineAiGateway, litellm, ollama, openai, openrouter, typesafe, vercel };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { a as cloudflareAccess, b as chatgpt, c as ollama, d as typesafe, f as vercel, i as cloudflare, l as openai, o as defineAiGateway, r as cliproxy, s as litellm, t as anthropic, u as openrouter, v as aiGatewayEnv } from "./presets-B2Xutktt.js";
|
|
2
|
+
//#region src/ask.ts
|
|
3
|
+
function isLabels(criteria) {
|
|
4
|
+
return Array.isArray(criteria);
|
|
5
|
+
}
|
|
6
|
+
function named(criteria) {
|
|
7
|
+
return isLabels(criteria) ? Object.fromEntries(criteria.map((label) => [label, null])) : criteria;
|
|
8
|
+
}
|
|
9
|
+
function choice(instructions, criteria) {
|
|
10
|
+
return {
|
|
11
|
+
criteria: named(criteria),
|
|
12
|
+
instructions,
|
|
13
|
+
type: "choice"
|
|
14
|
+
};
|
|
15
|
+
}
|
|
16
|
+
function askSwitch(instructions, criteria) {
|
|
17
|
+
return {
|
|
18
|
+
criteria: named(criteria),
|
|
19
|
+
instructions,
|
|
20
|
+
type: "switch"
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
function score(instructions, criteria) {
|
|
24
|
+
return {
|
|
25
|
+
criteria,
|
|
26
|
+
instructions,
|
|
27
|
+
type: "score"
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
function chance(instructions, criteria) {
|
|
31
|
+
return criteria === void 0 ? {
|
|
32
|
+
instructions,
|
|
33
|
+
type: "chance"
|
|
34
|
+
} : {
|
|
35
|
+
criteria,
|
|
36
|
+
instructions,
|
|
37
|
+
type: "chance"
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
function askIf(instructions, options = {}) {
|
|
41
|
+
const threshold = options.threshold ?? .5;
|
|
42
|
+
if (!Number.isFinite(threshold)) throw new TypeError("ask.if threshold must be a finite number");
|
|
43
|
+
if (threshold < 0 || threshold > 1) throw new TypeError("ask.if threshold must be between 0 and 1");
|
|
44
|
+
return {
|
|
45
|
+
instructions,
|
|
46
|
+
threshold,
|
|
47
|
+
type: "if"
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
function each(items, options) {
|
|
51
|
+
const questions = Object.create(null);
|
|
52
|
+
for (const item of items) {
|
|
53
|
+
const key = options.key(item);
|
|
54
|
+
if (typeof key !== "string" || !key.trim()) throw new TypeError("ask.each keys must be non-empty strings");
|
|
55
|
+
if (Object.hasOwn(questions, key)) throw new TypeError(`ask.each produced duplicate key ${JSON.stringify(key)}`);
|
|
56
|
+
questions[key] = options.question(item);
|
|
57
|
+
}
|
|
58
|
+
return questions;
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Builds TypeSafe Jev questions for `gateway.ask()` and `defineAgent({ driver: { ask } })`.
|
|
62
|
+
* Each builder returns a plain question object. The Driver sends questions in deterministic sequential batches when needed; the combined serialized shared state and each question must fit below 30,000 bytes, including request overhead.
|
|
63
|
+
*/
|
|
64
|
+
const ask = {
|
|
65
|
+
/** A yes or no question. Answers `{ chance }`, the probability of yes. */
|
|
66
|
+
chance,
|
|
67
|
+
/** Selects one option. Answers `{ choice, confidence, probabilities }`. */
|
|
68
|
+
choice,
|
|
69
|
+
/** Builds a keyed question map from a list. */
|
|
70
|
+
each,
|
|
71
|
+
/** A yes or no question. Answers `true` when the probability of yes is above `threshold` (0 to 1, default `0.5`). */
|
|
72
|
+
if: askIf,
|
|
73
|
+
/** Rates the state against 2 to 10 ordered levels. Answers `{ score, ratio, confidence, legend, probabilities }`. */
|
|
74
|
+
score,
|
|
75
|
+
/** Selects one option. Answers with the selected label only. */
|
|
76
|
+
switch: askSwitch
|
|
77
|
+
};
|
|
78
|
+
//#endregion
|
|
79
|
+
export { aiGatewayEnv, anthropic, ask, chatgpt, cliproxy, cloudflare, cloudflareAccess, defineAiGateway, litellm, ollama, openai, openrouter, typesafe, vercel };
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { A as AiGatewayContext, C as AiGatewayEnvPreset, M as AiGatewayDriver, P as AiGatewaySecret, S as AiGatewayEnvFieldName, T as aiGatewayEnvNames, at as isChatGPTGateway, b as AiGatewayTraceEvent, j as AiGatewayDefinition, l as askAiGateway } from "./presets-CY0KQOx8.js";
|
|
2
|
+
//#region src/definition.d.ts
|
|
3
|
+
/**
|
|
4
|
+
* Marks an AI gateway that answers Jev questions. A symbol key, so key checks and copies skip it. Such a gateway may
|
|
5
|
+
* have no Driver base URL.
|
|
6
|
+
*/
|
|
7
|
+
export declare const aiGatewayAsks: unique symbol;
|
|
8
|
+
/** Validate a gateway definition and return a frozen copy with its Driver routes. */
|
|
9
|
+
export declare function normalizeAiGateway(value: unknown): AiGatewayDefinition;
|
|
10
|
+
/** A secret as a trimmed string, or undefined when it is missing or empty. */
|
|
11
|
+
export declare function resolveAiGatewaySecret(value: AiGatewaySecret, context: AiGatewayContext): Promise<string | undefined>;
|
|
12
|
+
/** One Driver route of a gateway, with its key and headers resolved. */
|
|
13
|
+
interface AiGatewayDriverRoute {
|
|
14
|
+
apiKey: string;
|
|
15
|
+
auth: "bearer" | "x-api-key";
|
|
16
|
+
baseURL: string;
|
|
17
|
+
headers: [string, string][];
|
|
18
|
+
}
|
|
19
|
+
/** Whether a gateway has a base URL for the Driver. */
|
|
20
|
+
export declare function aiGatewaySupports(gateway: AiGatewayDefinition, driver: AiGatewayDriver): boolean;
|
|
21
|
+
/** Resolve the base URL, key, and headers of one Driver route. The caller checks `aiGatewaySupports()` first. */
|
|
22
|
+
export declare function resolveAiGatewayDriverRoute(gateway: AiGatewayDefinition, driver: AiGatewayDriver, context: AiGatewayContext): Promise<AiGatewayDriverRoute>;
|
|
23
|
+
//#endregion
|
|
24
|
+
export { type AiGatewayDriverRoute, type AiGatewayEnvFieldName, type AiGatewayEnvPreset, type AiGatewayTraceEvent, aiGatewayEnvNames, askAiGateway, isChatGPTGateway };
|
package/dist/internal.js
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { _ as resolveAiGatewaySecret, g as resolveAiGatewayDriverRoute, h as normalizeAiGateway, m as aiGatewaySupports, n as askAiGateway, p as aiGatewayAsks, x as isChatGPTGateway, y as aiGatewayEnvNames } from "./presets-B2Xutktt.js";
|
|
2
|
+
export { aiGatewayAsks, aiGatewayEnvNames, aiGatewaySupports, askAiGateway, isChatGPTGateway, normalizeAiGateway, resolveAiGatewayDriverRoute, resolveAiGatewaySecret };
|