@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/src/providers.ts CHANGED
@@ -1,15 +1,24 @@
1
1
  import { randomUUID } from "node:crypto";
2
- import { postJson } from "./http.js";
2
+ import { imageContentParts, imageReferences, imageUrl, isImageReference, mapImageReferences, namedImage, questionImageReferences } from "./image-content.js";
3
+ import { postJson, type JsonErrorDetail, type JsonRequestIdDetail } from "./http.js";
3
4
  import { estimateCost, tokenCount } from "./cost.js";
5
+ import { openRouterDecisionCapabilities } from "./config.js";
4
6
  import {
5
7
  ClassifierError,
6
8
  isRecord,
7
9
  type Answer,
8
10
  type ClassifierResult,
11
+ type DecisionCitation,
12
+ type QuestionContent,
9
13
  type PreparedImage,
10
14
  type PreparedInput,
15
+ type PreparedMedia,
16
+ type ProviderCost,
11
17
  type Question,
12
18
  type ResolvedModel,
19
+ type TextSpan,
20
+ type WebFetchedResult,
21
+ type WebSearchResult,
13
22
  } from "./types.js";
14
23
 
15
24
  /**
@@ -21,6 +30,7 @@ import {
21
30
 
22
31
  const OPENAI_LABEL = "OpenAI Decisions";
23
32
  const PERPLEXITY_LABEL = "Perplexity Decisions";
33
+ const SARVAM_LABEL = "Sarvam Prism";
24
34
  const TYPESAFE_LABEL = "TypeSafe System One";
25
35
  const CLOUDFLARE_LABEL = "Cloudflare Workers AI";
26
36
  const EPSILON = 1e-6;
@@ -35,10 +45,24 @@ export async function classifyWithProvider(
35
45
  switch (route.api) {
36
46
  case "openai-decisions":
37
47
  return classifyOpenAi(route, input, apiKey, signal);
48
+ case "openrouter-decisions":
49
+ return classifyOpenRouter(route, input, apiKey, signal);
50
+ case "gemini-decisions":
51
+ return classifyGemini(route, input, apiKey, signal);
52
+ case "inception-decisions":
53
+ return classifyInception(route, input, apiKey, signal);
54
+ case "parallel-decisions":
55
+ return classifyParallel(route, input, apiKey, signal);
56
+ case "local-system-one":
57
+ return classifyLocalSystemOne(route, input, apiKey, signal);
38
58
  case "perplexity-decisions":
39
59
  return classifyPerplexity(route, input, apiKey, signal);
60
+ case "sarvam-system-one":
61
+ return classifySarvam(route, input, apiKey, signal);
40
62
  case "system-one":
41
63
  return classifySystemOne(route, input, apiKey, signal);
64
+ case "liquid-system-one":
65
+ return classifyLiquid(route, input, apiKey, signal);
42
66
  case "microsoft-system-one":
43
67
  return classifyMicrosoft(route, input, apiKey, signal);
44
68
  case "cloudflare-system-one":
@@ -111,11 +135,28 @@ function normalizedUsage(
111
135
  return usage;
112
136
  }
113
137
 
138
+ function reportedCost(
139
+ value: unknown,
140
+ source: ProviderCost["source"],
141
+ ): ProviderCost | undefined {
142
+ if (!isRecord(value)) return undefined;
143
+ const raw = value.cost;
144
+ const total =
145
+ typeof raw === "number" && Number.isFinite(raw) && raw >= 0
146
+ ? raw
147
+ : typeof raw === "string" && /^\d+(?:\.\d+)?$/.test(raw)
148
+ ? Number(raw)
149
+ : undefined;
150
+ if (total === undefined) return undefined;
151
+ return { currency: "USD", total, source };
152
+ }
153
+
114
154
  function finish(
115
155
  route: ResolvedModel,
116
156
  answers: Record<string, Answer>,
117
157
  rawUsage: unknown,
118
158
  requestId: string | undefined,
159
+ providerCost?: ProviderCost,
119
160
  ): ClassifierResult {
120
161
  const result: ClassifierResult = {
121
162
  provider: route.route,
@@ -126,11 +167,45 @@ function finish(
126
167
  const usage = normalizedUsage(rawUsage);
127
168
  if (usage !== undefined) result.usage = usage;
128
169
  if (requestId !== undefined) result.requestId = requestId;
170
+ if (providerCost !== undefined) result.providerCost = providerCost;
129
171
  return result;
130
172
  }
131
173
 
132
- function dataUrl(image: PreparedImage): string {
133
- return "data:" + image.mimeType + ";base64," + image.data;
174
+ function textContent(value: QuestionContent): string {
175
+ if (typeof value === "string") return value;
176
+ if (value.some((part) => typeof part !== "string"))
177
+ throw new ClassifierError("capability", "This content placement does not support images on the selected route.");
178
+ return value.join("");
179
+ }
180
+
181
+ function openAiImagePart(image: PreparedImage, detail?: PreparedInput["imageDetail"]): Record<string, unknown> {
182
+ return {
183
+ type: "input_image",
184
+ image_url: imageUrl(image),
185
+ ...(detail !== undefined ? { detail } : {}),
186
+ };
187
+ }
188
+
189
+ function openAiContent(value: unknown, input: PreparedInput): unknown[] {
190
+ return imageContentParts(value, (id) => openAiImagePart(namedImage(input.images, id), input.imageDetail))
191
+ .map((part) => typeof part === "string" ? { type: "input_text", text: part } : part);
192
+ }
193
+
194
+ function jsonValueCount(value: unknown): number {
195
+ let total = 1;
196
+ if (Array.isArray(value)) for (const entry of value) total += jsonValueCount(entry);
197
+ else if (isRecord(value)) for (const entry of Object.values(value)) total += jsonValueCount(entry);
198
+ return total;
199
+ }
200
+
201
+ function openAiJsonPart(value: unknown): Record<string, unknown> | undefined {
202
+ if (isRecord(value) || (Array.isArray(value) && value.every((entry) => isRecord(entry)))) {
203
+ const bytes = Buffer.byteLength(JSON.stringify(value));
204
+ if (bytes > 256 * 1024 || jsonValueCount(value) > 10_000)
205
+ fail(OPENAI_LABEL + " input_json exceeds the documented 256 KiB / 10,000-value limit. Supply a smaller JSON state.");
206
+ return { type: "input_json", data: value };
207
+ }
208
+ return undefined;
134
209
  }
135
210
 
136
211
  /* Answer parsing for map-shaped answers (Perplexity, System One, Clef) --- */
@@ -166,6 +241,37 @@ function labelProbabilities(
166
241
  }
167
242
 
168
243
  /** Probability mass must be close to 1; it is never renormalized on the caller's behalf. */
