@abhishek944/pi-classifier 0.2.0 → 0.4.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 (57) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/COMPUTER_USE.md +117 -0
  3. package/README.md +268 -8
  4. package/dist/box-tool.d.ts +26 -0
  5. package/dist/box-tool.js +109 -0
  6. package/dist/box.d.ts +32 -0
  7. package/dist/box.js +148 -0
  8. package/dist/choices.d.ts +8 -0
  9. package/dist/choices.js +131 -0
  10. package/dist/classification-tree.d.ts +4 -0
  11. package/dist/classification-tree.js +143 -0
  12. package/dist/classify.d.ts +4 -2
  13. package/dist/classify.js +5 -2
  14. package/dist/computer-use-state.d.ts +9 -0
  15. package/dist/computer-use-state.js +160 -0
  16. package/dist/computer-use-tool.d.ts +52 -0
  17. package/dist/computer-use-tool.js +78 -0
  18. package/dist/computer-use-types.d.ts +132 -0
  19. package/dist/computer-use-types.js +1 -0
  20. package/dist/computer-use.d.ts +22 -0
  21. package/dist/computer-use.js +223 -0
  22. package/dist/config.js +44 -0
  23. package/dist/cost.d.ts +8 -0
  24. package/dist/cost.js +202 -0
  25. package/dist/extension.d.ts +164 -9
  26. package/dist/extension.js +164 -14
  27. package/dist/image-content.d.ts +12 -0
  28. package/dist/image-content.js +90 -0
  29. package/dist/index.d.ts +9 -1
  30. package/dist/index.js +3 -0
  31. package/dist/inputs.d.ts +11 -2
  32. package/dist/inputs.js +155 -131
  33. package/dist/providers.js +113 -100
  34. package/dist/tree.d.ts +4 -0
  35. package/dist/tree.js +136 -0
  36. package/dist/types.d.ts +113 -11
  37. package/dist/validation.js +63 -39
  38. package/package.json +2 -1
  39. package/src/box-tool.ts +145 -0
  40. package/src/box.ts +253 -0
  41. package/src/choices.ts +174 -0
  42. package/src/classification-tree.ts +181 -0
  43. package/src/classify.ts +16 -4
  44. package/src/computer-use-state.ts +145 -0
  45. package/src/computer-use-tool.ts +76 -0
  46. package/src/computer-use-types.ts +127 -0
  47. package/src/computer-use.ts +216 -0
  48. package/src/config.ts +55 -0
  49. package/src/cost.ts +250 -0
  50. package/src/extension.ts +191 -15
  51. package/src/image-content.ts +77 -0
  52. package/src/index.ts +18 -0
  53. package/src/inputs.ts +163 -185
  54. package/src/providers.ts +113 -119
  55. package/src/tree.ts +157 -0
  56. package/src/types.ts +117 -10
  57. package/src/validation.ts +62 -95
package/src/providers.ts CHANGED
@@ -1,11 +1,13 @@
1
1
  import { randomUUID } from "node:crypto";
2
+ import { imageContentParts, imageReferences, imageUrl, mapImageReferences, namedImage, questionImageReferences } from "./image-content.js";
2
3
  import { postJson } from "./http.js";
