@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/dist/config.js CHANGED
@@ -3,6 +3,8 @@ import { homedir } from "node:os";
3
3
  import { join } from "node:path";
4
4
  import { loadPiSettings, resolveConfigDir, } from "@amaster.ai/pi-shared/settings";
5
5
  import { cloudflareAccountId } from "./auth.js";
6
+ import { resolvePricing } from "./cost.js";
7
+ import { choicePolicy } from "./choices.js";
6
8
  import { ClassifierError, isRecord, } from "./types.js";
7
9
  export const SETTINGS_KEY = "pi-classifier";
8
10
  export const BUILT_INS = [
@@ -190,6 +192,7 @@ export function configuredRoutes(settings, field) {
190
192
  return value.map((entry, index) => routePair(entry, field + "[" + index + "]"));
191
193
  }
192
194
  export function resolveModel(settings, selected = configuredDefault(settings)) {
195
+ choicePolicy(settings);
193
196
  const { provider: routeId, model: modelId } = routePair(selected, "route");
194
197
  if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/.test(routeId) ||
195
198
  modelId.length > 256 ||
@@ -280,12 +283,49 @@ export function resolveModel(settings, selected = configuredDefault(settings)) {
280
283
  experimentalImages: raw.experimentalImages === true,
281
284
  requestTimeoutMs: timeout,
282
285
  };
286
+ const pricing = resolvePricing(result.provider, modelId, result.baseUrl, raw.pricing);
287
+ if (pricing)
288
+ result.pricing = pricing;
289
+ if (raw.maxChoices !== undefined) {
290
+ if (typeof raw.maxChoices !== "number" ||
291
+ !Number.isSafeInteger(raw.maxChoices) ||
292
+ raw.maxChoices < 2)
293
+ return configuration("Provider maxChoices must be a safe integer of at least 2.");
294
+ result.maxChoices = raw.maxChoices;
295
+ }
296
+ else {
297
+ const knownLimit = knownMaxChoices(result);
298
+ if (knownLimit !== undefined)
299
+ result.maxChoices = knownLimit;
300
+ }
283
301
  if (configuredApiKey)
284
302
  result.configuredApiKey = configuredApiKey;
285
303
  if (builtIn?.envVar)
286
304
  result.envVar = builtIn.envVar;
287
305
  return result;
288
306
  }
307
+ function knownMaxChoices(route) {
308
+ const directJev = route.provider === "typesafe" &&
309
+ route.baseUrl === "https://api.typesafe.ai/v1" &&
310
+ ["jev-latest", "jev-preview", "jev-1.13.0", "jev-1.14.0"].includes(route.model);
311
+ const openai = route.provider === "openai" &&
312
+ route.baseUrl === "https://api.openai.com/v1" &&
313
+ route.model === "gpt-6-luna";
314
+ const perplexity = route.provider === "perplexity" &&
315
+ route.baseUrl === "https://api.perplexity.ai/v1" &&
316
+ [
317
+ "pplx-decider-v1.1-27b",
318
+ "pplx-decider-v1-27b",
319
+ "pplx-decider-v1.2",
320
+ "pplx-decider-latest",
321
+ "pplx-decider-flash-v1.2",
322
+ "pplx-decider-flash-latest",
323
+ ].includes(route.model);
324
+ const clef = route.provider === "cloudflare" &&
325
+ /^https:\/\/api\.cloudflare\.com\/client\/v4\/accounts\/[^/]+\/ai$/.test(route.baseUrl) &&
326
+ ["@cf/cloudflare/clef", "@cf/cloudflare/clef-flash"].includes(route.model);
327
+ return directJev || openai || perplexity || clef ? 255 : undefined;
328
+ }
289
329
  export function listModels(settings) {
290
330
  const lines = BUILT_INS.flatMap((provider) => provider.models.map((model) => provider.route + " " + model.id));
291
331
  for (const [id, provider] of Object.entries(settings.customProviders ?? {})) {
package/dist/cost.d.ts ADDED
@@ -0,0 +1,8 @@
1
+ import { type ClassifierCost, type ClassifierResult, type ResolvedModel } from "./types.js";
2
+ /** Validate overrides before a request; use public prices only for known official endpoints. */
3
+ export declare function resolvePricing(provider: string, model: string, baseUrl: string, overrides: unknown): ResolvedModel["pricing"];
4
+ export declare function tokenCount(value: unknown): number | undefined;
5
+ /** Raw usage is intentional: legacy normalized usage fills missing counters with zero. */
6
+ export declare function estimateCost(route: ResolvedModel, usage: unknown): ClassifierCost;
7
+ export declare function sumUsage(left: ClassifierResult["usage"], right: ClassifierResult["usage"]): ClassifierResult["usage"];
8
+ export declare function sumCost(left: ClassifierCost, right: ClassifierCost): ClassifierCost;
package/dist/cost.js ADDED
@@ -0,0 +1,202 @@
1
+ import { ClassifierError, isRecord, } from "./types.js";
2
+ // Standard public USD rates, not account-specific billing. Sources and caveats are in README.
3
+ // Keep exact model matches: newer IDs and other hosts must not inherit guessed prices.
4
+ const PRICES = {
5
+ openai: {
6
+ "gpt-6-luna": {
7
+ inputPerMillion: 0.1,
8
+ outputPerMillion: 0,
9
+ cachedInputPerMillion: 0.01,
10
+ cacheWritePerMillion: 0.125,
11
+ },
12
+ },
13
+ typesafe: Object.fromEntries(["jev-latest", "jev-preview", "jev-1.13.0", "jev-1.14.0"].map((id) => [
14
+ id,
15
+ { inputPerMillion: 0.042, outputPerMillion: 0 },
16
+ ])),
17
+ perplexity: {
18
+ "pplx-decider-v1.1-27b": { inputPerMillion: 0.02, outputPerMillion: 0 },
19
+ "pplx-decider-v1-27b": { inputPerMillion: 0.02, outputPerMillion: 0 },
20
+ "pplx-decider-v1.2": { inputPerMillion: 0.02, outputPerMillion: 0 },
21
+ "pplx-decider-latest": { inputPerMillion: 0.02, outputPerMillion: 0 },
22
+ "pplx-decider-flash-v1.2": { inputPerMillion: 0.01, outputPerMillion: 0 },
23
+ "pplx-decider-flash-latest": { inputPerMillion: 0.01, outputPerMillion: 0 },
24
+ },
25
+ cloudflare: {
26
+ "@cf/cloudflare/clef": { inputPerMillion: 0.24, outputPerMillion: 0 },
27
+ "@cf/cloudflare/clef-flash": { inputPerMillion: 0.038, outputPerMillion: 0 },
28
+ "typesafe/jev": {
29
+ inputPerMillion: 0.042,
30
+ outputPerMillion: 0,
31
+ cachedInputPerMillion: 0,
32
+ },
33
+ },
34
+ };
35
+ /** Validate overrides before a request; use public prices only for known official endpoints. */
36
+ export function resolvePricing(provider, model, baseUrl, overrides) {
37
+ if (overrides !== undefined) {
38
+ if (!isRecord(overrides))
39
+ throw new ClassifierError("configuration", "Provider pricing must be a model-keyed object.");
40
+ if (Object.hasOwn(overrides, model)) {
41
+ const value = overrides[model];
42
+ const keys = [
43
+ "inputPerMillion",
44
+ "outputPerMillion",
45
+ "cachedInputPerMillion",
46
+ "cacheWritePerMillion",
47
+ ];
48
+ if (!isRecord(value) ||
49
+ Object.keys(value).some((key) => !keys.includes(key)) ||
50
+ !validRate(value.inputPerMillion) ||
51
+ !validRate(value.outputPerMillion) ||
52
+ keys.slice(2).some((key) => value[key] !== undefined && !validRate(value[key])))
53
+ throw new ClassifierError("configuration", "Model pricing requires finite, non-negative inputPerMillion and outputPerMillion USD rates, with optional cachedInputPerMillion and cacheWritePerMillion.");
54
+ const rates = {
55
+ inputPerMillion: value.inputPerMillion,
56
+ outputPerMillion: value.outputPerMillion,
57
+ };
58
+ if (validRate(value.cachedInputPerMillion))
59
+ rates.cachedInputPerMillion = value.cachedInputPerMillion;
60
+ if (validRate(value.cacheWritePerMillion))
61
+ rates.cacheWritePerMillion = value.cacheWritePerMillion;
62
+ return { rates, source: "configured" };
63
+ }
64
+ }
65
+ const official = (provider === "openai" && baseUrl === "https://api.openai.com/v1") ||
66
+ (provider === "typesafe" && baseUrl === "https://api.typesafe.ai/v1") ||
67
+ (provider === "perplexity" && baseUrl === "https://api.perplexity.ai/v1") ||
68
+ (provider === "cloudflare" &&
69
+ /^https:\/\/api\.cloudflare\.com\/client\/v4\/accounts\/[^/]+\/ai$/.test(baseUrl));
70
+ const catalog = Object.hasOwn(PRICES, provider) ? PRICES[provider] : undefined;
71
+ const rates = official && catalog && Object.hasOwn(catalog, model)
72
+ ? catalog[model]
73
+ : undefined;
74
+ return rates ? { rates: { ...rates }, source: "builtin" } : undefined;
75
+ }
76
+ function validRate(value) {
77
+ return typeof value === "number" && Number.isFinite(value) && value >= 0;
78
+ }
79
+ export function tokenCount(value) {
80
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0
81
+ ? value
82
+ : undefined;
83
+ }
84
+ function unavailable(reason) {
85
+ return { status: "unavailable", currency: "USD", reason };
86
+ }
87
+ /** Raw usage is intentional: legacy normalized usage fills missing counters with zero. */
88
+ export function estimateCost(route, usage) {
89
+ if (!route.pricing)
90
+ return unavailable("unknown_pricing");
91
+ if (!isRecord(usage) || usage.input_tokens === undefined)
92
+ return unavailable("missing_usage");
93
+ const inputTokens = tokenCount(usage.input_tokens);
94
+ if (usage.output_tokens === undefined &&
95
+ route.pricing.rates.outputPerMillion !== 0)
96
+ return unavailable("missing_usage");
97
+ // Missing output usage is harmless only when the output rate is zero.
98
+ const outputTokens = usage.output_tokens === undefined ? 0 : tokenCount(usage.output_tokens);
99
+ if (inputTokens === undefined || outputTokens === undefined)
100
+ return unavailable("invalid_usage");
101
+ const details = usage.input_tokens_details;
102
+ if (details !== undefined && !isRecord(details))
103
+ return unavailable("invalid_usage");
104
+ const cached = isRecord(details) && details.cached_tokens !== undefined
105
+ ? tokenCount(details.cached_tokens)
106
+ : 0;
107
+ const writes = isRecord(details) && details.cache_write_tokens !== undefined
108
+ ? tokenCount(details.cache_write_tokens)
109
+ : 0;
110
+ if (cached === undefined ||
111
+ writes === undefined ||
112
+ cached > inputTokens ||
113
+ writes > inputTokens - cached)
114
+ return unavailable("invalid_usage");
115
+ const rates = { ...route.pricing.rates };
116
+ // The extension uses default 30m cache writes. Do not misprice an unexpected 12h write.
117
+ if (isRecord(details) && details.cache_write_tokens_details !== undefined) {
118
+ const writeDetails = details.cache_write_tokens_details;
119
+ if (!isRecord(writeDetails))
120
+ return unavailable("invalid_usage");
121
+ const shortWrites = tokenCount(writeDetails.ttl_30m_tokens);
122
+ const longWrites = tokenCount(writeDetails.ttl_12h_tokens);
123
+ if (shortWrites === undefined ||
124
+ longWrites === undefined ||
125
+ shortWrites > writes ||
126
+ longWrites !== writes - shortWrites)
127
+ return unavailable("invalid_usage");
128
+ if (longWrites > 0)
129
+ return unavailable("missing_cache_pricing");
130
+ }
131
+ if ((cached > 0 && rates.cachedInputPerMillion === undefined) ||
132
+ (writes > 0 && rates.cacheWritePerMillion === undefined))
133
+ return unavailable("missing_cache_pricing");
134
+ // OpenAI doubles input rates for >272K context. Overrides already define effective rates.
135
+ if (route.provider === "openai" &&
136
+ route.pricing.source === "builtin" &&
137
+ inputTokens > 272_000) {
138
+ rates.inputPerMillion *= 2;
139
+ if (rates.cachedInputPerMillion !== undefined)
140
+ rates.cachedInputPerMillion *= 2;
141
+ if (rates.cacheWritePerMillion !== undefined)
142
+ rates.cacheWritePerMillion *= 2;
143
+ }
144
+ const input = ((inputTokens - cached - writes) / 1_000_000) * rates.inputPerMillion +
145
+ (cached / 1_000_000) * (rates.cachedInputPerMillion ?? 0) +
146
+ (writes / 1_000_000) * (rates.cacheWritePerMillion ?? 0);
147
+ const output = (outputTokens / 1_000_000) * rates.outputPerMillion;
148
+ const total = input + output;
149
+ if (![input, output, total].every(Number.isFinite))
150
+ return unavailable("calculation_overflow");
151
+ return {
152
+ status: "estimated",
153
+ currency: "USD",
154
+ input,
155
+ output,
156
+ total,
157
+ rates,
158
+ source: route.pricing.source,
159
+ };
160
+ }
161
+ export function sumUsage(left, right) {
162
+ if (!left || !right)
163
+ return undefined;
164
+ const result = {
165
+ inputTokens: left.inputTokens + right.inputTokens,
166
+ outputTokens: left.outputTokens + right.outputTokens,
167
+ totalTokens: left.totalTokens + right.totalTokens,
168
+ };
169
+ if (!Object.values(result).every(Number.isSafeInteger))
170
+ return undefined;
171
+ for (const field of ["cachedInputTokens", "cacheWriteTokens"]) {
172
+ if (left[field] !== undefined && right[field] !== undefined) {
173
+ const total = left[field] + right[field];
174
+ if (Number.isSafeInteger(total))
175
+ result[field] = total;
176
+ }
177
+ }
178
+ return result;
179
+ }
180
+ export function sumCost(left, right) {
181
+ if (left.status === "unavailable")
182
+ return left;
183
+ if (right.status === "unavailable")
184
+ return right;
185
+ const input = left.input + right.input;
186
+ const output = left.output + right.output;
187
+ const total = input + output;
188
+ if (![input, output, total].every(Number.isFinite))
189
+ return {
190
+ status: "unavailable",
191
+ currency: "USD",
192
+ reason: "calculation_overflow",
193
+ };
194
+ return {
195
+ status: "estimated",
196
+ currency: "USD",
197
+ source: "aggregated",
198
+ input,
199
+ output,
200
+ total,
201
+ };
202
+ }
@@ -34,6 +34,8 @@ export declare const classifyOutput: Type.TObject<{
34
34
  choice: Type.TString;
35
35
  probabilities: Type.TRecord<"^.*$", Type.TNumber>;
36
36
  confidence: Type.TNumber;
37
+ probabilityScope: Type.TOptional<Type.TLiteral<"batch">>;
38
+ noneOfAboveProbability: Type.TOptional<Type.TNumber>;
37
39
  }>, Type.TObject<{
38
40
  type: Type.TLiteral<"score">;
39
41
  score: Type.TNumber;
@@ -50,12 +52,44 @@ export declare const classifyOutput: Type.TObject<{
50
52
  confidence: Type.TNumber;
51
53
  }>, Type.TObject<{
52
54
  type: Type.TLiteral<"refusal">;
55
+ }>, Type.TObject<{
56
+ type: Type.TLiteral<"no_match">;
57
+ }>, Type.TObject<{
58
+ type: Type.TLiteral<"ambiguous">;
53
59
  }>]>>;
60
+ providerCalls: Type.TOptional<Type.TInteger>;
54
61
  usage: Type.TOptional<Type.TObject<{
55
62
  inputTokens: Type.TNumber;
56
63
  outputTokens: Type.TNumber;
57
64
  totalTokens: Type.TNumber;
65
+ cachedInputTokens: Type.TOptional<Type.TNumber>;
66
+ cacheWriteTokens: Type.TOptional<Type.TNumber>;
58
67
  }>>;
68
+ cost: Type.TUnion<[Type.TObject<{
69
+ status: Type.TLiteral<"estimated">;
70
+ currency: Type.TLiteral<"USD">;
71
+ input: Type.TNumber;
72
+ output: Type.TNumber;
73
+ total: Type.TNumber;
74
+ source: Type.TUnion<[Type.TLiteral<"builtin">, Type.TLiteral<"configured">]>;
75
+ rates: Type.TObject<{
76
+ inputPerMillion: Type.TNumber;
77
+ outputPerMillion: Type.TNumber;
78
+ cachedInputPerMillion: Type.TOptional<Type.TNumber>;
79
+ cacheWritePerMillion: Type.TOptional<Type.TNumber>;
80
+ }>;
81
+ }>, Type.TObject<{
82
+ status: Type.TLiteral<"estimated">;
83
+ currency: Type.TLiteral<"USD">;
84
+ input: Type.TNumber;
85
+ output: Type.TNumber;
86
+ total: Type.TNumber;
87
+ source: Type.TLiteral<"aggregated">;
88
+ }>, Type.TObject<{
89
+ status: Type.TLiteral<"unavailable">;
90
+ currency: Type.TLiteral<"USD">;
91
+ reason: Type.TUnion<[Type.TLiteral<"unknown_pricing">, Type.TLiteral<"missing_usage">, Type.TLiteral<"invalid_usage">, Type.TLiteral<"missing_cache_pricing">, Type.TLiteral<"calculation_overflow">]>;
92
+ }>]>;
59
93
  requestId: Type.TOptional<Type.TString>;
60
94
  attemptedRoutes: Type.TOptional<Type.TArray<Type.TObject<{
61
95
  provider: Type.TString;
@@ -80,6 +114,8 @@ export declare const classifyCompareOutput: Type.TObject<{
80
114
  choice: Type.TString;
81
115
  probabilities: Type.TRecord<"^.*$", Type.TNumber>;
82
116
  confidence: Type.TNumber;
117
+ probabilityScope: Type.TOptional<Type.TLiteral<"batch">>;
118
+ noneOfAboveProbability: Type.TOptional<Type.TNumber>;
83
119
  }>, Type.TObject<{
84
120
  type: Type.TLiteral<"score">;
85
121
  score: Type.TNumber;
@@ -96,12 +132,44 @@ export declare const classifyCompareOutput: Type.TObject<{
96
132
  confidence: Type.TNumber;
97
133
  }>, Type.TObject<{
98
134
  type: Type.TLiteral<"refusal">;
135
+ }>, Type.TObject<{
136
+ type: Type.TLiteral<"no_match">;
137
+ }>, Type.TObject<{
138
+ type: Type.TLiteral<"ambiguous">;
99
139
  }>]>>;
140
+ providerCalls: Type.TOptional<Type.TInteger>;
100
141
  usage: Type.TOptional<Type.TObject<{
101
142
  inputTokens: Type.TNumber;
102
143
  outputTokens: Type.TNumber;
103
144
  totalTokens: Type.TNumber;
145
+ cachedInputTokens: Type.TOptional<Type.TNumber>;
146
+ cacheWriteTokens: Type.TOptional<Type.TNumber>;
104
147
  }>>;
148
+ cost: Type.TUnion<[Type.TObject<{
149
+ status: Type.TLiteral<"estimated">;
150
+ currency: Type.TLiteral<"USD">;
151
+ input: Type.TNumber;
152
+ output: Type.TNumber;
153
+ total: Type.TNumber;
154
+ source: Type.TUnion<[Type.TLiteral<"builtin">, Type.TLiteral<"configured">]>;
155
+ rates: Type.TObject<{
156
+ inputPerMillion: Type.TNumber;
157
+ outputPerMillion: Type.TNumber;
158
+ cachedInputPerMillion: Type.TOptional<Type.TNumber>;
159
+ cacheWritePerMillion: Type.TOptional<Type.TNumber>;
160
+ }>;
161
+ }>, Type.TObject<{
162
+ status: Type.TLiteral<"estimated">;
163
+ currency: Type.TLiteral<"USD">;
164
+ input: Type.TNumber;
165
+ output: Type.TNumber;
166
+ total: Type.TNumber;
167
+ source: Type.TLiteral<"aggregated">;
168
+ }>, Type.TObject<{
169
+ status: Type.TLiteral<"unavailable">;
170
+ currency: Type.TLiteral<"USD">;
171
+ reason: Type.TUnion<[Type.TLiteral<"unknown_pricing">, Type.TLiteral<"missing_usage">, Type.TLiteral<"invalid_usage">, Type.TLiteral<"missing_cache_pricing">, Type.TLiteral<"calculation_overflow">]>;
172
+ }>]>;
105
173
  requestId: Type.TOptional<Type.TString>;
106
174
  attemptedRoutes: Type.TOptional<Type.TArray<Type.TObject<{
107
175
  provider: Type.TString;
@@ -119,4 +187,63 @@ export declare const classifyCompareOutput: Type.TObject<{
119
187
  }>;
120
188
  }>]>>;
121
189
  }>;
190
+ export declare const classifyTreeParameters: Type.TObject<{
191
+ state: Type.TUnion<[Type.TString, Type.TRecord<"^.*$", Type.TUnknown>, Type.TArray<Type.TUnknown>]>;
192
+ tree: Type.TUnion<[Type.TString, Type.TObject<{
193
+ roots: Type.TArray<Type.TRef<"#/$defs/ClassificationTreeNode">>;
194
+ }>]>;
195
+ instructions: Type.TOptional<Type.TString>;
196
+ images: Type.TOptional<Type.TArray<Type.TString>>;
197
+ }>;
198
+ export declare const classifyTreeOutput: Type.TObject<{
199
+ provider: Type.TString;
200
+ model: Type.TString;
201
+ status: Type.TUnion<[Type.TLiteral<"complete">, Type.TLiteral<"no_match">, Type.TLiteral<"ambiguous">, Type.TLiteral<"refusal">]>;
202
+ levels: Type.TRecord<"^.*$", Type.TString>;
203
+ steps: Type.TArray<Type.TObject<{
204
+ level: Type.TInteger;
205
+ id: Type.TString;
206
+ source: Type.TUnion<[Type.TLiteral<"automatic">, Type.TLiteral<"model">]>;
207
+ confidence: Type.TOptional<Type.TNumber>;
208
+ probabilityScope: Type.TOptional<Type.TUnion<[Type.TLiteral<"siblings">, Type.TLiteral<"batch">]>>;
209
+ noneOfAboveProbability: Type.TOptional<Type.TNumber>;
210
+ }>>;
211
+ providerCalls: Type.TInteger;
212
+ cost: Type.TUnion<[Type.TObject<{
213
+ status: Type.TLiteral<"estimated">;
214
+ currency: Type.TLiteral<"USD">;
215
+ input: Type.TNumber;
216
+ output: Type.TNumber;
217
+ total: Type.TNumber;
218
+ source: Type.TUnion<[Type.TLiteral<"builtin">, Type.TLiteral<"configured">]>;
219
+ rates: Type.TObject<{
220
+ inputPerMillion: Type.TNumber;
221
+ outputPerMillion: Type.TNumber;
222
+ cachedInputPerMillion: Type.TOptional<Type.TNumber>;
223
+ cacheWritePerMillion: Type.TOptional<Type.TNumber>;
224
+ }>;
225
+ }>, Type.TObject<{
226
+ status: Type.TLiteral<"estimated">;
227
+ currency: Type.TLiteral<"USD">;
228
+ input: Type.TNumber;
229
+ output: Type.TNumber;
230
+ total: Type.TNumber;
231
+ source: Type.TLiteral<"aggregated">;
232
+ }>, Type.TObject<{
233
+ status: Type.TLiteral<"unavailable">;
234
+ currency: Type.TLiteral<"USD">;
235
+ reason: Type.TUnion<[Type.TLiteral<"unknown_pricing">, Type.TLiteral<"missing_usage">, Type.TLiteral<"invalid_usage">, Type.TLiteral<"missing_cache_pricing">, Type.TLiteral<"calculation_overflow">]>;
236
+ }>]>;
237
+ usage: Type.TOptional<Type.TObject<{
238
+ inputTokens: Type.TNumber;
239
+ outputTokens: Type.TNumber;
240
+ totalTokens: Type.TNumber;
241
+ cachedInputTokens: Type.TOptional<Type.TNumber>;
242
+ cacheWriteTokens: Type.TOptional<Type.TNumber>;
243
+ }>>;
244
+ attemptedRoutes: Type.TOptional<Type.TArray<Type.TObject<{
245
+ provider: Type.TString;
246
+ model: Type.TString;
247
+ }>>>;
248
+ }>;
122
249
  export default function piClassifier(pi: ExtensionAPI): void;
package/dist/extension.js CHANGED
@@ -2,6 +2,7 @@ import { isProjectTrusted } from "@amaster.ai/pi-shared/settings";
2
2
  import { defineTool, } from "@earendil-works/pi-coding-agent";
3
3
  import { Type } from "typebox";
4
4
  import { classify, compareClassifiers } from "./classify.js";
5
+ import { classifyTree } from "./tree.js";
5
6
  import { configuredRoutes, listModels, loadClassifierSettings, resolveModel, } from "./config.js";
6
7
  import { updateProjectClassifierSettings } from "./settings-write.js";
7
8
  import { ClassifierError, userError } from "./types.js";
@@ -15,7 +16,7 @@ const question = Type.Union([
15
16
  Type.Object({
16
17
  type: Type.Literal("choice"),
17
18
  instructions: Type.String({ minLength: 1, maxLength: 16384 }),
18
- criteria: Type.Record(Type.String({ minLength: 1, maxLength: 128 }), shortText, { minProperties: 1, maxProperties: 64 }),
19
+ criteria: Type.Record(Type.String({ minLength: 1, maxLength: 128 }), shortText, { minProperties: 1 }),
19
20
  }, { additionalProperties: false }),
20
21
  Type.Object({
21
22
  type: Type.Literal("score"),
@@ -44,6 +45,12 @@ export const classifyParameters = Type.Object({
44
45
  description: "Local PNG/JPEG/WebP files inside cwd, in order. No URLs, symlinks or inline base64. Requires an image-capable model.",
45
46
  })),
46
47
  }, { additionalProperties: false });
48
+ const tokenPricing = Type.Object({
49
+ inputPerMillion: Type.Number({ minimum: 0 }),
50
+ outputPerMillion: Type.Number({ minimum: 0 }),
51
+ cachedInputPerMillion: Type.Optional(Type.Number({ minimum: 0 })),
52
+ cacheWritePerMillion: Type.Optional(Type.Number({ minimum: 0 })),
53
+ });
47
54
  export const classifyOutput = Type.Object({
48
55
  provider: Type.String(),
49
56
  model: Type.String(),
@@ -57,6 +64,8 @@ export const classifyOutput = Type.Object({
57
64
  choice: Type.String(),
58
65
  probabilities: Type.Record(Type.String(), Type.Number({ minimum: 0, maximum: 1 })),
59
66
  confidence: Type.Number({ minimum: 0, maximum: 1 }),
67
+ probabilityScope: Type.Optional(Type.Literal("batch")),
68
+ noneOfAboveProbability: Type.Optional(Type.Number({ minimum: 0, maximum: 1 })),
60
69
  }),
61
70
  Type.Object({
62
71
  type: Type.Literal("score"),
@@ -75,12 +84,47 @@ export const classifyOutput = Type.Object({
75
84
  confidence: Type.Number({ minimum: 0, maximum: 1 }),
76
85
  }),
77
86
  Type.Object({ type: Type.Literal("refusal") }),
87
+ Type.Object({ type: Type.Literal("no_match") }),
88
+ Type.Object({ type: Type.Literal("ambiguous") }),
78
89
  ])),
90
+ providerCalls: Type.Optional(Type.Integer({ minimum: 1 })),
79
91
  usage: Type.Optional(Type.Object({
80
92
  inputTokens: Type.Number(),
81
93
  outputTokens: Type.Number(),
82
94
  totalTokens: Type.Number(),
95
+ cachedInputTokens: Type.Optional(Type.Number()),
96
+ cacheWriteTokens: Type.Optional(Type.Number()),
83
97
  })),
98
+ cost: Type.Union([
99
+ Type.Object({
100
+ status: Type.Literal("estimated"),
101
+ currency: Type.Literal("USD"),
102
+ input: Type.Number({ minimum: 0 }),
103
+ output: Type.Number({ minimum: 0 }),
104
+ total: Type.Number({ minimum: 0 }),
105
+ source: Type.Union([Type.Literal("builtin"), Type.Literal("configured")]),
106
+ rates: tokenPricing,
107
+ }),
108
+ Type.Object({
109
+ status: Type.Literal("estimated"),
110
+ currency: Type.Literal("USD"),
111
+ input: Type.Number({ minimum: 0 }),
112
+ output: Type.Number({ minimum: 0 }),
113
+ total: Type.Number({ minimum: 0 }),
114
+ source: Type.Literal("aggregated"),
115
+ }),
116
+ Type.Object({
117
+ status: Type.Literal("unavailable"),
118
+ currency: Type.Literal("USD"),
119
+ reason: Type.Union([
120
+ Type.Literal("unknown_pricing"),
121
+ Type.Literal("missing_usage"),
122
+ Type.Literal("invalid_usage"),
123
+ Type.Literal("missing_cache_pricing"),
124
+ Type.Literal("calculation_overflow"),
125
+ ]),
126
+ }),
127
+ ]),
84
128
  requestId: Type.Optional(Type.String()),
85
129
  attemptedRoutes: Type.Optional(Type.Array(Type.Object({ provider: Type.String(), model: Type.String() }))),
86
130
  });
@@ -103,15 +147,57 @@ export const classifyCompareOutput = Type.Object({
103
147
  }),
104
148
  ])),
