@vite-hub/gateways 0.4.1 → 0.5.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.
- package/README.md +69 -15
- package/dist/ai-sdk.d.ts +4 -5
- package/dist/ai-sdk.js +68 -25
- package/dist/{definition-BVc8HZWs.js → definition-IHIWW_eG.js} +18 -129
- package/dist/diagnostics-CNIdO5-M.js +121 -0
- package/dist/index.d.ts +3 -3
- package/dist/index.js +5 -15
- package/dist/internal.d.ts +14 -7
- package/dist/internal.js +4 -3
- package/dist/jev-Kmwvxt8l.js +420 -0
- package/dist/presets-BowIdgYT.js +504 -0
- package/dist/{presets-QQzoSUSu.d.ts → presets-CmCCGdfk.d.ts} +21 -17
- package/dist/testing.d.ts +46 -0
- package/dist/testing.js +152 -0
- package/dist/{types-CF5dF7X1.d.ts → types-jSw-t3Dq.d.ts} +0 -8
- package/package.json +16 -9
- package/dist/presets-CRYxSoMw.js +0 -900
package/dist/presets-CRYxSoMw.js
DELETED
|
@@ -1,900 +0,0 @@
|
|
|
1
|
-
import { a as isRecord, l as resolveAiGatewaySecret, n as aiGatewayModelCredentials, o as normalizeAiGateway, r as aiGatewayOptionalCredentials, t as aiGatewayAsks, u as gatewayDiagnostics } from "./definition-BVc8HZWs.js";
|
|
2
|
-
//#region src/chatgpt.ts
|
|
3
|
-
/** Use a ChatGPT Connection with a Codex Driver or a model-backed Driver. Defaults to the `chatgpt` Connection. */
|
|
4
|
-
function chatgpt(options = {}) {
|
|
5
|
-
const connection = options.connection ?? "chatgpt";
|
|
6
|
-
if (Object.keys(options).some((key) => key !== "connection") || typeof connection !== "string" || !connection.trim() || connection !== connection.trim()) throw gatewayDiagnostics.GATEWAYS_R0001({ message: "[vitehub] chatgpt() accepts only a non-empty Connection name: chatgpt({ connection: \"chatgpt\" })." });
|
|
7
|
-
return Object.freeze({
|
|
8
|
-
kind: "chatgpt",
|
|
9
|
-
name: "chatgpt",
|
|
10
|
-
connection
|
|
11
|
-
});
|
|
12
|
-
}
|
|
13
|
-
function isChatGPTGateway(value) {
|
|
14
|
-
return typeof value === "object" && value !== null && "kind" in value && value.kind === "chatgpt" && "name" in value && value.name === "chatgpt" && "connection" in value && typeof value.connection === "string" && value.connection.length > 0 && value.connection === value.connection.trim() && Object.keys(value).every((key) => [
|
|
15
|
-
"kind",
|
|
16
|
-
"name",
|
|
17
|
-
"connection"
|
|
18
|
-
].includes(key));
|
|
19
|
-
}
|
|
20
|
-
//#endregion
|
|
21
|
-
//#region src/env.ts
|
|
22
|
-
const aiGatewayEnv = {
|
|
23
|
-
anthropic: { apiKey: {
|
|
24
|
-
names: ["ANTHROPIC_API_KEY"],
|
|
25
|
-
secret: true
|
|
26
|
-
} },
|
|
27
|
-
cliproxy: {
|
|
28
|
-
apiKey: {
|
|
29
|
-
names: ["CLIPROXY_API_KEY"],
|
|
30
|
-
secret: true
|
|
31
|
-
},
|
|
32
|
-
url: { names: ["CLIPROXY_URL"] }
|
|
33
|
-
},
|
|
34
|
-
cloudflare: {
|
|
35
|
-
accountId: { names: ["CLOUDFLARE_ACCOUNT_ID"] },
|
|
36
|
-
gatewayId: { names: ["CLOUDFLARE_AI_GATEWAY_ID"] },
|
|
37
|
-
providerApiKey: {
|
|
38
|
-
names: ["CLOUDFLARE_AI_GATEWAY_API_KEY"],
|
|
39
|
-
secret: true
|
|
40
|
-
},
|
|
41
|
-
slug: { names: ["CLOUDFLARE_AI_GATEWAY_SLUG"] },
|
|
42
|
-
token: {
|
|
43
|
-
names: ["CLOUDFLARE_AI_GATEWAY_TOKEN"],
|
|
44
|
-
secret: true
|
|
45
|
-
},
|
|
46
|
-
typesafeApiKey: {
|
|
47
|
-
names: ["TYPESAFE_API_KEY"],
|
|
48
|
-
secret: true
|
|
49
|
-
}
|
|
50
|
-
},
|
|
51
|
-
cloudflareAccess: {
|
|
52
|
-
clientId: {
|
|
53
|
-
names: ["CF_ACCESS_CLIENT_ID"],
|
|
54
|
-
secret: true
|
|
55
|
-
},
|
|
56
|
-
clientSecret: {
|
|
57
|
-
names: ["CF_ACCESS_CLIENT_SECRET"],
|
|
58
|
-
secret: true
|
|
59
|
-
}
|
|
60
|
-
},
|
|
61
|
-
litellm: {
|
|
62
|
-
apiKey: {
|
|
63
|
-
names: ["LITELLM_API_KEY"],
|
|
64
|
-
secret: true
|
|
65
|
-
},
|
|
66
|
-
url: { names: ["LITELLM_URL"] }
|
|
67
|
-
},
|
|
68
|
-
ollama: {
|
|
69
|
-
apiKey: {
|
|
70
|
-
names: ["OLLAMA_API_KEY"],
|
|
71
|
-
secret: true
|
|
72
|
-
},
|
|
73
|
-
url: { names: ["OLLAMA_URL"] }
|
|
74
|
-
},
|
|
75
|
-
openai: { apiKey: {
|
|
76
|
-
names: ["OPENAI_API_KEY"],
|
|
77
|
-
secret: true
|
|
78
|
-
} },
|
|
79
|
-
openrouter: { apiKey: {
|
|
80
|
-
names: ["OPENROUTER_API_KEY"],
|
|
81
|
-
secret: true
|
|
82
|
-
} },
|
|
83
|
-
typesafe: {
|
|
84
|
-
apiKey: {
|
|
85
|
-
names: ["TYPESAFE_API_KEY"],
|
|
86
|
-
secret: true
|
|
87
|
-
},
|
|
88
|
-
model: { names: ["TYPESAFE_DEFAULT_MODEL"] }
|
|
89
|
-
},
|
|
90
|
-
vercel: {
|
|
91
|
-
apiKey: {
|
|
92
|
-
names: ["AI_GATEWAY_API_KEY"],
|
|
93
|
-
secret: true
|
|
94
|
-
},
|
|
95
|
-
oidcToken: {
|
|
96
|
-
names: ["VERCEL_OIDC_TOKEN"],
|
|
97
|
-
secret: true
|
|
98
|
-
}
|
|
99
|
-
}
|
|
100
|
-
};
|
|
101
|
-
const fields = aiGatewayEnv;
|
|
102
|
-
function nameParts(segment) {
|
|
103
|
-
return segment.replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1_$2").split(/[^A-Za-z0-9]+/).filter(Boolean).map((part) => part.toUpperCase());
|
|
104
|
-
}
|
|
105
|
-
/** The variables of one preset value in lookup order: `VITEHUB_<PRESET>_<FIELD>`, then the vendor names. */
|
|
106
|
-
function aiGatewayEnvNames(preset, field) {
|
|
107
|
-
const vendor = fields[preset]?.[field]?.names ?? [];
|
|
108
|
-
return [.../* @__PURE__ */ new Set([[
|
|
109
|
-
"VITEHUB",
|
|
110
|
-
...nameParts(preset),
|
|
111
|
-
...nameParts(field)
|
|
112
|
-
].join("_"), ...vendor])];
|
|
113
|
-
}
|
|
114
|
-
/** The vendor names of one preset value, for diagnostics. */
|
|
115
|
-
function aiGatewayVendorNames(preset, field) {
|
|
116
|
-
return fields[preset]?.[field]?.names ?? [];
|
|
117
|
-
}
|
|
118
|
-
/** One preset value from `context.env`, else from `process.env`. An empty variable counts as unset. */
|
|
119
|
-
async function readAiGatewayEnv(context, preset, field) {
|
|
120
|
-
if (context.env) return await context.env(preset, field);
|
|
121
|
-
return aiGatewayEnvNames(preset, field).map((name) => globalThis.process?.env?.[name]).find((value) => value !== void 0 && value !== "");
|
|
122
|
-
}
|
|
123
|
-
//#endregion
|
|
124
|
-
//#region src/jev.ts
|
|
125
|
-
async function loadAdvocaat() {
|
|
126
|
-
try {
|
|
127
|
-
return await import("advocaat");
|
|
128
|
-
} catch (error) {
|
|
129
|
-
throw gatewayDiagnostics.GATEWAYS_R0006({
|
|
130
|
-
message: "[vitehub] TypeSafe Jev requests require the advocaat package. Install it with: pnpm add advocaat",
|
|
131
|
-
cause: error
|
|
132
|
-
});
|
|
133
|
-
}
|
|
134
|
-
}
|
|
135
|
-
function isObject(value) {
|
|
136
|
-
return typeof value === "object" && value !== null;
|
|
137
|
-
}
|
|
138
|
-
/** The custom provider URL of a Cloudflare AI Gateway. The TypeSafe client appends `/v1/systemone`. */
|
|
139
|
-
function cloudflareJevBaseURL(gateway) {
|
|
140
|
-
const segment = (value) => encodeURIComponent(value.trim());
|
|
141
|
-
return `https://gateway.ai.cloudflare.com/v1/${segment(gateway.accountId)}/${segment(gateway.gatewayId)}/custom-${segment(gateway.slug?.trim() || "typesafe")}`;
|
|
142
|
-
}
|
|
143
|
-
function toEntry(value) {
|
|
144
|
-
const serialized = JSON.stringify(value);
|
|
145
|
-
const parsed = serialized === void 0 ? null : JSON.parse(serialized);
|
|
146
|
-
return typeof parsed === "number" || typeof parsed === "boolean" ? String(parsed) : parsed;
|
|
147
|
-
}
|
|
148
|
-
function invalidQuestion(name) {
|
|
149
|
-
return gatewayDiagnostics.GATEWAYS_R0007({ message: `[vitehub] Jev question "${name}" must be built with ask.choice(), ask.score(), ask.chance(), ask.if(), or ask.switch().` });
|
|
150
|
-
}
|
|
151
|
-
function validateQuestionCriteria(name, question) {
|
|
152
|
-
if (question.type === "if" && (!Number.isFinite(question.threshold) || question.threshold < 0 || question.threshold > 1)) throw gatewayDiagnostics.GATEWAYS_R0007({ message: `[vitehub] Jev question "${name}" threshold must be a finite number between 0 and 1.` });
|
|
153
|
-
if (question.type === "choice" || question.type === "switch") {
|
|
154
|
-
const count = isObject(question.criteria) && !Array.isArray(question.criteria) ? Object.keys(question.criteria).length : 0;
|
|
155
|
-
if (count < 2 || count > 255) throw gatewayDiagnostics.GATEWAYS_R0007({ message: `[vitehub] Jev question "${name}" ${question.type} criteria must have between 2 and 255 choices.` });
|
|
156
|
-
} else if (question.type === "score") {
|
|
157
|
-
const count = Array.isArray(question.criteria) ? question.criteria.length : 0;
|
|
158
|
-
if (count < 2 || count > 10) throw gatewayDiagnostics.GATEWAYS_R0007({ message: `[vitehub] Jev question "${name}" score criteria must have between 2 and 10 levels.` });
|
|
159
|
-
}
|
|
160
|
-
}
|
|
161
|
-
function hasValidChoiceAnswer(question, answer) {
|
|
162
|
-
if (!isObject(answer) || answer.type !== "choice" || typeof answer.choice !== "string" || !isObject(answer.probabilities)) return false;
|
|
163
|
-
if (typeof answer.confidence !== "number" || !Number.isFinite(answer.confidence) || answer.confidence < 0 || answer.confidence > 1) return false;
|
|
164
|
-
if (!isObject(question.criteria) || !Object.hasOwn(question.criteria, answer.choice)) return false;
|
|
165
|
-
const probabilities = answer.probabilities;
|
|
166
|
-
const labels = Object.keys(question.criteria);
|
|
167
|
-
const probabilityLabels = Object.keys(probabilities);
|
|
168
|
-
if (labels.length !== probabilityLabels.length || probabilityLabels.some((label) => !Object.hasOwn(question.criteria, label))) return false;
|
|
169
|
-
const total = labels.reduce((sum, label) => {
|
|
170
|
-
const probability = probabilities[label];
|
|
171
|
-
return sum + (typeof probability === "number" && Number.isFinite(probability) && probability >= 0 && probability <= 1 ? probability : NaN);
|
|
172
|
-
}, 0);
|
|
173
|
-
return Number.isFinite(total) && Math.abs(total - 1) <= 1e-6;
|
|
174
|
-
}
|
|
175
|
-
function finiteNumber(value) {
|
|
176
|
-
return typeof value === "number" && Number.isFinite(value) ? value : void 0;
|
|
177
|
-
}
|
|
178
|
-
/** The SDK question for one Jev request: `if` asks a yes/no question and `switch` asks a choice. */
|
|
179
|
-
function toJevQuestion(question) {
|
|
180
|
-
if (question.type === "if") return {
|
|
181
|
-
instructions: question.instructions,
|
|
182
|
-
type: "noul"
|
|
183
|
-
};
|
|
184
|
-
if (question.type === "switch") return {
|
|
185
|
-
criteria: question.criteria,
|
|
186
|
-
instructions: question.instructions,
|
|
187
|
-
type: "choice"
|
|
188
|
-
};
|
|
189
|
-
return question;
|
|
190
|
-
}
|
|
191
|
-
/**
|
|
192
|
-
* Sends one batch through the SDK client, which also returns the model and the token usage,
|
|
193
|
-
* and maps the answers as `advocaat.ask()` does.
|
|
194
|
-
*/
|
|
195
|
-
async function requestJev(advocaat, state, batch, options) {
|
|
196
|
-
const { apiKey, baseURL, fetch, headers, protocol, signal } = options;
|
|
197
|
-
const wire = Object.fromEntries(Object.entries(batch).map(([name, question]) => [name, toJevQuestion(question)]));
|
|
198
|
-
const client = {
|
|
199
|
-
...apiKey ? { apiKey } : {},
|
|
200
|
-
...baseURL ? { baseURL } : {},
|
|
201
|
-
...fetch ? { fetch } : {},
|
|
202
|
-
...options.model ? { model: options.model } : {},
|
|
203
|
-
provider: protocol
|
|
204
|
-
};
|
|
205
|
-
const result = await advocaat.typesafe(client).systemOne({
|
|
206
|
-
questions: wire,
|
|
207
|
-
state
|
|
208
|
-
}, {
|
|
209
|
-
...headers ? { headers } : {},
|
|
210
|
-
signal
|
|
211
|
-
});
|
|
212
|
-
const answers = Object.create(null);
|
|
213
|
-
for (const [name, answer] of Object.entries(result.answers)) {
|
|
214
|
-
const question = batch[name];
|
|
215
|
-
if (answer.type === "noul") answers[name] = question?.type === "if" ? answer.noul > question.threshold : {
|
|
216
|
-
chance: answer.noul,
|
|
217
|
-
type: "chance"
|
|
218
|
-
};
|
|
219
|
-
else if (answer.type === "score") answers[name] = question?.type === "score" ? {
|
|
220
|
-
...answer,
|
|
221
|
-
ratio: answer.score / (question.criteria.length - 1)
|
|
222
|
-
} : answer;
|
|
223
|
-
else answers[name] = question?.type === "switch" ? answer.choice : answer;
|
|
224
|
-
}
|
|
225
|
-
const model = result.model;
|
|
226
|
-
const usage = result.usage;
|
|
227
|
-
return {
|
|
228
|
-
answers,
|
|
229
|
-
...typeof model === "string" && model ? { model } : {},
|
|
230
|
-
...isObject(usage) ? { usage: {
|
|
231
|
-
inputTokens: finiteNumber(usage.input_tokens),
|
|
232
|
-
outputTokens: finiteNumber(usage.output_tokens)
|
|
233
|
-
} } : {}
|
|
234
|
-
};
|
|
235
|
-
}
|
|
236
|
-
const retryableJevStatuses = /* @__PURE__ */ new Set([
|
|
237
|
-
408,
|
|
238
|
-
429,
|
|
239
|
-
500,
|
|
240
|
-
502,
|
|
241
|
-
503,
|
|
242
|
-
504
|
|
243
|
-
]);
|
|
244
|
-
const jevAttempts = 3;
|
|
245
|
-
function errorStatus(error) {
|
|
246
|
-
if (!isObject(error)) return void 0;
|
|
247
|
-
const status = Number.isInteger(error.statusCode) ? Number(error.statusCode) : error.status;
|
|
248
|
-
return Number.isInteger(status) ? Number(status) : void 0;
|
|
249
|
-
}
|
|
250
|
-
function errorRequestId(error) {
|
|
251
|
-
return isObject(error) && typeof error.requestId === "string" && error.requestId ? error.requestId : void 0;
|
|
252
|
-
}
|
|
253
|
-
function waitForRetry(attempt, signal) {
|
|
254
|
-
const delay = 250 * 2 ** attempt * (.75 + Math.random() / 2);
|
|
255
|
-
return new Promise((resolve, reject) => {
|
|
256
|
-
const timer = setTimeout(() => {
|
|
257
|
-
signal?.removeEventListener("abort", abort);
|
|
258
|
-
resolve();
|
|
259
|
-
}, delay);
|
|
260
|
-
function abort() {
|
|
261
|
-
clearTimeout(timer);
|
|
262
|
-
reject(signal?.reason);
|
|
263
|
-
}
|
|
264
|
-
signal?.addEventListener("abort", abort, { once: true });
|
|
265
|
-
});
|
|
266
|
-
}
|
|
267
|
-
/**
|
|
268
|
-
* Sends one batch and retries transient provider failures. Jev questions do not change state, so a retry is safe.
|
|
269
|
-
* A rejected key fails at once with GATEWAYS_R0008. A provider that keeps failing ends with GATEWAYS_R0009.
|
|
270
|
-
* Both keep the provider error as `cause` and expose `status`, `providerStatus`, and `requestId`.
|
|
271
|
-
*/
|
|
272
|
-
async function requestJevWithRetry(advocaat, state, batch, options) {
|
|
273
|
-
const provider = options.label;
|
|
274
|
-
for (let attempt = 0;; attempt++) try {
|
|
275
|
-
return [void 0, await requestJev(advocaat, state, batch, options)];
|
|
276
|
-
} catch (error) {
|
|
277
|
-
if (options.signal?.aborted) throw error;
|
|
278
|
-
const status = errorStatus(error);
|
|
279
|
-
const details = {
|
|
280
|
-
cause: error,
|
|
281
|
-
providerStatus: status,
|
|
282
|
-
requestId: errorRequestId(error)
|
|
283
|
-
};
|
|
284
|
-
if (status === 401 || status === 403) return [Object.assign(gatewayDiagnostics.GATEWAYS_R0008({
|
|
285
|
-
provider,
|
|
286
|
-
status,
|
|
287
|
-
env: options.keyEnv,
|
|
288
|
-
option: options.keyOption,
|
|
289
|
-
cause: error
|
|
290
|
-
}), {
|
|
291
|
-
...details,
|
|
292
|
-
providerStatus: status,
|
|
293
|
-
status: 503
|
|
294
|
-
}), void 0];
|
|
295
|
-
if (!(status === void 0 ? error instanceof TypeError && isObject(error) && "cause" in error : retryableJevStatuses.has(status))) throw error;
|
|
296
|
-
if (attempt + 1 >= jevAttempts) return [Object.assign(gatewayDiagnostics.GATEWAYS_R0009({
|
|
297
|
-
provider,
|
|
298
|
-
status,
|
|
299
|
-
attempts: jevAttempts,
|
|
300
|
-
cause: error
|
|
301
|
-
}), {
|
|
302
|
-
...details,
|
|
303
|
-
status: 502
|
|
304
|
-
}), void 0];
|
|
305
|
-
await waitForRetry(attempt, options.signal);
|
|
306
|
-
}
|
|
307
|
-
}
|
|
308
|
-
/** The usage record of one Jev request, or undefined when the response has no token counts. */
|
|
309
|
-
function jevUsageRecord(provider, response) {
|
|
310
|
-
const inputTokens = response.usage?.inputTokens;
|
|
311
|
-
const outputTokens = response.usage?.outputTokens;
|
|
312
|
-
if (inputTokens === void 0 && outputTokens === void 0) return void 0;
|
|
313
|
-
return {
|
|
314
|
-
...response.model ? { model: response.model } : {},
|
|
315
|
-
provider,
|
|
316
|
-
usage: {
|
|
317
|
-
...inputTokens !== void 0 ? { inputTokens } : {},
|
|
318
|
-
...outputTokens !== void 0 ? { outputTokens } : {},
|
|
319
|
-
...inputTokens !== void 0 && outputTokens !== void 0 ? { totalTokens: inputTokens + outputTokens } : {}
|
|
320
|
-
}
|
|
321
|
-
};
|
|
322
|
-
}
|
|
323
|
-
/** The value a person reads first: the selected label, the score, the chance, or the boolean. */
|
|
324
|
-
function jevAnswerValue(answer) {
|
|
325
|
-
if (!isObject(answer)) return answer;
|
|
326
|
-
if (answer.type === "choice") return answer.choice;
|
|
327
|
-
if (answer.type === "score") return answer.score;
|
|
328
|
-
if (answer.type === "chance") return answer.chance;
|
|
329
|
-
}
|
|
330
|
-
/**
|
|
331
|
-
* Records each question of one Jev request as `agent.tool.start`, then `agent.tool.finish` or `agent.tool.error`,
|
|
332
|
-
* and the token usage of the request as `agent.usage.recorded`. Without an observer, nothing is recorded.
|
|
333
|
-
*/
|
|
334
|
-
async function observeJevBatch(observe, options, questions, batch, position) {
|
|
335
|
-
const names = Object.keys(batch);
|
|
336
|
-
const startedAt = Date.now();
|
|
337
|
-
const settled = /* @__PURE__ */ new Set();
|
|
338
|
-
const emit = async (event) => {
|
|
339
|
-
try {
|
|
340
|
-
await observe?.(event);
|
|
341
|
-
} catch {}
|
|
342
|
-
};
|
|
343
|
-
const batchAttributes = {
|
|
344
|
-
"ask.batch.count": position.count,
|
|
345
|
-
"ask.batch.index": position.index,
|
|
346
|
-
"ask.batch.size": names.length,
|
|
347
|
-
"gen_ai.operation.name": "ask",
|
|
348
|
-
"gen_ai.provider.name": options.provider
|
|
349
|
-
};
|
|
350
|
-
const questionAttributes = (name) => ({
|
|
351
|
-
...batchAttributes,
|
|
352
|
-
...options.model ? { "ask.model": options.model } : {},
|
|
353
|
-
"ask.key": name,
|
|
354
|
-
"ask.type": questions[name]?.type,
|
|
355
|
-
"step.id": `ask:${name}`,
|
|
356
|
-
"tool.id": `ask:${name}`,
|
|
357
|
-
"tool.name": "ask",
|
|
358
|
-
"vitehub.activity.kind": "tool"
|
|
359
|
-
});
|
|
360
|
-
if (observe) for (const name of names) await emit({
|
|
361
|
-
attributes: {
|
|
362
|
-
...questionAttributes(name),
|
|
363
|
-
"tool.hasInput": true,
|
|
364
|
-
"tool.input": batch[name]
|
|
365
|
-
},
|
|
366
|
-
name: "agent.tool.start",
|
|
367
|
-
type: "run"
|
|
368
|
-
});
|
|
369
|
-
return {
|
|
370
|
-
async answered(name, answer, model) {
|
|
371
|
-
settled.add(name);
|
|
372
|
-
if (!observe) return;
|
|
373
|
-
const value = jevAnswerValue(answer);
|
|
374
|
-
const confidence = isObject(answer) ? finiteNumber(answer.confidence) : void 0;
|
|
375
|
-
const probabilities = isObject(answer) && isObject(answer.probabilities) ? { ...answer.probabilities } : void 0;
|
|
376
|
-
await emit({
|
|
377
|
-
attributes: {
|
|
378
|
-
...questionAttributes(name),
|
|
379
|
-
...model ? { "ask.model": model } : {},
|
|
380
|
-
...value !== void 0 ? { "ask.answer": value } : {},
|
|
381
|
-
...confidence !== void 0 ? { "ask.confidence": confidence } : {},
|
|
382
|
-
...probabilities ? { "ask.probabilities": probabilities } : {},
|
|
383
|
-
"tool.durationMs": Date.now() - startedAt,
|
|
384
|
-
"tool.hasOutput": true,
|
|
385
|
-
"tool.output": answer
|
|
386
|
-
},
|
|
387
|
-
name: "agent.tool.finish",
|
|
388
|
-
type: "run"
|
|
389
|
-
});
|
|
390
|
-
},
|
|
391
|
-
async failed(error) {
|
|
392
|
-
if (!observe) return;
|
|
393
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
394
|
-
const status = isObject(error) && Number.isInteger(error.providerStatus) ? error.providerStatus : errorStatus(error);
|
|
395
|
-
const requestId = errorRequestId(error);
|
|
396
|
-
for (const name of names) {
|
|
397
|
-
if (settled.has(name)) continue;
|
|
398
|
-
settled.add(name);
|
|
399
|
-
await emit({
|
|
400
|
-
attributes: {
|
|
401
|
-
...questionAttributes(name),
|
|
402
|
-
"error.message": message,
|
|
403
|
-
...error instanceof Error ? { "error.name": error.name } : {},
|
|
404
|
-
...status !== void 0 ? { "error.status": status } : {},
|
|
405
|
-
...requestId ? { "error.requestId": requestId } : {},
|
|
406
|
-
"tool.durationMs": Date.now() - startedAt,
|
|
407
|
-
"tool.error": message
|
|
408
|
-
},
|
|
409
|
-
name: "agent.tool.error",
|
|
410
|
-
type: "error"
|
|
411
|
-
});
|
|
412
|
-
}
|
|
413
|
-
},
|
|
414
|
-
async usage(response) {
|
|
415
|
-
if (!observe || !response.usage) return;
|
|
416
|
-
const { inputTokens, outputTokens } = response.usage;
|
|
417
|
-
await emit({
|
|
418
|
-
attributes: {
|
|
419
|
-
...batchAttributes,
|
|
420
|
-
"ask.durationMs": Date.now() - startedAt,
|
|
421
|
-
"usage.hasCost": false,
|
|
422
|
-
"usage.hasRaw": false,
|
|
423
|
-
...inputTokens !== void 0 ? { "usage.inputTokens": inputTokens } : {},
|
|
424
|
-
...response.model ? { "usage.model": response.model } : {},
|
|
425
|
-
...outputTokens !== void 0 ? { "usage.outputTokens": outputTokens } : {},
|
|
426
|
-
"usage.provider": options.provider,
|
|
427
|
-
...inputTokens !== void 0 && outputTokens !== void 0 ? { "usage.totalTokens": inputTokens + outputTokens } : {}
|
|
428
|
-
},
|
|
429
|
-
name: "agent.usage.recorded",
|
|
430
|
-
type: "run"
|
|
431
|
-
});
|
|
432
|
-
}
|
|
433
|
-
};
|
|
434
|
-
}
|
|
435
|
-
function toAdvocaatQuestion(name, question) {
|
|
436
|
-
validateQuestionCriteria(name, question);
|
|
437
|
-
const instructions = toEntry(question.instructions);
|
|
438
|
-
switch (question.type) {
|
|
439
|
-
case "chance": return {
|
|
440
|
-
criteria: question.criteria ? Object.fromEntries(Object.entries(question.criteria).map(([key, value]) => [key, toEntry(value)])) : void 0,
|
|
441
|
-
instructions,
|
|
442
|
-
type: "noul"
|
|
443
|
-
};
|
|
444
|
-
case "choice":
|
|
445
|
-
case "switch": return {
|
|
446
|
-
...question,
|
|
447
|
-
instructions,
|
|
448
|
-
criteria: Object.fromEntries(Object.entries(question.criteria).map(([key, value]) => [key, toEntry(value)]))
|
|
449
|
-
};
|
|
450
|
-
case "score": {
|
|
451
|
-
const [first, second, ...rest] = question.criteria;
|
|
452
|
-
return {
|
|
453
|
-
...question,
|
|
454
|
-
instructions,
|
|
455
|
-
criteria: [
|
|
456
|
-
toEntry(first),
|
|
457
|
-
toEntry(second),
|
|
458
|
-
...rest.map(toEntry)
|
|
459
|
-
]
|
|
460
|
-
};
|
|
461
|
-
}
|
|
462
|
-
case "if": return question;
|
|
463
|
-
}
|
|
464
|
-
throw invalidQuestion(name);
|
|
465
|
-
}
|
|
466
|
-
/** UTF-8 serialized bytes provide a conservative token bound, with room for request framing. */
|
|
467
|
-
function jevInputSize(value) {
|
|
468
|
-
return new TextEncoder().encode(JSON.stringify(value)).byteLength;
|
|
469
|
-
}
|
|
470
|
-
function jevQuestionBatches(state, wire) {
|
|
471
|
-
const sharedSize = jevInputSize(state) + 2048;
|
|
472
|
-
const maxRequestSize = 6e4;
|
|
473
|
-
const maxQuestionSize = 3e4;
|
|
474
|
-
if (sharedSize >= maxQuestionSize) throw gatewayDiagnostics.GATEWAYS_JEV_INPUT_TOO_LARGE({});
|
|
475
|
-
const batches = [];
|
|
476
|
-
let batch = Object.create(null);
|
|
477
|
-
let size = sharedSize;
|
|
478
|
-
for (const [name, question] of Object.entries(wire)) {
|
|
479
|
-
const questionSize = jevInputSize({ [name]: question }) + 128;
|
|
480
|
-
if (sharedSize + questionSize > maxQuestionSize) throw gatewayDiagnostics.GATEWAYS_JEV_INPUT_TOO_LARGE({ question: name });
|
|
481
|
-
if (size + questionSize > maxRequestSize && Object.keys(batch).length) {
|
|
482
|
-
batches.push(batch);
|
|
483
|
-
batch = Object.create(null);
|
|
484
|
-
size = sharedSize;
|
|
485
|
-
}
|
|
486
|
-
batch[name] = question;
|
|
487
|
-
size += questionSize;
|
|
488
|
-
}
|
|
489
|
-
if (Object.keys(batch).length) batches.push(batch);
|
|
490
|
-
return batches;
|
|
491
|
-
}
|
|
492
|
-
/** Runs independent keyed questions in bounded Jev requests; empty questions require no credentials or API call. */
|
|
493
|
-
async function askJev(context, state, questions) {
|
|
494
|
-
if (!isObject(questions) || Array.isArray(questions)) throw gatewayDiagnostics.GATEWAYS_R0007({ message: "[vitehub] Jev questions must be an object of questions built with ask." });
|
|
495
|
-
const wire = Object.fromEntries(Object.entries(questions).map(([name, question]) => {
|
|
496
|
-
if (!isObject(question)) throw invalidQuestion(name);
|
|
497
|
-
return [name, toAdvocaatQuestion(name, question)];
|
|
498
|
-
}));
|
|
499
|
-
if (!Object.keys(wire).length) return [void 0, {}];
|
|
500
|
-
const entry = toEntry(state);
|
|
501
|
-
const batches = jevQuestionBatches(entry, wire);
|
|
502
|
-
const advocaat = await loadAdvocaat();
|
|
503
|
-
const options = await context.route();
|
|
504
|
-
const output = Object.create(null);
|
|
505
|
-
for (const [batchIndex, batch] of batches.entries()) {
|
|
506
|
-
context.abortSignal?.throwIfAborted();
|
|
507
|
-
const observed = await observeJevBatch(context.observe, {
|
|
508
|
-
...options.model ? { model: options.model } : {},
|
|
509
|
-
provider: options.name
|
|
510
|
-
}, questions, batch, {
|
|
511
|
-
count: batches.length,
|
|
512
|
-
index: batchIndex
|
|
513
|
-
});
|
|
514
|
-
try {
|
|
515
|
-
const [error, response] = await requestJevWithRetry(advocaat, entry, batch, {
|
|
516
|
-
...options,
|
|
517
|
-
signal: context.abortSignal
|
|
518
|
-
});
|
|
519
|
-
if (error) {
|
|
520
|
-
await observed.failed(error);
|
|
521
|
-
return [error, void 0];
|
|
522
|
-
}
|
|
523
|
-
await observed.usage(response);
|
|
524
|
-
const usage = jevUsageRecord(options.name, response);
|
|
525
|
-
if (usage) context.recordUsage?.(usage);
|
|
526
|
-
context.abortSignal?.throwIfAborted();
|
|
527
|
-
for (const name of Object.keys(batch)) {
|
|
528
|
-
if (!Object.hasOwn(response.answers, name)) throw gatewayDiagnostics.GATEWAYS_JEV_RESPONSE_INVALID({
|
|
529
|
-
name,
|
|
530
|
-
problem: "missing"
|
|
531
|
-
});
|
|
532
|
-
const answer = response.answers[name];
|
|
533
|
-
const question = questions[name];
|
|
534
|
-
if (question.type === "choice" && !hasValidChoiceAnswer(question, answer)) throw gatewayDiagnostics.GATEWAYS_JEV_RESPONSE_INVALID({
|
|
535
|
-
name,
|
|
536
|
-
problem: "choice"
|
|
537
|
-
});
|
|
538
|
-
const scoreAnswer = isObject(answer) && answer.type === "score" ? answer : void 0;
|
|
539
|
-
output[name] = question?.type === "score" && scoreAnswer ? {
|
|
540
|
-
...scoreAnswer,
|
|
541
|
-
legend: Object.fromEntries(question.criteria.map((level, index) => [String(index), level]))
|
|
542
|
-
} : answer;
|
|
543
|
-
await observed.answered(name, output[name], response.model);
|
|
544
|
-
}
|
|
545
|
-
} catch (error) {
|
|
546
|
-
await observed.failed(error);
|
|
547
|
-
throw error;
|
|
548
|
-
}
|
|
549
|
-
}
|
|
550
|
-
return [void 0, Object.fromEntries(Object.entries(output))];
|
|
551
|
-
}
|
|
552
|
-
//#endregion
|
|
553
|
-
//#region src/presets.ts
|
|
554
|
-
function origin(url, label) {
|
|
555
|
-
if (typeof url !== "string" || !url.trim()) throw gatewayDiagnostics.GATEWAYS_R0001({ message: `[vitehub] ${label}({ url }) must be a non-empty URL.` });
|
|
556
|
-
return url.trim().replace(/\/+$/, "").replace(/\/v1$/, "");
|
|
557
|
-
}
|
|
558
|
-
function present(value) {
|
|
559
|
-
return isRecord(value) || typeof value === "string" && value.trim() !== "";
|
|
560
|
-
}
|
|
561
|
-
/** A resolver that reads one Server Env value and names its variables when the value is missing. */
|
|
562
|
-
function requiredEnv(preset, field, missing) {
|
|
563
|
-
return async (context) => {
|
|
564
|
-
const value = await readAiGatewayEnv(context, preset, field);
|
|
565
|
-
return present(value) ? value : missing(aiGatewayVendorNames(preset, field).join(" or "));
|
|
566
|
-
};
|
|
567
|
-
}
|
|
568
|
-
function apiKeyFromEnv(gateway) {
|
|
569
|
-
return requiredEnv(gateway, "apiKey", (names) => {
|
|
570
|
-
throw gatewayDiagnostics.GATEWAYS_R0002({ message: `[vitehub] Gateway "${gateway}" needs an API key. Set ${names}, or pass apiKey.` });
|
|
571
|
-
});
|
|
572
|
-
}
|
|
573
|
-
/** Base URLs for a hosted gateway. Without `url`, each invocation reads it from Server Env. */
|
|
574
|
-
function hostedBaseURL(gateway, url, fallback) {
|
|
575
|
-
if (url !== void 0 || fallback !== void 0) {
|
|
576
|
-
const root = origin(url ?? fallback, gateway);
|
|
577
|
-
return {
|
|
578
|
-
"codex": `${root}/v1`,
|
|
579
|
-
"claude-code": root,
|
|
580
|
-
"openai-compatible": `${root}/v1`
|
|
581
|
-
};
|
|
582
|
-
}
|
|
583
|
-
const read = requiredEnv(gateway, "url", (names) => {
|
|
584
|
-
throw gatewayDiagnostics.GATEWAYS_R0004({ message: `[vitehub] Gateway "${gateway}" needs a URL. Set ${names}, or pass url.` });
|
|
585
|
-
});
|
|
586
|
-
return {
|
|
587
|
-
"codex": async (context) => `${origin(await read(context), gateway)}/v1`,
|
|
588
|
-
"claude-code": async (context) => origin(await read(context), gateway),
|
|
589
|
-
"openai-compatible": async (context) => `${origin(await read(context), gateway)}/v1`
|
|
590
|
-
};
|
|
591
|
-
}
|
|
592
|
-
/** The route resolver of an ask gateway. ViteHub Agents call it with their Server Env context. */
|
|
593
|
-
const aiGatewayAskRoute = Symbol.for("vitehub.aiGateway.askRoute");
|
|
594
|
-
function jevRoute(name, spec) {
|
|
595
|
-
return async (context) => {
|
|
596
|
-
const resolvedKey = await resolveAiGatewaySecret(spec.apiKey, context);
|
|
597
|
-
const oidcToken = resolvedKey ? void 0 : await resolveAiGatewaySecret(spec.oidcToken, context);
|
|
598
|
-
const apiKey = resolvedKey ?? oidcToken;
|
|
599
|
-
if (!apiKey) throw gatewayDiagnostics.GATEWAYS_R0002({ message: spec.keyEnv ? `[vitehub] Gateway "${name}" needs an API key. Set ${spec.keyEnv}, or pass apiKey.` : `[vitehub] Gateway "${name}" apiKey resolved to an empty value.` });
|
|
600
|
-
const headers = {};
|
|
601
|
-
for (const [header, input] of Object.entries(spec.optionalHeaders ?? {})) {
|
|
602
|
-
const value = await resolveAiGatewaySecret(input, context);
|
|
603
|
-
if (value) headers[header] = value;
|
|
604
|
-
}
|
|
605
|
-
for (const [header, input] of Object.entries(spec.headers ?? {})) {
|
|
606
|
-
const value = await resolveAiGatewaySecret(input, context);
|
|
607
|
-
if (!value) throw gatewayDiagnostics.GATEWAYS_R0003({ message: `[vitehub] Gateway "${name}" header "${header}" resolved to an empty value.` });
|
|
608
|
-
if (/[\r\n]/.test(value)) throw gatewayDiagnostics.GATEWAYS_R0003({ message: `[vitehub] Gateway "${name}" header "${header}" must not contain line breaks.` });
|
|
609
|
-
headers[header] = value;
|
|
610
|
-
}
|
|
611
|
-
if (oidcToken) headers["ai-gateway-auth-method"] = "oidc";
|
|
612
|
-
return {
|
|
613
|
-
...apiKey ? { apiKey } : {},
|
|
614
|
-
baseURL: await spec.baseURL(context),
|
|
615
|
-
...spec.fetch ? { fetch: spec.fetch } : {},
|
|
616
|
-
...Object.keys(headers).length ? { headers } : {},
|
|
617
|
-
...spec.keyEnv ? { keyEnv: spec.keyEnv } : {},
|
|
618
|
-
...spec.keyOption ? { keyOption: spec.keyOption } : {},
|
|
619
|
-
label: spec.label,
|
|
620
|
-
model: typeof spec.model === "string" ? spec.model : await spec.model(context),
|
|
621
|
-
name,
|
|
622
|
-
protocol: spec.protocol
|
|
623
|
-
};
|
|
624
|
-
};
|
|
625
|
-
}
|
|
626
|
-
/** Asks through a gateway with a resolver context, observers, and usage records. ViteHub Agents use it for `driver.ask`. */
|
|
627
|
-
async function askAiGateway(gateway, state, questions, options = {}) {
|
|
628
|
-
const route = Reflect.get(gateway, aiGatewayAskRoute);
|
|
629
|
-
if (typeof route !== "function") return await unsupportedAsk(gateway.name)(state, questions);
|
|
630
|
-
const context = {
|
|
631
|
-
...options.context,
|
|
632
|
-
...options.signal ? { abortSignal: options.signal } : {}
|
|
633
|
-
};
|
|
634
|
-
return await askJev({
|
|
635
|
-
...options.signal ? { abortSignal: options.signal } : {},
|
|
636
|
-
...options.observe ? { observe: options.observe } : {},
|
|
637
|
-
...options.onUsage ? { recordUsage: options.onUsage } : {},
|
|
638
|
-
route: async () => await route(context)
|
|
639
|
-
}, state, questions);
|
|
640
|
-
}
|
|
641
|
-
function unsupportedAsk(name) {
|
|
642
|
-
return async () => {
|
|
643
|
-
throw gatewayDiagnostics.GATEWAYS_R0005({ message: `[vitehub] Gateway "${name}" routes model requests and cannot answer Jev questions. Use typesafe(), vercel(), or cloudflare() for ask().` });
|
|
644
|
-
};
|
|
645
|
-
}
|
|
646
|
-
function createAiGateway(definition, route, optional, modelApis, modelCredentials) {
|
|
647
|
-
const routes = normalizeAiGateway(route ? Object.defineProperty({ ...definition }, aiGatewayAsks, { value: true }) : definition);
|
|
648
|
-
const gateway = { ...routes };
|
|
649
|
-
if (modelApis) Object.defineProperty(gateway, "modelApis", { value: Object.freeze([...modelApis]) });
|
|
650
|
-
if (optional) Object.defineProperty(gateway, aiGatewayOptionalCredentials, { value: Object.freeze({
|
|
651
|
-
...optional,
|
|
652
|
-
headers: Object.freeze([...optional.headers])
|
|
653
|
-
}) });
|
|
654
|
-
if (modelCredentials) Object.defineProperty(gateway, aiGatewayModelCredentials, { value: modelCredentials });
|
|
655
|
-
Object.defineProperty(gateway, "ask", { value: route ? (async (state, questions, options = {}) => await askAiGateway(gateway, state, questions, options)) : unsupportedAsk(routes.name) });
|
|
656
|
-
if (route) Object.defineProperties(gateway, {
|
|
657
|
-
[aiGatewayAsks]: { value: true },
|
|
658
|
-
[aiGatewayAskRoute]: { value: route }
|
|
659
|
-
});
|
|
660
|
-
return Object.freeze(gateway);
|
|
661
|
-
}
|
|
662
|
-
function preset(definition, options) {
|
|
663
|
-
const value = { ...definition };
|
|
664
|
-
if (options && Object.hasOwn(options, "apiKey")) value.apiKey = options.apiKey;
|
|
665
|
-
if (options?.headers !== void 0) value.headers = options.headers;
|
|
666
|
-
return value;
|
|
667
|
-
}
|
|
668
|
-
/** Variables of the key, or undefined when the caller passed it. */
|
|
669
|
-
function keyEnv(preset, options) {
|
|
670
|
-
if (options && Object.hasOwn(options, "apiKey")) return void 0;
|
|
671
|
-
return [...aiGatewayVendorNames(preset, "apiKey"), ...preset === "vercel" ? aiGatewayVendorNames(preset, "oidcToken") : []].join(" or ");
|
|
672
|
-
}
|
|
673
|
-
function modelGateway(definition, optional) {
|
|
674
|
-
return createAiGateway(definition, void 0, optional);
|
|
675
|
-
}
|
|
676
|
-
/**
|
|
677
|
-
* Validate a custom gateway for an endpoint without a preset. Its type lists the model APIs in `baseURL`. It routes
|
|
678
|
-
* model requests; only the `typesafe()`, `vercel()`, and `cloudflare()` presets answer Jev questions.
|
|
679
|
-
*/
|
|
680
|
-
function defineAiGateway(gateway) {
|
|
681
|
-
return modelGateway(gateway);
|
|
682
|
-
}
|
|
683
|
-
/**
|
|
684
|
-
* Cloudflare Access service-token headers for a gateway behind Access.
|
|
685
|
-
* Reads `CF_ACCESS_CLIENT_ID` and `CF_ACCESS_CLIENT_SECRET` unless you pass the values.
|
|
686
|
-
*/
|
|
687
|
-
function cloudflareAccess(options = {}) {
|
|
688
|
-
const fromEnv = (field, header) => {
|
|
689
|
-
return requiredEnv("cloudflareAccess", field, (names) => {
|
|
690
|
-
throw gatewayDiagnostics.GATEWAYS_R0003({ message: `[vitehub] Gateway header "${header}" needs a value. Set ${names}, or pass cloudflareAccess({ ${field} }).` });
|
|
691
|
-
});
|
|
692
|
-
};
|
|
693
|
-
return {
|
|
694
|
-
"CF-Access-Client-Id": Object.hasOwn(options, "clientId") ? options.clientId : fromEnv("clientId", "CF-Access-Client-Id"),
|
|
695
|
-
"CF-Access-Client-Secret": Object.hasOwn(options, "clientSecret") ? options.clientSecret : fromEnv("clientSecret", "CF-Access-Client-Secret")
|
|
696
|
-
};
|
|
697
|
-
}
|
|
698
|
-
/** [CLIProxyAPI](https://github.com/router-for-me/CLIProxyAPI). Serves Codex and Claude Code. Reads `CLIPROXY_URL` and `CLIPROXY_API_KEY`. */
|
|
699
|
-
function cliproxy(options = {}) {
|
|
700
|
-
return modelGateway(preset({
|
|
701
|
-
name: "cliproxy",
|
|
702
|
-
baseURL: hostedBaseURL("cliproxy", options.url),
|
|
703
|
-
apiKey: apiKeyFromEnv("cliproxy")
|
|
704
|
-
}, options));
|
|
705
|
-
}
|
|
706
|
-
/** [LiteLLM Proxy](https://docs.litellm.ai/docs/simple_proxy). Serves Codex and Claude Code. Reads `LITELLM_URL` and `LITELLM_API_KEY`. */
|
|
707
|
-
function litellm(options = {}) {
|
|
708
|
-
return modelGateway(preset({
|
|
709
|
-
name: "litellm",
|
|
710
|
-
baseURL: hostedBaseURL("litellm", options.url),
|
|
711
|
-
apiKey: apiKeyFromEnv("litellm")
|
|
712
|
-
}, options));
|
|
713
|
-
}
|
|
714
|
-
/** [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. */
|
|
715
|
-
function ollama(options = {}) {
|
|
716
|
-
const read = (field) => async (context) => {
|
|
717
|
-
const value = await readAiGatewayEnv(context, "ollama", field);
|
|
718
|
-
return present(value) ? value : void 0;
|
|
719
|
-
};
|
|
720
|
-
const url = read("url");
|
|
721
|
-
const root = async (context) => origin(await url(context) ?? "http://localhost:11434", "ollama");
|
|
722
|
-
return modelGateway(preset({
|
|
723
|
-
name: "ollama",
|
|
724
|
-
baseURL: options.url !== void 0 ? hostedBaseURL("ollama", options.url) : {
|
|
725
|
-
"codex": async (context) => `${await root(context)}/v1`,
|
|
726
|
-
"claude-code": root,
|
|
727
|
-
"openai-compatible": async (context) => `${await root(context)}/v1`
|
|
728
|
-
},
|
|
729
|
-
apiKey: (async (context) => await read("apiKey")(context) ?? "ollama")
|
|
730
|
-
}, options));
|
|
731
|
-
}
|
|
732
|
-
/** [OpenRouter](https://openrouter.ai/docs). Serves Codex and Claude Code. Reads `OPENROUTER_API_KEY`. */
|
|
733
|
-
function openrouter(options) {
|
|
734
|
-
return modelGateway(preset({
|
|
735
|
-
name: "openrouter",
|
|
736
|
-
baseURL: {
|
|
737
|
-
"codex": "https://openrouter.ai/api/v1",
|
|
738
|
-
"claude-code": "https://openrouter.ai/api",
|
|
739
|
-
"openai-compatible": "https://openrouter.ai/api/v1"
|
|
740
|
-
},
|
|
741
|
-
apiKey: apiKeyFromEnv("openrouter")
|
|
742
|
-
}, options));
|
|
743
|
-
}
|
|
744
|
-
/**
|
|
745
|
-
* [Vercel AI Gateway](https://vercel.com/docs/ai-gateway). Serves Codex, Claude Code, and AI SDK models, and answers
|
|
746
|
-
* Jev questions as `typesafe-ai/jev`. Reads `AI_GATEWAY_API_KEY`, then `VERCEL_OIDC_TOKEN`.
|
|
747
|
-
*/
|
|
748
|
-
function vercel(options) {
|
|
749
|
-
const envSecret = (field) => async (context) => {
|
|
750
|
-
return await readAiGatewayEnv(context, "vercel", field);
|
|
751
|
-
};
|
|
752
|
-
const apiKey = envSecret("apiKey");
|
|
753
|
-
const oidcToken = envSecret("oidcToken");
|
|
754
|
-
const explicitKey = options && Object.hasOwn(options, "apiKey");
|
|
755
|
-
const definition = preset({
|
|
756
|
-
name: "vercel",
|
|
757
|
-
baseURL: {
|
|
758
|
-
"codex": "https://ai-gateway.vercel.sh/codex/v1",
|
|
759
|
-
"claude-code": "https://ai-gateway.vercel.sh/claude-code",
|
|
760
|
-
"openai-compatible": "https://ai-gateway.vercel.sh/v1"
|
|
761
|
-
},
|
|
762
|
-
apiKey: async (context) => await resolveAiGatewaySecret(apiKey, context) ?? await resolveAiGatewaySecret(oidcToken, context)
|
|
763
|
-
}, options);
|
|
764
|
-
const modelCredentials = async (context) => {
|
|
765
|
-
const resolvedKey = await resolveAiGatewaySecret(explicitKey ? definition.apiKey : apiKey, context);
|
|
766
|
-
const token = resolvedKey || explicitKey ? void 0 : await resolveAiGatewaySecret(oidcToken, context);
|
|
767
|
-
return {
|
|
768
|
-
apiKey: resolvedKey ?? token,
|
|
769
|
-
headers: [["ai-gateway-auth-method", token ? "oidc" : "api-key"]]
|
|
770
|
-
};
|
|
771
|
-
};
|
|
772
|
-
return createAiGateway(definition, jevRoute("vercel", {
|
|
773
|
-
apiKey: explicitKey ? definition.apiKey : apiKey,
|
|
774
|
-
baseURL: async () => "https://ai-gateway.vercel.sh/v4/ai",
|
|
775
|
-
...options?.fetch ? { fetch: options.fetch } : {},
|
|
776
|
-
...definition.headers ? { headers: definition.headers } : {},
|
|
777
|
-
...keyEnv("vercel", options) ? { keyEnv: keyEnv("vercel", options) } : {},
|
|
778
|
-
label: "Vercel AI Gateway",
|
|
779
|
-
model: options?.model?.trim() || "typesafe-ai/jev",
|
|
780
|
-
...!explicitKey ? { oidcToken } : {},
|
|
781
|
-
protocol: "vercel"
|
|
782
|
-
}), void 0, void 0, modelCredentials);
|
|
783
|
-
}
|
|
784
|
-
/** The OpenAI API with an API key. Serves Codex and AI SDK models. Reads `OPENAI_API_KEY`. */
|
|
785
|
-
function openai(options) {
|
|
786
|
-
return modelGateway(preset({
|
|
787
|
-
name: "openai",
|
|
788
|
-
baseURL: {
|
|
789
|
-
"codex": "https://api.openai.com/v1",
|
|
790
|
-
"openai-compatible": "https://api.openai.com/v1"
|
|
791
|
-
},
|
|
792
|
-
apiKey: apiKeyFromEnv("openai")
|
|
793
|
-
}, options));
|
|
794
|
-
}
|
|
795
|
-
/** The Anthropic API with an API key. Serves Claude Code and AI SDK models. Reads `ANTHROPIC_API_KEY`. */
|
|
796
|
-
function anthropic(options) {
|
|
797
|
-
return modelGateway(preset({
|
|
798
|
-
name: "anthropic",
|
|
799
|
-
baseURL: { "claude-code": "https://api.anthropic.com" },
|
|
800
|
-
apiKey: apiKeyFromEnv("anthropic"),
|
|
801
|
-
auth: "x-api-key"
|
|
802
|
-
}, options));
|
|
803
|
-
}
|
|
804
|
-
/** [TypeSafe](https://typesafe.ai). Answers Jev questions; it serves no model API. Reads `TYPESAFE_API_KEY` and `TYPESAFE_DEFAULT_MODEL`. */
|
|
805
|
-
function typesafe(options) {
|
|
806
|
-
const definition = preset({
|
|
807
|
-
name: "typesafe",
|
|
808
|
-
baseURL: {},
|
|
809
|
-
apiKey: apiKeyFromEnv("typesafe")
|
|
810
|
-
}, options);
|
|
811
|
-
return createAiGateway(definition, jevRoute("typesafe", {
|
|
812
|
-
apiKey: definition.apiKey,
|
|
813
|
-
baseURL: async () => "https://api.typesafe.ai",
|
|
814
|
-
...options?.fetch ? { fetch: options.fetch } : {},
|
|
815
|
-
...definition.headers ? { headers: definition.headers } : {},
|
|
816
|
-
...keyEnv("typesafe", options) ? { keyEnv: keyEnv("typesafe", options) } : {},
|
|
817
|
-
label: "TypeSafe",
|
|
818
|
-
model: options?.model?.trim() || (async (context) => {
|
|
819
|
-
const model = await readAiGatewayEnv(context, "typesafe", "model");
|
|
820
|
-
return typeof model === "string" && model.trim() ? model.trim() : "jev-latest";
|
|
821
|
-
}),
|
|
822
|
-
protocol: "typesafe"
|
|
823
|
-
}));
|
|
824
|
-
}
|
|
825
|
-
function cloudflareRoot(options, preset) {
|
|
826
|
-
const required = async (context, field) => {
|
|
827
|
-
const given = options[field];
|
|
828
|
-
const read = given !== void 0 ? given : await readAiGatewayEnv(context, preset, field);
|
|
829
|
-
const resolved = typeof read === "string" ? read.trim() : "";
|
|
830
|
-
if (resolved) return resolved;
|
|
831
|
-
const label = field === "accountId" ? "an account ID" : "a gateway ID";
|
|
832
|
-
throw gatewayDiagnostics.GATEWAYS_R0004({ message: `[vitehub] Gateway "${preset}" needs ${label}. Set ${aiGatewayVendorNames(preset, field).join(" or ")}, or pass ${field}.` });
|
|
833
|
-
};
|
|
834
|
-
return async (context) => ({
|
|
835
|
-
accountId: await required(context, "accountId"),
|
|
836
|
-
gatewayId: await required(context, "gatewayId")
|
|
837
|
-
});
|
|
838
|
-
}
|
|
839
|
-
/** A token that may be missing, read from `options.token` or Server Env, as a `cf-aig-authorization` value. */
|
|
840
|
-
function cloudflareToken(options, preset) {
|
|
841
|
-
const token = Object.hasOwn(options, "token") ? options.token : async (context) => await readAiGatewayEnv(context, preset, "token");
|
|
842
|
-
return async (context) => {
|
|
843
|
-
const resolved = await resolveAiGatewaySecret(token, context);
|
|
844
|
-
return resolved ? `Bearer ${resolved}` : void 0;
|
|
845
|
-
};
|
|
846
|
-
}
|
|
847
|
-
/**
|
|
848
|
-
* [Cloudflare AI Gateway](https://developers.cloudflare.com/ai-gateway/). Serves AI SDK models through its
|
|
849
|
-
* [OpenAI-compatible endpoint](https://developers.cloudflare.com/ai-gateway/usage/chat-completion/), with
|
|
850
|
-
* Chat Completions (`api: "chat"`) only, with `{provider}/{model}` model IDs such as `workers-ai/@cf/meta/llama-3.3-70b-instruct-fp8-fast`. Answers Jev questions
|
|
851
|
-
* through a TypeSafe [custom provider](https://developers.cloudflare.com/ai-gateway/configuration/custom-providers/).
|
|
852
|
-
* Each capability reads its own key: model requests need the gateway token, `CLOUDFLARE_AI_GATEWAY_API_KEY`, or both;
|
|
853
|
-
* `ask()` needs `TYPESAFE_API_KEY`. For Codex or Claude Code through Cloudflare, use `defineAiGateway()`.
|
|
854
|
-
*/
|
|
855
|
-
function cloudflare(options = {}) {
|
|
856
|
-
if (Object.hasOwn(options, "apiKey")) throw gatewayDiagnostics.GATEWAYS_R0001({ message: "[vitehub] cloudflare() reads two keys and has no apiKey. Pass typesafeApiKey for ask(), or providerApiKey for model requests." });
|
|
857
|
-
const root = cloudflareRoot(options, "cloudflare");
|
|
858
|
-
const token = cloudflareToken(options, "cloudflare");
|
|
859
|
-
const fromEnv = (field) => {
|
|
860
|
-
return async (context) => await readAiGatewayEnv(context, "cloudflare", field);
|
|
861
|
-
};
|
|
862
|
-
const definition = {
|
|
863
|
-
name: "cloudflare",
|
|
864
|
-
baseURL: { "openai-compatible": async (context) => {
|
|
865
|
-
const { accountId, gatewayId } = await root(context);
|
|
866
|
-
return `https://gateway.ai.cloudflare.com/v1/${encodeURIComponent(accountId)}/${encodeURIComponent(gatewayId)}/compat`;
|
|
867
|
-
} },
|
|
868
|
-
apiKey: Object.hasOwn(options, "providerApiKey") ? options.providerApiKey : fromEnv("providerApiKey"),
|
|
869
|
-
headers: {
|
|
870
|
-
...options.headers,
|
|
871
|
-
"cf-aig-authorization": token
|
|
872
|
-
}
|
|
873
|
-
};
|
|
874
|
-
const slug = async (context) => {
|
|
875
|
-
const read = options.slug !== void 0 ? options.slug : await readAiGatewayEnv(context, "cloudflare", "slug");
|
|
876
|
-
return typeof read === "string" ? read.trim() : "";
|
|
877
|
-
};
|
|
878
|
-
const explicitTypesafeKey = Object.hasOwn(options, "typesafeApiKey");
|
|
879
|
-
return createAiGateway(definition, jevRoute("cloudflare", {
|
|
880
|
-
apiKey: explicitTypesafeKey ? options.typesafeApiKey : fromEnv("typesafeApiKey"),
|
|
881
|
-
baseURL: async (context) => cloudflareJevBaseURL({
|
|
882
|
-
...await root(context),
|
|
883
|
-
slug: await slug(context)
|
|
884
|
-
}),
|
|
885
|
-
...options.fetch ? { fetch: options.fetch } : {},
|
|
886
|
-
...options.headers ? { headers: options.headers } : {},
|
|
887
|
-
optionalHeaders: { "cf-aig-authorization": token },
|
|
888
|
-
...explicitTypesafeKey ? {} : { keyEnv: aiGatewayVendorNames("cloudflare", "typesafeApiKey").join(" or ") },
|
|
889
|
-
keyOption: "typesafeApiKey",
|
|
890
|
-
label: "Cloudflare AI Gateway",
|
|
891
|
-
model: options.model?.trim() || "jev-latest",
|
|
892
|
-
protocol: "typesafe"
|
|
893
|
-
}), {
|
|
894
|
-
apiKey: true,
|
|
895
|
-
headers: ["cf-aig-authorization"],
|
|
896
|
-
missing: "Gateway \"cloudflare\" needs a gateway token or a provider key for model requests. Set CLOUDFLARE_AI_GATEWAY_TOKEN for stored provider keys or Unified Billing, or CLOUDFLARE_AI_GATEWAY_API_KEY, or pass token or providerApiKey."
|
|
897
|
-
}, ["chat"]);
|
|
898
|
-
}
|
|
899
|
-
//#endregion
|
|
900
|
-
export { cloudflareAccess as a, ollama as c, typesafe as d, vercel as f, isChatGPTGateway as g, chatgpt as h, cloudflare as i, openai as l, aiGatewayEnvNames as m, askAiGateway as n, defineAiGateway as o, aiGatewayEnv as p, cliproxy as r, litellm as s, anthropic as t, openrouter as u };
|