@abhishek944/pi-classifier 0.4.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 (58) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/README.md +269 -31
  3. package/dist/auth.d.ts +4 -2
  4. package/dist/auth.js +18 -2
  5. package/dist/box-tool.d.ts +2 -24
  6. package/dist/box-tool.js +5 -35
  7. package/dist/choices.js +35 -1
  8. package/dist/classify.d.ts +3 -0
  9. package/dist/classify.js +3 -3
  10. package/dist/config.d.ts +140 -3
  11. package/dist/config.js +401 -20
  12. package/dist/cost.js +42 -4
  13. package/dist/durable.d.ts +34 -0
  14. package/dist/durable.js +237 -0
  15. package/dist/extension.d.ts +2 -275
  16. package/dist/extension.js +49 -211
  17. package/dist/extract.d.ts +11 -0
  18. package/dist/extract.js +191 -0
  19. package/dist/http.d.ts +6 -1
  20. package/dist/http.js +64 -28
  21. package/dist/index.d.ts +3 -1
  22. package/dist/index.js +1 -0
  23. package/dist/inputs.d.ts +16 -1
  24. package/dist/inputs.js +421 -14
  25. package/dist/mcp-cli.d.ts +2 -0
  26. package/dist/mcp-cli.js +39 -0
  27. package/dist/mcp-server.d.ts +28 -0
  28. package/dist/mcp-server.js +121 -0
  29. package/dist/mcp-tool-definitions.d.ts +19 -0
  30. package/dist/mcp-tool-definitions.js +64 -0
  31. package/dist/providers.d.ts +1 -0
  32. package/dist/providers.js +1144 -53
  33. package/dist/tool-contracts.d.ts +785 -0
  34. package/dist/tool-contracts.js +530 -0
  35. package/dist/tree.js +1 -1
  36. package/dist/types.d.ts +284 -8
  37. package/dist/validation.js +122 -10
  38. package/package.json +32 -5
  39. package/src/auth.ts +26 -2
  40. package/src/box-tool.ts +12 -47
  41. package/src/choices.ts +42 -1
  42. package/src/classify.ts +6 -4
  43. package/src/config.ts +450 -23
  44. package/src/cost.ts +42 -4
  45. package/src/durable.ts +298 -0
  46. package/src/extension.ts +75 -288
  47. package/src/extract.ts +228 -0
  48. package/src/http.ts +63 -32
  49. package/src/index.ts +15 -0
  50. package/src/inputs.ts +454 -13
  51. package/src/mcp-cli.ts +44 -0
  52. package/src/mcp-server.ts +179 -0
  53. package/src/mcp-tool-definitions.ts +104 -0
  54. package/src/providers.ts +1323 -56
  55. package/src/tool-contracts.ts +785 -0
  56. package/src/tree.ts +1 -1
  57. package/src/types.ts +231 -5
  58. package/src/validation.ts +114 -9
package/src/providers.ts CHANGED
@@ -1,16 +1,24 @@
1
1
  import { randomUUID } from "node:crypto";
2
- import { imageContentParts, imageReferences, imageUrl, mapImageReferences, namedImage, questionImageReferences } from "./image-content.js";
3
- 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";
4
4
  import { estimateCost, tokenCount } from "./cost.js";
5
+ import { openRouterDecisionCapabilities } from "./config.js";
5
6
  import {
6
7
  ClassifierError,
7
8
  isRecord,
8
9
  type Answer,
9
10
  type ClassifierResult,
11
+ type DecisionCitation,
10
12
  type QuestionContent,
13
+ type PreparedImage,
11
14
  type PreparedInput,
15
+ type PreparedMedia,
16
+ type ProviderCost,
12
17
  type Question,
13
18
  type ResolvedModel,
19
+ type TextSpan,
20
+ type WebFetchedResult,
21
+ type WebSearchResult,
14
22
  } from "./types.js";
15
23
 