244
+ function independentLabelProbabilities(
245
+ label: string,
246
+ id: string,
247
+ value: unknown,
248
+ labels: string[],
249
+ ): Record<string, number> {
250
+ if (!isRecord(value))
251
+ fail(label + " returned invalid probabilities for " + id + ".");
252
+ const result = Object.create(null) as Record<string, number>;
253
+ for (const [key, entry] of Object.entries(value)) {
254
+ if (!labels.includes(key))
255
+ fail(
256
+ label +
257
+ " returned an unknown option in the probabilities for " +
258
+ id +
259
+ ".",
260
+ );
261
+ result[key] = probability(
262
+ label,
263
+ entry,
264
+ "probability for " + id + "." + key,
265
+ );
266
+ }
267
+ for (const key of labels) {
268
+ if (!Object.hasOwn(result, key))
269
+ fail(label + " did not return a probability for " + id + "." + key + ".");
270
+ }
271
+ // Liquid multi-select questions treat each label as its own yes/no decision.
272
+ return result;
273
+ }
274
+
169
275
  function checkDistribution(
170
276
  label: string,
171
277
  id: string,
@@ -236,6 +342,54 @@ function scoreValue(
236
342
  return Math.min(maximum, Math.max(0, value));
237
343
  }
238
344
 
345
+ function nonNegativeInteger(label: string, value: unknown, field: string): number {
346
+ if (!Number.isSafeInteger(value) || (value as number) < 0)
347
+ fail(label + " returned an invalid " + field + ".");
348
+ return value as number;
349
+ }
350
+
351
+ function codePointSlice(source: string, start: number, end: number): string {
352
+ const characters = Array.from(source);
353
+ if (start > end || end > characters.length) return "";
354
+ return characters.slice(start, end).join("");
355
+ }
356
+
357
+ function parseTextSpans(
358
+ label: string,
359
+ id: string,
360
+ value: unknown,
361
+ sources: { state?: string; snippets?: string[] },
362
+ ): TextSpan[] {
363
+ if (!Array.isArray(value)) fail(label + " returned invalid spans for " + id + ".");
364
+ return value.map((entry, index) => {
365
+ if (!isRecord(entry))
366
+ fail(label + " returned an invalid span for " + id + ".");
367
+ const start = nonNegativeInteger(label, entry.start, "span offset for " + id);
368
+ const end = nonNegativeInteger(label, entry.end, "span offset for " + id);
369
+ if (typeof entry.text !== "string" || end < start)
370
+ fail(label + " returned an invalid span for " + id + ".");
371
+ let searchResult: number | undefined;
372
+ if (entry.search_result !== undefined) {
373
+ searchResult = nonNegativeInteger(
374
+ label, entry.search_result, "search result index for " + id,
375
+ );
376
+ if (sources.snippets === undefined || searchResult >= sources.snippets.length)
377
+ fail(label + " returned an unknown search result for " + id + ".");
378
+ }
379
+ const source = searchResult === undefined ? sources.state : sources.snippets![searchResult];
380
+ if (source === undefined || codePointSlice(source, start, end) !== entry.text)
381
+ fail(label + " returned a span that does not match its source for " + id + ".");
382
+ const span: TextSpan = {
383
+ start,
384
+ end,
385
+ text: entry.text,
386
+ score: probability(label, entry.score, "span score for " + id + "." + index),
387
+ };
388
+ if (searchResult !== undefined) span.searchResult = searchResult;
389
+ return span;
390
+ });
391
+ }
392
+
239
393
  function parseBox(
240
394
  label: string,
241
395
  id: string,
@@ -274,6 +428,7 @@ function parseTypedAnswer(
274
428
  id: string,
275
429
  question: Question,
276
430
  answer: unknown,
431
+ sources: { state?: string; snippets?: string[] } = {},
277
432
  ): Answer {
278
433
  if (!isRecord(answer))
279
434
  fail(label + " returned an invalid answer for " + id + ".");
@@ -323,6 +478,11 @@ function parseTypedAnswer(
323
478
  ),
324
479
  };
325
480
  }
481
+ if (question.type === "locate") {
482
+ if (answer.type !== "locate")
483
+ fail(label + " did not return a locate answer for " + id + ".");
484
+ return { type: "locate", spans: parseTextSpans(label, id, answer.spans, sources) };
485
+ }
326
486
  if (answer.type !== "box")
327
487
  fail(label + " did not return a box answer for " + id + ".");
328
488
  return parseBox(label, id, answer.box, answer.confidence);
@@ -362,6 +522,7 @@ function parseTypedAnswers(
362
522
  label: string,
363
523
  value: unknown,
364
524
  questions: Record<string, Question>,
525
+ sources: { state?: string; snippets?: string[] } = {},
365
526
  ): Record<string, Answer> {
366
527
  if (!isRecord(value)) fail(label + " returned an unexpected response.");
367
528
  // Question IDs may be "__proto__", so answers are collected without a prototype.
@@ -372,7 +533,7 @@ function parseTypedAnswers(
372
533
  answers[id] = validateDecision(
373
534
  label,
374
535
  id,
375
- parseTypedAnswer(label, id, question, value[id]),
536
+ parseTypedAnswer(label, id, question, value[id], sources),
376
537
  );
377
538
  }
378
539
  return answers;
@@ -380,66 +541,106 @@ function parseTypedAnswers(
380
541
 
381
542
  /* OpenAI Decisions -------------------------------------------------------- */
382
543
 
383
- function predicateInstructions(
384
- question: Extract<Question, { type: "bool" }>,
385
- ): string {
544
+ function predicateInstructions(question: Extract<Question, { type: "bool" }>): QuestionContent {
386
545
  const meanings: string[] = [];
387
- if (question.criteria?.true)
388
- meanings.push("True means: " + question.criteria.true);
389
- if (question.criteria?.false)
390
- meanings.push("False means: " + question.criteria.false);
391
- return meanings.length > 0
392
- ? question.instructions + "\n" + meanings.join("\n")
393
- : question.instructions;
546
+ if (question.criteria?.true) meanings.push("True means: " + textContent(question.criteria.true));
547
+ if (question.criteria?.false) meanings.push("False means: " + textContent(question.criteria.false));
548
+ if (meanings.length === 0) return question.instructions;
549
+ const suffix = "\n" + meanings.join("\n");
550
+ return typeof question.instructions === "string" ? question.instructions + suffix : [...question.instructions, suffix];
394
551
  }
395
552
 
396
- function openAiQuestion(
397
- id: string,
398
- question: Question,
399
- ): Record<string, unknown> {
400
- if (question.type === "bool")
401
- return {
402
- type: "predicate",
403
- name: id,
404
- instructions: predicateInstructions(question),
405
- };
406
- if (question.type === "choice") {
407
- return {
408
- type: "choice",
409
- name: id,
410
- instructions: question.instructions,
411
- choices: Object.entries(question.criteria).map(
412
- ([value, description]) => ({ value, description }),
413
- ),
414
- };
415
- }
416
- if (question.type === "score") {
417
- return {
418
- type: "score",
419
- name: id,
420
- instructions: question.instructions,
421
- levels: question.criteria.map((label) => ({ label })),
553
+ function openAiQuestion(id: string, question: Question, input: PreparedInput): Record<string, unknown> {
554
+ const instructions = question.type === "bool" ? predicateInstructions(question) : question.instructions;
555
+ const wireInstructions = typeof instructions === "string" ? instructions : openAiContent(instructions, input);
556
+ if (question.type === "bool") return { type: "predicate", name: id, instructions: wireInstructions };
557
+ if (question.type === "choice") return {
558
+ type: "choice", name: id, instructions: wireInstructions,
559
+ choices: Object.entries(question.criteria).map(([value, description]) => ({
560
+ // Only caller-supplied boolean labels map to booleans. The internal NONE sentinel
561
+ // remains a distinct string so boolean questions can still reject all options.
562
+ value: question.booleanValues && (value === "true" || value === "false") ? value === "true" : value,
563
+ description: textContent(description),
564
+ })),
565
+ };
566
+ if (question.type === "score") return {
567
+ type: "score", name: id, instructions: wireInstructions,
568
+ levels: question.criteria.map((label, index) => ({
569
+ label: textContent(label),
570
+ ...(question.descriptions?.[index] !== undefined ? { description: question.descriptions[index] } : {}),
571
+ })),
572
+ };
573
+ throw unsupportedBox();
574
+ }
575
+
576
+ function openAiCachePayload(input: PreparedInput): Record<string, unknown> {
577
+ const payload: Record<string, unknown> = {};
578
+ if (input.promptCache?.key !== undefined) payload.prompt_cache_key = input.promptCache.key;
579
+ if (input.promptCache?.mode !== undefined || input.promptCache?.ttl !== undefined)
580
+ payload.prompt_cache_options = {
581
+ ...(input.promptCache?.mode !== undefined ? { mode: input.promptCache.mode } : {}),
582
+ ...(input.promptCache?.ttl !== undefined ? { ttl: input.promptCache.ttl } : {}),
422
583
  };
584
+ return payload;
585
+ }
586
+
587
+ function openAiSetBreakpoint(parts: unknown[]): boolean {
588
+ const first = parts.find((part) => isRecord(part) && (part.type === "input_text" || part.type === "input_image"));
589
+ if (isRecord(first)) {
590
+ first.prompt_cache_breakpoint = { mode: "explicit" };
591
+ return true;
423
592
  }
424
- throw unsupportedBox();
593
+ return false;
425
594
  }
426
595
 
427
- function openAiInput(input: PreparedInput): unknown {
428
- const text =
429
- typeof input.state === "string" ? input.state : JSON.stringify(input.state);
430
- if (input.images.length === 0) return text;
431
- return [
432
- {
433
- role: "user",
434
- content: [
435
- { type: "input_text", text },
436
- ...input.images.map((image) => ({
437
- type: "input_image",
438
- image_url: dataUrl(image),
439
- })),
440
- ],
441
- },
442
- ];
596
+ function openAiStateParts(input: PreparedInput): unknown[] {
597
+ const text = typeof input.state === "string" ? input.state : JSON.stringify(input.state);
598
+ const references = imageReferences(input.state);
599
+ const parts = references.length > 0
600
+ ? openAiContent(input.state, input)
601
+ : text
602
+ ? (() => {
603
+ const jsonPart = typeof input.state === "string" ? undefined : openAiJsonPart(input.state);
604
+ return jsonPart ? [{ type: "input_text", text: "Structured state:" }, jsonPart] : [{ type: "input_text", text }];
605
+ })()
606
+ : [];
607
+ for (const image of input.images.filter((entry) => entry.id === undefined))
608
+ parts.push(openAiImagePart(image, input.imageDetail));
609
+ return parts;
610
+ }
611
+
612
+ function openAiInput(input: PreparedInput): { input: unknown; payload: Record<string, unknown> } {
613
+ const payload = openAiCachePayload(input);
614
+ if (input.conversation !== undefined) {
615
+ const items = input.conversation.map((item) => ({ ...(isRecord(item) ? item : {}) }));
616
+ const stateParts = openAiStateParts(input);
617
+ if (stateParts.length > 0)
618
+ items.unshift({ type: "message", role: "user", content: stateParts });
619
+ if (input.promptCache?.breakpoints) {
620
+ const userItem = items.find((item) => isRecord(item) && item.type === "message" && item.role === "user" && Array.isArray(item.content));
621
+ if (!isRecord(userItem) || !openAiSetBreakpoint(userItem.content as unknown[])) {
622
+ const parts = [{ type: "input_text", text: "", prompt_cache_breakpoint: { mode: "explicit" } }];
623
+ items.unshift({ type: "message", role: "user", content: parts });
624
+ }
625
+ }
626
+ return { input: items, payload };
627
+ }
628
+ const content = openAiStateParts(input);
629
+ const breakpointSet = input.promptCache?.breakpoints === true && openAiSetBreakpoint(content);
630
+ if (!breakpointSet && input.promptCache?.breakpoints)
631
+ content.unshift({ type: "input_text", text: "", prompt_cache_breakpoint: { mode: "explicit" } });
632
+ const text = typeof input.state === "string" ? input.state : JSON.stringify(input.state);
633
+ if (
634
+ !breakpointSet &&
635
+ input.promptCache?.breakpoints !== true &&
636
+ content.length === 1 &&
637
+ isRecord(content[0]) &&
638
+ content[0].type === "input_text" &&
639
+ content[0].text === text &&
640
+ Object.keys(payload).length === 0
641
+ )
642
+ return { input: text, payload };
643
+ return { input: [{ type: "message", role: "user", content }], payload };
443
644
  }
444
645
 
445
646
  function openAiChoiceProbabilities(
@@ -447,26 +648,21 @@ function openAiChoiceProbabilities(
447
648
  id: string,
448
649
  value: unknown,
449
650
  labels: string[],
651
+ booleanValues: boolean,
450
652
  ): Record<string, number> {
451
653
  if (!Array.isArray(value))
452
654
  fail(label + " returned invalid probabilities for " + id + ".");
453
655
  const mapped = Object.create(null) as Record<string, unknown>;
454
656
  for (const entry of value) {
455
- if (
456
- !isRecord(entry) ||
457
- typeof entry.value !== "string" ||
458
- !labels.includes(entry.value)
459
- ) {
460
- fail(
461
- label +
462
- " returned an unknown option in the probabilities for " +
463
- id +
464
- ".",
465
- );
466
- }
467
- if (Object.hasOwn(mapped, entry.value))
657
+ if (!isRecord(entry)) fail(label + " returned an unknown option in the probabilities for " + id + ".");
658
+ const key = booleanValues && typeof entry.value === "boolean"
659
+ ? (entry.value ? "true" : "false")
660
+ : typeof entry.value === "string" ? entry.value : undefined;
661
+ if (key === undefined || !labels.includes(key))
662
+ fail(label + " returned an unknown option in the probabilities for " + id + ".");
663
+ if (Object.hasOwn(mapped, key))
468
664
  fail(label + " returned duplicate probabilities for " + id + ".");
469
- mapped[entry.value] = entry.probability;
665
+ mapped[key] = entry.probability;
470
666
  }
471
667
  return labelProbabilities(label, id, mapped, labels);
472
668
  }
@@ -524,18 +720,21 @@ function parseOpenAiAnswer(
524
720
  };
525
721
  }
526
722
  if (question.type === "choice") {
527
- if (answer.type !== "choice" || typeof answer.choice !== "string")
528
- fail(label + " did not return a choice answer for " + id + ".");
529
- if (!Object.hasOwn(question.criteria, answer.choice))
723
+ if (answer.type !== "choice") fail(label + " did not return a choice answer for " + id + ".");
724
+ const choice = question.booleanValues && typeof answer.choice === "boolean"
725
+ ? (answer.choice ? "true" : "false")
726
+ : typeof answer.choice === "string" ? answer.choice : undefined;
727
+ if (choice === undefined || !Object.hasOwn(question.criteria, choice))
530
728
  fail(label + " returned an unknown choice for " + id + ".");
531
729
  return {
532
730
  type: "choice",
533
- choice: answer.choice,
731
+ choice,
534
732
  probabilities: openAiChoiceProbabilities(
535
733
  label,
536
734
  id,
537
735
  answer.probabilities,
538
736
  Object.keys(question.criteria),
737
+ question.booleanValues === true,
539
738
  ),
540
739
  confidence: probability(label, answer.confidence, "confidence for " + id),
541
740
  };
@@ -597,25 +796,501 @@ async function classifyOpenAi(
597
796
  signal?: AbortSignal,
598
797
  ): Promise<ClassifierResult> {
599
798
  const questions = Object.entries(input.questions).map(([id, question]) =>
600
- openAiQuestion(id, question),
799
+ openAiQuestion(id, question, input),
601
800
  );
602
- const { body, requestId } = await postJson(
801
+ const preparedInput = openAiInput(input);
802
+ const { body, requestId, costHeader } = await postJson(
603
803
  route,
604
804
  "decisions",
605
805
  {
606
806
  model: route.model,
607
- input: openAiInput(input),
807
+ input: preparedInput.input,
608
808
  questions,
809
+ ...preparedInput.payload,
609
810
  },
610
811
  apiKey,
611
812
  signal,
612
813
  );
613
814
  if (!isRecord(body)) fail(OPENAI_LABEL + " returned an unexpected response.");
815
+ const metadata = isRecord(body.provider_metadata) ? body.provider_metadata.gateway : undefined;
816
+ const gatewayCost = reportedCost(metadata, "gateway") ??
817
+ (costHeader ? { currency: "USD" as const, total: Number(costHeader), source: "gateway" as const } : undefined);
614
818
  return finish(
615
819
  route,
616
820
  parseOpenAiAnswers(OPENAI_LABEL, body.answers, input.questions),
617
821
  body.usage,
618
822
  requestId,
823
+ gatewayCost,
824
+ );
825
+ }
826
+
827
+ /* OpenRouter alpha Decisions ---------------------------------------------- */
828
+
829
+ const OPENROUTER_LABEL = "OpenRouter Decisions";
830
+ const OPENROUTER_ID = /^[A-Za-z0-9_.:-]{1,128}$/;
831
+
832
+ function openRouterImagePart(image: PreparedImage, detail?: PreparedInput["imageDetail"]): Record<string, unknown> {
833
+ return {
834
+ type: "image_url",
835
+ image_url: {
836
+ url: imageUrl(image),
837
+ ...(detail !== undefined ? { detail } : {}),
838
+ },
839
+ };
840
+ }
841
+
842
+ function openRouterState(input: PreparedInput, flexible: boolean): unknown {
843
+ const shared = input.images.filter((image) => image.id === undefined);
844
+ if (!flexible) {
845
+ let parts: unknown[];
846
+ if (isImageReference(input.state)) parts = [openRouterImagePart(namedImage(input.images, input.state.$image), input.imageDetail)];
847
+ else if (Array.isArray(input.state)) {
848
+ parts = input.state.map((entry) => isImageReference(entry)
849
+ ? openRouterImagePart(namedImage(input.images, entry.$image), input.imageDetail)
850
+ : typeof entry === "string" ? entry : JSON.stringify(entry));
851
+ } else parts = [typeof input.state === "string" ? input.state : JSON.stringify(input.state)];
852
+ for (const image of shared) parts.push(openRouterImagePart(image, input.imageDetail));
853
+ return parts.length === 1 && typeof parts[0] === "string" ? parts[0] : parts;
854
+ }
855
+ if (input.images.length === 0) return input.state;
856
+ const parts = imageContentParts(input.state, (id) => openRouterImagePart(namedImage(input.images, id), input.imageDetail));
857
+ for (const image of shared) parts.push(openRouterImagePart(image, input.imageDetail));
858
+ if (parts.length === 0) return input.state;
859
+ return parts;
860
+ }
861
+
862
+ function openRouterMedia(media: PreparedMedia[]): Record<string, unknown>[] {
863
+ return media.map((entry) => entry.type === "audio"
864
+ ? {
865
+ type: "input_audio",
866
+ input_audio: {
867
+ data: entry.data,
868
+ format: entry.mimeType.slice(entry.mimeType.indexOf("/") + 1),
869
+ },
870
+ }
871
+ : { type: "video_url", video_url: { url: "data:" + entry.mimeType + ";base64," + entry.data } });
872
+ }
873
+
874
+ function openRouterQuestion(
875
+ id: string,
876
+ question: Question,
877
+ input: PreparedInput,
878
+ flexible: boolean,
879
+ ): Record<string, unknown> {
880
+ if (question.type === "extract")
881
+ throw new ClassifierError("capability", "OpenRouter Decisions does not support extract questions.");
882
+ const content = flexible
883
+ ? (value: QuestionContent) => mapImageReferences(value, (imageId) => openRouterImagePart(namedImage(input.images, imageId), input.imageDetail))
884
+ : textContent;
885
+ const wire: Record<string, unknown> = {
886
+ type: question.type === "bool" ? "noul" : question.type,
887
+ instructions: content(question.instructions),
888
+ };
889
+ if (question.type === "bool") {
890
+ if (question.criteria)
891
+ wire.criteria = Object.fromEntries(
892
+ Object.entries(question.criteria).map(([key, value]) => [key, content(value)]),
893
+ );
894
+ return wire;
895
+ }
896
+ if (question.type === "choice") {
897
+ wire.criteria = Object.fromEntries(
898
+ Object.entries(question.criteria).map(([key, value]) => [key, content(value)]),
899
+ );
900
+ return wire;
901
+ }
902
+ if (question.type === "score") {
903
+ wire.criteria = question.criteria.map(content);
904
+ return wire;
905
+ }
906
+ if (question.type === "box") return wire;
907
+ throw new ClassifierError("capability", "OpenRouter Decisions does not support " + question.type + " questions.");
908
+ }
909
+
910
+ function openRouterAnswers(
911
+ value: unknown,
912
+ questions: Record<string, Question>,
913
+ ): Record<string, Answer> {
914
+ if (!isRecord(value)) fail(OPENROUTER_LABEL + " returned an unexpected response.");
915
+ const answers = Object.create(null) as Record<string, unknown>;
916
+ for (const [id, question] of Object.entries(questions)) {
917
+ if (!Object.hasOwn(value, id))
918
+ fail(OPENROUTER_LABEL + " did not return an answer for " + id + ".");
919
+ const raw = value[id];
920
+ if (
921
+ isRecord(raw) &&
922
+ raw.type !== "refusal" &&
923
+ raw.confidence === undefined &&
924
+ isRecord(raw.probabilities) &&
925
+ (question.type === "choice" || question.type === "score")
926
+ ) {
927
+ const probabilities = Object.values(raw.probabilities).filter(
928
+ (entry) => typeof entry === "number" && Number.isFinite(entry),
929
+ ) as number[];
930
+ if (probabilities.length > 0) answers[id] = { ...raw, confidence: Math.max(...probabilities) };
931
+ else answers[id] = raw;
932
+ } else answers[id] = raw;
933
+ }
934
+ return parseTypedAnswers(OPENROUTER_LABEL, answers, questions);
935
+ }
936
+
937
+ async function classifyOpenRouter(
938
+ route: ResolvedModel,
939
+ input: PreparedInput,
940
+ apiKey: string,
941
+ signal?: AbortSignal,
942
+ ): Promise<ClassifierResult> {
943
+ const caps = openRouterDecisionCapabilities(route.model);
944
+ if (!caps.box && Object.values(input.questions).some((question) => question.type === "box"))
945
+ throw new ClassifierError("capability", "OpenRouter box questions require a TypeSafe Jev 1.14 endpoint.");
946
+ const stateParts = openRouterState(input, caps.flexibleImagePlacement);
947
+ const state = Array.isArray(stateParts) || typeof stateParts === "string" || isRecord(stateParts)
948
+ ? stateParts
949
+ : JSON.stringify(stateParts);
950
+ const payload: Record<string, unknown> = {
951
+ model: route.model,
952
+ state,
953
+ questions: Object.fromEntries(
954
+ Object.entries(input.questions).map(([id, question]) => [id, openRouterQuestion(id, question, input, caps.flexibleImagePlacement)]),
955
+ ),
956
+ };
957
+ if (input.media.length > 0) {
958
+ const withParts = Array.isArray(state) ? state : [state];
959
+ payload.state = [...withParts, ...openRouterMedia(input.media)];
960
+ }
961
+ const { body, requestId } = await postJson(
962
+ route,
963
+ "alpha/decisions",
964
+ payload,
965
+ apiKey,
966
+ signal,
967
+ );
968
+ if (!isRecord(body)) fail(OPENROUTER_LABEL + " returned an unexpected response.");
969
+ const bodyId = typeof body.id === "string" && OPENROUTER_ID.test(body.id) ? body.id : undefined;
970
+ return finish(
971
+ route,
972
+ openRouterAnswers(body.answers, input.questions),
973
+ body.usage,
974
+ requestId ?? bodyId,
975
+ reportedCost(body.usage, "provider"),
976
+ );
977
+ }
978
+
979
+ /* Shared derived-confidence parsing for newer System One-like adapters ---- */
980
+
981
+ function deriveConfidenceAnswers(
982
+ label: string,
983
+ rawAnswers: unknown,
984
+ questions: Record<string, Question>,
985
+ ): Record<string, Answer> {
986
+ if (!isRecord(rawAnswers)) fail(label + " returned an unexpected response.");
987
+ const answers = Object.create(null) as Record<string, unknown>;
988
+ for (const [id, question] of Object.entries(questions)) {
989
+ if (!Object.hasOwn(rawAnswers, id))
990
+ fail(label + " did not return an answer for " + id + ".");
991
+ const raw = rawAnswers[id];
992
+ if (
993
+ isRecord(raw) &&
994
+ raw.type !== "refusal" &&
995
+ raw.confidence === undefined &&
996
+ isRecord(raw.probabilities) &&
997
+ (question.type === "choice" || question.type === "score")
998
+ ) {
999
+ const values = Object.values(raw.probabilities).filter(
1000
+ (entry) => typeof entry === "number" && Number.isFinite(entry),
1001
+ ) as number[];
1002
+ answers[id] = values.length > 0 ? { ...raw, confidence: Math.max(...values) } : raw;
1003
+ } else answers[id] = raw;
1004
+ }
1005
+ return parseTypedAnswers(label, answers, questions);
1006
+ }
1007
+
1008
+ function mediaDataUrl(entry: PreparedMedia): string {
1009
+ return "data:" + entry.mimeType + ";base64," + entry.data;
1010
+ }
1011
+
1012
+ /* Google Gemini Decisions -------------------------------------------------- */
1013
+
1014
+ const GEMINI_LABEL = "Gemini Decisions";
1015
+
1016
+ function geminiInput(input: PreparedInput): unknown {
1017
+ const text = typeof input.state === "string" ? input.state : JSON.stringify(input.state);
1018
+ const blocks: unknown[] = text ? [{ type: "text", text }] : [];
1019
+ for (const image of input.images) {
1020
+ if ("url" in image) blocks.push({ type: "image", uri: image.url });
1021
+ else blocks.push({ type: "image", data: image.data, mime_type: image.mimeType });
1022
+ }
1023
+ for (const media of input.media)
1024
+ blocks.push({ type: media.type, data: media.data, mime_type: media.mimeType });
1025
+ if (blocks.length === 0) return text;
1026
+ return blocks.length === 1 && isRecord(blocks[0]) && blocks[0].type === "text" ? text : blocks;
1027
+ }
1028
+
1029
+ function geminiQuestion(id: string, question: Question): Record<string, unknown> {
1030
+ if (question.type === "extract")
1031
+ throw new ClassifierError("capability", "Gemini Decisions does not support extract questions.");
1032
+ const wire: Record<string, unknown> = {
1033
+ type: question.type === "bool" ? "noul" : question.type,
1034
+ instructions: textContent(question.instructions),
1035
+ };
1036
+ if (question.type === "bool" && question.criteria) {
1037
+ const criteria: Record<string, string> = {};
1038
+ if (question.criteria.true !== undefined) criteria.true_description = textContent(question.criteria.true);
1039
+ if (question.criteria.false !== undefined) criteria.false_description = textContent(question.criteria.false);
1040
+ if (Object.keys(criteria).length > 0) wire.criteria = criteria;
1041
+ } else if (question.type === "choice") {
1042
+ wire.criteria = Object.fromEntries(
1043
+ Object.entries(question.criteria).map(([key, value]) => [key, textContent(value)]),
1044
+ );
1045
+ } else if (question.type === "score") {
1046
+ wire.criteria = question.criteria.map(textContent);
1047
+ }
1048
+ return wire;
1049
+ }
1050
+
1051
+ async function classifyGemini(
1052
+ route: ResolvedModel,
1053
+ input: PreparedInput,
1054
+ apiKey: string,
1055
+ signal?: AbortSignal,
1056
+ ): Promise<ClassifierResult> {
1057
+ const payload = {
1058
+ model: route.model,
1059
+ input: geminiInput(input),
1060
+ questions: Object.fromEntries(
1061
+ Object.entries(input.questions).map(([id, question]) => [id, geminiQuestion(id, question)]),
1062
+ ),
1063
+ };
1064
+ const { body, requestId } = await postJson(route, "decisions", payload, apiKey, signal);
1065
+ if (!isRecord(body)) fail(GEMINI_LABEL + " returned an unexpected response.");
1066
+ const rawUsage = isRecord(body.usage)
1067
+ ? {
1068
+ input_tokens: body.usage.total_input_tokens,
1069
+ output_tokens: body.usage.total_output_tokens,
1070
+ total_tokens: body.usage.total_tokens,
1071
+ }
1072
+ : undefined;
1073
+ return finish(
1074
+ route,
1075
+ deriveConfidenceAnswers(GEMINI_LABEL, body.answers, input.questions),
1076
+ rawUsage,
1077
+ requestId,
1078
+ );
1079
+ }
1080
+
1081
+ /* Inception Mercury Decide ------------------------------------------------- */
1082
+
1083
+ const INCEPTION_LABEL = "Inception Mercury Decide";
1084
+
1085
+ function inceptionImagePart(image: PreparedImage): Record<string, unknown> {
1086
+ return { type: "image_url", image_url: { url: imageUrl(image) } };
1087
+ }
1088
+
1089
+ function inceptionState(input: PreparedInput): unknown {
1090
+ if (input.images.length === 0 && input.media.length === 0) return input.state;
1091
+ const parts = imageContentParts(input.state, (id) => inceptionImagePart(namedImage(input.images, id)));
1092
+ for (const image of input.images.filter((entry) => entry.id === undefined)) parts.push(inceptionImagePart(image));
1093
+ return parts.length === 1 && typeof parts[0] === "string" ? parts[0] : parts;
1094
+ }
1095
+
1096
+ function inceptionQuestion(id: string, question: Question, input: PreparedInput): Record<string, unknown> {
1097
+ const content = (value: QuestionContent) => mapImageReferences(value, (imageId) => inceptionImagePart(namedImage(input.images, imageId)));
1098
+ const wire: Record<string, unknown> = {
1099
+ type: question.type === "bool" ? "noul" : question.type,
1100
+ instructions: question.instructions === undefined ? undefined : content(question.instructions),
1101
+ };
1102
+ if (question.type === "choice") {
1103
+ wire.criteria = Object.fromEntries(
1104
+ Object.entries(question.criteria).map(([key, value]) => [key, content(value)]),
1105
+ );
1106
+ } else if (question.type === "score") {
1107
+ wire.criteria = question.criteria.map(content);
1108
+ } else if (question.type === "extract") {
1109
+ wire.criteria = Object.fromEntries(
1110
+ Object.entries(question.criteria).map(([key, value]) => [key, textContent(value)]),
1111
+ );
1112
+ if (question.source !== undefined) wire.source = question.source;
1113
+ if (question.threshold !== undefined) wire.threshold = question.threshold;
1114
+ if (question.snapToWords !== undefined) wire.snap_to_words = question.snapToWords;
1115
+ if (question.debug !== undefined) wire.debug = question.debug;
1116
+ } else if (question.type === "bool" && question.criteria) {
1117
+ wire.criteria = Object.fromEntries(
1118
+ Object.entries(question.criteria).map(([key, value]) => [key, content(value)]),
1119
+ );
1120
+ }
1121
+ return wire;
1122
+ }
1123
+
1124
+ function inceptionAnswers(
1125
+ rawAnswers: unknown,
1126
+ questions: Record<string, Question>,
1127
+ input: PreparedInput,
1128
+ ): Record<string, Answer> {
1129
+ if (!isRecord(rawAnswers)) fail(INCEPTION_LABEL + " returned an unexpected response.");
1130
+ const answers = Object.create(null) as Record<string, Answer>;
1131
+ for (const [id, question] of Object.entries(questions)) {
1132
+ const raw = rawAnswers[id];
1133
+ if (raw === undefined) fail(INCEPTION_LABEL + " did not return an answer for " + id + ".");
1134
+ if (question.type !== "extract") continue;
1135
+ if (!isRecord(raw) || !isRecord(raw.spans) || !isRecord(raw.not_stated))
1136
+ fail(INCEPTION_LABEL + " returned an invalid extract answer for " + id + ".");
1137
+ const sourceField = question.source;
1138
+ const sourceValue = typeof input.state === "string"
1139
+ ? input.state
1140
+ : sourceField !== undefined && isRecord(input.state)
1141
+ ? input.state[sourceField]
1142
+ : undefined;
1143
+ if (typeof sourceValue !== "string")
1144
+ fail(INCEPTION_LABEL + " cannot locate extract spans without a source string.");
1145
+ const source = sourceValue;
1146
+ const spans = Object.create(null) as Record<string, TextSpan[]>;
1147
+ const notStated = Object.create(null) as Record<string, number>;
1148
+ for (const field of Object.keys(question.criteria)) {
1149
+ const entries = raw.spans[field] ?? [];
1150
+ if (!Array.isArray(entries)) fail(INCEPTION_LABEL + " returned invalid extract spans for " + id + ".");
1151
+ spans[field] = entries.map((entry) => {
1152
+ if (!isRecord(entry) || typeof entry.text !== "string")
1153
+ fail(INCEPTION_LABEL + " returned an invalid extract span for " + id + ".");
1154
+ const start = nonNegativeInteger(INCEPTION_LABEL, entry.start, "extract span offset for " + id);
1155
+ const end = nonNegativeInteger(INCEPTION_LABEL, entry.end, "extract span offset for " + id);
1156
+ if (end < start || codePointSlice(source, start, end) !== entry.text)
1157
+ fail(INCEPTION_LABEL + " returned an extract span that does not match its source for " + id + ".");
1158
+ return {
1159
+ start,
1160
+ end,
1161
+ text: entry.text,
1162
+ score: probability(INCEPTION_LABEL, entry.confidence, "extract confidence for " + id),
1163
+ };
1164
+ });
1165
+ notStated[field] = probability(INCEPTION_LABEL, raw.not_stated[field], "not_stated for " + id);
1166
+ }
1167
+ answers[id] = { type: "extract", spans, notStated };
1168
+ }
1169
+ const coreQuestions = Object.fromEntries(
1170
+ Object.entries(questions).filter(([, question]) => question.type !== "extract"),
1171
+ );
1172
+ if (Object.keys(coreQuestions).length > 0) {
1173
+ const core = deriveConfidenceAnswers(INCEPTION_LABEL, rawAnswers, coreQuestions);
1174
+ for (const [id, answer] of Object.entries(core)) answers[id] = answer;
1175
+ }
1176
+ return answers;
1177
+ }
1178
+
1179
+ async function classifyInception(
1180
+ route: ResolvedModel,
1181
+ input: PreparedInput,
1182
+ apiKey: string,
1183
+ signal?: AbortSignal,
1184
+ ): Promise<ClassifierResult> {
1185
+ const payload = {
1186
+ model: route.model,
1187
+ state: inceptionState(input),
1188
+ questions: Object.fromEntries(
1189
+ Object.entries(input.questions).map(([id, question]) => [id, inceptionQuestion(id, question, input)]),
1190
+ ),
1191
+ };
1192
+ const { body, requestId } = await postJson(route, "decisions", payload, apiKey, signal);
1193
+ if (!isRecord(body)) fail(INCEPTION_LABEL + " returned an unexpected response.");
1194
+ return finish(
1195
+ route,
1196
+ inceptionAnswers(body.answers, input.questions, input),
1197
+ body.usage,
1198
+ requestId,
1199
+ );
1200
+ }
1201
+
1202
+ /* Parallel Decisions ------------------------------------------------------- */
1203
+
1204
+ const PARALLEL_LABEL = "Parallel Decisions";
1205
+
1206
+ function parallelCitations(value: unknown): DecisionCitation[] {
1207
+ if (value === undefined) return [];
1208
+ if (!Array.isArray(value)) fail(PARALLEL_LABEL + " returned invalid citations.");
1209
+ return value.map((entry) => {
1210
+ if (!isRecord(entry) || typeof entry.url !== "string")
1211
+ fail(PARALLEL_LABEL + " returned an invalid citation.");
1212
+ try {
1213
+ const url = new URL(entry.url);
1214
+ if (!["http:", "https:"].includes(url.protocol)) throw new Error();
1215
+ } catch {
1216
+ fail(PARALLEL_LABEL + " returned an invalid citation URL.");
1217
+ }
1218
+ const citation: DecisionCitation = { url: entry.url };
1219
+ if (typeof entry.title === "string") citation.title = entry.title;
1220
+ if (entry.excerpts !== undefined) {
1221
+ if (!Array.isArray(entry.excerpts) || !entry.excerpts.every((text) => typeof text === "string"))
1222
+ fail(PARALLEL_LABEL + " returned invalid citation excerpts.");
1223
+ citation.excerpts = entry.excerpts as string[];
1224
+ }
1225
+ return citation;
1226
+ });
1227
+ }
1228
+
1229
+ async function classifyParallel(
1230
+ route: ResolvedModel,
1231
+ input: PreparedInput,
1232
+ apiKey: string,
1233
+ signal?: AbortSignal,
1234
+ ): Promise<ClassifierResult> {
1235
+ if (input.images.length > 0 || input.media.length > 0 || input.mode !== undefined)
1236
+ throw new ClassifierError("capability", "Parallel Decisions accepts text/JSON state only.");
1237
+ const payload = {
1238
+ state: input.state,
1239
+ questions: systemOneQuestions(input.questions, false),
1240
+ mode: "fast",
1241
+ };
1242
+ const { body, requestId } = await postJson(route, "decisions", payload, apiKey, signal);
1243
+ if (!isRecord(body)) fail(PARALLEL_LABEL + " returned an unexpected response.");
1244
+ const result = finish(
1245
+ route,
1246
+ deriveConfidenceAnswers(PARALLEL_LABEL, body.answers, input.questions),
1247
+ body.usage,
1248
+ requestId,
1249
+ );
1250
+ const citations = parallelCitations(body.citations);
1251
+ if (citations.length > 0) result.citations = citations;
1252
+ if (typeof body.decision_id === "string" && /^[A-Za-z0-9_.:-]{1,128}$/.test(body.decision_id))
1253
+ result.requestId = result.requestId ?? body.decision_id;
1254
+ return result;
1255
+ }
1256
+
1257
+ /* Self-hosted System One runtimes ------------------------------------------ */
1258
+
1259
+ const LOCAL_LABEL = "Local System One";
1260
+
1261
+ async function classifyLocalSystemOne(
1262
+ route: ResolvedModel,
1263
+ input: PreparedInput,
1264
+ apiKey: string,
1265
+ signal?: AbortSignal,
1266
+ ): Promise<ClassifierResult> {
1267
+ const payload: Record<string, unknown> = {
1268
+ ...(route.provider !== "llamacpp" ? { model: route.model } : {}),
1269
+ state: input.state,
1270
+ questions: systemOneQuestions(input.questions, false),
1271
+ };
1272
+ if (input.images.length > 0)
1273
+ payload.images = input.images.map((image) => {
1274
+ if ("url" in image) throw new ClassifierError("capability", "Local System One routes require local image data.");
1275
+ return imageUrl(image);
1276
+ });
1277
+ const audio = input.media.filter((entry) => entry.type === "audio");
1278
+ const video = input.media.filter((entry) => entry.type === "video");
1279
+ if (route.provider === "llamacpp") {
1280
+ const files = [...input.images, ...input.media];
1281
+ if (files.length > 0)
1282
+ payload.files = files.map((entry) => ("type" in entry ? mediaDataUrl(entry) : imageUrl(entry)));
1283
+ } else {
1284
+ if (audio.length > 0) payload.audio = audio.map(mediaDataUrl);
1285
+ if (video.length > 0) payload.videos = video.map(mediaDataUrl);
1286
+ }
1287
+ const { body, requestId } = await postJson(route, "v1/systemone", payload, apiKey, signal);
1288
+ if (!isRecord(body)) fail(LOCAL_LABEL + " returned an unexpected response.");
1289
+ return finish(
1290
+ route,
1291
+ deriveConfidenceAnswers(LOCAL_LABEL, body.answers, input.questions),
1292
+ body.usage,
1293
+ requestId,
619
1294
  );
620
1295
  }
621
1296
 
@@ -624,53 +1299,124 @@ async function classifyOpenAi(
624
1299
  function systemOneQuestions(
625
1300
  questions: Record<string, Question>,
626
1301
  allowBox: boolean,
1302
+ content: (value: QuestionContent) => unknown = textContent,
627
1303
  ): Record<string, unknown> {
628
- // Question IDs may be "__proto__", so the wire map is collected without a prototype.
629
1304
  const result = Object.create(null) as Record<string, unknown>;
630
1305
  for (const [id, question] of Object.entries(questions)) {
631
- if (question.type === "bool") {
632
- const wire: Record<string, unknown> = {
633
- type: "noul",
634
- instructions: question.instructions,
635
- };
636
- if (question.criteria !== undefined) wire.criteria = question.criteria;
637
- result[id] = wire;
638
- } else if (question.type === "choice") {
639
- result[id] = {
640
- type: "choice",
641
- instructions: question.instructions,
642
- criteria: question.criteria,
643
- };
644
- } else if (question.type === "score") {
645
- result[id] = {
646
- type: "score",
647
- instructions: question.instructions,
648
- criteria: question.criteria,
649
- };
650
- } else if (allowBox) {
651
- result[id] = { type: "box", instructions: question.instructions };
652
- } else {
653
- throw unsupportedBox();
1306
+ if (question.type === "box") {
1307
+ if (!allowBox) throw unsupportedBox();
1308
+ result[id] = { type: "box", instructions: content(question.instructions) };
1309
+ continue;
1310
+ }
1311
+ if (question.type === "locate") {
1312
+ result[id] = { type: "locate", instructions: content(question.instructions) };
1313
+ continue;
654
1314
  }
1315
+ if (question.type !== "bool" && question.type !== "choice" && question.type !== "score")
1316
+ throw new ClassifierError(
1317
+ "capability",
1318
+ "The selected route does not support " + question.type + " questions.",
1319
+ );
1320
+ const wire: Record<string, unknown> = {
1321
+ type: question.type === "bool" ? "noul" : question.type,
1322
+ instructions: content(question.instructions),
1323
+ };
1324
+ if (question.type === "score") wire.criteria = question.criteria.map(content);
1325
+ else if (question.criteria !== undefined) wire.criteria = Object.fromEntries(
1326
+ Object.entries(question.criteria).map(([key, value]) => [key, content(value)]),
1327
+ );
1328
+ result[id] = wire;
655
1329
  }
656
1330
  return result;
657
1331
  }
658
1332
 
659
1333
  function perplexityState(input: PreparedInput): unknown {
660
- // Perplexity interprets native image parts inside state. Caller JSON is text;
661
- // only locally validated images may become provider-native image parts.
662
- const text =
663
- typeof input.state === "string" ? input.state : JSON.stringify(input.state);
664
- if (input.images.length === 0) return text;
1334
+ // Only explicit references become native image parts; other JSON stays text.
1335
+ const text = typeof input.state === "string" ? input.state : JSON.stringify(input.state);
1336
+ const shared = input.images.filter((image) => image.id === undefined);
1337
+ const references = imageReferences(input.state);
1338
+ if (shared.length + references.length > 8)
1339
+ throw new ClassifierError("input", "Perplexity accepts at most eight image occurrences per question.");
1340
+ if (shared.length === 0 && references.length === 0) return text;
665
1341
  return [
666
- text,
667
- ...input.images.map((image) => ({
668
- type: "image_url",
669
- image_url: { url: dataUrl(image) },
670
- })),
1342
+ ...(references.length ? imageContentParts(input.state, (id) => ({
1343
+ type: "image_url", image_url: { url: imageUrl(namedImage(input.images, id)) },
1344
+ })) : [text]),
1345
+ ...shared.map((image) => ({ type: "image_url", image_url: { url: imageUrl(image) } })),
671
1346
  ];
672
1347
  }
673
1348
 
1349
+ function webEntry(entry: unknown, field: string): WebFetchedResult {
1350
+ if (
1351
+ !isRecord(entry) ||
1352
+ typeof entry.title !== "string" ||
1353
+ typeof entry.url !== "string" ||
1354
+ typeof entry.snippet !== "string"
1355
+ )
1356
+ fail(PERPLEXITY_LABEL + " returned an invalid " + field + " entry.");
1357
+ try {
1358
+ const url = new URL(entry.url);
1359
+ if (!["http:", "https:"].includes(url.protocol)) throw new Error();
1360
+ } catch {
1361
+ fail(PERPLEXITY_LABEL + " returned an invalid URL in " + field + ".");
1362
+ }
1363
+ return { title: entry.title, url: entry.url, snippet: entry.snippet };
1364
+ }
1365
+
1366
+ function providerDate(value: unknown, field: string): string {
1367
+ if (typeof value !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(value))
1368
+ fail(PERPLEXITY_LABEL + " returned an invalid date in " + field + ".");
1369
+ return value;
1370
+ }
1371
+
1372
+ function parseSearchResults(value: unknown): WebSearchResult[] {
1373
+ if (value === undefined) return [];
1374
+ if (!Array.isArray(value) || value.length > 100)
1375
+ fail(PERPLEXITY_LABEL + " returned invalid search_results.");
1376
+ return value.map((entry) => {
1377
+ const base = webEntry(entry, "search_results");
1378
+ const result: WebSearchResult = { ...base };
1379
+ if (isRecord(entry) && entry.date !== undefined)
1380
+ result.date = providerDate(entry.date, "search_results");
1381
+ if (isRecord(entry) && entry.last_updated !== undefined)
1382
+ result.lastUpdated = providerDate(entry.last_updated, "search_results");
1383
+ return result;
1384
+ });
1385
+ }
1386
+
1387
+ function parseFetchedResults(value: unknown): WebFetchedResult[] {
1388
+ if (value === undefined) return [];
1389
+ if (!Array.isArray(value) || value.length > 1)
1390
+ fail(PERPLEXITY_LABEL + " returned invalid fetched_results.");
1391
+ return value.map((entry) => webEntry(entry, "fetched_results"));
1392
+ }
1393
+
1394
+ function withWebGroundingCost(
1395
+ cost: ClassifierResult["cost"],
1396
+ questionCount: number,
1397
+ fetched: number,
1398
+ ): ClassifierResult["cost"] {
1399
+ if (cost.status !== "estimated") return cost;
1400
+ const searchFeeMaximum = questionCount * 0.001;
1401
+ const fetchFee = fetched * 0.0005;
1402
+ return {
1403
+ ...cost,
1404
+ nonToken: {
1405
+ currency: "USD",
1406
+ webGrounding: {
1407
+ status: "estimated_maximum",
1408
+ searchesRequested: questionCount,
1409
+ searchFeeMaximum,
1410
+ successfulFetches: fetched,
1411
+ fetchFee,
1412
+ totalMaximum: searchFeeMaximum + fetchFee,
1413
+ note:
1414
+ "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.",
1415
+ },
1416
+ },
1417
+ };
1418
+ }
1419
+
674
1420
  async function classifyPerplexity(
675
1421
  route: ResolvedModel,
676
1422
  input: PreparedInput,
@@ -678,25 +1424,220 @@ async function classifyPerplexity(
678
1424
  signal?: AbortSignal,
679
1425
  ): Promise<ClassifierResult> {
680
1426
  const state = perplexityState(input);
1427
+ const payload: Record<string, unknown> = {
1428
+ model: route.model,
1429
+ state,
1430
+ questions: systemOneQuestions(input.questions, false),
1431
+ };
1432
+ if (input.mode !== undefined) payload.mode = input.mode;
681
1433
  const { body, requestId } = await postJson(
682
1434
  route,
683
1435
  "decisions",
684
- {
685
- model: route.model,
686
- state,
687
- questions: systemOneQuestions(input.questions, false),
688
- },
1436
+ payload,
689
1437
  apiKey,
690
1438
  signal,
691
1439
  );
692
1440
  if (!isRecord(body))
693
1441
  fail(PERPLEXITY_LABEL + " returned an unexpected response.");
694
- return finish(
1442
+ const searches = parseSearchResults(body.search_results);
1443
+ const fetched = parseFetchedResults(body.fetched_results);
1444
+ const snippets = searches.map((result) => result.snippet);
1445
+ const sources: { state?: string; snippets: string[] } = { snippets };
1446
+ if (typeof input.state === "string") sources.state = input.state;
1447
+ const result = finish(
695
1448
  route,
696
- parseTypedAnswers(PERPLEXITY_LABEL, body.answers, input.questions),
1449
+ parseTypedAnswers(
1450
+ PERPLEXITY_LABEL,
1451
+ body.answers,
1452
+ input.questions,
1453
+ sources,
1454
+ ),
697
1455
  body.usage,
698
1456
  requestId,
699
1457
  );
1458
+ if (input.mode === "web_grounding") {
1459
+ result.webGrounding = { searchResults: searches };
1460
+ if (fetched.length > 0) result.webGrounding.fetchedResults = fetched;
1461
+ result.cost = withWebGroundingCost(result.cost, Object.keys(input.questions).length, fetched.length);
1462
+ }
1463
+ return result;
1464
+ }
1465
+
1466
+ /* Sarvam Prism Decisions API ---------------------------------------------- */
1467
+
1468
+ const SARVAM_REQUEST_ID_PATTERN = /^[A-Za-z0-9_.:-]{1,128}$/;
1469
+
1470
+ function sarvamSafeDetail(
1471
+ value: unknown,
1472
+ apiKey: string,
1473
+ pattern: RegExp,
1474
+ ): string | undefined {
1475
+ if (typeof value !== "string" || !pattern.test(value)) return undefined;
1476
+ return apiKey.length > 0 && value.includes(apiKey) ? undefined : value;
1477
+ }
1478
+
1479
+ const sarvamHeaderRequestId: JsonRequestIdDetail = (value, apiKey) =>
1480
+ sarvamSafeDetail(value, apiKey, SARVAM_REQUEST_ID_PATTERN);
1481
+
1482
+ const sarvamErrorDetail: JsonErrorDetail = (status, body, apiKey) => {
1483
+ if (!isRecord(body) || !isRecord(body.error)) return undefined;
1484
+ const error = body.error;
1485
+ const code =
1486
+ typeof error.code === "string" &&
1487
+ [
1488
+ "invalid_request_error",
1489
+ "insufficient_quota_error",
1490
+ "invalid_api_key_error",
1491
+ "not_found_error",
1492
+ "unprocessable_entity_error",
1493
+ "rate_limit_exceeded_error",
1494
+ "internal_server_error",
1495
+ "model_call_failed",
1496
+ "model_overloaded",
1497
+ ].includes(error.code)
1498
+ ? error.code
1499
+ : undefined;
1500
+ const param = sarvamSafeDetail(
1501
+ error.param,
1502
+ apiKey,
1503
+ /^[A-Za-z0-9_.:-]{1,256}$/,
1504
+ );
1505
+ const requestId = sarvamSafeDetail(
1506
+ error.request_id,
1507
+ apiKey,
1508
+ SARVAM_REQUEST_ID_PATTERN,
1509
+ );
1510
+ if (!code && !param && !requestId) return undefined;
1511
+ const summaries: Record<number, string> = {
1512
+ 402: "Sarvam reported insufficient quota.",
1513
+ 403: "Sarvam rejected the API key.",
1514
+ 404: "Sarvam does not recognize the selected model.",
1515
+ 422: "Sarvam rejected the request shape.",
1516
+ 429: "Sarvam rate-limited the request.",
1517
+ 500: "Sarvam reported an internal error.",
1518
+ 502: "Sarvam could not reach the decision model.",
1519
+ 503: "Sarvam reported that the model is overloaded.",
1520
+ };
1521
+ let detail = summaries[status] ?? "Sarvam rejected the request.";
1522
+ if (code) detail += " Code: " + code + ".";
1523
+ if (param) detail += " Field: " + param + ".";
1524
+ if (requestId) detail += " Request ID: " + requestId + ".";
1525
+ return detail;
1526
+ };
1527
+
1528
+ function sarvamRequestId(
1529
+ body: Record<string, unknown>,
1530
+ apiKey: string,
1531
+ ): string | undefined {
1532
+ return sarvamSafeDetail(
1533
+ body.request_id,
1534
+ apiKey,
1535
+ SARVAM_REQUEST_ID_PATTERN,
1536
+ );
1537
+ }
1538
+
1539
+ function sarvamQuestion(id: string, question: Question, minimumChoices: number): Record<string, unknown> {
1540
+ if (question.type !== "bool" && question.type !== "choice" && question.type !== "score")
1541
+ throw new ClassifierError(
1542
+ "capability",
1543
+ "The selected route does not support " + question.type + " questions.",
1544
+ );
1545
+ const wire: Record<string, unknown> = {
1546
+ type: question.type === "bool" ? "noul" : question.type,
1547
+ instructions: textContent(question.instructions),
1548
+ };
1549
+ if (question.type === "bool") {
1550
+ if (question.criteria !== undefined)
1551
+ wire.criteria = Object.fromEntries(
1552
+ Object.entries(question.criteria).map(([key, value]) => [key, textContent(value)]),
1553
+ );
1554
+ return wire;
1555
+ }
1556
+ if (question.type === "choice") {
1557
+ const entries = Object.entries(question.criteria);
1558
+ if (entries.length < minimumChoices || entries.length > 255)
1559
+ throw new ClassifierError(
1560
+ "input",
1561
+ "Sarvam requires " + minimumChoices + " to 255 options for choice question " + id + ".",
1562
+ );
1563
+ wire.criteria = Object.fromEntries(
1564
+ entries.map(([key, value]) => [key, textContent(value)]),
1565
+ );
1566
+ return wire;
1567
+ }
1568
+ if (question.criteria.length < 2 || question.criteria.length > 10)
1569
+ throw new ClassifierError(
1570
+ "input",
1571
+ "Sarvam Prism requires 2 to 10 levels for score question " + id + ".",
1572
+ );
1573
+ wire.criteria = question.criteria.map(textContent);
1574
+ return wire;
1575
+ }
1576
+
1577
+ function sarvamAnswers(
1578
+ value: unknown,
1579
+ questions: Record<string, Question>,
1580
+ ): Record<string, Answer> {
1581
+ if (!isRecord(value)) fail(SARVAM_LABEL + " returned an unexpected response.");
1582
+ const answers = Object.create(null) as Record<string, unknown>;
1583
+ for (const [id, question] of Object.entries(questions)) {
1584
+ if (!Object.hasOwn(value, id))
1585
+ fail(SARVAM_LABEL + " did not return an answer for " + id + ".");
1586
+ const raw = value[id];
1587
+ if (question.type === "score" && isRecord(raw) && raw.probabilities === undefined)
1588
+ fail(SARVAM_LABEL + " did not return probabilities for score question " + id + ".");
1589
+ const expected = question.type === "bool" ? "noul" : question.type;
1590
+ answers[id] =
1591
+ isRecord(raw) && raw.type === undefined ? { ...raw, type: expected } : raw;
1592
+ }
1593
+ return parseTypedAnswers(SARVAM_LABEL, answers, questions);
1594
+ }
1595
+
1596
+ async function classifySarvam(
1597
+ route: ResolvedModel,
1598
+ input: PreparedInput,
1599
+ apiKey: string,
1600
+ signal?: AbortSignal,
1601
+ ): Promise<ClassifierResult> {
1602
+ const isClef = route.model === "clef";
1603
+ if (!isClef && (input.images.length > 0 || input.media.length > 0))
1604
+ throw new ClassifierError(
1605
+ "capability",
1606
+ "Sarvam Prism accepts text/JSON only; Sarvam Clef accepts base64 images.",
1607
+ );
1608
+ if (input.media.length > 0 || input.mode !== undefined)
1609
+ throw new ClassifierError("capability", "Sarvam does not accept media or web grounding.");
1610
+ const questions = Object.create(null) as Record<string, unknown>;
1611
+ for (const [id, question] of Object.entries(input.questions))
1612
+ questions[id] = sarvamQuestion(id, question, isClef ? 1 : 2);
1613
+ const payload: Record<string, unknown> = { model: route.model, state: input.state, questions };
1614
+ if (isClef && input.images.length > 0)
1615
+ payload.images = input.images.map((image) => {
1616
+ if ("url" in image) throw new ClassifierError("capability", "Sarvam Clef requires local image data.");
1617
+ return imageUrl(image);
1618
+ });
1619
+ const { body, requestId } = await postJson(
1620
+ route,
1621
+ "systemone",
1622
+ payload,
1623
+ apiKey,
1624
+ signal,
1625
+ undefined,
1626
+ sarvamErrorDetail,
1627
+ sarvamHeaderRequestId,
1628
+ );
1629
+ if (!isRecord(body))
1630
+ fail(SARVAM_LABEL + " returned an unexpected response.");
1631
+ if (body.model !== undefined && body.model !== route.model)
1632
+ fail(SARVAM_LABEL + " returned a model that does not match the selected route.");
1633
+ if (!isRecord(body.answers))
1634
+ fail(SARVAM_LABEL + " returned an unexpected response.");
1635
+ return finish(
1636
+ route,
1637
+ sarvamAnswers(body.answers, input.questions),
1638
+ body.usage,
1639
+ requestId ?? sarvamRequestId(body, apiKey),
1640
+ );
700
1641
  }
701
1642
 
702
1643
  /* Microsoft Foundry Decision-1 (text/JSON, API-key authentication) -------- */
@@ -707,15 +1648,45 @@ async function classifyMicrosoft(
707
1648
  apiKey: string,
708
1649
  signal?: AbortSignal,
709
1650
  ): Promise<ClassifierResult> {
710
- const label = "Microsoft Decision-1";
1651
+ const label = "Microsoft Foundry Decision-1.1";
1652
+ const assets = Object.create(null) as Record<string, unknown>;
1653
+ const sharedRefs: string[] = [];
1654
+ const namedRefs = new Map<string, string>();
1655
+ const used = new Set([...imageReferences(input.state), ...questionImageReferences(input.questions)]);
1656
+ for (const image of input.images) {
1657
+ if ("url" in image) throw new ClassifierError("capability", "Microsoft image assets require local images.");
1658
+ // Batching can remove a question or a criterion; unused assets are rejected upstream.
1659
+ if (image.id !== undefined && !used.has(image.id)) continue;
1660
+ const ref = randomUUID();
1661
+ if (image.id === undefined) sharedRefs.push("image:" + ref);
1662
+ else namedRefs.set(image.id, ref);
1663
+ assets[ref] = {
1664
+ type: "image",
1665
+ format: image.mimeType === "image/png" ? "png" : "jpg",
1666
+ data_base64: image.data,
1667
+ };
1668
+ }
1669
+ const reference = (id: string): string => {
1670
+ const ref = namedRefs.get(id);
1671
+ if (!ref) throw new ClassifierError("input", "Unknown named image reference.");
1672
+ return "image:" + ref;
1673
+ };
1674
+ let state = mapImageReferences(input.state, reference) as PreparedInput["state"];
1675
+ if (sharedRefs.length > 0) {
1676
+ if (typeof state === "string") state = state + "\n" + sharedRefs.join(" ");
1677
+ else if (isRecord(state)) state = { ...state, images: sharedRefs };
1678
+ else state = { state, images: sharedRefs };
1679
+ }
1680
+ const payload: Record<string, unknown> = {
1681
+ model: route.model, // Foundry deployment name, not necessarily the underlying model ID.
1682
+ state,
1683
+ questions: systemOneQuestions(input.questions, false, (value) => mapImageReferences(value, reference)),
1684
+ };
1685
+ if (Object.keys(assets).length > 0) payload.assets = assets;
711
1686
  const { body, requestId } = await postJson(
712
1687
  route,
713
1688
  "providers/microsoft/v1/systemone",
714
- {
715
- model: route.model, // Foundry deployment name, not necessarily the catalog model ID.
716
- state: input.state,
717
- questions: systemOneQuestions(input.questions, false),
718
- },
1689
+ payload,
719
1690
  apiKey,
720
1691
  signal,
721
1692
  );
@@ -775,28 +1746,43 @@ async function classifySystemOne(
775
1746
  signal?: AbortSignal,
776
1747
  ): Promise<ClassifierResult> {
777
1748
  const assets = Object.create(null) as Record<string, unknown>;
778
- const refs: string[] = [];
1749
+ const sharedRefs: string[] = [];
1750
+ const namedRefs = new Map<string, string>();
1751
+ const used = new Set([...imageReferences(input.state), ...questionImageReferences(input.questions)]);
779
1752
  for (const image of input.images) {
1753
+ // Batching can remove a question or a criterion. Jev rejects unused assets.
1754
+ if (image.id !== undefined && !used.has(image.id)) continue;
1755
+ if ("url" in image) throw new ClassifierError("capability", "Jev assets require local images.");
780
1756
  const ref = randomUUID();
781
- refs.push(ref);
1757
+ if (image.id === undefined) sharedRefs.push(ref);
1758
+ else namedRefs.set(image.id, ref);
782
1759
  assets[ref] = {
783
- type: "image",
784
- format: image.mimeType === "image/png" ? "png" : "jpg",
1760
+ type: "image", format: image.mimeType === "image/png" ? "png" : "jpg",
785
1761
  data_base64: image.data,
786
1762
  };
787
1763
  }
1764
+ const reference = (id: string): string => {
1765
+ const ref = namedRefs.get(id);
1766
+ if (!ref) throw new ClassifierError("input", "Unknown named image reference.");
1767
+ return ref;
1768
+ };
1769
+ const state = mapImageReferences(input.state, reference) as PreparedInput["state"];
788
1770
  const payload: Record<string, unknown> = {
789
1771
  model: route.model,
790
- state: refs.length === 0 ? input.state : withImageRefs(input.state, refs),
791
- questions: systemOneQuestions(input.questions, true),
1772
+ state: sharedRefs.length ? withImageRefs(state, sharedRefs) : state,
1773
+ questions: systemOneQuestions(input.questions, true, (value) => mapImageReferences(value, reference)),
792
1774
  };
793
- if (refs.length > 0) payload.assets = assets;
1775
+ if (Object.keys(assets).length > 0) payload.assets = assets;
794
1776
  const experimentalHeader =
795
- refs.length > 0 ||
1777
+ Object.keys(assets).length > 0 ||
796
1778
  Object.values(input.questions).some((question) => question.type === "box");
797
- const extraHeaders = experimentalHeader
798
- ? { "TypeSafe-Danger-Zone-Images": "true" }
799
- : undefined;
1779
+ const extraHeaders: Record<string, string> | undefined =
1780
+ experimentalHeader || route.longContext
1781
+ ? {
1782
+ ...(experimentalHeader ? { "TypeSafe-Danger-Zone-Images": "true" } : {}),
1783
+ ...(route.longContext ? { "TypeSafe-Danger-Zone-Long-Context": "true" } : {}),
1784
+ }
1785
+ : undefined;
800
1786
  const { body, requestId } = await postJson(
801
1787
  route,
802
1788
  "systemone",
@@ -818,10 +1804,14 @@ async function classifySystemOne(
818
1804
  /* Cloudflare Workers AI (Clef and third-party System One envelopes) ------- */
819
1805
 
820
1806
  function clefBodyModel(model: string): string | undefined {
821
- return /^@cf\/cloudflare\/(clef(?:-flash)?)$/.exec(model)?.[1];
1807
+ return /^@cf\/cloudflare\/(clef(?:-flash|-omni)?)$/.exec(model)?.[1];
1808
+ }
1809
+
1810
+ function cloudflareMedia(media: PreparedMedia[]): { content_type: string; base64: string }[] {
1811
+ return media.map((entry) => ({ content_type: entry.mimeType, base64: entry.data }));
822
1812
  }
823
1813
 
824
- function unwrapCloudflare(
1814
+ export function unwrapCloudflare(
825
1815
  label: string,
826
1816
  body: unknown,
827
1817
  ): Record<string, unknown> {
@@ -861,17 +1851,21 @@ async function classifyCloudflare(
861
1851
  questions: systemOneQuestions(input.questions, false),
862
1852
  };
863
1853
  if (input.images.length > 0) {
864
- payload.images = input.images.map((image) => ({
865
- content_type: image.mimeType,
866
- base64: image.data,
867
- }));
1854
+ payload.images = input.images.map((image) => {
1855
+ if ("url" in image) throw new ClassifierError("capability", "Clef requires local images.");
1856
+ return { content_type: image.mimeType, base64: image.data };
1857
+ });
868
1858
  }
1859
+ const audio = input.media.filter((media) => media.type === "audio");
1860
+ const videos = input.media.filter((media) => media.type === "video");
1861
+ if (audio.length) payload.audio = cloudflareMedia(audio);
1862
+ if (videos.length) payload.videos = cloudflareMedia(videos);
869
1863
  path = "run/" + route.model;
870
1864
  } else {
871
- if (input.images.length > 0)
1865
+ if (input.images.length > 0 || input.media.length > 0)
872
1866
  throw new ClassifierError(
873
1867
  "capability",
874
- "The selected route does not support images for this model.",
1868
+ "The selected route does not support media for this model.",
875
1869
  );
876
1870
  payload = {
877
1871
  model: route.model,
@@ -903,3 +1897,263 @@ async function classifyCloudflare(
903
1897
  requestId,
904
1898
  );
905
1899
  }
1900
+
1901
+ /* Liquid d1.2 System One extension --------------------------------------- */
1902
+
1903
+ function liquidUnsupported(feature: string): never {
1904
+ throw new ClassifierError(
1905
+ "capability",
1906
+ "The selected route does not support " + feature + ".",
1907
+ );
1908
+ }
1909
+
1910
+ function liquidQuestion(id: string, question: Question): Record<string, unknown> {
1911
+ if (question.type === "extract")
1912
+ return liquidUnsupported("extract questions on Liquid routes");
1913
+ const wire: Record<string, unknown> = {
1914
+ type: question.type === "bool" ? "noul" : question.type,
1915
+ instructions: textContent(question.instructions),
1916
+ };
1917
+ switch (question.type) {
1918
+ case "bool":
1919
+ if (question.criteria)
1920
+ wire.criteria = Object.fromEntries(
1921
+ Object.entries(question.criteria).map(([key, value]) => [key, textContent(value)]),
1922
+ );
1923
+ return wire;
1924
+ case "choice":
1925
+ case "multi_choice":
1926
+ wire.type = "choice";
1927
+ wire.criteria = Object.fromEntries(
1928
+ Object.entries(question.criteria).map(([key, value]) => [key, textContent(value)]),
1929
+ );
1930
+ if (question.type === "multi_choice") wire.multiple = true;
1931
+ return wire;
1932
+ case "score":
1933
+ wire.criteria = question.criteria.map(textContent);
1934
+ return wire;
1935
+ case "number":
1936
+ if (question.unit !== undefined) wire.unit = question.unit;
1937
+ if (question.range !== undefined) wire.range = question.range;
1938
+ if (question.step !== undefined) wire.step = question.step;
1939
+ return wire;
1940
+ case "spans":
1941
+ case "boxes":
1942
+ if (question.max !== undefined) wire.max = question.max;
1943
+ return wire;
1944
+ case "estimate":
1945
+ wire.type = "number";
1946
+ wire.range = question.range;
1947
+ if (question.step !== undefined) wire.step = question.step;
1948
+ if (question.unit !== undefined) wire.unit = question.unit;
1949
+ return wire;
1950
+ case "text":
1951
+ case "date":
1952
+ case "box":
1953
+ return wire;
1954
+ case "locate":
1955
+ return liquidUnsupported("locate questions on Liquid routes");
1956
+ }
1957
+ }
1958
+
1959
+ function stateText(state: PreparedInput["state"]): string {
1960
+ return typeof state === "string" ? state : JSON.stringify(state, null, 2);
1961
+ }
1962
+
1963
+ function optionalCharSpan(
1964
+ label: string,
1965
+ value: unknown,
1966
+ field: string,
1967
+ text: string,
1968
+ ): [number, number] | null | undefined {
1969
+ if (value === undefined) return undefined;
1970
+ if (value === null) return null;
1971
+ return charSpan(label, value, field, text);
1972
+ }
1973
+
1974
+ function charSpan(label: string, value: unknown, field: string, text: string): [number, number] {
1975
+ if (!Array.isArray(value) || value.length !== 2 ||
1976
+ value.some((entry) => !Number.isSafeInteger(entry) || (entry as number) < 0))
1977
+ fail(label + " returned an invalid " + field + ".");
1978
+ const start = value[0] as number;
1979
+ const end = value[1] as number;
1980
+ if (end < start || codePointSlice(text, start, end).length === 0 && end !== start)
1981
+ fail(label + " returned an invalid " + field + ".");
1982
+ return [start, end];
1983
+ }
1984
+
1985
+ function optionalFound(label: string, answer: Record<string, unknown>, id: string): number | undefined {
1986
+ return answer.found === undefined ? undefined : probability(label, answer.found, "found for " + id);
1987
+ }
1988
+
1989
+ function optionalPath(label: string, answer: Record<string, unknown>, id: string): string | undefined {
1990
+ if (answer.path === undefined) return undefined;
1991
+ if (typeof answer.path !== "string" || (answer.path !== "" && !answer.path.startsWith("/")))
1992
+ fail(label + " returned an invalid JSON pointer for " + id + ".");
1993
+ return answer.path;
1994
+ }
1995
+
1996
+ function parseLiquidAnswer(
1997
+ label: string,
1998
+ id: string,
1999
+ question: Question,
2000
+ answer: unknown,
2001
+ text: string,
2002
+ ): Answer | undefined {
2003
+ if (!isRecord(answer)) fail(label + " returned an invalid answer for " + id + ".");
2004
+ if (answer.type === "refusal") return { type: "refusal" };
2005
+ if (question.type === "bool" || question.type === "choice" || question.type === "score")
2006
+ return validateDecision(label, id, parseTypedAnswer(label, id, question, answer));
2007
+ const found = optionalFound(label, answer, id);
2008
+ if (question.type === "text") {
2009
+ if (typeof answer.text !== "string") fail(label + " returned an invalid text answer for " + id + ".");
2010
+ const result: Extract<Answer, { type: "text" }> = { type: "text", text: answer.text };
2011
+ const span = optionalCharSpan(label, answer.span, "span for " + id, text);
2012
+ if (span !== undefined) result.span = span;
2013
+ if (found !== undefined) result.found = found;
2014
+ const path = optionalPath(label, answer, id);
2015
+ if (path !== undefined) result.path = path;
2016
+ return result;
2017
+ }
2018
+ if (question.type === "number") {
2019
+ if (answer.number !== null && (typeof answer.number !== "number" || !Number.isFinite(answer.number)))
2020
+ fail(label + " returned an invalid number answer for " + id + ".");
2021
+ const value = typeof answer.number === "number" ? answer.number : null;
2022
+ const result: Extract<Answer, { type: "number" }> = { type: "number", value };
2023
+ if (typeof answer.unit === "string" || answer.unit === null) result.unit = answer.unit;
2024
+ if (typeof answer.text === "string" || answer.text === null) result.text = answer.text;
2025
+ const span = optionalCharSpan(label, answer.span, "span for " + id, text);
2026
+ if (span !== undefined) result.span = span;
2027
+ if (found !== undefined) result.found = found;
2028
+ const path = optionalPath(label, answer, id);
2029
+ if (path !== undefined) result.path = path;
2030
+ return result;
2031
+ }
2032
+ if (question.type === "date") {
2033
+ if (answer.date !== null && (typeof answer.date !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(answer.date)))
2034
+ fail(label + " returned an invalid date answer for " + id + ".");
2035
+ const date = typeof answer.date === "string" ? answer.date : null;
2036
+ const result: Extract<Answer, { type: "date" }> = { type: "date", date };
2037
+ if (typeof answer.text === "string" || answer.text === null) result.text = answer.text;
2038
+ const span = optionalCharSpan(label, answer.span, "span for " + id, text);
2039
+ if (span !== undefined) result.span = span;
2040
+ if (found !== undefined) result.found = found;
2041
+ const path = optionalPath(label, answer, id);
2042
+ if (path !== undefined) result.path = path;
2043
+ return result;
2044
+ }
2045
+ if (question.type === "spans") {
2046
+ if (!Array.isArray(answer.spans) || !Array.isArray(answer.presence) ||
2047
+ !Number.isSafeInteger(answer.count) || (answer.count as number) < 0 ||
2048
+ typeof answer.at_least !== "boolean")
2049
+ fail(label + " returned an invalid spans answer for " + id + ".");
2050
+ const presence = answer.presence.map((entry) => probability(label, entry, "presence for " + id));
2051
+ return {
2052
+ type: "spans",
2053
+ spans: answer.spans.map((entry) => {
2054
+ if (!isRecord(entry) || typeof entry.text !== "string")
2055
+ fail(label + " returned an invalid span for " + id + ".");
2056
+ return {
2057
+ text: entry.text,
2058
+ span: charSpan(label, entry.span, "span for " + id, text),
2059
+ found: probability(label, entry.found, "span found for " + id),
2060
+ };
2061
+ }),
2062
+ count: answer.count as number,
2063
+ atLeast: answer.at_least,
2064
+ presence,
2065
+ };
2066
+ }
2067
+ if (question.type === "boxes") {
2068
+ if (!Array.isArray(answer.boxes) || !Array.isArray(answer.presence) ||
2069
+ !Number.isSafeInteger(answer.count) || (answer.count as number) < 0 ||
2070
+ typeof answer.at_least !== "boolean")
2071
+ fail(label + " returned an invalid boxes answer for " + id + ".");
2072
+ const presence = answer.presence.map((entry) => probability(label, entry, "presence for " + id));
2073
+ return {
2074
+ type: "boxes",
2075
+ boxes: answer.boxes.map((entry) => {
2076
+ const parsed = parseBox(label, id, isRecord(entry) ? entry.box : undefined, isRecord(entry) ? entry.found : undefined);
2077
+ if (parsed.type !== "box") fail(label + " returned an invalid box for " + id + ".");
2078
+ return {
2079
+ box: parsed.box,
2080
+ found: parsed.confidence,
2081
+ confidence: probability(label, isRecord(entry) ? entry.confidence : undefined, "box confidence for " + id),
2082
+ };
2083
+ }),
2084
+ count: answer.count as number,
2085
+ atLeast: answer.at_least,
2086
+ presence,
2087
+ };
2088
+ }
2089
+ if (question.type === "estimate") {
2090
+ const value = answer.number;
2091
+ if (typeof value !== "number" || !Number.isFinite(value) || !Array.isArray(answer.interval) ||
2092
+ answer.interval.length !== 2 ||
2093
+ answer.interval.some((entry) => typeof entry !== "number" || !Number.isFinite(entry)) ||
2094
+ (answer.interval[0] as number) > value || value > (answer.interval[1] as number))
2095
+ fail(label + " returned an invalid estimate for " + id + ".");
2096
+ const result: Extract<Answer, { type: "estimate" }> = {
2097
+ type: "estimate",
2098
+ value,
2099
+ interval: [answer.interval[0] as number, answer.interval[1] as number],
2100
+ };
2101
+ if (typeof answer.unit === "string") result.unit = answer.unit;
2102
+ return result;
2103
+ }
2104
+ if (question.type === "multi_choice") {
2105
+ if (!Array.isArray(answer.choices) || !isRecord(answer.probabilities))
2106
+ fail(label + " returned an invalid multi-choice answer for " + id + ".");
2107
+ const labels = Object.keys(question.criteria);
2108
+ const choices = independentLabelProbabilities(label, id, answer.probabilities, labels);
2109
+ for (const choice of answer.choices) {
2110
+ if (typeof choice !== "string" || !Object.hasOwn(question.criteria, choice))
2111
+ fail(label + " returned an unknown choice for " + id + ".");
2112
+ }
2113
+ return { type: "multi_choice", choices: answer.choices as string[], probabilities: choices };
2114
+ }
2115
+ if (question.type === "box") {
2116
+ if (answer.box === null || (found !== undefined && found < 0.5)) return { type: "no_match" };
2117
+ const parsed = parseBox(label, id, answer.box, answer.confidence);
2118
+ if (parsed.type !== "box") fail(label + " returned an invalid box for " + id + ".");
2119
+ return found === undefined ? parsed : { ...parsed, found };
2120
+ }
2121
+ return liquidUnsupported("question type " + question.type);
2122
+ }
2123
+
2124
+ async function classifyLiquid(
2125
+ route: ResolvedModel,
2126
+ input: PreparedInput,
2127
+ apiKey: string,
2128
+ signal?: AbortSignal,
2129
+ ): Promise<ClassifierResult> {
2130
+ if (Object.values(input.questions).some((question) => question.type === "locate"))
2131
+ return liquidUnsupported("locate questions on Liquid routes");
2132
+ const payload: Record<string, unknown> = {
2133
+ model: route.model,
2134
+ state: input.state,
2135
+ questions: Object.fromEntries(
2136
+ Object.entries(input.questions).map(([id, question]) => [id, liquidQuestion(id, question)]),
2137
+ ),
2138
+ };
2139
+ if (input.images.length) {
2140
+ payload.images = input.images.map((image) => {
2141
+ if ("url" in image) throw new ClassifierError("capability", "Liquid requires local images.");
2142
+ return { content_type: image.mimeType, base64: image.data };
2143
+ });
2144
+ }
2145
+ const audio = input.media.filter((media) => media.type === "audio");
2146
+ if (audio.length)
2147
+ payload.audio = audio.map((media) => ({ content_type: media.mimeType, base64: media.data }));
2148
+ const { body, requestId } = await postJson(route, "systemone", payload, apiKey, signal);
2149
+ if (!isRecord(body)) fail("Liquid Decisions returned an unexpected response.");
2150
+ const text = stateText(input.state);
2151
+ const answers = Object.create(null) as Record<string, Answer>;
2152
+ for (const [id, question] of Object.entries(input.questions)) {
2153
+ if (!isRecord(body.answers) || !Object.hasOwn(body.answers, id))
2154
+ fail("Liquid Decisions did not return an answer for " + id + ".");
2155
+ const parsed = parseLiquidAnswer("Liquid Decisions", id, question, body.answers[id], text);
2156
+ if (parsed !== undefined) answers[id] = parsed;
2157
+ }
2158
+ return finish(route, answers, body.usage, requestId);
2159
+ }