@abhishek944/pi-classifier 0.4.0 → 0.5.1

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 (58) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/README.md +269 -31
  3. package/dist/auth.d.ts +4 -2
  4. package/dist/auth.js +18 -2
  5. package/dist/box-tool.d.ts +2 -24
  6. package/dist/box-tool.js +5 -35
  7. package/dist/choices.js +35 -1
  8. package/dist/classify.d.ts +3 -0
  9. package/dist/classify.js +3 -3
  10. package/dist/config.d.ts +140 -3
  11. package/dist/config.js +401 -20
  12. package/dist/cost.js +42 -4
  13. package/dist/durable.d.ts +34 -0
  14. package/dist/durable.js +237 -0
  15. package/dist/extension.d.ts +2 -275
  16. package/dist/extension.js +49 -211
  17. package/dist/extract.d.ts +11 -0
  18. package/dist/extract.js +191 -0
  19. package/dist/http.d.ts +6 -1
  20. package/dist/http.js +64 -28
  21. package/dist/index.d.ts +3 -1
  22. package/dist/index.js +1 -0
  23. package/dist/inputs.d.ts +16 -1
  24. package/dist/inputs.js +421 -14
  25. package/dist/mcp-cli.d.ts +2 -0
  26. package/dist/mcp-cli.js +39 -0
  27. package/dist/mcp-server.d.ts +28 -0
  28. package/dist/mcp-server.js +121 -0
  29. package/dist/mcp-tool-definitions.d.ts +19 -0
  30. package/dist/mcp-tool-definitions.js +64 -0
  31. package/dist/providers.d.ts +1 -0
  32. package/dist/providers.js +1144 -53
  33. package/dist/tool-contracts.d.ts +785 -0
  34. package/dist/tool-contracts.js +530 -0
  35. package/dist/tree.js +1 -1
  36. package/dist/types.d.ts +284 -8
  37. package/dist/validation.js +122 -10
  38. package/package.json +34 -6
  39. package/src/auth.ts +26 -2
  40. package/src/box-tool.ts +12 -47
  41. package/src/choices.ts +42 -1
  42. package/src/classify.ts +6 -4
  43. package/src/config.ts +450 -23
  44. package/src/cost.ts +42 -4
  45. package/src/durable.ts +298 -0
  46. package/src/extension.ts +75 -288
  47. package/src/extract.ts +228 -0
  48. package/src/http.ts +63 -32
  49. package/src/index.ts +15 -0
  50. package/src/inputs.ts +454 -13
  51. package/src/mcp-cli.ts +44 -0
  52. package/src/mcp-server.ts +179 -0
  53. package/src/mcp-tool-definitions.ts +104 -0
  54. package/src/providers.ts +1323 -56
  55. package/src/tool-contracts.ts +785 -0
  56. package/src/tree.ts +1 -1
  57. package/src/types.ts +231 -5
  58. package/src/validation.ts +114 -9
package/CHANGELOG.md CHANGED
@@ -1,5 +1,38 @@
1
1
  # Changelog
2
2
 
3
+ ## Unreleased
4
+
5
+ - Added verified built-in routes for Vercel AI Gateway, Google Gemini Decision 1, Inception Mercury Decide, Parallel Decisions, OpenRouter alpha Decisions and Extractions, LiteLLM extraction, and self-hosted llama.cpp/vLLM/Strands/Laya/Nimble System One runtimes with explicit capability tiers.
6
+ - Added Microsoft Foundry Decision-1.1 image assets and Entra bearer auth, TypeSafe long context, Liquid JSON `path` metadata, Clairic image rotation, OpenAI native `input_json`/boolean choices/score descriptions/image detail/prompt-cache controls, and per-route question/media limits.
7
+ - Generalized `classify_extract` to direct Cloudflare Clairic, OpenRouter alpha Extractions and LiteLLM `/v1/extraction`; added an Inception `extract` question primitive and Parallel request-wide citations.
8
+ - Reported gateway/provider charges separately as `providerCost` without replacing the token estimate. Perplexity `maxStaleness` was removed because upstream documents it as ignored.
9
+ - Corrected the legacy `openrouter` alias, native Gemini text blocks, Gemini/local A/V gates, shared images with OpenAI conversations, Inception extract sources and mixed questions, OpenRouter hosted URLs and `d1.2-ultra` images, cache breakpoints, OpenAI's 400-question limit, boolean NONE sentinels, and per-route extraction media and field schemas.
10
+ - Tightened OpenRouter extraction validation to the published model tiers and rejected nested image references, mixed ScaleDown text/asset requests and multi-asset ScaleDown requests before dispatch.
11
+ - Added `providers.cloudflare.gatewayId` for Cloudflare decision and extraction routes; it emits the documented `cf-aig-gateway-id` header and takes precedence over an equivalent custom header.
12
+ - Fixed OpenAI Decisions image input to include the documented `type: "message"` item field, which keeps the payload compatible with LiteLLM's `/v1/decisions` route.
13
+ - Documented verified LiteLLM decision gateways, OpenRouter pricing/choice overrides and Cloudflare gateway settings without adding unverified endpoint support or prices. The LiteLLM example uses `customProviders` because unknown route IDs under `providers` are rejected.
14
+ - Added Sarvam Prism through `sarvam-api` / `sarvam-prism` with `SARVAM_API_KEY`, the documented `api-subscription-key` header, `noul`/choice/score mapping, validated probabilities and safe provider error details. The route is text-only, explicit selection is required, and USD pricing needs an override because the published rate is in INR.
15
+ - Sarvam error field paths and request IDs are omitted when they echo the active API key, and Sarvam score answers now require the documented probability distribution without changing other providers' optional-probability behavior. Response-header request IDs are sanitized for Sarvam only, then fall back to the body request ID.
16
+ - Added Perplexity Decider v1.3 and Flash v1.3 to the built-in catalog, pricing and 255-choice limits. `latest` aliases now resolve to v1.3 upstream.
17
+ - Added Perplexity `locate` answers with Unicode-character spans and explicit `web_grounding`/`maxStaleness` support, including search evidence and documented non-token fee accounting.
18
+ - Added Liquid `d1.2` and `d1.2-ultra` with typed text/number/date reads, `spans`, `box`/`boxes`, ranged estimates, multi-select choices, top-level image/audio uploads and public pricing.
19
+ - Added Cloudflare `@cf/cloudflare/clef-omni` with local audio/video inputs and verified media limits, preserving the model-specific Clef wire branch.
20
+ - Added Cloudflare Clairic extraction through `classify_extract`, with documented field contracts, images/PDFs, grounding metadata, truncation reporting and scheduled pricing.
21
+ - Clairic caller options `includeQuantiles` and `returnStateText` are translated to the provider's documented `include_quantiles` and `return_state_text` wire keys.
22
+ - Liquid multi-select probabilities no longer require a sum of one, estimate ranges and intervals allow negative/fractional numbers, and unparseable number/date values preserve documented `found`/`text`/`span` metadata instead of collapsing to `no_match`.
23
+ - NONE-choice batching now preserves Perplexity web evidence from every call, rebases `locate.searchResult` indices onto the combined evidence, and no longer drops `result.webGrounding`.
24
+ - Shared desktop and Durable tool schemas were updated together. Model-facing JSON Schema avoids `$ref` fragments for `classify_extract` and `classify_tree`; recursive validation stays in runtime code. No live provider calls, paid usage, commits or unit tests were made for these changes.
25
+
26
+ ## 0.4.1
27
+
28
+ - Added `@abhishek944/pi-classifier/durable`, a settings-only native Durable extension named `classifier` that registers `classify`, `classify_compare`, `classify_tree`, and `classifier_box_image`.
29
+ - Tool names, descriptions and parameter/result schemas are shared with the desktop extension through `src/tool-contracts.ts`, so the two surfaces cannot drift; desktop-only registration fields stay with the desktop extension.
30
+ - Native credentials are explicit only (`providers.<id>.apiKey`, Cloudflare `accountId`, or the provider environment variable). The native path never reads Pi settings files or stored API-key credentials, and there are no admission, quota, authorization, or host callbacks.
31
+ - `classify`, `classify_compare` and `classify_tree` are marked `replay: "unsafe"` so uncertain or billable executions are never replayed; `classifier_box_image` stays a pure local render marked `replay: "safe"`. Cancellation follows the invocation abort signal.
32
+ - `classifier_computer_use` is not registered natively because Durable 1.1.0 exposes no generic tool-invocation API for Driver calls between decisions; no placeholder is shipped and the desktop extension remains the computer-use surface.
33
+
34
+ Verification: typecheck, build and package dry run passed. No unit tests or live provider calls were run for this release.
35
+
3
36
  ## 0.4.0
