@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/cost.ts ADDED
@@ -0,0 +1,250 @@
1
+ import {
2
+ ClassifierError,
3
+ isRecord,
4
+ type ClassifierCost,
5
+ type ClassifierResult,
6
+ type ResolvedModel,
7
+ type TokenPricing,
8
+ } from "./types.js";
9
+
10
+ // Standard public USD rates, not account-specific billing. Sources and caveats are in README.
11
+ // Keep exact model matches: newer IDs and other hosts must not inherit guessed prices.
12
+ const PRICES: Record<string, Record<string, TokenPricing>> = {
13
+ openai: {
14
+ "gpt-6-luna": {
15
+ inputPerMillion: 0.1,
16
+ outputPerMillion: 0,
17
+ cachedInputPerMillion: 0.01,
18
+ cacheWritePerMillion: 0.125,
19
+ },
20
+ },
21
+ typesafe: Object.fromEntries(
22
+ ["jev-latest", "jev-preview", "jev-1.13.0", "jev-1.14.0"].map((id) => [
23
+ id,
24
+ { inputPerMillion: 0.042, outputPerMillion: 0 },
25
+ ]),
26
+ ),
27
+ perplexity: {
28
+ "pplx-decider-v1.1-27b": { inputPerMillion: 0.02, outputPerMillion: 0 },
29
+ "pplx-decider-v1-27b": { inputPerMillion: 0.02, outputPerMillion: 0 },
30
+ "pplx-decider-v1.2": { inputPerMillion: 0.02, outputPerMillion: 0 },
31
+ "pplx-decider-latest": { inputPerMillion: 0.02, outputPerMillion: 0 },
32
+ "pplx-decider-flash-v1.2": { inputPerMillion: 0.01, outputPerMillion: 0 },
33
+ "pplx-decider-flash-latest": { inputPerMillion: 0.01, outputPerMillion: 0 },
34
+ },
35
+ cloudflare: {
36
+ "@cf/cloudflare/clef": { inputPerMillion: 0.24, outputPerMillion: 0 },
37
+ "@cf/cloudflare/clef-flash": { inputPerMillion: 0.038, outputPerMillion: 0 },
38
+ "typesafe/jev": {
39
+ inputPerMillion: 0.042,
40
+ outputPerMillion: 0,
41
+ cachedInputPerMillion: 0,
42
+ },
43
+ },
44
+ };
45
+
46
+ /** Validate overrides before a request; use public prices only for known official endpoints. */
47
+ export function resolvePricing(
48
+ provider: string,
49
+ model: string,
50
+ baseUrl: string,
51
+ overrides: unknown,
52
+ ): ResolvedModel["pricing"] {
53
+ if (overrides !== undefined) {
54
+ if (!isRecord(overrides))
55
+ throw new ClassifierError(
56
+ "configuration",
57
+ "Provider pricing must be a model-keyed object.",
58
+ );
59
+ if (Object.hasOwn(overrides, model)) {
60
+ const value = overrides[model];
61
+ const keys = [
62
+ "inputPerMillion",
63
+ "outputPerMillion",
64
+ "cachedInputPerMillion",
65
+ "cacheWritePerMillion",
66
+ ];
67
+ if (
68
+ !isRecord(value) ||
69
+ Object.keys(value).some((key) => !keys.includes(key)) ||
70
+ !validRate(value.inputPerMillion) ||
71
+ !validRate(value.outputPerMillion) ||
72
+ keys.slice(2).some(
73
+ (key) => value[key] !== undefined && !validRate(value[key]),
74
+ )
75
+ )
76
+ throw new ClassifierError(
77
+ "configuration",
78
+ "Model pricing requires finite, non-negative inputPerMillion and outputPerMillion USD rates, with optional cachedInputPerMillion and cacheWritePerMillion.",
79
+ );
80
+ const rates: TokenPricing = {
81
+ inputPerMillion: value.inputPerMillion,
82
+ outputPerMillion: value.outputPerMillion,
83
+ };
84
+ if (validRate(value.cachedInputPerMillion))
85
+ rates.cachedInputPerMillion = value.cachedInputPerMillion;
86
+ if (validRate(value.cacheWritePerMillion))
87
+ rates.cacheWritePerMillion = value.cacheWritePerMillion;
88
+ return { rates, source: "configured" };
89
+ }
90
+ }
91
+ const official =
92
+ (provider === "openai" && baseUrl === "https://api.openai.com/v1") ||
93
+ (provider === "typesafe" && baseUrl === "https://api.typesafe.ai/v1") ||
94
+ (provider === "perplexity" && baseUrl === "https://api.perplexity.ai/v1") ||
95
+ (provider === "cloudflare" &&
96
+ /^https:\/\/api\.cloudflare\.com\/client\/v4\/accounts\/[^/]+\/ai$/.test(baseUrl));
97
+ const catalog = Object.hasOwn(PRICES, provider) ? PRICES[provider] : undefined;
98
+ const rates =
99
+ official && catalog && Object.hasOwn(catalog, model)
100
+ ? catalog[model]
101
+ : undefined;
102
+ return rates ? { rates: { ...rates }, source: "builtin" } : undefined;
103
+ }
104
+
105
+ function validRate(value: unknown): value is number {
106
+ return typeof value === "number" && Number.isFinite(value) && value >= 0;
107
+ }
108
+
109
+ export function tokenCount(value: unknown): number | undefined {
110
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0
111
+ ? value
112
+ : undefined;
113
+ }
114
+
115
+ function unavailable(
116
+ reason: Extract<ClassifierCost, { status: "unavailable" }>["reason"],
117
+ ): ClassifierCost {
118
+ return { status: "unavailable", currency: "USD", reason };
119
+ }
120
+
121
+ /** Raw usage is intentional: legacy normalized usage fills missing counters with zero. */
122
+ export function estimateCost(
123
+ route: ResolvedModel,
124
+ usage: unknown,
125
+ ): ClassifierCost {
126
+ if (!route.pricing) return unavailable("unknown_pricing");
127
+ if (!isRecord(usage) || usage.input_tokens === undefined)
128
+ return unavailable("missing_usage");
129
+ const inputTokens = tokenCount(usage.input_tokens);
130
+ if (
131
+ usage.output_tokens === undefined &&
132
+ route.pricing.rates.outputPerMillion !== 0
133
+ )
134
+ return unavailable("missing_usage");
135
+ // Missing output usage is harmless only when the output rate is zero.
136
+ const outputTokens =
137
+ usage.output_tokens === undefined ? 0 : tokenCount(usage.output_tokens);
138
+ if (inputTokens === undefined || outputTokens === undefined)
139
+ return unavailable("invalid_usage");
140
+ const details = usage.input_tokens_details;
141
+ if (details !== undefined && !isRecord(details))
142
+ return unavailable("invalid_usage");
143
+ const cached =
144
+ isRecord(details) && details.cached_tokens !== undefined
145
+ ? tokenCount(details.cached_tokens)
146
+ : 0;
147
+ const writes =
148
+ isRecord(details) && details.cache_write_tokens !== undefined
149
+ ? tokenCount(details.cache_write_tokens)
150
+ : 0;
151
+ if (
152
+ cached === undefined ||
153
+ writes === undefined ||
154
+ cached > inputTokens ||
155
+ writes > inputTokens - cached
156
+ )
157
+ return unavailable("invalid_usage");
158
+ const rates = { ...route.pricing.rates };
159
+ // The extension uses default 30m cache writes. Do not misprice an unexpected 12h write.
160
+ if (isRecord(details) && details.cache_write_tokens_details !== undefined) {
161
+ const writeDetails = details.cache_write_tokens_details;
162
+ if (!isRecord(writeDetails)) return unavailable("invalid_usage");
163
+ const shortWrites = tokenCount(writeDetails.ttl_30m_tokens);
164
+ const longWrites = tokenCount(writeDetails.ttl_12h_tokens);
165
+ if (
166
+ shortWrites === undefined ||
167
+ longWrites === undefined ||
168
+ shortWrites > writes ||
169
+ longWrites !== writes - shortWrites
170
+ )
171
+ return unavailable("invalid_usage");
172
+ if (longWrites > 0) return unavailable("missing_cache_pricing");
173
+ }
174
+ if (
175
+ (cached > 0 && rates.cachedInputPerMillion === undefined) ||
176
+ (writes > 0 && rates.cacheWritePerMillion === undefined)
177
+ )
178
+ return unavailable("missing_cache_pricing");
179
+ // OpenAI doubles input rates for >272K context. Overrides already define effective rates.
180
+ if (
181
+ route.provider === "openai" &&
182
+ route.pricing.source === "builtin" &&
183
+ inputTokens > 272_000
184
+ ) {
185
+ rates.inputPerMillion *= 2;
186
+ if (rates.cachedInputPerMillion !== undefined)
187
+ rates.cachedInputPerMillion *= 2;
188
+ if (rates.cacheWritePerMillion !== undefined)
189
+ rates.cacheWritePerMillion *= 2;
190
+ }
191
+ const input =
192
+ ((inputTokens - cached - writes) / 1_000_000) * rates.inputPerMillion +
193
+ (cached / 1_000_000) * (rates.cachedInputPerMillion ?? 0) +
194
+ (writes / 1_000_000) * (rates.cacheWritePerMillion ?? 0);
195
+ const output = (outputTokens / 1_000_000) * rates.outputPerMillion;
196
+ const total = input + output;
197
+ if (![input, output, total].every(Number.isFinite))
198
+ return unavailable("calculation_overflow");
199
+ return {
200
+ status: "estimated",
201
+ currency: "USD",
202
+ input,
203
+ output,
204
+ total,
205
+ rates,
206
+ source: route.pricing.source,
207
+ };
208
+ }
209
+
210
+ export function sumUsage(
211
+ left: ClassifierResult["usage"],
212
+ right: ClassifierResult["usage"],
213
+ ): ClassifierResult["usage"] {
214
+ if (!left || !right) return undefined;
215
+ const result: NonNullable<ClassifierResult["usage"]> = {
216
+ inputTokens: left.inputTokens + right.inputTokens,
217
+ outputTokens: left.outputTokens + right.outputTokens,
218
+ totalTokens: left.totalTokens + right.totalTokens,
219
+ };
220
+ if (!Object.values(result).every(Number.isSafeInteger)) return undefined;
221
+ for (const field of ["cachedInputTokens", "cacheWriteTokens"] as const) {
222
+ if (left[field] !== undefined && right[field] !== undefined) {
223
+ const total = left[field] + right[field];
224
+ if (Number.isSafeInteger(total)) result[field] = total;
225
+ }
226
+ }
227
+ return result;
228
+ }
229
+
230
+ export function sumCost(left: ClassifierCost, right: ClassifierCost): ClassifierCost {
231
+ if (left.status === "unavailable") return left;
232
+ if (right.status === "unavailable") return right;
233
+ const input = left.input + right.input;
234
+ const output = left.output + right.output;
235
+ const total = input + output;
236
+ if (![input, output, total].every(Number.isFinite))
237
+ return {
238
+ status: "unavailable",
239
+ currency: "USD",
240
+ reason: "calculation_overflow",
241
+ };
242
+ return {
243
+ status: "estimated",
244
+ currency: "USD",
245
+ source: "aggregated",
246
+ input,
247
+ output,
248
+ total,
249
+ };
250
+ }
package/src/extension.ts CHANGED
@@ -6,6 +6,9 @@ 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";
10
+ import { registerBoxTool } from "./box-tool.js";
11
+ import { registerComputerUseTool } from "./computer-use-tool.js";
9
12
  import {
10
13
  configuredRoutes,
11
14
  listModels,
@@ -15,12 +18,26 @@ import {
15
18
  import { updateProjectClassifierSettings } from "./settings-write.js";
16
19
  import { ClassifierError, userError } from "./types.js";
17
20
 
18
- const shortText = Type.String({ maxLength: 4096 });
21
+ const imageReference = Type.Object(
22
+ { $image: Type.String({ pattern: "^[a-zA-Z0-9_-]{1,64}$" }) },
23
+ { additionalProperties: false },
24
+ );
25
+ function imageContent(maxLength: number, nonempty = false) {
26
+ return Type.Union([
27
+ Type.String({ maxLength, ...(nonempty ? { minLength: 1 } : {}) }),
28
+ Type.Array(Type.Union([Type.String({ maxLength }), imageReference]), {
29
+ minItems: 1, maxItems: 128,
30
+ description: "Ordered text and explicit {$image:id} references. References require named images; supported placements depend on the route.",
31
+ }),
32
+ ]);
33
+ }
34
+ const shortText = imageContent(4096);
35
+ const instructionContent = imageContent(16384, true);
19
36
  const question = Type.Union([
20
37
  Type.Object(
21
38
  {
22
39
  type: Type.Literal("bool"),
23
- instructions: Type.String({ minLength: 1, maxLength: 16384 }),
40
+ instructions: instructionContent,
24
41
  criteria: Type.Optional(
25
42
  Type.Object(
26
43
  { true: Type.Optional(shortText), false: Type.Optional(shortText) },
@@ -33,11 +50,11 @@ const question = Type.Union([
33
50
  Type.Object(
34
51
  {
35
52
  type: Type.Literal("choice"),
36
- instructions: Type.String({ minLength: 1, maxLength: 16384 }),
53
+ instructions: instructionContent,
37
54
  criteria: Type.Record(
38
55
  Type.String({ minLength: 1, maxLength: 128 }),
39
56
  shortText,
40
- { minProperties: 1, maxProperties: 64 },
57
+ { minProperties: 1 },
41
58
  ),
42
59
  },
43
60
  { additionalProperties: false },
@@ -45,8 +62,8 @@ const question = Type.Union([
45
62
  Type.Object(
46
63
  {
47
64
  type: Type.Literal("score"),
48
- instructions: Type.String({ minLength: 1, maxLength: 16384 }),
49
- criteria: Type.Array(Type.String({ minLength: 1, maxLength: 4096 }), {
65
+ instructions: instructionContent,
66
+ criteria: Type.Array(imageContent(4096, true), {
50
67
  minItems: 2,
51
68
  maxItems: 10,
52
69
  }),
@@ -56,7 +73,7 @@ const question = Type.Union([
56
73
  Type.Object(
57
74
  {
58
75
  type: Type.Literal("box"),
59
- instructions: Type.String({ minLength: 1, maxLength: 16384 }),
76
+ instructions: instructionContent,
60
77
  },
61
78
  { additionalProperties: false },
62
79
  ),
@@ -72,7 +89,7 @@ export const classifyParameters = Type.Object(
72
89
  ],
73
90
  {
74
91
  description:
75
- "Text or JSON data to classify. All questions refer to this same state.",
92
+ "Text or JSON data to classify. Use explicit {$image:id} objects to place named images in state on Jev, OpenAI or Perplexity. Other JSON remains data. All questions refer to this same state.",
76
93
  },
77
94
  ),
78
95
  questions: Type.Record(
@@ -81,16 +98,32 @@ export const classifyParameters = Type.Object(
81
98
  { minProperties: 1, maxProperties: 32 },
82
99
  ),
83
100
  images: Type.Optional(
84
- Type.Array(Type.String({ minLength: 1, maxLength: 4096 }), {
85
- maxItems: 5,
86
- description:
87
- "Local PNG/JPEG/WebP files inside cwd, in order. No URLs, symlinks or inline base64. Requires an image-capable model.",
101
+ Type.Array(Type.Union([
102
+ Type.String({ minLength: 1, maxLength: 4096 }),
103
+ Type.Object({
104
+ id: Type.String({ pattern: "^[a-zA-Z0-9_-]{1,64}$" }),
105
+ path: Type.String({ minLength: 1, maxLength: 4096 }),
106
+ }, { additionalProperties: false }),
107
+ Type.Object({
108
+ id: Type.String({ pattern: "^[a-zA-Z0-9_-]{1,64}$" }),
109
+ url: Type.String({ minLength: 1, maxLength: 4096 }),
110
+ }, { additionalProperties: false }),
111
+ ]), {
112
+ maxItems: 8,
113
+ description: "Legacy local paths are shared in order. Named {id,path} or {id,url} images must be referenced using {$image:id} in state or supported question content. URLs are OpenAI-only and sent to the provider, never fetched locally. No inline base64 or symlinks. Limits: Perplexity 8 images, Clef 4, others 5.",
88
114
  }),
89
115
  ),
90
116
  },
91
117
  { additionalProperties: false },
92
118
  );
93
119
 
120
+ const tokenPricing = Type.Object({
121
+ inputPerMillion: Type.Number({ minimum: 0 }),
122
+ outputPerMillion: Type.Number({ minimum: 0 }),
123
+ cachedInputPerMillion: Type.Optional(Type.Number({ minimum: 0 })),
124
+ cacheWritePerMillion: Type.Optional(Type.Number({ minimum: 0 })),
125
+ });
126
+
94
127
  export const classifyOutput = Type.Object({
95
128
  provider: Type.String(),
96
129
  model: Type.String(),
@@ -109,6 +142,10 @@ export const classifyOutput = Type.Object({
109
142
  Type.Number({ minimum: 0, maximum: 1 }),
110
143
  ),
111
144
  confidence: Type.Number({ minimum: 0, maximum: 1 }),
145
+ probabilityScope: Type.Optional(Type.Literal("batch")),
146
+ noneOfAboveProbability: Type.Optional(
147
+ Type.Number({ minimum: 0, maximum: 1 }),
148
+ ),
112
149
  }),
113
150
  Type.Object({
114
151
  type: Type.Literal("score"),
@@ -129,15 +166,50 @@ export const classifyOutput = Type.Object({
129
166
  confidence: Type.Number({ minimum: 0, maximum: 1 }),
130
167
  }),
131
168
  Type.Object({ type: Type.Literal("refusal") }),
169
+ Type.Object({ type: Type.Literal("no_match") }),
170
+ Type.Object({ type: Type.Literal("ambiguous") }),
132
171
  ]),
133
172
  ),
173
+ providerCalls: Type.Optional(Type.Integer({ minimum: 1 })),
134
174
  usage: Type.Optional(
135
175
  Type.Object({
136
176
  inputTokens: Type.Number(),
137
177
  outputTokens: Type.Number(),
138
178
  totalTokens: Type.Number(),
179
+ cachedInputTokens: Type.Optional(Type.Number()),
180
+ cacheWriteTokens: Type.Optional(Type.Number()),
139
181
  }),
140
182
  ),
183
+ cost: Type.Union([
184
+ Type.Object({
185
+ status: Type.Literal("estimated"),
186
+ currency: Type.Literal("USD"),
187
+ input: Type.Number({ minimum: 0 }),
188
+ output: Type.Number({ minimum: 0 }),
189
+ total: Type.Number({ minimum: 0 }),
190
+ source: Type.Union([Type.Literal("builtin"), Type.Literal("configured")]),
191
+ rates: tokenPricing,
192
+ }),
193
+ Type.Object({
194
+ status: Type.Literal("estimated"),
195
+ currency: Type.Literal("USD"),
196
+ input: Type.Number({ minimum: 0 }),
197
+ output: Type.Number({ minimum: 0 }),
198
+ total: Type.Number({ minimum: 0 }),
199
+ source: Type.Literal("aggregated"),
200
+ }),
201
+ Type.Object({
202
+ status: Type.Literal("unavailable"),
203
+ currency: Type.Literal("USD"),
204
+ reason: Type.Union([
205
+ Type.Literal("unknown_pricing"),
206
+ Type.Literal("missing_usage"),
207
+ Type.Literal("invalid_usage"),
208
+ Type.Literal("missing_cache_pricing"),
209
+ Type.Literal("calculation_overflow"),
210
+ ]),
211
+ }),
212
+ ]),
141
213
  requestId: Type.Optional(Type.String()),
142
214
  attemptedRoutes: Type.Optional(
143
215
  Type.Array(Type.Object({ provider: Type.String(), model: Type.String() })),
@@ -166,18 +238,80 @@ export const classifyCompareOutput = Type.Object({
166
238
  ),
167
239
  });
168
240
 
241
+ const classificationTreeNode = Type.Object(
242
+ {
243
+ id: Type.String({ minLength: 1, maxLength: 128 }),
244
+ description: Type.Optional(Type.String({ maxLength: 4096 })),
245
+ children: Type.Optional(Type.Array(Type.Ref("#/$defs/ClassificationTreeNode"))),
246
+ },
247
+ { additionalProperties: false },
248
+ );
249
+
250
+ export const classifyTreeParameters = Type.Object(
251
+ {
252
+ state: classifyParameters.properties.state,
253
+ tree: Type.Union([
254
+ Type.String({
255
+ minLength: 1,
256
+ maxLength: 4096,
257
+ description: "Local UTF-8 JSON file inside cwd; no URLs or symlinks.",
258
+ }),
259
+ Type.Object(
260
+ { roots: Type.Array(Type.Ref("#/$defs/ClassificationTreeNode"), { minItems: 1 }) },
261
+ { additionalProperties: false },
262
+ ),
263
+ ]),
264
+ instructions: Type.Optional(Type.String({ minLength: 1, maxLength: 8192 })),
265
+ images: classifyParameters.properties.images,
266
+ },
267
+ { additionalProperties: false, $defs: { ClassificationTreeNode: classificationTreeNode } },
268
+ );
269
+
270
+ export const classifyTreeOutput = Type.Object({
271
+ provider: Type.String(),
272
+ model: Type.String(),
273
+ status: Type.Union([
274
+ Type.Literal("complete"),
275
+ Type.Literal("no_match"),
276
+ Type.Literal("ambiguous"),
277
+ Type.Literal("refusal"),
278
+ ]),
279
+ levels: Type.Record(Type.String({ pattern: "^Level[1-9][0-9]*$" }), Type.String()),
280
+ steps: Type.Array(
281
+ Type.Object({
282
+ level: Type.Integer({ minimum: 1 }),
283
+ id: Type.String(),
284
+ source: Type.Union([Type.Literal("automatic"), Type.Literal("model")]),
285
+ confidence: Type.Optional(Type.Number({ minimum: 0, maximum: 1 })),
286
+ probabilityScope: Type.Optional(
287
+ Type.Union([Type.Literal("siblings"), Type.Literal("batch")]),
288
+ ),
289
+ noneOfAboveProbability: Type.Optional(
290
+ Type.Number({ minimum: 0, maximum: 1 }),
291
+ ),
292
+ }),
293
+ ),
294
+ providerCalls: Type.Integer({ minimum: 0 }),
295
+ cost: classifyOutput.properties.cost,
296
+ usage: classifyOutput.properties.usage,
297
+ attemptedRoutes: classifyOutput.properties.attemptedRoutes,
298
+ });
299
+
169
300
  export default function piClassifier(pi: ExtensionAPI): void {
301
+ registerBoxTool(pi);
302
+ registerComputerUseTool(pi);
170
303
  pi.registerTool(
171
304
  defineTool({
172
305
  name: "classify",
173
306
  label: "Classify",
174
307
  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.",
308
+ "Ask a decision model typed questions about text, JSON and supported images. Legacy image paths are shared; named path/url descriptors require explicit {$image:id} references. Jev supports images in instructions/criteria; OpenAI supports instruction images and hosted URLs. Unsupported placements fail locally. 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
309
  promptSnippet:
177
310
  "Classify text, JSON or supported images into typed probabilistic decisions.",
178
311
  promptGuidelines: [
179
312
  "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.",
313
+ "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.",
314
+ "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
315
  "Send only data the user intends to share with the configured provider.",
182
316
  "Ask /classifier status for the active model. Do not change provider settings without user direction.",
183
317
  ],
@@ -216,7 +350,7 @@ export default function piClassifier(pi: ExtensionAPI): void {
216
350
  name: "classify_compare",
217
351
  label: "Compare classifiers",
218
352
  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.",
353
+ "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
354
  promptSnippet:
221
355
  "Compare configured decision models only when the user explicitly requests a model comparison.",
222
356
  promptGuidelines: [
@@ -249,6 +383,45 @@ export default function piClassifier(pi: ExtensionAPI): void {
249
383
  }),
250
384
  );
251
385
 
386
+ pi.registerTool(
387
+ defineTool({
388
+ name: "classify_tree",
389
+ label: "Classify tree",
390
+ description:
391
+ "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.",
392
+ promptSnippet: "Classify through a supplied classification tree and return the selected levels.",
393
+ promptGuidelines: [
394
+ "Use classify_tree only when the user supplies or requests a classification tree; do not invent category branches.",
395
+ "Use meaningful node descriptions. Only the current siblings and selected parent path are submitted per decision, not every descendant.",
396
+ "Inspect status and steps: automatic steps have no model confidence, and partial paths are not complete classifications.",
397
+ "Configured choice batching may cause multiple billable requests per level. No fallback may replay completed model decisions.",
398
+ ],
399
+ parameters: classifyTreeParameters,
400
+ outputSchema: classifyTreeOutput,
401
+ annotations: {
402
+ readOnlyHint: true,
403
+ destructiveHint: false,
404
+ openWorldHint: true,
405
+ },
406
+ async execute(_id, params, signal, _onUpdate, ctx) {
407
+ try {
408
+ const result = await classifyTree(params, {
409
+ settings: loadClassifierSettings(ctx.cwd, isProjectTrusted(ctx)),
410
+ cwd: ctx.cwd,
411
+ ...(signal ? { signal } : {}),
412
+ });
413
+ return {
414
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
415
+ details: result,
416
+ structuredContent: { ...result },
417
+ };
418
+ } catch (error) {
419
+ throw new Error(userError(error));
420
+ }
421
+ },
422
+ }),
423
+ );
424
+
252
425
  pi.registerCommand("classifier", {
253
426
  description:
254
427
  "Classifier: status, list, reload, use <route> <model>, compare <JSON params>. Use writes trusted project defaults; compare makes potentially billable calls.",
@@ -298,6 +471,9 @@ export default function piClassifier(pi: ExtensionAPI): void {
298
471
  images: route.images,
299
472
  box: route.box,
300
473
  requestTimeoutMs: route.requestTimeoutMs,
474
+ none_of_above_choice: settings.none_of_above_choice ?? false,
475
+ remove_choice_limits: settings.remove_choice_limits ?? false,
476
+ maxChoicesPerRequest: route.maxChoices ?? "provider-defined",
301
477
  authentication: "API key only; independent of chat login",
302
478
  fallback: configuredRoutes(settings, "fallback"),
303
479
  compare: configuredRoutes(settings, "compare"),
@@ -0,0 +1,77 @@
1
+ import { ClassifierError, isRecord, type ImageReference, type PreparedImage, type Question } from "./types.js";
2
+
3
+ export function isImageReference(value: unknown): value is ImageReference {
4
+ return isRecord(value) && Object.hasOwn(value, "$image");
5
+ }
6
+
7
+ /** Only explicit reference objects are special; provider-native-looking user JSON stays data. */
8
+ export function imageReferences(value: unknown): string[] {
9
+ if (isImageReference(value)) return [value.$image];
10
+ if (Array.isArray(value)) return value.flatMap(imageReferences);
11
+ if (isRecord(value)) return Object.values(value).flatMap(imageReferences);
12
+ return [];
13
+ }
14
+
15
+ export function questionImageReferences(questions: Record<string, Question>): string[] {
16
+ return Object.values(questions).flatMap((question) => [
17
+ ...imageReferences(question.instructions),
18
+ ...("criteria" in question && question.criteria ? Object.values(question.criteria).flatMap(imageReferences) : []),
19
+ ]);
20
+ }
21
+
22
+ export function mapImageReferences(value: unknown, image: (id: string) => unknown): unknown {
23
+ if (isImageReference(value)) return image(value.$image);
24
+ if (Array.isArray(value)) return value.map((entry) => mapImageReferences(entry, image));
25
+ if (isRecord(value)) return Object.fromEntries(
26
+ Object.entries(value).map(([key, entry]) => [key, mapImageReferences(entry, image)]),
27
+ );
28
+ return value;
29
+ }
30
+
31
+ export function namedImage(images: PreparedImage[], id: string): PreparedImage {
32
+ const image = images.find((entry) => entry.id === id);
33
+ if (!image) throw new ClassifierError("input", "Unknown named image reference.");
34
+ return image;
35
+ }
36
+
37
+ export function imageUrl(image: PreparedImage): string {
38
+ return "url" in image ? image.url : "data:" + image.mimeType + ";base64," + image.data;
39
+ }
40
+
41
+ /** Preserve JSON punctuation as text, interleaving only explicitly referenced images.
42
+ * Raw user objects never become provider-native content parts.
43
+ */
44
+ export function imageContentParts(
45
+ value: unknown,
46
+ image: (id: string) => unknown,
47
+ ): unknown[] {
48
+ const parts: unknown[] = [];
49
+ let text = "";
50
+ const flush = () => { if (text) { parts.push(text); text = ""; } };
51
+ const visit = (entry: unknown): void => {
52
+ if (isImageReference(entry)) { flush(); parts.push(image(entry.$image)); }
53
+ else if (Array.isArray(entry)) {
54
+ text += "[";
55
+ entry.forEach((child, i) => { if (i) text += ","; visit(child); });
56
+ text += "]";
57
+ } else if (isRecord(entry)) {
58
+ text += "{";
59
+ Object.entries(entry).forEach(([key, child], i) => {
60
+ if (i) text += ",";
61
+ text += JSON.stringify(key) + ":";
62
+ visit(child);
63
+ });
64
+ text += "}";
65
+ } else text += JSON.stringify(entry);
66
+ };
67
+ // Ordered content arrays are convenient for instructions and simple multimodal state.
68
+ if (Array.isArray(value) && value.every((entry) => typeof entry === "string" || isImageReference(entry))) {
69
+ for (const entry of value) {
70
+ if (typeof entry === "string") text += entry;
71
+ else { flush(); parts.push(image(entry.$image)); }
72
+ }
73
+ } else if (typeof value === "string") text = value;
74
+ else visit(value);
75
+ flush();
76
+ return parts;
77
+ }
package/src/index.ts CHANGED
@@ -1,14 +1,32 @@
1
1
  export { classify, compareClassifiers } from "./classify.js";
2
+ export type { ClassifyOptions } from "./classify.js";
3
+ export type { MemoryImage } from "./inputs.js";
4
+ export { runComputerUse } from "./computer-use.js";
5
+ export type { ComputerUseOptions } from "./computer-use.js";
6
+ export type { ComputerUseParams, ComputerUseResult, ComputerUseSettings, ComputerControl, ComputerExpectation, DriverCall, DriverReply } from "./computer-use-types.js";
7
+ export { classifyTree } from "./tree.js";
8
+ export { renderClassifierBox } from "./box.js";
9
+ export type { ClassifierBoxMode, ClassifierBoxEdges, ClassifierBoxPixelBox, ClassifierBoxResult } from "./box.js";
2
10
  export { loadClassifierSettings, resolveModel, listModels } from "./config.js";
3
11
  export type {
4
12
  Answer,
5
13
  Question,
14
+ QuestionContent,
15
+ ImageInput,
16
+ ImageReference,
6
17
  ClassifierResult,
18
+ ClassifierCost,
19
+ TokenPricing,
7
20
  ClassifierRoute,
8
21
  ClassifierComparisonEntry,
9
22
  ClassifierComparisonResult,
10
23
  ClassifierSettings,
11
24
  ClassifyParams,
25
+ ClassifyTreeParams,
26
+ ClassifierTreeResult,
27
+ ClassificationTree,
28
+ ClassificationTreeNode,
29
+ TreeStep,
12
30
  CustomProviderSettings,
13
31
  ModelDefinition,
14
32
  ProviderSettings,