16
24
  /**
@@ -22,6 +30,7 @@ import {
22
30
 
23
31
  const OPENAI_LABEL = "OpenAI Decisions";
24
32
  const PERPLEXITY_LABEL = "Perplexity Decisions";
33
+ const SARVAM_LABEL = "Sarvam Prism";
25
34
  const TYPESAFE_LABEL = "TypeSafe System One";
26
35
  const CLOUDFLARE_LABEL = "Cloudflare Workers AI";
27
36
  const EPSILON = 1e-6;
@@ -36,10 +45,24 @@ export async function classifyWithProvider(
36
45
  switch (route.api) {
37
46
  case "openai-decisions":
38
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);
39
58
  case "perplexity-decisions":
40
59
  return classifyPerplexity(route, input, apiKey, signal);
60
+ case "sarvam-system-one":
61
+ return classifySarvam(route, input, apiKey, signal);
41
62
  case "system-one":
42
63
  return classifySystemOne(route, input, apiKey, signal);
64
+ case "liquid-system-one":
65
+ return classifyLiquid(route, input, apiKey, signal);
43
66
  case "microsoft-system-one":
44
67
  return classifyMicrosoft(route, input, apiKey, signal);
45
68
  case "cloudflare-system-one":
@@ -112,11 +135,28 @@ function normalizedUsage(
112
135
  return usage;
113
136
  }
114
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
+
115
154
  function finish(
116
155
  route: ResolvedModel,
117
156
  answers: Record<string, Answer>,
118
157
  rawUsage: unknown,
119
158
  requestId: string | undefined,
159
+ providerCost?: ProviderCost,
120
160
  ): ClassifierResult {
121
161
  const result: ClassifierResult = {
122
162
  provider: route.route,
@@ -127,6 +167,7 @@ function finish(
127
167
  const usage = normalizedUsage(rawUsage);
128
168
  if (usage !== undefined) result.usage = usage;
129
169
  if (requestId !== undefined) result.requestId = requestId;
170
+ if (providerCost !== undefined) result.providerCost = providerCost;
130
171
  return result;
131
172
  }
132
173
 
@@ -137,11 +178,36 @@ function textContent(value: QuestionContent): string {
137
178
  return value.join("");
138
179
  }
139
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
+
140
189
  function openAiContent(value: unknown, input: PreparedInput): unknown[] {
141
- return imageContentParts(value, (id) => ({ type: "input_image", image_url: imageUrl(namedImage(input.images, id)) }))
190
+ return imageContentParts(value, (id) => openAiImagePart(namedImage(input.images, id), input.imageDetail))
142
191
  .map((part) => typeof part === "string" ? { type: "input_text", text: part } : part);
143
192
  }
144
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;
209
+ }
210
+
145
211
  /* Answer parsing for map-shaped answers (Perplexity, System One, Clef) --- */
146
212
 
147
213
  function labelProbabilities(
@@ -175,6 +241,37 @@ function labelProbabilities(
175
241
  }
176
242
 
177
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
+
178
275
  function checkDistribution(
179
276
  label: string,
180
277
  id: string,
@@ -245,6 +342,54 @@ function scoreValue(
245
342
  return Math.min(maximum, Math.max(0, value));
246
343
  }
247
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
+
248
393
  function parseBox(
249
394
  label: string,
250
395
  id: string,
@@ -283,6 +428,7 @@ function parseTypedAnswer(
283
428
  id: string,
284
429
  question: Question,
285
430
  answer: unknown,
431
+ sources: { state?: string; snippets?: string[] } = {},
286
432
  ): Answer {
287
433
  if (!isRecord(answer))
288
434
  fail(label + " returned an invalid answer for " + id + ".");
@@ -332,6 +478,11 @@ function parseTypedAnswer(
332
478
  ),
333
479
  };
334
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
+ }
335
486
  if (answer.type !== "box")
336
487
  fail(label + " did not return a box answer for " + id + ".");
337
488
  return parseBox(label, id, answer.box, answer.confidence);
@@ -371,6 +522,7 @@ function parseTypedAnswers(
371
522
  label: string,
372
523
  value: unknown,
373
524
  questions: Record<string, Question>,
525
+ sources: { state?: string; snippets?: string[] } = {},
374
526
  ): Record<string, Answer> {
375
527
  if (!isRecord(value)) fail(label + " returned an unexpected response.");
376
528
  // Question IDs may be "__proto__", so answers are collected without a prototype.
@@ -381,7 +533,7 @@ function parseTypedAnswers(
381
533
  answers[id] = validateDecision(
382
534
  label,
383
535
  id,
384
- parseTypedAnswer(label, id, question, value[id]),
536
+ parseTypedAnswer(label, id, question, value[id], sources),
385
537
  );
386
538
  }
387
539
  return answers;
@@ -404,27 +556,91 @@ function openAiQuestion(id: string, question: Question, input: PreparedInput): R
404
556
  if (question.type === "bool") return { type: "predicate", name: id, instructions: wireInstructions };
405
557
  if (question.type === "choice") return {
406
558
  type: "choice", name: id, instructions: wireInstructions,
407
- choices: Object.entries(question.criteria).map(([value, description]) => ({ value, description: textContent(description) })),
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
+ })),
408
565
  };