4
+ import { estimateCost, tokenCount } from "./cost.js";
3
5
  import {
4
6
  ClassifierError,
5
7
  isRecord,
6
8
  type Answer,
7
9
  type ClassifierResult,
8
- type PreparedImage,
10
+ type QuestionContent,
9
11
  type PreparedInput,
10
12
  type Question,
11
13
  type ResolvedModel,
@@ -86,12 +88,6 @@ function unitInterval(label: string, value: unknown, field: string): number {
86
88
  return Math.min(1, Math.max(0, value));
87
89
  }
88
90
 
89
- function tokenCount(value: unknown): number | undefined {
90
- return typeof value === "number" && Number.isSafeInteger(value) && value >= 0
91
- ? value
92
- : undefined;
93
- }
94
-
95
91
  function normalizedUsage(
96
92
  value: unknown,
97
93
  ): ClassifierResult["usage"] | undefined {
@@ -102,31 +98,48 @@ function normalizedUsage(
102
98
  const total =
103
99
  tokenCount(value.total_tokens) ?? tokenCount((input ?? 0) + (output ?? 0));
104
100
  if (total === undefined) return undefined;
105
- return {
101
+ const usage: NonNullable<ClassifierResult["usage"]> = {
106
102
  inputTokens: input ?? 0,
107
103
  outputTokens: output ?? 0,
108
104
  totalTokens: total,
109
105
  };
106
+ if (isRecord(value.input_tokens_details)) {
107
+ const cached = tokenCount(value.input_tokens_details.cached_tokens);
108
+ const writes = tokenCount(value.input_tokens_details.cache_write_tokens);
109
+ if (cached !== undefined) usage.cachedInputTokens = cached;
110
+ if (writes !== undefined) usage.cacheWriteTokens = writes;
111
+ }
112
+ return usage;
110
113
  }
111
114
 
112
115
  function finish(
113
116
  route: ResolvedModel,
114
117
  answers: Record<string, Answer>,
115
- usage: ClassifierResult["usage"] | undefined,
118
+ rawUsage: unknown,
116
119
  requestId: string | undefined,
117
120
  ): ClassifierResult {
118
121
  const result: ClassifierResult = {
119
122
  provider: route.route,
120
123
  model: route.model,
121
124
  answers,
125
+ cost: estimateCost(route, rawUsage),
122
126
  };
127
+ const usage = normalizedUsage(rawUsage);
123
128
  if (usage !== undefined) result.usage = usage;
124
129
  if (requestId !== undefined) result.requestId = requestId;
125
130
  return result;
126
131
  }
127
132
 
128
- function dataUrl(image: PreparedImage): string {
129
- return "data:" + image.mimeType + ";base64," + image.data;
133
+ function textContent(value: QuestionContent): string {
134
+ if (typeof value === "string") return value;
135
+ if (value.some((part) => typeof part !== "string"))
136
+ throw new ClassifierError("capability", "This content placement does not support images on the selected route.");
137
+ return value.join("");
138
+ }
139
+
140
+ function openAiContent(value: unknown, input: PreparedInput): unknown[] {
141
+ return imageContentParts(value, (id) => ({ type: "input_image", image_url: imageUrl(namedImage(input.images, id)) }))
142
+ .map((part) => typeof part === "string" ? { type: "input_text", text: part } : part);
130
143
  }
131
144
 
132
145
  /* Answer parsing for map-shaped answers (Perplexity, System One, Clef) --- */
@@ -376,66 +389,42 @@ function parseTypedAnswers(
376
389
 
377
390
  /* OpenAI Decisions -------------------------------------------------------- */
378
391
 
379
- function predicateInstructions(
380
- question: Extract<Question, { type: "bool" }>,
381
- ): string {
392
+ function predicateInstructions(question: Extract<Question, { type: "bool" }>): QuestionContent {
382
393
  const meanings: string[] = [];
383
- if (question.criteria?.true)
384
- meanings.push("True means: " + question.criteria.true);
385
- if (question.criteria?.false)
386
- meanings.push("False means: " + question.criteria.false);
387
- return meanings.length > 0
388
- ? question.instructions + "\n" + meanings.join("\n")
389
- : question.instructions;
390
- }
391
-
392
- function openAiQuestion(
393
- id: string,
394
- question: Question,
395
- ): Record<string, unknown> {
396
- if (question.type === "bool")
397
- return {
398
- type: "predicate",
399
- name: id,
400
- instructions: predicateInstructions(question),
401
- };
402
- if (question.type === "choice") {
403
- return {
404
- type: "choice",
405
- name: id,
406
- instructions: question.instructions,
407
- choices: Object.entries(question.criteria).map(
408
- ([value, description]) => ({ value, description }),
409
- ),
410
- };
411
- }
412
- if (question.type === "score") {
413
- return {
414
- type: "score",
415
- name: id,
416
- instructions: question.instructions,
417
- levels: question.criteria.map((label) => ({ label })),
418
- };
419
- }
394
+ if (question.criteria?.true) meanings.push("True means: " + textContent(question.criteria.true));
395
+ if (question.criteria?.false) meanings.push("False means: " + textContent(question.criteria.false));
396
+ if (meanings.length === 0) return question.instructions;
397
+ const suffix = "\n" + meanings.join("\n");
398
+ return typeof question.instructions === "string" ? question.instructions + suffix : [...question.instructions, suffix];
399
+ }
400
+
401
+ function openAiQuestion(id: string, question: Question, input: PreparedInput): Record<string, unknown> {
402
+ const instructions = question.type === "bool" ? predicateInstructions(question) : question.instructions;
403
+ const wireInstructions = typeof instructions === "string" ? instructions : openAiContent(instructions, input);
404
+ if (question.type === "bool") return { type: "predicate", name: id, instructions: wireInstructions };
405
+ if (question.type === "choice") return {
406
+ type: "choice", name: id, instructions: wireInstructions,
407
+ choices: Object.entries(question.criteria).map(([value, description]) => ({ value, description: textContent(description) })),
408
+ };
409
+ if (question.type === "score") return {
410
+ type: "score", name: id, instructions: wireInstructions,
411
+ levels: question.criteria.map((label) => ({ label: textContent(label) })),
412
+ };
420
413
  throw unsupportedBox();
421
414
  }
422
415
 
423
416
  function openAiInput(input: PreparedInput): unknown {
424
- const text =
425
- typeof input.state === "string" ? input.state : JSON.stringify(input.state);
426
- if (input.images.length === 0) return text;
427
- return [
428
- {
429
- role: "user",
430
- content: [
431
- { type: "input_text", text },
432
- ...input.images.map((image) => ({
433
- type: "input_image",
434
- image_url: dataUrl(image),
435
- })),
436
- ],
437
- },
438
- ];
417
+ const text = typeof input.state === "string" ? input.state : JSON.stringify(input.state);
418
+ const shared = input.images.filter((image) => image.id === undefined);
419
+ 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
+ }];
439
428
  }
440
429
 
441
430
  function openAiChoiceProbabilities(
@@ -593,7 +582,7 @@ async function classifyOpenAi(
593
582
  signal?: AbortSignal,
594
583
  ): Promise<ClassifierResult> {
595
584
  const questions = Object.entries(input.questions).map(([id, question]) =>
596
- openAiQuestion(id, question),
585
+ openAiQuestion(id, question, input),
597
586
  );
598
587
  const { body, requestId } = await postJson(
599
588
  route,
@@ -610,7 +599,7 @@ async function classifyOpenAi(
610
599
  return finish(
611
600
  route,
612
601
  parseOpenAiAnswers(OPENAI_LABEL, body.answers, input.questions),
613
- normalizedUsage(body.usage),
602
+ body.usage,
614
603
  requestId,
615
604
  );
616
605
  }
@@ -620,50 +609,41 @@ async function classifyOpenAi(
620
609
  function systemOneQuestions(
621
610
  questions: Record<string, Question>,
622
611
  allowBox: boolean,
612
+ content: (value: QuestionContent) => unknown = textContent,
623
613
  ): Record<string, unknown> {
624
- // Question IDs may be "__proto__", so the wire map is collected without a prototype.
625
614
  const result = Object.create(null) as Record<string, unknown>;
626
615
  for (const [id, question] of Object.entries(questions)) {
627
- if (question.type === "bool") {
628
- const wire: Record<string, unknown> = {
629
- type: "noul",
630
- instructions: question.instructions,
631
- };
632
- if (question.criteria !== undefined) wire.criteria = question.criteria;
633
- result[id] = wire;
634
- } else if (question.type === "choice") {
635
- result[id] = {
636
- type: "choice",
637
- instructions: question.instructions,
638
- criteria: question.criteria,
639
- };
640
- } else if (question.type === "score") {
641
- result[id] = {
642
- type: "score",
643
- instructions: question.instructions,
644
- criteria: question.criteria,
645
- };
646
- } else if (allowBox) {
647
- result[id] = { type: "box", instructions: question.instructions };
648
- } else {
649
- throw unsupportedBox();
616
+ if (question.type === "box") {
617
+ if (!allowBox) throw unsupportedBox();
618
+ result[id] = { type: "box", instructions: content(question.instructions) };
619
+ continue;
650
620
  }
621
+ const wire: Record<string, unknown> = {
622
+ type: question.type === "bool" ? "noul" : question.type,
623
+ instructions: content(question.instructions),
624
+ };
625
+ if (question.type === "score") wire.criteria = question.criteria.map(content);
626
+ else if (question.criteria !== undefined) wire.criteria = Object.fromEntries(
627
+ Object.entries(question.criteria).map(([key, value]) => [key, content(value)]),
628
+ );
629
+ result[id] = wire;
651
630
  }
652
631
  return result;
653
632
  }
654
633
 
655
634
  function perplexityState(input: PreparedInput): unknown {
656
- // Perplexity interprets native image parts inside state. Caller JSON is text;
657
- // only locally validated images may become provider-native image parts.
658
- const text =
659
- typeof input.state === "string" ? input.state : JSON.stringify(input.state);
660
- if (input.images.length === 0) return text;
635
+ // Only explicit references become native image parts; other JSON stays text.
636
+ const text = typeof input.state === "string" ? input.state : JSON.stringify(input.state);
637
+ const shared = input.images.filter((image) => image.id === undefined);
638
+ const references = imageReferences(input.state);
639
+ if (shared.length + references.length > 8)
640
+ throw new ClassifierError("input", "Perplexity accepts at most eight image occurrences per question.");
641
+ if (shared.length === 0 && references.length === 0) return text;
661
642
  return [
662
- text,
663
- ...input.images.map((image) => ({
664
- type: "image_url",
665
- image_url: { url: dataUrl(image) },
666
- })),
643
+ ...(references.length ? imageContentParts(input.state, (id) => ({
644
+ type: "image_url", image_url: { url: imageUrl(namedImage(input.images, id)) },
645
+ })) : [text]),
646
+ ...shared.map((image) => ({ type: "image_url", image_url: { url: imageUrl(image) } })),
667
647
  ];
668
648
  }
669
649
 
@@ -690,7 +670,7 @@ async function classifyPerplexity(
690
670
  return finish(
691
671
  route,
692
672
  parseTypedAnswers(PERPLEXITY_LABEL, body.answers, input.questions),
693
- normalizedUsage(body.usage),
673
+ body.usage,
694
674
  requestId,
695
675
  );
696
676
  }
@@ -751,7 +731,7 @@ async function classifyMicrosoft(
751
731
  return finish(
752
732
  route,
753
733
  parseTypedAnswers(label, answers, input.questions),
754
- normalizedUsage(body.usage),
734
+ body.usage,
755
735
  requestId,
756
736
  );
757
737
  }
@@ -771,24 +751,35 @@ async function classifySystemOne(
771
751
  signal?: AbortSignal,
772
752
  ): Promise<ClassifierResult> {
773
753
  const assets = Object.create(null) as Record<string, unknown>;
774
- const refs: string[] = [];
754
+ const sharedRefs: string[] = [];
755
+ const namedRefs = new Map<string, string>();
756
+ const used = new Set([...imageReferences(input.state), ...questionImageReferences(input.questions)]);
775
757
  for (const image of input.images) {
758
+ // Batching can remove a question or a criterion. Jev rejects unused assets.
759
+ if (image.id !== undefined && !used.has(image.id)) continue;
760
+ if ("url" in image) throw new ClassifierError("capability", "Jev assets require local images.");
776
761
  const ref = randomUUID();
777
- refs.push(ref);
762
+ if (image.id === undefined) sharedRefs.push(ref);
763
+ else namedRefs.set(image.id, ref);
778
764
  assets[ref] = {
779
- type: "image",
780
- format: image.mimeType === "image/png" ? "png" : "jpg",
765
+ type: "image", format: image.mimeType === "image/png" ? "png" : "jpg",
781
766
  data_base64: image.data,
782
767
  };
783
768
  }
769
+ const reference = (id: string): string => {
770
+ const ref = namedRefs.get(id);
771
+ if (!ref) throw new ClassifierError("input", "Unknown named image reference.");
772
+ return ref;
773
+ };
774
+ const state = mapImageReferences(input.state, reference) as PreparedInput["state"];
784
775
  const payload: Record<string, unknown> = {
785
776
  model: route.model,
786
- state: refs.length === 0 ? input.state : withImageRefs(input.state, refs),
787
- questions: systemOneQuestions(input.questions, true),
777
+ state: sharedRefs.length ? withImageRefs(state, sharedRefs) : state,
778
+ questions: systemOneQuestions(input.questions, true, (value) => mapImageReferences(value, reference)),
788
779
  };
789
- if (refs.length > 0) payload.assets = assets;
780
+ if (Object.keys(assets).length > 0) payload.assets = assets;
790
781
  const experimentalHeader =
791
- refs.length > 0 ||
782
+ Object.keys(assets).length > 0 ||
792
783
  Object.values(input.questions).some((question) => question.type === "box");
793
784
  const extraHeaders = experimentalHeader
794
785
  ? { "TypeSafe-Danger-Zone-Images": "true" }
@@ -806,7 +797,7 @@ async function classifySystemOne(
806
797
  return finish(
807
798
  route,
808
799
  parseTypedAnswers(TYPESAFE_LABEL, body.answers, input.questions),
809
- normalizedUsage(body.usage),
800
+ body.usage,
810
801
  requestId,
811
802
  );
812
803
  }
@@ -857,10 +848,10 @@ async function classifyCloudflare(
857
848
  questions: systemOneQuestions(input.questions, false),
858
849
  };
859
850
  if (input.images.length > 0) {
860
- payload.images = input.images.map((image) => ({
861
- content_type: image.mimeType,
862
- base64: image.data,
863
- }));
851
+ payload.images = input.images.map((image) => {
852
+ if ("url" in image) throw new ClassifierError("capability", "Clef requires local images.");
853
+ return { content_type: image.mimeType, base64: image.data };
854
+ });
864
855
  }
865
856
  path = "run/" + route.model;
866
857
  } else {
@@ -887,8 +878,11 @@ async function classifyCloudflare(
887
878
  );
888
879
  const result = unwrapCloudflare(CLOUDFLARE_LABEL, body);
889
880
  const usage =
890
- normalizedUsage(result.usage) ??
891
- normalizedUsage(isRecord(body) ? body.usage : undefined);
881
+ normalizedUsage(result.usage) !== undefined
882
+ ? result.usage
883
+ : isRecord(body)
884
+ ? body.usage
885
+ : undefined;
892
886
  return finish(
893
887
  route,
894
888
  parseTypedAnswers(CLOUDFLARE_LABEL, result.answers, input.questions),
package/src/tree.ts ADDED
@@ -0,0 +1,157 @@
1
+ import { classify, type ClassifyOptions } from "./classify.js";
2
+ import { choicePolicy } from "./choices.js";
3
+ import { resolveModel } from "./config.js";
4
+ import { sumCost, sumUsage } from "./cost.js";
5
+ import { loadTreeInput } from "./classification-tree.js";
6
+ import {
7
+ ClassifierError,
8
+ userError,
9
+ type ClassifierResult,
10
+ type ClassifierRoute,
11
+ type ClassifierTreeResult,
12
+ type ClassificationTreeNode,
13
+ type TreeStep,
14
+ } from "./types.js";
15
+
16
+ /** Greedy sibling decisions over an already validated classification tree; forced edges make no model call. */
17
+ export async function classifyTree(
18
+ params: unknown,
19
+ options: ClassifyOptions,
20
+ ): Promise<ClassifierTreeResult> {
21
+ choicePolicy(options.settings);
22
+ const input = await loadTreeInput(params, options.cwd, options.signal);
23
+ const initial = resolveModel(options.settings);
24
+ const result: ClassifierTreeResult = {
25
+ provider: initial.route,
26
+ model: initial.model,
27
+ status: "complete",
28
+ levels: Object.create(null) as Record<string, string>,
29
+ steps: [],
30
+ providerCalls: 0,
31
+ usage: { inputTokens: 0, outputTokens: 0, totalTokens: 0 },
32
+ cost: {
33
+ status: "estimated",
34
+ currency: "USD",
35
+ source: "aggregated",
36
+ input: 0,
37
+ output: 0,
38
+ total: 0,
39
+ },
40
+ };
41
+ const path: string[] = [];
42
+ let siblings = input.tree.roots;
43
+ let pinned: ClassifierRoute | undefined;
44
+ while (siblings.length > 0) {
45
+ if (options.signal?.aborted)
46
+ throw new ClassifierError("aborted", "Classification was cancelled.");
47
+ let selected: ClassificationTreeNode;
48
+ let step: TreeStep;
49
+ const level = path.length + 1;
50
+ if (siblings.length === 1) {
51
+ selected = siblings[0]!;
52
+ step = { level, id: selected.id, source: "automatic" };
53
+ } else {
54
+ // Non-numeric wire keys preserve array order through JS object enumeration and batching.
55
+ const candidates = new Map(
56
+ siblings.map((node, index) => ["category_" + index, node]),
57
+ );
58
+ const instructions =
59
+ (input.instructions ?? "Choose the most appropriate category for the supplied state.") +
60
+ "\nChoose one child of this selected parent path (JSON IDs): " + JSON.stringify(path) +
61
+ ". Use the option descriptions to decide which branch contains the best category. Do not choose a descendant directly.";
62
+ let branch: ClassifierResult;
63
+ try {
64
+ branch = await classify(
65
+ {
66
+ state: input.state,
67
+ questions: {
68
+ tree: {
69
+ type: "choice",
70
+ instructions,
71
+ criteria: Object.fromEntries(
72
+ [...candidates].map(([key, node]) => [
73
+ key, node.description?.trim() ? node.description : node.id,
74
+ ]),
75
+ ),
76
+ },
77
+ },
78
+ ...(input.images !== undefined ? { images: input.images } : {}),
79
+ },
80
+ {
81
+ ...options,
82
+ // Only the first actual decision can select an explicitly configured fallback route.
83
+ settings: pinned
84
+ ? { ...options.settings, default: pinned, fallback: [] }
85
+ : options.settings,
86
+ },
87
+ );
88
+ } catch (error) {
89
+ if (
90
+ options.signal?.aborted ||
91
+ (error instanceof ClassifierError && error.code === "aborted")
92
+ )
93
+ throw new ClassifierError("aborted", "Classification was cancelled.");
94
+ if (result.providerCalls > 0)
95
+ throw new ClassifierError(
96
+ "partial_classification",
97
+ "Tree traversal stopped at Level" + level + " after " + result.providerCalls +
98
+ " completed provider request(s), which may be billed. No completed levels were replayed. " + userError(error),
99
+ );
100
+ throw error;
101
+ }
102
+ const usage = result.providerCalls === 0
103
+ ? branch.usage
104
+ : sumUsage(result.usage, branch.usage);
105
+ if (usage === undefined) delete result.usage;
106
+ else result.usage = usage;
107
+ result.cost = result.providerCalls === 0
108
+ ? branch.cost
109
+ : sumCost(result.cost, branch.cost);
110
+ result.providerCalls += branch.providerCalls ?? 1;
111
+ result.provider = branch.provider;
112
+ result.model = branch.model;
113
+ pinned = { provider: branch.provider, model: branch.model };
114
+ if (branch.attemptedRoutes !== undefined)
115
+ result.attemptedRoutes = branch.attemptedRoutes;
116
+ const answer = branch.answers.tree;
117
+ if (!answer) throw new ClassifierError("response", "Tree branch returned no answer.");
118
+ if (
119
+ answer.type === "no_match" || answer.type === "ambiguous" ||
120
+ answer.type === "refusal"
121
+ ) {
122
+ result.status = answer.type;
123
+ break;
124
+ }
125
+ if (answer.type !== "choice")
126
+ throw new ClassifierError("response", "Tree branch did not return a choice answer.");
127
+ const probabilities = Object.entries(answer.probabilities);
128
+ const maximum = Math.max(...probabilities.map(([, probability]) => probability));
129
+ const winners = probabilities.filter(([, probability]) => probability === maximum);
130
+ if (winners.length !== 1) {
131
+ result.status = "ambiguous";
132
+ break;
133
+ }
134
+ const node = candidates.get(winners[0]![0]);
135
+ if (!node) throw new ClassifierError("response", "Tree branch selected an unknown category.");
136
+ selected = node;
137
+ step = {
138
+ level,
139
+ id: selected.id,
140
+ source: "model",
141
+ confidence: answer.confidence,
142
+ probabilityScope: answer.probabilityScope ?? "siblings",
143
+ };
144
+ if (answer.noneOfAboveProbability !== undefined)
145
+ step.noneOfAboveProbability = answer.noneOfAboveProbability;
146
+ }
147
+ path.push(selected.id);
148
+ result.levels["Level" + level] = selected.id;
149
+ result.steps.push(step);
150
+ siblings = selected.children ?? [];
151
+ }
152
+ if (options.signal?.aborted)
153
+ throw new ClassifierError("aborted", "Classification was cancelled.");
154
+ if (Buffer.byteLength(JSON.stringify(result, null, 2)) > 40 * 1024)
155
+ throw new ClassifierError("response", "Tree result exceeds the 40 KiB tool output limit.");
156
+ return result;
157
+ }