@abhishek944/pi-classifier 0.0.0-stage → 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.
Files changed (50) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/LICENSE +201 -0
  3. package/README.md +425 -2
  4. package/THIRD_PARTY_NOTICES.md +48 -0
  5. package/dist/auth.d.ts +5 -0
  6. package/dist/auth.js +56 -0
  7. package/dist/choices.d.ts +8 -0
  8. package/dist/choices.js +131 -0
  9. package/dist/classification-tree.d.ts +4 -0
  10. package/dist/classification-tree.js +143 -0
  11. package/dist/classify.d.ts +10 -0
  12. package/dist/classify.js +120 -0
  13. package/dist/config.d.ts +82 -0
  14. package/dist/config.js +338 -0
  15. package/dist/cost.d.ts +8 -0
  16. package/dist/cost.js +202 -0
  17. package/dist/extension.d.ts +249 -0
  18. package/dist/extension.js +380 -0
  19. package/dist/http.d.ts +5 -0
  20. package/dist/http.js +85 -0
  21. package/dist/index.d.ts +5 -0
  22. package/dist/index.js +4 -0
  23. package/dist/inputs.d.ts +4 -0
  24. package/dist/inputs.js +184 -0
  25. package/dist/providers.d.ts +2 -0
  26. package/dist/providers.js +624 -0
  27. package/dist/settings-write.d.ts +10 -0
  28. package/dist/settings-write.js +110 -0
  29. package/dist/tree.d.ts +4 -0
  30. package/dist/tree.js +136 -0
  31. package/dist/types.d.ts +228 -0
  32. package/dist/types.js +18 -0
  33. package/dist/validation.d.ts +3 -0
  34. package/dist/validation.js +94 -0
  35. package/package.json +72 -4
  36. package/src/auth.ts +74 -0
  37. package/src/choices.ts +173 -0
  38. package/src/classification-tree.ts +181 -0
  39. package/src/classify.ts +167 -0
  40. package/src/config.ts +442 -0
  41. package/src/cost.ts +250 -0
  42. package/src/extension.ts +511 -0
  43. package/src/http.ts +108 -0
  44. package/src/index.ts +25 -0
  45. package/src/inputs.ts +239 -0
  46. package/src/providers.ts +905 -0
  47. package/src/settings-write.ts +145 -0
  48. package/src/tree.ts +157 -0
  49. package/src/types.ts +248 -0
  50. package/src/validation.ts +138 -0
