@abhishek944/pi-classifier 0.2.0 → 0.3.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.
package/src/extension.ts CHANGED
@@ -6,6 +6,7 @@ import {
6
6
  } from "@earendil-works/pi-coding-agent";
7
7
  import { Type } from "typebox";
8
8
  import { classify, compareClassifiers } from "./classify.js";
9
+ import { classifyTree } from "./tree.js";
9
10
  import {
10
11
  configuredRoutes,
11
12
  listModels,
@@ -37,7 +38,7 @@ const question = Type.Union([
37
38
  criteria: Type.Record(
38
39
  Type.String({ minLength: 1, maxLength: 128 }),
39
40
  shortText,
40
- { minProperties: 1, maxProperties: 64 },
41
+ { minProperties: 1 },
41
42
  ),
42
43
  },
43
44
  { additionalProperties: false },
@@ -91,6 +92,13 @@ export const classifyParameters = Type.Object(
91
92
  { additionalProperties: false },
92
93
  );
93
94
 
95
+ const tokenPricing = Type.Object({
96
+ inputPerMillion: Type.Number({ minimum: 0 }),
97
+ outputPerMillion: Type.Number({ minimum: 0 }),
98
+ cachedInputPerMillion: Type.Optional(Type.Number({ minimum: 0 })),
99
+ cacheWritePerMillion: Type.Optional(Type.Number({ minimum: 0 })),
100
+ });
101
+
94
102
  export const classifyOutput = Type.Object({
95
103
  provider: Type.String(),
96
104
  model: Type.String(),
@@ -109,6 +117,10 @@ export const classifyOutput = Type.Object({
109
117
  Type.Number({ minimum: 0, maximum: 1 }),
110
118
  ),
111
119
  confidence: Type.Number({ minimum: 0, maximum: 1 }),
120
+ probabilityScope: Type.Optional(Type.Literal("batch")),
121
+ noneOfAboveProbability: Type.Optional(
122
+ Type.Number({ minimum: 0, maximum: 1 }),
123
+ ),
112
124
  }),
113
125
  Type.Object({
114
126
  type: Type.Literal("score"),
@@ -129,15 +141,50 @@ export const classifyOutput = Type.Object({
129
141
  confidence: Type.Number({ minimum: 0, maximum: 1 }),
130
142
  }),
131
143
  Type.Object({ type: Type.Literal("refusal") }),
144
+ Type.Object({ type: Type.Literal("no_match") }),
145
+ Type.Object({ type: Type.Literal("ambiguous") }),
132
146
  ]),
133
147
  ),
148
+ providerCalls: Type.Optional(Type.Integer({ minimum: 1 })),
134
149
  usage: Type.Optional(
135
150
  Type.Object({
136
151
  inputTokens: Type.Number(),
137
152
  outputTokens: Type.Number(),
138
153
  totalTokens: Type.Number(),
154
+ cachedInputTokens: Type.Optional(Type.Number()),
155
+ cacheWriteTokens: Type.Optional(Type.Number()),
139
156
  }),
140
157
  ),
158
+ cost: Type.Union([
159
+ Type.Object({
160
+ status: Type.Literal("estimated"),
161
+ currency: Type.Literal("USD"),
162
+ input: Type.Number({ minimum: 0 }),
163
+ output: Type.Number({ minimum: 0 }),
164
+ total: Type.Number({ minimum: 0 }),
165
+ source: Type.Union([Type.Literal("builtin"), Type.Literal("configured")]),
166
+ rates: tokenPricing,
167
+ }),
168
+ Type.Object({
169
+ status: Type.Literal("estimated"),
170
+ currency: Type.Literal("USD"),
171
+ input: Type.Number({ minimum: 0 }),
172
+ output: Type.Number({ minimum: 0 }),
173
+ total: Type.Number({ minimum: 0 }),
174
+ source: Type.Literal("aggregated"),
175
+ }),
176
+ Type.Object({
177
+ status: Type.Literal("unavailable"),
178
+ currency: Type.Literal("USD"),
179
+ reason: Type.Union([
180
+ Type.Literal("unknown_pricing"),
181
+ Type.Literal("missing_usage"),
182
+ Type.Literal("invalid_usage"),
183
+ Type.Literal("missing_cache_pricing"),
184
+ Type.Literal("calculation_overflow"),
185
+ ]),
186
+ }),
187
+ ]),
141
188
  requestId: Type.Optional(Type.String()),
142
189
  attemptedRoutes: Type.Optional(
143
190
  Type.Array(Type.Object({ provider: Type.String(), model: Type.String() })),
@@ -166,18 +213,78 @@ export const classifyCompareOutput = Type.Object({
166
213
  ),
167
214
  });
168
215
 
216
+ const classificationTreeNode = Type.Object(
217
+ {
218
+ id: Type.String({ minLength: 1, maxLength: 128 }),
219
+ description: Type.Optional(Type.String({ maxLength: 4096 })),
220
+ children: Type.Optional(Type.Array(Type.Ref("#/$defs/ClassificationTreeNode"))),
221
+ },
222
+ { additionalProperties: false },
223
+ );
224
+
225
+ export const classifyTreeParameters = Type.Object(
226
+ {
227
+ state: classifyParameters.properties.state,
228
+ tree: Type.Union([
229
+ Type.String({
230
+ minLength: 1,
231
+ maxLength: 4096,
232
+ description: "Local UTF-8 JSON file inside cwd; no URLs or symlinks.",
233
+ }),
234
+ Type.Object(
235
+ { roots: Type.Array(Type.Ref("#/$defs/ClassificationTreeNode"), { minItems: 1 }) },
236
+ { additionalProperties: false },
237
+ ),
238
+ ]),
239
+ instructions: Type.Optional(Type.String({ minLength: 1, maxLength: 8192 })),
240
+ images: classifyParameters.properties.images,
241
+ },
242
+ { additionalProperties: false, $defs: { ClassificationTreeNode: classificationTreeNode } },
243
+ );
244
+
245
+ export const classifyTreeOutput = Type.Object({
246
+ provider: Type.String(),
247
+ model: Type.String(),
248
+ status: Type.Union([
249
+ Type.Literal("complete"),
250
+ Type.Literal("no_match"),
251
+ Type.Literal("ambiguous"),
252
+ Type.Literal("refusal"),
253
+ ]),
254
+ levels: Type.Record(Type.String({ pattern: "^Level[1-9][0-9]*$" }), Type.String()),
255
+ steps: Type.Array(
256
+ Type.Object({
257
+ level: Type.Integer({ minimum: 1 }),
258
+ id: Type.String(),
259
+ source: Type.Union([Type.Literal("automatic"), Type.Literal("model")]),
260
+ confidence: Type.Optional(Type.Number({ minimum: 0, maximum: 1 })),
261
+ probabilityScope: Type.Optional(
262
+ Type.Union([Type.Literal("siblings"), Type.Literal("batch")]),
263
+ ),
264
+ noneOfAboveProbability: Type.Optional(
265
+ Type.Number({ minimum: 0, maximum: 1 }),
266
+ ),
267
+ }),
268
+ ),
269
+ providerCalls: Type.Integer({ minimum: 0 }),
270
+ cost: classifyOutput.properties.cost,
271
+ usage: classifyOutput.properties.usage,
272
+ attemptedRoutes: classifyOutput.properties.attemptedRoutes,
273
+ });
274
+
169
275
  export default function piClassifier(pi: ExtensionAPI): void {
170
276
  pi.registerTool(
171
277
  defineTool({
172
278
  name: "classify",
173
279
  label: "Classify",
174
280
  description:
175
- "Ask a decision model typed questions about text, JSON and supported local images. Returns bool probabilities, choices with probabilities, or scores. Experimental box answers require explicit Jev configuration. Provider/model are fixed by pi-classifier.default (or legacy defaultProvider/defaultModel); this tool cannot override them. API-key authentication is independent of Codex chat login. Only explicitly configured fallback routes may be used after a missing key or HTTP 401/404/429; never after uncertainty, refusals, timeouts or network failures. Use /classifier list or status to inspect configuration.",
281
+ "Ask a decision model typed questions about text, JSON and supported local images. Returns bool probabilities, choices with probabilities, or scores, plus reported token usage and estimated USD cost (or an explicit unavailable reason). Experimental box answers require explicit Jev configuration. Provider/model are fixed by pi-classifier.default (or legacy defaultProvider/defaultModel); this tool cannot override them. API-key authentication is independent of Codex chat login. Only explicitly configured fallback routes may be used after a missing key or HTTP 401/404/429 before any batch has completed; never after uncertainty, refusals, timeouts or network failures. Use /classifier list or status to inspect configuration.",
176
282
  promptSnippet:
177
283
  "Classify text, JSON or supported images into typed probabilistic decisions.",
178
284
  promptGuidelines: [
179
285
  "Use for bounded judgments, classification and rubric scoring, not open-ended prose.",
180
- "Treat low confidence as uncertainty, not permission to switch models or retry.",
286
+ "Treat low confidence as uncertainty, not permission to switch models or retry. Only configured remove_choice_limits with none_of_above_choice permits internal sequential choice batches; this is first-match selection, not a global ranking.",
287
+ "Handle no_match and ambiguous answers explicitly. probabilityScope=batch and noneOfAboveProbability describe only the winning batch; they are not a full-list probability distribution.",
181
288
  "Send only data the user intends to share with the configured provider.",
182
289
  "Ask /classifier status for the active model. Do not change provider settings without user direction.",
183
290
  ],
@@ -216,7 +323,7 @@ export default function piClassifier(pi: ExtensionAPI): void {
216
323
  name: "classify_compare",
217
324
  label: "Compare classifiers",
218
325
  description:
219
- "Explicitly compare the same typed questions and state using exactly pi-classifier.compare provider/model pairs. Each entry is a separate potentially billable request. No fallback, default substitution, provider/model overrides, or default changes. Returns labeled results, duration, usage and safe per-entry failures; cancellation retains completed results and prevents later requests.",
326
+ "Explicitly compare the same typed questions and state using exactly pi-classifier.compare provider/model pairs. Each entry makes potentially billable requests, including multiple requests when choice batching is configured. No fallback, default substitution, provider/model overrides, or default changes. Returns labeled results, duration, usage, estimated USD costs (or unavailable reasons) and safe per-entry failures; cancellation retains completed results and prevents later requests.",
220
327
  promptSnippet:
221
328
  "Compare configured decision models only when the user explicitly requests a model comparison.",
222
329
  promptGuidelines: [
@@ -249,6 +356,45 @@ export default function piClassifier(pi: ExtensionAPI): void {
249
356
  }),
250
357
  );
251
358
 
359
+ pi.registerTool(
360
+ defineTool({
361
+ name: "classify_tree",
362
+ label: "Classify tree",
363
+ description:
364
+ "Classify text, JSON or supported images through a nested classification tree. tree is an inline roots/id/description/children object or a local JSON file inside cwd. Choose among siblings, automatically follow sole children without model calls, and return Level1/Level2/etc under levels with per-step provenance, total providerCalls, reported usage and estimated USD cost. NONE, batching and initial fallback follow configured settings; after a successful decision the route is pinned. no_match, ambiguous and refusal retain only the selected prefix. Automatic steps are structural, not model confirmation; greedy traversal is not a global best-path guarantee. No provider/model override or comparison.",
365
+ promptSnippet: "Classify through a supplied classification tree and return the selected levels.",
366
+ promptGuidelines: [
367
+ "Use classify_tree only when the user supplies or requests a classification tree; do not invent category branches.",
368
+ "Use meaningful node descriptions. Only the current siblings and selected parent path are submitted per decision, not every descendant.",
369
+ "Inspect status and steps: automatic steps have no model confidence, and partial paths are not complete classifications.",
370
+ "Configured choice batching may cause multiple billable requests per level. No fallback may replay completed model decisions.",
371
+ ],
372
+ parameters: classifyTreeParameters,
373
+ outputSchema: classifyTreeOutput,
374
+ annotations: {
375
+ readOnlyHint: true,
376
+ destructiveHint: false,
377
+ openWorldHint: true,
378
+ },
379
+ async execute(_id, params, signal, _onUpdate, ctx) {
380
+ try {
381
+ const result = await classifyTree(params, {
382
+ settings: loadClassifierSettings(ctx.cwd, isProjectTrusted(ctx)),
383
+ cwd: ctx.cwd,
384
+ ...(signal ? { signal } : {}),
385
+ });
386
+ return {
387
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
388
+ details: result,
389
+ structuredContent: { ...result },
390
+ };
391
+ } catch (error) {
392
+ throw new Error(userError(error));
393
+ }
394
+ },
395
+ }),
396
+ );
397
+
252
398
  pi.registerCommand("classifier", {
253
399
  description:
254
400
  "Classifier: status, list, reload, use <route> <model>, compare <JSON params>. Use writes trusted project defaults; compare makes potentially billable calls.",
@@ -298,6 +444,9 @@ export default function piClassifier(pi: ExtensionAPI): void {
298
444
  images: route.images,
299
445
  box: route.box,
300
446
  requestTimeoutMs: route.requestTimeoutMs,
447
+ none_of_above_choice: settings.none_of_above_choice ?? false,
448
+ remove_choice_limits: settings.remove_choice_limits ?? false,
449
+ maxChoicesPerRequest: route.maxChoices ?? "provider-defined",
301
450
  authentication: "API key only; independent of chat login",
302
451
  fallback: configuredRoutes(settings, "fallback"),
303
452
  compare: configuredRoutes(settings, "compare"),
package/src/index.ts CHANGED
@@ -1,14 +1,22 @@
1
1
  export { classify, compareClassifiers } from "./classify.js";
2
+ export { classifyTree } from "./tree.js";
2
3
  export { loadClassifierSettings, resolveModel, listModels } from "./config.js";
3
4
  export type {
4
5
  Answer,
5
6
  Question,
6
7
  ClassifierResult,
8
+ ClassifierCost,
9
+ TokenPricing,
7
10
  ClassifierRoute,
8
11
  ClassifierComparisonEntry,
9
12
  ClassifierComparisonResult,
10
13
  ClassifierSettings,
11
14
  ClassifyParams,
15
+ ClassifyTreeParams,
16
+ ClassifierTreeResult,
17
+ ClassificationTree,
18
+ ClassificationTreeNode,
19
+ TreeStep,
12
20
  CustomProviderSettings,
13
21
  ModelDefinition,
14
22
  ProviderSettings,
package/src/inputs.ts CHANGED
@@ -200,7 +200,7 @@ async function decodeImage(bytes: Buffer, signal?: AbortSignal): Promise<void> {
200
200
  const execFileAsync = promisify(execFile);
201
201
 
202
202
  /** Verify containment of the opened descriptor, not a raceable pre-open path. */
203
- async function verifyOpenedPath(
203
+ export async function verifyOpenedPath(
204
204
  fd: number,
205
205
  root: string,
206
206
  signal?: AbortSignal,
@@ -225,7 +225,7 @@ async function verifyOpenedPath(
225
225
  } else {
226
226
  throw new ClassifierError(
227
227
  "capability",
228
- "Safe local image loading currently supports macOS and Linux only. Text classification remains available.",
228
+ "Safe local file loading currently supports macOS and Linux only. Inline text/JSON classification remains available.",
229
229
  );
230
230
  }
231
231
  const inside = relative(root, openedPath);
package/src/providers.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import { postJson } from "./http.js";
3
+ import { estimateCost, tokenCount } from "./cost.js";
3
4
  import {
4
5
  ClassifierError,
5
6
  isRecord,
@@ -86,12 +87,6 @@ function unitInterval(label: string, value: unknown, field: string): number {
86
87
  return Math.min(1, Math.max(0, value));
87
88
  }
88
89
 
89
- function tokenCount(value: unknown): number | undefined {
90
- return typeof value === "number" && Number.isSafeInteger(value) && value >= 0
91
- ? value
92
- : undefined;
93
- }
94
-
95
90
  function normalizedUsage(
96
91
  value: unknown,
97
92
  ): ClassifierResult["usage"] | undefined {
@@ -102,24 +97,33 @@ function normalizedUsage(
102
97
  const total =
103
98
  tokenCount(value.total_tokens) ?? tokenCount((input ?? 0) + (output ?? 0));
104
99
  if (total === undefined) return undefined;
105
- return {
100
+ const usage: NonNullable<ClassifierResult["usage"]> = {
106
101
  inputTokens: input ?? 0,
107
102
  outputTokens: output ?? 0,
108
103
  totalTokens: total,
109
104
  };
105
+ if (isRecord(value.input_tokens_details)) {
106
+ const cached = tokenCount(value.input_tokens_details.cached_tokens);
107
+ const writes = tokenCount(value.input_tokens_details.cache_write_tokens);
108
+ if (cached !== undefined) usage.cachedInputTokens = cached;
109
+ if (writes !== undefined) usage.cacheWriteTokens = writes;
110
+ }
111
+ return usage;
110
112
  }
111
113
 
112
114
  function finish(
113
115
  route: ResolvedModel,
114
116
  answers: Record<string, Answer>,
115
- usage: ClassifierResult["usage"] | undefined,
117
+ rawUsage: unknown,
116
118
  requestId: string | undefined,
117
119
  ): ClassifierResult {
118
120
  const result: ClassifierResult = {
119
121
  provider: route.route,
120
122
  model: route.model,
121
123
  answers,
124
+ cost: estimateCost(route, rawUsage),
122
125
  };
126
+ const usage = normalizedUsage(rawUsage);
123
127
  if (usage !== undefined) result.usage = usage;
124
128
  if (requestId !== undefined) result.requestId = requestId;
125
129
  return result;
@@ -610,7 +614,7 @@ async function classifyOpenAi(
610
614
  return finish(
611
615
  route,
612
616
  parseOpenAiAnswers(OPENAI_LABEL, body.answers, input.questions),
613
- normalizedUsage(body.usage),
617
+ body.usage,
614
618
  requestId,
615
619
  );
616
620
  }
@@ -690,7 +694,7 @@ async function classifyPerplexity(
690
694
  return finish(
691
695
  route,
692
696
  parseTypedAnswers(PERPLEXITY_LABEL, body.answers, input.questions),
693
- normalizedUsage(body.usage),
697
+ body.usage,
694
698
  requestId,
695
699
  );
696
700
  }
@@ -751,7 +755,7 @@ async function classifyMicrosoft(
751
755
  return finish(
752
756
  route,
753
757
  parseTypedAnswers(label, answers, input.questions),
754
- normalizedUsage(body.usage),
758
+ body.usage,
755
759
  requestId,
756
760
  );
757
761
  }
@@ -806,7 +810,7 @@ async function classifySystemOne(
806
810
  return finish(
807
811
  route,
808
812
  parseTypedAnswers(TYPESAFE_LABEL, body.answers, input.questions),
809
- normalizedUsage(body.usage),
813
+ body.usage,
810
814
  requestId,
811
815
  );
812
816
  }
@@ -887,8 +891,11 @@ async function classifyCloudflare(
887
891
  );
888
892
  const result = unwrapCloudflare(CLOUDFLARE_LABEL, body);
889
893
  const usage =
890
- normalizedUsage(result.usage) ??
891
- normalizedUsage(isRecord(body) ? body.usage : undefined);
894
+ normalizedUsage(result.usage) !== undefined
895
+ ? result.usage
896
+ : isRecord(body)
897
+ ? body.usage
898
+ : undefined;
892
899
  return finish(
893
900
  route,
894
901
  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
+ }
package/src/types.ts CHANGED
@@ -22,6 +22,9 @@ export type Answer =
22
22
  choice: string;
23
23
  probabilities: Record<string, number>;
24
24
  confidence: number;
25
+ /** Present when probabilities cover one internally processed batch, not the full list. */
26
+ probabilityScope?: "batch";
27
+ noneOfAboveProbability?: number;
25
28
  }
26
29
  | {
27
30
  type: "score";
@@ -34,7 +37,9 @@ export type Answer =
34
37
  box: { top: number; bottom: number; left: number; right: number };
35
38
  confidence: number;
36
39
  }
37
- | { type: "refusal" };
40
+ | { type: "refusal" }
41
+ | { type: "no_match" }
42
+ | { type: "ambiguous" };
38
43
 
39
44
  export interface ClassifyParams {
40
45
  state: string | Record<string, unknown> | unknown[];
@@ -43,6 +48,42 @@ export interface ClassifyParams {
43
48
  images?: string[];
44
49
  }
45
50
 
51
+ export type ClassificationTreeNode = {
52
+ id: string;
53
+ description?: string;
54
+ children?: ClassificationTreeNode[];
55
+ };
56
+
57
+ export type ClassificationTree = { roots: ClassificationTreeNode[] };
58
+
59
+ export type ClassifyTreeParams = {
60
+ state: ClassifyParams["state"];
61
+ tree: string | ClassificationTree;
62
+ instructions?: string;
63
+ images?: string[];
64
+ };
65
+
66
+ export type TreeStep = {
67
+ level: number;
68
+ id: string;
69
+ source: "automatic" | "model";
70
+ confidence?: number;
71
+ probabilityScope?: "siblings" | "batch";
72
+ noneOfAboveProbability?: number;
73
+ };
74
+
75
+ export type ClassifierTreeResult = {
76
+ provider: string;
77
+ model: string;
78
+ status: "complete" | "no_match" | "ambiguous" | "refusal";
79
+ levels: Record<string, string>;
80
+ steps: TreeStep[];
81
+ providerCalls: number;
82
+ cost: ClassifierCost;
83
+ usage?: NonNullable<ClassifierResult["usage"]>;
84
+ attemptedRoutes?: ClassifierRoute[];
85
+ };
86
+
46
87
  export interface ModelDefinition {
47
88
  id: string;
48
89
  name?: string;
@@ -50,6 +91,43 @@ export interface ModelDefinition {
50
91
  box?: boolean;
51
92
  }
52
93
 
94
+ /** USD per million tokens. Cache counts, when reported, are part of input tokens. */
95
+ export type TokenPricing = {
96
+ inputPerMillion: number;
97
+ outputPerMillion: number;
98
+ cachedInputPerMillion?: number;
99
+ cacheWritePerMillion?: number;
100
+ };
101
+
102
+ export type ClassifierCost =
103
+ | {
104
+ status: "estimated";
105
+ currency: "USD";
106
+ input: number;
107
+ output: number;
108
+ total: number;
109
+ source: "builtin" | "configured";
110
+ rates: TokenPricing;
111
+ }
112
+ | {
113
+ status: "estimated";
114
+ currency: "USD";
115
+ input: number;
116
+ output: number;
117
+ total: number;
118
+ source: "aggregated";
119
+ }
120
+ | {
121
+ status: "unavailable";
122
+ currency: "USD";
123
+ reason:
124
+ | "unknown_pricing"
125
+ | "missing_usage"
126
+ | "invalid_usage"
127
+ | "missing_cache_pricing"
128
+ | "calculation_overflow";
129
+ };
130
+
53
131
  export interface ProviderSettings {
54
132
  apiKey?: string;
55
133
  baseUrl?: string;
@@ -57,6 +135,10 @@ export interface ProviderSettings {
57
135
  accountId?: string;
58
136
  experimentalImages?: boolean;
59
137
  experimentalBox?: boolean;
138
+ /** Model ID (or Azure deployment name) to explicit token rates. */
139
+ pricing?: Record<string, TokenPricing>;
140
+ /** Verified wire choice limit; needed for batching on endpoints without a known limit. */
141
+ maxChoices?: number;
60
142
  }
61
143
 
62
144
  export interface CustomProviderSettings extends ProviderSettings {
@@ -70,6 +152,8 @@ export type ClassifierRoute = {
70
152
  };
71
153
 
72
154
  export interface ClassifierSettings {
155
+ none_of_above_choice?: boolean;
156
+ remove_choice_limits?: boolean;
73
157
  default?: ClassifierRoute;
74
158
  fallback?: ClassifierRoute[];
75
159
  compare?: ClassifierRoute[];
@@ -94,6 +178,8 @@ export interface ResolvedModel {
94
178
  box: boolean;
95
179
  experimentalImages: boolean;
96
180
  requestTimeoutMs: number;
181
+ pricing?: { rates: TokenPricing; source: "builtin" | "configured" };
182
+ maxChoices?: number;
97
183
  }
98
184
 
99
185
  export interface PreparedImage {
@@ -113,7 +199,17 @@ export type ClassifierResult = {
113
199
  provider: string;
114
200
  model: string;
115
201
  answers: Record<string, Answer>;
116
- usage?: { inputTokens: number; outputTokens: number; totalTokens: number };
202
+ usage?: {
203
+ inputTokens: number;
204
+ outputTokens: number;
205
+ totalTokens: number;
206
+ cachedInputTokens?: number;
207
+ cacheWriteTokens?: number;
208
+ };
209
+ /** Successful provider requests made by automatic choice processing. */
210
+ providerCalls?: number;
211
+ /** Estimate for completed requests in this result, not an invoice or total of failed attempts. */
212
+ cost: ClassifierCost;
117
213
  requestId?: string;
118
214
  attemptedRoutes?: ClassifierRoute[];
119
215
  };