@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/dist/providers.js CHANGED
@@ -1,5 +1,7 @@
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 { ClassifierError, isRecord, } from "./types.js";
4
6
  /**
5
7
  * Provider protocol adapters. Every request goes through the shared `postJson` boundary, which
@@ -53,11 +55,6 @@ function unitInterval(label, value, field) {
53
55
  }
54
56
  return Math.min(1, Math.max(0, value));
55
57
  }
56
- function tokenCount(value) {
57
- return typeof value === "number" && Number.isSafeInteger(value) && value >= 0
58
- ? value
59
- : undefined;
60
- }
61
58
  function normalizedUsage(value) {
62
59
  if (!isRecord(value))
63
60
  return undefined;
@@ -68,26 +65,45 @@ function normalizedUsage(value) {
68
65
  const total = tokenCount(value.total_tokens) ?? tokenCount((input ?? 0) + (output ?? 0));
69
66
  if (total === undefined)
70
67
  return undefined;
71
- return {
68
+ const usage = {
72
69
  inputTokens: input ?? 0,
73
70
  outputTokens: output ?? 0,
74
71
  totalTokens: total,
75
72
  };
73
+ if (isRecord(value.input_tokens_details)) {
74
+ const cached = tokenCount(value.input_tokens_details.cached_tokens);
75
+ const writes = tokenCount(value.input_tokens_details.cache_write_tokens);
76
+ if (cached !== undefined)
77
+ usage.cachedInputTokens = cached;
78
+ if (writes !== undefined)
79
+ usage.cacheWriteTokens = writes;
80
+ }
81
+ return usage;
76
82
  }
77
- function finish(route, answers, usage, requestId) {
83
+ function finish(route, answers, rawUsage, requestId) {
78
84
  const result = {
79
85
  provider: route.route,
80
86
  model: route.model,
81
87
  answers,
88
+ cost: estimateCost(route, rawUsage),
82
89
  };
90
+ const usage = normalizedUsage(rawUsage);
83
91
  if (usage !== undefined)
84
92
  result.usage = usage;
85
93
  if (requestId !== undefined)
86
94
  result.requestId = requestId;
87
95
  return result;
88
96
  }
89
- function dataUrl(image) {
90
- return "data:" + image.mimeType + ";base64," + image.data;
97
+ function textContent(value) {
98
+ if (typeof value === "string")
99
+ return value;
100
+ if (value.some((part) => typeof part !== "string"))
101
+ throw new ClassifierError("capability", "This content placement does not support images on the selected route.");
102
+ return value.join("");
103
+ }
104
+ function openAiContent(value, input) {
105
+ return imageContentParts(value, (id) => ({ type: "input_image", image_url: imageUrl(namedImage(input.images, id)) }))
106
+ .map((part) => typeof part === "string" ? { type: "input_text", text: part } : part);
91
107
  }
92
108
  /* Answer parsing for map-shaped answers (Perplexity, System One, Clef) --- */