409
566
  if (question.type === "score") return {
410
567
  type: "score", name: id, instructions: wireInstructions,
411
- levels: question.criteria.map((label) => ({ label: textContent(label) })),
568
+ levels: question.criteria.map((label, index) => ({
569
+ label: textContent(label),
570
+ ...(question.descriptions?.[index] !== undefined ? { description: question.descriptions[index] } : {}),
571
+ })),
412
572
  };
413
573
  throw unsupportedBox();
414
574
  }
415
575
 
416
- function openAiInput(input: PreparedInput): unknown {
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 } : {}),
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;
592
+ }
593
+ return false;
594
+ }
595
+
596
+ function openAiStateParts(input: PreparedInput): unknown[] {
417
597
  const text = typeof input.state === "string" ? input.state : JSON.stringify(input.state);
418
- const shared = input.images.filter((image) => image.id === undefined);
419
598
  const references = imageReferences(input.state);
420
- if (shared.length === 0 && references.length === 0) return text;
421
- return [{
422
- role: "user",
423
- content: [
424
- ...(references.length ? openAiContent(input.state, input) : [{ type: "input_text", text }]),
425
- ...shared.map((image) => ({ type: "input_image", image_url: imageUrl(image) })),
426
- ],
427
- }];
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 };
428
644
  }
429
645
 
430
646
  function openAiChoiceProbabilities(
@@ -432,26 +648,21 @@ function openAiChoiceProbabilities(
432
648
  id: string,
433
649
  value: unknown,
434
650
  labels: string[],
651
+ booleanValues: boolean,
435
652
  ): Record<string, number> {
436
653
  if (!Array.isArray(value))
437
654
  fail(label + " returned invalid probabilities for " + id + ".");
438
655
  const mapped = Object.create(null) as Record<string, unknown>;
439
656
  for (const entry of value) {
440
- if (
441
- !isRecord(entry) ||
442
- typeof entry.value !== "string" ||
443
- !labels.includes(entry.value)
444
- ) {
445
- fail(
446
- label +
447
- " returned an unknown option in the probabilities for " +
448
- id +
449
- ".",
450
- );
451
- }
452
- 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))
453
664
  fail(label + " returned duplicate probabilities for " + id + ".");
454
- mapped[entry.value] = entry.probability;
665
+ mapped[key] = entry.probability;
455
666
  }
456
667
  return labelProbabilities(label, id, mapped, labels);
457
668
  }
@@ -509,18 +720,21 @@ function parseOpenAiAnswer(
509
720
  };
510
721
  }
511
722
  if (question.type === "choice") {
512
- if (answer.type !== "choice" || typeof answer.choice !== "string")
513
- fail(label + " did not return a choice answer for " + id + ".");
514
- 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))
515
728
  fail(label + " returned an unknown choice for " + id + ".");
516
729
  return {
517
730
  type: "choice",
518
- choice: answer.choice,
731
+ choice,
519
732
  probabilities: openAiChoiceProbabilities(
520
733
  label,
521
734
  id,
522
735
  answer.probabilities,
523
736
  Object.keys(question.criteria),
737
+ question.booleanValues === true,
524
738
  ),
525
739
  confidence: probability(label, answer.confidence, "confidence for " + id),
526
740
  };
@@ -584,23 +798,499 @@ async function classifyOpenAi(
584
798
  const questions = Object.entries(input.questions).map(([id, question]) =>
585
799
  openAiQuestion(id, question, input),
586
800
  );
587
- const { body, requestId } = await postJson(
801
+ const preparedInput = openAiInput(input);
802
+ const { body, requestId, costHeader } = await postJson(
588
803
  route,
589
804
  "decisions",
590
805
  {
591
806
  model: route.model,
592
- input: openAiInput(input),
807
+ input: preparedInput.input,
593
808
  questions,
809
+ ...preparedInput.payload,
594
810
  },
595
811
  apiKey,
596
812
  signal,
597
813
  );
598
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);
599
818
  return finish(
600
819
  route,
601
820
  parseOpenAiAnswers(OPENAI_LABEL, body.answers, input.questions),
602
821
  body.usage,
603
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,
604
1294
  );
605
1295
  }
