@abhishek944/pi-classifier 0.3.0 → 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.
Files changed (77) hide show
  1. package/CHANGELOG.md +48 -0
  2. package/COMPUTER_USE.md +117 -0
  3. package/README.md +344 -30
  4. package/dist/auth.d.ts +4 -2
  5. package/dist/auth.js +18 -2
  6. package/dist/box-tool.d.ts +4 -0
  7. package/dist/box-tool.js +79 -0
  8. package/dist/box.d.ts +32 -0
  9. package/dist/box.js +148 -0
  10. package/dist/choices.js +35 -1
  11. package/dist/classify.d.ts +6 -0
  12. package/dist/classify.js +4 -4
  13. package/dist/computer-use-state.d.ts +9 -0
  14. package/dist/computer-use-state.js +160 -0
  15. package/dist/computer-use-tool.d.ts +52 -0
  16. package/dist/computer-use-tool.js +78 -0
  17. package/dist/computer-use-types.d.ts +132 -0
  18. package/dist/computer-use-types.js +1 -0
  19. package/dist/computer-use.d.ts +22 -0
  20. package/dist/computer-use.js +223 -0
  21. package/dist/config.d.ts +140 -3
  22. package/dist/config.js +405 -20
  23. package/dist/cost.js +42 -4
  24. package/dist/durable.d.ts +34 -0
  25. package/dist/durable.js +237 -0
  26. package/dist/extension.d.ts +2 -247
  27. package/dist/extension.js +53 -190
  28. package/dist/extract.d.ts +11 -0
  29. package/dist/extract.js +191 -0
  30. package/dist/http.d.ts +6 -1
  31. package/dist/http.js +64 -28
  32. package/dist/image-content.d.ts +12 -0
  33. package/dist/image-content.js +90 -0
  34. package/dist/index.d.ts +10 -1
  35. package/dist/index.js +3 -0
  36. package/dist/inputs.d.ts +24 -2
  37. package/dist/inputs.js +565 -134
  38. package/dist/mcp-cli.d.ts +2 -0
  39. package/dist/mcp-cli.js +39 -0
  40. package/dist/mcp-server.d.ts +28 -0
  41. package/dist/mcp-server.js +121 -0
  42. package/dist/mcp-tool-definitions.d.ts +19 -0
  43. package/dist/mcp-tool-definitions.js +64 -0
  44. package/dist/providers.d.ts +1 -0
  45. package/dist/providers.js +1218 -124
  46. package/dist/tool-contracts.d.ts +785 -0
  47. package/dist/tool-contracts.js +530 -0
  48. package/dist/tree.js +1 -1
  49. package/dist/types.d.ts +314 -20
  50. package/dist/validation.js +181 -44
  51. package/package.json +33 -5
  52. package/src/auth.ts +26 -2
  53. package/src/box-tool.ts +110 -0
  54. package/src/box.ts +253 -0
  55. package/src/choices.ts +44 -2
  56. package/src/classify.ts +10 -6
  57. package/src/computer-use-state.ts +145 -0
  58. package/src/computer-use-tool.ts +76 -0
  59. package/src/computer-use-types.ts +127 -0
  60. package/src/computer-use.ts +216 -0
  61. package/src/config.ts +454 -23
  62. package/src/cost.ts +42 -4
  63. package/src/durable.ts +298 -0
  64. package/src/extension.ts +79 -265
  65. package/src/extract.ts +228 -0
  66. package/src/http.ts +63 -32
  67. package/src/image-content.ts +77 -0
  68. package/src/index.ts +25 -0
  69. package/src/inputs.ts +603 -184
  70. package/src/mcp-cli.ts +44 -0
  71. package/src/mcp-server.ts +179 -0
  72. package/src/mcp-tool-definitions.ts +104 -0
  73. package/src/providers.ts +1398 -144
  74. package/src/tool-contracts.ts +785 -0
  75. package/src/tree.ts +1 -1
  76. package/src/types.ts +248 -11
  77. package/src/validation.ts +169 -96
package/dist/providers.js CHANGED
@@ -1,6 +1,8 @@
1
1
  import { randomUUID } from "node:crypto";
2
+ import { imageContentParts, imageReferences, imageUrl, isImageReference, mapImageReferences, namedImage, questionImageReferences } from "./image-content.js";
2
3
  import { postJson } from "./http.js";
3
4
  import { estimateCost, tokenCount } from "./cost.js";
5
+ import { openRouterDecisionCapabilities } from "./config.js";
4
6
  import { ClassifierError, isRecord, } from "./types.js";
5
7
  /**
6
8
  * Provider protocol adapters. Every request goes through the shared `postJson` boundary, which
@@ -10,6 +12,7 @@ import { ClassifierError, isRecord, } from "./types.js";
10
12
  */
11
13
  const OPENAI_LABEL = "OpenAI Decisions";
12
14
  const PERPLEXITY_LABEL = "Perplexity Decisions";
15
+ const SARVAM_LABEL = "Sarvam Prism";
13
16
  const TYPESAFE_LABEL = "TypeSafe System One";
14
17
  const CLOUDFLARE_LABEL = "Cloudflare Workers AI";
15
18
  const EPSILON = 1e-6;
