@vite-hub/gateways 0.4.1 → 0.5.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/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
- import { u as gatewayDiagnostics } from "./definition-BVc8HZWs.js";
2
- import { a as cloudflareAccess, c as ollama, d as typesafe, f as vercel, h as chatgpt, i as cloudflare, l as openai, o as defineAiGateway, p as aiGatewayEnv, r as cliproxy, s as litellm, t as anthropic, u as openrouter } from "./presets-CRYxSoMw.js";
1
+ import { t as gatewayDiagnostics } from "./diagnostics-KWRXsfZ3.js";
2
+ import { a as cloudflareAccess, c as litellm, d as openrouter, f as typesafe, g as chatgpt, i as cloudflare, l as ollama, m as aiGatewayEnv, o as defineAiGateway, p as vercel, r as cliproxy, s as emulate, t as anthropic, u as openai } from "./presets-C7I0uIZc.js";
3
3
  //#region src/ask-model.ts
4
4
  async function loadAi(caller = "askWithModel()") {
5
5
  try {
@@ -78,7 +78,6 @@ function describeQuestion(name, question) {
78
78
  }
79
79
  return lines.join("\n");
80
80
  }
81
- /** The model names one option and how sure it is. The other options share the rest of the probability. */
82
81
  function spread(labels, chosen, sure) {
83
82
  const top = Math.max(sure, 1 / labels.length);
84
83
  const rest = labels.length > 1 ? (1 - top) / (labels.length - 1) : 0;
@@ -195,7 +194,6 @@ function checkSchema(schema) {
195
194
  vendor: String(readKey(standard, "vendor"))
196
195
  });
197
196
  }
198
- /** The first problem that the schema found in the answer, as `path: message`. */
199
197
  function firstIssue(error) {
200
198
  const cause = readKey(readKey(error, "cause"), "cause");
201
199
  const issues = Array.isArray(cause) ? cause : readKey(cause, "issues");
@@ -326,18 +324,12 @@ function each(items, options) {
326
324
  * })
327
325
  */
328
326
  const ask = Object.assign(askOnce, {
329
- /** A yes or no question. Answers `{ chance }`, the probability of yes. */
330
327
  chance,
331
- /** Selects one option. Answers `{ choice, confidence, probabilities }`. */
332
328
  choice,
333
- /** Builds a keyed question map from a list. */
334
329
  each,
335
- /** A yes or no question. Answers `true` when the probability of yes is above `threshold` (0 to 1, default `0.5`). */
336
330
  if: askIf,
337
- /** Rates the state against 2 to 10 ordered levels. Answers `{ score, ratio, confidence, legend, probabilities }`. */
338
331
  score,
339
- /** Selects one option. Answers with the selected label only. */
340
332
  switch: askSwitch
341
333
  });
342
334
  //#endregion
343
- export { aiGatewayEnv, anthropic, ask, askWithModel, chatgpt, cliproxy, cloudflare, cloudflareAccess, defineAiGateway, litellm, ollama, openai, openrouter, typesafe, vercel };
335
+ export { aiGatewayEnv, anthropic, ask, askWithModel, chatgpt, cliproxy, cloudflare, cloudflareAccess, defineAiGateway, emulate, litellm, ollama, openai, openrouter, typesafe, vercel };
@@ -1,5 +1,5 @@
1
- import { c as AiGatewayDefinition, f as AiGatewaySecret, s as AiGatewayContext, u as AiGatewayRoute } from "./types-CF5dF7X1.js";
2
- import { C as AiGatewayEnvFieldName, E as aiGatewayEnvNames, k as isChatGPTGateway, u as askAiGateway, w as AiGatewayEnvPreset, x as AiGatewayTraceEvent } from "./presets-QQzoSUSu.js";
1
+ import { c as AiGatewayDefinition, f as AiGatewaySecret, s as AiGatewayContext, u as AiGatewayRoute } from "./types-CYigOOA5.js";
2
+ import { C as AiGatewayTraceEvent, E as AiGatewayEnvPreset, O as aiGatewayEnvNames, T as AiGatewayEnvFieldName, d as askAiGateway, j as isChatGPTGateway } from "./presets-xSYbZBJS.js";
3
3
  import { Diagnostic } from "nostics";