606
1296
 
@@ -618,6 +1308,15 @@ function systemOneQuestions(
618
1308
  result[id] = { type: "box", instructions: content(question.instructions) };
619
1309
  continue;
620
1310
  }
1311
+ if (question.type === "locate") {
1312
+ result[id] = { type: "locate", instructions: content(question.instructions) };
1313
+ continue;
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
+ );
621
1320
  const wire: Record<string, unknown> = {
622
1321
  type: question.type === "bool" ? "noul" : question.type,
623
1322
  instructions: content(question.instructions),
@@ -647,6 +1346,77 @@ function perplexityState(input: PreparedInput): unknown {
647
1346
  ];
648
1347
  }
649
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
+
650
1420
  async function classifyPerplexity(
651
1421
  route: ResolvedModel,
652
1422
  input: PreparedInput,
@@ -654,25 +1424,220 @@ async function classifyPerplexity(
654
1424
  signal?: AbortSignal,
655
1425
  ): Promise<ClassifierResult> {
656
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;
657
1433
  const { body, requestId } = await postJson(
658
1434
  route,
659
1435
  "decisions",
660
- {
661
- model: route.model,
662
- state,
663
- questions: systemOneQuestions(input.questions, false),
664
- },
1436
+ payload,
665
1437
  apiKey,
666
1438
  signal,
667
1439
  );
668
1440
  if (!isRecord(body))
669
1441
  fail(PERPLEXITY_LABEL + " returned an unexpected response.");
670
- 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(
671
1448
  route,
672
- parseTypedAnswers(PERPLEXITY_LABEL, body.answers, input.questions),
1449
+ parseTypedAnswers(
1450
+ PERPLEXITY_LABEL,
1451
+ body.answers,
1452
+ input.questions,
1453
+ sources,
1454
+ ),
673
1455
  body.usage,
674
1456
  requestId,
675
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
+ );
676
1641
  }
677
1642
 
678
1643
  /* Microsoft Foundry Decision-1 (text/JSON, API-key authentication) -------- */
@@ -683,15 +1648,45 @@ async function classifyMicrosoft(
683
1648
  apiKey: string,
684
1649
  signal?: AbortSignal,
685
1650
  ): Promise<ClassifierResult> {
686
- 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;
687
1686
  const { body, requestId } = await postJson(
688
1687
  route,
689
1688
  "providers/microsoft/v1/systemone",
690
- {
691
- model: route.model, // Foundry deployment name, not necessarily the catalog model ID.
692
- state: input.state,
693
- questions: systemOneQuestions(input.questions, false),
694
- },
1689
+ payload,
695
1690
  apiKey,
696
1691
  signal,
697
1692
  );
@@ -781,9 +1776,13 @@ async function classifySystemOne(
781
1776
  const experimentalHeader =
782
1777
  Object.keys(assets).length > 0 ||
783
1778
  Object.values(input.questions).some((question) => question.type === "box");
784
- const extraHeaders = experimentalHeader
785
- ? { "TypeSafe-Danger-Zone-Images": "true" }
786
- : 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;
787
1786
  const { body, requestId } = await postJson(
788
1787
  route,
789
1788
  "systemone",
@@ -805,10 +1804,14 @@ async function classifySystemOne(
805
1804
  /* Cloudflare Workers AI (Clef and third-party System One envelopes) ------- */
806
1805
 
807
1806
  function clefBodyModel(model: string): string | undefined {
808
- 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 }));
809
1812
  }
810
1813
 
811
- function unwrapCloudflare(
1814
+ export function unwrapCloudflare(
812
1815
  label: string,
813
1816
  body: unknown,
814
1817
  ): Record<string, unknown> {
@@ -853,12 +1856,16 @@ async function classifyCloudflare(
853
1856
  return { content_type: image.mimeType, base64: image.data };
854
1857
  });
855
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);
856
1863
  path = "run/" + route.model;
857
1864
  } else {
858
- if (input.images.length > 0)
1865
+ if (input.images.length > 0 || input.media.length > 0)
859
1866
  throw new ClassifierError(
860
1867
  "capability",
861
- "The selected route does not support images for this model.",
1868
+ "The selected route does not support media for this model.",
862
1869
  );
863
1870
  payload = {
864
1871
  model: route.model,
@@ -890,3 +1897,263 @@ async function classifyCloudflare(
890
1897
  requestId,
891
1898
  );
892
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
+ }