@vite-hub/gateways 0.1.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,305 @@
1
+ import { Diagnostic } from "nostics";
2
+ //#region src/ask-model.d.ts
3
+ /**
4
+ * An AI SDK model instance or gateway model id. This structural boundary keeps the optional SDK out of root declarations.
5
+ * The SDK owns the call options and results; the adapter passes the model through without calling these hooks itself.
6
+ */
7
+ type AskModel = string | {
8
+ readonly specificationVersion: "v2" | "v3" | "v4";
9
+ readonly provider: string;
10
+ readonly modelId: string;
11
+ supportedUrls: Record<string, RegExp[]> | PromiseLike<Record<string, RegExp[]>>;
12
+ doGenerate: (...args: never[]) => PromiseLike<unknown>;
13
+ doStream: (...args: never[]) => PromiseLike<unknown>;
14
+ };
15
+ /**
16
+ * Answers `ask` questions with any AI SDK model, in one structured output request. Use it where a gateway with `ask()` goes,
17
+ * such as `defineChoices({ model })`. A chat model gives one answer and how sure it is, so `probabilities` put that number
18
+ * on the answer and share the rest between the other options. Jev gives a real probability for every option.
19
+ */
20
+ declare function askWithModel(model: AskModel): {
21
+ ask: AiGatewayAsk;
22
+ };
23
+ /**
24
+ * A [Standard Schema](https://standardschema.dev) that converts to JSON Schema, such as a Zod 4 or ArkType schema, or a
25
+ * Valibot schema wrapped with `toStandardJsonSchema()` from `@valibot/to-json-schema`.
26
+ */
27
+ interface AskSchema<TOutput = unknown> {
28
+ readonly "~standard": {
29
+ readonly version: 1;
30
+ readonly vendor: string;
31
+ readonly validate: (value: unknown) => unknown;
32
+ readonly types?: {
33
+ readonly input: unknown;
34
+ readonly output: TOutput;
35
+ } | undefined;
36
+ };
37
+ }
38
+ /** The type of the data that a schema validates. */
39
+ type AskSchemaOutput<TSchema extends AskSchema> = NonNullable<TSchema["~standard"]["types"]>["output"];
40
+ type AskOptions<TSchema extends AskSchema | undefined = undefined> = {
41
+ /** The model that answers: an AI SDK model, such as `languageModel(openrouter(), 'google/gemini-3-flash')`, or an AI SDK gateway model ID. */
42
+ model: AskModel;
43
+ /** System instructions, such as the role of the model and the rules of the answer. */
44
+ instructions?: string;
45
+ /** Receives the model, provider, and token counts of the request. */
46
+ onUsage?: (usage: AiGatewayUsage) => void;
47
+ /** Cancels the request. */
48
+ signal?: AbortSignal;
49
+ } & (TSchema extends AskSchema ? {
50
+ /** The shape of the answer. The model must answer with JSON that this schema accepts. */
51
+ schema: TSchema;
52
+ } : {
53
+ /** Without `schema`, `ask()` returns the answer as text. */
54
+ schema?: undefined;
55
+ });
56
+ /** Why `ask()` returned no data: the model request failed, or the answer did not match the schema or had no text. */
57
+ type AskError = Diagnostic<unknown, "GATEWAYS_ASK_MODEL_FAILED" | "GATEWAYS_ASK_OUTPUT_INVALID">;
58
+ /** `[error, data]`. Check `error` first. When `error` is `undefined`, `data` has the validated answer. */
59
+ type AskResult<TData> = [error: AskError, data: undefined] | [error: undefined, data: TData];
60
+ /**
61
+ * Asks a model one question and returns the answer as `[error, data]`. One request, no Agent, no tools.
62
+ * With `schema`, `data` is the validated, typed answer. Without `schema`, `data` is the answer text.
63
+ * The request and the model are the AI SDK's: pass `languageModel(gateway, modelId)` to send it through any gateway.
64
+ */
65
+ interface AskCall {
66
+ <const TSchema extends AskSchema>(prompt: string, options: AskOptions<TSchema> & {
67
+ schema: TSchema;
68
+ }): Promise<AskResult<AskSchemaOutput<TSchema>>>;
69
+ (prompt: string, options: AskOptions): Promise<AskResult<string>>;
70
+ }
71
+ //#endregion
72
+ //#region src/ask.d.ts
73
+ /** A JSON value that TypeSafe Jev can read. */
74
+ type AskJson = string | number | boolean | null | AskJson[] | {
75
+ [key: string]: AskJson;
76
+ };
77
+ /** A JSON scalar, object, array, or `null`. Root numbers and booleans become text in SDK requests; nested values stay native. */
78
+ type AskEntry = AskJson;
79
+ /** Option labels mapped to their descriptions. Jev accepts 2 to 255 options. */
80
+ type AskChoiceCriteria = {
81
+ [label: string]: AskEntry;
82
+ };
83
+ /** Two or more option labels without descriptions. */
84
+ type AskChoiceLabels = readonly [string, string, ...string[]];
85
+ /** Descriptions of each score level, indexed from zero. Jev accepts 2 to 10 levels. */
86
+ type AskScoreCriteria = readonly [AskEntry, AskEntry, ...AskEntry[]];
87
+ /** Optional descriptions of what counts as true or false. */
88
+ type AskChanceCriteria = {
89
+ false?: AskEntry;
90
+ true?: AskEntry;
91
+ } | null;
92
+ /** Labels become criteria with `null` descriptions. An object stays as it is. */
93
+ type AskNamedCriteria<T> = T extends AskChoiceLabels ? { [K in T[number]]: null; } : T;
94
+ /** Score level keys: the tuple indices for a fixed rubric, otherwise any numeric string. */
95
+ type AskScoreLevel<T extends AskScoreCriteria> = number extends T["length"] ? `${number}` : Extract<keyof T, `${number}`>;
96
+ interface AskChoiceAnswer<T extends AskChoiceCriteria = AskChoiceCriteria> {
97
+ readonly type: "choice";
98
+ /** The label with the highest probability. */
99
+ readonly choice: keyof T & string;
100
+ /** How much the top option stands out, from zero to one. */
101
+ readonly confidence: number;
102
+ /** Probability of each option, keyed by its label. */
103
+ readonly probabilities: { readonly [K in keyof T]: number; };
104
+ }
105
+ interface AskScoreAnswer<T extends AskScoreCriteria = AskScoreCriteria> {
106
+ readonly type: "score";
107
+ /** How much the top level stands out, from zero to one. */
108
+ readonly confidence: number;
109
+ /** Level descriptions keyed by level number. */
110
+ readonly legend: { readonly [K in AskScoreLevel<T>]: T[number]; };
111
+ /** Probability of each level, keyed by level number. */
112
+ readonly probabilities: { readonly [K in AskScoreLevel<T>]: number; };
113
+ /** `score` divided by the highest level, from zero to one. */
114
+ readonly ratio: number;
115
+ /** Sum of each level number times its probability. It can fall between levels. */
116
+ readonly score: number;
117
+ }
118
+ interface AskChanceAnswer {
119
+ readonly type: "chance";
120
+ /** Probability of a yes answer, from zero to one. */
121
+ readonly chance: number;
122
+ }
123
+ declare const askAnswerType: unique symbol;
124
+ /** Carries the answer type of a question so `driver.ask` can infer the Invocation output. */
125
+ interface AskAnswerType<TAnswer> {
126
+ readonly [askAnswerType]?: TAnswer;
127
+ }
128
+ /** Selects one labeled option. Answers with the label, confidence, and probabilities. */
129
+ interface AskChoiceQuestion<T extends AskChoiceCriteria = AskChoiceCriteria> extends AskAnswerType<AskChoiceAnswer<T>> {
130
+ readonly criteria: T;
131
+ readonly instructions: AskEntry;
132
+ readonly type: "choice";
133
+ }
134
+ /** Selects one labeled option. Answers with the label only. */
135
+ interface AskSwitchQuestion<T extends AskChoiceCriteria = AskChoiceCriteria> extends AskAnswerType<keyof T & string> {
136
+ readonly criteria: T;
137
+ readonly instructions: AskEntry;
138
+ readonly type: "switch";
139
+ }
140
+ /** Rates the state against ordered levels. */
141
+ interface AskScoreQuestion<T extends AskScoreCriteria = AskScoreCriteria> extends AskAnswerType<AskScoreAnswer<T>> {
142
+ readonly criteria: T;
143
+ readonly instructions: AskEntry;
144
+ readonly type: "score";
145
+ }
146
+ /** A yes or no question. Answers with the probability of yes. */
147
+ interface AskChanceQuestion extends AskAnswerType<AskChanceAnswer> {
148
+ readonly criteria?: AskChanceCriteria;
149
+ readonly instructions: AskEntry;
150
+ readonly type: "chance";
151
+ }
152
+ /** A yes or no question. Answers `true` when the probability of yes is above `threshold`. */
153
+ interface AskIfQuestion extends AskAnswerType<boolean> {
154
+ readonly instructions: string;
155
+ readonly threshold: number;
156
+ readonly type: "if";
157
+ }
158
+ type AskQuestion = AskChanceQuestion | AskChoiceQuestion | AskIfQuestion | AskScoreQuestion | AskSwitchQuestion;
159
+ /** Named questions that Jev answers together against the same state. */
160
+ type AskQuestions = {
161
+ readonly [name: string]: AskQuestion;
162
+ };
163
+ /** The answer type of one question. */
164
+ type AskAnswer<Q extends AskQuestion> = Q extends AskAnswerType<infer TAnswer> ? Exclude<TAnswer, undefined> : never;
165
+ /** Answers keyed by question name. This is the output of an Agent with `driver.ask`. */
166
+ type AskAnswers<Q extends AskQuestions> = { readonly [K in keyof Q]: AskAnswer<Q[K]>; };
167
+ declare function choice<const T extends AskChoiceCriteria | AskChoiceLabels>(instructions: AskEntry, criteria: T): AskChoiceQuestion<AskNamedCriteria<T>>;
168
+ declare function askSwitch<const T extends AskChoiceCriteria | AskChoiceLabels>(instructions: AskEntry, criteria: T): AskSwitchQuestion<AskNamedCriteria<T>>;
169
+ declare function score<const T extends AskScoreCriteria>(instructions: AskEntry, criteria: T): AskScoreQuestion<T>;
170
+ declare function chance(instructions: AskEntry, criteria?: AskChanceCriteria): AskChanceQuestion;
171
+ declare function askIf(instructions: string, options?: {
172
+ threshold?: number;
173
+ }): AskIfQuestion;
174
+ declare function each<T, Q extends AskQuestion>(items: readonly T[], options: {
175
+ key: (item: T) => string;
176
+ question: (item: T) => Q;
177
+ }): Record<string, Q>;
178
+ /**
179
+ * Asks a model one question and returns validated, typed data as `[error, data]`: `ask(prompt, { model, schema })`.
180
+ * Use it for one structured answer, such as extracted fields, without an Agent. Leave out `schema` to get the answer as text.
181
+ *
182
+ * Its properties build TypeSafe Jev questions for `gateway.ask()` and `defineAgent({ driver: { ask } })`.
183
+ * 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.
184
+ *
185
+ * @example
186
+ * import * as z from 'zod'
187
+ * import { ask, openrouter } from '@vite-hub/gateways'
188
+ * import { languageModel } from '@vite-hub/gateways/ai-sdk'
189
+ *
190
+ * const [error, receipt] = await ask('MERCADONA 23.10 -34.90 EUR', {
191
+ * model: languageModel(openrouter(), 'google/gemini-3-flash'),
192
+ * schema: z.object({ merchant: z.string(), amount: z.number() }),
193
+ * })
194
+ */
195
+ declare const ask: AskCall & {
196
+ chance: typeof chance;
197
+ choice: typeof choice;
198
+ each: typeof each;
199
+ if: typeof askIf;
200
+ score: typeof score;
201
+ switch: typeof askSwitch;
202
+ };
203
+ //#endregion
204
+ //#region src/types.d.ts
205
+ /** What a gateway value resolver receives. */
206
+ interface AiGatewayContext {
207
+ /** Aborts a resolver that reads remote storage. */
208
+ abortSignal?: AbortSignal;
209
+ /**
210
+ * Reads one value that a preset did not receive, such as `typesafe` `apiKey`. ViteHub Agents read Server Env here.
211
+ * Without it, presets read `process.env`: the `VITEHUB_<PRESET>_<FIELD>` name, then the vendor names.
212
+ */
213
+ env?: (preset: string, field: string) => unknown;
214
+ }
215
+ /** A value, or a resolver that runs each time the gateway is used. */
216
+ type AiGatewayValue<T> = T | ((context: AiGatewayContext) => T | Promise<T>) | {
217
+ resolve: (context: AiGatewayContext) => T | Promise<T>;
218
+ };
219
+ /** A secret that hides its value until `unseal()`, such as a ViteHub Server Env secret. */
220
+ interface AiGatewaySealedSecret {
221
+ unseal: () => string | undefined;
222
+ }
223
+ /**
224
+ * A gateway API key or header value: a string, a sealed secret, or a resolver. `undefined` or an empty string fails the
225
+ * request, so optional Server Env values can be passed directly.
226
+ */
227
+ type AiGatewaySecret = AiGatewayValue<string | AiGatewaySealedSecret | undefined>;
228
+ /** The provider Drivers that a gateway can serve. */
229
+ type AiGatewayDriver = "claude-code" | "codex";
230
+ /**
231
+ * The model APIs that a gateway can serve, keyed in `baseURL`:
232
+ * - `codex`: OpenAI Responses for the Codex Driver, at `<url>/responses`.
233
+ * - `claude-code`: Anthropic Messages for the Claude Code Driver and AI SDK models, at `<url>/v1/messages`.
234
+ * - `openai-compatible`: OpenAI Chat Completions and Responses for AI SDK models, at `<url>/chat/completions` and `<url>/responses`.
235
+ */
236
+ type AiGatewayRoute = AiGatewayDriver | "openai-compatible";
237
+ /** What an AI gateway can do. A preset sets its capabilities, so the type rejects a Driver or a model API that it does not serve. */
238
+ interface AiGatewayCapabilities {
239
+ /** AI SDK APIs supported by the preset, in addition to its URL routes. */
240
+ apis: "chat" | "responses" | "messages";
241
+ /** The gateway answers TypeSafe Jev questions with `gateway.ask()`. */
242
+ ask: boolean;
243
+ /** The model APIs in `baseURL`. */
244
+ routes: AiGatewayRoute;
245
+ }
246
+ /** A record of one request's model, provider, and token counts. */
247
+ interface AiGatewayUsage {
248
+ model?: string;
249
+ provider: string;
250
+ usage: {
251
+ inputTokens?: number;
252
+ outputTokens?: number;
253
+ totalTokens?: number;
254
+ };
255
+ }
256
+ interface AiGatewayAskOptions {
257
+ /** Receives the model, provider, and token counts of each Jev request. */
258
+ onUsage?: (usage: AiGatewayUsage) => void;
259
+ /** Cancels the pending Jev requests. */
260
+ signal?: AbortSignal;
261
+ }
262
+ /**
263
+ * Answers TypeSafe Jev questions about `state`. Build the questions with `ask`. Large question sets are sent in
264
+ * sequential bounded requests, and transient provider failures are retried.
265
+ */
266
+ type AiGatewayAsk = <const Q extends AskQuestions>(state: unknown, questions: Q, options?: AiGatewayAskOptions) => Promise<AskAnswers<Q>>;
267
+ /** How a provider Driver or an AI SDK model reaches an AI gateway: a base URL per model API, the key, and extra headers. */
268
+ interface AiGatewayDefinition {
269
+ /** Name shown in inspection and diagnostics. */
270
+ name: string;
271
+ /**
272
+ * Base URL for each model API. Codex sends OpenAI Responses requests to `<url>/responses`.
273
+ * Claude Code sends Anthropic Messages requests to `<url>/v1/messages`.
274
+ * AI SDK models send OpenAI Chat Completions requests to `<openai-compatible url>/chat/completions`.
275
+ * A Driver or model API without an entry cannot use this gateway.
276
+ */
277
+ baseURL: Partial<Record<AiGatewayRoute, AiGatewayValue<string>>>;
278
+ /** API key. When it is not set, the first non-empty variable in `apiKeyEnv` is read. */
279
+ apiKey?: AiGatewaySecret;
280
+ /** Process environment variables that supply the API key, in lookup order. */
281
+ apiKeyEnv?: readonly string[];
282
+ /** How the gateway receives the API key. `"bearer"` (default) sends `Authorization: Bearer`. `"x-api-key"` sends `x-api-key`. */
283
+ auth?: "bearer" | "x-api-key";
284
+ /** Extra request headers, such as Cloudflare Access service-token headers. Values are treated as secrets. */
285
+ headers?: Record<string, AiGatewaySecret>;
286
+ }
287
+ /**
288
+ * An AI gateway: where the model requests of provider Drivers and AI SDK models go and, when `TCapabilities` has
289
+ * `ask: true`, where TypeSafe Jev questions go (`gateway.ask()`). `TCapabilities["routes"]` lists the model APIs in
290
+ * `baseURL`, so `AiGateway<{ routes: "codex" }>` accepts only gateways that serve Codex. Build one with a preset or with
291
+ * `defineAiGateway()`.
292
+ */
293
+ type AiGateway<TCapabilities extends Partial<AiGatewayCapabilities> = Partial<AiGatewayCapabilities>> = AiGatewayDefinition & {
294
+ /** Optional API restriction for presets whose endpoint implements only some APIs. */
295
+ readonly modelApis?: readonly (TCapabilities["apis"] & AiGatewayCapabilities["apis"])[];
296
+ readonly baseURL: Readonly<Record<TCapabilities["routes"] extends AiGatewayRoute ? TCapabilities["routes"] : never, AiGatewayValue<string>>>;
297
+ } & (TCapabilities["ask"] extends true ? {
298
+ ask: AiGatewayAsk;
299
+ } : TCapabilities["ask"] extends false ? {
300
+ ask?: never;
301
+ } : {
302
+ ask?: AiGatewayAsk;
303
+ });
304
+ //#endregion
305
+ export { AskScoreQuestion as A, AskEntry as C, AskQuestions as D, AskQuestion as E, AskOptions as F, AskResult as I, AskSchema as L, ask as M, AskError as N, AskScoreAnswer as O, AskModel as P, askWithModel as R, AskChoiceQuestion as S, AskJson as T, AskChanceCriteria as _, AiGatewayContext as a, AskChoiceCriteria as b, AiGatewayRoute as c, AiGatewayUsage as d, AiGatewayValue as f, AskChanceAnswer as g, AskAnswers as h, AiGatewayCapabilities as i, AskSwitchQuestion as j, AskScoreCriteria as k, AiGatewaySealedSecret as l, AskAnswerType as m, AiGatewayAsk as n, AiGatewayDefinition as o, AskAnswer as p, AiGatewayAskOptions as r, AiGatewayDriver as s, AiGateway as t, AiGatewaySecret as u, AskChanceQuestion as v, AskIfQuestion as w, AskChoiceLabels as x, AskChoiceAnswer as y };
package/package.json CHANGED
@@ -1,14 +1,20 @@
1
1
  {
2
2
  "name": "@vite-hub/gateways",
3
- "version": "0.1.0",
4
- "description": "One AI gateway model: route Codex and Claude Code model requests, and ask TypeSafe Jev typed questions, through TypeSafe, Vercel AI Gateway, Cloudflare AI Gateway, CLIProxyAPI, LiteLLM, Ollama, OpenRouter, OpenAI, or Anthropic.",
3
+ "version": "0.3.1",
4
+ "description": "One AI gateway object for every consumer: route Codex, Claude Code, and AI SDK models, and ask TypeSafe Jev typed questions, through Vercel AI Gateway, Cloudflare AI Gateway, OpenRouter, LiteLLM, CLIProxyAPI, Ollama, OpenAI, Anthropic, or TypeSafe.",
5
5
  "keywords": [
6
6
  "ai",
7
7
  "ai-gateway",
8
+ "ai-sdk",
9
+ "anthropic",
8
10
  "cloudflare",
9
11
  "gateway",
10
12
  "jev",
13
+ "litellm",
11
14
  "llm",
15
+ "ollama",
16
+ "openai",
17
+ "openrouter",
12
18
  "typesafe",
13
19
  "typescript",
14
20
  "vercel",
@@ -36,6 +42,11 @@
36
42
  "import": "./dist/index.js",
37
43
  "default": "./dist/index.js"
38
44
  },
45
+ "./ai-sdk": {
46
+ "types": "./dist/ai-sdk.d.ts",
47
+ "import": "./dist/ai-sdk.js",
48
+ "default": "./dist/ai-sdk.js"
49
+ },
39
50
  "./internal": {
40
51
  "types": "./dist/internal.d.ts",
41
52
  "import": "./dist/internal.js",
@@ -44,32 +55,57 @@
44
55
  "./package.json": "./package.json"
45
56
  },
46
57
  "dependencies": {
47
- "nostics": "1.3.0"
58
+ "nostics": "1.4.0"
48
59
  },
49
60
  "devDependencies": {
61
+ "@ai-sdk/anthropic": "4.0.75",
62
+ "@ai-sdk/openai": "4.0.88",
63
+ "@ai-sdk/openai-compatible": "3.0.65",
64
+ "@ai-sdk/provider": "^4.0.24",
50
65
  "@types/node": "^24.19.1",
66
+ "@vite-hub/internal": "0.0.1",
51
67
  "advocaat": "^0.0.6",
68
+ "ai": "7.0.130",
52
69
  "publint": "^0.3.25",
53
70
  "typescript": "^6.0.3",
54
71
  "vite-plus": "^0.3.3",
55
- "vitest": "^4.1.11",
56
- "@vite-hub/internal": "0.0.1"
72
+ "vitest": "^4.1.11"
57
73
  },
58
74
  "peerDependencies": {
59
- "advocaat": "^0.0.6"
75
+ "@ai-sdk/anthropic": "^4.0.0",
76
+ "@ai-sdk/openai": "^4.0.0",
77
+ "@ai-sdk/openai-compatible": "^3.0.0",
78
+ "@ai-sdk/provider": "^4.0.0",
79
+ "advocaat": "^0.0.6",
80
+ "ai": "^6.0.0 || ^7.0.0-0"
60
81
  },
61
82
  "peerDependenciesMeta": {
83
+ "@ai-sdk/anthropic": {
84
+ "optional": true
85
+ },
86
+ "@ai-sdk/openai": {
87
+ "optional": true
88
+ },
89
+ "@ai-sdk/openai-compatible": {
90
+ "optional": true
91
+ },
92
+ "@ai-sdk/provider": {
93
+ "optional": true
94
+ },
62
95
  "advocaat": {
63
96
  "optional": true
97
+ },
98
+ "ai": {
99
+ "optional": true
64
100
  }
65
101
  },
66
102
  "engines": {
67
- "node": ">=24.0.0"
103
+ "node": ">=22.18.0"
68
104
  },
69
105
  "scripts": {
70
106
  "build": "vp pack",
71
107
  "dev": "vp pack --watch",
72
108
  "typecheck": "vp run --cache -t @vite-hub/gateways#build && node ../../test/package-typecheck.mjs --noEmit -p ./tsconfig.json",
73
- "test": "vp run -t @vite-hub/gateways#build && vp test"
109
+ "test": "vp run --cache -t @vite-hub/gateways#build && vp test"
74
110
  }
75
111
  }