4
37
 
5
38
  - Added the opt-in OpenAI Decisions `classifier_computer_use` tool for a bounded observe/select/act/verify loop through existing Cua Driver MCP tools and Pi permission hooks, without changing the normal classifier default.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # pi-classifier
2
2
 
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.
3
+ A Pi extension for typed, probabilistic decisions across Microsoft Foundry Decision-1.1, OpenAI Decisions, Perplexity Decisions, Sarvam Prism, TypeSafe Jev, Liquid d1.2, Cloudflare Clef/Clef Flash/Clef-omni, Google Gemini Decision 1, Inception Mercury Decide, Parallel Decisions, OpenRouter alpha Decisions, Vercel AI Gateway, self-hosted System One runtimes, and Clairic-shaped extraction. It also exposes Perplexity text-span location and web grounding, grounded Parallel citations, and typed reads from supported models.
4
4
 
5
5
  One configured default, optional selective fallback, and explicit model comparisons. No automatic retries or permission auto-approval.
6
6
 
@@ -9,7 +9,7 @@ One configured default, optional selective fallback, and explicit model comparis
9
9
  Requires Node.js 22.19+ and Pi 1.2+. Install the tagged release from GitHub:
10
10
 
11
11
  ```sh
12
- pi install git:github.com/abhishek944/pi-classifier@v0.4.0
12
+ pi install git:github.com/abhishek944/pi-classifier@v0.4.1
13
13
  ```
14
14
 
15
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.
@@ -30,7 +30,7 @@ To install persistently after trying it:
30
30
  pi install /absolute/path/to/pi-classifier
