@yourgpt/llm-sdk 2.6.0-beta.2 → 2.6.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.
Files changed (74) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +87 -17
  3. package/dist/adapters/index.d.mts +11 -13
  4. package/dist/adapters/index.d.ts +11 -13
  5. package/dist/adapters/index.js +406 -114
  6. package/dist/adapters/index.mjs +406 -114
  7. package/dist/audio-K-Z3-Bce.d.mts +191 -0
  8. package/dist/audio-K-Z3-Bce.d.ts +191 -0
  9. package/dist/{base-BICaQaRS.d.mts → base-6LzczuCg.d.ts} +8 -1
  10. package/dist/{base-CpRPB8u8.d.ts → base-DySbTP8C.d.mts} +8 -1
  11. package/dist/decisions-CJzOt87t.d.mts +137 -0
  12. package/dist/decisions-CJzOt87t.d.ts +137 -0
  13. package/dist/fallback/index.d.mts +4 -4
  14. package/dist/fallback/index.d.ts +4 -4
  15. package/dist/http-BQxUT5A9.d.mts +9 -0
  16. package/dist/http-BQxUT5A9.d.ts +9 -0
  17. package/dist/index.d.mts +17 -9
  18. package/dist/index.d.ts +17 -9
  19. package/dist/index.js +698 -205
  20. package/dist/index.mjs +695 -206
  21. package/dist/providers/anthropic/index.d.mts +7 -4
  22. package/dist/providers/anthropic/index.d.ts +7 -4
  23. package/dist/providers/anthropic/index.js +389 -115
  24. package/dist/providers/anthropic/index.mjs +389 -115
  25. package/dist/providers/azure/index.d.mts +3 -3
  26. package/dist/providers/azure/index.d.ts +3 -3
  27. package/dist/providers/cloudflare/index.d.mts +11 -0
  28. package/dist/providers/cloudflare/index.d.ts +11 -0
  29. package/dist/providers/cloudflare/index.js +743 -0
  30. package/dist/providers/cloudflare/index.mjs +741 -0
  31. package/dist/providers/fireworks/index.d.mts +3 -3
  32. package/dist/providers/fireworks/index.d.ts +3 -3
  33. package/dist/providers/fireworks/index.js +181 -60
  34. package/dist/providers/fireworks/index.mjs +181 -60
  35. package/dist/providers/google/index.d.mts +3 -3
  36. package/dist/providers/google/index.d.ts +3 -3
  37. package/dist/providers/google/index.js +181 -60
  38. package/dist/providers/google/index.mjs +181 -60
  39. package/dist/providers/ollama/index.d.mts +4 -4
  40. package/dist/providers/ollama/index.d.ts +4 -4
  41. package/dist/providers/openai/index.d.mts +38 -6
  42. package/dist/providers/openai/index.d.ts +38 -6
  43. package/dist/providers/openai/index.js +1451 -85
  44. package/dist/providers/openai/index.mjs +1449 -86
  45. package/dist/providers/openrouter/index.d.mts +21 -4
  46. package/dist/providers/openrouter/index.d.ts +21 -4
  47. package/dist/providers/openrouter/index.js +1040 -131
  48. package/dist/providers/openrouter/index.mjs +1040 -132
  49. package/dist/providers/togetherai/index.d.mts +3 -3
  50. package/dist/providers/togetherai/index.d.ts +3 -3
  51. package/dist/providers/togetherai/index.js +181 -60
  52. package/dist/providers/togetherai/index.mjs +181 -60
  53. package/dist/providers/typesafe/index.d.mts +8 -0
  54. package/dist/providers/typesafe/index.d.ts +8 -0
  55. package/dist/providers/typesafe/index.js +735 -0
  56. package/dist/providers/typesafe/index.mjs +733 -0
  57. package/dist/providers/xai/index.d.mts +3 -3
  58. package/dist/providers/xai/index.d.ts +3 -3
  59. package/dist/providers/xai/index.js +181 -60
  60. package/dist/providers/xai/index.mjs +181 -60
  61. package/dist/{types-DCFqkJAy.d.ts → types-B0y6VZSQ.d.ts} +1 -1
  62. package/dist/{types-DHQEMFHA.d.mts → types-BXQMtaCX.d.ts} +17 -3
  63. package/dist/{types-C3RgRbEC.d.mts → types-BY6BVhFg.d.mts} +1 -1
  64. package/dist/{types-Dikj3En4.d.ts → types-C7_qVSSd.d.mts} +17 -3
  65. package/dist/{types-Dg1Bcg1k.d.mts → types-D7lzMMLu.d.mts} +13 -1
  66. package/dist/{types-Dg1Bcg1k.d.ts → types-D7lzMMLu.d.ts} +13 -1
  67. package/dist/yourgpt/index.d.mts +1 -1
  68. package/dist/yourgpt/index.d.ts +1 -1
  69. package/docs/decisions.md +174 -0
  70. package/docs/media.md +201 -0
  71. package/docs/multimodal-and-audio.md +9 -2
  72. package/package.json +34 -12
  73. package/dist/audio-BBSwnjo8.d.mts +0 -92
  74. package/dist/audio-BBSwnjo8.d.ts +0 -92