93
109
  function labelProbabilities(label, id, value, labels) {
@@ -256,54 +272,44 @@ function parseTypedAnswers(label, value, questions) {
256
272
  function predicateInstructions(question) {
257
273
  const meanings = [];
258
274
  if (question.criteria?.true)
259
- meanings.push("True means: " + question.criteria.true);
275
+ meanings.push("True means: " + textContent(question.criteria.true));
260
276
  if (question.criteria?.false)
261
- meanings.push("False means: " + question.criteria.false);
262
- return meanings.length > 0
263
- ? question.instructions + "\n" + meanings.join("\n")
264
- : question.instructions;
265
- }
266
- function openAiQuestion(id, question) {
277
+ meanings.push("False means: " + textContent(question.criteria.false));
278
+ if (meanings.length === 0)
279
+ return question.instructions;
280
+ const suffix = "\n" + meanings.join("\n");
281
+ return typeof question.instructions === "string" ? question.instructions + suffix : [...question.instructions, suffix];
282
+ }
283
+ function openAiQuestion(id, question, input) {
284
+ const instructions = question.type === "bool" ? predicateInstructions(question) : question.instructions;
285
+ const wireInstructions = typeof instructions === "string" ? instructions : openAiContent(instructions, input);
267
286
  if (question.type === "bool")
287
+ return { type: "predicate", name: id, instructions: wireInstructions };
288
+ if (question.type === "choice")
268
289
  return {
269
- type: "predicate",
270
- name: id,
271
- instructions: predicateInstructions(question),
290
+ type: "choice", name: id, instructions: wireInstructions,
291
+ choices: Object.entries(question.criteria).map(([value, description]) => ({ value, description: textContent(description) })),
272
292
  };
273
- if (question.type === "choice") {
293
+ if (question.type === "score")
274
294
  return {
275
- type: "choice",
276
- name: id,
277
- instructions: question.instructions,
278
- choices: Object.entries(question.criteria).map(([value, description]) => ({ value, description })),
295
+ type: "score", name: id, instructions: wireInstructions,
296
+ levels: question.criteria.map((label) => ({ label: textContent(label) })),
279
297
  };
280
- }
281
- if (question.type === "score") {
282
- return {
283
- type: "score",
284
- name: id,
285
- instructions: question.instructions,
286
- levels: question.criteria.map((label) => ({ label })),
287
- };
288
- }
289
298
  throw unsupportedBox();
290
299
  }
291
300
  function openAiInput(input) {
292
301
  const text = typeof input.state === "string" ? input.state : JSON.stringify(input.state);
293
- if (input.images.length === 0)
302
+ const shared = input.images.filter((image) => image.id === undefined);
303
+ const references = imageReferences(input.state);
304
+ if (shared.length === 0 && references.length === 0)
294
305
  return text;
295
- return [
296
- {
306
+ return [{
297
307
  role: "user",
298
308
  content: [
299
- { type: "input_text", text },
300
- ...input.images.map((image) => ({
301
- type: "input_image",
302
- image_url: dataUrl(image),
303
- })),
309
+ ...(references.length ? openAiContent(input.state, input) : [{ type: "input_text", text }]),
310
+ ...shared.map((image) => ({ type: "input_image", image_url: imageUrl(image) })),
304
311
  ],
305
- },
306
- ];
312
+ }];
307
313
  }
308
314
  function openAiChoiceProbabilities(label, id, value, labels) {
309
315
  if (!Array.isArray(value))
@@ -409,7 +415,7 @@ function parseOpenAiAnswers(label, value, questions) {
409
415
  return answers;
410
416
  }
411
417
  async function classifyOpenAi(route, input, apiKey, signal) {
412
- const questions = Object.entries(input.questions).map(([id, question]) => openAiQuestion(id, question));
418
+ const questions = Object.entries(input.questions).map(([id, question]) => openAiQuestion(id, question, input));
413
419
  const { body, requestId } = await postJson(route, "decisions", {
414
420
  model: route.model,
415
421
  input: openAiInput(input),
@@ -417,57 +423,44 @@ async function classifyOpenAi(route, input, apiKey, signal) {
417
423
  }, apiKey, signal);
418
424
  if (!isRecord(body))
419
425
  fail(OPENAI_LABEL + " returned an unexpected response.");
420
- return finish(route, parseOpenAiAnswers(OPENAI_LABEL, body.answers, input.questions), normalizedUsage(body.usage), requestId);
426
+ return finish(route, parseOpenAiAnswers(OPENAI_LABEL, body.answers, input.questions), body.usage, requestId);
421
427
  }
422
428
  /* Perplexity Decisions ---------------------------------------------------- */
423
- function systemOneQuestions(questions, allowBox) {
424
- // Question IDs may be "__proto__", so the wire map is collected without a prototype.
429
+ function systemOneQuestions(questions, allowBox, content = textContent) {
425
430
  const result = Object.create(null);
426
431
  for (const [id, question] of Object.entries(questions)) {
427
- if (question.type === "bool") {
428
- const wire = {
429
- type: "noul",
430
- instructions: question.instructions,
431
- };
432
- if (question.criteria !== undefined)
433
- wire.criteria = question.criteria;
434
- result[id] = wire;
435
- }
436
- else if (question.type === "choice") {
437
- result[id] = {
438
- type: "choice",
439
- instructions: question.instructions,
440
- criteria: question.criteria,
441
- };
442
- }
443
- else if (question.type === "score") {
444
- result[id] = {
445
- type: "score",
446
- instructions: question.instructions,
447
- criteria: question.criteria,
448
- };
449
- }
450
- else if (allowBox) {
451
- result[id] = { type: "box", instructions: question.instructions };
452
- }
453
- else {
454
- throw unsupportedBox();
432
+ if (question.type === "box") {
433
+ if (!allowBox)
434
+ throw unsupportedBox();
435
+ result[id] = { type: "box", instructions: content(question.instructions) };
436
+ continue;
455
437
  }
438
+ const wire = {
439
+ type: question.type === "bool" ? "noul" : question.type,
440
+ instructions: content(question.instructions),
441
+ };
442
+ if (question.type === "score")
443
+ wire.criteria = question.criteria.map(content);
444
+ else if (question.criteria !== undefined)
445
+ wire.criteria = Object.fromEntries(Object.entries(question.criteria).map(([key, value]) => [key, content(value)]));
446
+ result[id] = wire;
456
447
  }
457
448
  return result;
458
449
  }
459
450
  function perplexityState(input) {
460
- // Perplexity interprets native image parts inside state. Caller JSON is text;
461
- // only locally validated images may become provider-native image parts.
451
+ // Only explicit references become native image parts; other JSON stays text.
462
452
  const text = typeof input.state === "string" ? input.state : JSON.stringify(input.state);
463
- if (input.images.length === 0)
453
+ const shared = input.images.filter((image) => image.id === undefined);
454
+ const references = imageReferences(input.state);
455
+ if (shared.length + references.length > 8)
456
+ throw new ClassifierError("input", "Perplexity accepts at most eight image occurrences per question.");
457
+ if (shared.length === 0 && references.length === 0)
464
458
  return text;
465
459
  return [
466
- text,
467
- ...input.images.map((image) => ({
468
- type: "image_url",
469
- image_url: { url: dataUrl(image) },
470
- })),
460
+ ...(references.length ? imageContentParts(input.state, (id) => ({
461
+ type: "image_url", image_url: { url: imageUrl(namedImage(input.images, id)) },
462
+ })) : [text]),
463
+ ...shared.map((image) => ({ type: "image_url", image_url: { url: imageUrl(image) } })),
471
464
  ];
472
465
  }
473
466
  async function classifyPerplexity(route, input, apiKey, signal) {
@@ -479,7 +472,7 @@ async function classifyPerplexity(route, input, apiKey, signal) {
479
472
  }, apiKey, signal);
480
473
  if (!isRecord(body))
481
474
  fail(PERPLEXITY_LABEL + " returned an unexpected response.");
482
- return finish(route, parseTypedAnswers(PERPLEXITY_LABEL, body.answers, input.questions), normalizedUsage(body.usage), requestId);
475
+ return finish(route, parseTypedAnswers(PERPLEXITY_LABEL, body.answers, input.questions), body.usage, requestId);
483
476
  }
484
477
  /* Microsoft Foundry Decision-1 (text/JSON, API-key authentication) -------- */
485
478
  async function classifyMicrosoft(route, input, apiKey, signal) {
@@ -515,7 +508,7 @@ async function classifyMicrosoft(route, input, apiKey, signal) {
515
508
  else
516
509
  answers[id] = answer;
517
510
  }
518
- return finish(route, parseTypedAnswers(label, answers, input.questions), normalizedUsage(body.usage), requestId);
511
+ return finish(route, parseTypedAnswers(label, answers, input.questions), body.usage, requestId);
519
512
  }
520
513
  /* TypeSafe System One (direct API and compatible gateways) --------------- */
521
514
  function withImageRefs(state, refs) {
@@ -525,24 +518,40 @@ function withImageRefs(state, refs) {
525
518
  }
526
519
  async function classifySystemOne(route, input, apiKey, signal) {
527
520
  const assets = Object.create(null);
528
- const refs = [];
521
+ const sharedRefs = [];
522
+ const namedRefs = new Map();
523
+ const used = new Set([...imageReferences(input.state), ...questionImageReferences(input.questions)]);
529
524
  for (const image of input.images) {
525
+ // Batching can remove a question or a criterion. Jev rejects unused assets.
526
+ if (image.id !== undefined && !used.has(image.id))
527
+ continue;
528
+ if ("url" in image)
529
+ throw new ClassifierError("capability", "Jev assets require local images.");
530
530
  const ref = randomUUID();
531
- refs.push(ref);
531
+ if (image.id === undefined)
532
+ sharedRefs.push(ref);
533
+ else
534
+ namedRefs.set(image.id, ref);
532
535
  assets[ref] = {
533
- type: "image",
534
- format: image.mimeType === "image/png" ? "png" : "jpg",
536
+ type: "image", format: image.mimeType === "image/png" ? "png" : "jpg",
535
537
  data_base64: image.data,
536
538
  };
537
539
  }
540
+ const reference = (id) => {
541
+ const ref = namedRefs.get(id);
542
+ if (!ref)
543
+ throw new ClassifierError("input", "Unknown named image reference.");
544
+ return ref;
545
+ };
546
+ const state = mapImageReferences(input.state, reference);
538
547
  const payload = {
539
548
  model: route.model,
540
- state: refs.length === 0 ? input.state : withImageRefs(input.state, refs),
541
- questions: systemOneQuestions(input.questions, true),
549
+ state: sharedRefs.length ? withImageRefs(state, sharedRefs) : state,
550
+ questions: systemOneQuestions(input.questions, true, (value) => mapImageReferences(value, reference)),
542
551
  };
543
- if (refs.length > 0)
552
+ if (Object.keys(assets).length > 0)
544
553
  payload.assets = assets;
545
- const experimentalHeader = refs.length > 0 ||
554
+ const experimentalHeader = Object.keys(assets).length > 0 ||
546
555
  Object.values(input.questions).some((question) => question.type === "box");
547
556
  const extraHeaders = experimentalHeader
548
557
  ? { "TypeSafe-Danger-Zone-Images": "true" }
@@ -550,7 +559,7 @@ async function classifySystemOne(route, input, apiKey, signal) {
550
559
  const { body, requestId } = await postJson(route, "systemone", payload, apiKey, signal, extraHeaders);
551
560
  if (!isRecord(body))
552
561
  fail(TYPESAFE_LABEL + " returned an unexpected response.");
553
- return finish(route, parseTypedAnswers(TYPESAFE_LABEL, body.answers, input.questions), normalizedUsage(body.usage), requestId);
562
+ return finish(route, parseTypedAnswers(TYPESAFE_LABEL, body.answers, input.questions), body.usage, requestId);
554
563
  }
555
564
  /* Cloudflare Workers AI (Clef and third-party System One envelopes) ------- */
556
565
  function clefBodyModel(model) {
@@ -587,10 +596,11 @@ async function classifyCloudflare(route, input, apiKey, signal) {
587
596
  questions: systemOneQuestions(input.questions, false),
588
597
  };
589
598
  if (input.images.length > 0) {
590
- payload.images = input.images.map((image) => ({
591
- content_type: image.mimeType,
592
- base64: image.data,
593
- }));
599
+ payload.images = input.images.map((image) => {
600
+ if ("url" in image)
601
+ throw new ClassifierError("capability", "Clef requires local images.");
602
+ return { content_type: image.mimeType, base64: image.data };
603
+ });
594
604
  }
595
605
  path = "run/" + route.model;
596
606
  }
@@ -608,7 +618,10 @@ async function classifyCloudflare(route, input, apiKey, signal) {
608
618
  }
609
619
  const { body, requestId } = await postJson(route, path, payload, apiKey, signal);
610
620
  const result = unwrapCloudflare(CLOUDFLARE_LABEL, body);
611
- const usage = normalizedUsage(result.usage) ??
612
- normalizedUsage(isRecord(body) ? body.usage : undefined);
621
+ const usage = normalizedUsage(result.usage) !== undefined
622
+ ? result.usage
623
+ : isRecord(body)
624
+ ? body.usage
625
+ : undefined;
613
626
  return finish(route, parseTypedAnswers(CLOUDFLARE_LABEL, result.answers, input.questions), usage, requestId);
614
627
  }
package/dist/tree.d.ts ADDED
@@ -0,0 +1,4 @@
1
+ import { type ClassifyOptions } from "./classify.js";
2
+ import { type ClassifierTreeResult } from "./types.js";
3
+ /** Greedy sibling decisions over an already validated classification tree; forced edges make no model call. */
4
+ export declare function classifyTree(params: unknown, options: ClassifyOptions): Promise<ClassifierTreeResult>;
package/dist/tree.js ADDED
@@ -0,0 +1,136 @@
1
+ import { classify } 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 { ClassifierError, userError, } from "./types.js";
7
+ /** Greedy sibling decisions over an already validated classification tree; forced edges make no model call. */
8
+ export async function classifyTree(params, options) {
9
+ choicePolicy(options.settings);
10
+ const input = await loadTreeInput(params, options.cwd, options.signal);
11
+ const initial = resolveModel(options.settings);
12
+ const result = {
13
+ provider: initial.route,
14
+ model: initial.model,
15
+ status: "complete",
16
+ levels: Object.create(null),
17
+ steps: [],
18
+ providerCalls: 0,
19
+ usage: { inputTokens: 0, outputTokens: 0, totalTokens: 0 },
20
+ cost: {
21
+ status: "estimated",
22
+ currency: "USD",
23
+ source: "aggregated",
24
+ input: 0,
25
+ output: 0,
26
+ total: 0,
27
+ },
28
+ };
29
+ const path = [];
30
+ let siblings = input.tree.roots;
31
+ let pinned;
32
+ while (siblings.length > 0) {
33
+ if (options.signal?.aborted)
34
+ throw new ClassifierError("aborted", "Classification was cancelled.");
35
+ let selected;
36
+ let step;
37
+ const level = path.length + 1;
38
+ if (siblings.length === 1) {
39
+ selected = siblings[0];
40
+ step = { level, id: selected.id, source: "automatic" };
41
+ }
42
+ else {
43
+ // Non-numeric wire keys preserve array order through JS object enumeration and batching.
44
+ const candidates = new Map(siblings.map((node, index) => ["category_" + index, node]));
45
+ const instructions = (input.instructions ?? "Choose the most appropriate category for the supplied state.") +
46
+ "\nChoose one child of this selected parent path (JSON IDs): " + JSON.stringify(path) +
47
+ ". Use the option descriptions to decide which branch contains the best category. Do not choose a descendant directly.";
48
+ let branch;
49
+ try {
50
+ branch = await classify({
51
+ state: input.state,
52
+ questions: {
53
+ tree: {
54
+ type: "choice",
55
+ instructions,
56
+ criteria: Object.fromEntries([...candidates].map(([key, node]) => [
57
+ key, node.description?.trim() ? node.description : node.id,
58
+ ])),
59
+ },
60
+ },
61
+ ...(input.images !== undefined ? { images: input.images } : {}),
62
+ }, {
63
+ ...options,
64
+ // Only the first actual decision can select an explicitly configured fallback route.
65
+ settings: pinned
66
+ ? { ...options.settings, default: pinned, fallback: [] }
67
+ : options.settings,
68
+ });
69
+ }
70
+ catch (error) {
71
+ if (options.signal?.aborted ||
72
+ (error instanceof ClassifierError && error.code === "aborted"))
73
+ throw new ClassifierError("aborted", "Classification was cancelled.");
74
+ if (result.providerCalls > 0)
75
+ throw new ClassifierError("partial_classification", "Tree traversal stopped at Level" + level + " after " + result.providerCalls +
76
+ " completed provider request(s), which may be billed. No completed levels were replayed. " + userError(error));
77
+ throw error;
78
+ }
79
+ const usage = result.providerCalls === 0
80
+ ? branch.usage
81
+ : sumUsage(result.usage, branch.usage);
82
+ if (usage === undefined)
83
+ delete result.usage;
84
+ else
85
+ result.usage = usage;
86
+ result.cost = result.providerCalls === 0
87
+ ? branch.cost
88
+ : sumCost(result.cost, branch.cost);
89
+ result.providerCalls += branch.providerCalls ?? 1;
90
+ result.provider = branch.provider;
91
+ result.model = branch.model;
92
+ pinned = { provider: branch.provider, model: branch.model };
93
+ if (branch.attemptedRoutes !== undefined)
94
+ result.attemptedRoutes = branch.attemptedRoutes;
95
+ const answer = branch.answers.tree;
96
+ if (!answer)
97
+ throw new ClassifierError("response", "Tree branch returned no answer.");
98
+ if (answer.type === "no_match" || answer.type === "ambiguous" ||
99
+ answer.type === "refusal") {
100
+ result.status = answer.type;
101
+ break;
102
+ }
103
+ if (answer.type !== "choice")
104
+ throw new ClassifierError("response", "Tree branch did not return a choice answer.");
105
+ const probabilities = Object.entries(answer.probabilities);
106
+ const maximum = Math.max(...probabilities.map(([, probability]) => probability));
107
+ const winners = probabilities.filter(([, probability]) => probability === maximum);
108
+ if (winners.length !== 1) {
109
+ result.status = "ambiguous";
110
+ break;
111
+ }
112
+ const node = candidates.get(winners[0][0]);
113
+ if (!node)
114
+ throw new ClassifierError("response", "Tree branch selected an unknown category.");
115
+ selected = node;
116
+ step = {
117
+ level,
118
+ id: selected.id,
119
+ source: "model",
120
+ confidence: answer.confidence,
121
+ probabilityScope: answer.probabilityScope ?? "siblings",
122
+ };
123
+ if (answer.noneOfAboveProbability !== undefined)
124
+ step.noneOfAboveProbability = answer.noneOfAboveProbability;
125
+ }
126
+ path.push(selected.id);
127
+ result.levels["Level" + level] = selected.id;
128
+ result.steps.push(step);
129
+ siblings = selected.children ?? [];
130
+ }
131
+ if (options.signal?.aborted)
132
+ throw new ClassifierError("aborted", "Classification was cancelled.");
133
+ if (Buffer.byteLength(JSON.stringify(result, null, 2)) > 40 * 1024)
134
+ throw new ClassifierError("response", "Tree result exceeds the 40 KiB tool output limit.");
135
+ return result;
136
+ }