31
31
  ```
32
32
 
33
- The package version and Git tag are `0.4.0` / `v0.4.0`. Installation is explicit. This release is prepared for GitHub; npm publication is a separate manual step.
33
+ The package version and Git tag are `0.4.1` / `v0.4.1`. Installation is explicit. This release is prepared for GitHub; npm publication is a separate manual step.
34
34
 
35
35
  ## Configuration: same shape as pi-image-gen
36
36
 
@@ -49,10 +49,13 @@ Use the `pi-classifier` namespace in Pi settings. Like `pi-image-gen`, route sel
49
49
  "providers": {
50
50
  "openai": { "apiKey": "${OPENAI_API_KEY}" },
51
51
  "perplexity": { "apiKey": "${PERPLEXITY_API_KEY}" },
52
+ "sarvam": { "apiKey": "${SARVAM_API_KEY}" },
52
53
  "typesafe": { "apiKey": "${TYPESAFE_API_KEY}" },
54
+ "liquid": { "apiKey": "${LIQUID_API_KEY}" },
53
55
  "cloudflare": {
54
56
  "apiKey": "${CLOUDFLARE_API_KEY}",
55
- "accountId": "${CLOUDFLARE_ACCOUNT_ID}"
57
+ "accountId": "${CLOUDFLARE_ACCOUNT_ID}",
58
+ "gatewayId": "${CLOUDFLARE_AI_GATEWAY_ID}"
56
59
  },
57
60
  "openrouter": { "apiKey": "${OPENROUTER_API_KEY}" }
58
61
  }
@@ -80,20 +83,50 @@ Stored API-key values support literal strings and `$NAME`/`${NAME}` references,
80
83
 
81
84
  ### Providers and models
82
85
 
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.2`, `pplx-decider-flash-v1.2`, latest aliases, legacy v1/v1.1 IDs | `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.
86
+ | Route | Provider settings key | Models | Credential |
87
+ | --- | --- | --- | --- |
88
+ | `microsoft-api` | `microsoft` | `Microsoft-Decision-1.1`, legacy `Microsoft-Decision-1`; use your deployment name | `AZURE_API_KEY` or Entra token via `authMode: "bearer"` |
89
+ | `openai-api` | `openai` | `gpt-6-luna` | `OPENAI_API_KEY` |
90
+ | `vercel-api` | `vercel` | `openai/gpt-6-luna-decisions`, `typesafe-ai/jev` | `VERCEL_AI_GATEWAY_API_KEY` |
91
+ | `gemini-api` | `gemini` | `gemini-decision-1` | `GEMINI_API_KEY` |
92
+ | `inception-api` | `inception` | `mercury-decide` | `INCEPTION_API_KEY` |
93
+ | `parallel-api` | `parallel` | `parallel-decisions` | `PARALLEL_API_KEY` |
94
+ | `perplexity-api` | `perplexity` | v1.3, Flash v1.3, v1.2, latest aliases, legacy v1/v1.1 IDs | `PERPLEXITY_API_KEY` |
95
+ | `sarvam-api` | `sarvam` | `sarvam-prism` | `SARVAM_API_KEY` |
96
+ | `liquid-api` | `liquid` | `d1.2`, `d1.2-ultra` | `LIQUID_API_KEY` |
97
+ | `typesafe-api` | `typesafe` | `jev-latest`, `jev-1.13.0`, `jev-preview`, `jev-1.14.0` | `TYPESAFE_API_KEY` |
98
+ | `cloudflare-api` | `cloudflare` | Clef, Clef Flash, Clef-omni, `typesafe/jev` | `CLOUDFLARE_API_KEY` |
99
+ | `clairic-api` | `cloudflare` | `@cf/cloudflare/clairic` | `CLOUDFLARE_API_KEY` |
100
+ | `openrouter-api` | `openrouter` | OpenRouter System One Jev models | `OPENROUTER_API_KEY` |
101
+ | `openrouter-decisions-api` | `openrouter` | Jev 1.14/latest, Microsoft, Clef, Liquid, OpenAI, Gemini, HeyGen and other documented slugs | `OPENROUTER_API_KEY` |
102
+ | `openrouter-extractions-api` | `openrouter` | `cloudflare/clairic`, Liquid, Perplexity, ScaleDown and other documented extraction slugs | `OPENROUTER_API_KEY` |
103
+ | `llamacpp-api`, `vllm-api`, `strands-api`, `laya-api`, `nimble-api` | same route key | documented local model IDs; require `baseUrl` | none or runtime key |
104
+
105
+ 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`. Set `providers.cloudflare.gatewayId` to select an AI Gateway for Workers AI requests; the package sends it as `cf-aig-gateway-id`. An explicitly configured `headers["cf-aig-gateway-id"]` still works when `gatewayId` is absent; when both are present, `gatewayId` wins.
106
+
107
+ A provider's `baseUrl` replaces the API root before the adapter's path: `decisions`, `alpha/decisions`, `alpha/extractions`, `systemone`, `v1/systemone`, `extraction`, Microsoft's `providers/microsoft/v1/systemone`, or Cloudflare's run path. Local runtimes take the server root, for example `http://127.0.0.1:8080`. Authentication/transport headers cannot be overridden. Custom headers are supported. HTTPS is required except for loopback HTTP.
108
+
109
+ 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. Set `providers.<id>.limits` only for verified account-specific envelopes; it does not assert unsupported capability.
110
+
111
+ ## Verified capability scope
112
+
113
+ | Surface | Question primitives | Media | Wallet / cost | Notes |
114
+ | --- | --- | --- | --- | --- |
115
+ | OpenAI Decisions and Vercel AI Gateway | bool, choice, score | text, native JSON, local/hosted images | gateway cost captured when returned | Boolean choice values, score descriptions, image detail and prompt-cache controls are supported on the OpenAI wire.
116
+ | OpenRouter alpha Decisions | bool, choice, score; box only on TypeSafe Jev 1.14/latest | per-adapter image/audio/video/file placement; remote URLs only for documented models | `usage.cost` reported as `providerCost` | Alpha contract; media placement and limits are registry-driven.
117
+ | Google Gemini Decisions | bool, choice, score | text, images, audio, video | no bundled rate | Direct `/v1beta/decisions` with `x-goog-api-key`; question media is rejected upstream.
118
+ | Inception Mercury Decide | bool, choice, score, `extract` | text and inline images; no media with extract | no bundled rate | The Mercury API is documented to shut down after 2026-12-28.
119
+ | Parallel Decisions | bool, choice, score | text/JSON only | no bundled rate | Web grounding is intrinsic; request-wide citations are returned as `citations`.
120
+ | Microsoft Foundry | bool, choice, score; no box | text/JSON and PNG/JPEG assets | account pricing | Entra bearer or API key; no published numeric image/context limits.
121
+ | Perplexity | bool, choice, score, locate | text and images | token estimate plus non-token search fees | `max_staleness` is ignored upstream and is not exposed.
122
+ | Sarvam | bool, choice, score | text only for Prism; Clef images require Provisioned Throughput | INR pricing requires explicit USD override | Clef is not bundled as a default.
123
+ | TypeSafe Jev | bool, choice, score, box on 1.14 | text and images | public USD rate | Images and box need experimental opt-ins; long context is `longContext: true`.
124
+ | Liquid hosted | bool, choice, score and typed reads | text, images, audio | public USD rate | Typed reads need text or OCR text in `state`; JSON states expose RFC 6901 `path`.
125
+ | Cloudflare Clef family | bool, choice, score | text, images; Clef-omni also audio/video | public USD rate | Only Clef-omni's schema exposes `videos`.
126
+ | Local System One runtimes | bool, choice, score | runtime/model specific | `unknown_pricing` | llama.cpp, vLLM, Strands, Laya and Nimble use explicit capability tiers; Transformers/mlx-vlm are in-process runtimes and have no HTTP endpoint in this package.
127
+ | Extraction | Clairic fields | text, images, PDFs on direct Clairic; images on gateways | gateway cost captured when returned | Direct Cloudflare, OpenRouter alpha and LiteLLM extraction routes share validation but use separate transports.
128
+
129
+ Unresolved by design: no live entitlement, codec, hardware-fit or invoice check was run; OpenRouter alpha shapes and dynamic model catalogs can change; Cloudflare's direct Workers AI REST gateway-header requirement is internally inconsistent in official docs; and Microsoft does not publish a complete answer schema or numeric image limits. These are reported as limits, not filled with guessed support.
97
130
 
98
131
  ## Use
99
132
 