@@ -0,0 +1,733 @@
1
+ import { randomUUID } from 'crypto';
2
+
3
+ // src/providers/decisions/model.ts
4
+
5
+ // src/core/decisions.ts
6
+ var decisionErrorMarker = /* @__PURE__ */ Symbol.for("yourgpt.llm-sdk.DecisionAPIError");
7
+ var _a, _b;
8
+ var DecisionAPIError = class extends (_b = Error, _a = decisionErrorMarker, _b) {
9
+ constructor(message, code, status, requestId) {
10
+ super(message);
11
+ this.code = code;
12
+ this.status = status;
13
+ this.requestId = requestId;
14
+ this.name = "DecisionAPIError";
15
+ this[_a] = true;
16
+ }
17
+ /** Works across CJS/ESM and separately bundled provider entry points. */
18
+ static isInstance(error) {
19
+ return typeof error === "object" && error !== null && /* @__PURE__ */ Symbol.for("yourgpt.llm-sdk.DecisionAPIError") in error;
20
+ }
21
+ /** Advisory only: this SDK does not retry Decisions automatically. */
22
+ get retryable() {
23
+ return this.code === "network_error" || this.code === "http_error" && (this.status === 408 || this.status === 429 || this.status != null && this.status >= 500);
24
+ }
25
+ };
26
+
27
+ // src/core/decision-validation.ts
28
+ function decisionInputError(message) {
29
+ throw new DecisionAPIError(message, "invalid_input");
30
+ }
31
+ function decisionResponseError(message) {
32
+ throw new DecisionAPIError(message, "invalid_response");
33
+ }
34
+ function isDecisionRecord(value) {
35
+ if (value === null || typeof value !== "object" || Array.isArray(value))
36
+ return false;
37
+ const proto = Object.getPrototypeOf(value);
38
+ return proto === Object.prototype || proto === null;
39
+ }
40
+ function json(value, seen = /* @__PURE__ */ new Set(), depth = 0) {
41
+ if (depth > 64) return false;
42
+ if (value === null || typeof value === "string" || typeof value === "boolean")
43
+ return true;
44
+ if (typeof value === "number") return Number.isFinite(value);
45
+ if (typeof value !== "object" || !Array.isArray(value) && !isDecisionRecord(value) || seen.has(value))
46
+ return false;
47
+ seen.add(value);
48
+ const valid = Object.getOwnPropertySymbols(value).length === 0 && (Array.isArray(value) ? Array.from(value) : Object.values(value)).every(
49
+ (item) => json(item, seen, depth + 1)
50
+ );
51
+ seen.delete(value);
52
+ return valid;
53
+ }
54
+ function input(value) {
55
+ return (typeof value === "string" || Array.isArray(value) || isDecisionRecord(value)) && json(value);
56
+ }
57
+ function assertDecisionKeys(value, allowed, label) {
58
+ if (Object.keys(value).some((key) => !allowed.includes(key)))
59
+ decisionInputError(`${label} contains an unsupported field`);
60
+ }
61
+ function validateDecisionInput(options) {
62
+ if (!isDecisionRecord(options))
63
+ decisionInputError("Decisions options must be an object");
64
+ assertDecisionKeys(
65
+ options,
66
+ ["state", "questions", "images", "signal", "timeoutMs", "providerOptions"],
67
+ "Decisions options"
68
+ );
69
+ if (!input(options.state))
70
+ decisionInputError(
71
+ "state must be finite, acyclic JSON text, object, or array (maximum depth 64)"
72
+ );
73
+ if (!isDecisionRecord(options.questions) || Object.keys(options.questions).length === 0)
74
+ decisionInputError("questions must be a nonempty map");
75
+ for (const [id, question] of Object.entries(options.questions)) {
76
+ if (!id.length || !isDecisionRecord(question) || !input(question.instructions))
77
+ decisionInputError(
78
+ "Every question needs a nonempty ID and JSON-compatible instructions"
79
+ );
80
+ assertDecisionKeys(
81
+ question,
82
+ ["type", "instructions", "criteria"],
83
+ "Question"
84
+ );
85
+ if (question.type === "boolean") {
86
+ if (question.criteria !== void 0 && (!isDecisionRecord(question.criteria) || Object.entries(question.criteria).some(
87
+ ([key, value]) => !["true", "false"].includes(key) || !input(value)
88
+ )))
89
+ decisionInputError("Boolean criteria may describe only true and false");
90
+ } else if (question.type === "choice") {
91
+ if (!isDecisionRecord(question.criteria) || Object.keys(question.criteria).length < 2 || Object.keys(question.criteria).length > 255 || Object.entries(question.criteria).some(
92
+ ([key, value]) => !key.length || value !== null && !input(value)
93
+ ))
94
+ decisionInputError(
95
+ "Choice criteria require 2\u2013255 named options with JSON descriptions or null"
96
+ );
97
+ } else if (question.type === "score") {
98
+ if (!Array.isArray(question.criteria) || question.criteria.length < 2 || !Array.from(question.criteria).every(input))
99
+ decisionInputError(
100
+ "Score criteria require at least two ordered JSON descriptions"
101
+ );
102
+ } else
103
+ decisionInputError("Question type must be boolean, choice, or score");
104
+ }
105
+ if (options.timeoutMs !== void 0 && (!Number.isInteger(options.timeoutMs) || options.timeoutMs < 1 || options.timeoutMs > 2147483647))
106
+ decisionInputError("timeoutMs must be a positive 32-bit integer");
107
+ if (options.providerOptions !== void 0 && (!isDecisionRecord(options.providerOptions) || !json(options.providerOptions)))
108
+ decisionInputError("providerOptions must be a JSON object");
109
+ if (options.images !== void 0 && (!Array.isArray(options.images) || !Array.from(options.images).every(
110
+ (image) => isDecisionRecord(image) && image.data instanceof Uint8Array
111
+ )))
112
+ decisionInputError(
113
+ "Decision images must contain encoded bytes; hosted image URLs are unsupported"
114
+ );
115
+ }
116
+ function probability(value) {
117
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= 1;
118
+ }
119
+ function exactKeys(value, keys) {
120
+ return Object.keys(value).length === keys.length && keys.every((key) => Object.prototype.hasOwnProperty.call(value, key));
121
+ }
122
+ function validateDecisionResult(questions, result) {
123
+ if (!isDecisionRecord(result) || !isDecisionRecord(result.answers) || !exactKeys(result.answers, Object.keys(questions)))
124
+ decisionResponseError(
125
+ "Decisions must return exactly one answer per question"
126
+ );
127
+ const rounding = result.rounding;
128
+ let pError = 0, sError = 0;
129
+ if (rounding !== void 0) {
130
+ if (!isDecisionRecord(rounding) || ![rounding.probabilityDecimals, rounding.scoreDecimals].every(
131
+ (v) => typeof v === "number" && Number.isInteger(v) && v >= 0 && v <= 15
132
+ ))
133
+ decisionResponseError("Invalid decision rounding precision");
134
+ pError = 0.5 * 10 ** -rounding.probabilityDecimals;
135
+ sError = 0.5 * 10 ** -rounding.scoreDecimals;
136
+ }
137
+ const epsilon = 1e-6;
138
+ for (const [id, question] of Object.entries(questions)) {
139
+ const answer = result.answers[id];
140
+ if (!isDecisionRecord(answer))
141
+ decisionResponseError("Invalid decision answer");
142
+ if (answer.type === "refusal") continue;
143
+ if (answer.type !== question.type)
144
+ decisionResponseError("Decision answer type does not match its question");
145
+ if (answer.confidence !== void 0 && !probability(answer.confidence))
146
+ decisionResponseError(
147
+ "Confidence must be finite and between zero and one"
148
+ );
149
+ if (question.type === "boolean") {
150
+ if (!probability(answer.probability))
151
+ decisionResponseError(
152
+ "Boolean probability must be between zero and one"
153
+ );
154
+ continue;
155
+ }
156
+ const keys = question.type === "choice" ? Object.keys(question.criteria) : question.criteria.map((_, index) => String(index));
157
+ if (question.type === "choice" && (typeof answer.choice !== "string" || !keys.includes(answer.choice)))
158
+ decisionResponseError("Decision selected an unknown choice");
159
+ if (question.type === "score" && (typeof answer.score !== "number" || !Number.isFinite(answer.score) || answer.score < 0 || answer.score > keys.length - 1))
160
+ decisionResponseError("Decision score is outside its ordered levels");
161
+ if (answer.probabilities === void 0) continue;
162
+ const distribution2 = answer.probabilities;
163
+ if (!isDecisionRecord(distribution2) || !exactKeys(distribution2, keys) || !Object.values(distribution2).every(probability))
164
+ decisionResponseError(
165
+ "Decision distribution must contain every option exactly once with finite probabilities"
166
+ );
167
+ const values = Object.values(distribution2);
168
+ if (Math.abs(values.reduce((a, b) => a + b, 0) - 1) > epsilon + keys.length * pError)
169
+ decisionResponseError("Decision probabilities do not sum to one");
170
+ if (question.type === "choice") {
171
+ if (values.some(
172
+ (v) => v > distribution2[answer.choice] + epsilon + 2 * pError
173
+ ))
174
+ decisionResponseError(
175
+ "Decision choice is not a highest-probability option"
176
+ );
177
+ } else {
178
+ const mean = keys.reduce(
179
+ (sum, key) => sum + Number(key) * distribution2[key],
180
+ 0
181
+ );
182
+ const tolerance = epsilon + sError + pError * keys.reduce((sum, key) => sum + Number(key), 0);
183
+ if (Math.abs(answer.score - mean) > tolerance)
184
+ decisionResponseError(
185
+ "Decision score does not match its probability-weighted levels"
186
+ );
187
+ }
188
+ }
189
+ }
190
+
191
+ // src/providers/decisions/http.ts
192
+ async function postDecision(url, headers, body, options, fetchFn, maxBytes) {
193
+ const encoded = JSON.stringify(body);
194
+ if (Buffer.byteLength(encoded, "utf8") > maxBytes)
195
+ decisionInputError("Decision request exceeds the provider's byte limit");
196
+ options.signal?.throwIfAborted();
197
+ const controller = new AbortController();
198
+ const relay = () => controller.abort(options.signal?.reason);
199
+ options.signal?.addEventListener("abort", relay, { once: true });
200
+ const timer = setTimeout(
201
+ () => controller.abort(
202
+ new DOMException("Decision request timed out", "TimeoutError")
203
+ ),
204
+ options.timeoutMs ?? 6e4
205
+ );
206
+ let rejectAbort = () => {
207
+ };
208
+ const aborted = new Promise((_, reject) => {
209
+ rejectAbort = () => reject(controller.signal.reason);
210
+ controller.signal.addEventListener("abort", rejectAbort, { once: true });
211
+ });
212
+ const perform = async () => {
213
+ let response;
214
+ try {
215
+ response = await fetchFn(url, {
216
+ method: "POST",
217
+ headers,
218
+ body: encoded,
219
+ signal: controller.signal,
220
+ redirect: "error"
221
+ });
222
+ } catch {
223
+ controller.signal.throwIfAborted();
224
+ throw new DecisionAPIError(
225
+ "Decision request failed before receiving a response",
226
+ "network_error"
227
+ );
228
+ }
229
+ const requestId = response.headers.get("x-request-id") ?? response.headers.get("cf-ray") ?? void 0;
230
+ if (controller.signal.aborted) {
231
+ void response.body?.cancel().catch(() => {
232
+ });
233
+ controller.signal.throwIfAborted();
234
+ }
235
+ if (!response.ok) {
236
+ void response.body?.cancel().catch(() => {
237
+ });
238
+ throw new DecisionAPIError(
239
+ `Decision API returned HTTP ${response.status}`,
240
+ "http_error",
241
+ response.status,
242
+ requestId
243
+ );
244
+ }
245
+ if (!response.body)
246
+ decisionResponseError("Decision API returned an empty body");
247
+ const reader = response.body.getReader();
248
+ const cancel = () => {
249
+ void reader.cancel().catch(() => {
250
+ });
251
+ };
252
+ controller.signal.addEventListener("abort", cancel, { once: true });
253
+ const chunks = [];
254
+ let size = 0;
255
+ try {
256
+ while (true) {
257
+ controller.signal.throwIfAborted();
258
+ const { value: value2, done } = await reader.read();
259
+ if (done) break;
260
+ size += value2.byteLength;
261
+ if (size > 8 * 1024 * 1024) {
262
+ cancel();
263
+ decisionResponseError("Decision API response exceeds 8 MiB");
264
+ }
265
+ chunks.push(value2);
266
+ }
267
+ } catch (error) {
268
+ controller.signal.throwIfAborted();
269
+ if (error instanceof DecisionAPIError) throw error;
270
+ throw new DecisionAPIError(
271
+ "Decision response could not be read",
272
+ "network_error",
273
+ response.status,
274
+ requestId
275
+ );
276
+ } finally {
277
+ controller.signal.removeEventListener("abort", cancel);
278
+ reader.releaseLock();
279
+ }
280
+ controller.signal.throwIfAborted();
281
+ let value;
282
+ try {
283
+ value = JSON.parse(Buffer.concat(chunks).toString("utf8"));
284
+ } catch {
285
+ decisionResponseError("Decision API did not return valid JSON");
286
+ }
287
+ return { value, status: response.status, requestId };
288
+ };
289
+ try {
290
+ return await Promise.race([perform(), aborted]);
291
+ } finally {
292
+ clearTimeout(timer);
293
+ options.signal?.removeEventListener("abort", relay);
294
+ controller.signal.removeEventListener("abort", rejectAbort);
295
+ }
296
+ }
297
+
298
+ // src/providers/decisions/images.ts
299
+ function unsupportedDecision(message) {
300
+ throw new DecisionAPIError(message, "unsupported_option");
301
+ }
302
+ function prepareDecisionImages(images, provider) {
303
+ if (provider === "openrouter" && images.length)
304
+ unsupportedDecision(
305
+ "OpenRouter's native Decisions schema does not support image inputs"
306
+ );
307
+ if (provider === "cloudflare" && images.length > 4)
308
+ decisionInputError("Cloudflare Decisions supports at most four images");
309
+ if (provider === "openai" && images.length > 128)
310
+ decisionInputError("OpenAI Decisions supports at most 128 images");
311
+ let total = 0;
312
+ return images.map((image) => {
313
+ assertDecisionKeys(
314
+ image,
315
+ ["data", "mediaType", "detail"],
316
+ "Decision image"
317
+ );
318
+ if (image.detail !== void 0) {
319
+ if (provider !== "openai")
320
+ unsupportedDecision(
321
+ "Image detail is only supported by OpenAI Decisions"
322
+ );
323
+ if (!["auto", "low", "high", "original"].includes(image.detail))
324
+ decisionInputError("Invalid image detail");
325
+ }
326
+ const data = Buffer.from(image.data);
327
+ const signature = data.subarray(0, 12).toString("latin1");
328
+ const mediaType = signature.startsWith("\x89PNG\r\n\n") ? "image/png" : data[0] === 255 && data[1] === 216 && data[2] === 255 ? "image/jpeg" : signature.startsWith("RIFF") && signature.slice(8) === "WEBP" ? "image/webp" : /^GIF8[79]a/.test(signature) ? "image/gif" : void 0;
329
+ if (!mediaType || image.mediaType !== void 0 && image.mediaType !== mediaType)
330
+ decisionInputError(
331
+ "Decision image bytes must match a supported encoded image format"
332
+ );
333
+ if (provider === "typesafe" && !["image/png", "image/jpeg"].includes(mediaType))
334
+ unsupportedDecision("Jev images must be PNG or JPEG");
335
+ if (provider === "cloudflare" && mediaType === "image/gif")
336
+ unsupportedDecision("Cloudflare Decisions does not accept GIF images");
337
+ const limit = provider === "cloudflare" ? 4 : provider === "typesafe" ? 16 : 20;
338
+ if (data.length > limit * 1024 * 1024)
339
+ decisionInputError("Decision image exceeds this provider's file limit");
340
+ total += data.length;
341
+ if (provider === "cloudflare" && total > 8 * 1024 * 1024)
342
+ decisionInputError("Cloudflare Decisions images exceed 8 MiB total");
343
+ const base64 = data.toString("base64");
344
+ return {
345
+ url: `data:${mediaType};base64,${base64}`,
346
+ base64,
347
+ mediaType,
348
+ detail: image.detail
349
+ };
350
+ });
351
+ }
352
+
353
+ // src/providers/decisions/response.ts
354
+ function distribution(value, score) {
355
+ if (!Array.isArray(value))
356
+ decisionResponseError(
357
+ "OpenAI Decisions omitted its probability distribution"
358
+ );
359
+ const entries = [];
360
+ const seen = /* @__PURE__ */ new Set();
361
+ for (const item of value) {
362
+ if (!isDecisionRecord(item) || (score ? typeof item.value !== "number" || !Number.isInteger(item.value) || item.value < 0 : typeof item.value !== "string"))
363
+ decisionResponseError("Invalid decision probability option");
364
+ const key = String(item.value);
365
+ if (seen.has(key))
366
+ decisionResponseError("Duplicate option in decision probabilities");
367
+ seen.add(key);
368
+ entries.push([key, item.probability]);
369
+ }
370
+ return Object.fromEntries(entries);
371
+ }
372
+ function parseDecisionResponse(raw, provider, questions, status, requestId) {
373
+ if (!isDecisionRecord(raw))
374
+ decisionResponseError("Decision response must be an object");
375
+ let payload = raw;
376
+ if (provider === "cloudflare") {
377
+ if (raw.success === false)
378
+ throw new DecisionAPIError(
379
+ "Cloudflare reported an unsuccessful decision request",
380
+ "http_error",
381
+ status,
382
+ requestId
383
+ );
384
+ if (raw.success !== true || !isDecisionRecord(raw.result))
385
+ decisionResponseError(
386
+ "Cloudflare Decisions returned an invalid result envelope"
387
+ );
388
+ payload = raw.result;
389
+ }
390
+ if (typeof payload.model !== "string" || !payload.model)
391
+ decisionResponseError("Decision response omitted its model identity");
392
+ const entries = [];
393
+ if (provider === "openai") {
394
+ if (!Array.isArray(payload.answers))
395
+ decisionResponseError("OpenAI Decisions answers must be an array");
396
+ const seen = /* @__PURE__ */ new Set();
397
+ for (const answer of payload.answers) {
398
+ if (!isDecisionRecord(answer))
399
+ decisionResponseError("Invalid OpenAI decision answer");
400
+ if (answer.type === "refusal" && answer.name == null)
401
+ throw new DecisionAPIError(
402
+ "OpenAI refused an unnamed decision question",
403
+ "refusal",
404
+ status,
405
+ requestId
406
+ );
407
+ if (typeof answer.name !== "string" || seen.has(answer.name))
408
+ decisionResponseError(
409
+ "OpenAI decision answers have missing or duplicate question identities"
410
+ );
411
+ seen.add(answer.name);
412
+ entries.push([answer.name, answer]);
413
+ }
414
+ } else {
415
+ if (!isDecisionRecord(payload.answers))
416
+ decisionResponseError("Decisions answers must be a named map");
417
+ entries.push(...Object.entries(payload.answers));
418
+ }
419
+ const answers = Object.fromEntries(
420
+ entries.map(([id, value]) => {
421
+ if (!isDecisionRecord(value))
422
+ decisionResponseError("Invalid decision answer");
423
+ if (value.type === "refusal" && provider === "openai")
424
+ return [id, { type: "refusal" }];
425
+ const booleanType = provider === "openai" ? "predicate" : "noul";
426
+ if (value.type === booleanType)
427
+ return [
428
+ id,
429
+ {
430
+ type: "boolean",
431
+ probability: provider === "openai" ? value.probability : value.noul
432
+ }
433
+ ];
434
+ if (value.type !== "choice" && value.type !== "score")
435
+ decisionResponseError(
436
+ "Provider returned an unsupported decision answer type"
437
+ );
438
+ if (provider !== "openrouter" && value.probabilities == null)
439
+ decisionResponseError(
440
+ "Provider omitted a required decision distribution"
441
+ );
442
+ const probabilities = provider === "openai" ? distribution(value.probabilities, value.type === "score") : value.probabilities;
443
+ const fields = {
444
+ ...probabilities !== void 0 && {
445
+ probabilities
446
+ },
447
+ ...value.confidence != null && {
448
+ confidence: value.confidence
449
+ }
450
+ };
451
+ return [
452
+ id,
453
+ value.type === "choice" ? { type: "choice", choice: value.choice, ...fields } : { type: "score", score: value.score, ...fields }
454
+ ];
455
+ })
456
+ );
457
+ const result = {
458
+ answers,
459
+ response: {
460
+ provider,
461
+ modelId: payload.model,
462
+ status,
463
+ requestId: requestId ?? (typeof payload.id === "string" ? payload.id : void 0),
464
+ body: raw
465
+ }
466
+ };
467
+ const typesafe = provider === "typesafe" || provider === "openrouter" && (payload.model.startsWith("typesafe/") || payload.provider === "TypeSafe");
468
+ if (typesafe) result.rounding = { probabilityDecimals: 2, scoreDecimals: 2 };
469
+ if (payload.usage != null) {
470
+ if (!isDecisionRecord(payload.usage))
471
+ decisionResponseError("Invalid decision usage");
472
+ const usage = payload.usage;
473
+ const details = isDecisionRecord(usage.input_tokens_details) ? usage.input_tokens_details : {};
474
+ result.usage = {};
475
+ const mapped = {
476
+ inputTokens: usage.input_tokens,
477
+ outputTokens: usage.output_tokens,
478
+ totalTokens: usage.total_tokens,
479
+ cachedInputTokens: details.cached_tokens,
480
+ cacheWriteTokens: details.cache_write_tokens,
481
+ costUsd: usage.cost
482
+ };
483
+ for (const [key, value] of Object.entries(mapped)) {
484
+ if (value == null) continue;
485
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0 || key !== "costUsd" && !Number.isInteger(value))
486
+ decisionResponseError("Invalid decision usage count");
487
+ result.usage[key] = value;
488
+ }
489
+ }
490
+ validateDecisionResult(questions, result);
491
+ return result;
492
+ }
493
+
494
+ // src/providers/decisions/model.ts
495
+ function asText(value) {
496
+ return typeof value === "string" ? value : JSON.stringify(value);
497
+ }
498
+ function requestOptions(options, provider) {
499
+ for (const key of Object.keys(options.providerOptions ?? {})) {
500
+ if (key !== provider)
501
+ unsupportedDecision(
502
+ "Decision providerOptions must match the selected provider"
503
+ );
504
+ }
505
+ const opts = options.providerOptions?.[provider] ?? {};
506
+ if (!isDecisionRecord(opts))
507
+ decisionInputError("Decision provider options must be an object");
508
+ const allowed = provider === "openai" ? ["safetyIdentifier", "promptCacheKey"] : provider === "typesafe" ? ["longContext"] : provider === "openrouter" ? ["sessionId", "provider"] : [];
509
+ assertDecisionKeys(opts, allowed, "Decision provider options");
510
+ for (const [key, limit] of [
511
+ ["safetyIdentifier", 128],
512
+ ["promptCacheKey", 64],
513
+ ["sessionId", 256]
514
+ ]) {
515
+ if (opts[key] !== void 0 && (typeof opts[key] !== "string" || opts[key].length > limit))
516
+ decisionInputError("Invalid decision identifier or cache key");
517
+ }
518
+ if (opts.longContext !== void 0 && typeof opts.longContext !== "boolean")
519
+ decisionInputError("longContext must be boolean");
520
+ if (opts.provider !== void 0) {
521
+ if (!isDecisionRecord(opts.provider))
522
+ decisionInputError("OpenRouter routing preferences must be an object");
523
+ assertDecisionKeys(
524
+ opts.provider,
525
+ ["order", "allowFallbacks"],
526
+ "OpenRouter routing preferences"
527
+ );
528
+ if (opts.provider.allowFallbacks !== void 0 && typeof opts.provider.allowFallbacks !== "boolean")
529
+ decisionInputError("allowFallbacks must be boolean");
530
+ if (opts.provider.order !== void 0 && (!Array.isArray(opts.provider.order) || !opts.provider.order.every(
531
+ (value) => typeof value === "string" && value.length
532
+ )))
533
+ decisionInputError("Provider order must be an array of provider names");
534
+ }
535
+ return opts;
536
+ }
537
+ function nativeDecisionModel(modelId, config) {
538
+ if (typeof modelId !== "string" || !modelId.trim())
539
+ decisionInputError("Decision model ID is required");
540
+ const provider = config.provider;
541
+ return {
542
+ provider,
543
+ modelId,
544
+ async doDecide(options) {
545
+ validateDecisionInput(options);
546
+ options.signal?.throwIfAborted();
547
+ const opts = requestOptions(options, provider);
548
+ const questions = Object.entries(options.questions);
549
+ if (provider === "openai" && questions.length > 200)
550
+ decisionInputError("OpenAI Decisions supports at most 200 questions");
551
+ if (provider === "cloudflare" && (questions.length > 64 || questions.some(([id]) => !/^[A-Za-z0-9_.-]{1,100}$/.test(id))))
552
+ decisionInputError(
553
+ "Cloudflare supports 1\u201364 questions with IDs of 1\u2013100 letters, digits, underscores, dots, or hyphens"
554
+ );
555
+ for (const [, question] of questions) {
556
+ if (provider !== "openai" && question.type === "score" && question.criteria.length > 10)
557
+ decisionInputError(
558
+ "System One adapters support at most ten score levels"
559
+ );
560
+ if (provider === "cloudflare" && typeof question.instructions === "string" && !question.instructions.trim())
561
+ decisionInputError("Cloudflare requires nonempty instructions");
562
+ if (provider === "openrouter" && question.type === "boolean" && question.criteria !== void 0 && (question.criteria.true === void 0 || question.criteria.false === void 0))
563
+ decisionInputError(
564
+ "OpenRouter boolean criteria must describe both true and false when supplied"
565
+ );
566
+ }
567
+ const images = prepareDecisionImages(options.images ?? [], provider);
568
+ const headers = Object.fromEntries(
569
+ Object.entries(config.headers ?? {}).filter(
570
+ ([name]) => !["authorization", "content-type"].includes(name.toLowerCase())
571
+ )
572
+ );
573
+ headers["Content-Type"] = "application/json";
574
+ const key = config.apiKey ?? process.env[config.keyEnv];
575
+ if (!key?.trim())
576
+ decisionInputError(`Missing ${config.keyEnv} for Decisions`);
577
+ headers.Authorization = `Bearer ${key}`;
578
+ let body;
579
+ if (provider === "openai") {
580
+ body = {
581
+ model: modelId,
582
+ input: [
583
+ {
584
+ role: "user",
585
+ content: [
586
+ { type: "input_text", text: asText(options.state) },
587
+ ...images.map((image) => ({
588
+ type: "input_image",
589
+ image_url: image.url,
590
+ ...image.detail !== void 0 && { detail: image.detail }
591
+ }))
592
+ ]
593
+ }
594
+ ],
595
+ questions: questions.map(([name, question]) => {
596
+ const instructions = asText(question.instructions);
597
+ if (question.type === "boolean")
598
+ return {
599
+ type: "predicate",
600
+ name,
601
+ instructions: [
602
+ instructions,
603
+ ...Object.entries(question.criteria ?? {}).map(
604
+ ([key2, value]) => `Criteria for ${key2}:
605
+ ${asText(value)}`
606
+ )
607
+ ].join("\n\n")
608
+ };
609
+ if (question.type === "choice")
610
+ return {
611
+ type: "choice",
612
+ name,
613
+ instructions,
614
+ choices: Object.entries(question.criteria).map(
615
+ ([value, description]) => ({
616
+ value,
617
+ ...description !== null && {
618
+ description: asText(description)
619
+ }
620
+ })
621
+ )
622
+ };
623
+ return {
624
+ type: "score",
625
+ name,
626
+ instructions,
627
+ levels: question.criteria.map((description, index) => ({
628
+ label: String(index),
629
+ description: asText(description)
630
+ }))
631
+ };
632
+ }),
633
+ ...opts.safetyIdentifier !== void 0 && {
634
+ safety_identifier: opts.safetyIdentifier
635
+ },
636
+ ...opts.promptCacheKey !== void 0 && {
637
+ prompt_cache_key: opts.promptCacheKey
638
+ }
639
+ };
640
+ } else {
641
+ body = {
642
+ model: config.bodyModel ?? modelId,
643
+ state: options.state,
644
+ questions: Object.fromEntries(
645
+ questions.map(([id, question]) => [
646
+ id,
647
+ {
648
+ ...question,
649
+ type: question.type === "boolean" ? "noul" : question.type
650
+ }
651
+ ])
652
+ )
653
+ };
654
+ if (provider === "typesafe") {
655
+ if (opts.longContext)
656
+ headers["TypeSafe-Danger-Zone-Long-Context"] = "true";
657
+ if (images.length) {
658
+ const refs = images.map(() => randomUUID());
659
+ body.state = { state: options.state, images: refs };
660
+ body.assets = Object.fromEntries(
661
+ images.map((image, index) => [
662
+ refs[index],
663
+ {
664
+ type: "image",
665
+ data_base64: image.base64,
666
+ format: image.mediaType === "image/png" ? "png" : "jpeg"
667
+ }
668
+ ])
669
+ );
670
+ headers["TypeSafe-Danger-Zone-Images"] = "true";
671
+ }
672
+ } else if (provider === "cloudflare" && images.length) {
673
+ body.images = images.map((image) => ({
674
+ content_type: image.mediaType,
675
+ base64: image.base64
676
+ }));
677
+ } else if (provider === "openrouter") {
678
+ if (opts.sessionId !== void 0) body.session_id = opts.sessionId;
679
+ if (isDecisionRecord(opts.provider))
680
+ body.provider = {
681
+ ...opts.provider.order !== void 0 && {
682
+ order: opts.provider.order
683
+ },
684
+ ...opts.provider.allowFallbacks !== void 0 && {
685
+ allow_fallbacks: opts.provider.allowFallbacks
686
+ }
687
+ };
688
+ }
689
+ }
690
+ const base = config.baseUrl ?? config.defaultBaseUrl;
691
+ let url;
692
+ try {
693
+ url = new URL(`${base.replace(/\/+$/, "")}${config.path}`);
694
+ } catch {
695
+ decisionInputError("Invalid Decisions base URL");
696
+ }
697
+ if (!["https:", "http:"].includes(url.protocol) || url.username || url.password || url.search || url.hash)
698
+ decisionInputError(
699
+ "Decisions base URL must be an HTTP(S) API root without credentials, query, or fragment"
700
+ );
701
+ const response = await postDecision(
702
+ url.href,
703
+ headers,
704
+ body,
705
+ options,
706
+ config.fetch ?? globalThis.fetch,
707
+ (provider === "cloudflare" ? 13 : 32) * 1024 * 1024
708
+ );
709
+ return parseDecisionResponse(
710
+ response.value,
711
+ provider,
712
+ options.questions,
713
+ response.status,
714
+ response.requestId
715
+ );
716
+ }
717
+ };
718
+ }
719
+
720
+ // src/providers/typesafe/index.ts
721
+ function typesafeDecision(modelId = "jev-latest", options = {}) {
722
+ return nativeDecisionModel(modelId, {
723
+ ...options,
724
+ provider: "typesafe",
725
+ keyEnv: "TYPESAFE_AI_API_KEY",
726
+ defaultBaseUrl: "https://api.typesafe.ai/v1",
727
+ path: "/systemone"
728
+ });
729
+ }
730
+
731
+ export { typesafeDecision };
732
+ //# sourceMappingURL=index.mjs.map
733
+ //# sourceMappingURL=index.mjs.map