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