4
4
  //#region src/definition.d.ts
5
5
  /**
@@ -7,6 +7,17 @@ import { Diagnostic } from "nostics";
7
7
  * have no model API base URL.
8
8
  */
9
9
  export declare const aiGatewayAsks: unique symbol;
10
+ /**
11
+ * The route of a model that `languageModel()` returns: its gateway name, model API, and model ID. A symbol key, so key
12
+ * checks and copies skip it. ViteHub Agents read it to send the same model to the AI emulator.
13
+ */
14
+ export declare const aiGatewayLanguageModel: unique symbol;
15
+ /** The value of `aiGatewayLanguageModel`. */
16
+ interface AiGatewayLanguageModelRoute {
17
+ api: "chat" | "messages" | "responses";
18
+ gateway: string;
19
+ modelId: string;
20
+ }
10
21
  /** Validate a gateway definition and return a frozen copy with its model API routes. */
11
22
  export declare function normalizeAiGateway(value: unknown): AiGatewayDefinition;
12
23
  /** A secret as a trimmed string, or undefined when it is missing or empty. */
@@ -39,4 +50,4 @@ export declare function getPublicAiGatewayDiagnostic(cause: unknown): {
39
50
  fix?: string;
40
51
  } | undefined;
41
52
  //#endregion
42
- export { type AiGatewayEnvFieldName, type AiGatewayEnvPreset, type AiGatewayModelRoute, type AiGatewayResolvedRoute, type AiGatewayTraceEvent, aiGatewayEnvNames, askAiGateway, isChatGPTGateway };
53
+ export { type AiGatewayEnvFieldName, type AiGatewayEnvPreset, type AiGatewayLanguageModelRoute, type AiGatewayModelRoute, type AiGatewayResolvedRoute, type AiGatewayTraceEvent, aiGatewayEnvNames, askAiGateway, isChatGPTGateway };
package/dist/internal.js CHANGED
@@ -1,3 +1,4 @@
1
- import { c as resolveAiGatewayRoute, d as getPublicAiGatewayDiagnostic, i as aiGatewaySupports, l as resolveAiGatewaySecret, o as normalizeAiGateway, s as resolveAiGatewayModelRoute, t as aiGatewayAsks } from "./definition-BVc8HZWs.js";
2
- import { g as isChatGPTGateway, m as aiGatewayEnvNames, n as askAiGateway } from "./presets-CRYxSoMw.js";
3
- export { aiGatewayAsks, aiGatewayEnvNames, aiGatewaySupports, askAiGateway, getPublicAiGatewayDiagnostic, isChatGPTGateway, normalizeAiGateway, resolveAiGatewayModelRoute, resolveAiGatewayRoute, resolveAiGatewaySecret };
1
+ import { n as getPublicAiGatewayDiagnostic } from "./diagnostics-KWRXsfZ3.js";
2
+ import { d as resolveAiGatewayRoute, f as resolveAiGatewaySecret, l as normalizeAiGateway, n as aiGatewayLanguageModel, s as aiGatewaySupports, t as aiGatewayAsks, u as resolveAiGatewayModelRoute } from "./definition-BQbaNIoi.js";
3
+ import { _ as isChatGPTGateway, h as aiGatewayEnvNames, n as askAiGateway } from "./presets-C7I0uIZc.js";
4
+ export { aiGatewayAsks, aiGatewayEnvNames, aiGatewayLanguageModel, aiGatewaySupports, askAiGateway, getPublicAiGatewayDiagnostic, isChatGPTGateway, normalizeAiGateway, resolveAiGatewayModelRoute, resolveAiGatewayRoute, resolveAiGatewaySecret };
@@ -0,0 +1,421 @@
1
+ import { t as gatewayDiagnostics } from "./diagnostics-KWRXsfZ3.js";
2
+ //#region src/jev.ts
3
+ async function loadAdvocaat() {
4
+ try {
5
+ return await import("advocaat");
6
+ } catch (error) {
7
+ throw gatewayDiagnostics.GATEWAYS_R0006({
8
+ message: "[vitehub] TypeSafe Jev requests require the advocaat package. Install it with: pnpm add advocaat",
9
+ cause: error
10
+ });
11
+ }
12
+ }
13
+ function isObject(value) {
14
+ return typeof value === "object" && value !== null;
15
+ }
16
+ /** The custom provider URL of a Cloudflare AI Gateway. The TypeSafe client appends `/v1/systemone`. */
17
+ function cloudflareJevBaseURL(gateway) {
18
+ const segment = (value) => encodeURIComponent(value.trim());
19
+ return `https://gateway.ai.cloudflare.com/v1/${segment(gateway.accountId)}/${segment(gateway.gatewayId)}/custom-${segment(gateway.slug?.trim() || "typesafe")}`;
20
+ }
21
+ function toEntry(value) {
22
+ const serialized = JSON.stringify(value);
23
+ const parsed = serialized === void 0 ? null : JSON.parse(serialized);
24
+ return typeof parsed === "number" || typeof parsed === "boolean" ? String(parsed) : parsed;
25
+ }
26
+ function invalidQuestion(name) {
27
+ return gatewayDiagnostics.GATEWAYS_R0007({ message: `[vitehub] Jev question "${name}" must be built with ask.choice(), ask.score(), ask.chance(), ask.if(), or ask.switch().` });
28
+ }
29
+ function validateQuestionCriteria(name, question) {
30
+ 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.` });
31
+ if (question.type === "choice" || question.type === "switch") {
32
+ const count = isObject(question.criteria) && !Array.isArray(question.criteria) ? Object.keys(question.criteria).length : 0;
33
+ if (count < 2 || count > 255) throw gatewayDiagnostics.GATEWAYS_R0007({ message: `[vitehub] Jev question "${name}" ${question.type} criteria must have between 2 and 255 choices.` });
34
+ } else if (question.type === "score") {
35
+ const count = Array.isArray(question.criteria) ? question.criteria.length : 0;
36
+ if (count < 2 || count > 10) throw gatewayDiagnostics.GATEWAYS_R0007({ message: `[vitehub] Jev question "${name}" score criteria must have between 2 and 10 levels.` });
37
+ }
38
+ }
39
+ function hasValidChoiceAnswer(question, answer) {
40
+ if (!isObject(answer) || answer.type !== "choice" || typeof answer.choice !== "string" || !isObject(answer.probabilities)) return false;
41
+ if (typeof answer.confidence !== "number" || !Number.isFinite(answer.confidence) || answer.confidence < 0 || answer.confidence > 1) return false;
42
+ if (!isObject(question.criteria) || !Object.hasOwn(question.criteria, answer.choice)) return false;
43
+ const probabilities = answer.probabilities;
44
+ const labels = Object.keys(question.criteria);
45
+ const probabilityLabels = Object.keys(probabilities);
46
+ if (labels.length !== probabilityLabels.length || probabilityLabels.some((label) => !Object.hasOwn(question.criteria, label))) return false;
47
+ const total = labels.reduce((sum, label) => {
48
+ const probability = probabilities[label];
49
+ return sum + (typeof probability === "number" && Number.isFinite(probability) && probability >= 0 && probability <= 1 ? probability : NaN);
50
+ }, 0);
51
+ return Number.isFinite(total) && Math.abs(total - 1) <= 1e-6;
52
+ }
53
+ function finiteNumber(value) {
54
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
55
+ }
56
+ function toJevQuestion(question) {
57
+ if (question.type === "if") return {
58
+ instructions: question.instructions,
59
+ type: "noul"
60
+ };
61
+ if (question.type === "switch") return {
62
+ criteria: question.criteria,
63
+ instructions: question.instructions,
64
+ type: "choice"
65
+ };
66
+ return question;
67
+ }
68
+ async function requestJev(advocaat, state, batch, options) {
69
+ const { apiKey, baseURL, fetch, headers, protocol, signal } = options;
70
+ const wire = Object.fromEntries(Object.entries(batch).map(([name, question]) => [name, toJevQuestion(question)]));
71
+ const client = {
72
+ ...apiKey ? { apiKey } : {},
73
+ ...baseURL ? { baseURL } : {},
74
+ ...fetch ? { fetch } : {},
75
+ ...options.model ? { model: options.model } : {},
76
+ provider: protocol
77
+ };
78
+ const result = await advocaat.typesafe(client).systemOne({
79
+ questions: wire,
80
+ state
81
+ }, {
82
+ ...headers ? { headers } : {},
83
+ signal
84
+ });
85
+ const answers = Object.create(null);
86
+ for (const [name, answer] of Object.entries(result.answers)) {
87
+ const question = batch[name];
88
+ if (answer.type === "noul") answers[name] = question?.type === "if" ? answer.noul > question.threshold : {
89
+ chance: answer.noul,
90
+ type: "chance"
91
+ };
92
+ else if (answer.type === "score") answers[name] = question?.type === "score" ? {
93
+ ...answer,
94
+ ratio: answer.score / (question.criteria.length - 1)
95
+ } : answer;
96
+ else answers[name] = question?.type === "switch" ? answer.choice : answer;
97
+ }
98
+ return {
99
+ answers,
100
+ ...jevResponseMetadata(result)
101
+ };
102
+ }
103
+ function jevResponseMetadata(body) {
104
+ const { model, usage } = body;
105
+ return {
106
+ ...typeof model === "string" && model ? { model } : {},
107
+ ...isObject(usage) ? { usage: {
108
+ inputTokens: finiteNumber(usage.input_tokens),
109
+ outputTokens: finiteNumber(usage.output_tokens)
110
+ } } : {}
111
+ };
112
+ }
113
+ const retryableJevStatuses = /* @__PURE__ */ new Set([
114
+ 408,
115
+ 429,
116
+ 500,
117
+ 502,
118
+ 503,
119
+ 504
120
+ ]);
121
+ const jevAttempts = 3;
122
+ function errorStatus(error) {
123
+ return isObject(error) && Number.isInteger(error.status) ? Number(error.status) : void 0;
124
+ }
125
+ function errorRequestId(error) {
126
+ return isObject(error) && typeof error.requestId === "string" && error.requestId ? error.requestId : void 0;
127
+ }
128
+ function waitForRetry(attempt, signal) {
129
+ const delay = 250 * 2 ** attempt * (.75 + Math.random() / 2);
130
+ return new Promise((resolve, reject) => {
131
+ const timer = setTimeout(() => {
132
+ signal?.removeEventListener("abort", abort);
133
+ resolve();
134
+ }, delay);
135
+ function abort() {
136
+ clearTimeout(timer);
137
+ reject(signal?.reason);
138
+ }
139
+ signal?.addEventListener("abort", abort, { once: true });
140
+ });
141
+ }
142
+ async function requestJevWithRetry(advocaat, state, batch, options) {
143
+ const provider = options.label;
144
+ for (let attempt = 0;; attempt++) try {
145
+ return [void 0, await requestJev(advocaat, state, batch, options)];
146
+ } catch (error) {
147
+ if (options.signal?.aborted) throw error;
148
+ const status = errorStatus(error);
149
+ const details = {
150
+ cause: error,
151
+ providerStatus: status,
152
+ requestId: errorRequestId(error)
153
+ };
154
+ if (status === 401 || status === 403) return [Object.assign(gatewayDiagnostics.GATEWAYS_R0008({
155
+ provider,
156
+ status,
157
+ env: options.keyEnv,
158
+ option: options.keyOption,
159
+ cause: error
160
+ }), {
161
+ ...details,
162
+ providerStatus: status,
163
+ status: 503
164
+ }), void 0];
165
+ if (!(status === void 0 ? error instanceof TypeError && isObject(error) && "cause" in error : retryableJevStatuses.has(status))) throw error;
166
+ if (attempt + 1 >= jevAttempts) return [Object.assign(gatewayDiagnostics.GATEWAYS_R0009({
167
+ provider,
168
+ status,
169
+ attempts: jevAttempts,
170
+ cause: error
171
+ }), {
172
+ ...details,
173
+ status: 502
174
+ }), void 0];
175
+ await waitForRetry(attempt, options.signal);
176
+ }
177
+ }
178
+ function jevUsageRecord(provider, response) {
179
+ const inputTokens = response.usage?.inputTokens;
180
+ const outputTokens = response.usage?.outputTokens;
181
+ if (inputTokens === void 0 && outputTokens === void 0) return void 0;
182
+ return {
183
+ ...response.model ? { model: response.model } : {},
184
+ provider,
185
+ usage: {
186
+ ...inputTokens !== void 0 ? { inputTokens } : {},
187
+ ...outputTokens !== void 0 ? { outputTokens } : {},
188
+ ...inputTokens !== void 0 && outputTokens !== void 0 ? { totalTokens: inputTokens + outputTokens } : {}
189
+ }
190
+ };
191
+ }
192
+ function jevAnswerValue(answer) {
193
+ if (!isObject(answer)) return answer;
194
+ if (answer.type === "choice") return answer.choice;
195
+ if (answer.type === "score") return answer.score;
196
+ if (answer.type === "chance") return answer.chance;
197
+ }
198
+ async function observeJevBatch(observe, options, questions, batch, position) {
199
+ const names = Object.keys(batch);
200
+ const startedAt = Date.now();
201
+ const settled = /* @__PURE__ */ new Set();
202
+ const emit = async (event) => {
203
+ try {
204
+ await observe?.(event);
205
+ } catch (error) {
206
+ console.warn(gatewayDiagnostics.GATEWAYS_TRACE_OBSERVER_FAILED({
207
+ event: event.name,
208
+ cause: error
209
+ }));
210
+ }
211
+ };
212
+ const batchAttributes = {
213
+ "ask.batch.count": position.count,
214
+ "ask.batch.index": position.index,
215
+ "ask.batch.size": names.length,
216
+ "gen_ai.operation.name": "ask",
217
+ "gen_ai.provider.name": options.provider
218
+ };
219
+ const questionAttributes = (name) => ({
220
+ ...batchAttributes,
221
+ ...options.model ? { "ask.model": options.model } : {},
222
+ "ask.key": name,
223
+ "ask.type": questions[name]?.type,
224
+ "step.id": `ask:${name}`,
225
+ "tool.id": `ask:${name}`,
226
+ "tool.name": "ask",
227
+ "vitehub.activity.kind": "tool"
228
+ });
229
+ if (observe) for (const name of names) await emit({
230
+ attributes: {
231
+ ...questionAttributes(name),
232
+ "tool.hasInput": true,
233
+ "tool.input": batch[name]
234
+ },
235
+ name: "agent.tool.start",
236
+ type: "run"
237
+ });
238
+ return {
239
+ async answered(name, answer, model) {
240
+ settled.add(name);
241
+ if (!observe) return;
242
+ const value = jevAnswerValue(answer);
243
+ const confidence = isObject(answer) ? finiteNumber(answer.confidence) : void 0;
244
+ const probabilities = isObject(answer) && isObject(answer.probabilities) ? { ...answer.probabilities } : void 0;
245
+ await emit({
246
+ attributes: {
247
+ ...questionAttributes(name),
248
+ ...model ? { "ask.model": model } : {},
249
+ ...value !== void 0 ? { "ask.answer": value } : {},
250
+ ...confidence !== void 0 ? { "ask.confidence": confidence } : {},
251
+ ...probabilities ? { "ask.probabilities": probabilities } : {},
252
+ "tool.durationMs": Date.now() - startedAt,
253
+ "tool.hasOutput": true,
254
+ "tool.output": answer
255
+ },
256
+ name: "agent.tool.finish",
257
+ type: "run"
258
+ });
259
+ },
260
+ async failed(error) {
261
+ if (!observe) return;
262
+ const message = error instanceof Error ? error.message : String(error);
263
+ const status = isObject(error) && Number.isInteger(error.providerStatus) ? error.providerStatus : errorStatus(error);
264
+ const requestId = errorRequestId(error);
265
+ for (const name of names) {
266
+ if (settled.has(name)) continue;
267
+ settled.add(name);
268
+ await emit({
269
+ attributes: {
270
+ ...questionAttributes(name),
271
+ "error.message": message,
272
+ ...error instanceof Error ? { "error.name": error.name } : {},
273
+ ...status !== void 0 ? { "error.status": status } : {},
274
+ ...requestId ? { "error.requestId": requestId } : {},
275
+ "tool.durationMs": Date.now() - startedAt,
276
+ "tool.error": message
277
+ },
278
+ name: "agent.tool.error",
279
+ type: "error"
280
+ });
281
+ }
282
+ },
283
+ async usage(response) {
284
+ if (!observe || !response.usage) return;
285
+ const { inputTokens, outputTokens } = response.usage;
286
+ await emit({
287
+ attributes: {
288
+ ...batchAttributes,
289
+ "ask.durationMs": Date.now() - startedAt,
290
+ "usage.hasCost": false,
291
+ "usage.hasRaw": false,
292
+ ...inputTokens !== void 0 ? { "usage.inputTokens": inputTokens } : {},
293
+ ...response.model ? { "usage.model": response.model } : {},
294
+ ...outputTokens !== void 0 ? { "usage.outputTokens": outputTokens } : {},
295
+ "usage.provider": options.provider,
296
+ ...inputTokens !== void 0 && outputTokens !== void 0 ? { "usage.totalTokens": inputTokens + outputTokens } : {}
297
+ },
298
+ name: "agent.usage.recorded",
299
+ type: "run"
300
+ });
301
+ }
302
+ };
303
+ }
304
+ function toAdvocaatQuestion(name, question) {
305
+ validateQuestionCriteria(name, question);
306
+ const instructions = toEntry(question.instructions);
307
+ switch (question.type) {
308
+ case "chance": return {
309
+ criteria: question.criteria ? Object.fromEntries(Object.entries(question.criteria).map(([key, value]) => [key, toEntry(value)])) : void 0,
310
+ instructions,
311
+ type: "noul"
312
+ };
313
+ case "choice":
314
+ case "switch": return {
315
+ ...question,
316
+ instructions,
317
+ criteria: Object.fromEntries(Object.entries(question.criteria).map(([key, value]) => [key, toEntry(value)]))
318
+ };
319
+ case "score": {
320
+ const [first, second, ...rest] = question.criteria;
321
+ return {
322
+ ...question,
323
+ instructions,
324
+ criteria: [
325
+ toEntry(first),
326
+ toEntry(second),
327
+ ...rest.map(toEntry)
328
+ ]
329
+ };
330
+ }
331
+ case "if": return question;
332
+ }
333
+ throw invalidQuestion(name);
334
+ }
335
+ function jevInputSize(value) {
336
+ return new TextEncoder().encode(JSON.stringify(value)).byteLength;
337
+ }
338
+ function jevQuestionBatches(state, wire) {
339
+ const sharedSize = jevInputSize(state) + 2048;
340
+ const maxRequestSize = 6e4;
341
+ const maxQuestionSize = 3e4;
342
+ if (sharedSize >= maxQuestionSize) throw gatewayDiagnostics.GATEWAYS_JEV_INPUT_TOO_LARGE({});
343
+ const batches = [];
344
+ let batch = Object.create(null);
345
+ let size = sharedSize;
346
+ for (const [name, question] of Object.entries(wire)) {
347
+ const questionSize = jevInputSize({ [name]: question }) + 128;
348
+ if (sharedSize + questionSize > maxQuestionSize) throw gatewayDiagnostics.GATEWAYS_JEV_INPUT_TOO_LARGE({ question: name });
349
+ if (size + questionSize > maxRequestSize && Object.keys(batch).length) {
350
+ batches.push(batch);
351
+ batch = Object.create(null);
352
+ size = sharedSize;
353
+ }
354
+ batch[name] = question;
355
+ size += questionSize;
356
+ }
357
+ if (Object.keys(batch).length) batches.push(batch);
358
+ return batches;
359
+ }
360
+ /** Runs independent keyed questions in bounded Jev requests; empty questions require no credentials or API call. */
361
+ async function askJev(context, state, questions) {
362
+ if (!isObject(questions) || Array.isArray(questions)) throw gatewayDiagnostics.GATEWAYS_R0007({ message: "[vitehub] Jev questions must be an object of questions built with ask." });
363
+ const wire = Object.fromEntries(Object.entries(questions).map(([name, question]) => {
364
+ if (!isObject(question)) throw invalidQuestion(name);
365
+ return [name, toAdvocaatQuestion(name, question)];
366
+ }));
367
+ if (!Object.keys(wire).length) return [void 0, {}];
368
+ const entry = toEntry(state);
369
+ const batches = jevQuestionBatches(entry, wire);
370
+ const advocaat = await loadAdvocaat();
371
+ const options = await context.route();
372
+ const output = Object.create(null);
373
+ for (const [batchIndex, batch] of batches.entries()) {
374
+ context.abortSignal?.throwIfAborted();
375
+ const observed = await observeJevBatch(context.observe, {
376
+ ...options.model ? { model: options.model } : {},
377
+ provider: options.name
378
+ }, questions, batch, {
379
+ count: batches.length,
380
+ index: batchIndex
381
+ });
382
+ try {
383
+ const [error, response] = await requestJevWithRetry(advocaat, entry, batch, {
384
+ ...options,
385
+ signal: context.abortSignal
386
+ });
387
+ if (error) {
388
+ await observed.failed(error);
389
+ return [error, void 0];
390
+ }
391
+ await observed.usage(response);
392
+ const usage = jevUsageRecord(options.name, response);
393
+ if (usage) context.recordUsage?.(usage);
394
+ context.abortSignal?.throwIfAborted();
395
+ for (const name of Object.keys(batch)) {
396
+ if (!Object.hasOwn(response.answers, name)) throw gatewayDiagnostics.GATEWAYS_JEV_RESPONSE_INVALID({
397
+ name,
398
+ problem: "missing"
399
+ });
400
+ const answer = response.answers[name];
401
+ const question = questions[name];
402
+ if (question.type === "choice" && !hasValidChoiceAnswer(question, answer)) throw gatewayDiagnostics.GATEWAYS_JEV_RESPONSE_INVALID({
403
+ name,
404
+ problem: "choice"
405
+ });
406
+ const scoreAnswer = isObject(answer) && answer.type === "score" ? answer : void 0;
407
+ output[name] = question?.type === "score" && scoreAnswer ? {
408
+ ...scoreAnswer,
409
+ legend: Object.fromEntries(question.criteria.map((level, index) => [String(index), level]))
410
+ } : answer;
411
+ await observed.answered(name, output[name], response.model);
412
+ }
413
+ } catch (error) {
414
+ await observed.failed(error);
415
+ throw error;
416
+ }
417
+ }
418
+ return [void 0, Object.fromEntries(Object.entries(output))];
419
+ }
420
+ //#endregion
421
+ export { cloudflareJevBaseURL as n, hasValidChoiceAnswer as r, askJev as t };