package/README.md CHANGED
@@ -1,3 +1,426 @@
1
- # Temporary Holding Version
1
+ # pi-classifier
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A Pi extension for typed, probabilistic decisions across Microsoft Decision-1, OpenAI Decisions, Perplexity Decisions, TypeSafe Jev, Cloudflare Clef/Clef Flash and SystemOne-compatible gateways.
4
+
5
+ One configured default, optional selective fallback, and explicit model comparisons. No automatic retries or permission auto-approval.
6
+
7
+ ## Install
8
+
9
+ Requires Node.js 22.19+ and Pi 1.2+. Install the tagged release from GitHub:
10
+
11
+ ```sh
12
+ pi install git:github.com/abhishek944/pi-classifier@v0.3.0
13
+ ```
14
+
15
+ The Pi package entrypoint is TypeScript source, so Git installs do not depend on committed build artifacts or a TypeScript compiler. Runtime dependencies are installed by Pi. The compiled `dist` exports remain available for library consumers after a build.
16
+
17
+ ### Local development
18
+
19
+ From this package:
20
+
21
+ ```sh
22
+ npm install
23
+ npm run build
24
+ pi -e ./dist/extension.js
25
+ ```
26
+
27
+ To install persistently after trying it:
28
+
29
+ ```sh
30
+ pi install /absolute/path/to/pi-classifier
31
+ ```
32
+
33
+ The package version and Git tag are `0.3.0` / `v0.3.0`. Installation is explicit. This release is prepared for GitHub; npm publication is a separate manual step.
34
+
35
+ ## Configuration: same shape as pi-image-gen
36
+
37
+ Use the `pi-classifier` namespace in Pi settings. Like `pi-image-gen`, route selection uses `default: { provider, model }`, optional ordered `fallback` pairs, and explicit `compare` pairs. Legacy `defaultProvider` and `defaultModel` remain supported when `default` is absent; a present but malformed `default` fails closed. No settings are automatically migrated; credentials/endpoints are nested under `providers.<provider-id>`. Default selection happens after settings layers are merged: if a user/agent layer has a nested `default`, a project's legacy default keys do not override it. Use a nested `default` in the project too; mixed-format per-layer normalization is not implemented. The two extensions have independent settings and do not change one another.
38
+
39
+ ```json
40
+ {
41
+ "pi-classifier": {
42
+ "default": { "provider": "openai-api", "model": "gpt-6-luna" },
43
+ "fallback": [{ "provider": "typesafe-api", "model": "jev-latest" }],
44
+ "compare": [
45
+ { "provider": "openai-api", "model": "gpt-6-luna" },
46
+ { "provider": "typesafe-api", "model": "jev-latest" }
47
+ ],
48
+ "requestTimeoutMs": 30000,
49
+ "providers": {
50
+ "openai": { "apiKey": "${OPENAI_API_KEY}" },
51
+ "perplexity": { "apiKey": "${PERPLEXITY_API_KEY}" },
52
+ "typesafe": { "apiKey": "${TYPESAFE_API_KEY}" },
53
+ "cloudflare": {
54
+ "apiKey": "${CLOUDFLARE_API_KEY}",
55
+ "accountId": "${CLOUDFLARE_ACCOUNT_ID}"
56
+ },
57
+ "openrouter": { "apiKey": "${OPENROUTER_API_KEY}" }
58
+ }
59
+ }
60
+ }
61
+ ```
62
+
63
+ Put environment references and secrets in global/agent settings, not project settings. Global/agent environment interpolation follows `@amaster.ai/pi-shared/settings`. Trusted project settings override the namespace's top-level keys, but are never environment-expanded. Nested `providers` maps follow the shared loader's shallow-merge behavior. Untrusted project settings are ignored. Malformed settings or a null namespace fail closed. Settings must be UTF-8 without a BOM; unlike Pi's main loader, the shared extension loader does not support BOM-prefixed files, so this package reports an explicit error rather than silently using another configuration. Configure endpoint overrides only for services you trust: the selected endpoint receives the API key and submitted state.
64
+
65
+ Do not add placeholder API-key fields for keys you want loaded from Pi's credential store. Omit those fields instead.
66
+
67
+ ### API-key selection, independent of Codex login
68
+
69
+ Credential priority is:
70
+
71
+ 1. Non-empty `providers.<id>.apiKey` (or the custom provider's `apiKey`).
72
+ 2. Pi's stored `api_key` credential for the provider, using Pi's own credential-store path.
73
+ 3. The provider's environment variable.
74
+
75
+ OAuth credentials are never used as API keys, never refreshed by this extension, and never changed. You can remain logged in to Codex for chat while using `openai-api` for classifier calls. If the stored `openai` slot contains OAuth rather than an API key, the extension skips it and uses your configured or environment API key.
76
+
77
+ Pi keeps one credential per provider ID, not both OAuth and an API key in the same slot. An OpenAI key stored under `openai` is distinct from Codex login under `openai-codex`.
78
+
79
+ Stored API-key values support literal strings and `$NAME`/`${NAME}` references, including provider-scoped stored environment values before process environment values. A missing reference leaves the stored key unresolved rather than sending a partial key. Shell-command credentials are intentionally not executed. Credentials and headers are never printed by status/list. This stored-key support is an addition in the classifier package: the current image-gen API route reads configuration/environment keys, while its subscription route resolves Pi's OAuth login.
80
+
81
+ ### Providers and models
82
+
83
+ | Route | Provider settings key | Models | Environment key |
84
+ | ---------------- | --------------------- | ------------------------------------------------------------------ | -------------------- |
85
+ | `microsoft-api` | `microsoft` | `Microsoft-Decision-1` (select your actual deployment name) | `AZURE_API_KEY` |
86
+ | `openai-api` | `openai` | `gpt-6-luna` | `OPENAI_API_KEY` |
87
+ | `perplexity-api` | `perplexity` | `pplx-decider-v1.1-27b`, `pplx-decider-v1-27b` | `PERPLEXITY_API_KEY` |
88
+ | `typesafe-api` | `typesafe` | `jev-latest`, `jev-1.13.0`, `jev-preview`, `jev-1.14.0` | `TYPESAFE_API_KEY` |
89
+ | `cloudflare-api` | `cloudflare` | `@cf/cloudflare/clef`, `@cf/cloudflare/clef-flash`, `typesafe/jev` | `CLOUDFLARE_API_KEY` |
90
+ | `openrouter-api` | `openrouter` | `typesafe/jev-1.13`, `~typesafe/jev-latest` | `OPENROUTER_API_KEY` |
91
+
92
+ Cloudflare also needs `providers.cloudflare.accountId`, the stored `cloudflare-workers-ai` API-key credential's `env.CLOUDFLARE_ACCOUNT_ID`, or `CLOUDFLARE_ACCOUNT_ID`, in that order. Its stored API token lives under `cloudflare-workers-ai`, not `cloudflare`.
93
+
94
+ A provider's `baseUrl` replaces the API root (before `decisions`, `systemone`, Microsoft's `providers/microsoft/v1/systemone`, or Cloudflare's run path). Authentication/transport headers cannot be overridden. Custom headers are supported. HTTPS is required except for loopback HTTP.
95
+
96
+ New text model IDs on built-in routes can be selected without a package release. They must actually implement that route's API; a normal chat model is not a decision model. New image capabilities require a known model or explicit custom model declaration.
97
+
98
+ ## Use
99
+
100
+ ```text
101
+ /classifier list
102
+ /classifier status
103
+ /classifier use cloudflare-api @cf/cloudflare/clef-flash
104
+ /classifier reload
105
+ ```
106
+
107
+ `use` writes only the nested `default` into trusted project `.pi/settings.json`, removing local legacy default keys and preserving unrelated settings, `fallback`, and `compare`. The project must be trusted. All calls load current settings, so `reload` validates and displays the current route rather than maintaining a separate configuration cache. To change global defaults, edit the global `pi-classifier` settings.
108
+
109
+ The model calls:
110
+
111
+ ```js
112
+ classify({
113
+ state: { ticket: "Checkout fails for every customer." },
114
+ questions: {
115
+ urgent: { type: "bool", instructions: "Is this urgent?" },
116
+ team: {
117
+ type: "choice",
118
+ instructions: "Which team should handle this?",
119
+ criteria: {
120
+ billing: "Charges and refunds",
121
+ engineering: "Errors and outages",
122
+ },
123
+ },
124
+ severity: {
125
+ type: "score",
126
+ instructions: "How severe is the customer impact?",
127
+ criteria: ["Minor", "Major", "Critical"],
128
+ },
129
+ },
130
+ });
131
+ ```
132
+
133
+ The tool takes no provider/model parameter. Its structured result identifies the configured route and model, typed answers, reported token usage, estimated USD cost (or an explicit unavailable reason) and an available request ID. `bool.probability` is the probability of true; `choice` includes a probability per label and confidence; `score` is a probability-weighted level index (starting at zero), not necessarily an integer. Refusals are explicit typed answers. Token counts are reported when available. Each successful result includes `cost`; classifier spending is not added to Pi's session billing totals. See [Per-call costs](#per-call-costs).
134
+
135
+ Provider results are checked for probability ranges/distribution sums and decision consistency (selected choices must be most likely; supplied score distributions must match the expected score within rounding tolerance). Low confidence is a valid answer, not an error. Calibrate thresholds on your own data; scores from different providers are not interchangeable.
136
+
137
+ ## Classification trees: `classify_tree`
138
+
139
+ Use `classify_tree` to follow a **nested classification tree**, rather than supply every leaf as one flat choice list. The extension orchestrates ordinary model decisions; this is not a native provider tree API. Existing `classify` and `classify_compare` behavior is unchanged.
140
+
141
+ A classification tree is an object with `roots`. Each node has an `id`, optional `description`, and optional `children`:
142
+
143
+ ```json
144
+ {
145
+ "roots": [
146
+ {
147
+ "id": "a",
148
+ "description": "Describe the domain covered by category a and its descendants.",
149
+ "children": [
150
+ { "id": "b", "children": [{ "id": "c" }] },
151
+ { "id": "c", "children": [{ "id": "d" }] }
152
+ ]
153
+ },
154
+ { "id": "c" },
155
+ { "id": "d", "children": [{ "id": "e" }] }
156
+ ]
157
+ }
158
+ ```
159
+
160
+ IDs must be non-empty, at most 128 characters, and unique **among siblings**. Root `c` and `a > c` are different nodes. Descriptions are at most 4096 characters; use meaningful descriptions to explain which parent branch to choose. Missing or empty `children` means leaf. Only `roots`, `id`, `description` and `children` are supported; internal-node stopping flags, path-list imports and graph references are not implemented.
161
+
162
+ Supply the same shape inline or by local file:
163
+
164
+ ```js
165
+ classify_tree({
166
+ state: "The content to classify",
167
+ tree: "./classification-tree.json",
168
+ instructions: "Choose the most appropriate category for this content."
169
+ });
170
+
171
+ classify_tree({
172
+ state: { ticket: "Refund requested for a duplicate payment." },
173
+ tree: {
174
+ roots: [
175
+ { id: "billing", description: "Charges, invoices and refunds" },
176
+ { id: "technical", description: "Errors, outages and integration problems" }
177
+ ]
178
+ }
179
+ });
180
+ ```
181
+
182
+ `instructions` is optional and at most 8192 characters. Text/JSON `state` and optional local `images` use the existing classifier input rules. No provider/model override is accepted. The library exports `classifyTree(params, { settings, cwd, signal? })` and the `ClassificationTree`, `ClassificationTreeNode`, `ClassifyTreeParams`, `TreeStep` and `ClassifierTreeResult` types.
183
+
184
+ ### Traversal and results
185
+
186
+ The example first chooses among `a`, `c` and `d`. After choosing `a`, it chooses between `b` and `c`. If it chooses `b`, its sole child `c` is automatic. Relevant result fields are:
187
+
188
+ ```json
189
+ {
190
+ "status": "complete",
191
+ "levels": { "Level1": "a", "Level2": "b", "Level3": "c" },
192
+ "steps": [
193
+ { "level": 1, "id": "a", "source": "model", "confidence": 0.9, "probabilityScope": "siblings" },
194
+ { "level": 2, "id": "b", "source": "model", "confidence": 0.8, "probabilityScope": "siblings" },
195
+ { "level": 3, "id": "c", "source": "automatic" }
196
+ ],
197
+ "providerCalls": 2
198
+ }
199
+ ```
200
+
201
+ The confidence values above are illustrative. Full results also identify the configured/selected provider and model and include estimated `cost` plus reported `usage` when complete. Model confidence describes its sibling decision (or one batch), **not the whole path**. No artificial confidence is assigned to automatic steps.
202
+
203
+ - A sole sibling is followed automatically, including a sole root. This is structural inference, not model confirmation. It intentionally bypasses a possible NONE rejection of that sole option even when NONE is enabled.
204
+ - An entirely forced chain makes **zero provider calls**, needs no API key, and returns genuine zero token usage and estimated zero cost. It still requires a valid configured route. `complete` means a leaf was reached, not that the model verified the input fits that chain.
205
+ - NONE, strict ties and refusals stop the traversal with `status: "no_match"`, `"ambiguous"` or `"refusal"`. `levels` and `steps` retain only the selected prefix; no deeper category is fabricated. Exact top ties stop even when NONE is disabled.
206
+ - The selected parent path and current sibling descriptions inform each question. Unselected descendant branches are not uploaded wholesale, so parent descriptions must explain their coverage. Selection is greedy and cannot recover a wrong parent; no global best-path or calibrated path-probability claim is made.
207
+ - Configured NONE/batching behavior applies at each branching node. A wide level can consume multiple provider requests; `providerCalls`, usage and cost account for inner batches and all completed model decisions. Missing usage or unavailable prices do not become complete-looking numeric subtotals.
208
+ - The first actual decision may use configured selective fallback. After a successful decision the actual provider/model is pinned for the rest of that traversal; later failures do not replay completed levels on another route. Failures/cancellation may still have billed completed work. Images use the ordinary classifier validation and upload behavior on each branching call.
209
+
210
+ ### Local-file and size limits
211
+
212
+ Classification trees must fit **2 MiB and 32 levels**; the full node structure is validated before any model call. Local files must be valid UTF-8 JSON regular files inside the session cwd with no symlink path components or URLs. Descriptor-based containment checks reuse the existing local-image boundary and support macOS/Linux; inline classification tree works on other platforms. Files are read once per `classify_tree` invocation; no persistent classification tree registry or cache is introduced.
213
+
214
+ Original classifier state/image/request protections remain. Each constructed branch question must fit the existing input limits, including its selected-path context. Tree results are bounded to 40 KiB. User-owned live verification should compare inline and file inputs, zero-call chains, deeper NONE/tie outcomes, wide sibling batching, and provider billing totals.
215
+
216
+ ## Per-call costs
217
+
218
+ Every successful `classify` result and each successful `classify_compare` entry includes one of:
219
+
220
+ ```json
221
+ {
222
+ "cost": {
223
+ "status": "estimated",
224
+ "currency": "USD",
225
+ "input": 0.000042,
226
+ "output": 0,
227
+ "total": 0.000042,
228
+ "source": "builtin",
229
+ "rates": { "inputPerMillion": 0.042, "outputPerMillion": 0 }
230
+ }
231
+ }
232
+ ```
233
+
234
+ This example uses 1,000 Jev input tokens. Amounts are not rounded to cents; doing so would hide most classifier charges. `source` is `builtin` for the bundled standard public rates or `configured` for explicit rates. `rates` contains the effective USD-per-million rates used. Multi-call choice processing sums all completed calls and uses `source: "aggregated"` without a single misleading rates table; `providerCalls` reports the number of completed provider requests. Usage is omitted if any completed call lacks usage, and aggregate cost is unavailable if any call lacks an estimate. These are estimates, not provider invoices: taxes, credits, free allowances, account discounts and unreported billable activity are not included. There is no network pricing lookup.
235
+
236
+ | Official route/model | Input USD / 1M tokens | Output USD / 1M tokens |
237
+ | --- | ---: | ---: |
238
+ | OpenAI Decisions `gpt-6-luna` | 0.10 | 0 |
239
+ | TypeSafe `jev-1.13.0`, `jev-1.14.0`, `jev-latest`, `jev-preview` | 0.042 | 0 |
240
+ | Perplexity `pplx-decider-v1.2`, `pplx-decider-latest`, `pplx-decider-v1.1-27b`, `pplx-decider-v1-27b` | 0.02 | 0 |
241
+ | Perplexity `pplx-decider-flash-v1.2`, `pplx-decider-flash-latest` | 0.01 | 0 |
242
+ | Cloudflare `@cf/cloudflare/clef` | 0.24 | 0 |
243
+ | Cloudflare `@cf/cloudflare/clef-flash` | 0.038 | 0 |
244
+ | Cloudflare `typesafe/jev` | 0.042 | 0 |
245
+
246
+ Sources: [OpenAI Decisions pricing](https://developers.openai.com/api/docs/guides/decisions#pricing-and-availability), [OpenAI rates](https://developers.openai.com/api/docs/pricing), [TypeSafe models](https://docs.typesafe.ai/models), [Perplexity Decisions](https://docs.perplexity.ai/docs/decisions/quickstart#pricing), [Clef](https://developers.cloudflare.com/workers-ai/models/clef/), [Clef Flash](https://developers.cloudflare.com/workers-ai/models/clef-flash/), [Cloudflare Jev](https://developers.cloudflare.com/ai/models/typesafe/jev/). Aliases can move and public prices can change; explicit overrides take precedence. Perplexity's [model names](https://docs.perplexity.ai/docs/decisions/quickstart#model-names) documentation maps the older v1/v1.1 IDs in the discovery catalog to v1.2 and bills them at its rate. New text model IDs may already be selected through settings, but this cost feature does not change image capability declarations.
247
+
248
+ When reported, cache reads and writes are exposed as `usage.cachedInputTokens` and `usage.cacheWriteTokens`. They are **included** in input tokens, not additional tokens. Input cost is `(ordinary input × input rate + cache reads × cached-input rate + cache writes × cache-write rate) / 1,000,000`; output cost uses its separate rate. OpenAI's bundled cached-input rate is $0.01/M and default 30-minute write rate is $0.125/M, with all input rates doubled above 272,000 input tokens. Cloudflare Jev's bundled cached-input rate is zero. Unexpected 12-hour writes are unavailable rather than priced as 30-minute writes.
249
+
250
+ If pricing or usable token counts are missing, `cost` is `{ "status": "unavailable", "currency": "USD", "reason": "unknown_pricing" }` (or `missing_usage`, `invalid_usage`, `missing_cache_pricing`, `calculation_overflow`). No numeric amounts are returned in that case. Zero means a calculated zero, never an unknown charge. Failed or cancelled calls may still be billable but do not have reliable cost results; a fallback success reports only the successful request, not a total for prior attempts. Comparison callers must not treat a sum of available estimates as complete if any entries failed or have unavailable costs.
251
+
252
+ ### Explicit deployment, gateway and custom pricing
253
+
254
+ Set `providers.<id>.pricing` to a map keyed by the **selected model ID** (Azure deployment name for Microsoft). Rates are non-negative finite USD per million tokens; input and output rates are required. Cache rates are optional, but reported cache activity needs the matching rate. Configured rates replace, rather than merge with, bundled rates. Custom providers accept the same `pricing` map.
255
+
256
+ ```json
257
+ {
258
+ "pi-classifier": {
259
+ "providers": {
260
+ "microsoft": {
261
+ "pricing": {
262
+ "my-decision-deployment": {
263
+ "inputPerMillion": 0.1,
264
+ "outputPerMillion": 0
265
+ }
266
+ }
267
+ }
268
+ }
269
+ }
270
+ }
271
+ ```
272
+
273
+ The numbers above are illustrative, **not a claim about Azure pricing**. Use your deployment's actual rates. Optional keys are `cachedInputPerMillion` and `cacheWritePerMillion`. Overrides specify effective rates; no automatic long-context multiplier is applied to them. Microsoft deployments, OpenRouter, unverified model IDs and custom or regional endpoints require verified explicit rates. Built-in prices apply only to exact known models on their official endpoint; a compatible gateway does not inherit the upstream provider's price. Misconfigured selected rates fail before a request; missing rates do not prevent classification.
274
+
275
+ ## Choice limits by provider
276
+
277
+ The artificial **64-choice cap has been removed** from both runtime validation and the tool schema. Known official model routes use their documented 255-option wire maximum. Unknown model/endpoint limits are left to the provider unless you configure `providers.<id>.maxChoices` (also available on custom providers). The package still accepts **1–32 questions per call**. The 128-character limit applies to an option's name, not to the option count.
278
+
279
+ | Provider/model | Documented upstream choice options per question | Evidence/qualification |
280
+ | --- | --- | --- |
281
+ | TypeSafe Jev | Up to 255 | [Choice docs](https://docs.typesafe.ai/primitives/choice); current Jev service documentation |
282
+ | OpenAI Decisions `gpt-6-luna` | 2–255 | [API reference](https://developers.openai.com/api/reference/resources/decisions/methods/create), confirmed from official indexed search results; direct reference fetch returned 404 during this investigation |
283
+ | Perplexity `pplx-decider-v1.2`, Flash v1.2 and documented aliases (including catalog v1/v1.1 IDs) | 1–255 | [Request limits](https://docs.perplexity.ai/docs/decisions/quickstart#request-limits) and [model names](https://docs.perplexity.ai/docs/decisions/quickstart#model-names) |
284
+ | Cloudflare Clef | 2–255 | [Official input schema](https://developers.cloudflare.com/workers-ai/models/clef/schema-input.json) |
285
+ | Cloudflare Clef Flash | 2–255 | [Official input schema](https://developers.cloudflare.com/workers-ai/models/clef-flash/schema-input.json) |
286
+ | Cloudflare-hosted Jev | Not independently verified | Do not assume direct-TypeSafe limits apply to every gateway |
287
+ | Microsoft Decision-1 | Not specified in the fetched guide | [Foundry guide](https://learn.microsoft.com/en-us/azure/foundry/foundry-models/how-to/use-foundry-models-microsoft-decision) |
288
+ | OpenRouter-hosted Jev / custom routes | Endpoint-dependent; not verified | Requires the selected gateway/model's contract |
289
+
290
+ A documented upstream maximum is not a live deployment guarantee. Limits are matched to known model IDs on official endpoints; other deployments and gateways must not silently inherit an upstream model's limit. A configured `maxChoices` must be a safe integer of at least 2 and must reflect that endpoint's actual capability.
291
+
292
+ ### Optional NONE and sequential choice batching
293
+
294
+ Both settings default to `false`:
295
+
296
+ ```json
297
+ {
298
+ "pi-classifier": {
299
+ "none_of_above_choice": true,
300
+ "remove_choice_limits": true
301
+ }
302
+ }
303
+ ```
304
+
305
+ `remove_choice_limits: true` **requires** `none_of_above_choice: true`. Both `classify` and `classify_compare` reject an invalid pair before any provider request, with:
306
+
307
+ ```text
308
+ remove_choice_limits requires none_of_above_choice: true. No classifier request was sent.
309
+ ```
310
+
311
+ With only `none_of_above_choice` enabled, the extension adds a collision-safe internal NONE option to every choice question. That option consumes one slot: a 255-option provider can accept 254 real choices plus NONE in a single request. If the list exceeds that capacity while `remove_choice_limits` is false, the call fails locally with instructions to enable both flags or reduce the list.
312
+
313
+ With both flags enabled, the extension walks the choices in their JavaScript/JSON object enumeration order, sending at most `maxChoices - 1` real choices plus NONE per batch. On a 255-option model this is **254 + 1**. A question advances only if NONE's probability is **strictly greater than every real option's probability**, not merely because the provider picked NONE and not necessarily greater than 50%. A unique real winner ends that question. An exact tie for top probability returns `{ "type": "ambiguous" }`. If all batches reject, the answer is `{ "type": "no_match" }`. Typed refusals stop that question without advancing.
314
+
315
+ Batching is **sequential first-match selection**, not a global best-choice guarantee. An early acceptable result can hide a better later option, and NONE itself can be unreliable. Returned choice probabilities cover only the winning batch's real options, with `probabilityScope: "batch"` and a separate `noneOfAboveProbability`; those real probabilities plus NONE sum to approximately one. Unseen options are not assigned fabricated zeros. The internal NONE label is never returned as the selected real choice. Ordinary calls without these flags retain their previous answer shapes.
316
+
317
+ Multiple choice questions progress independently in shared rounds; settled questions and bool/score/box questions are not resent. Images are prepared once per selected route and included in the required requests. Each request may be billed. Usage and estimated cost cover all completed calls in a successful result, with `providerCalls` for transparency. A multi-call result omits a single `requestId` because no one ID represents every request. If a later request fails after partial completion, the operation may have incurred charges; HTTP 401/404/429 after completed batches does not replay the operation on a fallback route.
318
+
319
+ For an endpoint without a known limit, automatic batching fails before any request until you set its verified `providers.<id>.maxChoices` or `customProviders.<id>.maxChoices`. This setting does not remove context-window, input-byte, image, output-size, timeout or cancellation protections. The 2 MiB original text/questions limit and 40 KiB returned-result limit remain in place. No automatic tree construction, retrieval, hidden model switching or cross-batch probability normalization is performed.
320
+
321
+ ## Microsoft Decision-1 on Foundry
322
+
323
+ Deploy `Microsoft-Decision-1` in Microsoft Foundry, then configure the **resource endpoint**, API key, and actual **deployment name**:
324
+
325
+ ```json
326
+ {
327
+ "pi-classifier": {
328
+ "default": { "provider": "microsoft-api", "model": "my-decision-deployment" },
329
+ "providers": {
330
+ "microsoft": {
331
+ "baseUrl": "https://YOUR-RESOURCE.services.ai.azure.com",
332
+ "apiKey": "${AZURE_API_KEY}"
333
+ }
334
+ }
335
+ }
336
+ }
337
+ ```
338
+
339
+ The extension appends `/providers/microsoft/v1/systemone` and uses the `api-key` header, not bearer API-key authentication. The catalog name is only a discovery entry: `model` must match your deployment, which may have another name. Microsoft currently supports text/JSON bool (wire type `noul`), choice, and score; images and box are rejected locally. Entra token authentication is not implemented. The selected deployment is reported in results even if Foundry returns a different underlying model name. If Microsoft omits confidence, choice confidence is derived from the selected probability and score confidence from the largest level probability. The official guide does not include a complete response JSON example; verify actual bool/choice/score responses on your deployment before relying on this integration.
340
+
341
+ ## Fallback and explicit comparison
342
+
343
+ `classify` uses the default first. It tries configured `fallback` entries in order **only** after a missing API key or an explicit HTTP **401, 404, or 429**. Each resolved endpoint/model is selected at most once in the fallback chain; explicitly configured choice batching can make multiple requests on that selected route. When fallback is exercised, `attemptedRoutes` identifies the routes considered, including missing-key failures.
344
+
345
+ No automatic fallback occurs after 403/policy refusal, 400/422, 5xx, timeout, network failure, cancellation, malformed answers, input/capability/configuration errors, low confidence, or typed refusals. Each candidate validates the original input against its own capabilities; incompatible images or box questions stop the chain, never silently drop input. Every attempted request has its own timeout. Crossing billing providers and sharing state with them happens only through explicitly configured route pairs. Omit `fallback` or use `[]` to disable it.
346
+
347
+ Use **`classify_compare`** only when you explicitly want a model comparison. It accepts the same `{ state, questions, images? }` as `classify`, runs exactly the entries in `compare` sequentially, and never substitutes the default, uses fallback, or changes settings. Every entry is a separate potentially billable classification; configured choice batching can make multiple provider requests for that entry. Responses contain labeled `results` with status, duration in milliseconds, typed answers/token usage and estimated cost (or an unavailable reason) on success, or safe errors. A failed entry does not discard successes. Duplicate endpoint/model entries report an error without another call. Cancellation retains completed results, records an in-flight cancellation when present, sets `cancelled`, and prevents later requests. Scores from different models are not assumed to be calibrated equally.
348
+
349
+ You can also run `/classifier compare <JSON params>`, for example:
350
+
351
+ ```text
352
+ /classifier compare {"state":"Checkout is down.","questions":{"urgent":{"type":"bool","instructions":"Is this urgent?"}}}
353
+ ```
354
+
355
+ The library exports `compareClassifiers(params, { settings, cwd, signal? })`. Neither tool accepts provider/model overrides. A missing or empty `compare` list is a configuration error and makes no calls. Comparison output can be larger than a single result; use the tool rather than the command for full structured results (command messages are truncated to 16,000 characters).
356
+
357
+ ### Images and experimental Jev box answers
358
+
359
+ Pass `images: ["photo.png"]`. Images are attached in order alongside state. OpenAI, Perplexity and Clef/Clef Flash support images. Cloudflare-hosted Jev and the built-in OpenRouter route are text-only in this package.
360
+
361
+ Image inputs are local non-animated PNG/JPEG/WebP regular files inside the session cwd, with no symlink components, URLs or inline base64. Safe descriptor-based loading currently supports macOS (requires the OS `/usr/sbin/lsof`) and Linux (`/proc`); other platforms support text classification only. Images are fully decoded locally before upload. Limits: five images; 5 MiB each, 10 MiB total and 16 megapixels each. Clef has stricter limits: four images, 4 MiB each and 8 MiB total. Perplexity requires at most 2048 tiles of 32×32 pixels per image; resize before sending. Images are not silently resized. Text/JSON plus questions are limited to 2 MiB, with at most 32 questions per call.
362
+
363
+ TypeSafe Jev images are experimental and require opt-in. Use PNG/JPEG. Each side must be 256–1568 pixels, with total area 78,400–2,458,624 pixels; resize or pad beforehand. These limits also apply to custom SystemOne image routes using Jev's assets protocol:
364
+
365
+ ```json
366
+ {
367
+ "pi-classifier": {
368
+ "defaultProvider": "typesafe-api",
369
+ "defaultModel": "jev-preview",
370
+ "providers": {
371
+ "typesafe": {
372
+ "experimentalImages": true,
373
+ "experimentalBox": true
374
+ }
375
+ }
376
+ }
377
+ }
378
+ ```
379
+
380
+ With an image, a question such as `{ "type": "box", "instructions": "Find the mug in the first image." }` returns normalized `top`, `bottom`, `left`, `right` edges and confidence. Box needs Jev 1.14 (`jev-preview` or `jev-1.14.0`) and both opt-ins. It is not production-grade localization. A box does not mean the object exists: pair it with a bool existence question when necessary.
381
+
382
+ ## Custom providers
383
+
384
+ Like image-gen, `customProviders` adds a named endpoint and explicit model list. Supported protocols are `openai-decisions`, `perplexity-decisions`, `system-one`, `cloudflare-system-one`, and `microsoft-system-one` (Foundry resource root and API-key authentication). A custom URL cannot make an arbitrary API compatible. Custom IDs must not shadow built-in provider/route IDs.
385
+
386
+ ```json
387
+ {
388
+ "pi-classifier": {
389
+ "defaultProvider": "local-decisions",
390
+ "defaultModel": "my-decision-model",
391
+ "customProviders": {
392
+ "local-decisions": {
393
+ "api": "system-one",
394
+ "baseUrl": "http://127.0.0.1:8133/v1",
395
+ "apiKey": "${LOCAL_DECISIONS_KEY}",
396
+ "models": [{ "id": "my-decision-model", "input": ["text"] }]
397
+ }
398
+ }
399
+ }
400
+ }
401
+ ```
402
+
403
+ Custom endpoints use their route ID as the Pi stored-credential provider ID. They have no implicit environment variable; use an explicit key reference. SystemOne image endpoints must implement Jev's assets protocol, declare image input and opt into `experimentalImages`. Box additionally requires `box: true` on the model and `experimentalBox: true` on the provider.
404
+
405
+ ## Development and live verification
406
+
407
+ ```sh
408
+ npm run typecheck
409
+ npm run build
410
+ npm pack --dry-run
411
+ ```
412
+
413
+ No provider calls are made by these commands. Live tests belong to the user:
414
+
415
+ 1. Keep Codex logged in and configure an OpenAI API key. Select `openai-api/gpt-6-luna`, classify one bool, and verify chat login did not change.
416
+ 2. Select each provider and ask bool/choice/score questions; check probabilities, selected model and usage.
417
+ 3. Try a small PNG on OpenAI, Perplexity and Clef. Enable Jev images explicitly before trying its preview; verify box coordinates separately.
418
+ 4. Cancel an in-flight call and check a deliberately invalid model/key. Errors must be safe; only missing keys and HTTP 401/404/429 may select an explicitly configured fallback. Timeout/network/403/5xx/malformed results must not trigger another route.
419
+ 5. Use `/classifier use` in a trusted project and confirm unrelated settings and both route lists remain intact. Check legacy-only defaults as well as nested defaults.
420
+ 6. Configure your Foundry endpoint and deployment name, select `microsoft-api`, and verify bool/choice/score responses and token usage. Verify an image is rejected locally.
421
+ 7. Configure two `compare` pairs and explicitly invoke `classify_compare`; confirm labeled successes/errors, duration, unchanged defaults, and that cancellation prevents subsequent calls. Each valid entry may be billed.
422
+ 8. In your own controlled deployment, verify missing keys and HTTP 401/404/429 allow only configured fallbacks; duplicate routes are never called twice. Verify low confidence and refusals return normally without switching models.
423
+
424
+ Provider schemas and previews can change; no live entitlement or model-accuracy claim is made by a local build.
425
+
426
+ Sources: [Microsoft Decision-1](https://learn.microsoft.com/en-us/azure/foundry/foundry-models/how-to/use-foundry-models-microsoft-decision), [OpenAI Decisions](https://developers.openai.com/api/docs/guides/decisions), [Perplexity Decisions](https://docs.perplexity.ai/docs/decisions/quickstart), [TypeSafe images](https://docs.typesafe.ai/images), [TypeSafe box](https://docs.typesafe.ai/primitives/box), [Cloudflare Clef](https://developers.cloudflare.com/workers-ai/models/clef/).
@@ -0,0 +1,48 @@
1
+ # Third-party notices
2
+
3
+ ## Pi
4
+
5
+ Provider protocol mappings were informed by the Pi classifier adapters:
6
+
7
+ - https://github.com/earendil-works/pi/tree/main/packages/ai/src/api
8
+ - OpenAI Decisions and SystemOne/Cloudflare classification adapters.
9
+
10
+ MIT License
11
+
12
+ Copyright (c) 2025 Mario Zechner
13
+
14
+ Permission is hereby granted, free of charge, to any person obtaining a copy
15
+ of this software and associated documentation files (the "Software"), to deal
16
+ in the Software without restriction, including without limitation the rights
17
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
18
+ copies of the Software, and to permit persons to whom the Software is
19
+ furnished to do so, subject to the following conditions:
20
+
21
+ The above copyright notice and this permission notice shall be included in all
22
+ copies or substantial portions of the Software.
23
+
24
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
25
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
26
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
27
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
28
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
29
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
30
+ SOFTWARE.
31
+
32
+ ## pi-image-gen
33
+
34
+ The configuration conventions and safe atomic project-settings writer follow the sibling pi-image-gen extension:
35
+
36
+ - https://github.com/abhishek944/pi-image-gen
37
+ - Licensed under Apache License 2.0. See LICENSE.
38
+ - Its original extension attribution is TGYD-helige/pi, packages/pi-image-gen (Apache License 2.0).
39
+
40
+ No Codex image transport, UPNG, or sprite-generation code is included here.
41
+
42
+ ## Sharp and libvips
43
+
44
+ Sharp validates and decodes local image inputs:
45
+
46
+ - https://github.com/lovell/sharp
47
+ - Sharp is Apache License 2.0; its package includes its license and dependency notices.
48
+ - Its native dependencies include libvips (LGPL-2.1-or-later) and image codecs, whose packages include their applicable licenses/notices. They are dependencies, not embedded in this package's tarball.
package/dist/auth.d.ts ADDED
@@ -0,0 +1,5 @@
1
+ import { type ResolvedModel } from "./types.js";
2
+ /** Read the API-key entry only. Never resolve OAuth or mutate Pi's login state. */
3
+ export declare function storedApiCredential(provider: string): import("@earendil-works/pi-ai").ApiKeyCredential | undefined;
4
+ export declare function resolveApiKey(route: ResolvedModel): string;
5
+ export declare function cloudflareAccountId(configured: string | undefined): string;
package/dist/auth.js ADDED
@@ -0,0 +1,56 @@
1
+ import { readStoredCredential } from "@earendil-works/pi-coding-agent";
2
+ import { ClassifierError } from "./types.js";
3
+ /** Read the API-key entry only. Never resolve OAuth or mutate Pi's login state. */
4
+ export function storedApiCredential(provider) {
5
+ try {
6
+ const value = readStoredCredential(provider);
7
+ return value?.type === "api_key" ? value : undefined;
8
+ }
9
+ catch {
10
+ throw new ClassifierError("credentials", "Could not read Pi API-key credentials.");
11
+ }
12
+ }
13
+ function storedValue(value, env = {}) {
14
+ if (!value?.trim())
15
+ return undefined;
16
+ value = value.trim();
17
+ if (value.startsWith("!")) {
18
+ throw new ClassifierError("credentials", "Stored API-key shell commands are not supported. Use a literal key or an environment reference.");
19
+ }
20
+ let missing = false;
21
+ const resolved = value.replace(/\$\$|\$!|\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)/g, (match, braced, bare) => {
22
+ if (match === "$$")
23
+ return "$";
24
+ if (match === "$!")
25
+ return "!";
26
+ const name = braced ?? bare ?? "";
27
+ const replacement = env[name] ?? process.env[name];
28
+ if (!replacement)
29
+ missing = true;
30
+ return replacement ?? "";
31
+ });
32
+ return missing ? undefined : resolved.trim() || undefined;
33
+ }
34
+ export function resolveApiKey(route) {
35
+ if (route.configuredApiKey)
36
+ return route.configuredApiKey;
37
+ const credential = storedApiCredential(route.credentialProvider);
38
+ const key = storedValue(credential?.key, credential?.env) ??
39
+ (route.envVar ? process.env[route.envVar]?.trim() : undefined);
40
+ if (!key) {
41
+ throw new ClassifierError("missing_credentials", "No API key is configured for the selected classifier. Set providers.<id>.apiKey, save an API-key credential in Pi, or set the provider environment variable. Codex/OAuth tokens are not used.");
42
+ }
43
+ return key;
44
+ }
45
+ export function cloudflareAccountId(configured) {
46
+ const stored = configured
47
+ ? undefined
48
+ : storedApiCredential("cloudflare-workers-ai");
49
+ const id = configured?.trim() ??
50
+ storedValue(stored?.env?.CLOUDFLARE_ACCOUNT_ID, stored?.env) ??
51
+ process.env.CLOUDFLARE_ACCOUNT_ID?.trim();
52
+ if (!id || !/^[a-zA-Z0-9_-]+$/.test(id)) {
53
+ throw new ClassifierError("configuration", "Cloudflare requires a valid accountId or CLOUDFLARE_ACCOUNT_ID.");
54
+ }
55
+ return id;
56
+ }
@@ -0,0 +1,8 @@
1
+ import { type ClassifierResult, type ClassifierSettings, type PreparedInput, type Question, type ResolvedModel } from "./types.js";
2
+ export type ChoicePolicy = {
3
+ none: boolean;
4
+ batch: boolean;
5
+ };
6
+ export declare function choicePolicy(settings: ClassifierSettings): ChoicePolicy;
7
+ /** Only this operation owns batching. Transport, images, credentials and routes stay with the caller. */
8
+ export declare function executeChoices(input: PreparedInput, route: ResolvedModel, policy: ChoicePolicy, call: (questions: Record<string, Question>) => Promise<ClassifierResult>, signal?: AbortSignal): Promise<ClassifierResult>;