@@ -132,6 +165,8 @@ classify({
132
165
 
133
166
  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
167
 
168
+ OpenAI-compatible routes can also send `conversation` input items (messages, function calls/outputs and custom tool calls/outputs) when judging a prior exchange. The package validates item types but preserves the documented fields; pair them with a `state` string when you also need shared context. It also sends structured JSON state as native `input_json`, supports boolean-valued two-option choices and score-level descriptions, accepts `imageDetail`, and exposes documented `promptCache` controls. These fields are rejected on routes without the same wire contract.
169
+
135
170
  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
171
 
137
172
  ## Classification trees: `classify_tree`
@@ -237,13 +272,19 @@ This example uses 1,000 Jev input tokens. Amounts are not rounded to cents; doin
237
272
  | --- | ---: | ---: |
238
273
  | OpenAI Decisions `gpt-6-luna` | 0.10 | 0 |
239
274
  | 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 |
275
+ | Perplexity `pplx-decider-v1.3`, `pplx-decider-latest`, `pplx-decider-v1.2`, `pplx-decider-v1.1-27b`, `pplx-decider-v1-27b` | 0.02 | 0 |
276
+ | Perplexity `pplx-decider-flash-v1.3`, `pplx-decider-flash-latest`, `pplx-decider-flash-v1.2` | 0.01 | 0 |
242
277
  | Cloudflare `@cf/cloudflare/clef` | 0.24 | 0 |
243
278
  | Cloudflare `@cf/cloudflare/clef-flash` | 0.038 | 0 |
279
+ | Cloudflare `@cf/cloudflare/clef-omni` | 0.15 | 0 |
280
+ | Cloudflare `@cf/cloudflare/clairic` | 0.10 until 2026-12-01, then 0.24 | 0 |
281
+ | Liquid `d1.2` | 0.02 | 0 |
282
+ | Liquid `d1.2-ultra` | 0.042 | 0 |
244
283
  | Cloudflare `typesafe/jev` | 0.042 | 0 |
245
284
 
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.
285
+ 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), [Perplexity changelog](https://docs.perplexity.ai/docs/resources/changelog), [Clef](https://developers.cloudflare.com/workers-ai/models/clef/), [Clef Flash](https://developers.cloudflare.com/workers-ai/models/clef-flash/), [Clef-omni](https://developers.cloudflare.com/workers-ai/models/clef-omni/), [Clairic](https://developers.cloudflare.com/workers-ai/models/clairic/), [Cloudflare Jev](https://developers.cloudflare.com/ai/models/typesafe/jev/), [Liquid d1.2](https://docs.liquid.ai/lfm/models/d1). Aliases can move and public prices can change; explicit overrides take precedence. Perplexity's `pplx-decider-latest` now selects v1.3 and `pplx-decider-flash-latest` selects Flash v1.3; revalidate thresholds tuned on earlier models. Its [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.
286
+
287
+ Sarvam publishes Prism's rate in INR (₹4 per million input tokens, zero output tokens). This package reports USD, so `sarvam-api` has no bundled rate and returns `cost.reason: "unknown_pricing"` until you set `providers.sarvam.pricing` with a verified USD rate. No exchange rate is invented.
247
288
 
248
289
  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
290
 
@@ -274,15 +315,18 @@ The numbers above are illustrative, **not a claim about Azure pricing**. Use you
274
315
 
275
316
  ## Choice limits by provider
276
317
 
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.
318
+ 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 accepts **1–1000 questions per call** as a documented envelope; each route enforces its own lower limit. The 128-character limit applies to an option's name, not to the option count.
278
319
 
279
320
  | Provider/model | Documented upstream choice options per question | Evidence/qualification |
280
321
  | --- | --- | --- |
281
322
  | TypeSafe Jev | Up to 255 | [Choice docs](https://docs.typesafe.ai/primitives/choice); current Jev service documentation |
282
323
  | 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) |
324
+ | Sarvam Prism | 2–255 | [Decision API reference](https://docs.sarvam.ai/api-reference/decisions/systemone) |
325
+ | Perplexity v1.3, Flash v1.3, 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
326
  | Cloudflare Clef | 2–255 | [Official input schema](https://developers.cloudflare.com/workers-ai/models/clef/schema-input.json) |
285
327
  | Cloudflare Clef Flash | 2–255 | [Official input schema](https://developers.cloudflare.com/workers-ai/models/clef-flash/schema-input.json) |
328
+ | Cloudflare Clef-omni | 2–255 | [Official input schema](https://developers.cloudflare.com/workers-ai/models/clef-omni/schema-input.json) |
329
+ | Liquid `d1.2`, `d1.2-ultra` | 2–255 | [Liquid Decisions reference](https://docs.liquid.ai/api/reference/decision-models/make-decisions) |
286
330
  | Cloudflare-hosted Jev | Not independently verified | Do not assume direct-TypeSafe limits apply to every gateway |
287
331
  | 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
332
  | OpenRouter-hosted Jev / custom routes | Endpoint-dependent; not verified | Requires the selected gateway/model's contract |
@@ -312,12 +356,100 @@ With only `none_of_above_choice` enabled, the extension adds a collision-safe in
312
356
 
313
357
  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
358
 
359
+ With Perplexity web grounding, evidence from each completed batch is retained in call order under `webGrounding.searchResults`, and a grounded `locate.searchResult` index refers to that combined array rather than to a single batch. Fetched results are retained the same way.
360
+
315
361
  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
362
 
317
363
  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
364
 
319
365
  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
366
 
367
+ ## Perplexity `locate` and web grounding
368
+
369
+ Perplexity v1.3 adds a `locate` question that returns verbatim text spans with Unicode-character offsets. It requires a string `state`, no images, and `pplx-decider-v1.3`, `pplx-decider-flash-v1.3`, or the matching `-latest` alias. Other routes reject it locally.
370
+
371
+ ```js
372
+ classify({
373
+ state: "AeroPress arrived broken; email help@brewco.example.",
374
+ questions: {
375
+ products: { type: "locate", instructions: "Every product name mentioned" },
376
+ },
377
+ });
378
+ ```
379
+
380
+ Each answer has `{ type: "locate", spans: [{ start, end, text, score, searchResult? }] }`. `end` is exclusive. The package checks each span against the original state or, when `searchResult` is present, against that search result's snippet. No span is fabricated when nothing matches.
381
+
382
+ Set `mode: "web_grounding"` only when the answer should use public web evidence. Perplexity sends one search query per question containing the question text and the start of `state`, then adds the results to the model's input. A URL-only string `state` is fetched before searching. Perplexity documents `max_staleness` as accepted but currently ignored, so this package does not expose a `maxStaleness` option and does not claim a page-age check.
383
+
384
+ ```js
385
+ classify({
386
+ mode: "web_grounding",
387
+ state: "Claim: the telescope launched in December 2021.",
388
+ questions: { supported: { type: "bool", instructions: "Is the claim supported?" } },
389
+ });
390
+ ```
391
+
392
+ The result adds `webGrounding.searchResults` (and `webGrounding.fetchedResults` when a page was fetched). `cost.nonToken.webGrounding` reports the documented maximum search fee from one search per question and the exact successful-fetch fee. Perplexity does not report the number of searches actually billed, so the search amount is an upper bound: duplicate queries may share a search and failed searches are not billed. Fetched text and search evidence are already included in `usage.input_tokens`. Grounded requests are limited to 100 questions by the provider; the common 32-question package limit still applies.
393
+
394
+ Grounded `locate` requires ordinary text state, not a URL-only state. A span found in search evidence has `searchResult`, and its offsets refer to that result's snippet.
395
+
396
+ ## Liquid d1.2 typed reads and media
397
+
398
+ `liquid-api` uses `POST https://api.liquid.ai/decisions/v1/systemone` with `LIQUID_API_KEY`. It supports bool, choice, score, box, and d1.2's typed reads and estimates. Values are read, not converted: a number answer keeps the printed `text`, `unit`, `span` and `found` probability when the provider reports them. Spans count Unicode code points; JSON object positions use the provider's two-space-indented rendering.
399
+
400
+ ```js
401
+ classify({
402
+ state: "Invoice total: 1234.50 EUR, due 03/04/2026.",
403
+ questions: {
404
+ total: { type: "number", instructions: "Invoice total", unit: "EUR" },
405
+ due: { type: "date", instructions: "Payment due date" },
406
+ people: { type: "estimate", instructions: "How many people attended?", range: [0, 60], step: 1, unit: "people" },
407
+ topics: { type: "multi_choice", instructions: "Which topics apply?", criteria: { billing: "Charges", delivery: "Shipping" } },
408
+ },
409
+ });
410
+ ```
411
+
412
+ `text` returns a typed value. `number` and `date` preserve a present-but-unparseable value as `value: null` or `date: null`, together with the provider's `found`, `text` and `span` metadata; this is different from a field that was not found at all. `spans` and `boxes` return provider slot semantics: `presence` gives each slot's probability, `spans`/`boxes` retain slots at or above 0.5, and `atLeast: true` means more matches may exist. `estimate` returns `{ value, interval, unit? }`; request ranges and returned intervals may be negative or fractional. Multi-select answers use `choices` plus independent per-label probabilities that do **not** sum to one.
413
+
414
+ Liquid images are top-level `{ content_type, base64 }` entries, not Jev assets. The package validates local PNG/JPEG/WebP files and allows eight images, each within 10,000 32×32 patches and a 100:1 aspect ratio. Audio is sent in a top-level `audio` array as WAV, MP3, FLAC or OGG; up to eight clips and 300 seconds total are documented by Liquid. Video is not documented for Liquid and is rejected locally. Codec compatibility and clip duration remain provider-owned; the package validates container bytes and transport size, not decoded audio length.
415
+
416
+ ## Clef-omni media
417
+
418
+ `@cf/cloudflare/clef-omni` uses Clef's Workers AI body shape with `model: "clef-omni"` and the same noul/choice/score answers. It adds top-level `audio` and `videos` arrays beside `images`:
419
+
420
+ ```js
421
+ classify({
422
+ state: "Describe the reported problem.",
423
+ questions: { urgent: { type: "bool", instructions: "Needs urgent intervention?" } },
424
+ media: [
425
+ { type: "audio", path: "call.mp3" },
426
+ { type: "video", path: "demo.mp4" },
427
+ ],
428
+ });
429
+ ```
430
+
431
+ Local audio may be WAV, MP3, FLAC or OGG; local video may be MP4 or WebM. Container bytes must match. The documented provider maxima are four audio clips of 8 MiB and 300 seconds each, and two videos of 16 MiB and 60 seconds each with at most 16 MiB combined audio/video. Existing package request and image limits still apply. Duration and codec compatibility are enforced by the provider, not by the package. Media on other Cloudflare models is rejected locally instead of being silently dropped.
432
+
433
+ ## Cloudflare Clairic extraction
434
+
435
+ Use **`classify_extract`** for structured extraction. It selects the configured default route and sends `fields`, not classifier questions; use `clairic-api`, `openrouter-extractions-api` or `litellm-extraction-api` as the default. The library exports `extract(params, { settings, cwd, signal? })`.
436
+
437
+ ```js
438
+ classify_extract({
439
+ state: "Invoice INV-2291, issued 2026-09-02, net 30.",
440
+ fields: {
441
+ invoice_number: { type: "text" },
442
+ due_date: { type: "date", instructions: "Issue date plus payment days" },
443
+ days_to_pay: { type: "estimate", min: 0, max: 120, step: 1 },
444
+ },
445
+ referenceDate: "2026-11-20",
446
+ });
447
+ ```
448
+
449
+ Clairic field types are `text`, `number`, `compute`, `date`, `time`, `datetime`, `duration`, `boolean`, `enum`, `object`, `list`, `estimate` and `forecast`. The tool validates names and documented field keys, including nested `properties` and `items`. Each result answer contains the provider's `type`, `value`, and any documented metadata it returned, such as `span`, `confidence`, `source`, `mean` or `quantiles`. `truncated: true` means generated fields were incomplete or invalid; do not treat that output as complete.
450
+
451
+ Caller options use `includeQuantiles` and `returnStateText`; adapters send the documented snake_case wire keys. Direct Clairic accepts PNG/JPEG/WebP images and PDF documents as local files, with optional clockwise `rotation: 0 | 90 | 180 | 270` on an image descriptor. It allows at most four rendered images/PDF pages combined, 4 MiB per file and 8 MiB combined decoded media. OpenRouter Extractions uses `assets` instead, does not accept PDFs on the Clairic model, and enforces per-model field tiers and keys from its native schema. Liquid images require estimate-only fields with text list items; ScaleDown accepts one PDF or image and no simultaneous text state; LiteLLM `/v1/extraction` supports Clairic-shaped fields and images but not PDFs. Remote URLs and encrypted PDFs are rejected. Exact PDF page rendering and character-offset units remain provider-owned. Current direct Clairic pricing is $0.10 per million input tokens until 2026-12-01 and $0.24 afterward; output generation is not charged separately. Configure an explicit `pricing` override if your account has different rates.
452
+
321
453
  ## Microsoft Decision-1 on Foundry
322
454
 
323
455
  Deploy `Microsoft-Decision-1` in Microsoft Foundry, then configure the **resource endpoint**, API key, and actual **deployment name**:
@@ -336,7 +468,23 @@ Deploy `Microsoft-Decision-1` in Microsoft Foundry, then configure the **resourc
336
468
  }
337
469
  ```
338
470
 
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.
471
+ The extension appends `/providers/microsoft/v1/systemone`. It uses the `api-key` header by default; set `providers.microsoft.authMode: "bearer"` when the configured key is an Entra token (`https://cognitiveservices.azure.com` resource). The catalog name is only a discovery entry: `model` must match your deployment, which may have another name. Microsoft Decision-1.1 supports text/JSON bool (wire type `noul`), choice, score and local PNG/JPEG images through the documented `assets` map and `image:<name>` references; box is rejected. 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. Microsoft does not publish a complete answer schema or numeric image/context limits in the current guide; verify those details on your deployment.
472
+
473
+ ## Sarvam Prism
474
+
475
+ `sarvam-api` calls `POST https://api.sarvam.ai/v2/systemone` with the `api-subscription-key` header. Select it explicitly; installing this package does not change the existing default route. Its only built-in model is `sarvam-prism`.
476
+
477
+ ```json
478
+ {
479
+ "pi-classifier": {
480
+ "default": { "provider": "sarvam-api", "model": "sarvam-prism" }
481
+ }
482
+ }
483
+ ```
484
+
485
+ The credential is `providers.sarvam.apiKey`, Pi's stored `sarvam` API-key credential, or `SARVAM_API_KEY`. Prism supports text/JSON state and `bool` (wire `noul`), `choice`, and `score` questions. It returns a yes probability, a top choice with per-option probabilities, or a probability-weighted score, all checked by the same distribution and consistency rules as other decision providers. Sarvam score answers must include the documented probability distribution. Prism rejects images; the Provisioned Throughput-only `clef` model accepts local base64 images in the documented `images` array. Both models accept `api-subscription-key` by default; set `providers.sarvam.authMode: "bearer"` for a bearer key. Media, web grounding, `locate`, and `box` are rejected locally. Prism choice questions need 2–255 options and Clef needs 1–255; score questions need 2–10 levels.
486
+
487
+ Provider errors are reported with the standard safe HTTP error plus a whitelisted Sarvam code, field path and request ID when present. Untrusted field paths and request IDs that contain the active API key are omitted, including response-header request IDs before falling back to the body; raw provider text and credentials are never printed. Selecting a custom `baseUrl` does not inherit the bundled USD pricing; set `providers.sarvam.pricing` explicitly if you need a cost estimate. Clef requires Provisioned Throughput access; an unavailable entitlement returns a safe HTTP error rather than a silent fallback.
340
488
 
341
489
  ## Fallback and explicit comparison
342
490
 
@@ -358,9 +506,9 @@ The library exports `compareClassifiers(params, { settings, cwd, signal? })`. Ne
358
506
 
359
507
  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
508
 
361
- Local image inputs are non-animated PNG/JPEG/WebP regular files inside the session cwd, with no symlink components or inline base64. Safe descriptor-based loading supports macOS (requires the OS `/usr/sbin/lsof`) and Linux (`/proc`). Images are fully decoded locally before upload. Limits: five images on OpenAI/Jev, eight on Perplexity; 5 MiB each, 10 MiB total and 16 megapixels each. Clef has stricter limits: four images, 4 MiB each and 8 MiB total. Perplexity allows at most eight image occurrences in shared state, including repeated references, and requires at most 2048 tiles of 32×32 pixels per image. Images are not silently resized. Text/JSON plus questions remain limited to 2 MiB and 32 questions.
509
+ Local image inputs are non-animated PNG/JPEG/WebP regular files inside the session cwd, with no symlink components or inline base64. Safe descriptor-based loading supports macOS (requires the OS `/usr/sbin/lsof`) and Linux (`/proc`). Images are fully decoded locally before upload. Per-route image limits come from the published contracts: eight on Perplexity and hosted Liquid, four on Clef and Clef-omni, eight on Microsoft per question, 16 on Inception and Mercury/Baseten OpenRouter adapters, 100 on HeyGen, 128 on GPT-6 Luna Decisions, and 128 as the package envelope. Each existing route keeps its documented byte and patch constraints; images are not silently resized. Text/JSON plus questions remain limited to 2 MiB, while the question count uses the documented envelope and each route's lower limit.
362
510
 
363
- Named hosted URLs on OpenAI do not require local file loading and work on other platforms. They are passed directly to the selected OpenAI-compatible endpoint, never downloaded by this package. The provider must be able to access them and enforces remote image format/size limits; local byte/pixel validation cannot inspect them. URLs must use HTTP(S), with no credentials or fragment. Do not send sensitive URLs unless you intend to share them with that endpoint.
511
+ Named hosted URLs on OpenAI and on OpenRouter's documented Gemini/HeyGen Decisions models do not require local file loading. They are passed directly to the selected endpoint, never downloaded by this package; OpenRouter adapters place them in top-level `state` image parts and reject other placements. The provider must be able to access them and enforces remote image format/size limits; local byte/pixel validation cannot inspect them. URLs must use HTTP(S), with no credentials or fragment. Do not send sensitive URLs unless you intend to share them with that endpoint.
364
512
 
365
513
  TypeSafe Jev images are experimental and require opt-in. Use PNG/JPEG. Each side must be **280–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:
366
514
 
@@ -424,7 +572,8 @@ Declare these images in the surrounding request's `images` list. The same conten
424
572
  | Named references in shared state | Yes, opt-in | Yes | Yes | No |
425
573
  | Images in question instructions | Yes, opt-in | Yes | No | No |
426
574
  | Images in criteria | Yes, opt-in | No | No | No |
427
- | Named hosted URL descriptors | No | Yes | No | No |
575
+ | Named hosted URL descriptors | No | Yes | No | No; OpenRouter Gemini/HeyGen accept them as top-level state image parts |
576
+ | Top-level image/audio media | No | No | No | Clef-omni audio/video and Liquid images/audio use provider-specific base64 objects |
428
577
 
429
578
  For OpenAI, replace a named local descriptor with `{"id":"target","url":"https://example.com/reference.jpg"}` and reference it in state or instructions. Nested JSON state is represented as text fragments interleaved with the referenced images; it is not an upstream JSON object containing embedded native parts. Unsupported placements fail locally before a request, including on fallback and comparison routes. No image is silently dropped or moved.
430
579
 
@@ -446,11 +595,11 @@ The default `overlay` mode draws the box. Set `mode: "crop"` to extract its regi
446
595
 
447
596
  The library exports `renderClassifierBox(params, { cwd, signal? })`, which returns PNG base64 data, MIME type, dimensions, pixel box and mode. Saving the result is the caller's responsibility. A box is not proof that an object exists; check existence separately.
448
597
 
449
- Video descriptions in Cloudflare's model pages do not establish a hosted video API contract. Video, segmentation masks, multi-object box lists, image generation/editing and gateway image parity are not implemented.
598
+ Clef-omni's official input schema establishes the hosted video contract used here. Video is rejected on other Cloudflare models and gateways. Segmentation masks, image generation/editing and gateway image parity are not implemented; Liquid `boxes` and Clairic documents have provider-specific contracts described above.
450
599
 
451
600
  ## Custom providers
452
601
 
453
- 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.
602
+ Like image-gen, `customProviders` adds a named endpoint and explicit model list. Supported protocols are `openai-decisions`, `openrouter-decisions`, `gemini-decisions`, `inception-decisions`, `parallel-decisions`, `local-system-one`, `perplexity-decisions`, `sarvam-system-one`, `system-one`, `liquid-system-one`, `cloudflare-system-one`, `cloudflare-clairic`, `openrouter-extractions`, `litellm-extraction`, and `microsoft-system-one` (Foundry resource root and API-key or Entra bearer authentication). A custom URL cannot make an arbitrary API compatible. Custom IDs must not shadow built-in provider/route IDs.
454
603
 
455
604
  ```json
456
605
  {
@@ -471,10 +620,96 @@ Like image-gen, `customProviders` adds a named endpoint and explicit model list.
471
620
 
472
621
  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.
473
622
 
623
+ ### LiteLLM decision gateways
624
+
625
+ LiteLLM documents both `POST /v1/decisions` and `POST /v1/systemone` with bearer virtual keys. Add the decision model to LiteLLM's `model_list`, then configure either protocol explicitly:
626
+
627
+ ```json
628
+ {
629
+ "pi-classifier": {
630
+ "default": { "provider": "litellm-decisions", "model": "luna" },
631
+ "customProviders": {
632
+ "litellm-decisions": {
633
+ "api": "openai-decisions",
634
+ "baseUrl": "https://litellm.example/v1",
635
+ "apiKey": "${LITELLM_VIRTUAL_KEY}",
636
+ "models": [{ "id": "luna", "input": ["text"] }],
637
+ "pricing": { "luna": { "inputPerMillion": 0.042, "outputPerMillion": 0 } },
638
+ "maxChoices": 255
639
+ }
640
+ }
641
+ }
642
+ }
643
+ ```
644
+
645
+ Because `litellm-decisions` is not a built-in route, it must be declared under `customProviders`; an unknown ID placed under `providers` is rejected. Use `"api": "system-one"` with `baseUrl: "https://litellm.example/v1"` to call `/v1/systemone` instead. The price above is illustrative; set it from your actual LiteLLM pricing. `maxChoices` must match the deployment's verified decision limit before choice batching. Text-only payloads fit both routes; LiteLLM image support depends on the selected upstream model and release, so declare image input only for a model you have verified. Custom gateways do not inherit bundled upstream prices.
646
+
647
+ ### OpenRouter pricing and choice limits
648
+
649
+ The built-in `openrouter-api` route targets the documented `POST /api/v1/systemone` endpoint. It has no bundled USD price and no verified choice cap. Set both from your account and the selected model when you need cost reporting or choice batching:
650
+
651
+ ```json
652
+ {
653
+ "pi-classifier": {
654
+ "providers": {
655
+ "openrouter": {
656
+ "apiKey": "${OPENROUTER_API_KEY}",
657
+ "pricing": { "typesafe/jev-1.13": { "inputPerMillion": 0.042, "outputPerMillion": 0 } },
658
+ "maxChoices": 255
659
+ }
660
+ }
661
+ }
662
+ }
663
+ ```
664
+
665
+ The legacy `openrouter-api` System One route remains text-only in this package. Use `openrouter-decisions-api` for `POST /api/alpha/decisions` and `openrouter-extractions-api` for `POST /api/alpha/extractions`. Both are alpha contracts: media placement, question support and extraction field tiers are selected by model/provider capability registries, and `usage.cost` is reported as `providerCost` without being substituted for the token estimate.
666
+
667
+ ## Native Durable entrypoint (`/durable`)
668
+
669
+ `@abhishek944/pi-classifier/durable` exposes `createClassifierExtension(settings, options?)`, a settings-only native Durable extension named `classifier` with `classify`, `classify_compare`, `classify_tree`, `classify_extract`, and `classifier_box_image`. Tool names, descriptions, and parameter/result schemas are shared with the desktop extension through `src/tool-contracts.ts`, so the two surfaces cannot drift. Desktop-only registration fields (labels, prompt guidance, annotations) stay with the desktop extension.
670
+
671
+ ```js
672
+ import { createClassifierExtension } from "@abhishek944/pi-classifier/durable";
673
+
674
+ const extension = createClassifierExtension(
675
+ {
676
+ default: { provider: "openai-api", model: "gpt-6-luna" },
677
+ providers: { openai: { apiKey: process.env.OPENAI_API_KEY } },
678
+ },
679
+ { cwd: "/work/session" }, // optional; otherwise the Durable environment cwd, agent cwd, then process cwd
680
+ );
681
+ ```
682
+
683
+ Credentials must be explicit: `providers.<id>.apiKey` (plus `providers.cloudflare.accountId` for Cloudflare) or the provider environment variable. The native path never reads Pi settings files or Pi's stored API-key credentials, and there are no admission, quota, authorization, or host callbacks. `classify`, `classify_compare`, and `classify_tree` never replay after an uncertain or billable execution (`replay: "unsafe"`); `classifier_box_image` is a pure local render with no provider request, upload, or disk write (`replay: "safe"`). Cancellation follows the invocation abort signal. `classifier_computer_use` is not registered natively: its observe/select/act/verify loop needs to invoke Driver tools between decisions, and Durable 1.1.0 exposes no generic tool-invocation API, so no placeholder is shipped. Use the desktop extension for computer use.
684
+
474
685
  ## Goal-running computer use (OpenAI Decisions)
475
686
 
476
687
  The optional `classifier_computer_use` tool runs a bounded Cua Driver loop inside Pi, selecting only supervisor-permitted controls and returning explicit handoff/continuation when help is needed. It has a separate opt-in OpenAI route, preserves the normal classifier default, accepts transient Driver screenshots without disk files, and verifies completion through fresh Driver predicates. See [COMPUTER_USE.md](COMPUTER_USE.md) for setup, real input/output examples, safety limits, supervisor resumption and verification.
477
688
 
689
+ ## Use from other agents (MCP)
690
+
691
+ The package includes an independent stdio MCP server. It exposes `classify`, `classify_compare`, `classify_tree`, `classify_extract`, and `classifier_box_image`. Pi-only `classifier_computer_use` is not exposed because it needs Pi's Driver tool loop. Tool names, descriptions, and parameter schemas come from the package-owned tool contracts; there is no gateway and no hosted HTTP endpoint.
692
+
693
+ Add it as one MCP server, separate from any image-gen or web server:
694
+
695
+ ```json
696
+ {
697
+ "mcpServers": {
698
+ "pi-classifier": {
699
+ "command": "npx",
700
+ "args": ["-y", "-p", "@abhishek944/pi-classifier", "pi-classifier-mcp"],
701
+ "cwd": "/work/session"
702
+ }
703
+ }
704
+ }
705
+ ```
706
+
707
+ If the package is installed, `pi mcp add pi-classifier -- pi-classifier-mcp` uses the installed bin instead. The CLI uses stdio only: stdout carries JSON-RPC and diagnostics go to stderr. It does not listen on a port or expose an HTTP path. `cwd` is optional and sets the directory for relative local images, media, and tree-file paths; without it, the MCP child inherits the client session directory. Global and agent settings are read at startup; project settings are not loaded. Restart the server after changing settings.
708
+
709
+ The standalone server uses explicit provider credentials by default (environment variables or configured `providers.<id>.apiKey`). It does not silently use Pi chat login. An embedding host can opt into stored Pi credentials through `createClassifierMcpServer({ credentialSource: "pi-store" })`. `@abhishek944/pi-classifier/mcp` also exports the MCP tool definitions.
710
+
711
+ Classification and comparison calls send supplied state to the configured provider and may incur charges. Only send data the caller intends to share.
712
+
478
713
  ## Development and live verification
479
714
 
480
715
  ```sh
@@ -490,13 +725,16 @@ No provider calls are made by these commands. Live tests belong to the user:
490
725
  3. Try a small PNG on OpenAI, Perplexity and Clef. Enable Jev images explicitly before trying its preview; verify box coordinates separately.
491
726
  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.
492
727
  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.
493
- 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.
728
+ 6. Configure your Foundry endpoint and deployment name, select `microsoft-api`, and verify bool/choice/score responses and token usage. Verify that a PNG image is sent through `assets` and that box is rejected locally; repeat with an Entra bearer token only when you own one.
494
729
  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.
495
730
  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.
496
731
  9. On Jev, enable the image/box flags and try the named scene/reference example above. Compare visual choice/score criteria, then a box plus a separate existence question. Verify repeated references and choice batching do not leave unreferenced assets. Try a 279-pixel side and confirm local rejection.
497
732
  10. On OpenAI, try one shared named local image plus a question-specific local image, then replace the latter with a public HTTPS descriptor. Confirm references stay in their intended placements. On Perplexity, try named state references and eight small images; instruction/criterion images should fail locally.
498
733
  11. Invoke `classifier_box_image` with the exact local scene and a returned box in both overlay and crop modes. Confirm pixel bounds and orientation visually, no files are written, invalid/reversed edges are rejected, and cancellation interrupts processing. Check EXIF-oriented photos carefully: no automatic rotation is applied.
734
+ 12. On Perplexity v1.3, verify locate spans against the original text, then run a small web-grounded bool and inspect `search_results`, `fetched_results` and the non-token fee accounting. Do not enable grounding for sensitive state.
735
+ 13. On Liquid d1.2, verify a typed read, a ranged estimate, a multi-select choice, one image and one audio clip. Confirm that unparseable values become `no_match` rather than converted guesses.
736
+ 14. On Clef-omni, verify text, one image, one audio clip and one video in one request, then confirm unsupported media on Clef Flash fails locally. On Clairic, verify a field contract with grounding metadata and `truncated` reporting.
499
737
 
500
738
  Provider schemas and previews can change; no live entitlement or model-accuracy claim is made by a local build.
501
739
 
502
- 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/).
740
+ Sources: [Microsoft Decision-1.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), [OpenRouter Decisions](https://openrouter.ai/docs/guides/features/decisions), [OpenRouter multimodal contracts](https://openrouter.ai/docs/guides/community/multimodal-decisions), [OpenRouter Extractions](https://openrouter.ai/docs/guides/community/extractions), [Vercel Decisions](https://vercel.com/docs/ai-gateway/sdks-and-apis/openai-decisions), [Gemini Decisions API](https://aistudio.google.com/docs/decisions-api), [Inception Decisions](https://docs.inceptionlabs.ai/capabilities/decisions), [Parallel Decisions](https://docs.parallel.ai/decisions/decisions-quickstart), [Perplexity Decisions](https://docs.perplexity.ai/docs/decisions/decisions), [Sarvam Decisions](https://docs.sarvam.ai/api-reference/decisions/systemone), [TypeSafe images](https://docs.typesafe.ai/images), [TypeSafe box](https://docs.typesafe.ai/primitives/box), [Liquid decisions](https://docs.liquid.ai/api/guides/decisions), [Liquid open weights](https://docs.liquid.ai/lfm/models/decision-models), [Cloudflare Clef](https://developers.cloudflare.com/workers-ai/models/clef/), [Cloudflare Clairic](https://developers.cloudflare.com/workers-ai/models/clairic/), [LiteLLM decisions](https://docs.litellm.ai/docs/decisions), [LiteLLM extraction](https://docs.litellm.ai/docs/extraction), [Cloudflare AI Gateway REST API](https://developers.cloudflare.com/ai-gateway/usage/rest-api/).
package/dist/auth.d.ts CHANGED
@@ -1,5 +1,7 @@
1
1
  import { type ResolvedModel } from "./types.js";
2
+ /** Where provider credentials may come from. Desktop keeps the "pi-store" default; the native Durable factory uses "explicit" only. */
3
+ export type CredentialSource = "pi-store" | "explicit";
2
4
  /** Read the API-key entry only. Never resolve OAuth or mutate Pi's login state. */
3
5
  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;
6
+ export declare function resolveApiKey(route: ResolvedModel, source?: CredentialSource): string;
7
+ export declare function cloudflareAccountId(configured: string | undefined, source?: CredentialSource): string;
package/dist/auth.js CHANGED
@@ -31,9 +31,18 @@ function storedValue(value, env = {}) {
31
31
  });
32
32
  return missing ? undefined : resolved.trim() || undefined;
33
33
  }
34
- export function resolveApiKey(route) {
34
+ export function resolveApiKey(route, source = "pi-store") {
35
+ if (route.authMode === "none")
36
+ return "";
35
37
  if (route.configuredApiKey)
36
38
  return route.configuredApiKey;
39
+ if (source === "explicit") {
40
+ const key = route.envVar ? process.env[route.envVar]?.trim() : undefined;
41
+ if (!key) {
42
+ throw new ClassifierError("missing_credentials", "No API key is configured for the selected classifier. Set providers.<id>.apiKey or the provider environment variable. Pi credential-store lookup is disabled on the explicit native path.");
43
+ }
44
+ return key;
45
+ }
37
46
  const credential = storedApiCredential(route.credentialProvider);
38
47
  const key = storedValue(credential?.key, credential?.env) ??
39
48
  (route.envVar ? process.env[route.envVar]?.trim() : undefined);
@@ -42,7 +51,14 @@ export function resolveApiKey(route) {
42
51
  }
43
52
  return key;
44
53
  }
45
- export function cloudflareAccountId(configured) {
54
+ export function cloudflareAccountId(configured, source = "pi-store") {
55
+ if (source === "explicit") {
56
+ const id = configured?.trim() ?? process.env.CLOUDFLARE_ACCOUNT_ID?.trim();
57
+ if (!id || !/^[a-zA-Z0-9_-]+$/.test(id)) {
58
+ throw new ClassifierError("configuration", "Cloudflare requires a valid accountId or CLOUDFLARE_ACCOUNT_ID.");
59
+ }
60
+ return id;
61
+ }
46
62
  const stored = configured
47
63
  ? undefined
48
64
  : storedApiCredential("cloudflare-workers-ai");
@@ -1,26 +1,4 @@
1
1
  import { type ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
- import { Type } from "typebox";
3
- export declare const boxParameters: Type.TObject<{
4
- image: Type.TString;
5
- box: Type.TObject<{
6
- top: Type.TNumber;
7
- bottom: Type.TNumber;
8
- left: Type.TNumber;
9
- right: Type.TNumber;
10
- }>;
11
- mode: Type.TOptional<Type.TUnion<[Type.TLiteral<"overlay">, Type.TLiteral<"crop">]>>;
12
- }>;
13
- export declare const boxOutput: Type.TObject<{
14
- mode: Type.TUnion<[Type.TLiteral<"overlay">, Type.TLiteral<"crop">]>;
15
- mimeType: Type.TLiteral<"image/png">;
16
- width: Type.TInteger;
17
- height: Type.TInteger;
18
- pixelBox: Type.TObject<{
19
- left: Type.TInteger;
20
- top: Type.TInteger;
21
- width: Type.TInteger;
22
- height: Type.TInteger;
23
- }>;
24
- byteLength: Type.TInteger;
25
- }>;
2
+ import { boxOutput, boxParameters } from "./tool-contracts.js";
3
+ export { boxOutput, boxParameters };
26
4
  export declare function registerBoxTool(pi: ExtensionAPI): void;