@@ -18,10 +21,24 @@ export async function classifyWithProvider(route, input, apiKey, signal) {
18
21
  switch (route.api) {
19
22
  case "openai-decisions":
20
23
  return classifyOpenAi(route, input, apiKey, signal);
24
+ case "openrouter-decisions":
25
+ return classifyOpenRouter(route, input, apiKey, signal);
26
+ case "gemini-decisions":
27
+ return classifyGemini(route, input, apiKey, signal);
28
+ case "inception-decisions":
29
+ return classifyInception(route, input, apiKey, signal);
30
+ case "parallel-decisions":
31
+ return classifyParallel(route, input, apiKey, signal);
32
+ case "local-system-one":
33
+ return classifyLocalSystemOne(route, input, apiKey, signal);
21
34
  case "perplexity-decisions":
22
35
  return classifyPerplexity(route, input, apiKey, signal);
36
+ case "sarvam-system-one":
37
+ return classifySarvam(route, input, apiKey, signal);
23
38
  case "system-one":
24
39
  return classifySystemOne(route, input, apiKey, signal);
40
+ case "liquid-system-one":
41
+ return classifyLiquid(route, input, apiKey, signal);
25
42
  case "microsoft-system-one":
26
43
  return classifyMicrosoft(route, input, apiKey, signal);
27
44
  case "cloudflare-system-one":
@@ -79,7 +96,20 @@ function normalizedUsage(value) {
79
96
  }
80
97
  return usage;
81
98
  }
82
- function finish(route, answers, rawUsage, requestId) {
99
+ function reportedCost(value, source) {
100
+ if (!isRecord(value))
101
+ return undefined;
102
+ const raw = value.cost;
103
+ const total = typeof raw === "number" && Number.isFinite(raw) && raw >= 0
104
+ ? raw
105
+ : typeof raw === "string" && /^\d+(?:\.\d+)?$/.test(raw)
106
+ ? Number(raw)
107
+ : undefined;
108
+ if (total === undefined)
109
+ return undefined;
110
+ return { currency: "USD", total, source };
111
+ }
112
+ function finish(route, answers, rawUsage, requestId, providerCost) {
83
113
  const result = {
84
114
  provider: route.route,
85
115
  model: route.model,
@@ -91,10 +121,46 @@ function finish(route, answers, rawUsage, requestId) {
91
121
  result.usage = usage;
92
122
  if (requestId !== undefined)
93
123
  result.requestId = requestId;
124
+ if (providerCost !== undefined)
125
+ result.providerCost = providerCost;
94
126
  return result;
95
127
  }
96
- function dataUrl(image) {
97
- return "data:" + image.mimeType + ";base64," + image.data;
128
+ function textContent(value) {
129
+ if (typeof value === "string")
130
+ return value;
131
+ if (value.some((part) => typeof part !== "string"))
132
+ throw new ClassifierError("capability", "This content placement does not support images on the selected route.");
133
+ return value.join("");
134
+ }
135
+ function openAiImagePart(image, detail) {
136
+ return {
137
+ type: "input_image",
138
+ image_url: imageUrl(image),
139
+ ...(detail !== undefined ? { detail } : {}),
140
+ };
141
+ }
142
+ function openAiContent(value, input) {
143
+ return imageContentParts(value, (id) => openAiImagePart(namedImage(input.images, id), input.imageDetail))
144
+ .map((part) => typeof part === "string" ? { type: "input_text", text: part } : part);
145
+ }
146
+ function jsonValueCount(value) {
147
+ let total = 1;
148
+ if (Array.isArray(value))
149
+ for (const entry of value)
150
+ total += jsonValueCount(entry);
151
+ else if (isRecord(value))
152
+ for (const entry of Object.values(value))
153
+ total += jsonValueCount(entry);
154
+ return total;
155
+ }
156
+ function openAiJsonPart(value) {
157
+ if (isRecord(value) || (Array.isArray(value) && value.every((entry) => isRecord(entry)))) {
158
+ const bytes = Buffer.byteLength(JSON.stringify(value));
159
+ if (bytes > 256 * 1024 || jsonValueCount(value) > 10_000)
160
+ fail(OPENAI_LABEL + " input_json exceeds the documented 256 KiB / 10,000-value limit. Supply a smaller JSON state.");
161
+ return { type: "input_json", data: value };
162
+ }
163
+ return undefined;
98
164
  }
99
165
  /* Answer parsing for map-shaped answers (Perplexity, System One, Clef) --- */
100
166
  function labelProbabilities(label, id, value, labels) {
@@ -116,6 +182,25 @@ function labelProbabilities(label, id, value, labels) {
116
182
  return checkDistribution(label, id, result);
117
183
  }
118
184
  /** Probability mass must be close to 1; it is never renormalized on the caller's behalf. */
185
+ function independentLabelProbabilities(label, id, value, labels) {
186
+ if (!isRecord(value))
187
+ fail(label + " returned invalid probabilities for " + id + ".");
188
+ const result = Object.create(null);
189
+ for (const [key, entry] of Object.entries(value)) {
190
+ if (!labels.includes(key))
191
+ fail(label +
192
+ " returned an unknown option in the probabilities for " +
193
+ id +
194
+ ".");
195
+ result[key] = probability(label, entry, "probability for " + id + "." + key);
196
+ }
197
+ for (const key of labels) {
198
+ if (!Object.hasOwn(result, key))
199
+ fail(label + " did not return a probability for " + id + "." + key + ".");
200
+ }
201
+ // Liquid multi-select questions treat each label as its own yes/no decision.
202
+ return result;
203
+ }
119
204
  function checkDistribution(label, id, probabilities) {
120
205
  let total = 0;
121
206
  for (const value of Object.values(probabilities))
@@ -158,6 +243,47 @@ function scoreValue(label, id, value, levels) {
158
243
  fail(label + " returned a score outside the rubric for " + id + ".");
159
244
  return Math.min(maximum, Math.max(0, value));
160
245
  }
246
+ function nonNegativeInteger(label, value, field) {
247
+ if (!Number.isSafeInteger(value) || value < 0)
248
+ fail(label + " returned an invalid " + field + ".");
249
+ return value;
250
+ }
251
+ function codePointSlice(source, start, end) {
252
+ const characters = Array.from(source);
253
+ if (start > end || end > characters.length)
254
+ return "";
255
+ return characters.slice(start, end).join("");
256
+ }
257
+ function parseTextSpans(label, id, value, sources) {
258
+ if (!Array.isArray(value))
259
+ fail(label + " returned invalid spans for " + id + ".");
260
+ return value.map((entry, index) => {
261
+ if (!isRecord(entry))
262
+ fail(label + " returned an invalid span for " + id + ".");
263
+ const start = nonNegativeInteger(label, entry.start, "span offset for " + id);
264
+ const end = nonNegativeInteger(label, entry.end, "span offset for " + id);
265
+ if (typeof entry.text !== "string" || end < start)
266
+ fail(label + " returned an invalid span for " + id + ".");
267
+ let searchResult;
268
+ if (entry.search_result !== undefined) {
269
+ searchResult = nonNegativeInteger(label, entry.search_result, "search result index for " + id);
270
+ if (sources.snippets === undefined || searchResult >= sources.snippets.length)
271
+ fail(label + " returned an unknown search result for " + id + ".");
272
+ }
273
+ const source = searchResult === undefined ? sources.state : sources.snippets[searchResult];
274
+ if (source === undefined || codePointSlice(source, start, end) !== entry.text)
275
+ fail(label + " returned a span that does not match its source for " + id + ".");
276
+ const span = {
277
+ start,
278
+ end,
279
+ text: entry.text,
280
+ score: probability(label, entry.score, "span score for " + id + "." + index),
281
+ };
282
+ if (searchResult !== undefined)
283
+ span.searchResult = searchResult;
284
+ return span;
285
+ });
286
+ }
161
287
  function parseBox(label, id, value, confidence) {
162
288
  if (!isRecord(value))
163
289
  fail(label + " returned an invalid box for " + id + ".");
@@ -181,7 +307,7 @@ function parseBox(label, id, value, confidence) {
181
307
  confidence: probability(label, confidence, "confidence for " + id),
182
308
  };
183
309
  }
184
- function parseTypedAnswer(label, id, question, answer) {
310
+ function parseTypedAnswer(label, id, question, answer, sources = {}) {
185
311
  if (!isRecord(answer))
186
312
  fail(label + " returned an invalid answer for " + id + ".");
187
313
  if (answer.type === "refusal")
@@ -222,6 +348,11 @@ function parseTypedAnswer(label, id, question, answer) {
222
348
  probabilities: levelProbabilities(label, id, answer.probabilities, question.criteria.length),
223
349
  };
224
350
  }
351
+ if (question.type === "locate") {
352
+ if (answer.type !== "locate")
353
+ fail(label + " did not return a locate answer for " + id + ".");
354
+ return { type: "locate", spans: parseTextSpans(label, id, answer.spans, sources) };
355
+ }
225
356
  if (answer.type !== "box")
226
357
  fail(label + " did not return a box answer for " + id + ".");
227
358
  return parseBox(label, id, answer.box, answer.confidence);
@@ -247,7 +378,7 @@ function validateDecision(label, id, answer) {
247
378
  }
248
379
  return answer;
249
380
  }
250
- function parseTypedAnswers(label, value, questions) {
381
+ function parseTypedAnswers(label, value, questions, sources = {}) {
251
382
  if (!isRecord(value))
252
383
  fail(label + " returned an unexpected response.");
253
384
  // Question IDs may be "__proto__", so answers are collected without a prototype.
@@ -255,7 +386,7 @@ function parseTypedAnswers(label, value, questions) {
255
386
  for (const [id, question] of Object.entries(questions)) {
256
387
  if (!Object.hasOwn(value, id))
257
388
  fail(label + " did not return an answer for " + id + ".");
258
- answers[id] = validateDecision(label, id, parseTypedAnswer(label, id, question, value[id]));
389
+ answers[id] = validateDecision(label, id, parseTypedAnswer(label, id, question, value[id], sources));
259
390
  }
260
391
  return answers;
261
392
  }
@@ -263,71 +394,119 @@ function parseTypedAnswers(label, value, questions) {
263
394
  function predicateInstructions(question) {
264
395
  const meanings = [];
265
396
  if (question.criteria?.true)
266
- meanings.push("True means: " + question.criteria.true);
397
+ meanings.push("True means: " + textContent(question.criteria.true));
267
398
  if (question.criteria?.false)
268
- meanings.push("False means: " + question.criteria.false);
269
- return meanings.length > 0
270
- ? question.instructions + "\n" + meanings.join("\n")
271
- : question.instructions;
399
+ meanings.push("False means: " + textContent(question.criteria.false));
400
+ if (meanings.length === 0)
401
+ return question.instructions;
402
+ const suffix = "\n" + meanings.join("\n");
403
+ return typeof question.instructions === "string" ? question.instructions + suffix : [...question.instructions, suffix];
272
404
  }
273
- function openAiQuestion(id, question) {
405
+ function openAiQuestion(id, question, input) {
406
+ const instructions = question.type === "bool" ? predicateInstructions(question) : question.instructions;
407
+ const wireInstructions = typeof instructions === "string" ? instructions : openAiContent(instructions, input);
274
408
  if (question.type === "bool")
409
+ return { type: "predicate", name: id, instructions: wireInstructions };
410
+ if (question.type === "choice")
275
411
  return {
276
- type: "predicate",
277
- name: id,
278
- instructions: predicateInstructions(question),
412
+ type: "choice", name: id, instructions: wireInstructions,
413
+ choices: Object.entries(question.criteria).map(([value, description]) => ({
414
+ // Only caller-supplied boolean labels map to booleans. The internal NONE sentinel
415
+ // remains a distinct string so boolean questions can still reject all options.
416
+ value: question.booleanValues && (value === "true" || value === "false") ? value === "true" : value,
417
+ description: textContent(description),
418
+ })),
279
419
  };
280
- if (question.type === "choice") {
420
+ if (question.type === "score")
281
421
  return {
282
- type: "choice",
283
- name: id,
284
- instructions: question.instructions,
285
- choices: Object.entries(question.criteria).map(([value, description]) => ({ value, description })),
422
+ type: "score", name: id, instructions: wireInstructions,
423
+ levels: question.criteria.map((label, index) => ({
424
+ label: textContent(label),
425
+ ...(question.descriptions?.[index] !== undefined ? { description: question.descriptions[index] } : {}),
426
+ })),
286
427
  };
287
- }
288
- if (question.type === "score") {
289
- return {
290
- type: "score",
291
- name: id,
292
- instructions: question.instructions,
293
- levels: question.criteria.map((label) => ({ label })),
428
+ throw unsupportedBox();
429
+ }
430
+ function openAiCachePayload(input) {
431
+ const payload = {};
432
+ if (input.promptCache?.key !== undefined)
433
+ payload.prompt_cache_key = input.promptCache.key;
434
+ if (input.promptCache?.mode !== undefined || input.promptCache?.ttl !== undefined)
435
+ payload.prompt_cache_options = {
436
+ ...(input.promptCache?.mode !== undefined ? { mode: input.promptCache.mode } : {}),
437
+ ...(input.promptCache?.ttl !== undefined ? { ttl: input.promptCache.ttl } : {}),
294
438
  };
439
+ return payload;
440
+ }
441
+ function openAiSetBreakpoint(parts) {
442
+ const first = parts.find((part) => isRecord(part) && (part.type === "input_text" || part.type === "input_image"));
443
+ if (isRecord(first)) {
444
+ first.prompt_cache_breakpoint = { mode: "explicit" };
445
+ return true;
295
446
  }
296
- throw unsupportedBox();
447
+ return false;
448
+ }
449
+ function openAiStateParts(input) {
450
+ const text = typeof input.state === "string" ? input.state : JSON.stringify(input.state);
451
+ const references = imageReferences(input.state);
452
+ const parts = references.length > 0
453
+ ? openAiContent(input.state, input)
454
+ : text
455
+ ? (() => {
456
+ const jsonPart = typeof input.state === "string" ? undefined : openAiJsonPart(input.state);
457
+ return jsonPart ? [{ type: "input_text", text: "Structured state:" }, jsonPart] : [{ type: "input_text", text }];
458
+ })()
459
+ : [];
460
+ for (const image of input.images.filter((entry) => entry.id === undefined))
461
+ parts.push(openAiImagePart(image, input.imageDetail));
462
+ return parts;
297
463
  }
298
464
  function openAiInput(input) {
465
+ const payload = openAiCachePayload(input);
466
+ if (input.conversation !== undefined) {
467
+ const items = input.conversation.map((item) => ({ ...(isRecord(item) ? item : {}) }));
468
+ const stateParts = openAiStateParts(input);
469
+ if (stateParts.length > 0)
470
+ items.unshift({ type: "message", role: "user", content: stateParts });
471
+ if (input.promptCache?.breakpoints) {
472
+ const userItem = items.find((item) => isRecord(item) && item.type === "message" && item.role === "user" && Array.isArray(item.content));
473
+ if (!isRecord(userItem) || !openAiSetBreakpoint(userItem.content)) {
474
+ const parts = [{ type: "input_text", text: "", prompt_cache_breakpoint: { mode: "explicit" } }];
475
+ items.unshift({ type: "message", role: "user", content: parts });
476
+ }
477
+ }
478
+ return { input: items, payload };
479
+ }
480
+ const content = openAiStateParts(input);
481
+ const breakpointSet = input.promptCache?.breakpoints === true && openAiSetBreakpoint(content);
482
+ if (!breakpointSet && input.promptCache?.breakpoints)
483
+ content.unshift({ type: "input_text", text: "", prompt_cache_breakpoint: { mode: "explicit" } });
299
484
  const text = typeof input.state === "string" ? input.state : JSON.stringify(input.state);
300
- if (input.images.length === 0)
301
- return text;
302
- return [
303
- {
304
- role: "user",
305
- content: [
306
- { type: "input_text", text },
307
- ...input.images.map((image) => ({
308
- type: "input_image",
309
- image_url: dataUrl(image),
310
- })),
311
- ],
312
- },
313
- ];
485
+ if (!breakpointSet &&
486
+ input.promptCache?.breakpoints !== true &&
487
+ content.length === 1 &&
488
+ isRecord(content[0]) &&
489
+ content[0].type === "input_text" &&
490
+ content[0].text === text &&
491
+ Object.keys(payload).length === 0)
492
+ return { input: text, payload };
493
+ return { input: [{ type: "message", role: "user", content }], payload };
314
494
  }
315
- function openAiChoiceProbabilities(label, id, value, labels) {
495
+ function openAiChoiceProbabilities(label, id, value, labels, booleanValues) {
316
496
  if (!Array.isArray(value))
317
497
  fail(label + " returned invalid probabilities for " + id + ".");
318
498
  const mapped = Object.create(null);
319
499
  for (const entry of value) {
320
- if (!isRecord(entry) ||
321
- typeof entry.value !== "string" ||
322
- !labels.includes(entry.value)) {
323
- fail(label +
324
- " returned an unknown option in the probabilities for " +
325
- id +
326
- ".");
327
- }
328
- if (Object.hasOwn(mapped, entry.value))
500
+ if (!isRecord(entry))
501
+ fail(label + " returned an unknown option in the probabilities for " + id + ".");
502
+ const key = booleanValues && typeof entry.value === "boolean"
503
+ ? (entry.value ? "true" : "false")
504
+ : typeof entry.value === "string" ? entry.value : undefined;
505
+ if (key === undefined || !labels.includes(key))
506
+ fail(label + " returned an unknown option in the probabilities for " + id + ".");
507
+ if (Object.hasOwn(mapped, key))
329
508
  fail(label + " returned duplicate probabilities for " + id + ".");
330
- mapped[entry.value] = entry.probability;
509
+ mapped[key] = entry.probability;
331
510
  }
332
511
  return labelProbabilities(label, id, mapped, labels);
333
512
  }
@@ -366,14 +545,17 @@ function parseOpenAiAnswer(label, id, question, answer) {
366
545
  };
367
546
  }
368
547
  if (question.type === "choice") {
369
- if (answer.type !== "choice" || typeof answer.choice !== "string")
548
+ if (answer.type !== "choice")
370
549
  fail(label + " did not return a choice answer for " + id + ".");
371
- if (!Object.hasOwn(question.criteria, answer.choice))
550
+ const choice = question.booleanValues && typeof answer.choice === "boolean"
551
+ ? (answer.choice ? "true" : "false")
552
+ : typeof answer.choice === "string" ? answer.choice : undefined;
553
+ if (choice === undefined || !Object.hasOwn(question.criteria, choice))
372
554
  fail(label + " returned an unknown choice for " + id + ".");
373
555
  return {
374
556
  type: "choice",
375
- choice: answer.choice,
376
- probabilities: openAiChoiceProbabilities(label, id, answer.probabilities, Object.keys(question.criteria)),
557
+ choice,
558
+ probabilities: openAiChoiceProbabilities(label, id, answer.probabilities, Object.keys(question.criteria), question.booleanValues === true),
377
559
  confidence: probability(label, answer.confidence, "confidence for " + id),
378
560
  };
379
561
  }
@@ -416,86 +598,712 @@ function parseOpenAiAnswers(label, value, questions) {
416
598
  return answers;
417
599
  }
418
600
  async function classifyOpenAi(route, input, apiKey, signal) {
419
- const questions = Object.entries(input.questions).map(([id, question]) => openAiQuestion(id, question));
420
- const { body, requestId } = await postJson(route, "decisions", {
601
+ const questions = Object.entries(input.questions).map(([id, question]) => openAiQuestion(id, question, input));
602
+ const preparedInput = openAiInput(input);
603
+ const { body, requestId, costHeader } = await postJson(route, "decisions", {
421
604
  model: route.model,
422
- input: openAiInput(input),
605
+ input: preparedInput.input,
423
606
  questions,
607
+ ...preparedInput.payload,
424
608
  }, apiKey, signal);
425
609
  if (!isRecord(body))
426
610
  fail(OPENAI_LABEL + " returned an unexpected response.");
427
- return finish(route, parseOpenAiAnswers(OPENAI_LABEL, body.answers, input.questions), body.usage, requestId);
611
+ const metadata = isRecord(body.provider_metadata) ? body.provider_metadata.gateway : undefined;
612
+ const gatewayCost = reportedCost(metadata, "gateway") ??
613
+ (costHeader ? { currency: "USD", total: Number(costHeader), source: "gateway" } : undefined);
614
+ return finish(route, parseOpenAiAnswers(OPENAI_LABEL, body.answers, input.questions), body.usage, requestId, gatewayCost);
428
615
  }
429
- /* Perplexity Decisions ---------------------------------------------------- */
430
- function systemOneQuestions(questions, allowBox) {
431
- // Question IDs may be "__proto__", so the wire map is collected without a prototype.
432
- const result = Object.create(null);
616
+ /* OpenRouter alpha Decisions ---------------------------------------------- */
617
+ const OPENROUTER_LABEL = "OpenRouter Decisions";
618
+ const OPENROUTER_ID = /^[A-Za-z0-9_.:-]{1,128}$/;
619
+ function openRouterImagePart(image, detail) {
620
+ return {
621
+ type: "image_url",
622
+ image_url: {
623
+ url: imageUrl(image),
624
+ ...(detail !== undefined ? { detail } : {}),
625
+ },
626
+ };
627
+ }
628
+ function openRouterState(input, flexible) {
629
+ const shared = input.images.filter((image) => image.id === undefined);
630
+ if (!flexible) {
631
+ let parts;
632
+ if (isImageReference(input.state))
633
+ parts = [openRouterImagePart(namedImage(input.images, input.state.$image), input.imageDetail)];
634
+ else if (Array.isArray(input.state)) {
635
+ parts = input.state.map((entry) => isImageReference(entry)
636
+ ? openRouterImagePart(namedImage(input.images, entry.$image), input.imageDetail)
637
+ : typeof entry === "string" ? entry : JSON.stringify(entry));
638
+ }
639
+ else
640
+ parts = [typeof input.state === "string" ? input.state : JSON.stringify(input.state)];
641
+ for (const image of shared)
642
+ parts.push(openRouterImagePart(image, input.imageDetail));
643
+ return parts.length === 1 && typeof parts[0] === "string" ? parts[0] : parts;
644
+ }
645
+ if (input.images.length === 0)
646
+ return input.state;
647
+ const parts = imageContentParts(input.state, (id) => openRouterImagePart(namedImage(input.images, id), input.imageDetail));
648
+ for (const image of shared)
649
+ parts.push(openRouterImagePart(image, input.imageDetail));
650
+ if (parts.length === 0)
651
+ return input.state;
652
+ return parts;
653
+ }
654
+ function openRouterMedia(media) {
655
+ return media.map((entry) => entry.type === "audio"
656
+ ? {
657
+ type: "input_audio",
658
+ input_audio: {
659
+ data: entry.data,
660
+ format: entry.mimeType.slice(entry.mimeType.indexOf("/") + 1),
661
+ },
662
+ }
663
+ : { type: "video_url", video_url: { url: "data:" + entry.mimeType + ";base64," + entry.data } });
664
+ }
665
+ function openRouterQuestion(id, question, input, flexible) {
666
+ if (question.type === "extract")
667
+ throw new ClassifierError("capability", "OpenRouter Decisions does not support extract questions.");
668
+ const content = flexible
669
+ ? (value) => mapImageReferences(value, (imageId) => openRouterImagePart(namedImage(input.images, imageId), input.imageDetail))
670
+ : textContent;
671
+ const wire = {
672
+ type: question.type === "bool" ? "noul" : question.type,
673
+ instructions: content(question.instructions),
674
+ };
675
+ if (question.type === "bool") {
676
+ if (question.criteria)
677
+ wire.criteria = Object.fromEntries(Object.entries(question.criteria).map(([key, value]) => [key, content(value)]));
678
+ return wire;
679
+ }
680
+ if (question.type === "choice") {
681
+ wire.criteria = Object.fromEntries(Object.entries(question.criteria).map(([key, value]) => [key, content(value)]));
682
+ return wire;
683
+ }
684
+ if (question.type === "score") {
685
+ wire.criteria = question.criteria.map(content);
686
+ return wire;
687
+ }
688
+ if (question.type === "box")
689
+ return wire;
690
+ throw new ClassifierError("capability", "OpenRouter Decisions does not support " + question.type + " questions.");
691
+ }
692
+ function openRouterAnswers(value, questions) {
693
+ if (!isRecord(value))
694
+ fail(OPENROUTER_LABEL + " returned an unexpected response.");
695
+ const answers = Object.create(null);
433
696
  for (const [id, question] of Object.entries(questions)) {
434
- if (question.type === "bool") {
435
- const wire = {
436
- type: "noul",
437
- instructions: question.instructions,
438
- };
439
- if (question.criteria !== undefined)
440
- wire.criteria = question.criteria;
441
- result[id] = wire;
697
+ if (!Object.hasOwn(value, id))
698
+ fail(OPENROUTER_LABEL + " did not return an answer for " + id + ".");
699
+ const raw = value[id];
700
+ if (isRecord(raw) &&
701
+ raw.type !== "refusal" &&
702
+ raw.confidence === undefined &&
703
+ isRecord(raw.probabilities) &&
704
+ (question.type === "choice" || question.type === "score")) {
705
+ const probabilities = Object.values(raw.probabilities).filter((entry) => typeof entry === "number" && Number.isFinite(entry));
706
+ if (probabilities.length > 0)
707
+ answers[id] = { ...raw, confidence: Math.max(...probabilities) };
708
+ else
709
+ answers[id] = raw;
442
710
  }
443
- else if (question.type === "choice") {
444
- result[id] = {
445
- type: "choice",
446
- instructions: question.instructions,
447
- criteria: question.criteria,
448
- };
711
+ else
712
+ answers[id] = raw;
713
+ }
714
+ return parseTypedAnswers(OPENROUTER_LABEL, answers, questions);
715
+ }
716
+ async function classifyOpenRouter(route, input, apiKey, signal) {
717
+ const caps = openRouterDecisionCapabilities(route.model);
718
+ if (!caps.box && Object.values(input.questions).some((question) => question.type === "box"))
719
+ throw new ClassifierError("capability", "OpenRouter box questions require a TypeSafe Jev 1.14 endpoint.");
720
+ const stateParts = openRouterState(input, caps.flexibleImagePlacement);
721
+ const state = Array.isArray(stateParts) || typeof stateParts === "string" || isRecord(stateParts)
722
+ ? stateParts
723
+ : JSON.stringify(stateParts);
724
+ const payload = {
725
+ model: route.model,
726
+ state,
727
+ questions: Object.fromEntries(Object.entries(input.questions).map(([id, question]) => [id, openRouterQuestion(id, question, input, caps.flexibleImagePlacement)])),
728
+ };
729
+ if (input.media.length > 0) {
730
+ const withParts = Array.isArray(state) ? state : [state];
731
+ payload.state = [...withParts, ...openRouterMedia(input.media)];
732
+ }
733
+ const { body, requestId } = await postJson(route, "alpha/decisions", payload, apiKey, signal);
734
+ if (!isRecord(body))
735
+ fail(OPENROUTER_LABEL + " returned an unexpected response.");
736
+ const bodyId = typeof body.id === "string" && OPENROUTER_ID.test(body.id) ? body.id : undefined;
737
+ return finish(route, openRouterAnswers(body.answers, input.questions), body.usage, requestId ?? bodyId, reportedCost(body.usage, "provider"));
738
+ }
739
+ /* Shared derived-confidence parsing for newer System One-like adapters ---- */
740
+ function deriveConfidenceAnswers(label, rawAnswers, questions) {
741
+ if (!isRecord(rawAnswers))
742
+ fail(label + " returned an unexpected response.");
743
+ const answers = Object.create(null);
744
+ for (const [id, question] of Object.entries(questions)) {
745
+ if (!Object.hasOwn(rawAnswers, id))
746
+ fail(label + " did not return an answer for " + id + ".");
747
+ const raw = rawAnswers[id];
748
+ if (isRecord(raw) &&
749
+ raw.type !== "refusal" &&
750
+ raw.confidence === undefined &&
751
+ isRecord(raw.probabilities) &&
752
+ (question.type === "choice" || question.type === "score")) {
753
+ const values = Object.values(raw.probabilities).filter((entry) => typeof entry === "number" && Number.isFinite(entry));
754
+ answers[id] = values.length > 0 ? { ...raw, confidence: Math.max(...values) } : raw;
449
755
  }
450
- else if (question.type === "score") {
451
- result[id] = {
452
- type: "score",
453
- instructions: question.instructions,
454
- criteria: question.criteria,
455
- };
756
+ else
757
+ answers[id] = raw;
758
+ }
759
+ return parseTypedAnswers(label, answers, questions);
760
+ }
761
+ function mediaDataUrl(entry) {
762
+ return "data:" + entry.mimeType + ";base64," + entry.data;
763
+ }
764
+ /* Google Gemini Decisions -------------------------------------------------- */
765
+ const GEMINI_LABEL = "Gemini Decisions";
766
+ function geminiInput(input) {
767
+ const text = typeof input.state === "string" ? input.state : JSON.stringify(input.state);
768
+ const blocks = text ? [{ type: "text", text }] : [];
769
+ for (const image of input.images) {
770
+ if ("url" in image)
771
+ blocks.push({ type: "image", uri: image.url });
772
+ else
773
+ blocks.push({ type: "image", data: image.data, mime_type: image.mimeType });
774
+ }
775
+ for (const media of input.media)
776
+ blocks.push({ type: media.type, data: media.data, mime_type: media.mimeType });
777
+ if (blocks.length === 0)
778
+ return text;
779
+ return blocks.length === 1 && isRecord(blocks[0]) && blocks[0].type === "text" ? text : blocks;
780
+ }
781
+ function geminiQuestion(id, question) {
782
+ if (question.type === "extract")
783
+ throw new ClassifierError("capability", "Gemini Decisions does not support extract questions.");
784
+ const wire = {
785
+ type: question.type === "bool" ? "noul" : question.type,
786
+ instructions: textContent(question.instructions),
787
+ };
788
+ if (question.type === "bool" && question.criteria) {
789
+ const criteria = {};
790
+ if (question.criteria.true !== undefined)
791
+ criteria.true_description = textContent(question.criteria.true);
792
+ if (question.criteria.false !== undefined)
793
+ criteria.false_description = textContent(question.criteria.false);
794
+ if (Object.keys(criteria).length > 0)
795
+ wire.criteria = criteria;
796
+ }
797
+ else if (question.type === "choice") {
798
+ wire.criteria = Object.fromEntries(Object.entries(question.criteria).map(([key, value]) => [key, textContent(value)]));
799
+ }
800
+ else if (question.type === "score") {
801
+ wire.criteria = question.criteria.map(textContent);
802
+ }
803
+ return wire;
804
+ }
805
+ async function classifyGemini(route, input, apiKey, signal) {
806
+ const payload = {
807
+ model: route.model,
808
+ input: geminiInput(input),
809
+ questions: Object.fromEntries(Object.entries(input.questions).map(([id, question]) => [id, geminiQuestion(id, question)])),
810
+ };
811
+ const { body, requestId } = await postJson(route, "decisions", payload, apiKey, signal);
812
+ if (!isRecord(body))
813
+ fail(GEMINI_LABEL + " returned an unexpected response.");
814
+ const rawUsage = isRecord(body.usage)
815
+ ? {
816
+ input_tokens: body.usage.total_input_tokens,
817
+ output_tokens: body.usage.total_output_tokens,
818
+ total_tokens: body.usage.total_tokens,
456
819
  }
457
- else if (allowBox) {
458
- result[id] = { type: "box", instructions: question.instructions };
820
+ : undefined;
821
+ return finish(route, deriveConfidenceAnswers(GEMINI_LABEL, body.answers, input.questions), rawUsage, requestId);
822
+ }
823
+ /* Inception Mercury Decide ------------------------------------------------- */
824
+ const INCEPTION_LABEL = "Inception Mercury Decide";
825
+ function inceptionImagePart(image) {
826
+ return { type: "image_url", image_url: { url: imageUrl(image) } };
827
+ }
828
+ function inceptionState(input) {
829
+ if (input.images.length === 0 && input.media.length === 0)
830
+ return input.state;
831
+ const parts = imageContentParts(input.state, (id) => inceptionImagePart(namedImage(input.images, id)));
832
+ for (const image of input.images.filter((entry) => entry.id === undefined))
833
+ parts.push(inceptionImagePart(image));
834
+ return parts.length === 1 && typeof parts[0] === "string" ? parts[0] : parts;
835
+ }
836
+ function inceptionQuestion(id, question, input) {
837
+ const content = (value) => mapImageReferences(value, (imageId) => inceptionImagePart(namedImage(input.images, imageId)));
838
+ const wire = {
839
+ type: question.type === "bool" ? "noul" : question.type,
840
+ instructions: question.instructions === undefined ? undefined : content(question.instructions),
841
+ };
842
+ if (question.type === "choice") {
843
+ wire.criteria = Object.fromEntries(Object.entries(question.criteria).map(([key, value]) => [key, content(value)]));
844
+ }
845
+ else if (question.type === "score") {
846
+ wire.criteria = question.criteria.map(content);
847
+ }
848
+ else if (question.type === "extract") {
849
+ wire.criteria = Object.fromEntries(Object.entries(question.criteria).map(([key, value]) => [key, textContent(value)]));
850
+ if (question.source !== undefined)
851
+ wire.source = question.source;
852
+ if (question.threshold !== undefined)
853
+ wire.threshold = question.threshold;
854
+ if (question.snapToWords !== undefined)
855
+ wire.snap_to_words = question.snapToWords;
856
+ if (question.debug !== undefined)
857
+ wire.debug = question.debug;
858
+ }
859
+ else if (question.type === "bool" && question.criteria) {
860
+ wire.criteria = Object.fromEntries(Object.entries(question.criteria).map(([key, value]) => [key, content(value)]));
861
+ }
862
+ return wire;
863
+ }
864
+ function inceptionAnswers(rawAnswers, questions, input) {
865
+ if (!isRecord(rawAnswers))
866
+ fail(INCEPTION_LABEL + " returned an unexpected response.");
867
+ const answers = Object.create(null);
868
+ for (const [id, question] of Object.entries(questions)) {
869
+ const raw = rawAnswers[id];
870
+ if (raw === undefined)
871
+ fail(INCEPTION_LABEL + " did not return an answer for " + id + ".");
872
+ if (question.type !== "extract")
873
+ continue;
874
+ if (!isRecord(raw) || !isRecord(raw.spans) || !isRecord(raw.not_stated))
875
+ fail(INCEPTION_LABEL + " returned an invalid extract answer for " + id + ".");
876
+ const sourceField = question.source;
877
+ const sourceValue = typeof input.state === "string"
878
+ ? input.state
879
+ : sourceField !== undefined && isRecord(input.state)
880
+ ? input.state[sourceField]
881
+ : undefined;
882
+ if (typeof sourceValue !== "string")
883
+ fail(INCEPTION_LABEL + " cannot locate extract spans without a source string.");
884
+ const source = sourceValue;
885
+ const spans = Object.create(null);
886
+ const notStated = Object.create(null);
887
+ for (const field of Object.keys(question.criteria)) {
888
+ const entries = raw.spans[field] ?? [];
889
+ if (!Array.isArray(entries))
890
+ fail(INCEPTION_LABEL + " returned invalid extract spans for " + id + ".");
891
+ spans[field] = entries.map((entry) => {
892
+ if (!isRecord(entry) || typeof entry.text !== "string")
893
+ fail(INCEPTION_LABEL + " returned an invalid extract span for " + id + ".");
894
+ const start = nonNegativeInteger(INCEPTION_LABEL, entry.start, "extract span offset for " + id);
895
+ const end = nonNegativeInteger(INCEPTION_LABEL, entry.end, "extract span offset for " + id);
896
+ if (end < start || codePointSlice(source, start, end) !== entry.text)
897
+ fail(INCEPTION_LABEL + " returned an extract span that does not match its source for " + id + ".");
898
+ return {
899
+ start,
900
+ end,
901
+ text: entry.text,
902
+ score: probability(INCEPTION_LABEL, entry.confidence, "extract confidence for " + id),
903
+ };
904
+ });
905
+ notStated[field] = probability(INCEPTION_LABEL, raw.not_stated[field], "not_stated for " + id);
459
906
  }
460
- else {
461
- throw unsupportedBox();
907
+ answers[id] = { type: "extract", spans, notStated };
908
+ }
909
+ const coreQuestions = Object.fromEntries(Object.entries(questions).filter(([, question]) => question.type !== "extract"));
910
+ if (Object.keys(coreQuestions).length > 0) {
911
+ const core = deriveConfidenceAnswers(INCEPTION_LABEL, rawAnswers, coreQuestions);
912
+ for (const [id, answer] of Object.entries(core))
913
+ answers[id] = answer;
914
+ }
915
+ return answers;
916
+ }
917
+ async function classifyInception(route, input, apiKey, signal) {
918
+ const payload = {
919
+ model: route.model,
920
+ state: inceptionState(input),
921
+ questions: Object.fromEntries(Object.entries(input.questions).map(([id, question]) => [id, inceptionQuestion(id, question, input)])),
922
+ };
923
+ const { body, requestId } = await postJson(route, "decisions", payload, apiKey, signal);
924
+ if (!isRecord(body))
925
+ fail(INCEPTION_LABEL + " returned an unexpected response.");
926
+ return finish(route, inceptionAnswers(body.answers, input.questions, input), body.usage, requestId);
927
+ }
928
+ /* Parallel Decisions ------------------------------------------------------- */
929
+ const PARALLEL_LABEL = "Parallel Decisions";
930
+ function parallelCitations(value) {
931
+ if (value === undefined)
932
+ return [];
933
+ if (!Array.isArray(value))
934
+ fail(PARALLEL_LABEL + " returned invalid citations.");
935
+ return value.map((entry) => {
936
+ if (!isRecord(entry) || typeof entry.url !== "string")
937
+ fail(PARALLEL_LABEL + " returned an invalid citation.");
938
+ try {
939
+ const url = new URL(entry.url);
940
+ if (!["http:", "https:"].includes(url.protocol))
941
+ throw new Error();
942
+ }
943
+ catch {
944
+ fail(PARALLEL_LABEL + " returned an invalid citation URL.");
945
+ }
946
+ const citation = { url: entry.url };
947
+ if (typeof entry.title === "string")
948
+ citation.title = entry.title;
949
+ if (entry.excerpts !== undefined) {
950
+ if (!Array.isArray(entry.excerpts) || !entry.excerpts.every((text) => typeof text === "string"))
951
+ fail(PARALLEL_LABEL + " returned invalid citation excerpts.");
952
+ citation.excerpts = entry.excerpts;
953
+ }
954
+ return citation;
955
+ });
956
+ }
957
+ async function classifyParallel(route, input, apiKey, signal) {
958
+ if (input.images.length > 0 || input.media.length > 0 || input.mode !== undefined)
959
+ throw new ClassifierError("capability", "Parallel Decisions accepts text/JSON state only.");
960
+ const payload = {
961
+ state: input.state,
962
+ questions: systemOneQuestions(input.questions, false),
963
+ mode: "fast",
964
+ };
965
+ const { body, requestId } = await postJson(route, "decisions", payload, apiKey, signal);
966
+ if (!isRecord(body))
967
+ fail(PARALLEL_LABEL + " returned an unexpected response.");
968
+ const result = finish(route, deriveConfidenceAnswers(PARALLEL_LABEL, body.answers, input.questions), body.usage, requestId);
969
+ const citations = parallelCitations(body.citations);
970
+ if (citations.length > 0)
971
+ result.citations = citations;
972
+ if (typeof body.decision_id === "string" && /^[A-Za-z0-9_.:-]{1,128}$/.test(body.decision_id))
973
+ result.requestId = result.requestId ?? body.decision_id;
974
+ return result;
975
+ }
976
+ /* Self-hosted System One runtimes ------------------------------------------ */
977
+ const LOCAL_LABEL = "Local System One";
978
+ async function classifyLocalSystemOne(route, input, apiKey, signal) {
979
+ const payload = {
980
+ ...(route.provider !== "llamacpp" ? { model: route.model } : {}),
981
+ state: input.state,
982
+ questions: systemOneQuestions(input.questions, false),
983
+ };
984
+ if (input.images.length > 0)
985
+ payload.images = input.images.map((image) => {
986
+ if ("url" in image)
987
+ throw new ClassifierError("capability", "Local System One routes require local image data.");
988
+ return imageUrl(image);
989
+ });
990
+ const audio = input.media.filter((entry) => entry.type === "audio");
991
+ const video = input.media.filter((entry) => entry.type === "video");
992
+ if (route.provider === "llamacpp") {
993
+ const files = [...input.images, ...input.media];
994
+ if (files.length > 0)
995
+ payload.files = files.map((entry) => ("type" in entry ? mediaDataUrl(entry) : imageUrl(entry)));
996
+ }
997
+ else {
998
+ if (audio.length > 0)
999
+ payload.audio = audio.map(mediaDataUrl);
1000
+ if (video.length > 0)
1001
+ payload.videos = video.map(mediaDataUrl);
1002
+ }
1003
+ const { body, requestId } = await postJson(route, "v1/systemone", payload, apiKey, signal);
1004
+ if (!isRecord(body))
1005
+ fail(LOCAL_LABEL + " returned an unexpected response.");
1006
+ return finish(route, deriveConfidenceAnswers(LOCAL_LABEL, body.answers, input.questions), body.usage, requestId);
1007
+ }
1008
+ /* Perplexity Decisions ---------------------------------------------------- */
1009
+ function systemOneQuestions(questions, allowBox, content = textContent) {
1010
+ const result = Object.create(null);
1011
+ for (const [id, question] of Object.entries(questions)) {
1012
+ if (question.type === "box") {
1013
+ if (!allowBox)
1014
+ throw unsupportedBox();
1015
+ result[id] = { type: "box", instructions: content(question.instructions) };
1016
+ continue;
1017
+ }
1018
+ if (question.type === "locate") {
1019
+ result[id] = { type: "locate", instructions: content(question.instructions) };
1020
+ continue;
462
1021
  }
1022
+ if (question.type !== "bool" && question.type !== "choice" && question.type !== "score")
1023
+ throw new ClassifierError("capability", "The selected route does not support " + question.type + " questions.");
1024
+ const wire = {
1025
+ type: question.type === "bool" ? "noul" : question.type,
1026
+ instructions: content(question.instructions),
1027
+ };
1028
+ if (question.type === "score")
1029
+ wire.criteria = question.criteria.map(content);
1030
+ else if (question.criteria !== undefined)
1031
+ wire.criteria = Object.fromEntries(Object.entries(question.criteria).map(([key, value]) => [key, content(value)]));
1032
+ result[id] = wire;
463
1033
  }
464
1034
  return result;
465
1035
  }
466
1036
  function perplexityState(input) {
467
- // Perplexity interprets native image parts inside state. Caller JSON is text;
468
- // only locally validated images may become provider-native image parts.
1037
+ // Only explicit references become native image parts; other JSON stays text.
469
1038
  const text = typeof input.state === "string" ? input.state : JSON.stringify(input.state);
470
- if (input.images.length === 0)
1039
+ const shared = input.images.filter((image) => image.id === undefined);
1040
+ const references = imageReferences(input.state);
1041
+ if (shared.length + references.length > 8)
1042
+ throw new ClassifierError("input", "Perplexity accepts at most eight image occurrences per question.");
1043
+ if (shared.length === 0 && references.length === 0)
471
1044
  return text;
472
1045
  return [
473
- text,
474
- ...input.images.map((image) => ({
475
- type: "image_url",
476
- image_url: { url: dataUrl(image) },
477
- })),
1046
+ ...(references.length ? imageContentParts(input.state, (id) => ({
1047
+ type: "image_url", image_url: { url: imageUrl(namedImage(input.images, id)) },
1048
+ })) : [text]),
1049
+ ...shared.map((image) => ({ type: "image_url", image_url: { url: imageUrl(image) } })),
478
1050
  ];
479
1051
  }
1052
+ function webEntry(entry, field) {
1053
+ if (!isRecord(entry) ||
1054
+ typeof entry.title !== "string" ||
1055
+ typeof entry.url !== "string" ||
1056
+ typeof entry.snippet !== "string")
1057
+ fail(PERPLEXITY_LABEL + " returned an invalid " + field + " entry.");
1058
+ try {
1059
+ const url = new URL(entry.url);
1060
+ if (!["http:", "https:"].includes(url.protocol))
1061
+ throw new Error();
1062
+ }
1063
+ catch {
1064
+ fail(PERPLEXITY_LABEL + " returned an invalid URL in " + field + ".");
1065
+ }
1066
+ return { title: entry.title, url: entry.url, snippet: entry.snippet };
1067
+ }
1068
+ function providerDate(value, field) {
1069
+ if (typeof value !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(value))
1070
+ fail(PERPLEXITY_LABEL + " returned an invalid date in " + field + ".");
1071
+ return value;
1072
+ }
1073
+ function parseSearchResults(value) {
1074
+ if (value === undefined)
1075
+ return [];
1076
+ if (!Array.isArray(value) || value.length > 100)
1077
+ fail(PERPLEXITY_LABEL + " returned invalid search_results.");
1078
+ return value.map((entry) => {
1079
+ const base = webEntry(entry, "search_results");
1080
+ const result = { ...base };
1081
+ if (isRecord(entry) && entry.date !== undefined)
1082
+ result.date = providerDate(entry.date, "search_results");
1083
+ if (isRecord(entry) && entry.last_updated !== undefined)
1084
+ result.lastUpdated = providerDate(entry.last_updated, "search_results");
1085
+ return result;
1086
+ });
1087
+ }
1088
+ function parseFetchedResults(value) {
1089
+ if (value === undefined)
1090
+ return [];
1091
+ if (!Array.isArray(value) || value.length > 1)
1092
+ fail(PERPLEXITY_LABEL + " returned invalid fetched_results.");
1093
+ return value.map((entry) => webEntry(entry, "fetched_results"));
1094
+ }
1095
+ function withWebGroundingCost(cost, questionCount, fetched) {
1096
+ if (cost.status !== "estimated")
1097
+ return cost;
1098
+ const searchFeeMaximum = questionCount * 0.001;
1099
+ const fetchFee = fetched * 0.0005;
1100
+ return {
1101
+ ...cost,
1102
+ nonToken: {
1103
+ currency: "USD",
1104
+ webGrounding: {
1105
+ status: "estimated_maximum",
1106
+ searchesRequested: questionCount,
1107
+ searchFeeMaximum,
1108
+ successfulFetches: fetched,
1109
+ fetchFee,
1110
+ totalMaximum: searchFeeMaximum + fetchFee,
1111
+ note: "Perplexity bills one Fast Search per question before duplicate-query sharing and failed-search exclusions are known; exact billed searches are not returned. The token estimate already includes fetched page text and search evidence.",
1112
+ },
1113
+ },
1114
+ };
1115
+ }
480
1116
  async function classifyPerplexity(route, input, apiKey, signal) {
481
1117
  const state = perplexityState(input);
482
- const { body, requestId } = await postJson(route, "decisions", {
1118
+ const payload = {
483
1119
  model: route.model,
484
1120
  state,
485
1121
  questions: systemOneQuestions(input.questions, false),
486
- }, apiKey, signal);
1122
+ };
1123
+ if (input.mode !== undefined)
1124
+ payload.mode = input.mode;
1125
+ const { body, requestId } = await postJson(route, "decisions", payload, apiKey, signal);
487
1126
  if (!isRecord(body))
488
1127
  fail(PERPLEXITY_LABEL + " returned an unexpected response.");
489
- return finish(route, parseTypedAnswers(PERPLEXITY_LABEL, body.answers, input.questions), body.usage, requestId);
1128
+ const searches = parseSearchResults(body.search_results);
1129
+ const fetched = parseFetchedResults(body.fetched_results);
1130
+ const snippets = searches.map((result) => result.snippet);
1131
+ const sources = { snippets };
1132
+ if (typeof input.state === "string")
1133
+ sources.state = input.state;
1134
+ const result = finish(route, parseTypedAnswers(PERPLEXITY_LABEL, body.answers, input.questions, sources), body.usage, requestId);
1135
+ if (input.mode === "web_grounding") {
1136
+ result.webGrounding = { searchResults: searches };
1137
+ if (fetched.length > 0)
1138
+ result.webGrounding.fetchedResults = fetched;
1139
+ result.cost = withWebGroundingCost(result.cost, Object.keys(input.questions).length, fetched.length);
1140
+ }
1141
+ return result;
1142
+ }
1143
+ /* Sarvam Prism Decisions API ---------------------------------------------- */
1144
+ const SARVAM_REQUEST_ID_PATTERN = /^[A-Za-z0-9_.:-]{1,128}$/;
1145
+ function sarvamSafeDetail(value, apiKey, pattern) {
1146
+ if (typeof value !== "string" || !pattern.test(value))
1147
+ return undefined;
1148
+ return apiKey.length > 0 && value.includes(apiKey) ? undefined : value;
1149
+ }
1150
+ const sarvamHeaderRequestId = (value, apiKey) => sarvamSafeDetail(value, apiKey, SARVAM_REQUEST_ID_PATTERN);
1151
+ const sarvamErrorDetail = (status, body, apiKey) => {
1152
+ if (!isRecord(body) || !isRecord(body.error))
1153
+ return undefined;
1154
+ const error = body.error;
1155
+ const code = typeof error.code === "string" &&
1156
+ [
1157
+ "invalid_request_error",
1158
+ "insufficient_quota_error",
1159
+ "invalid_api_key_error",
1160
+ "not_found_error",
1161
+ "unprocessable_entity_error",
1162
+ "rate_limit_exceeded_error",
1163
+ "internal_server_error",
1164
+ "model_call_failed",
1165
+ "model_overloaded",
1166
+ ].includes(error.code)
1167
+ ? error.code
1168
+ : undefined;
1169
+ const param = sarvamSafeDetail(error.param, apiKey, /^[A-Za-z0-9_.:-]{1,256}$/);
1170
+ const requestId = sarvamSafeDetail(error.request_id, apiKey, SARVAM_REQUEST_ID_PATTERN);
1171
+ if (!code && !param && !requestId)
1172
+ return undefined;
1173
+ const summaries = {
1174
+ 402: "Sarvam reported insufficient quota.",
1175
+ 403: "Sarvam rejected the API key.",
1176
+ 404: "Sarvam does not recognize the selected model.",
1177
+ 422: "Sarvam rejected the request shape.",
1178
+ 429: "Sarvam rate-limited the request.",
1179
+ 500: "Sarvam reported an internal error.",
1180
+ 502: "Sarvam could not reach the decision model.",
1181
+ 503: "Sarvam reported that the model is overloaded.",
1182
+ };
1183
+ let detail = summaries[status] ?? "Sarvam rejected the request.";
1184
+ if (code)
1185
+ detail += " Code: " + code + ".";
1186
+ if (param)
1187
+ detail += " Field: " + param + ".";
1188
+ if (requestId)
1189
+ detail += " Request ID: " + requestId + ".";
1190
+ return detail;
1191
+ };
1192
+ function sarvamRequestId(body, apiKey) {
1193
+ return sarvamSafeDetail(body.request_id, apiKey, SARVAM_REQUEST_ID_PATTERN);
1194
+ }
1195
+ function sarvamQuestion(id, question, minimumChoices) {
1196
+ if (question.type !== "bool" && question.type !== "choice" && question.type !== "score")
1197
+ throw new ClassifierError("capability", "The selected route does not support " + question.type + " questions.");
1198
+ const wire = {
1199
+ type: question.type === "bool" ? "noul" : question.type,
1200
+ instructions: textContent(question.instructions),
1201
+ };
1202
+ if (question.type === "bool") {
1203
+ if (question.criteria !== undefined)
1204
+ wire.criteria = Object.fromEntries(Object.entries(question.criteria).map(([key, value]) => [key, textContent(value)]));
1205
+ return wire;
1206
+ }
1207
+ if (question.type === "choice") {
1208
+ const entries = Object.entries(question.criteria);
1209
+ if (entries.length < minimumChoices || entries.length > 255)
1210
+ throw new ClassifierError("input", "Sarvam requires " + minimumChoices + " to 255 options for choice question " + id + ".");
1211
+ wire.criteria = Object.fromEntries(entries.map(([key, value]) => [key, textContent(value)]));
1212
+ return wire;
1213
+ }
1214
+ if (question.criteria.length < 2 || question.criteria.length > 10)
1215
+ throw new ClassifierError("input", "Sarvam Prism requires 2 to 10 levels for score question " + id + ".");
1216
+ wire.criteria = question.criteria.map(textContent);
1217
+ return wire;
1218
+ }
1219
+ function sarvamAnswers(value, questions) {
1220
+ if (!isRecord(value))
1221
+ fail(SARVAM_LABEL + " returned an unexpected response.");
1222
+ const answers = Object.create(null);
1223
+ for (const [id, question] of Object.entries(questions)) {
1224
+ if (!Object.hasOwn(value, id))
1225
+ fail(SARVAM_LABEL + " did not return an answer for " + id + ".");
1226
+ const raw = value[id];
1227
+ if (question.type === "score" && isRecord(raw) && raw.probabilities === undefined)
1228
+ fail(SARVAM_LABEL + " did not return probabilities for score question " + id + ".");
1229
+ const expected = question.type === "bool" ? "noul" : question.type;
1230
+ answers[id] =
1231
+ isRecord(raw) && raw.type === undefined ? { ...raw, type: expected } : raw;
1232
+ }
1233
+ return parseTypedAnswers(SARVAM_LABEL, answers, questions);
1234
+ }
1235
+ async function classifySarvam(route, input, apiKey, signal) {
1236
+ const isClef = route.model === "clef";
1237
+ if (!isClef && (input.images.length > 0 || input.media.length > 0))
1238
+ throw new ClassifierError("capability", "Sarvam Prism accepts text/JSON only; Sarvam Clef accepts base64 images.");
1239
+ if (input.media.length > 0 || input.mode !== undefined)
1240
+ throw new ClassifierError("capability", "Sarvam does not accept media or web grounding.");
1241
+ const questions = Object.create(null);
1242
+ for (const [id, question] of Object.entries(input.questions))
1243
+ questions[id] = sarvamQuestion(id, question, isClef ? 1 : 2);
1244
+ const payload = { model: route.model, state: input.state, questions };
1245
+ if (isClef && input.images.length > 0)
1246
+ payload.images = input.images.map((image) => {
1247
+ if ("url" in image)
1248
+ throw new ClassifierError("capability", "Sarvam Clef requires local image data.");
1249
+ return imageUrl(image);
1250
+ });
1251
+ const { body, requestId } = await postJson(route, "systemone", payload, apiKey, signal, undefined, sarvamErrorDetail, sarvamHeaderRequestId);
1252
+ if (!isRecord(body))
1253
+ fail(SARVAM_LABEL + " returned an unexpected response.");
1254
+ if (body.model !== undefined && body.model !== route.model)
1255
+ fail(SARVAM_LABEL + " returned a model that does not match the selected route.");
1256
+ if (!isRecord(body.answers))
1257
+ fail(SARVAM_LABEL + " returned an unexpected response.");
1258
+ return finish(route, sarvamAnswers(body.answers, input.questions), body.usage, requestId ?? sarvamRequestId(body, apiKey));
490
1259
  }
491
1260
  /* Microsoft Foundry Decision-1 (text/JSON, API-key authentication) -------- */
492
1261
  async function classifyMicrosoft(route, input, apiKey, signal) {
493
- const label = "Microsoft Decision-1";
494
- const { body, requestId } = await postJson(route, "providers/microsoft/v1/systemone", {
495
- model: route.model, // Foundry deployment name, not necessarily the catalog model ID.
496
- state: input.state,
497
- questions: systemOneQuestions(input.questions, false),
498
- }, apiKey, signal);
1262
+ const label = "Microsoft Foundry Decision-1.1";
1263
+ const assets = Object.create(null);
1264
+ const sharedRefs = [];
1265
+ const namedRefs = new Map();
1266
+ const used = new Set([...imageReferences(input.state), ...questionImageReferences(input.questions)]);
1267
+ for (const image of input.images) {
1268
+ if ("url" in image)
1269
+ throw new ClassifierError("capability", "Microsoft image assets require local images.");
1270
+ // Batching can remove a question or a criterion; unused assets are rejected upstream.
1271
+ if (image.id !== undefined && !used.has(image.id))
1272
+ continue;
1273
+ const ref = randomUUID();
1274
+ if (image.id === undefined)
1275
+ sharedRefs.push("image:" + ref);
1276
+ else
1277
+ namedRefs.set(image.id, ref);
1278
+ assets[ref] = {
1279
+ type: "image",
1280
+ format: image.mimeType === "image/png" ? "png" : "jpg",
1281
+ data_base64: image.data,
1282
+ };
1283
+ }
1284
+ const reference = (id) => {
1285
+ const ref = namedRefs.get(id);
1286
+ if (!ref)
1287
+ throw new ClassifierError("input", "Unknown named image reference.");
1288
+ return "image:" + ref;
1289
+ };
1290
+ let state = mapImageReferences(input.state, reference);
1291
+ if (sharedRefs.length > 0) {
1292
+ if (typeof state === "string")
1293
+ state = state + "\n" + sharedRefs.join(" ");
1294
+ else if (isRecord(state))
1295
+ state = { ...state, images: sharedRefs };
1296
+ else
1297
+ state = { state, images: sharedRefs };
1298
+ }
1299
+ const payload = {
1300
+ model: route.model, // Foundry deployment name, not necessarily the underlying model ID.
1301
+ state,
1302
+ questions: systemOneQuestions(input.questions, false, (value) => mapImageReferences(value, reference)),
1303
+ };
1304
+ if (Object.keys(assets).length > 0)
1305
+ payload.assets = assets;
1306
+ const { body, requestId } = await postJson(route, "providers/microsoft/v1/systemone", payload, apiKey, signal);
499
1307
  if (!isRecord(body) || !isRecord(body.answers))
500
1308
  fail(label + " returned an unexpected response.");
501
1309
  // Some System One endpoints omit confidence; derive it only from validated probabilities.
@@ -532,27 +1340,46 @@ function withImageRefs(state, refs) {
532
1340
  }
533
1341
  async function classifySystemOne(route, input, apiKey, signal) {
534
1342
  const assets = Object.create(null);
535
- const refs = [];
1343
+ const sharedRefs = [];
1344
+ const namedRefs = new Map();
1345
+ const used = new Set([...imageReferences(input.state), ...questionImageReferences(input.questions)]);
536
1346
  for (const image of input.images) {
1347
+ // Batching can remove a question or a criterion. Jev rejects unused assets.
1348
+ if (image.id !== undefined && !used.has(image.id))
1349
+ continue;
1350
+ if ("url" in image)
1351
+ throw new ClassifierError("capability", "Jev assets require local images.");
537
1352
  const ref = randomUUID();
538
- refs.push(ref);
1353
+ if (image.id === undefined)
1354
+ sharedRefs.push(ref);
1355
+ else
1356
+ namedRefs.set(image.id, ref);
539
1357
  assets[ref] = {
540
- type: "image",
541
- format: image.mimeType === "image/png" ? "png" : "jpg",
1358
+ type: "image", format: image.mimeType === "image/png" ? "png" : "jpg",
542
1359
  data_base64: image.data,
543
1360
  };
544
1361
  }
1362
+ const reference = (id) => {
1363
+ const ref = namedRefs.get(id);
1364
+ if (!ref)
1365
+ throw new ClassifierError("input", "Unknown named image reference.");
1366
+ return ref;
1367
+ };
1368
+ const state = mapImageReferences(input.state, reference);
545
1369
  const payload = {
546
1370
  model: route.model,
547
- state: refs.length === 0 ? input.state : withImageRefs(input.state, refs),
548
- questions: systemOneQuestions(input.questions, true),
1371
+ state: sharedRefs.length ? withImageRefs(state, sharedRefs) : state,
1372
+ questions: systemOneQuestions(input.questions, true, (value) => mapImageReferences(value, reference)),
549
1373
  };
550
- if (refs.length > 0)
1374
+ if (Object.keys(assets).length > 0)
551
1375
  payload.assets = assets;
552
- const experimentalHeader = refs.length > 0 ||
1376
+ const experimentalHeader = Object.keys(assets).length > 0 ||
553
1377
  Object.values(input.questions).some((question) => question.type === "box");
554
- const extraHeaders = experimentalHeader
555
- ? { "TypeSafe-Danger-Zone-Images": "true" }
1378
+ const extraHeaders = experimentalHeader || route.longContext
1379
+ ? {
1380
+ ...(experimentalHeader ? { "TypeSafe-Danger-Zone-Images": "true" } : {}),
1381
+ ...(route.longContext ? { "TypeSafe-Danger-Zone-Long-Context": "true" } : {}),
1382
+ }
556
1383
  : undefined;
557
1384
  const { body, requestId } = await postJson(route, "systemone", payload, apiKey, signal, extraHeaders);
558
1385
  if (!isRecord(body))
@@ -561,9 +1388,12 @@ async function classifySystemOne(route, input, apiKey, signal) {
561
1388
  }
562
1389
  /* Cloudflare Workers AI (Clef and third-party System One envelopes) ------- */
563
1390
  function clefBodyModel(model) {
564
- return /^@cf\/cloudflare\/(clef(?:-flash)?)$/.exec(model)?.[1];
1391
+ return /^@cf\/cloudflare\/(clef(?:-flash|-omni)?)$/.exec(model)?.[1];
1392
+ }
1393
+ function cloudflareMedia(media) {
1394
+ return media.map((entry) => ({ content_type: entry.mimeType, base64: entry.data }));
565
1395
  }
566
- function unwrapCloudflare(label, body) {
1396
+ export function unwrapCloudflare(label, body) {
567
1397
  if (!isRecord(body))
568
1398
  fail(label + " returned an unexpected response.");
569
1399
  if (body.success === false)
@@ -594,16 +1424,23 @@ async function classifyCloudflare(route, input, apiKey, signal) {
594
1424
  questions: systemOneQuestions(input.questions, false),
595
1425
  };
596
1426
  if (input.images.length > 0) {
597
- payload.images = input.images.map((image) => ({
598
- content_type: image.mimeType,
599
- base64: image.data,
600
- }));
1427
+ payload.images = input.images.map((image) => {
1428
+ if ("url" in image)
1429
+ throw new ClassifierError("capability", "Clef requires local images.");
1430
+ return { content_type: image.mimeType, base64: image.data };
1431
+ });
601
1432
  }
1433
+ const audio = input.media.filter((media) => media.type === "audio");
1434
+ const videos = input.media.filter((media) => media.type === "video");
1435
+ if (audio.length)
1436
+ payload.audio = cloudflareMedia(audio);
1437
+ if (videos.length)
1438
+ payload.videos = cloudflareMedia(videos);
602
1439
  path = "run/" + route.model;
603
1440
  }
604
1441
  else {
605
- if (input.images.length > 0)
606
- throw new ClassifierError("capability", "The selected route does not support images for this model.");
1442
+ if (input.images.length > 0 || input.media.length > 0)
1443
+ throw new ClassifierError("capability", "The selected route does not support media for this model.");
607
1444
  payload = {
608
1445
  model: route.model,
609
1446
  input: {
@@ -622,3 +1459,260 @@ async function classifyCloudflare(route, input, apiKey, signal) {
622
1459
  : undefined;
623
1460
  return finish(route, parseTypedAnswers(CLOUDFLARE_LABEL, result.answers, input.questions), usage, requestId);
624
1461
  }
1462
+ /* Liquid d1.2 System One extension --------------------------------------- */
1463
+ function liquidUnsupported(feature) {
1464
+ throw new ClassifierError("capability", "The selected route does not support " + feature + ".");
1465
+ }
1466
+ function liquidQuestion(id, question) {
1467
+ if (question.type === "extract")
1468
+ return liquidUnsupported("extract questions on Liquid routes");
1469
+ const wire = {
1470
+ type: question.type === "bool" ? "noul" : question.type,
1471
+ instructions: textContent(question.instructions),
1472
+ };
1473
+ switch (question.type) {
1474
+ case "bool":
1475
+ if (question.criteria)
1476
+ wire.criteria = Object.fromEntries(Object.entries(question.criteria).map(([key, value]) => [key, textContent(value)]));
1477
+ return wire;
1478
+ case "choice":
1479
+ case "multi_choice":
1480
+ wire.type = "choice";
1481
+ wire.criteria = Object.fromEntries(Object.entries(question.criteria).map(([key, value]) => [key, textContent(value)]));
1482
+ if (question.type === "multi_choice")
1483
+ wire.multiple = true;
1484
+ return wire;
1485
+ case "score":
1486
+ wire.criteria = question.criteria.map(textContent);
1487
+ return wire;
1488
+ case "number":
1489
+ if (question.unit !== undefined)
1490
+ wire.unit = question.unit;
1491
+ if (question.range !== undefined)
1492
+ wire.range = question.range;
1493
+ if (question.step !== undefined)
1494
+ wire.step = question.step;
1495
+ return wire;
1496
+ case "spans":
1497
+ case "boxes":
1498
+ if (question.max !== undefined)
1499
+ wire.max = question.max;
1500
+ return wire;
1501
+ case "estimate":
1502
+ wire.type = "number";
1503
+ wire.range = question.range;
1504
+ if (question.step !== undefined)
1505
+ wire.step = question.step;
1506
+ if (question.unit !== undefined)
1507
+ wire.unit = question.unit;
1508
+ return wire;
1509
+ case "text":
1510
+ case "date":
1511
+ case "box":
1512
+ return wire;
1513
+ case "locate":
1514
+ return liquidUnsupported("locate questions on Liquid routes");
1515
+ }
1516
+ }
1517
+ function stateText(state) {
1518
+ return typeof state === "string" ? state : JSON.stringify(state, null, 2);
1519
+ }
1520
+ function optionalCharSpan(label, value, field, text) {
1521
+ if (value === undefined)
1522
+ return undefined;
1523
+ if (value === null)
1524
+ return null;
1525
+ return charSpan(label, value, field, text);
1526
+ }
1527
+ function charSpan(label, value, field, text) {
1528
+ if (!Array.isArray(value) || value.length !== 2 ||
1529
+ value.some((entry) => !Number.isSafeInteger(entry) || entry < 0))
1530
+ fail(label + " returned an invalid " + field + ".");
1531
+ const start = value[0];
1532
+ const end = value[1];
1533
+ if (end < start || codePointSlice(text, start, end).length === 0 && end !== start)
1534
+ fail(label + " returned an invalid " + field + ".");
1535
+ return [start, end];
1536
+ }
1537
+ function optionalFound(label, answer, id) {
1538
+ return answer.found === undefined ? undefined : probability(label, answer.found, "found for " + id);
1539
+ }
1540
+ function optionalPath(label, answer, id) {
1541
+ if (answer.path === undefined)
1542
+ return undefined;
1543
+ if (typeof answer.path !== "string" || (answer.path !== "" && !answer.path.startsWith("/")))
1544
+ fail(label + " returned an invalid JSON pointer for " + id + ".");
1545
+ return answer.path;
1546
+ }
1547
+ function parseLiquidAnswer(label, id, question, answer, text) {
1548
+ if (!isRecord(answer))
1549
+ fail(label + " returned an invalid answer for " + id + ".");
1550
+ if (answer.type === "refusal")
1551
+ return { type: "refusal" };
1552
+ if (question.type === "bool" || question.type === "choice" || question.type === "score")
1553
+ return validateDecision(label, id, parseTypedAnswer(label, id, question, answer));
1554
+ const found = optionalFound(label, answer, id);
1555
+ if (question.type === "text") {
1556
+ if (typeof answer.text !== "string")
1557
+ fail(label + " returned an invalid text answer for " + id + ".");
1558
+ const result = { type: "text", text: answer.text };
1559
+ const span = optionalCharSpan(label, answer.span, "span for " + id, text);
1560
+ if (span !== undefined)
1561
+ result.span = span;
1562
+ if (found !== undefined)
1563
+ result.found = found;
1564
+ const path = optionalPath(label, answer, id);
1565
+ if (path !== undefined)
1566
+ result.path = path;
1567
+ return result;
1568
+ }
1569
+ if (question.type === "number") {
1570
+ if (answer.number !== null && (typeof answer.number !== "number" || !Number.isFinite(answer.number)))
1571
+ fail(label + " returned an invalid number answer for " + id + ".");
1572
+ const value = typeof answer.number === "number" ? answer.number : null;
1573
+ const result = { type: "number", value };
1574
+ if (typeof answer.unit === "string" || answer.unit === null)
1575
+ result.unit = answer.unit;
1576
+ if (typeof answer.text === "string" || answer.text === null)
1577
+ result.text = answer.text;
1578
+ const span = optionalCharSpan(label, answer.span, "span for " + id, text);
1579
+ if (span !== undefined)
1580
+ result.span = span;
1581
+ if (found !== undefined)
1582
+ result.found = found;
1583
+ const path = optionalPath(label, answer, id);
1584
+ if (path !== undefined)
1585
+ result.path = path;
1586
+ return result;
1587
+ }
1588
+ if (question.type === "date") {
1589
+ if (answer.date !== null && (typeof answer.date !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(answer.date)))
1590
+ fail(label + " returned an invalid date answer for " + id + ".");
1591
+ const date = typeof answer.date === "string" ? answer.date : null;
1592
+ const result = { type: "date", date };
1593
+ if (typeof answer.text === "string" || answer.text === null)
1594
+ result.text = answer.text;
1595
+ const span = optionalCharSpan(label, answer.span, "span for " + id, text);
1596
+ if (span !== undefined)
1597
+ result.span = span;
1598
+ if (found !== undefined)
1599
+ result.found = found;
1600
+ const path = optionalPath(label, answer, id);
1601
+ if (path !== undefined)
1602
+ result.path = path;
1603
+ return result;
1604
+ }
1605
+ if (question.type === "spans") {
1606
+ if (!Array.isArray(answer.spans) || !Array.isArray(answer.presence) ||
1607
+ !Number.isSafeInteger(answer.count) || answer.count < 0 ||
1608
+ typeof answer.at_least !== "boolean")
1609
+ fail(label + " returned an invalid spans answer for " + id + ".");
1610
+ const presence = answer.presence.map((entry) => probability(label, entry, "presence for " + id));
1611
+ return {
1612
+ type: "spans",
1613
+ spans: answer.spans.map((entry) => {
1614
+ if (!isRecord(entry) || typeof entry.text !== "string")
1615
+ fail(label + " returned an invalid span for " + id + ".");
1616
+ return {
1617
+ text: entry.text,
1618
+ span: charSpan(label, entry.span, "span for " + id, text),
1619
+ found: probability(label, entry.found, "span found for " + id),
1620
+ };
1621
+ }),
1622
+ count: answer.count,
1623
+ atLeast: answer.at_least,
1624
+ presence,
1625
+ };
1626
+ }
1627
+ if (question.type === "boxes") {
1628
+ if (!Array.isArray(answer.boxes) || !Array.isArray(answer.presence) ||
1629
+ !Number.isSafeInteger(answer.count) || answer.count < 0 ||
1630
+ typeof answer.at_least !== "boolean")
1631
+ fail(label + " returned an invalid boxes answer for " + id + ".");
1632
+ const presence = answer.presence.map((entry) => probability(label, entry, "presence for " + id));
1633
+ return {
1634
+ type: "boxes",
1635
+ boxes: answer.boxes.map((entry) => {
1636
+ const parsed = parseBox(label, id, isRecord(entry) ? entry.box : undefined, isRecord(entry) ? entry.found : undefined);
1637
+ if (parsed.type !== "box")
1638
+ fail(label + " returned an invalid box for " + id + ".");
1639
+ return {
1640
+ box: parsed.box,
1641
+ found: parsed.confidence,
1642
+ confidence: probability(label, isRecord(entry) ? entry.confidence : undefined, "box confidence for " + id),
1643
+ };
1644
+ }),
1645
+ count: answer.count,
1646
+ atLeast: answer.at_least,
1647
+ presence,
1648
+ };
1649
+ }
1650
+ if (question.type === "estimate") {
1651
+ const value = answer.number;
1652
+ if (typeof value !== "number" || !Number.isFinite(value) || !Array.isArray(answer.interval) ||
1653
+ answer.interval.length !== 2 ||
1654
+ answer.interval.some((entry) => typeof entry !== "number" || !Number.isFinite(entry)) ||
1655
+ answer.interval[0] > value || value > answer.interval[1])
1656
+ fail(label + " returned an invalid estimate for " + id + ".");
1657
+ const result = {
1658
+ type: "estimate",
1659
+ value,
1660
+ interval: [answer.interval[0], answer.interval[1]],
1661
+ };
1662
+ if (typeof answer.unit === "string")
1663
+ result.unit = answer.unit;
1664
+ return result;
1665
+ }
1666
+ if (question.type === "multi_choice") {
1667
+ if (!Array.isArray(answer.choices) || !isRecord(answer.probabilities))
1668
+ fail(label + " returned an invalid multi-choice answer for " + id + ".");
1669
+ const labels = Object.keys(question.criteria);
1670
+ const choices = independentLabelProbabilities(label, id, answer.probabilities, labels);
1671
+ for (const choice of answer.choices) {
1672
+ if (typeof choice !== "string" || !Object.hasOwn(question.criteria, choice))
1673
+ fail(label + " returned an unknown choice for " + id + ".");
1674
+ }
1675
+ return { type: "multi_choice", choices: answer.choices, probabilities: choices };
1676
+ }
1677
+ if (question.type === "box") {
1678
+ if (answer.box === null || (found !== undefined && found < 0.5))
1679
+ return { type: "no_match" };
1680
+ const parsed = parseBox(label, id, answer.box, answer.confidence);
1681
+ if (parsed.type !== "box")
1682
+ fail(label + " returned an invalid box for " + id + ".");
1683
+ return found === undefined ? parsed : { ...parsed, found };
1684
+ }
1685
+ return liquidUnsupported("question type " + question.type);
1686
+ }
1687
+ async function classifyLiquid(route, input, apiKey, signal) {
1688
+ if (Object.values(input.questions).some((question) => question.type === "locate"))
1689
+ return liquidUnsupported("locate questions on Liquid routes");
1690
+ const payload = {
1691
+ model: route.model,
1692
+ state: input.state,
1693
+ questions: Object.fromEntries(Object.entries(input.questions).map(([id, question]) => [id, liquidQuestion(id, question)])),
1694
+ };
1695
+ if (input.images.length) {
1696
+ payload.images = input.images.map((image) => {
1697
+ if ("url" in image)
1698
+ throw new ClassifierError("capability", "Liquid requires local images.");
1699
+ return { content_type: image.mimeType, base64: image.data };
1700
+ });
1701
+ }
1702
+ const audio = input.media.filter((media) => media.type === "audio");
1703
+ if (audio.length)
1704
+ payload.audio = audio.map((media) => ({ content_type: media.mimeType, base64: media.data }));
1705
+ const { body, requestId } = await postJson(route, "systemone", payload, apiKey, signal);
1706
+ if (!isRecord(body))
1707
+ fail("Liquid Decisions returned an unexpected response.");
1708
+ const text = stateText(input.state);
1709
+ const answers = Object.create(null);
1710
+ for (const [id, question] of Object.entries(input.questions)) {
1711
+ if (!isRecord(body.answers) || !Object.hasOwn(body.answers, id))
1712
+ fail("Liquid Decisions did not return an answer for " + id + ".");
1713
+ const parsed = parseLiquidAnswer("Liquid Decisions", id, question, body.answers[id], text);
1714
+ if (parsed !== undefined)
1715
+ answers[id] = parsed;
1716
+ }
1717
+ return finish(route, answers, body.usage, requestId);
1718
+ }