@vite-hub/gateways 0.1.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.
@@ -1,378 +0,0 @@
1
- //#region src/chatgpt.d.ts
2
- /** A runtime-owned ChatGPT plan route. It contains no credentials. */
3
- interface ChatGPTGateway {
4
- readonly kind: "chatgpt";
5
- readonly name: "chatgpt";
6
- readonly connection: string;
7
- }
8
- /** Use a ChatGPT Connection with a Codex Driver. Defaults to the `chatgpt` Connection. */
9
- declare function chatgpt(options?: {
10
- connection?: string;
11
- }): ChatGPTGateway;
12
- declare function isChatGPTGateway(value: unknown): value is ChatGPTGateway;
13
- //#endregion
14
- //#region src/ask.d.ts
15
- /** A JSON value that TypeSafe Jev can read. */
16
- type AskJson = string | number | boolean | null | AskJson[] | {
17
- [key: string]: AskJson;
18
- };
19
- /** A JSON scalar, object, array, or `null`. Root numbers and booleans become text in SDK requests; nested values stay native. */
20
- type AskEntry = AskJson;
21
- /** Option labels mapped to their descriptions. Jev accepts 2 to 255 options. */
22
- type AskChoiceCriteria = {
23
- [label: string]: AskEntry;
24
- };
25
- /** Two or more option labels without descriptions. */
26
- type AskChoiceLabels = readonly [string, string, ...string[]];
27
- /** Descriptions of each score level, indexed from zero. Jev accepts 2 to 10 levels. */
28
- type AskScoreCriteria = readonly [AskEntry, AskEntry, ...AskEntry[]];
29
- /** Optional descriptions of what counts as true or false. */
30
- type AskChanceCriteria = {
31
- false?: AskEntry;
32
- true?: AskEntry;
33
- } | null;
34
- /** Labels become criteria with `null` descriptions. An object stays as it is. */
35
- type AskNamedCriteria<T> = T extends AskChoiceLabels ? { [K in T[number]]: null; } : T;
36
- /** Score level keys: the tuple indices for a fixed rubric, otherwise any numeric string. */
37
- type AskScoreLevel<T extends AskScoreCriteria> = number extends T["length"] ? `${number}` : Extract<keyof T, `${number}`>;
38
- interface AskChoiceAnswer<T extends AskChoiceCriteria = AskChoiceCriteria> {
39
- readonly type: "choice";
40
- /** The label with the highest probability. */
41
- readonly choice: keyof T & string;
42
- /** How much the top option stands out, from zero to one. */
43
- readonly confidence: number;
44
- /** Probability of each option, keyed by its label. */
45
- readonly probabilities: { readonly [K in keyof T]: number; };
46
- }
47
- interface AskScoreAnswer<T extends AskScoreCriteria = AskScoreCriteria> {
48
- readonly type: "score";
49
- /** How much the top level stands out, from zero to one. */
50
- readonly confidence: number;
51
- /** Level descriptions keyed by level number. */
52
- readonly legend: { readonly [K in AskScoreLevel<T>]: T[number]; };
53
- /** Probability of each level, keyed by level number. */
54
- readonly probabilities: { readonly [K in AskScoreLevel<T>]: number; };
55
- /** `score` divided by the highest level, from zero to one. */
56
- readonly ratio: number;
57
- /** Sum of each level number times its probability. It can fall between levels. */
58
- readonly score: number;
59
- }
60
- interface AskChanceAnswer {
61
- readonly type: "chance";
62
- /** Probability of a yes answer, from zero to one. */
63
- readonly chance: number;
64
- }
65
- declare const askAnswerType: unique symbol;
66
- /** Carries the answer type of a question so `driver.ask` can infer the Invocation output. */
67
- interface AskAnswerType<TAnswer> {
68
- readonly [askAnswerType]?: TAnswer;
69
- }
70
- /** Selects one labeled option. Answers with the label, confidence, and probabilities. */
71
- interface AskChoiceQuestion<T extends AskChoiceCriteria = AskChoiceCriteria> extends AskAnswerType<AskChoiceAnswer<T>> {
72
- readonly criteria: T;
73
- readonly instructions: AskEntry;
74
- readonly type: "choice";
75
- }
76
- /** Selects one labeled option. Answers with the label only. */
77
- interface AskSwitchQuestion<T extends AskChoiceCriteria = AskChoiceCriteria> extends AskAnswerType<keyof T & string> {
78
- readonly criteria: T;
79
- readonly instructions: AskEntry;
80
- readonly type: "switch";
81
- }
82
- /** Rates the state against ordered levels. */
83
- interface AskScoreQuestion<T extends AskScoreCriteria = AskScoreCriteria> extends AskAnswerType<AskScoreAnswer<T>> {
84
- readonly criteria: T;
85
- readonly instructions: AskEntry;
86
- readonly type: "score";
87
- }
88
- /** A yes or no question. Answers with the probability of yes. */
89
- interface AskChanceQuestion extends AskAnswerType<AskChanceAnswer> {
90
- readonly criteria?: AskChanceCriteria;
91
- readonly instructions: AskEntry;
92
- readonly type: "chance";
93
- }
94
- /** A yes or no question. Answers `true` when the probability of yes is above `threshold`. */
95
- interface AskIfQuestion extends AskAnswerType<boolean> {
96
- readonly instructions: string;
97
- readonly threshold: number;
98
- readonly type: "if";
99
- }
100
- type AskQuestion = AskChanceQuestion | AskChoiceQuestion | AskIfQuestion | AskScoreQuestion | AskSwitchQuestion;
101
- /** Named questions that Jev answers together against the same state. */
102
- type AskQuestions = {
103
- readonly [name: string]: AskQuestion;
104
- };
105
- /** The answer type of one question. */
106
- type AskAnswer<Q extends AskQuestion> = Q extends AskAnswerType<infer TAnswer> ? Exclude<TAnswer, undefined> : never;
107
- /** Answers keyed by question name. This is the output of an Agent with `driver.ask`. */
108
- type AskAnswers<Q extends AskQuestions> = { readonly [K in keyof Q]: AskAnswer<Q[K]>; };
109
- declare function choice<const T extends AskChoiceCriteria | AskChoiceLabels>(instructions: AskEntry, criteria: T): AskChoiceQuestion<AskNamedCriteria<T>>;
110
- declare function askSwitch<const T extends AskChoiceCriteria | AskChoiceLabels>(instructions: AskEntry, criteria: T): AskSwitchQuestion<AskNamedCriteria<T>>;
111
- declare function score<const T extends AskScoreCriteria>(instructions: AskEntry, criteria: T): AskScoreQuestion<T>;
112
- declare function chance(instructions: AskEntry, criteria?: AskChanceCriteria): AskChanceQuestion;
113
- declare function askIf(instructions: string, options?: {
114
- threshold?: number;
115
- }): AskIfQuestion;
116
- declare function each<T, Q extends AskQuestion>(items: readonly T[], options: {
117
- key: (item: T) => string;
118
- question: (item: T) => Q;
119
- }): Record<string, Q>;
120
- /**
121
- * Builds TypeSafe Jev questions for `gateway.ask()` and `defineAgent({ driver: { ask } })`.
122
- * 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.
123
- */
124
- declare const ask: {
125
- chance: typeof chance;
126
- choice: typeof choice;
127
- each: typeof each;
128
- if: typeof askIf;
129
- score: typeof score;
130
- switch: typeof askSwitch;
131
- };
132
- //#endregion
133
- //#region src/types.d.ts
134
- /** What a gateway value resolver receives. */
135
- interface AiGatewayContext {
136
- /** Aborts a resolver that reads remote storage. */
137
- abortSignal?: AbortSignal;
138
- /**
139
- * Reads one value that a preset did not receive, such as `typesafe` `apiKey`. ViteHub Agents read Server Env here.
140
- * Without it, presets read `process.env`: the `VITEHUB_<PRESET>_<FIELD>` name, then the vendor names.
141
- */
142
- env?: (preset: string, field: string) => unknown;
143
- }
144
- /** A value, or a resolver that runs each time the gateway is used. */
145
- type AiGatewayValue<T> = T | ((context: AiGatewayContext) => T | Promise<T>) | {
146
- resolve: (context: AiGatewayContext) => T | Promise<T>;
147
- };
148
- /** A secret that hides its value until `unseal()`, such as a ViteHub Server Env secret. */
149
- interface AiGatewaySealedSecret {
150
- unseal: () => string | undefined;
151
- }
152
- /**
153
- * A gateway API key or header value: a string, a sealed secret, or a resolver. `undefined` or an empty string fails the
154
- * request, so optional Server Env values can be passed directly.
155
- */
156
- type AiGatewaySecret = AiGatewayValue<string | AiGatewaySealedSecret | undefined>;
157
- /** The provider Drivers that a gateway can serve. */
158
- type AiGatewayDriver = "claude-code" | "codex";
159
- /** What an AI gateway does besides routing the model requests of provider Drivers. */
160
- interface AiGatewayCapabilities {
161
- /** The gateway answers TypeSafe Jev questions with `gateway.ask()`. */
162
- ask: boolean;
163
- }
164
- /** A record of one request's model, provider, and token counts. */
165
- interface AiGatewayUsage {
166
- model?: string;
167
- provider: string;
168
- usage: {
169
- inputTokens?: number;
170
- outputTokens?: number;
171
- totalTokens?: number;
172
- };
173
- }
174
- interface AiGatewayAskOptions {
175
- /** Receives the model, provider, and token counts of each Jev request. */
176
- onUsage?: (usage: AiGatewayUsage) => void;
177
- /** Cancels the pending Jev requests. */
178
- signal?: AbortSignal;
179
- }
180
- /**
181
- * Answers TypeSafe Jev questions about `state`. Build the questions with `ask`. Large question sets are sent in
182
- * sequential bounded requests, and transient provider failures are retried.
183
- */
184
- type AiGatewayAsk = <const Q extends AskQuestions>(state: unknown, questions: Q, options?: AiGatewayAskOptions) => Promise<AskAnswers<Q>>;
185
- /** How a provider Driver reaches an AI gateway: a base URL per Driver, the key, and extra headers. */
186
- interface AiGatewayDefinition {
187
- /** Name shown in inspection and diagnostics. */
188
- name: string;
189
- /**
190
- * Base URL for each Driver. Codex sends OpenAI Responses requests to `<url>/responses`.
191
- * Claude Code sends Anthropic Messages requests to `<url>/v1/messages`.
192
- * A Driver without an entry cannot use this gateway.
193
- */
194
- baseURL: Partial<Record<AiGatewayDriver, AiGatewayValue<string>>>;
195
- /** API key. When it is not set, the first non-empty variable in `apiKeyEnv` is read. */
196
- apiKey?: AiGatewaySecret;
197
- /** Process environment variables that supply the API key, in lookup order. */
198
- apiKeyEnv?: readonly string[];
199
- /** How the gateway receives the API key. `"bearer"` (default) sends `Authorization: Bearer`. `"x-api-key"` sends `x-api-key`. */
200
- auth?: "bearer" | "x-api-key";
201
- /** Extra request headers, such as Cloudflare Access service-token headers. Values are treated as secrets. */
202
- headers?: Record<string, AiGatewaySecret>;
203
- }
204
- /**
205
- * An AI gateway: where the model requests of provider Drivers go and, when `TCapabilities` has `ask: true`, where
206
- * TypeSafe Jev questions go (`gateway.ask()`). Build one with a preset or with `defineAiGateway()`.
207
- */
208
- type AiGateway<TCapabilities extends Partial<AiGatewayCapabilities> = Partial<AiGatewayCapabilities>> = AiGatewayDefinition & (TCapabilities["ask"] extends true ? {
209
- ask: AiGatewayAsk;
210
- } : TCapabilities["ask"] extends false ? {
211
- ask?: never;
212
- } : {
213
- ask?: AiGatewayAsk;
214
- });
215
- //#endregion
216
- //#region src/env.d.ts
217
- /** One preset value that is read from the environment when the preset does not receive it. */
218
- interface AiGatewayEnvField {
219
- /** Vendor variable names in lookup order, after the `VITEHUB_` name. */
220
- names: readonly [string, ...string[]];
221
- secret?: true;
222
- }
223
- /**
224
- * The variables that each preset reads, keyed by preset and then by field. ViteHub declares the presets that Agent files
225
- * use in Server Env as `env.server.<preset>.<field>`.
226
- */
227
- /** The presets that read the environment. */
228
- type AiGatewayEnvPreset = "anthropic" | "cliproxy" | "cloudflare" | "cloudflareAccess" | "litellm" | "ollama" | "openai" | "openrouter" | "typesafe" | "vercel";
229
- declare const aiGatewayEnv: Readonly<Record<AiGatewayEnvPreset, Readonly<Record<string, AiGatewayEnvField>>>>;
230
- /** A field of a preset, such as `apiKey`. */
231
- type AiGatewayEnvFieldName<_TPreset extends AiGatewayEnvPreset = AiGatewayEnvPreset> = string;
232
- /** The variables of one preset value in lookup order: `VITEHUB_<PRESET>_<FIELD>`, then the vendor names. */
233
- declare function aiGatewayEnvNames<TPreset extends AiGatewayEnvPreset>(preset: TPreset, field: AiGatewayEnvFieldName<TPreset>): string[];
234
- //#endregion
235
- //#region src/jev.d.ts
236
- /** One trace event of a Jev request. ViteHub Agents record these in the Invocation trace. */
237
- interface AiGatewayTraceEvent {
238
- attributes: Record<string, unknown>;
239
- name: string;
240
- type: "error" | "run";
241
- }
242
- interface JevRequestContext {
243
- abortSignal?: AbortSignal;
244
- /** Receives one `agent.tool.*` event per question and one `agent.usage.recorded` event per Jev request. */
245
- observe?: (event: AiGatewayTraceEvent) => Promise<void>;
246
- /** Receives the usage of each Jev request: its model, provider, and token counts. */
247
- recordUsage?: (usage: AiGatewayUsage) => void;
248
- /** Resolves the route of the gateway for this request. */
249
- route: () => Promise<JevRoute>;
250
- }
251
- /**
252
- * One resolved Jev route. `protocol` selects the advocaat client: the TypeSafe API (also behind a Cloudflare AI Gateway
253
- * custom provider) or Vercel AI Gateway.
254
- */
255
- interface JevRoute {
256
- apiKey?: string;
257
- baseURL?: string;
258
- fetch?: typeof globalThis.fetch;
259
- headers?: Record<string, string>;
260
- /** The variables that hold the credentials, for the fix of a rejected key. Undefined when the caller passed them. */
261
- keyEnv?: string;
262
- /** Shown in diagnostics, such as "Cloudflare AI Gateway". */
263
- label: string;
264
- model?: string;
265
- /** The gateway name in usage records and traces, such as `cloudflare`. */
266
- name: string;
267
- protocol: "typesafe" | "vercel";
268
- }
269
- //#endregion
270
- //#region src/presets.d.ts
271
- /** Options shared by every gateway preset. */
272
- interface AiGatewayPresetOptions {
273
- /** API key. When it is not set, the preset reads its Server Env value, such as `CLIPROXY_API_KEY`. */
274
- apiKey?: AiGatewaySecret;
275
- /** Extra request headers, such as `cloudflareAccess()`. */
276
- headers?: Record<string, AiGatewaySecret>;
277
- }
278
- /** Options for a gateway that you host. */
279
- interface AiHostedGatewayOptions extends AiGatewayPresetOptions {
280
- /** Origin of the gateway, such as `https://proxy.example.com`. A trailing `/v1` is removed. When it is not set, the preset reads its Server Env value, such as `CLIPROXY_URL`. */
281
- url?: string;
282
- }
283
- /** Options for a gateway that answers TypeSafe Jev questions. */
284
- interface AiAskGatewayOptions {
285
- /** Custom fetch implementation for Jev requests. Default: `globalThis.fetch`. */
286
- fetch?: typeof globalThis.fetch;
287
- /** Jev model ID for `ask()`. Default: `jev-latest`, or `typesafe-ai/jev` through Vercel AI Gateway. */
288
- model?: string;
289
- }
290
- /** Options for `typesafe()`. */
291
- interface TypesafeGatewayOptions extends AiAskGatewayOptions, AiGatewayPresetOptions {}
292
- /** Options for `vercel()`. `model` selects the Jev model of `ask()`; Driver models come from `driver.model`. */
293
- interface VercelGatewayOptions extends AiAskGatewayOptions, AiGatewayPresetOptions {}
294
- /** Options for `cloudflare()`. Each value defaults to its Server Env value. */
295
- interface CloudflareGatewayOptions extends AiAskGatewayOptions {
296
- /** Cloudflare account ID. Defaults to `CLOUDFLARE_ACCOUNT_ID`. */
297
- accountId?: string;
298
- /** TypeSafe API key that the gateway forwards. Defaults to `TYPESAFE_API_KEY`. */
299
- apiKey?: AiGatewaySecret;
300
- /** AI Gateway ID. Defaults to `CLOUDFLARE_AI_GATEWAY_ID`. */
301
- gatewayId?: string;
302
- /** Custom provider slug; the gateway URL uses `custom-<slug>`. Defaults to `CLOUDFLARE_AI_GATEWAY_SLUG`, then `typesafe`. */
303
- slug?: string;
304
- /** Gateway token of an authenticated gateway, sent as `cf-aig-authorization`. Defaults to `CLOUDFLARE_AI_GATEWAY_TOKEN`. */
305
- token?: AiGatewaySecret;
306
- }
307
- /** Options for `cloudflareAccess()`. Each value defaults to its Server Env value. */
308
- interface CloudflareAccessOptions {
309
- /** Service token client ID. Defaults to `CF_ACCESS_CLIENT_ID`. */
310
- clientId?: AiGatewaySecret;
311
- /** Service token client secret. Defaults to `CF_ACCESS_CLIENT_SECRET`. */
312
- clientSecret?: AiGatewaySecret;
313
- }
314
- /** Asks through a gateway with a resolver context, observers, and usage records. ViteHub Agents use it for `driver.ask`. */
315
- declare function askAiGateway<const Q extends AskQuestions>(gateway: AiGateway, state: unknown, questions: Q, options?: {
316
- context?: AiGatewayContext;
317
- observe?: JevRequestContext["observe"];
318
- onUsage?: (usage: AiGatewayUsage) => void;
319
- signal?: AbortSignal;
320
- }): Promise<AskAnswers<Q>>;
321
- /**
322
- * Validate a custom gateway for an endpoint without a preset. It routes Driver model requests; only the `typesafe()`,
323
- * `vercel()`, and `cloudflare()` presets answer Jev questions.
324
- */
325
- declare function defineAiGateway(gateway: AiGatewayDefinition): AiGateway<{
326
- ask: false;
327
- }>;
328
- /**
329
- * Cloudflare Access service-token headers for a gateway behind Access.
330
- * Reads `CF_ACCESS_CLIENT_ID` and `CF_ACCESS_CLIENT_SECRET` unless you pass the values.
331
- */
332
- declare function cloudflareAccess(options?: CloudflareAccessOptions): Record<string, AiGatewaySecret>;
333
- /** [CLIProxyAPI](https://github.com/router-for-me/CLIProxyAPI). Serves Codex and Claude Code. Reads `CLIPROXY_URL` and `CLIPROXY_API_KEY`. */
334
- declare function cliproxy(options?: AiHostedGatewayOptions): AiGateway<{
335
- ask: false;
336
- }>;
337
- /** [LiteLLM Proxy](https://docs.litellm.ai/docs/simple_proxy). Serves Codex and Claude Code. Reads `LITELLM_URL` and `LITELLM_API_KEY`. */
338
- declare function litellm(options?: AiHostedGatewayOptions): AiGateway<{
339
- ask: false;
340
- }>;
341
- /** [Ollama](https://docs.ollama.com). Serves Codex and Claude Code. Reads `OLLAMA_URL` and `OLLAMA_API_KEY`; defaults to `http://localhost:11434` without a key. */
342
- declare function ollama(options?: AiHostedGatewayOptions): AiGateway<{
343
- ask: false;
344
- }>;
345
- /** [OpenRouter](https://openrouter.ai/docs). Serves Codex and Claude Code. Reads `OPENROUTER_API_KEY`. */
346
- declare function openrouter(options?: AiGatewayPresetOptions): AiGateway<{
347
- ask: false;
348
- }>;
349
- /**
350
- * [Vercel AI Gateway](https://vercel.com/docs/ai-gateway). Serves Codex and Claude Code, and answers Jev questions as
351
- * `typesafe-ai/jev`. Reads `AI_GATEWAY_API_KEY`, then `VERCEL_OIDC_TOKEN`.
352
- */
353
- declare function vercel(options?: VercelGatewayOptions): AiGateway<{
354
- ask: true;
355
- }>;
356
- /** The OpenAI API with an API key. Serves Codex. Reads `OPENAI_API_KEY`. */
357
- declare function openai(options?: AiGatewayPresetOptions): AiGateway<{
358
- ask: false;
359
- }>;
360
- /** The Anthropic API with an API key. Serves Claude Code. Reads `ANTHROPIC_API_KEY`. */
361
- declare function anthropic(options?: AiGatewayPresetOptions): AiGateway<{
362
- ask: false;
363
- }>;
364
- /** [TypeSafe](https://typesafe.ai). Answers Jev questions; it serves no Driver. Reads `TYPESAFE_API_KEY` and `TYPESAFE_DEFAULT_MODEL`. */
365
- declare function typesafe(options?: TypesafeGatewayOptions): AiGateway<{
366
- ask: true;
367
- }>;
368
- /**
369
- * TypeSafe through a [Cloudflare AI Gateway](https://developers.cloudflare.com/ai-gateway/configuration/custom-providers/)
370
- * custom provider whose base URL is `https://api.typesafe.ai`. Answers Jev questions; it serves no Driver. Reads
371
- * `TYPESAFE_API_KEY`, `CLOUDFLARE_ACCOUNT_ID`, `CLOUDFLARE_AI_GATEWAY_ID`, `CLOUDFLARE_AI_GATEWAY_TOKEN`, and
372
- * `CLOUDFLARE_AI_GATEWAY_SLUG`.
373
- */
374
- declare function cloudflare(options?: CloudflareGatewayOptions): AiGateway<{
375
- ask: true;
376
- }>;
377
- //#endregion
378
- export { AskScoreCriteria as $, AiGatewayContext as A, AskChanceAnswer as B, AiGatewayEnvPreset as C, AiGatewayAsk as D, AiGateway as E, AiGatewayUsage as F, AskChoiceLabels as G, AskChanceQuestion as H, AiGatewayValue as I, AskIfQuestion as J, AskChoiceQuestion as K, AskAnswer as L, AiGatewayDriver as M, AiGatewaySealedSecret as N, AiGatewayAskOptions as O, AiGatewaySecret as P, AskScoreAnswer as Q, AskAnswerType as R, AiGatewayEnvFieldName as S, aiGatewayEnvNames as T, AskChoiceAnswer as U, AskChanceCriteria as V, AskChoiceCriteria as W, AskQuestion as X, AskJson as Y, AskQuestions as Z, openrouter as _, CloudflareGatewayOptions as a, isChatGPTGateway as at, AiGatewayTraceEvent as b, anthropic as c, cloudflare as d, AskScoreQuestion as et, cloudflareAccess as f, openai as g, ollama as h, CloudflareAccessOptions as i, chatgpt as it, AiGatewayDefinition as j, AiGatewayCapabilities as k, askAiGateway as l, litellm as m, AiGatewayPresetOptions as n, ask as nt, TypesafeGatewayOptions as o, defineAiGateway as p, AskEntry as q, AiHostedGatewayOptions as r, ChatGPTGateway as rt, VercelGatewayOptions as s, AiAskGatewayOptions as t, AskSwitchQuestion as tt, cliproxy as u, typesafe as v, aiGatewayEnv as w, AiGatewayEnvField as x, vercel as y, AskAnswers as z };