105
149
  });
150
+ const classificationTreeNode = Type.Object({
151
+ id: Type.String({ minLength: 1, maxLength: 128 }),
152
+ description: Type.Optional(Type.String({ maxLength: 4096 })),
153
+ children: Type.Optional(Type.Array(Type.Ref("#/$defs/ClassificationTreeNode"))),
154
+ }, { additionalProperties: false });
155
+ export const classifyTreeParameters = Type.Object({
156
+ state: classifyParameters.properties.state,
157
+ tree: Type.Union([
158
+ Type.String({
159
+ minLength: 1,
160
+ maxLength: 4096,
161
+ description: "Local UTF-8 JSON file inside cwd; no URLs or symlinks.",
162
+ }),
163
+ Type.Object({ roots: Type.Array(Type.Ref("#/$defs/ClassificationTreeNode"), { minItems: 1 }) }, { additionalProperties: false }),
164
+ ]),
165
+ instructions: Type.Optional(Type.String({ minLength: 1, maxLength: 8192 })),
166
+ images: classifyParameters.properties.images,
167
+ }, { additionalProperties: false, $defs: { ClassificationTreeNode: classificationTreeNode } });
168
+ export const classifyTreeOutput = Type.Object({
169
+ provider: Type.String(),
170
+ model: Type.String(),
171
+ status: Type.Union([
172
+ Type.Literal("complete"),
173
+ Type.Literal("no_match"),
174
+ Type.Literal("ambiguous"),
175
+ Type.Literal("refusal"),
176
+ ]),
177
+ levels: Type.Record(Type.String({ pattern: "^Level[1-9][0-9]*$" }), Type.String()),
178
+ steps: Type.Array(Type.Object({
179
+ level: Type.Integer({ minimum: 1 }),
180
+ id: Type.String(),
181
+ source: Type.Union([Type.Literal("automatic"), Type.Literal("model")]),
182
+ confidence: Type.Optional(Type.Number({ minimum: 0, maximum: 1 })),
183
+ probabilityScope: Type.Optional(Type.Union([Type.Literal("siblings"), Type.Literal("batch")])),
184
+ noneOfAboveProbability: Type.Optional(Type.Number({ minimum: 0, maximum: 1 })),
185
+ })),
186
+ providerCalls: Type.Integer({ minimum: 0 }),
187
+ cost: classifyOutput.properties.cost,
188
+ usage: classifyOutput.properties.usage,
189
+ attemptedRoutes: classifyOutput.properties.attemptedRoutes,
190
+ });
106
191
  export default function piClassifier(pi) {
107
192
  pi.registerTool(defineTool({
108
193
  name: "classify",
109
194
  label: "Classify",
110
- description: "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.",
195
+ description: "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.",
111
196
  promptSnippet: "Classify text, JSON or supported images into typed probabilistic decisions.",
112
197
  promptGuidelines: [
113
198
  "Use for bounded judgments, classification and rubric scoring, not open-ended prose.",
114
- "Treat low confidence as uncertainty, not permission to switch models or retry.",
199
+ "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.",
200
+ "Handle no_match and ambiguous answers explicitly. probabilityScope=batch and noneOfAboveProbability describe only the winning batch; they are not a full-list probability distribution.",
115
201
  "Send only data the user intends to share with the configured provider.",
116
202
  "Ask /classifier status for the active model. Do not change provider settings without user direction.",
117
203
  ],
@@ -145,7 +231,7 @@ export default function piClassifier(pi) {
145
231
  pi.registerTool(defineTool({
146
232
  name: "classify_compare",
147
233
  label: "Compare classifiers",
148
- description: "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.",
234
+ description: "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.",
149
235
  promptSnippet: "Compare configured decision models only when the user explicitly requests a model comparison.",
150
236
  promptGuidelines: [
151
237
  "Use only when the user explicitly asks to compare classifier models; never use automatically for low confidence or refusals.",
@@ -176,6 +262,42 @@ export default function piClassifier(pi) {
176
262
  }
177
263
  },
178
264
  }));
265
+ pi.registerTool(defineTool({
266
+ name: "classify_tree",
267
+ label: "Classify tree",
268
+ description: "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.",
269
+ promptSnippet: "Classify through a supplied classification tree and return the selected levels.",
270
+ promptGuidelines: [
271
+ "Use classify_tree only when the user supplies or requests a classification tree; do not invent category branches.",
272
+ "Use meaningful node descriptions. Only the current siblings and selected parent path are submitted per decision, not every descendant.",
273
+ "Inspect status and steps: automatic steps have no model confidence, and partial paths are not complete classifications.",
274
+ "Configured choice batching may cause multiple billable requests per level. No fallback may replay completed model decisions.",
275
+ ],
276
+ parameters: classifyTreeParameters,
277
+ outputSchema: classifyTreeOutput,
278
+ annotations: {
279
+ readOnlyHint: true,
280
+ destructiveHint: false,
281
+ openWorldHint: true,
282
+ },
283
+ async execute(_id, params, signal, _onUpdate, ctx) {
284
+ try {
285
+ const result = await classifyTree(params, {
286
+ settings: loadClassifierSettings(ctx.cwd, isProjectTrusted(ctx)),
287
+ cwd: ctx.cwd,
288
+ ...(signal ? { signal } : {}),
289
+ });
290
+ return {
291
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
292
+ details: result,
293
+ structuredContent: { ...result },
294
+ };
295
+ }
296
+ catch (error) {
297
+ throw new Error(userError(error));
298
+ }
299
+ },
300
+ }));
179
301
  pi.registerCommand("classifier", {
180
302
  description: "Classifier: status, list, reload, use <route> <model>, compare <JSON params>. Use writes trusted project defaults; compare makes potentially billable calls.",
181
303
  handler: async (args, ctx) => {
@@ -214,6 +336,9 @@ export default function piClassifier(pi) {
214
336
  images: route.images,
215
337
  box: route.box,
216
338
  requestTimeoutMs: route.requestTimeoutMs,
339
+ none_of_above_choice: settings.none_of_above_choice ?? false,
340
+ remove_choice_limits: settings.remove_choice_limits ?? false,
341
+ maxChoicesPerRequest: route.maxChoices ?? "provider-defined",
217
342
  authentication: "API key only; independent of chat login",
218
343
  fallback: configuredRoutes(settings, "fallback"),
219
344
  compare: configuredRoutes(settings, "compare"),
package/dist/index.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  export { classify, compareClassifiers } from "./classify.js";
2
+ export { classifyTree } from "./tree.js";
2
3
  export { loadClassifierSettings, resolveModel, listModels } from "./config.js";
3
- export type { Answer, Question, ClassifierResult, ClassifierRoute, ClassifierComparisonEntry, ClassifierComparisonResult, ClassifierSettings, ClassifyParams, CustomProviderSettings, ModelDefinition, ProviderSettings, ApiStyle, } from "./types.js";
4
+ export type { Answer, Question, ClassifierResult, ClassifierCost, TokenPricing, ClassifierRoute, ClassifierComparisonEntry, ClassifierComparisonResult, ClassifierSettings, ClassifyParams, ClassifyTreeParams, ClassifierTreeResult, ClassificationTree, ClassificationTreeNode, TreeStep, CustomProviderSettings, ModelDefinition, ProviderSettings, ApiStyle, } from "./types.js";
4
5
  export { ClassifierError } from "./types.js";