Build AI methods with your coding agent, then run them anywhere: as an MCP for chatbots, as a webapp for people, or via API for your software.
feature/Typesafe-backend · L-260919-502f36 — judgment cogt family, typesafe worker (#1216)
Louis Choquel1ae9a40e420d
diff --git a/.env.example b/.env.exampleindex ad710cc16..9960041c2 100644--- a/.env.example+++ b/.env.example@@ -63,3 +63,6 @@ LANGFUSE_SECRET_KEY=# Web Search & FetchLINKUP_API_KEY=++# Judgment+TYPESAFE_API_KEY=diff --git a/.pipelex-dev/test_profiles.toml b/.pipelex-dev/test_profiles.tomlindex f202a27f1..ae1d16f7c 100644--- a/.pipelex-dev/test_profiles.toml+++ b/.pipelex-dev/test_profiles.toml@@ -49,6 +49,7 @@ all = ["vertexai","xai","linkup",+ "typesafe","internal",]@@ -239,6 +240,10 @@ qwen = ["qwen-image"]# --- Search Models ---linkup = ["linkup-standard", "linkup-deep"]+[collections.judgment]+# --- Judgment Models ---+typesafe = ["jev-1.13.0"]+[collections.extract]# --- Web Extraction Models ---from_web = ["linkup-fetch"]@@ -325,6 +330,21 @@ extract_models = ["azure-document-intelligence", "linkup-fetch"]search_models = ["linkup-standard"]judgment_models = []+################################################################################+# TypeSafe Profile+################################################################################+# The judgment family's live tests and nothing else. Every other model list is empty on purpose:+# the combo fixtures route the whole deck to one backend for the duration of a run, and TypeSafe+# serves judgments alone — a profile naming an LLM here would send it somewhere that cannot answer.+[profiles.typesafe]+description = "TypeSafe judgment models, for the judgment family's live tests"+backends = ["typesafe"]+llm_models = []+img_gen_models = []+extract_models = []+search_models = []+judgment_models = ["@typesafe"]+################################################################################# Coverage Profile################################################################################diff --git a/.pipelex/inference/backends.toml b/.pipelex/inference/backends.tomlindex eb2803675..28a5a7777 100644--- a/.pipelex/inference/backends.toml+++ b/.pipelex/inference/backends.toml@@ -110,6 +110,11 @@ enabled = trueendpoint = "${SCALEWAY_ENDPOINT}"api_key = "${SCALEWAY_API_KEY}"+[typesafe]+display_name = "TypeSafe"+enabled = true+api_key = "${TYPESAFE_API_KEY}"+[vertexai]display_name = "Google Vertex AI"enabled = false # This is the only one we disable because setting it up requires internet access just to get credentials so it fails in CI sandboxesdiff --git a/.pipelex/inference/backends/typesafe.toml b/.pipelex/inference/backends/typesafe.tomlnew file mode 100644index 000000000..85b3a1a83--- /dev/null+++ b/.pipelex/inference/backends/typesafe.toml@@ -0,0 +1,41 @@+################################################################################+# TypeSafe Backend Configuration+################################################################################+#+# This file defines the model specifications for TypeSafe judgment models.+# TypeSafe's System One answers closed-form questions — yes/no, choice, rating —+# over some material, and returns the probability behind each verdict.+#+# Documentation: https://docs.pipelex.com+# Support: https://go.pipelex.com/discord+#+################################################################################++################################################################################+# MODEL DEFAULTS+################################################################################++[defaults]+model_type = "judgment"+sdk = "typesafe"+thinking_mode = "none"++################################################################################+# JUDGMENT MODELS+################################################################################+#+# Always a VERSIONED id, never one of the provider's moving aliases: a verdict model that changes+# under a method silently changes what every threshold in that method means.+#+# Finding the next version is a documentation read, not a lookup. `GET /v1/models` lists only the+# aliases `jev-latest` and `jev-preview` and names no version anywhere in its body, so the versioned+# id comes from the provider's own models page. A truncated id is refused outright.+#+# Output tokens are genuinely free at the time of writing, which is why they are priced at zero+# rather than at an output rate. Prices are USD per million tokens.++["jev-1.13.0"]+model_id = "jev-1.13.0"+inputs = ["text"]+outputs = ["judgments"]+costs = { input = 0.042, output = 0 }diff --git a/.pipelex/inference/deck/6_judgment_deck.toml b/.pipelex/inference/deck/6_judgment_deck.tomlindex 3692726eb..01e45b3c5 100644--- a/.pipelex/inference/deck/6_judgment_deck.toml+++ b/.pipelex/inference/deck/6_judgment_deck.toml@@ -36,8 +36,12 @@## A judgment alias points at a VERSIONED model id, never at a provider's `latest` alias: a verdict# model that changes under a method silently changes what every threshold in that method means.+#+# `jev-1.13.0` is TypeSafe's. Its next version is found on the provider's models page and not through+# its API, whose model listing names only the moving aliases — moving this pin is a documentation read.[judgment.aliases]+default-judgment = "jev-1.13.0"##################################################################################################### Judgment Presetsdiff --git a/.pipelex/inference/routing_profiles.toml b/.pipelex/inference/routing_profiles.tomlindex 57407e0a6..25619b1ee 100644--- a/.pipelex/inference/routing_profiles.toml+++ b/.pipelex/inference/routing_profiles.toml@@ -28,6 +28,11 @@ active = "all_pipelex_gateway"description = "Use Pipelex Gateway for all its supported models"default = "pipelex_gateway"+# Judgment models are brought by you rather than served by Pipelex, so they go to their own backend+# whenever it is enabled. An optional route is inert while its backend is disabled.+[profiles.all_pipelex_gateway.optional_routes]+"jev-*" = "typesafe"+# The same model names, served by the Pipelex-operated inference service instead. Switching between# this profile and the one above needs no other edit: a model's wire id and sdk are per-backend, so# decks, aliases and presets keep naming the same handles.@@ -35,6 +40,11 @@ default = "pipelex_gateway"description = "Use Pipelex Manifold (private beta) for all its supported models"default = "pipelex_manifold"+# Judgment models are brought by you rather than served by Pipelex, so they go to their own backend+# whenever it is enabled. An optional route is inert while its backend is disabled.+[profiles.all_pipelex_manifold.optional_routes]+"jev-*" = "typesafe"+[profiles.all_anthropic]description = "Use Anthropic backend for all its supported models"default = "anthropic"@@ -99,6 +109,10 @@ default = "portkey"description = "Use Scaleway backend for all its supported models"default = "scaleway"+[profiles.all_typesafe]+description = "Use TypeSafe backend for all its supported models"+default = "typesafe"+[profiles.all_vertexai]description = "Use Vertex AI backend for all its supported models"default = "vertexai"diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e2500e82b..1f4275ade 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,7 +4,8 @@### Added-- **A `judgment` inference family**: a new family beside `llm`, `img_gen`, `extract`, `search` and `doc_gen`, for models that answer a closed-form question over some material — yes or no, one option out of a declared set, or a position on a declared scale — and report how sure they are. The worker contract is batch-shaped (one state, a map of questions, a map of answers), every measure of uncertainty is optional so a backend that measures none can still serve the family honestly, and usage is reported as real input and output tokens priced per million. The deck gains a `[judgment]` section in a new managed file, `6_judgment_deck.toml`, which `pipelex update` installs, and a deck installed before it keeps loading with no judgment model; it ships with no `choice_default`, because no backend serves the family yet, so a judgment names its own model. `pipelex-agent models` lists the new category, and a `judgment` pytest marker joins the inference markers.+- **A `judgment` inference family**: a new family beside `llm`, `img_gen`, `extract`, `search` and `doc_gen`, for models that answer a closed-form question over some material — yes or no, one option out of a declared set, or a position on a declared scale — and report how sure they are. The worker contract is batch-shaped (one state, a map of questions, a map of answers), every measure of uncertainty is optional so a backend that measures none can still serve the family honestly, and usage is reported as real input and output tokens priced per million. The deck gains a `[judgment]` section in a new managed file, `6_judgment_deck.toml`, which `pipelex update` installs, and a deck installed before it keeps loading with no judgment model; it ships with no `choice_default`, because the family's models come with your own key and a default the Pipelex Gateway does not serve would fail every boot, so a judgment names its own model. `pipelex-agent models` lists the new category, and a `judgment` pytest marker joins the inference markers.+- **TypeSafe, the judgment family's first backend**: a built-in `typesafe` plugin, installed with the new `pipelex[typesafe]` extra, serves the family from TypeSafe's System One API and is reachable as `@default-judgment`, pinned to the versioned model `jev-1.13.0`. Set `TYPESAFE_API_KEY` to use it: the default routing profile sends `jev-*` models to the backend whenever it is enabled, because the Pipelex Gateway does not serve them. A rating scale longer than ten levels is refused by this backend before any request is made, and a response answered by a model other than the pinned one is reported as a warning.### Changed@@ -13,6 +14,7 @@### Fixed- **Markdown with unclosed emphasis is converted in memory proportional to its length**: the Markdown parser behind the `markdown` filter, the `Markdown` concept's HTML and the built-in PDF engine held memory growing with the square of the text when emphasis or strikethrough markers were left unmatched, about 1.5 GB for 64,000 characters of `**a `; it now joins the text they leave behind in one pass, and renders the same HTML.+- **Routing profiles no longer rewrite their own routes**: matching a model merged the enabled `optional_routes` into the profile's declared `routes` in place, so after the first match a route declared optional had become an unconditional one in the loaded profile. Only the enablement checks each match repeats kept that from changing a routing decision.### Securitydiff --git a/api/.pipelex/inference/backends.toml b/api/.pipelex/inference/backends.tomlindex a76495598..6d5dcb985 100644--- a/api/.pipelex/inference/backends.toml+++ b/api/.pipelex/inference/backends.toml@@ -114,6 +114,11 @@ enabled = falseendpoint = "${SCALEWAY_ENDPOINT}"api_key = "${SCALEWAY_API_KEY}"+[typesafe]+display_name = "TypeSafe"+enabled = false+api_key = "${TYPESAFE_API_KEY}"+[vertexai]display_name = "Google Vertex AI"enabled = false # This is the only one we disable because setting it up requires internet access just to get credentials so it fails in CI sandboxesdiff --git a/api/.pipelex/inference/backends/typesafe.toml b/api/.pipelex/inference/backends/typesafe.tomlnew file mode 100644index 000000000..85b3a1a83--- /dev/null+++ b/api/.pipelex/inference/backends/typesafe.toml@@ -0,0 +1,41 @@+################################################################################+# TypeSafe Backend Configuration+################################################################################+#+# This file defines the model specifications for TypeSafe judgment models.+# TypeSafe's System One answers closed-form questions — yes/no, choice, rating —+# over some material, and returns the probability behind each verdict.+#+# Documentation: https://docs.pipelex.com+# Support: https://go.pipelex.com/discord+#+################################################################################++################################################################################+# MODEL DEFAULTS+################################################################################++[defaults]+model_type = "judgment"+sdk = "typesafe"+thinking_mode = "none"++################################################################################+# JUDGMENT MODELS+################################################################################+#+# Always a VERSIONED id, never one of the provider's moving aliases: a verdict model that changes+# under a method silently changes what every threshold in that method means.+#+# Finding the next version is a documentation read, not a lookup. `GET /v1/models` lists only the+# aliases `jev-latest` and `jev-preview` and names no version anywhere in its body, so the versioned+# id comes from the provider's own models page. A truncated id is refused outright.+#+# Output tokens are genuinely free at the time of writing, which is why they are priced at zero+# rather than at an output rate. Prices are USD per million tokens.++["jev-1.13.0"]+model_id = "jev-1.13.0"+inputs = ["text"]+outputs = ["judgments"]+costs = { input = 0.042, output = 0 }diff --git a/api/.pipelex/inference/deck/6_judgment_deck.toml b/api/.pipelex/inference/deck/6_judgment_deck.tomlindex 3692726eb..01e45b3c5 100644--- a/api/.pipelex/inference/deck/6_judgment_deck.toml+++ b/api/.pipelex/inference/deck/6_judgment_deck.toml@@ -36,8 +36,12 @@## A judgment alias points at a VERSIONED model id, never at a provider's `latest` alias: a verdict# model that changes under a method silently changes what every threshold in that method means.+#+# `jev-1.13.0` is TypeSafe's. Its next version is found on the provider's models page and not through+# its API, whose model listing names only the moving aliases — moving this pin is a documentation read.[judgment.aliases]+default-judgment = "jev-1.13.0"##################################################################################################### Judgment Presetsdiff --git a/api/.pipelex/inference/routing_profiles.toml b/api/.pipelex/inference/routing_profiles.tomlindex 57407e0a6..25619b1ee 100644--- a/api/.pipelex/inference/routing_profiles.toml+++ b/api/.pipelex/inference/routing_profiles.toml@@ -28,6 +28,11 @@ active = "all_pipelex_gateway"description = "Use Pipelex Gateway for all its supported models"default = "pipelex_gateway"+# Judgment models are brought by you rather than served by Pipelex, so they go to their own backend+# whenever it is enabled. An optional route is inert while its backend is disabled.+[profiles.all_pipelex_gateway.optional_routes]+"jev-*" = "typesafe"+# The same model names, served by the Pipelex-operated inference service instead. Switching between# this profile and the one above needs no other edit: a model's wire id and sdk are per-backend, so# decks, aliases and presets keep naming the same handles.@@ -35,6 +40,11 @@ default = "pipelex_gateway"description = "Use Pipelex Manifold (private beta) for all its supported models"default = "pipelex_manifold"+# Judgment models are brought by you rather than served by Pipelex, so they go to their own backend+# whenever it is enabled. An optional route is inert while its backend is disabled.+[profiles.all_pipelex_manifold.optional_routes]+"jev-*" = "typesafe"+[profiles.all_anthropic]description = "Use Anthropic backend for all its supported models"default = "anthropic"@@ -99,6 +109,10 @@ default = "portkey"description = "Use Scaleway backend for all its supported models"default = "scaleway"+[profiles.all_typesafe]+description = "Use TypeSafe backend for all its supported models"+default = "typesafe"+[profiles.all_vertexai]description = "Use Vertex AI backend for all its supported models"default = "vertexai"diff --git a/docs/api-server/openapi/pipelex-api.openapi.yaml b/docs/api-server/openapi/pipelex-api.openapi.yamlindex 89577a9d6..5cebd2da5 100644--- a/docs/api-server/openapi/pipelex-api.openapi.yaml+++ b/docs/api-server/openapi/pipelex-api.openapi.yaml@@ -6818,6 +6818,7 @@ components:- huggingface- gateway- linkup+ - typesafe- docling- pypdfium2title: ProviderNamediff --git a/docs/configuration/config-technical/inference-backend-config.md b/docs/configuration/config-technical/inference-backend-config.mdindex 1d73b9858..e0b121bd2 100644--- a/docs/configuration/config-technical/inference-backend-config.md+++ b/docs/configuration/config-technical/inference-backend-config.md@@ -72,6 +72,7 @@ All inference backend configurations are stored in the `.pipelex/inference/` dir│ ├── vertexai.toml # Google Vertex AI models (LLMs)│ ├── fal.toml # FAL models (image generation)│ ├── linkup.toml # Linkup models (web search)+ │ ├── typesafe.toml # TypeSafe models (judgment)│ ├── internal.toml # Internal/local models (text extraction, the built-in document engine), managed by `pipelex update`│ └── ...└── deck/ # Model deck configurations@@ -258,6 +259,8 @@ GCP_CREDENTIALS_FILE_PATH=gcp_credentials.jsonFAL_API_KEY=LINKUP_API_KEY=++TYPESAFE_API_KEY=# ... (see .env.example for full list)```@@ -286,6 +289,10 @@ api_key = "${FAL_API_KEY}"enabled = trueapi_key = "${LINKUP_API_KEY}"+[typesafe]+enabled = true+api_key = "${TYPESAFE_API_KEY}"+[internal]enabled = true# No API key needed for internal/local processing@@ -293,6 +300,8 @@ enabled = trueThe `${VARIABLE_NAME}` syntax automatically loads values from your `.env` file. Set `enabled = true` to activate a backend, or `false` to disable it.+Judgment models are never served by the Pipelex Gateway, so the default routing profile sends them to their own backend through an optional route (`"jev-*" = "typesafe"`), which applies only while that backend is enabled. With a `TYPESAFE_API_KEY` set, `@default-judgment` works under the default profile with no routing edit.+### Model SpecificationsEach backend has its own model specification file in `.pipelex/inference/backends/`:diff --git a/docs/contribute/inference-family-surface.md b/docs/contribute/inference-family-surface.mdnew file mode 100644index 000000000..71394eb7e--- /dev/null+++ b/docs/contribute/inference-family-surface.md@@ -0,0 +1,53 @@+---+description: Every place a new inference family, and a new backend for it, has to be wired in — and which omissions fail silently.+---++# Inference family surface++An inference family is a kind of model call — LLM completion, image generation, extraction, web search, judgment. Adding one is not one package: the family's name is spelled in several enums, its usage flows through reporting and cost, its models live in a deck, and each of those places is separate, with nothing inferring one from another. This page is the checklist, written from the judgment family's addition, and a sibling of [the registration surface](registration-surface.md) for pipe kinds.++Most of the list is enforced by the type checker: the matches over the family enums are exhaustive with no `case _`, so adding the enum value walks you to their arms. The entries marked **silent** are the ones nothing walks you to, and they are the reason this page exists.++## A new family++1. **The family's package**, `pipelex/cogt/<family>/`, mirroring `pipelex/cogt/search/`: the question/request and answer models, the setting and its model-choice union, the job, the job factory, the usage report, the worker contract (`<Family>WorkerAbstract` with one template method and one abstract hook) and the worker factory, which resolves its worker through the inference-backend registry and holds no `match` over SDK strings.++2. **The family enums, together.** `InferenceFamily` in `pipelex/plugins/inference_backend_registry.py`, `ModelType` in `pipelex/cogt/model_backends/model_type.py`, `InferenceErrorFamily` in `pipelex/cogt/inference/error_render.py` with an entry in both its failure-class and not-found-class tables, and `ModelCategory` in `pipelex/builder/operations/models_ops.py`, which is what `pipelex-agent models` and `check-model` list from.++3. **The error classes** in `pipelex/cogt/exceptions.py`: a job failure, a model-not-found (subclassing `ModelNotFoundError`) and a handle-not-found. Then regenerate the error pages and the identity snapshot (`make gep`, `make gei`); the snapshot test fails until you do.++4. **The job identity** in `pipelex/system/job_metadata.py`: a `JobCategory` member, a `UnitJobId` member and its display arm.++5. **The deck.** A `<Family>DeckBlueprint`, its flat fields on `ModelDeck`, the setting getter, the preset validator, the choice check, the suggestion arms, and the model manager's handle collection and flattening. The kit deck is `pipelex/kit/configs/inference/deck/<n>_<family>_deck.toml` — the numeric prefix is what makes `pipelex update` manage it — mirrored into the repository's own `.pipelex/inference/deck/`.++6. **Reporting and cost.** The usage and cost-report classes join both unions in `pipelex/reporting/reporting_types.py`, `ReportingManager` gets its dispatch arm, and `CostRegistry.compute_cost_report` gets an arm in its `match`, which closes with `assert_never` so a family that falls through fails the type check. Update the `model_type` comment on `ModelUsageSpec` in `pipelex/graph/graphspec.py` to say how the family is billed.++7. **The content-generation leaf.** An assignment model in `pipelex/cogt/content_generation/assignment_models.py`, a `<family>_generate.py` module whose coroutine opens with the dry branch, the dry mock in `dry_mock.py`, and the method on `ContentGeneratorProtocol` with its `@override` in `ContentGenerator`. A host runtime's durable execution needs an activity and a queue for the new leaf in its own plugin.++8. **Test infrastructure.** A pytest marker in `pyproject.toml` and its term in the default deselect expression; the family in every table of `pipelex/cli/dev_cli/commands/preprocess_test_models_cmd.py`; a `<family>_models` key on every profile in `.pipelex-dev/test_profiles.toml`; a combo getter in `tests/integration/pipelex/fixtures/model_selection.py`, a combo fixture in `combo_fixtures.py` and its re-export in `tests/integration/pipelex/conftest.py`.++9. **The migration golden.** A new `ModelType` value changes the inference-backend surface's fingerprint; `make umig` records it, and the real-surfaces test fails until you do.++10. **Silent: fakes that stand in for the deck.** Any test double that impersonates `ModelDeck` by attribute — the fake deck in `tests/unit/pipelex/cli/test_agent_models_cmd.py` is one — needs the new family's presets, aliases and waterfalls, or every case using it fails with an `AttributeError` far from the cause.++11. **Silent: the MTHDS protocol's model categories.** `PipelexMTHDSProtocol.models()` in `pipelex/pipeline/runner.py` types each preset by the protocol's own `ModelCategory`. A family the protocol cannot name is skipped there rather than raised on; the protocol has to learn the member before the family's presets are visible through it.++12. **Silent: a default the gateway does not serve fails every boot.** The model manager checks, at boot, every handle a deck's presets and choice defaults name against the Pipelex Gateway's specs when the active routing profile sends that handle there. A family whose models only a bring-your-own-key backend serves must therefore ship **no** `choice_default` and **no** preset in the kit deck — an alias is fine, because aliases are not walked. Getting this wrong fails the boot of every installation, whether or not it ever uses the family.++## A new backend for a family++1. **The provider package**, `pipelex/providers/<vendor>/`: the plugin, the worker, the translation to and from the vendor's vocabulary, and a `<vendor>_exceptions.py`. The vendor's own limits are enforced in the translation, not in a blueprint.++2. **Error classification.** An `extract_<vendor>_metadata` function and a `ProviderName` member in `pipelex/cogt/inference/`, with the member added to every exhaustive match over `ProviderName` and to the parity test in `tests/unit/pipelex/cogt/inference/test_provider_classification_parity.py`. When the vendor's status codes cannot separate its failures, the worker branches on the body before handing the rest to the shared classifier.++3. **Registration.** The plugin joins `KERNEL_BUILTIN_PLUGINS` in `pipelex/providers/builtins.py`. Its `make_worker` closure calls `require_sdk` before importing the worker, and imports no SDK at module level. Record the `register` method's subject grant before `make agent-check`, whose keyword-only fixer would otherwise rewrite it into a signature the plugin protocol refuses.++4. **Configuration.** The backend's table in the kit's `backends.toml`, its model file under `backends/`, and an `all_<vendor>` routing profile — which is also what the integration combo fixtures route to — all mirrored into `.pipelex/inference/`. Its API key variable goes in `.env.example`.++5. **Silent: the default routing profile.** Under `all_pipelex_gateway` every handle routes to the gateway by default, and a handle the gateway does not serve is silently dropped from the deck — so a user who has the vendor's key still cannot use its models. Give the managed profiles an `optional_routes` entry sending the vendor's models to its backend; an optional route applies only while that backend is enabled.++6. **Silent: the CI placeholder list.** CI runners hold no provider keys, and every test module boots live, so each variable an enabled kit backend references must be in `ENV_VAR_KEYS_WHICH_MAY_NEED_PLACEHOLDERS_IN_CI` in `pipelex/test_extras/shared_pytest_plugins.py`. `tests/unit/pipelex/test_extras/test_ci_placeholder_keys.py` fails when one is missing. The agent CLI's end-to-end tests build their own hermetic environment, with a dummy value per variable, in the `offline_subprocess_env` fixture of `tests/e2e/agent_cli/conftest.py`, and nothing checks that list: a variable missing there only makes a dry run skip the backend.++7. **Plugin surface tests.** The `(family, sdk)` pair in `tests/unit/pipelex/plugins/test_inference_backend_coverage.py`, a missing-extra guard test mirroring Linkup's, the SDK's import name in the blocked list of `tests/unit/pipelex/plugins/test_import_light_boot.py`, and an arm in `tests/integration/pipelex/system/test_keyless_boot_forced_dry.py` showing that a keyless boot does not need the key.++8. **Live tests** under a test profile of their own, marked with the family's marker and `inference`, so that `make ti PROF=<profile>` runs them and every other profile skips them.diff --git a/docs/errors/inference-and-providers.md b/docs/errors/inference-and-providers.mdindex bed8c44f8..20d21eec7 100644--- a/docs/errors/inference-and-providers.md+++ b/docs/errors/inference-and-providers.md@@ -119,6 +119,9 @@ own page. Classes are grouped by subsystem.- [`PortkeyCredentialsError`](portkey-credentials-error.md) — Portkey credentials- [`PortkeyError`](portkey-error.md) — Portkey- [`PortkeyFactoryError`](portkey-factory-error.md) — Portkey factory+- [`TypesafeError`](typesafe-error.md) — Typesafe+- [`TypesafeJudgmentResponseError`](typesafe-judgment-response-error.md) — Typesafe judgment response+- [`TypesafeQuestionUnsupportedError`](typesafe-question-unsupported-error.md) — Typesafe question unsupported- [`VertexAIConfigError`](vertex-ai-config-error.md) — VertexAI configuration error- [`VertexAICredentialsError`](vertex-ai-credentials-error.md) — VertexAI credentials errordiff --git a/docs/errors/typesafe-error.md b/docs/errors/typesafe-error.mdnew file mode 100644index 000000000..cdffc1954--- /dev/null+++ b/docs/errors/typesafe-error.md@@ -0,0 +1,21 @@+---+title: "Typesafe"+description: "Reference for the `TypesafeError` Pipelex error class."+---++<!-- pipelex:generated -->++# Typesafe++Base for every error this backend raises, so callers can catch the provider as a family.++| Field | Value |+|---|---|+| `error_type` | `TypesafeError` |+| `title` | Typesafe |+| `type_uri` | `https://docs.pipelex.com/latest/errors/typesafe-error/` |+| `error_domain` | _(inherited from parent)_ |+| Defined in | `pipelex.providers.typesafe.typesafe_exceptions` |+| Parent class | [`CogtError`](cogt-error.md) |++[Back to Error Reference](index.md)diff --git a/docs/errors/typesafe-judgment-response-error.md b/docs/errors/typesafe-judgment-response-error.mdnew file mode 100644index 000000000..08d4554d8--- /dev/null+++ b/docs/errors/typesafe-judgment-response-error.md@@ -0,0 +1,21 @@+---+title: "Typesafe judgment response"+description: "Reference for the `TypesafeJudgmentResponseError` Pipelex error class."+---++<!-- pipelex:generated -->++# Typesafe judgment response++The TypeSafe API answered a judgment with an answer that is missing, or of the wrong kind.++| Field | Value |+|---|---|+| `error_type` | `TypesafeJudgmentResponseError` |+| `title` | Typesafe judgment response |+| `type_uri` | `https://docs.pipelex.com/latest/errors/typesafe-judgment-response-error/` |+| `error_domain` | _(inherited from parent)_ |+| Defined in | `pipelex.providers.typesafe.typesafe_exceptions` |+| Parent class | [`TypesafeError`](typesafe-error.md) |++[Back to Error Reference](index.md)diff --git a/docs/errors/typesafe-question-unsupported-error.md b/docs/errors/typesafe-question-unsupported-error.mdnew file mode 100644index 000000000..768be068c--- /dev/null+++ b/docs/errors/typesafe-question-unsupported-error.md@@ -0,0 +1,21 @@+---+title: "Typesafe question unsupported"+description: "Reference for the `TypesafeQuestionUnsupportedError` Pipelex error class."+---++<!-- pipelex:generated -->++# Typesafe question unsupported++The question is legal MTHDS that this backend will not serve.++| Field | Value |+|---|---|+| `error_type` | `TypesafeQuestionUnsupportedError` |+| `title` | Typesafe question unsupported |+| `type_uri` | `https://docs.pipelex.com/latest/errors/typesafe-question-unsupported-error/` |+| `error_domain` | _(inherited from parent)_ |+| Defined in | `pipelex.providers.typesafe.typesafe_exceptions` |+| Parent class | [`TypesafeError`](typesafe-error.md) |++[Back to Error Reference](index.md)diff --git a/docs/under-the-hood/distributed-content-generation.md b/docs/under-the-hood/distributed-content-generation.mdindex 96d8d9f87..f9cd004db 100644--- a/docs/under-the-hood/distributed-content-generation.md+++ b/docs/under-the-hood/distributed-content-generation.md@@ -7,7 +7,7 @@ description: "How Pipelex serializes dynamic Pydantic models and large binary coThis page is for contributors working on Pipelex internals. For the capability overview, see the user-facing [Distributed Execution](../distributed-execution/index.md) page instead.-When content generation (LLM structured output, image generation, PDF extraction, web search) runs on a separate worker process, two serialization problems appear that single-process execution never faces. This page covers them backend-neutrally — the mechanisms live in open core and are the same regardless of which host runtime carries the payload. The concrete activity dispatch is a [commercial platform capability](https://pipelex.com/products#durable-execution); each backend (Temporal, Mistral Workflows) realizes it in its own plugin.+When content generation (LLM structured output, image generation, PDF extraction, web search, judgment) runs on a separate worker process, two serialization problems appear that single-process execution never faces. This page covers them backend-neutrally — the mechanisms live in open core and are the same regardless of which host runtime carries the payload. The concrete activity dispatch is a [commercial platform capability](https://pipelex.com/products#durable-execution); each backend (Temporal, Mistral Workflows) realizes it in its own plugin.!!! note "Every inference leaf goes through the same seam"All inference operators dispatch their leaf call through the swappable `ContentGenerator` abstraction (`pipelex/cogt/content_generation/content_generator.py`): direct inline, or — on a host runtime — wrapped as an activity by the runtime's in-workflow content generator. The backend choice is independent of the run mode: under `run_mode=DRY` the chosen backend still dispatches and the leaf mocks inside it. Wrapping the leaf as a host-runtime activity is what makes it replay-safe (the result is recorded in the run's history) and lets a leaf failure cross the worker boundary as a classified error, instead of re-executing on every replay and hanging the submitter with an unclassified fault.@@ -127,6 +127,10 @@ Structured web search (`PipeSearch` with a non-text output concept) faces the idThe sourced-answer path (`make_search_sourced_answer`) has no dynamic class at all: it returns a `SearchResultContent`, a native serializable model.+### Judgments need neither mechanism++A judgment's leaf, `judgment_gen_answers`, has one entry point where search has three, because nothing about it is dynamic. Its `JudgmentAssignment` carries the state as a JSON object, the questions as the family's own discriminated models and the resolved `JudgmentSetting`; its result is a map of answers that are plain models of the same package. No caller class travels down and no schema is shipped, so the in-process arm and the boundary arm would be the same function, and there is nothing to split.+---## Large payload management@@ -166,6 +170,7 @@ What gets stored vs. what crosses the boundary, by content type:| LLM object | Nothing (JSON is small) | `BaseModel` + `__kajson_class_source__` in metadata || Search sourced answer | Nothing (answer + source refs are small) | `SearchResultContent` (answer + `DocumentContent` sources) || Search structured | Nothing (JSON is small) | Raw `dict`, re-validated against the output class on the submitter |+| Judgment answers | Nothing (verdicts are small) | `dict[str, JudgmentAnswer]` keyed as the questions were |Each host-runtime plugin dispatches these through its own activities and queue routing; for the Temporal realization (the `act_*` activity set, per-activity task queues), see our Temporal plugin's own docs.@@ -218,6 +223,7 @@ Resolution order:| Content generator (type bridge) | `pipelex/cogt/content_generation/content_generator.py` || LLM generation functions | `pipelex/cogt/content_generation/llm_generate.py` || Search generation functions | `pipelex/cogt/content_generation/search_generate.py` |+| Judgment generation function | `pipelex/cogt/content_generation/judgment_generate.py` || Generated content factory (storage) | `pipelex/cogt/content_generation/generated_content_factory.py` || Kajson serialization | `kajson` (external PyPI package) || ImageContent model | `pipelex/core/stuffs/image_content.py` |diff --git a/docs/under-the-hood/inference-backend-plugins.md b/docs/under-the-hood/inference-backend-plugins.mdindex b7910e3c3..939fca852 100644--- a/docs/under-the-hood/inference-backend-plugins.md+++ b/docs/under-the-hood/inference-backend-plugins.md@@ -65,7 +65,7 @@ registrar.add_inference_backend(A registry key is `(family, sdk)`. The same `sdk` string may appear in two families (e.g. `google` serves both `LLM` and `IMG_GEN`); they are distinct keys. A duplicate `(family, sdk)` fails loud with `DuplicateInferenceBackendError` naming **both** contributing plugins.-One plugin may register across several families from a single `register` — the built-in `gateway` plugin serves the four inference families, `mistral` serves `LLM` + `EXTRACT`, `linkup` serves `EXTRACT` + `SEARCH`. This is the cross-family-vendor coordination point: one plugin, many backends. `DOC_GEN` is the family of the document engines a `PipeDocGen` step prints with, local libraries rather than inference, which the built-in `reportlab` plugin and the Pipelex document generation plugin serve (see [Document Engine Plugins](document-engine-plugins.md)).+One plugin may register across several families from a single `register` — the built-in `gateway` plugin serves the four inference families, `mistral` serves `LLM` + `EXTRACT`, `linkup` serves `EXTRACT` + `SEARCH`, and `typesafe` serves `JUDGMENT` alone. This is the cross-family-vendor coordination point: one plugin, many backends. `DOC_GEN` is the family of the document engines a `PipeDocGen` step prints with, local libraries rather than inference, which the built-in `reportlab` plugin and the Pipelex document generation plugin serve (see [Document Engine Plugins](document-engine-plugins.md)).A plugin whose backend runs without an external service, such as a document engine, may also declare the models it serves rather than leave them to a backend file. `add_internal_model(name=…, spec=…)` declares a model in the `internal` backend, the spec being the table a backend file would hold for it, and `add_doc_gen_default(doc_gen_format=…, source=…, model=…)` declares the model deck's default engine for a document format and source. Both are stored at registration and merged by the model manager at boot, and [Document Engine Plugins](document-engine-plugins.md#registering-an-engine) gives their rules.@@ -89,7 +89,7 @@ The factory always passes all four keyword arguments. A stateless backend simplyTwo invariants shape what goes *inside* the closure:-- **Import-light.** The plugin module must import no backend SDK at module load. Do the SDK import **inside** the closure (`# noqa: PLC0415`), so merely discovering the plugin never pulls a heavy/optional dependency. Booting Pipelex with the built-ins registered imports none of `anthropic`, `mistralai`, `google.genai`, `boto3`, `fal_client`, `huggingface_hub`, `docling`, `linkup`, … — enforced by a subprocess import-blocker guard.+- **Import-light.** The plugin module must import no backend SDK at module load. Do the SDK import **inside** the closure (`# noqa: PLC0415`), so merely discovering the plugin never pulls a heavy/optional dependency. Booting Pipelex with the built-ins registered imports none of `anthropic`, `mistralai`, `google.genai`, `boto3`, `fal_client`, `huggingface_hub`, `docling`, `linkup`, `typesafe_sdk`, … — enforced by a subprocess import-blocker guard.- **Fail at use, not at boot.** Guard an optional dependency with `require_sdk(...)` *inside* the closure. A missing extra then raises `MissingDependencyError` (naming the package and the `pipelex[<extra>]` install hint) only when the backend is actually used.Client memoization goes through `sdk_clients.get_or_create(handle=…, build=lambda: …)` — the registry caches one SDK client per `ModelHandle`, so repeated worker construction reuses the connection.diff --git a/mkdocs.yml b/mkdocs.ymlindex 6c15d031c..f82775bc7 100644--- a/mkdocs.yml+++ b/mkdocs.yml@@ -368,6 +368,7 @@ plugins:- contribute/actions-allowlist.md: "Actions Allowlist"- contribute/test-duration-map.md: "Test Duration Map"- contribute/registration-surface.md: "Registration Surface"+ - contribute/inference-family-surface.md: "Inference Family Surface"- contribute/drift-contracts.md: "Drift Contracts"- contribute/mthds-test-corpus.md: "MTHDS Test Corpus"- contribute/trace-input-semantics.md: "Tracing Input Semantics"@@ -620,6 +621,7 @@ nav:- Actions Allowlist: contribute/actions-allowlist.md- Test Duration Map: contribute/test-duration-map.md- Registration Surface: contribute/registration-surface.md+ - Inference Family Surface: contribute/inference-family-surface.md- Drift Contracts: contribute/drift-contracts.md- MTHDS Test Corpus: contribute/mthds-test-corpus.md- Tracing Input Semantics: contribute/trace-input-semantics.mddiff --git a/pipelex/cogt/inference/error_classification.py b/pipelex/cogt/inference/error_classification.pyindex b65719455..eab0cac73 100644--- a/pipelex/cogt/inference/error_classification.py+++ b/pipelex/cogt/inference/error_classification.py@@ -10,6 +10,7 @@ import jsonfrom datetime import UTC, datetimefrom email.utils import parsedate_to_datetimefrom enum import StrEnum+from http import HTTPStatusfrom typing import Any, TypeAlias, castimport httpx@@ -413,7 +414,13 @@ class ProviderErrorMetadata(BaseModel):case ProviderName.GATEWAY:return _is_quota_exhaustion_gateway(self.message, status_code=self.status_code or 0)case (- ProviderName.AZURE | ProviderName.FAL | ProviderName.HUGGINGFACE | ProviderName.LINKUP | ProviderName.DOCLING | ProviderName.PYPDFIUM2+ ProviderName.AZURE+ | ProviderName.FAL+ | ProviderName.HUGGINGFACE+ | ProviderName.LINKUP+ | ProviderName.TYPESAFE+ | ProviderName.DOCLING+ | ProviderName.PYPDFIUM2):return False@@ -1389,6 +1396,76 @@ def extract_linkup_metadata(exc: BaseException) -> ProviderErrorMetadata:)+# The ``error_type`` values TypeSafe puts in an object-shaped ``detail``. Spelled here rather than+# in the provider package because ``provider_error_code`` is this module's field and the classifier+# reads it: a value that never appears here is a value nothing downstream can branch on.+TYPESAFE_AUTHENTICATION_ERROR_TYPE = "authentication_error"+TYPESAFE_MAX_TOKENS_EXCEEDED_ERROR_TYPE = "max_tokens_exceeded"+TYPESAFE_API_USAGE_ERROR_TYPE = "api_usage_error"++# What a bare-string ``detail`` on a ``400`` is reported as. TypeSafe answers 400 with a plain sentence for the+# question-shape refusals — "Noul question must have criteria or instructions: q", "Too many score+# levels. Must have at most 10 levels." — and carries no ``error_type`` at all. The absence is the+# signal, so it is given a code of its own instead of leaving ``provider_error_code`` empty, which+# would make "the body said nothing" indistinguishable from "there was no body".+TYPESAFE_MALFORMED_REQUEST_CODE = "pipelex_typesafe_malformed_request"+++def _typesafe_detail(*, body: Any) -> Any | None:+ """The ``detail`` member of a TypeSafe error body, whatever shape it has."""+ if isinstance(body, str):+ try:+ body = json.loads(body)+ except (TypeError, ValueError):+ return None+ if isinstance(body, dict):+ return cast("dict[str, Any]", body).get("detail")+ return None+++def extract_typesafe_metadata(exc: BaseException) -> ProviderErrorMetadata:+ """Distill a TypeSafe SDK exception into a ``ProviderErrorMetadata``.++ Two exception shapes reach here and they carry different things. A ``TypeSafeAPIError``+ subclass reached the server and carries ``status``, ``body``, ``endpoint`` and a ``request_id``+ that is declared ``str | None`` and safe to read plainly. A bare ``TypeSafeError`` is the SDK+ refusing before it sent anything — no status, no body, no request id — and the absent status is+ what routes it to the status-less arm of the classifier.++ ``provider_error_code`` is the discriminator the status cannot supply. Every validation failure+ this API produces is a ``400``, covering an illegal question, an oversized state and an unknown+ model alike, so the code is lifted out of the body: the ``error_type`` of an object-shaped+ ``detail``, or ``TYPESAFE_MALFORMED_REQUEST_CODE`` when a ``400``'s ``detail`` is a bare+ sentence. A bare sentence on any other status says nothing the status does not, so a rate limit+ or an outage answered in that shape keeps the status ladder's verdict.+ """+ body = getattr(exc, "body", None)+ status_code = getattr(exc, "status", None)+ detail = _typesafe_detail(body=body)+ provider_error_code: str | None = None+ if isinstance(detail, dict):+ error_type = cast("dict[str, Any]", detail).get("error_type")+ if isinstance(error_type, str):+ provider_error_code = error_type+ elif isinstance(detail, str) and status_code == HTTPStatus.BAD_REQUEST:+ provider_error_code = TYPESAFE_MALFORMED_REQUEST_CODE+ request_id = getattr(exc, "request_id", None)+ headers = getattr(exc, "headers", None)+ retry_after_seconds: float | None = None+ if headers is not None:+ retry_after_seconds = _parse_retry_after_seconds(headers.get("retry-after"))+ return ProviderErrorMetadata(+ provider=ProviderName.TYPESAFE,+ sdk_exception_type=type(exc).__name__,+ message=str(exc),+ status_code=status_code,+ request_id=request_id if isinstance(request_id, str) else None,+ retry_after_seconds=retry_after_seconds,+ provider_error_code=provider_error_code,+ body=body,+ )++_LOCAL_EXTRACT_TYPE_HIERARCHY: tuple[tuple[type[BaseException], str], ...] = (# ``FileNotFoundError`` is itself an ``OSError`` subclass, so it must be probed# first; otherwise a missing file would normalize to ``OSError`` → TRANSIENTdiff --git a/pipelex/cogt/inference/error_classify.py b/pipelex/cogt/inference/error_classify.pyindex f1b5ea0ea..103d28ee1 100644--- a/pipelex/cogt/inference/error_classify.py+++ b/pipelex/cogt/inference/error_classify.py@@ -78,6 +78,14 @@ _STATUSLESS_BY_TYPE_NAME: dict[str, tuple[InferenceErrorCategory, UserActionKind"LinkupFetchUrlIsFileError": (InferenceErrorCategory.CONTENT, UserActionKind.CHANGE_INPUT),"LinkupFailedFetchError": (InferenceErrorCategory.TRANSIENT, UserActionKind.WAIT_AND_RETRY),"LinkupUnknownError": (InferenceErrorCategory.TRANSIENT, UserActionKind.WAIT_AND_RETRY),+ # TypeSafe's client-side refusal: the SDK validates a request it will not send (an empty+ # questions map, a rating with no levels) and raises the bare base class, with no status, no+ # body and no request id. Every one of those is a shape our own blueprint validation is+ # supposed to have refused first, so it is a Pipelex defect rather than a vendor failure —+ # CONFIGURATION says nothing the caller wrote caused it and CONTACT_SUPPORT says who can fix+ # it. Its HTTP-reaching siblings (``TypeSafeAPITimeoutError``, ``TypeSafeAPIConnectionError``)+ # never arrive here: ``is_network_error`` matches their names first.+ "TypeSafeError": (InferenceErrorCategory.CONFIGURATION, UserActionKind.CONTACT_SUPPORT),# FAL's typed credential failure — raised before any HTTP call when the API key is unset"MissingCredentialsError": (InferenceErrorCategory.CONFIGURATION, UserActionKind.CHECK_CREDENTIALS),# FAL's generic SDK error (base class) — caught last in the worker; HTTP/timeout variantsdiff --git a/pipelex/cogt/inference/provider_name.py b/pipelex/cogt/inference/provider_name.pyindex d7cb90ead..00fee491c 100644--- a/pipelex/cogt/inference/provider_name.py+++ b/pipelex/cogt/inference/provider_name.py@@ -22,6 +22,7 @@ class ProviderName(StrEnum):HUGGINGFACE = "huggingface"GATEWAY = "gateway"LINKUP = "linkup"+ TYPESAFE = "typesafe"DOCLING = "docling"PYPDFIUM2 = "pypdfium2"@@ -47,5 +48,6 @@ class ProviderName(StrEnum):| ProviderName.HUGGINGFACE| ProviderName.GATEWAY| ProviderName.LINKUP+ | ProviderName.TYPESAFE):return Falsediff --git a/pipelex/cogt/model_routing/routing_profile.py b/pipelex/cogt/model_routing/routing_profile.pyindex 822aef0e6..b30790a30 100644--- a/pipelex/cogt/model_routing/routing_profile.py+++ b/pipelex/cogt/model_routing/routing_profile.py@@ -34,7 +34,8 @@ class RoutingProfile(ConfigModel):Backend name to use for this model"""- possible_routes = self.routes+ # A copy: the enabled optional routes are merged for this match only, never into the declared `routes`.+ possible_routes = dict(self.routes)for pattern, backend in self.optional_routes.items():if backend not in enabled_backends:continuediff --git a/pipelex/graph/graphspec.py b/pipelex/graph/graphspec.pyindex b82a92325..51710f3ea 100644--- a/pipelex/graph/graphspec.py+++ b/pipelex/graph/graphspec.py@@ -309,10 +309,11 @@ class ModelUsageSpec(BaseModel):inference_model_name: strinference_model_id: str- # Kind of inference: "llm", "img_gen", "extract", "search". The discriminator a+ # Kind of inference: "llm", "img_gen", "extract", "search", "judgment". The discriminator a# consumer needs before displaying token counts: extract/search/img_gen are billed# PER REQUEST, and that price is encoded by putting 1_000_000 in each token# category (rates are per-million), so their "tokens" are a scaled request counter.+ # llm and judgment report the real tokens the provider read and wrote.model_type: strinference_calls: int = 0rated_inference_calls: int = 0diff --git a/pipelex/kit/configs/inference/backends.toml b/pipelex/kit/configs/inference/backends.tomlindex eb2803675..28a5a7777 100644--- a/pipelex/kit/configs/inference/backends.toml+++ b/pipelex/kit/configs/inference/backends.toml@@ -110,6 +110,11 @@ enabled = trueendpoint = "${SCALEWAY_ENDPOINT}"api_key = "${SCALEWAY_API_KEY}"+[typesafe]+display_name = "TypeSafe"+enabled = true+api_key = "${TYPESAFE_API_KEY}"+[vertexai]display_name = "Google Vertex AI"enabled = false # This is the only one we disable because setting it up requires internet access just to get credentials so it fails in CI sandboxesdiff --git a/pipelex/kit/configs/inference/backends/typesafe.toml b/pipelex/kit/configs/inference/backends/typesafe.tomlnew file mode 100644index 000000000..85b3a1a83--- /dev/null+++ b/pipelex/kit/configs/inference/backends/typesafe.toml@@ -0,0 +1,41 @@+################################################################################+# TypeSafe Backend Configuration+################################################################################+#+# This file defines the model specifications for TypeSafe judgment models.+# TypeSafe's System One answers closed-form questions — yes/no, choice, rating —+# over some material, and returns the probability behind each verdict.+#+# Documentation: https://docs.pipelex.com+# Support: https://go.pipelex.com/discord+#+################################################################################++################################################################################+# MODEL DEFAULTS+################################################################################++[defaults]+model_type = "judgment"+sdk = "typesafe"+thinking_mode = "none"++################################################################################+# JUDGMENT MODELS+################################################################################+#+# Always a VERSIONED id, never one of the provider's moving aliases: a verdict model that changes+# under a method silently changes what every threshold in that method means.+#+# Finding the next version is a documentation read, not a lookup. `GET /v1/models` lists only the+# aliases `jev-latest` and `jev-preview` and names no version anywhere in its body, so the versioned+# id comes from the provider's own models page. A truncated id is refused outright.+#+# Output tokens are genuinely free at the time of writing, which is why they are priced at zero+# rather than at an output rate. Prices are USD per million tokens.++["jev-1.13.0"]+model_id = "jev-1.13.0"+inputs = ["text"]+outputs = ["judgments"]+costs = { input = 0.042, output = 0 }diff --git a/pipelex/kit/configs/inference/deck/6_judgment_deck.toml b/pipelex/kit/configs/inference/deck/6_judgment_deck.tomlindex 3692726eb..01e45b3c5 100644--- a/pipelex/kit/configs/inference/deck/6_judgment_deck.toml+++ b/pipelex/kit/configs/inference/deck/6_judgment_deck.toml@@ -36,8 +36,12 @@## A judgment alias points at a VERSIONED model id, never at a provider's `latest` alias: a verdict# model that changes under a method silently changes what every threshold in that method means.+#+# `jev-1.13.0` is TypeSafe's. Its next version is found on the provider's models page and not through+# its API, whose model listing names only the moving aliases — moving this pin is a documentation read.[judgment.aliases]+default-judgment = "jev-1.13.0"##################################################################################################### Judgment Presetsdiff --git a/pipelex/kit/configs/inference/routing_profiles.toml b/pipelex/kit/configs/inference/routing_profiles.tomlindex 57407e0a6..25619b1ee 100644--- a/pipelex/kit/configs/inference/routing_profiles.toml+++ b/pipelex/kit/configs/inference/routing_profiles.toml@@ -28,6 +28,11 @@ active = "all_pipelex_gateway"description = "Use Pipelex Gateway for all its supported models"default = "pipelex_gateway"+# Judgment models are brought by you rather than served by Pipelex, so they go to their own backend+# whenever it is enabled. An optional route is inert while its backend is disabled.+[profiles.all_pipelex_gateway.optional_routes]+"jev-*" = "typesafe"+# The same model names, served by the Pipelex-operated inference service instead. Switching between# this profile and the one above needs no other edit: a model's wire id and sdk are per-backend, so# decks, aliases and presets keep naming the same handles.@@ -35,6 +40,11 @@ default = "pipelex_gateway"description = "Use Pipelex Manifold (private beta) for all its supported models"default = "pipelex_manifold"+# Judgment models are brought by you rather than served by Pipelex, so they go to their own backend+# whenever it is enabled. An optional route is inert while its backend is disabled.+[profiles.all_pipelex_manifold.optional_routes]+"jev-*" = "typesafe"+[profiles.all_anthropic]description = "Use Anthropic backend for all its supported models"default = "anthropic"@@ -99,6 +109,10 @@ default = "portkey"description = "Use Scaleway backend for all its supported models"default = "scaleway"+[profiles.all_typesafe]+description = "Use TypeSafe backend for all its supported models"+default = "typesafe"+[profiles.all_vertexai]description = "Use Vertex AI backend for all its supported models"default = "vertexai"diff --git a/pipelex/kit/deck_variants/multi_provider/6_judgment_deck.toml b/pipelex/kit/deck_variants/multi_provider/6_judgment_deck.tomlindex 3692726eb..01e45b3c5 100644--- a/pipelex/kit/deck_variants/multi_provider/6_judgment_deck.toml+++ b/pipelex/kit/deck_variants/multi_provider/6_judgment_deck.toml@@ -36,8 +36,12 @@## A judgment alias points at a VERSIONED model id, never at a provider's `latest` alias: a verdict# model that changes under a method silently changes what every threshold in that method means.+#+# `jev-1.13.0` is TypeSafe's. Its next version is found on the provider's models page and not through+# its API, whose model listing names only the moving aliases — moving this pin is a documentation read.[judgment.aliases]+default-judgment = "jev-1.13.0"##################################################################################################### Judgment Presetsdiff --git a/pipelex/providers/builtins.py b/pipelex/providers/builtins.pyindex 3185617df..4b0ec9058 100644--- a/pipelex/providers/builtins.py+++ b/pipelex/providers/builtins.py@@ -20,6 +20,7 @@ from pipelex.providers.pypdfium2.pypdfium2_plugin import Pypdfium2Pluginfrom pipelex.providers.reportlab.reportlab_plugin import ReportlabDocGenPluginfrom pipelex.providers.secrets.secrets_plugin import SecretsPluginfrom pipelex.providers.storage.storage_plugin import StoragePlugin+from pipelex.providers.typesafe.typesafe_plugin import TypesafePlugin# The **kernel-layer** half of the plugins Pipelex ships with: inference backends, extraction and# search drivers, storage and secrets. Every one of them adapts a kernel-layer port, so this module@@ -56,6 +57,7 @@ KERNEL_BUILTIN_PLUGINS: list[PipelexPlugin] = [Pypdfium2Plugin(),LinkupPlugin(),ReportlabDocGenPlugin(),+ TypesafePlugin(),]# Kernel-layer built-ins that core requires unconditionally — naming one in ``runtime.plugins.disabled`` is adiff --git a/pipelex/providers/typesafe/__init__.py b/pipelex/providers/typesafe/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/pipelex/providers/typesafe/typesafe_client_factory.py b/pipelex/providers/typesafe/typesafe_client_factory.pynew file mode 100644index 000000000..5026b4fda--- /dev/null+++ b/pipelex/providers/typesafe/typesafe_client_factory.py@@ -0,0 +1,49 @@+"""The one place this backend's transport behaviour is decided.++The SDK ships a `RetryPolicy` of its own and would apply it silently. Retrying is a Pipelex+decision, so the policy is built here from the runtime's own `transport_max_retries` and handed to+the client explicitly.++**There are three timeouts in this SDK and they are not the same one.** The client carries a+timeout, the retry policy carries its own beside it, and `system_one` takes a per-call override.+Both of the first two are set here, deliberately and to the same value, so that a retried request+cannot outlive the budget the caller was promised. The per-call override is deliberately never+passed: it exists to depart from the client's settings, and this backend has no call that should.+"""++from typesafe_sdk import AsyncTypeSafeClient, RetryPolicy++from pipelex.cogt.model_backends.backend import InferenceBackend+from pipelex.config import get_config+from pipelex.providers.typesafe.typesafe_exceptions import TypesafeError++# How long one judgment may take, retries included. A single request answers in about a quarter of+# a second and fifty questions in one request answer in the same quarter, so this is a wide margin+# rather than a working budget — it is here to bound a hung connection, not to bound the model.+TYPESAFE_REQUEST_TIMEOUT_SECONDS = 60.0+++def make_typesafe_client(*, backend: InferenceBackend) -> AsyncTypeSafeClient:+ """Build the shared async client for a TypeSafe backend.++ One client serves every concurrent judgment — the spike ran forty at once through a single one+ with no interference — which is why the plugin caches it in the ``SdkClientRegistry`` rather+ than building one per worker.+ """+ if not backend.api_key:+ msg = f"Inference backend '{backend.name}' has no API key configured, so TypeSafe judgments cannot be requested"+ raise TypesafeError(msg)+ return AsyncTypeSafeClient(+ api_key=backend.api_key,+ base_url=backend.endpoint,+ retry=make_typesafe_retry_policy(),+ timeout=TYPESAFE_REQUEST_TIMEOUT_SECONDS,+ )+++def make_typesafe_retry_policy() -> RetryPolicy:+ """The retry budget this backend runs under, taken from the runtime's own transport setting."""+ return RetryPolicy(+ max_retries=get_config().inference.transport_max_retries,+ timeout=TYPESAFE_REQUEST_TIMEOUT_SECONDS,+ )diff --git a/pipelex/providers/typesafe/typesafe_error_classification.py b/pipelex/providers/typesafe/typesafe_error_classification.pynew file mode 100644index 000000000..c22e266f0--- /dev/null+++ b/pipelex/providers/typesafe/typesafe_error_classification.py@@ -0,0 +1,76 @@+"""Turning a TypeSafe refusal into a verdict, when the HTTP status cannot say what happened.++The shared Classify step reads the status ladder, and for most providers that is enough. It is not+enough here: **every validation failure this API produces is a `400`** — an illegal question, a+state over the context limit and a model name that does not exist all arrive under the same status,+and the ladder reads all three as "the provider rejected your content". The three have nothing in+common: one is our own bug, one is the caller's material, one is the deck.++What separates them is the body. TypeSafe answers with a `detail` that is either an object carrying+an ``error_type`` or a bare sentence, and the Extract step lifts that into ``provider_error_code``.+This module branches on it and hands everything it does not recognise — including every status the+ladder already reads correctly, ``401`` and ``429`` and the 5xx range — straight to the shared+classifier, which stays provider-blind.+"""++from pipelex.cogt.exceptions import InferenceErrorCategory+from pipelex.cogt.inference.error_classification import (+ TYPESAFE_API_USAGE_ERROR_TYPE,+ TYPESAFE_AUTHENTICATION_ERROR_TYPE,+ TYPESAFE_MALFORMED_REQUEST_CODE,+ TYPESAFE_MAX_TOKENS_EXCEEDED_ERROR_TYPE,+ SDKErrorEnvelope,+ UserActionKind,+)+from pipelex.cogt.inference.error_classify import ClassificationResult, classify_inference_error++# What an ``api_usage_error`` says when the model name is the thing that was wrong. The only shape+# of that code seen against the live API, and the one worth naming a verdict for.+_UNKNOWN_MODEL_MARKER = "unknown model"+++def classify_typesafe_error(metadata: SDKErrorEnvelope) -> ClassificationResult:+ """Classify a TypeSafe failure, reading the body's ``error_type`` before the status ladder."""+ match metadata.provider_error_code:+ case None:+ return classify_inference_error(metadata)+ case code if code == TYPESAFE_AUTHENTICATION_ERROR_TYPE:+ # Observed on a 401, where the ladder agrees. Named anyway because the code is the+ # contract and the status is not: this API answers 400 for everything else it refuses.+ return ClassificationResult(+ category=InferenceErrorCategory.CONFIGURATION,+ user_action_kind=UserActionKind.CHECK_CREDENTIALS,+ )+ case code if code == TYPESAFE_MAX_TOKENS_EXCEEDED_ERROR_TYPE:+ # The state plus the longest question went over the context limit. The caller's+ # material is what has to shrink, and the ladder's 400 arm happens to agree.+ return ClassificationResult(+ category=InferenceErrorCategory.CONTENT,+ user_action_kind=UserActionKind.CHANGE_INPUT,+ )+ case code if code == TYPESAFE_API_USAGE_ERROR_TYPE:+ if _UNKNOWN_MODEL_MARKER in metadata.message.lower():+ # The deck names a judgment model this API does not serve. Not the caller's+ # content, and the flag is what selects ``JudgmentModelNotFoundError``.+ return ClassificationResult(+ category=InferenceErrorCategory.CONFIGURATION,+ user_action_kind=UserActionKind.CHANGE_MODEL,+ is_model_not_found=True,+ )+ # Some other misuse of the API. It is still not the caller's content — which is all the+ # ladder's 400 arm would have said — but nothing here knows what to tell them to change.+ return ClassificationResult(+ category=InferenceErrorCategory.CONFIGURATION,+ user_action_kind=UserActionKind.CONTACT_SUPPORT,+ )+ case code if code == TYPESAFE_MALFORMED_REQUEST_CODE:+ # A bare-sentence ``detail``: the question itself was illegal — no instructions and no+ # criteria, a rating scale past the vendor's cap. Our own validation is supposed to+ # have refused every one of those before a request was built, so reaching here is a+ # Pipelex defect and not something the caller wrote.+ return ClassificationResult(+ category=InferenceErrorCategory.CONFIGURATION,+ user_action_kind=UserActionKind.CONTACT_SUPPORT,+ )+ case _:+ return classify_inference_error(metadata)diff --git a/pipelex/providers/typesafe/typesafe_exceptions.py b/pipelex/providers/typesafe/typesafe_exceptions.pynew file mode 100644index 000000000..4e2b8a035--- /dev/null+++ b/pipelex/providers/typesafe/typesafe_exceptions.py@@ -0,0 +1,25 @@+from pipelex.cogt.exceptions import CogtError+++class TypesafeError(CogtError):+ """Base for every error this backend raises, so callers can catch the provider as a family."""+++class TypesafeJudgmentResponseError(TypesafeError):+ """The TypeSafe API answered a judgment with an answer that is missing, or of the wrong kind.++ The worker asks a named question of a known kind and reads the answer back under the same+ name; an answer that is absent, or that came back as a choice where a rating was asked for,+ cannot be translated at all. The family's own guard in ``JudgmentWorkerAbstract`` catches the+ same two mistakes one layer up, but only after translation has already had to produce+ something — so this is where the wrong shape actually stops.+ """+++class TypesafeQuestionUnsupportedError(TypesafeError):+ """The question is legal MTHDS that this backend will not serve.++ The vendor's own bounds, not the language's: a rating scale longer than this backend answers.+ Enforcing it here rather than in the blueprint is deliberate — a method that exceeds it stays+ valid and a different judgment backend may well accept it.+ """diff --git a/pipelex/providers/typesafe/typesafe_judgment_worker.py b/pipelex/providers/typesafe/typesafe_judgment_worker.pynew file mode 100644index 000000000..b4f9dc57c--- /dev/null+++ b/pipelex/providers/typesafe/typesafe_judgment_worker.py@@ -0,0 +1,113 @@+from typesafe_sdk import AsyncTypeSafeClient, SystemOneResponse, TypeSafeError+from typing_extensions import override++from pipelex import log+from pipelex.cogt.inference.error_classification import extract_typesafe_metadata+from pipelex.cogt.inference.error_render import InferenceErrorFamily, render_inference_error+from pipelex.cogt.judgment.judgment_job import JudgmentJob+from pipelex.cogt.judgment.judgment_models import JudgmentAnswer+from pipelex.cogt.judgment.judgment_worker_abstract import JudgmentWorkerAbstract+from pipelex.cogt.model_backends.model_spec import InferenceModelSpec+from pipelex.cogt.usage.token_category import NbTokensByCategoryDict, TokenCategory+from pipelex.providers.typesafe.typesafe_error_classification import classify_typesafe_error+from pipelex.providers.typesafe.typesafe_translation import from_typesafe_response, to_typesafe_questions+from pipelex.reporting.reporting_protocol import ReportingProtocol+++class TypesafeJudgmentWorker(JudgmentWorkerAbstract):+ """Serves the judgment family from TypeSafe's System One endpoint.++ One request carries the whole job, which is the reason the family's contract is batch-shaped:+ three questions over one state cost 506 input tokens together against 1138 apart, and answered+ in 0.27 s against 0.66 s. The state is paid for once, so a caller that asks everything it wants+ to know in one job is rewarded for it.+ """++ def __init__(+ self,+ *,+ sdk_instance: AsyncTypeSafeClient,+ inference_model: InferenceModelSpec,+ reporting_delegate: ReportingProtocol | None = None,+ ) -> None:+ JudgmentWorkerAbstract.__init__(self, inference_model=inference_model, reporting_delegate=reporting_delegate)+ self._typesafe_client = sdk_instance++ @override+ async def _judge(+ self,+ judgment_job: JudgmentJob,+ ) -> dict[str, JudgmentAnswer]:+ typesafe_questions = to_typesafe_questions(questions=judgment_job.questions)+ try:+ # The SDK types its state as a recursive JSON alias that pyright cannot resolve to the end.+ response = await self._typesafe_client.system_one( # pyright: ignore[reportUnknownMemberType]+ judgment_job.state,+ typesafe_questions,+ model=self.inference_model.model_id,+ )+ except TypeSafeError as sdk_exc:+ # The whole vendor family in one arm, on purpose. ``TypeSafeError`` is the SDK's base+ # class: its API subclasses carry a status and a body, and the bare class is the SDK+ # refusing a request it would not send. Both are failures of this call and both are+ # classified from the metadata, which is where the difference is read.+ metadata = extract_typesafe_metadata(sdk_exc)+ classification = classify_typesafe_error(metadata)+ raise render_inference_error(+ metadata=metadata,+ classification=classification,+ family=InferenceErrorFamily.JUDGMENT,+ model_desc=self.inference_model.desc,+ model_handle=self.inference_model.name,+ ) from sdk_exc++ self._log_request_id(response=response)+ self._warn_if_another_model_answered(response=response)+ self._record_usage(judgment_job=judgment_job, response=response)+ return from_typesafe_response(questions=judgment_job.questions, response=response)++ def _log_request_id(self, *, response: SystemOneResponse) -> None:+ """Trace the provider's own request id, which it returns on success as well as on failure.++ The read has to be guarded, and this is the trap the spike walked into first: on a response+ ``request_id`` is a property that **raises** when the header was absent rather than+ returning ``None``. On an error object the same attribute is a plain ``str | None``, which+ is why the error path reads it without any of this.+ """+ try:+ request_id = response.request_id+ except TypeSafeError:+ return+ log.debug(f"TypeSafe judgment answered by '{response.model}' (request_id={request_id})")++ def _warn_if_another_model_answered(self, *, response: SystemOneResponse) -> None:+ """Say so when the API answered under a model other than the one the deck pinned.++ The deck names a versioned model precisely so that a threshold keeps meaning what it meant+ when the method was written, and this API reports which model actually answered. The spike+ saw it echo the pinned id back unchanged, so a mismatch means the pin was not honoured —+ worth a warning on the run, not worth failing a call that did answer.+ """+ if response.model != self.inference_model.model_id:+ log.warning(+ f"TypeSafe was asked for judgment model '{self.inference_model.model_id}' and answered as "+ f"'{response.model}': verdicts and their thresholds may not mean what they meant under the pinned model"+ )++ def _record_usage(self, *, judgment_job: JudgmentJob, response: SystemOneResponse) -> None:+ """Record the real token counts this call was billed for.++ Usage is reported per *request*, never per question, and both fields are optional in the+ SDK's model even though the live API has always filled them. An absent field records no+ tokens for that category rather than a guess — the family's rule for a backend that does+ not report what it read.+ """+ judgment_tokens_usage = judgment_job.job_report.judgment_tokens_usage+ if judgment_tokens_usage is None:+ return+ nb_tokens_by_category: NbTokensByCategoryDict = {}+ if response.usage.input_tokens is not None:+ nb_tokens_by_category[TokenCategory.INPUT] = response.usage.input_tokens+ if response.usage.output_tokens is not None:+ nb_tokens_by_category[TokenCategory.OUTPUT] = response.usage.output_tokens+ judgment_tokens_usage.nb_tokens_by_category = nb_tokens_by_categorydiff --git a/pipelex/providers/typesafe/typesafe_plugin.py b/pipelex/providers/typesafe/typesafe_plugin.pynew file mode 100644index 000000000..ce05fb53e--- /dev/null+++ b/pipelex/providers/typesafe/typesafe_plugin.py@@ -0,0 +1,45 @@+from pipelex.cogt.inference.inference_worker_abstract import InferenceWorkerAbstract+from pipelex.cogt.model_backends.backend import InferenceBackend+from pipelex.cogt.model_backends.model_spec import InferenceModelSpec+from pipelex.plugins.contract import PLUGIN_API_VERSION+from pipelex.plugins.inference_backend_registry import InferenceFamily, require_sdk+from pipelex.plugins.model_handle import ModelHandle+from pipelex.plugins.registrar import PluginRegistrar+from pipelex.plugins.sdk_client_registry import SdkClientRegistry+from pipelex.reporting.reporting_protocol import ReportingProtocol++_TYPESAFE_MISSING_MSG = "The typesafe-sdk package is required in order to use TypeSafe judgment models."+++def _make_typesafe_judgment_worker(+ *,+ inference_model: InferenceModelSpec,+ backend: InferenceBackend,+ sdk_clients: SdkClientRegistry,+ reporting_delegate: ReportingProtocol | None,+) -> InferenceWorkerAbstract:+ require_sdk(spec="typesafe_sdk", extra="typesafe", msg=_TYPESAFE_MISSING_MSG)++ from pipelex.providers.typesafe.typesafe_client_factory import make_typesafe_client # ruff: ignore[import-outside-top-level]+ from pipelex.providers.typesafe.typesafe_judgment_worker import TypesafeJudgmentWorker # ruff: ignore[import-outside-top-level]++ model_handle = ModelHandle.make_for_inference_model(inference_model=inference_model)+ sdk_instance = sdk_clients.get_or_create(+ handle=model_handle,+ build=lambda: make_typesafe_client(backend=backend),+ )+ return TypesafeJudgmentWorker(+ sdk_instance=sdk_instance,+ inference_model=inference_model,+ reporting_delegate=reporting_delegate,+ )+++class TypesafePlugin:+ """Built-in driver for TypeSafe, the judgment family's first backend, via the typesafe-sdk package."""++ name = "typesafe"+ targets_api = PLUGIN_API_VERSION++ def register(self, registrar: PluginRegistrar) -> None:+ registrar.add_inference_backend(family=InferenceFamily.JUDGMENT, sdk="typesafe", make_worker=_make_typesafe_judgment_worker)diff --git a/pipelex/providers/typesafe/typesafe_translation.py b/pipelex/providers/typesafe/typesafe_translation.pynew file mode 100644index 000000000..fccd526be--- /dev/null+++ b/pipelex/providers/typesafe/typesafe_translation.py@@ -0,0 +1,190 @@+"""The two-way translation between the judgment family's vocabulary and TypeSafe's.++The family speaks yes/no, choice and rating; this vendor speaks *noul*, *choice* and *score*. The+mapping is one-to-one, and it lives here alone — nothing outside this module knows a vendor word.++**The vendor's bounds are enforced here, not in the blueprint.** A rating scale longer than this+API answers is legal MTHDS that this one backend refuses, exactly as the design's Part 5 says: the+language's own minimums belong to the question models, and a vendor's maximum belongs to the+vendor's worker, so a second judgment backend is free to accept what this one will not.+"""++from typing import Any, assert_never++from typesafe_sdk import (+ Choice as TypesafeChoice,+)+from typesafe_sdk import (+ ChoiceAnswer as TypesafeChoiceAnswer,+)+from typesafe_sdk import (+ Noul as TypesafeNoul,+)+from typesafe_sdk import (+ NoulAnswer as TypesafeNoulAnswer,+)+from typesafe_sdk import (+ NoulCriteria as TypesafeNoulCriteria,+)+from typesafe_sdk import (+ Question as TypesafeQuestion,+)+from typesafe_sdk import (+ Score as TypesafeScore,+)+from typesafe_sdk import (+ ScoreAnswer as TypesafeScoreAnswer,+)+from typesafe_sdk import (+ SystemOneResponse,+)++from pipelex.cogt.exceptions import InferenceErrorCategory+from pipelex.cogt.inference.error_classification import UserAction, UserActionKind+from pipelex.cogt.judgment.judgment_models import (+ ChoiceAnswer,+ ChoiceQuestion,+ JudgmentAnswer,+ JudgmentQuestion,+ RatingAnswer,+ RatingQuestion,+ YesNoAnswer,+ YesNoQuestion,+)+from pipelex.providers.typesafe.typesafe_exceptions import TypesafeJudgmentResponseError, TypesafeQuestionUnsupportedError++# The longest rating scale this API answers, probed at the boundary in the campaign's spike: ten+# levels are accepted and eleven are refused with a 400. The vendor's own advice explains why the+# cap is not a nuisance — at ten thin levels the model's confidence collapsed to 0.54 and spread+# across four of them, against 1.0 on a single level for a three-level scale over the same material.+TYPESAFE_MAX_RATING_LEVELS = 10+++def to_typesafe_questions(*, questions: dict[str, JudgmentQuestion]) -> dict[str, TypesafeQuestion]:+ """Render every question of a job into the vendor's own question objects."""+ return {question_key: to_typesafe_question(question_key=question_key, question=question) for question_key, question in questions.items()}+++def to_typesafe_question(*, question_key: str, question: JudgmentQuestion) -> TypesafeQuestion:+ """Render one question into the vendor's vocabulary, refusing what the vendor will not take."""+ match question:+ case YesNoQuestion():+ return TypesafeNoul(instructions=question.instructions, criteria=_noul_criteria(question=question))+ case ChoiceQuestion():+ return TypesafeChoice(instructions=question.instructions, criteria=dict(question.options))+ case RatingQuestion():+ nb_levels = len(question.levels)+ if nb_levels > TYPESAFE_MAX_RATING_LEVELS:+ msg = (+ f"Judgment question '{question_key}' asks for a {nb_levels}-level rating, and this backend "+ f"answers at most {TYPESAFE_MAX_RATING_LEVELS} levels"+ )+ raise TypesafeQuestionUnsupportedError(+ msg,+ error_category=InferenceErrorCategory.CONTENT,+ user_action=UserAction(+ kind=UserActionKind.CHANGE_INPUT,+ detail=(+ f"Shorten the rating scale to {TYPESAFE_MAX_RATING_LEVELS} levels or fewer — levels that "+ "describe distinct situations read better than a long formulaic scale anyway."+ ),+ ),+ provider_metadata=None,+ )+ return TypesafeScore(instructions=question.instructions, criteria=list(question.levels))+ case _:+ assert_never(question)+++def _noul_criteria(*, question: YesNoQuestion) -> TypesafeNoulCriteria | None:+ """The vendor's yes/no criteria, or nothing at all when the question declared neither side.++ Both sides are individually optional and an absent map is legal as long as the instructions are+ there. A key the vendor does not know is accepted and silently ignored, so only the two names+ it does know are ever sent.+ """+ criteria: TypesafeNoulCriteria = {}+ if question.yes_criterion is not None:+ criteria["true"] = question.yes_criterion+ if question.no_criterion is not None:+ criteria["false"] = question.no_criterion+ return criteria or None+++def from_typesafe_response(*, questions: dict[str, JudgmentQuestion], response: SystemOneResponse) -> dict[str, JudgmentAnswer]:+ """Read every answer back into the family's vocabulary, keyed as the questions were."""+ answers: dict[str, JudgmentAnswer] = {}+ for question_key, question in questions.items():+ typesafe_answer = response.answers.get(question_key)+ if typesafe_answer is None:+ msg = f"TypeSafe answered a judgment without an answer for question '{question_key}'"+ raise _response_error(msg=msg)+ answers[question_key] = _from_typesafe_answer(question_key=question_key, question=question, typesafe_answer=typesafe_answer)+ return answers+++def _from_typesafe_answer(*, question_key: str, question: JudgmentQuestion, typesafe_answer: Any) -> JudgmentAnswer:+ """Read one answer back, refusing one that does not match the kind its question asked for."""+ match question:+ case YesNoQuestion():+ if not isinstance(typesafe_answer, TypesafeNoulAnswer):+ raise _wrong_kind_error(question_key=question_key, question=question, typesafe_answer=typesafe_answer)+ # The probability *is* the confidence for this kind, and the verdict is deliberately+ # left absent: whoever holds the threshold decides which side of it this falls on.+ return YesNoAnswer(probability=typesafe_answer.noul)+ case ChoiceQuestion():+ if not isinstance(typesafe_answer, TypesafeChoiceAnswer):+ raise _wrong_kind_error(question_key=question_key, question=question, typesafe_answer=typesafe_answer)+ return ChoiceAnswer(+ choice=typesafe_answer.choice,+ confidence=typesafe_answer.confidence,+ probabilities=dict(typesafe_answer.probabilities),+ )+ case RatingQuestion():+ if not isinstance(typesafe_answer, TypesafeScoreAnswer):+ raise _wrong_kind_error(question_key=question_key, question=question, typesafe_answer=typesafe_answer)+ probabilities = dict(typesafe_answer.probabilities)+ return RatingAnswer(+ level=_most_probable_level(probabilities=probabilities, score=typesafe_answer.score, nb_levels=len(question.levels)),+ position=typesafe_answer.score,+ confidence=typesafe_answer.confidence,+ probabilities=probabilities or None,+ )+ case _:+ assert_never(question)+++def _most_probable_level(*, probabilities: dict[int, float], score: float, nb_levels: int) -> int:+ """The level a rating verdict names, derived from what the backend actually measured.++ This vendor reports a distribution and a ``score`` that is its probability-weighted position, so+ the score usually falls *between* levels and is not itself a verdict. The verdict is the most+ probable level, and deriving it is the worker's job because only the worker knows what its+ backend measured. Ties go to the lower level, so the same distribution always names the same+ verdict. With no distribution at all — which this API has never been seen to do — the weighted+ position rounded to the nearest level is the best remaining reading.+ """+ highest_level = max(nb_levels - 1, 0)+ if probabilities:+ return min(max(probabilities, key=lambda level: (probabilities[level], -level)), highest_level)+ return min(max(round(score), 0), highest_level)+++def _wrong_kind_error(*, question_key: str, question: JudgmentQuestion, typesafe_answer: Any) -> TypesafeJudgmentResponseError:+ msg = (+ f"TypeSafe answered question '{question_key}' with a '{getattr(typesafe_answer, 'type', type(typesafe_answer).__name__)}' "+ f"answer, but it asked for a '{question.kind}'"+ )+ return _response_error(msg=msg)+++def _response_error(*, msg: str) -> TypesafeJudgmentResponseError:+ return TypesafeJudgmentResponseError(+ msg,+ error_category=InferenceErrorCategory.UNKNOWN,+ user_action=UserAction(+ kind=UserActionKind.CHANGE_MODEL,+ detail="TypeSafe returned a malformed judgment response — try a different judgment model.",+ ),+ provider_metadata=None,+ )diff --git a/pipelex/test_extras/shared_pytest_plugins.py b/pipelex/test_extras/shared_pytest_plugins.pyindex 3c0c93c8e..f0feaa22b 100644--- a/pipelex/test_extras/shared_pytest_plugins.py+++ b/pipelex/test_extras/shared_pytest_plugins.py@@ -52,6 +52,7 @@ ENV_VAR_KEYS_WHICH_MAY_NEED_PLACEHOLDERS_IN_CI = ["LINKUP_API_KEY","OPENROUTER_API_KEY","MINIMAX_API_KEY",+ "TYPESAFE_API_KEY",]diff --git a/subject_grants.toml b/subject_grants.tomlindex 6a9f9d427..f3e96fc9f 100644--- a/subject_grants.toml+++ b/subject_grants.toml@@ -1952,6 +1952,10 @@ rationale = "Extracts from the exc; single operand."param = "exc"rationale = "Extracts from the exc; single operand."+["pipelex/cogt/inference/error_classification.py::extract_typesafe_metadata"]+param = "exc"+rationale = "Extracts from the exc; single operand."+["pipelex/cogt/inference/error_classification.py::extract_underlying_sdk_exception"]param = "instructor_exc"rationale = "Extracts from the instructor_exc; single operand."@@ -5524,6 +5528,14 @@ rationale = "Positional-Callable protocol: registered as a StorageProviderFactorparam = "config"rationale = "Positional-Callable protocol: registered as a StorageProviderFactoryFn."+["pipelex/providers/typesafe/typesafe_error_classification.py::classify_typesafe_error"]+param = "metadata"+rationale = "Classifies the metadata; single operand, mirroring classify_inference_error."++["pipelex/providers/typesafe/typesafe_plugin.py::TypesafePlugin.register"]+param = "registrar"+rationale = "Plugin protocol register: the registrar is the sole sink the plugin populates."+["pipelex/reporting/cost_report_renderer.py::render_cost_report_for_output"]param = "pipe_output"rationale = "Verb-object: renders the report for the pipe output; single operand."diff --git a/tests/data/errors/error_identity.txt b/tests/data/errors/error_identity.txtindex 7b8e81c5f..2bd4e302f 100644--- a/tests/data/errors/error_identity.txt+++ b/tests/data/errors/error_identity.txt@@ -336,6 +336,9 @@ TemplateSigilSyntaxError | Template sigil syntax | https://docs.pipelex.com/lateTomlError | TOML parse error | https://docs.pipelex.com/latest/errors/toml-error/ToolError | Tool error | https://docs.pipelex.com/latest/errors/tool-error/TracebackMessageError | Traceback message | https://docs.pipelex.com/latest/errors/traceback-message-error/+TypesafeError | Typesafe | https://docs.pipelex.com/latest/errors/typesafe-error/+TypesafeJudgmentResponseError | Typesafe judgment response | https://docs.pipelex.com/latest/errors/typesafe-judgment-response-error/+TypesafeQuestionUnsupportedError | Typesafe question unsupported | https://docs.pipelex.com/latest/errors/typesafe-question-unsupported-error/UnknownBootOrchestratorError | Unknown boot orchestrator | https://docs.pipelex.com/latest/errors/unknown-boot-orchestrator-error/UnknownInputNameError | Unknown input name | https://docs.pipelex.com/latest/errors/unknown-input-name-error/UnknownLogSinkError | Unknown log sink | https://docs.pipelex.com/latest/errors/unknown-log-sink-error/diff --git a/tests/data/typesafe/responses/01_three_shapes.json b/tests/data/typesafe/responses/01_three_shapes.jsonnew file mode 100644index 000000000..5368ae57a--- /dev/null+++ b/tests/data/typesafe/responses/01_three_shapes.json@@ -0,0 +1,39 @@+{+ "answers": {+ "is_urgent": {+ "noul": 0.98,+ "type": "noul"+ },+ "severity": {+ "confidence": 1.0,+ "legend": {+ "0": "Cosmetic; no impact on functionality",+ "1": "A feature is degraded, but a workaround exists",+ "2": "Blocking issue; no workaround exists"+ },+ "probabilities": {+ "0": 0.0,+ "1": 0.0,+ "2": 1.0+ },+ "score": 2.0,+ "type": "score"+ },+ "team": {+ "choice": "payments",+ "confidence": 1.0,+ "probabilities": {+ "accounts": 0.0,+ "other": 0.0,+ "payments": 1.0,+ "shipping": 0.0+ },+ "type": "choice"+ }+ },+ "model": "jev-1.13.0",+ "usage": {+ "input_tokens": 506,+ "output_tokens": 78+ }+}diff --git a/tests/data/typesafe/responses/02_usage_one_question.json b/tests/data/typesafe/responses/02_usage_one_question.jsonnew file mode 100644index 000000000..bdf4e0d86--- /dev/null+++ b/tests/data/typesafe/responses/02_usage_one_question.json@@ -0,0 +1,13 @@+{+ "answers": {+ "is_urgent": {+ "noul": 0.98,+ "type": "noul"+ }+ },+ "model": "jev-1.13.0",+ "usage": {+ "input_tokens": 354,+ "output_tokens": 23+ }+}diff --git a/tests/data/typesafe/responses/04_choice_null_descriptions.json b/tests/data/typesafe/responses/04_choice_null_descriptions.jsonnew file mode 100644index 000000000..8090e8cf1--- /dev/null+++ b/tests/data/typesafe/responses/04_choice_null_descriptions.json@@ -0,0 +1,18 @@+{+ "answers": {+ "q": {+ "choice": "angry",+ "confidence": 0.97,+ "probabilities": {+ "angry": 0.98,+ "calm": 0.02+ },+ "type": "choice"+ }+ },+ "model": "jev-1.13.0",+ "usage": {+ "input_tokens": 337,+ "output_tokens": 34+ }+}diff --git a/tests/data/typesafe/responses/04_score_eleven_levels_error.json b/tests/data/typesafe/responses/04_score_eleven_levels_error.jsonnew file mode 100644index 000000000..2d3ad0565--- /dev/null+++ b/tests/data/typesafe/responses/04_score_eleven_levels_error.json@@ -0,0 +1,25 @@+{+ "body": {+ "detail": "Too many score levels. Must have at most 10 levels."+ },+ "class": "TypeSafeBadRequestError",+ "endpoint": "POST https://api.typesafe.ai/v1/systemone",+ "module": "typesafe_sdk._core.errors",+ "mro": [+ "TypeSafeAPIError",+ "TypeSafeError",+ "Exception",+ "BaseException"+ ],+ "request_id": "req_01a0b97a99c67924bd08c1bce9c2a487",+ "response_headers": {+ "content-length": "64",+ "content-type": "application/json",+ "date": "Sat, 19 Sep 2026 11:43:34 GMT",+ "server": "istio-envoy",+ "x-envoy-upstream-service-time": "10",+ "x-typesafe-request-id": "req_01a0b97a99c67924bd08c1bce9c2a487"+ },+ "status": 400,+ "str": "POST https://api.typesafe.ai/v1/systemone: 400 Too many score levels. Must have at most 10 levels. (request_id=req_01a0b97a99c67924bd08c1bce9c2a487)"+}diff --git a/tests/data/typesafe/responses/04_score_ten_levels.json b/tests/data/typesafe/responses/04_score_ten_levels.jsonnew file mode 100644index 000000000..66f0a8262--- /dev/null+++ b/tests/data/typesafe/responses/04_score_ten_levels.json@@ -0,0 +1,38 @@+{+ "answers": {+ "q": {+ "confidence": 0.54,+ "legend": {+ "0": "Severity level 0",+ "1": "Severity level 1",+ "2": "Severity level 2",+ "3": "Severity level 3",+ "4": "Severity level 4",+ "5": "Severity level 5",+ "6": "Severity level 6",+ "7": "Severity level 7",+ "8": "Severity level 8",+ "9": "Severity level 9"+ },+ "probabilities": {+ "0": 0.0,+ "1": 0.0,+ "2": 0.0,+ "3": 0.01,+ "4": 0.03,+ "5": 0.05,+ "6": 0.05,+ "7": 0.12,+ "8": 0.31,+ "9": 0.43+ },+ "score": 7.86,+ "type": "score"+ }+ },+ "model": "jev-1.13.0",+ "usage": {+ "input_tokens": 413,+ "output_tokens": 17+ }+}diff --git a/tests/data/typesafe/responses/04b_state_200k_chars_error.json b/tests/data/typesafe/responses/04b_state_200k_chars_error.jsonnew file mode 100644index 000000000..b0d92ad07--- /dev/null+++ b/tests/data/typesafe/responses/04b_state_200k_chars_error.json@@ -0,0 +1,27 @@+{+ "body": {+ "detail": {+ "error_type": "max_tokens_exceeded"+ }+ },+ "class": "TypeSafeBadRequestError",+ "endpoint": "POST https://api.typesafe.ai/v1/systemone",+ "module": "typesafe_sdk._core.errors",+ "mro": [+ "TypeSafeAPIError",+ "TypeSafeError",+ "Exception",+ "BaseException"+ ],+ "request_id": "req_01a0b97a9b537fe18c53d7231f72b913",+ "response_headers": {+ "content-length": "47",+ "content-type": "application/json",+ "date": "Sat, 19 Sep 2026 11:43:34 GMT",+ "server": "istio-envoy",+ "x-envoy-upstream-service-time": "26",+ "x-typesafe-request-id": "req_01a0b97a9b537fe18c53d7231f72b913"+ },+ "status": 400,+ "str": "POST https://api.typesafe.ai/v1/systemone: 400 {\"detail\":{\"error_type\":\"max_tokens_exceeded\"}} (request_id=req_01a0b97a9b537fe18c53d7231f72b913)"+}diff --git a/tests/data/typesafe/responses/05_model_jev_does_not_exist_error.json b/tests/data/typesafe/responses/05_model_jev_does_not_exist_error.jsonnew file mode 100644index 000000000..63074e810--- /dev/null+++ b/tests/data/typesafe/responses/05_model_jev_does_not_exist_error.json@@ -0,0 +1,28 @@+{+ "body": {+ "detail": {+ "error_type": "api_usage_error",+ "message": "Unknown model: jev-does-not-exist"+ }+ },+ "class": "TypeSafeBadRequestError",+ "endpoint": "POST https://api.typesafe.ai/v1/systemone",+ "module": "typesafe_sdk._core.errors",+ "mro": [+ "TypeSafeAPIError",+ "TypeSafeError",+ "Exception",+ "BaseException"+ ],+ "request_id": "req_01a0b97aa532770083aece1331cb7c76",+ "response_headers": {+ "content-length": "89",+ "content-type": "application/json",+ "date": "Sat, 19 Sep 2026 11:43:37 GMT",+ "server": "istio-envoy",+ "x-envoy-upstream-service-time": "34",+ "x-typesafe-request-id": "req_01a0b97aa532770083aece1331cb7c76"+ },+ "status": 400,+ "str": "POST https://api.typesafe.ai/v1/systemone: 400 Unknown model: jev-does-not-exist (request_id=req_01a0b97aa532770083aece1331cb7c76)"+}diff --git a/tests/data/typesafe/responses/06_empty_questions.json b/tests/data/typesafe/responses/06_empty_questions.jsonnew file mode 100644index 000000000..c06f7591c--- /dev/null+++ b/tests/data/typesafe/responses/06_empty_questions.json@@ -0,0 +1,9 @@+{+ "class": "TypeSafeError",+ "module": "typesafe_sdk._core.errors",+ "mro": [+ "Exception",+ "BaseException"+ ],+ "str": "At least one question is required."+}diff --git a/tests/data/typesafe/responses/06_malformed_question.json b/tests/data/typesafe/responses/06_malformed_question.jsonnew file mode 100644index 000000000..c3c889631--- /dev/null+++ b/tests/data/typesafe/responses/06_malformed_question.json@@ -0,0 +1,25 @@+{+ "body": {+ "detail": "Noul question must have criteria or instructions: q"+ },+ "class": "TypeSafeBadRequestError",+ "endpoint": "POST https://api.typesafe.ai/v1/systemone",+ "module": "typesafe_sdk._core.errors",+ "mro": [+ "TypeSafeAPIError",+ "TypeSafeError",+ "Exception",+ "BaseException"+ ],+ "request_id": "req_01a0b97ab1f575f69871f8b3006b6da2",+ "response_headers": {+ "content-length": "64",+ "content-type": "application/json",+ "date": "Sat, 19 Sep 2026 11:43:40 GMT",+ "server": "istio-envoy",+ "x-envoy-upstream-service-time": "10",+ "x-typesafe-request-id": "req_01a0b97ab1f575f69871f8b3006b6da2"+ },+ "status": 400,+ "str": "POST https://api.typesafe.ai/v1/systemone: 400 Noul question must have criteria or instructions: q (request_id=req_01a0b97ab1f575f69871f8b3006b6da2)"+}diff --git a/tests/data/typesafe/responses/06_timeout.json b/tests/data/typesafe/responses/06_timeout.jsonnew file mode 100644index 000000000..21bb6269a--- /dev/null+++ b/tests/data/typesafe/responses/06_timeout.json@@ -0,0 +1,14 @@+{+ "class": "TypeSafeAPITimeoutError",+ "module": "typesafe_sdk._core.errors",+ "mro": [+ "TypeSafeAPIConnectionError",+ "TypeSafeError",+ "ConnectionError",+ "TimeoutError",+ "OSError",+ "Exception",+ "BaseException"+ ],+ "str": "Request timed out (timeout=0.001)."+}diff --git a/tests/data/typesafe/responses/06_wrong_key.json b/tests/data/typesafe/responses/06_wrong_key.jsonnew file mode 100644index 000000000..c4801e322--- /dev/null+++ b/tests/data/typesafe/responses/06_wrong_key.json@@ -0,0 +1,28 @@+{+ "body": {+ "detail": {+ "error_type": "authentication_error",+ "message": "Cannot authenticate with the server. Please check your API key and try again."+ }+ },+ "class": "TypeSafeAuthenticationError",+ "endpoint": "POST https://api.typesafe.ai/v1/systemone",+ "module": "typesafe_sdk._core.errors",+ "mro": [+ "TypeSafeAPIError",+ "TypeSafeError",+ "Exception",+ "BaseException"+ ],+ "request_id": "req_01a0b97aaffa7b9d977632354ba0bd9d",+ "response_headers": {+ "content-length": "138",+ "content-type": "application/json",+ "date": "Sat, 19 Sep 2026 11:43:40 GMT",+ "server": "istio-envoy",+ "x-envoy-upstream-service-time": "22",+ "x-typesafe-request-id": "req_01a0b97aaffa7b9d977632354ba0bd9d"+ },+ "status": 401,+ "str": "POST https://api.typesafe.ai/v1/systemone: 401 Cannot authenticate with the server. Please check your API key and try again. (request_id=req_01a0b97aaffa7b9d977632354ba0bd9d)"+}diff --git a/tests/e2e/agent_cli/conftest.py b/tests/e2e/agent_cli/conftest.pyindex 322c44401..500d13554 100644--- a/tests/e2e/agent_cli/conftest.py+++ b/tests/e2e/agent_cli/conftest.py@@ -304,6 +304,7 @@ def offline_subprocess_env(hermetic_home: Path) -> dict[str, str]:"PORTKEY_API_KEY": "dummy-portkey-key","SCALEWAY_API_KEY": "dummy-scaleway-key","SCALEWAY_ENDPOINT": "https://example.invalid",+ "TYPESAFE_API_KEY": "dummy-typesafe-key","XAI_API_KEY": "dummy-xai-key",}return envdiff --git a/tests/integration/pipelex/cogt/config_coverage/test_cc_judgment.py b/tests/integration/pipelex/cogt/config_coverage/test_cc_judgment.pynew file mode 100644index 000000000..951c5d36b--- /dev/null+++ b/tests/integration/pipelex/cogt/config_coverage/test_cc_judgment.py@@ -0,0 +1,31 @@+import pytest++from pipelex import log, pretty_print+from pipelex.cogt.judgment.judgment_job_factory import JudgmentJobFactory+from pipelex.cogt.judgment.judgment_setting import JudgmentSetting+from pipelex.cogt.judgment.judgment_worker_factory import JudgmentWorkerFactory+from pipelex.cogt.model_backends.model_type import ModelType+from pipelex.runtime_hub import get_model_deck+from pipelex.system.job_metadata import JobMetadata+from tests.integration.pipelex.cogt.test_data import JudgmentTestCases+from tests.integration.pipelex.fixtures.model_combo import ModelCombo++[email protected](loop_scope="class")+class TestConfigCoverageJudgment:+ async def test_judgment(self, judgment_combo: ModelCombo, job_metadata: JobMetadata) -> None:+ """Verify that a judgment answers for this model and backend."""+ log.info(f"Config coverage: testing judgment '{judgment_combo.handle}'")+ inference_model = get_model_deck().get_required_inference_model(model_handle=judgment_combo.handle, model_type=ModelType.JUDGMENT)+ worker = JudgmentWorkerFactory.make_judgment_worker(inference_model)+ judgment_job = JudgmentJobFactory.make_judgment_job(+ state=JudgmentTestCases.STATE,+ questions={"is_urgent": JudgmentTestCases.IS_URGENT},+ judgment_setting=JudgmentSetting(model=judgment_combo.handle),+ job_metadata=job_metadata,+ )+ answers = await worker.judge(judgment_job)+ assert set(answers) == {"is_urgent"}+ pretty_print(answers, title=f"Judgment answer for '{judgment_combo.handle}'")diff --git a/tests/integration/pipelex/cogt/test_data.py b/tests/integration/pipelex/cogt/test_data.pyindex dcac102ff..36c3973e8 100644--- a/tests/integration/pipelex/cogt/test_data.py+++ b/tests/integration/pipelex/cogt/test_data.py@@ -4,6 +4,7 @@ from typing import Any, ClassVarfrom pydantic import BaseModel, Field, field_validatorfrom pipelex.cogt.image.prompt_image import PromptImageUri+from pipelex.cogt.judgment.judgment_models import ChoiceQuestion, JudgmentKind, JudgmentQuestion, RatingQuestion, YesNoQuestionfrom pipelex.cogt.llm.llm_prompt import LLMPromptfrom tests.cases import ImageTestCasesfrom tests.cases.documents import DocumentTestCases@@ -264,3 +265,65 @@ class LLMReasoningTestCases:# """,# ),]+++class JudgmentTestCases:+ """Live judgment material, and every string in it is pinned on purpose.++ The spike measured what moves an answer: repeating the same request moved a borderline case by+ 0.01, while rewording a single instruction moved it from 0.11 to 0.30. So the wording here is+ part of the test, copied from the spike's recorded three-question probe, and a failure after an+ innocent-looking edit to it is telling the truth. Verdicts are asserted exactly; a probability+ gets ``PROBABILITY_MARGIN``, fifteen times the noise the spike observed.+ """++ PROBABILITY_MARGIN = 0.05++ STATE: ClassVar[dict[str, Any]] = {+ "message": (+ "Our production checkout has been returning 500s for every card payment since 09:14 UTC. "+ "Nothing is going through. I have three customers on the phone right now. Please help."+ ),+ "channel": "support_email",+ }++ IS_URGENT = YesNoQuestion(+ instructions="Is the message urgent?",+ yes_criterion="Needs attention now",+ no_criterion="Can wait until the next working day",+ )+ TEAM = ChoiceQuestion(+ instructions="Which team should handle this message?",+ options={+ "payments": "Charges, invoices, payment processing failures",+ "shipping": "Delivery status, delays, lost packages",+ "accounts": "Sign-in, passwords, account settings",+ "other": "None of the above",+ },+ )+ SEVERITY = RatingQuestion(+ instructions="How severe is the reported issue?",+ levels=[+ "Cosmetic; no impact on functionality",+ "A feature is degraded, but a workaround exists",+ "Blocking issue; no workaround exists",+ ],+ )++ THREE_QUESTIONS: ClassVar[dict[str, JudgmentQuestion]] = {+ "is_urgent": IS_URGENT,+ "team": TEAM,+ "severity": SEVERITY,+ }++ # (topic, question, kind) — each kind alone, as a batch of one, on the unambiguous case.+ EACH_KIND: ClassVar[list[tuple[str, JudgmentQuestion, JudgmentKind]]] = [+ ("yes_no", IS_URGENT, JudgmentKind.YES_NO),+ ("choice", TEAM, JudgmentKind.CHOICE),+ ("rating", SEVERITY, JudgmentKind.RATING),+ ]++ # What the spike recorded for this material, bit-identical across eight repeats.+ EXPECTED_IS_URGENT_PROBABILITY = 0.98+ EXPECTED_TEAM = "payments"+ EXPECTED_SEVERITY_LEVEL = 2diff --git a/tests/integration/pipelex/cogt/test_judgment.py b/tests/integration/pipelex/cogt/test_judgment.pynew file mode 100644index 000000000..b6b71967b--- /dev/null+++ b/tests/integration/pipelex/cogt/test_judgment.py@@ -0,0 +1,109 @@+import pytest++from pipelex import pretty_print+from pipelex.cogt.exceptions import JudgmentModelNotFoundError+from pipelex.cogt.judgment.judgment_job import JudgmentJob+from pipelex.cogt.judgment.judgment_job_factory import JudgmentJobFactory+from pipelex.cogt.judgment.judgment_models import (+ ChoiceAnswer,+ JudgmentAnswer,+ JudgmentKind,+ JudgmentQuestion,+ RatingAnswer,+ YesNoAnswer,+)+from pipelex.cogt.judgment.judgment_setting import JudgmentSetting+from pipelex.cogt.judgment.judgment_worker_factory import JudgmentWorkerFactory+from pipelex.cogt.model_backends.model_spec import InferenceModelSpec+from pipelex.cogt.model_backends.model_type import ModelType+from pipelex.cogt.usage.token_category import TokenCategory+from pipelex.runtime_hub import get_model_deck+from pipelex.system.job_metadata import JobMetadata+from tests.integration.pipelex.cogt.test_data import JudgmentTestCases+from tests.integration.pipelex.fixtures.model_combo import ModelCombo+++def _inference_model(judgment_combo: ModelCombo) -> InferenceModelSpec:+ return get_model_deck().get_required_inference_model(model_handle=judgment_combo.handle, model_type=ModelType.JUDGMENT)+++def _job(*, judgment_combo: ModelCombo, job_metadata: JobMetadata, questions: dict[str, JudgmentQuestion]) -> JudgmentJob:+ return JudgmentJobFactory.make_judgment_job(+ state=JudgmentTestCases.STATE,+ questions=questions,+ judgment_setting=JudgmentSetting(model=judgment_combo.handle),+ job_metadata=job_metadata,+ )+++def _assert_expected_verdict(*, answer: JudgmentAnswer) -> None:+ """The verdict exactly, the probability within the margin the spike's stability measure sets."""+ match answer:+ case YesNoAnswer():+ assert answer.probability is not None, "TypeSafe measures a probability for every yes/no answer"+ assert answer.probability > 0.5, "The unambiguous case must land on the yes side"+ assert abs(answer.probability - JudgmentTestCases.EXPECTED_IS_URGENT_PROBABILITY) <= JudgmentTestCases.PROBABILITY_MARGIN+ case ChoiceAnswer():+ assert answer.choice == JudgmentTestCases.EXPECTED_TEAM+ assert answer.probabilities is not None+ assert set(answer.probabilities) == set(JudgmentTestCases.TEAM.options)+ case RatingAnswer():+ assert answer.level == JudgmentTestCases.EXPECTED_SEVERITY_LEVEL+ assert answer.probabilities is not None+ assert set(answer.probabilities) == set(range(len(JudgmentTestCases.SEVERITY.levels)))++[email protected](loop_scope="class")+class TestJudgment:+ @pytest.mark.parametrize(("topic", "question", "kind"), JudgmentTestCases.EACH_KIND)+ async def test_each_kind_on_an_unambiguous_case(+ self,+ judgment_combo: ModelCombo,+ job_metadata: JobMetadata,+ topic: str,+ question: JudgmentQuestion,+ kind: JudgmentKind,+ ) -> None:+ """Each question kind alone, as a batch of one, answers the same verdict the spike recorded."""+ worker = JudgmentWorkerFactory.make_judgment_worker(_inference_model(judgment_combo))+ answers = await worker.judge(_job(judgment_combo=judgment_combo, job_metadata=job_metadata, questions={topic: question}))+ pretty_print(answers, title=f"Judgment answer ({topic})")++ assert set(answers) == {topic}+ assert answers[topic].kind == kind+ _assert_expected_verdict(answer=answers[topic])++ async def test_several_questions_in_one_job(self, judgment_combo: ModelCombo, job_metadata: JobMetadata) -> None:+ """The three kinds in one request, each answered under its own key, with real usage and the pinned model on the report."""+ inference_model = _inference_model(judgment_combo)+ worker = JudgmentWorkerFactory.make_judgment_worker(inference_model)+ job = _job(judgment_combo=judgment_combo, job_metadata=job_metadata, questions=JudgmentTestCases.THREE_QUESTIONS)++ answers = await worker.judge(job)+ pretty_print(answers, title="Judgment answers (three questions, one request)")++ assert set(answers) == set(JudgmentTestCases.THREE_QUESTIONS)+ for answer in answers.values():+ _assert_expected_verdict(answer=answer)++ usage = job.job_report.judgment_tokens_usage+ assert usage is not None+ assert usage.nb_tokens_by_category.get(TokenCategory.INPUT, 0) > 0, "Usage is per request and the API has always reported it"+ assert TokenCategory.OUTPUT in usage.nb_tokens_by_category+ assert usage.inference_model_id == inference_model.model_id+ assert usage.inference_model_id.startswith("jev-")+ assert usage.inference_model_id != "jev-latest", "The deck pins a versioned id"++ async def test_an_unknown_model_is_a_missing_model(self, judgment_combo: ModelCombo, job_metadata: JobMetadata) -> None:+ """A model id this API does not serve comes back as a 400 and is rendered as the family's model-not-found error."""+ inference_model = _inference_model(judgment_combo).model_copy(update={"model_id": "jev-does-not-exist"})+ worker = JudgmentWorkerFactory.make_judgment_worker(inference_model)++ with pytest.raises(JudgmentModelNotFoundError) as exc_info:+ await worker.judge(_job(judgment_combo=judgment_combo, job_metadata=job_metadata, questions={"is_urgent": JudgmentTestCases.IS_URGENT}))++ assert exc_info.value.provider_metadata is not None+ assert exc_info.value.provider_metadata.status_code == 400+ assert exc_info.value.provider_metadata.request_id is not Nonediff --git a/tests/integration/pipelex/system/test_keyless_boot_forced_dry.py b/tests/integration/pipelex/system/test_keyless_boot_forced_dry.pyindex 4fae43514..3fae78ef8 100644--- a/tests/integration/pipelex/system/test_keyless_boot_forced_dry.py+++ b/tests/integration/pipelex/system/test_keyless_boot_forced_dry.py@@ -19,6 +19,7 @@ from collections.abc import Generatorimport pytest+from pipelex.base_exceptions import PipelexSetupErrorfrom pipelex.cogt.content_generation.content_generator import ContentGeneratorfrom pipelex.config import get_configfrom pipelex.core.concepts.native.concept_native import NativeConceptCode@@ -120,6 +121,26 @@ class TestKeylessBootForcedDry:finally:Pipelex.teardown_if_needed()+ def test_keyless_boot_needs_no_key_for_an_enabled_judgment_backend(self, monkeypatch: pytest.MonkeyPatch) -> None:+ """An enabled judgment backend whose key is unset is skipped by a keyless boot, as Linkup's is.++ The kit ships `[typesafe]` enabled like every other bring-your-own-key backend, so a machine+ without `TYPESAFE_API_KEY` must still validate and dry-run. The keyed boot is the one that+ names the missing key, which the second half pins so the two postures cannot drift apart.+ """+ monkeypatch.delenv("TYPESAFE_API_KEY", raising=False)+ try:+ self._boot_keyless()+ assert is_dry_run_forced()+ finally:+ Pipelex.teardown_if_needed()++ try:+ with pytest.raises(PipelexSetupError, match="'typesafe'"):+ Pipelex.make(integration_mode=_test_integration_mode())+ finally:+ Pipelex.teardown_if_needed()+def test_keyed_boot_does_not_force_dry(self) -> None:"""Control arm: a normal boot leaves the flag unset."""try:diff --git a/tests/unit/pipelex/cogt/inference/test_provider_classification_parity.py b/tests/unit/pipelex/cogt/inference/test_provider_classification_parity.pyindex 0e7ff9535..3c786e5fc 100644--- a/tests/unit/pipelex/cogt/inference/test_provider_classification_parity.py+++ b/tests/unit/pipelex/cogt/inference/test_provider_classification_parity.py@@ -22,6 +22,7 @@ from pipelex.cogt.inference.error_classification import (extract_local_extract_metadata,extract_mistral_metadata,extract_openai_metadata,+ extract_typesafe_metadata,)from pipelex.cogt.inference.provider_name import ProviderName@@ -39,6 +40,7 @@ _PROVIDER_TO_EXTRACT_FN: dict[ProviderName, Callable[..., ProviderErrorMetadata]ProviderName.HUGGINGFACE: extract_huggingface_metadata,ProviderName.GATEWAY: extract_gateway_metadata,ProviderName.LINKUP: extract_linkup_metadata,+ ProviderName.TYPESAFE: extract_typesafe_metadata,ProviderName.DOCLING: extract_local_extract_metadata,ProviderName.PYPDFIUM2: extract_local_extract_metadata,}diff --git a/tests/unit/pipelex/cogt/model_routing/test_routing_profile_optional_routes.py b/tests/unit/pipelex/cogt/model_routing/test_routing_profile_optional_routes.pyindex 3c9d3ea6d..8bc19869e 100644--- a/tests/unit/pipelex/cogt/model_routing/test_routing_profile_optional_routes.py+++ b/tests/unit/pipelex/cogt/model_routing/test_routing_profile_optional_routes.py@@ -65,3 +65,37 @@ class TestRoutingProfileOptionalRoutes:assert result is not Noneassert result.backend_name == "openai"assert result.matching_method == BackendMatchingMethod.DEFAULT++ def test_a_pattern_optional_route_serves_a_whole_family_of_versions(self):+ """`jev-*` sends every versioned judgment model to its backend while that backend is enabled."""+ routing_profile = RoutingProfile(+ name="test_profile",+ default="pipelex_gateway",+ optional_routes={"jev-*": "typesafe"},+ )++ result = routing_profile.get_backend_match_for_model(enabled_backends=["pipelex_gateway", "typesafe"], model_name="jev-1.13.0")++ assert result is not None+ assert result.backend_name == "typesafe"+ assert result.matching_method == BackendMatchingMethod.PATTERN_MATCH+ assert result.matched_pattern == "jev-*"++ def test_matching_leaves_the_declared_routes_untouched(self):+ """Regression: matching used to merge the enabled optional routes into `routes` in place.++ The merge survived the call, so after the first match the profile's `routes` no longer said+ what its file said — a pattern declared optional had silently become unconditional in the+ model, and it was only the per-match enablement checks that kept that from mattering.+ """+ routing_profile = RoutingProfile(+ name="test_profile",+ default="pipelex_gateway",+ routes={"gpt-*": "openai"},+ optional_routes={"jev-*": "typesafe"},+ )++ routing_profile.get_backend_match_for_model(enabled_backends=["pipelex_gateway", "openai", "typesafe"], model_name="jev-1.13.0")++ assert routing_profile.routes == {"gpt-*": "openai"}+ assert routing_profile.optional_routes == {"jev-*": "typesafe"}diff --git a/tests/unit/pipelex/plugins/test_import_light_boot.py b/tests/unit/pipelex/plugins/test_import_light_boot.pyindex f955fec4a..9bcad8507 100644--- a/tests/unit/pipelex/plugins/test_import_light_boot.py+++ b/tests/unit/pipelex/plugins/test_import_light_boot.py@@ -28,6 +28,7 @@ _GUARD_SCRIPT = textwrap.dedent("openai","portkey_ai","pypdfium2",+ "typesafe_sdk",# No web framework either: the F3 HTTP-error-mapper seam is framework-agnostic# (it carries the core ``ErrorReport`` type). A host runtime owns FastAPI/Starlette;# discovery/registration in core must never pull one in.diff --git a/tests/unit/pipelex/plugins/test_inference_backend_coverage.py b/tests/unit/pipelex/plugins/test_inference_backend_coverage.pyindex e28a1d4af..8965bea03 100644--- a/tests/unit/pipelex/plugins/test_inference_backend_coverage.py+++ b/tests/unit/pipelex/plugins/test_inference_backend_coverage.py@@ -66,6 +66,8 @@ EXPECTED_BACKENDS: list[tuple[InferenceFamily, str]] = [# SEARCH(InferenceFamily.SEARCH, "linkup"),(InferenceFamily.SEARCH, "gateway_search"),+ # JUDGMENT+ (InferenceFamily.JUDGMENT, "typesafe"),]diff --git a/tests/unit/pipelex/providers/typesafe/test_data.py b/tests/unit/pipelex/providers/typesafe/test_data.pynew file mode 100644index 000000000..4a2109a87--- /dev/null+++ b/tests/unit/pipelex/providers/typesafe/test_data.py@@ -0,0 +1,87 @@+"""Replay material for the TypeSafe backend, recorded against the live API.++Every file under ``tests/data/typesafe/responses/`` was captured by the campaign's spike and is+kept verbatim. A success is the **wire body**, taken from the raw HTTP response rather than from+the SDK's own dump, so a replay test checks our reading of the API and not the SDK's reading of+itself — which matters here, because a rating answer's keys are strings on the wire and integers+only after the SDK has parsed them. A refusal is saved as an envelope describing the exception,+with the wire body nested under ``body``, and is rebuilt into a real SDK exception below.+"""++import json+import re+from pathlib import Path+from typing import Any, ClassVar, cast++import typesafe_sdk+from httpx2 import Headers+from typesafe_sdk import SystemOneResponse, TypeSafeAPIError, TypeSafeAPITimeoutError, TypeSafeError++RESPONSES_DIR = Path(__file__).parents[4] / "data" / "typesafe" / "responses"+++def load_recorded(name: str) -> dict[str, Any]:+ """The recorded JSON document, whether it holds a wire body or an exception envelope."""+ return cast("dict[str, Any]", json.loads((RESPONSES_DIR / f"{name}.json").read_text(encoding="utf-8")))+++def load_recorded_response(name: str) -> SystemOneResponse:+ """A recorded success, parsed by the SDK exactly as a live call would parse it.++ From the JSON *text*, not from a decoded dict, and the difference is not cosmetic: a rating's+ ``probabilities`` and ``legend`` are keyed by strings on the wire, and the SDK's models only+ coerce those keys to integers in JSON mode. Validating the decoded dict refuses every rating.+ """+ return SystemOneResponse.model_validate_json((RESPONSES_DIR / f"{name}.json").read_text(encoding="utf-8"))+++def rebuild_recorded_exception(name: str) -> BaseException:+ """The SDK exception a recorded refusal produced, rebuilt from its envelope.++ Rebuilt as the real class rather than as a stand-in because the class name is itself part of+ what the classification reads: a bare ``TypeSafeError`` is a different verdict from any of its+ API subclasses, and a stand-in would let that distinction pass untested.+ """+ envelope = load_recorded(name)+ class_name: str = envelope["class"]+ if "status" in envelope:+ api_error_class = cast("type[TypeSafeAPIError]", getattr(typesafe_sdk, class_name))+ return api_error_class(+ status=envelope["status"],+ body=envelope.get("body"),+ headers=Headers(envelope.get("response_headers", {})),+ message=envelope["str"],+ endpoint=envelope.get("endpoint"),+ )+ if class_name == TypeSafeAPITimeoutError.__name__:+ timeout_match = re.search(r"timeout=([0-9.]+)\)", envelope["str"])+ assert timeout_match is not None, f"recorded timeout carries no duration: {envelope['str']!r}"+ return TypeSafeAPITimeoutError(timeout=float(timeout_match.group(1)))+ assert class_name == TypeSafeError.__name__, f"no rebuild rule for recorded class {class_name!r}"+ return TypeSafeError(envelope["str"])+++class TestData:+ """The recorded cases each test reads, named by what they demonstrate."""++ # Successes — wire bodies.+ THREE_SHAPES = "01_three_shapes"+ USAGE_ONE_QUESTION = "02_usage_one_question"+ CHOICE_NULL_DESCRIPTIONS = "04_choice_null_descriptions"+ SCORE_TEN_LEVELS = "04_score_ten_levels"++ # Refusals — exception envelopes. The first four are the four verdicts a `400` can mean.+ STATE_TOO_LARGE = "04b_state_200k_chars_error"+ UNKNOWN_MODEL = "05_model_jev_does_not_exist_error"+ MALFORMED_QUESTION = "06_malformed_question"+ TOO_MANY_LEVELS = "04_score_eleven_levels_error"+ WRONG_KEY = "06_wrong_key"+ EMPTY_QUESTIONS = "06_empty_questions"+ TIMEOUT = "06_timeout"++ # The questions `01_three_shapes` was recorded from, spelled exactly as they were sent.+ THREE_SHAPES_INSTRUCTIONS: ClassVar[dict[str, str]] = {+ "is_urgent": "Is the message urgent?",+ "team": "Which team should handle this message?",+ "severity": "How severe is the reported issue?",+ }diff --git a/tests/unit/pipelex/providers/typesafe/test_typesafe_client_factory.py b/tests/unit/pipelex/providers/typesafe/test_typesafe_client_factory.pynew file mode 100644index 000000000..c20cfcee2--- /dev/null+++ b/tests/unit/pipelex/providers/typesafe/test_typesafe_client_factory.py@@ -0,0 +1,15 @@+import pytest++from pipelex.cogt.model_backends.backend import InferenceBackend+from pipelex.providers.typesafe.typesafe_client_factory import make_typesafe_client+from pipelex.providers.typesafe.typesafe_exceptions import TypesafeError+++class TestTypesafeClientFactory:+ @pytest.mark.parametrize("api_key", [None, ""], ids=["absent", "empty"])+ def test_it_refuses_a_backend_without_a_usable_key(self, api_key: str | None) -> None:+ """An empty key is no key: the SDK would send `Bearer ` and fail as a retried connection error."""+ backend = InferenceBackend(name="typesafe", endpoint=None, api_key=api_key)++ with pytest.raises(TypesafeError, match="no API key"):+ make_typesafe_client(backend=backend)diff --git a/tests/unit/pipelex/providers/typesafe/test_typesafe_error_classification.py b/tests/unit/pipelex/providers/typesafe/test_typesafe_error_classification.pynew file mode 100644index 000000000..acd22c552--- /dev/null+++ b/tests/unit/pipelex/providers/typesafe/test_typesafe_error_classification.py@@ -0,0 +1,177 @@+import pytest+from httpx2 import Headers+from typesafe_sdk import TypeSafeAPIError, TypeSafeAuthenticationError, TypeSafeInternalServerError, TypeSafeRateLimitError++from pipelex.cogt.exceptions import InferenceErrorCategory, JudgmentJobFailureError, JudgmentModelNotFoundError+from pipelex.cogt.inference.error_classification import (+ TYPESAFE_API_USAGE_ERROR_TYPE,+ TYPESAFE_AUTHENTICATION_ERROR_TYPE,+ TYPESAFE_MALFORMED_REQUEST_CODE,+ TYPESAFE_MAX_TOKENS_EXCEEDED_ERROR_TYPE,+ UserActionKind,+ extract_typesafe_metadata,+)+from pipelex.cogt.inference.error_render import InferenceErrorFamily, render_inference_error+from pipelex.cogt.inference.provider_name import ProviderName+from pipelex.providers.typesafe.typesafe_error_classification import classify_typesafe_error+from tests.unit.pipelex.providers.typesafe.test_data import TestData, rebuild_recorded_exception+++class TestTypesafeErrorClassification:+ @pytest.mark.parametrize(+ ("recorded", "status_code", "provider_error_code", "category", "user_action_kind", "is_model_not_found"),+ [+ pytest.param(+ TestData.WRONG_KEY,+ 401,+ TYPESAFE_AUTHENTICATION_ERROR_TYPE,+ InferenceErrorCategory.CONFIGURATION,+ UserActionKind.CHECK_CREDENTIALS,+ False,+ id="wrong_key_is_credentials",+ ),+ pytest.param(+ TestData.STATE_TOO_LARGE,+ 400,+ TYPESAFE_MAX_TOKENS_EXCEEDED_ERROR_TYPE,+ InferenceErrorCategory.CONTENT,+ UserActionKind.CHANGE_INPUT,+ False,+ id="oversized_state_is_the_callers_content",+ ),+ pytest.param(+ TestData.UNKNOWN_MODEL,+ 400,+ TYPESAFE_API_USAGE_ERROR_TYPE,+ InferenceErrorCategory.CONFIGURATION,+ UserActionKind.CHANGE_MODEL,+ True,+ id="unknown_model_is_a_missing_model",+ ),+ pytest.param(+ TestData.MALFORMED_QUESTION,+ 400,+ TYPESAFE_MALFORMED_REQUEST_CODE,+ InferenceErrorCategory.CONFIGURATION,+ UserActionKind.CONTACT_SUPPORT,+ False,+ id="illegal_question_is_a_pipelex_defect",+ ),+ pytest.param(+ TestData.TOO_MANY_LEVELS,+ 400,+ TYPESAFE_MALFORMED_REQUEST_CODE,+ InferenceErrorCategory.CONFIGURATION,+ UserActionKind.CONTACT_SUPPORT,+ False,+ id="scale_past_the_cap_is_a_pipelex_defect",+ ),+ pytest.param(+ TestData.EMPTY_QUESTIONS,+ None,+ None,+ InferenceErrorCategory.CONFIGURATION,+ UserActionKind.CONTACT_SUPPORT,+ False,+ id="client_side_refusal_is_a_pipelex_defect",+ ),+ pytest.param(+ TestData.TIMEOUT,+ None,+ None,+ InferenceErrorCategory.TRANSIENT,+ UserActionKind.WAIT_AND_RETRY,+ False,+ id="timeout_is_transient",+ ),+ ],+ )+ def test_each_recorded_refusal_gets_its_own_verdict(+ self,+ recorded: str,+ status_code: int | None,+ provider_error_code: str | None,+ category: InferenceErrorCategory,+ user_action_kind: UserActionKind,+ is_model_not_found: bool,+ ) -> None:+ """Four different verdicts share status 400 on this API, and only the body tells them apart."""+ metadata = extract_typesafe_metadata(rebuild_recorded_exception(recorded))+ classification = classify_typesafe_error(metadata)++ assert metadata.provider is ProviderName.TYPESAFE+ assert metadata.status_code == status_code+ assert metadata.provider_error_code == provider_error_code+ assert classification.category is category+ assert classification.user_action_kind is user_action_kind+ assert classification.is_model_not_found is is_model_not_found++ @pytest.mark.parametrize(+ ("exception", "category", "user_action_kind"),+ [+ pytest.param(+ TypeSafeRateLimitError(status=429, body={"detail": "Rate limit exceeded"}, headers=Headers()),+ InferenceErrorCategory.TRANSIENT,+ UserActionKind.WAIT_AND_RETRY,+ id="rate_limit",+ ),+ pytest.param(+ TypeSafeInternalServerError(status=503, body={"detail": "Service Unavailable"}, headers=Headers()),+ InferenceErrorCategory.TRANSIENT,+ UserActionKind.WAIT_AND_RETRY,+ id="unavailable",+ ),+ pytest.param(+ TypeSafeAuthenticationError(status=401, body={"detail": "Not authenticated"}, headers=Headers()),+ InferenceErrorCategory.CONFIGURATION,+ UserActionKind.CHECK_CREDENTIALS,+ id="unauthenticated",+ ),+ ],+ )+ def test_a_bare_sentence_off_a_400_goes_to_the_status_ladder(+ self,+ exception: TypeSafeAPIError,+ category: InferenceErrorCategory,+ user_action_kind: UserActionKind,+ ) -> None:+ """Only a `400` with a bare-sentence detail is a malformed request; any other status keeps its own verdict."""+ metadata = extract_typesafe_metadata(exception)+ classification = classify_typesafe_error(metadata)++ assert metadata.provider_error_code is None+ assert classification.category is category+ assert classification.user_action_kind is user_action_kind++ def test_a_rate_limit_carries_its_retry_after(self) -> None:+ exception = TypeSafeRateLimitError(status=429, body={"detail": "Rate limit exceeded"}, headers=Headers({"retry-after": "3"}))+ assert extract_typesafe_metadata(exception).retry_after_seconds == 3.0++ def test_an_api_error_carries_its_request_id(self) -> None:+ """On the error path the request id is a plain attribute, read without the guard the success path needs."""+ metadata = extract_typesafe_metadata(rebuild_recorded_exception(TestData.UNKNOWN_MODEL))+ assert metadata.request_id == "req_01a0b97aa532770083aece1331cb7c76"++ def test_a_client_side_refusal_has_no_request_id(self) -> None:+ metadata = extract_typesafe_metadata(rebuild_recorded_exception(TestData.EMPTY_QUESTIONS))+ assert metadata.request_id is None+ assert metadata.sdk_exception_type == "TypeSafeError"++ @pytest.mark.parametrize(+ ("recorded", "expected_class"),+ [+ pytest.param(TestData.UNKNOWN_MODEL, JudgmentModelNotFoundError, id="unknown_model"),+ pytest.param(TestData.STATE_TOO_LARGE, JudgmentJobFailureError, id="state_too_large"),+ ],+ )+ def test_the_verdict_selects_the_judgment_family_class(self, recorded: str, expected_class: type[Exception]) -> None:+ """An unknown model renders as the family's model-not-found error; every other refusal as its job failure."""+ metadata = extract_typesafe_metadata(rebuild_recorded_exception(recorded))+ rendered = render_inference_error(+ metadata=metadata,+ classification=classify_typesafe_error(metadata),+ family=InferenceErrorFamily.JUDGMENT,+ model_desc="jev-does-not-exist",+ model_handle="jev-does-not-exist",+ )+ assert type(rendered) is expected_classdiff --git a/tests/unit/pipelex/providers/typesafe/test_typesafe_judgment_worker.py b/tests/unit/pipelex/providers/typesafe/test_typesafe_judgment_worker.pynew file mode 100644index 000000000..e17d7698a--- /dev/null+++ b/tests/unit/pipelex/providers/typesafe/test_typesafe_judgment_worker.py@@ -0,0 +1,158 @@+from typing import cast++import pytest+from pytest_mock import MockerFixture+from typesafe_sdk import AsyncTypeSafeClient, SystemOneResponse+from typesafe_sdk import Noul as TypesafeNoul+from typing_extensions import override++from pipelex.cogt.exceptions import JudgmentModelNotFoundError+from pipelex.cogt.inference.inference_job_abstract import InferenceJobAbstract+from pipelex.cogt.judgment.judgment_job import JudgmentJob+from pipelex.cogt.judgment.judgment_job_factory import JudgmentJobFactory+from pipelex.cogt.judgment.judgment_models import ChoiceQuestion, JudgmentQuestion, RatingQuestion, YesNoAnswer, YesNoQuestion+from pipelex.cogt.judgment.judgment_setting import JudgmentSetting+from pipelex.cogt.llm.thinking_mode import ThinkingMode+from pipelex.cogt.model_backends.model_spec import InferenceModelSpec+from pipelex.cogt.model_backends.model_type import ModelType+from pipelex.cogt.usage.cost_category import CostCategory+from pipelex.cogt.usage.token_category import TokenCategory+from pipelex.providers.typesafe.typesafe_judgment_worker import TypesafeJudgmentWorker+from pipelex.reporting.reporting_protocol import ReportingNoOp+from pipelex.system.job_metadata import JobMetadata, RunMetadata+from tests.unit.pipelex.providers.typesafe.test_data import TestData, load_recorded_response, rebuild_recorded_exception++THREE_SHAPES_QUESTIONS: dict[str, JudgmentQuestion] = {+ "is_urgent": YesNoQuestion(instructions=TestData.THREE_SHAPES_INSTRUCTIONS["is_urgent"]),+ "team": ChoiceQuestion(+ instructions=TestData.THREE_SHAPES_INSTRUCTIONS["team"],+ options={"payments": None, "shipping": None, "accounts": None, "other": None},+ ),+ "severity": RatingQuestion(+ instructions=TestData.THREE_SHAPES_INSTRUCTIONS["severity"],+ levels=["Cosmetic", "Degraded with a workaround", "Blocking"],+ ),+}+++class _RecordingDelegate(ReportingNoOp):+ def __init__(self) -> None:+ self.reported: list[InferenceJobAbstract] = []++ @override+ def report_inference_job(self, inference_job: InferenceJobAbstract) -> None:+ self.reported.append(inference_job)+++def _model() -> InferenceModelSpec:+ return InferenceModelSpec(+ backend_name="typesafe",+ name="jev-1.13.0",+ sdk="typesafe",+ model_type=ModelType.JUDGMENT,+ model_id="jev-1.13.0",+ inputs=["text"],+ outputs=["judgments"],+ costs={CostCategory.INPUT: 0.042, CostCategory.OUTPUT: 0},+ thinking_mode=ThinkingMode.NONE,+ max_tokens=None,+ max_prompt_images=None,+ )+++def _job(questions: dict[str, JudgmentQuestion]) -> JudgmentJob:+ return JudgmentJobFactory.make_judgment_job(+ state={"message": "Our production checkout has been returning 500s for every card payment since 09:14 UTC."},+ questions=questions,+ judgment_setting=JudgmentSetting(model="jev-1.13.0"),+ job_metadata=JobMetadata(run_metadata=RunMetadata(storage_scope="test/scope", read_scope=None, user_id="u", pipeline_run_id="run_typesafe")),+ )+++class TestTypesafeJudgmentWorker:+ async def test_one_request_carries_the_whole_job_and_its_usage_is_recorded(self, mocker: MockerFixture) -> None:+ """The job goes out as a single request under the pinned model id, and the billed tokens land on the report."""+ client = mocker.Mock(spec=AsyncTypeSafeClient)+ client.system_one = mocker.AsyncMock(return_value=load_recorded_response(TestData.THREE_SHAPES))+ delegate = _RecordingDelegate()+ worker = TypesafeJudgmentWorker(sdk_instance=cast("AsyncTypeSafeClient", client), inference_model=_model(), reporting_delegate=delegate)+ job = _job(THREE_SHAPES_QUESTIONS)++ answers = await worker.judge(job)++ client.system_one.assert_awaited_once()+ call = client.system_one.await_args+ assert call is not None+ sent_state, sent_questions = call.args+ assert sent_state == job.state+ assert set(sent_questions) == set(THREE_SHAPES_QUESTIONS)+ assert isinstance(sent_questions["is_urgent"], TypesafeNoul)+ assert call.kwargs == {"model": "jev-1.13.0"}++ assert answers["is_urgent"] == YesNoAnswer(probability=0.98)+ usage = job.job_report.judgment_tokens_usage+ assert usage is not None+ assert usage.nb_tokens_by_category == {TokenCategory.INPUT: 506, TokenCategory.OUTPUT: 78}+ assert delegate.reported == [job]++ async def test_absent_usage_records_no_tokens_rather_than_a_guess(self, mocker: MockerFixture) -> None:+ response = load_recorded_response(TestData.USAGE_ONE_QUESTION)+ response_without_usage = SystemOneResponse.model_validate_json(+ response.model_dump_json().replace('"input_tokens":354', '"input_tokens":null').replace('"output_tokens":23', '"output_tokens":null')+ )+ client = mocker.Mock(spec=AsyncTypeSafeClient)+ client.system_one = mocker.AsyncMock(return_value=response_without_usage)+ worker = TypesafeJudgmentWorker(sdk_instance=cast("AsyncTypeSafeClient", client), inference_model=_model())+ job = _job({"is_urgent": YesNoQuestion(instructions="Is the message urgent?")})++ await worker.judge(job)++ usage = job.job_report.judgment_tokens_usage+ assert usage is not None+ assert usage.nb_tokens_by_category == {}++ async def test_a_refusal_is_classified_rendered_and_still_reported(self, mocker: MockerFixture) -> None:+ """An unknown model surfaces as the family's model-not-found error, carrying this backend, and the attempt is reported."""+ client = mocker.Mock(spec=AsyncTypeSafeClient)+ client.system_one = mocker.AsyncMock(side_effect=rebuild_recorded_exception(TestData.UNKNOWN_MODEL))+ delegate = _RecordingDelegate()+ worker = TypesafeJudgmentWorker(sdk_instance=cast("AsyncTypeSafeClient", client), inference_model=_model(), reporting_delegate=delegate)+ job = _job({"is_urgent": YesNoQuestion(instructions="Is the message urgent?")})++ with pytest.raises(JudgmentModelNotFoundError) as exc_info:+ await worker.judge(job)++ assert exc_info.value.backend_name == "typesafe"+ assert exc_info.value.provider_metadata is not None+ assert exc_info.value.provider_metadata.request_id == "req_01a0b97aa532770083aece1331cb7c76"+ assert delegate.reported == [job]+ usage = job.job_report.judgment_tokens_usage+ assert usage is not None+ assert usage.nb_tokens_by_category == {}++ @pytest.mark.parametrize(+ ("requested_model_id", "expects_warning"),+ [+ pytest.param("jev-1.13.0", False, id="pin_honoured"),+ pytest.param("jev-latest", True, id="another_model_answered"),+ ],+ )+ async def test_it_warns_when_another_model_answered(self, mocker: MockerFixture, requested_model_id: str, expects_warning: bool) -> None:+ """The recorded response names ``jev-1.13.0``; asking for anything else is a pin the API did not honour."""+ warning = mocker.patch("pipelex.providers.typesafe.typesafe_judgment_worker.log.warning")+ client = mocker.Mock(spec=AsyncTypeSafeClient)+ client.system_one = mocker.AsyncMock(return_value=load_recorded_response(TestData.USAGE_ONE_QUESTION))+ worker = TypesafeJudgmentWorker(+ sdk_instance=cast("AsyncTypeSafeClient", client),+ inference_model=_model().model_copy(update={"model_id": requested_model_id}),+ )++ await worker.judge(_job({"is_urgent": YesNoQuestion(instructions="Is the message urgent?")}))++ if expects_warning:+ warning.assert_called_once()+ assert "'jev-latest'" in warning.call_args.args[0]+ assert "'jev-1.13.0'" in warning.call_args.args[0]+ else:+ warning.assert_not_called()diff --git a/tests/unit/pipelex/providers/typesafe/test_typesafe_plugin_guard.py b/tests/unit/pipelex/providers/typesafe/test_typesafe_plugin_guard.pynew file mode 100644index 000000000..5992308f0--- /dev/null+++ b/tests/unit/pipelex/providers/typesafe/test_typesafe_plugin_guard.py@@ -0,0 +1,44 @@+from __future__ import annotations++from types import SimpleNamespace+from typing import TYPE_CHECKING, cast++import pytest++from pipelex.plugins.inference_backend_registry import InferenceFamily+from pipelex.plugins.registrar import PluginRegistrar+from pipelex.providers.typesafe.typesafe_plugin import TypesafePlugin+from pipelex.system.exceptions import MissingDependencyError++if TYPE_CHECKING:+ from pytest_mock import MockerFixture++ from pipelex.cogt.model_backends.backend import InferenceBackend+ from pipelex.cogt.model_backends.model_spec import InferenceModelSpec+ from pipelex.plugins.sdk_client_registry import SdkClientRegistry+ from pipelex.system.configuration.configs import PipelexConfig++REGISTRY_MODULE = "pipelex.plugins.inference_backend_registry"+++class TestTypesafeJudgmentWorkerGuard:+ def test_missing_typesafe_sdk_raises_missing_dependency(self, mocker: MockerFixture) -> None:+ """The judgment backend guards the optional SDK before importing a worker that imports it at the top.++ An absent extra must surface as a MissingDependencyError naming ``pipelex[typesafe]``, not+ as a raw ModuleNotFoundError from deep inside the worker module.+ """+ mocker.patch(f"{REGISTRY_MODULE}.importlib.util.find_spec", return_value=None)++ registrar = PluginRegistrar(config=cast("PipelexConfig", SimpleNamespace()))+ TypesafePlugin().register(registrar)+ make_judgment_worker = registrar.inference_backends[InferenceFamily.JUDGMENT, "typesafe"]++ with pytest.raises(MissingDependencyError) as exc_info:+ make_judgment_worker(+ inference_model=cast("InferenceModelSpec", None),+ backend=cast("InferenceBackend", None),+ sdk_clients=cast("SdkClientRegistry", None),+ reporting_delegate=None,+ )+ assert "pipelex[typesafe]" in str(exc_info.value)diff --git a/tests/unit/pipelex/providers/typesafe/test_typesafe_translation.py b/tests/unit/pipelex/providers/typesafe/test_typesafe_translation.pynew file mode 100644index 000000000..5a8ca2e08--- /dev/null+++ b/tests/unit/pipelex/providers/typesafe/test_typesafe_translation.py@@ -0,0 +1,180 @@+import pytest+from typesafe_sdk import Choice as TypesafeChoice+from typesafe_sdk import Noul as TypesafeNoul+from typesafe_sdk import Score as TypesafeScore+from typesafe_sdk import SystemOneResponse++from pipelex.cogt.judgment.judgment_models import (+ ChoiceAnswer,+ ChoiceQuestion,+ JudgmentQuestion,+ RatingAnswer,+ RatingQuestion,+ YesNoAnswer,+ YesNoQuestion,+)+from pipelex.providers.typesafe.typesafe_exceptions import TypesafeJudgmentResponseError, TypesafeQuestionUnsupportedError+from pipelex.providers.typesafe.typesafe_translation import (+ TYPESAFE_MAX_RATING_LEVELS,+ from_typesafe_response,+ to_typesafe_question,+)+from tests.unit.pipelex.providers.typesafe.test_data import TestData, load_recorded, load_recorded_response++SEVERITY_LEVELS = [+ "Cosmetic; no impact on functionality",+ "A feature is degraded, but a workaround exists",+ "Blocking issue; no workaround exists",+]+++class TestTypesafeTranslation:+ def test_yes_no_sends_only_the_criteria_it_declares(self) -> None:+ """Both sides go out under the vendor's own keys, one side alone goes out alone, and neither sends no map at all."""+ both = to_typesafe_question(+ question_key="q", question=YesNoQuestion(instructions="Is it urgent?", yes_criterion="Needs attention now", no_criterion="Can wait")+ )+ yes_only = to_typesafe_question(question_key="q", question=YesNoQuestion(instructions="Is it urgent?", yes_criterion="Needs attention now"))+ neither = to_typesafe_question(question_key="q", question=YesNoQuestion(instructions="Is it urgent?"))++ assert isinstance(both, TypesafeNoul)+ assert both.model_dump()["criteria"] == {"true": "Needs attention now", "false": "Can wait"}+ assert isinstance(yes_only, TypesafeNoul)+ assert yes_only.model_dump()["criteria"] == {"true": "Needs attention now"}+ assert isinstance(neither, TypesafeNoul)+ assert "criteria" not in neither.model_dump()+ assert neither.model_dump()["instructions"] == "Is it urgent?"++ def test_choice_keeps_an_undescribed_option_as_null(self) -> None:+ question = ChoiceQuestion(instructions="What is the tone?", options={"calm": None, "angry": "Raised voice, blame"})+ rendered = to_typesafe_question(question_key="tone", question=question)++ assert isinstance(rendered, TypesafeChoice)+ assert rendered.model_dump()["criteria"] == {"calm": None, "angry": "Raised voice, blame"}++ def test_rating_goes_out_as_an_ordered_score(self) -> None:+ rendered = to_typesafe_question(question_key="severity", question=RatingQuestion(instructions="How severe?", levels=SEVERITY_LEVELS))++ assert isinstance(rendered, TypesafeScore)+ assert rendered.model_dump()["criteria"] == SEVERITY_LEVELS++ @pytest.mark.parametrize(+ ("nb_levels", "is_accepted"),+ [+ pytest.param(TYPESAFE_MAX_RATING_LEVELS, True, id="at_the_cap"),+ pytest.param(TYPESAFE_MAX_RATING_LEVELS + 1, False, id="one_past_the_cap"),+ ],+ )+ def test_the_vendor_rating_cap_is_enforced_at_its_boundary(self, nb_levels: int, is_accepted: bool) -> None:+ """Ten levels go out and eleven are refused before any request is built, as the live API refuses them."""+ question = RatingQuestion(instructions="How severe?", levels=[f"Level {index_level}" for index_level in range(nb_levels)])+ if is_accepted:+ assert isinstance(to_typesafe_question(question_key="q", question=question), TypesafeScore)+ return+ with pytest.raises(TypesafeQuestionUnsupportedError) as exc_info:+ to_typesafe_question(question_key="q", question=question)+ assert "'q'" in str(exc_info.value)+ assert f"{nb_levels}-level" in str(exc_info.value)++ def test_the_three_kinds_read_back_from_one_recorded_response(self) -> None:+ """The recorded three-question response maps back to the family's three answer kinds, value for value."""+ questions: dict[str, JudgmentQuestion] = {+ "is_urgent": YesNoQuestion(instructions=TestData.THREE_SHAPES_INSTRUCTIONS["is_urgent"]),+ "team": ChoiceQuestion(+ instructions=TestData.THREE_SHAPES_INSTRUCTIONS["team"],+ options={"payments": None, "shipping": None, "accounts": None, "other": None},+ ),+ "severity": RatingQuestion(instructions=TestData.THREE_SHAPES_INSTRUCTIONS["severity"], levels=SEVERITY_LEVELS),+ }+ answers = from_typesafe_response(questions=questions, response=load_recorded_response(TestData.THREE_SHAPES))++ assert answers["is_urgent"] == YesNoAnswer(probability=0.98)+ assert answers["team"] == ChoiceAnswer(+ choice="payments",+ confidence=1.0,+ probabilities={"accounts": 0.0, "other": 0.0, "payments": 1.0, "shipping": 0.0},+ )+ assert answers["severity"] == RatingAnswer(level=2, position=2.0, confidence=1.0, probabilities={0: 0.0, 1: 0.0, 2: 1.0})++ def test_a_yes_no_answer_leaves_the_verdict_to_the_threshold(self) -> None:+ """The backend measured a probability; the side of the threshold is the caller's decision, so ``yes_no`` stays absent."""+ answers = from_typesafe_response(+ questions={"is_urgent": YesNoQuestion(instructions="Is the message urgent?")},+ response=load_recorded_response(TestData.USAGE_ONE_QUESTION),+ )+ answer = answers["is_urgent"]+ assert isinstance(answer, YesNoAnswer)+ assert answer.yes_no is None+ assert answer.probability == 0.98++ def test_a_spread_rating_names_its_most_probable_level_not_its_position(self) -> None:+ """The recorded ten-level answer sits at position 7.86 but is most probable at level 9 — the verdict is 9."""+ answers = from_typesafe_response(+ questions={"q": RatingQuestion(instructions="How severe?", levels=[f"Severity level {index_level}" for index_level in range(10)])},+ response=load_recorded_response(TestData.SCORE_TEN_LEVELS),+ )+ answer = answers["q"]+ assert isinstance(answer, RatingAnswer)+ assert answer.level == 9+ assert answer.position == 7.86+ assert answer.confidence == 0.54+ assert answer.probabilities is not None+ assert answer.probabilities[9] == 0.43++ @pytest.mark.parametrize(+ ("wire_probabilities", "score", "expected_level"),+ [+ pytest.param('{"0": 0.2, "1": 0.5, "2": 0.3}', 1.1, 1, id="peak_in_the_middle"),+ pytest.param('{"0": 0.6, "1": 0.1, "2": 0.3}', 0.7, 0, id="peak_at_the_floor_above_the_position"),+ pytest.param('{"0": 0.4, "1": 0.4, "2": 0.2}', 0.8, 0, id="a_tie_goes_to_the_lower_level"),+ ],+ )+ def test_the_rating_verdict_is_the_most_probable_level(self, wire_probabilities: str, score: float, expected_level: int) -> None:+ """Not the top level and not the rounded position: the peak of the distribution, ties going low."""+ wire_body = (+ '{"model": "jev-1.13.0", "usage": {"input_tokens": 1, "output_tokens": 1}, "answers": {"q": '+ f'{{"type": "score", "score": {score}, "confidence": 0.5, "legend": {{"0": "a", "1": "b", "2": "c"}}, '+ f'"probabilities": {wire_probabilities}}}}}}}'+ )+ answers = from_typesafe_response(+ questions={"q": RatingQuestion(instructions="How severe?", levels=["a", "b", "c"])},+ response=SystemOneResponse.model_validate_json(wire_body),+ )+ answer = answers["q"]+ assert isinstance(answer, RatingAnswer)+ assert answer.level == expected_level+ assert answer.position == score++ def test_rating_keys_are_strings_on_the_wire_and_integers_once_read(self) -> None:+ """The replay fixture holds the wire form; the family's answer holds integer levels."""+ wire_probabilities = load_recorded(TestData.SCORE_TEN_LEVELS)["answers"]["q"]["probabilities"]+ assert all(isinstance(level, str) for level in wire_probabilities)++ answers = from_typesafe_response(+ questions={"q": RatingQuestion(instructions="How severe?", levels=[f"Severity level {index_level}" for index_level in range(10)])},+ response=load_recorded_response(TestData.SCORE_TEN_LEVELS),+ )+ answer = answers["q"]+ assert isinstance(answer, RatingAnswer)+ assert answer.probabilities is not None+ assert sorted(answer.probabilities) == list(range(10))++ def test_an_answer_of_the_wrong_kind_is_refused(self) -> None:+ """A choice answer read back for a question asked as a rating cannot be translated at all."""+ with pytest.raises(TypesafeJudgmentResponseError) as exc_info:+ from_typesafe_response(+ questions={"q": RatingQuestion(instructions="How severe?", levels=SEVERITY_LEVELS)},+ response=load_recorded_response(TestData.CHOICE_NULL_DESCRIPTIONS),+ )+ assert "'q'" in str(exc_info.value)+ assert "'choice'" in str(exc_info.value)+ assert "'rating'" in str(exc_info.value)++ def test_a_missing_answer_is_refused(self) -> None:+ with pytest.raises(TypesafeJudgmentResponseError) as exc_info:+ from_typesafe_response(+ questions={"never_answered": YesNoQuestion(instructions="Is it urgent?")},+ response=load_recorded_response(TestData.USAGE_ONE_QUESTION),+ )+ assert "'never_answered'" in str(exc_info.value)+ assert "without an answer" in str(exc_info.value)diff --git a/tests/unit/pipelex/test_extras/test_ci_placeholder_keys.py b/tests/unit/pipelex/test_extras/test_ci_placeholder_keys.pynew file mode 100644index 000000000..e9f3716da--- /dev/null+++ b/tests/unit/pipelex/test_extras/test_ci_placeholder_keys.py@@ -0,0 +1,34 @@+import re+import tomllib+from pathlib import Path+from typing import Any, cast++from pipelex.test_extras.shared_pytest_plugins import ENV_VAR_KEYS_WHICH_MAY_NEED_PLACEHOLDERS_IN_CI++KIT_BACKENDS_PATH = Path(__file__).parents[4] / "pipelex" / "kit" / "configs" / "inference" / "backends.toml"++# `${VAR}` and `${env:VAR}`. A `${secret:…}` reference is resolved by the secrets provider and a+# fallback chain (`|`) carries its own default, so neither needs a CI placeholder.+_ENV_REFERENCE = re.compile(r"\$\{(?:env:)?([A-Z0-9_]+)\}")+++class TestCiPlaceholderKeys:+ def test_every_enabled_kit_backend_variable_gets_a_ci_placeholder(self) -> None:+ """A kit backend shipped enabled must have each of its variables in the CI placeholder list.++ CI runners hold no provider keys at all, and every test module boots live, so an enabled+ backend whose variable is not given a placeholder fails the boot of every shard — which is+ what a new bring-your-own-key backend does if this list is forgotten.+ """+ backends = cast("dict[str, dict[str, Any]]", tomllib.loads(KIT_BACKENDS_PATH.read_text(encoding="utf-8")))+ missing: dict[str, str] = {}+ for backend_name, backend_table in backends.items():+ if not backend_table.get("enabled", True):+ continue+ for value in backend_table.values():+ if not isinstance(value, str):+ continue+ for var_name in _ENV_REFERENCE.findall(value):+ if var_name not in ENV_VAR_KEYS_WHICH_MAY_NEED_PLACEHOLDERS_IN_CI:+ missing[var_name] = backend_name+ assert not missing, f"Add these to ENV_VAR_KEYS_WHICH_MAY_NEED_PLACEHOLDERS_IN_CI (variable -> backend): {missing}"diff --git a/wip/judgment-family/design.md b/wip/judgment-family/design.mdindex 8fc39556c..82ed9f120 100644--- a/wip/judgment-family/design.md+++ b/wip/judgment-family/design.md@@ -1,5 +1,5 @@----status: draft+status: activeitem: L-260919-9965d0---@@ -9,7 +9,7 @@ A judgment is a closed-form verdict on some material: a yes or a no, one optionThis design adds a new `InferenceFamily` member beside `search` (`pipelex/plugins/inference_backend_registry.py:11`), a worker contract for it, a new operator that reaches it, and a first backend: TypeSafe's Jev model, whose question types are exactly these verdict shapes. `search` is the family it copies, because `search` is the lightest: no core config section, no cached workers, one leaf module, one kernel module.-**Scope of this document:** the contracts and the decisions. The implementation tracker is the `plan.md` beside it, and the campaign's items are filed on the ledger under the epic. Ratification is still outstanding — the open questions at the end are what it has to settle — and phase 3's gate waits on it; phases 1 and 2 depend on nothing it leaves open, which is why phase 1 has already run.+**Scope of this document:** the contracts and the decisions. The implementation tracker is the `plan.md` beside it, and the campaign's items are filed on the ledger under the epic. Ratified by Louis on 2026-09-20, and what the ratification settled is the last section, `Ratified decisions`. Phases 1 and 2 depended on nothing it left open, which is why they ran before it; what remains of phase 3's gate is the standard change in `mthds`.## What the backend offers, as observed@@ -78,7 +78,7 @@ levels = [**`PipeJudgeBlueprint` fields** (`pipelex/pipe_operators/judge/pipe_judge_blueprint.py`, mirroring `pipe_search_blueprint.py`):- `type: Literal["PipeJudge"]`, `pipe_category: Literal["PipeOperator"]`.-- `question: str` — required. A template, preprocessed and parsed exactly as `PipeSearchBlueprint.prompt` is, so `$name` and `@name` behave as they do everywhere else and `validate_inputs` diffs required variables against declared inputs with the same code.+- `question: str` — required. A template, preprocessed and parsed exactly as `PipeSearchBlueprint.prompt` is, so `$name` and `@name` behave as they do everywhere else and `validate_inputs` diffs required variables against declared inputs with the same code. **`prompt` is accepted as a synonym of `question`**, resolved at parse time: exactly one of the two may be set, both set is a blueprint validation error naming `question`, and `question` is what the blueprint carries, what the spec layer round-trips and what the builder and the agent CLI emit. Nothing downstream of parsing ever sees `prompt`.- `model: JudgmentModelChoice | None` — a preset, an alias, a waterfall or a bare handle, resolved by the same ladder as `SearchModelChoice`.- `options: dict[str, str] | None` — the choice question's option set, key to description. An empty string is an option with no description, since TOML has no null. At least two options, with non-empty keys. Keys are what the answer carries, and a `PipeCondition` outcome map is keyed by plain strings too, so a `Choice` drives a `PipeCondition` with no translation (`expression = "routing.choice"`, one outcome per option).- `levels: list[str] | None` — the rating question's scale, low to high. At least two levels, each a non-empty description. A level's index in this list is the level number, starting at zero.@@ -120,7 +120,7 @@ Plain rendering follows `YesNoContent`, which renders as "yes" or "no": a `Choic- *One polymorphic `Judgment` native.* Its verdict would be a boolean, a text or a number depending on the producer, which is no type at all.- *`Text` and `Number` as the choice and rating outputs.* Tempting, because `label` is a text-valued intent and `rating` a number-valued one, but a `Text` has nowhere to put a confidence. A later "bare verdict" tier that also accepts a `Text`-compatible or `Number`-compatible output is possible without breaking anything, and is deferred until an author asks: it would silently drop the uncertainty, which is the wrong default.-**Cost of the change, stated plainly.** The natives are pinned by the standard (`pipelex/core/concepts/native/pinned_blueprints.py`, held to `mthds/docs/spec/native-concepts.md` by `test_pinned_natives_vs_standard.py`), so this lands in the `mthds` spec page first, re-pins the set at a new standard version, and ripples to every port: `NativeConceptCode` and its exhaustive matches, new `ChoiceContent` and `RatingContent` classes registered in `CoreRegistryModels.STUFF`, the concept factory, codegen's native expansion, and the projection corpus committed in `mthds-js` and `mthds-python`. Two questions belong to that standard change and are left open here with a recommendation: `Choice` and `Rating` should join the out-of-matrix natives (`OUT_OF_MATRIX_NATIVES` in `pipelex/cli/dev_cli/commands/projection_reference.py`) beside `SearchResult`, because a bare `"billing"` at a `Choice` position is indistinguishable from a `Text`; and `YesNo`'s light form should stay the bare boolean, which means a projection that flattens a judged `YesNo` loses its probability and a consumer who wants it reads the full form.+**Cost of the change, stated plainly.** The natives are pinned by the standard (`pipelex/core/concepts/native/pinned_blueprints.py`, held to `mthds/docs/spec/native-concepts.md` by `test_pinned_natives_vs_standard.py`), so this lands in the `mthds` spec page first, re-pins the set at a new standard version, and ripples to every port: `NativeConceptCode` and its exhaustive matches, new `ChoiceContent` and `RatingContent` classes registered in `CoreRegistryModels.STUFF`, the concept factory, codegen's native expansion, and the projection corpus committed in `mthds-js` and `mthds-python`. Two questions belong to that standard change, and this design states its position rather than settling them here: `Choice` and `Rating` should join the out-of-matrix natives (`OUT_OF_MATRIX_NATIVES` in `pipelex/cli/dev_cli/commands/projection_reference.py`) beside `SearchResult`, because a bare `"billing"` at a `Choice` position is indistinguishable from a `Text`; and `YesNo`'s light form should stay the bare boolean, which means a projection that flattens a judged `YesNo` loses its probability and a consumer who wants it reads the full form.If the standard change cannot land soon, the fallback that wastes the least work is to ship the yes/no kind alone against today's `YesNo`, with the probability in the trace only, and to hold choice and rating until the natives exist. It is a fallback and not the plan, because it ships the operator without its point.@@ -141,7 +141,7 @@ The answers follow the same rule as the natives: `choice` and `level` are the on**Setting and deck.** `JudgmentSetting(ConfigModel)` has `model: str` and `description: str | None` and nothing else; `JudgmentModelChoice` is the usual union with a parsed model reference. `JudgmentDeckBlueprint` has `aliases`, `waterfalls`, `presets` and `choice_default`, flattened onto `ModelDeck` with `get_judgment_setting`, `validate_judgment_presets` and `check_judgment_choice_with_deck` as for search. The deck file is `pipelex/kit/configs/inference/deck/5_judgment_deck.toml` — the numeric prefix is what makes it kit-managed (`pipelex/cogt/models/deck_manifest.py:98`) — and an alias in it points at a versioned handle, never at a `latest` alias: a verdict model that changes under a method silently changes what every threshold in that method means.-**`choice_default` is optional for this family alone, and phase 2 discovered why.** Every other family's default names a handle the Pipelex Gateway carries, so it always resolves. A judgment backend is brought by the user, and `ModelManager._enforce_gateway_model_membership` walks every handle a deck's presets and choice defaults name: a default resolving to `jev-1.13.0`, which the active routing profile sends to the gateway by default and which the gateway does not serve, raises `GatewayUnknownModelError` at **every boot**, for every user, whether or not they ever ask for a judgment. So `JudgmentDeckBlueprint.choice_default` is `JudgmentModelChoice | None = None`, the kit deck ships no default, and a judgment names its own model. The consequence for Part 1 is real and belongs to the "hosted serving" open question: `@default-judgment` is not a usable default for `PipeJudge` until the hosted plane serves the family, so phase 3's operator must require an explicit model or fail with a message saying no judgment model is configured.+**`choice_default` is optional for this family alone, and phase 2 discovered why.** Every other family's default names a handle the Pipelex Gateway carries, so it always resolves. A judgment backend is brought by the user, and `ModelManager._enforce_gateway_model_membership` walks every handle a deck's presets and choice defaults name: a default resolving to `jev-1.13.0`, which the active routing profile sends to the gateway by default and which the gateway does not serve, raises `GatewayUnknownModelError` at **every boot**, for every user, whether or not they ever ask for a judgment. So `JudgmentDeckBlueprint.choice_default` is `JudgmentModelChoice | None = None`, the kit deck ships no default, and a judgment names its own model. Ratification made that permanent rather than temporary: the hosted plane does not serve this family, so no default the kit ships can ever resolve, `@default-judgment` is not a usable default for `PipeJudge`, and phase 3's operator names its model or fails with a message saying no judgment model is configured. A user holding their own key remains free to name a default in their own deck, which the optional `"jev-*"` route resolves.**The family enums.** There are several, and all must move together: `InferenceFamily` (`inference_backend_registry.py:11`), `ModelType` (`pipelex/cogt/model_backends/model_type.py:4`), `InferenceErrorFamily` with its failure and not-found class tables (`pipelex/cogt/inference/error_render.py:35`), and `ModelCategory` in the builder (`pipelex/builder/operations/models_ops.py`). The match statements over them are exhaustive and free of `case _`, so the type checker walks to most arms.@@ -166,9 +166,9 @@ The answers follow the same rule as the natives: `choice` and `level` are the onA built-in plugin at `pipelex/providers/typesafe/`, appended to `KERNEL_BUILTIN_PLUGINS`, registering `add_inference_backend(family=InferenceFamily.JUDGMENT, sdk="typesafe", make_worker=…)`. The `make_worker` closure calls `require_sdk(spec="typesafe_sdk", extra="typesafe", dependency_name="typesafe-sdk", …)` and imports the worker lazily, as `linkup_plugin.py` does.- **Dependency: the SDK, behind a `typesafe` optional extra.** The spike settled this. Using the SDK rather than a hand-written POST buys typed exception classes carrying `status`, `body`, `endpoint` and `request_id` — exactly what the error classification below is written from — and the coercion of a rating answer's string keys to integers, both of which a bare `httpx` worker would have to rebuild. The feared cost did not materialise: the extra added five packages (`typesafe-sdk`, `httpx2`, `httpcore2`, `httpx2-jsfetch`, `truststore`), moved nothing else in the lock, left pydantic where it was, and disturbed neither `mypy` nor `pyright` on any unrelated import. The worker passes an explicit retry policy and timeout rather than inheriting the SDK's defaults, so retry behaviour is a Pipelex decision recorded in one place; note that `RetryPolicy` carries a `timeout` of its own beside the client's and the per-call one, and all three are set deliberately.-- **Backend records.** `[typesafe]` in `backends.toml` with `api_key = "${TYPESAFE_API_KEY}"`, and `backends/typesafe.toml` with `model_type = "judgment"`, `sdk = "typesafe"`, one table per versioned model (`inputs = ["text"]`, `outputs = ["judgments"]`, `costs = { input = 0.042, output = 0 }` per million tokens, from the vendor's models page at the time of writing, output being genuinely free), and a routing profile. The default alias points at `jev-1.13.0`, with a comment saying that a newer versioned id is found on the vendor's models page and not through `GET /v1/models`, which lists only aliases. All mirrored into `.pipelex/inference/`.+- **Backend records.** `[typesafe]` in `backends.toml` with `api_key = "${TYPESAFE_API_KEY}"`, and `backends/typesafe.toml` with `model_type = "judgment"`, `sdk = "typesafe"`, one table per versioned model (`inputs = ["text"]`, `outputs = ["judgments"]`, `costs = { input = 0.042, output = 0 }` per million tokens, from the vendor's models page at the time of writing, output being genuinely free), and a routing profile. **The managed routing profiles also carry an optional route, `"jev-*" = "typesafe"`**, which phase 2 found necessary: under `all_pipelex_gateway` every handle routes to the gateway by default, the gateway does not serve Jev, and a handle nobody serves is silently dropped from the deck — so without it a user holding a TypeSafe key still could not reach the model. An optional route applies only while its backend is enabled. The kit deck carries the alias and still no preset, since a preset would reach the gateway membership check whenever the backend is disabled. The default alias points at `jev-1.13.0`, with a comment saying that a newer versioned id is found on the vendor's models page and not through `GET /v1/models`, which lists only aliases. All mirrored into `.pipelex/inference/`.- **Translation.** The worker maps `YesNoQuestion` to the vendor's yes/no type with `true` and `false` criteria, `ChoiceQuestion` to a choice with a `null` for an undescribed option, `RatingQuestion` to a score, and maps the answers back. The vendor's limits on option and level counts are enforced here, not in the blueprint, because they are this vendor's and not the language's.-- **Errors.** `TypesafeJudgmentResponseError` for an answer that is missing or of the wrong kind. Classification branches on `error_type` where the body carries one and falls back to the status, because a single `400` covers an illegal question, an unknown model and an oversized state: `authentication_error` classifies as credentials, `max_tokens_exceeded` as content, `api_usage_error` naming an unknown model as configuration, rate limit and overload as transient, and a `400` with a bare-string `detail` as a Pipelex defect, since static validation should have caught a malformed question. A bare `TypeSafeError`, raised before the call, is always a Pipelex defect. The family classes are `JudgmentJobFailureError`, `JudgmentModelNotFoundError` and `JudgmentHandleNotFoundError`, and the operator's are `PipeJudgeError` and `PipeJudgeFactoryError`. Error pages and the identity snapshot are regenerated (`gep`, `gei`).+- **Errors.** `TypesafeJudgmentResponseError` for an answer that is missing or of the wrong kind, and `TypesafeQuestionUnsupportedError` for a question this backend's bounds refuse, both under a `TypesafeError` base. Classification branches on `error_type` where the body carries one and falls back to the status, because a single `400` covers an illegal question, an unknown model and an oversized state: `authentication_error` classifies as credentials, `max_tokens_exceeded` as content, `api_usage_error` naming an unknown model as configuration, rate limit and overload as transient, and a `400` with a bare-string `detail` as a Pipelex defect, since static validation should have caught a malformed question. A bare `TypeSafeError`, raised before the call, is always a Pipelex defect. As built, the extract step lifts the body's `error_type` — or a code of its own for a bare-string `detail` — into `provider_error_code`, and the branching lives in the provider package (`classify_typesafe_error`), which hands everything it does not recognise to the shared classifier; that keeps the shared classifier free of vendor names. An `api_usage_error` whose message does not name an unknown model is classified as configuration with a contact-support action, since nothing observed says what else it covers. The worker also warns when the response names a model other than the pinned one, the one case where the pin could fail silently. The family classes are `JudgmentJobFailureError`, `JudgmentModelNotFoundError` and `JudgmentHandleNotFoundError`, and the operator's are `PipeJudgeError` and `PipeJudgeFactoryError`. Error pages and the identity snapshot are regenerated (`gep`, `gei`).**A second backend, not in this campaign.** A worker that emulates the family on a generative model through structured output makes a method using `PipeJudge` runnable on any deck, which matters for an operator that belongs to an open standard. It returns verdicts without uncertainty, which decision 9 makes legal. It is deferred because it is a second implementation of a contract that should first be proven by one.@@ -182,7 +182,7 @@ Not touched, and worth saying so: `InferenceBackendRegistry` and `PluginRegistraThe operator follows `docs/contribute/registration-surface.md`: `PipeType.PIPE_JUDGE` and its category arm, membership in `PipeBlueprintUnion`, `PipeJudge` and `PipeJudgeFactory` in `pipelex/pipe_machinery/registry_models.py` (the omission that boots cleanly and fails later in deserialisation), the output renderer's match, the spec map and the spec union, the TOML emission branch in `pipelex/builder/operations/pipe_ops.py` and its twin in `pipelex/cli/agent_cli/commands/pipe_cmd.py`. No page enumerates what a new inference family touches; this campaign writes it, as a sibling of the registration-surface page, from the site map gathered for this design.-Tests, written first: blueprint kind-resolution and its error messages; output agreement with refinements; state building per content kind; threshold application at and around the boundary; the worker template method's key and kind checks, mutation-tested by breaking each guard; the translation to and from the vendor's shapes against recorded responses; the dry branch; the cost-registry arm, with a test that fails if a family falls through to extract; the registry split test; the kernel boot contract arm. A `judgment` pytest marker joins the default deselect expression, `preprocess_test_models_cmd.py` learns the model type in each of its family tables, the test profiles gain a `judgment_models` key, and an e2e bundle under `tests/e2e/pipelex/pipes/pipe_operators/pipe_judge/` covers the question kinds against the live model.+Tests, written first: blueprint kind-resolution and its error messages, including the `prompt` synonym and the error when both spellings are set; output agreement with refinements; state building per content kind; threshold application at and around the boundary; the worker template method's key and kind checks, mutation-tested by breaking each guard; the translation to and from the vendor's shapes against recorded responses; the dry branch; the cost-registry arm, with a test that fails if a family falls through to extract; the registry split test; the kernel boot contract arm. A `judgment` pytest marker joins the default deselect expression, `preprocess_test_models_cmd.py` learns the model type in each of its family tables, the test profiles gain a `judgment_models` key, and an e2e bundle under `tests/e2e/pipelex/pipes/pipe_operators/pipe_judge/` covers the question kinds against the live model.Corpus: a `[operator.judge]` vocabulary entry and new entries under `pipelex/test_extras/mthds_corpus/entries/`, the first being the urgent-message scenario re-cut with `PipeJudge`. `native_yes_no_urgent_message` stays as it is: it covers `native.yes_no` produced by `PipeLLM`, which remains valid MTHDS.@@ -195,16 +195,16 @@ The order is set by what each step needs from the one before.1. `mthds` — the standard change: the native set in `docs/spec/native-concepts.md`, the `PipeJudge` operator in the language reference, and the two projection questions from Part 2.2. `pipelex` — natives, family, operator, backend, in that order, each independently mergeable: the natives change stands alone, the family is testable with a fake worker before any vendor code exists, and the operator needs both.3. After a `pipelex` release — the schema copies through the `mthds-schema-sync` skill (`mthds`, `vscode-pipelex`, `mthds-ui`), the corpus through `mthds-corpus-sync`, the projection corpus in `mthds-js` and `mthds-python`, a node rendering for the new operator in `mthds-ui`, and the operator lists the authoring skills in `pipelex-plugins` and `mthds-plugins` teach from.-4. The hosted plane — `pipelex-server/temporal/` registers an activity for the new leaf and a queue for it; the pin moves across `pipelex-server` in one commit; and serving the family from the hosted plane without a customer-held key means a route in `pipelex-manifold` and model entries in `pipelex-remote-config`. That last step is a product decision before it is an engineering one.+4. The hosted plane — `pipelex-server/temporal/` registers an activity for the new leaf and a queue for it, and the pin moves across `pipelex-server` in one commit. Nothing else: ratification decided the plane does not serve this family on a Pipelex-held key, so there is no `pipelex-manifold` route and no `pipelex-remote-config` entry to write, and a hosted run reaches a judgment model on the customer's own key or not at all.-## Open questions for ratification+## Ratified decisions-The vendor-dependency question that stood here is closed: the phase 1 spike settled it in favour of the SDK behind an extra, for the reasons in Part 5 and in `spike-findings.md`.+Ratified by Louis on 2026-09-20. The vendor-dependency question that stood here was closed earlier, by the phase 1 spike, in favour of the SDK behind an extra, for the reasons in Part 5 and in `spike-findings.md`.-- **The standard change.** Is extending `YesNo` and adding `Choice` and `Rating` acceptable to the standard, and are those the names? `Rating` is chosen over the vendor's "Score" because the language already owns the word.-- **How much optional surface to pin on day one.** `probabilities` and `position` are the members most shaped by the first backend. The smaller alternative pins only the verdict and one optional scalar per native (`probability` on `YesNo`, `confidence` on `Choice` and `Rating`), keeps the distribution and the position in the trace, and promotes them to the natives when a method needs to branch on them. It is cheaper for the standard and every port, and nothing is lost that cannot be added later; it costs the patterns that read a distribution inside a method, such as falling back to the second most probable option. This design pins them as optional members; the smaller set is the one to take if the standard change meets resistance.-- **`question` or `prompt`.** Every other inference operator calls its template `prompt`. `question` says what the field is; `prompt` is what an authoring agent will reach for. This design takes `question`.-- **Hosted serving.** Whether the hosted plane serves this family with a Pipelex-held key, and therefore whether step 4's manifold work is in the campaign or after it.+- **The natives are `Choice` and `Rating`**, and `YesNo` gains its optional `probability`. `Rating` keeps the word the language already owns, against the vendor's "Score", which reads as an exact magnitude — the reading the vendor's own limitations page warns against.+- **The whole optional surface is pinned on day one**: `probability` on `YesNo`; `confidence` and `probabilities` on `Choice`; `confidence`, `probabilities` and `position` on `Rating`. The smaller alternative above — the verdict and one scalar apiece — was the fallback against resistance from the standard, and this workspace owns the standard, so there is none to trade against. A method can read a distribution, and fall back to the second most probable option, from the day the natives exist.+- **The operator's template field is `question`, with `prompt` accepted as a synonym**, as Part 1 now specifies. `question` is canonical and is what every layer below the parser speaks; `prompt` exists because every other inference operator calls its template that, so an author reaching for it is right about the language and wrong only about this operator.+- **The family is bring-your-own-key, permanently.** The hosted plane does not serve judgments: no Pipelex-held vendor key, no Manifold route, no remote-config entry, and therefore no default the kit can ship. `PipeJudge` names its model or says that none is configured, and the docs teach that a judgment names its own model. This is the settled design rather than a state waiting on the plane, which is what Part 3's `choice_default` paragraph and route step 4 now record.## Deferreddiff --git a/wip/judgment-family/plan.md b/wip/judgment-family/plan.mdindex 93e11cfa4..6d8accf61 100644--- a/wip/judgment-family/plan.md+++ b/wip/judgment-family/plan.md@@ -84,13 +84,13 @@ Both carry the same item; 2a is `Advances` and 2b is `Closes`. Whether 2b stacks- [x] **Deck.** `JudgmentDeckBlueprint`, the flat fields on `ModelDeck`, `get_judgment_setting`, `validate_judgment_presets`, `check_judgment_choice_with_deck`, the suggestion arms, the model manager's handle collection and flattening, and `pipelex/kit/configs/inference/deck/5_judgment_deck.toml` with the default alias on a versioned handle.- [x] **Reporting and cost.** `JudgmentTokensUsage` and its report in both unions, the `ReportingManager` dispatch arm, and in `CostRegistry.compute_cost_report` a judgment arm, an explicit extract arm, and `assert_never` to close. Real token counts, priced per million like an LLM; update the `model_type` comment on `ModelUsageSpec`.- [x] **The leaf.** `JudgmentAssignment`, `pipelex/cogt/content_generation/judgment_generate.py` with the dry branch first, `dry_judgment_gen_answers` (deterministic, uncertainty absent), and `make_judgment_answers` on the protocol and the generator. A unit test pins the dry branch.-- [ ] **The backend.** `pipelex/providers/typesafe/`: plugin, worker, translation both ways, exceptions and error classification, written against the four findings above and unit-tested by replaying the recorded responses in `spike/responses/` — the successes are wire bodies and the refusals are `describe_exception` envelopes with the wire body under `body`, which is what the classification tests read. The vendor's ten-level cap and its option-count limits are enforced in this translation, not in the blueprint. The plugin joins `KERNEL_BUILTIN_PLUGINS`; the client is cached through the `SdkClientRegistry`; retry and timeout are passed explicitly. Backend record in `backends.toml`, `backends/typesafe.toml`, a routing profile, and the `.pipelex/inference/` mirror with its kit manifest. Check that a boot with the backend enabled and the key unset behaves as it does for Linkup, and add the arm to the keyless boot test.-- [ ] **Plugin surface tests.** The expected-backends table in `tests/unit/pipelex/plugins/test_inference_backend_coverage.py`, and a missing-extra guard test mirroring Linkup's.+- [x] **The backend.** `pipelex/providers/typesafe/`: plugin, worker, translation both ways, exceptions and error classification, written against the four findings above and unit-tested by replaying the recorded responses in `spike/responses/` — the successes are wire bodies and the refusals are `describe_exception` envelopes with the wire body under `body`, which is what the classification tests read. The vendor's ten-level cap and its option-count limits are enforced in this translation, not in the blueprint. The plugin joins `KERNEL_BUILTIN_PLUGINS`; the client is cached through the `SdkClientRegistry`; retry and timeout are passed explicitly. Backend record in `backends.toml`, `backends/typesafe.toml`, a routing profile, and the `.pipelex/inference/` mirror with its kit manifest. Check that a boot with the backend enabled and the key unset behaves as it does for Linkup, and add the arm to the keyless boot test.+- [x] **Plugin surface tests.** The expected-backends table in `tests/unit/pipelex/plugins/test_inference_backend_coverage.py`, and a missing-extra guard test mirroring Linkup's.- [x] **Model listing.** `ModelCategory.JUDGMENT` in `pipelex/builder/operations/models_ops.py` with its arms, so `pipelex-agent models` and `check-model` know the family.- [x] **Test infrastructure.** The `judgment` marker and its term in the default deselect expression in `pyproject.toml`; every family table in `preprocess_test_models_cmd.py`; a `[collections.judgment]` and a `judgment_models` key on every profile in `.pipelex-dev/test_profiles.toml`, empty everywhere except a new `[profiles.typesafe]` whose `backends` is `["typesafe"]`; `get_judgment_combos` with its skip, the `judgment_combo` fixture and its re-export; regenerate `_generated_model_sets.py`.-- [ ] **Live tests**, marked `inference` and `judgment`, in `tests/integration/pipelex/cogt/test_judgment.py` and `config_coverage/test_cc_judgment.py`: each question kind on an unambiguous case, several questions in one job, usage tokens present, a versioned model id reported, and an error case (an unknown model handle). Verdicts are asserted exactly and probabilities within ±0.05, per checkpoint 1; the exact instruction strings are pinned, since rewording moved one case from 0.11 to 0.30 while repetition moved it 0.01.-- [ ] **Docs.** `docs/under-the-hood/inference-backend-plugins.md` (the family comment, the "serves all four" sentence, the worker-contract table), the distributed content generation, dry-run and per-node usage pages, a new `docs/contribute/inference-family-surface.md` listing every site a family touches, and its `mkdocs.yml` entry. Regenerate the error pages and the identity snapshot (`make gep`, `make gei`). Changelog entry.-- [ ] `make agent-check`, resolving any drift contract it opens; `make agent-test`; `make ti PROF=typesafe TEST=judgment`; then `make rtm` to put the generated model sets back on the default profile before committing, since the `PROF=` run rewrites that tracked file.+- [x] **Live tests**, marked `inference` and `judgment`, in `tests/integration/pipelex/cogt/test_judgment.py` and `config_coverage/test_cc_judgment.py`: each question kind on an unambiguous case, several questions in one job, usage tokens present, a versioned model id reported, and an error case (an unknown model handle). Verdicts are asserted exactly and probabilities within ±0.05, per checkpoint 1; the exact instruction strings are pinned, since rewording moved one case from 0.11 to 0.30 while repetition moved it 0.01.+- [x] **Docs.** `docs/under-the-hood/inference-backend-plugins.md` (the family comment, the "serves all four" sentence, the worker-contract table), the distributed content generation, dry-run and per-node usage pages, a new `docs/contribute/inference-family-surface.md` listing every site a family touches, and its `mkdocs.yml` entry. Regenerate the error pages and the identity snapshot (`make gep`, `make gei`). Changelog entry.+- [x] `make agent-check`, resolving any drift contract it opens; `make agent-test`; `make ti PROF=typesafe TEST=judgment`; then `make rtm` to put the generated model sets back on the default profile before committing, since the `PROF=` run rewrites that tracked file.### What 2a changed against the design@@ -100,7 +100,7 @@ Two things, both recorded in `design.md` in the same change.**`CostRegistry.compute_cost_report` became a `match` rather than an `if`-chain.** With an explicit extract arm the trailing `isinstance` was provably true, which pyright refuses as `reportUnnecessaryIsInstance`, so the dispatch is a match over the usage classes closed by `case _: assert_never(...)`. The guarantee the design asked for is unchanged and now has a runtime test beside the static one (`test_every_family_gets_its_own_cost_report`).-**The MTHDS protocol has no word for the family, and `PipelexMTHDSProtocol.models()` would have raised on it.** `mthds.protocol.models.ModelCategory` carries `llm`, `extract`, `img_gen` and `search`; the runner builds one `ModelInfo` per preset and types it by calling that enum on our own category key, so the first judgment preset in a deck turns `models()` into a `ValueError` for every caller, not just for judgment. The runner now skips a category the protocol cannot name, leaving the judgment aliases and waterfalls on the string-keyed routing extensions, and [L-260919-afb6c0](http://localhost:4747/i/L-260919-afb6c0) asks `mthds` for the member. Nothing is broken today only because the kit deck ships no judgment preset — **2b's typesafe deck is what makes this live**, so that item is effectively a gate on 2b rather than a nicety.+**The MTHDS protocol has no word for the family, and `PipelexMTHDSProtocol.models()` would have raised on it.** `mthds.protocol.models.ModelCategory` carries `llm`, `extract`, `img_gen` and `search`; the runner builds one `ModelInfo` per preset and types it by calling that enum on our own category key, so the first judgment preset in a deck turns `models()` into a `ValueError` for every caller, not just for judgment. The runner now skips a category the protocol cannot name, leaving the judgment aliases and waterfalls on the string-keyed routing extensions, and L-260919-afb6c0 asks `mthds` for the member. Nothing is broken today only because the kit deck ships no judgment preset. 2b was expected to make it live and did not: it ships an alias and no preset (see checkpoint 2), so the gap stays dormant until a deck gains a judgment preset.**One pre-existing test was loosened, and it is worth knowing why.** `test_parity_with_aggregate_run_total` compared two float sums for bit-for-bit equality; they are the same per-record costs added in different orders, and a fifth record made the last bit diverge. It now compares to within `1e-12`, which is still many orders of magnitude tighter than any real drift between the two cost paths.@@ -119,26 +119,80 @@ Two things, both recorded in `design.md` in the same change.- `make rtm` after any `make ti PROF=…` run. In this repo `tests/integration/pipelex/fixtures/_generated_model_sets.py` is **gitignored**, so the plan's warning about it being a tracked file does not apply here — running `rtm` is still right for local consistency.- ⚠ `make agent-check` runs the keyword-only auto-fixer, and it **silently rewrote four of this phase's signatures** before their grants existed: `get_judgment_setting`, `_warn_if_ambiguous_judgment` and both `JudgmentTokenCostReportField.report_field_for_*` staticmethods. Record the grant with `make sgr FUNC=… RATIONALE=…` *before* running the check, and do not put backticks in a rationale.-**Open questions, none blocking 2b's code.** The design's own list still stands unratified (the standard's native names, how much optional surface to pin, `question` against `prompt`, hosted serving), and phase 3's gate waits on it. What 2a added to that list is the consequence recorded above: with no `choice_default`, `PipeJudge` cannot default a model, so "hosted serving" is now a question with a user-visible cost attached rather than a purely internal one.+**Open questions, none blocking 2b's code.** The design's own list stood unratified while 2a was written (the standard's native names, how much optional surface to pin, `question` against `prompt`, hosted serving), and what 2a added to it was the consequence recorded above: with no `choice_default`, `PipeJudge` cannot default a model, which gave "hosted serving" a user-visible cost rather than a purely internal one. All four were ratified on 2026-09-20, and the answers are the design's `Ratified decisions`; phase 3's gate below carries what they mean for the work.-### Checkpoint 2+### Checkpoint 2 — reached-Record here: what the live tests cover and the command that ran them; any contract change against the design, with the design corrected; the measured cost of a test run. File the follow-up for `pipelex-server/temporal/` (an activity and a queue for the new leaf), which can be written as soon as the leaf exists. Confirm the gate below before starting phase 3.+**Where the work is.** 2b is on `feature/Typesafe-backend` in worktree `_pipelex--typesafe-backend`, stacked on 2a's `feature/Judgment-cogt-family`, which is itself stacked on phase 1's `feature/Judgment-family` (PR #1214). Each pull request targets the branch below it until that one merges. 2a's branch gained one commit after checkpoint 2a, because the full suite had never finished on it and was red: a fake model deck missing the family's fields, and three generated artefacts (the error identity snapshot, the error pages, the inference-backend migration golden) that had not been regenerated. Nine end-to-end failures in the same run were the machine's global deck predating the judgment section, not the code.++**What the live tests cover and how they ran.** `make ti PROF=typesafe TEST=judgment` ran six tests green against the live API: each question kind alone on the unambiguous case, the three kinds in one request (usage recorded, the pinned model on the report), an unknown model id rendered as `JudgmentModelNotFoundError` with its request id, and the config-coverage call. Under the default profile, which lists no judgment model, the same six skip with "No judgment combos in test profile". The wording and the state are the spike's own, pinned, and a yes/no probability is held to ±0.05 of the recorded 0.98.++**What a run costs.** The five requests that reach the model read 1,998 input tokens and wrote 186 output tokens, which at $0.042 per million input tokens and free output is **$0.00008 per run**. Cost is not a reason to keep these tests thin.++**Contract changes against the design**, all recorded in `design.md` Part 5:++- **The managed routing profiles carry an optional route, `"jev-*" = "typesafe"`.** Without it a user holding a TypeSafe key still could not reach the model under the default profile: every handle routes to the gateway by default, and one the gateway does not serve is dropped from the deck without a word. The kit deck carries `@default-judgment` and still no preset.+- **Classification lives in the provider package** and branches on the body's code before handing the rest to the shared classifier, which stays free of vendor names.+- **The worker warns when the API names a model other than the pinned one**, the one way the pin could fail silently.++**Sites no plan named, found on the way**, now all listed in `docs/contribute/inference-family-surface.md`: the CI placeholder list in `pipelex/test_extras/shared_pytest_plugins.py`, whose omission would have failed the boot of every CI shard (now guarded by `tests/unit/pipelex/test_extras/test_ci_placeholder_keys.py`); the SDK in the import-light boot guard's blocked list; and `.env.example`. A pre-existing bug was fixed on the way: `RoutingProfile.get_backend_match_for_model` merged the enabled optional routes into the profile's declared `routes` in place, harmless until now only because each match re-checks enablement, and this is the kit's first real use of optional routes.++**A replay trap for the next backend.** The SDK coerces a rating's string-keyed `probabilities` to integers only when it parses JSON text; validating the decoded dict refuses every rating. The unit tests replay the recorded wire bodies with `model_validate_json` for that reason, and the fixtures they read are copied into `tests/data/typesafe/responses/` so they outlive this campaign directory.++**What waits elsewhere.** The Temporal activity and queue for the leaf are L-260919-9da413, owned by `pipelex-server/temporal`; the protocol's missing `judgment` model category is L-260919-afb6c0 in `mthds`, which a judgment *preset* would make live — the kit ships none.++**Review round 1 (profile 4, bar `open`).** `ledger review-profile` measures a branch only against `origin/dev`, which would have re-read phase 1 in 2a's review and phases 1 and 2a in 2b's, so each layer was reviewed as a commit target: 2a's "Add the judgment inference family at the cogt level" and 2b's "Serve the judgment family from TypeSafe". Reviewers were cubic and the official code-review at medium; one verifier checked the fix group. Eight confirmed findings were fixed, 2a's in the commit "Apply the round 1 review of the judgment family" and 2b's in "Apply the round 1 review of the TypeSafe backend":++- The deck's `judgment` section is defaulted. Required, it failed the boot of every deck installed before `5_judgment_deck.toml` existed — including the checked-in decks of `pipelex-server/worker`, `pipelex-api`, `pipelex-cookbook` and `cocode` — with a remedy pointing at `pipelex init config`.+- The worker's answer guard refuses an option the question does not list and a level beyond its scale, in the verdict and in its distribution's keys.+- A plain-sentence `detail` is a malformed request only on a `400`; a rate limit, an outage or a refused key answered in that shape keeps the status ladder's verdict.+- The TypeSafe extractor reads `retry-after` like every other extractor with headers, and the client factory refuses an empty key as well as an absent one.+- Smaller: the deck-directory docs list the judgment file, a stale generated fixtures file names `make regenerate-test-models` instead of interrupting collection, and the worker contract test imports its data from the root package.++Rejected: the stale `ModelUsageSpec.model_type` comment (2b rewrites it), and an empty `TYPESAFE_API_KEY` reaching the SDK through the kit's `${TYPESAFE_API_KEY}` declaration, since `get_required_env` treats an empty variable as unset. The factory's own empty-key refusal is not dead code: it is the only guard on the paths that do let an empty key through — a literal `api_key = ""` in an override, the `${env:…|secret:…}` fallback form, which returns an empty variable as it is, and a secrets provider other than the environment.++**Deferred from the review, unverified** — each is a reviewer's claim nobody has checked:++- The status-less `TypeSafeError` verdict sits in the shared classifier's `_STATUSLESS_BY_TYPE_NAME` table (`pipelex/cogt/inference/error_classify.py`) rather than in `classify_typesafe_error`, which splits one provider's verdicts across two modules. Worth deciding with the next backend: either vendor exception names belong in that table or none do.+- `_from_typesafe_answer` takes `typesafe_answer: Any` (`pipelex/providers/typesafe/typesafe_translation.py`), where the SDK's answer union would let the checker see its three `isinstance` arms.+- Round 2: `_check_answer_is_offered` (`pipelex/cogt/judgment/judgment_worker_abstract.py`) ends in `case _: pass`, so a fourth question kind with an offered set of its own would pass unchecked. Naming the yes/no pair and raising in the fallback, or matching on the `JudgmentKind` enum so pyright proves exhaustiveness, would make the next kind fail loudly.+- Round 2: the TypeSafe extractor reads `retry-after` but not `retry-after-ms`, which the SDK's own `parse_retry_after` reads first. Only the rendered retry hint and the API's `Retry-After` projection are affected, and TypeSafe's 429 has never been provoked, so its header is unknown.++**`[typesafe]` ships enabled**, like Linkup, decided on 2026-09-19. It was verified to behave identically: a live boot without `TYPESAFE_API_KEY` fails naming `'typesafe'`, and a keyless boot succeeds. `pipelex update` touches only the deck, so upgraders never receive the table; only a fresh `pipelex init` meets it.++**What is left of phase 2, for a session starting cold.** `make agent-check`, the full `make agent-test` and `make ti PROF=typesafe TEST=judgment` passed before review; the live tests skip under the default profile after `make rtm`. What remains:++- Review round 2 (profile 4, bar `defects`) read each branch's review-fix commit and found no code defect; it corrected the empty-key rejection above. The 2b pass of round 1 is recorded on a commit the rebase onto the fixed 2a replaced; round 2's passes name commits both branches carry, which is what the merge gate counts. `ledger review-profile` says whether a further round is owed.+- Open the two pull requests, each targeting the branch below it: 2a with `Advances L-260919-502f36`, 2b with `Closes L-260919-502f36`. Phase 1 (PR #1214) merges first.++**The traps met here**, all worth knowing before touching this branch:++- `make agent-check` runs the keyword-only fixer, which rewrote `TypesafePlugin.register` before its grant existed. Grant first (`make sgr FUNC=… RATIONALE=…`).+- `make gei` and `make gep` must be rerun after any change to an error class; the identity snapshot test fails otherwise.++**Confirm the gate below before starting phase 3.**## Phase 3 — `PipeJudge`Item: L-260919-406599, "Run judgments from a bundle with the PipeJudge operator". Blocked by phase 2 and by L-260919-178ad6, the standard change in `mthds`. Design parts 1, 2, 4 and 7.-**Gate.** Two things must be true first. The design is ratified — the native names, how much optional surface to pin, and `question` against `prompt` are its open questions — and its `status` is `active`. And the standard change has merged in `mthds` and the sibling `mthds/` checkout has been refreshed: `tests/unit/pipelex/core/concepts/test_pinned_natives_vs_standard.py` reads the spec page from that checkout, so the engine's natives cannot go green before the page moves.+**Gate.** The design was ratified on 2026-09-20 and its `status` is `active`, so one half of this gate is met and the other is not: the standard change must have merged in `mthds` and the sibling `mthds/` checkout must have been refreshed, because `tests/unit/pipelex/core/concepts/test_pinned_natives_vs_standard.py` reads the spec page from that checkout and the engine's natives cannot go green before the page moves.++**What ratification settled, and what each decision costs this phase.** The full statements are in the design's `Ratified decisions`; these are the consequences the steps below carry.++- The natives are `Choice` and `Rating`, and `YesNo` gains an optional `probability`.+- Every optional member is pinned on day one: `probability` on `YesNo`; `confidence` and `probabilities` on `Choice`; `confidence`, `probabilities` and `position` on `Rating`. The contents, the renderers, the pinned blueprints, codegen's native expansion and both projection corpora carry the full set.+- The operator's template field is `question`, and `prompt` parses as a synonym of it. Exactly one may be set; both is a validation error naming `question`; `question` is what the blueprint carries and what the builder and the agent CLI emit.+- The family is bring-your-own-key permanently, so no kit default exists to resolve and the operator names its model or says none is configured. The error message and the docs state it as the design rather than as a temporary gap, and no `pipelex-manifold` or `pipelex-remote-config` work belongs to this campaign.- [ ] **Natives in the engine.** `NativeConceptCode` members and every exhaustive match over them, `ChoiceContent` and `RatingContent` with their renderers, the optional `probability` on `YesNoContent` (strict, like `yes_no`), the pinned blueprints and `PINNED_NATIVES_MTHDS_VERSION`, the concept factory, `CoreRegistryModels.STUFF`, the input shaper and the out-of-matrix set as the standard decided, codegen's native expansion, and `docs/building-methods/concepts/native-concepts.md`. Run `make test-ts-gates` if an emitter moved, and `trace-input-semantics` since the structure side changed. If this step alone makes a reviewable diff, land it as its own pull request under the same item.- [ ] **Kernel.** `pipelex/kernel/judgment_ops.py` (`resolve_judgment_setting`, `run_judgment`) and `judgment_results.py`: render the question, build the state from the inputs by name as checkpoint 1 settled it, send a batch of one, apply the threshold, warn when a threshold has no probability to apply to, build the native content, store it. Tests cover state building per content kind and the threshold at and around its boundary. Add the arm to `tests/unit/pipelex/kernel/test_kernel_boot_contract.py` and the row to `docs/under-the-hood/pipelex-kernel.md`, and acknowledge the `pipelex-kernel-docs` drift contract.-- [ ] **Operator.** `pipelex/pipe_operators/judge/`: blueprint with kind resolution and its error messages, pipe, factory with the output agreement (refinements admitted), exceptions, execution data for the trace. Then the registration surface from `docs/contribute/registration-surface.md`: `PipeType.PIPE_JUDGE` and its category arm, `PipeBlueprintUnion`, `registry_models.py`, the output renderer's match. Regenerate the schema (`make gms`).-- [ ] **Builder.** `PipeJudgeSpec`, the spec map and the spec union, the TOML emission branch in `pipe_ops.py` and its twin in the agent CLI's `pipe_cmd.py`, with their tests; `pipelex/builder/CLAUDE.md`, adding the missing `PipeStructure` while there.+- [ ] **Operator.** `pipelex/pipe_operators/judge/`: blueprint with kind resolution, the `question`/`prompt` synonym and its error messages, pipe, factory with the output agreement (refinements admitted), exceptions, execution data for the trace. Then the registration surface from `docs/contribute/registration-surface.md`: `PipeType.PIPE_JUDGE` and its category arm, `PipeBlueprintUnion`, `registry_models.py`, the output renderer's match. Regenerate the schema (`make gms`).+- [ ] **Builder.** `PipeJudgeSpec` carrying `question` alone, the spec map and the spec union, the TOML emission branch in `pipe_ops.py` and its twin in the agent CLI's `pipe_cmd.py`, with their tests; `pipelex/builder/CLAUDE.md`, adding the missing `PipeStructure` while there.- [ ] **Corpus and end to end.** The `[operator.judge]` vocabulary entry and the urgent-message scenario re-cut with `PipeJudge` as a new corpus entry, leaving `native_yes_no_urgent_message` as it is; an e2e bundle under `tests/e2e/pipelex/pipes/pipe_operators/pipe_judge/` covering the question kinds, a threshold, and a `Choice` driving a `PipeCondition`; the error-report parity fixture beside search's in `pipelex/test_extras/error_report_parity.py`; a dry-run test.-- [ ] **Docs.** `docs/building-methods/pipes/pipe-operators/PipeJudge.md` carrying the authoring guidance from the design's part 4, a feature page, the operator round-ups, `mkdocs.yml`. Regenerate the error pages and the identity snapshot. Changelog entry.+- [ ] **Docs.** `docs/building-methods/pipes/pipe-operators/PipeJudge.md` carrying the authoring guidance from the design's part 4, saying that a judgment names its own model and that `prompt` is accepted where `question` is meant, a feature page, the operator round-ups, `mkdocs.yml`. Regenerate the error pages and the identity snapshot. Changelog entry.- [ ] `make agent-check`, `make agent-test`, `make ti PROF=typesafe TEST=judge`, `make rtm`.### Checkpoint 3-Record here: the version `pipelex` shipped the operator in, and the follow-ups filed for what waits on that release — the schema copies (`mthds-schema-sync`), the corpus (`mthds-corpus-sync`), the projection corpus in `mthds-js` and `mthds-python`, a node rendering in `mthds-ui`, the operator lists the authoring skills teach from in `pipelex-plugins` and `mthds-plugins`, and the decision on serving the family from the hosted plane.+Record here: the version `pipelex` shipped the operator in, and the follow-ups filed for what waits on that release — the schema copies (`mthds-schema-sync`), the corpus (`mthds-corpus-sync`), the projection corpus in `mthds-js` and `mthds-python`, a node rendering in `mthds-ui`, and the operator lists the authoring skills teach from in `pipelex-plugins` and `mthds-plugins`. Serving the family from the hosted plane is not among them: ratification decided against it.diff --git a/wip/judgment-family/resume.md b/wip/judgment-family/resume.mdnew file mode 100644index 000000000..faaedbeb8--- /dev/null+++ b/wip/judgment-family/resume.md@@ -0,0 +1,46 @@+---+status: active+item: L-260919-9965d0+---++# Judgment family — what is left, and in what order++Phases 1 and 2 are built and reviewed, and the design was ratified on 2026-09-20, so nothing is waiting on a decision. Three things finish the campaign, and they are ordered: the last branch lands, the standard change merges, then phase 3 is written. `design.md` holds the contracts and the ratified decisions; `plan.md` is the tracker and carries phase 3's checklist; this file is the way back in.++Re-derive where things stand rather than trusting a note: `gh pr list --repo Pipelex/pipelex`, `wt list`, and `ledger show <id>`.++## 1. Land #1216 — `pipelex`++The bottom two pull requests of the stack have landed on `dev`: #1214 (phase 1, the spike, its findings and the campaign documents) as `fbe8dffa9`, and #1215 (phase 2a, the judgment family at the cogt level) as `9d54f072b`. Before #1215 landed, its deck file was renumbered `6_judgment_deck.toml`, so that it no longer shares the `5_` prefix with `5_doc_gen_deck.toml`. One pull request is left, and it now targets `dev`:++| PR | Branch | Worktree | What it carries |+| --- | --- | --- | --- |+| #1216 | `feature/Typesafe-backend` | `_pipelex--typesafe-backend` | Phase 2b: the TypeSafe backend, and the ratification |++Land it with `/ledger-land pipelex#1216 --merge`, which squashes it into `dev`, reaps the worktree and reads the body's ledger lines. If `dev` has moved since the branch last took it in, merge `origin/dev` into the branch first so CI runs against the real `dev`. Where that merge conflicts on a file #1215 also touched, the branch's side is dev's content plus the TypeSafe layer, so keep it and add only what `dev` has gained since.++**Never rebase this branch.** A rebase rewrites its commits, the recorded `/rev` passes stop being ancestors of the head, and the merge gate then refuses the landing. Merging `dev` in, by `git merge origin/dev` or `gh pr update-branch`, is safe.++#1214 closed L-260919-3aeab8 and advanced the epic, #1215 advanced L-260919-502f36, and #1216 closes it. Once #1216 is on `dev`, checkpoint 1's release condition is met — the `typesafe` extra is no longer published against an SDK nothing imports — and the changelog entries under `## [Unreleased]` announce the family and the backend together.++## 2. The standard change — `mthds`++Item L-260919-178ad6, and phase 3 cannot go green before it. In `mthds`, re-pin the native set in `docs/spec/native-concepts.md` at a new standard version, and add `PipeJudge` to the language reference:++- `YesNo` — unchanged required `yes_no`, plus optional `probability`.+- `Choice` — required `choice`; optional `confidence` and `probabilities`.+- `Rating` — required `level`; optional `confidence`, `probabilities` and `position`.++Two questions are this change's own to settle, and the design's position on each is recorded on the item: `Choice` and `Rating` join the out-of-matrix natives, and a light-form `YesNo` stays the bare boolean. `PipeJudge`'s template field is `question`, with `prompt` accepted as a synonym.++It is done when the page has merged **and** the sibling `mthds/` checkout at the workspace root has been refreshed, because `tests/unit/pipelex/core/concepts/test_pinned_natives_vs_standard.py` reads that page live from it.++## 3. Phase 3, the operator — `pipelex`++Item L-260919-406599, blocked by both steps above. `wt add --for L-260919-406599`, `ledger claim` from inside it, and work the phase 3 checklist in `plan.md`, which already carries what ratification costs each step. Its first item, the natives in the engine, is the one that may be worth a pull request of its own.++## Loose ends to pick up on the way++- **Unverified review deferrals**, listed in `plan.md` at checkpoint 2: the wildcard arm in `_check_answer_is_offered`, the unread `retry-after-ms` header, the status-less `TypeSafeError` sitting in the shared classifier's table, and `typesafe_answer: Any` in the translation. Each is a reviewer's claim nobody has checked.+- **Filed elsewhere**: L-260919-9da413, the Temporal activity and queue for the leaf, owned by `pipelex-server`; and L-260919-afb6c0, the protocol's missing `judgment` model category, owned by `mthds`.+- **Leases**: release them when pausing with `ledger wrap-up`, and claim again with `ledger claim <id> --renew` from inside the worktree when picking the work back up.