Skip to content

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/Import-pipelex-api · L-260930-f6bcc7 (#1308)

Louis Choquele90f0f5ad914
diff --git a/.claude/skills/release/SKILL.md b/.claude/skills/release/SKILL.md
index 59c8d67d8..7000bc109 100644
--- a/.claude/skills/release/SKILL.md
+++ b/.claude/skills/release/SKILL.md
@@ -39,6 +39,7 @@ git -C <main> fetch --tags --prune origin && git -C <main> tag --list vX.Y.Z
- **The lock** — `make li` (lock + install) regenerates `uv.lock`. Stop and report if it fails; `uv-lock-check` in CI fails the pull request over a stale lock.
- **Also stamped:**
- **`.badges/tests.json`** — set `"message"` to what `make test-count` prints, leaving every other field alone, then run `make check-test-badge` to confirm the two agree. A mismatch is a CI failure on the pull request.
+ - **`api/docs/openapi/pipelex-api.openapi.yaml`** — `make -C api openapi-export`. The API server in `api/` takes the library's version, and its committed OpenAPI artifact carries it as `info.version`, so the bump moves the artifact and `make agent-check`, whose `api-agent-check` runs `openapi-check`, fails until it is re-exported. The only change it should show is that one line; anything more is a wire change that belongs in the changelog.
- **`.test_durations`** — `make store-test-durations`, the per-test timing map `pytest-split` uses to balance the CI test shards. The refresh is incremental: it collects the suite and measures only the tests missing from the map, so it takes seconds on a quiet release and writes no diff at all when nothing was missing. Read the coverage line it prints before judging how long it should take — past roughly 40% of the suite missing it falls back to re-measuring everything, which takes minutes; treat a long run as a hang only when it reported few tests missing. Include the file in the commit only when it changed. `make store-test-durations-force` is **not** part of the release flow; it is for when recorded values are no longer comparable to each other because the machine or the suite changed shape. The rationale is `docs/contribute/test-duration-map.md`.
- **`pipelex/migration/ledgers/*.toml` and `pipelex/migration/goldens/`** — only when the migration gate below finds an unaccounted schema change, and then written by the `add-migration` skill, never by hand.
@@ -62,7 +63,7 @@ git -C <main> fetch --tags --prune origin && git -C <main> tag --list vX.Y.Z
## The release commit
-`pyproject.toml`, `CHANGELOG.md`, `uv.lock`, `.badges/tests.json`, `.test_durations` when `make store-test-durations` changed it, whatever `make agent-check` rewrote, and the `pipelex/migration/ledgers/*.toml` and `pipelex/migration/goldens/` files the `add-migration` skill wrote when it ran. By name.
+`pyproject.toml`, `CHANGELOG.md`, `uv.lock`, `.badges/tests.json`, `api/docs/openapi/pipelex-api.openapi.yaml`, `.test_durations` when `make store-test-durations` changed it, whatever `make agent-check` rewrote, and the `pipelex/migration/ledgers/*.toml` and `pipelex/migration/goldens/` files the `add-migration` skill wrote when it ran. By name.
## CI on the release pull request
diff --git a/.dockerignore b/.dockerignore
new file mode 100644
index 000000000..229678834
--- /dev/null
+++ b/.dockerignore
@@ -0,0 +1,48 @@
+# The ignore file for `docker build -f api/Dockerfile .`, the API server's image, which is the only image
+# built from this repository. It sits at the root of the context rather than beside the Dockerfile as
+# `api/Dockerfile.dockerignore`, because the legacy builder (`DOCKER_BUILDKIT=0`) reads no other file:
+# without this one it would send the whole repository and copy the untracked overrides below into the
+# image. The context is the whole repository, so this is an allowlist: everything is left out, then
+# only what the Dockerfile reads is let back in.
+*
+
+# The workspace: its lock, and the root project's metadata, which a build of the `pipelex` package
+# reads. The Dockerfile copies the `.gitignore` files too, because hatchling leaves out of a wheel what
+# they ignore, so the wheels are built with the same exclusions as anywhere else.
+!pyproject.toml
+!uv.lock
+!README.md
+!LICENSE
+!.gitignore
+!pipelex/
+
+# The server: its metadata, its package, and the configuration the image ships as /root/.pipelex.
+!api/pyproject.toml
+!api/README.md
+!api/LICENSE
+!api/.gitignore
+!api/pipelex_api/
+!api/.pipelex/
+
+# Never inside those: bytecode and OS droppings.
+**/__pycache__
+**/*.py[cod]
+**/.DS_Store
+
+# Per-developer Pipelex overrides and runtime leftovers. These files are untracked, so CI builds the
+# published image without them — but a local `make docker-build` would otherwise bake one machine's
+# settings into the image: its storage backend, its log level, its telemetry credentials. The image
+# would then behave differently from the published one, and nothing in the diff would say so. An
+# operator supplies overrides to a container by mounting them at /root/.pipelex, the documented path.
+#
+# The runtime layers more than the `_override` tier over a base file: `_local`, `_{environment}`
+# selected by PIPELEX_ENV, and `_temporary_override`, for every configuration family in the
+# directory rather than for `pipelex` alone. Environment names are open-ended, so the exclusion is
+# by shape — any suffixed variant of a base file — and the one tracked variant is named back in.
+# The nested inference overrides need their own line because a pattern's `*` does not cross a `/`.
+api/.pipelex/*_*.toml
+!api/.pipelex/pipelex_service.toml
+api/.pipelex/inference/*_override.toml
+api/.pipelex/storage
+api/.pipelex/traces
+api/.pipelex/**/*.bak.*
diff --git a/.pipelex/plxt.toml b/.pipelex/plxt.toml
index 2b8425c74..f9b91157a 100644
--- a/.pipelex/plxt.toml
+++ b/.pipelex/plxt.toml
@@ -24,6 +24,17 @@ exclude = [
"node_modules/**",
".git/**",
"*.lock",
+ # The `api/` workspace member's own environment and caches, which the patterns above name only at the root.
+ "api/.venv/**",
+ "api/.mypy_cache/**",
+ "api/.ruff_cache/**",
+ "api/.pytest_cache/**",
+ "api/site/**",
+ # Its vendored inference tree, which its own sync keeps byte-identical to the kit, so a reformat here
+ # would read as drift; the kit's copy is formatted and linted where it lives, in `pipelex/kit/`.
+ "api/.pipelex/inference/**",
+ # Its deliberately invalid sample bundles, whose faults are the point of the files.
+ "api/postman/sample-bundles/invalid/**",
# The MTHDS Test Corpus's schema-fault entries, and ONLY those. Every other deliberately invalid
# entry is linted like any other .mthds file in this repo: its fault needs the runtime to notice,
# so the schema has nothing to say about it and a clean lint is the correct outcome. The two below
diff --git a/.worktreeinclude b/.worktreeinclude
index ecaf0b08e..c5fb6283b 100644
--- a/.worktreeinclude
+++ b/.worktreeinclude
@@ -7,3 +7,7 @@
.pipelex/inference/routing_profiles_override.toml
.pipelex/pipelex_service.toml
.pipelex-dev/test_profiles_override.toml
+# The api/ server (a workspace member) keeps its own .env and Pipelex overrides.
+api/.env
+api/.pipelex/pipelex_override.toml
+api/.pipelex/telemetry_override.toml
diff --git a/AGENTS.md b/AGENTS.md
index 656c7ff03..edaf4b3bb 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -9,7 +9,7 @@
```bash
make agent-check
# If the current system doesn't have the `make` command,
- # lookup the "agent-check" target in the Makefile and run the commands one by one (targets fix-unused-imports fix-keyword-only format lint pyright mypy check-ledger check-keyword-only check-hub-layering check-rich-imports drift-check)
+ # lookup the "agent-check" target in the Makefile and run the commands one by one (targets fix-unused-imports fix-keyword-only format lint pyright mypy check-ledger check-keyword-only check-hub-layering check-rich-imports drift-check api-agent-check)
```
This runs multiple code quality tools:
@@ -19,6 +19,7 @@
- plxt: Format and lint TOML, MTHDS, and PLX files
- Migration ledgers: every checked-in ledger must be legal and replay harmlessly over its reference documents (`make check-ledger`, alias `cl`)
- Drift contracts: open code↔docs review obligations fail the gate (note the digest reads the git index, so stage your changes for the check to see them)
+ - The Pipelex API server's own gate (`make -C api agent-check`): the server lives in `api/` as a uv workspace member with its own environment, and its checks include the drift of its OpenAPI artifact and of its vendored inference tree
Always fix any issues reported by these tools before proceeding.
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ea7e8b3b1..5d4e04c06 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,12 +8,19 @@
- **Document engines are models**: the engine that prints a `PipeDocGen` step is a model of a new `doc_gen` family, which a step names with `model = "pipelex-pdf"` or leaves to the default for its format and source in the new deck file `5_doc_gen_deck.toml`, and whose worker a plugin registers with `add_inference_backend(family=InferenceFamily.DOC_GEN, …)`, declaring its model with `add_internal_model` and its deck defaults with `add_doc_gen_default`. A step whose engine is not in the deck, does not print its format from its source, or has no installed worker is refused when the method loads, so a runtime that disables the built-in `reportlab` plugin in `[runtime.plugins] disabled` refuses every `PipeDocGen` step. An engine receives a `RenderJob` of plain data, reads the files its document names through `RenderResources` under the run's read scope, and may check a step's template file at the dry run. `pipelex update` now also refreshes `backends/internal.toml`, backing up a locally edited copy first, so run it to get the deck file and the built-in `reportlab-pdf` engine.
- **The `markdown` template filter**: an HTML template turns Markdown held in a text field into HTML with `{{ order.notes | markdown }}`. Raw HTML in the source is shown as text, and only URLs with a scheme become links.
- **The `Markdown` native concept**: `Markdown` refines `Text` and holds a text written in Markdown, which a `PipeLLM` with `output = "Markdown"` writes as free text and a `Markdown` input takes as a string or as `{"concept": "Markdown", "content": "…"}`; Pipelex defines it ahead of the MTHDS standard. A `Markdown` value is accepted wherever a `Text` is, while a `Text`, or any concept refining `Text`, is refused where a `Markdown` is required. `pipelex run --save-main-stuff` saves it verbatim as `main_stuff.md`, an HTML template prints `{{ report }}` and `$report` as HTML with raw HTML escaped, and `Stuff.as_markdown` and `PipeOutput.main_stuff_as_markdown` read it from Python.
+- **The Pipelex API server ships from this repository**: the FastAPI runner published as the `pipelex/pipelex-api` image now lives in the `api/` directory, as the `pipelex-api` member of a uv workspace, and it runs the `pipelex` of the same commit instead of a pinned release. It is released together with `pipelex`, under the same version, so the image tag that follows `0.33.2` is a `pipelex` version; the image keeps its name, its port and its `/root/.pipelex` configuration mount, and `Pipelex/pipelex-api` keeps the server's earlier history.
### Changed
- **`Markdown` is a reserved native concept code (Breaking)**: a bundle declaring its own concept named `Markdown` is refused with `native_concept_redeclaration`; rename it, or use the native.
- **A string under a concept refining `Text` keeps the concept's class**: a bare string or a `{"concept": …, "content": "…"}` envelope for such a concept now holds the concept's own content class where it held a plain `TextContent`, as the `YesNo`, `Date` and `Time` envelopes already did.
- **`markdown-it-py` replaces `markdown` in the dependencies**: the `markdown` package, which pipelex no longer imported, is dropped, and `markdown-it-py` with its `linkify` extra renders the Markdown of `PipeDocGen`, the `markdown` filter and the `Markdown` concept.
+- **The API server's import package is `pipelex_api` (Breaking)**: the server's package `api` is renamed `pipelex_api`, so an application wrapping the server imports `pipelex_api.main` and serves `pipelex_api.main:app`, and the `logger` field of the server's log records reads `pipelex_api.…`.
+- **The API image is built from the `pipelex` repository**: `docker build -f api/Dockerfile .` at the repository root installs `pipelex` and `pipelex-api` from that commit, with the dependency versions of the repository's lock, which moves some provider SDKs to the versions `pipelex` is tested with. The container starts `uvicorn` from its virtual environment rather than through `uv run`, and carries no `uv`.
+
+### Fixed
+
+- **The API image runs methods by address**: the image carries `git`, which fetching a method named by `method_ref` needs, where the `0.33.2` image removed it with the build tools and failed every such run.
## [v0.70.0] - 2026-09-29
diff --git a/CLAUDE.md b/CLAUDE.md
index 98a993e72..693fac15b 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -4,10 +4,11 @@
`make` targets activate the virtual environment themselves; anything else (`pytest`, `pipelex`, `pipelex-dev`) runs from `.venv/bin/` (`.venv\Scripts\` on Windows), never bare. The Makefile is the reference for every target and alias; without `make`, read the target there and run its prerequisites one by one.
-- **`make agent-check` after every code change, and fix everything it reports.** Its prerequisites are `fix-unused-imports fix-keyword-only format lint pyright mypy check-ledger check-keyword-only check-hub-layering check-rich-imports drift-check`: the import and keyword-only fixers, ruff, pyright, mypy, `plxt` over TOML/MTHDS/PLX, the migration-ledger replay (`cl`), the hub-layering check, the Rich import check (`cri`: Rich is the `cli` extra, so no module outside `pipelex/cli/` imports it at module level or reaches it through a CLI module) and the drift contracts. The drift digest reads the git index, so stage your changes before the check.
+- **`make agent-check` after every code change, and fix everything it reports.** Its prerequisites are `fix-unused-imports fix-keyword-only format lint pyright mypy check-ledger check-keyword-only check-hub-layering check-rich-imports drift-check api-agent-check`: the import and keyword-only fixers, ruff, pyright, mypy, `plxt` over TOML/MTHDS/PLX, the migration-ledger replay (`cl`), the hub-layering check, the Rich import check (`cri`: Rich is the `cli` extra, so no module outside `pipelex/cli/` imports it at module level or reaches it through a CLI module), the drift contracts, and the server's own gate. The drift digest reads the git index, so stage your changes before the check.
+- **The Pipelex API server is the `api/` workspace member** (the `pipelex-api` distribution, package `pipelex_api`; its guide is `api/CLAUDE.md`). It runs the pipelex of the same commit from its own environment, `api/.venv`, which its targets provision themselves. `make agent-check` ends with `api-agent-check` (`make -C api agent-check`: its install, ruff, pyright, mypy, and the drift checks of its OpenAPI artifact and of its vendored inference tree) and `make agent-test` with `api-agent-test`, so a library change that breaks the server, moves its wire or leaves its inference tree behind fails in the same change. A kit change reaches the server's tree through `make up-kit-configs` (`ukc`); a change to the server's wire is committed with `make -C api openapi-export`.
- **Keyword-only arguments** (the convention is in the standards and in `docs/contribute/keyword-only-arguments.md`): `make check-keyword-only` (`cko`) is the gate, `make fix-keyword-only` (`fko`) inserts the bare `*` where it can — on ungranted subjects too — and reports the shapes it cannot fix, and `make subject-grant FUNC="<path>::<qualname>" RATIONALE="…"` (`sgr`) grants a positional subject. Grant before `make agent-check`, which runs the fixer.
- **Drift contracts.** When `make drift-check` reports an open contract: `make drift-plan`, review and fix the stale targets, `git add` the trigger files, then `make drift-ack CONTRACT=<id> RATIONALE="<verdict>: …"`, the rationale opening with its verdict, `real-catch`, `clean-pass` or `friction`. No bypass flag; "clean-pass: reviewed, no doc change needed" is a legitimate rationale. See `docs/contribute/drift-contracts.md` and the `/drift-review` skill.
-- **`make agent-test` at the end of every coding session.** Heartbeat lines while running, full output only on failure. If it hangs or fails opaquely, `make agent-test-debug` (`atd`) adds stale-process cleanup, an outer timeout and a live log; the methodology is `docs/agents/debugging-hanging-pytest-runs.md`. At intermediate steps in a local setup, running only the relevant tests is fine: `.venv/bin/pytest -x -q tests/unit/path/to/test_module.py`, or `make t TEST=<name>` (pytest `-k` substring matching; `TEST=LF` reruns the last failures). `make tp` / `make test-with-prints` are for a human at a terminal; an agent in the cloud or in a sandbox uses `make agent-test` only.
+- **`make agent-test` at the end of every coding session.** Heartbeat lines while running, full output only on failure; the server's unit tests run after the library's. If it hangs or fails opaquely, `make agent-test-debug` (`atd`) adds stale-process cleanup, an outer timeout and a live log; the methodology is `docs/agents/debugging-hanging-pytest-runs.md`. At intermediate steps in a local setup, running only the relevant tests is fine: `.venv/bin/pytest -x -q tests/unit/path/to/test_module.py`, or `make t TEST=<name>` (pytest `-k` substring matching; `TEST=LF` reruns the last failures). `make tp` / `make test-with-prints` are for a human at a terminal; an agent in the cloud or in a sandbox uses `make agent-test` only.
- **`make test-ts-gates` (`ttg`) after touching anything under `pipelex/codegen/emitters/`, or moving the pinned prettier version.** `make agent-test` does not cover the TypeScript emission: the two gates that read the emitted TypeScript as TypeScript need a node toolchain and skip silently without one. This target provisions a pinned prettier and zod into `.ts-toolchain/` (npm, node >= 22.6) and makes those gates fail instead of skip, as CI does. See `docs/contribute/typescript-emission-gates.md`.
- **`make cleanderived`** when linters or pytest collection get confused after files were erased or moved.
- **`CLAUDE.md` and `AGENTS.md` are generated.** Edit the sources in `pipelex/kit/agent_rules/` (assembled per `pipelex/kit/index.toml`) and run `make rules`; `make check-rules` is the CI gate, and `make agent-check` does not include it.
diff --git a/Makefile b/Makefile
index 56d22758c..76bd92879 100644
--- a/Makefile
+++ b/Makefile
@@ -103,7 +103,7 @@ make plxt-lint - Lint MTHDS/TOML/PLX files with plxt
make rules - Install agent rules for contributing to Pipelex
make rules-claude-standalone - Install a standalone CLAUDE.md (full ruleset, for contributors without the Pipelex workspace)
-make up-kit-configs - Update kit configs from .pipelex/
+make up-kit-configs - Update kit configs from .pipelex/, then the api/ server's vendored inference tree from the kit
make ukc - Shorthand -> up-kit-configs
make check-config-sync - Verify .pipelex and pipelex/kit/configs are in sync
make ccs - Shorthand -> check-config-sync
@@ -152,7 +152,9 @@ make codex-tests - Run tests for Codex (exit on first failure) (no
make gha-tests - Run tests for github actions (exit on first failure) (no inference, no gha_disabled)
make test - Run unit tests (no inference)
make test-xdist - Run unit tests with xdist (no inference)
-make agent-test - Run unit tests, silent on success, output on failure (for AI agents)
+make agent-test - Run unit tests, silent on success, output on failure (for AI agents), then the server's (api-agent-test)
+make api-agent-check - The api/ server's own gate: its install, ruff, pyright, mypy, OpenAPI and vendored-kit drift checks
+make api-agent-test - The api/ server's unit tests, in its own environment
make agent-test-debug - Debug variant: cleanup + outer timeout + live log; use when agent-test hangs or fails opaquely
make atd - Shorthand -> agent-test-debug
make ts-toolchain - Install the pinned prettier + zod the TypeScript emission gates need
@@ -232,7 +234,7 @@ export HELP
test-llm tl test-img-gen tg test-extract te codex-tests gha-tests \
store-test-durations std store-test-durations-force stdf \
run-all-tests run-manual-trigger-gha-tests run-gha_disabled-tests \
- validate v check c cc agent-check agent-test agent-test-debug atd \
+ validate v check c cc agent-check agent-test agent-test-debug atd api-agent-check api-agent-test \
test-durations td test-durations-serial tds test-time tt test-time-serial tts \
merge-check-ruff-lint merge-check-ruff-format merge-check-mypy merge-check-pyright merge-check-plxt-format merge-check-plxt-lint \
li check-unused-imports fix-unused-imports check-TODOs check-uv \
@@ -351,9 +353,15 @@ cu: env
# Kit configs are mirrored from .pipelex/ by the pipelex-dev CLI, which derives its
# exclude list from the single source of truth in pipelex/kit/paths.py — the same sets
# `make check-config-sync` enforces, so a sync is always followed by a passing check.
+# The api/ server serves the models of its own vendored copy of the kit's inference tree,
+# so the same step carries a kit change there too, keeping the server's own choices (its
+# backend switches, its x_custom deck files); `make -C api kit-check`, part of the gate,
+# fails a change that skipped it. The script only imports pipelex, so the root venv runs it.
up-kit-configs: env
$(call PRINT_TITLE,"Updating kit configs from .pipelex/")
$(VENV_PIPELEX_DEV) sync-kit-configs
+ $(call PRINT_TITLE,"Re-syncing the vendored inference tree of the api/ server from the kit")
+ $(VENV_PYTHON) api/scripts/sync_vendored_kit.py api/.pipelex
ukc: up-kit-configs
@echo "> done: ukc = up-kit-configs"
@@ -899,6 +907,18 @@ agent-test: env
rm -f "$$tmpfile"; \
if [ $$exit_code -eq 0 ]; then echo "• All tests passed."; fi; \
exit $$exit_code
+ @$(MAKE) --no-print-directory api-agent-test
+
+# The Pipelex API server is the `api/` workspace member (see api/CLAUDE.md). It keeps its own
+# environment (`api/.venv`, provisioned by its own `install` on the first run) and its own gates, which
+# the root `agent-check` and `agent-test` run after pipelex's: the server runs the library of the same
+# commit, so a library change that breaks the server, moves its OpenAPI artifact or leaves its vendored
+# inference tree behind fails here, in the same change.
+api-agent-check:
+ @$(MAKE) --no-print-directory -C api agent-check
+
+api-agent-test:
+ @$(MAKE) --no-print-directory -C api agent-test
# Debug variant of agent-test for when the suite hangs or fails opaquely.
# Use this instead of agent-test when:
@@ -1285,7 +1305,7 @@ up: generate-mthds-schema-quiet generate-corpus-vocabulary-quiet update-gateway-
check: cleanderived regenerate-test-models-quiet generate-mthds-schema-quiet update-gateway-models-quiet check-unused-imports check-config-sync check-rules check-urls check-gateway-models check-mthds-schema check-ledger check-migration-schemas check-keyword-only check-hub-layering check-rich-imports drift-check format lint pyright mypy pylint
@echo "> done: check"
-agent-check: fix-unused-imports fix-keyword-only format lint pyright mypy check-ledger check-keyword-only check-hub-layering check-rich-imports drift-check
+agent-check: fix-unused-imports fix-keyword-only format lint pyright mypy check-ledger check-keyword-only check-hub-layering check-rich-imports drift-check api-agent-check
@echo "> done: agent-check"
v: validate
diff --git a/README.md b/README.md
index cdca0f0ed..e4b9be237 100644
--- a/README.md
+++ b/README.md
@@ -193,7 +193,7 @@ The same `.mthds` file runs from multiple execution targets:
| **CLI** | `pipelex run bundle method.mthds --inputs inputs.json` |
| **Python** | `PipelexMTHDSProtocol().execute(...)` |
| **TypeScript / Node** | [`@pipelex/sdk`](https://www.npmjs.com/package/@pipelex/sdk) against the hosted API, or [`mthds`](https://www.npmjs.com/package/mthds) against any MTHDS API |
-| **REST API** | Self-host [`pipelex-api`](https://github.com/Pipelex/pipelex-api); the hosted API is the one in the Quick start above |
+| **REST API** | Self-host the [`pipelex/pipelex-api`](https://hub.docker.com/r/pipelex/pipelex-api) image, built from this repository's [`api/`](https://github.com/Pipelex/pipelex/tree/main/api) directory; the hosted API is the one in the Quick start above |
| **MCP** | The [Pipelex MCP](https://github.com/Pipelex/pipelex-mcp): your chatbot runs the methods saved in your account |
| **n8n** | [`n8n-nodes-pipelex`](https://github.com/Pipelex/n8n-nodes-pipelex) for workflow automation |
diff --git a/api/.claude/commands/update-postman.md b/api/.claude/commands/update-postman.md
new file mode 100644
index 000000000..94b9c9037
--- /dev/null
+++ b/api/.claude/commands/update-postman.md
@@ -0,0 +1,309 @@
+# Update Postman Collection
+
+You update the **Pipelex FastAPI** collection directly in the user's Postman desktop app via the Postman API. You take an incremental, diff-based approach: read what's already in Postman, compare against the current API state, and only change what's needed.
+
+**You do NOT write JSON files to the repo.** You push changes directly to Postman using `https://api.getpostman.com`.
+
+## Constants
+
+- **Collection UID**: `35082494-559c5753-885c-409a-af63-7647fe28d301`
+- **Collection name**: `Pipelex FastAPI`
+- **Postman API base**: `https://api.getpostman.com`
+- **Local API**: `http://127.0.0.1:8081`
+- **Auth token for local testing**: `test-api-key`
+
+## Prerequisites
+
+You need the `POSTMAN_API_KEY` environment variable. **Always** run `source ~/.zshrc 2>/dev/null` before any command that uses it.
+
+If `POSTMAN_API_KEY` is not set after sourcing, tell the user:
+> I need your Postman API key. Generate one in Postman: **Settings > API keys > Generate API Key**. Then add to `~/.zshrc`:
+> ```
+> export POSTMAN_API_KEY="your-key-here"
+> ```
+
+## Steps
+
+### 1. Fetch the current collection from Postman
+
+```bash
+source ~/.zshrc 2>/dev/null
+curl -s -H "X-API-Key: $POSTMAN_API_KEY" \
+ "https://api.getpostman.com/collections/35082494-559c5753-885c-409a-af63-7647fe28d301" \
+ > /tmp/postman_current.json
+```
+
+Parse and inventory the current state using Python — list every folder, request name, URL path, and method. This is your **baseline**.
+
+```bash
+python3 -c "
+import json
+with open('/tmp/postman_current.json') as f:
+ data = json.load(f)
+col = data['collection']
+
+def inventory(items, prefix=''):
+ for item in items:
+ if 'item' in item:
+ print(f\"{prefix}[folder] {item['name']} ({len(item['item'])} items)\")
+ inventory(item['item'], prefix + ' ')
+ elif 'request' in item:
+ r = item['request']
+ method = r.get('method', '?')
+ print(f\"{prefix}{method} {item['name']}\")
+
+inventory(col['item'])
+"
+```
+
+If the collection does not exist (404), the baseline is empty — you'll create it from scratch with `POST /collections` at the end.
+
+### 2. Discover what changed in the code
+
+Run `git diff origin/dev...HEAD --name-only -- api/` to see which of the server's files changed on the current branch. The server lives in the `api/` directory of the pipelex repository, and git prints paths from the repository root, so every path below starts with `api/`.
+If $ARGUMENTS contains a PR number, use `gh pr diff <number> --name-only` instead.
+
+Categorize the changed files:
+- **Route files** (`api/pipelex_api/routes/**/*.py`, `api/pipelex_api/main.py`) → endpoints may have been added, removed, or modified
+- **Schema files** (`api/pipelex_api/schemas/models.py`) → request/response shapes may have changed
+- **Security** (`api/pipelex_api/security.py`) → auth behavior may have changed
+- **Other files** → likely no Postman impact
+
+If NO route/schema/security files changed, tell the user "No API changes detected — Postman collection is already up to date" and stop.
+
+### 3. Read the changed route files
+
+Only read the route files that actually changed (from step 2). Also read:
+- `api/pipelex_api/routes/__init__.py` and any `__init__.py` in the hierarchy — to check if routers were added/removed
+- `api/pipelex_api/main.py` — to check if prefix structure changed
+
+Glob `api/pipelex_api/routes/**/*.py` to detect any **new** route files not yet in Postman.
+
+### 4. Determine what needs to change
+
+Compare the Postman baseline (step 1) against the code (step 3):
+
+- **New endpoints** — route exists in code but no matching request in Postman
+- **Removed endpoints** — request exists in Postman but route was deleted from code
+- **Modified endpoints** — route file changed; check if method, path, request body schema, query params, or response shape differ
+- **Unchanged endpoints** — leave these exactly as they are (preserve user edits!)
+
+Produce a clear **change plan** and show it to the user before proceeding:
+```
+Changes to apply:
+ + ADD: POST /v1/new-endpoint (folder: Build)
+ ~ UPDATE: POST /v1/build/pipe-spec — request body changed (added "model" field)
+ - REMOVE: POST /v1/build/pipe — endpoint deleted
+ = UNCHANGED: 28 requests
+```
+
+### 5. Fetch the OpenAPI spec for changed endpoints
+
+Only needed for endpoints that are new or modified.
+
+Check if the API is running: `curl -s http://127.0.0.1:8081/health`
+If not running, start it: `make -C api run` (runs in background) and wait a few seconds.
+
+Fetch `http://127.0.0.1:8081/openapi.json` to get the ground truth:
+- Exact parameter names and types
+- Enum values (e.g., format uses lowercase `schema`, `json`, `python` — NOT uppercase)
+- Required vs optional fields
+- Response shapes
+
+### 6. Test changed endpoints against the running API
+
+Only test endpoints that are **new or modified**. For each, curl with:
+- A happy-path request → capture the real response shape
+- An error request → capture the error format
+
+Always use `-H "Authorization: Bearer test-api-key"` for authenticated endpoints.
+
+### 7. Build examples for new/modified endpoints
+
+For **new endpoints**, create rich examples following the rules below.
+For **modified endpoints**, update existing examples to match the new schema while preserving intent.
+For **unchanged endpoints**, do NOT touch them.
+
+#### Example rules:
+- Each endpoint must have at least one **happy path** and one **error** example
+- Use realistic, meaningful data — never "test", "foo", "bar"
+- All examples must be **self-contained** and **copy-pasteable**
+- Response bodies must match **actual API responses** (from step 6)
+- Read `api/postman/sample-bundles/` for `.mthds` files and their `.inputs.json` companions
+
+#### Pipe type diversity — for endpoints accepting `mthds_contents`:
+1. **PipeLLM** — text analysis, summarization, Q&A
+2. **PipeExtract** — structured data extraction
+3. **PipeSequence** — multi-step pipeline
+4. **PipeCompose** — combining concepts
+5. **PipeCondition** — branching on a field value
+6. **PipeParallel** — concurrent pipe execution
+7. **PipeBatch** — iterating over a list
+
+#### Endpoint-specific minimums:
+
+| Endpoint | Required examples |
+|---|---|
+| Pipeline Execute/Start | 1 per pipe type, 1 pipe_code only, 1 error |
+| Validate | 1 valid, 1 missing main_pipe error |
+| Build Inputs | 1 happy path, 1 pipe not found error |
+| Build Output | 1 per format (`schema`, `json`, `python`) |
+| Build Runner | 1 happy path, 1 error |
+| Build Concept | structured fields, refines, concept_ref, 1 error |
+| Build Pipe Spec | 1 per pipe type, 1 invalid type error |
+| Models | no filter, filter by `llm`, filter by `extract`, multi-type |
+| Presigned Post URLs | single file, multiple files |
+| Version | version (protocol handshake) |
+
+### 8. Apply changes to the collection using Python
+
+Use a Python script to modify the collection JSON in `/tmp/postman_current.json`. This is the proven pattern:
+
+```bash
+python3 << 'PYEOF'
+import json
+
+with open('/tmp/postman_current.json') as f:
+ data = json.load(f)
+
+col = data['collection']
+
+# Navigate to the right folder
+# Example: find Agent > Build Pipe Spec
+for folder in col['item']:
+ if folder['name'] == 'Agent':
+ for sub in folder['item']:
+ if sub['name'] == 'Build Pipe Spec':
+ target = sub
+ break
+
+# Build the new request item
+new_item = {
+ "name": "PipeCondition — route by match score",
+ "request": {
+ "method": "POST",
+ "header": [{"key": "Content-Type", "value": "application/json"}],
+ "body": {
+ "mode": "raw",
+ "raw": json.dumps({...}, indent="\t")
+ },
+ "url": {
+ "raw": "{{base_url}}/v1/build/pipe-spec",
+ "host": ["{{base_url}}"],
+ "path": ["v1", "build", "pipe-spec"]
+ },
+ "description": "..."
+ },
+ "response": [
+ {
+ "name": "200 OK",
+ "originalRequest": {"method": "POST", "url": {"raw": "{{base_url}}/v1/build/pipe-spec", "host": ["{{base_url}}"], "path": ["v1", "build", "pipe-spec"]}},
+ "status": "OK",
+ "code": 200,
+ "body": json.dumps({...})
+ }
+ ]
+}
+
+# Insert before the error example (usually last)
+error_idx = len(target['item']) - 1
+target['item'].insert(error_idx, new_item)
+
+# For removals: target['item'] = [i for i in target['item'] if i['name'] != 'Old Item']
+# For updates: find the item by name and replace its request/response
+
+with open('/tmp/postman_updated.json', 'w') as f:
+ json.dump(data, f)
+
+print("Ready to push")
+PYEOF
+```
+
+Key patterns:
+- **Add**: `folder['item'].insert(position, new_item)` — insert before the error example
+- **Remove**: filter out by name
+- **Update**: find by name, replace `request` and/or `response` keys
+- **New folder**: `{"name": "New Folder", "item": [...]}`
+- Always use `json.dumps(body, indent="\t")` for request body `raw` field
+
+#### Collection structure rules:
+- Auth: Bearer with `{{auth_token}}`
+- Variables: `base_url`, `auth_token`
+- All URL paths use `{{base_url}}` prefix
+- `{ "type": "noauth" }` for health/root endpoints only
+
+#### Folder organization:
+- `Health & Info` → `Root`, `Health Check`
+- `Version` → version (protocol handshake)
+- `Pipeline` → `Execute (sync)`, `Start (async)`
+- `Validate` → with valid/invalid sub-examples
+- `Build` → `Build Inputs`, `Build Output`, `Build Runner`
+- `Agent` → `Build Concept`, `Build Pipe Spec`, `Models`
+- `Uploader` → `Presigned Post URLs`
+
+### 9. Push to Postman
+
+```bash
+source ~/.zshrc 2>/dev/null
+curl -s -X PUT \
+ -H "X-API-Key: $POSTMAN_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d @/tmp/postman_updated.json \
+ "https://api.getpostman.com/collections/35082494-559c5753-885c-409a-af63-7647fe28d301" \
+ | python3 -m json.tool
+```
+
+If creating a new collection (no existing UID), use `POST /collections` instead of PUT.
+
+**Clean up:**
+```bash
+rm -f /tmp/postman_current.json /tmp/postman_updated.json
+```
+
+### 10. Verify
+
+```bash
+source ~/.zshrc 2>/dev/null
+curl -s -H "X-API-Key: $POSTMAN_API_KEY" \
+ "https://api.getpostman.com/collections/35082494-559c5753-885c-409a-af63-7647fe28d301" \
+ | python3 -c "
+import json, sys
+data = json.load(sys.stdin)
+col = data['collection']
+
+def count(items):
+ folders = requests = 0
+ for item in items:
+ if 'item' in item:
+ folders += 1
+ f, r = count(item['item'])
+ folders += f
+ requests += r
+ elif 'request' in item:
+ requests += 1
+ return folders, requests
+
+f, r = count(col['item'])
+print(f\"Collection '{col['info']['name']}' synced: {f} folders, {r} requests\")
+"
+```
+
+Report a summary:
+```
+Postman collection updated:
+ + Added: 1 request (PipeCondition — route by match score)
+ = Unchanged: 34 requests
+ Total: 35 requests across 19 folders
+```
+
+Changes appear in Postman desktop immediately (auto-sync).
+
+## Important constraints
+
+- **Do NOT write JSON files to the repo** — only use `/tmp/` for the API push, then clean up
+- **Preserve user edits** — never overwrite unchanged endpoints
+- **Show the change plan before pushing** — never push silently
+- **Always `source ~/.zshrc 2>/dev/null`** before any command using `$POSTMAN_API_KEY`
+- The Postman API expects `{"collection": {...}}` envelope — the fetched JSON already has this structure, so just modify `data['collection']` and write `data` back
+- Enum values are lowercase: `schema`, `json`, `python` — NOT uppercase
+- `mthds_contents` is always `list[str]`, even for a single file
diff --git a/api/.claude/settings.json b/api/.claude/settings.json
new file mode 100644
index 000000000..5f21195b4
--- /dev/null
+++ b/api/.claude/settings.json
@@ -0,0 +1,20 @@
+{
+ "permissions": {
+ "allow": [
+ "Bash(make:*)",
+ "Bash(python3:*)",
+ "Bash(source ~/.zshrc:*)",
+ "Bash(git diff:*)",
+ "Bash(git log:*)",
+ "Bash(git status:*)",
+ "Bash(gh pr view:*)",
+ "Bash(gh pr diff:*)",
+ "Bash(curl -s http://127.0.0.1:8081/*)",
+ "Bash(curl -s -X POST http://127.0.0.1:8081/*)",
+ "Bash(curl -s -H *api.getpostman.com/*)",
+ "Bash(curl -s -X PUT *api.getpostman.com/*)",
+ "Bash(curl -s -X POST *api.getpostman.com/*)",
+ "Bash(rm -f /tmp/postman_*)"
+ ]
+ }
+}
diff --git a/api/.claude/skills/postman-bundle/SKILL.md b/api/.claude/skills/postman-bundle/SKILL.md
new file mode 100644
index 000000000..174fdcc6a
--- /dev/null
+++ b/api/.claude/skills/postman-bundle/SKILL.md
@@ -0,0 +1,230 @@
+---
+name: postman-bundle
+description: >-
+ Turn a Pipelex MTHDS bundle into an API request against any bundle-shaped pipelex-api route — push it
+ as a ready-to-run query into the live "Pipelex FastAPI" Postman collection, emit a curl command,
+ execute it directly, or just preview the body. Covers the whole bundle surface: run (/v1/execute,
+ /v1/start), dry-run validate (/v1/validate — no inference, no cost), crate resolution (/v1/resolve),
+ typed codegen (/v1/codegen — ts-zod, python-pydantic, python-structures), and the per-pipe build
+ projections (/v1/build/inputs, /v1/build/output, /v1/build/runner). Use this whenever the user points
+ at a bundle directory or a .mthds file (often with an inputs.json) and wants to run, validate,
+ resolve, codegen, or otherwise test it via the API — e.g. "make a Postman query for this bundle",
+ "run the fashion_moodboard bundle against the API", "validate this bundle via the API", "resolve this
+ bundle to a crate", "codegen this bundle", "generate the TypeScript types for this method over the
+ API", "test /v1/resolve on this bundle", "build the inputs template via the API", "give me the curl
+ for this bundle", or just "postman" said alongside a bundle path. It resolves the bundle exactly like
+ `pipelex run bundle <path>` (auto-detects bundle.mthds / the single .mthds, reads main_pipe, loads the
+ sibling inputs.json). Trigger it even when the user does not name the endpoint or the word "skill".
+---
+
+# Postman Bundle
+
+Create runnable API requests for one Pipelex MTHDS bundle and push them into the live **Pipelex FastAPI** collection (or emit curl, or run them directly), so the user can exercise any bundle-shaped endpoint against a Pipelex API server. The query resolves the bundle the same way the CLI's `pipelex run bundle <path>` does.
+
+This is a focused, one-bundle-at-a-time tool. It is **not** the full collection sync — for diffing the whole API surface against the code, that's the separate `/update-postman` command.
+
+## Endpoint cheat sheet
+
+| `--endpoint` | Route | Body envelope | Needs a pipe? | Needs `inputs`? | Inference? |
+|---|---|---|---|---|---|
+| `execute` | `POST /v1/execute` | run (`pipe_code`) | yes | yes | **YES — costs money** |
+| `start` | `POST /v1/start` | run + `callback_urls` | yes | yes | **YES — costs money** |
+| `validate` | `POST /v1/validate` | `mthds_contents` | no | no | no (free dry-run) |
+| `resolve` | `POST /v1/resolve` | `files[]` crate | no | no | no (free) |
+| `codegen` | `POST /v1/codegen` | `files[]` crate + `kind`/`target` | no | no | no (free) |
+| `build-inputs` | `POST /v1/build/inputs` | `files[]` + `pipe_ref` + `format`/`explicit` | optional | no | no (free) |
+| `build-output` | `POST /v1/build/output` | `files[]` + `pipe_ref` + `format` | optional | no | no (free) |
+| `build-runner` | `POST /v1/build/runner` | `files[]` + `pipe_ref` + `allow_signatures` | optional | no | no (free) |
+
+Every non-run endpoint answers with the **`/validate` verdict discipline**: a produced verdict is always a `200` discriminated on `is_valid` — the artifact on the valid arm, structured `validation_errors[]` on the invalid arm. Non-2xx is reserved for no-verdict conditions (request-shape `422`, auth `401`/`403`, server `5xx`), rendered as RFC 7807 `problem+json`.
+
+## What it produces in Postman
+
+For the bundle the user names, it upserts requests into the collection under:
+
+```
+Bundles/
+ <bundle>/ (named by the bundle's `domain`, or the filename)
+ Execute (sync) Start (async) Validate (dry-run)
+ Resolve (crate) Codegen (types → <target>)
+ Build Inputs Build Output (<format>) Build Runner
+```
+
+Which requests appear depends on `--endpoint`: the default `both` is `execute` + `start`; every other endpoint is pushed alone. Pushes **merge by request name** — pushing `--endpoint codegen` doesn't wipe an Execute/Start pair pushed earlier, and two codegen targets (distinct names) coexist. Requests use the collection variable `{{base_url}}` and inherit the collection's `{{auth_token}}` bearer auth (and the **Start** request's `callback_urls` is the `{{callback_url}}` variable), so the same query works against a local or hosted server by switching the Postman environment.
+
+(The top folder used to be `Run Bundle/` — if a stale folder by that name lingers in the collection, it can be deleted.)
+
+## The two request envelopes
+
+**Run + validate routes** carry the bundle as parallel lists — `mthds_contents` (full text of each `.mthds` file, main one first) plus, on `/validate`, `mthds_sources` (one filename per content, so `validation_errors[].source` names the owning file):
+
+```json
+{
+ "pipe_code": "<the bundle's main_pipe>",
+ "mthds_contents": ["<file text>", "..."],
+ "inputs": { "...": "inputs.json copied verbatim" },
+ "allow_signatures": false
+}
+```
+
+(`pipe_code` and `inputs` ride execute/start only; `allow_signatures` rides validate.)
+
+**Crate + build routes** (`resolve`, `codegen`, `build-*`) pair each content with its source in one `files[]` entry — the envelope the codegen spec pins. No `inputs`; the closure is the whole request. The build routes add a `pipe_ref` (the **qualified** `domain.pipe_code`; optional on the wire, defaulting to the closure's `main_pipe` — this skill always sends it explicitly):
+
+```json
+{
+ "kind": "types",
+ "target": "ts-zod",
+ "files": [{ "content": "<file text>", "source": "<file name>" }]
+}
+```
+
+(`kind`/`target` are codegen-only; `pipe_ref` is build-only.) The **start** body additionally carries `callback_urls` (see [Callback URLs](#callback-urls-the-async-start-endpoint)). The **validate** body optionally carries `render` (see below).
+
+## Validate = the API's dry-run
+
+`POST /v1/validate` is the API's dry-run: it parses, loads, and dry-runs every pipe with mock inputs and **zero inference** (no LLM calls, no cost), then returns the validated bundle blueprint, a `graph_spec`, and per-pipe input/output JSON-Schema `pipe_io_contracts`. It confirms the whole pipeline wires up without ever running it — the safe, free counterpart to `execute`/`start`. Reach for it to "just check" or "dry-run" a bundle.
+
+- **`main_pipe` is optional for `/validate`.** A bundle with no `main_pipe` still validates (200, `is_valid: true`) — you just get `graph_spec: null`. `--pipe` is ignored.
+- **`allow_signatures`** (`--allow-signatures`) tolerates unimplemented pipe signatures instead of rejecting the bundle (each dry-runs trivially by minting a mock). Useful for in-progress bundles. It parameterizes the **dry-run sweep**, so it rides `validate` and `build-runner` only — the static `build-inputs`/`build-output` projections dropped the sweep and do not accept it. Default strict.
+- **`render`** (`--render markdown`) opts into a server-rendered Markdown view of the verdict, riding the 200 on both arms as `rendered_markdown`. This is what a **skill**-driven validate sends; a **hook** omits it and reads the structured `is_valid`. The structured fields stay the contract; the Markdown is the view.
+
+## Resolve & Codegen (the crate routes)
+
+**`POST /v1/resolve`** resolves the library closure into its **normalized crate** — fully qualified refs, flattened refinement, materialized natives, fingerprint set. It runs no dry-run sweep (runnability is `/validate`'s vocabulary). The valid arm carries the canonical JSON crate — the same bytes `pipelex resolve --format json` prints, so a fingerprint computed from either surface agrees.
+
+**`POST /v1/codegen`** resolves the closure the same way, then projects the crate through two explicit axes: `kind` (only `types` is served — input templates ride `/build/inputs` instead) × `target`:
+
+- `ts-zod` — zod schemas + inferred TypeScript types
+- `python-pydantic` — self-contained pydantic BaseModels
+- `python-structures` — Pipelex runtime `StructuredContent` classes (a Pipelex extension)
+
+The valid arm carries the **stamped** artifact set plus its `codegen.lock`: a client that writes them verbatim reproduces a local `pipelex codegen types` run **byte-for-byte** and passes the offline `pipelex codegen check`. There is deliberately no server-side check route (the drift check is offline by design). An unknown `kind`/`target`, or a `pipe_ref` on the concept-set-wide `types`, is a request-shape `422`.
+
+`--target` is **required** for codegen — there is no default; ask the user which consumer they're generating for if unclear. The request envelope also accepts a `method_ref` instead of `files[]`, but the server answers `501` until server-side method-registry resolution exists — this skill always sends `files[]`.
+
+## Build routes (per-pipe projections)
+
+`POST /v1/build/{inputs,output,runner}` project one artifact for one pipe of the closure, with no inference. They ride the same `files[]` closure selector as the crate routes plus a `pipe_ref` — resolved here from the bundle's `domain` + `main_pipe`, or from `--pipe`.
+
+`build-inputs` and `build-output` are **static**: they resolve the closure and read the pipe's *declared* IO — no dry-run sweep, so a valid verdict from them is not a promise the pipe runs (ask `validate` for that). `build-runner` keeps the sweep, because a runner script *is* that promise.
+
+- **`build-inputs`** → the inputs template for the pipe (what an `inputs.json` should look like). The valid arm carries `inputs` (a parsed object) for the default `format: json`, or `inputs_toml` (raw text) for `format: toml`; `explicit: true` swaps the light values for the ceremonial `{concept, content}` envelopes.
+- **`build-output`** → the pipe's output representation; `--output-format schema|json|python` (default `schema`). `schema`/`json` land in `output` (a parsed object); `python` lands in `output_python` (source text).
+- **`build-runner`** → a Python runner script spelling its imports with the **emitted** class names, plus the `structures` projection it imports from (stamped `structures.py` + `codegen.lock`, to write into a `structures/` directory beside the script) — matching what a local `pipelex build runner` scaffolds. A pipe recorded SKIPPED by the sweep (unresolved cross-package dependency) is a request-shape `422`.
+
+## Callback URLs (the async `start` endpoint)
+
+`/v1/start` is fire-and-forget: it returns a `run_id` immediately and POSTs the finished result to a webhook later, so a `start` request **must** carry `callback_urls`.
+
+**Postman push (default mode) always uses the `{{callback_url}}` collection variable** — never a baked-in URL. The pushed body is `"callback_urls": ["{{callback_url}}"]`, so the callback is switchable in the Postman environment right alongside `base_url` and `auth_token` (local vs hosted). Nothing to resolve — just tell the user to set `callback_url` in their Postman environment (a `https://webhook.site/...` endpoint is the easy way to watch the result land).
+
+**`--run` / `--curl` (a real HTTP call, or a preview of one) need a concrete URL.** Resolution order there:
+
+1. **`--callback-url <url>`** (repeatable — the field is a JSON list; a single URL is the common case).
+2. **`CALLBACK_URL`** in the environment or the repo `.env`. `make` exports `.env`; the script also reads `.env` directly when invoked outside `make`.
+3. **Ask the user.** If neither is set, the script stops with a clear error — ask for a callback URL and re-run with `--callback-url`.
+
+This only affects `start` — no other endpoint takes `callback_urls`. The API's SSRF guard rejects loopback/private/metadata hosts, so a `localhost` callback won't validate — use a public `https://` URL.
+
+## How to run it
+
+Every command on this page runs from `api/`, the server's directory in the pipelex repository: `cd api` first, or prefix the make targets with `-C api` from the repository root (`make -C api bundle-run …`), and give `BUNDLE` and the script's paths relative to `api/`. The make targets are the convenient wrapper (they run the script with the server's venv):
+
+```bash
+make bundle-run BUNDLE=<dir|.mthds> # POST to a running API, print the response
+make bundle-validate BUNDLE=<dir|.mthds> # dry-run validate via /v1/validate (free)
+make bundle-resolve BUNDLE=<dir|.mthds> # resolve to the normalized crate (free)
+make bundle-codegen BUNDLE=<dir|.mthds> TARGET=ts-zod # project typed artifacts + lock (free)
+make bundle-curl BUNDLE=<dir|.mthds> # emit a ready-to-run curl
+make bundle-postman BUNDLE=<dir|.mthds> # push request(s) into the Postman collection
+make bundle-dry BUNDLE=<dir|.mthds> # print the request body only
+# optional: ENDPOINT=execute|start|validate|resolve|codegen|build-inputs|build-output|build-runner|both
+# PIPE=<code> INPUTS=<path> NAME=<folder> ALLOW_SIGNATURES=1 TARGET=<codegen target>
+# OUTPUT_FORMAT=schema|json|python CALLBACK_URL=<url> BASE_URL=<url> TOKEN=<bearer> ARGS=<extra>
+```
+
+`bundle-validate` / `bundle-resolve` / `bundle-codegen` hardcode `--run` with their endpoint (they're free and safe to run live). The build routes ride the generic targets via `ENDPOINT=`, e.g. `make bundle-run ENDPOINT=build-inputs`, `make bundle-postman ENDPOINT=build-runner`, `make bundle-curl ENDPOINT=build-output OUTPUT_FORMAT=json`.
+
+Under the hood it's one script that resolves the bundle once and sends the request to one of four sinks. `<bundle-path>` is a bundle **directory** (preferred) or a single `.mthds` file. Call the script directly for a path outside the repo or finer control:
+
+**Push into the Postman collection** (default). Source the env first so the Postman key is present (it lives in `~/.zshenv`):
+
+```bash
+source ~/.zshenv 2>/dev/null
+python3 .claude/skills/postman-bundle/scripts/build_postman_query.py <bundle-path> [--endpoint <ep>] [--target <t>]
+```
+
+After a successful push, tell the user it's in Postman (it auto-syncs), and that they should set `base_url` and `auth_token` in their Postman environment, then Send.
+
+**Run it yourself from Claude Code** — POSTs the exact same body to a running API and prints the response:
+
+```bash
+python3 .claude/skills/postman-bundle/scripts/build_postman_query.py <bundle-path> --run --endpoint <ep>
+# defaults to http://127.0.0.1:8081 and no auth (AUTH_MODE=none). Override:
+# --base-url https://api.pipelex.com --token <bearer>
+```
+
+The API must be up — start it locally with `make run` first. **Heads-up: only `execute`/`start` trigger real inference (cost + latency)** — confirm the user wants a live run for those. Every other endpoint is free and safe to fire without confirmation:
+
+```bash
+python3 .claude/skills/postman-bundle/scripts/build_postman_query.py <bundle-path> --run --endpoint validate
+python3 .claude/skills/postman-bundle/scripts/build_postman_query.py <bundle-path> --run --endpoint resolve
+python3 .claude/skills/postman-bundle/scripts/build_postman_query.py <bundle-path> --run --endpoint codegen --target python-pydantic
+python3 .claude/skills/postman-bundle/scripts/build_postman_query.py <bundle-path> --run --endpoint build-inputs
+```
+
+**Emit a curl command** (`--curl`) — writes the body to a temp file and prints a `curl --data @file`, so the multi-line contents never need shell escaping. **Preview only** (`--dry-run`) — print the request body, touch nothing.
+
+Useful options (apply across modes):
+
+| Option | When to use |
+|---|---|
+| `--endpoint <ep>` | Pick the endpoint (see cheat sheet). Default `both` (= execute + start) for Postman/curl; `--run both` runs `execute`. |
+| `--target <t>` | (codegen only, **required**) `ts-zod`, `python-pydantic`, or `python-structures`. |
+| `--output-format <f>` | (build-output only) `schema` (default), `json`, or `python`. |
+| `--allow-signatures` | (validate + build routes) Tolerate unimplemented pipe signatures. Default strict. |
+| `--render <fmt>` | (validate only) Opt-in server-side view, e.g. `--render markdown` → response carries `rendered_markdown` (what a skill-driven validate sends). Omit for the lean structured body a hook reads. Repeatable. |
+| `--inputs <path>` | Inputs JSON lives elsewhere, or you point at a `.mthds` file directly (file mode does not auto-detect inputs). execute/start only. |
+| `--pipe <pipe_code>` | The bundle has no `main_pipe`, or you want a different pipe. Used by execute/start (as `pipe_code`) and the build routes (qualified into `pipe_ref`); ignored by validate/resolve/codegen. |
+| `--callback-url <url>` | (start only) Webhook the async result is POSTed to. Repeatable. Falls back to `CALLBACK_URL` in env/`.env`. |
+| `--base-url` / `--token` | Target server + bearer for `--run`/`--curl`. |
+| `--name <folder>` | Override the per-bundle Postman subfolder name. |
+
+### Which endpoint/mode should I use?
+
+- **"Run this bundle"** → `--run` (execute; confirm first — real inference).
+- **"Validate / dry-run / just check it"** (no cost) → `--run --endpoint validate` (or `make bundle-validate`).
+- **"Resolve it / get the crate / test /v1/resolve"** → `--run --endpoint resolve`.
+- **"Generate types / codegen / zod schemas / pydantic models"** → `--run --endpoint codegen --target <t>` — ask which target if the user didn't say.
+- **"What inputs does this pipe need?" via the API** → `--run --endpoint build-inputs`.
+- **"What does the output look like?"** → `--run --endpoint build-output` (`--output-format json` for an example-shaped view).
+- **"Give me a runner script"** → `--run --endpoint build-runner`.
+- **"Put it in Postman so I can click around"** → default mode (push), with the right `--endpoint`.
+- **"Give me the curl"** → `--curl`. **Just checking resolution** → `--dry-run`.
+
+## Resolution rules (mirrors `pipelex run bundle`)
+
+- **Directory** → use `bundle.mthds` if present, else the single `*.mthds` in the dir. Multiple `.mthds` and no `bundle.mthds` is ambiguous → ask the user to pass the file directly. The sibling `inputs.json` is auto-detected. Every `*.mthds` in the directory is sent (main one first), so multi-file bundles resolve.
+- **`.mthds` file** → used as-is; inputs only come from `--inputs`.
+- **`pipe_code`** (run routes) comes from the bundle's `main_pipe` (override with `--pipe`); the build routes send it qualified as `pipe_ref` (`domain.pipe_code`).
+- **`inputs`** is the inputs.json content copied verbatim — exactly what the API receives, same as the CLI.
+
+## Important: file/document inputs are out of scope
+
+We are not doing uploads. If inputs.json references a **local file** (e.g. `"url": "inputs/cv.pdf"`), the script copies it verbatim and prints a warning listing those URLs. Pass that warning on to the user: those entries must be replaced with real `https://` URLs before the request will run. Prefer demoing on a self-contained, text-input bundle.
+
+A related limit: the API receives only the inline bundle text, not the bundle directory. Bundles that depend on Python structure classes in a `structures/` folder (rather than inline `[concept.X.structure]` blocks) won't be fully self-contained over the API — flag that if you see a `structures/` dir doing real work.
+
+## If something's missing
+
+- **No `POSTMAN_API_KEY`** → the script exits asking you to `source ~/.zshenv`. Do that and retry. If still unset, the user needs to add it (Postman → Settings → API keys → Generate).
+- **No `main_pipe` and no `--pipe`** (execute/start/build routes) → the script exits; ask the user which pipe and pass `--pipe`.
+- **`codegen` without `--target`** → the script exits listing the three targets; ask the user which consumer they're generating for.
+- **`start` selected via `--run`/`--curl` and no callback URL** → the script exits. Resolve from `--callback-url`, `CALLBACK_URL` in `.env`, or ask the user (e.g. a `https://webhook.site/...` endpoint). (The Postman push never hits this — it uses the `{{callback_url}}` variable and needs no resolution.)
+- **No `main_pipe`, validating/resolving** → fine, not an error: those endpoints need no pipe; validate just returns `graph_spec: null`. (On the build routes a missing `main_pipe` means `pipe_ref` cannot be defaulted — pass `--pipe`, or the server answers `422`.)
+
+## Constants
+
+- Collection UID: `35082494-559c5753-885c-409a-af63-7647fe28d301` (Pipelex FastAPI). Override with `--collection-uid`.
+- Postman API base: `https://api.getpostman.com` (the script handles GET + PUT).
diff --git a/api/.claude/skills/postman-bundle/scripts/build_postman_query.py b/api/.claude/skills/postman-bundle/scripts/build_postman_query.py
new file mode 100644
index 000000000..c111403f3
--- /dev/null
+++ b/api/.claude/skills/postman-bundle/scripts/build_postman_query.py
@@ -0,0 +1,890 @@
+#!/usr/bin/env python3
+"""Build a runnable Postman request from a Pipelex MTHDS bundle and push it live.
+
+Mirrors ``pipelex run bundle <path>`` resolution: given a bundle directory (or a
+single ``.mthds`` file), it finds the bundle file(s), extracts ``main_pipe``,
+loads the sibling ``inputs.json``, and inserts a ready-to-run request into the
+live "Pipelex FastAPI" Postman collection under ``Bundles/<bundle>/``.
+
+Requests are generated per bundle (configurable via ``--endpoint``):
+``Execute (sync)`` -> ``POST /v1/execute``, ``Start (async)`` ->
+``POST /v1/start``, ``Validate (dry-run)`` -> ``POST /v1/validate``,
+``Resolve (crate)`` -> ``POST /v1/resolve``, ``Codegen (types)`` ->
+``POST /v1/codegen``, and the three bundle build routes ->
+``POST /v1/build/{inputs,output,runner}``. Only execute/start trigger
+inference — every other endpoint parses/loads/dry-runs with zero cost. All use
+the collection's ``{{base_url}}`` and inherit its ``{{auth_token}}`` bearer auth.
+
+The async ``Start (async)`` body additionally carries ``callback_urls`` — the
+webhook(s) the runner POSTs the finished result to. It is resolved from
+``--callback-url``, else ``CALLBACK_URL`` in the environment / ``.env``; a start
+request fails fast (asking for one) if none is found.
+
+File/document inputs are NOT uploaded. Any local (non-http) ``url`` in
+inputs.json is copied verbatim and reported so you can swap in a real URL before
+running. Run this against a self-contained bundle (concepts/structures declared
+inline in the .mthds) — the API only receives the inline mthds_contents, not the
+directory, so sibling Python structure classes are not available.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import os
+import re
+import sys
+import tempfile
+import urllib.error
+import urllib.request
+from pathlib import Path
+from typing import Any, NoReturn, cast
+
+try:
+ import tomllib
+except ModuleNotFoundError: # Python < 3.11 — fall back to regex extraction.
+ tomllib = None # type: ignore[assignment]
+
+DEFAULT_COLLECTION_UID = "35082494-559c5753-885c-409a-af63-7647fe28d301"
+POSTMAN_API_BASE = "https://api.getpostman.com"
+DEFAULT_BUNDLE_FILE_NAME = "bundle.mthds"
+DEFAULT_INPUTS_FILE_NAME = "inputs.json"
+MTHDS_EXTENSION = ".mthds"
+TOP_FOLDER_NAME = "Bundles"
+
+# name -> (request display name, URL path segments, body kind)
+# Body kind selects the request shape:
+# "run" -> {pipe_code, mthds_contents, inputs} for the sync /execute
+# "start" -> the same plus {callback_urls} for the async /start
+# "validate" -> {mthds_contents, allow_signatures [, mthds_sources, render]}
+# "resolve" -> {files: [{content, source}]} — the crate envelope
+# "codegen" -> the crate envelope plus {kind, target}
+# "build_inputs" -> the crate envelope plus {pipe_ref, format, explicit}
+# "build_output" -> the crate envelope plus {pipe_ref, format}
+# "build_runner" -> the crate envelope plus {pipe_ref, allow_signatures}
+# Only "run"/"start" trigger inference; every other kind is a free
+# parse/load/dry-run on the server.
+ENDPOINTS: dict[str, tuple[str, list[str], str]] = {
+ "execute": ("Execute (sync)", ["v1", "execute"], "run"),
+ "start": ("Start (async)", ["v1", "start"], "start"),
+ "validate": ("Validate (dry-run)", ["v1", "validate"], "validate"),
+ "resolve": ("Resolve (crate)", ["v1", "resolve"], "resolve"),
+ "codegen": ("Codegen (types)", ["v1", "codegen"], "codegen"),
+ "build-inputs": ("Build Inputs", ["v1", "build", "inputs"], "build_inputs"),
+ "build-output": ("Build Output", ["v1", "build", "output"], "build_output"),
+ "build-runner": ("Build Runner", ["v1", "build", "runner"], "build_runner"),
+}
+
+# Which endpoints need what. execute/start run a specific pipe with real inputs;
+# the build routes target a specific pipe but take no inputs; validate and the
+# crate routes (resolve/codegen) derive everything from the bundle text.
+PIPE_CODE_ENDPOINTS = {"execute", "start", "build-inputs", "build-output", "build-runner"}
+INPUTS_ENDPOINTS = {"execute", "start"}
+SIGNATURE_ENDPOINTS = {"validate", "build-runner"}
+CRATE_ENDPOINTS = {"resolve", "codegen"}
+
+CODEGEN_TARGETS = ["ts-zod", "python-pydantic", "python-structures"]
+OUTPUT_FORMATS = ["schema", "json", "python"]
+INPUTS_FORMATS = ["json", "toml"]
+
+
+def fail(msg: str) -> NoReturn:
+ print(f"ERROR: {msg}", file=sys.stderr)
+ sys.exit(1)
+
+
+# --- bundle resolution (mirrors `pipelex run bundle`) ---------------------
+
+
+def resolve_bundle(raw_path: str, inputs_override: str | None) -> tuple[Path, list[Path], Path | None]:
+ """Resolve a bundle path into (main_file, all_mthds_files, inputs_path).
+
+ Directory mode auto-detects ``bundle.mthds`` (or the single ``*.mthds``) and
+ a sibling ``inputs.json``, exactly like the CLI. File mode takes the .mthds
+ as-is and only uses ``--inputs`` if given (the CLI does not auto-detect
+ inputs in file mode).
+ """
+ target = Path(raw_path).expanduser()
+
+ if target.is_dir():
+ bundle_file = target / DEFAULT_BUNDLE_FILE_NAME
+ if bundle_file.is_file():
+ main_file = bundle_file
+ else:
+ mthds_files = sorted(target.glob(f"*{MTHDS_EXTENSION}"))
+ if not mthds_files:
+ fail(f"no {MTHDS_EXTENSION} bundle file found in directory '{raw_path}'")
+ if len(mthds_files) > 1:
+ names = ", ".join(path.name for path in mthds_files)
+ fail(
+ f"multiple {MTHDS_EXTENSION} files in '{raw_path}' ({names}) and no "
+ f"{DEFAULT_BUNDLE_FILE_NAME}. Pass the .mthds file directly, or set a "
+ f"{DEFAULT_BUNDLE_FILE_NAME}, or override with --pipe."
+ )
+ main_file = mthds_files[0]
+
+ # Send every .mthds in the directory (main first), mirroring how the CLI
+ # adds the directory as a library dir so sibling bundles resolve.
+ all_mthds = [main_file] + [path for path in sorted(target.glob(f"*{MTHDS_EXTENSION}")) if path != main_file]
+
+ inputs_path: Path | None = None
+ if inputs_override:
+ inputs_path = Path(inputs_override).expanduser()
+ else:
+ candidate = target / DEFAULT_INPUTS_FILE_NAME
+ if candidate.is_file():
+ inputs_path = candidate
+ return main_file, all_mthds, inputs_path
+
+ if target.is_file() and target.suffix == MTHDS_EXTENSION:
+ inputs_path = Path(inputs_override).expanduser() if inputs_override else None
+ return target, [target], inputs_path
+
+ fail(f"'{raw_path}' is not a {MTHDS_EXTENSION} file or directory")
+
+
+def parse_bundle_meta(text: str) -> tuple[str | None, str | None]:
+ """Extract (main_pipe, domain) from a .mthds bundle.
+
+ Uses tomllib when available (the .mthds top level is valid TOML), falling
+ back to a line-anchored regex so a non-standard bundle still yields a guess.
+ """
+ if tomllib is not None:
+ try:
+ data = tomllib.loads(text)
+ main_pipe = data.get("main_pipe")
+ domain = data.get("domain")
+ return (
+ main_pipe if isinstance(main_pipe, str) else None,
+ domain if isinstance(domain, str) else None,
+ )
+ except tomllib.TOMLDecodeError:
+ pass
+ main_match = re.search(r'(?m)^\s*main_pipe\s*=\s*"([^"]+)"', text)
+ domain_match = re.search(r'(?m)^\s*domain\s*=\s*"([^"]+)"', text)
+ return (
+ main_match.group(1) if main_match else None,
+ domain_match.group(1) if domain_match else None,
+ )
+
+
+# --- inputs ----------------------------------------------------------------
+
+
+def load_inputs(path: Path | None) -> tuple[Any, list[str]]:
+ """Load inputs.json verbatim and report any local (non-http) url values."""
+ if path is None:
+ return None, []
+ if not path.is_file():
+ fail(f"inputs file not found: {path}")
+ try:
+ data = json.loads(path.read_text(encoding="utf-8"))
+ except json.JSONDecodeError as exc:
+ fail(f"inputs file '{path}' is not valid JSON: {exc}")
+ return data, collect_local_urls(data)
+
+
+def collect_local_urls(value: Any, acc: list[str] | None = None) -> list[str]:
+ """Walk a JSON value and collect ``url`` strings that are not http(s)."""
+ if acc is None:
+ acc = []
+ if isinstance(value, dict):
+ for key, val in cast("dict[str, Any]", value).items():
+ if key == "url" and isinstance(val, str) and not val.startswith(("http://", "https://")):
+ acc.append(val)
+ else:
+ collect_local_urls(val, acc)
+ elif isinstance(value, list):
+ for item in cast("list[Any]", value):
+ collect_local_urls(item, acc)
+ return acc
+
+
+# --- callback urls (async /start only) --------------------------------------
+
+CALLBACK_URL_ENV_VAR = "CALLBACK_URL"
+
+# In the Postman push, the async-start callback rides a collection/environment
+# variable — switchable alongside {{base_url}} and {{auth_token}} — never a
+# baked-in URL. Only --run/--curl (real HTTP calls) need a resolved URL.
+POSTMAN_CALLBACK_VAR = "{{callback_url}}"
+
+
+def resolve_callback_urls(cli_values: list[str] | None) -> list[str]:
+ """Resolve the async-start callback URL(s): --callback-url, then CALLBACK_URL.
+
+ Order: explicit ``--callback-url`` (repeatable) wins; otherwise fall back to
+ ``CALLBACK_URL`` from the process environment (``make`` exports ``.env``), then
+ from a ``.env`` file found at or above the cwd (covers running the script
+ directly). Returns an empty list when nothing is found — the caller decides
+ whether that is fatal.
+ """
+ if cli_values:
+ return cli_values
+ from_env = os.environ.get(CALLBACK_URL_ENV_VAR)
+ if from_env:
+ return [from_env]
+ from_dotenv = read_dotenv_value(CALLBACK_URL_ENV_VAR)
+ if from_dotenv:
+ return [from_dotenv]
+ return []
+
+
+def read_dotenv_value(key: str) -> str | None:
+ """Read a single ``KEY=VALUE`` from the nearest ``.env`` (cwd upward).
+
+ Minimal parser — enough to pick up ``CALLBACK_URL`` when the script is run
+ directly (without ``make``, which would otherwise export ``.env`` for us).
+ Skips blanks/comments, tolerates an ``export`` prefix, and strips matching
+ surrounding quotes.
+ """
+ cwd = Path.cwd()
+ for directory in [cwd, *cwd.parents]:
+ env_file = directory / ".env"
+ if not env_file.is_file():
+ continue
+ for line in env_file.read_text(encoding="utf-8").splitlines():
+ stripped = line.strip()
+ if not stripped or stripped.startswith("#"):
+ continue
+ if stripped.startswith("export "):
+ stripped = stripped[len("export ") :].lstrip()
+ name, sep, value = stripped.partition("=")
+ if not sep or name.strip() != key:
+ continue
+ value = value.strip()
+ if len(value) >= 2 and value[0] == value[-1] and value[0] in "\"'":
+ value = value[1:-1]
+ return value or None
+ return None
+
+
+# --- Postman request construction -----------------------------------------
+
+
+def build_run_body(
+ pipe_code: str | None,
+ mthds_contents: list[str],
+ inputs: Any,
+ callback_urls: list[str] | None = None,
+) -> str:
+ """Body for /execute and /start: pipe_code + mthds_contents + inputs.
+
+ The async /start adds ``callback_urls`` — the webhook(s) the runner
+ POSTs the finished result to. It is omitted for the sync /execute.
+ """
+ body: dict[str, Any] = {}
+ if pipe_code:
+ body["pipe_code"] = pipe_code
+ body["mthds_contents"] = mthds_contents
+ if inputs is not None:
+ body["inputs"] = inputs
+ if callback_urls:
+ body["callback_urls"] = callback_urls
+ return json.dumps(body, indent=2, ensure_ascii=False)
+
+
+def build_validate_body(
+ mthds_contents: list[str],
+ allow_signatures: bool,
+ *,
+ mthds_sources: list[str] | None = None,
+ render: list[str] | None = None,
+) -> str:
+ """Body for /validate — the skill-faithful wire shape.
+
+ The endpoint takes no ``pipe_code`` and no ``inputs`` — it parses, loads, and
+ dry-runs every pipe with mock inputs and zero inference, so it needs only the
+ bundle text. This mirrors exactly what ``mthds-agent validate bundle <file>``
+ sends through ``--runner api`` (see ``mthds-js`` ``MthdsApiClient.validate``):
+
+ - ``mthds_contents`` — always.
+ - ``allow_signatures`` — always present (real clients send the bool verbatim;
+ ``false`` is the strict default).
+ - ``mthds_sources`` — when provided, parallel to ``mthds_contents``; each entry
+ names the owning file so server-side ``validation_errors[].source`` resolves.
+ - ``render`` — the opt-in Pipelex-API presentation hint (e.g. ``["markdown"]``).
+ A **skill** validates with the default Markdown view, so it sends
+ ``render: ["markdown"]`` and reads the ``rendered_markdown`` the 200 carries; a
+ **hook** validates with ``--format json`` and omits ``render`` (lean structured
+ body). Pass ``--render markdown`` to reproduce the skill flow.
+ """
+ body: dict[str, Any] = {
+ "mthds_contents": mthds_contents,
+ "allow_signatures": allow_signatures,
+ }
+ if mthds_sources:
+ body["mthds_sources"] = mthds_sources
+ if render:
+ body["render"] = render
+ return json.dumps(body, indent=2, ensure_ascii=False)
+
+
+def build_crate_body(
+ mthds_contents: list[str],
+ mthds_sources: list[str],
+ *,
+ codegen_kind: str | None = None,
+ codegen_target: str | None = None,
+) -> str:
+ """Body for /resolve and /codegen — the crate routes' ``files[]`` envelope.
+
+ Unlike validate's parallel ``mthds_contents[]``/``mthds_sources[]`` lists, the
+ crate routes pair each content with its source in one ``{content, source}``
+ entry (the shape the codegen spec pins). No ``pipe_code``, no ``inputs`` —
+ the closure is the whole request. /codegen adds the two projection axes:
+ ``kind`` (only ``types`` is served — input templates ride /build/inputs) and
+ ``target`` (``ts-zod`` | ``python-pydantic`` | ``python-structures``).
+ """
+ body: dict[str, Any] = {}
+ if codegen_kind:
+ body["kind"] = codegen_kind
+ if codegen_target:
+ body["target"] = codegen_target
+ body["files"] = [{"content": content, "source": source} for content, source in zip(mthds_contents, mthds_sources)]
+ return json.dumps(body, indent=2, ensure_ascii=False)
+
+
+def build_build_body(
+ mthds_contents: list[str],
+ mthds_sources: list[str],
+ *,
+ pipe_ref: str | None,
+ allow_signatures: bool | None = None,
+ output_format: str | None = None,
+ inputs_format: str | None = None,
+ explicit: bool | None = None,
+) -> str:
+ """Body for /build/{inputs,output,runner} — the SAME ``files[]`` closure envelope as
+ /resolve and /codegen, plus a pipe selector.
+
+ ``pipe_ref`` is the qualified ``domain.pipe_code`` and is optional on the wire
+ (it defaults to the closure's ``main_pipe``); it is sent explicitly here so the
+ generated query is unambiguous and stays correct if the bundle later declares
+ several main_pipes.
+
+ Each route projects one artifact for that pipe — an inputs template (``format``:
+ json | toml, plus ``explicit``; /build/inputs only), an output representation
+ (``format``: schema | json | python; /build/output only), or a runner script. No
+ ``inputs`` on the wire — nothing runs.
+
+ ``format`` is a per-route axis with a different vocabulary on each, so the two are
+ threaded separately (``inputs_format`` vs ``output_format``) and only ever one is set.
+
+ ``allow_signatures`` is sent only for /build/runner: it parameterizes the dry-run
+ sweep, and the static /build/{inputs,output} projections dropped that sweep.
+ """
+ body: dict[str, Any] = {}
+ if pipe_ref:
+ body["pipe_ref"] = pipe_ref
+ if allow_signatures is not None:
+ body["allow_signatures"] = allow_signatures
+ if output_format:
+ body["format"] = output_format
+ if inputs_format:
+ body["format"] = inputs_format
+ if explicit is not None:
+ body["explicit"] = explicit
+ body["files"] = [{"content": content, "source": source} for content, source in zip(mthds_contents, mthds_sources)]
+ return json.dumps(body, indent=2, ensure_ascii=False)
+
+
+def build_request_item(name: str, path_parts: list[str], body_raw: str, description: str) -> dict[str, Any]:
+ return {
+ "name": name,
+ "request": {
+ "method": "POST",
+ "header": [{"key": "Content-Type", "value": "application/json"}],
+ "body": {"mode": "raw", "raw": body_raw, "options": {"raw": {"language": "json"}}},
+ "url": {
+ "raw": "{{base_url}}/" + "/".join(path_parts),
+ "host": ["{{base_url}}"],
+ "path": path_parts,
+ },
+ "description": description,
+ },
+ "response": [],
+ }
+
+
+# --- Postman collection upsert --------------------------------------------
+
+
+def find_or_create_folder(items: list[dict[str, Any]], name: str) -> dict[str, Any]:
+ for item in items:
+ if item.get("name") == name and "item" in item:
+ return item
+ folder: dict[str, Any] = {"name": name, "item": []}
+ items.append(folder)
+ return folder
+
+
+def upsert_bundle_folder(collection: dict[str, Any], subfolder_name: str, requests: list[dict[str, Any]]) -> str:
+ """Merge requests into the bundle's subfolder, matched by request name.
+
+ A same-name request is replaced (fresh body), anything else in the folder is
+ kept — so pushing `--endpoint codegen` doesn't wipe the Execute/Start pair
+ pushed earlier, and two codegen targets (distinct display names) coexist.
+ """
+ top = find_or_create_folder(collection["item"], TOP_FOLDER_NAME)
+ for item in top["item"]:
+ if item.get("name") == subfolder_name and "item" in item:
+ existing: list[dict[str, Any]] = item["item"]
+ for request in requests:
+ for index, existing_request in enumerate(existing):
+ if existing_request.get("name") == request["name"]:
+ existing[index] = request
+ break
+ else:
+ existing.append(request)
+ return "updated"
+ top["item"].append({"name": subfolder_name, "item": requests})
+ return "created"
+
+
+def postman_request(uid: str, api_key: str, method: str, payload: dict[str, Any] | None) -> dict[str, Any]:
+ data = json.dumps(payload).encode("utf-8") if payload is not None else None
+ headers = {"X-API-Key": api_key}
+ if data is not None:
+ headers["Content-Type"] = "application/json"
+ request = urllib.request.Request(
+ f"{POSTMAN_API_BASE}/collections/{uid}",
+ data=data,
+ headers=headers,
+ method=method,
+ )
+ try:
+ with urllib.request.urlopen(request) as response:
+ return json.loads(response.read())
+ except urllib.error.HTTPError as exc:
+ detail = exc.read().decode(errors="replace")
+ fail(f"Postman {method} failed ({exc.code}): {detail}")
+ except urllib.error.URLError as exc:
+ fail(f"Postman {method} could not reach {POSTMAN_API_BASE}: {exc.reason}")
+
+
+# --- direct run / curl (run the same query from Claude Code) ---------------
+
+DEFAULT_BASE_URL = "http://127.0.0.1:8081"
+
+
+def write_body_file(subfolder_name: str, body_raw: str) -> Path:
+ """Persist the request body so curl can `--data @file` (no shell escaping)."""
+ safe = re.sub(r"[^A-Za-z0-9_.-]", "_", subfolder_name)
+ path = Path(tempfile.gettempdir()) / f"run_bundle_{safe}.json"
+ path.write_text(body_raw, encoding="utf-8")
+ return path
+
+
+def render_curl(base_url: str, token: str | None, path_parts: list[str], body_path: Path) -> str:
+ url = base_url.rstrip("/") + "/" + "/".join(path_parts)
+ lines = [f"curl -sS -X POST '{url}' \\", " -H 'Content-Type: application/json' \\"]
+ if token:
+ lines.append(f" -H 'Authorization: Bearer {token}' \\")
+ lines.append(f" --data @{body_path} | jq .")
+ return "\n".join(lines)
+
+
+def run_pipeline(base_url: str, token: str | None, path_parts: list[str], body_raw: str) -> tuple[int, str]:
+ url = base_url.rstrip("/") + "/" + "/".join(path_parts)
+ headers = {"Content-Type": "application/json"}
+ if token:
+ headers["Authorization"] = f"Bearer {token}"
+ request = urllib.request.Request(url, data=body_raw.encode("utf-8"), headers=headers, method="POST")
+ try:
+ with urllib.request.urlopen(request) as response:
+ return response.status, response.read().decode("utf-8", errors="replace")
+ except urllib.error.HTTPError as exc:
+ # The API renders errors as RFC 7807 problem+json — surface the body as-is.
+ return exc.code, exc.read().decode("utf-8", errors="replace")
+ except urllib.error.URLError as exc:
+ fail(f"could not reach {url}: {exc.reason}. Is the API running? Start it with `make run`.")
+
+
+def pretty_json(text: str) -> str:
+ try:
+ return json.dumps(json.loads(text), indent=2, ensure_ascii=False)
+ except json.JSONDecodeError:
+ return text
+
+
+# --- main ------------------------------------------------------------------
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(
+ description="Resolve a Pipelex MTHDS bundle and either push a Postman query, emit curl, or run it."
+ )
+ parser.add_argument("bundle", help="Path to a bundle directory or a .mthds file")
+ parser.add_argument("--inputs", help="Override inputs JSON path (default: auto-detect inputs.json in a directory)")
+ parser.add_argument("--pipe", help="Override main_pipe (sets pipe_code). Ignored by --endpoint validate.")
+ parser.add_argument(
+ "--callback-url",
+ action="append",
+ metavar="URL",
+ help=(
+ "Webhook URL for the async /start callback (repeatable; only used by the start "
+ "endpoint). Falls back to CALLBACK_URL in the environment / .env. Required whenever start "
+ "is the endpoint being built or run."
+ ),
+ )
+ parser.add_argument(
+ "--allow-signatures",
+ action="store_true",
+ help=(
+ "(validate + build-runner) Tolerate unimplemented pipe signatures instead of rejecting the bundle. "
+ "Parameterizes the dry-run sweep, so the static build-inputs/build-output projections do not take it. "
+ "Default: strict."
+ ),
+ )
+ parser.add_argument(
+ "--target",
+ choices=CODEGEN_TARGETS,
+ help=(
+ "(codegen only) Projection target: ts-zod (zod schemas + inferred types), python-pydantic "
+ "(self-contained BaseModels), or python-structures (Pipelex runtime StructuredContent classes). "
+ "Required when --endpoint codegen."
+ ),
+ )
+ parser.add_argument(
+ "--output-format",
+ choices=OUTPUT_FORMATS,
+ default="schema",
+ help="(build-output only) Output representation format (default: schema). `python` returns source text in `output_python`.",
+ )
+ parser.add_argument(
+ "--inputs-format",
+ choices=INPUTS_FORMATS,
+ default="json",
+ help=(
+ "(build-inputs only) Inputs template encoding (default: json). `json` returns a parsed object in `inputs`; "
+ "`toml` returns raw text in `inputs_toml`, carrying the per-key `# concept:` comments JSON cannot."
+ ),
+ )
+ parser.add_argument(
+ "--explicit",
+ action="store_true",
+ help=(
+ "(build-inputs only) Emit the ceremonial {concept, content} envelope for every input instead of the "
+ "default light shape (a bare string for a Text input, and so on)."
+ ),
+ )
+ parser.add_argument(
+ "--render",
+ action="append",
+ metavar="FORMAT",
+ help=(
+ "(validate only) Opt-in server-side view format to request, e.g. --render markdown. Adds `render` "
+ "to the body so /validate returns a `rendered_markdown` view of the verdict — this is what a "
+ "skill-driven validate (default Markdown) sends. Repeatable. Omit it for the lean structured body "
+ "a hook reads (--format json)."
+ ),
+ )
+ parser.add_argument(
+ "--endpoint",
+ choices=[*ENDPOINTS, "both"],
+ default="both",
+ help=(
+ "Which endpoint(s) to target (default: both = execute + start). Besides the run pair, "
+ "every choice is inference-free: 'validate' dry-runs the bundle, 'resolve' returns the "
+ "normalized library crate, 'codegen' projects the crate into typed artifacts "
+ "(needs --target), and 'build-inputs'/'build-output'/'build-runner' project one "
+ "artifact for the requested pipe. For --run, 'both' runs execute (sync)."
+ ),
+ )
+ parser.add_argument("--name", help="Override the per-bundle subfolder name (default: bundle domain or filename)")
+ parser.add_argument("--collection-uid", default=DEFAULT_COLLECTION_UID, help="Target Postman collection UID")
+ # Output mode (default: push to Postman). At most one of these.
+ parser.add_argument("--dry-run", action="store_true", help="Print the request body; touch nothing")
+ parser.add_argument("--curl", action="store_true", help="Emit a ready-to-run curl command; do not execute")
+ parser.add_argument("--run", action="store_true", help="Execute the request against --base-url and print the response")
+ # Only used by --run / --curl.
+ parser.add_argument("--base-url", default=DEFAULT_BASE_URL, help=f"API base URL for --run/--curl (default: {DEFAULT_BASE_URL})")
+ parser.add_argument("--token", help="Bearer token for --run/--curl (omit when the server runs AUTH_MODE=none)")
+ args = parser.parse_args()
+
+ if sum([args.dry_run, args.curl, args.run]) > 1:
+ fail("choose at most one of --dry-run, --curl, --run.")
+ mode = "run" if args.run else "curl" if args.curl else "dry" if args.dry_run else "postman"
+
+ api_key = os.environ.get("POSTMAN_API_KEY")
+ if mode == "postman" and not api_key:
+ fail("POSTMAN_API_KEY is not set. Run `source ~/.zshenv` (or add the key there), then retry.")
+
+ selected = ["execute", "start"] if args.endpoint == "both" else [args.endpoint]
+ # The single endpoint --run fires: 'both' is not meaningful for one run, so use
+ # execute (sync), which waits for and returns the result.
+ run_key = "execute" if args.endpoint == "both" else selected[0]
+ # In --run mode only run_key actually fires, so build/require only its body.
+ # Every other mode (postman/curl/dry) materializes all selected endpoints.
+ active_keys = [run_key] if mode == "run" else selected
+
+ needs_run = any(ENDPOINTS[key][2] == "run" for key in active_keys)
+ needs_start = any(ENDPOINTS[key][2] == "start" for key in active_keys)
+ needs_validate = any(ENDPOINTS[key][2] == "validate" for key in active_keys)
+ needs_crate = any(key in CRATE_ENDPOINTS for key in active_keys)
+ needs_signatures = any(key in SIGNATURE_ENDPOINTS for key in active_keys)
+ # execute/start need pipe_code + inputs; the build routes need pipe_code only.
+ needs_pipe = any(key in PIPE_CODE_ENDPOINTS for key in active_keys)
+ needs_inputs = any(key in INPUTS_ENDPOINTS for key in active_keys)
+
+ # /codegen requires the projection target up front — fail before any network work.
+ if "codegen" in active_keys and not args.target:
+ fail(f"--endpoint codegen requires --target <{'|'.join(CODEGEN_TARGETS)}>.")
+
+ main_file, all_mthds, inputs_path = resolve_bundle(args.bundle, args.inputs)
+ main_text = main_file.read_text(encoding="utf-8")
+ main_pipe, domain = parse_bundle_meta(main_text)
+
+ # `pipe_code` is required only by the run endpoints — /validate derives
+ # everything it needs from the bundle text and takes no pipe_code.
+ pipe_code = args.pipe or main_pipe
+ if needs_pipe and not pipe_code:
+ fail(
+ f"could not determine main_pipe from '{main_file}'. Declare main_pipe in the bundle, "
+ "or pass --pipe <pipe_code>."
+ )
+
+ # callback_urls belongs to the async /start endpoint only. In the Postman
+ # push it is always the {{callback_url}} collection variable — switchable
+ # alongside base_url/auth_token, never a baked-in URL. For --run/--curl/--dry
+ # (real HTTP calls, or a preview of one) resolve a concrete URL from
+ # --callback-url, then CALLBACK_URL (environment or .env); if none is found,
+ # stop and ask the user for one.
+ callback_urls: list[str] = []
+ if needs_start:
+ if mode == "postman":
+ callback_urls = [POSTMAN_CALLBACK_VAR]
+ else:
+ callback_urls = resolve_callback_urls(args.callback_url)
+ if not callback_urls:
+ fail(
+ "the async /start endpoint requires callback_urls, but none was found. "
+ "Pass --callback-url <https-url>, or set CALLBACK_URL in your .env. If you don't "
+ "have one, ask the user for a callback URL (e.g. a https://webhook.site/... endpoint)."
+ )
+
+ mthds_contents = [path.read_text(encoding="utf-8") for path in all_mthds]
+
+ # inputs (and their local-url warnings) matter only to the run endpoints;
+ # every other endpoint ignores them, so don't load or warn otherwise.
+ inputs: Any = None
+ local_url_warnings: list[str] = []
+ if needs_inputs:
+ inputs, local_url_warnings = load_inputs(inputs_path)
+
+ subfolder_name = args.name or domain or main_file.stem
+
+ # Per-file sources, parallel to mthds_contents. /validate sends them as the
+ # `mthds_sources` list; the crate routes pair them into `files[].source`.
+ # Either way, server-side diagnostics name the owning file. `render` is the
+ # opt-in presentation hint on /validate: a skill validates with the default
+ # Markdown view (`--render markdown`), a hook omits it and reads the
+ # structured body.
+ mthds_sources = [path.name for path in all_mthds]
+ render_formats: list[str] = []
+ for raw_format in cast("list[str]", args.render or []):
+ normalized = raw_format.strip().lower()
+ if normalized and normalized not in render_formats:
+ render_formats.append(normalized)
+
+ # One body per endpoint kind in play (kinds are unique per endpoint, except
+ # execute/start which share the run-request shape via "run"/"start").
+ bodies: dict[str, str] = {}
+ if needs_run:
+ bodies["run"] = build_run_body(pipe_code, mthds_contents, inputs)
+ if needs_start:
+ bodies["start"] = build_run_body(pipe_code, mthds_contents, inputs, callback_urls=callback_urls)
+ if needs_validate:
+ bodies["validate"] = build_validate_body(
+ mthds_contents,
+ args.allow_signatures,
+ mthds_sources=mthds_sources,
+ render=render_formats or None,
+ )
+ if "resolve" in active_keys:
+ bodies["resolve"] = build_crate_body(mthds_contents, mthds_sources)
+ if "codegen" in active_keys:
+ bodies["codegen"] = build_crate_body(mthds_contents, mthds_sources, codegen_kind="types", codegen_target=args.target)
+ # The build routes take the QUALIFIED pipe ref (`domain.pipe_code`).
+ #
+ # Only `main_pipe` is guaranteed to live in the MAIN file's domain, so only it may be qualified
+ # with that domain. A `--pipe` override is passed through verbatim: in a multi-file closure the
+ # user may well be naming a pipe in a sibling domain, and stapling the main file's domain onto it
+ # would silently select the wrong pipe (or 422 on a ref that doesn't exist). A bare `--pipe` still
+ # resolves — the engine's lookup matches a bare code too — and the user can always qualify it.
+ if args.pipe:
+ pipe_ref = args.pipe
+ elif domain and main_pipe:
+ pipe_ref = f"{domain}.{main_pipe}"
+ else:
+ pipe_ref = main_pipe
+ if "build-inputs" in active_keys:
+ bodies["build_inputs"] = build_build_body(
+ mthds_contents,
+ mthds_sources,
+ pipe_ref=pipe_ref,
+ inputs_format=args.inputs_format,
+ explicit=args.explicit or None,
+ )
+ if "build-output" in active_keys:
+ bodies["build_output"] = build_build_body(mthds_contents, mthds_sources, pipe_ref=pipe_ref, output_format=args.output_format)
+ if "build-runner" in active_keys:
+ # Only /build/runner still runs the dry-run sweep that `allow_signatures` parameterizes.
+ bodies["build_runner"] = build_build_body(
+ mthds_contents, mthds_sources, pipe_ref=pipe_ref, allow_signatures=args.allow_signatures
+ )
+
+ print(f"Bundle: {main_file}")
+ print(f"mthds files: {', '.join(path.name for path in all_mthds)}")
+ if needs_pipe:
+ print(f"pipe_code: {pipe_code}")
+ if needs_inputs:
+ print(f"inputs: {inputs_path or 'none'}")
+ if needs_start:
+ print(f"callback: {', '.join(callback_urls)}")
+ if needs_signatures:
+ print(f"signatures: allow_signatures={args.allow_signatures}")
+ if needs_validate:
+ render_note = ", ".join(render_formats) or "none (structured-only, hook-style)"
+ print(f"validate: POST /v1/validate (no inference) — sources: {', '.join(mthds_sources)}")
+ print(f" render: {render_note}")
+ if needs_crate:
+ print(f"crate: files[] envelope — sources: {', '.join(mthds_sources)} (no inference)")
+ if "codegen" in active_keys:
+ print(f"codegen: kind=types target={args.target}")
+ if "build-output" in active_keys:
+ print(f"format: {args.output_format}")
+ if local_url_warnings:
+ warn_target = "the API" if mode in ("run", "curl") else "Postman"
+ print("\nWARNING: inputs reference local (non-http) url(s) — file uploads are out of scope.")
+ print(f"Replace these with real https URLs before running against {warn_target}:")
+ for url in local_url_warnings:
+ print(f" - {url}")
+
+ if mode == "dry":
+ for kind, body in bodies.items():
+ print(f"\n--- request body ({kind}) ---")
+ print(body)
+ return
+
+ if mode == "curl":
+ body_paths = {kind: write_body_file(f"{subfolder_name}-{kind}", body) for kind, body in bodies.items()}
+ for path in body_paths.values():
+ print(f"Body written to {path}")
+ for key in selected:
+ print(f"\n# {ENDPOINTS[key][0]}")
+ print(render_curl(args.base_url, args.token, ENDPOINTS[key][1], body_paths[ENDPOINTS[key][2]]))
+ return
+
+ if mode == "run":
+ # Only run_key (resolved above) actually fires — for 'both' that's execute (sync).
+ name, path_parts, kind = ENDPOINTS[run_key]
+ url = args.base_url.rstrip("/") + "/" + "/".join(path_parts)
+ print(f"\nRunning {name}: POST {url}")
+ status, response_text = run_pipeline(args.base_url, args.token, path_parts, bodies[kind])
+ print(f"HTTP {status}")
+ print(pretty_json(response_text))
+ if status >= 400:
+ sys.exit(1)
+ return
+
+ # mode == "postman"
+ assert api_key is not None # guaranteed above for the postman path
+ trailer = (
+ "Generated by the postman-bundle skill. Set `base_url` and `auth_token` in your "
+ "Postman environment before running."
+ )
+ source_lines = f"- Source: `{main_file}`\n- .mthds files sent: {len(mthds_contents)}\n"
+
+ def describe(key: str) -> str:
+ """Per-endpoint Postman request description (shown in the collection)."""
+ if key in ("execute", "start"):
+ callback_note = (
+ f"- callback_urls (Start only): `{', '.join(callback_urls)}` — set `callback_url` in your Postman environment\n"
+ if needs_start
+ else ""
+ )
+ return (
+ f"Run the `{subfolder_name}` bundle (mirrors `pipelex run bundle`). Triggers REAL inference.\n\n"
+ f"{source_lines}"
+ f"- main_pipe: `{pipe_code}`\n"
+ f"- inputs: {inputs_path or 'none'}\n"
+ f"{callback_note}\n{trailer}"
+ )
+ if key == "validate":
+ render_line = (
+ f"- render: `{render_formats}` → response carries `rendered_markdown` (a skill-driven validate)\n"
+ if render_formats
+ else "- render: none (lean structured body — what a hook reads with --format json)\n"
+ )
+ return (
+ f"Validate (dry-run) the `{subfolder_name}` bundle — parse, load, and dry-run every pipe "
+ "with NO inference (free, no LLM cost).\n\n"
+ f"{source_lines}"
+ f"- mthds_sources: `{mthds_sources}`\n"
+ f"- allow_signatures: {args.allow_signatures}\n"
+ f"{render_line}\n"
+ "Takes no pipe_code and no inputs. 200 discriminated on `is_valid`: the bundle blueprint, "
+ f"graph spec, and per-pipe IO contracts — or structured validation_errors[]. {trailer}"
+ )
+ if key == "resolve":
+ return (
+ f"Resolve the `{subfolder_name}` library closure into its NORMALIZED CRATE — fully qualified "
+ "refs, flattened refinement, materialized natives, fingerprint. NO inference, no dry-run sweep.\n\n"
+ f"{source_lines}\n"
+ "200 discriminated on `is_valid`: the canonical JSON crate on the valid arm, structured "
+ f"validation_errors[] on the invalid arm. {trailer}"
+ )
+ if key == "codegen":
+ return (
+ f"Project the `{subfolder_name}` crate into typed artifacts (kind=types, target={args.target}) "
+ "plus its codegen.lock. NO inference.\n\n"
+ f"{source_lines}\n"
+ "A client that writes the artifacts and lock verbatim reproduces a local `pipelex codegen types` "
+ f"run byte-for-byte, so the offline `pipelex codegen check` passes. {trailer}"
+ )
+ # build-inputs / build-output / build-runner
+ artifact = {
+ "build-inputs": "the inputs JSON template",
+ "build-output": f"the output representation (format={args.output_format})",
+ "build-runner": "a runner script (plus the structures projection it imports)",
+ }[key]
+ if key == "build-runner":
+ return (
+ f"Generate {artifact} for pipe `{pipe_code}` of the `{subfolder_name}` bundle. Validates the "
+ "bundle first (dry-run sweep scoped to the pipe, NO inference).\n\n"
+ f"{source_lines}"
+ f"- allow_signatures: {args.allow_signatures}\n\n"
+ f"200 discriminated on `is_valid`. {trailer}"
+ )
+ return (
+ f"Generate {artifact} for pipe `{pipe_code}` of the `{subfolder_name}` bundle. Static projection: "
+ "resolves the closure and renders the pipe's declared IO — no dry-run sweep, NO inference.\n\n"
+ f"{source_lines}\n"
+ f"200 discriminated on `is_valid`. {trailer}"
+ )
+
+ def display_name(key: str) -> str:
+ if key == "codegen":
+ return f"Codegen (types → {args.target})"
+ if key == "build-output":
+ return f"Build Output ({args.output_format})"
+ return ENDPOINTS[key][0]
+
+ requests = [build_request_item(display_name(key), ENDPOINTS[key][1], bodies[ENDPOINTS[key][2]], describe(key)) for key in selected]
+ print(f"requests: {', '.join(display_name(key) for key in selected)} -> {TOP_FOLDER_NAME}/{subfolder_name}")
+
+ envelope = postman_request(args.collection_uid, api_key, "GET", None)
+ if "collection" not in envelope:
+ fail(f"unexpected Postman GET response: {json.dumps(envelope)[:300]}")
+ action = upsert_bundle_folder(envelope["collection"], subfolder_name, requests)
+ postman_request(args.collection_uid, api_key, "PUT", envelope)
+
+ vars_to_set = "base_url + auth_token" + (" + callback_url" if needs_start else "")
+ print(f"\n{action.upper()} '{TOP_FOLDER_NAME}/{subfolder_name}' in the Pipelex FastAPI collection.")
+ print(f"Open Postman (auto-syncs), set {vars_to_set}, and Send.")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/api/.env.example b/api/.env.example
new file mode 100644
index 000000000..6b19dad2c
--- /dev/null
+++ b/api/.env.example
@@ -0,0 +1,76 @@
+# ──────────────────────────────────────────────────────────────────────────────
+# Required
+# ──────────────────────────────────────────────────────────────────────────────
+
+# Pipelex Gateway API key — used by the API to call LLMs through Pipelex's
+# unified inference layer. Get one at https://app.pipelex.com (free credits
+# included).
+#
+# This is the only credential needed *if* you keep the default routing profile.
+# If you switch the inference backend in your Pipelex config to use OpenAI,
+# Anthropic, Azure, Bedrock, etc. directly, you'll need that backend's own env
+# vars instead. See https://docs.pipelex.com for backend configuration.
+
+PIPELEX_GATEWAY_API_KEY=
+
+# ──────────────────────────────────────────────────────────────────────────────
+# Authentication (optional — defaults to AUTH_MODE=none)
+# ──────────────────────────────────────────────────────────────────────────────
+
+# One of: none | api_key | jwt
+# AUTH_MODE=none
+
+# Used when AUTH_MODE=api_key. Clients pass: Authorization: Bearer <API_KEY>
+# API_KEY=
+
+# Used when AUTH_MODE=jwt. Tokens must be HS256 and contain an "email" claim.
+# JWT_SECRET_KEY=
+
+# When AUTH_MODE=none and the API sits behind a trusted reverse proxy that
+# performs authentication and forwards identity via X-User-Email / X-User-Sub
+# / X-User-Id / X-Auth-Method headers, set this to "true" to honor those
+# headers. DEFAULT IS OFF: if you set this, you MUST ensure your proxy strips
+# inbound copies of those headers before adding its own — otherwise any
+# external client can spoof user identity by sending the headers themselves.
+# TRUST_FORWARDED_IDENTITY_HEADERS=false
+
+# ──────────────────────────────────────────────────────────────────────────────
+# Uploader (optional — only relevant if you use POST /v1/upload)
+# ──────────────────────────────────────────────────────────────────────────────
+
+# Maximum decoded size, in MiB, accepted by the /upload endpoint. Defaults to
+# 50. Raise it for larger documents/datasets, lower it to harden the server
+# against memory exhaustion. Read once at startup — change requires a restart.
+# MAX_UPLOAD_MIB=50
+
+# ──────────────────────────────────────────────────────────────────────────────
+# Pipelex environment selector (optional)
+# ──────────────────────────────────────────────────────────────────────────────
+
+# Selects which pipelex_{PIPELEX_ENV}.toml override file is layered on top of
+# the baseline configuration. Defaults to "dev" when unset. See docs/configuration.md.
+# PIPELEX_ENV=dev
+
+# ──────────────────────────────────────────────────────────────────────────────
+# Temporal (optional — only needed when [temporal] is_enabled = true in your config)
+# ──────────────────────────────────────────────────────────────────────────────
+
+# Pipelex's [temporal] config block can interpolate env vars via ${VAR}
+# (e.g. `api_key = "${TEMPORAL_API_KEY}"`). This var has no effect on its own —
+# it's only useful if your mounted `.pipelex/` config references it.
+# TEMPORAL_API_KEY=
+
+# ──────────────────────────────────────────────────────────────────────────────
+# Bundle runner tooling (optional — used by `make bundle-*` / the
+# postman-bundle skill, NOT read by the API server itself)
+# ──────────────────────────────────────────────────────────────────────────────
+
+# Default callback webhook for the async POST /v1/start endpoint.
+# A `start` request is fire-and-forget: it returns a run_id immediately
+# and POSTs the finished result to this URL later. The `make bundle-*` targets
+# and the postman-bundle skill read this when building a `start` query
+# (override per run with CALLBACK_URL=... or --callback-url). Must be a public
+# http(s) URL — loopback/private/metadata hosts are rejected by the API's SSRF
+# guard. A throwaway https://webhook.site/<id> endpoint is the easy way to watch
+# results land.
+# CALLBACK_URL=
diff --git a/api/.gitignore b/api/.gitignore
new file mode 100644
index 000000000..7829d8470
--- /dev/null
+++ b/api/.gitignore
@@ -0,0 +1,63 @@
+
+
+# Byte-compiled / optimized / DLL files
+__pycache__/
+*.py[cod]
+*$py.class
+
+# Distribution / packaging
+dist/
+*.egg-info/
+
+# mkdocs
+site/
+
+# Unit test / coverage reports
+htmlcov/
+.pytest_cache/
+.coverage
+coverage.xml
+
+# Environments
+.env
+.venv
+env/
+venv/
+ENV/
+env.bak/
+venv.bak/
+
+# mypy
+.mypy_cache/
+
+# Ruff
+.ruff_cache/
+
+# General System Files
+*.log
+.DS_Store
+Thumbs.db
+
+# Files generated by unit tests
+reports/
+results/
+
+# temporary files
+temp/
+
+# editor/tool backup artifacts
+*.bak
+*.bak.*
+
+gcp_credentials.json
+
+.pipelex/storage
+
+# personnal pipelex config files that overrides the default one
+pipelex_super.toml
+pipelex_override.toml
+telemetry_override.toml
+# local-only env override (boots the runner as the hosted runner; needs a plugin CI lacks)
+.pipelex/pipelex_dev.toml
+
+.gstack/
diff --git a/api/.pipelex/.gitignore b/api/.pipelex/.gitignore
new file mode 100644
index 000000000..653ec55a9
--- /dev/null
+++ b/api/.pipelex/.gitignore
@@ -0,0 +1,9 @@
+# Written by pipelex when it set this directory up. Yours from here on — pipelex reads this file
+# never, and rewrites it never. Delete a line and it stays deleted.
+#
+# The timestamped copy `pipelex migrate` takes of every file before it rewrites it. It is our own
+# transient artifact; the durable history of these files is your commits.
+#
+# A `<file>.rescue.<stamp>` copy is deliberately NOT listed. One of those exists only because a
+# write could not be vouched for, and seeing it in `git status` is how you find out.
+*.bak.[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]T[0-9][0-9][0-9][0-9][0-9][0-9]Z
diff --git a/api/.pipelex/inference/backends.toml b/api/.pipelex/inference/backends.toml
new file mode 100644
index 000000000..a76495598
--- /dev/null
+++ b/api/.pipelex/inference/backends.toml
@@ -0,0 +1,131 @@
+# pipelex-api: this is the kit's `inference/backends.toml` from the pipelex of this repository, re-synced
+# by `make kit-sync`. Only the `enabled` switches are this image's own choice, and the sync keeps them;
+# any other edit is reported as drift by `make kit-check`.
+#
+####################################################################################################
+# Pipelex Inference Backends Configuration
+####################################################################################################
+#
+# This file configures the inference backends available to Pipelex.
+# Each backend connects to a different AI service provider (OpenAI, Anthropic, Google, etc.).
+#
+# Documentation: https://docs.pipelex.com
+# Support: https://go.pipelex.com/discord
+#
+####################################################################################################
+
+[pipelex_gateway]
+display_name = "⭐ Pipelex Gateway"
+enabled = true # Enable after accepting terms via `pipelex init config`
+api_key = "${PIPELEX_GATEWAY_API_KEY}"
+
+# Pipelex Manifold is a closed private beta: leave it off unless you have been invited.
+[pipelex_manifold]
+display_name = "Pipelex Manifold (private beta)"
+enabled = false
+endpoint = "${PIPELEX_MANIFOLD_ENDPOINT}"
+api_key = "${PIPELEX_MANIFOLD_API_KEY}"
+model_specs_section = "manifold_model_specs"
+auth_header = "x-pipelex-api-key"
+
+[anthropic]
+enabled = false
+api_key = "${ANTHROPIC_API_KEY}"
+
+[azure_openai]
+display_name = "Azure OpenAI"
+enabled = false
+endpoint = "${AZURE_API_BASE}"
+api_key = "${AZURE_API_KEY}"
+api_version = "${AZURE_API_VERSION}"
+
+[bedrock]
+display_name = "Amazon Bedrock"
+enabled = false
+aws_region = "${AWS_REGION}"
+
+[blackboxai]
+display_name = "BlackBox AI"
+enabled = false
+endpoint = "https://api.blackbox.ai/v1"
+api_key = "${BLACKBOX_API_KEY}"
+
+[fal]
+display_name = "FAL"
+enabled = false
+api_key = "${FAL_API_KEY}"
+
+[google]
+display_name = "Google AI"
+enabled = false
+api_key = "${GOOGLE_API_KEY}"
+
+[groq]
+display_name = "Groq"
+enabled = false
+endpoint = "https://api.groq.com/openai/v1"
+api_key = "${GROQ_API_KEY}"
+
+[huggingface]
+display_name = "Hugging Face"
+enabled = false
+api_key = "${HF_TOKEN}"
+
+[linkup]
+display_name = "Linkup"
+enabled = false
+api_key = "${LINKUP_API_KEY}"
+
+[minimax]
+display_name = "MiniMax"
+enabled = false
+endpoint = "https://api.minimax.io/anthropic"
+api_key = "${MINIMAX_API_KEY}"
+
+[mistral]
+display_name = "Mistral AI"
+enabled = false
+api_key = "${MISTRAL_API_KEY}"
+
+[ollama]
+enabled = false
+endpoint = "http://localhost:11434/v1"
+
+[openai]
+display_name = "OpenAI"
+enabled = false
+api_key = "${OPENAI_API_KEY}"
+
+[openrouter]
+display_name = "OpenRouter"
+enabled = false
+endpoint = "https://openrouter.ai/api/v1"
+api_key = "${OPENROUTER_API_KEY}"
+
+[portkey]
+display_name = "Portkey"
+enabled = false
+endpoint = "https://api.portkey.ai/v1"
+api_key = "${PORTKEY_API_KEY}"
+
+[scaleway]
+display_name = "Scaleway"
+enabled = false
+endpoint = "${SCALEWAY_ENDPOINT}"
+api_key = "${SCALEWAY_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 sandboxes
+gcp_project_id = "${GCP_PROJECT_ID}"
+gcp_location = "${GCP_LOCATION}"
+gcp_credentials_file_path = "${GCP_CREDENTIALS_FILE_PATH}"
+
+[xai]
+display_name = "xAI"
+enabled = false
+endpoint = "https://api.x.ai/v1"
+api_key = "${XAI_API_KEY}"
+
+[internal] # software-only backend, runs internally, without AI
+enabled = true
diff --git a/api/.pipelex/inference/backends/.kit_manifest.json b/api/.pipelex/inference/backends/.kit_manifest.json
new file mode 100644
index 000000000..7d6f49bef
--- /dev/null
+++ b/api/.pipelex/inference/backends/.kit_manifest.json
@@ -0,0 +1,6 @@
+{
+ "files": {
+ "internal.toml": "30d0f6f9de1c4cba586e04acc370e431123954bef5cb05a54eef05134d590d4c"
+ },
+ "kit_version": "0.70.0"
+}
diff --git a/api/.pipelex/inference/backends/anthropic.toml b/api/.pipelex/inference/backends/anthropic.toml
new file mode 100644
index 000000000..dbe8fd8cf
--- /dev/null
+++ b/api/.pipelex/inference/backends/anthropic.toml
@@ -0,0 +1,186 @@
+################################################################################
+# Anthropic Backend Configuration
+################################################################################
+#
+# This file defines the model specifications for Anthropic Claude models.
+# It contains model definitions for various Claude language models
+# accessible through the Anthropic API.
+#
+# Configuration structure:
+# - Each model is defined in its own section with the model name as the header
+# - Headers with dots must be quoted (e.g., ["claude-3.5-sonnet"])
+# - Model costs are in USD per million tokens (input/output)
+#
+# Documentation: https://docs.pipelex.com
+# Support: https://go.pipelex.com/discord
+#
+################################################################################
+
+################################################################################
+# MODEL DEFAULTS
+################################################################################
+
+[defaults]
+model_type = "llm"
+sdk = "anthropic"
+structure_method = "instructor/anthropic_tools"
+thinking_mode = "manual"
+
+################################################################################
+# LANGUAGE MODELS
+################################################################################
+
+# --- Claude 3 Series ----------------------------------------------------------
+[claude-3-haiku]
+model_id = "claude-3-haiku-20240307"
+max_tokens = 4096
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+max_prompt_images = 100
+costs = { input = 0.25, output = 1.25 }
+thinking_mode = "none"
+
+# --- Claude 3.7 Series --------------------------------------------------------
+["claude-3.7-sonnet"]
+model_id = "claude-3-7-sonnet-20250219"
+max_tokens = 8192
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+max_prompt_images = 100
+costs = { input = 3.0, output = 15.0 }
+
+# --- Claude 4 Series ----------------------------------------------------------
+[claude-4-sonnet]
+model_id = "claude-sonnet-4-20250514"
+max_tokens = 64000
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+max_prompt_images = 100
+costs = { input = 3.0, output = 15.0 }
+
+[claude-4-opus]
+model_id = "claude-opus-4-20250514"
+max_tokens = 32000
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+max_prompt_images = 100
+costs = { input = 3.0, output = 15.0 }
+
+# --- Claude 4.1 Series --------------------------------------------------------
+["claude-4.1-opus"]
+model_id = "claude-opus-4-1-20250805"
+max_tokens = 32000
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+max_prompt_images = 100
+costs = { input = 3.0, output = 15.0 }
+
+# --- Claude 4.5 Series --------------------------------------------------------
+["claude-4.5-sonnet"]
+model_id = "claude-sonnet-4-5-20250929"
+max_tokens = 64000
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+max_prompt_images = 100
+costs = { input = 3.0, output = 15.0 }
+
+["claude-4.5-haiku"]
+model_id = "claude-haiku-4-5-20251001"
+max_tokens = 64000
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+max_prompt_images = 100
+costs = { input = 1.0, output = 5.0 }
+
+["claude-4.5-opus"]
+model_id = "claude-opus-4-5-20251101"
+max_tokens = 64000
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+max_prompt_images = 100
+costs = { input = 5.0, output = 25.0 }
+
+["claude-4.6-sonnet"]
+model_id = "claude-sonnet-4-6"
+max_tokens = 64000
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+max_prompt_images = 100
+costs = { input = 3.0, output = 15.0 }
+thinking_mode = "adaptive"
+
+["claude-4.6-opus"]
+model_id = "claude-opus-4-6"
+max_tokens = 64000
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+max_prompt_images = 100
+costs = { input = 5.0, output = 25.0 }
+thinking_mode = "adaptive"
+
+# --- Claude 4.7 Series --------------------------------------------------------
+["claude-4.7-opus"]
+model_id = "claude-opus-4-7"
+max_tokens = 128000
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+max_prompt_images = 100
+costs = { input = 5.0, output = 25.0 }
+thinking_mode = "adaptive"
+listed_constraints = ["temperature_unsupported"]
+
+# --- Claude 4.8 Series --------------------------------------------------------
+["claude-4.8-opus"]
+model_id = "claude-opus-4-8"
+max_tokens = 128000
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+max_prompt_images = 100
+costs = { input = 5.0, output = 25.0 }
+thinking_mode = "adaptive"
+listed_constraints = ["temperature_unsupported"]
+
+# --- Claude 5 Series ----------------------------------------------------------
+[claude-5-sonnet]
+model_id = "claude-sonnet-5"
+max_tokens = 64000
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+max_prompt_images = 100
+costs = { input = 2.0, output = 10.0 }
+thinking_mode = "adaptive"
+listed_constraints = ["temperature_unsupported"]
+
+[claude-5-opus]
+model_id = "claude-opus-5"
+max_tokens = 128000
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+max_prompt_images = 100
+costs = { input = 5.0, output = 25.0 }
+thinking_mode = "adaptive"
+listed_constraints = ["temperature_unsupported"]
+
+[claude-5-fable]
+model_id = "claude-fable-5"
+max_tokens = 128000
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+max_prompt_images = 100
+costs = { input = 10.0, output = 50.0 }
+thinking_mode = "adaptive"
+listed_constraints = ["temperature_unsupported"]
+
+# --- Claude 5.1 Series --------------------------------------------------------
+["claude-5.1-fable"]
+model_id = "claude-fable-5-1"
+max_tokens = 128000
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+max_prompt_images = 100
+costs = { input = 10.0, output = 50.0 }
+thinking_mode = "adaptive"
+# Fable 5.1 refuses tool_choice "tool" and "any", which is what the section default
+# instructor/anthropic_tools forces; the reasoning variant leaves tool_choice on auto.
+structure_method = "instructor/anthropic_reasoning_tools"
+listed_constraints = ["temperature_unsupported"]
diff --git a/api/.pipelex/inference/backends/azure_openai.toml b/api/.pipelex/inference/backends/azure_openai.toml
new file mode 100644
index 000000000..7649888fe
--- /dev/null
+++ b/api/.pipelex/inference/backends/azure_openai.toml
@@ -0,0 +1,210 @@
+################################################################################
+# Azure OpenAI Backend Configuration
+################################################################################
+#
+# This file defines the model specifications for Azure OpenAI models.
+# It contains model definitions for OpenAI models deployed on Azure
+# accessible through the Azure OpenAI API.
+#
+# Configuration structure:
+# - Each model is defined in its own section with the model name as the header
+# - Headers with dots must be quoted (e.g., ["gpt-5.4"])
+# - Model costs are in USD per million tokens (input/output)
+#
+# Documentation: https://docs.pipelex.com
+# Support: https://go.pipelex.com/discord
+#
+################################################################################
+
+################################################################################
+# MODEL DEFAULTS
+################################################################################
+
+[defaults]
+model_type = "llm"
+sdk = "azure_openai_responses"
+structure_method = "instructor/openai_responses_tools"
+thinking_mode = "none"
+
+################################################################################
+# LANGUAGE MODELS
+################################################################################
+
+# --- GPT-4o Series ------------------------------------------------------------
+[gpt-4o]
+model_id = "gpt-4o-2024-11-20"
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 2.5, output = 10.0 }
+
+[gpt-4o-mini]
+model_id = "gpt-4o-mini-2024-07-18"
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 0.15, output = 0.6 }
+
+# --- GPT-5.3 Series -------------------------------------------------------------
+["gpt-5.3-codex"]
+model_id = "gpt-5.3-codex-2026-02-24"
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 1.75, output = 14.0 }
+valued_constraints = { fixed_temperature = 1 }
+thinking_mode = "manual"
+
+# --- GPT-5.4 Series -----------------------------------------------------------
+["gpt-5.4"]
+model_id = "gpt-5.4-2026-03-05"
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+costs = { input = 2.5, output = 15.0 }
+thinking_mode = "manual"
+
+["gpt-5.4-pro"]
+model_id = "gpt-5.4-pro-2026-03-05"
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+costs = { input = 30.0, output = 180.0 }
+valued_constraints = { fixed_temperature = 1 }
+thinking_mode = "manual"
+
+["gpt-5.4-mini"]
+model_id = "gpt-5.4-mini-2026-03-17"
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+costs = { input = 0.75, output = 4.5 }
+thinking_mode = "manual"
+
+["gpt-5.4-nano"]
+model_id = "gpt-5.4-nano-2026-03-17"
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+costs = { input = 0.2, output = 1.25 }
+thinking_mode = "manual"
+
+# --- GPT-5.5 Series -----------------------------------------------------------
+["gpt-5.5"]
+model_id = "gpt-5.5-2026-04-24"
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+costs = { input = 5.0, output = 30.0 }
+valued_constraints = { fixed_temperature = 1 }
+thinking_mode = "manual"
+
+# --- GPT-5.6 Series -----------------------------------------------------------
+["gpt-5.6-sol"]
+model_id = "gpt-5.6-sol-2026-07-09"
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+costs = { input = 4.0, output = 20.0 }
+valued_constraints = { fixed_temperature = 1 }
+thinking_mode = "manual"
+
+["gpt-5.6-terra"]
+model_id = "gpt-5.6-terra-2026-07-09"
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+costs = { input = 2.0, output = 12.0 }
+valued_constraints = { fixed_temperature = 1 }
+thinking_mode = "manual"
+
+["gpt-5.6-luna"]
+model_id = "gpt-5.6-luna-2026-07-09"
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+costs = { input = 0.2, output = 1.2 }
+valued_constraints = { fixed_temperature = 1 }
+thinking_mode = "manual"
+
+# --- GPT-6 Series -------------------------------------------------------------
+["gpt-6-astra"]
+model_id = "gpt-6-astra-2026-09-03"
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+costs = { input = 10.0, output = 50.0 }
+valued_constraints = { fixed_temperature = 1 }
+thinking_mode = "manual"
+
+################################################################################
+# IMAGE GENERATION MODELS
+################################################################################
+
+# --- OpenAI Image Generation --------------------------------------------------
+[gpt-image-1]
+sdk = "azure_rest_img_gen"
+model_type = "img_gen"
+model_id = "gpt-image-1-2025-04-15"
+inputs = ["text", "images"]
+outputs = ["image"]
+costs = { input = 10, output = 40 }
+
+[gpt-image-1.rules]
+prompt = "positive_only"
+num_images = "gpt_image"
+aspect_ratio = "gpt_image_legacy"
+background = "available"
+inference = "gpt_image"
+safety_checker = "unavailable"
+output_format = "gpt_image_legacy"
+output_compression = "gpt_image_legacy"
+input_images = "gpt_image"
+input_fidelity = "gpt_image_legacy"
+
+[gpt-image-1-mini]
+sdk = "azure_rest_img_gen"
+model_type = "img_gen"
+model_id = "gpt-image-1-mini-2025-10-06"
+inputs = ["text", "images"]
+outputs = ["image"]
+costs = { input = 2.5, output = 8 }
+
+[gpt-image-1-mini.rules]
+prompt = "positive_only"
+num_images = "gpt_image"
+aspect_ratio = "gpt_image_legacy"
+background = "available"
+inference = "gpt_image"
+safety_checker = "unavailable"
+output_format = "gpt_image_legacy"
+output_compression = "gpt_image_legacy"
+input_images = "gpt_image"
+input_fidelity = "gpt_image_legacy"
+
+["gpt-image-1.5"]
+sdk = "azure_rest_img_gen"
+model_type = "img_gen"
+model_id = "gpt-image-1.5-2025-12-16"
+inputs = ["text", "images"]
+outputs = ["image"]
+costs = { input = 8, output = 32 }
+
+["gpt-image-1.5".rules]
+prompt = "positive_only"
+num_images = "gpt_image"
+aspect_ratio = "gpt_image_legacy"
+background = "available"
+inference = "gpt_image"
+safety_checker = "unavailable"
+output_format = "gpt_image_legacy"
+output_compression = "gpt_image_legacy"
+input_images = "gpt_image"
+input_fidelity = "gpt_image_legacy"
+
+[gpt-image-2]
+sdk = "azure_rest_img_gen"
+model_type = "img_gen"
+inputs = ["text", "images"]
+outputs = ["image"]
+costs = { input = 8, output = 30 }
+
+[gpt-image-2.rules]
+prompt = "positive_only"
+num_images = "gpt_image"
+aspect_ratio = "gpt_image_2"
+background = "unavailable"
+inference = "gpt_image"
+safety_checker = "unavailable"
+output_format = "unavailable"
+output_compression = "unavailable"
+input_images = "gpt_image"
+input_fidelity = "unavailable"
diff --git a/api/.pipelex/inference/backends/bedrock.toml b/api/.pipelex/inference/backends/bedrock.toml
new file mode 100644
index 000000000..e876def7c
--- /dev/null
+++ b/api/.pipelex/inference/backends/bedrock.toml
@@ -0,0 +1,169 @@
+################################################################################
+# Amazon Bedrock Backend Configuration
+################################################################################
+#
+# This file defines the model specifications for Amazon Bedrock models.
+# It contains model definitions for various language models
+# accessible through the Amazon Bedrock service.
+#
+# Configuration structure:
+# - Each model is defined in its own section with the model name as the header
+# - Headers with dots must be quoted (e.g., ["claude-3.5-sonnet"])
+# - Model costs are in USD per million tokens (input/output)
+#
+# Documentation: https://docs.pipelex.com
+# Support: https://go.pipelex.com/discord
+#
+################################################################################
+
+################################################################################
+# MODEL DEFAULTS
+################################################################################
+
+[defaults]
+model_type = "llm"
+sdk = "bedrock_aioboto"
+thinking_mode = "none"
+
+################################################################################
+# LANGUAGE MODELS
+################################################################################
+
+# --- Mistral Models -----------------------------------------------------------
+[bedrock-mistral-large]
+model_id = "mistral.mistral-large-2407-v1:0"
+max_tokens = 8192
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 4.0, output = 12.0 }
+
+# --- Meta Llama Models --------------------------------------------------------
+[bedrock-meta-llama-3-3-70b-instruct]
+model_id = "us.meta.llama3-3-70b-instruct-v1:0"
+max_tokens = 8192
+inputs = ["text"]
+outputs = ["text"]
+# TODO: find out the actual cost per million tokens for llama3 on bedrock
+costs = { input = 3.0, output = 15.0 }
+
+# --- Amazon Nova Models -------------------------------------------------------
+[bedrock-nova-pro]
+model_id = "us.amazon.nova-pro-v1:0"
+max_tokens = 5120
+inputs = ["text"]
+outputs = ["text"]
+# TODO: find out the actual cost per million tokens for nova on bedrock
+costs = { input = 3.0, output = 15.0 }
+
+# --- DeepSeek Models ----------------------------------------------------------
+["deepseek-v3.1"]
+model_id = "deepseek.v3-v1:0"
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 0, output = 0 }
+max_tokens = 8192
+
+# --- Claude LLMs --------------------------------------------------------------
+[claude-4-sonnet]
+sdk = "bedrock_anthropic"
+model_id = "us.anthropic.claude-sonnet-4-20250514-v1:0"
+max_tokens = 64000
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+max_prompt_images = 100
+costs = { input = 3.0, output = 15.0 }
+thinking_mode = "manual"
+
+[claude-4-opus]
+sdk = "bedrock_anthropic"
+model_id = "us.anthropic.claude-opus-4-20250514-v1:0"
+max_tokens = 32000
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+max_prompt_images = 100
+costs = { input = 3.0, output = 15.0 }
+thinking_mode = "manual"
+
+["claude-4.1-opus"]
+sdk = "bedrock_anthropic"
+model_id = "us.anthropic.claude-opus-4-1-20250805-v1:0"
+max_tokens = 32000
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+max_prompt_images = 100
+costs = { input = 3.0, output = 15.0 }
+thinking_mode = "manual"
+
+["claude-4.5-sonnet"]
+sdk = "bedrock_anthropic"
+model_id = "us.anthropic.claude-sonnet-4-5-20250929-v1:0"
+max_tokens = 64000
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+max_prompt_images = 100
+costs = { input = 3.0, output = 15.0 }
+thinking_mode = "manual"
+
+["claude-4.5-haiku"]
+sdk = "bedrock_anthropic"
+model_id = "us.anthropic.claude-haiku-4-5-20251001-v1:0"
+max_tokens = 64000
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+max_prompt_images = 100
+costs = { input = 1.0, output = 5.0 }
+thinking_mode = "manual"
+
+["claude-4.5-opus"]
+sdk = "bedrock_anthropic"
+model_id = "global.anthropic.claude-opus-4-5-20251101-v1:0"
+max_tokens = 64000
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+max_prompt_images = 100
+costs = { input = 5.0, output = 25.0 }
+thinking_mode = "manual"
+
+["claude-4.6-sonnet"]
+sdk = "bedrock_anthropic"
+model_id = "global.anthropic.claude-sonnet-4-6"
+max_tokens = 64000
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+max_prompt_images = 100
+costs = { input = 3.0, output = 15.0 }
+thinking_mode = "adaptive"
+
+["claude-4.6-opus"]
+sdk = "bedrock_anthropic"
+model_id = "global.anthropic.claude-opus-4-6-v1"
+max_tokens = 64000
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+max_prompt_images = 100
+costs = { input = 5.0, output = 25.0 }
+thinking_mode = "adaptive"
+
+# --- Claude 4.7 Series --------------------------------------------------------
+["claude-4.7-opus"]
+sdk = "bedrock_anthropic"
+model_id = "global.anthropic.claude-opus-4-7"
+max_tokens = 128000
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+max_prompt_images = 100
+costs = { input = 5.0, output = 25.0 }
+thinking_mode = "adaptive"
+listed_constraints = ["temperature_unsupported"]
+
+# --- Claude 4.8 Series --------------------------------------------------------
+["claude-4.8-opus"]
+sdk = "bedrock_anthropic"
+model_id = "global.anthropic.claude-opus-4-8"
+max_tokens = 128000
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+max_prompt_images = 100
+costs = { input = 5.0, output = 25.0 }
+thinking_mode = "adaptive"
+listed_constraints = ["temperature_unsupported"]
diff --git a/api/.pipelex/inference/backends/blackboxai.toml b/api/.pipelex/inference/backends/blackboxai.toml
new file mode 100644
index 000000000..dc1642df6
--- /dev/null
+++ b/api/.pipelex/inference/backends/blackboxai.toml
@@ -0,0 +1,165 @@
+################################################################################
+# BlackBoxAI Backend Configuration
+################################################################################
+#
+# This file defines the model specifications for BlackBoxAI models.
+# It contains model definitions for various language models from different providers
+# accessible through the BlackBoxAI API.
+#
+# Configuration structure:
+# - Each model is defined in its own section with the model name as the header
+# - Headers with dots must be quoted (e.g., ["gpt-5.2"])
+# - Model costs are in USD per million tokens (input/output)
+#
+# Documentation: https://docs.pipelex.com
+# Support: https://go.pipelex.com/discord
+#
+################################################################################
+
+################################################################################
+# MODEL DEFAULTS
+################################################################################
+
+[defaults]
+model_type = "llm"
+sdk = "openai"
+structure_method = "instructor/openai_tools"
+thinking_mode = "none"
+
+################################################################################
+# LANGUAGE MODELS
+################################################################################
+
+# --- Anthropic Claude Models --------------------------------------------------
+["claude-4.5-sonnet"]
+model_id = "blackboxai/anthropic/claude-sonnet-4.5"
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 3.00, output = 15.00 }
+thinking_mode = "manual"
+
+["claude-4.5-haiku"]
+model_id = "blackboxai/anthropic/claude-haiku-4.5"
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 1.00, output = 5.00 }
+thinking_mode = "manual"
+
+[claude-4-sonnet]
+model_id = "blackboxai/anthropic/claude-sonnet-4"
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 3.00, output = 15.00 }
+thinking_mode = "manual"
+
+["claude-4.5-opus"]
+model_id = "blackboxai/anthropic/claude-opus-4.5"
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 5.00, output = 25.00 }
+thinking_mode = "manual"
+
+["claude-4.6-opus"]
+model_id = "blackboxai/anthropic/claude-opus-4.6"
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 5.00, output = 25.00 }
+thinking_mode = "adaptive"
+
+# --- OpenAI GPT-5 Models ------------------------------------------------------
+[gpt-5-mini]
+model_id = "blackboxai/openai/gpt-5-mini"
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 0.25, output = 2.00 }
+
+[gpt-5]
+model_id = "blackboxai/openai/gpt-5"
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 1.25, output = 10.00 }
+
+[gpt-5-pro]
+model_id = "blackboxai/openai/gpt-5-pro"
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 15.00, output = 120.00 }
+
+[gpt-5-codex]
+model_id = "blackboxai/openai/gpt-5-codex"
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 1.25, output = 10.00 }
+
+["gpt-5.1"]
+model_id = "blackboxai/openai/gpt-5.1"
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 1.25, output = 10.00 }
+
+["gpt-5.1-codex"]
+model_id = "blackboxai/openai/gpt-5.1-codex"
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 1.25, output = 10.00 }
+
+["gpt-5.2"]
+model_id = "blackboxai/openai/gpt-5.2"
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 1.75, output = 14.00 }
+
+["gpt-5.2-pro"]
+model_id = "blackboxai/openai/gpt-5.2-pro"
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 2.00, output = 16.00 }
+
+# --- Google Gemini Models -----------------------------------------------------
+["gemini-2.5-pro"]
+model_id = "blackboxai/google/gemini-2.5-pro"
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 1.25, output = 10.00 }
+thinking_mode = "none"
+
+["gemini-2.5-flash"]
+model_id = "blackboxai/google/gemini-2.5-flash"
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 0.30, output = 2.50 }
+thinking_mode = "none"
+
+# --- MiniMax Models -----------------------------------------------------------
+[minimax-m2]
+model_id = "blackboxai/minimax/minimax-m2"
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.27, output = 1.15 }
+
+# --- Qwen Models --------------------------------------------------------------
+[qwen3-max]
+model_id = "blackboxai/qwen/qwen3-max"
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 2.00, output = 10.00 }
+
+[qwen3-coder]
+model_id = "blackboxai/qwen/qwen3-coder"
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 1.50, output = 8.00 }
+
+# --- Qwen VL Models -------------------------------------------------
+[qwen3-vl-235b-a22b]
+model_id = "blackboxai/qwen3-vl-235b-a22b"
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 3.00, output = 15.00 }
+
+[qwen3-vl-32b]
+model_id = "blackboxai/qwen3-vl-32b"
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 1.00, output = 5.00 }
+structure_method = "instructor/openrouter_structured_outputs"
diff --git a/api/.pipelex/inference/backends/fal.toml b/api/.pipelex/inference/backends/fal.toml
new file mode 100644
index 000000000..d8dc03f68
--- /dev/null
+++ b/api/.pipelex/inference/backends/fal.toml
@@ -0,0 +1,112 @@
+################################################################################
+# FAL Backend Configuration
+################################################################################
+#
+# This file defines the model specifications for FAL (Fast AI Labs) models.
+# It contains model definitions for various image generation models
+# accessible through the FAL API.
+#
+# Configuration structure:
+# - Each model is defined in its own section with the model name as the header
+# - Headers with dots must be quoted (e.g., ["flux-pro/v1.1"])
+# - Model costs are in USD per million tokens (input/output)
+#
+# Documentation: https://docs.pipelex.com
+# Support: https://go.pipelex.com/discord
+#
+################################################################################
+
+################################################################################
+# MODEL DEFAULTS
+################################################################################
+
+[defaults]
+model_type = "img_gen"
+sdk = "fal"
+thinking_mode = "none"
+
+################################################################################
+# IMAGE GENERATION MODELS
+################################################################################
+
+# --- Flux Pro Series ----------------------------------------------------------
+[flux-pro]
+model_id = "fal-ai/flux-pro"
+inputs = ["text"]
+outputs = ["image"]
+costs = { input = 0.05, output = 0.0 }
+
+[flux-pro.rules]
+model_choice = "model_id"
+prompt = "positive_only"
+num_images = "fal"
+aspect_ratio = "flux"
+inference = "flux"
+safety_checker = "available"
+output_format = "flux_1"
+specific = "fal"
+
+["flux-pro/v1.1"]
+model_id = "fal-ai/flux-pro/v1.1"
+inputs = ["text"]
+outputs = ["image"]
+costs = { input = 0.05, output = 0.0 }
+
+["flux-pro/v1.1".rules]
+model_choice = "model_id"
+prompt = "positive_only"
+num_images = "fal"
+aspect_ratio = "flux"
+inference = "flux"
+safety_checker = "available"
+output_format = "flux_1"
+specific = "fal"
+
+["flux-pro/v1.1-ultra"]
+model_id = "fal-ai/flux-pro/v1.1-ultra"
+inputs = ["text"]
+outputs = ["image"]
+costs = { input = 0.06, output = 0.0 }
+
+["flux-pro/v1.1-ultra".rules]
+model_choice = "model_id"
+prompt = "positive_only"
+num_images = "fal"
+aspect_ratio = "flux_11_ultra"
+inference = "flux_11_ultra"
+safety_checker = "available"
+output_format = "flux_1"
+specific = "fal"
+
+[flux-2]
+model_id = "fal-ai/flux-2"
+inputs = ["text"]
+outputs = ["image"]
+costs = { input = 0.05, output = 0.0 }
+
+[flux-2.rules]
+model_choice = "model_id"
+prompt = "positive_only"
+num_images = "fal"
+aspect_ratio = "flux"
+inference = "flux"
+safety_checker = "available"
+output_format = "flux_2"
+specific = "fal"
+
+# --- SDXL models --------------------------------------------------------------
+[fast-lightning-sdxl]
+model_id = "fal-ai/fast-lightning-sdxl"
+inputs = ["text"]
+outputs = ["image"]
+costs = { input = 0.0003, output = 0.0 }
+
+[fast-lightning-sdxl.rules]
+model_choice = "model_id"
+prompt = "positive_only"
+num_images = "fal"
+aspect_ratio = "flux"
+inference = "sdxl_lightning"
+safety_checker = "unavailable"
+output_format = "sdxl"
+specific = "fal"
diff --git a/api/.pipelex/inference/backends/google.toml b/api/.pipelex/inference/backends/google.toml
new file mode 100644
index 000000000..69d8ddf68
--- /dev/null
+++ b/api/.pipelex/inference/backends/google.toml
@@ -0,0 +1,158 @@
+################################################################################
+# Google Gemini API Backend Configuration
+################################################################################
+#
+# This file defines the model specifications for Google Gemini API models.
+# It contains model definitions for Gemini language models
+# accessible through the Google Gemini API (not VertexAI).
+#
+# Configuration structure:
+# - Each model is defined in its own section with the model name as the header
+# - Headers with dots must be quoted (e.g., ["gemini-3.1-pro"])
+# - Model costs are in USD per million tokens (input/output)
+#
+# Documentation: https://docs.pipelex.com
+# Support: https://go.pipelex.com/discord
+#
+################################################################################
+
+################################################################################
+# MODEL DEFAULTS
+################################################################################
+
+[defaults]
+model_type = "llm"
+sdk = "google"
+structure_method = "instructor/genai_structured_outputs" # Gemini's native JSON output
+thinking_mode = "manual"
+
+################################################################################
+# LANGUAGE MODELS
+################################################################################
+
+# --- Gemini 2.5 Series ----------------------------------------
+["gemini-2.5-pro"]
+model_id = "gemini-2.5-pro"
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+max_prompt_images = 3000
+costs = { input = 1.25, output = 10.0 }
+
+["gemini-2.5-flash"]
+model_id = "gemini-2.5-flash"
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+max_prompt_images = 3000
+costs = { input = 0.30, output = 2.50 }
+
+["gemini-2.5-flash-lite"]
+model_id = "gemini-2.5-flash-lite"
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+max_prompt_images = 3000
+costs = { input = 0.10, output = 0.40 }
+
+# --- Gemini 3.0 Series ----------------------------------------
+["gemini-3.0-flash"]
+model_id = "gemini-3-flash-preview"
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+max_prompt_images = 3000
+costs = { input = 0.5, output = 3.0 }
+thinking_mode = "adaptive"
+
+# --- Gemini 3.1 Series ----------------------------------------
+["gemini-3.1-flash-lite"]
+model_id = "gemini-3.1-flash-lite-preview"
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+max_prompt_images = 3000
+costs = { input = 0.25, output = 1.50 }
+thinking_mode = "adaptive"
+
+["gemini-3.1-pro"]
+model_id = "gemini-3.1-pro-preview"
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+max_prompt_images = 3000
+costs = { input = 2, output = 12.0 }
+thinking_mode = "adaptive"
+
+# --- Gemini 3.5 Series ----------------------------------------
+["gemini-3.5-flash"]
+model_id = "gemini-3.5-flash"
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+max_prompt_images = 3000
+costs = { input = 1.5, output = 9.0 }
+thinking_mode = "adaptive"
+
+# --- Latest Aliases (point to current generation, change over time) -----------
+["gemini-pro-latest"]
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+max_prompt_images = 3000
+costs = { input = 1.25, output = 10.0 }
+thinking_mode = "adaptive"
+
+["gemini-flash-latest"]
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+max_prompt_images = 3000
+costs = { input = 0.30, output = 2.50 }
+thinking_mode = "adaptive"
+
+["gemini-flash-lite-latest"]
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+max_prompt_images = 3000
+costs = { input = 0.10, output = 0.40 }
+thinking_mode = "adaptive"
+
+################################################################################
+# IMAGE GENERATION MODELS (Nano Banana)
+################################################################################
+
+[nano-banana]
+model_type = "img_gen"
+model_id = "gemini-2.5-flash-image"
+inputs = ["text", "images"]
+outputs = ["image"]
+thinking_mode = "none"
+costs = { input = 0.30, output = 30 }
+
+[nano-banana.rules]
+aspect_ratio = "gemini_2_5"
+
+[nano-banana-pro]
+model_type = "img_gen"
+model_id = "gemini-3-pro-image-preview"
+inputs = ["text", "images"]
+outputs = ["image"]
+thinking_mode = "none"
+costs = { input = 2.0, output = 120 }
+
+[nano-banana-pro.rules]
+aspect_ratio = "gemini_3_pro"
+
+[nano-banana-2]
+model_type = "img_gen"
+model_id = "gemini-3.1-flash-image-preview"
+inputs = ["text", "images"]
+outputs = ["image"]
+thinking_mode = "none"
+costs = { input = 0.50, output = 60 }
+
+[nano-banana-2.rules]
+aspect_ratio = "gemini_3_flash"
+
+[nano-banana-2-lite]
+model_type = "img_gen"
+model_id = "gemini-3.1-flash-lite-image"
+inputs = ["text", "images"]
+outputs = ["image"]
+thinking_mode = "none"
+costs = { input = 0.25, output = 30 }
+
+[nano-banana-2-lite.rules]
+aspect_ratio = "gemini_3_flash_lite"
diff --git a/api/.pipelex/inference/backends/groq.toml b/api/.pipelex/inference/backends/groq.toml
new file mode 100644
index 000000000..cb480942b
--- /dev/null
+++ b/api/.pipelex/inference/backends/groq.toml
@@ -0,0 +1,130 @@
+################################################################################
+# Groq Backend Configuration
+################################################################################
+#
+# This file defines the model specifications for Groq models.
+# It contains model definitions for various LLM models accessible through
+# the Groq API, including text-only and vision-capable models.
+#
+# Configuration structure:
+# - Each model is defined in its own section with the model name as the header
+# - Headers with dots or slashes must be quoted (e.g., ["meta-llama/llama-4-scout"])
+# - Model costs are in USD per million tokens (input/output)
+# - Vision models support max 5 images per request, 33MP max resolution
+#
+# Documentation: https://docs.pipelex.com
+# Support: https://go.pipelex.com/discord
+#
+################################################################################
+
+################################################################################
+# MODEL DEFAULTS
+################################################################################
+
+[defaults]
+model_type = "llm"
+sdk = "openai"
+structure_method = "instructor/json"
+thinking_mode = "none"
+
+################################################################################
+# PRODUCTION TEXT MODELS
+################################################################################
+
+# --- Meta Llama 3.x Series ----------------------------------------------------
+["llama-3.1-8b-instant"]
+model_id = "llama-3.1-8b-instant"
+max_tokens = 131072
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.05, output = 0.08 }
+
+["llama-3.3-70b-versatile"]
+model_id = "llama-3.3-70b-versatile"
+max_tokens = 32768
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.59, output = 0.79 }
+
+# --- Meta Llama Guard ---------------------------------------------------------
+[llama-guard-4-12b]
+model_id = "meta-llama/llama-guard-4-12b"
+max_tokens = 1024
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.20, output = 0.20 }
+
+# --- OpenAI GPT-OSS Models ----------------------------------------------------
+[gpt-oss-20b]
+model_id = "openai/gpt-oss-20b"
+max_tokens = 65536
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.075, output = 0.30 }
+
+[gpt-oss-120b]
+model_id = "openai/gpt-oss-120b"
+max_tokens = 65536
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.15, output = 0.60 }
+
+# --- Groq Compound Systems ----------------------------------------------------
+["groq/compound"]
+model_id = "groq/compound"
+max_tokens = 8192
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.15, output = 0.45 }
+
+["groq/compound-mini"]
+model_id = "groq/compound-mini"
+max_tokens = 8192
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.10, output = 0.30 }
+
+################################################################################
+# PREVIEW MODELS
+################################################################################
+
+# --- Meta Llama 4 Vision Models (Preview) -------------------------------------
+[llama-4-scout-17b-16e-instruct]
+model_id = "meta-llama/llama-4-scout-17b-16e-instruct"
+max_tokens = 8192
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+max_prompt_images = 5
+costs = { input = 0.11, output = 0.34 }
+
+[llama-4-maverick-17b-128e-instruct]
+model_id = "meta-llama/llama-4-maverick-17b-128e-instruct"
+max_tokens = 8192
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+max_prompt_images = 5
+costs = { input = 0.20, output = 0.60 }
+
+# --- Moonshot Kimi K2 ---------------------------------------------------------
+[kimi-k2-instruct-0905]
+model_id = "moonshotai/kimi-k2-instruct-0905"
+max_tokens = 16384
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 1.00, output = 3.00 }
+
+# --- OpenAI Safety Model ------------------------------------------------------
+[gpt-oss-safeguard-20b]
+model_id = "openai/gpt-oss-safeguard-20b"
+max_tokens = 65536
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.075, output = 0.30 }
+
+# --- Qwen 3 -------------------------------------------------------------------
+[qwen3-32b]
+model_id = "qwen/qwen3-32b"
+max_tokens = 40960
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.29, output = 0.59 }
diff --git a/api/.pipelex/inference/backends/huggingface.toml b/api/.pipelex/inference/backends/huggingface.toml
new file mode 100644
index 000000000..ea4665fb7
--- /dev/null
+++ b/api/.pipelex/inference/backends/huggingface.toml
@@ -0,0 +1,44 @@
+################################################################################
+# Hugging Face Backend Configuration
+################################################################################
+#
+# This file defines the model specifications for Hugging Face models.
+# It contains model definitions for various image generation models
+# accessible through the Hugging Face Inference API with provider="auto".
+#
+# Configuration structure:
+# - Each model is defined in its own section with the model name as the header
+# - Headers with dots or slashes must be quoted (e.g., ["stabilityai/stable-diffusion-2-1"])
+# - Model costs are in USD per million tokens (input/output)
+#
+# Documentation: https://docs.pipelex.com
+# Support: https://go.pipelex.com/discord
+#
+################################################################################
+
+################################################################################
+# MODEL DEFAULTS
+################################################################################
+
+[defaults]
+model_type = "img_gen"
+sdk = "huggingface_img_gen"
+thinking_mode = "none"
+
+################################################################################
+# IMAGE GENERATION MODELS
+################################################################################
+
+# --- Qwen Image Models --------------------------------------------------
+[qwen-image]
+model_id = "Qwen/Qwen-Image"
+inputs = ["text"]
+outputs = ["image"]
+costs = { input = 0.0, output = 0.0 }
+variant = "fal-ai" # alternative: "replicate"
+
+[qwen-image.rules]
+model_choice = "model_id"
+prompt = "with_negative"
+aspect_ratio = "qwen_image"
+inference = "qwen_image"
diff --git a/api/.pipelex/inference/backends/internal.toml b/api/.pipelex/inference/backends/internal.toml
new file mode 100644
index 000000000..1503a8457
--- /dev/null
+++ b/api/.pipelex/inference/backends/internal.toml
@@ -0,0 +1,68 @@
+################################################################################
+# Internal Backend Configuration
+################################################################################
+#
+# This file defines the model specifications for internal software-only models.
+# These models run internally without external APIs or AI services.
+#
+# Configuration structure:
+# - Each model is defined in its own section with the model name as the header
+# - Model costs are in USD per million tokens (input/output)
+#
+# Managed by `pipelex update`, which refreshes this file from the kit and backs
+# up a locally edited copy to <file>.bak.<timestamp> first, so local edits will
+# not survive future runs. Declare your own models in a backend of your own.
+#
+# Documentation: https://docs.pipelex.com
+# Support: https://go.pipelex.com/discord
+#
+################################################################################
+
+################################################################################
+# MODEL DEFAULTS
+################################################################################
+
+[defaults]
+thinking_mode = "none"
+
+################################################################################
+# TEXT EXTRACTION MODELS
+################################################################################
+
+# --- PyPDFium2 Text Extractor -------------------------------------------------
+[pypdfium2-extract-pdf]
+model_type = "text_extractor"
+sdk = "pypdfium2"
+model_id = "extract-text"
+inputs = ["pdf"]
+outputs = ["pages"]
+costs = {}
+
+# --- Docling Text Extractor ---------------------------------------------------
+[docling-extract-text]
+model_type = "text_extractor"
+sdk = "docling_sdk"
+model_id = "extract-text"
+inputs = ["pdf", "image"]
+outputs = ["pages"]
+costs = {}
+
+################################################################################
+# DOCUMENT GENERATION ENGINES
+################################################################################
+#
+# The engines a PipeDocGen step prints with. Their inputs are the sources they
+# print from: "layout" is the auto-layout of the step's inputs, "html" an HTML
+# template, "template_file" an office template file. Their outputs are the
+# formats they print. reportlab-pdf is built into Pipelex. The other engines
+# come with the Pipelex document generation plugin, pipelex-doc-gen, which
+# declares them itself when it loads: they are never listed in this file.
+
+# --- ReportLab PDF ------------------------------------------------------------
+[reportlab-pdf]
+model_type = "doc_gen"
+sdk = "reportlab"
+model_id = "print-pdf"
+inputs = ["layout"]
+outputs = ["pdf"]
+costs = {}
diff --git a/api/.pipelex/inference/backends/linkup.toml b/api/.pipelex/inference/backends/linkup.toml
new file mode 100644
index 000000000..73ba1d78c
--- /dev/null
+++ b/api/.pipelex/inference/backends/linkup.toml
@@ -0,0 +1,49 @@
+################################################################################
+# Linkup Backend Configuration
+################################################################################
+#
+# This file defines the model specifications for Linkup search models.
+# Linkup provides web search capabilities with sourced answers and structured
+# data extraction.
+#
+# Documentation: https://docs.pipelex.com
+# Support: https://go.pipelex.com/discord
+#
+################################################################################
+
+################################################################################
+# MODEL DEFAULTS
+################################################################################
+
+[defaults]
+model_type = "search"
+sdk = "linkup"
+thinking_mode = "none"
+
+################################################################################
+# SEARCH MODELS
+################################################################################
+
+["linkup-standard"]
+model_id = "standard"
+inputs = ["text"]
+outputs = ["sourced-answers", "structured"]
+costs = { input = 0.005, output = 0 }
+
+["linkup-deep"]
+model_id = "deep"
+inputs = ["text"]
+outputs = ["sourced-answers", "structured"]
+costs = { input = 0.05, output = 0 }
+
+################################################################################
+# FETCH / EXTRACT MODELS
+################################################################################
+
+["linkup-fetch"]
+model_type = "text_extractor"
+sdk = "linkup_fetch"
+model_id = "fetch"
+inputs = ["web_page"]
+outputs = ["pages"]
+costs = { input = 0.005, output = 0 }
diff --git a/api/.pipelex/inference/backends/minimax.toml b/api/.pipelex/inference/backends/minimax.toml
new file mode 100644
index 000000000..2f4998a8a
--- /dev/null
+++ b/api/.pipelex/inference/backends/minimax.toml
@@ -0,0 +1,77 @@
+################################################################################
+# MiniMax Backend Configuration
+################################################################################
+#
+# This file defines the model specifications for MiniMax models.
+# It contains model definitions for MiniMax language models
+# accessible through the MiniMax Anthropic-compatible API.
+#
+# Configuration structure:
+# - Each model is defined in its own section with the model name as the header
+# - Headers with dots must be quoted (e.g., ["minimax-m2.1"])
+# - Model costs are in USD per million tokens (input/output)
+#
+# Documentation: https://docs.pipelex.com
+# Support: https://go.pipelex.com/discord
+#
+################################################################################
+
+################################################################################
+# MODEL DEFAULTS
+################################################################################
+
+[defaults]
+model_type = "llm"
+sdk = "anthropic"
+structure_method = "instructor/anthropic_tools"
+thinking_mode = "manual"
+max_tokens = 16384
+
+################################################################################
+# LANGUAGE MODELS
+################################################################################
+
+# --- MiniMax M2 Series --------------------------------------------------------
+[minimax-m2]
+model_id = "MiniMax-M2"
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.3, output = 1.2 }
+
+["minimax-m2.1"]
+model_id = "MiniMax-M2.1"
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.3, output = 1.2 }
+
+["minimax-m2.1-highspeed"]
+model_id = "MiniMax-M2.1-highspeed"
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.6, output = 2.4 }
+
+# --- MiniMax M2.5 Series ------------------------------------------------------
+["minimax-m2.5"]
+model_id = "MiniMax-M2.5"
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.3, output = 1.2 }
+
+["minimax-m2.5-highspeed"]
+model_id = "MiniMax-M2.5-highspeed"
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.6, output = 2.4 }
+
+# --- MiniMax M2.7 Series ------------------------------------------------------
+["minimax-m2.7"]
+model_id = "MiniMax-M2.7"
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.3, output = 1.2 }
+
+["minimax-m2.7-highspeed"]
+model_id = "MiniMax-M2.7-highspeed"
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.6, output = 2.4 }
diff --git a/api/.pipelex/inference/backends/mistral.toml b/api/.pipelex/inference/backends/mistral.toml
new file mode 100644
index 000000000..f4866ac56
--- /dev/null
+++ b/api/.pipelex/inference/backends/mistral.toml
@@ -0,0 +1,235 @@
+################################################################################
+# Mistral Backend Configuration
+################################################################################
+#
+# This file defines the model specifications for Mistral AI models.
+# It contains model definitions for various Mistral language models and specialized models
+# accessible through the Mistral API.
+#
+# Configuration structure:
+# - Each model is defined in its own section with the model name as the header
+# - Headers with dots must be quoted (e.g., ["ministral-3b"])
+# - Model costs are in USD per million tokens (input/output)
+#
+# Documentation: https://docs.pipelex.com
+# Support: https://go.pipelex.com/discord
+#
+################################################################################
+
+################################################################################
+# MODEL DEFAULTS
+################################################################################
+
+[defaults]
+model_type = "llm"
+sdk = "mistral"
+structure_method = "instructor/mistral_tools"
+thinking_mode = "none"
+
+################################################################################
+# LANGUAGE MODELS
+################################################################################
+
+# --- Ministral Series ---------------------------------------------------------
+[ministral-3b]
+model_id = "ministral-3b-latest"
+max_tokens = 131072
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.04, output = 0.04 }
+
+[ministral-8b]
+model_id = "ministral-8b-latest"
+max_tokens = 131072
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.1, output = 0.1 }
+
+# --- Mistral 7B Series --------------------------------------------------------
+[mistral-7b-2312]
+model_id = "mistral-large-2402"
+max_tokens = 32768
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.25, output = 0.25 }
+
+# --- Mistral 8x7B Series ------------------------------------------------------
+[mistral-8x7b-2312]
+model_id = "open-mixtral-8x7b"
+max_tokens = 32768
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 0.7, output = 0.7 }
+
+# --- Mistral Codestral Series -------------------------------------------------
+[mistral-codestral-2405]
+model_id = "codestral-2405"
+max_tokens = 262144
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 1.0, output = 3.0 }
+
+# --- Pixtral Series -----------------------------------------------------------
+[pixtral-12b]
+model_id = "pixtral-12b-latest"
+max_tokens = 131072
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 0.15, output = 0.15 }
+
+[pixtral-large]
+model_id = "pixtral-large-latest"
+max_tokens = 131072
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 2.0, output = 6.0 }
+
+# --- Mistral Small Series -----------------------------------------------------
+[mistral-small-2506]
+model_id = "mistral-small-2506"
+max_tokens = 128000
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.1, output = 0.3 }
+
+["mistral-small-3.2"]
+model_id = "mistral-small-2506"
+max_tokens = 128000
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.1, output = 0.3 }
+
+[mistral-small-2603]
+model_id = "mistral-small-2603"
+max_tokens = 256000
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 0.15, output = 0.60 }
+thinking_mode = "manual"
+
+["mistral-small-4"]
+model_id = "mistral-small-2603"
+max_tokens = 256000
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 0.15, output = 0.60 }
+thinking_mode = "manual"
+
+[mistral-small]
+model_id = "mistral-small-latest"
+max_tokens = 256000
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 0.15, output = 0.60 }
+thinking_mode = "manual"
+
+# --- Mistral Medium Series ----------------------------------------------------
+[mistral-medium-2508]
+model_id = "mistral-medium-2508"
+max_tokens = 128000
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+costs = { input = 0.4, output = 2.0 }
+
+["mistral-medium-3.1"]
+model_id = "mistral-medium-2508"
+max_tokens = 128000
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+costs = { input = 0.4, output = 2.0 }
+
+[mistral-medium]
+model_id = "mistral-medium-latest"
+max_tokens = 128000
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+costs = { input = 0.4, output = 2.0 }
+
+# --- Mistral Large Series -----------------------------------------------------
+[mistral-large-2512]
+model_id = "mistral-large-2512"
+max_tokens = 256000
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+costs = { input = 0.5, output = 1.5 }
+
+[mistral-large-3]
+model_id = "mistral-large-2512"
+max_tokens = 256000
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+costs = { input = 0.5, output = 1.5 }
+
+[mistral-large]
+model_id = "mistral-large-latest"
+max_tokens = 256000
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+costs = { input = 0.5, output = 1.5 }
+
+# --- Magistral Series (reasoning models) ------------------------------------
+[magistral-small-2509]
+model_id = "magistral-small-2509"
+max_tokens = 128000
+inputs = ["text", "pdf"]
+outputs = ["text"]
+costs = { input = 0.5, output = 1.5 }
+thinking_mode = "manual"
+
+[magistral-small]
+model_id = "magistral-small-latest"
+max_tokens = 128000
+inputs = ["text", "pdf"]
+outputs = ["text"]
+costs = { input = 0.5, output = 1.5 }
+thinking_mode = "manual"
+
+[magistral-medium-2509]
+model_id = "magistral-medium-2509"
+max_tokens = 128000
+inputs = ["text", "pdf"]
+outputs = ["text"]
+costs = { input = 2, output = 5 }
+thinking_mode = "manual"
+
+[magistral-medium]
+model_id = "magistral-medium-latest"
+max_tokens = 128000
+inputs = ["text", "pdf"]
+outputs = ["text"]
+costs = { input = 2, output = 5 }
+thinking_mode = "manual"
+
+################################################################################
+# EXTRACTION MODELS
+################################################################################
+
+# TODO: add support to pricing per page
+
+[mistral-ocr-2503]
+model_type = "text_extractor"
+model_id = "mistral-ocr-2503"
+max_tokens = 16384
+inputs = ["pdf", "image"]
+outputs = ["pages"]
+
+[mistral-ocr-2505]
+model_type = "text_extractor"
+model_id = "mistral-ocr-2505"
+max_tokens = 16384
+inputs = ["pdf", "image"]
+outputs = ["pages"]
+
+[mistral-ocr-2512]
+model_type = "text_extractor"
+model_id = "mistral-ocr-2512"
+max_tokens = 16384
+inputs = ["pdf", "image"]
+outputs = ["pages"]
+
+[mistral-ocr]
+model_type = "text_extractor"
+model_id = "mistral-ocr-latest"
+max_tokens = 16384
+inputs = ["pdf", "image"]
+outputs = ["pages"]
diff --git a/api/.pipelex/inference/backends/ollama.toml b/api/.pipelex/inference/backends/ollama.toml
new file mode 100644
index 000000000..3828f43da
--- /dev/null
+++ b/api/.pipelex/inference/backends/ollama.toml
@@ -0,0 +1,63 @@
+################################################################################
+# Ollama Backend Configuration
+################################################################################
+#
+# This file defines the model specifications for Ollama models.
+# It contains model definitions for local language models
+# accessible through the Ollama API.
+#
+# Configuration structure:
+# - Each model is defined in its own section with the model name as the header
+# - Headers with dots must be quoted (e.g., ["mistral-small3.1-24b"])
+# - Model costs are in USD per million tokens (input/output)
+#
+# Documentation: https://docs.pipelex.com
+# Support: https://go.pipelex.com/discord
+#
+################################################################################
+
+################################################################################
+# MODEL DEFAULTS
+################################################################################
+
+[defaults]
+model_type = "llm"
+sdk = "openai"
+structure_method = "instructor/openai_tools"
+thinking_mode = "none"
+
+################################################################################
+# LANGUAGE MODELS
+################################################################################
+
+# --- Gemma Models -------------------------------------------------------------
+[gemma3-4b]
+model_id = "gemma3:4b"
+inputs = ["text"]
+outputs = ["text"]
+max_prompt_images = 3000
+costs = { input = 0, output = 0 }
+
+# --- Llama Models -------------------------------------------------------------
+[llama4-scout]
+model_id = "llama4:scout"
+inputs = ["text"]
+outputs = ["text"]
+max_prompt_images = 3000
+costs = { input = 0, output = 0 }
+
+# --- Mistral Models -----------------------------------------------------------
+["mistral-small3.1-24b"]
+model_id = "mistral-small3.1:24b"
+inputs = ["text"]
+outputs = ["text"]
+max_prompt_images = 3000
+costs = { input = 0, output = 0 }
+
+# --- Qwen Models --------------------------------------------------------------
+[qwen3-8b]
+model_id = "qwen3:8b"
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 0, output = 0 }
+# TODO: support <think> tokens
diff --git a/api/.pipelex/inference/backends/openai.toml b/api/.pipelex/inference/backends/openai.toml
new file mode 100644
index 000000000..1bea020e0
--- /dev/null
+++ b/api/.pipelex/inference/backends/openai.toml
@@ -0,0 +1,220 @@
+################################################################################
+# OpenAI Backend Configuration
+################################################################################
+#
+# This file defines the model specifications for OpenAI models.
+# It contains model definitions for various LLM and image generation models
+# accessible through the OpenAI API.
+#
+# Configuration structure:
+# - Each model is defined in its own section with the model name as the header
+# - Headers with dots must be quoted (e.g., ["gpt-5.4"])
+# - Model costs are in USD per million tokens (input/output)
+#
+# Documentation: https://docs.pipelex.com
+# Support: https://go.pipelex.com/discord
+#
+################################################################################
+
+################################################################################
+# MODEL DEFAULTS
+################################################################################
+
+[defaults]
+model_type = "llm"
+sdk = "openai_responses"
+structure_method = "instructor/openai_responses_tools"
+thinking_mode = "none"
+
+################################################################################
+# LANGUAGE MODELS
+################################################################################
+
+# --- GPT-4o Series ------------------------------------------------------------
+[gpt-4o]
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+costs = { input = 2.5, output = 10.0 }
+
+[gpt-4o-mini]
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+costs = { input = 0.15, output = 0.6 }
+
+# --- GPT-5.3 Series -------------------------------------------------------------
+["gpt-5.3-codex"]
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+costs = { input = 1.75, output = 14.0 }
+valued_constraints = { fixed_temperature = 1 }
+thinking_mode = "manual"
+
+# --- GPT-5.4 Series -----------------------------------------------------------
+["gpt-5.4"]
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+costs = { input = 2.5, output = 15.0 }
+thinking_mode = "manual"
+
+["gpt-5.4-pro"]
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+costs = { input = 30.0, output = 180.0 }
+valued_constraints = { fixed_temperature = 1 }
+thinking_mode = "manual"
+
+["gpt-5.4-mini"]
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+costs = { input = 0.75, output = 4.5 }
+thinking_mode = "manual"
+
+["gpt-5.4-nano"]
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+costs = { input = 0.2, output = 1.25 }
+thinking_mode = "manual"
+
+# --- GPT-5.5 Series -----------------------------------------------------------
+["gpt-5.5"]
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+costs = { input = 5.0, output = 30.0 }
+valued_constraints = { fixed_temperature = 1 }
+thinking_mode = "manual"
+
+# --- GPT-5.6 Series -----------------------------------------------------------
+["gpt-5.6-sol"]
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+costs = { input = 4.0, output = 20.0 }
+valued_constraints = { fixed_temperature = 1 }
+thinking_mode = "manual"
+
+["gpt-5.6-terra"]
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+costs = { input = 2.0, output = 12.0 }
+valued_constraints = { fixed_temperature = 1 }
+thinking_mode = "manual"
+
+["gpt-5.6-luna"]
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+costs = { input = 0.2, output = 1.2 }
+valued_constraints = { fixed_temperature = 1 }
+thinking_mode = "manual"
+
+# --- GPT-6 Series -------------------------------------------------------------
+["gpt-6-astra"]
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+costs = { input = 10.0, output = 50.0 }
+valued_constraints = { fixed_temperature = 1 }
+thinking_mode = "manual"
+
+################################################################################
+# IMAGE GENERATION MODELS
+################################################################################
+
+# --- OpenAI Image Generation --------------------------------------------------
+[gpt-image-1]
+sdk = "openai_img_gen"
+model_type = "img_gen"
+inputs = ["text", "images"]
+outputs = ["image"]
+costs = { input = 10, output = 40 }
+
+[gpt-image-1.rules]
+model_choice = "model_id"
+prompt = "positive_only"
+num_images = "gpt_image"
+aspect_ratio = "gpt_image_legacy"
+background = "available"
+inference = "gpt_image"
+safety_checker = "openai_moderation"
+output_format = "gpt_image_legacy"
+output_compression = "gpt_image_legacy"
+input_images = "gpt_image"
+input_fidelity = "gpt_image_legacy"
+
+[gpt-image-1-mini]
+sdk = "openai_img_gen"
+model_type = "img_gen"
+inputs = ["text", "images"]
+outputs = ["image"]
+costs = { input = 2.5, output = 8 }
+
+[gpt-image-1-mini.rules]
+model_choice = "model_id"
+prompt = "positive_only"
+num_images = "gpt_image"
+aspect_ratio = "gpt_image_legacy"
+background = "available"
+inference = "gpt_image"
+safety_checker = "openai_moderation"
+output_format = "gpt_image_legacy"
+output_compression = "gpt_image_legacy"
+input_images = "gpt_image"
+input_fidelity = "gpt_image_legacy"
+
+["gpt-image-1.5"]
+sdk = "openai_img_gen"
+model_type = "img_gen"
+model_id = "gpt-image-1.5"
+inputs = ["text", "images"]
+outputs = ["image"]
+costs = { input = 8, output = 32 }
+
+["gpt-image-1.5".rules]
+model_choice = "model_id"
+prompt = "positive_only"
+num_images = "gpt_image"
+aspect_ratio = "gpt_image_legacy"
+background = "available"
+inference = "gpt_image"
+safety_checker = "openai_moderation"
+output_format = "gpt_image_legacy"
+output_compression = "gpt_image_legacy"
+input_images = "gpt_image"
+input_fidelity = "gpt_image_legacy"
+
+[gpt-image-2-2026-04-21]
+sdk = "openai_img_gen"
+model_type = "img_gen"
+inputs = ["text", "images"]
+outputs = ["image"]
+costs = { input = 8, output = 30 }
+
+[gpt-image-2-2026-04-21.rules]
+model_choice = "model_id"
+prompt = "positive_only"
+num_images = "gpt_image"
+aspect_ratio = "gpt_image_2"
+background = "unavailable"
+inference = "gpt_image"
+safety_checker = "unavailable"
+output_format = "unavailable"
+output_compression = "unavailable"
+input_images = "gpt_image"
+input_fidelity = "unavailable"
+
+[gpt-image-2]
+sdk = "openai_img_gen"
+model_type = "img_gen"
+inputs = ["text", "images"]
+outputs = ["image"]
+costs = { input = 8, output = 30 }
+
+[gpt-image-2.rules]
+model_choice = "model_id"
+prompt = "positive_only"
+num_images = "gpt_image"
+aspect_ratio = "gpt_image_2"
+background = "unavailable"
+inference = "gpt_image"
+safety_checker = "unavailable"
+output_format = "unavailable"
+output_compression = "unavailable"
+input_images = "gpt_image"
+input_fidelity = "unavailable"
diff --git a/api/.pipelex/inference/backends/openrouter.toml b/api/.pipelex/inference/backends/openrouter.toml
new file mode 100644
index 000000000..48fe657c5
--- /dev/null
+++ b/api/.pipelex/inference/backends/openrouter.toml
@@ -0,0 +1,2263 @@
+################################################################################
+# OpenRouter Backend Configuration
+################################################################################
+#
+# This file defines the model specifications for OpenRouter models.
+# It contains model definitions for various LLM and image generation models
+# accessible through the OpenRouter API.
+#
+# Configuration structure:
+# - Each model is defined in its own section with the model name as the header
+# - Headers with dots or colons must be quoted (e.g., ["anthropic/claude-3.5-sonnet"])
+# - Model costs are in USD per million tokens (input/output)
+#
+# Documentation: https://docs.pipelex.com
+# Support: https://go.pipelex.com/discord
+#
+################################################################################
+
+################################################################################
+# MODEL DEFAULTS
+################################################################################
+
+[defaults]
+model_type = "llm"
+sdk = "openai"
+structure_method = "instructor/openai_tools"
+thinking_mode = "none"
+
+################################################################################
+# LANGUAGE MODELS
+################################################################################
+
+# --- ai21 ----------------------------------------------------------------
+
+["ai21/jamba-large-1.7"]
+max_tokens = 256000
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 2, output = 8 }
+
+# --- aion-labs -----------------------------------------------------------
+
+["aion-labs/aion-1.0"]
+max_tokens = 131072
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 4, output = 8 }
+
+["aion-labs/aion-1.0-mini"]
+max_tokens = 131072
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 0.7, output = 1.4 }
+
+["aion-labs/aion-rp-llama-3.1-8b"]
+max_tokens = 32768
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 0.8, output = 1.6 }
+
+# --- alfredpros ----------------------------------------------------------
+
+["alfredpros/codellama-7b-instruct-solidity"]
+max_tokens = 4096
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 0.8, output = 1.2 }
+
+# --- alibaba -------------------------------------------------------------
+
+["alibaba/tongyi-deepresearch-30b-a3b"]
+max_tokens = 131072
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.09, output = 0.45 }
+
+# --- allenai -------------------------------------------------------------
+
+["allenai/molmo-2-8b"]
+max_tokens = 36864
+inputs = ["text", "images", "video"]
+outputs = ["text"]
+costs = { input = 0.2, output = 0.2 }
+
+["allenai/olmo-2-0325-32b-instruct"]
+max_tokens = 128000
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 0.05, output = 0.2 }
+
+["allenai/olmo-3-32b-think"]
+max_tokens = 65536
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 0.15, output = 0.5 }
+
+["allenai/olmo-3-7b-instruct"]
+max_tokens = 65536
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 0.1, output = 0.2 }
+
+["allenai/olmo-3-7b-think"]
+max_tokens = 65536
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 0.12, output = 0.2 }
+
+["allenai/olmo-3.1-32b-instruct"]
+max_tokens = 65536
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.2, output = 0.6 }
+
+["allenai/olmo-3.1-32b-think"]
+max_tokens = 65536
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 0.15, output = 0.5 }
+
+# --- alpindale -----------------------------------------------------------
+
+["alpindale/goliath-120b"]
+max_tokens = 6144
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 3.75, output = 7.5 }
+
+# --- amazon --------------------------------------------------------------
+
+["amazon/nova-2-lite-v1"]
+max_tokens = 1000000
+inputs = ["text", "images", "video", "pdf"]
+outputs = ["text", "structured"]
+costs = { input = 0.3, output = 2.5 }
+
+["amazon/nova-lite-v1"]
+max_tokens = 300000
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 0.06, output = 0.24 }
+
+["amazon/nova-micro-v1"]
+max_tokens = 128000
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.035, output = 0.14 }
+
+["amazon/nova-premier-v1"]
+max_tokens = 1000000
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 2.5, output = 12.5 }
+
+["amazon/nova-pro-v1"]
+max_tokens = 300000
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 0.8, output = 3.2 }
+
+# --- anthracite-org ------------------------------------------------------
+
+["anthracite-org/magnum-v4-72b"]
+max_tokens = 16384
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 3, output = 5 }
+
+# --- anthropic -----------------------------------------------------------
+
+["anthropic/claude-3-haiku"]
+max_tokens = 200000
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 0.25, output = 1.25 }
+
+["anthropic/claude-3.5-haiku"]
+max_tokens = 200000
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 0.8, output = 4 }
+
+["anthropic/claude-3.5-sonnet"]
+max_tokens = 200000
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+costs = { input = 6, output = 30 }
+
+["anthropic/claude-3.7-sonnet"]
+max_tokens = 200000
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+costs = { input = 3, output = 15 }
+
+["anthropic/claude-3.7-sonnet:thinking"]
+max_tokens = 200000
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+costs = { input = 3, output = 15 }
+
+["anthropic/claude-haiku-4.5"]
+max_tokens = 200000
+inputs = ["images", "text"]
+outputs = ["text", "structured"]
+costs = { input = 1, output = 5 }
+
+["anthropic/claude-opus-4"]
+max_tokens = 200000
+inputs = ["images", "text", "pdf"]
+outputs = ["text", "structured"]
+costs = { input = 15, output = 75 }
+
+["anthropic/claude-opus-4.1"]
+max_tokens = 200000
+inputs = ["images", "text", "pdf"]
+outputs = ["text", "structured"]
+costs = { input = 15, output = 75 }
+
+["anthropic/claude-opus-4.5"]
+max_tokens = 200000
+inputs = ["pdf", "images", "text"]
+outputs = ["text", "structured"]
+costs = { input = 5, output = 25 }
+
+["anthropic/claude-opus-4.6"]
+max_tokens = 1000000
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 5, output = 25 }
+
+["anthropic/claude-sonnet-4"]
+max_tokens = 1000000
+inputs = ["images", "text", "pdf"]
+outputs = ["text", "structured"]
+costs = { input = 3, output = 15 }
+
+["anthropic/claude-sonnet-4.5"]
+max_tokens = 1000000
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+costs = { input = 3, output = 15 }
+
+["anthropic/claude-sonnet-4.6"]
+max_tokens = 1000000
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 3, output = 15 }
+
+# --- arcee-ai ------------------------------------------------------------
+
+["arcee-ai/coder-large"]
+max_tokens = 32768
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 0.5, output = 0.8 }
+
+["arcee-ai/maestro-reasoning"]
+max_tokens = 131072
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 0.9, output = 3.3 }
+
+["arcee-ai/spotlight"]
+max_tokens = 131072
+inputs = ["images", "text"]
+outputs = ["text"]
+costs = { input = 0.18, output = 0.18 }
+
+["arcee-ai/trinity-large-preview:free"]
+max_tokens = 131000
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0, output = 0 }
+
+["arcee-ai/trinity-mini"]
+max_tokens = 131072
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.045, output = 0.15 }
+
+["arcee-ai/trinity-mini:free"]
+max_tokens = 131072
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0, output = 0 }
+
+["arcee-ai/virtuoso-large"]
+max_tokens = 131072
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.75, output = 1.2 }
+
+# --- baidu ---------------------------------------------------------------
+
+["baidu/ernie-4.5-21b-a3b"]
+max_tokens = 120000
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.07, output = 0.28 }
+
+["baidu/ernie-4.5-21b-a3b-thinking"]
+max_tokens = 131072
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 0.07, output = 0.28 }
+
+["baidu/ernie-4.5-300b-a47b"]
+max_tokens = 123000
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 0.28, output = 1.1 }
+
+["baidu/ernie-4.5-vl-28b-a3b"]
+max_tokens = 30000
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 0.14, output = 0.56 }
+
+["baidu/ernie-4.5-vl-424b-a47b"]
+max_tokens = 123000
+inputs = ["images", "text"]
+outputs = ["text"]
+costs = { input = 0.42, output = 1.25 }
+
+# --- bytedance -----------------------------------------------------------
+
+["bytedance/ui-tars-1.5-7b"]
+max_tokens = 128000
+inputs = ["images", "text"]
+outputs = ["text"]
+costs = { input = 0.1, output = 0.2 }
+
+# --- bytedance-seed ------------------------------------------------------
+
+["bytedance-seed/seed-1.6"]
+max_tokens = 262144
+inputs = ["images", "text", "video"]
+outputs = ["text", "structured"]
+costs = { input = 0.25, output = 2 }
+
+["bytedance-seed/seed-1.6-flash"]
+max_tokens = 262144
+inputs = ["images", "text", "video"]
+outputs = ["text", "structured"]
+costs = { input = 0.075, output = 0.3 }
+
+# --- cognitivecomputations -----------------------------------------------
+
+["cognitivecomputations/dolphin-mistral-24b-venice-edition:free"]
+max_tokens = 32768
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 0, output = 0 }
+
+# --- cohere --------------------------------------------------------------
+
+["cohere/command-a"]
+max_tokens = 256000
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 2.5, output = 10 }
+
+["cohere/command-r-08-2024"]
+max_tokens = 128000
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.15, output = 0.6 }
+
+["cohere/command-r-plus-08-2024"]
+max_tokens = 128000
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 2.5, output = 10 }
+
+["cohere/command-r7b-12-2024"]
+max_tokens = 128000
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 0.0375, output = 0.15 }
+
+# --- deepcogito ----------------------------------------------------------
+
+["deepcogito/cogito-v2.1-671b"]
+max_tokens = 128000
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 1.25, output = 1.25 }
+
+# --- deepseek ------------------------------------------------------------
+
+["deepseek/deepseek-chat"]
+max_tokens = 163840
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.32, output = 0.89 }
+
+["deepseek/deepseek-chat-v3-0324"]
+max_tokens = 163840
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.19, output = 0.87 }
+
+["deepseek/deepseek-chat-v3.1"]
+max_tokens = 32768
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.15, output = 0.75 }
+
+["deepseek/deepseek-r1"]
+max_tokens = 64000
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.7, output = 2.5 }
+
+["deepseek/deepseek-r1-0528"]
+max_tokens = 163840
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.4, output = 1.75 }
+
+["deepseek/deepseek-r1-0528:free"]
+max_tokens = 163840
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 0, output = 0 }
+
+["deepseek/deepseek-r1-distill-llama-70b"]
+max_tokens = 131072
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 0.7, output = 0.8 }
+
+["deepseek/deepseek-r1-distill-qwen-32b"]
+max_tokens = 32768
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 0.29, output = 0.29 }
+
+["deepseek/deepseek-v3.1-terminus"]
+max_tokens = 163840
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.21, output = 0.79 }
+
+["deepseek/deepseek-v3.1-terminus:exacto"]
+max_tokens = 163840
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.21, output = 0.79 }
+
+["deepseek/deepseek-v3.2"]
+max_tokens = 163840
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.26, output = 0.38 }
+
+["deepseek/deepseek-v3.2-exp"]
+max_tokens = 163840
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.27, output = 0.41 }
+
+["deepseek/deepseek-v3.2-speciale"]
+max_tokens = 163840
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 0.4, output = 1.2 }
+
+# --- eleutherai ----------------------------------------------------------
+
+["eleutherai/llemma_7b"]
+max_tokens = 4096
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 0.8, output = 1.2 }
+
+# --- essentialai ---------------------------------------------------------
+
+["essentialai/rnj-1-instruct"]
+max_tokens = 32768
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 0.15, output = 0.15 }
+
+# --- google --------------------------------------------------------------
+
+["google/gemini-2.0-flash-001"]
+max_tokens = 1048576
+inputs = ["text", "images", "pdf", "audio", "video"]
+outputs = ["text", "structured"]
+costs = { input = 0.1, output = 0.4 }
+
+["google/gemini-2.0-flash-lite-001"]
+max_tokens = 1048576
+inputs = ["text", "images", "pdf", "audio", "video"]
+outputs = ["text", "structured"]
+costs = { input = 0.075, output = 0.3 }
+
+["google/gemini-2.5-flash"]
+max_tokens = 1048576
+inputs = ["pdf", "images", "text", "audio", "video"]
+outputs = ["text", "structured"]
+costs = { input = 0.3, output = 2.5 }
+
+["google/gemini-2.5-flash-lite"]
+max_tokens = 1048576
+inputs = ["text", "images", "pdf", "audio", "video"]
+outputs = ["text", "structured"]
+costs = { input = 0.1, output = 0.4 }
+
+["google/gemini-2.5-flash-lite-preview-09-2025"]
+max_tokens = 1048576
+inputs = ["text", "images", "pdf", "audio", "video"]
+outputs = ["text", "structured"]
+costs = { input = 0.1, output = 0.4 }
+
+["google/gemini-2.5-pro"]
+max_tokens = 1048576
+inputs = ["text", "images", "pdf", "audio", "video"]
+outputs = ["text", "structured"]
+costs = { input = 1.25, output = 10 }
+
+["google/gemini-2.5-pro-preview"]
+max_tokens = 1048576
+inputs = ["pdf", "images", "text", "audio"]
+outputs = ["text", "structured"]
+costs = { input = 1.25, output = 10 }
+
+["google/gemini-2.5-pro-preview-05-06"]
+max_tokens = 1048576
+inputs = ["text", "images", "pdf", "audio", "video"]
+outputs = ["text", "structured"]
+costs = { input = 1.25, output = 10 }
+
+["google/gemini-3-flash-preview"]
+max_tokens = 1048576
+inputs = ["text", "images", "pdf", "audio", "video"]
+outputs = ["text", "structured"]
+costs = { input = 0.5, output = 3 }
+
+["google/gemini-3.1-pro-preview"]
+max_tokens = 1048576
+inputs = ["audio", "pdf", "images", "text", "video"]
+outputs = ["text", "structured"]
+costs = { input = 2, output = 12 }
+
+["google/gemma-2-27b-it"]
+max_tokens = 8192
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 0.65, output = 0.65 }
+
+["google/gemma-2-9b-it"]
+max_tokens = 8192
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 0.03, output = 0.09 }
+
+["google/gemma-3-12b-it"]
+max_tokens = 131072
+inputs = ["text", "images"]
+outputs = ["text"]
+costs = { input = 0.04, output = 0.13 }
+
+["google/gemma-3-12b-it:free"]
+max_tokens = 32768
+inputs = ["text", "images"]
+outputs = ["text"]
+costs = { input = 0, output = 0 }
+
+["google/gemma-3-27b-it"]
+max_tokens = 128000
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 0.04, output = 0.15 }
+
+["google/gemma-3-27b-it:free"]
+max_tokens = 131072
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 0, output = 0 }
+
+["google/gemma-3-4b-it"]
+max_tokens = 131072
+inputs = ["text", "images"]
+outputs = ["text"]
+costs = { input = 0.04, output = 0.08 }
+
+["google/gemma-3-4b-it:free"]
+max_tokens = 32768
+inputs = ["text", "images"]
+outputs = ["text"]
+costs = { input = 0, output = 0 }
+
+["google/gemma-3n-e2b-it:free"]
+max_tokens = 8192
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 0, output = 0 }
+
+["google/gemma-3n-e4b-it"]
+max_tokens = 32768
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 0.02, output = 0.04 }
+
+["google/gemma-3n-e4b-it:free"]
+max_tokens = 8192
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 0, output = 0 }
+
+# --- gryphe --------------------------------------------------------------
+
+["gryphe/mythomax-l2-13b"]
+max_tokens = 4096
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 0.06, output = 0.06 }
+
+# --- ibm-granite ---------------------------------------------------------
+
+["ibm-granite/granite-4.0-h-micro"]
+max_tokens = 131000
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 0.017, output = 0.11 }
+
+# --- inception -----------------------------------------------------------
+
+["inception/mercury"]
+max_tokens = 128000
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.25, output = 1 }
+
+["inception/mercury-coder"]
+max_tokens = 128000
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.25, output = 1 }
+
+# --- inflection ----------------------------------------------------------
+
+["inflection/inflection-3-pi"]
+max_tokens = 8000
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 2.5, output = 10 }
+
+["inflection/inflection-3-productivity"]
+max_tokens = 8000
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 2.5, output = 10 }
+
+# --- kwaipilot -----------------------------------------------------------
+
+["kwaipilot/kat-coder-pro"]
+max_tokens = 256000
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.207, output = 0.828 }
+
+# --- liquid --------------------------------------------------------------
+
+["liquid/lfm-2.2-6b"]
+max_tokens = 32768
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 0.01, output = 0.02 }
+
+["liquid/lfm-2.5-1.2b-instruct:free"]
+max_tokens = 32768
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 0, output = 0 }
+
+["liquid/lfm-2.5-1.2b-thinking:free"]
+max_tokens = 32768
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 0, output = 0 }
+
+["liquid/lfm2-8b-a1b"]
+max_tokens = 32768
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 0.01, output = 0.02 }
+
+# --- mancer --------------------------------------------------------------
+
+["mancer/weaver"]
+max_tokens = 8000
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 0.75, output = 1 }
+
+# --- meituan -------------------------------------------------------------
+
+["meituan/longcat-flash-chat"]
+max_tokens = 131072
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 0.2, output = 0.8 }
+
+# --- meta-llama ----------------------------------------------------------
+
+["meta-llama/llama-3-70b-instruct"]
+max_tokens = 8192
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 0.51, output = 0.74 }
+
+["meta-llama/llama-3-8b-instruct"]
+max_tokens = 8192
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.03, output = 0.04 }
+
+["meta-llama/llama-3.1-405b"]
+max_tokens = 32768
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 4, output = 4 }
+
+["meta-llama/llama-3.1-405b-instruct"]
+max_tokens = 131000
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 4, output = 4 }
+
+["meta-llama/llama-3.1-70b-instruct"]
+max_tokens = 131072
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.4, output = 0.4 }
+
+["meta-llama/llama-3.1-8b-instruct"]
+max_tokens = 16384
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.02, output = 0.05 }
+
+["meta-llama/llama-3.2-11b-vision-instruct"]
+max_tokens = 131072
+inputs = ["text", "images"]
+outputs = ["text"]
+costs = { input = 0.049, output = 0.049 }
+
+["meta-llama/llama-3.2-1b-instruct"]
+max_tokens = 60000
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 0.027, output = 0.2 }
+
+["meta-llama/llama-3.2-3b-instruct"]
+max_tokens = 131072
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 0.02, output = 0.02 }
+
+["meta-llama/llama-3.2-3b-instruct:free"]
+max_tokens = 131072
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 0, output = 0 }
+
+["meta-llama/llama-3.3-70b-instruct"]
+max_tokens = 131072
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.1, output = 0.32 }
+
+["meta-llama/llama-3.3-70b-instruct:free"]
+max_tokens = 128000
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0, output = 0 }
+
+["meta-llama/llama-4-maverick"]
+max_tokens = 1048576
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 0.15, output = 0.6 }
+
+["meta-llama/llama-4-scout"]
+max_tokens = 327680
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 0.08, output = 0.3 }
+
+["meta-llama/llama-guard-2-8b"]
+max_tokens = 8192
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 0.2, output = 0.2 }
+
+["meta-llama/llama-guard-3-8b"]
+max_tokens = 131072
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 0.02, output = 0.06 }
+
+["meta-llama/llama-guard-4-12b"]
+max_tokens = 163840
+inputs = ["images", "text"]
+outputs = ["text"]
+costs = { input = 0.18, output = 0.18 }
+
+# --- microsoft -----------------------------------------------------------
+
+["microsoft/phi-4"]
+max_tokens = 16384
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 0.06, output = 0.14 }
+
+["microsoft/wizardlm-2-8x22b"]
+max_tokens = 65535
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 0.62, output = 0.62 }
+
+# --- minimax -------------------------------------------------------------
+
+["minimax/minimax-01"]
+max_tokens = 1000192
+inputs = ["text", "images"]
+outputs = ["text"]
+costs = { input = 0.2, output = 1.1 }
+
+["minimax/minimax-m1"]
+max_tokens = 1000000
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.4, output = 2.2 }
+
+["minimax/minimax-m2"]
+max_tokens = 196608
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.255, output = 1 }
+
+["minimax/minimax-m2-her"]
+max_tokens = 65536
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 0.3, output = 1.2 }
+
+["minimax/minimax-m2.1"]
+max_tokens = 196608
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.27, output = 0.95 }
+
+["minimax/minimax-m2.5"]
+max_tokens = 196608
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.3, output = 1.1 }
+
+# --- mistralai -----------------------------------------------------------
+
+["mistralai/codestral-2508"]
+max_tokens = 256000
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.3, output = 0.9 }
+
+["mistralai/devstral-2512"]
+max_tokens = 262144
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.4, output = 2 }
+
+["mistralai/devstral-medium"]
+max_tokens = 131072
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.4, output = 2 }
+
+["mistralai/devstral-small"]
+max_tokens = 131072
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.1, output = 0.3 }
+
+["mistralai/ministral-14b-2512"]
+max_tokens = 262144
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 0.2, output = 0.2 }
+
+["mistralai/ministral-3b-2512"]
+max_tokens = 131072
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 0.1, output = 0.1 }
+
+["mistralai/ministral-8b-2512"]
+max_tokens = 262144
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 0.15, output = 0.15 }
+
+["mistralai/mistral-7b-instruct"]
+max_tokens = 32768
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 0.2, output = 0.2 }
+
+["mistralai/mistral-7b-instruct-v0.1"]
+max_tokens = 2824
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 0.11, output = 0.19 }
+
+["mistralai/mistral-7b-instruct-v0.2"]
+max_tokens = 32768
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 0.2, output = 0.2 }
+
+["mistralai/mistral-7b-instruct-v0.3"]
+max_tokens = 32768
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 0.2, output = 0.2 }
+
+["mistralai/mistral-large"]
+max_tokens = 128000
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 2, output = 6 }
+
+["mistralai/mistral-large-2407"]
+max_tokens = 131072
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 2, output = 6 }
+
+["mistralai/mistral-large-2411"]
+max_tokens = 131072
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 2, output = 6 }
+
+["mistralai/mistral-large-2512"]
+max_tokens = 262144
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 0.5, output = 1.5 }
+
+["mistralai/mistral-medium-3"]
+max_tokens = 131072
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 0.4, output = 2 }
+
+["mistralai/mistral-medium-3.1"]
+max_tokens = 131072
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 0.4, output = 2 }
+
+["mistralai/mistral-nemo"]
+max_tokens = 131072
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.02, output = 0.04 }
+
+["mistralai/mistral-saba"]
+max_tokens = 32768
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.2, output = 0.6 }
+
+["mistralai/mistral-small-24b-instruct-2501"]
+max_tokens = 32768
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.05, output = 0.08 }
+
+["mistralai/mistral-small-3.1-24b-instruct"]
+max_tokens = 128000
+inputs = ["text", "images"]
+outputs = ["text"]
+costs = { input = 0.35, output = 0.56 }
+
+["mistralai/mistral-small-3.1-24b-instruct:free"]
+max_tokens = 128000
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 0, output = 0 }
+
+["mistralai/mistral-small-3.2-24b-instruct"]
+max_tokens = 131072
+inputs = ["images", "text"]
+outputs = ["text", "structured"]
+costs = { input = 0.06, output = 0.18 }
+
+["mistralai/mistral-small-creative"]
+max_tokens = 32768
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.1, output = 0.3 }
+
+["mistralai/mixtral-8x22b-instruct"]
+max_tokens = 65536
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 2, output = 6 }
+
+["mistralai/mixtral-8x7b-instruct"]
+max_tokens = 32768
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.54, output = 0.54 }
+
+["mistralai/pixtral-large-2411"]
+max_tokens = 131072
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 2, output = 6 }
+
+["mistralai/voxtral-small-24b-2507"]
+max_tokens = 32000
+inputs = ["text", "audio"]
+outputs = ["text", "structured"]
+costs = { input = 0.1, output = 0.3 }
+
+# --- moonshotai ----------------------------------------------------------
+
+["moonshotai/kimi-k2"]
+max_tokens = 131072
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.5, output = 2.4 }
+
+["moonshotai/kimi-k2-0905"]
+max_tokens = 131072
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.4, output = 2 }
+
+["moonshotai/kimi-k2-0905:exacto"]
+max_tokens = 262144
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.6, output = 2.5 }
+
+["moonshotai/kimi-k2-thinking"]
+max_tokens = 131072
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.47, output = 2 }
+
+["moonshotai/kimi-k2.5"]
+max_tokens = 262144
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 0.45, output = 2.2 }
+
+# --- morph ---------------------------------------------------------------
+
+["morph/morph-v3-fast"]
+max_tokens = 81920
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 0.8, output = 1.2 }
+
+["morph/morph-v3-large"]
+max_tokens = 262144
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 0.9, output = 1.9 }
+
+# --- neversleep ----------------------------------------------------------
+
+["neversleep/llama-3.1-lumimaid-8b"]
+max_tokens = 32768
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 0.09, output = 0.6 }
+
+["neversleep/noromaid-20b"]
+max_tokens = 4096
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 1, output = 1.75 }
+
+# --- nex-agi -------------------------------------------------------------
+
+["nex-agi/deepseek-v3.1-nex-n1"]
+max_tokens = 131072
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.27, output = 1 }
+
+# --- nousresearch --------------------------------------------------------
+
+["nousresearch/hermes-2-pro-llama-3-8b"]
+max_tokens = 8192
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 0.14, output = 0.14 }
+
+["nousresearch/hermes-3-llama-3.1-405b"]
+max_tokens = 131072
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 1, output = 1 }
+
+["nousresearch/hermes-3-llama-3.1-405b:free"]
+max_tokens = 131072
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 0, output = 0 }
+
+["nousresearch/hermes-3-llama-3.1-70b"]
+max_tokens = 65536
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 0.3, output = 0.3 }
+
+["nousresearch/hermes-4-405b"]
+max_tokens = 131072
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 1, output = 3 }
+
+["nousresearch/hermes-4-70b"]
+max_tokens = 131072
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 0.13, output = 0.4 }
+
+# --- nvidia --------------------------------------------------------------
+
+["nvidia/llama-3.1-nemotron-70b-instruct"]
+max_tokens = 131072
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 1.2, output = 1.2 }
+
+["nvidia/llama-3.1-nemotron-ultra-253b-v1"]
+max_tokens = 131072
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 0.6, output = 1.8 }
+
+["nvidia/llama-3.3-nemotron-super-49b-v1.5"]
+max_tokens = 131072
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.1, output = 0.4 }
+
+["nvidia/nemotron-3-nano-30b-a3b"]
+max_tokens = 262144
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.05, output = 0.2 }
+
+["nvidia/nemotron-3-nano-30b-a3b:free"]
+max_tokens = 256000
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0, output = 0 }
+
+["nvidia/nemotron-nano-12b-v2-vl"]
+max_tokens = 131072
+inputs = ["images", "text", "video"]
+outputs = ["text"]
+costs = { input = 0.07, output = 0.2 }
+
+["nvidia/nemotron-nano-12b-v2-vl:free"]
+max_tokens = 128000
+inputs = ["images", "text", "video"]
+outputs = ["text", "structured"]
+costs = { input = 0, output = 0 }
+
+["nvidia/nemotron-nano-9b-v2"]
+max_tokens = 131072
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.04, output = 0.16 }
+
+["nvidia/nemotron-nano-9b-v2:free"]
+max_tokens = 128000
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0, output = 0 }
+
+# --- openai --------------------------------------------------------------
+
+["openai/gpt-3.5-turbo"]
+max_tokens = 16385
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.5, output = 1.5 }
+
+["openai/gpt-3.5-turbo-0613"]
+max_tokens = 4095
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 1, output = 2 }
+
+["openai/gpt-3.5-turbo-16k"]
+max_tokens = 16385
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 3, output = 4 }
+
+["openai/gpt-3.5-turbo-instruct"]
+max_tokens = 4095
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 1.5, output = 2 }
+
+["openai/gpt-4"]
+max_tokens = 8191
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 30, output = 60 }
+
+["openai/gpt-4-0314"]
+max_tokens = 8191
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 30, output = 60 }
+
+["openai/gpt-4-1106-preview"]
+max_tokens = 128000
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 10, output = 30 }
+
+["openai/gpt-4-turbo"]
+max_tokens = 128000
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 10, output = 30 }
+
+["openai/gpt-4-turbo-preview"]
+max_tokens = 128000
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 10, output = 30 }
+
+["openai/gpt-4.1"]
+max_tokens = 1047576
+inputs = ["images", "text", "pdf"]
+outputs = ["text", "structured"]
+costs = { input = 2, output = 8 }
+
+["openai/gpt-4.1-mini"]
+max_tokens = 1047576
+inputs = ["images", "text", "pdf"]
+outputs = ["text", "structured"]
+costs = { input = 0.4, output = 1.6 }
+
+["openai/gpt-4.1-nano"]
+max_tokens = 1047576
+inputs = ["images", "text", "pdf"]
+outputs = ["text", "structured"]
+costs = { input = 0.1, output = 0.4 }
+
+["openai/gpt-4o"]
+max_tokens = 128000
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+costs = { input = 2.5, output = 10 }
+
+["openai/gpt-4o-2024-05-13"]
+max_tokens = 128000
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+costs = { input = 5, output = 15 }
+
+["openai/gpt-4o-2024-08-06"]
+max_tokens = 128000
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+costs = { input = 2.5, output = 10 }
+
+["openai/gpt-4o-2024-11-20"]
+max_tokens = 128000
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+costs = { input = 2.5, output = 10 }
+
+["openai/gpt-4o-audio-preview"]
+max_tokens = 128000
+inputs = ["audio", "text"]
+outputs = ["text", "audio", "structured"]
+costs = { input = 2.5, output = 10 }
+
+["openai/gpt-4o-mini"]
+max_tokens = 128000
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+costs = { input = 0.15, output = 0.6 }
+
+["openai/gpt-4o-mini-2024-07-18"]
+max_tokens = 128000
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+costs = { input = 0.15, output = 0.6 }
+
+["openai/gpt-4o-mini-search-preview"]
+max_tokens = 128000
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 0.15, output = 0.6 }
+
+["openai/gpt-4o-search-preview"]
+max_tokens = 128000
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 2.5, output = 10 }
+
+["openai/gpt-4o:extended"]
+max_tokens = 128000
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+costs = { input = 6, output = 18 }
+
+["openai/gpt-5"]
+max_tokens = 400000
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+costs = { input = 1.25, output = 10 }
+
+["openai/gpt-5-chat"]
+max_tokens = 128000
+inputs = ["pdf", "images", "text"]
+outputs = ["text"]
+costs = { input = 1.25, output = 10 }
+
+["openai/gpt-5-codex"]
+max_tokens = 400000
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 1.25, output = 10 }
+
+["openai/gpt-5-mini"]
+max_tokens = 400000
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+costs = { input = 0.25, output = 2 }
+
+["openai/gpt-5-nano"]
+max_tokens = 400000
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+costs = { input = 0.05, output = 0.4 }
+
+["openai/gpt-5-pro"]
+max_tokens = 400000
+inputs = ["images", "text", "pdf"]
+outputs = ["text", "structured"]
+costs = { input = 15, output = 120 }
+
+["openai/gpt-5.1"]
+max_tokens = 400000
+inputs = ["images", "text", "pdf"]
+outputs = ["text", "structured"]
+costs = { input = 1.25, output = 10 }
+
+["openai/gpt-5.1-chat"]
+max_tokens = 128000
+inputs = ["pdf", "images", "text"]
+outputs = ["text", "structured"]
+costs = { input = 1.25, output = 10 }
+
+["openai/gpt-5.1-codex"]
+max_tokens = 400000
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 1.25, output = 10 }
+
+["openai/gpt-5.1-codex-max"]
+max_tokens = 400000
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 1.25, output = 10 }
+
+["openai/gpt-5.1-codex-mini"]
+max_tokens = 400000
+inputs = ["images", "text"]
+outputs = ["text", "structured"]
+costs = { input = 0.25, output = 2 }
+
+["openai/gpt-5.2"]
+max_tokens = 400000
+inputs = ["pdf", "images", "text"]
+outputs = ["text", "structured"]
+costs = { input = 1.75, output = 14 }
+
+["openai/gpt-5.2-chat"]
+max_tokens = 128000
+inputs = ["pdf", "images", "text"]
+outputs = ["text", "structured"]
+costs = { input = 1.75, output = 14 }
+
+["openai/gpt-5.2-codex"]
+max_tokens = 400000
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 1.75, output = 14 }
+
+["openai/gpt-5.2-pro"]
+max_tokens = 400000
+inputs = ["images", "text", "pdf"]
+outputs = ["text", "structured"]
+costs = { input = 21, output = 168 }
+
+["openai/gpt-audio"]
+max_tokens = 128000
+inputs = ["text", "audio"]
+outputs = ["text", "audio"]
+costs = { input = 2.5, output = 10 }
+
+["openai/gpt-audio-mini"]
+max_tokens = 128000
+inputs = ["text", "audio"]
+outputs = ["text", "audio"]
+costs = { input = 0.6, output = 2.4 }
+
+["openai/gpt-oss-120b"]
+max_tokens = 131072
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.039, output = 0.19 }
+
+["openai/gpt-oss-120b:exacto"]
+max_tokens = 131072
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.039, output = 0.19 }
+
+["openai/gpt-oss-120b:free"]
+max_tokens = 131072
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0, output = 0 }
+
+["openai/gpt-oss-20b"]
+max_tokens = 131072
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.03, output = 0.14 }
+
+["openai/gpt-oss-20b:free"]
+max_tokens = 131072
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0, output = 0 }
+
+["openai/gpt-oss-safeguard-20b"]
+max_tokens = 131072
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.075, output = 0.3 }
+
+["openai/o1"]
+max_tokens = 200000
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+costs = { input = 15, output = 60 }
+
+["openai/o1-pro"]
+max_tokens = 200000
+inputs = ["text", "images", "pdf"]
+outputs = ["text"]
+costs = { input = 150, output = 600 }
+
+["openai/o3"]
+max_tokens = 200000
+inputs = ["images", "text", "pdf"]
+outputs = ["text", "structured"]
+costs = { input = 2, output = 8 }
+
+["openai/o3-deep-research"]
+max_tokens = 200000
+inputs = ["images", "text", "pdf"]
+outputs = ["text", "structured"]
+costs = { input = 10, output = 40 }
+
+["openai/o3-mini"]
+max_tokens = 200000
+inputs = ["text", "pdf"]
+outputs = ["text", "structured"]
+costs = { input = 1.1, output = 4.4 }
+
+["openai/o3-mini-high"]
+max_tokens = 200000
+inputs = ["text", "pdf"]
+outputs = ["text", "structured"]
+costs = { input = 1.1, output = 4.4 }
+
+["openai/o3-pro"]
+max_tokens = 200000
+inputs = ["text", "pdf", "images"]
+outputs = ["text", "structured"]
+costs = { input = 20, output = 80 }
+
+["openai/o4-mini"]
+max_tokens = 200000
+inputs = ["images", "text", "pdf"]
+outputs = ["text", "structured"]
+costs = { input = 1.1, output = 4.4 }
+
+["openai/o4-mini-deep-research"]
+max_tokens = 200000
+inputs = ["pdf", "images", "text"]
+outputs = ["text", "structured"]
+costs = { input = 2, output = 8 }
+
+["openai/o4-mini-high"]
+max_tokens = 200000
+inputs = ["images", "text", "pdf"]
+outputs = ["text", "structured"]
+costs = { input = 1.1, output = 4.4 }
+
+# --- opengvlab -----------------------------------------------------------
+
+["opengvlab/internvl3-78b"]
+max_tokens = 32768
+inputs = ["images", "text"]
+outputs = ["text"]
+costs = { input = 0.15, output = 0.6 }
+
+# --- openrouter ----------------------------------------------------------
+
+["openrouter/auto"]
+max_tokens = 2000000
+inputs = ["text", "images", "audio", "pdf", "video"]
+outputs = ["text", "image", "structured"]
+
+["openrouter/bodybuilder"]
+max_tokens = 128000
+inputs = ["text"]
+outputs = ["text"]
+
+["openrouter/free"]
+max_tokens = 200000
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 0, output = 0 }
+
+# --- perplexity ----------------------------------------------------------
+
+["perplexity/sonar"]
+max_tokens = 127072
+inputs = ["text", "images"]
+outputs = ["text"]
+costs = { input = 1, output = 1 }
+
+["perplexity/sonar-deep-research"]
+max_tokens = 128000
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 2, output = 8 }
+
+["perplexity/sonar-pro"]
+max_tokens = 200000
+inputs = ["text", "images"]
+outputs = ["text"]
+costs = { input = 3, output = 15 }
+
+["perplexity/sonar-pro-search"]
+max_tokens = 200000
+inputs = ["text", "images"]
+outputs = ["text"]
+costs = { input = 3, output = 15 }
+
+["perplexity/sonar-reasoning-pro"]
+max_tokens = 128000
+inputs = ["text", "images"]
+outputs = ["text"]
+costs = { input = 2, output = 8 }
+
+# --- prime-intellect -----------------------------------------------------
+
+["prime-intellect/intellect-3"]
+max_tokens = 131072
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.2, output = 1.1 }
+
+# --- qwen ----------------------------------------------------------------
+
+["qwen/qwen-2.5-72b-instruct"]
+max_tokens = 32768
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.12, output = 0.39 }
+
+["qwen/qwen-2.5-7b-instruct"]
+max_tokens = 32768
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.04, output = 0.1 }
+
+["qwen/qwen-2.5-coder-32b-instruct"]
+max_tokens = 32768
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 0.2, output = 0.2 }
+
+["qwen/qwen-2.5-vl-7b-instruct"]
+max_tokens = 32768
+inputs = ["text", "images"]
+outputs = ["text"]
+costs = { input = 0.2, output = 0.2 }
+
+["qwen/qwen-max"]
+max_tokens = 32768
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 1.6, output = 6.4 }
+
+["qwen/qwen-plus"]
+max_tokens = 1000000
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.4, output = 1.2 }
+
+["qwen/qwen-plus-2025-07-28"]
+max_tokens = 1000000
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.4, output = 1.2 }
+
+["qwen/qwen-plus-2025-07-28:thinking"]
+max_tokens = 1000000
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.4, output = 1.2 }
+
+["qwen/qwen-turbo"]
+max_tokens = 131072
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.05, output = 0.2 }
+
+["qwen/qwen-vl-max"]
+max_tokens = 131072
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 0.8, output = 3.2 }
+
+["qwen/qwen-vl-plus"]
+max_tokens = 131072
+inputs = ["text", "images"]
+outputs = ["text"]
+costs = { input = 0.21, output = 0.63 }
+
+["qwen/qwen2.5-coder-7b-instruct"]
+max_tokens = 32768
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 0.03, output = 0.09 }
+
+["qwen/qwen2.5-vl-32b-instruct"]
+max_tokens = 128000
+inputs = ["text", "images"]
+outputs = ["text"]
+costs = { input = 0.2, output = 0.6 }
+
+["qwen/qwen2.5-vl-72b-instruct"]
+max_tokens = 32000
+inputs = ["text", "images"]
+outputs = ["text"]
+costs = { input = 0.25, output = 0.75 }
+
+["qwen/qwen3-14b"]
+max_tokens = 40960
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.06, output = 0.24 }
+
+["qwen/qwen3-235b-a22b"]
+max_tokens = 131072
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.455, output = 1.82 }
+
+["qwen/qwen3-235b-a22b-2507"]
+max_tokens = 262144
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.071, output = 0.1 }
+
+["qwen/qwen3-235b-a22b-thinking-2507"]
+max_tokens = 131072
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0, output = 0 }
+
+["qwen/qwen3-30b-a3b"]
+max_tokens = 40960
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.08, output = 0.28 }
+
+["qwen/qwen3-30b-a3b-instruct-2507"]
+max_tokens = 262144
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.09, output = 0.3 }
+
+["qwen/qwen3-30b-a3b-thinking-2507"]
+max_tokens = 32768
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.051, output = 0.34 }
+
+["qwen/qwen3-32b"]
+max_tokens = 40960
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.08, output = 0.24 }
+
+["qwen/qwen3-4b:free"]
+max_tokens = 40960
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0, output = 0 }
+
+["qwen/qwen3-8b"]
+max_tokens = 32000
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.05, output = 0.4 }
+
+["qwen/qwen3-coder"]
+max_tokens = 262144
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.22, output = 1 }
+
+["qwen/qwen3-coder-30b-a3b-instruct"]
+max_tokens = 160000
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.07, output = 0.27 }
+
+["qwen/qwen3-coder-flash"]
+max_tokens = 1000000
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.3, output = 1.5 }
+
+["qwen/qwen3-coder-next"]
+max_tokens = 262144
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.12, output = 0.75 }
+
+["qwen/qwen3-coder-plus"]
+max_tokens = 1000000
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 1, output = 5 }
+
+["qwen/qwen3-coder:exacto"]
+max_tokens = 262144
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.22, output = 1.8 }
+
+["qwen/qwen3-coder:free"]
+max_tokens = 262000
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0, output = 0 }
+
+["qwen/qwen3-max"]
+max_tokens = 262144
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 1.2, output = 6 }
+
+["qwen/qwen3-max-thinking"]
+max_tokens = 262144
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 1.2, output = 6 }
+
+["qwen/qwen3-next-80b-a3b-instruct"]
+max_tokens = 262144
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.09, output = 1.1 }
+
+["qwen/qwen3-next-80b-a3b-instruct:free"]
+max_tokens = 262144
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0, output = 0 }
+
+["qwen/qwen3-next-80b-a3b-thinking"]
+max_tokens = 128000
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.15, output = 1.2 }
+
+["qwen/qwen3-vl-235b-a22b-instruct"]
+max_tokens = 262144
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 0.2, output = 0.88 }
+
+["qwen/qwen3-vl-235b-a22b-thinking"]
+max_tokens = 131072
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 0, output = 0 }
+
+["qwen/qwen3-vl-30b-a3b-instruct"]
+max_tokens = 131072
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 0.13, output = 0.52 }
+
+["qwen/qwen3-vl-30b-a3b-thinking"]
+max_tokens = 131072
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 0, output = 0 }
+
+["qwen/qwen3-vl-32b-instruct"]
+max_tokens = 131072
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 0.104, output = 0.416 }
+
+["qwen/qwen3-vl-8b-instruct"]
+max_tokens = 131072
+inputs = ["images", "text"]
+outputs = ["text", "structured"]
+costs = { input = 0.08, output = 0.5 }
+
+["qwen/qwen3-vl-8b-thinking"]
+max_tokens = 131072
+inputs = ["images", "text"]
+outputs = ["text", "structured"]
+costs = { input = 0.117, output = 1.365 }
+
+["qwen/qwen3.5-397b-a17b"]
+max_tokens = 262144
+inputs = ["text", "images", "video"]
+outputs = ["text", "structured"]
+costs = { input = 0.15, output = 1 }
+
+["qwen/qwen3.5-plus-02-15"]
+max_tokens = 1000000
+inputs = ["text", "images", "video"]
+outputs = ["text", "structured"]
+costs = { input = 0.4, output = 2.4 }
+
+["qwen/qwq-32b"]
+max_tokens = 32768
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.15, output = 0.4 }
+
+# --- raifle --------------------------------------------------------------
+
+["raifle/sorcererlm-8x22b"]
+max_tokens = 16000
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 4.5, output = 4.5 }
+
+# --- relace --------------------------------------------------------------
+
+["relace/relace-apply-3"]
+max_tokens = 256000
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 0.85, output = 1.25 }
+
+["relace/relace-search"]
+max_tokens = 256000
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 1, output = 3 }
+
+# --- sao10k --------------------------------------------------------------
+
+["sao10k/l3-euryale-70b"]
+max_tokens = 8192
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 1.48, output = 1.48 }
+
+["sao10k/l3-lunaris-8b"]
+max_tokens = 8192
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 0.04, output = 0.05 }
+
+["sao10k/l3.1-70b-hanami-x1"]
+max_tokens = 16000
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 3, output = 3 }
+
+["sao10k/l3.1-euryale-70b"]
+max_tokens = 32768
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.65, output = 0.75 }
+
+["sao10k/l3.3-euryale-70b"]
+max_tokens = 131072
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 0.65, output = 0.75 }
+
+# --- stepfun -------------------------------------------------------------
+
+["stepfun/step-3.5-flash"]
+max_tokens = 256000
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.1, output = 0.3 }
+
+["stepfun/step-3.5-flash:free"]
+max_tokens = 256000
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0, output = 0 }
+
+# --- switchpoint ---------------------------------------------------------
+
+["switchpoint/router"]
+max_tokens = 131072
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 0.85, output = 3.4 }
+
+# --- tencent -------------------------------------------------------------
+
+["tencent/hunyuan-a13b-instruct"]
+max_tokens = 131072
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 0.14, output = 0.57 }
+
+# --- thedrummer ----------------------------------------------------------
+
+["thedrummer/cydonia-24b-v4.1"]
+max_tokens = 131072
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 0.3, output = 0.5 }
+
+["thedrummer/rocinante-12b"]
+max_tokens = 32768
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.17, output = 0.43 }
+
+["thedrummer/skyfall-36b-v2"]
+max_tokens = 32768
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 0.55, output = 0.8 }
+
+["thedrummer/unslopnemo-12b"]
+max_tokens = 32768
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.4, output = 0.4 }
+
+# --- tngtech -------------------------------------------------------------
+
+["tngtech/deepseek-r1t2-chimera"]
+max_tokens = 163840
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.25, output = 0.85 }
+
+# --- undi95 --------------------------------------------------------------
+
+["undi95/remm-slerp-l2-13b"]
+max_tokens = 6144
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 0.45, output = 0.65 }
+
+# --- upstage -------------------------------------------------------------
+
+["upstage/solar-pro-3:free"]
+max_tokens = 128000
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0, output = 0 }
+
+# --- writer --------------------------------------------------------------
+
+["writer/palmyra-x5"]
+max_tokens = 1040000
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 0.6, output = 6 }
+
+# --- x-ai ----------------------------------------------------------------
+
+["x-ai/grok-3"]
+max_tokens = 131072
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 3, output = 15 }
+
+["x-ai/grok-3-beta"]
+max_tokens = 131072
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 3, output = 15 }
+
+["x-ai/grok-3-mini"]
+max_tokens = 131072
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.3, output = 0.5 }
+
+["x-ai/grok-3-mini-beta"]
+max_tokens = 131072
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.3, output = 0.5 }
+
+["x-ai/grok-4"]
+max_tokens = 256000
+inputs = ["images", "text"]
+outputs = ["text", "structured"]
+costs = { input = 3, output = 15 }
+
+["x-ai/grok-4-fast"]
+max_tokens = 2000000
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 0.2, output = 0.5 }
+
+["x-ai/grok-4.1-fast"]
+max_tokens = 2000000
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 0.2, output = 0.5 }
+
+["x-ai/grok-code-fast-1"]
+max_tokens = 256000
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.2, output = 1.5 }
+
+# --- xiaomi --------------------------------------------------------------
+
+["xiaomi/mimo-v2-flash"]
+max_tokens = 262144
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.09, output = 0.29 }
+
+# --- z-ai ----------------------------------------------------------------
+
+["z-ai/glm-4-32b"]
+max_tokens = 128000
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.1, output = 0.1 }
+
+["z-ai/glm-4.5"]
+max_tokens = 131000
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.55, output = 2 }
+
+["z-ai/glm-4.5-air"]
+max_tokens = 131072
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.13, output = 0.85 }
+
+["z-ai/glm-4.5-air:free"]
+max_tokens = 131072
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0, output = 0 }
+
+["z-ai/glm-4.5v"]
+max_tokens = 65536
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+costs = { input = 0.6, output = 1.8 }
+
+["z-ai/glm-4.6"]
+max_tokens = 202752
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.35, output = 1.71 }
+
+["z-ai/glm-4.6:exacto"]
+max_tokens = 204800
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.44, output = 1.76 }
+
+["z-ai/glm-4.6v"]
+max_tokens = 131072
+inputs = ["images", "text", "video"]
+outputs = ["text", "structured"]
+costs = { input = 0.3, output = 0.9 }
+
+["z-ai/glm-4.7"]
+max_tokens = 202752
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.38, output = 1.7 }
+
+["z-ai/glm-4.7-flash"]
+max_tokens = 202752
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.06, output = 0.4 }
+
+["z-ai/glm-5"]
+max_tokens = 204800
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.95, output = 2.55 }
+
+################################################################################
+# IMAGE GENERATION MODELS
+################################################################################
+
+# --- black-forest-labs ---------------------------------------------------
+
+["black-forest-labs/flux.2-flex"]
+model_type = "img_gen"
+sdk = "openrouter_img_gen"
+max_tokens = 67344
+inputs = ["text", "images"]
+outputs = ["image"]
+costs = { input = 0, output = 0 }
+
+["black-forest-labs/flux.2-klein-4b"]
+model_type = "img_gen"
+sdk = "openrouter_img_gen"
+max_tokens = 40960
+inputs = ["text", "images"]
+outputs = ["image"]
+costs = { input = 0, output = 0 }
+
+["black-forest-labs/flux.2-max"]
+model_type = "img_gen"
+sdk = "openrouter_img_gen"
+max_tokens = 46864
+inputs = ["text", "images"]
+outputs = ["image"]
+costs = { input = 0, output = 0 }
+
+["black-forest-labs/flux.2-pro"]
+model_type = "img_gen"
+sdk = "openrouter_img_gen"
+max_tokens = 46864
+inputs = ["text", "images"]
+outputs = ["image"]
+costs = { input = 0, output = 0 }
+
+# --- bytedance-seed ------------------------------------------------------
+
+["bytedance-seed/seedream-4.5"]
+model_type = "img_gen"
+sdk = "openrouter_img_gen"
+max_tokens = 4096
+inputs = ["images", "text"]
+outputs = ["image"]
+costs = { input = 0, output = 0 }
+
+# --- google --------------------------------------------------------------
+
+["google/gemini-2.5-flash-image"]
+model_type = "img_gen"
+sdk = "openrouter_img_gen"
+max_tokens = 32768
+inputs = ["images", "text"]
+outputs = ["image", "text"]
+costs = { input = 0.3, output = 2.5 }
+
+["google/gemini-3-pro-image-preview"]
+model_type = "img_gen"
+sdk = "openrouter_img_gen"
+max_tokens = 65536
+inputs = ["images", "text"]
+outputs = ["image", "text"]
+costs = { input = 2, output = 12 }
+
+# --- openai --------------------------------------------------------------
+
+["openai/gpt-5-image"]
+model_type = "img_gen"
+sdk = "openrouter_img_gen"
+max_tokens = 400000
+inputs = ["images", "text", "pdf"]
+outputs = ["image", "text", "structured"]
+costs = { input = 10, output = 10 }
+
+["openai/gpt-5-image-mini"]
+model_type = "img_gen"
+sdk = "openrouter_img_gen"
+max_tokens = 400000
+inputs = ["pdf", "images", "text"]
+outputs = ["image", "text", "structured"]
+costs = { input = 2.5, output = 2 }
+
+# --- sourceful -----------------------------------------------------------
+
+["sourceful/riverflow-v2-fast"]
+model_type = "img_gen"
+sdk = "openrouter_img_gen"
+max_tokens = 8192
+inputs = ["text", "images"]
+outputs = ["image"]
+costs = { input = 0, output = 0 }
+
+["sourceful/riverflow-v2-fast-preview"]
+model_type = "img_gen"
+sdk = "openrouter_img_gen"
+max_tokens = 8192
+inputs = ["text", "images"]
+outputs = ["image"]
+costs = { input = 0, output = 0 }
+
+["sourceful/riverflow-v2-max-preview"]
+model_type = "img_gen"
+sdk = "openrouter_img_gen"
+max_tokens = 8192
+inputs = ["text", "images"]
+outputs = ["image"]
+costs = { input = 0, output = 0 }
+
+["sourceful/riverflow-v2-pro"]
+model_type = "img_gen"
+sdk = "openrouter_img_gen"
+max_tokens = 8192
+inputs = ["text", "images"]
+outputs = ["image"]
+costs = { input = 0, output = 0 }
+
+["sourceful/riverflow-v2-standard-preview"]
+model_type = "img_gen"
+sdk = "openrouter_img_gen"
+max_tokens = 8192
+inputs = ["text", "images"]
+outputs = ["image"]
+costs = { input = 0, output = 0 }
diff --git a/api/.pipelex/inference/backends/pipelex_gateway.toml b/api/.pipelex/inference/backends/pipelex_gateway.toml
new file mode 100644
index 000000000..5b02901ee
--- /dev/null
+++ b/api/.pipelex/inference/backends/pipelex_gateway.toml
@@ -0,0 +1,41 @@
+################################################################################
+# Pipelex Gateway Local Overrides
+################################################################################
+#
+# TELEMETRY NOTICE:
+#
+# Using Pipelex Gateway enables identified telemetry tied to your API key
+# (hashed for security). This is independent from your telemetry.toml settings.
+#
+# We collect only technical data (model names, token counts, latency, error rates).
+# We do NOT collect prompts, completions, pipe codes, or business data.
+#
+# This allows us to monitor service quality, enforce fair usage, and support you.
+#
+################################################################################
+#
+# WARNING: USE AT YOUR OWN RISK!
+#
+# The actual model configuration is fetched remotely from Pipelex servers.
+# Any override in this file may cause unexpected behavior or failures,
+# as the remote configuration may change at any time.
+#
+# If you must override, you may ONLY use these keys per model:
+# - sdk
+# - structure_method
+#
+# All other keys will be ignored.
+#
+# If you need custom configurations, consider using your own API keys
+# with direct provider backends (openai, anthropic, etc.) instead.
+#
+# Documentation:
+# https://docs.pipelex.com/latest/configuration/config-technical/inference-backend-config/
+# Support: https://go.pipelex.com/discord
+#
+################################################################################
+
+# Per-model overrides example:
+# [gpt-4o]
+# sdk = "gateway_completions"
+# structure_method = "instructor/openai_tools"
diff --git a/api/.pipelex/inference/backends/pipelex_gateway_models.md b/api/.pipelex/inference/backends/pipelex_gateway_models.md
new file mode 100644
index 000000000..c0acba8cf
--- /dev/null
+++ b/api/.pipelex/inference/backends/pipelex_gateway_models.md
@@ -0,0 +1,513 @@
+# Pipelex Gateway — Available Models
+This file lists the LLMs, document extraction models, and image generation models currently available through Pipelex Gateway.
+For configuration details, see the [documentation](https://docs.pipelex.com/latest/setup/configure-ai-providers/#option-1-pipelex-gateway-easiest-and-most-powerful-for-getting-started).
+
+## Language Models (LLM)
+
+<table>
+<thead>
+<tr>
+<th rowspan="2">Model</th>
+<th colspan="3" style="text-align:center;background-color:rgba(33,150,243,0.15)">Inputs</th>
+<th colspan="2" style="text-align:center;background-color:rgba(76,175,80,0.15)">Outputs</th>
+</tr>
+<tr>
+<th style="text-align:center;background-color:rgba(33,150,243,0.15)">text</th>
+<th style="text-align:center;background-color:rgba(33,150,243,0.15)">images</th>
+<th style="text-align:center;background-color:rgba(33,150,243,0.15)">pdf</th>
+<th style="text-align:center;background-color:rgba(76,175,80,0.15)">text</th>
+<th style="text-align:center;background-color:rgba(76,175,80,0.15)">structured</th>
+</tr>
+</thead>
+<tbody>
+<tr>
+<td>claude-4-opus</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+</tr>
+<tr>
+<td>claude-4-sonnet</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+</tr>
+<tr>
+<td>claude-4.1-opus</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+</tr>
+<tr>
+<td>claude-4.5-haiku</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+</tr>
+<tr>
+<td>claude-4.5-opus</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+</tr>
+<tr>
+<td>claude-4.5-sonnet</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+</tr>
+<tr>
+<td>claude-4.6-opus</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+</tr>
+<tr>
+<td>claude-4.6-sonnet</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+</tr>
+<tr>
+<td>claude-4.7-opus</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+</tr>
+<tr>
+<td>claude-4.8-opus</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+</tr>
+<tr>
+<td>claude-5-opus</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+</tr>
+<tr>
+<td>claude-5-sonnet</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+</tr>
+<tr>
+<td>deepseek-v3.2</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">❌</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">❌</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+</tr>
+<tr>
+<td>gemini-2.5-flash</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+</tr>
+<tr>
+<td>gemini-2.5-flash-lite</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+</tr>
+<tr>
+<td>gemini-2.5-pro</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+</tr>
+<tr>
+<td>gemini-3.0-flash</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+</tr>
+<tr>
+<td>gemini-3.1-flash-lite</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+</tr>
+<tr>
+<td>gemini-3.1-pro</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+</tr>
+<tr>
+<td>gemini-3.5-flash</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+</tr>
+<tr>
+<td>gemini-flash-latest</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+</tr>
+<tr>
+<td>gemini-flash-lite-latest</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+</tr>
+<tr>
+<td>gemini-pro-latest</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+</tr>
+<tr>
+<td>gpt-4o</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+</tr>
+<tr>
+<td>gpt-4o-mini</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+</tr>
+<tr>
+<td>gpt-5.3-codex</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+</tr>
+<tr>
+<td>gpt-5.4</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+</tr>
+<tr>
+<td>gpt-5.4-mini</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+</tr>
+<tr>
+<td>gpt-5.4-nano</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+</tr>
+<tr>
+<td>gpt-5.4-pro</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+</tr>
+<tr>
+<td>gpt-5.5</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+</tr>
+<tr>
+<td>gpt-5.6-luna</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+</tr>
+<tr>
+<td>gpt-5.6-sol</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+</tr>
+<tr>
+<td>gpt-5.6-terra</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+</tr>
+<tr>
+<td>gpt-oss-120b</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">❌</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">❌</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+</tr>
+<tr>
+<td>gpt-oss-20b</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">❌</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">❌</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+</tr>
+<tr>
+<td>grok-3</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">❌</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">❌</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">❌</td>
+</tr>
+<tr>
+<td>grok-3-mini</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">❌</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">❌</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">❌</td>
+</tr>
+<tr>
+<td>grok-4</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">❌</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">❌</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+</tr>
+<tr>
+<td>grok-4-fast-non-reasoning</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">❌</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+</tr>
+<tr>
+<td>grok-4-fast-reasoning</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">❌</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+</tr>
+<tr>
+<td>kimi-k2-thinking</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">❌</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">❌</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+</tr>
+<tr>
+<td>mistral-large</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+</tr>
+<tr>
+<td>phi-4</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">❌</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">❌</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">❌</td>
+</tr>
+<tr>
+<td>phi-4-multimodal</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">❌</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">❌</td>
+</tr>
+<tr>
+<td>qwen3-vl-235b-a22b</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">❌</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+</tr>
+</tbody>
+</table>
+
+## Document Extraction Models
+
+<table>
+<thead>
+<tr>
+<th rowspan="2">Model</th>
+<th colspan="3" style="text-align:center;background-color:rgba(33,150,243,0.15)">Inputs</th>
+<th colspan="2" style="text-align:center;background-color:rgba(76,175,80,0.15)">Outputs</th>
+</tr>
+<tr>
+<th style="text-align:center;background-color:rgba(33,150,243,0.15)">image</th>
+<th style="text-align:center;background-color:rgba(33,150,243,0.15)">pdf</th>
+<th style="text-align:center;background-color:rgba(33,150,243,0.15)">web_page</th>
+<th style="text-align:center;background-color:rgba(76,175,80,0.15)">pages</th>
+<th style="text-align:center;background-color:rgba(76,175,80,0.15)">captions</th>
+</tr>
+</thead>
+<tbody>
+<tr>
+<td>azure-document-intelligence</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">❌</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+</tr>
+<tr>
+<td>deepseek-ocr</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">❌</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">❌</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">❌</td>
+</tr>
+<tr>
+<td>linkup-fetch</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">❌</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">❌</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">❌</td>
+</tr>
+</tbody>
+</table>
+
+
+!!! info About extracted pages
+ Each page contains Markdown text (based on AI-interpreted layout) and optional extracted images. A single image input is treated as one page. Pipelex also wraps the `pypdfium2` library for raw text (without any AI interpretation) and images extraction and page views rendering. All these elements can be used as inputs into downstream pipes, including LLM prompts.
+## Image Generation Models
+
+<table>
+<thead>
+<tr>
+<th rowspan="2">Model</th>
+<th colspan="2" style="text-align:center;background-color:rgba(33,150,243,0.15)">Inputs</th>
+<th colspan="1" style="text-align:center;background-color:rgba(76,175,80,0.15)">Outputs</th>
+</tr>
+<tr>
+<th style="text-align:center;background-color:rgba(33,150,243,0.15)">text</th>
+<th style="text-align:center;background-color:rgba(33,150,243,0.15)">images</th>
+<th style="text-align:center;background-color:rgba(76,175,80,0.15)">image</th>
+</tr>
+</thead>
+<tbody>
+<tr>
+<td>gpt-image-1</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+</tr>
+<tr>
+<td>gpt-image-1-mini</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+</tr>
+<tr>
+<td>gpt-image-1.5</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+</tr>
+<tr>
+<td>gpt-image-2</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+</tr>
+<tr>
+<td>nano-banana</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+</tr>
+<tr>
+<td>nano-banana-2</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+</tr>
+<tr>
+<td>nano-banana-2-lite</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+</tr>
+<tr>
+<td>nano-banana-pro</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+</tr>
+</tbody>
+</table>
+
+
+> **AUTO-GENERATED FILE** - Do not edit manually.
+> Last updated: 2026-09-21T10:54:05Z
+>
+> Run `pipelex-dev update-gateway-models` or `make ugm` to regenerate.
\ No newline at end of file
diff --git a/api/.pipelex/inference/backends/pipelex_gateway_models_plain.md b/api/.pipelex/inference/backends/pipelex_gateway_models_plain.md
new file mode 100644
index 000000000..9ea4543d5
--- /dev/null
+++ b/api/.pipelex/inference/backends/pipelex_gateway_models_plain.md
@@ -0,0 +1,195 @@
+# Pipelex Gateway — Available Models (Plain Text)
+
+This file lists the LLMs, document extraction models, and image generation models currently available through Pipelex Gateway.
+For configuration details, see the [documentation](https://docs.pipelex.com/latest/setup/configure-ai-providers/#option-1-pipelex-gateway-easiest-and-most-powerful-for-getting-started).
+
+**Note:** This is the plain-text readable version. See `pipelex_gateway_models.md` for the HTML-styled version.
+
+## Language Models (LLM)
+
+- **claude-4-opus**
+ - inputs: text, images, pdf
+ - outputs: text, structured
+- **claude-4-sonnet**
+ - inputs: text, images, pdf
+ - outputs: text, structured
+- **claude-4.1-opus**
+ - inputs: text, images, pdf
+ - outputs: text, structured
+- **claude-4.5-haiku**
+ - inputs: text, images, pdf
+ - outputs: text, structured
+- **claude-4.5-opus**
+ - inputs: text, images, pdf
+ - outputs: text, structured
+- **claude-4.5-sonnet**
+ - inputs: text, images, pdf
+ - outputs: text, structured
+- **claude-4.6-opus**
+ - inputs: text, images, pdf
+ - outputs: text, structured
+- **claude-4.6-sonnet**
+ - inputs: text, images, pdf
+ - outputs: text, structured
+- **claude-4.7-opus**
+ - inputs: text, images, pdf
+ - outputs: text, structured
+- **claude-4.8-opus**
+ - inputs: text, images, pdf
+ - outputs: text, structured
+- **claude-5-opus**
+ - inputs: text, images, pdf
+ - outputs: text, structured
+- **claude-5-sonnet**
+ - inputs: text, images, pdf
+ - outputs: text, structured
+- **deepseek-v3.2**
+ - inputs: text
+ - outputs: text, structured
+- **gemini-2.5-flash**
+ - inputs: text, images, pdf
+ - outputs: text, structured
+- **gemini-2.5-flash-lite**
+ - inputs: text, images, pdf
+ - outputs: text, structured
+- **gemini-2.5-pro**
+ - inputs: text, images, pdf
+ - outputs: text, structured
+- **gemini-3.0-flash**
+ - inputs: text, images, pdf
+ - outputs: text, structured
+- **gemini-3.1-flash-lite**
+ - inputs: text, images, pdf
+ - outputs: text, structured
+- **gemini-3.1-pro**
+ - inputs: text, images, pdf
+ - outputs: text, structured
+- **gemini-3.5-flash**
+ - inputs: text, images, pdf
+ - outputs: text, structured
+- **gemini-flash-latest**
+ - inputs: text, images, pdf
+ - outputs: text, structured
+- **gemini-flash-lite-latest**
+ - inputs: text, images, pdf
+ - outputs: text, structured
+- **gemini-pro-latest**
+ - inputs: text, images, pdf
+ - outputs: text, structured
+- **gpt-4o**
+ - inputs: text, images, pdf
+ - outputs: text, structured
+- **gpt-4o-mini**
+ - inputs: text, images, pdf
+ - outputs: text, structured
+- **gpt-5.3-codex**
+ - inputs: text, images, pdf
+ - outputs: text, structured
+- **gpt-5.4**
+ - inputs: text, images, pdf
+ - outputs: text, structured
+- **gpt-5.4-mini**
+ - inputs: text, images, pdf
+ - outputs: text, structured
+- **gpt-5.4-nano**
+ - inputs: text, images, pdf
+ - outputs: text, structured
+- **gpt-5.4-pro**
+ - inputs: text, images, pdf
+ - outputs: text, structured
+- **gpt-5.5**
+ - inputs: text, images, pdf
+ - outputs: text, structured
+- **gpt-5.6-luna**
+ - inputs: text, images, pdf
+ - outputs: text, structured
+- **gpt-5.6-sol**
+ - inputs: text, images, pdf
+ - outputs: text, structured
+- **gpt-5.6-terra**
+ - inputs: text, images, pdf
+ - outputs: text, structured
+- **gpt-oss-120b**
+ - inputs: text
+ - outputs: text, structured
+- **gpt-oss-20b**
+ - inputs: text
+ - outputs: text, structured
+- **grok-3**
+ - inputs: text
+ - outputs: text
+- **grok-3-mini**
+ - inputs: text
+ - outputs: text
+- **grok-4**
+ - inputs: text
+ - outputs: text, structured
+- **grok-4-fast-non-reasoning**
+ - inputs: text, images
+ - outputs: text, structured
+- **grok-4-fast-reasoning**
+ - inputs: text, images
+ - outputs: text, structured
+- **kimi-k2-thinking**
+ - inputs: text
+ - outputs: text, structured
+- **mistral-large**
+ - inputs: text, images, pdf
+ - outputs: text, structured
+- **phi-4**
+ - inputs: text
+ - outputs: text
+- **phi-4-multimodal**
+ - inputs: text, images
+ - outputs: text
+- **qwen3-vl-235b-a22b**
+ - inputs: text, images
+ - outputs: text, structured
+
+## Document Extraction Models
+
+- **azure-document-intelligence**
+ - inputs: image, pdf
+ - outputs: pages, captions
+- **deepseek-ocr**
+ - inputs: image
+ - outputs: pages
+- **linkup-fetch**
+ - inputs: web_page
+ - outputs: pages
+
+
+**About extracted pages:** Each page contains Markdown text (based on AI-interpreted layout) and optional extracted images. A single image input is treated as one page. Pipelex also wraps the `pypdfium2` library for raw text (without any AI interpretation) and images extraction and page views rendering. All these elements can be used as inputs into downstream pipes, including LLM prompts.
+
+## Image Generation Models
+
+- **gpt-image-1**
+ - inputs: text, images
+ - outputs: image
+- **gpt-image-1-mini**
+ - inputs: text, images
+ - outputs: image
+- **gpt-image-1.5**
+ - inputs: text, images
+ - outputs: image
+- **gpt-image-2**
+ - inputs: text, images
+ - outputs: image
+- **nano-banana**
+ - inputs: text, images
+ - outputs: image
+- **nano-banana-2**
+ - inputs: text, images
+ - outputs: image
+- **nano-banana-2-lite**
+ - inputs: text, images
+ - outputs: image
+- **nano-banana-pro**
+ - inputs: text, images
+ - outputs: image
+
+
+> **AUTO-GENERATED FILE** - Do not edit manually.
+> Last updated: 2026-09-21T10:54:05Z
+>
+> Run `pipelex-dev update-gateway-models` or `make ugm` to regenerate.
\ No newline at end of file
diff --git a/api/.pipelex/inference/backends/pipelex_manifold.toml b/api/.pipelex/inference/backends/pipelex_manifold.toml
new file mode 100644
index 000000000..1a9adc718
--- /dev/null
+++ b/api/.pipelex/inference/backends/pipelex_manifold.toml
@@ -0,0 +1,56 @@
+################################################################################
+# Pipelex Manifold Local Overrides
+################################################################################
+#
+# PRIVATE BETA:
+#
+# Pipelex Manifold is the Pipelex-operated inference service. It is in private
+# beta, it ships disabled in backends.toml, and this file does nothing until you
+# enable it there and set PIPELEX_MANIFOLD_ENDPOINT and PIPELEX_MANIFOLD_API_KEY.
+#
+################################################################################
+#
+# TELEMETRY NOTICE:
+#
+# Enabling pipelex_gateway alongside this backend enables identified telemetry
+# from your machine, tied to your Pipelex Gateway API key (hashed for security).
+# This is independent from your telemetry.toml settings.
+#
+# That client-side telemetry follows the gateway key and nothing else, so an
+# installation running Pipelex Manifold ALONE sends none of it. Manifold is a
+# Pipelex-operated service, though, so your usage of it is recorded server-side
+# the way any hosted platform records the calls it serves.
+#
+# Either way we collect only technical data (model names, token counts, latency,
+# error rates). We do NOT collect prompts, completions, pipe codes, or business
+# data.
+#
+# This allows us to monitor service quality, enforce fair usage, and support you.
+#
+################################################################################
+#
+# WARNING: USE AT YOUR OWN RISK!
+#
+# The actual model configuration is fetched remotely from Pipelex servers.
+# Any override in this file may cause unexpected behavior or failures,
+# as the remote configuration may change at any time.
+#
+# If you must override, you may ONLY use these keys per model:
+# - sdk
+# - structure_method
+#
+# All other keys will be ignored.
+#
+# If you need custom configurations, consider using your own API keys
+# with direct provider backends (openai, anthropic, etc.) instead.
+#
+# Documentation:
+# https://docs.pipelex.com/latest/configuration/config-technical/inference-backend-config/
+# Support: https://go.pipelex.com/discord
+#
+################################################################################
+
+# Per-model overrides example:
+# [gpt-4o]
+# sdk = "manifold_completions"
+# structure_method = "instructor/openai_tools"
diff --git a/api/.pipelex/inference/backends/portkey.toml b/api/.pipelex/inference/backends/portkey.toml
new file mode 100644
index 000000000..f46825eb1
--- /dev/null
+++ b/api/.pipelex/inference/backends/portkey.toml
@@ -0,0 +1,291 @@
+################################################################################
+# Portkey Configuration
+################################################################################
+#
+# This file defines the model specifications for the Portkey backend.
+# It contains model definitions for various AI models.
+#
+# Configuration structure:
+# - Each model is defined in its own section with the model name as the header
+# - Headers with dots must be quoted (e.g., ["gpt-4.1"])
+# - Model costs are in USD per million tokens (input/output)
+#
+# Documentation: https://docs.pipelex.com
+# Support: https://go.pipelex.com/discord
+#
+################################################################################
+
+################################################################################
+# MODEL DEFAULTS
+################################################################################
+
+[defaults]
+model_type = "llm"
+sdk = "portkey_completions"
+structure_method = "instructor/openai_tools"
+thinking_mode = "none"
+
+################################################################################
+# LANGUAGE MODELS
+################################################################################
+
+# --- OpenAI LLMs --------------------------------------------------------------
+[gpt-4o-mini]
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+costs = { input = 0.15, output = 0.6 }
+sdk = "portkey_responses"
+structure_method = "instructor/openai_responses_tools"
+thinking_mode = "none"
+x-portkey-provider = "@openai"
+
+[gpt-4o]
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+costs = { input = 2.5, output = 10.0 }
+sdk = "portkey_responses"
+structure_method = "instructor/openai_responses_tools"
+thinking_mode = "none"
+x-portkey-provider = "@openai"
+
+["gpt-4.1-nano"]
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+costs = { input = 0.1, output = 0.4 }
+sdk = "portkey_responses"
+structure_method = "instructor/openai_responses_tools"
+thinking_mode = "none"
+x-portkey-provider = "@openai"
+
+["gpt-4.1-mini"]
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+costs = { input = 0.4, output = 1.6 }
+sdk = "portkey_responses"
+structure_method = "instructor/openai_responses_tools"
+thinking_mode = "none"
+x-portkey-provider = "@openai"
+
+["gpt-4.1"]
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+costs = { input = 2, output = 8 }
+sdk = "portkey_responses"
+structure_method = "instructor/openai_responses_tools"
+thinking_mode = "none"
+x-portkey-provider = "@openai"
+
+[o1]
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+costs = { input = 15.0, output = 60.0 }
+valued_constraints = { fixed_temperature = 1 }
+sdk = "portkey_responses"
+structure_method = "instructor/openai_responses_tools"
+thinking_mode = "manual"
+x-portkey-provider = "@openai"
+
+[o3-mini]
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 1.1, output = 4.4 }
+valued_constraints = { fixed_temperature = 1 }
+sdk = "portkey_responses"
+structure_method = "instructor/openai_responses_tools"
+thinking_mode = "manual"
+x-portkey-provider = "@openai"
+
+[o3]
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+costs = { input = 2, output = 8 }
+valued_constraints = { fixed_temperature = 1 }
+sdk = "portkey_responses"
+structure_method = "instructor/openai_responses_tools"
+thinking_mode = "manual"
+x-portkey-provider = "@openai"
+
+[gpt-5-nano]
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+costs = { input = 0.05, output = 0.4 }
+valued_constraints = { fixed_temperature = 1 }
+sdk = "portkey_responses"
+structure_method = "instructor/openai_responses_tools"
+thinking_mode = "manual"
+x-portkey-provider = "@openai"
+
+[gpt-5-mini]
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+costs = { input = 0.25, output = 2.0 }
+valued_constraints = { fixed_temperature = 1 }
+sdk = "portkey_responses"
+structure_method = "instructor/openai_responses_tools"
+thinking_mode = "manual"
+x-portkey-provider = "@openai"
+
+[gpt-5]
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+costs = { input = 1.25, output = 10.0 }
+valued_constraints = { fixed_temperature = 1 }
+sdk = "portkey_responses"
+structure_method = "instructor/openai_responses_tools"
+thinking_mode = "manual"
+x-portkey-provider = "@openai"
+
+["gpt-5.1"]
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+costs = { input = 1.25, output = 10.0 }
+valued_constraints = { fixed_temperature = 1 }
+sdk = "portkey_responses"
+structure_method = "instructor/openai_responses_tools"
+thinking_mode = "manual"
+x-portkey-provider = "@openai"
+
+["gpt-5.1-codex"]
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+costs = { input = 1.25, output = 10.0 }
+valued_constraints = { fixed_temperature = 1 }
+sdk = "portkey_responses"
+structure_method = "instructor/openai_responses_tools"
+thinking_mode = "manual"
+x-portkey-provider = "@openai"
+
+# --- Claude LLMs --------------------------------------------------------------
+[claude-3-haiku]
+model_id = "claude-3-haiku-20240307"
+max_tokens = 4096
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+max_prompt_images = 100
+costs = { input = 0.25, output = 1.25 }
+thinking_mode = "none"
+x-portkey-provider = "@anthropic"
+
+["claude-3.7-sonnet"]
+model_id = "claude-3-7-sonnet-20250219"
+max_tokens = 8192
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+max_prompt_images = 100
+costs = { input = 3.0, output = 15.0 }
+thinking_mode = "manual"
+x-portkey-provider = "@anthropic"
+
+[claude-4-sonnet]
+model_id = "claude-sonnet-4-20250514"
+max_tokens = 64000
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+max_prompt_images = 100
+costs = { input = 3.0, output = 15.0 }
+thinking_mode = "manual"
+x-portkey-provider = "@anthropic"
+
+[claude-4-opus]
+model_id = "claude-opus-4-20250514"
+max_tokens = 32000
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+max_prompt_images = 100
+costs = { input = 3.0, output = 15.0 }
+thinking_mode = "manual"
+x-portkey-provider = "@anthropic"
+
+["claude-4.1-opus"]
+model_id = "claude-opus-4-1-20250805"
+max_tokens = 32000
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+max_prompt_images = 100
+costs = { input = 3.0, output = 15.0 }
+thinking_mode = "manual"
+x-portkey-provider = "@anthropic"
+
+["claude-4.5-sonnet"]
+model_id = "claude-sonnet-4-5-20250929"
+max_tokens = 64000
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+max_prompt_images = 100
+costs = { input = 3.0, output = 15.0 }
+thinking_mode = "manual"
+x-portkey-provider = "@anthropic"
+
+["claude-4.5-haiku"]
+model_id = "claude-haiku-4-5-20251001"
+max_tokens = 64000
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+max_prompt_images = 100
+costs = { input = 1.0, output = 5.0 }
+thinking_mode = "manual"
+x-portkey-provider = "@anthropic"
+
+["claude-4.5-opus"]
+model_id = "claude-opus-4-5-20251101"
+max_tokens = 64000
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+max_prompt_images = 100
+costs = { input = 5.0, output = 25.0 }
+thinking_mode = "manual"
+x-portkey-provider = "@anthropic"
+
+["claude-4.6-opus"]
+model_id = "claude-opus-4-6"
+max_tokens = 64000
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+max_prompt_images = 100
+costs = { input = 5.0, output = 25.0 }
+thinking_mode = "adaptive"
+x-portkey-provider = "@anthropic"
+
+# --- Gemini LLMs --------------------------------------------------------------
+["gemini-2.5-pro"]
+model_id = "gemini-2.5-pro"
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+max_prompt_images = 3000
+costs = { input = 1.25, output = 10.0 }
+thinking_mode = "manual"
+x-portkey-provider = "@google"
+
+["gemini-2.5-flash"]
+model_id = "gemini-2.5-flash"
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+costs = { input = 0.30, output = 2.50 }
+thinking_mode = "manual"
+x-portkey-provider = "@google"
+
+["gemini-2.5-flash-lite"]
+model_id = "gemini-2.5-flash-lite"
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+costs = { input = 0.10, output = 0.40 }
+thinking_mode = "manual"
+x-portkey-provider = "@google"
+
+["gemini-3.1-pro"]
+model_id = "gemini-3.1-pro-preview"
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+max_prompt_images = 3000
+costs = { input = 2, output = 12.0 }
+thinking_mode = "adaptive"
+x-portkey-provider = "@google"
+
+["gemini-3.0-flash"]
+model_id = "gemini-3-flash-preview"
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+max_prompt_images = 3000
+costs = { input = 0.5, output = 3.0 }
+thinking_mode = "adaptive"
+x-portkey-provider = "@google"
diff --git a/api/.pipelex/inference/backends/scaleway.toml b/api/.pipelex/inference/backends/scaleway.toml
new file mode 100644
index 000000000..79cc7045e
--- /dev/null
+++ b/api/.pipelex/inference/backends/scaleway.toml
@@ -0,0 +1,68 @@
+################################################################################
+# Scaleway Backend Configuration
+################################################################################
+#
+# This file defines the model specifications for Scaleway models.
+# It contains model definitions for various LLM models accessible through
+# the Scaleway API, including text-only and vision-capable models.
+#
+# Configuration structure:
+# - Each model is defined in its own section with the model name as the header
+# - Headers with dots or slashes must be quoted (e.g., ["meta-llama/llama-4-scout"])
+# - Model costs are in USD per million tokens (input/output)
+# - Vision models support max 5 images per request, 33MP max resolution
+#
+# Documentation: https://docs.pipelex.com
+# Support: https://go.pipelex.com/discord
+#
+################################################################################
+
+################################################################################
+# MODEL DEFAULTS
+################################################################################
+
+[defaults]
+model_type = "llm"
+sdk = "openai"
+structure_method = "instructor/json"
+thinking_mode = "none"
+
+# --- DeepSeek Models ----------------------------------------------------------
+[deepseek-r1-distill-llama-70b]
+max_tokens = 32768
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.90, output = 0.90 }
+
+# --- Meta Llama 3.x Series ----------------------------------------------------
+["llama-3.1-8b-instruct"]
+max_tokens = 131072
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.2, output = 0.2 }
+
+["llama-3.3-70b-instruct"]
+max_tokens = 32768
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.90, output = 0.90 }
+
+# --- OpenAI GPT-OSS Models ----------------------------------------------------
+[gpt-oss-120b]
+max_tokens = 65536
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.15, output = 0.60 }
+
+# --- Qwen 3 -------------------------------------------------------------------
+[qwen3-235b-a22b-instruct-2507]
+max_tokens = 40960
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.75, output = 2.25 }
+
+[qwen3-coder-30b-a3b-instruct]
+max_tokens = 40960
+inputs = ["text"]
+outputs = ["text", "structured"]
+costs = { input = 0.20, output = 0.80 }
diff --git a/api/.pipelex/inference/backends/vertexai.toml b/api/.pipelex/inference/backends/vertexai.toml
new file mode 100644
index 000000000..c65f76335
--- /dev/null
+++ b/api/.pipelex/inference/backends/vertexai.toml
@@ -0,0 +1,46 @@
+################################################################################
+# VertexAI Backend Configuration
+################################################################################
+#
+# This file defines the model specifications for Google VertexAI models.
+# It contains model definitions for Gemini language models
+# accessible through the Google VertexAI API.
+#
+# Configuration structure:
+# - Each model is defined in its own section with the model name as the header
+# - Headers with dots must be quoted (e.g., ["gemini-2.5-pro"])
+# - Model costs are in USD per million tokens (input/output)
+#
+# Documentation: https://docs.pipelex.com
+# Support: https://go.pipelex.com/discord
+#
+################################################################################
+
+################################################################################
+# MODEL DEFAULTS
+################################################################################
+
+[defaults]
+model_type = "llm"
+sdk = "openai"
+structure_method = "instructor/vertexai_tools"
+thinking_mode = "none"
+
+################################################################################
+# LANGUAGE MODELS
+################################################################################
+
+# --- Gemini 2.5 Series --------------------------------------------------------
+["gemini-2.5-pro"]
+model_id = "google/gemini-2.5-pro"
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+max_prompt_images = 3000
+costs = { input = 1.25, output = 10.0 }
+
+["gemini-2.5-flash"]
+model_id = "google/gemini-2.5-flash"
+inputs = ["text", "images"]
+outputs = ["text", "structured"]
+max_prompt_images = 3000
+costs = { input = 0.30, output = 2.50 }
diff --git a/api/.pipelex/inference/backends/xai.toml b/api/.pipelex/inference/backends/xai.toml
new file mode 100644
index 000000000..402529979
--- /dev/null
+++ b/api/.pipelex/inference/backends/xai.toml
@@ -0,0 +1,56 @@
+################################################################################
+# XAI Backend Configuration
+################################################################################
+#
+# This file defines the model specifications for XAI (formerly Twitter AI) models.
+# It contains model definitions for Grok language models
+# accessible through the XAI API.
+#
+# Configuration structure:
+# - Each model is defined in its own section with the model name as the header
+# - Headers with dots must be quoted (e.g., ["grok-3"])
+# - Model costs are in USD per million tokens (input/output)
+#
+# Documentation: https://docs.pipelex.com
+# Support: https://go.pipelex.com/discord
+#
+################################################################################
+
+################################################################################
+# MODEL DEFAULTS
+################################################################################
+
+[defaults]
+model_type = "llm"
+sdk = "openai"
+structure_method = "instructor/openai_tools"
+thinking_mode = "none"
+
+################################################################################
+# LANGUAGE MODELS
+################################################################################
+
+# --- Grok 3 Series ------------------------------------------------------------
+[grok-3]
+model_id = "grok-3"
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 3, output = 15 }
+
+[grok-3-mini]
+model_id = "grok-3-mini"
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 0.3, output = 0.5 }
+
+[grok-3-fast]
+model_id = "grok-3-fast-latest"
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 5, output = 25 }
+
+[grok-3-mini-fast]
+model_id = "grok-3-mini-fast-latest"
+inputs = ["text"]
+outputs = ["text"]
+costs = { input = 0.15, output = 4 }
diff --git a/api/.pipelex/inference/deck/.kit_manifest.json b/api/.pipelex/inference/deck/.kit_manifest.json
new file mode 100644
index 000000000..e9c32f088
--- /dev/null
+++ b/api/.pipelex/inference/deck/.kit_manifest.json
@@ -0,0 +1,10 @@
+{
+ "files": {
+ "1_llm_deck.toml": "1316c59eb52db62820d313ff92569b736a3f5427ab8c10f495a02b463f37c97a",
+ "2_img_gen_deck.toml": "00d570907cee9261882922afebc53556013e46d29419fce4cf189135e2849fd6",
+ "3_extract_deck.toml": "560a40bd3254b1be011cfb35340fef6c40d70136e5ddce33a961899f92fd70ba",
+ "4_search_deck.toml": "08e3bd1bee0f9f8ed0ffc735a932705392d0ecfbdeefce64c9815d4b2d8d7e22",
+ "5_doc_gen_deck.toml": "3f48b443eb9245a87c6d8051223982bf6134155868bb44a3b167c8e05077c372"
+ },
+ "kit_version": "0.61.0"
+}
diff --git a/api/.pipelex/inference/deck/1_llm_deck.toml b/api/.pipelex/inference/deck/1_llm_deck.toml
new file mode 100644
index 000000000..77d234fed
--- /dev/null
+++ b/api/.pipelex/inference/deck/1_llm_deck.toml
@@ -0,0 +1,110 @@
+####################################################################################################
+# Pipelex Model Deck - LLM Configuration
+####################################################################################################
+#
+# This file defines model defaults, aliases, and presets for LLMs
+#
+# Managed by `pipelex update`. To customize without conflict, edit
+# x_custom_llm_deck.toml in this directory — pipelex never tracks or
+# overwrites x_custom_* files. Local edits to this file are backed up
+# to <file>.bak.<timestamp> on update but will not survive future runs.
+#
+# Model Reference Syntax:
+# - Preset: $preset_name or preset:preset_name
+# - Alias: @alias_name or alias:alias_name
+#
+# Documentation: https://docs.pipelex.com
+# Support: https://go.pipelex.com/discord
+#
+####################################################################################################
+
+####################################################################################################
+# LLM Default Choices
+####################################################################################################
+
+# `default_temperature` is the temperature paired with a model named outside a preset — an alias, a
+# waterfall or a bare handle written straight into a pipe, and the `for_text` / `for_object` choices
+# below. Every model this deck resolves to fixes its temperature at 1, so any other value here would
+# be overridden by the worker and warned about on every single call.
+
+[llm.choice_defaults]
+default_temperature = 1
+for_text = "@default-general"
+for_object = "@default-general"
+
+####################################################################################################
+# LLM Aliases
+####################################################################################################
+#
+# The ladder runs over the GPT-5.6 range and nothing else: luna is the cheap tier, terra the
+# intermediate one that carries most of the deck, and sol the premium tier. Read an alias as the job
+# it names rather than as a model: repointing a tier is a one-line change here, and every preset
+# that goes through an alias follows. The four that name a handle outright — `retrieval-cheap`,
+# `retrieval-premium`, `engineering-code-cheap` and `engineering-code-cheaper` — do not, and have to
+# be repointed with it.
+
+[llm.aliases]
+best-gpt = "gpt-5.6-sol"
+
+# Default aliases (first choice from waterfalls)
+default-general = "gpt-5.6-terra"
+default-premium = "gpt-5.6-sol"
+default-premium-vision = "gpt-5.6-sol"
+default-premium-structured = "gpt-5.6-sol"
+default-large-context-code = "gpt-5.6-terra"
+default-large-context-text = "gpt-5.6-terra"
+default-small = "gpt-5.6-luna"
+default-small-structured = "gpt-5.6-luna"
+default-small-vision = "gpt-5.6-luna"
+default-small-creative = "gpt-5.6-luna"
+
+####################################################################################################
+# LLM Presets
+####################################################################################################
+
+# Every preset here carries temperature = 1, because every model this deck resolves to — the whole
+# GPT-5.6 range — fixes its temperature at 1. Declaring anything else would be
+# overridden by the worker and warned about on every single call, so the deck states the value the
+# model will actually use. Presets are therefore distinguished by their model tier and their
+# reasoning effort, not by temperature. If a tier ever moves to a model that accepts a temperature,
+# these are the presets to revisit.
+
+[llm.presets]
+
+# Writing
+writing-factual = { model = "@default-premium", temperature = 1, description = "Factual writing with high accuracy" }
+writing-factual-cheap = { model = "@default-small", temperature = 1, description = "Cheap factual writing with high accuracy" }
+writing-creative = { model = "@default-premium", temperature = 1, description = "Creative writing with high variability" }
+writing-creative-cheap = { model = "@default-small-creative", temperature = 1, description = "Cheap creative writing with high variability" }
+
+# Retrieval
+retrieval = { model = "@default-large-context-text", temperature = 1, description = "Data retrieval from large text corpora" }
+retrieval-cheap = { model = "gpt-5.6-luna", temperature = 1, description = "Cheap data retrieval from large text corpora" }
+retrieval-premium = { model = "gpt-5.6-terra", temperature = 1, reasoning_effort = "high", description = "Premium data retrieval with highest accuracy" }
+
+# Engineering
+engineering-structured = { model = "@default-premium-structured", temperature = 1, description = "Structured engineering output (JSON, schemas)" }
+engineering-code = { model = "@default-premium", temperature = 1, description = "Code generation and analysis" }
+engineering-code-cheap = { model = "gpt-5.6-terra", temperature = 1, description = "Cheap code generation and analysis" }
+engineering-code-cheaper = { model = "gpt-5.6-luna", temperature = 1, description = "Cheapest code generation and analysis" }
+engineering-codebase-analysis = { model = "@default-large-context-code", temperature = 1, description = "Large codebase analysis" }
+
+# Vision
+vision = { model = "@default-premium-vision", temperature = 1, description = "Understanding and interpreting images" }
+vision-cheap = { model = "@default-small-vision", temperature = 1, description = "Cheap image understanding for simple tasks" }
+vision-diagram = { model = "@default-premium-vision", temperature = 1, description = "Diagram and chart interpretation" }
+vision-table = { model = "@default-premium-vision", temperature = 1, description = "Table extraction from images" }
+
+# Image generation prompting
+img-gen-prompting = { model = "@default-premium", temperature = 1, description = "Crafting image generation prompts" }
+img-gen-prompting-cheap = { model = "@default-small-creative", temperature = 1, description = "Cheap image prompt generation" }
+
+# Reasoning
+deep-analysis = { model = "@default-premium", temperature = 1, reasoning_effort = "high", description = "Deep reasoning and analysis" }
+quick-reasoning = { model = "@default-premium", temperature = 1, reasoning_effort = "low", description = "Quick reasoning for simple tasks" }
+
+# Testing
+testing-text = { model = "@default-small", temperature = 1, description = "Testing preset for text generation" }
+testing-structured = { model = "@default-small-structured", temperature = 1, description = "Testing preset for structured output" }
+testing-vision = { model = "@default-small-vision", temperature = 1, description = "Testing preset for vision tasks" }
+testing-vision-structured = { model = "@default-small-vision", temperature = 1, description = "Testing preset for structured vision output" }
diff --git a/api/.pipelex/inference/deck/2_img_gen_deck.toml b/api/.pipelex/inference/deck/2_img_gen_deck.toml
new file mode 100644
index 000000000..503413857
--- /dev/null
+++ b/api/.pipelex/inference/deck/2_img_gen_deck.toml
@@ -0,0 +1,56 @@
+####################################################################################################
+# Pipelex Model Deck - Image Generation Configuration
+####################################################################################################
+#
+# This file defines model aliases and presets for image generation models
+#
+# Managed by `pipelex update`. To customize without conflict, create an
+# x_custom_*.toml file in this directory — pipelex never tracks or
+# overwrites x_custom_* files. Local edits to this file are backed up
+# to <file>.bak.<timestamp> on update but will not survive future runs.
+#
+# Model Reference Syntax:
+# - Preset: $preset_name or preset:preset_name
+# - Alias: @alias_name or alias:alias_name
+#
+# Documentation: https://docs.pipelex.com
+# Support: https://go.pipelex.com/discord
+#
+####################################################################################################
+
+####################################################################################################
+# Image Generation Default Choices
+####################################################################################################
+
+[img_gen]
+default_quality = "medium"
+choice_default = "$gen-image"
+
+####################################################################################################
+# Image Generation Aliases
+####################################################################################################
+
+[img_gen.aliases]
+best-gpt = "gpt-image-2"
+
+default-general = "gpt-image-2"
+default-premium = "gpt-image-2"
+default-small = "gpt-image-1-mini"
+
+####################################################################################################
+# Image Generation Presets
+####################################################################################################
+
+[img_gen.presets]
+
+# General purpose
+gen-image = { model = "@default-general", quality = "medium", description = "Standard image generation" }
+gen-image-fast = { model = "@default-small", quality = "low", description = "Fast image generation with lower quality" }
+gen-image-high-quality = { model = "@default-premium", quality = "high", description = "High-quality image generation" }
+
+# Testing
+gen-image-testing = { model = "@default-small", quality = "low", description = "Testing preset for image generation" }
+gen-image-testing-img2img = { model = "@default-premium", description = "Testing preset for image-to-image" }
+synthesize-photo = { model = "@default-small", quality = "low", description = "Synthesize realistic photos for testing" }
+synthesize-ui = { model = "@default-premium", description = "Synthesize UI screenshots for testing" }
+synthesize-chart = { model = "@default-premium", description = "Synthesize charts and graphs for testing" }
diff --git a/api/.pipelex/inference/deck/3_extract_deck.toml b/api/.pipelex/inference/deck/3_extract_deck.toml
new file mode 100644
index 000000000..c67d393f1
--- /dev/null
+++ b/api/.pipelex/inference/deck/3_extract_deck.toml
@@ -0,0 +1,48 @@
+####################################################################################################
+# Pipelex Model Deck - Base Configuration
+####################################################################################################
+#
+# This file defines model aliases and presets for Document extraction models, including
+# extraction of text and images from documents and OCR and text extraction from images.
+#
+# Managed by `pipelex update`. To customize without conflict, edit
+# x_custom_extract_deck.toml in this directory — pipelex never tracks or
+# overwrites x_custom_* files. Local edits to this file are backed up
+# to <file>.bak.<timestamp> on update but will not survive future runs.
+#
+# Model Reference Syntax:
+# - Preset: $preset_name or preset:preset_name
+# - Alias: @alias_name or alias:alias_name
+#
+# Documentation: https://docs.pipelex.com
+# Support: https://go.pipelex.com/discord
+#
+####################################################################################################
+
+####################################################################################################
+# Document Extraction Default Choices
+####################################################################################################
+
+[extract]
+choice_default = "@default-extract-document"
+
+####################################################################################################
+# Aliases
+####################################################################################################
+
+[extract.aliases]
+default-premium = "azure-document-intelligence"
+default-extract-document = "azure-document-intelligence"
+default-extract-image = "azure-document-intelligence"
+default-text-from-pdf = "pypdfium2-extract-pdf"
+default-no-inference = "pypdfium2-extract-pdf"
+default-extract-web-page = "linkup-fetch"
+
+####################################################################################################
+# Extract Presets
+####################################################################################################
+
+[extract.presets]
+
+# Testing
+extract-testing = { model = "@default-extract-document", max_nb_images = 5, image_min_size = 50, description = "Testing preset for document extraction" }
diff --git a/api/.pipelex/inference/deck/4_search_deck.toml b/api/.pipelex/inference/deck/4_search_deck.toml
new file mode 100644
index 000000000..230a1ec67
--- /dev/null
+++ b/api/.pipelex/inference/deck/4_search_deck.toml
@@ -0,0 +1,42 @@
+####################################################################################################
+# Pipelex Model Deck - Search Configuration
+####################################################################################################
+#
+# This file defines model aliases and presets for Search models, including
+# web search providers like Linkup.
+#
+# Managed by `pipelex update`. To customize without conflict, create an
+# x_custom_*.toml file in this directory — pipelex never tracks or
+# overwrites x_custom_* files. Local edits to this file are backed up
+# to <file>.bak.<timestamp> on update but will not survive future runs.
+#
+# Model Reference Syntax:
+# - Preset: $preset_name or preset:preset_name
+# - Alias: @alias_name or alias:alias_name
+#
+# Documentation: https://docs.pipelex.com
+# Support: https://go.pipelex.com/discord
+#
+####################################################################################################
+
+####################################################################################################
+# Search Default Choices
+####################################################################################################
+
+[search]
+choice_default = "@default-search"
+
+####################################################################################################
+# Aliases
+####################################################################################################
+
+[search.aliases]
+default-search = "linkup-standard"
+
+####################################################################################################
+# Search Presets
+####################################################################################################
+
+[search.presets]
+standard = { model = "linkup-standard", include_images = false, include_inline_citations = true }
+deep = { model = "linkup-deep", include_images = false, include_inline_citations = true }
diff --git a/api/.pipelex/inference/deck/5_doc_gen_deck.toml b/api/.pipelex/inference/deck/5_doc_gen_deck.toml
new file mode 100644
index 000000000..cdb0ee676
--- /dev/null
+++ b/api/.pipelex/inference/deck/5_doc_gen_deck.toml
@@ -0,0 +1,41 @@
+####################################################################################################
+# Pipelex Model Deck - Document Generation Configuration
+####################################################################################################
+#
+# This file defines the default engine a PipeDocGen step prints with, for each format and source,
+# when the step names none with `model`. A source is where the document comes from: "layout" is the
+# auto-layout of the step's inputs, "html" an HTML template, "template_file" an office template file.
+#
+# Open Pipelex prints a pdf from the auto-layout, on its built-in engine reportlab-pdf, so that is
+# the one default this file sets. The Pipelex document generation plugin, pipelex-doc-gen, declares
+# the defaults for a pdf from a template and for xlsx, docx and pptx itself when it loads. You can
+# still set any default yourself, for any format and source, in an x_custom_*.toml file, which
+# overrides both this file and the plugin.
+#
+# Managed by `pipelex update`. To customize without conflict, create an
+# x_custom_*.toml file in this directory — pipelex never tracks or
+# overwrites x_custom_* files. Local edits to this file are backed up
+# to <file>.bak.<timestamp> on update but will not survive future runs.
+#
+# Model Reference Syntax:
+# - Preset: $preset_name or preset:preset_name
+# - Alias: @alias_name or alias:alias_name
+#
+# Documentation: https://docs.pipelex.com
+# Support: https://go.pipelex.com/discord
+#
+####################################################################################################
+
+####################################################################################################
+# Document Generation Default Choices, keyed "<format>.<source>"
+####################################################################################################
+
+[doc_gen.choice_defaults]
+"pdf.layout" = "@default-pdf"
+
+####################################################################################################
+# Aliases
+####################################################################################################
+
+[doc_gen.aliases]
+default-pdf = "reportlab-pdf"
diff --git a/api/.pipelex/inference/deck/x_custom_extract_deck.toml b/api/.pipelex/inference/deck/x_custom_extract_deck.toml
new file mode 100644
index 000000000..24fc260ee
--- /dev/null
+++ b/api/.pipelex/inference/deck/x_custom_extract_deck.toml
@@ -0,0 +1,40 @@
+####################################################################################################
+# Pipelex Model Deck - Custom Configurations for Document Extraction Models
+####################################################################################################
+#
+# This file allows you to override or complete the base model decks.
+#
+# ADVANCED USERS ONLY: This file is for users who bring their own API keys and connect directly
+# to AI providers (Azure, Mistral, etc.) without using the Pipelex Gateway.
+#
+# If you're using the standard Pipelex Gateway setup, you don't need to modify this file.
+# The Gateway handles model routing automatically and supports all available models.
+#
+# Waterfalls are useful when using multiple backends directly - they define ordered lists
+# of models that are resolved at configuration time based on which backends are available.
+# This enables defining pipelines that work across different environments with varying
+# backend configurations.
+#
+# Documentation: https://docs.pipelex.com
+# Support: https://go.pipelex.com/discord
+#
+####################################################################################################
+
+
+####################################################################################################
+# Waterfalls — ordered lists of models resolved at configuration time by backend availability
+#####################################################################################################
+
+# Example (uncomment to use):
+# [extract.waterfalls]
+# document_extractor = ["azure-document-intelligence", "mistral-document-ai-2505"]
+# pdf_text_extractor = [
+# "azure-document-intelligence",
+# "mistral-document-ai-2505",
+# "pypdfium2-extract-pdf",
+# ]
+# image_text_extractor = [
+# "azure-document-intelligence",
+# "mistral-document-ai-2505",
+# ]
+####################################################################################################
diff --git a/api/.pipelex/inference/deck/x_custom_llm_deck.toml b/api/.pipelex/inference/deck/x_custom_llm_deck.toml
new file mode 100644
index 000000000..d751552d1
--- /dev/null
+++ b/api/.pipelex/inference/deck/x_custom_llm_deck.toml
@@ -0,0 +1,72 @@
+####################################################################################################
+# Pipelex Model Deck - Custom Configurations for LLMs
+####################################################################################################
+#
+# This file allows you to override or complete the base model decks.
+#
+# ADVANCED USERS ONLY: This file is for users who bring their own API keys and connect directly
+# to AI providers (OpenAI, Anthropic, Google, etc.) without using the Pipelex Gateway.
+#
+# If you're using the standard Pipelex Gateway setup, you don't need to modify this file.
+# The Gateway handles model routing automatically and supports all available models.
+#
+# Waterfalls are useful when using multiple backends directly - they define ordered lists
+# of models that are resolved at configuration time based on which backends are available.
+# This enables defining pipelines that work across different environments with varying
+# backend configurations.
+#
+# Documentation: https://docs.pipelex.com
+# Support: https://go.pipelex.com/discord
+#
+####################################################################################################
+
+####################################################################################################
+# LLM Deck overrides
+####################################################################################################
+
+[llm.choice_overrides]
+for_text = "disabled"
+for_object = "disabled"
+
+
+####################################################################################################
+# Waterfalls — ordered lists of models resolved at configuration time by backend availability
+#####################################################################################################
+
+# Example (uncomment to use):
+# [llm.waterfalls]
+# premium-llm = ["claude-4.5-opus", "gemini-3.1-pro", "gpt-5.4", "grok-4"]
+# premium-llm-vision = [
+# "claude-4.5-opus",
+# "gemini-3.1-pro",
+# "gpt-5.4",
+# "grok-4-fast-reasoning",
+# ]
+# premium-llm-structured = [
+# "claude-4.5-opus",
+# "gemini-3.1-pro",
+# "gpt-5.4",
+# "grok-4",
+# ]
+# large-context-llm-code = [
+# "gemini-3.1-pro",
+# "claude-4.5-opus",
+# "gpt-5.4",
+# "grok-4-fast-reasoning",
+# ]
+# large-context-llm-text = ["gemini-2.5-flash", "claude-4.5-sonnet"]
+# small-llm = [
+# "gemini-2.5-flash-lite",
+# "gpt-4o-mini",
+# "claude-3-haiku",
+# "phi-4",
+# "grok-3-mini",
+# ]
+# small-llm-structured = [
+# "gemini-2.5-flash-lite",
+# "gpt-4o-mini",
+# "claude-3-haiku",
+# ]
+# small-llm-vision = ["gemini-2.5-flash-lite", "gpt-4o-mini", "claude-3-haiku"]
+# small-llm-creative = ["gemini-2.5-flash-lite", "gpt-4o-mini", "claude-3-haiku"]
+####################################################################################################
diff --git a/api/.pipelex/inference/routing_profiles.toml b/api/.pipelex/inference/routing_profiles.toml
new file mode 100644
index 000000000..57407e0a6
--- /dev/null
+++ b/api/.pipelex/inference/routing_profiles.toml
@@ -0,0 +1,168 @@
+# Routing profile library - Routes models to their backends
+# =========================================================================================
+# This file controls which backend serves which model.
+# Simply change the 'active' field to switch profiles,
+# or you can add your own custom profiles.
+#
+# Documentation: https://docs.pipelex.com
+# Support: https://go.pipelex.com/discord
+# =========================================================================================
+
+# Note: The internal backend (software-only models) is always available regardless of
+# which routing profile you select. See the documentation for details.
+
+# Which profile to use (change this to switch routing)
+active = "all_pipelex_gateway"
+
+# We recommend using the "all_pipelex_gateway" profile to get a head start with all models.
+# To use the Pipelex Gateway backend:
+# 1. Get your API key at https://app.pipelex.com (free credits included)
+# 2. Add it to your .env file: PIPELEX_GATEWAY_API_KEY=your-key-here
+# 3. Run `pipelex init` and accept the Gateway terms of service
+
+# =========================================================================================
+# Routing Profiles
+# =========================================================================================
+
+[profiles.all_pipelex_gateway]
+description = "Use Pipelex Gateway for all its supported models"
+default = "pipelex_gateway"
+
+# 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.
+[profiles.all_pipelex_manifold]
+description = "Use Pipelex Manifold (private beta) for all its supported models"
+default = "pipelex_manifold"
+
+[profiles.all_anthropic]
+description = "Use Anthropic backend for all its supported models"
+default = "anthropic"
+
+[profiles.all_azure_openai]
+description = "Use Azure OpenAI backend for all its supported models"
+default = "azure_openai"
+
+[profiles.all_bedrock]
+description = "Use Bedrock backend for all its supported models"
+default = "bedrock"
+
+[profiles.all_blackboxai]
+description = "Use BlackBoxAI backend for all its supported models"
+default = "blackboxai"
+
+[profiles.all_fal]
+description = "Use FAL backend for all its supported models"
+default = "fal"
+
+[profiles.all_google]
+description = "Use Google GenAI backend for all its supported models"
+default = "google"
+
+[profiles.all_groq]
+description = "Use groq backend for all its supported models"
+default = "groq"
+
+[profiles.all_huggingface]
+description = "Use HuggingFace backend for all its supported models"
+default = "huggingface"
+
+[profiles.all_linkup]
+description = "Use Linkup backend for all its supported models"
+default = "linkup"
+
+[profiles.all_minimax]
+description = "Use MiniMax backend for all its supported models"
+default = "minimax"
+
+[profiles.all_mistral]
+description = "Use Mistral backend for all its supported models"
+default = "mistral"
+
+[profiles.all_ollama]
+description = "Use Ollama backend for all its supported models"
+default = "ollama"
+
+[profiles.all_openai]
+description = "Use OpenAI backend for all its supported models"
+default = "openai"
+
+[profiles.all_openrouter]
+description = "Use OpenRouter backend for all its supported models"
+default = "openrouter"
+
+[profiles.all_portkey]
+description = "Use Portkey backend for all its supported models"
+default = "portkey"
+
+[profiles.all_scaleway]
+description = "Use Scaleway backend for all its supported models"
+default = "scaleway"
+
+[profiles.all_vertexai]
+description = "Use Vertex AI backend for all its supported models"
+default = "vertexai"
+
+[profiles.all_xai]
+description = "Use xAI backend for all its supported models"
+default = "xai"
+
+[profiles.all_internal]
+description = "Use internal backend for all its supported models"
+default = "internal"
+
+# =========================================================================================
+# Custom Profiles
+# =========================================================================================
+# Add your own profiles below following the same pattern:
+#
+# [profiles.your_profile_name]
+# description = "What this profile does"
+# default = "backend-name" # Where to route models by default
+# [profiles.your_profile_name.routes]
+# "model-pattern" = "backend-name" # Specific routing rules
+#
+# Pattern matching supports:
+# - Exact names: "gpt-4o-mini"
+# - Wildcards: "claude-*" (matches all models starting with claude-)
+# - Partial wildcards: "*-sonnet" (matches all sonnet variants)
+
+# =========================================================================================
+# Example of a custom routing profile with mostly pattern matching and one specific model
+# =========================================================================================
+[profiles.example_routing_using_patterns]
+description = "Example routing profile using patterns"
+default = "pipelex_gateway"
+
+[profiles.example_routing_using_patterns.routes]
+# Pattern matching: "model-pattern" = "backend-name"
+"gpt-*" = "azure_openai"
+"claude-*" = "bedrock"
+"gemini-*" = "google"
+"grok-*" = "xai"
+"*-sdxl" = "fal"
+"flux-*" = "fal"
+"gpt-image-1" = "openai"
+
+# =========================================================================================
+# Example of a custom routing profile with specific model matching
+# =========================================================================================
+
+[profiles.example_routing_using_specific_models]
+description = "Example routing profile using specific models"
+
+[profiles.example_routing_using_specific_models.routes]
+"gpt-5.4-nano" = "pipelex_gateway"
+"gpt-4o-mini" = "blackboxai"
+"gpt-5.4-mini" = "openai"
+"gpt-5.5" = "azure_openai"
+
+"claude-4-sonnet" = "pipelex_gateway"
+"claude-3.7-sonnet" = "blackboxai"
+
+"gemini-2.5-flash-lite" = "pipelex_gateway"
+"gemini-2.5-flash" = "blackboxai"
+"gemini-2.5-pro" = "vertexai"
+
+"grok-3" = "pipelex_gateway"
+"grok-3-mini" = "xai"
diff --git a/api/.pipelex/pipelex.toml b/api/.pipelex/pipelex.toml
new file mode 100644
index 000000000..e19d43c18
--- /dev/null
+++ b/api/.pipelex/pipelex.toml
@@ -0,0 +1,210 @@
+####################################################################################################
+# Pipelex Configuration File
+####################################################################################################
+#
+# This configuration file is copied to client projects' .pipelex/ directory when running:
+# `pipelex init config`
+#
+# Purpose:
+# - This file allows you to override Pipelex's default settings for specific projects
+# - All values below are set to their defaults - modify them as needed
+# - The values here will override the defaults from the Pipelex package
+#
+# Finding Available Settings:
+# - See the full default configuration in: pipelex/pipelex.toml (in the Pipelex package)
+# - See the configuration structure classes in: pipelex/config.py and pipelex/cogt/config_cogt.py
+#
+# Common customizations include:
+# - Logging levels and behavior
+# - Excluded directories for scanning
+# - LLM prompt dumping for debugging
+# - Feature flags
+# - Observer and reporting output directories
+#
+# Documentation: https://docs.pipelex.com
+# Support: https://go.pipelex.com/discord
+#
+####################################################################################################
+
+####################################################################################################
+# Pipeline Execution Config
+####################################################################################################
+
+[interpreter.pipeline_execution]
+# Set to false to disable conversion of incoming data URLs to pipelex-storage:// URIs
+is_normalize_data_urls_to_storage = true
+# Set to false to disable generation of execution graphs
+is_generate_graph = true
+
+[interpreter.pipeline_execution.graph.data_inclusion]
+# Control what data is included in graph outputs
+stuff_json_content = true
+error_stack_traces = true
+
+[interpreter.pipeline_execution.graph.graphs_inclusion]
+# Control which graph outputs are generated
+graphspec_json = true
+mermaidflow_mmd = true
+mermaidflow_html = true
+reactflow_html = true
+
+[interpreter.pipeline_execution.graph.reactflow]
+# Customize ReactFlow graph rendering
+edge_type = "bezier" # Options: "bezier", "smoothstep", "step", "straight"
+nodesep = 50 # Horizontal spacing between nodes
+ranksep = 30 # Vertical spacing between ranks/levels
+initial_zoom = 1.0 # Initial zoom level (1.0 = 100%)
+pan_to_top = true # Pan to show top of graph on load
+
+[interpreter.pipeline_execution.graph.reactflow.style]
+theme = "dark"
+palette = "dracula"
+
+####################################################################################################
+# Scan Config
+####################################################################################################
+
+[interpreter.scan]
+# Directories to exclude when scanning for pipeline files
+excluded_dirs = [
+ ".venv",
+ "venv",
+ "env",
+ ".env",
+ "virtualenv",
+ ".virtualenv",
+ ".git",
+ "__pycache__",
+ ".pytest_cache",
+ ".mypy_cache",
+ ".ruff_cache",
+ "node_modules",
+ "results",
+]
+
+####################################################################################################
+# Builder Config
+####################################################################################################
+
+[interpreter.builder]
+# Settings for generated pipelines
+default_output_dir = "."
+default_bundle_file_name = "bundle"
+default_directory_base_name = "pipeline"
+
+####################################################################################################
+# Inference Config (model deck, LLM, image generation, extraction)
+####################################################################################################
+
+[inference.model_deck]
+# Model fallback behavior: if true, uses secondary model options when primary fails
+is_model_fallback_enabled = true
+# Reaction to missing presets: "raise", "log", or "none"
+missing_presets_reaction = "log"
+
+[inference.llm]
+# Enable dumping of LLM inputs/outputs for debugging
+is_dump_text_prompts_enabled = false
+is_dump_response_text_enabled = false
+
+[inference.llm.instructor]
+# Enable dumping of structured content generation details for debugging
+is_dump_kwargs_enabled = false
+is_dump_response_enabled = false
+is_dump_error_enabled = false
+
+####################################################################################################
+# Storage Config
+####################################################################################################
+
+[runtime.storage]
+# Storage method: "local", "in_memory", "s3", or "gcp"
+method = "local"
+# Whether to fetch remote HTTP URLs and store them locally
+is_fetch_remote_content_enabled = true
+# Whether to upload local file paths to storage and replace with pipelex-storage:// URIs
+is_upload_local_content_enabled = true
+
+[runtime.storage.local]
+# Local storage settings
+uri_format = "{hash}.{extension}"
+local_storage_path = ".pipelex/storage"
+
+[runtime.storage.in_memory]
+# In-memory storage settings
+uri_format = "{hash}.{extension}"
+
+[runtime.storage.s3]
+# AWS S3 storage settings (requires boto3: `pip install pipelex[s3]`)
+uri_format = "{hash}.{extension}"
+bucket_name = ""
+region = ""
+signed_urls_lifespan_seconds = 3600 # Set to "disabled" for public URLs
+
+[runtime.storage.gcp]
+# Google Cloud Storage settings (requires google-cloud-storage: `pip install pipelex[gcp-storage]`)
+uri_format = "{hash}.{extension}"
+bucket_name = ""
+project_id = ""
+signed_urls_lifespan_seconds = 3600 # Set to "disabled" for public URLs
+
+####################################################################################################
+# Log Config
+####################################################################################################
+
+[runtime.log]
+# Default logging level: "DEBUG", "INFO", "WARNING", "ERROR"
+default_log_level = "INFO"
+# The registered log sink this server installs. "json" writes one JSON object per line, with every
+# field, the bound run identifiers and the message flat beside each other — the shape a log agent
+# in front of a container ingests without a parser. The alternative, "console", is the Rich
+# renderer meant for a terminal; this server does not ask for the `cli` extra that declares Rich,
+# which is what makes the renderer unused here rather than unavailable — see pretty_print_mode.
+sink = "json"
+# The stream the json sink writes to: "stdout" or "stderr". Logs are diagnostics and belong off
+# the data channel.
+console_log_target = "stderr"
+console_print_target = "stdout"
+# The panels `pretty_print(...)` draws, the "Output of pipe" one after every operator pipe among
+# them. A server has no terminal to draw into and must not spend time rendering on the thread
+# serving a request, so nothing is printed and no renderable is built. This is what keeps Rich off
+# the request path, and it is not the same as keeping it out of the image: `typer` and `instructor`
+# are core pipelex dependencies that require Rich unconditionally, so an `import pipelex` loads it
+# whatever this file says. Selecting "rich" here, or the "console" sink above, would therefore work
+# rather than refuse — these two keys are the whole of what keeps the renderer unused.
+pretty_print_mode = "silent"
+
+[runtime.log.package_log_levels]
+# Log levels for specific packages (use "-" instead of "." in package names)
+pipelex = "INFO"
+
+####################################################################################################
+# Reporting Config
+####################################################################################################
+
+[runtime.reporting]
+# Cost reporting settings
+is_log_costs_to_console = false
+is_generate_cost_report_file_enabled = false
+cost_report_dir_path = "reports"
+cost_report_base_name = "cost_report"
+cost_report_extension = "csv"
+cost_report_unit_scale = 1.0
+
+####################################################################################################
+# Tracing Config
+####################################################################################################
+
+[runtime.tracing]
+# Tracing is opt-in. Enable in your own pipelex_override.toml and set the backend
+# of your choice. See pipelex/pipelex.toml in the Pipelex package for all options.
+is_enabled = false
+backend = "ndjson"
+
+[runtime.tracing.ndjson]
+traces_dir = ".pipelex/traces"
+
+[runtime.tracing.dynamodb]
+# Configure your own table_name + region in your override file when backend = "dynamodb".
+table_name = ""
+region = ""
diff --git a/api/.pipelex/pipelex_service.toml b/api/.pipelex/pipelex_service.toml
new file mode 100644
index 000000000..afe39a2bd
--- /dev/null
+++ b/api/.pipelex/pipelex_service.toml
@@ -0,0 +1,19 @@
+####################################################################################################
+# Pipelex Service Configuration
+####################################################################################################
+#
+# This file stores settings related to Pipelex managed services.
+# Currently used for Pipelex Gateway terms acceptance.
+#
+# Documentation: https://docs.pipelex.com
+# Support: https://go.pipelex.com/discord
+#
+####################################################################################################
+
+[agreement]
+# Set to true after accepting Pipelex terms of service.
+terms_accepted = true
+
+# Note: when using pipelex_gateway, telemetry is enabled to monitor service usage.
+# We collect technical data (model, pipe type...) and quantitative data (token counts...)
+# but NOT your content, pipe codes, or output class names.
diff --git a/api/.pipelex/plxt.toml b/api/.pipelex/plxt.toml
new file mode 100644
index 000000000..f1aacd76b
--- /dev/null
+++ b/api/.pipelex/plxt.toml
@@ -0,0 +1,120 @@
+# =============================================================================
+# Pipelex TOML Configuration for pipelex-demo
+# =============================================================================
+# Configures MTHDS/TOML formatting and linting behaviour for this project.
+# Powered by the Pipelex extension (plxt / taplo engine).
+#
+# Docs: https://taplo.tamasfe.dev/configuration/
+# =============================================================================
+
+# ---------------------------------------------------------------------------
+# File discovery
+# ---------------------------------------------------------------------------
+
+# Glob patterns for files to process.
+include = ["**/*.toml", "**/*.mthds"]
+
+exclude = [
+ ".venv/**",
+ ".mypy_cache/**",
+ ".ruff_cache/**",
+ ".pytest_cache/**",
+ "__pycache__/**",
+ "target/**",
+ "node_modules/**",
+ ".git/**",
+ "*.lock",
+] # Glob patterns for files to ignore.
+# These are evaluated relative to the config file location.
+
+# =============================================================================
+# Global formatting defaults
+# =============================================================================
+# These apply to every file matched by `include` unless overridden by a
+# [[rule]].formatting section below. Every option is shown at its built-in
+# default so you can tune any of them in one place.
+
+[formatting]
+align_entries = false # line up "=" signs across consecutive entries
+align_comments = true # align end-of-line comments on consecutive lines
+align_single_comments = true # also align lone comments (requires align_comments)
+array_trailing_comma = true
+array_auto_expand = true # go multiline when array exceeds column_width
+array_auto_collapse = false # don't re-collapse multiline arrays that fit
+inline_table_expand = true # expand inline tables exceeding column_width
+compact_arrays = true # [1, 2] not [ 1, 2 ]
+compact_inline_tables = false # keep spaces inside braces: { a = 1 }
+compact_entries = false # keep spaces around "=": key = value
+column_width = 80
+indent_tables = false
+indent_entries = false
+indent_string = " "
+trailing_newline = true
+reorder_keys = false
+reorder_arrays = false
+reorder_inline_tables = false
+allowed_blank_lines = 2
+crlf = false
+
+# =============================================================================
+# Per-file-type rules
+# =============================================================================
+# Each [[rule]] can narrow its scope with `include` / `exclude` globs and
+# provide its own [rule.formatting] overrides. Options not listed here fall
+# back to the global [formatting] section above.
+
+
+# ---------------------------------------------------------------------------
+# Rule: TOML files
+# ---------------------------------------------------------------------------
+[[rule]]
+# Which files this rule applies to (relative globs).
+include = ["**/*.toml"]
+
+# Per-rule formatting overrides — all at defaults so you can tweak them
+# independently of .mthds files.
+[rule.formatting]
+# align_entries = false
+# align_comments = true
+# align_single_comments = true
+# array_trailing_comma = true
+# array_auto_expand = true
+# array_auto_collapse = true
+# inline_table_expand = true
+# compact_arrays = true
+# compact_inline_tables = false
+# compact_entries = false
+# column_width = 80
+# indent_tables = false
+# indent_entries = false
+# indent_string = " "
+# trailing_newline = true
+# allowed_blank_lines = 2
+
+
+# ---------------------------------------------------------------------------
+# Rule: MTHDS files (Pipelex pipeline definitions)
+# ---------------------------------------------------------------------------
+[[rule]]
+# Which files this rule applies to (relative globs).
+include = ["**/*.mthds"]
+
+# Per-rule formatting overrides — all at defaults so you can tweak them
+# independently of .toml files.
+[rule.formatting]
+align_entries = true
+# align_comments = true
+# align_single_comments = true
+# array_trailing_comma = true
+# array_auto_expand = true
+# array_auto_collapse = true
+# inline_table_expand = true
+# compact_arrays = true
+# compact_inline_tables = false
+# compact_entries = false
+# column_width = 80
+# indent_tables = false
+# indent_entries = false
+# indent_string = " "
+# trailing_newline = true
+# allowed_blank_lines = 2
diff --git a/api/.pipelex/telemetry.toml b/api/.pipelex/telemetry.toml
new file mode 100644
index 000000000..ed9a90901
--- /dev/null
+++ b/api/.pipelex/telemetry.toml
@@ -0,0 +1,92 @@
+####################################################################################################
+# Custom Telemetry Configuration
+####################################################################################################
+#
+# This file controls YOUR custom telemetry settings for observability and analytics.
+# Configure your own PostHog, Langfuse, or OTLP-compatible backends here.
+#
+# NOTE: When using Pipelex Gateway, identified telemetry is automatically enabled
+# (tied to your Gateway API key, hashed for security). This allows us to monitor
+# service quality, enforce fair usage, and provide you with better support.
+# Gateway telemetry operates independently from your settings below - you can have both!
+#
+# To disable all telemetry, set the DO_NOT_TRACK=1 environment variable.
+#
+# Documentation: https://docs.pipelex.com
+# Support: https://go.pipelex.com/discord
+#
+####################################################################################################
+
+# ──────────────────────────────────────────────────────────────────────────────
+# PostHog Configuration (Event tracking + AI span tracing)
+# ──────────────────────────────────────────────────────────────────────────────
+
+[custom_posthog]
+mode = "off" # Values: "off" | "anonymous" | "identified"
+# user_id = "your_user_id" # Required when mode = "identified"
+endpoint = "${POSTHOG_ENDPOINT}" # Default: https://us.i.posthog.com (or https://eu.i.posthog.com for EU)
+api_key = "${POSTHOG_API_KEY}" # Get from PostHog Project Settings
+geoip = true # Enable GeoIP lookup
+debug = false # Enable PostHog debug mode
+redact_properties = [
+ "prompt",
+ "system_prompt",
+ "response",
+ "file_path",
+ "url",
+] # Event properties to redact
+
+# AI span tracing to YOUR PostHog (does NOT affect Langfuse/OTLP - they receive full data)
+[custom_posthog.tracing]
+enabled = false # Send AI spans to your PostHog
+
+# Privacy controls for data sent to YOUR PostHog only
+[custom_posthog.tracing.capture]
+content = false # Capture prompt/completion content
+# content_max_length = 1000 # Max length for captured content (omit for unlimited)
+pipe_codes = false # Include pipe codes in span names/attributes
+output_class_names = false # Include output class names in span names/attributes
+
+# ──────────────────────────────────────────────────────────────────────────────
+# Portkey SDK Configuration
+# ──────────────────────────────────────────────────────────────────────────────
+
+[custom_portkey]
+force_debug_enabled = false
+force_tracing_enabled = false
+
+# ──────────────────────────────────────────────────────────────────────────────
+# Langfuse Integration
+# Note: Langfuse receives FULL span data (no redaction)
+# ──────────────────────────────────────────────────────────────────────────────
+
+[langfuse]
+enabled = false
+# endpoint = "https://cloud.langfuse.com" # Override for self-hosted Langfuse
+# public_key = "${LANGFUSE_PUBLIC_KEY}" # Langfuse public key
+# secret_key = "${LANGFUSE_SECRET_KEY}" # Langfuse secret key
+
+# ──────────────────────────────────────────────────────────────────────────────
+# Additional OTLP Exporters (array for multiple)
+# Note: OTLP exporters receive FULL span data (no redaction)
+# ──────────────────────────────────────────────────────────────────────────────
+
+# [[otlp]]
+# name = "my-collector" # Identifier for logging
+# endpoint = "https://..." # OTLP endpoint URL
+# headers = { Authorization = "Bearer ${OTLP_AUTH_TOKEN}" } # Headers for OTLP export
+
+# ──────────────────────────────────────────────────────────────────────────────
+# Custom Telemetry Allowed Modes
+# Controls which integration modes can use custom telemetry settings above.
+# ──────────────────────────────────────────────────────────────────────────────
+
+[telemetry_allowed_modes]
+ci = false # CI environments don't use custom telemetry
+cli = true # CLI usage allows custom telemetry
+docker = true # Docker deployments allow custom telemetry
+fastapi = true # FastAPI integrations allow custom telemetry
+mcp = true # MCP integrations allow custom telemetry
+n8n = true # n8n integrations allow custom telemetry
+pytest = false # Tests don't use custom telemetry
+python = false # Direct Python SDK usage doesn't use custom telemetry by default
diff --git a/api/CHANGELOG.md b/api/CHANGELOG.md
new file mode 100644
index 000000000..c5a194758
--- /dev/null
+++ b/api/CHANGELOG.md
@@ -0,0 +1,862 @@
+# Changelog
+
+This changelog ends at v0.33.2, the server's last release from the `Pipelex/pipelex-api` repository. The server is now released together with pipelex, under pipelex's version, and its changes are recorded in the pipelex repository's own `CHANGELOG.md`.
+
+## [v0.33.2] - 2026-10-01
+
+### Changed
+
+- **The server is moving into `Pipelex/pipelex`**: from the next release, the server ships from the pipelex repository's `api/` directory together with the pipelex library and under its version number, so the next `pipelex/pipelex-api` image tag is a pipelex version; the image name, its port and its `/root/.pipelex` mount do not change, and this repository will be archived once the move lands.
+
+### Fixed
+
+- **The `callback_urls` description says what a completion webhook carries**: the OpenAPI description and the run docs said the runner posts the run's result to each callback URL; they now say the body is a completion notice (`pipeline_run_id`, `state` with its legacy `status` alias, the `result_url` storage key prefix and `error`), and that the results themselves stay in storage under that prefix. The description also says that the `X-Completion-Signature` header signs the run id, not the body.
+
+## [v0.33.1] - 2026-09-30
+
+### Fixed
+
+- **A pipe selection refusal names its failure in `error_type`**: on `POST /v1/pipe-io` and `POST /v1/build/inputs`, `/v1/build/output` and `/v1/build/runner`, a selection the server cannot make is still an input `422`, but its `error_type` is now `EntryPipeNotFoundError` (a `pipe_ref` naming no pipe, a manifest `main_pipe` the closure lacks, or no `pipe_ref` over a closure declaring no `main_pipe`) or `EntryPipeAmbiguousError` (a bare code matching several domains, or no `pipe_ref` over a closure whose domains declare several `main_pipe`s), the values the run routes answer for an unknown or ambiguous `pipe_code`, where it was the `ValidationError` of a malformed request. The problem's `type` and `title` follow the class, and so does its `user_action`, except that the two refusals of an omitted `pipe_ref` ask for a `pipe_ref` instead of a pipe-code check.
+- **The published OpenAPI never names the hosted selector field**: the `POST /v1/pipe-io` request schema's description no longer names the hosted catalog's selector field, and a test keeps that name out of the whole document.
+
+## [v0.33.0] - 2026-09-30
+
+### Highlights
+
+**A method's I/O artifacts without a validation.** `POST /v1/pipe-io` returns the pipe I/O contracts, input form and output form of one pipe, or of every pipe, off one load of the method and with no dry run, so a caller that shows a method, prepares its inputs or generates types for it no longer pays for a `/v1/validate` sweep. The per-pipe selectors also stop calling an ambiguous pipe missing.
+
+### Added
+
+- **`POST /v1/pipe-io`**: returns a method's `pipe_io_contracts`, `input_form` and `output_form` without a dry run, keyed by qualified `pipe_ref`, for the selected pipe or, with `all_pipes: true`, for every pipe, beside the resolved `pipe_ref`, the method's own `default_pipe_ref`, `pending_signatures` and `is_runnable`. It takes the same `files` or `method_ref` closure selector and `pipe_ref` as the `/v1/build/*` routes, `include_files: true` echoes the closure's `.mthds` files, and each artifact equals `/v1/validate`'s same-named view for a closure both routes accept.
+
+### Fixed
+
+- **An ambiguous pipe selector says it is ambiguous**: on `POST /v1/build/inputs`, `/v1/build/output` and `/v1/build/runner`, a bare `pipe_ref` or manifest `main_pipe` that matches pipes in several domains is still a `422`, and its detail now says the code matches several domains and names the qualified refs to choose from, where it said the pipe was not found.
+
+## [v0.32.0] - 2026-09-29
+
+### Highlights
+
+**The runner no longer trusts the run body or the methods it is handed.** `POST /v1/execute` and `POST /v1/start` parse their body as plain JSON, which closes a path by which any caller could make the runner import and instantiate a class. On `pipelex` 0.70.0, a run reads storage only under its read scope, every template renders in Jinja's sandbox, a URL fetch refuses private destinations, and a sandbox-hosted deployment refuses a bundle that declares Python structure classes. A multi-tenant host must now send `read_scope`, and a method that ran on 0.69.0 can now be refused, as the entries below describe.
+
+### Changed
+
+- **Pinned `pipelex` 0.70.0 (Breaking)**: up from `==0.69.0`, exactly. It is the release that carries the read scope and the structure-class refusal described under Security, and it hardens the runtime for methods it did not write, so a method that ran on 0.69.0 can now be refused, as the entries below describe. The `.pipelex/` config shipped here already sits at the current schema, and the release moves no own-key backend's model roster.
+- **PipeCompose, PipeSearch and PipeImgGen refuse an input they never read (Breaking)**: as PipeLLM already did, validation refuses a declared input that none of the pipe's templates reads, as `extraneous_input_variable` naming the input. Reference it in a template, or remove it from `inputs`.
+- **A structure field naming an undeclared concept refuses the load (Breaking)**: a concept whose field names a concept that no bundle it can see declares is now refused at load with `LibraryLoadingError`, naming the concept, its bundle and the missing structure class, where it loaded and then failed at first use with pydantic's "not fully defined" error.
+- **`POST /v1/codegen` stamps `engine_version` `0.70.0`**: the stamp is the pinned `pipelex` version, so a `codegen.lock` committed against `0.69.0` no longer matches until it is regenerated. `POST /v1/build/runner` carries the same stamp.
+
+### Fixed
+
+- **A template's reads are seen wherever it makes them**: an input read only through a subscript, a call or a `{% set %}`, such as `{{ items[0].text }}` or `{{ record['meta'].title }}`, now counts as read, where validation refused it as unread, and `{{ combo.summary }}` resolves the named parts of a `Composite` output, which rendered empty.
+- **Concepts holding other concepts resolve**: a field typed by a method package's concept, by a concept an earlier load declared, by a concept backed by a Python class, or as `native.Anything` now resolves, where each loaded and then failed at first use with pydantic's "not fully defined" error.
+- **A generated file's storage key names its format**: a fetched `image/svg+xml` is stored under a `.svg` key, and a type with no extension of its own under `.bin`, where both got `.jpg`.
+
+### Security
+
+- **The run body is plain JSON, and class markers in it are refused (Breaking)**: `POST /v1/execute` and `POST /v1/start` parse their body with a plain JSON parser instead of kajson, which imported and instantiated any class a body named with `__class__` and `__module__`, so any caller able to reach the runner could run code on it. A body carrying a `__class__` or `__module__` key, or a key starting with `__kajson`, in any object at any depth now answers `422 ReservedObjectKey`, and the published request schema no longer offers a serialized working memory as `inputs`.
+- **Runs read only under their read scope (Breaking)**: `POST /v1/execute` and `POST /v1/start` take a `read_scope`, the prefix every `pipelex-storage://` key a run reads must lie under, and a scoped run reads no local path. Omitted, it is the caller's own id on a deployment that identifies callers and unscoped on a single-tenant one, so a multi-tenant host must send it; a malformed read scope, or a storage scope outside it, is a `422` `InvalidReadScope`. A read outside the scope is refused when the run makes it, as `UriReadRefusedError`: a `422` on `/execute`, and on `/start` a synchronous `422` for an input or a run that ends `FAILED` for a URL a pipe reaches during the run.
+- **A bundle declaring Python structure classes is refused (Breaking)**: on a sandbox-hosted deployment, a `files` or `bundle_b64` bundle whose Python declares a `StructuredContent` subclass now answers `403` `MethodStructuresRefusedError` naming each file and class, as a fetched `method_ref` package already did, and none of its modules is imported. Declare the types as MTHDS concepts instead; the unedited module `pipelex build structures` writes is accepted.
+- **Every template renders in Jinja's sandbox (Breaking)**: a prompt, a compose or construct template, an image or search prompt, or a condition expression may read data and call methods of plain values only. One that reaches for a Python internal, calls a method of a Pipelex or pydantic object, or reads a name starting with an underscore other than an input's `_stuff_name`, `_content_class`, `_concept_code` and `_stuff_code` fails with `Jinja2TemplateSecurityError`, and validation refuses the visible cases as `template_private_name`. `_content` and `stuff` are no longer readable on an input, and a PipeCompose construct `from` path or a `list_to_dict_keyed_by` name with a segment starting with an underscore is refused at validation.
+- **Fetching a URL refuses private destinations (Breaking)**: every download of a URL a value carries, such as a document to extract or a prompt image for a provider that does not take URLs, now refuses a host that is `localhost`, a cloud metadata alias, or resolves to a private, loopback, link-local or metadata address, on every redirect hop, and fails the pipe with `SsrfBlockedError` naming the host. The guarded fetch ignores `HTTP_PROXY` and `HTTPS_PROXY`. The image keeps the guard on; a self-hosted deployment reading documents from an intranet host, or reaching the internet only through a proxy, sets `[runtime.network] is_fetch_ssrf_guard_enabled = false`, as [Configuration](docs/configuration.md) describes.
+
+## [v0.31.0] - 2026-09-28
+
+### Highlights
+
+**Run inputs take the values their concept declares, and own-key backends offer today's models.** On `pipelex` 0.69.0, an `Anything` input accepts a string, a number, a boolean or an object and a `JSON` input an object, where most of them used to be refused, and the image's own-key backend files are now the pinned release's, so a deployment that switches one on is offered the current model roster. A deployment that mounts its own `.pipelex/` renames its Bedrock handle to `bedrock_aioboto` and replaces any model handle that went.
+
+### Changed
+
+- **Pinned `pipelex` 0.69.0 (Breaking)**: up from `==0.68.0`, exactly, the release that moves structured output to `instructor` 1.17 and the provider SDKs with it, so the image now carries `mistralai` 2.x and `aiobotocore` 3.x in place of `aioboto3`. Under `instructor` 1.17 the `instructor/openai_structured_outputs` structure method sends a non-strict tool schema, so OpenAI no longer enforces the schema itself; pipelex still validates the response and re-asks on a mismatch.
+- **The Bedrock SDK handle is `bedrock_aioboto` (Breaking)**: the shipped `.pipelex/inference/backends/bedrock.toml` now sets `sdk = "bedrock_aioboto"`, and a deployment that mounts its own `.pipelex/` still setting `sdk = "bedrock_aioboto3"` keeps booting but fails every call to those Bedrock models. `pipelex migrate` names such a file without rewriting it, so replace the handle by hand, in `[defaults]` and in any model table that overrides it.
+- **`Anything` and `JSON` run inputs are read by what they declare (Breaking)**: on `POST /v1/execute` and `POST /v1/start`, a bare string at an `Anything` input becomes a `native.Anything` value rather than `native.Text`, a bare string at a `JSON` input is refused, an item holding `concept` and `content` keys inside a bare `Anything[]` or `JSON[]` list is refused, an explicit single value at a fixed-count `Concept[N]` input raises `MultiplicityCountMismatchError`, and `NaN` or an infinity at a `Number`, `JSON` or `Anything` input is refused. A value the fallback cannot build, such as a list of plain objects at a `Dynamic` input, now answers `StructureValidationError` naming the input and its concept instead of `StuffFactoryError`.
+- **The `json_schema` of an `Anything` value excludes arrays and `null`**: in the `pipe_io_contracts` that `POST /v1/validate` and `POST /v1/execute` return, the `json_schema` of a single `Anything` input or output now carries `"not": {"type": ["array", "null"]}`, and so does the `items` schema of an `Anything[]` input, so a form or validator generated from it refuses what the run refuses.
+- **`POST /v1/build/inputs` renders a `JSON` input as the bare object (Breaking)**: the compact template of a `JSON` input is the object itself, where it was the envelope `{"concept": "native.JSON", "content": {"json_obj": …}}`.
+- **`POST /v1/codegen` stamps `engine_version` `0.69.0`**: the stamp is the pinned `pipelex` version, so a `codegen.lock` committed against `0.68.0` no longer matches until it is regenerated. `POST /v1/build/runner` carries the same stamp.
+- **Own-key backends offer the pinned `pipelex` model roster (Breaking)**: the image's `inference/backends/` files, unchanged since `pipelex` 0.14.0, are now the `pipelex` 0.69.0 kit's, as is `inference/routing_profiles.toml`, so a deployment that switches on an own-key backend is offered the current models and resolves the model deck's default aliases, whose GPT-5.6 targets `openai` and `azure_openai` did not declare. Handles that went, which a method must replace on a deployment that switched their backend on: on `openai`, `gpt-3.5-turbo`, `gpt-4`, `gpt-4-turbo`, the dated `gpt-4o-2024-11-20` and `gpt-4o-mini-2024-07-18`, every `gpt-4.1`, `gpt-5`, `gpt-5.1` and `gpt-5.2` handle, and `o1`, `o3`, `o3-mini` and `o4-mini`; on `azure_openai`, every `gpt-4.1`, `gpt-5`, `gpt-5.1` and `gpt-5.2` handle, and `o1`, `o1-mini`, `o3` and `o3-mini`; on `google` and `portkey`, `gemini-3.0-pro` (replaced by `gemini-3.1-pro`) and `gemini-3.0-flash-preview` (renamed `gemini-3.0-flash`), and on `portkey` also `o4-mini`; on `bedrock`, `claude-3.7-sonnet`; on `openrouter`, `google/gemini-3-pro-preview`. The kit's new `minimax` and `pipelex_manifold` backends ship switched off, the unused `perplexity` and `pipelex_inference` files are gone, and the default Pipelex Gateway deployment, whose catalog comes from the remote config, is unaffected.
+
+### Fixed
+
+- **`Anything` and `JSON` inputs take the values they declare**: an `Anything` input accepts a string, a number, a boolean or an object, and `Anything[]` a list of them, where all but a bare string used to be refused, while `null` and a list at a single `Anything` input, and a `null` or nested-list item of an `Anything[]` list, are refused with a `422`; a `JSON` input accepts an object and `JSON[]` a list of objects, which used to be refused with an error naming neither the input nor its concept.
+- **Structured output on Gemini works with enum fields and honours the prompt settings**: on a deployment that enables the `google` backend, a structured call whose schema has an enum field no longer fails on every attempt, and the system prompt, temperature and token limit now reach Gemini.
+- **A structured-output call keeps its provider error and re-asks when the model returns no tool call**: a rate limit, timeout or refused connection inside a structured call keeps its category and retryability instead of reading as an unknown error, and a response carrying no tool call or no JSON is re-asked instead of failing at once.
+- **A model the inference gateway refuses reads as a configuration fault**: the gateway's `model_not_allowed_error` refusal is now a `config` error whose `user_action` is `change_model` naming the model handle, where it told the caller to review the prompt, parameters and inputs; the status stays `500`.
+
+## [v0.30.0] - 2026-09-28
+
+### Highlights
+
+**A run dispatched to a worker keeps the caller's request id.** On `pipelex` 0.68.0, the lines a worker writes while it runs a `POST /v1/execute` run carry the `request_id` the response echoes, and the runtime's own span moves under `pipelex.*` on every log line.
+
+### Changed
+
+- **Pinned `pipelex` 0.68.0 (Breaking)**: up from `==0.67.0`, exactly, the release whose `execute` accepts the inbound request id the host is serving. The `.pipelex/` config shipped here already sits at the current schema, so no migration is required, but a deployment that selects the `gcp` log sink instead of `json` now refuses to boot when Google rejects its credentials, where it used to boot and lose every record in silence.
+- **A log line's trace keys name the host's span, and the runtime's span moves under `pipelex.*` (Breaking)**: `trace_id`, `span_id` and `trace_flags` now name the process's current OpenTelemetry span, which this server does not open, so they are absent unless the deployment runs it under OpenTelemetry instrumentation of its own. A line the runtime emits from inside a traced run carries the runtime's span as `pipelex.trace_id` and `pipelex.span_id` instead, so a query that joined lines to the runtime's exported spans on `trace_id` now joins on `pipelex.trace_id`.
+- **`POST /v1/codegen` stamps `engine_version` `0.68.0`**: the stamp is the pinned `pipelex` version, so a `codegen.lock` committed against `0.67.0` no longer matches until it is regenerated. `POST /v1/build/runner` carries the same stamp.
+
+### Fixed
+
+- **A distributed `POST /v1/execute` run's worker lines carry the request id**: the route now puts the request id it resolved on the run's metadata, as `POST /v1/start` already did, so on a deployment whose `orchestration_mode` dispatches to a worker, such as `temporal`, the lines the worker writes while it runs the run's workflow and activities carry the `request_id` the response echoes. The logging page now says how the id reaches a worker's lines, and that a `POST /v1/validate` dispatched to a worker does not carry it yet.
+
+## [v0.29.0] - 2026-09-27
+
+### Highlights
+
+**A caught error reaches the caller with its reason and its place.** A run of an invalid bundle is refused before any pipe runs with the same located validation items `/validate` gives, a failed run names the pipe that failed and its root fault, and a run the caller's own method refuses keeps its explanation under STRICT disclosure.
+
+### Added
+
+- **Validation items carry more locators**: a TOML syntax error's item carries the 1-based `line` and `column` the parser stopped at, an `unresolved_concept` item carries `declared_concepts`, and the new `unknown_model` item carries `model_reference` (the reference as the bundle wrote it), `model_type` and `suggestions` (the model deck's close matches of that kind), with an `unsafe` rename fix when there is exactly one. The OpenAPI artifact publishes the new fields and the new `unknown_model` value of `PipeValidationErrorType`.
+- **A run graph marks a list-valued stuff**: every io item of a `graph_spec` carries `multiplicity`, `true` when the stuff is a list, a fixed-count one included, and `null` otherwise, so a renderer can show a `Document[]` input or a `Record[]` output as a list. The schema also admits a positive integer, which the runtime does not emit.
+
+### Changed
+
+- **Pinned `pipelex` 0.67.0 (Breaking)**: up from `==0.66.1`, exactly, the release that carries the located error reporting the entries below describe. The `.pipelex/` config shipped here already sits at the current schema, so no migration is required. The next step of an invalid-bundle verdict, its `user_action.detail`, now reads "Edit the bundle as each validation error says: apply its suggested fix where it has one, after confirming an unsafe one".
+- **The run routes refuse an invalid bundle with its validation verdict (Breaking)**: `POST /v1/execute` and `POST /v1/start` answer every refusal of the bundle while it loads, before any pipe runs, with the `422` `ValidateBundleError` problem document carrying the same located `validation_errors` `POST /v1/validate` gives, which STRICT disclosure keeps. A misspelled concept or a wiring mismatch used to answer a `500`, a TOML fault a `422` without items, and an unknown model the raw model-choice error. An entry pipe the bundle does not declare still answers its own `PipeNotFoundError`.
+- **A failed run reports its root fault, located at the failing pipe (Breaking)**: a run failure's problem document carries the `error_type`, `title`, `type`, `error_domain` and status of the innermost Pipelex error rather than the run-level wrapper's, and its `detail` opens with `Pipe '<pipe>' failed (<entry pipe> → … → <pipe>):`, so a consumer branching on `error_type == "PipelineExecutionError"` branches on the root fault's type. A run the caller's own method refuses, such as a `PipeCondition` whose outcome is `fail`, a `PipeParallel` branch whose multiplicity does not fit its field, a step missing a required input or an inline model the deck does not define, answers a `422` with a `detail` STRICT disclosure keeps, where it answered `500` with `An internal error occurred.`. The completion webhook's `error` carries the same report.
+- **Every load-time refusal is an item of the validation verdict (Breaking)**: `POST /v1/validate`, `POST /v1/resolve`, `POST /v1/codegen` and `POST /v1/build/*` answer any refusal of the submitted bundle, an unknown model and a pipe factory's refusal included, as a `200` `is_valid: false` verdict with a located item, where some of them escaped as a no-verdict problem document.
+- **A failing dry run is one located `dry_run` item per failing pipe (Breaking)**: an invalid verdict's `validation_errors` carries one `dry_run` item per pipe whose dry run failed, with the `pipe_code`, `domain_code` and `source` of the innermost pipe that failed, where it carried a single message-only item for the whole sweep. Its message is the failure's own when that is caller-facing and its title otherwise, so a configuration fault met during a dry run no longer reaches the caller through the verdict.
+- **`POST /v1/codegen` stamps `engine_version` `0.67.0`**: the stamp is the pinned `pipelex` version, so a `codegen.lock` committed against `0.66.1` no longer matches until it is regenerated. `POST /v1/build/runner` carries the same stamp.
+
+### Fixed
+
+- **A verdict names no path on the server**: an item located inside a package a method depends on by address names the bundle by the package's address and its path inside it, and an item located in one of the server's own library directories carries no `source` or `field_path` naming its file, so STRICT disclosure no longer hands a caller a path on the host.
+
+## [v0.28.1] - 2026-09-27
+
+### Changed
+
+- **Pinned `pipelex` 0.66.1**: up from `==0.66.0`, exactly. The release makes loading a library cheaper, since `are_classes_equivalent` settles most comparisons without generating a JSON schema, and it adds `load_from_crate(..., is_crate_prevalidated=True)`, which this server does not call. Nothing on the wire, in the configuration or in the logs moves.
+
+## [v0.28.0] - 2026-09-25
+
+### Highlights
+
+**The runner's logs are structured.** Every line it writes to stderr is one JSON object with each value under a key of its own, the request id rides every record a request emits, the Pipelex runtime's included, and secrets are scrubbed before a line is written.
+
+### Changed
+
+- **The server's logs are structured, one JSON object per line on stderr (Breaking)**: `[runtime.log] sink = "json"` replaces the Rich console renderer, `console_log_target` moves to `stderr`, and `pretty_print_mode = "silent"` stops an operator pipe drawing its "Output of pipe" panel on the thread serving a request. Every value an error line carries — `route`, `status`, `error_type`, `error_domain`, `retryable`, `user_id` / `pipe_code` / `pipeline_run_id` when the request bound them, and `detail` on the failures this API authors itself — is a key of its own now rather than part of a `key=value` run inside the message, and `request_id` rides the runtime's request-scoped log context, so it lands on every record emitted during a request, including the ones Pipelex emits from inside a run. The message is a short sentence built only from the status and the error type, so no caller-supplied string reaches it and the API's own escaping is gone: the sink is what serializes a value now. A log query matching `event=api_error` as text has to move to the `event` field. The new `docs/logging.md` documents the line and every field on it. Uvicorn's own banner and access log are unchanged and still plain text.
+- **Pinned `pipelex` 0.66.0 (Breaking)**: up from `==0.65.0`, exactly, the release that carries the structured-log seam the entry above rides on: named fields and the run-scoped log context, the `json` sink selected by `[runtime.log] sink`, the redaction of secrets before any sink sees a record, and Rich behind the `cli` extra, which this server's extras leave out. On this server's lines that means a credential echoed into `detail` reads `[REDACTED]`, a control character in a field's value reads as its printable escape (`\n` where a caller sent a newline), and a line logged inside a traced run carries `trace_id`, `span_id` and `trace_flags`; `docs/logging.md` says so. The `.pipelex/` config shipped here already sits at the schema that release migrates to, so no migration is required. One change reaches an operator beyond the logs: the S3 storage provider now signs links and reads and writes objects on the bucket's own regional host, `<bucket>.s3.<region>.amazonaws.com`, so a deployment whose egress rules allow S3 by hostname must allow `*.s3.<region>.amazonaws.com`. Nothing on the wire moves.
+- **`POST /v1/codegen` stamps `engine_version` `0.66.0`**: the stamp is the pinned `pipelex` version, so a `codegen.lock` committed against `0.65.0` no longer matches until it is regenerated. `POST /v1/build/runner` carries the same stamp.
+
+### Fixed
+
+- **A local image build no longer bakes the builder's own Pipelex overrides in**: `.pipelex/pipelex_override.toml` and `.pipelex/telemetry_override.toml` are untracked per-developer files, so CI never had them, but `make docker-build` copied whatever the developer had into the image — their storage backend, their log level, their telemetry credentials. A locally built image then behaved differently from the published one, with nothing in the diff to say so. `.dockerignore` excludes them; an operator still supplies overrides to a container by mounting them at `/root/.pipelex`.
+
+## [v0.27.5] - 2026-09-25
+
+### Changed
+
+- **`POST /v1/validate` graphs a `method_ref` package's manifest entry pipe**: the valid arm's `graph_spec` is now drawn from the pipe `default_pipe_ref` names, so a package whose `METHODS.toml` names a `main_pipe` is graphed from that pipe rather than from its primary bundle's own `main_pipe`. A published method whose entry pipe only its manifest declares, which used to answer `graph_spec: null`, now carries its graph, and a manifest `main_pipe` the package does not resolve answers `null` rather than a graph of another pipe. Inline `mthds_contents` are graphed as before.
+- **Pinned `pipelex` 0.65.0**: up from `==0.64.2`, exactly. The runtime's bundle-validator seam now takes the pipe to graph, which the `POST /v1/validate` change above rides on. The `.pipelex/` config schema did not move, so no migration is required.
+- **`POST /v1/codegen` stamps `engine_version` `0.65.0`**: the stamp is the pinned `pipelex` version, so a `codegen.lock` committed against `0.64.2` no longer matches until it is regenerated. `POST /v1/build/runner` carries the same stamp.
+
+### Fixed
+
+- **In-page links on the Pipe Validate docs page**: the page's topical sections are now headings, so the links to the effective entry pipe, the opt-in extras, sourcing submitted files, where validation runs and who the validation is done for land on their section instead of the top of the page, from that page and from Pipe Builder. The deployment resource note is back under where validation runs.
+
+## [v0.27.4] - 2026-09-24
+
+### Changed
+
+- **Pinned `pipelex` 0.64.2**: up from `==0.64.1`, exactly, a patch release that keeps the message of an unknown model reference under strict error disclosure. A `/v1/validate` or run of a method naming a model the deck does not know now answers its 422 with the model that was named and the "Did you mean" suggestions, instead of "An internal error occurred.". No wire, config or OpenAPI change.
+- **`POST /v1/codegen` stamps `engine_version` `0.64.2`**: the stamp is the pinned `pipelex` version, so a `codegen.lock` committed against `0.64.1` no longer matches until it is regenerated. `POST /v1/build/runner` carries the same stamp.
+
+## [v0.27.3] - 2026-09-24
+
+### Changed
+
+- **Pinned `pipelex` 0.64.1**: up from `==0.64.0`, exactly, a patch release whose runtime change keeps a test run's telemetry off the Pipelex Gateway stream and which moves its own exact pin to `mthds` 0.16.0, so the image now ships that version. Nothing on the wire moves — the committed `docs/openapi/pipelex-api.openapi.yaml` changes only in its `info.version` — and the `.pipelex/` config schema did not move, so no migration is required.
+- **`POST /v1/codegen` stamps `engine_version` `0.64.1`**: the stamp is the pinned `pipelex` version, so a `codegen.lock` committed against `0.64.0` no longer matches until it is regenerated. `POST /v1/build/runner` carries the same stamp.
+
+## [v0.27.2] - 2026-09-24
+
+### Added
+
+- **`analytics_groups` on `POST /v1/validate` and `POST /v1/build/runner`**: both routes dry-run the submitted pipes, and that telemetry — the `pipe_dry_run` event and the dry runs themselves — is now attributed to the caller: the authenticated user and the request's optional `analytics_groups`, which follow the same rules as on a run and are refused with the same `422` `InvalidAnalyticsGroups`. Before this, every validation on a hosted deployment reported under one constant id per deployment.
+
+### Changed
+
+- **Pinned `pipelex` 0.64.0**: up from `==0.63.0`, exactly, because the caller a validation is done for is a required argument of the runtime's bundle-validator seam from that release on, and the runtime now carries a run's caller context as `extras`, which the `analytics_groups` wire field maps onto. Nothing else on the wire moves and the `.pipelex/` config schema did not move, so no migration is required.
+- **`POST /v1/codegen` stamps `engine_version` `0.64.0`**: the stamp is the pinned `pipelex` version, so a `codegen.lock` committed against `0.63.0` no longer matches until it is regenerated. `POST /v1/build/runner` carries the same stamp.
+
+## [v0.27.1] - 2026-09-23
+
+### Added
+
+- **`analytics_groups` on `POST /v1/execute` and `POST /v1/start`**: a run request may carry an opaque mapping of group type to group key, such as `{"organization": "org_acme"}`, which the runtime stamps on every span of the run as `pipelex.run.analytics_groups` and which the deployment's own PostHog stream, in `identified` mode, attaches to each capture as PostHog groups. It follows the runtime's own rules — lowercase snake_case group types, group keys from `A-Za-z0-9_-`, at most five entries — and a mapping outside them is refused with a `422` whose `error_type` is `InvalidAnalyticsGroups`; omitting it leaves the run in no group.
+
+### Changed
+
+- **Pinned `pipelex` 0.63.0**: up from `==0.62.0`, exactly, for the run-scoped analytics groups and per-caller telemetry that `analytics_groups` rides on. A deployment reporting to its own PostHog or OpenTelemetry backend now sees each run under its caller — the run's `user_id` becomes the PostHog `distinct_id` and is written on every span as `pipelex.run.user_id` — while a single-tenant deployment, whose runs all carry the shared `single-tenant` id, keeps reporting under its configured identity. Nothing on the wire moves and the `.pipelex/` config schema did not move, so no migration is required.
+- **`POST /v1/codegen` stamps `engine_version` `0.63.0`**: the stamp is the pinned `pipelex` version, so a `codegen.lock` committed against `0.62.0` no longer matches until it is regenerated. `POST /v1/build/runner` carries the same stamp.
+
+### Fixed
+
+- **A run route's `422` names the extension field that failed**: every failure on `pipeline_run_id`, `callback_urls`, `orchestration_mode` or `storage_scope` used to answer `error_type` `InvalidCallbackUrls`, including a traversal in `storage_scope` on a request that carried no callback at all. An invalid `storage_scope` now answers `InvalidStorageScope`, an invalid `callback_urls` still answers `InvalidCallbackUrls`, and a failure on any other field, or on more than one at once, carries the generic `ValidationError`.
+
+## [v0.27.0] - 2026-09-21
+
+### Changed
+
+- **Pinned `pipelex` 0.62.0**: up from `==0.61.0`, exactly, for the shipped model deck's move onto the models the Pipelex Gateway serves from Azure. Nothing on the wire moves — the committed `docs/openapi/pipelex-api.openapi.yaml` changes only in its `info.version` — and the `.pipelex/` config schema did not move, so no migration is required.
+- **The vendored model deck resolves only to models the Pipelex Gateway serves from Azure (Breaking)**: this image serves the `.pipelex/inference/` tree it ships rather than the installed wheel's kit, and that deck had not been re-synced since v0.14.0, so every previous pin move left the roster untouched. Every default alias and preset keeps its name, but the language ladder is now the GPT-5.6 range — the premium tier and `@best-gpt` resolve to `gpt-5.6-sol`, the general and large-context tiers to `gpt-5.6-terra`, the small tiers to `gpt-5.6-luna`, where they previously resolved to `claude-4.7-opus`, `claude-4.6-sonnet`, the Gemini `*-latest` pair and `gpt-4o-mini` — and image generation's tiers resolve to `gpt-image-2` in place of `nano-banana` and `nano-banana-2`. `GET /v1/models` answers this deck, so its `aliases` and `waterfalls` change with it, and `$engineering-codebase-analysis` reaches its model through `@default-large-context-code` rather than a provider-named alias.
+- **A deployment holding its own provider key must declare the new handles (Breaking)**: the Pipelex Gateway resolves them from the remote config it fetches at boot, so the default deployment needs nothing, but the vendored `backends/` rosters declare none of the GPT-5.6 range. Such a deployment still starts — `missing_presets_reaction` is `log`, and an alias satisfies the deck's membership check without its target being declared — and then answers `500` on the first `/execute` that takes a default tier. Declare the handles in the backend file, or keep the previous models by naming them in an `x_custom_llm_deck.toml`, which `pipelex update` never touches.
+- **The vendored deck declares `temperature = 1` throughout (Breaking)**: every model in the GPT-5.6 range fixes its temperature at 1, so every preset states that value in place of one the worker would override while warning on every call, and `[llm.choice_defaults].default_temperature` is 1 for the same reason. Presets are therefore distinguished by their model tier and their reasoning effort alone, so `$writing-factual` and `$writing-creative` now issue the same call. A method that needs a temperature of its own must write an inline LLM settings table — `model = { model = "gpt-4o", temperature = 0.8 }`.
+- **The vendored Gateway roster reference agrees with the deck again**: `backends/pipelex_gateway_models.md` and its plain twin are generated from the served remote config and had never been refreshed since this repo was created, so they advertised `gpt-5.2` and carried no `gpt-5.6-*` handle at all while the deck resolved every tier to one. Both are re-synced, so the reference an operator opens to pick a handle now matches what the deck runs on.
+- **`POST /v1/codegen` stamps `engine_version` `0.62.0`**: the stamp is the pinned `pipelex` version, so a `codegen.lock` committed against `0.61.0` no longer matches until it is regenerated. `POST /v1/build/runner` carries the same stamp.
+
+### Fixed
+
+- **The vendored deck no longer aliases a handle no enabled backend declares**: `@best-claude` and `@default-premium` both resolved to `claude-4.7-opus`, which the vendored `backends/anthropic.toml` does not declare — it stops at `claude-4.6-opus`. The re-synced deck removes the dangling target.
+
+### Removed
+
+- **`best-claude`, `best-gemini` and `best-mistral` are gone from the vendored deck (Breaking)**: an alias naming a provider cannot honestly resolve to a GPT model, and the image deck's `best-gemini` goes with them. A method referencing one now fails validation with the usual alias-not-found error; declare it in an `x_custom_llm_deck.toml` to keep it.
+
+## [v0.26.1] - 2026-09-20
+
+### Changed
+
+- **Pinned `pipelex` 0.61.0**: up from `==0.60.0`, exactly, for a set of fixes to the way generated and remote images are fetched and stored, which are the changes that actually reach a run here. Nothing on the wire moves — the committed `docs/openapi/pipelex-api.openapi.yaml` is unchanged — and the `.pipelex/` config schema did not move either, so no migration is required. The model roster is unaffected as well: 0.61.0 revises the handles in pipelex's own bundled kit, but this server reads the vendored `.pipelex/inference/` it ships rather than that kit, so `GET /v1/models` answers exactly what it answered under 0.60.0.
+- **`POST /v1/codegen` stamps `engine_version` `0.61.0`**: the stamp is the pinned `pipelex` version, so a `codegen.lock` committed against `0.60.0` no longer matches until it is regenerated. `POST /v1/build/runner` carries the same stamp.
+
+### Fixed
+
+- **A generated image is stored and reported under its real media type**: `pipelex` resolved a generated image's mime type to mint its storage key but never handed that type to the storage provider, so S3 stored every generated image untyped and served it back as `binary/octet-stream`; an image fetched from a remote URL now also keeps the type that URL served instead of falling through to a hardcoded `image/jpeg`. A caller that trusts the `mime_type` on an image a run returns, or that serves the stored object straight to a browser, now gets the type the bytes actually are.
+- **A remote image that fails to download no longer fails the whole run**: the upstream fallback for an unreachable remote image — log the warning, keep the URL — guarded on exception types the fetch never raised, so a 404 or a timeout on an image input propagated out and failed the run instead. A fetch given no explicit timeout also had no timeout at all, leaving a hanging server to block the caller indefinitely. Both are fixed in `pipelex` 0.61.0 and `POST /v1/execute` inherits them.
+
+## [v0.26.0] - 2026-09-19
+
+### Changed
+
+- **Pinned `pipelex` 0.60.0**: up from `==0.59.0`, exactly, so a stuff on the wire names its concept instead of carrying its definition. The release also corrects `PINNED_NATIVES_MTHDS_VERSION`, which labelled the engine's pinned native set `1.0.0` where the standard pins it at `2.0.0`. It brings `mthds` 0.15.0 in with it, and the `.pipelex/` config schema did not move, so no migration is required.
+- **A returned stuff names its concept by ref (Breaking)**: every working memory `POST /v1/execute` returns now spells each stuff as `{"concept": "<domain>.<Code>", "content": …}` instead of carrying the whole `Concept` object with its `description`, `structure_class_name` and `refines`, which is what the standard's I/O contract asks for — a stuff names its concept and the definition stays in the library the method loads. The committed `docs/openapi/pipelex-api.openapi.yaml` is regenerated to match: `Stuff.concept` is now a `string` where it was a `$ref` to `Concept`. A caller that read `concept.code`, `concept.domain_code` or `concept.structure_class_name` off a returned stuff must read the ref string and resolve it against the method's own definitions, and a caller that validated a response back into a typed `Stuff` can no longer do so, because the definition no longer travels with the data.
+- **`POST /v1/codegen` stamps `engine_version` `0.60.0`**: the stamp is the pinned `pipelex` version, so a `codegen.lock` committed against `0.59.0` no longer matches until it is regenerated.
+
+### Fixed
+
+- **`make pylint` lints `api/`**: the target, which `make check` runs, linted the installed `pipelex` package in `.venv` instead of this repository's own code, so `api/` was never checked by pylint. It now lints `api` and `tests`.
+
+## [v0.25.0] - 2026-09-16
+
+### Changed
+
+- **Pinned `pipelex` 0.59.0**: up from `==0.58.0`, exactly, so a run no longer renders every traced input and output to Rich text and HTML on the execution path, which on the hosted runner happened on the Temporal worker's workflow thread. The release also fixes the "Output of pipe" panels hanging a run in `poor` pretty-print mode on a narrow headless console, and escapes every `<` in the graph and stuff viewer pages. It adds `pretty_print_mode` (`rich`, `poor` or `silent`) under `[runtime.log]`, which this server leaves at its `rich` default.
+- **The graph spec's `IOSpec` no longer carries `data_text` or `data_html` (Breaking)**: `pipelex` 0.59.0 removes the text and HTML renderings of traced data, so both fields are gone from every graph spec the run routes return, and the committed `docs/openapi/pipelex-api.openapi.yaml` is regenerated to match. A graph spec saved by an earlier version is refused when read back. The settings that asked for those renderings, `stuff_text_content` and `stuff_html_content` under `[interpreter.pipeline_execution.graph.data_inclusion]`, no longer exist and boot rejects them, so they are removed from this server's `.pipelex/pipelex.toml`; an operator running it against their own `.pipelex/` must run `pipelex migrate` or delete the two keys by hand.
+- **A remote input is checked for syntax only (Breaking)**: an http(s) URL on a `Document` or `Image` input is refused before the run with `PipelineInputUrlInvalidError`, answered as a 422, only when it does not parse. Whether the resource exists is no longer checked up front: the operator that fetches it raises `RemoteFileFetchError`, an `INPUT`-domain error naming the URL and the answer it got, in place of a raw `httpx` error. Those fetches now identify themselves as `Pipelex/0.59.0`, without the `(https://pipelex.com)` suffix. A local file path must still exist before the run starts.
+- **`POST /v1/codegen` stamps `engine_version` `0.59.0`**: the stamp is the pinned `pipelex` version, so a `codegen.lock` committed against `0.58.0` no longer matches until it is regenerated.
+
+## [v0.24.0] - 2026-09-14
+
+### Changed
+
+- **License (Breaking)**: `pipelex-api` is now licensed under the Elastic License 2.0 (ELv2) instead of MIT: `LICENSE` names Evotis S.A.S. as the copyright holder, the package metadata declares the SPDX expression `Elastic-2.0` in place of the MIT license classifier, which makes hatchling 1.27 or later a requirement for building from source, the OpenAPI contract the server publishes carries `info.license` `Elastic-2.0` (the committed `docs/openapi/pipelex-api.openapi.yaml` is regenerated to match, its summary now calling the runner source-available), and the Docker image's `org.opencontainers.image.licenses` label reads `Elastic-2.0`; every earlier version and Docker image tag, up to and including v0.23.0, stays under MIT. ELv2 is source-available: you may run `pipelex-api` for your own team or company, on your own infrastructure or in your own cloud account, while its main limitation rules out offering others a hosted API or runner that executes methods, whether they send the methods themselves or pick them from a catalog you make available. `LICENSE` carries the full terms, including its conditions on notices and redistribution, and the [license page](https://docs.pipelex.com/latest/license/) explains how Pipelex reads them.
+- **Pinned `pipelex` 0.58.0**: up from `==0.57.0`, exactly, for the relicense of `pipelex` to the Elastic License 2.0, which this server now depends on under that license. The runtime did not change and neither did the `.pipelex/` config schema, so no migration is required.
+- **`POST /v1/codegen` stamps `engine_version` `0.58.0`**: the stamp is the pinned `pipelex` version, so every generated artifact header and every `codegen.lock` this release emits differs from the previous one, and a lock committed against `0.57.0` no longer matches until it is regenerated.
+
+## [v0.23.0] - 2026-09-08
+
+### Added
+
+- **`POST /v1/execute` carries the run's I/O artifacts beside its execution graph**: `pipe_output.pipe_io_artifacts` groups the `pipe_io_contracts`, `input_form` and `output_form` that `/validate` produces, keyed by namespaced `pipe_ref` over the run library's own pipes, so a consumer rendering a run's graph can describe a data node from the run itself rather than pairing that graph with a validation of some other bundle text. It is `null` unless the run generated a graph with `graphs_inclusion.graphspec_json` on, and `pipe_io_artifacts_error` carries the message when the build ran and failed.
+
+### Changed
+
+- **Pinned `pipelex` 0.57.0**: up from `==0.56.0`, exactly, for the `PipeIOArtifacts` carrier and its SPI transport that the `/v1/execute` addition above reads back onto the public wire. The `.pipelex/` config schema did not move, so no migration is required.
+- **The normalized crate is stamped `mthds_version: "2.0.0"` (Breaking)**: `pipelex` 0.57.0 moves to `mthds` 0.14.0, whose `MTHDS_STANDARD_VERSION` was cut from `1.0.0`, so every crate `POST /v1/resolve` emits and `POST /v1/build/runner` normalizes carries the new stamp and a consumer comparing against `1.0.0` has to move. Crate fingerprints are unaffected — `mthds_version` is excluded from the hashed payload by design — but a `METHODS.toml` pinning the old major, such as `^1.0.0`, now warns where it did not before. The MTHDS Protocol version is unchanged at `0.6.0`.
+- **`POST /v1/codegen` stamps `engine_version` `0.57.0`**: the stamp is the pinned `pipelex` version, so every generated artifact header and every `codegen.lock` this release emits differs from the previous one, and a lock committed against `0.56.0` no longer matches until it is regenerated.
+- **OpenAPI artifact regenerated** for the new `PipeIOArtifacts` schema and the `pipe_io_artifacts` / `pipe_io_artifacts_error` fields it brings to `PipeOutputWire`, both inherited from pipelex's `PipeOutput` rather than declared here. Nothing was removed and no type loosened, but `PipeOutputWire` publishes `additionalProperties: false`, so a strictly-validating client generated from the previous artifact rejects the added fields until it is regenerated.
+
+### Fixed
+
+- **The `/execute` response reference documents its execution graph**: `docs/pipe-run.md` listed `tokens_usages` and `usage_assembly_error` under `pipe_output` but never `graph_spec` or `graph_assembly_error`, so a caller reading the reference had no way to learn the graph was on the wire at all. Both are documented now, beside the `pipe_io_artifacts` pair added above, each with the configuration setting that actually gates it.
+- **The `/validate` reference documents the `output_form` view**: `docs/pipe-validate.md` still described `input_form` as the only supported `views` token and carried no field reference for `output_form`, which has been wrong since that view shipped in v0.22.0.
+
+## [v0.22.0] - 2026-09-03
+
+### Added
+
+- **`POST /v1/validate` carries the output-form descriptor, under the new `views` token `output_form`.** The valid arm gains a second opt-in structured view beside `input_form`, with identical mechanics: a supported token attaches a same-named top-level field, keyed exactly like `pipe_io_contracts`; without the token the field is absent and the body is byte-identical to a request that omits `views`; an unknown token is still lenient-ignored rather than a 422.
+
+ Two tokens rather than one, because they answer separate questions — a caller building a fill-in form wants the inputs, a caller rendering a result or registering a tool signature with a return type wants the output — and neither should pay for the other. Like `input_form`, the field is a canonical report field re-declared with a default here so the wire gate keeps it out of the published schema's `required` set, and it rides the valid arm only: it derives from a crate an invalid bundle never assembled.
+
+ The payload's **schema** needs no token: it rides `pipe_io_contracts[…].output.json_schema`, which the standard added in the same version. That pairing is the point — the descriptor states what the output IS, the schema names the property its payload arrives under, and a consumer holding one but not the other is back to inferring the other from a value.
+
+- **`POST /v1/validate` reports the effective entry pipe.** The valid arm carries a new wire-only extra, `default_pipe_ref` (string | null): the qualified `domain.pipe_code` a caller gets by omitting the pipe selector — the pipe a selector-less run of that same request would execute. On a `method_ref` request it is the fetched package manifest's `main_pipe`, qualified against the closure; otherwise, and when the manifest declares none, it is the closure's primary blueprint's `main_pipe` qualified by its domain. It is `null` when no entry pipe is determined: no blueprint declares `main_pipe`, or a manifest names a pipe the closure does not declare or declares in several domains — cases in which a selector-less run by that address would fail to resolve it too. The field closes a real gap for validate-by-address: the canonical report is manifest-blind (`bundle_blueprint` is the batch's primary blueprint), so a package whose `METHODS.toml` entry differs from, or exists without, a bundle-level `main_pipe` validated with a report from which a consumer could only derive the wrong entry pipe, or none. It states the **run** default rather than the `/build/*` routes' stricter one: a closure whose domains each declare a `main_pipe` is refused by `/build/*` but runs happily, so the field names the pipe that would run. It rides the valid arm only — the invalid arm assembles no library. See `docs/pipe-validate.md` → "The effective entry pipe".
+
+### Fixed
+
+- **The per-pipe build routes honor a fetched package's manifest `main_pipe`.** `POST /v1/build/{inputs,output,runner}` with an address-form `method_ref` and no `pipe_ref` used to answer `422` ("the closure declares no `main_pipe`") whenever the package's domains declared none themselves — even though its `METHODS.toml` named an entry pipe, which the run routes already honored. The tooling routes now default the pipe with the run routes' precedence: the request's `pipe_ref`, then the fetched manifest's `main_pipe`, then the closure's own declared `main_pipe` (still a `422` when that declares none, or several). Inline `files[]` requests carry no manifest and behave exactly as before. A manifest `main_pipe` naming a pipe the closure does not contain is a `422` that says where the selector came from. `/resolve` and `/codegen` select no pipe and are unchanged. The OpenAPI artifact's `pipe_ref` / `requested_pipe_ref` descriptions are regenerated to say so.
+
+## [v0.21.0] - 2026-08-29
+
+### Added
+
+- **`method_ref` on the wire — run a published method by address.** `POST /v1/execute` and `POST /v1/start` accept `method_ref` as a third run source, mutually exclusive with `mthds_contents` and with a `files`/`bundle_b64` bundle. An **address-form** reference — `github.com/<owner>/<repo>`, an optional package selector, an optional `@<tag>` (tags only; branch names are refused) — is fetched server-side, the package located by manifest identity, and its files materialized as the run's library. The entry pipe defaults to the manifest's `main_pipe`; `pipe_code` overrides it. The `/execute` response, the `/start` ack, and the run logs carry `method_provenance` — the resolved `{address, tag, commit_sha}` — so a run by reference is always attributable to an exact commit. See `docs/pipe-run.md` → "Running a method by address".
+- **`/v1/validate` accepts `method_ref` natively.** `mthds_contents` is now optional there: exactly one of `mthds_contents` or `method_ref` selects what is validated. A fetched package's real relative file names feed `mthds_sources`, so per-file attribution in `validation_errors[]` names the package's own files. Selector-resolution failures (parse, fetch, no package found) are non-2xx `problem+json` — never an `is_valid: false` verdict.
+- **Tooling routes resolve address-form `method_ref`.** `POST /v1/resolve`, `POST /v1/codegen`, and `POST /v1/build/{inputs,output,runner}` now resolve an address-form `method_ref` through the same fetch path (only `.mthds` data travels — a package's Python never loads on these routes). The **registry form** (any non-address reference) keeps the `501` `MethodRefNotSupported` until a method registry exists.
+- **SHA-keyed clone cache.** Fetched repositories are cached on disk per resolved commit SHA — a `git ls-remote` pre-resolution turns the reference into a SHA before any clone, so a cached commit is never re-cloned and a moved tag always fetches fresh (never cached by tag alone). The cache is bounded by count, total bytes, and age, tunable via `METHOD_CACHE_DIR`, `MAX_METHOD_CACHE_CLONES`, `MAX_METHOD_CACHE_TOTAL_KIB`, and `MAX_METHOD_CACHE_AGE_HOURS` (see `docs/configuration.md`).
+- **Execution-locus security gate for fetched packages.** On a deployment that is not sandbox-hosted, a fetched package shipping any `.py` is refused with `403` `CustomCodeRequiresSandbox`. On a sandbox-hosted deployment, PipeFunc `.py` is accepted (captured as text, executed in the sandbox), but a package declaring Python structure classes is always refused with `403` `MethodStructuresRefusedError` — structures would import into the runner's own process.
+- **Distinct error surface for `method_ref` failures.** `MethodRefParseError`, `MethodFetchError`, `MethodPackageAmbiguityError`, and `MethodPackageTooLargeError` map to `422`; `MethodPackageNotFoundError` to `404` (its detail lists the packages the repository does contain); `MethodStructuresRefusedError` to `403` — each an RFC 7807 `problem+json` document. Documented in `docs/error-responses.md`.
+
+### Changed
+
+- **Pinned `pipelex` 0.55.0** (up from `==0.54.0`, exactly). It brings the `pipelex.methods` package — the reference grammar, the git fetcher with its bounds, package location by manifest identity, and the structure-refusal gate — that this release's `method_ref` support is built on. The `.pipelex/` config schema did not move, so no migration is required.
+- **OpenAPI artifact regenerated** for the new surface: the `method_ref` request fields, the `method_provenance` response fields (including the new `PipelexApiStartResponse`), and the per-route `403`/`404`/`501` problem responses.
+
+## [v0.20.0] - 2026-08-28
+
+### Changed
+
+- **Pinned `pipelex` 0.54.0.** Up from `==0.53.0`, exactly; it brings `mthds` 0.11.1, which now types the input-form descriptor and the pipe I/O contract models for the whole stack. The `.pipelex/` config schema did not move, so no migration is required. Two upstream changes reach callers of this server:
+ - **The `input_form` view's published schema is now the standard's kind-discriminated union (Breaking for generated clients).** `PipeInputFormDescriptor.fields` items are a `oneOf` over one closed model per field kind — `TextField`, `ProseField`, `DateField`, `NumberField`, `BooleanField`, `EnumField`, `DocumentField`, `ImageField`, `ObjectField`, `ListField`, `UnknownField` — discriminated on `kind`, with a parallel `*Item` family for list items. The flat `InputFormField` and the `FieldKind` enum leave the artifact, so a client regenerated from `docs/openapi/pipelex-api.openapi.yaml` loses those type names and gains the per-kind ones. The JSON on the wire is unchanged; hand-written clients are unaffected. The arms publish their full closed shapes (`additionalProperties: false`, real properties), as `mthds` 0.11.1 fixed the serializer annotation that previously erased them to opaque objects.
+ - **A count of one is strictly singular (Breaking).** Upstream, `Concept[1]` is universally the single form: a `[1]` input takes the value itself and refuses a list, a `[1]` output produces one object rather than a one-item list, and `Concept[0]` is rejected at validation time. Methods executed through this server that relied on `[1]` list behavior must be updated.
+- **OpenAPI docs** — Regenerated `docs/openapi/pipelex-api.openapi.yaml` for the pin. Beyond the `input_form` union above, four previously opaque schemas — `ConceptBlueprint`, `ConceptStructureBlueprint`, `ConstructBlueprint`, `InputSlotBlueprint` — now publish their real closed shapes instead of `{"additionalProperties": true}`, another consequence of the same upstream serializer fix.
+
+### Added
+
+- **Contract test for the `input_form` union.** `tests/unit/test_openapi_contract.py` now pins that `PipeInputFormDescriptor.fields` is discriminated on `kind` with exactly the standard's kind set, that every arm is a published closed schema with real properties, and that the flat `InputFormField`/`FieldKind` never resurface — so an upstream regression to the flat or opaque shape fails here instead of shipping silently.
+
+## [v0.19.0] - 2026-08-26
+
+### Added
+
+- **New validation error type** — Added `input_presence_vacuous` to `PipeValidationErrorType`, an advisory lint that warns when a required method input points to a concept with no required fields. It is scoped to the bundle's declared `main_pipe`. This does not affect `is_valid`, but consumers performing exhaustive matches over the enum must handle the new member. (Breaking)
+
+### Changed
+
+- **Dependency** — Pinned `pipelex` to `0.53.0` (up from `0.52.0`). The `.pipelex/` config schema did not move, so no migration is required.
+- **Warning output** — Intent-hint warnings are now capped at five unknown-hint-key findings per site, collapsing the rest into an `...and N more` item; hint keys or intent words longer than 60 characters are elided with an ellipsis.
+- **OpenAPI docs** — Regenerated `docs/openapi/pipelex-api.openapi.yaml` to include the new `PipeValidationErrorType` member and updated docstring references (moved from `pipelex.pipeline.optionality_warnings` to `pipelex.pipeline.advisory_warnings`).
+
+### Fixed
+
+- **`.mthds` parsing** — An empty `[concept.X.structure]` table now parses as an object with no fields instead of being described as prose refining `native.Text`.
+- **Python class reflection** — Registered Python classes declaring no fields now reflect as empty objects rather than `unknown`.
+- **Domain locators** — Hierarchical domains (e.g., `legal.contracts`) are now split at the last dot rather than the first when building an advisory warning's locator, so the locator names the correct domain.
+
+## [v0.18.0] - 2026-08-24
+
+### Added
+
+- **New `views` parameter on `/v1/validate`.** `ValidateRequest` now accepts `views: list[str]` (default `[]`), the structured-view counterpart to `render`. Tokens are resolved leniently and as a set: each is matched independently against the supported set, unknown or unsupported tokens are silently dropped and never trigger a 422, and order and duplicates do not matter. `input_form` is the only supported token today, attached exclusively to the valid arm of the response. The two lists are independent — a request may carry both, and a token does not cross axes.
+- **Documentation.** `docs/pipe-validate.md` now covers the new `views` parameter, the previously undocumented `render` parameter (including the lenient, set-based, mutually independent mechanics they share), the `orchestration_mode` override, and the opt-in response fields (`input_form`, `rendered_markdown`).
+- **Tests.** `tests/unit/test_validate_views.py` pins the gate: absent by default on both arms, present on the valid arm when requested, never on the invalid arm even when requested, unknown tokens ignored rather than rejected, and `views` / `render` resolving independently. `tests/unit/test_protocol_parity.py` gained the complementary pair — a default call omits `input_form`, and an opt-in call matches the local canonical report exactly.
+
+### Changed
+
+- **`input_form` is now an opt-in structured view on `/v1/validate` (Breaking).** v0.17.0 shipped it unconditionally on every valid verdict, as a side effect of the `pipelex` 0.52.0 pin rather than a decision. It is now gated: a caller that does not ask no longer receives it, so the high-frequency consumers — editor hooks, CI gates, agent loops — stop paying for a form they discard. An empty or unknown `views` list changes nothing either, so the default body is byte-identical to a request that omits the field entirely. Callers that need it must send `{"views": ["input_form"]}`, which returns exactly what v0.17.0 returned unconditionally. In the published OpenAPI artifact, `input_form` leaves `ValidReport`'s `required` set to reflect the opt-in wire behavior; the canonical report still requires it internally, so a backend that forgets to derive it fails loudly rather than shipping an empty view.
+
+## [v0.17.0] - 2026-08-24
+
+### Added
+
+- **A source-less request now names the extension args this deployment does not handle.** A body that carries no run source this server understands, but at least one key it does not handle, gets a `422` naming those keys instead of the generic precondition text. The canonical case is a hosted client pointed at an open-source runner: `{"method_id": "mt_…"}` used to produce an obscure "pipe_code and mthds_contents cannot both be empty", and now explains that a hosted-only selector must be sent to the hosted API, which resolves it into a run source before any runner sees the request. The wording is deployment-neutral on purpose — the server reports what *it* handles rather than asserting anything about the caller's topology. Keys it does handle (`pipeline_run_id`, `callback_urls`, `orchestration_mode`, `storage_scope`, and the legacy singular `mthds_content`) are never named as unhandled, and a source-less body carrying only those keeps the base guidance. No wire-shape change and no OpenAPI artifact change.
+
+### Changed
+
+- **Pinned `pipelex` 0.52.0 (Breaking).** Up from `==0.50.0`, exactly, and `mthds` follows to 0.8.2 transitively. No code changed on this side — the report is assembled inside pipelex — but the published `/v1/validate` contract moved in several places:
+
+ - `ValidReport` gained a **required** `input_form`, mapping each `pipe_ref` to a `PipeInputFormDescriptor`, so a caller can render a form from the verdict alone instead of reverse-engineering one from the emitted JSON Schema. The closed `FieldKind` vocabulary arrives with it. A consumer deserializing the report strictly must add the member.
+ - `PipeInputContract.optional` (boolean) is **replaced** by `presence`, a three-valued `PresenceMarker` — `plain`, `optional` (`?`) or `force` (`!`) — so a `!` use-site assertion is now visible where it previously read as an ordinary required slot. Read `presence != "plain"` where you read `optional == true`.
+ - `IOMultiplicity` gained `fixed`, and both the input and the output contract now carry `multiplicity`, with an `item_count` present exactly when it is `fixed`. A fixed-count list slot (`Concept[N]`, for `N > 1`) used to report `variable` and lose its count. Any consumer branching on `variable` to mean "a list" must accept `fixed` as a list too.
+ - Every pipe blueprint's `inputs` map widened from `string` values to `string | InputSlotBlueprint`.
+ - `PipeValidationError.error_type` gained the advisory `HintLintErrorType` members (`hint_unknown_key`, `hint_unknown_intent`, `hint_inapplicable_intent`). They ride the report's `warnings` and never make a verdict invalid, but an exhaustive `match` over the union has to handle them.
+
+ Two authoring changes reach anyone posting `.mthds` content: an unknown key in a concept structure-field table is now rejected at parse instead of silently dropped, and `required = true` may no longer be paired with `default_value`. The `.pipelex/` config schema did not move, so no migration is required.
+
+- **Four schemas in the OpenAPI artifact went opaque, upstream.** `ConceptBlueprint`, `ConceptStructureBlueprint`, `InputSlotBlueprint` and `InputFormField` now publish as a bare `{"type": "object", "additionalProperties": true}`. This is a side effect of how intent hints are serialized, not an intentional loosening: each model gained a `@model_serializer(mode="wrap")` returning `dict[str, Any]` in order to drop absent `hints` rather than emit `null`, and pydantic derives a model's **serialization** schema from that annotation — which is the one FastAPI publishes. The validation-mode schema is still complete and still `extra="forbid"`. The artifact is regenerated as-is rather than hand-patched, and the issue is filed upstream.
+
+### Fixed
+
+- **A source-less run request no longer slips through on an unknown key.** `RunRequest.validate_request` used to **waive** the "at least one of `pipe_code` / `mthds_contents` / method bundle" precondition whenever the body carried any key outside the declared fields, on the theory that an extension might be the method selector. That theory is obsolete under the layered extension policy written down in the Pipelex workspace spec `docs/specs/pipelex-platform-api.md`: an extension-borne method selector is resolved by the layer that owns it *before* the request reaches this server, so a body arriving here with no run source is an error whatever else it carries. The waiver was also already dead on every live path — the run routes build the model through `RunRequest.from_body`, which copies the declared fields only, so unknown keys were stripped before the validator ever saw them. Removing it is therefore behaviour-neutral, and the substantive change is the message described above. A body that does have a real run source still accepts unknown extension keys untouched: the model stays extension-open.
+
+## [v0.16.0] - 2026-08-20
+
+### Changed
+
+- **Built on `pipelex`'s `RunMetadata` split (Breaking).** `JobMetadata` moved its run-constant half — `user_id`, `pipeline_run_id`, `storage_scope`, `request_id` — into a nested `RunMetadata`, reached as `job_metadata.run_metadata.*`. This server's own surface is untouched: `pipeline_run_setup` still takes those four as flat keyword arguments and builds the `JobMetadata` itself, so no route, request model or response shape changes. Only the test doubles that construct a `JobMetadata` directly had to follow.
+
+ The wire contract is unchanged, including the published OpenAPI artifact — see below for the one place that was nearly not true.
+
+- **Pinned `pipelex` 0.50.0.** Up from `==0.47.0`, an exact PyPI pin as this dependency is meant to be expressed. It was briefly a `[tool.uv.sources]` git rev while `RunMetadata` was unreleased; that is gone, and with it the transitive override a source imposes.
+
+ The jump crosses three releases, so it picks up more than the `RunMetadata` split: `PipeFactoryErrorType` / `PipeValidationErrorType` moved to `pipelex.validation_error_types` (0.49.0), and the import follows them.
+
+### Fixed
+
+- **`PipeOutput` gained a field upstream, and `test_openapi_contract` earned its keep.** `pipelex` first carried the run's job on `PipeOutput` as a **model field**. `PipelexApiExecuteResponse.pipe_output` references `PipeOutput`, and `/v1/execute` returns `response.model_dump(...)` — so that field published `user_id`, `request_id`, `otel_context` and `trace_context` into this public API's response body **and** its committed OpenAPI schema.
+
+ `test_execute_publishes_the_tokens_usage_wire_records` asserts `{"LLMTokensUsage", "ImgGenTokensUsage", "JobMetadata"}.isdisjoint(schemas)`, and it failed. Upstream now carries the value as a private attribute behind a property — readable by a transport resolving a storage scope, absent from `model_dump`, `model_json_schema` and therefore the wire. **No change was needed on this side**, which is the right shape of fix: the artifact was never supposed to have to trim it.
+
+## [v0.15.1] - 2026-08-20
+
+### Changed
+
+- **Pinned `pipelex` 0.48.0.** Up from `==0.47.0`, exactly. A quiet bump for this server: nothing in it reaches the wire, the committed OpenAPI artifact is unchanged, and no tracked configuration moved. The release is upstream test infrastructure — a canonical MTHDS test corpus that now ships inside the `pipelex` wheel at `pipelex.test_extras.mthds_corpus`, with a loader API (`iter_entries()`, `get_entry()`) for selecting fixtures by tag, execution tier, validity and granularity.
+
+ Worth knowing rather than acting on today: that corpus exists so consumers stop keeping their own copies of language-level `.mthds` methods, which is a duplication this repo's own tests currently have. Adopting it is a separate change, and this pin is what makes it available.
+
+## [v0.15.0] - 2026-08-20
+
+### Added
+
+- **`storage_scope` — the runner is told where to write instead of deriving it.** `pipeline_run_setup` requires it, and this server never passed it, so every `/start` and `/execute` against a current `pipelex` died with `TypeError: pipeline_run_setup() missing 1 required keyword-only argument: 'storage_scope'` — a 500 from the runner and a 502 at the caller, on the happy path.
+
+ It arrives in the **body**, not a header, because it is data rather than identity: the runner needs to know where to write, not who to trust. A multi-tenant host computes it where it knows its own tenancy (hosted Pipelex sends `<org_id>/<method_id>/<run_id>`) and this server treats it as an opaque prefix, composing its own leaves (`assets/`, `results/`, `payloads/`) onto it. Validated at the wire by `validate_storage_scope`, so a traversal is a `422` naming the field rather than a `500` from deep inside the run — the runtime seam validates too, so this is a second gate, not the only one.
+
+ `_validate_extras` is a key ALLOWLIST rather than a passthrough, so the field had to be added there too — a key missing from it is dropped with no error, and the run would have written under the fallback prefix while answering `202`. Covered by tests that assert the constructor kwarg, not just the status code.
+
+ **Omitted, a run is scoped to the caller's own id** — never a shared constant. That is the safe default for a single-tenant deployment, and it keeps a multi-tenant deployment that forgets to send a scope isolating its callers instead of pooling them. A shared literal here would be the `anonymous/` bug in a new spelling.
+
+### Fixed
+
+- **`uri_format` in the shipped `.pipelex/pipelex.toml` renders the filename only.** The placeholder set narrowed again: the storage prefix (`{storage_scope}` plus the `generated/` leaf) is composed in code so a config cannot omit it, leaving `{hash}` and `{extension}`. A config still naming `{storage_scope}` is refused at boot.
+
+- **Every run's output was written to `<scope>/results/results/`.** The delivery target was built as `StorageTarget(key_prefix="results")`, from the layout where the executor composed `{user_id}/{key_prefix}{pipeline_run_id}` and the caller supplied the leaf. It now composes `{storage_scope}/{key_prefix}results` — the runtime owns the `results/` leaf — so passing it here applied it twice. Nothing failed: the write succeeded, the run reported COMPLETED, and only a later reader of `<scope>/results/` found an empty prefix, which is exactly where the hosted platform's run reconciler looks. `key_prefix` remains the caller's slot for an extra level between the scope and the leaf; it is not where the leaf comes from.
+
+- **`uri_format` in the shipped `.pipelex/pipelex.toml` still used the removed `{primary_id}` / `{secondary_id}` placeholders.** The supported set is now `{extension}`, `{hash}`, `{storage_scope}`, so config validation raised `StorageConfigError` at fixture setup and **every** test in the suite errored — a total red that looked like a code failure and was purely stale config. Migrated to `{storage_scope}/{hash}.{extension}`, matching the kit default in `pipelex`.
+
+### Changed
+
+- **Pinned `pipelex` 0.47.0 (Breaking, and it moves this deployment's own config files).** Up from `==0.46.4`, exactly. 0.47.0 is the release that makes the runtime *told* where a run's bytes go instead of deriving it from who ran it, which is what the `storage_scope` work above is built on — so this server cannot run on 0.46.x at all: `pipeline_run_setup` now requires `storage_scope`, and calling it without one is a `TypeError` on the happy path, not a degraded mode.
+
+ **It also narrows `uri_format`, and a config that has not moved fails at boot rather than at first use.** The format now renders the FILENAME only: the prefix is composed in code as `{storage_scope}/generated/`, so `{storage_scope}` is no longer a supported placeholder and `{primary_id}` / `{secondary_id}` stay retired. The tracked `.pipelex/pipelex.toml` here is already on `{hash}.{extension}`; **anyone running this server against their own `.pipelex/` must make the same edit**, or boot raises `StorageConfigError` naming the offending placeholder and listing the supported set. There is deliberately no migration for it — a value-domain narrowing on a free string can never be proven stale from the schema, so the failure is loud at boot instead of a silent rewrite of a value an operator may have chosen.
+
+ Generated bytes consequently land under a `generated/` leaf beside `assets/` (what the caller supplied) and `results/` (the delivered envelope), rather than loose at the root of the scope.
+
+- **Breaking: the `anonymous` caller no longer exists.** `ANONYMOUS_USER_ID` is gone, along with every branch that produced or tolerated it. It was reached by *fallback*: `_get_user_id` returned the literal `"anonymous"` whenever no identity had been established, and that string became the first path segment of every storage key the run wrote. A deployment serving many callers therefore put all of them in one namespace where each could read the others' outputs — and it looked like a working request the whole way through. A silent multi-tenant collision is the worst possible failure for a fallback to produce.
+
+ Two changes replace it.
+
+ **`TRUST_FORWARDED_IDENTITY_HEADERS=true` now rejects a request with no forwarded id (`401`).** Turning that flag on is a deployment asserting *"a proxy in front of me authenticates every caller"*. A request arriving without the header means that proxy is absent, misconfigured or bypassed, and continuing under a shared owner is exactly the degradation this removes. Previously both an absent header and the literal `anonymous` were read as "the proxy says this one is anonymous" and let through. **This is the hosted configuration**, so on a hosted deployment an unidentified request is now impossible rather than merely unlikely.
+
+ **A deployment that declares no user model gets a named single tenant, not an unknown caller.** `AUTH_MODE=none` without a trusted proxy, or the shared static `api_key`, establishes no per-caller identity *by configuration* — that is one tenant, and `SINGLE_TENANT_USER_ID` names it. This is not the old sentinel renamed: nothing falls back to it, it is used only where the deployment has said it has no users, and `verify_jwt` refuses a token claiming it (so an authenticated caller on a server that *does* have users cannot land in that namespace).
+
+### Removed
+
+- **`POST /v1/upload` and `POST /v1/resolve-storage-url` are gone (Breaking).** Both were explicitly non-contract — neither the MTHDS Protocol nor the Pipelex API extensions ever included them, and both carried a "slated for replacement by the storage redesign, do not build new integrations on it" notice in their descriptions. That redesign has landed, and the routes moved to the hosted platform.
+
+ They could not stay. Both keyed S3 objects by the caller's `user_id` (`{user_id}/assets/{uuid}.{ext}`) and authorized a read by comparing that first path segment against the requester — an ownership model with no notion of a team. This server has no organization concept to fix it with, which is precisely why the routes belong on the hosted side, where membership is already resolved before the request arrives.
+
+ A self-hoster who was using them needs their own upload path. The storage *provider* is untouched: `get_storage_provider()`, `pipelex-storage://` URIs and everything the runtime does with them work exactly as before — only the two HTTP routes are removed. `ErrorType.INVALID_URI`, `UPLOAD_FAILED` and `PRESIGN_FAILED` are removed with them, and `api.security.is_safe_user_id` stays (the pipeline routes use it).
+## [v0.14.0] - 2026-08-18
+
+### Changed
+
+- **Pinned `pipelex` 0.46.4 (Breaking, and it moves this deployment's own config files).** Up from `==0.45.0`, exactly. 0.46.0 reshapes the `pipelex.toml` root to mirror the runtime layers and drops the redundant `_config` suffix from keys — `[pipelex]` splits into `[runtime]` / `[interpreter]`, `[cogt]` becomes `[inference]` — so the tracked `.pipelex/` files in this repo were migrated in place with `pipelex migrate`, which kept every value this deployment had chosen and carried each section banner along with the table it introduces. **Anyone running this server against their own `.pipelex/` must run `pipelex migrate` after upgrading**, including on the inference backend files: 0.46.0 removes `prompting_target`, and a surviving per-model one fails the strict boot by name. Migrate with **0.46.1 or later**: 0.46.0's migrator left a moved table's banner behind, so a file it rewrote needs its comments tidied by hand — or its `.bak` restored and the migration re-run. The pin names 0.46.4 rather than 0.46.0 for a run of fixes that ride along and change nothing on this API's wire: 0.46.1 restores the migrator's comment fidelity, 0.46.2 keeps a `.gitignore` inside `.pipelex/` so the timestamped backups a migration leaves behind stop showing up as untracked files, 0.46.3 makes that `.gitignore` reach a machine that had nothing to migrate (0.46.2 wrote it only on a run that actually carried a file forward, which is the minority case), and 0.46.4 is pipelex's own dogfooding of the convention plus a fix to its config-sync gate — developer tooling in that repo, invisible here. This repo's root `.gitignore` already ignored `*.bak.*`, so the tracked `.pipelex/` here is unaffected either way.
+
+- **The runner tolerates a stale-but-migratable config the way pipelex's own boot does.** `_resolve_http_error_mappers` loaded the raw config dict and validated it itself, which bypassed the boot tolerance 0.46.0 added — a config whose drift the migration ledger can fully explain. Because that call resolves at module import, the app would have died on the import line over a file `Pipelex.make` accepts moments later in `lifespan`, with the app-construction traceback instead of the "run `pipelex migrate`" warning. It now goes through `config_manager.load_config_validated`, the same tolerant entry point the boot uses. A config the ledger *cannot* explain still fails the app fast, as before.
+
+- **Swept onto `build_registrar`'s new `boot_orchestrator` parameter.** 0.46.0 removed the `plugins.boot_orchestrator` config key: the boot orchestrator is a boot argument now, and an orchestrator plugin gates its hub-slot claims on the value the registrar was built with. `_resolve_http_error_mappers` passes `None`, which is correct rather than merely convenient — the gate governs only the slot claims, which this throwaway registrar never applies, while a plugin contributes its HTTP-error mapper unconditionally. So the resolved map is what it always was, and the import-time resolution stays honest.
+
+- **Config access moved with the keys.** `get_config().pipelex.pipeline_execution_config` is `get_config().interpreter.pipeline_execution` — the only reader of the config tree in this repo.
+
+- **OpenAPI artifact refreshed, and the suggested-fix op vocabulary changed shape (Breaking on the wire).** A `suggested_fix`'s `ops[]` were a single open `FixOp` carrying a `FixOpKind` enum beside optional fields; 0.46.0 makes them a **union discriminated on `kind`**, one member schema per kind (`SetKeyOp`, `EnsureTableOp`, `DeleteKeyOp`, `DeleteTableOp`, `RenameTableKeyOp`, and the two new `MoveKeyOp` / `RemapValueOp`). A client reading `kind` and branching is unaffected in substance; one that validates against the published `FixOp` schema must move to the union. Also in the artifact: `PromptingTarget` and every `prompting_target` field are gone, and `PipeLLM` gains `templating_style` — 0.46.0 makes prompt templating an authoring decision on the pipe rather than something inferred from the model, with the runtime default now XML tags.
+
+### Fixed
+
+- **`docs/error-responses.md` no longer carries the "Suggested fixes" section twice.** The whole section — prose, example, field list and op table — was duplicated verbatim; a reader hitting the second copy had no way to tell which was current. One copy remains, and it documents the discriminated-union op shape and the full seven-kind vocabulary.
+
+## [v0.13.0] - 2026-08-14
+
+### Changed
+
+- **Pinned `pipelex` 0.45.0 (Breaking, and a hard pairing).** Up from `==0.43.1`, exactly. The pin crosses two releases, and the code changes below come from the first of them, not the one the pin is named after.
+
+ 0.45.0 adds per-node token usage, cost and model attribution to the run GraphSpec: `NodeSpec` gains a `usage` object, `GraphSpec` gains a run-level `usage` rollup, and each node's usage carries `by_model` — the model that *actually* ran, read off the usage records rather than off the authored choice or an unresolved alias. Both models are `extra="forbid"`, which is what makes the pairing hard in the other direction — an older `pipelex` rejects the new JSON — so this repo and `pipelex` 0.45.0 must move together. `graph_spec` is on this API's wire (`POST /v1/execute` carries one, `POST /v1/validate` a best-effort one) and is validated back from `model_dump(mode="json")` against `strict=True` models, so the new fields reach `docs/openapi/pipelex-api.openapi.yaml`, regenerated here.
+
+ 0.45.0's other two changes do not reach this repo: a `PipeCondition` dry run is now reproducible (it sorts its branch walk instead of iterating a hash-ordered set), and a `{concept, content}` envelope carrying an empty list is now a value rather than an error — the latter only widens what an input may be, so no caller that worked before stops working.
+
+- **Swept onto automatic search scope (Breaking).** 0.44.0 replaced the `search_domain_codes` list across the public API (`PipelexMTHDSProtocol`, `pipeline_run_setup`, `InputShaper`, `WorkingMemoryFactory`) with a single `search_scope` string that `pipeline_run_setup` derives from the entry pipe itself, so `ApiRunner.start` no longer passes one. Caller-visible in how a request's inputs resolve their concepts: the scope is now the entry pipe's own domain — `alias->domain` when the entry pipe comes from a dependency package — rather than whatever the runner supplied, and every entry-lookup refusal (invalid string, miss, ambiguity) now arrives as `ConceptLibraryConceptNotFoundError`.
+
+### Fixed
+
+- **A bare `pipe_ref` resolves again on the build routes.** 0.44.0 made in-body pipe references strict: the resolver behind `get_required_pipe` is a key lookup with deliberately no bare-code search, because a reference that can find a pipe in a domain its author never named is one `[exports]` cannot constrain. `resolve_requested_pipe` was still on it, so `POST /v1/build/inputs`, `/v1/build/output` and `/v1/build/runner` answered `422 Pipe '<code>' not found in the submitted closure` for *every* bare `pipe_ref` — a closure declaring `smoke.echo` refused `"echo"`, the spelling the route's own contract promises to accept and echo back qualified.
+
+ A code a human typed at an entry point is a different question from a reference one pipe makes to another, and 0.44.0 gave it its own answer: `get_required_entry_pipe` matches a bare code across every domain the library holds, ignores `[exports]` (package visibility governs in-body references, not hand-typed entry points), and excludes aliased dependency entries so installing a package cannot make a host pipe's code ambiguous. The route now uses it. An ambiguous bare code raises rather than picking a winner, and still surfaces as a `422` naming the candidates.
+
+## [v0.12.0] - 2026-08-12
+
+### Changed
+
+- **Pinned `pipelex` 0.43.1 (Breaking, and a hard pairing).** Up from `==0.42.0`, exactly. The two releases must move together in both directions: 0.43.0 retires the single `pipelex.plugins` entry-point group, so a plugin still declared under it now fails the boot with `RetiredPluginEntryPointGroupError` rather than going quietly undiscovered — while 0.42.0 does not read the new groups at all and would discover no plugin published under them. The rest of 0.43's breaking surface does not reach this repo: `ImageReference` / `DocumentReference` moved to `pipelex.kernel.prompt_references`, `LLMPromptBlueprintValueError` / `ImgGenPromptBlueprintValueError` unified into `PromptContentError`, `StructuredContentComposer` dropped `pipe_run_params`, `InputShaper` now resolves through its injected provider, and 0.43.1 made `PipeRunParams.batch_max_concurrency` required — none of those symbols has an import site here.
+- **OpenAPI artifact refreshed.** The committed schema tracks pipelex's own models, and 0.43.1 reworded the `CodegenTarget` docstring. Description text only — no route, field, type or requiredness moved, so the wire contract is unchanged.
+- **Swept onto the plugin entry-point group split.** `pipelex` replaced its single `pipelex.plugins` entry-point group with `pipelex.plugins.kernel` and `pipelex.plugins.interpreter`, and `build_registrar` gained a required `entry_point_groups` parameter naming which of them to read. `_resolve_http_error_mappers` passes `ENTRY_POINT_GROUPS` from `pipelex.interpreter_plugins.builtins` — the composed both-group list, matching the `BUILTIN_PLUGINS` / `CORE_UNCONDITIONAL_PLUGIN_NAMES` it already injects and the `pipelex plugins list` diagnostic this function is modelled on. The runner boots the full interpreter, so it must read both groups: reading the kernel group alone would silently drop an installed orchestrator plugin's HTTP-error mapper and leave transport faults unmapped. The parameter is required rather than defaulted, so this omission would have surfaced as an import-time `TypeError` — the call site resolves at module scope, taking the whole app down on the next `pipelex` bump rather than degrading one feature. `test_exception_handlers.py` follows the matching `registrar.begin_plugin` signature change, passing `group=None`.
+
+## [v0.11.1] - 2026-08-03
+
+### Fixed
+
+- **The catch-all 500 now honors `ERROR_DISCLOSURE` like every other response.** `handle_unexpected_error` hard-coded `"An unexpected error occurred. The request id is included for support."` and never read the disclosure mode, so a `verbose` deployment — the default, and what every deployment runs, since the var is unset everywhere — got real messages for every *classified* error and a dead end for the one error nobody classified. That is backwards: an unclassified failure is precisely the one a caller cannot diagnose from a request id alone. A raw `pydantic.ValidationError` escaping input building (it is not a `PipelexError`, so no handler claimed it) landed here, and its reason was reachable only in CloudWatch.
+
+ Under `verbose`, `detail` is now `"<ExceptionClass>: <message>"`. Under `strict` the body is byte-identical to before — a deployment that wants nothing leaked keeps that, and provenance-gated redaction (`_authors_caller_facing_message`) is unchanged. A traceback still reaches the client in neither mode; the class name and full traceback continue to go to the operator log, correlated by request id. Docs: `docs/error-responses.md` → "Disclosure modes".
+
+## [v0.11.0] - 2026-08-01
+
+### Added
+
+- **Storage transport documentation (`docs/storage-transport.md`):** documents the `/upload` and `/resolve-storage-url` routes — their non-public contract status, their role as the current transport behind the SDKs' input-preparation surface, the two-layer size-limit enforcement (request-level `422` vs. post-decode `413`), and the planned migration to `pipelex-platform`. Linked from `docs/index.md` and added to the `mkdocs.yml` nav.
+- **Upload size-limit test:** `test_decoded_payload_over_cap_returns_413` covers the narrow window where a base64 payload clears the request's `max_length` validation but decodes over `MAX_UPLOAD_BYTES` — the only path that yields a `413`.
+
+### Changed
+
+- **Breaking — swept onto `pipelex`'s 0.41.0 restructuring.** The release deleted `pipelex.hub`, moved the MTHDS parser and the Pipe machinery out of `core/`, and relocated a set of types to the packages that own them; every import is re-pointed at the address that now defines the symbol.
+ - **The hub split.** `pipelex.hub` is gone with no shim, split into `pipelex.runtime_hub` and `pipelex.interpreter_hub` by owning layer. This falls out neatly along the route boundaries: the storage and uploader routes take `get_storage_provider` from the **runtime** hub and the pipeline route takes the orchestrator/bundle-validator registries from it too, while the build-runner and crate-ops routes take the library and pipe accessors from the **interpreter** hub.
+ - **`build_registrar` now requires its built-ins to be injected.** It no longer imports them, because the built-in list spans both layers and importing it inside a runtime-layer module would put the method interpreter back into every runtime closure. `_resolve_http_error_mappers` passes `BUILTIN_PLUGINS` / `CORE_UNCONDITIONAL_PLUGIN_NAMES` from `pipelex.interpreter_plugins.builtins` — the composed both-layer lists, matching the `pipelex plugins list` diagnostic this function is modelled on. The discovery function stays pure and repeatable, so resolving the mapper map at import is still safe.
+ - **Address moves:** `PipelexBundleBlueprint` → `pipelex.mthds_parsing.pipelex_bundle_blueprint`; `PipeAbstract` → `pipelex.pipe_machinery.pipe_abstract`; the input/output renderers → `pipelex.pipe_machinery.rendering.*`; `PipelexBundleBlueprintValidationErrorData` → `pipelex.core.exceptions`; `JobMetadata` → `pipelex.system.job_metadata`.
+ - The dotted pipelex class paths in `pyproject.toml`'s `runtime-evaluated-base-classes` (`PipeOutput`, `PipelexRunResultExecute`) were checked against 0.41.0 and did **not** move.
+- **Breaking — wire-visible error rename:** `PipelexInterpreterError` is now `MthdsParserError`. The class name *is* the `error_type` value on the wire, so this changes what clients see — `docs/error-responses.md` (the caller-facing-`detail` allowlist) and the webhook-recovery test fixture are updated to match.
+- **Dependencies:** Bumped `pipelex` from `0.40.0` to `0.42.0`.
+
+### Fixed
+
+- **`docs/error-responses.md` had a duplicated "Suggested fixes" section.** The 0.41.0 sweep accidentally duplicated the section (originally documented in v0.9.0) while moving surrounding content; removed the duplicate, no content change.
+
+## [v0.10.0] - 2026-07-19
+
+### Changed
+- **Breaking: `/execute` now returns `pipe_output.tokens_usages` as client wire records (`TokensUsageRecord`), not dumps of pipelex's internal usage models.** The route applies pipelex's `apply_tokens_usage_wire_shape` to the response dump, so each record is flat and closed: `model_type`, model name/id, `pipe_code`, `job_category`, `unit_job_id`, `nb_tokens_by_category`, computed USD `cost` (`null` when the model has no rate table), ISO `started_at`/`completed_at`. Runtime internals (`job_metadata` and its contexts/ids, `unit_costs`) no longer cross the wire. Null semantics unchanged (`null` = usage assembly off, `[]` = no inference). Documented in [Pipe Run](docs/pipe-run.md).
+- **The OpenAPI artifact now publishes the wire shape it actually emits.** `/execute` returns a `JSONResponse` built from the trimmed dump, so FastAPI never serializes through `response_model` — the declared 200 body was still the internal usage union (`LLMTokensUsage | ImgGenTokensUsage | …` with required `job_metadata` and `unit_costs`), and a client generated from the artifact would have rejected every real response carrying usage data. The route now declares `PipelexApiExecuteResponse` (the run result whose `pipe_output.tokens_usages` is `TokensUsageRecord[]`), so the published schema matches the body. The internal usage models leave the artifact entirely; `tests/unit/test_openapi_contract.py` pins the published record alongside the runtime guard, so the two fail together if either drifts again.
+- **Dependencies:** Bumped `pipelex` from `0.39.1` to `0.40.0`. This release carries `apply_tokens_usage_wire_shape` and the `TokensUsageRecord` wire shape the `/execute` change above depends on. (It supersedes the interim `0.39.2` bump — which unblocked the hosted runner resolving against a git-sourced `dev` — with a released PyPI pin.)
+
+## [v0.9.1] - 2026-07-15
+
+### Changed
+- **Dependencies:** Bumped `pipelex` from `0.39.0` to `0.39.1`.
+
+## [v0.9.0] - 2026-07-14
+
+### Added
+- **`POST /v1/resolve` (MTHDS Protocol resolution capability):** resolve a library closure into its **normalized library crate** over HTTP. Request selects the closure with inline `files[]` (each `{content, source?}`) XOR a `method_ref`; a produced verdict is a `200` discriminated on `is_valid` — the canonical JSON crate (qualified refs, flattened refinement, materialized natives, fingerprint) on the valid arm, the structured `validation_errors[]` on the invalid arm. `method_ref` is accepted by the envelope but answers `501` (`MethodRefNotSupported`) until server-side method-registry resolution exists.
+- **`POST /v1/codegen` (MTHDS Protocol type-projection capability):** project the crate into typed artifacts with the two explicit axes — `kind` (`types`) × `target` (`ts-zod`, `python-pydantic`, and the Pipelex-extension `python-structures`). The valid arm carries the **stamped** artifact set plus its `codegen.lock`: a client that writes them verbatim reproduces a local `pipelex codegen types` run byte-for-byte and passes the offline `pipelex codegen check`. An unknown `kind`/`target` (or a `pipe_ref` on the concept-set-wide `types`) is a request-shape `422` problem+json. There is deliberately no server-side check route (the drift check is offline by design), and no `inputs` kind: served-kind membership follows the stamp/lock trust chain, and an inputs template is a user-editable scaffold that is never stamped or locked — it rides `POST /v1/build/inputs` instead.
+- **Docs:** new [Resolve & Codegen](docs/codegen.md) page; [Pipe Builder](docs/pipe-builder.md) rewritten to the new envelopes.
+- **`postman-bundle` skill (renamed from `postman-run-bundle`) now covers the whole bundle surface:** besides `/v1/execute`, `/v1/start`, and `/v1/validate`, the skill and its `build_postman_query.py` script target `/v1/resolve`, `/v1/codegen` (with `--target ts-zod|python-pydantic|python-structures`), and `/v1/build/{inputs,output,runner}` (with `--output-format` for `build/output`, and `--inputs-format json|toml` + `--explicit` for `build/inputs`). New make targets `bundle-resolve` and `bundle-codegen`; the build routes ride the generic targets via `ENDPOINT=`. Postman pushes now land under a `Bundles/` top folder (was `Run Bundle/`) and merge by request name instead of replacing the whole per-bundle subfolder, so requests for different endpoints coexist.
+
+- **`suggested_fix` on validation errors (from pipelex codegen):** a `validation_errors[]` item may now carry a structured, deterministic repair the runtime's fix planner derived from the *typed* error data (never by parsing a message string) — `fix_code` (kebab-case rule id), `description`, `safety` (`safe` | `unsafe`), an optional `source`, and `ops[]`: semantic TOML patch operations (`set_key`, `ensure_table`, `delete_key`, `delete_table`, `rename_table_key`) addressed by `table_path`. The ops are the machine contract; any rendered diff is presentation. Optional and additive — a non-fixable item omits the field and a client that ignores it is unaffected. It rides every surface that carries the items: the `200` invalid arms of `/v1/validate`, `/v1/resolve`, `/v1/codegen`, and `/v1/build/*`, and the RFC 7807 problem documents. Documented in [Error Responses → Suggested fixes](docs/error-responses.md#suggested-fixes).
+
+### Changed
+- **`pipelex` is pinned to a git rev while `codegen` is unreleased.** The dependency source moved from a local editable path (`../pipelex`) to a git rev on the `pipelex` repo. The editable path only ever resolved on a workspace checkout — it fails `uv sync` anywhere else, CI included. The pinned rev carries the unreleased codegen engine this API rides; it reverts to a plain `==<version>` PyPI pin once a `pipelex` release ships it.
+- **The OpenAPI artifact now documents the real error contract.** Every failure this server emits is an RFC 7807 `application/problem+json` problem document, but the published artifact said otherwise: it advertised FastAPI's default `HTTPValidationError` on `application/json` for the 422 of nearly every route, `/v1/execute` and `/v1/start` documented no failure at all, and no route documented 401/403/409/413/429/500/501. Now every `/v1` operation documents `401`/`413`/`422`/`500` as a typed `ProblemDocument` under `application/problem+json`, plus the statuses it alone can produce — `/execute`: `403`, `429` (with `Retry-After`); `/start`: `400`, `403`, `409`, `501`; `/validate`: `403`; `/resolve` + `/codegen`: `501`. `GET /v1/version` stays public and 401-free. `HTTPValidationError` is gone from the artifact entirely.
+- **Breaking — `/v1/resolve` and `/v1/codegen` are no longer tagged `x-mthds-protocol`.** They are **Pipelex API extensions**, not MTHDS Protocol operations: the protocol is, and stays, the five routes `execute` / `start` / `validate` / `models` / `version` that the standard's own normative OpenAPI defines. The flag is how a conformance suite or a third-party runner extracts the portable subset of the artifact, so tagging a Pipelex route misrepresented the standard. The *crate* `/v1/resolve` emits remains standard-owned (the MTHDS Library Crate Format) with brand-neutral wire fields — only the routes' protocol membership changed, and no request or response shape moved. `tests/unit/test_openapi_contract.py` now pins the tagged set exactly, in both directions.
+- **Docs:** [Error Responses](docs/error-responses.md) gains a *Suggested fixes* section and the missing `missing_pipe_code` field, and its status-code list now covers the `400` (`StartRequiresAsyncOrchestration`), the `orchestration_mode` `403`, and the `method_ref` `501` (the `501` bullet also named a stale `/pipeline/start` path). The [Overview](docs/index.md) endpoint catalog gains the *Resolve & Codegen* section and `GET /`, and corrects the uploader auth requirement — `/v1/upload` and `/v1/resolve-storage-url` need an authenticated **user identity**, which `AUTH_MODE=api_key` does not establish (the key is shared, not per-caller).
+- **Breaking — `/v1/build/{inputs,output,runner}` migrated onto the `/validate` verdict discipline:** a produced verdict is now always a `200` discriminated on `is_valid`. `build/inputs` and `build/output` wrap their previous bare JSON payload in the valid arm (`inputs` / `output` fields); an invalid bundle — including a failed dry-run of the requested pipe — is now a `200` `is_valid: false` with the structured `validation_errors[]` instead of a `422`. `build/runner` drops the retired `success` bool.
+- **Breaking — `/v1/build/runner` rides the codegen types projection (D9):** the generated script spells its imports, example inputs, and output cast with the **emitted** class names, and the valid arm now also carries the `structures` projection it imports from (stamped `structures.py` + `codegen.lock`, written into a `structures/` directory beside the script) — matching what a local `pipelex build runner` scaffolds. A requested pipe recorded SKIPPED by the sweep (cross-package dependency absent from the request) remains a request-shape `422`.
+- **Breaking — `/v1/build/*` now ride the same request envelope as `/v1/resolve` and `/v1/codegen`:** the closure selector is inline `files[]` (each `{content, source?}`) XOR a `method_ref` (`501` until the method registry lands), replacing the bare `mthds_contents[]` strings. The per-file `source` label means build diagnostics can finally name the owning file, and there is no second breaking migration waiting when `method_ref` resolution arrives. The pipe selector becomes **`pipe_ref`** — the qualified `domain.pipe_code`, and now **optional**: omitted, it defaults to the closure's declared `main_pipe`, exactly like `pipelex codegen inputs --pipe`. A closure declaring *no* `main_pipe`, or *several* across domains, cannot be defaulted, so an omitted `pipe_ref` is a `422` there. Every valid arm echoes the resolved `pipe_ref` plus the submitted `requested_pipe_ref` (absent when defaulted). The echoed `pipe_ref` is always **qualified**, read back off the resolved pipe rather than off the request — a bare code still resolves through the engine's cross-domain fallback, and the caller is told the qualified ref it landed on. The old bare-`mthds_contents` envelope now survives on `/v1/validate` alone, which keeps it because changing a protocol route's envelope is the MTHDS spec's call, not this server's.
+- **Breaking — `/v1/build/inputs` and `/v1/build/output` are static; `allow_signatures` is gone from both.** They now resolve their closure through the same static core as `/resolve` and `/codegen` and read the requested pipe's *declared* IO — no dry-run sweep, so no `allow_signatures` (the flag only ever parameterized that sweep). A valid verdict from them says the closure is structurally sound, **not** that the pipe runs; runnability stays `/v1/validate`'s vocabulary. `/v1/build/runner` is the deliberate exception — a runner script *is* a promise the pipe runs, so it keeps both the sweep and the flag. When its `pipe_ref` is omitted the sweep cannot be scoped before the closure loads, so the whole closure is swept.
+- **Breaking — `/v1/build/inputs` gains the CLI's two rendering axes, and its payload's JSON type follows the format.** New `format` (`json`, default | `toml`) and `explicit` (bool, default `false` — the ceremonial `{concept, content}` envelope instead of the default light, signature-driven shape), rendered through the same engine renderers `pipelex codegen inputs` uses. The template rides the field its format names: `inputs` (a parsed object) for JSON, `inputs_toml` (raw text) for TOML — TOML cannot ride as a parsed object without losing the concept comments and key order that are the reason to ask for it. The unselected field is omitted from the body. A pipe declaring no inputs is a *valid* verdict carrying an empty template, not an error (the CLI likewise exits 0 on it).
+
+### Fixed
+- **`/v1/build/runner` could read the wrong pipe's output multiplicity.** A blueprint's pipe map is keyed by *bare* code, and the multiplicity lookup scanned by bare code alone. In a closure where two domains declare a pipe with the same name, it returned whichever blueprint came first — so a list-output pipe could be handed a scalar runner script (`main_stuff_as` instead of `main_stuff_as_items`), and vice versa. The lookup now matches the owning domain too.
+- **`/v1/build/output` with `format=python` was a hard `500`.** The route parsed *every* format with `json.loads` and typed the field `dict`, so the Python-source representation crashed on arrival. The representation now rides the field its format names, mirroring `/build/inputs`: `output` (a parsed object) for `schema`/`json`, `output_python` (source text) for `python`. Separately, a pipe whose `native.Anything` output has no determinable shape (which `render_output` reports with a bare `ValueError`) is now an honest request-shape `422` rather than an unhandled `500`.
+- **Docs — [Error Responses](docs/error-responses.md) no longer contradicts the 200-verdict discipline.** Two sections still said an invalid bundle rides a `422` on the build routes, and the 422 example showed `POST /v1/validate` producing one; both now correctly attribute the `ValidateBundleError` 422 to the run routes (`/execute`, `/start`) alone, with the diagnostic routes answering `200` `is_valid: false`.
+
+## [v0.8.0] - 2026-07-06
+
+### Changed
+- **Dependencies:** Bumped `pipelex` from `0.37.0` to `0.38.0`.
+- **Adapted to pipelex 0.38.0 breaking changes:** `StrEnum` is now imported from the stdlib `enum` — pipelex 0.38.0 dropped Python 3.10 and deleted the `pipelex.types` re-export module that used to provide it. And `PipeSignature` is no longer a pipe type: a signature (contract-only pipe) is declared by **omitting** `type`, so the signature test fixtures and the `/validate` docs were updated to the typeless form (writing `type = "PipeSignature"` is now rejected by the runtime).
+
+### Added
+- **Optionality surface on `/validate` and working memory (from pipelex 0.38.0):** the regenerated OpenAPI artifact exposes pipelex's new optionals feature — `optional` (`?`) markers on IO contracts and data edges, `liftable_pipes` (pipes that may be skipped when an optional input resolves absent) plus a general `warnings` array on the validation report, `skip_reason` on graph nodes, and an `absences` ledger (`AbsenceRecord` / `AbsenceKind`) on the serialized working memory.
+
+## [v0.7.0] - 2026-07-04
+
+### Added
+- **Core:** Introduced `PipelexPipeDispatchAck` payload to handle fire-and-forget job acknowledgments (returning IDs only), replacing incomplete `PipelexPipeRunOutput` objects for async dispatches.
+
+### Changed
+- **Architecture:** Replaced the `DeliveryMode` flag and unified `orchestrator.run()` method with explicit wait-semantics methods: synchronous `/execute` requests drive the blocking `orchestrator.execute()`, while asynchronous `/start` requests drive the fire-and-forget `orchestrator.start()`.
+- **Dependencies:** Bumped `pipelex` from `0.36.0` to `0.37.0`.
+- **Developer Tools:** Streamlined `Makefile` commands and `CLAUDE.md` docs: renamed `make c` to `make agent-check` and `make t` to `make agent-test` (both silent on success), and added `make cleanderived` to clear caches and compiled files.
+- **Testing:** Aligned test stubs (`_StubOrchestrator`, `_RecordingStub`) and protocol conformance tests with the new `execute`/`start` protocol, and enhanced the `execute` stub to promote input stuff to main stuff via the `MAIN_STUFF_NAME` alias, enforcing the completed-memory invariant.
+- **Documentation:** Updated internal API routing comments to reference `{MTHDS_BASE_URL}` instead of `{MTHDS_API_URL}`.
+
+## [v0.6.0] - 2026-06-30
+
+Orchestrator-agnostic base. `pipelex-api` no longer hard-wires Temporal: the published base names **no** orchestrator and runs every pipeline in-process, while distributed execution (Temporal, Mistral Workflows, …) becomes a deployment *flavor* = base image + exactly one orchestrator plugin + that plugin's activation. `api/` imports no `pipelex.temporal` / `temporalio`.
+
+### Added
+ - **`orchestration_mode` deployment config:** a top-level run's backend is read from a new packaged `api.toml` (`orchestration_mode`, default `direct`; `allow_request_orchestration_mode_override`, default `false`), env-layered like the Pipelex config (`api_{env}.toml` / `api_override.toml`). `orchestration_mode` is an **open string token** (core owns `direct`; each orchestrator plugin owns its own, e.g. `temporal`); an unregistered token fails loud at dispatch. `POST /v1/execute`, `POST /v1/start`, and `POST /v1/validate` may each carry a per-request `orchestration_mode` override, honored only when the deployment opts in — otherwise refused with a `403` (`OrchestrationModeOverrideForbidden`). The **delivery** axis (blocking vs fire-and-forget) is endpoint-intrinsic, never configured or requestable. See [Configuration → Orchestration mode](docs/configuration.md).
+ - **Orchestrator HTTP-error mappers:** the app discovers each installed orchestrator plugin's transport-fault mapper (via the plugin SPI `add_http_error_mapper`) at construction and registers one RFC 7807 handler per mapped exception type — so a plugin's transport fault renders correctly while the base imports no orchestrator SDK.
+ - **`make docker-run-hub` target:** pull and run the published `pipelex/pipelex-api` Docker Hub image without a local checkout or build, using the same `.env` contract as `make docker-run`. Pin a tag with `HUB_TAG=<tag>` (defaults to `latest`).
+
+### Changed
+ - **Two orthogonal axes — `orchestration_mode` (open token) + delivery (endpoint-set):** the backend (*which orchestrator*) and the wait-semantics (*whether the caller waits*) are now distinct. `orchestration_mode` names only the backend and is an open string token. Delivery is `DeliveryMode {BLOCKING, FIRE_AND_FORGET}`, threaded into the orchestrator by the endpoint and never received from a caller: `/execute` and `/validate` dispatch `BLOCKING`, `/start` dispatches `FIRE_AND_FORGET`. The conflated `execution_mode` enum (which carried `temporal_blocking` / `temporal_fire_and_forget` / `mistral_native`) is gone.
+ - **`/execute` dispatches by `orchestration_mode`:** `POST /v1/execute` selects its backend from the resolved `orchestration_mode` — dispatching the locally-built run job through the hub's `OrchestratorRegistry` with `BLOCKING` delivery, symmetric with `/start` — instead of the boot-global pipe-run slot. `orchestration_mode` is the single source of truth for top-level dispatch (`boot_orchestrator` narrows to the execution stack). A per-request `orchestration_mode` override is gated by the same `403` policy as `/start`. The full output is preserved across the dispatch: the orchestrator's JSON-safe result is rehydrated back into the canonical `PipeOutput` the response wraps.
+ - **`/start` is HONEST about fire-and-forget:** `POST /v1/start` builds the run job locally (preserving `request_id`, `output_multiplicity`, `dynamic_output_concept_ref`, run registration, and telemetry) and dispatches it through the hub's `OrchestratorRegistry` with `FIRE_AND_FORGET` delivery. It checks the resolved orchestrator's `supports_fire_and_forget` capability **before** loading a library: an async-capable backend (`temporal`, contributed by the `pipelex-temporal` plugin) acks `202` with its `workflow_id`, while the in-process `direct` base is blocking-only and is refused with a `400` (`StartRequiresAsyncOrchestration`) — use `/execute` — instead of silently running blocking and acking.
+ - **`/validate` dispatches by `orchestration_mode` (verdict-as-value):** like `/start`, `/validate` resolves the deployment's `orchestration_mode` and dispatches through the hub's `BundleValidatorRegistry`, returning the verdict as a value — a 200 valid `PipelexValidationReport` or a 200 invalid `ErrorReport` (no exception-as-control-flow at the route). Validation is inherently blocking, so there is no delivery axis here. `direct` validates **in-process** on the API side; a `temporal` mode dispatches the whole job to a **worker** (contributed by the `pipelex-temporal` plugin) and assembles the same canonical report API-side from the worker's result. A per-request `orchestration_mode` override is gated by the same policy as `/start` (`403` when forbidden). The verdict wire is byte-identical across backends. Size in-process `/validate` traffic for the library load; on a worker-dispatched flavor the library work happens worker-side.
+ - **Dependencies:** pinned `pipelex` to the published `0.36.0` (`pipelex[mistralai,anthropic,google,google-genai,bedrock,fal]==0.36.0`), replacing the prior git-rev pin (`[tool.uv.sources]` removed). Dropped the `temporal` extra — the base depends on no orchestrator plugin — and dropped the now-redundant direct `mthds` dependency (pulled in transitively by `pipelex`).
+
+## [v0.5.0] - 2026-06-18
+
+### Added
+ - **Opt-in Markdown rendering on `/validate`:** `POST /v1/validate` now accepts an optional `render` list of view-format tokens (e.g., `["markdown"]`). When requested, the response includes a `rendered_markdown` field on both valid and invalid arms, matching the local CLI output. Unknown tokens are ignored to keep presentation hints separate from the verdict contract. This is supported end-to-end via a new `--render` flag in `build_postman_query.py` and a `RENDER` variable in `Makefile.local.mk`.
+ - **Postman sample bundles:** Added a suite of sample `.mthds` bundles and `.inputs.json` files in `postman/sample-bundles/` covering valid, invalid, and runnable pipeline states.
+
+### Changed
+ - **`mthds_sources` migrated to `extra` hook:** `ApiRunner.validate` now passes `mthds_sources` through the generalized `extra: dict | None` extension point, matching the updated `PipelexMTHDSProtocol.validate` signature from `mthds-python 0.5.0`.
+ - **`main_pipe` is now optional for validation:** Bundles without a main pipe validate successfully (`is_valid: true`) but return `graph_spec: null`. Documentation and scripts updated accordingly.
+ - **OpenAPI Makefile targets depend on `install`:** `openapi-export` and `openapi-check` now depend on `install` instead of `env`, ensuring the schema is generated and validated against a fully synced environment to prevent silent CI drift.
+ - **Dependencies:** Bumped `pipelex` to `0.35.0` and added `mthds>=0.5.0` to `pyproject.toml`.
+
+## [v0.4.0] - 2026-06-17
+
+MTHDS Protocol surface alignment (Phase 2): `/validate` (like `/models`) now routes through `ApiRunner` (extending `PipelexMTHDSProtocol`), exactly like `/execute` and `/start`. The runner owns backend selection (in-process vs a single dispatched Temporal activity), the runtime owns the canonical artifact shapes, and the route only adds wire extras — so hosted and local runners answer with identical artifacts.
+
+### Added
+ - **Source threading for diagnostics:** Added an optional `mthds_sources` parameter to `POST /v1/validate`, letting clients pass per-file sources parallel to `mthds_contents`. Each source is threaded onto the corresponding `blueprint.source` and onto the structured errors, so cross-file diagnostics map back to their owning file. Additive — sourceless callers are unchanged; a length mismatch against `mthds_contents` is a request-shape 422.
+ - **Structured validation errors:** An invalid bundle now returns a non-empty `validation_errors` array on the 200 `InvalidReport`, where each item carries detailed locators (`category`, `message`, `error_type`, `source`, `field_path`, etc.) to map the error back to a specific construct and line. The items are builder-identical to the agent CLI's `validation_errors` (one shared pipelex builder, two surfaces).
+ - **Runnability facts:** Added `validated_pipes`, `pending_signatures`, and `is_runnable` to the validation report to communicate the runnability verdict across the HTTP surface.
+
+### Changed
+ - **`/validate` is now a 200-diagnostic endpoint:** An invalid bundle is a successfully produced verdict and returns **200 OK** with an `InvalidReport` (`is_valid: false`) instead of a 422. 422/5xx are reserved for no-verdict conditions (malformed request body, `mthds_sources` length mismatch, auth, server faults). The response is a discriminated union keyed on `is_valid`, returning either a `ValidReport` (structural artifacts) or an `InvalidReport` (structured errors). The previous `main_pipe` precondition is dropped: bundles without a main pipe now validate successfully with `graph_spec: null`.
+ - **Canonical validation report schema updates:** Renamed `pipelex_bundle_blueprint` to `bundle_blueprint` (the primary blueprint — first file declaring `main_pipe`, else first); `pipe_io_contracts` is now keyed by the namespaced `pipe_ref` (e.g. `domain.code`) instead of the bare pipe code; and within each entry the input/output identifier was renamed from `concept_code` to `concept_ref` (now always the namespaced `concept.concept_ref`). `BuildConceptResponse.concept_code` on `/v1/build/concept` is unaffected — it accepts a bare or qualified code.
+ - **`allow_signatures` behavior:** Unimplemented `PipeSignature` declarations no longer reject a bundle. `allow_signatures` now only controls sweep mechanics (whether signature pipes are mock-run and listed in `validated_pipes`); outstanding signatures are reported via `pending_signatures` with `is_runnable: false` on a 200 `ValidReport`.
+ - **`/models` returns the protocol `ModelDeck`:** `/models` now routes through `ApiRunner` and returns the canonical `ModelDeck` — the flat `models` list plus this implementation's category-keyed `aliases`/`waterfalls` routing extensions (a flat map would silently drop the same alias name across categories). The `?type=` query is now strictly single-value, matching the protocol arity.
+ - **Protocol version from the SDK:** `/version` and the OpenAPI metadata now source `PROTOCOL_VERSION` from `mthds.protocol.protocol`; the `pipelex.pipeline.runner.MTHDS_PROTOCOL_VERSION` alias is gone.
+ - **Temporal mode optimization:** The worker now computes all library-dependent artifacts (`pipe_io_contracts`, `pending_signatures`, `graph_spec`, status map, structured errors) within its single library load and ships them on the activity result, so the API side no longer re-acquires a library to build response artifacts.
+ - **Dependency & version bumps:** Bumped the API version to `0.4.0` and updated the pinned `pipelex` dependency to track the keyword-only-arguments refactor (`parse_pipe_spec(spec, pipe_type=...)`, keyword-only `Pipelex.make`) and the new structured-error / signatures-as-data contract.
+ - **Documentation:** Updated the OpenAPI artifact (`pipelex-api.openapi.yaml`), `pipe-validate.md`, and `error-responses.md` to reflect the 200-diagnostic contract, structured errors, and source threading.
+
+### Removed
+ - **`success` wire field:** Dropped the redundant `success` field from the `/validate` and `/models` responses in favor of the canonical `is_valid` discriminant.
+ - **Legacy `/models` keys:** Dropped the unused raw `presets` keys (keyed by category) from the `/models` response and removed support for multi-category `?type=` queries.
+
+## [v0.3.0] - 2026-06-17
+
+### Changed — `user_id` is opaque again (path-safe, not UUID-shaped)
+
+The runner no longer requires `user_id` to be a bare UUID. `user_id` is the owner segment of every storage key (`<user_id>/...`), and the runner is a generic execution engine: identity is the deployment's concern (enforced upstream by the gateway/auth layer that injects `X-User-Id`, or by the JWT issuer), not the runner's. The previous UUID-shape check wrongly rejected any non-UUID id — including hosted deployments that use prefixed ids like `user_<uuid>`, which were **silently downgraded to anonymous** and wrote results under `anonymous/...`.
+
+- `USER_ID_UUID_REGEX` is replaced by `is_safe_user_id(value)` in `api/security.py`: the only constraint is that the id be a single, **unambiguous path segment** — path-safe (no `/`, `\`, NUL/control chars, DEL; not `.`/`..`) and free of URI gen-delims (`:`, `?`, `#`, `[`, `]`, `@`). Any other opaque id (`user_<uuid>`, a bare uuid, `user-123`, …) is accepted as-is.
+- URI gen-delims are rejected because the id is embedded into a `pipelex-storage://<user_id>/...` URI: a value like `google#abc` is owner `google#abc` by raw split but `google` under a standard URI parser (`urlparse`), so a consumer could resolve a different owner than the one this server authorized.
+- Applies to all three sites: the JWT `user_id` claim, the forwarded `X-User-Id` header (`TRUST_FORWARDED_IDENTITY_HEADERS=true`), and `pipelex-storage://` URI parsing (`/resolve-storage-url`).
+- This reverses the prior "must be a UUID" constraint. Path-traversal protection is unchanged (it never depended on the UUID shape).
+
+### Fixed — close the `anonymous`-sentinel and malformed-forwarded-id gaps
+
+The opaque-id change above made `anonymous` a path-safe value and left the forwarded-id path failing open. Both are now closed in `api/security.py`:
+
+- **The reserved `anonymous` sentinel can no longer be claimed by an authenticated token.** A JWT with `user_id: "anonymous"` previously passed the path-safety check and bound that exact value — landing the caller's runs in the shared `anonymous/...` namespace while storage/upload routes still treated them as unauthenticated. `verify_jwt` now rejects it with `401 InvalidToken`. The value is centralized as `ANONYMOUS_USER_ID`.
+- **A malformed forwarded `X-User-Id` now fails closed.** When `TRUST_FORWARDED_IDENTITY_HEADERS=true` and the proxy forwards a non-empty but path-unsafe id, `no_auth` previously logged and silently downgraded to anonymous; it now rejects the request with `400 BadRequest`. The absent-header and explicit-`anonymous` cases still stay anonymous (the proxy's deliberate "this request is anonymous" signal).
+- **`is_safe_user_id` now rejects DEL (`\x7f`).** The unsafe-character class covered C0 controls (`\x00-\x1f`) but let DEL through, contradicting the "no control characters" invariant. DEL is now rejected across all three sites (JWT claim, forwarded header, storage-URI parsing).
+
+## [v0.2.0] - 2026-06-12
+
+### Changed — extension args are this server's own (callback_urls)
+
+- The MTHDS Protocol no longer defines `callback_urls` (or any completion channel) — it is now formally THIS server's extension. The `/start` OpenAPI schema is published from the server's own `PipelexApiStartRequest` model (protocol `StartRequest` + the documented `callback_urls` extension) instead of relying on the protocol model to advertise it. `ApiRunner.start` drops the dead `method_id` compatibility param (the hosted platform handles `method_id` itself and never forwards it) and gains the protocol's generic `extra` slot. SDK clients pass server-specific args via `extra` — e.g. `client.start(..., extra={"callback_urls": [...]})`.
+
+### Breaking Changes — MTHDS Protocol alignment (master plan 05, Phase C1)
+
+This server is now the reference implementation of the **[MTHDS Protocol](https://mthds.ai)** (contract nesting: MTHDS Protocol ⊂ Pipelex API ⊂ Pipelex hosted API). Clients on the new SDKs (`mthds` Python/JS protocol releases) require a pipelex-api image carrying these changes — **the minimum image version for the `/v1` surface is this release**; an older image 404s on every `/v1/*` call.
+
+- **Base path: `/api/v1` → `/v1`, no aliases.** The API router now mounts at `/v1` (SDKs compose `{MTHDS_API_URL}/v1/{endpoint}`). Zero `/api/v1` routes remain.
+- **Run routes renamed:** `POST /api/v1/pipeline/execute` → `POST /v1/execute`, `POST /api/v1/pipeline/start` → `POST /v1/start`. `/start` now answers **202 Accepted** (protocol `StartAck`) instead of 200.
+- **Wire fields renamed (D1):** request extra `pipeline_run_id` → `pipeline_run_id` (client-supplied run ids on `/start` are still accepted — the protocol allows it and `StartAck.pipeline_run_id` is authoritative); responses serialize `pipeline_run_id` / `state` instead of `pipeline_run_id` / `pipeline_state`. The pipelex runtime internals keep `pipeline_run_id` — only the wire renames.
+- **`GET /version` replaces `GET /pipelex_version` + `GET /api_version` (both deleted, no alias).** Returns the protocol `VersionInfo`: `{protocol_version, implementation: "pipelex-api", implementation_version, runtime_version}`. PUBLIC — excluded from auth exactly like `/health` (it's the handshake clients use before they have credentials).
+- **Completion-callback payload now carries `pipeline_run_id`.** The webhook POSTed to `callback_urls` carries the protocol `pipeline_run_id` field alongside the runtime's existing `pipeline_run_id`/`status` keys; the `X-Completion-Signature` is `HMAC-SHA256(secret, pipeline_run_id)` (unchanged scheme, renamed input). The `status` → `state` key rename lives in the pipelex runtime's delivery executor and ships with a later pipelex release — receivers should read `pipeline_run_id` + `status` for now.
+- **Pipelex pinned to 0.33.0** (`PipelexMTHDSProtocol` — the renamed `PipelexRunner` — with protocol methods `execute`/`start`/`validate`/`models`/`version`; `PipelexRunResult`/`PipelexStartAck` response models).
+
+### Added — MTHDS Protocol alignment
+
+- **Committed OpenAPI artifact + drift gate.** `docs/openapi/pipelex-api.openapi.yaml` is the layer-2 contract, exported from the live app via `make openapi-export` and drift-checked in CI via `make openapi-check` (wired into the lint workflow and `make check`). The five protocol routes are tagged `x-mthds-protocol: true`; `/upload` and `/resolve-storage-url` are documented as NON-CONTRACT in their descriptions (kept in the schema for self-hosters' interactive docs).
+- **Protocol conformance suite.** `tests/unit/test_protocol_conformance.py` gates CI on: the five protocol paths under `/v1` (and zero legacy paths), the `RunRequest` anyOf rule (422 on empty body), the public `/version` handshake + shape, client-supplied `pipeline_run_id` acceptance, and the completion-callback E2E — a local in-test HTTP receiver verifies delivery, the `X-Completion-Signature` HMAC, and the payload's `pipeline_run_id`/status fields through the real `DeliveryExecutor` code path (Temporal dispatch faked in-process).
+
+### Changed — `/validate` fast path restored
+
+- **Temporal-enabled `/validate` dispatches one in-process activity again.** The earlier temporary regression (direct in-process `validate_bundle` + `dry_run_pipeline`) is undone now that the pinned pipelex ships `wf_dry_validate` / `act_dry_validate`. On a Temporal-enabled runner, `/validate` runs the whole sweep **+** graph dry-run as ONE `act_dry_validate` activity (a single worker round-trip) instead of dispatching the dry-run pipeline pipe-by-pipe through Temporal (one workflow + activities per pipe) — restoring the fast path first added in PR #12. Direct (Temporal-disabled) mode is unchanged. Same wire contract; the error contract and best-effort-graph semantics are identical across both backends.
+
+### Changed
+
+- **Duplicate `pipeline_run_id` now returns 409 Conflict instead of 500.** `PipelineManagerAlreadyExistsError` — raised when a submission reuses a `pipeline_run_id` that is still registered for an in-flight run — is mapped to 409 via `_ERROR_TYPE_STATUS_OVERRIDES`, so a genuinely concurrent duplicate is a client-visible conflict rather than an opaque internal error. Pairs with the pipelex-side fix that frees a run's registry entry when it completes or fails, making serial resubmission of the same id succeed (previously every resubmission of a used id 500'd until process restart). Documented in [`docs/error-responses.md`](https://github.com/Pipelex/pipelex-api/blob/main/docs/error-responses.md).
+- **Error-log disposition is now keyed off the final HTTP status, not the error domain.** A 4xx logs at `warning` (no traceback); a 5xx logs at `error` (with traceback). This keeps API-level 4xx overrides — the new 409 conflict, and the provider-429 passthrough — out of error dashboards instead of paging on a normal client conflict. The previous rule (only `INPUT`-domain → `warning`) left domain-less 4xx errors logging at `error`.
+- **Temporal-enabled `/validate` now runs as ONE worker round-trip.** When `temporal.is_enabled` is true, the route dispatches the whole job — validation sweep **+** graph dry-run — as the one-step wrapper workflow `wf_dry_validate` (→ the single in-process `act_dry_validate` activity) via pipelex's `dispatch_dry_validate`, instead of running `validate_bundle` API-side and `dry_run_pipeline` as a top-level worker workflow with a tracing-backend round-trip. The worker traces the graph in memory and returns `{status map, graph_spec}` on the activity result; the route re-parses the blueprints and builds `pipe_io_contracts` from a local load-only library acquisition. The wire contract is unchanged on both backends: same 200 `ValidateResponse` envelope, same best-effort `graph_spec` (null when the graph dry-run fails), same RFC 7807 422 carrying `error_type=ValidationError` for the missing-`main_pipe` precondition and `error_type=ValidateBundleError` for validation failures — both with `error_domain=input` (the structured report crosses the activity boundary and the global handler renders it identically). Direct mode (Temporal disabled) is untouched. Requires a pipelex version that ships `act_dry_validate` (newer than v0.32.1).
+
+### Breaking Changes
+
+- **Every error response is now [RFC 7807 `application/problem+json`](https://github.com/Pipelex/pipelex-api/blob/main/docs/error-responses.md).** Replaces the legacy `{"detail": {"error_type", "message"}}` envelope across pipelex domain errors, validation (422), auth (401/403), payload limits (413), and the catch-all 500. Standard members on the wire: `type` / `title` / `status` / `detail` / `instance`. Extension members: `error_type`, `error_domain`, `retryable`, `request_id`, and — when populated by pipelex — `error_category`, `user_action`, `provider_metadata`, `model`, `provider`. Content-Type is `application/problem+json`. Clients reading the legacy `data.detail.message` must read RFC 7807 `detail` (top-level string) instead.
+- **`/validate` failure envelope removed.** A failing validation no longer returns `HTTP 200` with `{success: false, mthds_contents, message}`; it now returns `HTTP 422` (`ValidateBundleError`) with the RFC 7807 envelope. The former 400 "no `main_pipe`" path is also 422 now. **Success path (200 `ValidateResponse`) is unchanged** — same `mthds_contents`, `pipelex_bundle_blueprint`, `graph_spec`, `pipe_io_contracts`, `success: true`, `message` fields. Cross-repo consumers in `pipelex-app` and `mthds-js` updated in companion PRs.
+- **`X-Request-ID` is now echoed on every response** (success and error). Inbound `X-Request-ID` is respected; otherwise the server generates a UUID. The same id rides through `JobMetadata.request_id` to every Temporal worker log record.
+
+### Added
+
+- **`ERROR_DISCLOSURE` env var.** `verbose` (default) renders the full `ErrorReport`; `strict` redacts `detail` for non-caller-facing errors and always strips `model` / `provider` / `provider_metadata`. Provenance-gated via pipelex's `_authors_caller_facing_message` ClassVar — `error_domain` no longer drives redaction. Server logs stay verbose regardless of disclosure mode.
+- **[`docs/error-responses.md`](https://github.com/Pipelex/pipelex-api/blob/main/docs/error-responses.md)** — public API error-contract page describing the envelope, status-code mapping (`input`→422, `config`/`runtime`→500), the `type` URI namespace, disclosure modes, request correlation, and worked examples. Linked from `docs/pipe-run.md` and `docs/pipe-validate.md`.
+- **`allow_signatures` API flag.** Opt-in boolean on `/validate`, `/build/inputs`, `/build/output`, and `/build/runner`. When `true`, the validation sweep tolerates unimplemented `PipeSignature` placeholders (dry-running them by minting a mock) instead of rejecting the bundle. Defaults to `false` (strict).
+- **Postman & `curl` bundle runner.** New `postman-run-bundle` Claude skill and `build_postman_query.py` script that turn a local MTHDS bundle into a Postman request, a `curl` command, or a direct API execution. Resolves the bundle exactly like `pipelex run bundle <path>` and targets `/api/v1/pipeline/execute`, `/start`, and `/api/v1/validate`.
+- **Bundle testing Make targets.** `make bundle-run`, `bundle-validate`, `bundle-curl`, `bundle-postman`, and `bundle-dry` exercise a bundle against the API from the CLI.
+- **Local Pipelex WIP support.** `make run-wip` / `install-wip-pipelex` run the API against a local, editable `pipelex` working tree without hand-editing `pyproject.toml`.
+
+### Changed
+
+- **Adapt to post-#931/#933 pipelex surface.**
+ - Phase 6 module relocation: `EnvVarNotFoundError` is now imported from `pipelex.system.exceptions` (was `pipelex.system.environment`). Tests updated; no production code touched the moved import.
+ - Acronym-casing fix: pipelex's `pascal_case_to_sentence` now preserves trailing acronym casing (`InvalidJSON` → `Invalid JSON`); the `test_error_uri.py::test_error_type_title` assertion updated.
+ - **Native `request_id` wiring at dispatch.** `POST /pipeline/start` now reads the request-scoped `request_id` contextvar and passes it as `request_id=` to `pipeline_run_setup(...)`, so it lands on `JobMetadata.request_id` and rides every worker-side `WorkflowLog` record. No more `webhook.payload["request_id"]` piggyback needed (and `WebhookTarget.payload` would now reject it as a reserved key anyway).
+ - **Cross-path consistency regression (T6).** New `tests/unit/test_webhook_recovery.py` pins the invariant: given the same source `ErrorReport`, the classification fields surface identically via the sync HTTP RFC 7807 response and via the webhook `error` payload (composed upstream by `DeliveryExecutor._notify_webhook`).
+ - **STRICT-disclosure audit (no code change).** Confirmed `api/problem_document.py` delegates wholesale to `report.to_problem_document(disclosure_mode=...)`, so pipelex's provenance-gated keying flip (Decision D1) flows through untouched. The two `error_domain == INPUT` sites in `api/exception_handlers.py` are log-level switches, not wire-disclosure switches, and remain correct.
+- **Shared request validation.** Consolidated the MTHDS payload validation (the `mthds_contents` bound + per-file size guard) and the new `allow_signatures` flag into a shared `MthdsContentsRequest` Pydantic base model that `/validate` and the build routes subclass, so the validation routes can't drift.
+- **`/build/inputs` and `/build/output` reuse the validated library.** Both now read the requested pipe from the library `validate_bundle` already opened and left current, instead of opening and loading a second one — less work and memory per request — and scope the dry-run sweep to the requested pipe.
+- **Unit tests run with Temporal disabled.** `tests/unit/conftest.py` forces `temporal_enabled=False`, so the suite executes pipelines (including dry-run validation) in-process and hermetically.
+- **`pyproject.toml` tooling config.** Set pyright `venvPath` / `venv` and expanded the `exclude` lists to ignore `node_modules`, hidden files, and `.claude/`.
+
+### Fixed
+
+- **Library resource leak in `/validate`, `/build/inputs`, and `/build/output`.** The library `validate_bundle` opens and leaves current on success was never torn down, orphaning a library in the `LibraryManager` on every successful call. Each route now owns that teardown in a `finally`.
+- **`/build/runner` returned 500 on a failed dry-run.** A failed dry-run of a caller-submitted bundle now becomes a 422 `ValidateBundleError` (RFC 7807 problem response), matching `/validate`, `/build/inputs`, and `/build/output`. (The bare `DryRunError` carried no `error_domain`, so the global handler had been rendering it as a server fault.)
+- **`/build/runner` generated code for a `SKIPPED` pipe.** When the requested pipe was `SKIPPED` during validation (an unresolved cross-package dependency), the endpoint used to emit runner code for a pipeline that can't actually run; it now rejects the request with 422.
+- **Makefile `help` output.** `Makefile_basics.mk` no longer overrides the root `help` target, so the local and deployment help sections all compose.
+
+### Known follow-ups (deferred, not in this set of changes)
+
+- Structured logging on `_notify_webhook` (`event=webhook_delivery` / `event=webhook_failure`) — lives in pipelex upstream at `delivery_executor.py`, not in this repo. Tracked for a separate pipelex PR.
+
+## [v0.1.2] - 2026-05-20
+
+### Changed
+
+- **Trimmed `RequestUser` to `user_id` only.** Dropped the `email`, `sub`, and `auth_method` fields. The runner is a generic execution engine — the only piece of identity it consumes is an opaque user id, which it scopes S3 storage keys under (`<user_id>/...`). Anything else (email, OAuth subject, auth method) is metadata the runner has no use for; handlers that need it look it up by `user_id` against the deployment's own user store.
+- **JWT auth now requires a `user_id` claim (UUID).** No fallback to the standard `sub` claim, and the value is now validated as a UUID (`^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$`) at the auth boundary. Storage URIs require the owner segment to match the same shape; provider-issued `sub` values like `"google#abc"` (or any non-UUID `user_id`) would otherwise let a caller upload to S3 under a key that `/resolve-storage-url` would later refuse to resolve. Deployments using OAuth JWTs must mint their own `user_id` claim (a UUID for that caller) when issuing tokens.
+- **Forwarded identity headers reduced to a single `X-User-Id` (must be a UUID).** With `TRUST_FORWARDED_IDENTITY_HEADERS=true`, only `X-User-Id` is honored and its value is validated against the same UUID shape as JWT `user_id`. Non-UUID values are silently ignored and the request stays anonymous. The previous `X-User-Email`, `X-User-Sub`, and `X-Auth-Method` headers are gone — they were metadata the runner never used.
+- Bumped Pipelex to v0.28.0. See changelog here: https://docs.pipelex.com/latest/changelog/
+
+### Fixed
+
+- `mkdocs build --strict` no longer fails on relative links inside the `CONTRIBUTING.md` snippet included into `docs/contributing.md`. Those links are authored to resolve from the repo root on GitHub; mkdocs validation for them is downgraded from `warn` to `info`.
+
+### Security
+
+- **Tightened `pipelex-storage://` owner-segment validation.** `parse_storage_uri` previously accepted any 36-character mix of hex and dashes (`^[a-f0-9-]{36}$`), so values like 36 dashes or `aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa` could pass through. The check now enforces the canonical UUID positional shape `8-4-4-4-12`, matching the validator newly applied at the auth boundary so the two layers cannot drift.
+
+## [v0.1.1] - 2026-05-07
+
+### Added
+
+- `/release` Claude Code skill (`.claude/skills/release/`) automating the release workflow: version bump in `pyproject.toml`, changelog finalization, `make check`, `make li`, release branch creation, commit, push, and PR.
+
+### Changed
+
+- Bumped Pipelex to v0.27.0. See changelog here: https://docs.pipelex.com/latest/changelog/
+
+## [v0.1.0] - 2026-05-04
+
+### Changed
+
+- **The published `pipelex/pipelex-api` Docker image is now generic.** Temporal is **off** by default, no S3 storage is configured, and no DynamoDB tracing is enabled. Anything environment-specific is now expected to come from a user-supplied `.pipelex/pipelex_override.toml` (or `pipelex_<env>.toml`) mounted into `/root/.pipelex/`. See [`docs/configuration.md`](https://github.com/Pipelex/pipelex-api/blob/main/docs/configuration.md).
+- **Removed deployment-specific env configs from the repo.** `pipelex_dev.toml`, `pipelex_staging.toml`, `pipelex_prod.toml`, and `pipelex_service.toml` previously baked one specific deployment's Temporal cluster, S3 buckets, and DynamoDB table names into the public image. They are gone — bring your own via a mounted `.pipelex/` override (see [`docs/configuration.md`](https://github.com/Pipelex/pipelex-api/blob/main/docs/configuration.md)).
+- **AWS/ECR deploy targets removed.** `Makefile.deploy.api.mk` now only contains `deploy-docker-hub`. The previous `deploy-api`, `deploy-api-dev`, `deploy-api-staging` targets and their corresponding workflows are gone — they were specific to one deployment's AWS account. CI in this repo now publishes to Docker Hub only on every push to `main`. Self-hosters wire their own deploy from a separate infra-as-code repo.
+- **Hardcoded `temporal_enabled=True` removed from `api/main.py`.** Temporal is now controlled entirely by `[temporal] is_enabled` in your config, with no Python-level override.
+- **Dockerfile cleans up `/app/.pipelex` after copying it to `/root/.pipelex`** so user-supplied overrides at `/root/.pipelex/*.toml` are not shadowed by a project-level `.pipelex/` inside the image.
+- **`.env.example` trimmed** to universally-needed vars only (`PIPELEX_GATEWAY_API_KEY`). Auth, Temporal, and callback-secret vars are now optional / deployment-specific.
+- **`COMPLETION_CALLBACK_SECRET` is no longer required at boot.** `api/routes/pipelex/pipeline.py` now reads it lazily inside `_completion_signature()` instead of at module import. The image boots with just `PIPELEX_GATEWAY_API_KEY`; the secret is only required when you actually use `POST /api/v1/pipeline/start` with a `callback_url`. See [`docs/pipe-run.md`](https://github.com/Pipelex/pipelex-api/blob/main/docs/pipe-run.md) → "Async Completion Callbacks".
+
+### Added
+
+- [`docs/configuration.md`](https://github.com/Pipelex/pipelex-api/blob/main/docs/configuration.md) — explains the env vars this Docker image accepts, the Pipelex config layering inside the container, and how to mount your own `.pipelex/` overrides. The actual Pipelex configuration syntax (storage, tracing, inference, Temporal, …) lives at https://docs.pipelex.com.
+
+### Fixed
+
+- Move `Pipelex.make()` from module top-level into a FastAPI `lifespan` handler in `api/main.py`. Importing `api.main` no longer mutates the global Pipelex singleton, which was causing `make t` to fail under `pytest-xdist` once enough unit tests existed for workers to share processes with the e2e import-smoke test.
+- Set a placeholder `COMPLETION_CALLBACK_SECRET` in `tests/conftest.py` so test collection succeeds in CI environments where `.env` isn't present. `api/routes/pipelex/pipeline.py` reads this var at import time, which was breaking `make gha-tests` collection as soon as any test transitively imported `api.routes`.
+
+### Security
+
+- `/upload` now rejects unauthenticated and `anonymous` callers with `401 Unauthenticated`, mirroring `/resolve-storage-url`. Previously, anonymous uploads were silently accepted and stored under an `anonymous/assets/…` prefix.
+
+### Changed
+
+- `/upload` returns `400 InvalidBase64` (instead of `500`) when the request body's `data` field isn't valid base64. Genuine storage failures still surface as `500`.
+- `UploadRequest` now uses `ConfigDict(extra="forbid")`, so unknown fields produce `422` instead of being silently ignored.
+- **`mthds_content` → `mthds_contents`** — Updated `ApiRunner.start_pipeline`, pipeline routes, and build routes to use `mthds_contents: list[str] | None` instead of singular `mthds_content`. Aligns with the updated `RunnerProtocol` in `mthds>=0.2.0`.
+- **`bundle_uri` → `bundle_uris`** — Renamed to `bundle_uris: list[str] | None` in `ApiRunner` to match the updated `PipelexRunner` interface.
+
+## [v0.0.12] - 2026-01-15
+
+### Changed
+
+- Bump `pipelex` to `v0.18.0`, the `Chicago` release: See changelog [here](https://docs.pipelex.com/changelog/)
+
+## [v0.0.11] - 2025-12-01
+
+### Added
+
+- `pyjwt` dependency.
+
+## [v0.0.10] - 2025-12-01
+
+### Changed
+
+- Bump `pipelex` to `v0.17.3`: See `Pipelex` changelog [here](https://docs.pipelex.com/changelog/)
+
+### Added
+
+- JWT authentication support.
+
+## [v0.0.9] - 2025-11-26
+
+### Changed
+
+- Bump `pipelex` to `v0.17.1`: See `Pipelex` changelog [here](https://docs.pipelex.com/changelog/)
+
+## [v0.0.8] - 2025-11-04
+
+### Added
+
+- Documentation for the API.
+
+### Changed
+
+- Reverted the `all_blackboxai` routing profile to the pipelex default one.
+
+## [v0.0.7] - 2025-10-29
+
+### Changed
+
+- Hardcoded routing profile `all_blackboxai` for the pipelex hackathon.
+
+## [v0.0.6] - 2025-10-29
+
+### Changed
+
+- More robust library management.
+
+## [v0.0.5] - 2025-10-27
+
+### Fixed
+
+- Updated `Pipelex` dependency to `v0.14.0`.
+
+## [v0.0.4] - 2025-10-26
+
+### Fixed
+
+- Updated telemetry settings.
+
+## [v0.0.3] - 2025-10-25
+
+### Feature
+
+- You can now run directly a pipelex bundle from the API.
+
+### Added
+
+- `Pipelex.make(IntegrationMode.FASTAPI)` to the API
+
+## [v0.0.2] - 2e25-10-22
+
+### Added
+
+- `docker-compose.yml` file
+
+### Changed
+
+- `README.md` Added more precise instructions for local, docker run, and docker compose.
+
+## [v0.0.1] - 2025-10-22
+
+- Initial commit!
diff --git a/api/CLAUDE.md b/api/CLAUDE.md
new file mode 100644
index 000000000..90d0bb78d
--- /dev/null
+++ b/api/CLAUDE.md
@@ -0,0 +1,240 @@
+# Pipelex API
+
+Pipelex API is the official FastAPI REST server for [Pipelex](https://github.com/Pipelex/pipelex). It wraps the Pipelex core library and exposes pipeline building, execution, and validation as HTTP endpoints. It is designed to be deployed via Docker and consumed by frontends, agents, and external services.
+
+## Where this server lives
+
+This directory is the `api/` member of the pipelex repository's uv workspace: the distribution `pipelex-api`, the import package `pipelex_api`, and the image `pipelex/pipelex-api`. It moved here from the `Pipelex/pipelex-api` repository at that repository's last release, v0.33.2, which remains the place to read its history; `git blame` here starts at the import. Its own `CHANGELOG.md` stops at 0.33.2, and a change to the server is now an entry in pipelex's `CHANGELOG.md`, at the repository root.
+
+- **It runs the pipelex of the same commit.** `pyproject.toml` takes `pipelex` from the workspace (`[tool.uv.sources] pipelex = { workspace = true }`), and the repository keeps one `uv.lock`, at its root. There is no pin to bump and no git source to move: a library change reaches the server in the change that makes it, and the server's gate, which the root `make agent-check` and `make agent-test` run, fails that change when it breaks the server. pipelex's pull-request workflows do not run that gate, so run it before pushing. The dependency names no version, since uv ignores a specifier on a workspace source.
+- **It has the library's version.** `pyproject.toml` declares the version dynamic and hatch reads it from the root `pyproject.toml` (`[tool.hatch.version]`), so a release bumps one file and `/v1/version`, the OpenAPI artifact and the image tag (`make deploy-docker-hub`) all carry the library's number. The published wheel's exact pin on `pipelex` is still to be added with the release chain that publishes it.
+- **It has its own environment.** Every uv command in the Makefile targets `api/.venv` (`UV_PROJECT_ENVIRONMENT`), where `uv sync` installs this member with its extras and pipelex, in editable mode, with the server's extras and without `cli`. The targets that need the environment provision it, so a fresh worktree needs nothing run by hand first.
+- **Its gate runs from the root.** The root `make agent-check` ends with `make -C api agent-check` and the root `make agent-test` with `make -C api agent-test`; run them here directly while working on the server. Upgrading dependencies is done for the whole workspace, at the root.
+- **The image is built from the repository root** as its context, `docker build -f api/Dockerfile .`, which is what `make docker-build` runs, so the image installs the pipelex of the same commit. The root `.dockerignore` keeps that context to the files the build reads.
+
+## Project Structure
+
+```
+pipelex_api/
+ main.py # App init (PipelexFastAPI), middleware, router registration (mounts at /v1)
+ openapi_schema.py # PipelexFastAPI — publishes every 4xx/5xx as application/problem+json
+ openapi_responses.py # ProblemDocument + the shared per-status `responses=` declarations
+ security.py # Authentication (API Key + JWT)
+ schemas/models.py # Pydantic request/response models
+ routes/
+ health.py # GET /health (no auth)
+ version.py # GET /v1/version (no auth — MTHDS Protocol handshake)
+ pipelex/
+ pipeline.py # POST /v1/execute, /v1/start (MTHDS Protocol run routes)
+ validate.py # POST /v1/validate
+ resolve.py # POST /v1/resolve (closure → normalized crate)
+ pipe_io.py # POST /v1/pipe-io (closure → one pipe's, or every pipe's, I/O artifacts; no dry run)
+ codegen.py # POST /v1/codegen (crate → typed artifacts)
+ crate_ops.py # Closure resolution, the pipe selection chain, and the invalid-arm envelope the crate routes share
+ tools.py # POST /v1/lint, /v1/format (editor tooling)
+ build/ # POST /v1/build/{inputs,output,runner}
+ agent/ # POST /v1/build/{concept,pipe-spec}, GET /v1/models
+tests/
+ unit/ # Unit tests
+scripts/
+ export_openapi.py # Writes or drift-checks the committed OpenAPI artifact
+ sync_vendored_kit.py # Writes or drift-checks the vendored .pipelex/inference/ tree
+```
+
+This server is the reference implementation of the [MTHDS Protocol](https://mthds.ai): `POST /execute`, `POST /start`, `POST /validate`, `GET /models`, `GET /version` under the `/v1` base path, tagged `x-mthds-protocol: true` in the committed OpenAPI artifact (`docs/openapi/pipelex-api.openapi.yaml`, regenerated via `make openapi-export`, drift-checked via `make openapi-check`). Contract nesting: MTHDS Protocol ⊂ Pipelex API ⊂ Pipelex hosted API.
+
+**Only those five operations carry `x-mthds-protocol`** — the flag is how a conformance suite or a third-party runner extracts the portable subset of the artifact, so tagging a Pipelex route would misrepresent the standard. Everything else this server serves is a Pipelex API extension: `/resolve` + `/codegen`, `/pipe-io`, `/build/*`, and `/lint` + `/format`. Watch `/resolve` and `/codegen` in particular: they *look* protocol-shaped (they speak the `/validate` verdict discipline, and the crate `/resolve` emits is genuinely standard-owned — the MTHDS Library Crate Format, so its wire fields stay brand-neutral), but the routes are ours and the standard specifies no type projection at all. `tests/unit/test_openapi_contract.py` pins the tagged set exactly, in both directions.
+
+pipelex's own models ride this wire (the run result, the bundle blueprint, the validation error vocabulary), so a library change can move the artifact with no change to the server's code. `openapi-check` is part of `make agent-check` for that reason: regenerate with `make openapi-export` and read the diff, which states what the change did to the server's callers.
+
+## The vendored inference tree
+
+The image serves the models its `/root/.pipelex/inference/` tree declares, which is this member's `.pipelex/inference/`, and `make run` and the tests read the same tree. pipelex never falls back to the kit inside its own package once a config directory exists, so a kit change reaches the server only when this tree moves with it. `scripts/sync_vendored_kit.py` owns the tree: the kit's backend files, routing profiles, numbered deck files and manifests are mirrored byte for byte, while the `enabled` switches in `inference/backends.toml` and the `x_custom_*` deck overrides stay this server's own choice.
+
+**The tree stays committed and checked, rather than generated when the image is built.** A kit change is synced in the same change that makes it: the root `make up-kit-configs` (`ukc`), the step a kit change already takes, runs the sync here too, and `make kit-check`, part of `make agent-check`, fails a change that skipped it. Generating the tree at build time was rejected for two reasons. `make run` and the tests read the committed tree, so an image generating its own would serve something no local run had exercised. And the sync refuses when the kit ships an entry none of its rules covers, which only a person can resolve, so a build-time sync would fail at release time, long after the change that caused it. Because the manifests are mirrored rather than recomputed, a release's version bump moves nothing in the tree.
+
+## Commands
+
+```bash
+make install # Create api/.venv and install the server's dependencies, pipelex from the workspace included
+make run # Run the API with uvicorn (hot reload, no Docker)
+make fui # Fix unused imports
+make agent-check # install, fix-unused-imports, format, lint, pyright, mypy, openapi-check, kit-check (use this)
+make agent-test # install, then the unit tests — output only on failure (use this)
+make cleanderived # Remove compiled files, caches, logs — run when the pyright/mypy cache is stale
+make openapi-export # Regenerate the committed OpenAPI artifact
+make kit-sync # Re-sync the vendored .pipelex/inference/ tree from the kit (the root `make ukc` runs it too)
+make kit-check # Fail if that tree drifts from the kit (part of agent-check)
+make tp # Run unit tests with prints visible
+make test # Run unit tests (sequential)
+make gha-tests # Tests for GitHub Actions (no inference)
+make li # lock + install
+make docker-build # Build the image from local source, with the repository root as the build context
+make docker-run # Build + run in Docker on http://localhost:8081 (foreground)
+make docker-run-hub # Pull + run the published Docker Hub image (no local build); HUB_TAG=<tag> to pin
+make docker-stop # Force-stop the Docker container
+make docker-logs # Tail Docker container logs
+```
+
+**ALWAYS** run `make agent-check` after code changes (it supersedes `make fui && make c`).
+**ALWAYS** run `make agent-test` before committing to ensure tests pass (silent on success, output only on failure).
+
+---
+
+# Coding Standards
+
+## Python Version
+
+- **Python 3.11+** (requires-python = ">=3.11,<3.15")
+- Avoid Python 3.10 idioms that changed in 3.11+
+
+## Variable Naming
+
+- Minimum 3 characters for variable names (e.g., `exc`, `idx`, not `e`, `i`)
+- Exception: conventional unpacking like `_` for discarded values
+- Use `for key, value in ...` instead of `for key in dict.keys()`
+- Use `a = b or c` instead of `a = b if b else c`
+
+## Type Hints
+
+- **Always** type-annotate every function parameter and return value
+- Use lowercase generic types: `dict[]`, `list[]`, `tuple[]` (not `Dict`, `List`, `Tuple`)
+- Avoid `# type: ignore` -- use `cast()` or typed variables instead
+- Use `Annotated` for FastAPI dependencies
+
+## Imports
+
+- All imports at top of file, no inline imports
+- No re-exports in `__init__.py`
+- `TYPE_CHECKING` blocks must be last in the import section
+- Logging: `from pipelex import log`
+
+## Enums
+
+- Import `StrEnum` from the stdlib `enum`
+- Use `match/case` for enum comparisons, never test equality directly
+- Never add a default `case _:` in exhaustive match statements
+
+## Error Handling
+
+- Never catch generic `Exception`. Find the actual narrow exception types raised
+ by the code you're calling (read the source if needed) and catch those.
+- **Never** silence the `BLE001` lint rule with `# noqa: BLE001`. If `BLE001`
+ fires, the right answer is always to identify the real exception types and
+ narrow the `except`, not to suppress the warning.
+- Always chain exceptions: `raise NewError(msg) from exc`
+- Write the error message as a variable before raising
+- Convert third-party exceptions to domain-specific ones
+
+```python
+try:
+ result = some_operation()
+except SomeSpecificError as exc:
+ msg = "Descriptive message about what went wrong"
+ raise DomainError(msg) from exc
+```
+
+## Pydantic Models
+
+- Use Pydantic v2 standards
+- Use `Field(default_factory=...)` for mutable defaults (lists, dicts)
+- Keep models single-purpose and focused
+- Use `ConfigDict(extra="forbid")` when appropriate
+
+## Docstrings
+
+- Google-style docstrings when needed
+- Don't add docstrings to code you didn't write or change
+
+## Testing
+
+- **pytest-mock** only (never `unittest.mock`)
+- One `TestClass` per test module
+- Test files: `test_*.py` prefix
+- Test data in `test_data.py` files
+- Fixtures in `conftest.py` at appropriate hierarchy levels
+- Use `@pytest.mark.asyncio(loop_scope="class")` for async test classes
+- Use `@pytest.mark.parametrize` for multiple test cases
+- Strong asserts: test values, not just types
+
+---
+
+# FastAPI Coding Standards
+
+## Router Organization
+
+- One router per feature domain, tagged for OpenAPI: `APIRouter(tags=["pipeline"])`
+- Routers composed hierarchically in `routes/__init__.py`
+- Auth applied at router level via `dependencies=[Depends(auth_dependency)]`
+- Health check endpoint excluded from auth
+
+## Endpoints
+
+- All endpoints are `async`
+- Always declare `response_model` on endpoints
+- Use `Annotated[T, Depends(...)]` for dependency injection
+- Return `JSONResponse` with `model_dump(mode="json", serialize_as_any=True, by_alias=True)` for complex responses
+
+```python
[email protected]("/execute", response_model=PipelexRunResult)
+async def execute(
+ run_request: Annotated[RunRequest, Depends(request_deserialization)],
+) -> PipelexRunResult: ...
+```
+
+## Error Responses
+
+Every error is rendered as RFC 7807 `application/problem+json` by the global handlers in `pipelex_api/exception_handlers.py`. **Route handlers do not shape errors themselves** — they call into pipelex and let exceptions propagate. The wire contract is documented at `docs/error-responses.md`.
+
+- **Domain errors** (pipelex `PipelexError` subclasses) — raise from your code and let them propagate. The `PipelexError` global handler obtains an `ErrorReport` via `to_error_report()` and renders it into a problem document. Do not wrap, classify, or re-shape.
+- **API-authored 4xx/5xx** — use the helpers in `pipelex_api/errors.py`: `raise_validation_error`, `raise_bad_request`, `raise_forbidden`, `raise_unauthenticated`, `raise_payload_too_large`, `raise_internal_server_error`. Each raises an `ApiError` carrying a pre-built problem document; the global handler emits it. **Do not raise `HTTPException` directly** — FastAPI's default handler wraps the body as `{"detail": <whatever>}` and cannot emit a flat RFC 7807 document.
+- **Auth errors** — the helpers set `WWW-Authenticate: Bearer` automatically on 401.
+- **Logging** — the global handlers emit one structured record per error, carrying `event: "api_error"`, `route`, `error_type`, `error_domain`, `retryable`, `status`, and `user_id` / `pipe_code` / `pipeline_run_id` when the request bound them. `detail` rides the API-authored path only: a Pipelex `ErrorReport`'s body text has been through disclosure redaction, so it is not the cause and is deliberately not logged. They travel as `fields=` on the runtime's log call, never interpolated into the message, and `request_id` is not among them: `RequestIdMiddleware` binds it on the runtime's log context, so every record emitted under the request already carries it. The server selects the `json` sink, so a record reaches stderr as one JSON object per line — see `docs/logging.md`. Log disposition follows the final HTTP status: 4xx logs at `warning` (caller mistakes, the provider-429 passthrough, and API-level 4xx overrides like the 409 conflict); 5xx logs at `error` with traceback. Routes should not log error tracebacks themselves.
+- **Documenting a failure in OpenAPI** — the shared, typed `responses=` declarations live in `pipelex_api/openapi_responses.py` (`ProblemDocument` + one constant per status). Every auth-wrapped `/v1` route already documents `401`/`413`/`422`/`500` via the composite router's `responses=` (`pipelex_api/routes/__init__.py`); a route declares on its own decorator only the statuses **it alone** can produce. Never hand-write an error `content` block: `pipelex_api/openapi_schema.py` re-keys the generated schema onto `application/problem+json`, because FastAPI renders a response `model` under the route's response-class media type and offers no per-response override. Adding a new status means adding a constant there and referencing it — then `make openapi-export`.
+
+Typical route:
+
+```python
[email protected]("/start", response_model=PipelexStartAck, status_code=202)
+async def start(
+ request: Request,
+ run_request: Annotated[RunRequest, Depends(request_deserialization)],
+ user: Annotated[RequestUser | None, Depends(get_optional_user)],
+) -> PipelexStartAck:
+ # Let PipelexError / EnvVarNotFoundError / etc. propagate to the global handler.
+ # `request_id_of` (pipelex_api/middleware.py) reads back what RequestIdMiddleware put on the request.
+ return await api_runner.start(run_request, user=user, request_id=request_id_of(request))
+```
+
+For an API-authored failure that has no `PipelexError`:
+
+```python
+if upload_size > MAX_UPLOAD_BYTES:
+ raise_payload_too_large(message=f"Upload exceeds {MAX_UPLOAD_BYTES} bytes.")
+```
+
+## Request/Response Models
+
+- Define in `pipelex_api/schemas/models.py`
+- Use `Field(...)` with `description` for required fields
+- Use descriptive field names
+
+## Authentication
+
+- Three modes via `AUTH_MODE` env var: `none` (default), `jwt`, `api_key`
+- `none`: No auth (self-hosted default, or behind API Gateway in hosted version)
+- `jwt`: Validate `Authorization: Bearer <jwt>` using `JWT_SECRET_KEY`
+- `api_key`: Validate `Authorization: Bearer <key>` against `API_KEY` env var
+- Selection is environment-based via `get_auth_dependency()`
+- Bearer token format for jwt and api_key modes
+
+## Middleware
+
+- CORS configured in `main.py` (permissive for all origins)
+- No custom middleware -- keep it simple
+
+## Pipelex Integration
+
+- App initializes with `Pipelex.make(IntegrationMode.FASTAPI)`
+- Use `ApiRunner` (extends `PipelexMTHDSProtocol`) for pipeline execution
+- Services are instantiated per-request, not as singletons
diff --git a/api/Dockerfile b/api/Dockerfile
new file mode 100644
index 000000000..d33b6bdab
--- /dev/null
+++ b/api/Dockerfile
@@ -0,0 +1,77 @@
+# The build context is the repository root, not this directory:
+#
+# docker build -f api/Dockerfile . (what `make -C api docker-build` runs)
+#
+# The server is a member of the uv workspace rooted there, and it installs pipelex from the same
+# commit rather than from PyPI, so the image cannot run a pipelex other than the one it was released
+# with. The root `.dockerignore` keeps that context down to the files this build reads.
+
+# ─── builder: the virtual environment, built from the workspace lock ──────────
+FROM python:3.11-slim AS builder
+
+RUN apt-get update \
+ && apt-get install -y --no-install-recommends build-essential \
+ && rm -rf /var/lib/apt/lists/*
+
+RUN pip install --no-cache-dir uv
+
+WORKDIR /app
+
+# The lock and the two projects' metadata first, so the layer holding the third-party dependencies
+# is cached across source changes. `--package pipelex-api` installs the server's dependency set:
+# pipelex with the extras the server's pyproject.toml names, and `cli` deliberately not among them,
+# because the server selects the `json` log sink and a Rich-free pretty-print mode, so nothing it does
+# on a request renders a terminal. (Rich itself is still installed — typer and instructor both
+# require it unconditionally — it is simply never reached.)
+COPY pyproject.toml uv.lock README.md LICENSE ./
+COPY api/pyproject.toml api/README.md api/LICENSE api/
+RUN uv sync --frozen --no-dev --package pipelex-api --no-install-workspace
+
+# Then the two packages themselves, built as wheels rather than linked to the source tree, so the
+# image runs what the published `pipelex` and `pipelex-api` distributions contain. hatchling leaves
+# out of a wheel what the project's `.gitignore` ignores, so those come first: without them, a local
+# build would ship whatever ignored files lie in the working tree.
+COPY .gitignore ./
+COPY api/.gitignore api/
+COPY pipelex/ pipelex/
+COPY api/pipelex_api/ api/pipelex_api/
+RUN uv sync --frozen --no-dev --package pipelex-api --no-editable
+
+# ─── runtime ──────────────────────────────────────────────────────────────────
+FROM python:3.11-slim
+
+# curl serves the HEALTHCHECK below, and git is what pipelex runs to fetch a method by its address
+# (`method_ref` on the run and validate routes).
+RUN apt-get update \
+ && apt-get install -y --no-install-recommends curl git \
+ && rm -rf /var/lib/apt/lists/*
+
+WORKDIR /app
+
+COPY --from=builder /app/.venv /app/.venv
+ENV PATH="/app/.venv/bin:${PATH}"
+
+# ─── Pipelex global config (terms acceptance, backends) ────────────────────────
+# The server's bundled config becomes ~/.pipelex (the global config dir), and no project-level
+# .pipelex exists in the image, so users mounting overrides into /root/.pipelex aren't shadowed.
+# See api/docs/configuration.md.
+COPY api/.pipelex/ /root/.pipelex/
+
+# ─── runtime config ────────────────────────────────────────────────────────────
+# Note: container runs as root. Relocating the bundled `.pipelex/` to a
+# non-root user's $HOME is planned for the next minor release — coupling that
+# with the documented mount path at `/root/.pipelex` would be a breaking
+# change for current deployments.
+
+LABEL org.opencontainers.image.title="pipelex-api" \
+ org.opencontainers.image.description="Official Pipelex REST API server" \
+ org.opencontainers.image.source="https://github.com/Pipelex/pipelex" \
+ org.opencontainers.image.licenses="Elastic-2.0" \
+ org.opencontainers.image.vendor="Evotis S.A.S."
+
+EXPOSE 8081
+
+HEALTHCHECK --interval=30s --timeout=5s --start-period=15s --retries=3 \
+ CMD curl -fsS http://127.0.0.1:8081/health || exit 1
+
+CMD ["uvicorn", "pipelex_api.main:app", "--host", "0.0.0.0", "--port", "8081"]
diff --git a/api/LICENSE b/api/LICENSE
new file mode 100644
index 000000000..455bf8ae6
--- /dev/null
+++ b/api/LICENSE
@@ -0,0 +1,95 @@
+Copyright (c) 2025-2026 Evotis S.A.S.
+
+Elastic License 2.0
+
+URL: https://www.elastic.co/licensing/elastic-license
+
+## Acceptance
+
+By using the software, you agree to all of the terms and conditions below.
+
+## Copyright License
+
+The licensor grants you a non-exclusive, royalty-free, worldwide,
+non-sublicensable, non-transferable license to use, copy, distribute, make
+available, and prepare derivative works of the software, in each case subject to
+the limitations and conditions below.
+
+## Limitations
+
+You may not provide the software to third parties as a hosted or managed
+service, where the service provides users with access to any substantial set of
+the features or functionality of the software.
+
+You may not move, change, disable, or circumvent the license key functionality
+in the software, and you may not remove or obscure any functionality in the
+software that is protected by the license key.
+
+You may not alter, remove, or obscure any licensing, copyright, or other notices
+of the licensor in the software. Any use of the licensor’s trademarks is subject
+to applicable law.
+
+## Patents
+
+The licensor grants you a license, under any patent claims the licensor can
+license, or becomes able to license, to make, have made, use, sell, offer for
+sale, import and have imported the software, in each case subject to the
+limitations and conditions in this license. This license does not cover any
+patent claims that you cause to be infringed by modifications or additions to
+the software. If you or your company make any written claim that the software
+infringes or contributes to infringement of any patent, your patent license for
+the software granted under these terms ends immediately. If your company makes
+such a claim, your patent license ends immediately for work on behalf of your
+company.
+
+## Notices
+
+You must ensure that anyone who gets a copy of any part of the software from you
+also gets a copy of these terms.
+
+If you modify the software, you must include in any modified copies of the
+software prominent notices stating that you have modified the software.
+
+## No Other Rights
+
+These terms do not imply any licenses other than those expressly granted in
+these terms.
+
+## Termination
+
+If you use the software in violation of these terms, such use is not licensed,
+and your licenses will automatically terminate. If the licensor provides you
+with a notice of your violation, and you cease all violation of this license no
+later than 30 days after you receive that notice, your licenses will be
+reinstated retroactively. However, if you violate these terms after such
+reinstatement, any additional violation of these terms will cause your licenses
+to terminate automatically and permanently.
+
+## No Liability
+
+*As far as the law allows, the software comes as is, without any warranty or
+condition, and the licensor will not be liable to you for any damages arising
+out of these terms or the use or nature of the software, under any kind of
+legal claim.*
+
+## Definitions
+
+The **licensor** is the entity offering these terms, and the **software** is the
+software the licensor makes available under these terms, including any portion
+of it.
+
+**you** refers to the individual or entity agreeing to these terms.
+
+**your company** is any legal entity, sole proprietorship, or other kind of
+organization that you work for, plus all organizations that have control over,
+are under the control of, or are under common control with that
+organization. **control** means ownership of substantially all the assets of an
+entity, or the power to direct its management and policies by vote, contract, or
+otherwise. Control can be direct or indirect.
+
+**your licenses** are all the licenses granted to you for the software under
+these terms.
+
+**use** means anything you do with the software requiring one of your licenses.
+
+**trademark** means trademarks, service marks, and similar rights.
diff --git a/api/Makefile b/api/Makefile
new file mode 100644
index 000000000..b5a40b56c
--- /dev/null
+++ b/api/Makefile
@@ -0,0 +1,50 @@
+#################################################################################
+################################# HELPERS #################################
+#################################################################################
+
+# Print title for each section
+PRINT_TITLE = @echo "\n\033[1m>>> $1\033[0m\n"
+
+# Colorized variables
+YELLOW = \033[33m
+GREEN = \033[32m
+RESET = \033[0m
+
+# Unified help output
+help:
+ @echo "$(YELLOW)Available commands:$(RESET)"
+ @echo ""
+ @echo "$$HELP"
+ @echo ""
+ @echo "$$HELP_LOCAL"
+ @echo ""
+ @echo "$$HELP_DEPLOY_API"
+ @echo ""
+ @echo "$(YELLOW)Use 'make <command>' to run a specific command.$(RESET)"
+
+###########################################################################
+############################## Initialization #############################
+###########################################################################
+
+# Include the secrets of the .env file
+ifneq (,$(wildcard .env))
+ include .env
+ export $(shell sed 's/=.*//' .env)
+endif
+
+# The server takes the library's version, from the root `pyproject.toml` (see this member's `[tool.hatch.version]`).
+$(eval VERSION=$(shell grep -m1 '^version' ../pyproject.toml | sed -E 's/version = "(.*)"/\1/'))
+
+check-version-format:
+ @echo "Checking version format: $(VERSION)"
+ @if ! echo "$(VERSION)" | grep -Eq '^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$$'; then \
+ echo "Error: Version $(VERSION) is not in the correct format (x.y.z where x, y, z are non-negative integers)."; \
+ exit 1; \
+ else \
+ echo "Version $(VERSION) is valid."; \
+ fi
+
+
+-include Makefiles/Makefile_basics.mk
+-include Makefiles/Makefile.local.mk
+-include Makefiles/Makefile.deploy.api.mk
\ No newline at end of file
diff --git a/api/Makefiles/Makefile.deploy.api.mk b/api/Makefiles/Makefile.deploy.api.mk
new file mode 100644
index 000000000..86c610c4b
--- /dev/null
+++ b/api/Makefiles/Makefile.deploy.api.mk
@@ -0,0 +1,39 @@
+#################################################################################
+################################# HELPERS #################################
+#################################################################################
+
+define HELP_DEPLOY_API
+ $(GREEN)Deployment Commands:$(RESET)
+ make deploy-docker-hub - Deploy the image to Docker Hub.
+endef
+export HELP_DEPLOY_API
+
+###########################################################################
+############################ Docker Hub Deploy ############################
+###########################################################################
+
+# Builds the public Pipelex API image and publishes it to Docker Hub as
+# pipelex/pipelex-api:$(VERSION) and :latest, with the repository root as the
+# build context (see the Dockerfile's header). $(VERSION) is the library's
+# version, read from the root pyproject.toml. No workflow runs this target yet:
+# publishing the image from pipelex's release is still to be wired, so until
+# then a release does not push an image. This repo only publishes to Docker
+# Hub — anything beyond (private registries, ECR/ACR/GCR, ECS/k8s deploys) is
+# the user's responsibility, typically in a separate infra repo.
+.PHONY: deploy-docker-hub
+deploy-docker-hub:
+ @echo "\n########################### Docker Hub Build ##########################"
+ @echo "Logging in to Docker Hub..."
+ @echo "$(DOCKER_HUB_TOKEN)" | docker login --username pipelex --password-stdin
+
+ @echo "Building Docker image for Docker Hub..."
+ docker build --platform linux/amd64 -f $(CURDIR)/Dockerfile -t pipelex-api:$(VERSION) $(WORKSPACE_ROOT)
+ docker tag pipelex-api:$(VERSION) pipelex/pipelex-api:$(VERSION)
+ docker tag pipelex-api:$(VERSION) pipelex/pipelex-api:latest
+
+ @echo "Pushing to Docker Hub..."
+ docker push pipelex/pipelex-api:$(VERSION)
+ docker push pipelex/pipelex-api:latest
+
+ @echo "✓ Built and pushed image pipelex-api:$(VERSION) and latest to Docker Hub"
+ @echo "✓ Image available at: https://hub.docker.com/r/pipelex/pipelex-api"
diff --git a/api/Makefiles/Makefile.local.mk b/api/Makefiles/Makefile.local.mk
new file mode 100644
index 000000000..b8e581e1d
--- /dev/null
+++ b/api/Makefiles/Makefile.local.mk
@@ -0,0 +1,233 @@
+#################################################################################
+################################# HELPERS #################################
+#################################################################################
+
+LOCAL_IMAGE := pipelex-api:local
+HUB_IMAGE_NAME := pipelex/pipelex-api
+HUB_TAG ?= latest
+HUB_IMAGE := $(HUB_IMAGE_NAME):$(HUB_TAG)
+ENV_FILE ?= .env
+CONTAINER_NAME ?= pipelex-api
+
+define HELP_LOCAL
+ $(GREEN)Run the API locally — two ways:$(RESET)
+
+ $(YELLOW)Native (uvicorn, hot reload — fastest dev loop):$(RESET)
+ make run$(RESET): Run the API with uvicorn against the pipelex of this repository (requires `make install` first).
+
+ $(YELLOW)Docker (closest to what's deployed):$(RESET)
+ make docker-build$(RESET): Build the API image from local source, with the repository root as the build context.
+ make docker-run$(RESET): Build + run the image on http://localhost:8081 (foreground, Ctrl+C to stop).
+ make docker-run-hub$(RESET): Pull + run the PUBLISHED Docker Hub image (no local build). Tag: make docker-run-hub HUB_TAG=0.5.0
+ make docker-stop$(RESET): Force-stop the Docker container.
+ make docker-logs$(RESET): Tail Docker container logs.
+
+ $(YELLOW)Local Temporal dev server (when TEMPORAL is enabled in config):$(RESET)
+ make temporal-server$(RESET) ($(GREEN)ts$(RESET)): Start a local Temporal dev server (:7233, UI :8233) WITH search attributes registered.
+ make temporal-server-bare$(RESET) ($(GREEN)ts-bare$(RESET)): Start it WITHOUT search attributes (reproduce the missing-attribute error).
+ make temporal-stop$(RESET) ($(GREEN)tstop$(RESET)): Stop the local Temporal dev server.
+
+ $(YELLOW)Send an MTHDS bundle through the API (resolves like `pipelex run bundle`):$(RESET)
+ make bundle-run$(RESET) BUNDLE=<dir|.mthds>: POST the bundle to a running API and print the response (start `make run` first).
+ make bundle-validate$(RESET) BUNDLE=<dir|.mthds>: Dry-run validate the bundle via /v1/validate — no pipe_code/inputs, no inference, no cost.
+ make bundle-resolve$(RESET) BUNDLE=<dir|.mthds>: Resolve the bundle to its normalized crate via /v1/resolve — no inference, no cost.
+ make bundle-codegen$(RESET) BUNDLE=<dir|.mthds> TARGET=<t>: Project typed artifacts + codegen.lock via /v1/codegen (ts-zod|python-pydantic|python-structures).
+ make bundle-curl$(RESET) BUNDLE=<dir|.mthds>: Emit a ready-to-run curl command for the bundle.
+ make bundle-postman$(RESET) BUNDLE=<dir|.mthds>: Push request(s) into the live Pipelex FastAPI Postman collection.
+ make bundle-dry$(RESET) BUNDLE=<dir|.mthds>: Print the request body only — touch nothing.
+ Optional: ENDPOINT=execute|start|validate|resolve|codegen|build-inputs|build-output|build-runner|both
+ PIPE=<code> INPUTS=<path> NAME=<folder> ALLOW_SIGNATURES=1 TARGET=<codegen target> OUTPUT_FORMAT=schema|json|python
+ CALLBACK_URL=<url> BASE_URL=<url> TOKEN=<bearer> ARGS=<extra>
+ (the async start endpoint needs CALLBACK_URL — set it here, or via CALLBACK_URL in .env)
+
+endef
+export HELP_LOCAL
+
+.PHONY: docker-build docker-run docker-run-hub docker-stop docker-logs
+.PHONY: temporal-server ts temporal-server-bare ts-bare tsb temporal-stop tstop
+.PHONY: check-bundle-arg bundle-run bundle-validate bundle-resolve bundle-codegen bundle-curl bundle-postman bundle-dry
+
+#################################################################################
+################################# API #################################
+#################################################################################
+
+# Build the generic pipelex-api image from local source. The build context is the repository root,
+# because the image installs pipelex from the same commit as the server (see the Dockerfile's header).
+docker-build:
+ @echo "\n=== Build $(LOCAL_IMAGE) from local source ==="
+ docker build --platform linux/amd64 -f $(CURDIR)/Dockerfile -t $(LOCAL_IMAGE) $(WORKSPACE_ROOT)
+
+# Run the API on http://localhost:8081, foreground. Reads all env from .env.
+# Required: PIPELEX_GATEWAY_API_KEY (only if you use the default routing profile).
+# Optional: AUTH_MODE, API_KEY, JWT_SECRET_KEY (see .env.example).
+docker-run: docker-build
+ @docker rm -f $(CONTAINER_NAME) 2>/dev/null || true
+ @test -f $(ENV_FILE) || (echo "ERROR: $(ENV_FILE) not found. Copy .env.example to .env and fill it in." && exit 1)
+ @echo "\n=== Run $(LOCAL_IMAGE) on http://localhost:8081 — Ctrl+C to stop ==="
+ docker run --rm --name $(CONTAINER_NAME) -p 8081:8081 \
+ --env-file $(ENV_FILE) \
+ $(LOCAL_IMAGE)
+
+# Pull and run the PUBLISHED image from Docker Hub — no local checkout/build needed.
+# Same env contract as docker-run (reads all env from .env).
+# Required: PIPELEX_GATEWAY_API_KEY (only if you use the default routing profile).
+# Optional: AUTH_MODE, API_KEY, JWT_SECRET_KEY (see .env.example).
+# Override the published tag with HUB_TAG, e.g. make docker-run-hub HUB_TAG=0.5.0
+docker-run-hub:
+ @docker rm -f $(CONTAINER_NAME) 2>/dev/null || true
+ @test -f $(ENV_FILE) || (echo "ERROR: $(ENV_FILE) not found. Copy .env.example to .env and fill it in." && exit 1)
+ @echo "\n=== Pull $(HUB_IMAGE) from Docker Hub ==="
+ docker pull $(HUB_IMAGE)
+ @echo "\n=== Run $(HUB_IMAGE) on http://localhost:8081 — Ctrl+C to stop ==="
+ docker run --rm --name $(CONTAINER_NAME) -p 8081:8081 \
+ --env-file $(ENV_FILE) \
+ $(HUB_IMAGE)
+
+docker-stop:
+ @docker rm -f $(CONTAINER_NAME) 2>/dev/null && echo "Stopped $(CONTAINER_NAME)" || echo "$(CONTAINER_NAME) was not running"
+
+docker-logs:
+ docker logs -f $(CONTAINER_NAME)
+
+#################################################################################
+################################# TEMPORAL #################################
+#################################################################################
+
+# Pipelex attaches these five custom Keyword search attributes to every workflow
+# start. A namespace missing them rejects StartWorkflow with "Namespace <ns> has
+# no mapping defined for search attribute ...". `temporal-server` pre-registers
+# them so /v1/execute and /v1/start work out of the box;
+# `temporal-server-bare` omits them so you can reproduce the missing-attribute
+# error (SearchAttributeRegistrationError). Keep in lockstep with
+# [temporal.search_attributes].attributes in the pipelex config.
+TEMPORAL_SEARCH_ATTRS := PipeCode PipelineRunId SessionId UserId DomainCode
+
+# Start a local Temporal dev server WITH the search attributes registered. Only
+# needed when the API runs with TEMPORAL enabled (selected_server pointed at the
+# local server). Runs in the foreground — start it in its own terminal.
+temporal-server:
+ @if ! command -v temporal >/dev/null 2>&1; then \
+ echo "ERROR: 'temporal' CLI not found. Install it with: brew install temporal"; \
+ exit 1; \
+ fi
+ @echo "• Temporal Web UI at http://localhost:8233"
+ @echo "• Temporal gRPC service at localhost:7233"
+ @echo "• Registering search attributes: $(TEMPORAL_SEARCH_ATTRS)"
+ @echo "• Press Ctrl+C to stop"
+ temporal server start-dev $(foreach attr,$(TEMPORAL_SEARCH_ATTRS),--search-attribute $(attr)=Keyword)
+
+ts: temporal-server
+
+# Start the dev server WITHOUT the search attributes, to reproduce the
+# missing-search-attribute error on /v1/execute and /v1/start.
+temporal-server-bare:
+ @if ! command -v temporal >/dev/null 2>&1; then \
+ echo "ERROR: 'temporal' CLI not found. Install it with: brew install temporal"; \
+ exit 1; \
+ fi
+ @echo "• Temporal Web UI at http://localhost:8233"
+ @echo "• Temporal gRPC service at localhost:7233"
+ @echo "• NO search attributes registered — workflow starts are rejected when [temporal.search_attributes].enabled = true (use this to test the error path)"
+ @echo "• Press Ctrl+C to stop"
+ temporal server start-dev
+
+ts-bare: temporal-server-bare
+tsb: temporal-server-bare
+
+# Stop the local Temporal dev server. Only kills processes on :7233 whose
+# command is the Temporal binary, so an unrelated service bound to that port
+# is left alone.
+temporal-stop:
+ @PIDS=$$(lsof -tiTCP:7233 -sTCP:LISTEN 2>/dev/null); \
+ if [ -z "$$PIDS" ]; then \
+ echo "• No process found on port 7233"; \
+ else \
+ for PID in $$PIDS; do \
+ CMD=$$(ps -p $$PID -o comm= 2>/dev/null); \
+ case "$$CMD" in \
+ *temporal*) kill $$PID && echo "• Killed Temporal server (PID $$PID)";; \
+ *) echo "• Skipped PID $$PID on :7233 — not a Temporal process ($$CMD)";; \
+ esac; \
+ done; \
+ fi
+
+tstop: temporal-stop
+
+#################################################################################
+########################## RUN A BUNDLE VIA THE API #########################
+#################################################################################
+
+# Resolve an MTHDS bundle the same way `pipelex run bundle <path>` does and send
+# it to the API as a request — run it directly, dry-run validate it, resolve it
+# to its normalized crate, project typed codegen artifacts, emit curl, push a
+# Postman query, or just print the body. Runs the skill's helper script with OUR
+# venv python.
+#
+# make bundle-run BUNDLE=../../pipelex-demos/mthds-wip/fashion_moodboard
+# make bundle-validate BUNDLE=../../pipelex-demos/mthds-wip/fashion_moodboard
+# make bundle-resolve BUNDLE=../../pipelex-demos/mthds-wip/fashion_moodboard
+# make bundle-codegen BUNDLE=../../pipelex-demos/mthds-wip/fashion_moodboard TARGET=ts-zod
+# make bundle-curl BUNDLE=../../pipelex-demos/mthds-wip/fashion_moodboard
+# make bundle-postman BUNDLE=../../pipelex-demos/mthds-wip/fashion_moodboard
+# make bundle-dry BUNDLE=../../pipelex-demos/mthds-wip/fashion_moodboard
+#
+# Only execute/start trigger inference. bundle-validate (/v1/validate),
+# bundle-resolve (/v1/resolve), and bundle-codegen (/v1/codegen) are free —
+# parse/load/dry-run only — so they hardcode --run. The build routes
+# (/v1/build/{inputs,output,runner}) ride the generic targets via ENDPOINT=,
+# e.g. `make bundle-run ENDPOINT=build-inputs` or
+# `make bundle-postman ENDPOINT=build-output OUTPUT_FORMAT=json`.
+#
+# Optional pass-throughs: ENDPOINT, PIPE, INPUTS, NAME, ALLOW_SIGNATURES,
+# TARGET (codegen only — required), OUTPUT_FORMAT (build-output only),
+# RENDER (validate only — e.g. RENDER=markdown reproduces a skill-driven
+# validate, response carries rendered_markdown), CALLBACK_URL (all modes);
+# BASE_URL, TOKEN (run/curl); ARGS for anything else.
+# The async start endpoint requires CALLBACK_URL — pass it here, or set
+# CALLBACK_URL in .env (make exports it to the script). bundle-postman needs
+# POSTMAN_API_KEY in the environment (it lives in ~/.zshenv, so any zsh-launched
+# make has it).
+BUNDLE_SCRIPT := .claude/skills/postman-bundle/scripts/build_postman_query.py
+BUNDLE_OPTS = $(if $(ENDPOINT),--endpoint $(ENDPOINT)) $(if $(PIPE),--pipe $(PIPE)) $(if $(INPUTS),--inputs $(INPUTS)) $(if $(NAME),--name $(NAME)) $(if $(ALLOW_SIGNATURES),--allow-signatures) $(if $(TARGET),--target $(TARGET)) $(if $(OUTPUT_FORMAT),--output-format $(OUTPUT_FORMAT)) $(if $(RENDER),--render $(RENDER)) $(if $(CALLBACK_URL),--callback-url '$(CALLBACK_URL)') $(ARGS)
+BUNDLE_RUN_OPTS = $(if $(BASE_URL),--base-url $(BASE_URL)) $(if $(TOKEN),--token $(TOKEN))
+
+check-bundle-arg:
+ @test -n "$(BUNDLE)" || { echo "ERROR: set BUNDLE=<bundle dir or .mthds file>, e.g. make bundle-run BUNDLE=../../pipelex-demos/mthds-wip/fashion_moodboard"; exit 1; }
+
+bundle-run: env check-bundle-arg
+ $(call PRINT_TITLE,"Running bundle against the API")
+ $(VENV_PYTHON) $(BUNDLE_SCRIPT) $(BUNDLE) --run $(BUNDLE_RUN_OPTS) $(BUNDLE_OPTS)
+
+# Dry-run validate via /v1/validate — hardcodes --endpoint validate (so don't
+# pass ENDPOINT here). NAME/ALLOW_SIGNATURES/RENDER/BASE_URL/TOKEN/ARGS still
+# apply (RENDER=markdown reproduces a skill-driven validate); PIPE/INPUTS are
+# intentionally omitted — the validate endpoint ignores them.
+bundle-validate: env check-bundle-arg
+ $(call PRINT_TITLE,"Validating bundle via the API - dry-run with no inference")
+ $(VENV_PYTHON) $(BUNDLE_SCRIPT) $(BUNDLE) --run --endpoint validate $(if $(ALLOW_SIGNATURES),--allow-signatures) $(if $(RENDER),--render $(RENDER)) $(if $(NAME),--name $(NAME)) $(BUNDLE_RUN_OPTS) $(ARGS)
+
+# Resolve the bundle's closure to its normalized library crate via /v1/resolve —
+# no inference, no dry-run sweep, no cost. PIPE/INPUTS are intentionally
+# omitted — the crate routes take neither.
+bundle-resolve: env check-bundle-arg
+ $(call PRINT_TITLE,"Resolving bundle to its normalized crate via the API")
+ $(VENV_PYTHON) $(BUNDLE_SCRIPT) $(BUNDLE) --run --endpoint resolve $(if $(NAME),--name $(NAME)) $(BUNDLE_RUN_OPTS) $(ARGS)
+
+# Project typed artifacts + codegen.lock via /v1/codegen — no inference, no
+# cost. TARGET is required: ts-zod | python-pydantic | python-structures.
+bundle-codegen: env check-bundle-arg
+ @test -n "$(TARGET)" || { echo "ERROR: set TARGET=<ts-zod|python-pydantic|python-structures>, e.g. make bundle-codegen BUNDLE=... TARGET=ts-zod"; exit 1; }
+ $(call PRINT_TITLE,"Generating typed artifacts via the API codegen route")
+ $(VENV_PYTHON) $(BUNDLE_SCRIPT) $(BUNDLE) --run --endpoint codegen --target $(TARGET) $(if $(NAME),--name $(NAME)) $(BUNDLE_RUN_OPTS) $(ARGS)
+
+bundle-curl: env check-bundle-arg
+ $(call PRINT_TITLE,"Emitting curl for bundle")
+ $(VENV_PYTHON) $(BUNDLE_SCRIPT) $(BUNDLE) --curl $(BUNDLE_RUN_OPTS) $(BUNDLE_OPTS)
+
+bundle-postman: env check-bundle-arg
+ $(call PRINT_TITLE,"Pushing Postman query for bundle")
+ $(VENV_PYTHON) $(BUNDLE_SCRIPT) $(BUNDLE) $(BUNDLE_OPTS)
+
+bundle-dry: env check-bundle-arg
+ $(call PRINT_TITLE,"Bundle request body - dry run only")
+ $(VENV_PYTHON) $(BUNDLE_SCRIPT) $(BUNDLE) --dry-run $(BUNDLE_OPTS)
diff --git a/api/Makefiles/Makefile_basics.mk b/api/Makefiles/Makefile_basics.mk
new file mode 100644
index 000000000..e25f701fc
--- /dev/null
+++ b/api/Makefiles/Makefile_basics.mk
@@ -0,0 +1,489 @@
+ifeq ($(wildcard .env),.env)
+include .env
+export
+endif
+VIRTUAL_ENV := $(CURDIR)/.venv
+PROJECT_NAME := $(shell grep '^name = ' pyproject.toml | sed -E 's/name = "(.*)"/\1/')
+
+# This directory is a member of the uv workspace rooted at the repository root, which holds the one
+# `uv.lock`. uv would sync a member into the workspace root's `.venv`, pipelex's own environment, so
+# every uv command here is pointed at this member's own `.venv` instead: the server is tested with
+# exactly the dependencies it declares (pipelex with the server's extras, and without `cli`), and
+# pipelex is installed from the workspace in editable mode, so an edit to the library reaches this
+# environment without a reinstall.
+export UV_PROJECT_ENVIRONMENT := $(VIRTUAL_ENV)
+WORKSPACE_ROOT := $(abspath $(CURDIR)/..)
+
+# The "?" is used to make the variable optional, so that it can be overridden by the user.
+PYTHON_VERSION ?= 3.13
+VENV_PYTHON := $(VIRTUAL_ENV)/bin/python
+VENV_PYTEST := $(VIRTUAL_ENV)/bin/pytest
+VENV_RUFF := $(VIRTUAL_ENV)/bin/ruff
+VENV_PYRIGHT := $(VIRTUAL_ENV)/bin/pyright
+VENV_MYPY := $(VIRTUAL_ENV)/bin/mypy
+VENV_PIPELEX := $(VIRTUAL_ENV)/bin/pipelex
+VENV_MKDOCS := $(VIRTUAL_ENV)/bin/mkdocs
+VENV_PYLINT := $(VIRTUAL_ENV)/bin/pylint
+
+UV_MIN_VERSION = $(shell grep -m1 'required-version' $(WORKSPACE_ROOT)/pyproject.toml | sed -E 's/.*= *"([^<>=, ]+).*/\1/')
+
+USUAL_PYTEST_MARKERS := "(dry_runnable or not (inference or llm or img_gen or ocr)) and not (needs_output or pipelex_api)"
+
+define PRINT_TITLE
+ $(eval PROJECT_PART := [$(PROJECT_NAME)])
+ $(eval TARGET_PART := ($@))
+ $(eval MESSAGE_PART := $(1))
+ $(if $(MESSAGE_PART),\
+ $(eval FULL_TITLE := === $(PROJECT_PART) ===== $(TARGET_PART) ====== $(MESSAGE_PART) ),\
+ $(eval FULL_TITLE := === $(PROJECT_PART) ===== $(TARGET_PART) ====== )\
+ )
+ $(eval TITLE_LENGTH := $(shell echo -n "$(FULL_TITLE)" | wc -c | tr -d ' '))
+ $(eval PADDING_LENGTH := $(shell echo $$((126 - $(TITLE_LENGTH)))))
+ $(eval PADDING := $(shell printf '%*s' $(PADDING_LENGTH) '' | tr ' ' '='))
+ $(eval PADDED_TITLE := $(FULL_TITLE)$(PADDING))
+ @echo ""
+ @echo "$(PADDED_TITLE)"
+endef
+
+define HELP
+Manage $(PROJECT_NAME) located in $(CURDIR).
+Usage:
+
+make env - Create python virtual env
+make lock - Refresh the workspace uv.lock (at the repository root) without updating anything
+make install - Create local virtualenv & install all dependencies
+make build - Build the pipelex-api wheel and sdist
+
+make format - format with ruff format
+make lint - lint with ruff check
+make pyright - Check types with pyright
+make mypy - Check types with mypy
+
+make cleanenv - Remove virtual env and lock files
+make cleanderived - Remove extraneous compiled files, caches, logs, etc.
+make cleanall - Remove all -> cleanenv + cleanderived
+
+make merge-check-ruff-lint - Run ruff merge check without updating files
+make merge-check-ruff-format - Run ruff merge check without updating files
+make merge-check-mypy - Run mypy merge check without updating files
+make merge-check-pyright - Run pyright merge check without updating files
+
+make codex-tests - Run tests for Codex (exit on first failure) (no inference, no codex_disabled)
+make gha-tests - Run tests for github actions (exit on first failure) (no inference, no gha_disabled)
+make test - Run unit tests (no inference)
+make test-xdist - Run unit tests with xdist (no inference)
+make t - Shorthand -> test-xdist
+make test-quiet - Run unit tests without prints (no inference)
+make tq - Shorthand -> test-quiet
+make test-with-prints - Run tests with prints (no inference)
+make tp - Shorthand -> test-with-prints
+make test-inference - Run unit tests only for inference (with prints)
+make ti - Shorthand -> test-inference
+make tip - Shorthand -> test-inference-with-prints (parallelized inference tests)
+make test-ocr - Run unit tests only for ocr (with prints)
+make to - Shorthand -> test-ocr
+make test-img-gen - Run unit tests only for img_gen (with prints)
+make test-g - Shorthand -> test-img-gen
+
+make check-unused-imports - Check for unused imports without fixing
+make fix-unused-imports - Fix unused imports with ruff
+make fui - Shorthand -> fix-unused-imports
+make check-TODOs - Check for TODOs
+
+make docs - Serve documentation locally with mkdocs
+make docs-check - Check documentation build with mkdocs
+
+make openapi-export - Export the FastAPI OpenAPI schema to docs/openapi/pipelex-api.openapi.yaml
+make openapi-check - Fail if the committed OpenAPI artifact drifts from the app
+
+make kit-sync - Re-sync the vendored .pipelex/inference/ tree from the pipelex kit of this repository
+make kit-check - Fail if the vendored .pipelex/inference/ tree drifts from the pipelex kit of this repository
+
+make agent-check - Install, then fix-unused-imports format lint pyright mypy openapi-check kit-check (for AI agents)
+make agent-test - Install, then run unit tests, silent on success, output on failure (for AI agents)
+
+make check - Shorthand -> format lint mypy
+make c - Shorthand -> check
+make cc - Shorthand -> cleanderived check
+make li - Shorthand -> lock install
+
+endef
+export HELP
+
+.PHONY: \
+ all help env lock install build \
+ format lint pyright mypy pylint \
+ cleanderived cleanenv cleanall \
+ agent-check agent-test \
+ test test-xdist t test-quiet tq test-with-prints tp test-inference ti \
+ test-img-gen tg test-ocr to codex-tests gha-tests \
+ run-all-tests run-manual-trigger-gha-tests run-gha_disabled-tests \
+ check c cc \
+ merge-check-ruff-lint merge-check-ruff-format merge-check-mypy merge-check-pyright \
+ li check-unused-imports fix-unused-imports check-uv check-TODOs docs docs-check \
+ openapi-export openapi-check \
+ kit-sync kit-check \
+ test-count check-test-badge
+
+# `help` is owned by the root Makefile, which composes this $$HELP block with
+# $$HELP_LOCAL and $$HELP_DEPLOY_API. Defining `help` here too (this file is
+# `-include`d after the root target) would override it and hide those sections —
+# so this rule binds only `all`.
+all:
+ @echo "$$HELP"
+
+
+##########################################################################################
+### SETUP
+##########################################################################################
+
+check-uv:
+ $(call PRINT_TITLE,"Ensuring uv ≥ $(UV_MIN_VERSION)")
+ @command -v uv >/dev/null 2>&1 || { \
+ echo "uv not found – installing latest …"; \
+ curl -LsSf https://astral.sh/uv/install.sh | sh; \
+ }
+ @uv self update >/dev/null 2>&1 || true
+
+
+env: check-uv
+ $(call PRINT_TITLE,"Creating virtual environment")
+ @if [ ! -d $(VIRTUAL_ENV) ]; then \
+ echo "Creating Python virtual env in \`${VIRTUAL_ENV}\`"; \
+ uv venv $(VIRTUAL_ENV) --python $(PYTHON_VERSION); \
+ else \
+ echo "Python virtual env already exists in \`${VIRTUAL_ENV}\`"; \
+ fi
+ @echo "Using Python: $$($(VENV_PYTHON) --version) from $$(which $$(readlink -f $(VENV_PYTHON)))"
+
+# `uv sync` from this directory syncs this member (pipelex-api) with all of its own extras, and
+# pipelex with the extras the member's dependency names; upgrading dependencies is done for the whole
+# workspace from the repository root.
+install: env
+ $(call PRINT_TITLE,"Installing dependencies")
+ @uv sync --all-extras && \
+ echo "Installed pipelex-api dependencies in ${VIRTUAL_ENV} with all extras.";
+
+lock: env
+ $(call PRINT_TITLE,"Resolving dependencies without update")
+ @uv lock && \
+ echo uv lock without update;
+
+build: env
+ $(call PRINT_TITLE,"Building the pipelex-api wheel and sdist")
+ @uv build --package pipelex-api
+
+##############################################################################################
+############################ Cleaning ############################
+##############################################################################################
+
+cleanderived:
+ $(call PRINT_TITLE,"Erasing derived files and directories")
+ @find . -name '.coverage' -delete && \
+ find . -wholename '**/*.pyc' -delete && \
+ find . -type d -wholename '__pycache__' -exec rm -rf {} + && \
+ find . -type d -wholename './.cache' -exec rm -rf {} + && \
+ find . -type d -wholename './.mypy_cache' -exec rm -rf {} + && \
+ find . -type d -wholename './.ruff_cache' -exec rm -rf {} + && \
+ find . -type d -wholename '.pytest_cache' -exec rm -rf {} + && \
+ find . -type d -wholename '**/.pytest_cache' -exec rm -rf {} + && \
+ find . -type d -wholename './logs/*.log' -exec rm -rf {} + && \
+ find . -type d -wholename './.reports/*' -exec rm -rf {} + && \
+ echo "Cleaned up derived files and directories";
+
+cleanenv:
+ $(call PRINT_TITLE,"Erasing virtual environment")
+ rm -rf "$(VIRTUAL_ENV)" && \
+ echo "Cleaned up virtual env";
+
+cleanall: cleanderived cleanenv
+ @echo "Cleaned up all derived files and directories";
+
+##########################################################################################
+### TESTING
+##########################################################################################
+
+codex-tests: env
+ $(call PRINT_TITLE,"Unit testing for Codex")
+ @echo "• Running unit tests for Codex (excluding inference and codex_disabled)"
+ $(VENV_PYTEST) --exitfirst --disable-inference -m "(dry_runnable or not inference) and not (needs_output or pipelex_api or codex_disabled)" || [ $$? = 5 ]
+
+gha-tests: env
+ $(call PRINT_TITLE,"Unit testing for github actions")
+ @echo "• Running unit tests for github actions (excluding inference and gha_disabled)"
+ $(VENV_PYTEST) --exitfirst --quiet --disable-inference -m "(dry_runnable or not inference) and not (gha_disabled or pipelex_api)" || [ $$? = 5 ]
+
+run-all-tests: env
+ $(call PRINT_TITLE,"Running all unit tests")
+ @echo "• Running all unit tests"
+ $(VENV_PYTEST) -n auto --exitfirst --quiet
+
+run-manual-trigger-gha-tests: env
+ $(call PRINT_TITLE,"Running GHA tests")
+ @echo "• Running GHA unit tests for inference, llm, and not gha_disabled"
+ $(VENV_PYTEST) --exitfirst --quiet -m "not (gha_disabled or pipelex_api) and (inference or llm)" || [ $$? = 5 ]
+
+run-gha_disabled-tests: env
+ $(call PRINT_TITLE,"Running GHA disabled tests")
+ @echo "• Running GHA disabled unit tests"
+ $(VENV_PYTEST) --exitfirst --quiet -m "gha_disabled" || [ $$? = 5 ]
+
+test: env
+ $(call PRINT_TITLE,"Unit testing without prints but displaying logs via pytest for WARNING level and above")
+ @echo "• Running unit tests"
+ @if [ -n "$(TEST)" ]; then \
+ $(VENV_PYTEST) -s -m $(USUAL_PYTEST_MARKERS) -o log_cli=true -o log_level=WARNING -k "$(TEST)" $(if $(filter 1,$(VERBOSE)),-v,$(if $(filter 2,$(VERBOSE)),-vv,$(if $(filter 3,$(VERBOSE)),-vvv,))); \
+ else \
+ $(VENV_PYTEST) -s -m $(USUAL_PYTEST_MARKERS) -o log_cli=true -o log_level=WARNING $(if $(filter 1,$(VERBOSE)),-v,$(if $(filter 2,$(VERBOSE)),-vv,$(if $(filter 3,$(VERBOSE)),-vvv,))); \
+ fi
+
+test-xdist: env
+ $(call PRINT_TITLE,"Unit testing without prints but displaying logs via pytest for WARNING level and above")
+ @echo "• Running unit tests"
+ @if [ -n "$(TEST)" ]; then \
+ $(VENV_PYTEST) -n auto -m $(USUAL_PYTEST_MARKERS) -o log_level=WARNING -k "$(TEST)" $(if $(filter 1,$(VERBOSE)),-v,$(if $(filter 2,$(VERBOSE)),-vv,$(if $(filter 3,$(VERBOSE)),-vvv,))); \
+ else \
+ $(VENV_PYTEST) -n auto -m $(USUAL_PYTEST_MARKERS) -o log_level=WARNING $(if $(filter 1,$(VERBOSE)),-v,$(if $(filter 2,$(VERBOSE)),-vv,$(if $(filter 3,$(VERBOSE)),-vvv,))); \
+ fi
+
+t: test-xdist
+ @echo "> done: t = test-xdist"
+
+test-quiet: env
+ $(call PRINT_TITLE,"Unit testing without prints but displaying logs via pytest for WARNING level and above")
+ @echo "• Running unit tests"
+ @if [ -n "$(TEST)" ]; then \
+ $(VENV_PYTEST) -m $(USUAL_PYTEST_MARKERS) -o log_cli=true -o log_level=WARNING -k "$(TEST)" $(if $(filter 1,$(VERBOSE)),-v,$(if $(filter 2,$(VERBOSE)),-vv,$(if $(filter 3,$(VERBOSE)),-vvv,))); \
+ else \
+ $(VENV_PYTEST) -m $(USUAL_PYTEST_MARKERS) -o log_cli=true -o log_level=WARNING $(if $(filter 1,$(VERBOSE)),-v,$(if $(filter 2,$(VERBOSE)),-vv,$(if $(filter 3,$(VERBOSE)),-vvv,))); \
+ fi
+
+tq: test-quiet
+ @echo "> done: tq = test-quiet"
+
+test-with-prints: env
+ $(call PRINT_TITLE,"Unit testing with prints and our rich logs")
+ @echo "• Running unit tests"
+ @if [ -n "$(TEST)" ]; then \
+ $(VENV_PYTEST) -s -m $(USUAL_PYTEST_MARKERS) -k "$(TEST)" $(if $(filter 1,$(VERBOSE)),-v,$(if $(filter 2,$(VERBOSE)),-vv,$(if $(filter 3,$(VERBOSE)),-vvv,))); \
+ else \
+ $(VENV_PYTEST) -s -m $(USUAL_PYTEST_MARKERS) $(if $(filter 1,$(VERBOSE)),-v,$(if $(filter 2,$(VERBOSE)),-vv,$(if $(filter 3,$(VERBOSE)),-vvv,))); \
+ fi
+
+tp: test-with-prints
+ @echo "> done: tp = test-with-prints"
+
+test-inference-with-prints: env
+ $(call PRINT_TITLE,"Unit testing")
+ @if [ -n "$(TEST)" ]; then \
+ $(VENV_PYTEST) --pipe-run-mode live -m "inference and not img_gen" -s -k "$(TEST)" $(if $(filter 1,$(VERBOSE)),-v,$(if $(filter 2,$(VERBOSE)),-vv,$(if $(filter 3,$(VERBOSE)),-vvv,))); \
+ else \
+ $(VENV_PYTEST) --pipe-run-mode live -m "inference and not img_gen" -s $(if $(filter 1,$(VERBOSE)),-v,$(if $(filter 2,$(VERBOSE)),-vv,$(if $(filter 3,$(VERBOSE)),-vvv,))); \
+ fi
+
+test-inference-fast: env
+ $(call PRINT_TITLE,"Unit testing")
+ @if [ -n "$(TEST)" ]; then \
+ $(VENV_PYTEST) -n auto --pipe-run-mode live -m "inference and not img_gen" -s -k "$(TEST)" $(if $(filter 1,$(VERBOSE)),-v,$(if $(filter 2,$(VERBOSE)),-vv,$(if $(filter 3,$(VERBOSE)),-vvv,))); \
+ else \
+ $(VENV_PYTEST) -n auto --pipe-run-mode live -m "inference and not img_gen" -s $(if $(filter 1,$(VERBOSE)),-v,$(if $(filter 2,$(VERBOSE)),-vv,$(if $(filter 3,$(VERBOSE)),-vvv,))); \
+ fi
+
+tip: test-inference-with-prints
+ @echo "> done: tip = test-inference-with-prints"
+
+ti: test-inference-fast
+ @echo "> done: ti-fast = test-inference-fast"
+
+ti-dry: env
+ $(call PRINT_TITLE,"Unit testing")
+ @if [ -n "$(TEST)" ]; then \
+ $(VENV_PYTEST) --pipe-run-mode dry --exitfirst -m "inference and not img_gen" -s -k "$(TEST)" $(if $(filter 1,$(VERBOSE)),-v,$(if $(filter 2,$(VERBOSE)),-vv,$(if $(filter 3,$(VERBOSE)),-vvv,))); \
+ else \
+ $(VENV_PYTEST) --pipe-run-mode dry --exitfirst -m "inference and not img_gen" -s $(if $(filter 1,$(VERBOSE)),-v,$(if $(filter 2,$(VERBOSE)),-vv,$(if $(filter 3,$(VERBOSE)),-vvv,))); \
+ fi
+
+cov: env
+ $(call PRINT_TITLE,"Unit testing with coverage")
+ @echo "• Running unit tests with coverage"
+ @if [ -n "$(TEST)" ]; then \
+ $(VENV_PYTEST) --cov=$(if $(PKG),$(PKG),pipelex) -k "$(TEST)" $(if $(filter 2,$(VERBOSE)),-vv,$(if $(filter 3,$(VERBOSE)),-vvv,-v)); \
+ else \
+ $(VENV_PYTEST) --cov=$(if $(PKG),$(PKG),pipelex) $(if $(filter 2,$(VERBOSE)),-vv,$(if $(filter 3,$(VERBOSE)),-vvv,-v)); \
+ fi
+
+cov-missing: env
+ $(call PRINT_TITLE,"Unit testing with coverage and missing lines")
+ @echo "• Running unit tests with coverage and missing lines"
+ @if [ -n "$(TEST)" ]; then \
+ $(VENV_PYTEST) --cov=$(if $(PKG),$(PKG),pipelex) --cov-report=term-missing -k "$(TEST)" $(if $(filter 2,$(VERBOSE)),-vv,$(if $(filter 3,$(VERBOSE)),-vvv,-v)); \
+ else \
+ $(VENV_PYTEST) --cov=$(if $(PKG),$(PKG),pipelex) --cov-report=term-missing $(if $(filter 2,$(VERBOSE)),-vv,$(if $(filter 3,$(VERBOSE)),-vvv,-v)); \
+ fi
+
+cm: cov-missing
+ @echo "> done: cm = cov-missing"
+
+############################################################################################
+############################ Linting ############################
+############################################################################################
+
+format: env
+ $(call PRINT_TITLE,"Formatting with ruff")
+ $(VENV_RUFF) format . --config pyproject.toml
+
+lint: env
+ $(call PRINT_TITLE,"Linting with ruff")
+ $(VENV_RUFF) check . --fix --config pyproject.toml
+
+pyright: env
+ $(call PRINT_TITLE,"Typechecking with pyright")
+ $(VENV_PYRIGHT) --pythonpath $(VENV_PYTHON) --project pyproject.toml
+
+mypy: env
+ $(call PRINT_TITLE,"Typechecking with mypy")
+ $(VENV_MYPY) --config-file pyproject.toml
+
+pylint: env
+ $(call PRINT_TITLE,"Linting with pylint")
+ $(VENV_PYLINT) --rcfile pyproject.toml pipelex_api tests
+
+
+##########################################################################################
+### MERGE CHECKS
+##########################################################################################
+
+merge-check-ruff-format: env
+ $(call PRINT_TITLE,"Formatting with ruff")
+ $(VENV_RUFF) format --check . --config pyproject.toml
+
+merge-check-ruff-lint: env check-unused-imports
+ $(call PRINT_TITLE,"Linting with ruff without fixing files")
+ $(VENV_RUFF) check . --config pyproject.toml
+
+merge-check-pyright: env
+ $(call PRINT_TITLE,"Typechecking with pyright")
+ $(VENV_PYRIGHT) --pythonpath $(VIRTUAL_ENV)/bin/python3
+
+merge-check-mypy: env
+ $(call PRINT_TITLE,"Typechecking with mypy")
+ $(VENV_MYPY) --config-file pyproject.toml
+
+merge-check-pylint: env
+ $(call PRINT_TITLE,"Linting with pylint")
+ $(VENV_PYLINT) --rcfile pyproject.toml .
+
+##########################################################################################
+### RUN API
+##########################################################################################
+
+run: install
+ $(call PRINT_TITLE,"Running API server with uvicorn")
+ $(VIRTUAL_ENV)/bin/uvicorn pipelex_api.main:app --reload --log-level debug --port 8081
+
+##########################################################################################
+### MISCELLANEOUS
+##########################################################################################
+
+check-unused-imports: env
+ $(call PRINT_TITLE,"Checking for unused imports without fixing")
+ $(VENV_RUFF) check --select=F401 --no-fix .
+
+fix-unused-imports: env
+ $(call PRINT_TITLE,"Fixing unused imports")
+ $(VENV_RUFF) check --select=F401 --fix .
+
+fui: fix-unused-imports
+ @echo "> done: fui = fix-unused-imports"
+
+check-TODOs: env
+ $(call PRINT_TITLE,"Checking for TODOs")
+ @$(VENV_RUFF) check --select=TD -v .
+
+
+##########################################################################################
+### SHORTHANDS
+##########################################################################################
+
+# The drift gates ride along, so a pipelex change that moves the server's wire or the kit fails here,
+# in the same change: the OpenAPI artifact and the vendored inference tree both follow the pipelex of
+# this commit. `install` comes first because both gates, like the type checkers, must see the
+# environment the lock describes, and it makes a fresh worktree's first run provision itself.
+agent-check: install fix-unused-imports format lint pyright mypy openapi-check kit-check
+ @echo "> done: agent-check"
+
+agent-test: install
+ @echo "• Running unit tests..."
+ @tmpfile=$$(mktemp); \
+ $(VENV_PYTEST) -n auto -m $(USUAL_PYTEST_MARKERS) -o log_level=WARNING --tb=short -q > "$$tmpfile" 2>&1; \
+ exit_code=$$?; \
+ if [ $$exit_code -ne 0 ]; then grep -vE '\[\s*[0-9]+%\]\s*$$' "$$tmpfile"; fi; \
+ rm -f "$$tmpfile"; \
+ if [ $$exit_code -eq 0 ]; then echo "• All tests passed."; fi; \
+ exit $$exit_code
+
+c: format lint pyright mypy
+ @echo "> done: c = check"
+
+cc: cleanderived c
+ @echo "> done: cc = cleanderived format lint pyright mypy"
+
+check: cc check-unused-imports pylint openapi-check kit-check
+ @echo "> done: check"
+
+li: lock install
+ @echo "> done: lock install"
+
+##########################################################################################
+### DOCUMENTATION
+##########################################################################################
+
+docs: env
+ $(call PRINT_TITLE,"Serving documentation with mkdocs")
+ $(VENV_MKDOCS) serve -a 127.0.0.1:8001 --watch docs
+
+docs-check: env
+ $(call PRINT_TITLE,"Checking documentation build with mkdocs")
+ $(VENV_MKDOCS) build --strict
+
+
+##########################################################################################
+### OPENAPI ARTIFACT
+##########################################################################################
+
+OPENAPI_ARTIFACT := docs/openapi/pipelex-api.openapi.yaml
+
+# These depend on `install` (not `env`) on purpose: `env` only ensures the venv
+# directory exists, it never runs `uv sync`. The schema is generated from whatever
+# is actually installed in .venv, so without a sync the export/check validates the
+# committed artifact against a drifted venv and silently passes where a fresh install
+# would see the real drift. pipelex itself is an editable install from the workspace,
+# so its models reach the artifact as soon as they change, and `openapi-check` in
+# `agent-check` fails the change that moved them when the gate runs.
+openapi-export: install
+ $(call PRINT_TITLE,"Exporting OpenAPI schema to $(OPENAPI_ARTIFACT)")
+ $(VENV_PYTHON) scripts/export_openapi.py $(OPENAPI_ARTIFACT)
+
+openapi-check: install
+ $(call PRINT_TITLE,"Checking committed OpenAPI artifact against the app")
+ $(VENV_PYTHON) scripts/export_openapi.py --check $(OPENAPI_ARTIFACT)
+
+##########################################################################################
+### VENDORED PIPELEX KIT
+##########################################################################################
+
+VENDORED_CONFIG_DIR := .pipelex
+
+# The image serves the models `.pipelex/inference/` declares, and pipelex never reads its own
+# package's kit once that tree exists, so a kit change reaches the server only when this tree moves
+# with it. The root `make up-kit-configs` (`ukc`), the step a kit change already takes, runs the same
+# sync, and `kit-check` in `agent-check` fails a change that left the tree behind. The rules (what is
+# mirrored, what stays this image's own choice) are in scripts/sync_vendored_kit.py, and the reason
+# the tree stays committed rather than generated when the image is built is in CLAUDE.md.
+kit-sync: install
+ $(call PRINT_TITLE,"Re-syncing $(VENDORED_CONFIG_DIR)/inference/ from the pipelex kit")
+ $(VENV_PYTHON) scripts/sync_vendored_kit.py $(VENDORED_CONFIG_DIR)
+
+kit-check: install
+ $(call PRINT_TITLE,"Checking $(VENDORED_CONFIG_DIR)/inference/ against the pipelex kit")
+ $(VENV_PYTHON) scripts/sync_vendored_kit.py --check $(VENDORED_CONFIG_DIR)
diff --git a/api/README.md b/api/README.md
new file mode 100644
index 000000000..6660ca3d5
--- /dev/null
+++ b/api/README.md
@@ -0,0 +1,143 @@
+<div align="center">
+ <a href="https://www.pipelex.com/"><img src="https://raw.githubusercontent.com/Pipelex/pipelex/main/.github/assets/logo.png" alt="Pipelex Logo" width="400" style="max-width: 100%; height: auto;"></a>
+
+ <h2 align="center">Pipelex API</h2>
+
+The official REST API server for building and executing Pipelex pipelines. Deploy your pipelines as HTTP endpoints and integrate them into any application or workflow.
+
+ <div>
+ <a href="https://docs.pipelex.com/pages/api/"><strong>API Documentation</strong></a> -
+ <a href="https://github.com/Pipelex/pipelex"><strong>Pipelex Core</strong></a> -
+ <a href="https://go.pipelex.com/discord"><strong>Discord</strong></a>
+ </div>
+ <br/>
+
+ <p align="center">
+ <a href="LICENSE"><img src="https://img.shields.io/badge/License-Elastic--2.0-blue.svg" alt="Elastic License 2.0"></a>
+ <a href="https://go.pipelex.com/discord"><img src="https://img.shields.io/badge/Discord-5865F2?logo=discord&logoColor=white" alt="Discord"></a>
+ <a href="https://docs.pipelex.com/"><img src="https://img.shields.io/badge/Docs-03bb95?logo=read-the-docs&logoColor=white&style=flat" alt="Documentation"></a>
+ </p>
+</div>
+
+---
+
+> [!IMPORTANT]
+> **This server lives in [`Pipelex/pipelex`](https://github.com/Pipelex/pipelex), as the repository's `api/` directory.** It moved there from `Pipelex/pipelex-api` after v0.33.2 and is released together with the pipelex library, under the library's version number, so the tag of the `pipelex/pipelex-api` image that follows 0.33.2 is a pipelex version. The image keeps its name, its port and its `/root/.pipelex` configuration mount. Please open issues on `Pipelex/pipelex`.
+
+# 📑 Table of Contents
+
+- [Introduction](#introduction)
+- [Quick Start with Docker](#-quick-start-with-docker)
+- [Run your first pipeline](#-run-your-first-pipeline)
+- [How to scale Pipelex](#-how-to-scale-pipelex)
+- [API Documentation](#-api-documentation)
+- [Support](#-support)
+- [License](#-license)
+
+# Introduction
+
+The **Pipelex API Server** is a FastAPI-based REST API that allows you to execute [Pipelex](https://github.com/Pipelex/pipelex) pipelines via HTTP requests. Deploy your pipelines as HTTP endpoints and integrate them into any application or workflow.
+
+It is the source-available reference implementation of the **[MTHDS Protocol](https://mthds.ai)** — the minimal HTTP contract every MTHDS runner implements (`POST /execute`, `POST /start`, `POST /validate`, `GET /models`, `GET /version`). The contracts nest: **MTHDS Protocol ⊂ Pipelex API (this server) ⊂ Pipelex hosted API**. This server adds the build tooling extensions (`/build/*`) on top of the protocol; the hosted API at `api.pipelex.com/v1` adds durable runs, the method catalog, and account management on top of this server — same shapes throughout. All routes live under the `/v1` base path; the committed contract is [`docs/openapi/pipelex-api.openapi.yaml`](docs/openapi/pipelex-api.openapi.yaml).
+
+# 🚀 Quick Start with Docker
+
+**Official Docker image available at:** [`pipelex/pipelex-api`](https://hub.docker.com/r/pipelex/pipelex-api)
+
+The published image is **generic and configuration-light**: Temporal is off, no S3, no remote tracing. It boots with a single required env var (`PIPELEX_GATEWAY_API_KEY`), and you bring your own [Pipelex configuration](docs/configuration.md) on top to enable storage, tracing, Temporal, or anything else.
+
+### 1. Run with Docker
+
+The only required env var is `PIPELEX_GATEWAY_API_KEY`. Get a free key (with free credits) at https://app.pipelex.com, then run:
+
+```bash
+docker run --name pipelex-api -p 8081:8081 \
+ -e PIPELEX_GATEWAY_API_KEY=your-pipelex-gateway-api-key \
+ pipelex/pipelex-api:latest
+```
+
+To require authentication on the API, add `-e AUTH_MODE=api_key -e API_KEY=your-secret` (or `AUTH_MODE=jwt` + `JWT_SECRET_KEY`). See [`.env.example`](.env.example) for the full list of supported variables and [docs/configuration.md](docs/configuration.md) for `--env-file` and `docker compose` patterns if you'd rather keep config out of your shell history.
+
+If you'd rather build the image yourself instead of pulling, replace `pipelex/pipelex-api:latest` with a local tag after `docker build -f api/Dockerfile -t pipelex-api .`, run from the root of a `Pipelex/pipelex` checkout: the build context is the repository root, so the image installs the pipelex library of the same commit.
+
+### 2. Verify
+
+```bash
+curl http://localhost:8081/health
+```
+
+The API is now running at `http://localhost:8081`. To customize behavior (enable Temporal, swap to S3 storage, layer in env-specific overrides, …), see [docs/configuration.md](docs/configuration.md).
+
+# 🧪 Run your first pipeline
+
+Once `/health` is green, send an inline pipeline definition and inputs to `/v1/execute`. The example below summarizes a string with a one-pipe MTHDS bundle — no files, no auth, copy-paste:
+
+```bash
+curl -s http://localhost:8081/v1/execute \
+ -H "Content-Type: application/json" \
+ -d '{
+ "pipe_code": "summarize",
+ "mthds_contents": ["domain = \"hello\"\nmain_pipe = \"summarize\"\n\n[pipe.summarize]\ntype = \"PipeLLM\"\ndescription = \"Summarize the input text in one sentence\"\ninputs = { text = \"Text\" }\noutput = \"Text\"\nprompt = \"Summarize in one sentence:\\n@text\"\n"],
+ "inputs": { "text": "Pipelex turns plain-language pipeline definitions into reproducible AI workflows that run as HTTP endpoints." }
+ }'
+```
+
+You'll get back a JSON response with `state: "COMPLETED"` and the summary under `pipe_output.working_memory.root.<main_stuff_name>.content`.
+
+**Passing files (PDFs, images) as inputs.** Use the `Document` concept and point it at any HTTP(S) URL:
+
+```json
+{
+ "pipe_code": "your_pipe",
+ "mthds_contents": ["...your MTHDS..."],
+ "inputs": {
+ "cv": { "concept": "Document", "content": { "url": "https://example.com/resume.pdf" } }
+ }
+}
+```
+
+`Document` accepts public HTTP/HTTPS URLs, `pipelex-storage://` URIs, or base64 data URLs. For images, use the `Image` concept with the same `{ "url": "..." }` shape.
+
+For inline MTHDS in the request, `mthds_contents` is a JSON array of raw `.mthds` (TOML) file contents as strings — typically `[open("my_pipe.mthds").read()]` from a client. See [docs/pipe-run.md](docs/pipe-run.md) for every supported input shape and the full `/execute` reference.
+
+# 📈 How to scale Pipelex
+
+A single Pipelex API container is great for development, prototyping, and low-concurrency workloads — pipelines run in-process and `/v1/execute` blocks the request thread until they finish.
+
+For production-scale workloads (high concurrency, long-running pipelines, retries, durable execution, horizontal scaling), the recommended path is to run Pipelex on top of [**Temporal**](https://temporal.io/). With Temporal enabled:
+
+- Pipeline runs become durable workflows — survive worker crashes, support retries and timeouts out of the box.
+- The API container becomes a thin orchestrator: it submits workflows to a Temporal cluster and returns a `pipeline_run_id` immediately (this is what `POST /v1/start` already does).
+- Pipeline execution itself runs on a separate pool of **Pipelex workers** that you scale independently from the HTTP layer.
+- Async completion callbacks (`callback_urls` + `X-Completion-Signature`, see [pipe-run.md](docs/pipe-run.md)) let your application be notified when each run finishes, without polling.
+
+Pipelex already integrates with Temporal under the hood, and the Docker image accepts `TEMPORAL_API_KEY` plus a `[temporal] is_enabled = true` override in `.pipelex/`. **A complete deployment recipe (Temporal cluster sizing, worker container, autoscaling guidance, and an end-to-end docker-compose) is coming soon.** In the meantime, if you need to scale today, get in touch on [Discord](https://go.pipelex.com/discord) and we'll help you wire it up.
+
+# 📖 API Documentation
+
+The full reference for this API server lives next to the code in [`docs/`](docs/):
+
+- [Overview](docs/index.md) — endpoints, authentication, deployment
+- [Pipe Run](docs/pipe-run.md) — `/execute`, `/start`, every input shape
+- [Pipe Validate](docs/pipe-validate.md) — `/validate`
+- [Pipe Builder](docs/pipe-builder.md) — `/build/inputs`, `/build/output`, `/build/runner`
+- [Configuration](docs/configuration.md) — env vars, mounting your own `.pipelex/` config
+
+For broader Pipelex documentation (MTHDS language, concepts, pipe types, the Gateway): **[https://docs.pipelex.com/](https://docs.pipelex.com/)**
+
+# 💬 Support
+
+- **API Documentation**: [https://docs.pipelex.com/pages/api/](https://docs.pipelex.com/pages/api/)
+- **Pipelex Documentation**: [https://docs.pipelex.com/](https://docs.pipelex.com/)
+- **Discord Community**: [https://go.pipelex.com/discord](https://go.pipelex.com/discord)
+- **Main Repository**: [https://github.com/Pipelex/pipelex](https://github.com/Pipelex/pipelex)
+
+# 📝 License
+
+This project is licensed under the Elastic License 2.0 (ELv2); see [LICENSE](LICENSE) for the terms, and the [license page](https://docs.pipelex.com/latest/license/) for how Pipelex reads them. Runtime dependencies are distributed under their own licenses via PyPI.
+
+---
+
+"Pipelex" is a trademark of Evotis S.A.S.
+
+© 2025-2026 Evotis S.A.S.
diff --git a/api/docker-compose.yml b/api/docker-compose.yml
new file mode 100644
index 000000000..aa2c531f0
--- /dev/null
+++ b/api/docker-compose.yml
@@ -0,0 +1,19 @@
+services:
+ pipelex-api:
+ image: pipelex/pipelex-api:latest
+ container_name: pipelex-api
+ restart: unless-stopped
+ ports:
+ - "8081:8081"
+ env_file:
+ - .env
+ healthcheck:
+ test: ["CMD", "curl", "-fsS", "http://127.0.0.1:8081/health"]
+ interval: 30s
+ timeout: 5s
+ retries: 3
+ start_period: 15s
+ # Optional: mount your own Pipelex configuration to override the defaults
+ # baked into the image. See docs/configuration.md for details.
+ # volumes:
+ # - ./.pipelex:/root/.pipelex:ro
diff --git a/api/docs/CODE_OF_CONDUCT.md b/api/docs/CODE_OF_CONDUCT.md
new file mode 100644
index 000000000..7e3ea63d8
--- /dev/null
+++ b/api/docs/CODE_OF_CONDUCT.md
@@ -0,0 +1,5 @@
+---
+title: Code of Conduct
+---
+
+--8<-- "CODE_OF_CONDUCT.md"
\ No newline at end of file
diff --git a/api/docs/changelog.md b/api/docs/changelog.md
new file mode 100644
index 000000000..ece2e41b0
--- /dev/null
+++ b/api/docs/changelog.md
@@ -0,0 +1,5 @@
+---
+title: Changelog
+---
+
+--8<-- "CHANGELOG.md"
\ No newline at end of file
diff --git a/api/docs/codegen.md b/api/docs/codegen.md
new file mode 100644
index 000000000..0f916f3f6
--- /dev/null
+++ b/api/docs/codegen.md
@@ -0,0 +1,100 @@
+# Resolve & Codegen
+
+Resolve a library closure into its **normalized library crate**, and project that crate into typed artifacts (zod schemas, pydantic models, runtime structures) — over HTTP, with the same engine and the same trust chain as the local `pipelex resolve` / `pipelex codegen` commands.
+
+Both are **Pipelex API extensions**, not MTHDS Protocol routes: they are not tagged `x-mthds-protocol` in the [OpenAPI artifact](openapi/pipelex-api.openapi.yaml), and an MTHDS runner is not required to serve them. The *crate* is a different matter — its shape is the standard's [Library Crate Format](https://mthds.ai), so the wire fields are brand-neutral and any MTHDS tool can read one. What is ours is the HTTP surface that produces it, and the type projection on top (the standard specifies none).
+
+Both endpoints speak the [`POST /v1/validate`](pipe-validate.md) verdict discipline: a **produced verdict is always a `200`** discriminated on `is_valid`; the invalid arm carries the structured `validation_errors[]` from pipelex's one shared builder — each item optionally carrying a [`suggested_fix`](error-responses.md#suggested-fixes). Non-2xx is reserved for *no verdict could be produced*: request-shape errors (an unknown projection `kind`/`target`, a malformed closure selector) are `422` RFC 7807 `application/problem+json`, a registry-form `method_ref` is `501`, an address-form `method_ref` that fails to resolve maps per the [`method_ref` error table](pipe-run.md#running-a-method-by-address-method_ref), auth is `401`/`403`, server faults are `5xx`.
+
+## Selecting the closure
+
+Both endpoints accept the same closure selector — exactly one of:
+
+- `files` (list, content-passing): inline MTHDS bundles, each `{ "content": "...", "source": "optional/logical/path.mthds" }`. `source` threads onto diagnostics and the crate's `source_map`.
+- `method_ref` (string): a reference to a published method. The **address form** — `github.com/<owner>/<repo>` plus an optional package selector and `@<tag>` — is resolved server-side through the same fetch path as a [`method_ref` run](pipe-run.md#running-a-method-by-address-method_ref): the package's `.mthds` files feed the closure, each with its real relative path as `source` (so diagnostics and the crate's `source_map` carry true per-file labels). Only `.mthds` data travels on these routes — the package's Python (if any) never loads here. The **registry form** (any non-address reference) stays reserved: the server answers **`501`** (`MethodRefNotSupported`) until method-registry resolution lands.
+
+Providing neither or both is a request-shape `422`.
+
+## Resolve
+
+**Endpoint:** `POST /v1/resolve`
+
+Resolution is a first-class language operation alongside validation: the closure is merged, every ref fully qualified, refinement flattened, natives materialized, and the crate's canonical `fingerprint` computed. Resolution is **static** — it runs no dry-run sweep (runnability is `/validate`'s vocabulary), and the crate is emitted only from a library that loaded and validated.
+
+**Request Body:**
+
+```json
+{
+ "files": [
+ { "content": "...bundle one...", "source": "main.mthds" },
+ { "content": "...bundle two...", "source": "steps.mthds" }
+ ]
+}
+```
+
+**Response (valid verdict):**
+
+```json
+{
+ "is_valid": true,
+ "crate": {
+ "mthds_version": "…",
+ "concepts": { "…": {} },
+ "pipes": { "…": {} },
+ "domains": { "…": {} },
+ "source_map": { "…": "main.mthds" },
+ "fingerprint": "…"
+ },
+ "message": "MTHDS library resolved successfully"
+}
+```
+
+`crate` is the canonical JSON encoding of the normalized crate — the same bytes `pipelex resolve --format json` prints, so fingerprints computed from either surface agree.
+
+**Response (invalid verdict):** `200` with `is_valid: false` and `validation_errors[]` (no crate exists).
+
+## Codegen
+
+**Endpoint:** `POST /v1/codegen`
+
+Resolves the closure exactly like `/resolve`, then projects the crate through the two explicit axes:
+
+- `kind` (string, required): what to project. Served: `types` (the crate's concept set as typed models). Membership follows the **trust chain** — a kind is served here exactly when its artifacts are stamped and locked, which is the promise the valid arm makes by carrying a `lock`. Input templates are user-editable scaffolds, never stamped or locked, so they cannot make that promise: they ride [`POST /v1/build/inputs`](pipe-builder.md) instead and `inputs` is deliberately **not** a kind here.
+- `target` (string, required): for whom. `ts-zod` (zod schemas + inferred types), `python-pydantic` (self-contained pydantic models), or `python-structures` (runtime `StructuredContent` classes, for a Pipelex host).
+- `pipe_ref` (string, optional): pipe selector for future per-pipe kinds — not accepted for `types` (request-shape `422`).
+
+An unknown `kind` or `target` is a request-shape `422` problem+json, never a `200` with an error body.
+
+**Request Body:**
+
+```json
+{
+ "files": [{ "content": "...bundle..." }],
+ "kind": "types",
+ "target": "ts-zod"
+}
+```
+
+**Response (valid verdict):**
+
+```json
+{
+ "is_valid": true,
+ "kind": "types",
+ "target": "ts-zod",
+ "crate_fingerprint": "…",
+ "engine_version": "…",
+ "artifacts": [
+ { "path": "types.ts", "content": "// >>> pipelex-codegen-stamp >>>\n…" }
+ ],
+ "lock": "# codegen.lock — generated artifact set (Pipelex codegen). Do not edit by hand.\n…",
+ "lock_filename": "codegen.lock",
+ "message": "Codegen artifacts generated successfully"
+}
+```
+
+### The trust chain over HTTP
+
+Every artifact ships **stamped** (source-crate fingerprint, engine version, projection, content hash) and the response carries the matching `codegen.lock`. A client that writes each `artifacts[]` entry and the `lock` **verbatim** reproduces a local `pipelex codegen types` run byte-for-byte — so the offline `pipelex codegen check` passes on the written tree exactly as it would on locally generated files.
+
+There is deliberately **no** server-side check route: the drift check is pure hashing over local files, offline by design.
diff --git a/api/docs/configuration.md b/api/docs/configuration.md
new file mode 100644
index 000000000..31277b5bd
--- /dev/null
+++ b/api/docs/configuration.md
@@ -0,0 +1,275 @@
+# Configuration
+
+This page covers how to configure the **Docker image** — the env vars it needs at boot, and how to pass your own Pipelex config files into the container.
+
+For the syntax and meaning of Pipelex config itself (storage backends, tracing, inference routing, model decks, …), see the official Pipelex documentation: **https://docs.pipelex.com**. This page does not duplicate that.
+
+> **The official `pipelex/pipelex-api` image is generic and orchestrator-agnostic.** It runs every pipeline **in-process** (no distributed orchestrator), with no S3, no remote tracing, and the Pipelex Gateway as the only enabled inference backend. Anything environment-specific is meant to be supplied by you, on top of the image, via a mounted `.pipelex/` override file. Distributed execution (Temporal, Mistral Workflows, …) is **not** built in — it is added by installing exactly one orchestrator plugin on top of this base to produce a deployment *flavor* (see "Execution mode" below).
+
+## Environment variables
+
+The API reads its settings from environment variables. With Docker, the easiest way is a `.env` file:
+
+```bash
+# Pipelex Gateway API key — used to call LLMs through Pipelex's inference layer.
+# Required only if you keep the default routing profile. If you reconfigure
+# Pipelex to call providers directly (OpenAI, Anthropic, Bedrock, …), you'll
+# need those providers' own env vars instead — see https://docs.pipelex.com.
+PIPELEX_GATEWAY_API_KEY=your-pipelex-gateway-key
+
+# Authentication for the API itself (optional — defaults to AUTH_MODE=none)
+AUTH_MODE=none # one of: none | api_key | jwt
+API_KEY=your-api-key # used when AUTH_MODE=api_key
+JWT_SECRET_KEY=your-jwt-secret # used when AUTH_MODE=jwt
+
+# Selects which pipelex_{PIPELEX_ENV}.toml override file is layered on top
+# (see "Pipelex configuration files" below). Defaults to "dev" when unset.
+PIPELEX_ENV=dev
+
+# Required ONLY if you use POST /v1/start with `callback_urls`
+# (see pipe-run.md → "Async Completion Callbacks"). HMAC secret shared between
+# this server (signs callbacks) and your callback receiver (verifies them).
+# Read lazily — the server boots without it; the env var is only required at
+# the moment a callback signature is computed.
+# COMPLETION_CALLBACK_SECRET=<shared-with-your-callback-receiver>
+
+# Maximum request body size, in MiB, before the body-size middleware
+# rejects with 413. Defaults to 100 MiB. Raise it for larger documents,
+# lower it to harden the server. Read at startup — change requires a restart.
+# MAX_REQUEST_BODY_MIB=100
+
+# ── Running a method by address (`method_ref`) ────────────────────────────
+# See pipe-run.md → "Running a method by address". All read at startup.
+#
+# The per-instance clone cache (one entry per resolved commit SHA):
+# METHOD_CACHE_DIR=/var/cache/pipelex-api-methods # default: under the OS temp dir
+# MAX_METHOD_CACHE_CLONES=64 # cached clones kept before oldest-first eviction
+# MAX_METHOD_CACHE_TOTAL_KIB=524288 # total bytes across cached clones (default 512 MiB)
+# MAX_METHOD_CACHE_AGE_HOURS=24 # a clone unused this long is evicted
+#
+# Fetched-package ceilings (enforced by the pipelex runtime on every fetch):
+# PIPELEX_MAX_FETCHED_PACKAGE_FILES=256 # files in the selected package
+# PIPELEX_MAX_FETCHED_PACKAGE_TOTAL_KIB=8192 # bytes across the selected package (default 8 MiB)
+# PIPELEX_MAX_SCANNED_MANIFESTS=100 # METHODS.toml files considered per repository
+# PIPELEX_MAX_MANIFEST_FILE_KIB=256 # per METHODS.toml read during package location
+```
+
+Pipelex config TOML files can reference env vars via `${VAR}` substitution — that's how secrets like provider API keys flow from the container's environment into Pipelex's runtime config without hard-coding them. Set whichever vars your mounted `.pipelex/` files reference.
+
+### Setting env vars in Docker
+
+You have three idiomatic options. Pick whichever fits your workflow — they all do the same thing.
+
+**Option 1 — `.env` file (recommended).** Edit your `.env` and pass it to the container with `--env-file`. Best for long-lived deployments and when you want the config in version control next to your `docker-compose.yml`.
+
+```bash
+# .env
+PIPELEX_GATEWAY_API_KEY=your-pipelex-gateway-key
+MAX_REQUEST_BODY_MIB=200
+AUTH_MODE=api_key
+API_KEY=your-strong-secret
+```
+
+```bash
+docker run --name pipelex-api -p 8081:8081 --env-file .env pipelex/pipelex-api:latest
+```
+
+**Option 2 — Inline `-e` flags on `docker run`.** Best for one-off overrides or quickly testing a single value without editing files.
+
+```bash
+docker run --name pipelex-api -p 8081:8081 \
+ -e PIPELEX_GATEWAY_API_KEY=your-pipelex-gateway-key \
+ -e MAX_REQUEST_BODY_MIB=200 \
+ pipelex/pipelex-api:latest
+```
+
+**Option 3 — Compose `environment:` block.** Same as `env_file:` but inline, useful when you want the values visible in `docker-compose.yml` itself.
+
+```yaml
+services:
+ pipelex-api:
+ image: pipelex/pipelex-api:latest
+ ports: ["8081:8081"]
+ env_file: .env # for shared values + secrets
+ environment: # for explicit per-service overrides
+ MAX_REQUEST_BODY_MIB: "200"
+```
+
+You can mix `env_file:` and `environment:` — values in `environment:` win.
+
+> **After changing any env var, restart the container.** All API-side env vars are read once at startup; live changes don't take effect until the process restarts (`docker restart pipelex-api` or `docker compose up -d` after editing).
+
+## Pipelex configuration files
+
+The Pipelex runtime loads `.toml` config files in a layered, deep-merged order. Later layers override earlier ones:
+
+1. Package defaults (shipped inside the `pipelex` Python library)
+2. Global config — `~/.pipelex/pipelex.toml`
+3. Project config — `{cwd}/.pipelex/pipelex.toml` (if present and different from global)
+4. `pipelex_local.toml`
+5. `pipelex_{PIPELEX_ENV}.toml` — picked from the `PIPELEX_ENV` env var (e.g. `pipelex_dev.toml`, `pipelex_prod.toml`)
+6. `pipelex_{run_mode}.toml`
+7. `pipelex_override.toml` — your final override
+8. `pipelex_temporary_override.toml` — ephemeral, safe for tools to write/delete
+
+In the official Docker image, the server's `.pipelex/` directory (`api/.pipelex/` in the pipelex repository) is copied to `/root/.pipelex` at build time, and the image holds no project-level `.pipelex/`. That means **`/root/.pipelex/` is the single config dir the runtime reads from**, and any file you mount there participates in the layering above. To override anything, you only need to provide the keys you want to change — the layering does the rest.
+
+**The inference tree the image ships is the defaults of the `pipelex` it runs.** The image is released together with `pipelex`, under the same version, and every file under `inference/backends/`, the routing profiles and the numbered model deck files are that release's defaults, unchanged, so the models an own-key backend offers are the ones that `pipelex` lists: read `api/.pipelex/inference/backends/<backend>.toml` in the pipelex repository at the image's tag to see them. Only two things are this image's own choice: the `enabled` switches in `inference/backends.toml`, which leave the Pipelex Gateway and the software-only `internal` backend on and every own-key backend off, and the `x_custom_*` deck overrides. A copy of `inference/backends.toml` you mount yourself therefore keeps the backend list of the release you took it from, so take it again when you move to a newer image.
+
+For the schema and meaning of every key in these files, see https://docs.pipelex.com.
+
+## Orchestration mode
+
+The base is **orchestrator-agnostic**. WHICH backend a top-level run dispatches to is a deployment choice, read from a separate **`api.toml`** config file (not the main `pipelex_{env}.toml` — the core config rejects unknown sections). It is layered exactly like the Pipelex config above, but with its own base name: `api.toml` (packaged default) → `api_{PIPELEX_ENV}.toml` → `api_override.toml`. Two keys:
+
+| Key | Meaning | Base default |
+| --- | --- | --- |
+| `orchestration_mode` | Which **backend** (orchestrator) a top-level run dispatches to. An **open string token**: `direct` (in-process), `temporal`, and any plugin-provided token are accepted; an unregistered token fails loud at dispatch with the plugin's install hint. | `direct` |
+| `allow_request_orchestration_mode_override` | Whether a caller may set `orchestration_mode` per request on `POST /v1/execute`, `POST /v1/start`, and `POST /v1/validate`. When `false`, a requested token that differs from the deployment default is refused with a `403`. | `false` |
+
+The packaged default (`orchestration_mode = "direct"`, override off) is what the generic image ships.
+
+**Boot-coherence guard.** A process boots under exactly one orchestrator (the server derives it from `orchestration_mode`), so enabling `allow_request_orchestration_mode_override` on a `direct` default is **refused at boot**: a request overriding to a non-direct mode would resolve that orchestrator's dispatch arm while the process claimed no async execution hub, failing only at dispatch. The app fails fast at startup instead — set a non-direct `orchestration_mode` default (which claims the hub, and still serves a per-request `direct` override in-process) or leave override off.
+
+**`orchestration_mode` is one of two orthogonal axes.** It names only the **backend**. The other axis — *delivery*, i.e. whether the caller waits — is **endpoint-intrinsic**, never configured and never requestable:
+
+- `POST /v1/execute` and `POST /v1/validate` are **synchronous** (`BLOCKING` delivery): they return the full output / the verdict.
+- `POST /v1/start` is **fire-and-forget** (`FIRE_AND_FORGET` delivery): it returns immediately with a `workflow_id`. It works only on a backend that is genuinely async-capable. A Temporal deployment (`orchestration_mode = "temporal"`) enqueues on `/start` and returns a `workflow_id`. On the orchestrator-agnostic base (`orchestration_mode = "direct"`) the in-process orchestrator is blocking-only, so `/start` is **HONEST**: it refuses with a `400` (`StartRequiresAsyncOrchestration`) — use `/execute` — rather than silently running blocking and acking.
+
+So a deployment sets **one** `orchestration_mode` and each endpoint applies its own delivery — there is no fire-and-forget token to configure or request.
+
+**`orchestration_mode` vs `boot_orchestrator` — two knobs, two jobs.** `orchestration_mode` (here) selects the backend a **top-level entry** (`/execute`, `/start`, `/validate`) dispatches to. `boot_orchestrator` (a core Pipelex setting) selects the **execution stack** used wherever a pipe actually runs — on a distributed worker, and for the in-process scoping inside the `direct` orchestrator. On a correctly-configured deployment the two agree (a Temporal flavor sets `orchestration_mode = "temporal"` *and* boots under Temporal); keeping them distinct is what lets `orchestration_mode` be the single source of truth for top-level dispatch without coupling it to how the stack is booted. A `temporal` `orchestration_mode` still requires the process to be booted under Temporal — set them together on a Temporal flavor.
+
+A **flavor** image (e.g. the hosted Temporal flavor) installs one orchestrator plugin and bakes an `api_{env}.toml` to flip the default, e.g.:
+
+```toml
+# api_prod.toml (keys at the file root — no [api] wrapper)
+orchestration_mode = "temporal" # /start is fire-and-forget (async-capable); /execute + /validate stay blocking
+allow_request_orchestration_mode_override = false
+```
+
+Mount your own `api_{env}.toml` / `api_override.toml` into `/root/.pipelex/` exactly like any other override file (see below).
+
+## Providing your own configuration to Docker
+
+Two patterns. Both rely on mounting files into `/root/.pipelex/` inside the container.
+
+### Option 1 — Override individual files
+
+You can mount **any single file** that lives under `/root/.pipelex/` in the image. The bind mount replaces just that one file; everything else stays as shipped. **Recommended for most users.**
+
+Common targets:
+
+```yaml
+services:
+ pipelex-api:
+ image: pipelex/pipelex-api:latest
+ ports: ["8081:8081"]
+ env_file: .env
+ volumes:
+ # Layer your overrides on top of the baseline (one of the override tiers
+ # — see "Pipelex configuration files" above for the load order):
+ - ./pipelex_override.toml:/root/.pipelex/pipelex_override.toml:ro
+
+ # Or env-specific (selected by PIPELEX_ENV):
+ - ./pipelex_dev.toml:/root/.pipelex/pipelex_dev.toml:ro
+
+ # Or replace inference layer files directly:
+ - ./backends.toml:/root/.pipelex/inference/backends.toml:ro
+ - ./routing_profiles.toml:/root/.pipelex/inference/routing_profiles.toml:ro
+
+ # Or the telemetry config:
+ - ./telemetry.toml:/root/.pipelex/telemetry.toml:ro
+```
+
+In other words: any `.toml` file the runtime reads from `/root/.pipelex/` (top-level files OR nested files like `inference/backends.toml`) is replaceable via a single-file bind mount. The image keeps everything else, so you only ship what differs.
+
+For overrides that fit the layering model (`pipelex_override.toml`, `pipelex_<env>.toml`, …), Pipelex deep-merges them on top of the baseline. For files that aren't layered (like `inference/backends.toml`), the mount fully replaces the file — so include all the keys you need.
+
+### Option 2 — Replace the entire config directory
+
+Drop a full `.pipelex/` next to your `docker-compose.yml`:
+
+```yaml
+services:
+ pipelex-api:
+ image: pipelex/pipelex-api:latest
+ ports: ["8081:8081"]
+ env_file: .env
+ volumes:
+ - ./.pipelex:/root/.pipelex:ro
+```
+
+Use this when you want full control — for example, to ship your own inference backends, model deck, or routing profiles. You're now responsible for keeping the contents in sync with the version of Pipelex inside the image (the image's bundled `inference/`, `pipelex.toml`, etc. are no longer present at runtime).
+
+!!! warning "Your `pipelex.toml` must re-supply the logging keys"
+
+ The shipped `pipelex.toml` is what puts this server on structured logs, and replacing the directory replaces it. Without these three keys Pipelex falls back to its own defaults, which are written for someone at a terminal: the Rich console sink instead of JSON lines, and the "Output of pipe" panel rendered on the thread serving each request. Copy them into your own file:
+
+ ```toml
+ [runtime.log]
+ sink = "json"
+ console_log_target = "stderr"
+ pretty_print_mode = "silent"
+ ```
+
+ See [Logging](logging.md#configuration) for what each one does. Option 1 above does not have this problem — a layered override keeps the keys you did not mention.
+
+### `docker run` equivalent
+
+```bash
+docker run --name pipelex-api -p 8081:8081 \
+ --env-file .env \
+ -v $(pwd)/pipelex_override.toml:/root/.pipelex/pipelex_override.toml:ro \
+ pipelex/pipelex-api:latest
+```
+
+## Quick recipes
+
+### Local, default everything
+
+`.env`:
+
+```bash
+PIPELEX_GATEWAY_API_KEY=your-pipelex-gateway-key
+```
+
+`docker-compose.yml`:
+
+```yaml
+services:
+ pipelex-api:
+ image: pipelex/pipelex-api:latest
+ ports: ["8081:8081"]
+ env_file: .env
+```
+
+`docker compose up`, then `curl http://localhost:8081/health`. No override file needed.
+
+### Local, with API key auth
+
+Same as above but add:
+
+```bash
+AUTH_MODE=api_key
+API_KEY=your-strong-secret
+```
+
+Clients now need `Authorization: Bearer your-strong-secret`.
+
+### Documents on an intranet host, or egress through a proxy
+
+When a run fetches a URL that a value carries (a document to extract, a prompt image for a provider that does not take URLs, a generated image a provider returned as a link), the runtime refuses a host that is `localhost`, a cloud metadata alias, or that resolves to a private, loopback, link-local or metadata address, on the first request and on every redirect hop. The pipe fails with `SsrfBlockedError` naming the host. The guarded fetch also connects directly, ignoring `HTTP_PROXY` and `HTTPS_PROXY`. The image ships with the guard on, which is right for any deployment that runs methods it did not write.
+
+A deployment whose documents live on an intranet host, or whose only way out is an HTTP proxy, turns it off in a `pipelex_override.toml`:
+
+```toml
+[runtime.network]
+is_fetch_ssrf_guard_enabled = false
+```
+
+Webhook delivery stays guarded whatever this says.
+
+### Customizing Pipelex (storage, tracing, inference, model decks, …)
+
+Write a `pipelex_override.toml` (or env-specific `pipelex_<env>.toml`) with the keys you want to change. Reference any provider credentials from env vars via `${VAR}` so they stay out of the file. Mount it into the container as shown above. Refer to https://docs.pipelex.com for the full set of available keys and their semantics.
diff --git a/api/docs/contributing.md b/api/docs/contributing.md
new file mode 100644
index 000000000..ec207150d
--- /dev/null
+++ b/api/docs/contributing.md
@@ -0,0 +1,5 @@
+---
+title: Contributing to Pipelex
+---
+
+--8<-- "CONTRIBUTING.md"
diff --git a/api/docs/error-responses.md b/api/docs/error-responses.md
new file mode 100644
index 000000000..1e0272ecd
--- /dev/null
+++ b/api/docs/error-responses.md
@@ -0,0 +1,302 @@
+# Error Responses
+
+Every error returned by the API uses the RFC 7807 `application/problem+json` envelope. The same shape applies across pipelex domain errors, validation errors, auth failures, payload-size limits, and the catch-all 500.
+
+## Envelope
+
+A failure response looks like this:
+
+```json
+{
+ "type": "https://docs.pipelex.com/latest/errors/validate-bundle-error/",
+ "title": "Validate bundle",
+ "status": 422,
+ "detail": "TOML syntax error at line 1, column 6: Expected '=' after a key in a key/value pair",
+ "instance": "/v1/validate",
+ "error_type": "ValidateBundleError",
+ "error_domain": "input",
+ "retryable": false,
+ "request_id": "9f2c1ab3-…"
+}
+```
+
+`Content-Type` is `application/problem+json` and `X-Request-ID` is always echoed in the response headers.
+
+## Fields
+
+**Standard RFC 7807 members** — `type`, `title`, `status`, `detail`, `instance`.
+
+**Extension members** — only `error_type` is always present; the others appear when the originating error populates them:
+
+- `error_type` — stable class name of the originating error (`ValidateBundleError`, `EnvVarNotFoundError`, `WorkflowExecutionError`, …). The same identifier the `type` URI is derived from.
+- `error_domain` — one of `input`, `config`, `runtime`. See [Status codes](#status-codes). Absent for domain-less pipelex errors (some pipelex tool errors, e.g. `EnvVarNotFoundError`, do not classify a domain — the HTTP status still defaults to **500**).
+- `retryable` — whether retrying the same request can plausibly succeed. Always emitted for API-authored 4xx/5xx (always `false`). For pipelex-originated errors, present only when the source error populates it — `true` only when the originating error explicitly classifies itself as transient (e.g. inference provider rate limits); absent on pipelex errors that don't set it (e.g. `EnvVarNotFoundError`, `PipelexConfigError`).
+- `request_id` — server-correlated identifier for the request. Echoed from inbound `X-Request-ID` if provided, otherwise generated. Use this when reporting issues.
+- `error_category` — finer classification when the originating error provides one (currently used by inference errors — see [`InferenceErrorCategory`](https://docs.pipelex.com/latest/errors/) upstream).
+- `user_action` — structured suggestion of what the caller should do next, when the error can author one.
+- `model`, `provider`, `provider_metadata` — populated when the failure originated in an upstream inference call. **Stripped under STRICT disclosure** (see [Disclosure modes](#disclosure-modes)).
+- `validation_errors` — structured per-error list carried by a `ValidateBundleError`. On the run routes (`/execute`, `/start`) it rides this 422 problem document; on the diagnostic routes (`/validate`, `/resolve`, `/codegen`, `/build/{inputs,output,runner}`) it rides the **200 `is_valid: false`** body instead (see [Pipe Validate](pipe-validate.md)). See [Structured validation errors](#structured-validation-errors).
+
+## Structured validation errors
+
+When a bundle fails validation, the `ValidateBundleError` carries a `validation_errors` array — the per-error diagnostics an editor maps to per-line problems. Where it surfaces depends on the endpoint: on the diagnostic routes (`/validate`, `/resolve`, `/codegen`, `/build/{inputs,output,runner}`) it rides the **200 `is_valid: false`** body (the diagnostic-endpoint contract — see [Pipe Validate](pipe-validate.md)); on the run routes (`/execute`, `/start`) — where an invalid bundle means the run cannot proceed — it rides the **422** problem document alongside the single human-readable `detail`. Built by pipelex's one shared builder, the items are identical wherever they appear (and to the agent CLI's). Each item is one categorized validation failure:
+
+| Field | Meaning |
+|---|---|
+| `category` | The failure family — one of `blueprint_validation`, `pipe_factory`, `pipe_validation`, `dry_run`. |
+| `message` | Human-readable description of this specific error. |
+| `error_type` | Finer error subtype within the category, when the source error provides one. |
+| `source` | The owning file of the error, when the runtime could attribute it to one: on `blueprint_validation` and `pipe_validation` items, and on a `dry_run` item, where it is the file of the pipe whose dry run failed. On the in-memory submit path it is the matching `mthds_sources[i]` (see [Sourcing submitted files](pipe-validate.md)), so it is absent when the caller sent no sources. Absent on `pipe_factory` items and on the parse-level residual described below. Beside a server's own library directories, an item never names one of their files. |
+| `pipe_code`, `concept_code`, `domain_code` | The pipe / concept / domain the error is about, when applicable. On a `dry_run` item they name the innermost pipe that failed, not the controller the failure passed through. |
+| `field_path`, `field_name` | The offending field within the bundle, when the error localizes to one. |
+| `variable_names`, `missing_concept_code`, `missing_pipe_code`, `declared_concepts` | Extra context for specific failure shapes (undefined variables, an unresolved concept or pipe reference, the set of concepts that were declared). |
+| `line`, `column` | The 1-based position where the TOML parser stopped, on a TOML syntax error. |
+| `model_reference`, `model_type`, `suggestions` | On an `unknown_model` item — a pipe naming a model the deployment's model deck does not define — the reference as the bundle wrote it, the kind of model the pipe needs (`llm`, `extract`, …), and the deck's close matches of that kind. With exactly one suggestion the item also carries an `unsafe` `suggested_fix` renaming the model. |
+| `suggested_fix` | A structured, deterministic fix for this error — present only when the fix planner derived one. See [Suggested fixes](#suggested-fixes). |
+
+Items carry only the fields that apply to their category — absent fields are omitted, not null. `validation_errors` is **retained under STRICT disclosure** (it describes the caller's own submitted bundle, not server internals). It is present only on `ValidateBundleError`; other error types omit it.
+
+Every invalid verdict carries a **non-empty** `validation_errors` array — the structured-info invariant is total. A parse-level failure the runtime cannot attribute to a known pipe/concept/field — an empty blueprint, an elaborator failure — still becomes one `blueprint_validation` residual item carrying the failure message (no `source`, no `error_type` at this layer), so the array is never empty on an invalid verdict. A TOML syntax error is an item of the same category without an `error_type`, which carries the `line` and `column` the parser stopped at and the `source` when the caller sent one. A failing dry run is one `dry_run` item per failing pipe, located at the innermost pipe that failed. The richer, locator-bearing items appear only when the runtime could attribute the failure; the human-readable summary (the `detail` on a run-route 422, the `message` on a diagnostic-route 200 invalid verdict) stays available alongside, but a consumer can always read at least one structured item.
+
+On the run routes, **every refusal of the bundle while it loads is this verdict**, and the load happens before any pipe runs: a misspelled concept, a wiring mismatch, an unknown model, a TOML fault or a refusal raised while a pipe is built all answer the same **422** carrying the same items validating the bundle gives. None of them reaches a run as a `500`. An entry pipe the bundle does not declare keeps its own `EntryPipeNotFoundError`, and a bare code matching pipes in several domains its own `EntryPipeAmbiguousError`.
+
+## Suggested fixes
+
+A validation error item may carry a `suggested_fix`: a deterministic repair the runtime's fix planner derived from the *typed* error data — never by parsing a message string. It is optional and additive. An item the planner has no rule for simply omits the field, and a client that ignores `suggested_fix` entirely behaves exactly as before.
+
+```json
+{
+ "category": "pipe_validation",
+ "message": "Pipe 'summarize_and_translate' declares output 'Text' but its last step produces 'Translation'",
+ "error_type": "inadequate_output_concept",
+ "pipe_code": "summarize_and_translate",
+ "source": "translate.mthds",
+ "suggested_fix": {
+ "fix_code": "match-sequence-output",
+ "description": "Set output of pipe 'summarize_and_translate' to 'Translation' to match its last step",
+ "safety": "safe",
+ "source": "translate.mthds",
+ "ops": [
+ {
+ "kind": "set_key",
+ "table_path": ["pipe", "summarize_and_translate"],
+ "key": "output",
+ "value": "Translation"
+ }
+ ]
+ }
+}
+```
+
+**Fields:**
+
+- `fix_code` — the kebab-case rule id that produced the fix (`match-sequence-output`, `sync-controller-inputs`, `strip-native-concept-redecl`, `strip-namespace`, …). Stable; use it to allow-list or suppress rules.
+- `description` — human-readable summary of what the fix does.
+- `safety` — `safe` or `unsafe`. Only apply an `unsafe` fix behind an explicit opt-in: it is a likely correction, such as the one close match for an unknown model, that a person or an agent must confirm, and `pipelex fix bundle` never applies one on its own.
+- `source` — the file the ops target, when known. **An applier must only apply ops to the file they target** — in a multi-file library the ops are meaningless against any other file.
+- `ops` — the semantic TOML patch operations, in order.
+
+**Ops** are addressed by `table_path` (the containing table, e.g. `["pipe", "my_seq"]` — the same addressing convention as the items' `field_path`). An op is a **union discriminated on `kind`**: read `kind` off the wire and you know exactly which other fields the op carries, because each kind is its own shape in the OpenAPI artifact rather than one open shape with everything optional.
+
+| `kind` | Effect | Carries besides `table_path` |
+|---|---|---|
+| `set_key` | Set (or add) a key in the table | `key`, `value` |
+| `ensure_table` | Create the table when it is absent | — |
+| `delete_key` | Remove a key from the table | `key` |
+| `delete_table` | Remove the table | — |
+| `rename_table_key` | Rename a key in place, keeping its position | `key`, `new_key` |
+| `move_key` | Relocate a key to another table, creating missing destination parents | `key`, `new_table_path`, `new_key` |
+| `remap_value` | Rewrite a key's string value through an explicit old-to-new `mapping`, doing nothing when the current value is not a mapped one | `key`, `mapping` |
+
+For `ensure_table` and `delete_table`, `table_path` addresses the table itself rather than its parent, so it is never empty — the document root always exists and is never a target. `move_key` is addressed at both ends and the two ends follow different rules: `table_path` is the table the key currently sits in, per the general convention above, while `new_table_path` addresses the destination table itself. Neither is constrained to be non-empty: an empty `table_path` reads a key off the document root, and an empty `new_table_path` moves it there. `move_key` moves a table-valued key with its whole subtree.
+
+`value` is a TOML scalar (string, integer, float, boolean) or a flat scalar mapping, which a fix that must create a whole table at once — a missing `inputs` mapping, say — writes as an inline table.
+
+**The ops are the machine contract; any rendered diff is presentation.** Apply them with a style-preserving TOML editor rather than reconstructing the file from a diff: that is what keeps the caller's formatting, comments, and key order intact.
+
+## Run failures: the root fault, located at the failing pipe
+
+When a run fails, the problem document describes the **root fault**, the innermost Pipelex error on the cause chain, never the run-level wrapper around it: `error_type`, `title` and `type` are the root fault's, and so are `error_domain`, the HTTP status and whether STRICT disclosure keeps the `detail`. The `detail` names the pipe that failed and its path from the entry pipe, `Pipe '<failing pipe>' failed (<entry pipe> → … → <failing pipe>): <the fault's own message>`, and `user_action` names the next step for that pipe. A consumer that branched on `error_type == "PipelineExecutionError"` branches on the root fault's type instead.
+
+So a run the caller's own method refuses reads its reason even under STRICT: a `PipeCondition` whose outcome is `fail`, a `PipeParallel` branch whose multiplicity does not match its output field, a step started without a required input, or a model named inline that the deck does not define all answer a **422** in the `input` domain, with a `detail` that says what to change. A model the deck names but does not serve stays a redacted `config` failure, since the deployment, not the caller, has to fix it.
+
+```http
+HTTP/1.1 422 Unprocessable Entity
+Content-Type: application/problem+json
+
+{
+ "type": "https://docs.pipelex.com/latest/errors/stuff-factory-error/",
+ "title": "Stuff factory",
+ "status": 422,
+ "detail": "Pipe 'analyze_topic' failed (review_topic → analyze_topic): PipeParallel 'analyze_topic' cannot combine its branch results into its output 'TopicReview'. Branch 'draft_idea' gives result 'ideas' as a single 'Idea', but field 'ideas' of 'TopicReview' holds a list. Declare the field as a single concept in the structure of 'TopicReview', with type 'concept' and concept_ref 'Idea', or make branch 'draft_idea' output 'Idea[]'.",
+ "instance": "/v1/execute",
+ "error_type": "StuffFactoryError",
+ "error_domain": "input",
+ "user_action": {
+ "kind": "change_input",
+ "detail": "Branch 'draft_idea' gives result 'ideas' as a single 'Idea', but field 'ideas' of 'TopicReview' holds a list. Declare the field as a single concept in the structure of 'TopicReview', with type 'concept' and concept_ref 'Idea', or make branch 'draft_idea' output 'Idea[]'."
+ },
+ "request_id": "9f2c1ab3-…"
+}
+```
+
+The failure of a `/start` run reaches its completion webhook as the same report, under the payload's `error` key (see [Async callbacks](#async-callbacks-webhook-payload)).
+
+## Status codes
+
+The HTTP status follows pipelex's `error_domain_to_http_status`:
+
+- `error_domain = "input"` → **422** — the caller can fix it (bad `.mthds`, malformed arguments, validation failure).
+- `error_domain = "config"` → **500** — the deployment needs a fix (missing env var, bad TOML override).
+- `error_domain = "runtime"` → **500** — failure during execution (worker crash, upstream service failure).
+- Unclassified / unknown → **500**.
+
+A few specific statuses bypass the domain mapping:
+
+- **400** — a well-formed request this deployment cannot serve. `error_type = "StartRequiresAsyncOrchestration"`: `POST /v1/start` is fire-and-forget by nature, and this deployment's orchestrator is blocking-only (the in-process `direct` default), so it refuses honestly rather than blocking and acking — use `POST /v1/execute` instead.
+- **401** — missing/invalid bearer token. `WWW-Authenticate: Bearer` is set. Only reachable when the deployment enables auth (`AUTH_MODE=api_key` or `AUTH_MODE=jwt`).
+- **403** — authenticated but not authorized, or refused by deployment policy. The cases: a storage-ownership mismatch; `error_type = "OrchestrationModeOverrideForbidden"` — the request asked for an `orchestration_mode` this deployment does not allow overriding per request (`allow_request_orchestration_mode_override = false`); `error_type = "CustomCodeRequiresSandbox"` — the method (an uploaded bundle, or a fetched `method_ref` package) ships custom Python `.py` files and this deployment is not sandbox-hosted, so running caller-supplied code in-process is refused; `error_type = "MethodStructuresRefusedError"` — a fetched `method_ref` package declares in-process Python structure classes (`StructuredContent` subclasses), which hosted execution always refuses, sandbox or not — express the types as MTHDS concepts with inline structures instead (see [Pipe Run](pipe-run.md#running-a-method-by-address-method_ref)).
+- **404** — `error_type = "MethodPackageNotFoundError"`: the `method_ref` repository was fetched, but no package in it matches the requested address by manifest identity. The `detail` lists the package addresses the repository does contain, so the caller can correct the selector.
+- **409** — `error_type = "PipelineManagerAlreadyExistsError"`: the submitted `pipeline_run_id` is already registered for a run that is still in flight on this server. Completed and failed runs free their id, so this only fires for genuinely concurrent duplicates — resubmit after the in-flight run finishes, or pick a fresh id. Only `POST /v1/start` accepts a client-supplied `pipeline_run_id`, so only `/start` can produce it.
+- **413** — request body exceeds the configured size limit (`MAX_REQUEST_BODY_MIB`, 100 MiB by default).
+- **429** — an upstream inference provider rate-limited the run. `Retry-After` is set when the originating error carries `provider_metadata.retry_after_seconds`. Only `POST /v1/execute` runs inference, so only `/execute` can produce it.
+- **501** — a request shape the published contract accepts but this server cannot serve. `error_type = "AsyncExecutionNotEnabledError"`: this deployment does not provide async pipeline execution (`POST /v1/start`). `error_type = "MethodRefNotSupported"`: the request selected its closure by a **registry-form** `method_ref` — not a `github.com/...` address — and no server-side method registry resolves those yet. Address-form references are fetched and resolved server-side (see [Pipe Run](pipe-run.md#running-a-method-by-address-method_ref)); use one of those, or submit inline `files[]`. Both 501s are permanent under the current deployment — do not retry.
+
+The `method_ref` resolution errors are also mapped explicitly rather than through the domain table: `MethodRefParseError`, `MethodFetchError`, `MethodPackageAmbiguityError` and `MethodPackageTooLargeError` are **422** (the caller can fix the reference, pin a tag, or shrink the package), `MethodPackageNotFoundError` is the **404** above, and `MethodStructuresRefusedError` is a **403**, whether the method was fetched by `method_ref` or sent as a bundle. These pipelex `MethodRefError` subclasses do not classify an `error_domain`, so without the explicit mapping they would fall through to the 500 default — which would misreport caller-fixable failures as server faults.
+
+The run routes read their body as plain JSON before anything else, and two refusals come from that step, both **422**. A body that is not valid UTF-8, not valid JSON, nested too deeply to parse, or not a JSON object answers `InvalidJSON`. A body carrying, in any object at any depth, a key named `__class__` or `__module__`, or a key starting with `__kajson`, answers `ReservedObjectKey`, and the `detail` names the key, cut short when it is long. Those are the keys a kajson decoder reads as an order to import and instantiate a class, so the runner refuses them rather than carry them as data. Only keys are checked: a string value that mentions `__class__` is accepted.
+
+A pipe selection the server cannot make is an input **422** named for its failure, never the generic `ValidationError`: `EntryPipeNotFoundError` when the selector names no pipe, and `EntryPipeAmbiguousError` when a bare code matches pipes in several domains. The run routes answer an unknown or ambiguous `pipe_code` that way. `POST /v1/pipe-io` and the `/v1/build/*` routes answer every selection refusal that way, counting a request with no `pipe_ref` over a method that declares no `main_pipe` as `EntryPipeNotFoundError` and one over a method whose domains declare several as `EntryPipeAmbiguousError` (see [Pipe I/O](pipe-io.md#pipe-selection)).
+
+The run routes' extension fields are validated before any method is fetched or any library loaded, and a failure there is a **422** whose `error_type` names the field that failed: `InvalidCallbackUrls` for `callback_urls`, `InvalidStorageScope` for `storage_scope`, `InvalidReadScope` for `read_scope`, `InvalidAnalyticsGroups` for `analytics_groups` (see [Pipe Run](pipe-run.md#host-supplied-run-context-storage_scope-and-analytics_groups)). A storage scope that does not lie under the run's read scope, whether either was sent or defaulted, is an `InvalidReadScope` as well. A failure on another extension field, or on more than one at once, carries the generic `ValidationError`, and the `detail` names every field that failed. `POST /v1/validate` and `POST /v1/build/runner` take `analytics_groups` too and classify it the same way: a body failing on that field alone answers `InvalidAnalyticsGroups`, and one failing on it and another field answers `ValidationError`.
+
+The HTTP status is the source of truth for success vs failure — there is no `success: true/false` field anywhere in the envelope.
+
+Which statuses a given route can actually produce is documented per operation in the [committed OpenAPI artifact](openapi/pipelex-api.openapi.yaml), each as an `application/problem+json` `ProblemDocument`.
+
+**What is *not* an error status:** an invalid `.mthds` bundle. On the diagnostic routes — `/validate`, `/resolve`, `/codegen`, and `/build/{inputs,output,runner}` — a bundle that fails validation is the *successful product* of the call, so it rides a **200** discriminated on `is_valid: false`, carrying the same `validation_errors[]` described above. Non-2xx on those routes is reserved for *no verdict could be produced*. See [Pipe Validate](pipe-validate.md).
+
+## Disclosure modes
+
+The `ERROR_DISCLOSURE` env var controls how much of the originating error makes it onto the wire:
+
+- `verbose` (default) — renders the full `ErrorReport`. Use in dev, staging, and any deployment where the caller is trusted.
+- `strict` — redacts `detail` and provider fields for errors that do not author caller-facing messages. Specifically:
+ - `detail` is preserved only when the error authored a caller-facing message: the bundle's validation verdict (`ValidateBundleError`), a parse error (`MthdsParserError`), and a failure the runtime classifies as the caller's own, such as a pipe refused while it is built or a run that the submitted method itself refuses (see [Run failures](#run-failures-the-root-fault-located-at-the-failing-pipe)). Everything else has `detail` replaced with a generic title-derived string.
+ - `model`, `provider`, `provider_metadata` are always stripped — they have no business on a caller-facing surface.
+ - The redaction is keyed on the **provenance of the message** (`_authors_caller_facing_message` ClassVar), not on `error_domain`. A `RuntimeError` raised `from` an `INPUT`-domain cause does not leak the wrapper's internal message.
+
+Server logs are always verbose regardless of `ERROR_DISCLOSURE` — the operator sees the full picture, the caller sees what the error chose to disclose.
+
+The mode governs **every** response, including the catch-all 500 (`error_category: "unknown"` — a failure that matched no more specific handler). Under `verbose` its `detail` is `"<ExceptionClass>: <message>"`; under `strict` it is the fixed `"An unexpected error occurred. The request id is included for support."`. A traceback never reaches the caller in either mode.
+
+An unclassified failure is the one error a caller cannot diagnose from a request id alone, so it is exactly the one a `verbose` deployment must not turn into a dead end. If you want unclassified failures opaque, that is what `strict` is for — and note it redacts by message provenance, so a deployment wanting *nothing* leaked should set `strict` rather than rely on the catch-all to be silent.
+
+## The `type` URI
+
+`type` is a stable URI pointing at the per-class documentation page upstream:
+
+```
+https://docs.pipelex.com/latest/errors/<kebab-class-name>/
+```
+
+Every `PipelexError` subclass resolves to a live page (the trailing slash is canonical — pipelex emits it to match the MkDocs `use_directory_urls: true` form). The page describes the class, the typical cause, and how to recover.
+
+API-authored errors (`ValidationError`, `BadRequest`, `Unauthenticated`, etc.) follow the same convention with their own slugs.
+
+## Request correlation
+
+Every response carries `X-Request-ID`. The middleware respects an inbound `X-Request-ID` header if present, otherwise mints one. It also binds that id onto the Pipelex runtime's log context for the duration of the request, so every record emitted underneath carries it as a `request_id` field — the server's own error lines and the runtime's lines from inside a run alike. Both run routes, `POST /v1/execute` and `POST /v1/start`, also put the id on the run's metadata, so when a run is dispatched to a worker, the lines the worker writes while it runs the run's workflow and activities carry the same id. What those lines look like, which fields they carry and where the id does not reach are in [Logging](logging.md).
+
+When opening an issue, include the `request_id` from the response (or response headers) and the timestamp.
+
+## Examples
+
+### 422 — input validation failure
+
+```http
+POST /v1/execute
+{
+ "mthds_contents": ["domain = \"broken\"\nmain_pipe = \"Not A Valid Pipe Code!\"\n"]
+}
+```
+
+```http
+HTTP/1.1 422 Unprocessable Entity
+Content-Type: application/problem+json
+X-Request-ID: 9f2c1ab3-…
+
+{
+ "type": "https://docs.pipelex.com/latest/errors/validate-bundle-error/",
+ "title": "Validate bundle",
+ "status": 422,
+ "detail": "Value error, Invalid main pipe syntax 'Not A Valid Pipe Code!'. Must be in snake_case.",
+ "instance": "/v1/execute",
+ "error_type": "ValidateBundleError",
+ "error_domain": "input",
+ "user_action": {
+ "kind": "change_input",
+ "detail": "Edit the bundle as each validation error says: apply its suggested fix where it has one, after confirming an unsafe one"
+ },
+ "request_id": "9f2c1ab3-…",
+ "validation_errors": [
+ {
+ "category": "blueprint_validation",
+ "message": "Value error, Invalid main pipe syntax 'Not A Valid Pipe Code!'. Must be in snake_case.",
+ "error_type": "invalid_pipe_code_syntax",
+ "domain_code": "broken"
+ }
+ ]
+}
+```
+
+The single `detail` is the human summary; `validation_errors` is the machine-readable list a client maps to per-line diagnostics. Only the run routes answer an invalid bundle with this 422 — on the diagnostic routes the same bundle is a **200 `is_valid: false`** verdict, where per-file `source` attribution is also available — see [Structured validation errors](#structured-validation-errors) and [Sourcing submitted files](pipe-validate.md).
+
+### 500 — deployment configuration fault
+
+```http
+HTTP/1.1 500 Internal Server Error
+Content-Type: application/problem+json
+X-Request-ID: 9f2c1ab3-…
+
+{
+ "type": "https://docs.pipelex.com/latest/errors/env-var-not-found-error/",
+ "title": "Environment variable not set",
+ "status": 500,
+ "detail": "Missing required environment variable: COMPLETION_CALLBACK_SECRET",
+ "instance": "/v1/start",
+ "error_type": "EnvVarNotFoundError",
+ "request_id": "9f2c1ab3-…"
+}
+```
+
+`EnvVarNotFoundError` is a domain-less pipelex tool error — neither `error_domain` nor `retryable` is populated on the report, so both extension members are absent on the wire. The HTTP status is still **500** (the deployment, not the caller, has to fix it), but the classification fields only ride along when the originating error sets them. See [Fields](#fields).
+
+Under `ERROR_DISCLOSURE=strict` the same failure has `detail` redacted to `"Server configuration error"` — the env var name lives in the server log only.
+
+### 401 — missing bearer token
+
+```http
+HTTP/1.1 401 Unauthorized
+Content-Type: application/problem+json
+WWW-Authenticate: Bearer
+X-Request-ID: 9f2c1ab3-…
+
+{
+ "type": "https://docs.pipelex.com/latest/errors/unauthenticated/",
+ "title": "Unauthenticated",
+ "status": 401,
+ "detail": "Missing bearer token.",
+ "instance": "/v1/execute",
+ "error_type": "Unauthenticated",
+ "error_domain": "input",
+ "retryable": false,
+ "request_id": "9f2c1ab3-…"
+}
+```
+
+## Async callbacks (webhook payload)
+
+For [async pipeline runs](pipe-run.md) registering a `callback_url`, the failure payload delivered to the caller's webhook **does not** use this envelope. The webhook body carries the raw `ErrorReport` dict under an `error` key, alongside `pipeline_run_id` (the protocol field) plus the runtime's legacy `pipeline_run_id` / `status` keys — a non-HTTP receiver (queue, log shipper) does not necessarily want an RFC 7807 wrapper.
+
+The classification fields (`error_type`, `error_domain`, `retryable`, etc.) surface identically on both paths; only the envelope members (`type`, `status`, `detail`, `instance`, `request_id`) are sync-only. See [Pipe Run → Async Completion Callbacks](pipe-run.md) for the full webhook contract.
diff --git a/api/docs/index.md b/api/docs/index.md
new file mode 100644
index 000000000..c0708d793
--- /dev/null
+++ b/api/docs/index.md
@@ -0,0 +1,198 @@
+# Pipelex API Documentation
+
+!!! important "This server lives in [`Pipelex/pipelex`](https://github.com/Pipelex/pipelex), as the repository's `api/` directory"
+ It moved there from `Pipelex/pipelex-api` after v0.33.2 and is released together with the pipelex library, under the library's version number, so the tag of the `pipelex/pipelex-api` image that follows 0.33.2 is a pipelex version. The image keeps its name, its port and its `/root/.pipelex` configuration mount. Please open issues on `Pipelex/pipelex`.
+
+Welcome to the Pipelex API documentation. The API provides programmatic access to the Pipelex system.
+
+## The three-layer contract
+
+This server is the source-available reference implementation of the **[MTHDS Protocol](https://mthds.ai)** — the minimal HTTP contract every MTHDS runner implements. The contracts nest:
+
+```
+MTHDS Protocol ⊂ Pipelex API (this server) ⊂ Pipelex hosted API
+(the standard) (protocol + build tooling) (+ durable runs, catalog, account)
+```
+
+- **MTHDS Protocol** — five routes: `POST /execute`, `POST /start`, `POST /validate`, `GET /models`, `GET /version`. Tagged `x-mthds-protocol: true` in the [committed OpenAPI artifact](openapi/pipelex-api.openapi.yaml), and **only** those five — the flag is how a conformance suite or a third-party runner extracts the portable subset.
+- **Pipelex API (this server)** — the protocol verbatim, plus the Pipelex extensions: resolve and codegen (`/resolve`, `/codegen`), pipe I/O (`/pipe-io`), build tooling (`/build/*`), and editor tooling (`/lint`, `/format`). `/upload` and `/resolve-storage-url` were non-contract convenience routes and have been **removed** — see [Storage Transport](storage-transport.md) for where they went and why.
+- **Pipelex hosted API** (`api.pipelex.com/v1`) — everything here, same shapes, plus durable runs, the method catalog, and account management.
+
+All routes are served under the `/v1` base path (clients compose `{base}/v1/{endpoint}`).
+
+## What the API Offers
+
+The API currently allows you to:
+
+1. **Run** any Pipelex pipeline with flexible inputs (sync or async)
+2. **Validate** any Pipelex pipeline to ensure correctness
+3. **Resolve** a library closure into its normalized crate, and **codegen** typed artifacts from it (TypeScript/Zod, Pydantic, Pipelex structures)
+4. **Build** pipeline components — generate input schemas, output representations, runner code, concepts, and pipe specs
+5. **Lint and format** single `.mthds` files for editor workflows
+6. **List** available model presets and configurations
+
+## Deployment
+
+Deploy the Pipelex API anywhere that runs Docker (your laptop, ECS, Cloud Run, Kubernetes, …) using our Docker image: [`pipelex/pipelex-api`](https://hub.docker.com/r/pipelex/pipelex-api).
+
+### 1. Run with Docker
+
+The only required env var is `PIPELEX_GATEWAY_API_KEY`. Get a free key (with free credits) at https://app.pipelex.com — it's the default path to LLMs and gives you access to every supported model with a single credential. (If you'd rather call providers like OpenAI, Anthropic, Bedrock, or Vertex directly, you reconfigure that on the Pipelex side, not here — see https://docs.pipelex.com.)
+
+```bash
+docker run --name pipelex-api -p 8081:8081 \
+ -e PIPELEX_GATEWAY_API_KEY=your-pipelex-gateway-api-key \
+ pipelex/pipelex-api:latest
+```
+
+To require authentication on the API itself, add `-e AUTH_MODE=api_key -e API_KEY=your-secret` (or `AUTH_MODE=jwt` + `JWT_SECRET_KEY`). The full set of accepted env vars is documented in [Configuration](configuration.md) and `.env.example`.
+
+If you'd rather keep config out of your shell history, use `--env-file .env` or a `docker-compose.yml` instead — see [Configuration → Setting env vars in Docker](configuration.md#setting-env-vars-in-docker) for both patterns.
+
+To build the image yourself instead of pulling, replace `pipelex/pipelex-api:latest` with a local tag after `docker build -f api/Dockerfile -t pipelex-api .`, run from the root of a `Pipelex/pipelex` checkout: the build context is the repository root, so the image installs the pipelex library of the same commit.
+
+### 2. Verify
+
+```bash
+curl http://localhost:8081/health
+```
+
+### 3. Run your first pipeline
+
+Send an inline MTHDS bundle and inputs to `/v1/execute`:
+
+```bash
+curl -s http://localhost:8081/v1/execute \
+ -H "Content-Type: application/json" \
+ -d '{
+ "pipe_code": "summarize",
+ "mthds_contents": ["domain = \"hello\"\nmain_pipe = \"summarize\"\n\n[pipe.summarize]\ntype = \"PipeLLM\"\ndescription = \"Summarize the input text in one sentence\"\ninputs = { text = \"Text\" }\noutput = \"Text\"\nprompt = \"Summarize in one sentence:\\n@text\"\n"],
+ "inputs": { "text": "Pipelex turns plain-language pipeline definitions into reproducible AI workflows that run as HTTP endpoints." }
+ }'
+```
+
+The response contains `state: "COMPLETED"` and the result under `pipe_output.working_memory.root.<main_stuff_name>.content`. See **[Pipe Run →](pipe-run.md)** for every input shape (text, structured objects, `Document`, `Image`, …) and the full `/execute` and `/start` reference.
+
+### 4. Customize the configuration
+
+Need to change the execution mode, point to a different storage backend, or ship your own model deck? See **[Configuration →](configuration.md)** for how to provide your own `.pipelex/` config files to the Docker image. The base runs every pipeline in-process by default; distributed execution (Temporal, …) is added by a deployment flavor, not configured on the base.
+
+## Base URL
+
+Once deployed locally, the API is available at:
+
+```
+http://localhost:8081/v1
+```
+
+## Authentication
+
+The API supports three authentication modes via the `AUTH_MODE` environment variable:
+
+### No Authentication (Default)
+
+By default (`AUTH_MODE=none`), the API requires no authentication. This is the default for self-hosted deployments and for running behind an API Gateway that handles auth.
+
+If you sit this API behind a trusted reverse proxy that authenticates users and forwards the caller identity via the `X-User-Id` header, set `TRUST_FORWARDED_IDENTITY_HEADERS=true` to honor it. The runner is a generic execution engine — it does not own user metadata (email, OAuth subject, auth method), so a single opaque caller id is the entire trusted surface. The value must be a single path-safe segment (`is_safe_user_id`). **Default is off** — without this flag the API ignores `X-User-Id` entirely and the deployment is treated as single-tenant. With it on, a request arriving *without* the header is rejected with `401`: turning the flag on asserts that a proxy authenticates every caller, so a missing id means that proxy is absent, misconfigured or bypassed. Only enable it when your proxy strips any inbound copy of the header before adding its own; otherwise, any external client can spoof user identity by sending it directly.
+
+### API Key Authentication
+
+Set `AUTH_MODE=api_key` and provide the `API_KEY` environment variable. Include it in the Authorization header:
+
+```
+Authorization: Bearer YOUR_API_KEY
+```
+
+```bash
+docker run --name pipelex-api -p 8081:8081 \
+ -e AUTH_MODE=api_key \
+ -e API_KEY=your-api-key \
+ pipelex/pipelex-api:latest
+```
+
+### JWT Authentication
+
+Set `AUTH_MODE=jwt` and provide the `JWT_SECRET_KEY` environment variable:
+
+```bash
+docker run --name pipelex-api -p 8081:8081 \
+ -e AUTH_MODE=jwt \
+ -e JWT_SECRET_KEY=your-jwt-secret-key \
+ pipelex/pipelex-api:latest
+```
+
+**JWT Requirements:**
+
+- Tokens must be signed with the HS256 algorithm
+- Tokens must contain a `user_id` claim that is a single path-safe segment (`is_safe_user_id`) — it becomes a key segment in storage paths, so provider-issued `sub` values carrying `/`, `#` or `:` (like `"google#abc"`) are NOT accepted. Deployments using OAuth must mint their own `user_id` claim mapping each caller to such a value.
+- Pass the JWT in the Authorization header: `Authorization: Bearer YOUR_JWT_TOKEN`
+
+## API Endpoints
+
+Every failure is an RFC 7807 `application/problem+json` problem document — see **[Error Responses →](error-responses.md)**, and the [committed OpenAPI artifact](openapi/pipelex-api.openapi.yaml) for the statuses each route can produce.
+
+### Health & Version
+
+- `GET /` — Service identity banner (no auth required)
+- `GET /health` — Health check (no auth required)
+- `GET /v1/version` — MTHDS Protocol version handshake (no auth required): `{protocol_version, implementation, implementation_version, runtime_version}`. Replaces the former `/pipelex_version` and `/api_version` routes.
+
+### Pipe Run
+Execute pipelines with flexible input formats, either synchronously or asynchronously.
+
+- `POST /v1/execute` — Run a pipeline and wait for completion (200 + full result)
+- `POST /v1/start` — Start a pipeline execution without waiting (202 + `StartAck`)
+
+[Learn more →](pipe-run.md)
+
+### Pipe Validate
+Validate MTHDS content to ensure pipelines are correctly defined before execution.
+
+- `POST /v1/validate` — Parse, validate, and dry-run pipelines
+
+[Learn more →](pipe-validate.md)
+
+### Pipe I/O
+Read a method's I/O artifacts without a validation. A Pipelex API extension carrying the standard's artifacts.
+
+- `POST /v1/pipe-io` — The pipe I/O contracts, input form and output form of one pipe, or of every pipe with `all_pipes`, beside the method's entry pipe and its pending signatures; no dry run. Takes the same closure selector as `/v1/resolve`, and `include_files` echoes the closure's `.mthds` files
+
+[Learn more →](pipe-io.md)
+
+### Resolve & Codegen
+Resolve a library closure into its normalized crate, and project that crate into typed artifacts. Pipelex API extensions — not MTHDS Protocol routes, though the crate they emit is the standard's Library Crate Format.
+
+- `POST /v1/resolve` — Resolve a closure into the normalized library crate (fully qualified refs, flattened refinement, materialized natives, fingerprint)
+- `POST /v1/codegen` — Generate typed artifacts from the crate: `kind` (`types`) × `target` (`ts-zod`, `python-pydantic`, `python-structures`), plus the `codegen.lock` that makes the result reproducible offline
+
+[Learn more →](codegen.md)
+
+### MTHDS Tools
+Lint and format single `.mthds` files without loading or executing a pipeline.
+
+- `POST /v1/lint` — Return syntax, semantic, or schema diagnostics
+- `POST /v1/format` — Return formatted content, changed status, and blocking syntax diagnostics
+
+[Learn more →](mthds-tools.md)
+
+### Pipe Builder
+Generate input templates, output representations, and runner code for one pipe of a library closure. All three take the same closure selector as `/v1/resolve` and `/v1/codegen` (inline `files[]` XOR `method_ref`), plus an optional qualified `pipe_ref` defaulting to the fetched package manifest's `main_pipe` on a `method_ref` request, else to the closure's declared `main_pipe`.
+
+- `POST /v1/build/inputs` — Generate an example inputs template for a pipe (JSON or TOML)
+- `POST /v1/build/output` — Generate an output representation (schema, JSON, or Python)
+- `POST /v1/build/runner` — Generate Python runner code for a pipe
+
+[Learn more →](pipe-builder.md)
+
+### Agent
+Tools for AI agents building pipelines programmatically.
+
+- `POST /v1/build/concept` — Convert a JSON concept spec to TOML
+- `POST /v1/build/pipe-spec` — Convert a JSON pipe spec to TOML
+- `GET /v1/models` — The protocol model deck this runner routes to (flat `models` list, plus category-keyed `aliases`/`waterfalls` routing extensions); optional single `?type=` category filter
+
+### Uploader (removed)
+
+`POST /v1/upload` and `POST /v1/resolve-storage-url` have been **removed** ([Storage Transport](storage-transport.md)). The storage provider itself is untouched — only the two HTTP routes are gone.
+
+For most use cases you don't need either: pass any public HTTP(S) URL (or base64 data URL) directly as `Document.content.url` and skip the upload step entirely.
diff --git a/api/docs/license.md b/api/docs/license.md
new file mode 100644
index 000000000..3ddc5d7b5
--- /dev/null
+++ b/api/docs/license.md
@@ -0,0 +1,11 @@
+---
+title: License
+hide:
+- feedback
+---
+
+# License
+
+```
+--8<-- "LICENSE"
+```
\ No newline at end of file
diff --git a/api/docs/logging.md b/api/docs/logging.md
new file mode 100644
index 000000000..fdc06ea22
--- /dev/null
+++ b/api/docs/logging.md
@@ -0,0 +1,84 @@
+# Logging
+
+The server writes structured logs: one JSON object per line, on **stderr**, with every value the line carries sitting as a key of its own. That is the shape a log agent in front of a container ingests without a parser — the CloudWatch agent, the Google Cloud Logging agent, an OTLP collector — so a query filters on a field rather than matching a substring of a message.
+
+## What a line looks like
+
+An error response produces exactly one line. A caller mistake:
+
+```json
+{"time": "2026-09-18T13:53:17.919Z", "severity": "WARNING", "logger": "pipelex_api.exception_handlers", "message": "API error 422: InvalidModelCategory", "request_id": "01M2TCP02W04RZG6DTM8AR508C", "event": "api_error", "route": "/v1/models", "error_type": "InvalidModelCategory", "error_domain": "input", "retryable": false, "status": 422, "detail": "Invalid model category. Valid values: extract, img_gen, llm, search"}
+```
+
+A server fault looks the same at `ERROR`, and carries the traceback under an `exception` key.
+
+The `message` is a short, stable sentence built from the HTTP status and the error type — both of them values the server chose. Nothing a caller supplied ever reaches it: the caller-facing explanation rides the `detail` field instead, so a body crafted with newlines or quotes cannot break the line or forge a key. Two layers keep the `detail` value safe to write. Before any sink sees a record, the Pipelex runtime's redaction processor replaces a control character in a field's value with its printable escape, so a newline a caller sent reads as `\n` in `detail`, and replaces a credential it recognises, an `Authorization` header's token or an API key, with `[REDACTED]`. The sink then escapes what it writes, so a quote or an `=` stays inside its value. The processor is configured under `[runtime.log.redaction]` and is on by default.
+
+## The fields a line carries
+
+These keys come from the sink itself and are on every line written by the process, this server's and the Pipelex runtime's alike:
+
+| Key | What it is |
+| --- | --- |
+| `time` | When the record was created — ISO 8601, UTC, milliseconds, `Z` |
+| `severity` | The level name: `WARNING`, `ERROR`, … |
+| `logger` | The module that emitted it |
+| `message` | The human-readable summary |
+| `exception` | The traceback, when the record carries one |
+| `trace_id`, `span_id`, `trace_flags` | The process's current OpenTelemetry span, in lowercase hex, when one names a trace. This server registers no tracer and instruments nothing, so as shipped no line carries them; they appear only when the deployment runs it under OpenTelemetry instrumentation of its own that makes a span current |
+| `pipelex.trace_id`, `pipelex.span_id` | The Pipelex span a runtime line was logged in, the pipe's or the LLM call's, in lowercase hex. Present on the runtime's lines inside a live run the runtime traces, which it does whenever the Pipelex Gateway's telemetry is on or AI span tracing is enabled on your own PostHog; never on the server's own lines, an error line included |
+
+The two pairs name different traces. Pipelex's spans belong to a trace of their own, which only Pipelex's exporters receive, so if you export them to a backend of your own, such as Langfuse, an OTLP collector or your PostHog, join a line to them on `pipelex.trace_id` and `pipelex.span_id`. To gather a run's lines whether or not anything traces, use `request_id` or `pipeline_run_id`. How each sink writes both pairs is in the Pipelex documentation's [trace context](https://docs.pipelex.com/0.69.0/tools/logging/#the-trace-context) section.
+
+`request_id` reaches a line in one of two ways, depending on which process writes it. In this server's own process, the request-id middleware binds it on the runtime's log context for the whole request, so every record emitted there while the request is in flight carries it: the server's own lines, like the example above, and the lines the Pipelex runtime emits from inside a run executed in-process (`orchestration_mode = "direct"`), without any call site passing it along. A run dispatched to a worker, under a distributed `orchestration_mode` such as `temporal`, happens in another process, which that binding does not reach, so the id travels with the run instead: both run routes, `POST /v1/execute` and `POST /v1/start`, put it on the run's metadata, and the worker binds it from there while it runs the run's workflow and activities, so the lines written inside them carry the same id. A line the worker writes outside those bindings does not, such as the one the orchestration SDK logs after an activity has failed. One path does not carry it at all yet: when `POST /v1/validate` dispatches its dry run to a worker, the lines that worker writes for it have no `request_id`. The value is the one echoed in the response's `X-Request-ID` header and in the problem document's `request_id` member, so a caller reporting a failure hands you the key to its log lines.
+
+The remaining keys are what the error handlers attach to an `event: "api_error"` record:
+
+| Key | What it is |
+| --- | --- |
+| `event` | Always `api_error` on an error line — the one key a query filters this server's error stream on |
+| `route` | The request's URL path |
+| `status` | The HTTP status actually sent, including any API-level override |
+| `error_type` | The class or `ErrorType` name the response reports |
+| `error_domain` | `input`, `config`, `runtime`, … — who fixes it |
+| `error_category` | A Pipelex classification, on the failures it classifies; `unknown` on the catch-all 500 |
+| `retryable` | Whether a blind retry can help, when the failure says |
+| `detail` | The operator-facing explanation, the same text the response body carries — on an API-authored failure only, see below |
+| `user_id` | The authenticated caller, when auth bound one |
+| `pipe_code` | The pipe the request named, on a run route whose body parsed |
+| `pipeline_run_id` | The run the request named, on a run route whose body parsed |
+| `provider`, `model`, `provider_status_code`, `provider_request_id` | The inference provider's own identifiers, on a failure that reached one |
+
+A key whose value is not set for this request is **absent** from the line rather than written as `null`, so a query filtering on presence gets an honest answer.
+
+`detail` is the one field whose absence follows the failure's origin rather than the request's shape, and it is worth knowing which way round. A failure this API authored itself — a validation error, an unknown model category — carries `detail` on the record. A failure that arrives as a Pipelex `ErrorReport`, which is most `5xx` and every domain error, does not: the response body still carries a `detail`, but the record does not, because the body's text has been through disclosure redaction and the cause has not. So a `4xx` from that path logs as `API error 422: SomeError` with no explanation and no traceback, and the response is where the explanation is. Build an operator query on `error_type` and `route`, which every line carries, rather than on `detail`.
+
+Every field in that table is a **record attribute**, which is a different thing from the message. A structured sink — `json` here, and the OTLP sink — writes them beside the message as keys. The Rich console sink renders the message alone and ignores them entirely, so a deployment that switches the sink to `"console"` does not get a more readable version of these lines: it gets `API error 500: PipelexConfigError` and nothing else. That is a reason to keep `sink = "json"` wherever the lines are being read by anything other than a person at a terminal.
+
+Disposition follows the HTTP status, not the error domain: a `4xx` is a caller mistake and logs at `WARNING` without a traceback; a `5xx` is a server fault and logs at `ERROR` with one. See [Error Responses](error-responses.md) for the response side of the same failure.
+
+## Configuration
+
+The keys live in `[runtime.log]` of the `.pipelex/pipelex.toml` this repository ships, which the image copies to `/root/.pipelex/`:
+
+```toml
+[runtime.log]
+default_log_level = "INFO"
+sink = "json"
+console_log_target = "stderr"
+pretty_print_mode = "silent"
+
+[runtime.log.package_log_levels]
+pipelex = "INFO"
+```
+
+- `sink = "json"` selects the one-object-per-line renderer. The alternative, `"console"`, is the Rich renderer meant for a terminal. This server does not ask for Pipelex's `cli` extra, but that does not put the renderer out of reach: `typer` and `instructor` are core Pipelex dependencies that require Rich unconditionally, so Rich is installed in the image and an `import pipelex` loads it. Selecting `"console"` here would therefore give you a working console sink, not a refusal. This key is what keeps the renderer unused, and it is the only thing that does.
+- `console_log_target = "stderr"` keeps logs off the data channel.
+- `pretty_print_mode = "silent"` suppresses the "Output of pipe" panel an operator pipe would otherwise draw: there is no terminal to draw into, and a server should not spend time rendering on the thread serving a request.
+- `[runtime.log.package_log_levels]` raises or lowers one package's level independently of `default_log_level`.
+
+To change any of this for a deployment, mount a `pipelex_override.toml` into `/root/.pipelex/` with just the keys you want different — see [Configuration](configuration.md#providing-your-own-configuration-to-docker). Note that replacing the whole config directory, which that page documents as Option 2, drops the shipped `pipelex.toml` along with the three keys above and silently returns the server to Pipelex's terminal-facing defaults; a layered override does not.
+
+## Uvicorn's own lines
+
+Uvicorn logs through its own handlers, not through the sink above, so its startup banner and its access log are plain text rather than JSON: the banner on stderr, the access log on stdout. Pass `--no-access-log` to turn the access log off, which is what the hosted deployment does; configure uvicorn's `--log-config` if you want its lines structured too.
diff --git a/api/docs/mthds-tools.md b/api/docs/mthds-tools.md
new file mode 100644
index 000000000..fe443ab3d
--- /dev/null
+++ b/api/docs/mthds-tools.md
@@ -0,0 +1,90 @@
+# MTHDS Tools
+
+The MTHDS Tools endpoints expose lightweight editor tooling for a single `.mthds`
+file. They are Pipelex API extensions, not MTHDS Protocol routes.
+
+## Lint
+
+**Endpoint:** `POST /v1/lint`
+
+`/lint` checks one `.mthds` file with `pipelex-tools-py`. It validates fully
+offline against the embedded official MTHDS schema; the request path does not
+fetch schemas or read local catalog files.
+
+### Request
+
+- `content` (string, required): one `.mthds` file's contents
+- `source` (string | null, optional): logical filename reserved for diagnostic
+ locators; accepted for parity with `pipelex-tools-py`
+
+```json
+{
+ "content": "domain = \"hello\"\nmain_pipe = \"echo\"\n",
+ "source": "hello.mthds"
+}
+```
+
+### Response
+
+`/lint` is a diagnostic endpoint: malformed `.mthds` content returns HTTP 200
+with diagnostics in the body. Request-shape problems, such as missing `content`
+or a file over the configured per-file limit, return RFC 7807 problem responses.
+
+```json
+{
+ "diagnostics": [
+ {
+ "kind": "syntax",
+ "severity": "error",
+ "message": "expected value",
+ "location": null,
+ "range": {
+ "start_offset": 6,
+ "end_offset": 6,
+ "start_line": 1,
+ "start_col": 7,
+ "end_line": 1,
+ "end_col": 7
+ }
+ }
+ ]
+}
+```
+
+An empty `diagnostics` array means the file is clean.
+
+## Format
+
+**Endpoint:** `POST /v1/format`
+
+`/format` formats one `.mthds` file with the canonical formatter from
+`pipelex-tools-py`.
+
+### Request
+
+- `content` (string, required): one `.mthds` file's contents
+- `options` (object | null, optional): formatter options passed through to
+ `pipelex-tools-py`, such as `column_width`
+
+```json
+{
+ "content": "a=1",
+ "options": { "column_width": 120 }
+}
+```
+
+### Response
+
+Syntax errors return HTTP 200 with the original content unchanged and diagnostics
+describing the blocking issue. Malformed formatter options, such as a non-numeric
+`column_width`, are caller input errors and return RFC 7807 422 responses.
+
+```json
+{
+ "formatted": "a = 1\n",
+ "changed": true,
+ "diagnostics": []
+}
+```
+
+`changed` is `true` when `formatted` differs from `content`.
diff --git a/api/docs/openapi/pipelex-api.openapi.yaml b/api/docs/openapi/pipelex-api.openapi.yaml
new file mode 100644
index 000000000..a4b0e5958
--- /dev/null
+++ b/api/docs/openapi/pipelex-api.openapi.yaml
@@ -0,0 +1,8199 @@
+# GENERATED FILE — do not edit by hand. Regenerate with `make openapi-export`.
+openapi: 3.1.0
+info:
+ title: Pipelex API
+ summary: The source-available Pipelex runner — implements MTHDS Protocol v0.6.0.
+ description: 'This server implements the [MTHDS Protocol](https://mthds.ai) v0.6.0 (`POST /execute`, `POST /start`, `POST
+ /validate`, `GET /models`, `GET /version` — marked `x-mthds-protocol: true`) plus the Pipelex API extensions: resolve
+ and codegen (`/resolve`, `/codegen`), build tooling (`/build/*`), and editor tooling (`/lint`, `/format`). Contract layering:
+ MTHDS Protocol ⊂ Pipelex API (this server) ⊂ Pipelex hosted API. All endpoints are served under the `/v1` base path; every
+ error is an RFC 7807 `application/problem+json` problem document, documented per operation as a `ProblemDocument`.'
+ license:
+ name: Elastic License 2.0
+ identifier: Elastic-2.0
+ version: 0.70.0
+paths:
+ /health:
+ get:
+ tags:
+ - health
+ summary: Liveness probe
+ description: 'Report that this server process is up and serving. No auth required.
+
+
+ A pure liveness probe for load balancers and orchestrators: it touches no
+
+ dependency (no pipelex library load, no storage, no inference provider), so
+
+ a 200 means "the process is serving", never "the deployment is correctly
+
+ configured". It is mounted outside the `/v1` base path and outside the auth
+
+ dependency, and cannot fail.'
+ operationId: get_health_health_get
+ responses:
+ '200':
+ description: Successful Response
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/HealthResponse'
+ /v1/version:
+ get:
+ tags:
+ - discovery
+ summary: Get Version
+ description: 'Protocol and implementation versions (MTHDS Protocol `GET /version`).
+
+
+ The handshake clients use for feature detection: `implementation`
+
+ identifies this runner, `implementation_version` is this server package''s
+
+ version, and `runtime_version` is the underlying pipelex runtime version.'
+ operationId: get_version_v1_version_get
+ responses:
+ '200':
+ description: Successful Response
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/PipelexVersionInfo'
+ '500':
+ description: A `config`-domain or `runtime`-domain failure the caller cannot fix (a missing env var, a bad TOML
+ override, a backend fault), or an unclassified error sanitized by the catch-all handler. Report the `request_id`.
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/ProblemDocument'
+ x-mthds-protocol: true
+ /v1/build/inputs:
+ post:
+ tags:
+ - build
+ summary: Build Inputs
+ description: "Generate an example inputs template for a pipe (the inputs projection, per pipe).\n\nRides the **same\
+ \ static core** as `POST /resolve` and `POST /codegen`: the closure is resolved to\nits normalized crate, the requested\
+ \ pipe is read live from the library that leaves loaded, and its\n*declared* inputs are rendered — the exact projection\
+ \ `pipelex codegen inputs` writes, on both of\nits axes (`format`, `explicit`).\n\nStatic is the point: a template\
+ \ is a read of the pipe's declared IO, so there is **no dry-run\nsweep** here (that is `/validate`'s vocabulary, and\
+ \ `/build/runner`'s need). A valid verdict says\nthe closure is structurally sound and the template matches what the\
+ \ pipe declares — it is *not* a\npromise the pipe runs. Ask `/validate` for that.\n\nThis projection is deliberately\
+ \ **not** a `/codegen` kind: the templates are user-editable\nscaffolds, never stamped or locked, so they cannot ride\
+ \ the trust chain `/codegen`'s valid arm\npromises (see `CodegenRouteKind`).\n\nResponse contract (the `/validate`\
+ \ discipline):\n\n- **Valid verdict (200, `is_valid: true`):** the template, in `inputs` or `inputs_toml` per `format`.\n\
+ - **Invalid verdict (200, `is_valid: false`):** the closure could not be parsed, loaded, or\n validated — `validation_errors[]`\
+ \ from pipelex's one shared builder; no template exists.\n- **No verdict (non-2xx):** a selection refusal — an unknown\
+ \ pipe ref, or an omitted `pipe_ref` that\n nothing defaults (no fetched-manifest `main_pipe`, and a closure declaring\
+ \ no — or several —\n `main_pipe`) — is an input 422 whose `error_type` is `EntryPipeNotFoundError` or\n `EntryPipeAmbiguousError`;\
+ \ a malformed closure selector is a request-shape 422 problem+json; a\n registry-form `method_ref` is a 501 until\
+ \ server-side method-registry resolution exists.\n\nAn omitted `pipe_ref` defaults the way a run by address does:\
+ \ to the fetched package manifest's\n`main_pipe` on a `method_ref` request, else to the closure's own declared `main_pipe`."
+ operationId: build_inputs_v1_build_inputs_post
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/BuildInputsRequest'
+ required: true
+ responses:
+ '200':
+ description: Successful Response
+ content:
+ application/json:
+ schema:
+ oneOf:
+ - $ref: '#/components/schemas/BuildInputsValidReport'
+ - $ref: '#/components/schemas/CrateInvalidReport'
+ title: Response Build Inputs V1 Build Inputs Post
+ discriminator:
+ propertyName: is_valid
+ mapping:
+ 'True': '#/components/schemas/BuildInputsValidReport'
+ 'False': '#/components/schemas/CrateInvalidReport'
+ '401':
+ description: Missing or invalid bearer token. Only reachable when the deployment enables auth (`AUTH_MODE=api_key`
+ or `AUTH_MODE=jwt`).
+ headers:
+ WWW-Authenticate:
+ description: Authentication challenge — always `Bearer`.
+ schema:
+ type: string
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/ProblemDocument'
+ '413':
+ description: Request body exceeds the deployment's size limit (`MAX_REQUEST_BODY_MIB`, 100 MiB by default).
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/ProblemDocument'
+ '422':
+ description: 'The request could not be processed: a malformed body, a field failing validation, or an `input`-domain
+ pipelex error (a `.mthds` bundle the caller must fix). Note that on the diagnostic routes an *invalid bundle*
+ is a **200** verdict, not a 422 — see each route''s response contract.'
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/ProblemDocument'
+ '500':
+ description: A `config`-domain or `runtime`-domain failure the caller cannot fix (a missing env var, a bad TOML
+ override, a backend fault), or an unclassified error sanitized by the catch-all handler. Report the `request_id`.
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/ProblemDocument'
+ '404':
+ description: '`MethodPackageNotFoundError` — the `method_ref` repository was fetched, but no package in it matches
+ the requested address by manifest identity. The message lists the packages the repository does contain.'
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/ProblemDocument'
+ '501':
+ description: '`MethodRefNotSupported` — the request selected its closure by a **registry-form** `method_ref` (not
+ a `github.com/...` address), and no server-side method registry resolves those yet. Use an address-form reference
+ or submit inline `files[]` instead.'
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/ProblemDocument'
+ /v1/build/output:
+ post:
+ tags:
+ - build
+ summary: Build Output
+ description: "Generate an example output representation for a pipe (the output projection, per pipe).\n\nRides the **same\
+ \ static core** as `POST /resolve`, `POST /codegen` and `POST /build/inputs`: the\nclosure is resolved to its normalized\
+ \ crate, the requested pipe is read live from the library that\nleaves loaded, and its *declared* output is rendered.\n\
+ \nStatic is the point: the representation is a read of the pipe's declared IO, so there is **no\ndry-run sweep** here.\
+ \ A valid verdict says the closure is structurally sound and the shape matches\nwhat the pipe declares — it is *not*\
+ \ a promise the pipe runs. Ask `/validate` for that.\n\nResponse contract (the `/validate` discipline):\n\n- **Valid\
+ \ verdict (200, `is_valid: true`):** the representation, in `output` or `output_python` per `format`.\n- **Invalid\
+ \ verdict (200, `is_valid: false`):** the closure could not be parsed, loaded, or\n validated — `validation_errors[]`;\
+ \ no representation exists.\n- **No verdict (non-2xx):** a selection refusal — an unknown pipe ref, or an omitted\
+ \ `pipe_ref` that\n nothing defaults (no fetched-manifest `main_pipe`, and a closure declaring no — or several —\n\
+ \ `main_pipe`) — is an input 422 whose `error_type` is `EntryPipeNotFoundError` or\n `EntryPipeAmbiguousError`;\
+ \ a pipe whose `native.Anything` output has no determinable shape, or a\n malformed closure selector, is a request-shape\
+ \ 422 problem+json; a registry-form `method_ref` is a 501 until server-side\n method-registry resolution exists.\n\
+ \nAn omitted `pipe_ref` defaults the way a run by address does: to the fetched package manifest's\n`main_pipe` on\
+ \ a `method_ref` request, else to the closure's own declared `main_pipe`."
+ operationId: build_output_v1_build_output_post
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/BuildOutputRequest'
+ required: true
+ responses:
+ '200':
+ description: Successful Response
+ content:
+ application/json:
+ schema:
+ oneOf:
+ - $ref: '#/components/schemas/BuildOutputValidReport'
+ - $ref: '#/components/schemas/CrateInvalidReport'
+ title: Response Build Output V1 Build Output Post
+ discriminator:
+ propertyName: is_valid
+ mapping:
+ 'True': '#/components/schemas/BuildOutputValidReport'
+ 'False': '#/components/schemas/CrateInvalidReport'
+ '401':
+ description: Missing or invalid bearer token. Only reachable when the deployment enables auth (`AUTH_MODE=api_key`
+ or `AUTH_MODE=jwt`).
+ headers:
+ WWW-Authenticate:
+ description: Authentication challenge — always `Bearer`.
+ schema:
+ type: string
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/ProblemDocument'
+ '413':
+ description: Request body exceeds the deployment's size limit (`MAX_REQUEST_BODY_MIB`, 100 MiB by default).
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/ProblemDocument'
+ '422':
+ description: 'The request could not be processed: a malformed body, a field failing validation, or an `input`-domain
+ pipelex error (a `.mthds` bundle the caller must fix). Note that on the diagnostic routes an *invalid bundle*
+ is a **200** verdict, not a 422 — see each route''s response contract.'
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/ProblemDocument'
+ '500':
+ description: A `config`-domain or `runtime`-domain failure the caller cannot fix (a missing env var, a bad TOML
+ override, a backend fault), or an unclassified error sanitized by the catch-all handler. Report the `request_id`.
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/ProblemDocument'
+ '404':
+ description: '`MethodPackageNotFoundError` — the `method_ref` repository was fetched, but no package in it matches
+ the requested address by manifest identity. The message lists the packages the repository does contain.'
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/ProblemDocument'
+ '501':
+ description: '`MethodRefNotSupported` — the request selected its closure by a **registry-form** `method_ref` (not
+ a `github.com/...` address), and no server-side method registry resolves those yet. Use an address-form reference
+ or submit inline `files[]` instead.'
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/ProblemDocument'
+ /v1/build/runner:
+ post:
+ tags:
+ - build
+ summary: Build Runner
+ description: 'Generate a Python runner script for a pipe, riding the codegen types projection.
+
+
+ The one `/build/*` projection that is **not** static: a runner script is a promise the pipe can
+
+ actually run, so this route keeps the dry-run sweep its siblings dropped (and with it
+
+ `allow_signatures`, which only ever parameterized that sweep). `validate_bundle` opens a single
+
+ library, loads the closure, sweeps, and on success leaves the library loaded + current; on failure
+
+ it tears it down itself. On the success path the crate is read from that library, the
+
+ `python-structures` projection is emitted and stamped, and the runner script is generated with the
+
+ **emitted** class names — the same flow as a local `pipelex build runner`.
+
+
+ The sweep is scoped to the requested pipe, so unrelated broken siblings do not block a good pipe.
+
+ When `pipe_ref` is omitted the scope is not settled before the closure loads, so the whole closure
+
+ is swept and the pipe then defaults the way a run by address does — to the fetched package
+
+ manifest''s `main_pipe` on a `method_ref` request, else to the closure''s own declared `main_pipe` —
+
+ a stricter verdict, and the honest one for a caller who did not say which pipe they meant.
+
+
+ Response contract (the `/validate` discipline): an invalid closure — including a failed dry-run of
+
+ the requested pipe — is a produced verdict: a **200** `is_valid: false` with the structured
+
+ `validation_errors[]`. Non-2xx is reserved for no-verdict conditions: a selection refusal (an
+
+ unknown pipe ref, an omitted `pipe_ref` that nothing defaults — no fetched-manifest `main_pipe`,
+
+ and a closure declaring no, or several, `main_pipe`), an input 422 whose `error_type` is
+
+ `EntryPipeNotFoundError` or `EntryPipeAmbiguousError`; a request-shape 422 for a requested pipe
+
+ whose cross-package dependencies are absent from the request; a 501 for a registry-form `method_ref`, auth, server
+
+ fault — RFC 7807 via the global handlers.'
+ operationId: build_runner_v1_build_runner_post
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/BuildRunnerRequest'
+ required: true
+ responses:
+ '200':
+ description: Successful Response
+ content:
+ application/json:
+ schema:
+ oneOf:
+ - $ref: '#/components/schemas/BuildRunnerValidReport'
+ - $ref: '#/components/schemas/CrateInvalidReport'
+ title: Response Build Runner V1 Build Runner Post
+ discriminator:
+ propertyName: is_valid
+ mapping:
+ 'True': '#/components/schemas/BuildRunnerValidReport'
+ 'False': '#/components/schemas/CrateInvalidReport'
+ '401':
+ description: Missing or invalid bearer token. Only reachable when the deployment enables auth (`AUTH_MODE=api_key`
+ or `AUTH_MODE=jwt`).
+ headers:
+ WWW-Authenticate:
+ description: Authentication challenge — always `Bearer`.
+ schema:
+ type: string
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/ProblemDocument'
+ '413':
+ description: Request body exceeds the deployment's size limit (`MAX_REQUEST_BODY_MIB`, 100 MiB by default).
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/ProblemDocument'
+ '422':
+ description: 'The request could not be processed: a malformed body, a field failing validation, or an `input`-domain
+ pipelex error (a `.mthds` bundle the caller must fix). Note that on the diagnostic routes an *invalid bundle*
+ is a **200** verdict, not a 422 — see each route''s response contract.'
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/ProblemDocument'
+ '500':
+ description: A `config`-domain or `runtime`-domain failure the caller cannot fix (a missing env var, a bad TOML
+ override, a backend fault), or an unclassified error sanitized by the catch-all handler. Report the `request_id`.
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/ProblemDocument'
+ '404':
+ description: '`MethodPackageNotFoundError` — the `method_ref` repository was fetched, but no package in it matches
+ the requested address by manifest identity. The message lists the packages the repository does contain.'
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/ProblemDocument'
+ '501':
+ description: '`MethodRefNotSupported` — the request selected its closure by a **registry-form** `method_ref` (not
+ a `github.com/...` address), and no server-side method registry resolves those yet. Use an address-form reference
+ or submit inline `files[]` instead.'
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/ProblemDocument'
+ /v1/execute:
+ post:
+ tags:
+ - run
+ summary: Execute
+ description: 'Execute a method synchronously and return its full output (MTHDS Protocol `POST /execute`).
+
+
+ The backend is selected by the resolved `orchestration_mode` (deployment default + optional
+
+ policy-gated per-request override via the `orchestration_mode` extra), symmetric with `/start` —
+
+ not by `boot_orchestrator`. `/execute` is synchronous, so it dispatches with `BLOCKING` delivery
+
+ regardless of backend (wait-semantics is endpoint-set, never requestable). Pipelex domain
+
+ failures propagate untouched: the global `PipelexError` handler in `pipelex_api.exception_handlers`
+
+ turns them into an RFC 7807 problem response.'
+ operationId: execute_v1_execute_post
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $defs:
+ StuffContentAbstract:
+ properties: {}
+ type: object
+ title: StuffContentAbstract
+ properties:
+ pipe_code:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Pipe Code
+ mthds_contents:
+ anyOf:
+ - items:
+ type: string
+ type: array
+ - type: 'null'
+ title: Mthds Contents
+ inputs:
+ anyOf:
+ - additionalProperties:
+ anyOf:
+ - type: string
+ - items:
+ type: string
+ type: array
+ - $ref: '#/$defs/StuffContentAbstract'
+ - items:
+ $ref: '#/$defs/StuffContentAbstract'
+ type: array
+ - additionalProperties: true
+ type: object
+ type: object
+ - type: 'null'
+ title: Inputs
+ output_name:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Output Name
+ output_multiplicity:
+ anyOf:
+ - type: boolean
+ - type: integer
+ - type: 'null'
+ title: Output Multiplicity
+ dynamic_output_concept_ref:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Dynamic Output Concept Ref
+ bundle_b64:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Bundle B64
+ description: PIPELEX-API EXTENSION (not part of the MTHDS Protocol) — base64-encoded zip of the whole method
+ bundle (`.mthds` + `.py` + `structures/*.py` + `requirements.txt`), materialized into a temporary library
+ directory before the run so custom PipeFunc Python travels with the method. Mutually exclusive with `files`.
+ Custom `.py` is only honored on a sandbox-hosted deployment.
+ files:
+ anyOf:
+ - additionalProperties:
+ type: string
+ type: object
+ - type: 'null'
+ title: Files
+ description: 'PIPELEX-API EXTENSION (not part of the MTHDS Protocol) — the method bundle as a `{relative_path:
+ text}` map (the unzipped equivalent of `bundle_b64`). Mutually exclusive with `bundle_b64`.'
+ method_ref:
+ anyOf:
+ - type: string
+ maxLength: 512
+ minLength: 1
+ - type: 'null'
+ title: Method Ref
+ description: 'PIPELEX-API EXTENSION (not part of the MTHDS Protocol) — run a published method by reference
+ instead of inline source. Address form: `github.com/<owner>/<repo>[/<selector>][@<tag>]` (e.g. `github.com/Pipelex/methods/[email protected]`)
+ — resolved by THIS runner: the repository is fetched at the tag (a bare address means the default branch
+ at HEAD), the package is located by manifest identity, and the resolved commit SHA is recorded as `method_provenance`
+ on the response. Mutually exclusive with `mthds_contents` and with a method bundle (`bundle_b64` / `files`);
+ `pipe_code` may accompany it to override the manifest''s `main_pipe`. A package shipping custom Python
+ is only honored on a sandbox-hosted deployment, and a package declaring Python structure classes is always
+ refused — hosted execution accepts MTHDS concepts and sandboxed PipeFuncs, not in-process Python.'
+ orchestration_mode:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Orchestration Mode
+ description: 'PIPELEX-API EXTENSION (not part of the MTHDS Protocol) — request the orchestration mode (the
+ backend) for this run. An OPEN string token: `direct` (in-process, the base default), `temporal`, and
+ any other plugin-provided token are accepted; an unregistered token is refused at dispatch. The delivery
+ axis (blocking vs fire-and-forget) is endpoint-set, never requestable. Honored ONLY when the deployment
+ sets `allow_request_orchestration_mode_override = true` in its `api.toml`; otherwise a token that differs
+ from the deployment default is refused with a 403. Omit it to use the deployment default.'
+ storage_scope:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Storage Scope
+ description: PIPELEX-API EXTENSION (not part of the MTHDS Protocol) — the host-supplied prefix every object
+ this run writes lands under. One to three path-safe segments (e.g. `tenant/run` or `org/method/run`);
+ the runtime composes its own leaves (`assets/`, `generated/`, `results/`, `payloads/`) onto it and never
+ interprets the value. Omit it and the run is scoped to the caller's own id, which is correct for a single-tenant
+ deployment and wrong for a multi-tenant one — a host serving many tenants MUST send this.
+ read_scope:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Read Scope
+ description: PIPELEX-API EXTENSION (not part of the MTHDS Protocol) — the host-supplied prefix every stored
+ object this run reads must lie under, and on a scoped run no local path is read at all. One to three path-safe
+ segments, which must be the `storage_scope` or one of its leading segments, since a run reads back what
+ it writes. Omit it and the run is scoped to the caller's own id when the deployment identifies callers,
+ and unscoped when it is single-tenant — a host serving many tenants MUST send this.
+ analytics_groups:
+ anyOf:
+ - additionalProperties:
+ type: string
+ type: object
+ - type: 'null'
+ title: Analytics Groups
+ description: 'PIPELEX-API EXTENSION (not part of the MTHDS Protocol) — the host-supplied groups this run''s
+ telemetry belongs to, as a mapping of group type to group key (e.g. `{"organization": "org_acme"}`). The
+ runtime never reads a key by name: it carries the mapping on the run as its `extras` and stamps it on
+ every span as `pipelex.run.extras`, so every OpenTelemetry exporter receives it, and the deployment''s
+ own PostHog stream, in `identified` mode, forwards it as the capture''s groups. What Pipelex''s own Gateway
+ telemetry stream receives is the runtime''s decision, not this server''s: the pinned runtime attributes
+ it the same way, with the run''s `user_id` and these groups. Group types are lowercase snake_case starting
+ with a letter, at most 32 characters; group keys are 1 to 128 characters from `[A-Za-z0-9_-]`; at most
+ five entries. Omit it and the run belongs to no group, which is right for a single-tenant deployment.'
+ additionalProperties: true
+ type: object
+ title: PipelexApiExecuteRequest
+ description: 'Documented body of `POST /execute` — the protocol''s `RunRequest` plus THIS server''s run extensions.
+
+
+ Used only to publish the OpenAPI request schema: `/execute` reads the body through the raw
+
+ `Request` (plain JSON, parsed by the route), so FastAPI cannot infer the body type; this model documents the
+
+ extensions the route actually honors (`orchestration_mode`, `storage_scope`, `read_scope`, `analytics_groups`,
+
+ all parsed by `PipelineApiExtras`).'
+ required: true
+ responses:
+ '200':
+ description: Successful Response
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/PipelexApiExecuteResponse'
+ '401':
+ description: Missing or invalid bearer token. Only reachable when the deployment enables auth (`AUTH_MODE=api_key`
+ or `AUTH_MODE=jwt`).
+ headers:
+ WWW-Authenticate:
+ description: Authentication challenge — always `Bearer`.
+ schema:
+ type: string
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/ProblemDocument'
+ '413':
+ description: Request body exceeds the deployment's size limit (`MAX_REQUEST_BODY_MIB`, 100 MiB by default).
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/ProblemDocument'
+ '422':
+ description: 'The request could not be processed: a malformed body, a field failing validation, or an `input`-domain
+ pipelex error (a `.mthds` bundle the caller must fix). Note that on the diagnostic routes an *invalid bundle*
+ is a **200** verdict, not a 422 — see each route''s response contract.'
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/ProblemDocument'
+ '500':
+ description: A `config`-domain or `runtime`-domain failure the caller cannot fix (a missing env var, a bad TOML
+ override, a backend fault), or an unclassified error sanitized by the catch-all handler. Report the `request_id`.
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/ProblemDocument'
+ '403':
+ description: 'A deployment-policy refusal: `OrchestrationModeOverrideForbidden` — the request asked for an `orchestration_mode`
+ this deployment does not allow overriding per request (`allow_request_orchestration_mode_override = false`); `CustomCodeRequiresSandbox`
+ — the method (a bundle, or a fetched `method_ref` package) ships custom Python and this deployment is not sandbox-hosted;
+ or `MethodStructuresRefusedError` — the method''s Python declares structure classes (`StructuredContent` subclasses),
+ whether it arrived as a bundle (`files` or `bundle_b64`) or as a fetched `method_ref` package: a sandbox-hosted
+ deployment imports no caller Python into its own process, so it refuses them before loading anything (express
+ the types as MTHDS concepts instead).'
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/ProblemDocument'
+ '404':
+ description: '`MethodPackageNotFoundError` — the `method_ref` repository was fetched, but no package in it matches
+ the requested address by manifest identity. The message lists the packages the repository does contain.'
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/ProblemDocument'
+ '429':
+ description: An upstream inference provider rate-limited the run. Passed through from the provider; `Retry-After`
+ is set when the provider supplied a hint.
+ headers:
+ Retry-After:
+ description: Seconds to wait before retrying, when the upstream provider supplied a hint.
+ schema:
+ type: integer
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/ProblemDocument'
+ x-mthds-protocol: true
+ /v1/start:
+ post:
+ tags:
+ - run
+ summary: Start
+ description: 'Start a method run and return its pipeline_run_id with a 202 ack (MTHDS Protocol `POST /start`).
+
+
+ Answers `202 Accepted` with a `StartAck`. A client-supplied `pipeline_run_id` is
+
+ honored (the protocol lets an implementation decline it; this runner accepts it, and
+
+ `StartAck.pipeline_run_id` is always authoritative). Pipelex domain failures propagate untouched: the global
+
+ `PipelexError` handler in `pipelex_api.exception_handlers` turns them into an
+
+ RFC 7807 problem response.
+
+
+ Fire-and-forget is a property of THIS endpoint (its delivery axis), honored only by an
+
+ async-capable backend. A deployment configures the backend (`orchestration_mode`) once; `/start`
+
+ sets `FIRE_AND_FORGET` delivery and checks the resolved orchestrator can honor it. A Temporal
+
+ deployment (`orchestration_mode = "temporal"`) enqueues the run and returns immediately with a
+
+ `workflow_id`. On the orchestrator-agnostic base (`orchestration_mode = "direct"`, the default)
+
+ the in-process orchestrator is blocking-only, so `/start` is HONEST: it refuses with a `400`
+
+ (`StartRequiresAsyncOrchestration`) — use `/execute` — rather than silently blocking and acking.
+
+ The completion callback (`callback_urls` / storage delivery) fires on the async path.'
+ operationId: start_v1_start_post
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $defs:
+ StuffContentAbstract:
+ properties: {}
+ type: object
+ title: StuffContentAbstract
+ properties:
+ pipe_code:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Pipe Code
+ mthds_contents:
+ anyOf:
+ - items:
+ type: string
+ type: array
+ - type: 'null'
+ title: Mthds Contents
+ inputs:
+ anyOf:
+ - additionalProperties:
+ anyOf:
+ - type: string
+ - items:
+ type: string
+ type: array
+ - $ref: '#/$defs/StuffContentAbstract'
+ - items:
+ $ref: '#/$defs/StuffContentAbstract'
+ type: array
+ - additionalProperties: true
+ type: object
+ type: object
+ - type: 'null'
+ title: Inputs
+ output_name:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Output Name
+ output_multiplicity:
+ anyOf:
+ - type: boolean
+ - type: integer
+ - type: 'null'
+ title: Output Multiplicity
+ dynamic_output_concept_ref:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Dynamic Output Concept Ref
+ bundle_b64:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Bundle B64
+ description: PIPELEX-API EXTENSION (not part of the MTHDS Protocol) — base64-encoded zip of the whole method
+ bundle (`.mthds` + `.py` + `structures/*.py` + `requirements.txt`), materialized into a temporary library
+ directory before the run so custom PipeFunc Python travels with the method. Mutually exclusive with `files`.
+ Custom `.py` is only honored on a sandbox-hosted deployment.
+ files:
+ anyOf:
+ - additionalProperties:
+ type: string
+ type: object
+ - type: 'null'
+ title: Files
+ description: 'PIPELEX-API EXTENSION (not part of the MTHDS Protocol) — the method bundle as a `{relative_path:
+ text}` map (the unzipped equivalent of `bundle_b64`). Mutually exclusive with `bundle_b64`.'
+ method_ref:
+ anyOf:
+ - type: string
+ maxLength: 512
+ minLength: 1
+ - type: 'null'
+ title: Method Ref
+ description: 'PIPELEX-API EXTENSION (not part of the MTHDS Protocol) — run a published method by reference
+ instead of inline source. Address form: `github.com/<owner>/<repo>[/<selector>][@<tag>]` (e.g. `github.com/Pipelex/methods/[email protected]`)
+ — resolved by THIS runner: the repository is fetched at the tag (a bare address means the default branch
+ at HEAD), the package is located by manifest identity, and the resolved commit SHA is recorded as `method_provenance`
+ on the response. Mutually exclusive with `mthds_contents` and with a method bundle (`bundle_b64` / `files`);
+ `pipe_code` may accompany it to override the manifest''s `main_pipe`. A package shipping custom Python
+ is only honored on a sandbox-hosted deployment, and a package declaring Python structure classes is always
+ refused — hosted execution accepts MTHDS concepts and sandboxed PipeFuncs, not in-process Python.'
+ pipeline_run_id:
+ anyOf:
+ - type: string
+ maxLength: 128
+ - type: 'null'
+ title: Pipeline Run Id
+ callback_urls:
+ anyOf:
+ - items:
+ type: string
+ type: array
+ - type: 'null'
+ title: Callback Urls
+ description: PIPELEX-API EXTENSION (not part of the MTHDS Protocol) — completion webhooks. When the run
+ finishes, the runner POSTs a completion notice to each URL, with an X-Completion-Signature header holding
+ the HMAC-SHA256 of the run id (not of the body). The body carries `pipeline_run_id`, `state` (with the
+ legacy `status` alias), `result_url` (the storage key prefix of the stored results, when results were
+ stored) and `error` on failure; it does not carry the run's output. http/https only; private, loopback,
+ link-local and cloud-metadata hosts are rejected.
+ orchestration_mode:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Orchestration Mode
+ description: 'PIPELEX-API EXTENSION (not part of the MTHDS Protocol) — request the orchestration mode (the
+ backend) for this run. An OPEN string token: `direct` (in-process, the base default), `temporal`, and
+ any other plugin-provided token are accepted; an unregistered token is refused at dispatch. The delivery
+ axis (blocking vs fire-and-forget) is endpoint-set, never requestable. Honored ONLY when the deployment
+ sets `allow_request_orchestration_mode_override = true` in its `api.toml`; otherwise a token that differs
+ from the deployment default is refused with a 403. Omit it to use the deployment default.'
+ storage_scope:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Storage Scope
+ description: PIPELEX-API EXTENSION (not part of the MTHDS Protocol) — the host-supplied prefix every object
+ this run writes lands under. One to three path-safe segments (e.g. `tenant/run` or `org/method/run`);
+ the runtime composes its own leaves (`assets/`, `generated/`, `results/`, `payloads/`) onto it and never
+ interprets the value. Omit it and the run is scoped to the caller's own id, which is correct for a single-tenant
+ deployment and wrong for a multi-tenant one — a host serving many tenants MUST send this.
+ read_scope:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Read Scope
+ description: PIPELEX-API EXTENSION (not part of the MTHDS Protocol) — the host-supplied prefix every stored
+ object this run reads must lie under, and on a scoped run no local path is read at all. One to three path-safe
+ segments, which must be the `storage_scope` or one of its leading segments, since a run reads back what
+ it writes. Omit it and the run is scoped to the caller's own id when the deployment identifies callers,
+ and unscoped when it is single-tenant — a host serving many tenants MUST send this.
+ analytics_groups:
+ anyOf:
+ - additionalProperties:
+ type: string
+ type: object
+ - type: 'null'
+ title: Analytics Groups
+ description: 'PIPELEX-API EXTENSION (not part of the MTHDS Protocol) — the host-supplied groups this run''s
+ telemetry belongs to, as a mapping of group type to group key (e.g. `{"organization": "org_acme"}`). The
+ runtime never reads a key by name: it carries the mapping on the run as its `extras` and stamps it on
+ every span as `pipelex.run.extras`, so every OpenTelemetry exporter receives it, and the deployment''s
+ own PostHog stream, in `identified` mode, forwards it as the capture''s groups. What Pipelex''s own Gateway
+ telemetry stream receives is the runtime''s decision, not this server''s: the pinned runtime attributes
+ it the same way, with the run''s `user_id` and these groups. Group types are lowercase snake_case starting
+ with a letter, at most 32 characters; group keys are 1 to 128 characters from `[A-Za-z0-9_-]`; at most
+ five entries. Omit it and the run belongs to no group, which is right for a single-tenant deployment.'
+ additionalProperties: true
+ type: object
+ title: PipelexApiStartRequest
+ description: 'Documented body of `POST /start` — the protocol''s `StartRequest` plus THIS server''s extensions.
+
+
+ Used only to publish the OpenAPI request schema: the protocol model no
+
+ longer advertises implementation extensions, so this server documents the
+
+ ones it implements itself. Wire validation happens in `PipelineApiExtras`.'
+ required: true
+ responses:
+ '202':
+ description: Successful Response
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/PipelexApiStartResponse'
+ '401':
+ description: Missing or invalid bearer token. Only reachable when the deployment enables auth (`AUTH_MODE=api_key`
+ or `AUTH_MODE=jwt`).
+ headers:
+ WWW-Authenticate:
+ description: Authentication challenge — always `Bearer`.
+ schema:
+ type: string
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/ProblemDocument'
+ '413':
+ description: Request body exceeds the deployment's size limit (`MAX_REQUEST_BODY_MIB`, 100 MiB by default).
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/ProblemDocument'
+ '422':
+ description: 'The request could not be processed: a malformed body, a field failing validation, or an `input`-domain
+ pipelex error (a `.mthds` bundle the caller must fix). Note that on the diagnostic routes an *invalid bundle*
+ is a **200** verdict, not a 422 — see each route''s response contract.'
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/ProblemDocument'
+ '500':
+ description: A `config`-domain or `runtime`-domain failure the caller cannot fix (a missing env var, a bad TOML
+ override, a backend fault), or an unclassified error sanitized by the catch-all handler. Report the `request_id`.
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/ProblemDocument'
+ '400':
+ description: '`StartRequiresAsyncOrchestration` — this deployment''s orchestrator is blocking-only and cannot honor
+ fire-and-forget delivery. Use `POST /execute` instead.'
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/ProblemDocument'
+ '403':
+ description: 'A deployment-policy refusal: `OrchestrationModeOverrideForbidden` — the request asked for an `orchestration_mode`
+ this deployment does not allow overriding per request (`allow_request_orchestration_mode_override = false`); `CustomCodeRequiresSandbox`
+ — the method (a bundle, or a fetched `method_ref` package) ships custom Python and this deployment is not sandbox-hosted;
+ or `MethodStructuresRefusedError` — the method''s Python declares structure classes (`StructuredContent` subclasses),
+ whether it arrived as a bundle (`files` or `bundle_b64`) or as a fetched `method_ref` package: a sandbox-hosted
+ deployment imports no caller Python into its own process, so it refuses them before loading anything (express
+ the types as MTHDS concepts instead).'
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/ProblemDocument'
+ '404':
+ description: '`MethodPackageNotFoundError` — the `method_ref` repository was fetched, but no package in it matches
+ the requested address by manifest identity. The message lists the packages the repository does contain.'
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/ProblemDocument'
+ '409':
+ description: '`PipelineManagerAlreadyExistsError` — the submitted `pipeline_run_id` is still registered for an in-flight
+ run. Completed and failed runs free their id, so this only fires for genuinely concurrent duplicates.'
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/ProblemDocument'
+ '501':
+ description: '`AsyncExecutionNotEnabledError` — this deployment does not provide async pipeline execution. Permanent
+ under the current deployment; do not retry.'
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/ProblemDocument'
+ x-mthds-protocol: true
+ /v1/validate:
+ post:
+ tags:
+ - validate
+ summary: Validate Mthds
+ description: "Validate MTHDS content by parsing, loading, and dry-running pipes (MTHDS Protocol `POST /validate`).\n\
+ \n`/validate` is a **diagnostic endpoint**: any verdict the validator can produce — valid,\ninvalid, or valid-but-not-runnable\
+ \ — rides a **200** discriminated in the body on `is_valid`.\nNon-2xx is reserved for the cases where *no verdict\
+ \ could be produced*.\n\nResponse contract:\n\n- **Valid verdict (200, `is_valid: true`):** the `ValidReport` arm\
+ \ — the canonical report\n (primary `bundle_blueprint`, `pipe_io_contracts` keyed by namespaced `pipe_ref`, per-pipe\n\
+ \ `validated_pipes` sweep outcomes, `pending_signatures` + `is_runnable` runnability verdict,\n best-effort `graph_spec`)\
+ \ plus the wire extras (`mthds_contents` echo, `message`,\n `default_pipe_ref`). The graph is drawn from the pipe\
+ \ a selector-less run of this request\n would execute: on a `method_ref` request whose manifest names a `main_pipe`,\
+ \ that pipe;\n otherwise the primary blueprint's `main_pipe`. A bundle that declares no `main_pipe`, with\n no manifest\
+ \ naming one, validates fine and carries `graph_spec=null`, and so does a\n manifest `main_pipe` the closure does\
+ \ not resolve. Pending signatures are reported as `pending_signatures` +\n `is_runnable: false`, never as an error.\
+ \ `default_pipe_ref` names the pipe a selector-less\n run of this same request would execute — on a `method_ref`\
+ \ request that is the fetched\n manifest's `main_pipe`, which the canonical report cannot see, so the field is the\
+ \ only\n signal a consumer can project a by-address entry signature from.\n The opt-in `views` tokens `input_form`\
+ \ and `output_form` additionally attach the per-pipe\n input-form and output-form descriptors as same-named top-level\
+ \ fields, keyed like\n `pipe_io_contracts`; without a token the matching field is absent and the body is\n byte-identical\
+ \ to a request that omits `views`. They are separate tokens because they answer\n separate questions — a caller building\
+ \ a fill-in form wants the inputs, a caller rendering a\n result or registering a tool signature with a return type\
+ \ wants the output.\n- **Invalid verdict (200, `is_valid: false`):** the `InvalidReport` arm — `validation_errors[]`\n\
+ \ (the structured per-error diagnostics, built by pipelex's one shared builder, incl. one\n located `dry_run` item\
+ \ per pipe whose dry run failed) + `message`, with the structural artifacts absent. The runner\n returns this as\
+ \ a value (`ErrorReport` with `validation_errors`) regardless of backend — the\n in-process arm from the bundle's\
+ \ `ValidateBundleError`, the dispatched arm recovered from the\n worker — so the route maps it to a 200 by matching\
+ \ validation diagnostics, never by catching an\n exception. Returned `ErrorReport`s without validation diagnostics\
+ \ are backend/config/runtime\n faults and keep the global RFC 7807 problem response path.\n- **No verdict (non-2xx):**\
+ \ a malformed request body, an `mthds_sources` length mismatch, or\n both/neither of `mthds_contents` / `method_ref`\
+ \ is a request-shape **422**; a forbidden\n `orchestration_mode` override is a **403**; a host-wiring programmer\
+ \ error or a genuine\n orchestrator fault is a **5xx**; auth is **401/403**. A `method_ref` **resolution failure**\n\
+ \ is also a no-verdict condition — never an `is_valid: false`: a malformed reference or a\n failed fetch is a **422**,\
+ \ no matching package in the repository a **404**, and the\n custom-Python policy (the sandbox gate, the structures\
+ \ refusal) a **403**, each with the\n originating error class as `error_type`. All are RFC 7807 `application/problem+json`\n\
+ \ rendered by the global handler in `pipelex_api.exception_handlers` — routes never shape them."
+ operationId: validate_mthds_v1_validate_post
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ValidateRequest'
+ required: true
+ responses:
+ '200':
+ description: Successful Response
+ content:
+ application/json:
+ schema:
+ oneOf:
+ - $ref: '#/components/schemas/ValidReport'
+ - $ref: '#/components/schemas/InvalidReport'
+ title: Response Validate Mthds V1 Validate Post
+ discriminator:
+ propertyName: is_valid
+ mapping:
+ 'True': '#/components/schemas/ValidReport'
+ 'False': '#/components/schemas/InvalidReport'
+ '401':
+ description: Missing or invalid bearer token. Only reachable when the deployment enables auth (`AUTH_MODE=api_key`
+ or `AUTH_MODE=jwt`).
+ headers:
+ WWW-Authenticate:
+ description: Authentication challenge — always `Bearer`.
+ schema:
+ type: string
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/ProblemDocument'
+ '413':
+ description: Request body exceeds the deployment's size limit (`MAX_REQUEST_BODY_MIB`, 100 MiB by default).
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/ProblemDocument'
+ '422':
+ description: 'The request could not be processed: a malformed body, a field failing validation, or an `input`-domain
+ pipelex error (a `.mthds` bundle the caller must fix). Note that on the diagnostic routes an *invalid bundle*
+ is a **200** verdict, not a 422 — see each route''s response contract.'
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/ProblemDocument'
+ '500':
+ description: A `config`-domain or `runtime`-domain failure the caller cannot fix (a missing env var, a bad TOML
+ override, a backend fault), or an unclassified error sanitized by the catch-all handler. Report the `request_id`.
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/ProblemDocument'
+ '403':
+ description: 'A deployment-policy refusal: `OrchestrationModeOverrideForbidden` — the request asked for an `orchestration_mode`
+ this deployment does not allow overriding per request (`allow_request_orchestration_mode_override = false`); `CustomCodeRequiresSandbox`
+ — the method (a bundle, or a fetched `method_ref` package) ships custom Python and this deployment is not sandbox-hosted;
+ or `MethodStructuresRefusedError` — the method''s Python declares structure classes (`StructuredContent` subclasses),
+ whether it arrived as a bundle (`files` or `bundle_b64`) or as a fetched `method_ref` package: a sandbox-hosted
+ deployment imports no caller Python into its own process, so it refuses them before loading anything (express
+ the types as MTHDS concepts instead).'
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/ProblemDocument'
+ '404':
+ description: '`MethodPackageNotFoundError` — the `method_ref` repository was fetched, but no package in it matches
+ the requested address by manifest identity. The message lists the packages the repository does contain.'
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/ProblemDocument'
+ x-mthds-protocol: true
+ /v1/resolve:
+ post:
+ tags:
+ - resolve
+ summary: Resolve Mthds
+ description: "Resolve a library closure into its normalized crate (Pipelex API extension).\n\nResolution is a first-class\
+ \ language operation alongside validation: assemble the closure from\nthe inline `files[]`, load + statically validate\
+ \ the library, and emit the **normalized\nlibrary crate** (fully qualified refs, refinement flattened, natives materialized,\
+ \ fingerprint\nset) — the artifact shape the MTHDS standard specifies as the Library Crate Format. It runs no\ndry-run\
+ \ sweep — runnability is `/validate`'s vocabulary.\n\nResponse contract (the `/validate` discipline):\n\n- **Valid\
+ \ verdict (200, `is_valid: true`):** the crate on the valid arm.\n- **Invalid verdict (200, `is_valid: false`):**\
+ \ the library could not be parsed, loaded, or\n validated — `validation_errors[]` from pipelex's one shared builder.\n\
+ - **No verdict (non-2xx):** a malformed request body (neither/both closure selectors, an\n over-limit file) is a\
+ \ request-shape 422; `method_ref` is a 501 until server-side method\n registry resolution exists; auth is 401/403;\
+ \ server fault is 5xx. All RFC 7807\n `application/problem+json` via the global handlers."
+ operationId: resolve_mthds_v1_resolve_post
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/MthdsFilesRequest'
+ required: true
+ responses:
+ '200':
+ description: Successful Response
+ content:
+ application/json:
+ schema:
+ oneOf:
+ - $ref: '#/components/schemas/ResolveValidReport'
+ - $ref: '#/components/schemas/CrateInvalidReport'
+ title: Response Resolve Mthds V1 Resolve Post
+ discriminator:
+ propertyName: is_valid
+ mapping:
+ 'True': '#/components/schemas/ResolveValidReport'
+ 'False': '#/components/schemas/CrateInvalidReport'
+ '401':
+ description: Missing or invalid bearer token. Only reachable when the deployment enables auth (`AUTH_MODE=api_key`
+ or `AUTH_MODE=jwt`).
+ headers:
+ WWW-Authenticate:
+ description: Authentication challenge — always `Bearer`.
+ schema:
+ type: string
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/ProblemDocument'
+ '413':
+ description: Request body exceeds the deployment's size limit (`MAX_REQUEST_BODY_MIB`, 100 MiB by default).
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/ProblemDocument'
+ '422':
+ description: 'The request could not be processed: a malformed body, a field failing validation, or an `input`-domain
+ pipelex error (a `.mthds` bundle the caller must fix). Note that on the diagnostic routes an *invalid bundle*
+ is a **200** verdict, not a 422 — see each route''s response contract.'
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/ProblemDocument'
+ '500':
+ description: A `config`-domain or `runtime`-domain failure the caller cannot fix (a missing env var, a bad TOML
+ override, a backend fault), or an unclassified error sanitized by the catch-all handler. Report the `request_id`.
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/ProblemDocument'
+ '404':
+ description: '`MethodPackageNotFoundError` — the `method_ref` repository was fetched, but no package in it matches
+ the requested address by manifest identity. The message lists the packages the repository does contain.'
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/ProblemDocument'
+ '501':
+ description: '`MethodRefNotSupported` — the request selected its closure by a **registry-form** `method_ref` (not
+ a `github.com/...` address), and no server-side method registry resolves those yet. Use an address-form reference
+ or submit inline `files[]` instead.'
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/ProblemDocument'
+ /v1/pipe-io:
+ post:
+ tags:
+ - pipe-io
+ summary: Pipe Io
+ description: "Return a method's pipe I/O contracts, input form and output form, with no dry run (Pipelex API extension).\n\
+ \nThe closure resolves through the static core `/resolve` rides, a pipe is selected the way the\nper-pipe routes select\
+ \ one, and the three artifacts are derived with `build_pipe_io_artifacts`,\nthe builder `/validate` and every run\
+ \ call — so a call costs one load and one derivation where\n`/validate` dry-runs every pipe.\n\nResponse contract\
+ \ (the `/validate` discipline):\n\n- **Valid verdict (200, `is_valid: true`):** the three artifact maps keyed by qualified\
+ \ `pipe_ref`,\n beside `pipe_ref`, `default_pipe_ref`, `pending_signatures`, `is_runnable`, and `files` when\n `include_files`\
+ \ is true.\n- **Invalid verdict (200, `is_valid: false`):** the closure could not be parsed, loaded, or\n statically\
+ \ validated — the crate verdict, carrying no artifact, no selection and no files.\n- **No verdict (non-2xx):** a malformed\
+ \ body and neither or both closure selectors are\n request-shape 422s (`ValidationError`); a selection refusal is\
+ \ an input 422 named for its failure,\n `EntryPipeNotFoundError` for an unknown `pipe_ref` or a single-pipe request\
+ \ whose chain finds no\n entry pipe, `EntryPipeAmbiguousError` for an ambiguous one or a chain that finds several;\
+ \ the\n `method_ref` fetch outcomes are those of `/resolve` (404, 422, 501);\n an artifact that cannot be derived\
+ \ (`PipeIOContractError`) is a 500. All RFC 7807\n `application/problem+json` via the global handlers."
+ operationId: pipe_io_v1_pipe_io_post
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/PipeIORequest'
+ required: true
+ responses:
+ '200':
+ description: Successful Response
+ content:
+ application/json:
+ schema:
+ oneOf:
+ - $ref: '#/components/schemas/PipeIOValidReport'
+ - $ref: '#/components/schemas/CrateInvalidReport'
+ title: Response Pipe Io V1 Pipe Io Post
+ discriminator:
+ propertyName: is_valid
+ mapping:
+ 'True': '#/components/schemas/PipeIOValidReport'
+ 'False': '#/components/schemas/CrateInvalidReport'
+ '401':
+ description: Missing or invalid bearer token. Only reachable when the deployment enables auth (`AUTH_MODE=api_key`
+ or `AUTH_MODE=jwt`).
+ headers:
+ WWW-Authenticate:
+ description: Authentication challenge — always `Bearer`.
+ schema:
+ type: string
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/ProblemDocument'
+ '413':
+ description: Request body exceeds the deployment's size limit (`MAX_REQUEST_BODY_MIB`, 100 MiB by default).
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/ProblemDocument'
+ '422':
+ description: 'The request could not be processed: a malformed body, a field failing validation, or an `input`-domain
+ pipelex error (a `.mthds` bundle the caller must fix). Note that on the diagnostic routes an *invalid bundle*
+ is a **200** verdict, not a 422 — see each route''s response contract.'
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/ProblemDocument'
+ '500':
+ description: A `config`-domain or `runtime`-domain failure the caller cannot fix (a missing env var, a bad TOML
+ override, a backend fault), or an unclassified error sanitized by the catch-all handler. Report the `request_id`.
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/ProblemDocument'
+ '404':
+ description: '`MethodPackageNotFoundError` — the `method_ref` repository was fetched, but no package in it matches
+ the requested address by manifest identity. The message lists the packages the repository does contain.'
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/ProblemDocument'
+ '501':
+ description: '`MethodRefNotSupported` — the request selected its closure by a **registry-form** `method_ref` (not
+ a `github.com/...` address), and no server-side method registry resolves those yet. Use an address-form reference
+ or submit inline `files[]` instead.'
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/ProblemDocument'
+ /v1/codegen:
+ post:
+ tags:
+ - codegen
+ summary: Codegen Mthds
+ description: "Generate typed artifacts from a library closure (Pipelex API extension).\n\nResolves the closure to its\
+ \ normalized crate (exactly like `POST /resolve`), then projects it\nthrough the requested `kind`/`target` axes and\
+ \ returns the **stamped** artifact set plus its\n`codegen.lock` — everything a client needs to materialize a byte-identical\
+ \ local projection\nand run the offline drift check. There is deliberately **no** server-side check route: the\ncheck\
+ \ is offline by design.\n\nResponse contract (the `/validate` discipline):\n\n- **Valid verdict (200, `is_valid: true`):**\
+ \ the artifacts + lock on the valid arm.\n- **Invalid verdict (200, `is_valid: false`):** the library could not be\
+ \ parsed, loaded, or\n validated — `validation_errors[]` from pipelex's one shared builder; no artifacts exist.\n\
+ - **No verdict (non-2xx):** an unknown projection `kind`/`target`, a `pipe_ref` on a\n concept-set-wide kind, or\
+ \ a malformed closure selector is a request-shape 422 problem+json;\n `method_ref` is a 501 until server-side method\
+ \ registry resolution exists; auth is 401/403;\n server fault is 5xx."
+ operationId: codegen_mthds_v1_codegen_post
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/CodegenRequest'
+ required: true
+ responses:
+ '200':
+ description: Successful Response
+ content:
+ application/json:
+ schema:
+ oneOf:
+ - $ref: '#/components/schemas/CodegenValidReport'
+ - $ref: '#/components/schemas/CrateInvalidReport'
+ title: Response Codegen Mthds V1 Codegen Post
+ discriminator:
+ propertyName: is_valid
+ mapping:
+ 'True': '#/components/schemas/CodegenValidReport'
+ 'False': '#/components/schemas/CrateInvalidReport'
+ '401':
+ description: Missing or invalid bearer token. Only reachable when the deployment enables auth (`AUTH_MODE=api_key`
+ or `AUTH_MODE=jwt`).
+ headers:
+ WWW-Authenticate:
+ description: Authentication challenge — always `Bearer`.
+ schema:
+ type: string
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/ProblemDocument'
+ '413':
+ description: Request body exceeds the deployment's size limit (`MAX_REQUEST_BODY_MIB`, 100 MiB by default).
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/ProblemDocument'
+ '422':
+ description: 'The request could not be processed: a malformed body, a field failing validation, or an `input`-domain
+ pipelex error (a `.mthds` bundle the caller must fix). Note that on the diagnostic routes an *invalid bundle*
+ is a **200** verdict, not a 422 — see each route''s response contract.'
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/ProblemDocument'
+ '500':
+ description: A `config`-domain or `runtime`-domain failure the caller cannot fix (a missing env var, a bad TOML
+ override, a backend fault), or an unclassified error sanitized by the catch-all handler. Report the `request_id`.
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/ProblemDocument'
+ '404':
+ description: '`MethodPackageNotFoundError` — the `method_ref` repository was fetched, but no package in it matches
+ the requested address by manifest identity. The message lists the packages the repository does contain.'
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/ProblemDocument'
+ '501':
+ description: '`MethodRefNotSupported` — the request selected its closure by a **registry-form** `method_ref` (not
+ a `github.com/...` address), and no server-side method registry resolves those yet. Use an address-form reference
+ or submit inline `files[]` instead.'
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/ProblemDocument'
+ /v1/lint:
+ post:
+ tags:
+ - tools
+ summary: Lint Mthds
+ description: 'Lint one .mthds file with the embedded MTHDS schema.
+
+
+ Malformed .mthds content is a produced diagnostic verdict and returns 200.
+
+ Request-shape problems remain RFC 7807 422 responses through the global handlers.'
+ operationId: lint_mthds_v1_lint_post
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/LintRequest'
+ required: true
+ responses:
+ '200':
+ description: Successful Response
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/LintResponse'
+ '401':
+ description: Missing or invalid bearer token. Only reachable when the deployment enables auth (`AUTH_MODE=api_key`
+ or `AUTH_MODE=jwt`).
+ headers:
+ WWW-Authenticate:
+ description: Authentication challenge — always `Bearer`.
+ schema:
+ type: string
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/ProblemDocument'
+ '413':
+ description: Request body exceeds the deployment's size limit (`MAX_REQUEST_BODY_MIB`, 100 MiB by default).
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/ProblemDocument'
+ '422':
+ description: 'The request could not be processed: a malformed body, a field failing validation, or an `input`-domain
+ pipelex error (a `.mthds` bundle the caller must fix). Note that on the diagnostic routes an *invalid bundle*
+ is a **200** verdict, not a 422 — see each route''s response contract.'
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/ProblemDocument'
+ '500':
+ description: A `config`-domain or `runtime`-domain failure the caller cannot fix (a missing env var, a bad TOML
+ override, a backend fault), or an unclassified error sanitized by the catch-all handler. Report the `request_id`.
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/ProblemDocument'
+ /v1/format:
+ post:
+ tags:
+ - tools
+ summary: Format Mthds
+ description: 'Format one .mthds file with the canonical MTHDS formatter.
+
+
+ Syntax errors return 200 with diagnostics and unchanged content. Malformed
+
+ formatter options are caller input errors and return RFC 7807 422.'
+ operationId: format_mthds_v1_format_post
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/FormatRequest'
+ required: true
+ responses:
+ '200':
+ description: Successful Response
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/FormatResponse'
+ '401':
+ description: Missing or invalid bearer token. Only reachable when the deployment enables auth (`AUTH_MODE=api_key`
+ or `AUTH_MODE=jwt`).
+ headers:
+ WWW-Authenticate:
+ description: Authentication challenge — always `Bearer`.
+ schema:
+ type: string
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/ProblemDocument'
+ '413':
+ description: Request body exceeds the deployment's size limit (`MAX_REQUEST_BODY_MIB`, 100 MiB by default).
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/ProblemDocument'
+ '422':
+ description: 'The request could not be processed: a malformed body, a field failing validation, or an `input`-domain
+ pipelex error (a `.mthds` bundle the caller must fix). Note that on the diagnostic routes an *invalid bundle*
+ is a **200** verdict, not a 422 — see each route''s response contract.'
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/ProblemDocument'
+ '500':
+ description: A `config`-domain or `runtime`-domain failure the caller cannot fix (a missing env var, a bad TOML
+ override, a backend fault), or an unclassified error sanitized by the catch-all handler. Report the `request_id`.
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/ProblemDocument'
+ /v1/models:
+ get:
+ tags:
+ - agent
+ summary: Get Models
+ description: 'List the model deck this runner can route to (MTHDS Protocol `GET /models`).
+
+
+ Answers the protocol `ModelDeck` as produced by `PipelexMTHDSProtocol.models` —
+
+ the flat `models` list (`{name, type}` entries) plus this implementation''s
+
+ category-keyed routing extensions (`aliases`, `waterfalls`). The `type` query
+
+ param is a SINGLE protocol `ModelCategory` value: repeated `?type=` values
+
+ (arity, `ValidationError`) and unknown categories (`InvalidModelCategory`) are
+
+ both 422s (RFC 7807).'
+ operationId: get_models_v1_models_get
+ parameters:
+ - name: type
+ in: query
+ required: false
+ schema:
+ anyOf:
+ - type: string
+ - type: 'null'
+ description: 'Filter by model category: llm, extract, img_gen, search. Single value (protocol arity).'
+ title: Type
+ description: 'Filter by model category: llm, extract, img_gen, search. Single value (protocol arity).'
+ responses:
+ '200':
+ description: Successful Response
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/PipelexModelDeck'
+ '401':
+ description: Missing or invalid bearer token. Only reachable when the deployment enables auth (`AUTH_MODE=api_key`
+ or `AUTH_MODE=jwt`).
+ headers:
+ WWW-Authenticate:
+ description: Authentication challenge — always `Bearer`.
+ schema:
+ type: string
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/ProblemDocument'
+ '413':
+ description: Request body exceeds the deployment's size limit (`MAX_REQUEST_BODY_MIB`, 100 MiB by default).
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/ProblemDocument'
+ '422':
+ description: 'The request could not be processed: a malformed body, a field failing validation, or an `input`-domain
+ pipelex error (a `.mthds` bundle the caller must fix). Note that on the diagnostic routes an *invalid bundle*
+ is a **200** verdict, not a 422 — see each route''s response contract.'
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/ProblemDocument'
+ '500':
+ description: A `config`-domain or `runtime`-domain failure the caller cannot fix (a missing env var, a bad TOML
+ override, a backend fault), or an unclassified error sanitized by the catch-all handler. Report the `request_id`.
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/ProblemDocument'
+ x-mthds-protocol: true
+ /v1/build/concept:
+ post:
+ tags:
+ - agent
+ summary: Build Concept
+ description: 'Convert a JSON concept spec to TOML format.
+
+
+ A malformed spec surfaces as a Pydantic `ValidationError` — an API-owned
+
+ 422. Pipelex domain failures propagate untouched to the global
+
+ `PipelexError` handler in `pipelex_api.exception_handlers`.
+
+
+ A malformed shape — a non-mapping `structure` (`{"structure": "string"}`)
+
+ or a `structure` field that is neither a string nor a mapping
+
+ (`{"structure": {"f": 42}}`) — is refused by `parse_concept_spec` itself
+
+ with a typed `ConceptSpecError`, which that same handler answers. Nothing
+
+ broader is caught here: a bare exception from pipelex is the signal of a
+
+ real programming bug, and a route-level catch would mask it.'
+ operationId: build_concept_v1_build_concept_post
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/BuildConceptRequest'
+ required: true
+ responses:
+ '200':
+ description: Successful Response
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/BuildConceptResponse'
+ '401':
+ description: Missing or invalid bearer token. Only reachable when the deployment enables auth (`AUTH_MODE=api_key`
+ or `AUTH_MODE=jwt`).
+ headers:
+ WWW-Authenticate:
+ description: Authentication challenge — always `Bearer`.
+ schema:
+ type: string
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/ProblemDocument'
+ '413':
+ description: Request body exceeds the deployment's size limit (`MAX_REQUEST_BODY_MIB`, 100 MiB by default).
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/ProblemDocument'
+ '422':
+ description: 'The request could not be processed: a malformed body, a field failing validation, or an `input`-domain
+ pipelex error (a `.mthds` bundle the caller must fix). Note that on the diagnostic routes an *invalid bundle*
+ is a **200** verdict, not a 422 — see each route''s response contract.'
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/ProblemDocument'
+ '500':
+ description: A `config`-domain or `runtime`-domain failure the caller cannot fix (a missing env var, a bad TOML
+ override, a backend fault), or an unclassified error sanitized by the catch-all handler. Report the `request_id`.
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/ProblemDocument'
+ /v1/build/pipe-spec:
+ post:
+ tags:
+ - agent
+ summary: Build Pipe Spec
+ description: 'Convert a JSON pipe spec to TOML format.
+
+
+ Two caller-mistake paths surface as a 422 here: a `ValidationError` from
+
+ Pydantic when the spec shape doesn''t match the chosen pipe type, and a
+
+ `ValueError` from `parse_pipe_spec` when `pipe_type` is not one of the
+
+ known pipe types (documented in `parse_pipe_spec`''s docstring; raised at
+
+ exactly one site). Pipelex domain failures propagate untouched to the
+
+ global `PipelexError` handler in `pipelex_api.exception_handlers`.'
+ operationId: build_pipe_spec_v1_build_pipe_spec_post
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/BuildPipeSpecRequest'
+ required: true
+ responses:
+ '200':
+ description: Successful Response
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/BuildPipeSpecResponse'
+ '401':
+ description: Missing or invalid bearer token. Only reachable when the deployment enables auth (`AUTH_MODE=api_key`
+ or `AUTH_MODE=jwt`).
+ headers:
+ WWW-Authenticate:
+ description: Authentication challenge — always `Bearer`.
+ schema:
+ type: string
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/ProblemDocument'
+ '413':
+ description: Request body exceeds the deployment's size limit (`MAX_REQUEST_BODY_MIB`, 100 MiB by default).
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/ProblemDocument'
+ '422':
+ description: 'The request could not be processed: a malformed body, a field failing validation, or an `input`-domain
+ pipelex error (a `.mthds` bundle the caller must fix). Note that on the diagnostic routes an *invalid bundle*
+ is a **200** verdict, not a 422 — see each route''s response contract.'
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/ProblemDocument'
+ '500':
+ description: A `config`-domain or `runtime`-domain failure the caller cannot fix (a missing env var, a bad TOML
+ override, a backend fault), or an unclassified error sanitized by the catch-all handler. Report the `request_id`.
+ content:
+ application/problem+json:
+ schema:
+ $ref: '#/components/schemas/ProblemDocument'
+ /:
+ get:
+ tags:
+ - health
+ summary: Service identity banner
+ description: 'Identify the service answering on this origin. No auth required.
+
+
+ A human-facing banner for someone who lands on the bare origin — not a
+
+ liveness probe (that is `GET /health`) and not the protocol handshake
+
+ (`GET /v1/version`). It reads nothing and can only succeed.'
+ operationId: root__get
+ responses:
+ '200':
+ description: Successful Response
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ServiceIdentity'
+components:
+ schemas:
+ AbsenceKind:
+ type: string
+ enum:
+ - declared_absent
+ - skipped
+ - not_provided
+ title: AbsenceKind
+ description: "How a slot came to hold no value.\n\n- DECLARED_ABSENT: a producer with an optional (`?`) output declared\
+ \ it produced nothing\n (e.g. a PipeCondition `continue` outcome, or — phase 2 — an LLM maybe-wrapper).\n- SKIPPED:\
+ \ the producing pipe was lifted (skipped) because one of its plain inputs was absent.\n- NOT_PROVIDED: the caller\
+ \ omitted an optional method input from the pipeline inputs."
+ AbsenceRecord:
+ properties:
+ variable_name:
+ type: string
+ title: Variable Name
+ kind:
+ $ref: '#/components/schemas/AbsenceKind'
+ reason:
+ type: string
+ title: Reason
+ producing_pipe:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Producing Pipe
+ upstream:
+ anyOf:
+ - $ref: '#/components/schemas/AbsenceRecord'
+ - type: 'null'
+ additionalProperties: false
+ type: object
+ required:
+ - variable_name
+ - kind
+ - reason
+ title: AbsenceRecord
+ description: 'A recorded fact that a named slot holds no value, with provenance (D2).
+
+
+ Absence stays what it mechanically is — no Stuff under the name — but becomes a recorded
+
+ fact: who produced it, why, and which upstream absence it chains to. Provenance is captured
+
+ at the moment absence is produced, not reconstructed at failure time.'
+ AspectRatio:
+ type: string
+ enum:
+ - square
+ - landscape_4_3
+ - landscape_3_2
+ - landscape_16_9
+ - landscape_21_9
+ - landscape_4_1
+ - landscape_8_1
+ - portrait_3_4
+ - portrait_2_3
+ - portrait_9_16
+ - portrait_9_21
+ - portrait_1_4
+ - portrait_1_8
+ title: AspectRatio
+ Background:
+ type: string
+ enum:
+ - transparent
+ - opaque
+ - auto
+ title: Background
+ BooleanField:
+ properties:
+ title:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Title
+ concept_ref:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Concept Ref
+ refines:
+ anyOf:
+ - items:
+ type: string
+ type: array
+ - type: 'null'
+ title: Refines
+ description:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Description
+ required:
+ type: boolean
+ title: Required
+ presence:
+ anyOf:
+ - $ref: '#/components/schemas/PresenceMarker'
+ - type: 'null'
+ gating:
+ anyOf:
+ - type: boolean
+ - type: 'null'
+ title: Gating
+ default_value:
+ title: Default Value
+ examples:
+ anyOf:
+ - items: {}
+ type: array
+ - type: 'null'
+ title: Examples
+ hints:
+ anyOf:
+ - additionalProperties:
+ type: string
+ type: object
+ - type: 'null'
+ title: Hints
+ kind:
+ type: string
+ const: boolean
+ title: Kind
+ default: boolean
+ name:
+ type: string
+ title: Name
+ additionalProperties: false
+ type: object
+ required:
+ - required
+ - name
+ title: BooleanField
+ description: '`boolean` at a named position.'
+ BooleanItem:
+ properties:
+ title:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Title
+ concept_ref:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Concept Ref
+ refines:
+ anyOf:
+ - items:
+ type: string
+ type: array
+ - type: 'null'
+ title: Refines
+ description:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Description
+ required:
+ type: boolean
+ title: Required
+ presence:
+ anyOf:
+ - $ref: '#/components/schemas/PresenceMarker'
+ - type: 'null'
+ gating:
+ anyOf:
+ - type: boolean
+ - type: 'null'
+ title: Gating
+ default_value:
+ title: Default Value
+ examples:
+ anyOf:
+ - items: {}
+ type: array
+ - type: 'null'
+ title: Examples
+ hints:
+ anyOf:
+ - additionalProperties:
+ type: string
+ type: object
+ - type: 'null'
+ title: Hints
+ kind:
+ type: string
+ const: boolean
+ title: Kind
+ default: boolean
+ additionalProperties: false
+ type: object
+ required:
+ - required
+ title: BooleanItem
+ description: '`boolean` — true or false.'
+ BuildConceptRequest:
+ properties:
+ spec:
+ additionalProperties: true
+ type: object
+ title: Spec
+ description: JSON concept specification.
+ type: object
+ required:
+ - spec
+ title: BuildConceptRequest
+ BuildConceptResponse:
+ properties:
+ success:
+ type: boolean
+ title: Success
+ description: Whether the operation was successful
+ default: true
+ concept_code:
+ type: string
+ title: Concept Code
+ description: The concept code that was generated
+ toml:
+ type: string
+ title: Toml
+ description: Generated TOML content for the concept
+ type: object
+ required:
+ - concept_code
+ - toml
+ title: BuildConceptResponse
+ BuildInputsRequest:
+ properties:
+ files:
+ anyOf:
+ - items:
+ $ref: '#/components/schemas/MthdsFileItem'
+ type: array
+ maxItems: 16
+ minItems: 1
+ - type: 'null'
+ title: Files
+ description: Inline MTHDS bundles forming the closure to resolve (content-passing — no server-side path reads).
+ method_ref:
+ anyOf:
+ - type: string
+ maxLength: 512
+ minLength: 1
+ - type: 'null'
+ title: Method Ref
+ description: Reference to a published method, resolving to its package's `.mthds` files. Address form (`github.com/<owner>/<repo>[/<selector>][@<tag>]`)
+ is fetched and resolved server-side; the registry form stays reserved (501 until a method registry exists).
+ pipe_ref:
+ anyOf:
+ - type: string
+ maxLength: 256
+ minLength: 1
+ - type: 'null'
+ title: Pipe Ref
+ description: Qualified pipe ref (`domain.pipe_code`) to project. Optional — defaults to the fetched package manifest's
+ `main_pipe` on a `method_ref` request, else to the closure's declared `main_pipe`; a closure declaring none, or
+ several, with no manifest `main_pipe` to settle it, requires it explicitly.
+ format:
+ $ref: '#/components/schemas/InputsTemplateFormat'
+ description: Template encoding. `json` returns the parsed template in `inputs`; `toml` returns the raw text in `inputs_toml`.
+ default: json
+ explicit:
+ type: boolean
+ title: Explicit
+ description: When true, emit the ceremonial `{concept, content}` envelope for every input. Defaults to false — the
+ light, signature-driven shape that smart inputs accepts (a bare string for a Text input, and so on).
+ default: false
+ type: object
+ title: BuildInputsRequest
+ description: 'The inputs-template request: the shared closure + pipe selectors, plus the two rendering axes.
+
+
+ Both axes mirror `pipelex codegen inputs` exactly — `--format` and `--explicit` — and every
+
+ combination of them is served, as on the CLI.'
+ BuildInputsValidReport:
+ properties:
+ is_valid:
+ type: boolean
+ const: true
+ title: Is Valid
+ default: true
+ pipe_ref:
+ type: string
+ title: Pipe Ref
+ description: The qualified pipe the template was generated for — the resolved selector.
+ requested_pipe_ref:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Requested Pipe Ref
+ description: The `pipe_ref` as submitted. Absent when it was omitted and defaulted — to the fetched package manifest's
+ `main_pipe` on a `method_ref` request, else to the closure's declared `main_pipe`.
+ format:
+ $ref: '#/components/schemas/InputsTemplateFormat'
+ description: The template encoding (echo of the request).
+ explicit:
+ type: boolean
+ title: Explicit
+ description: Whether the ceremonial envelope shape was emitted (echo of the request).
+ inputs:
+ anyOf:
+ - additionalProperties: true
+ type: object
+ - type: 'null'
+ title: Inputs
+ description: The parsed inputs template — present exactly when `format` is `json`.
+ inputs_toml:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Inputs Toml
+ description: The inputs template as TOML text — present exactly when `format` is `toml`.
+ message:
+ type: string
+ title: Message
+ description: Status message
+ default: Inputs template generated successfully
+ type: object
+ required:
+ - pipe_ref
+ - format
+ - explicit
+ title: BuildInputsValidReport
+ description: 'The 200 **valid** arm: the example inputs template for the requested pipe.
+
+
+ The template rides **one of two fields, chosen by `format`** — `inputs` (parsed object) for
+
+ `json`, `inputs_toml` (raw text) for `toml`. TOML cannot be carried as a parsed object without
+
+ losing what makes it worth asking for (its concept comments and key order), and the JSON case
+
+ must stay a real object, since that is what the deploy dialog and the SDKs consume. So the two
+
+ are separate, honestly-typed fields, and the unused one is omitted from the body entirely.
+
+
+ A pipe that declares no inputs is a *valid* verdict, not an error (the CLI likewise exits 0):
+
+ the template is simply empty, and `message` says so.'
+ BuildOutputRequest:
+ properties:
+ files:
+ anyOf:
+ - items:
+ $ref: '#/components/schemas/MthdsFileItem'
+ type: array
+ maxItems: 16
+ minItems: 1
+ - type: 'null'
+ title: Files
+ description: Inline MTHDS bundles forming the closure to resolve (content-passing — no server-side path reads).
+ method_ref:
+ anyOf:
+ - type: string
+ maxLength: 512
+ minLength: 1
+ - type: 'null'
+ title: Method Ref
+ description: Reference to a published method, resolving to its package's `.mthds` files. Address form (`github.com/<owner>/<repo>[/<selector>][@<tag>]`)
+ is fetched and resolved server-side; the registry form stays reserved (501 until a method registry exists).
+ pipe_ref:
+ anyOf:
+ - type: string
+ maxLength: 256
+ minLength: 1
+ - type: 'null'
+ title: Pipe Ref
+ description: Qualified pipe ref (`domain.pipe_code`) to project. Optional — defaults to the fetched package manifest's
+ `main_pipe` on a `method_ref` request, else to the closure's declared `main_pipe`; a closure declaring none, or
+ several, with no manifest `main_pipe` to settle it, requires it explicitly.
+ format:
+ $ref: '#/components/schemas/ConceptRepresentationFormat'
+ description: Representation to render. `schema` (JSON Schema) and `json` (example value) return a parsed object
+ in `output`; `python` returns Python source in `output_python`.
+ default: schema
+ type: object
+ title: BuildOutputRequest
+ description: 'The output-representation request: the shared closure + pipe selectors, plus the format axis.'
+ BuildOutputValidReport:
+ properties:
+ is_valid:
+ type: boolean
+ const: true
+ title: Is Valid
+ default: true
+ pipe_ref:
+ type: string
+ title: Pipe Ref
+ description: The qualified pipe the representation was generated for — the resolved selector.
+ requested_pipe_ref:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Requested Pipe Ref
+ description: The `pipe_ref` as submitted. Absent when it was omitted and defaulted — to the fetched package manifest's
+ `main_pipe` on a `method_ref` request, else to the closure's declared `main_pipe`.
+ format:
+ $ref: '#/components/schemas/ConceptRepresentationFormat'
+ description: The representation format (echo of the request).
+ output:
+ anyOf:
+ - additionalProperties: true
+ type: object
+ - type: 'null'
+ title: Output
+ description: The parsed output representation — present exactly when `format` is `schema` or `json`.
+ output_python:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Output Python
+ description: The output representation as Python source — present exactly when `format` is `python`.
+ message:
+ type: string
+ title: Message
+ description: Status message
+ default: Output representation generated successfully
+ type: object
+ required:
+ - pipe_ref
+ - format
+ title: BuildOutputValidReport
+ description: 'The 200 **valid** arm: the example output representation for the requested pipe.
+
+
+ The representation rides **one of two fields, chosen by `format`**, for the same reason
+
+ `/build/inputs` splits `inputs` / `inputs_toml`: `schema` and `json` are objects, `python` is
+
+ source text. (Before this split the route parsed *every* format as JSON, so `format=python` was a
+
+ hard 500 — it fed Python source to `json.loads`.)'
+ BuildPipeSpecRequest:
+ properties:
+ pipe_type:
+ type: string
+ maxLength: 128
+ minLength: 1
+ title: Pipe Type
+ description: The pipe type (e.g. PipeLLM, PipeSequence, etc.).
+ spec:
+ additionalProperties: true
+ type: object
+ title: Spec
+ description: JSON pipe specification.
+ type: object
+ required:
+ - pipe_type
+ - spec
+ title: BuildPipeSpecRequest
+ BuildPipeSpecResponse:
+ properties:
+ success:
+ type: boolean
+ title: Success
+ description: Whether the operation was successful
+ default: true
+ pipe_code:
+ type: string
+ title: Pipe Code
+ description: The pipe code that was generated
+ pipe_type:
+ type: string
+ title: Pipe Type
+ description: The pipe type
+ toml:
+ type: string
+ title: Toml
+ description: Generated TOML content for the pipe
+ type: object
+ required:
+ - pipe_code
+ - pipe_type
+ - toml
+ title: BuildPipeSpecResponse
+ BuildRunnerRequest:
+ properties:
+ analytics_groups:
+ anyOf:
+ - additionalProperties:
+ type: string
+ type: object
+ - type: 'null'
+ title: Analytics Groups
+ description: 'PIPELEX-API EXTENSION (not part of the MTHDS Protocol) — the host-supplied groups the caller of this
+ request belongs to, as a mapping of group type to group key (e.g. `{"organization": "org_acme"}`), exactly as
+ a run request states them. The work this request does is not a run, but it still emits telemetry — the validation
+ sweep''s `pipe_dry_run` event and its dry runs — and that telemetry is attributed to the caller: the authenticated
+ user and these groups. Same rules and same 422 `InvalidAnalyticsGroups` refusal as on `/execute` and `/start`.
+ Omit it and the caller belongs to no group.'
+ files:
+ anyOf:
+ - items:
+ $ref: '#/components/schemas/MthdsFileItem'
+ type: array
+ maxItems: 16
+ minItems: 1
+ - type: 'null'
+ title: Files
+ description: Inline MTHDS bundles forming the closure to resolve (content-passing — no server-side path reads).
+ method_ref:
+ anyOf:
+ - type: string
+ maxLength: 512
+ minLength: 1
+ - type: 'null'
+ title: Method Ref
+ description: Reference to a published method, resolving to its package's `.mthds` files. Address form (`github.com/<owner>/<repo>[/<selector>][@<tag>]`)
+ is fetched and resolved server-side; the registry form stays reserved (501 until a method registry exists).
+ pipe_ref:
+ anyOf:
+ - type: string
+ maxLength: 256
+ minLength: 1
+ - type: 'null'
+ title: Pipe Ref
+ description: Qualified pipe ref (`domain.pipe_code`) to project. Optional — defaults to the fetched package manifest's
+ `main_pipe` on a `method_ref` request, else to the closure's declared `main_pipe`; a closure declaring none, or
+ several, with no manifest `main_pipe` to settle it, requires it explicitly.
+ allow_signatures:
+ type: boolean
+ title: Allow Signatures
+ description: When true, the validation sweep tolerates unimplemented pipe signatures instead of rejecting the bundle
+ (signatures dry-run trivially by minting a mock). Defaults to false (strict).
+ default: false
+ type: object
+ title: BuildRunnerRequest
+ description: 'The runner-script request: the shared closure + pipe selectors, plus the sweep''s `allow_signatures`.
+
+
+ Alone among the `/build/*` projections this route keeps `allow_signatures`, because alone among
+
+ them it still runs the dry-run sweep — the flag only ever parameterized that sweep.'
+ BuildRunnerValidReport:
+ properties:
+ is_valid:
+ type: boolean
+ const: true
+ title: Is Valid
+ default: true
+ pipe_ref:
+ type: string
+ title: Pipe Ref
+ description: The qualified pipe the runner was generated for — the resolved selector.
+ requested_pipe_ref:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Requested Pipe Ref
+ description: The `pipe_ref` as submitted. Absent when it was omitted and defaulted — to the fetched package manifest's
+ `main_pipe` on a `method_ref` request, else to the closure's declared `main_pipe`.
+ python_code:
+ type: string
+ title: Python Code
+ description: Generated Python script for running the pipeline, imports spelled with the emitted class names.
+ structures:
+ $ref: '#/components/schemas/RunnerStructures'
+ description: The typed-structures projection the script imports from.
+ message:
+ type: string
+ title: Message
+ description: Status message
+ default: Runner code generated successfully
+ type: object
+ required:
+ - pipe_ref
+ - python_code
+ - structures
+ title: BuildRunnerValidReport
+ description: 'The 200 **valid** arm: the runner script plus the structures projection it imports from.'
+ CodegenRequest:
+ properties:
+ files:
+ anyOf:
+ - items:
+ $ref: '#/components/schemas/MthdsFileItem'
+ type: array
+ maxItems: 16
+ minItems: 1
+ - type: 'null'
+ title: Files
+ description: Inline MTHDS bundles forming the closure to resolve (content-passing — no server-side path reads).
+ method_ref:
+ anyOf:
+ - type: string
+ maxLength: 512
+ minLength: 1
+ - type: 'null'
+ title: Method Ref
+ description: Reference to a published method, resolving to its package's `.mthds` files. Address form (`github.com/<owner>/<repo>[/<selector>][@<tag>]`)
+ is fetched and resolved server-side; the registry form stays reserved (501 until a method registry exists).
+ kind:
+ $ref: '#/components/schemas/CodegenRouteKind'
+ description: What to project. `types` projects the crate's concept set into typed models.
+ target:
+ $ref: '#/components/schemas/CodegenTarget'
+ description: 'For whom: `ts-zod` (zod schemas + inferred types), `python-pydantic` (self-contained BaseModels),
+ or `python-structures` (runtime StructuredContent classes, for a Pipelex host).'
+ pipe_ref:
+ anyOf:
+ - type: string
+ maxLength: 512
+ - type: 'null'
+ title: Pipe Ref
+ description: Pipe selector for per-pipe projection kinds. Not accepted for `types` (a concept-set-wide projection).
+ type: object
+ required:
+ - kind
+ - target
+ title: CodegenRequest
+ description: 'The codegen request: the shared closure selector plus the two explicit projection axes.'
+ CodegenRouteKind:
+ type: string
+ enum:
+ - types
+ title: CodegenRouteKind
+ description: 'The projection kinds this route serves — the `kind` axis of the codegen request.
+
+
+ Membership follows the **trust chain**: a kind is served here exactly when its artifacts are
+
+ stamped and locked, so a client can write them verbatim and pass the offline `codegen check` —
+
+ the promise this route''s valid arm makes by carrying a `lock`. Input templates are user-editable
+
+ scaffolds, never stamped or locked, so they cannot make that promise; they ride
+
+ `POST /build/inputs` instead and `inputs` is therefore not a kind here. Future per-pipe kinds
+
+ (`docs`, `tools`, `tests`) do emit tracked artifacts, so they join this enum and select their
+
+ pipe via `pipe_ref`. An unknown kind is a request-shape 422 listing the served set.'
+ CodegenTarget:
+ type: string
+ enum:
+ - python-structures
+ - python-pydantic
+ - ts-zod
+ title: CodegenTarget
+ description: 'A codegen target flavor. All targets are Pipelex projections — the MTHDS standard specifies no
+
+ type projection (see the codegen spec → "Ownership"). They differ in audience:
+
+ `ts-zod` and `python-pydantic` emit idiom-neutral types any consumer can use; `python-structures`
+
+ emits StructuredContent classes for a Pipelex runtime host.'
+ CodegenValidReport:
+ properties:
+ is_valid:
+ type: boolean
+ const: true
+ title: Is Valid
+ default: true
+ kind:
+ $ref: '#/components/schemas/CodegenRouteKind'
+ description: The projected kind (echo of the request).
+ target:
+ $ref: '#/components/schemas/CodegenTarget'
+ description: The projection target (echo of the request).
+ crate_fingerprint:
+ type: string
+ title: Crate Fingerprint
+ description: Fingerprint of the normalized crate the artifacts were generated from.
+ engine_version:
+ type: string
+ title: Engine Version
+ description: The pipelex engine version that generated the artifacts.
+ artifacts:
+ items:
+ $ref: '#/components/schemas/GeneratedArtifact'
+ type: array
+ title: Artifacts
+ description: The stamped generated files.
+ lock:
+ type: string
+ title: Lock
+ description: The `codegen.lock` content (TOML) tracking the artifact set — write verbatim beside the artifacts.
+ lock_filename:
+ type: string
+ title: Lock Filename
+ description: Filename the lock content must be written as.
+ default: codegen.lock
+ message:
+ type: string
+ title: Message
+ description: Status message
+ default: Codegen artifacts generated successfully
+ type: object
+ required:
+ - kind
+ - target
+ - crate_fingerprint
+ - engine_version
+ - lock
+ title: CodegenValidReport
+ description: 'The 200 **valid** arm: the stamped artifact set plus its lock.
+
+
+ A client that writes each artifact and the lock verbatim reproduces a local
+
+ `pipelex codegen types` run byte-for-byte — the same stamps, the same `codegen.lock` — so the
+
+ offline `codegen check` passes on the written tree exactly as it would locally.'
+ Concept:
+ properties:
+ code:
+ type: string
+ title: Code
+ domain_code:
+ type: string
+ title: Domain Code
+ description:
+ type: string
+ title: Description
+ structure_class_name:
+ type: string
+ title: Structure Class Name
+ refines:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Refines
+ additionalProperties: false
+ type: object
+ required:
+ - code
+ - domain_code
+ - description
+ - structure_class_name
+ title: Concept
+ description: 'A concept as the runtime holds it in memory: its name and its definition.
+
+
+ The protocol model, `ConceptAbstract`, is a name and nothing more — `code`, `domain_code`
+
+ and the `concept_ref` they form — because the standard keeps a concept''s definition in the
+
+ library a method loads, never beside a stuff. The runtime needs the definition in memory to
+
+ resolve a structure class, check compatibility and render a representation, so it declares
+
+ those fields here, on its own subclass.
+
+
+ The fields declared here never travel beside a stuff: `StuffAbstract` serializes `concept`
+
+ as the ref string, so every dump of a `Stuff`, of a `WorkingMemory` and of a `PipeOutput`
+
+ carries `{"concept": "<domain>.<Code>", "content": …}`. A reader of such a dump resolves the
+
+ ref through the concept library the method loads, the way the input side does.'
+ ConceptBlueprint:
+ properties:
+ source:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Source
+ description:
+ type: string
+ title: Description
+ structure:
+ anyOf:
+ - type: string
+ - additionalProperties:
+ anyOf:
+ - type: string
+ - $ref: '#/components/schemas/ConceptStructureBlueprint'
+ type: object
+ - type: 'null'
+ title: Structure
+ refines:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Refines
+ hints:
+ anyOf:
+ - additionalProperties:
+ type: string
+ type: object
+ - type: 'null'
+ title: Hints
+ additionalProperties: false
+ type: object
+ required:
+ - description
+ title: ConceptBlueprint
+ ConceptRepresentationFormat:
+ type: string
+ enum:
+ - json
+ - python
+ - schema
+ title: ConceptRepresentationFormat
+ description: Output format for concept representations.
+ ConceptStructureBlueprint:
+ properties:
+ description:
+ type: string
+ title: Description
+ type:
+ anyOf:
+ - $ref: '#/components/schemas/ConceptStructureBlueprintFieldType'
+ - type: 'null'
+ key_type:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Key Type
+ value_type:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Value Type
+ item_type:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Item Type
+ concept_ref:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Concept Ref
+ item_concept_ref:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Item Concept Ref
+ choices:
+ anyOf:
+ - items:
+ type: string
+ type: array
+ - type: 'null'
+ title: Choices
+ default_value:
+ anyOf:
+ - {}
+ - type: 'null'
+ title: Default Value
+ required:
+ type: boolean
+ title: Required
+ default: false
+ hints:
+ anyOf:
+ - additionalProperties:
+ type: string
+ type: object
+ - type: 'null'
+ title: Hints
+ additionalProperties: false
+ type: object
+ required:
+ - description
+ title: ConceptStructureBlueprint
+ description: 'One field of a concept''s structure table. Unknown keys are rejected — the field table''s
+
+ keys are strict, exactly like an input slot table''s; hint *content* stays lenient (unknown
+
+ hint keys warn and are preserved, per intent-hints.md).'
+ ConceptStructureBlueprintFieldType:
+ type: string
+ enum:
+ - text
+ - list
+ - dict
+ - integer
+ - boolean
+ - number
+ - date
+ - datetime
+ - time
+ - concept
+ title: ConceptStructureBlueprintFieldType
+ ConstructBlueprint:
+ properties:
+ fields:
+ additionalProperties:
+ $ref: '#/components/schemas/ConstructFieldBlueprint'
+ type: object
+ title: Fields
+ additionalProperties: false
+ type: object
+ required:
+ - fields
+ title: ConstructBlueprint
+ description: "Blueprint for composing a StructuredContent from working memory.\n\nParsed from `[pipe.name.construct]`\
+ \ section in MTHDS files.\n\nAttributes:\n fields: Dictionary mapping field names to their composition blueprints"
+ ConstructFieldBlueprint:
+ properties:
+ method:
+ $ref: '#/components/schemas/ConstructFieldMethod'
+ fixed_value:
+ anyOf:
+ - {}
+ - type: 'null'
+ title: Fixed Value
+ from_path:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: From Path
+ template:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Template
+ nested:
+ anyOf:
+ - $ref: '#/components/schemas/ConstructBlueprint'
+ - type: 'null'
+ list_to_dict_keyed_by:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: List To Dict Keyed By
+ additionalProperties: false
+ type: object
+ required:
+ - method
+ title: ConstructFieldBlueprint
+ description: "Blueprint for composing a single field in a StructuredContent.\n\nDefines how a field value is composed\
+ \ using one of 4 methods:\n1. Fixed value: literal string, number, bool, or list\n2. Variable reference (from): path\
+ \ to variable in working memory\n3. Template: Jinja2 template string (with $ preprocessing)\n4. Nested construct:\
+ \ recursive ConstructBlueprint\n\nAttributes:\n method: The composition method to use\n fixed_value: Literal\
+ \ value (for FIXED method)\n from_path: Variable path in working memory (for FROM_VAR method)\n template: Jinja2\
+ \ template string (for TEMPLATE method)\n nested: Nested ConstructBlueprint (for NESTED method)\n list_to_dict_keyed_by:\
+ \ Optional modifier for FROM_VAR method that converts\n a ListContent/list to dict keyed by the specified attribute\
+ \ name"
+ ConstructFieldMethod:
+ type: string
+ enum:
+ - fixed
+ - from_var
+ - template
+ - nested
+ title: ConstructFieldMethod
+ description: Method used to compose a field value.
+ CrateInvalidReport:
+ properties:
+ is_valid:
+ type: boolean
+ const: false
+ title: Is Valid
+ default: false
+ validation_errors:
+ items:
+ $ref: '#/components/schemas/ValidationErrorItem'
+ type: array
+ title: Validation Errors
+ description: Per-error diagnostics, built by pipelex's one shared builder — non-empty on every invalid verdict.
+ message:
+ type: string
+ title: Message
+ description: Human-readable summary of the verdict.
+ default: MTHDS library could not be resolved
+ type: object
+ title: CrateInvalidReport
+ description: 'The 200 **invalid** arm shared by `/resolve` and `/codegen` — the crate-verdict vocabulary.
+
+
+ Same discipline as `/validate`''s `InvalidReport`: an invalid library is the *successful
+
+ product* of a diagnostic call (the request was well-formed; the library was not), so it rides
+
+ a 200 discriminated on `is_valid`, carrying the same structured `ValidationErrorItem`s the
+
+ local CLI and `/validate` emit for the identical failure.'
+ DateField:
+ properties:
+ title:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Title
+ concept_ref:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Concept Ref
+ refines:
+ anyOf:
+ - items:
+ type: string
+ type: array
+ - type: 'null'
+ title: Refines
+ description:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Description
+ required:
+ type: boolean
+ title: Required
+ presence:
+ anyOf:
+ - $ref: '#/components/schemas/PresenceMarker'
+ - type: 'null'
+ gating:
+ anyOf:
+ - type: boolean
+ - type: 'null'
+ title: Gating
+ default_value:
+ title: Default Value
+ examples:
+ anyOf:
+ - items: {}
+ type: array
+ - type: 'null'
+ title: Examples
+ hints:
+ anyOf:
+ - additionalProperties:
+ type: string
+ type: object
+ - type: 'null'
+ title: Hints
+ kind:
+ type: string
+ const: date
+ title: Kind
+ default: date
+ datetime:
+ type: boolean
+ title: Datetime
+ name:
+ type: string
+ title: Name
+ additionalProperties: false
+ type: object
+ required:
+ - required
+ - datetime
+ - name
+ title: DateField
+ description: '`date` at a named position.'
+ DateItem:
+ properties:
+ title:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Title
+ concept_ref:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Concept Ref
+ refines:
+ anyOf:
+ - items:
+ type: string
+ type: array
+ - type: 'null'
+ title: Refines
+ description:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Description
+ required:
+ type: boolean
+ title: Required
+ presence:
+ anyOf:
+ - $ref: '#/components/schemas/PresenceMarker'
+ - type: 'null'
+ gating:
+ anyOf:
+ - type: boolean
+ - type: 'null'
+ title: Gating
+ default_value:
+ title: Default Value
+ examples:
+ anyOf:
+ - items: {}
+ type: array
+ - type: 'null'
+ title: Examples
+ hints:
+ anyOf:
+ - additionalProperties:
+ type: string
+ type: object
+ - type: 'null'
+ title: Hints
+ kind:
+ type: string
+ const: date
+ title: Kind
+ default: date
+ datetime:
+ type: boolean
+ title: Datetime
+ additionalProperties: false
+ type: object
+ required:
+ - required
+ - datetime
+ title: DateItem
+ description: '`date` — a calendar date, or a point in time.'
+ DeleteKeyOp:
+ properties:
+ table_path:
+ items:
+ type: string
+ type: array
+ title: Table Path
+ kind:
+ type: string
+ const: delete_key
+ title: Kind
+ default: delete_key
+ key:
+ type: string
+ title: Key
+ additionalProperties: false
+ type: object
+ required:
+ - table_path
+ - key
+ title: DeleteKeyOp
+ description: Drop ``key`` from the addressed table.
+ DeleteTableOp:
+ properties:
+ table_path:
+ items:
+ type: string
+ type: array
+ minItems: 1
+ title: Table Path
+ kind:
+ type: string
+ const: delete_table
+ title: Kind
+ default: delete_table
+ additionalProperties: false
+ type: object
+ required:
+ - table_path
+ title: DeleteTableOp
+ description: 'Drop the addressed table, including every chunk of one written out of order.
+
+
+ ``table_path`` *is* the target rather than its parent, so it cannot be empty — deleting the
+
+ document root is not a thing an op may express.'
+ Diagnostic:
+ properties:
+ kind:
+ type: string
+ enum:
+ - syntax
+ - semantic
+ - schema
+ title: Kind
+ severity:
+ type: string
+ title: Severity
+ message:
+ type: string
+ title: Message
+ location:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Location
+ range:
+ anyOf:
+ - $ref: '#/components/schemas/Range'
+ - type: 'null'
+ type: object
+ required:
+ - kind
+ - severity
+ - message
+ - location
+ - range
+ title: Diagnostic
+ description: Structured lint/format diagnostic returned by `pipelex-tools-py`.
+ DocGenFormat:
+ type: string
+ enum:
+ - pdf
+ - xlsx
+ - docx
+ - pptx
+ title: DocGenFormat
+ description: 'The file formats a `PipeDocGen` step can ask for.
+
+
+ The tokens are MTHDS: a method names one, and it loads wherever the standard is read. Which of them a
+
+ runtime prints depends on the document engines installed in it, each a model of the `doc_gen` family:
+
+ open Pipelex prints a `pdf` laid out without a template, on `reportlab-pdf`, and the Pipelex document
+
+ generation plugin prints the rest. HTML is not a format: `PipeCompose` already produces the native
+
+ `Html`.'
+ DocGenSetting:
+ properties:
+ model:
+ type: string
+ title: Model
+ description:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Description
+ additionalProperties: false
+ type: object
+ required:
+ - model
+ title: DocGenSetting
+ description: 'The document engine a `PipeDocGen` step prints with: a model of the `doc_gen` family, such as `reportlab-pdf`.'
+ DocumentField:
+ properties:
+ title:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Title
+ concept_ref:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Concept Ref
+ refines:
+ anyOf:
+ - items:
+ type: string
+ type: array
+ - type: 'null'
+ title: Refines
+ description:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Description
+ required:
+ type: boolean
+ title: Required
+ presence:
+ anyOf:
+ - $ref: '#/components/schemas/PresenceMarker'
+ - type: 'null'
+ gating:
+ anyOf:
+ - type: boolean
+ - type: 'null'
+ title: Gating
+ default_value:
+ title: Default Value
+ examples:
+ anyOf:
+ - items: {}
+ type: array
+ - type: 'null'
+ title: Examples
+ hints:
+ anyOf:
+ - additionalProperties:
+ type: string
+ type: object
+ - type: 'null'
+ title: Hints
+ kind:
+ type: string
+ const: document
+ title: Kind
+ default: document
+ name:
+ type: string
+ title: Name
+ additionalProperties: false
+ type: object
+ required:
+ - required
+ - name
+ title: DocumentField
+ description: '`document` at a named position.'
+ DocumentItem:
+ properties:
+ title:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Title
+ concept_ref:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Concept Ref
+ refines:
+ anyOf:
+ - items:
+ type: string
+ type: array
+ - type: 'null'
+ title: Refines
+ description:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Description
+ required:
+ type: boolean
+ title: Required
+ presence:
+ anyOf:
+ - $ref: '#/components/schemas/PresenceMarker'
+ - type: 'null'
+ gating:
+ anyOf:
+ - type: boolean
+ - type: 'null'
+ title: Gating
+ default_value:
+ title: Default Value
+ examples:
+ anyOf:
+ - items: {}
+ type: array
+ - type: 'null'
+ title: Examples
+ hints:
+ anyOf:
+ - additionalProperties:
+ type: string
+ type: object
+ - type: 'null'
+ title: Hints
+ kind:
+ type: string
+ const: document
+ title: Kind
+ default: document
+ additionalProperties: false
+ type: object
+ required:
+ - required
+ title: DocumentItem
+ description: '`document` — a document supplied as a file or a URL.
+
+
+ No accept-list and no upload affordance: what the value is rides `concept_ref` and `refines`,
+
+ and how a renderer offers a file is the renderer''s decision.'
+ DryRunStatus:
+ type: string
+ enum:
+ - SUCCESS
+ - FAILURE
+ - SKIPPED
+ title: DryRunStatus
+ EdgeKind:
+ type: string
+ enum:
+ - control
+ - data
+ - contains
+ - selected_outcome
+ - batch_item
+ - batch_aggregate
+ - parallel_combine
+ title: EdgeKind
+ description: Types of edges in the execution graph.
+ EdgeSpec:
+ properties:
+ id:
+ type: string
+ title: Id
+ source:
+ type: string
+ title: Source
+ target:
+ type: string
+ title: Target
+ kind:
+ $ref: '#/components/schemas/EdgeKind'
+ optional:
+ type: boolean
+ title: Optional
+ default: false
+ label:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Label
+ source_stuff_digest:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Source Stuff Digest
+ target_stuff_digest:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Target Stuff Digest
+ meta:
+ additionalProperties: true
+ type: object
+ title: Meta
+ additionalProperties: false
+ type: object
+ required:
+ - id
+ - source
+ - target
+ - kind
+ title: EdgeSpec
+ description: Specification for an edge in the execution graph.
+ ElaborationMetadata:
+ properties:
+ parent_pipe_code:
+ type: string
+ title: Parent Pipe Code
+ step_role:
+ $ref: '#/components/schemas/StepRole'
+ type: object
+ required:
+ - parent_pipe_code
+ - step_role
+ title: ElaborationMetadata
+ description: Side-table entry recording how a synthetic pipe was generated by the bundle elaborator.
+ EnsureTableOp:
+ properties:
+ table_path:
+ items:
+ type: string
+ type: array
+ minItems: 1
+ title: Table Path
+ kind:
+ type: string
+ const: ensure_table
+ title: Kind
+ default: ensure_table
+ additionalProperties: false
+ type: object
+ required:
+ - table_path
+ title: EnsureTableOp
+ description: 'Create the addressed table when it is absent, leaving an existing one untouched.
+
+
+ Here ``table_path`` addresses the table to create, not its parent, so it cannot be empty:
+
+ the document root always exists.'
+ EnumField:
+ properties:
+ title:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Title
+ concept_ref:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Concept Ref
+ refines:
+ anyOf:
+ - items:
+ type: string
+ type: array
+ - type: 'null'
+ title: Refines
+ description:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Description
+ required:
+ type: boolean
+ title: Required
+ presence:
+ anyOf:
+ - $ref: '#/components/schemas/PresenceMarker'
+ - type: 'null'
+ gating:
+ anyOf:
+ - type: boolean
+ - type: 'null'
+ title: Gating
+ default_value:
+ title: Default Value
+ examples:
+ anyOf:
+ - items: {}
+ type: array
+ - type: 'null'
+ title: Examples
+ hints:
+ anyOf:
+ - additionalProperties:
+ type: string
+ type: object
+ - type: 'null'
+ title: Hints
+ kind:
+ type: string
+ const: enum
+ title: Kind
+ default: enum
+ choices:
+ items:
+ type: string
+ type: array
+ title: Choices
+ name:
+ type: string
+ title: Name
+ additionalProperties: false
+ type: object
+ required:
+ - required
+ - choices
+ - name
+ title: EnumField
+ description: '`enum` at a named position.'
+ EnumItem:
+ properties:
+ title:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Title
+ concept_ref:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Concept Ref
+ refines:
+ anyOf:
+ - items:
+ type: string
+ type: array
+ - type: 'null'
+ title: Refines
+ description:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Description
+ required:
+ type: boolean
+ title: Required
+ presence:
+ anyOf:
+ - $ref: '#/components/schemas/PresenceMarker'
+ - type: 'null'
+ gating:
+ anyOf:
+ - type: boolean
+ - type: 'null'
+ title: Gating
+ default_value:
+ title: Default Value
+ examples:
+ anyOf:
+ - items: {}
+ type: array
+ - type: 'null'
+ title: Examples
+ hints:
+ anyOf:
+ - additionalProperties:
+ type: string
+ type: object
+ - type: 'null'
+ title: Hints
+ kind:
+ type: string
+ const: enum
+ title: Kind
+ default: enum
+ choices:
+ items:
+ type: string
+ type: array
+ title: Choices
+ additionalProperties: false
+ type: object
+ required:
+ - required
+ - choices
+ title: EnumItem
+ description: '`enum` — one of a fixed set of values.'
+ ErrorSpec:
+ properties:
+ error_type:
+ type: string
+ title: Error Type
+ message:
+ type: string
+ title: Message
+ stack:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Stack
+ additionalProperties: false
+ type: object
+ required:
+ - error_type
+ - message
+ title: ErrorSpec
+ description: 'Error information for failed nodes.
+
+
+ Stack traces are automatically truncated to MAX_STACK_LENGTH.'
+ ExtractSetting:
+ properties:
+ model:
+ type: string
+ title: Model
+ max_nb_images:
+ anyOf:
+ - type: integer
+ minimum: 0.0
+ - type: 'null'
+ title: Max Nb Images
+ image_min_size:
+ anyOf:
+ - type: integer
+ minimum: 0.0
+ - type: 'null'
+ title: Image Min Size
+ description:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Description
+ additionalProperties: false
+ type: object
+ required:
+ - model
+ title: ExtractSetting
+ FixSafety:
+ type: string
+ enum:
+ - safe
+ - unsafe
+ title: FixSafety
+ description: 'Whether a fix is safe to auto-apply (SAFE), or a likely correction that needs a person''s or an agent''s
+
+ confirmation (UNSAFE), which ``pipelex fix bundle`` never applies.'
+ FormatRequest:
+ properties:
+ content:
+ type: string
+ title: Content
+ description: Single .mthds file content to lint or format.
+ options:
+ anyOf:
+ - additionalProperties: true
+ type: object
+ - type: 'null'
+ title: Options
+ description: Optional formatter options passed through to `pipelex_tools.format_mthds`, such as `column_width`.
+ Malformed option values return a 422 problem response.
+ type: object
+ required:
+ - content
+ title: FormatRequest
+ description: Body of `POST /format`.
+ FormatResponse:
+ properties:
+ formatted:
+ type: string
+ title: Formatted
+ changed:
+ type: boolean
+ title: Changed
+ diagnostics:
+ items:
+ $ref: '#/components/schemas/Diagnostic'
+ type: array
+ title: Diagnostics
+ type: object
+ required:
+ - formatted
+ - changed
+ - diagnostics
+ title: FormatResponse
+ description: Response body of `POST /format`.
+ GeneratedArtifact:
+ properties:
+ path:
+ type: string
+ title: Path
+ description: Artifact path, relative to the output root the client writes into.
+ content:
+ type: string
+ title: Content
+ description: Complete file content, stamp header included — write verbatim.
+ type: object
+ required:
+ - path
+ - content
+ title: GeneratedArtifact
+ description: 'One generated file: its path relative to the client''s chosen output root, and its full content.'
+ GraphSpec:
+ properties:
+ graph_id:
+ type: string
+ title: Graph Id
+ created_at:
+ type: string
+ format: date-time
+ title: Created At
+ pipeline_ref:
+ $ref: '#/components/schemas/PipelineRef'
+ nodes:
+ items:
+ $ref: '#/components/schemas/NodeSpec'
+ type: array
+ title: Nodes
+ edges:
+ items:
+ $ref: '#/components/schemas/EdgeSpec'
+ type: array
+ title: Edges
+ usage:
+ anyOf:
+ - $ref: '#/components/schemas/GraphUsageSpec'
+ - type: 'null'
+ meta:
+ additionalProperties: true
+ type: object
+ title: Meta
+ pipe_registry:
+ additionalProperties:
+ additionalProperties: true
+ type: object
+ type: object
+ title: Pipe Registry
+ concept_registry:
+ additionalProperties:
+ additionalProperties: true
+ type: object
+ type: object
+ title: Concept Registry
+ additionalProperties: false
+ type: object
+ required:
+ - graph_id
+ - created_at
+ title: GraphSpec
+ description: 'The canonical specification for a pipeline execution graph.
+
+
+ This is the top-level model representing a complete run graph.
+
+ It is versioned and designed for JSON serialization.'
+ GraphUsageSpec:
+ properties:
+ total:
+ $ref: '#/components/schemas/NodeUsageSpec'
+ unattributed:
+ $ref: '#/components/schemas/NodeUsageSpec'
+ additionalProperties: false
+ type: object
+ required:
+ - total
+ - unattributed
+ title: GraphUsageSpec
+ description: 'Run-level inference usage for a whole GraphSpec.
+
+
+ ``total`` covers every usage the run reported, attributed or not — it is the graph''s
+
+ comparand for the cost report''s own total. ``unattributed`` is the part that named no
+
+ live node (the ``UNATTRIBUTED_NODE_ID`` fallback, or a node that never emitted a
+
+ start event): surfaced as its own bucket rather than dropped, so the graph''s total
+
+ can never silently disagree with the cost report''s.
+
+
+ Both reuse ``NodeUsageSpec`` — one usage shape in the contract, not two. Neither has
+
+ a subtree distinct from itself, so their ``subtree_*`` fields repeat their own.'
+ HealthResponse:
+ properties:
+ status:
+ type: string
+ title: Status
+ description: Always `ok` — the endpoint answers only when the process is serving.
+ message:
+ type: string
+ title: Message
+ description: Human-readable confirmation that the server is up.
+ type: object
+ required:
+ - status
+ - message
+ title: HealthResponse
+ description: Body of `GET /health`.
+ HintLintErrorType:
+ type: string
+ enum:
+ - hint_unknown_key
+ - hint_unknown_intent
+ - hint_inapplicable_intent
+ title: HintLintErrorType
+ description: 'Advisory intent-hints lint findings (spec: intent-hints.md).
+
+
+ Every member is advisory-only: it rides the validation report''s ``warnings`` array and never
+
+ makes a verdict invalid — hints are non-normative, and well-formed unknown content is
+
+ preserved, only warned about. A separate enum rather than new ``PipeValidationErrorType``
+
+ members because hints attach to concepts and structure fields too, so the pipe enum is the
+
+ wrong home.'
+ IOMultiplicity:
+ type: string
+ enum:
+ - single
+ - variable
+ - fixed
+ title: IOMultiplicity
+ description: 'How many items a slot takes or a pipe resolves to: one item, a variable-length list, or a fixed count.
+
+
+ Read together with `item_count`, which is non-null exactly on the `fixed` arm. `Concept[1]`
+
+ is `single` — one item, no list framing — because the language says so, so a `fixed` count on
+
+ this wire is always greater than one.'
+ IOSpec:
+ properties:
+ name:
+ type: string
+ title: Name
+ concept:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Concept
+ content_type:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Content Type
+ preview:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Preview
+ size:
+ anyOf:
+ - type: integer
+ - type: 'null'
+ title: Size
+ digest:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Digest
+ data:
+ anyOf:
+ - type: string
+ - additionalProperties: true
+ type: object
+ - items:
+ type: string
+ type: array
+ - items:
+ additionalProperties: true
+ type: object
+ type: array
+ - type: 'null'
+ title: Data
+ multiplicity:
+ anyOf:
+ - type: boolean
+ - type: integer
+ exclusiveMinimum: 0.0
+ - type: 'null'
+ title: Multiplicity
+ extra:
+ additionalProperties: true
+ type: object
+ title: Extra
+ additionalProperties: false
+ type: object
+ required:
+ - name
+ title: IOSpec
+ description: 'Specification for an input or output variable.
+
+
+ Previews are automatically truncated to MAX_PREVIEW_LENGTH to prevent
+
+ accidental storage of large payloads or sensitive data.
+
+
+ The optional `data` field can hold the full serialized content when
+
+ full data capture is enabled (via --graph-full-data CLI option).
+
+
+ `concept` is always the bare concept code; whether the stuff is a list is `multiplicity`,
+
+ in the encoding the pipe registry uses for a stuff spec''s multiplicity: `True` for a
+
+ variable-length list, a positive integer for a fixed count, `None` (or `False`) for a single
+
+ value, a count of one reading as single. A reader takes absence as single.'
+ ImageField:
+ properties:
+ title:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Title
+ concept_ref:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Concept Ref
+ refines:
+ anyOf:
+ - items:
+ type: string
+ type: array
+ - type: 'null'
+ title: Refines
+ description:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Description
+ required:
+ type: boolean
+ title: Required
+ presence:
+ anyOf:
+ - $ref: '#/components/schemas/PresenceMarker'
+ - type: 'null'
+ gating:
+ anyOf:
+ - type: boolean
+ - type: 'null'
+ title: Gating
+ default_value:
+ title: Default Value
+ examples:
+ anyOf:
+ - items: {}
+ type: array
+ - type: 'null'
+ title: Examples
+ hints:
+ anyOf:
+ - additionalProperties:
+ type: string
+ type: object
+ - type: 'null'
+ title: Hints
+ kind:
+ type: string
+ const: image
+ title: Kind
+ default: image
+ name:
+ type: string
+ title: Name
+ additionalProperties: false
+ type: object
+ required:
+ - required
+ - name
+ title: ImageField
+ description: '`image` at a named position.'
+ ImageFormat:
+ type: string
+ enum:
+ - png
+ - jpeg
+ - webp
+ title: ImageFormat
+ ImageItem:
+ properties:
+ title:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Title
+ concept_ref:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Concept Ref
+ refines:
+ anyOf:
+ - items:
+ type: string
+ type: array
+ - type: 'null'
+ title: Refines
+ description:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Description
+ required:
+ type: boolean
+ title: Required
+ presence:
+ anyOf:
+ - $ref: '#/components/schemas/PresenceMarker'
+ - type: 'null'
+ gating:
+ anyOf:
+ - type: boolean
+ - type: 'null'
+ title: Gating
+ default_value:
+ title: Default Value
+ examples:
+ anyOf:
+ - items: {}
+ type: array
+ - type: 'null'
+ title: Examples
+ hints:
+ anyOf:
+ - additionalProperties:
+ type: string
+ type: object
+ - type: 'null'
+ title: Hints
+ kind:
+ type: string
+ const: image
+ title: Kind
+ default: image
+ additionalProperties: false
+ type: object
+ required:
+ - required
+ title: ImageItem
+ description: '`image` — an image, which a renderer may preview.'
+ ImageSize:
+ properties:
+ width:
+ type: integer
+ exclusiveMinimum: 0.0
+ title: Width
+ height:
+ type: integer
+ exclusiveMinimum: 0.0
+ title: Height
+ type: object
+ required:
+ - width
+ - height
+ title: ImageSize
+ ImgGenSetting:
+ properties:
+ model:
+ type: string
+ title: Model
+ quality:
+ anyOf:
+ - $ref: '#/components/schemas/Quality'
+ - type: 'null'
+ nb_steps:
+ anyOf:
+ - type: integer
+ exclusiveMinimum: 0.0
+ - type: 'null'
+ title: Nb Steps
+ guidance_scale:
+ anyOf:
+ - type: number
+ exclusiveMinimum: 0.0
+ - type: 'null'
+ title: Guidance Scale
+ is_moderated:
+ anyOf:
+ - type: boolean
+ - type: 'null'
+ title: Is Moderated
+ safety_tolerance:
+ anyOf:
+ - type: integer
+ maximum: 6.0
+ minimum: 1.0
+ - type: 'null'
+ title: Safety Tolerance
+ description:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Description
+ additionalProperties: false
+ type: object
+ required:
+ - model
+ title: ImgGenSetting
+ InputSlotBlueprint:
+ properties:
+ concept:
+ type: string
+ title: Concept
+ hints:
+ anyOf:
+ - additionalProperties:
+ type: string
+ type: object
+ - type: 'null'
+ title: Hints
+ additionalProperties: false
+ type: object
+ required:
+ - concept
+ title: InputSlotBlueprint
+ description: 'The expanded input-slot form: `name = { concept = "…", hints = { … } }` (spec: intent-hints.md).
+
+
+ `concept` carries the full slot grammar of the string form (ref, optional multiplicity, optional
+
+ presence marker). The form is deliberately closed (`extra="forbid"` implements the spec''s
+
+ "unknown slot-table keys MUST be rejected") so future per-slot semantic keys land here without a
+
+ second syntax. A slot table carrying no hints collapses to its plain string at parse time (see
+
+ `PipeBlueprint.collapse_hint_free_slot_tables`), so a slot value that IS a table carries
+
+ non-empty hints — hint-free bundles produce byte-identical blueprints to the string form.'
+ InputsTemplateFormat:
+ type: string
+ enum:
+ - json
+ - toml
+ title: InputsTemplateFormat
+ description: Serialization format for a generated inputs template.
+ InvalidReport:
+ properties:
+ is_valid:
+ type: boolean
+ const: false
+ title: Is Valid
+ default: false
+ validation_errors:
+ items:
+ $ref: '#/components/schemas/ValidationErrorItem'
+ type: array
+ title: Validation Errors
+ description: Per-error diagnostics, built by pipelex's one shared builder — non-empty on every invalid verdict.
+ pending_signatures:
+ items:
+ type: string
+ type: array
+ title: Pending Signatures
+ description: Best-effort outstanding signatures; empty on the invalid arm since no library was assembled.
+ is_runnable:
+ type: boolean
+ const: false
+ title: Is Runnable
+ default: false
+ message:
+ type: string
+ title: Message
+ description: Human-readable summary of the verdict.
+ default: MTHDS validation found errors
+ rendered_markdown:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Rendered Markdown
+ description: 'Opt-in Pipelex-API presentation extra: a server-rendered Markdown view of the invalid verdict''s `validation_errors`,
+ present only when the request''s `render` includes `markdown`. Absent by default.'
+ type: object
+ title: InvalidReport
+ description: 'The 200 **invalid** arm: a produced "invalid" verdict, discriminated on `is_valid: false`.
+
+
+ An invalid bundle is the *successful product* of a diagnostic call, not a transport failure
+
+ (the request was well-formed; the bundle was not), so it rides a **200** — the global
+
+ `problem+json` 422/5xx is reserved for the no-verdict conditions (malformed request body,
+
+ `mthds_sources` length mismatch, auth, server fault). The structural artifacts
+
+ (`bundle_blueprint`, `pipe_io_contracts`, `graph_spec`, `validated_pipes`) do not exist when
+
+ load/parse/wiring failed, so this arm omits them and carries only the per-error diagnostics
+
+ plus the runnability facts. The `input_form` and `output_form` views follow them into absence for
+
+ the same reason — both derive from a crate that was never assembled — so neither is declared here and `views`
+
+ has no effect on this arm (unlike `rendered_markdown`, which rides both arms because failure
+
+ text is exactly what a human surface wants).'
+ LLMSetting:
+ properties:
+ model:
+ type: string
+ title: Model
+ temperature:
+ type: number
+ maximum: 1.0
+ minimum: 0.0
+ title: Temperature
+ max_tokens:
+ anyOf:
+ - type: integer
+ - enum:
+ - auto
+ - type: 'null'
+ title: Max Tokens
+ image_detail:
+ anyOf:
+ - $ref: '#/components/schemas/PromptImageDetail'
+ - type: 'null'
+ reasoning_effort:
+ anyOf:
+ - $ref: '#/components/schemas/ReasoningEffort'
+ - type: 'null'
+ reasoning_budget:
+ anyOf:
+ - type: integer
+ exclusiveMinimum: 0.0
+ - type: 'null'
+ title: Reasoning Budget
+ description:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Description
+ additionalProperties: false
+ type: object
+ required:
+ - model
+ - temperature
+ title: LLMSetting
+ LiftablePipeEntry:
+ properties:
+ pipe_ref:
+ type: string
+ title: Pipe Ref
+ within_pipe_ref:
+ type: string
+ title: Within Pipe Ref
+ skipped_when_absent:
+ items:
+ type: string
+ type: array
+ title: Skipped When Absent
+ absence_source:
+ type: string
+ title: Absence Source
+ type: object
+ required:
+ - pipe_ref
+ - within_pipe_ref
+ - absence_source
+ title: LiftablePipeEntry
+ description: One pipe that may be skipped (lifted) when an optional slot resolves absent.
+ LintRequest:
+ properties:
+ content:
+ type: string
+ title: Content
+ description: Single .mthds file content to lint or format.
+ source:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Source
+ description: Optional logical filename for the content. Accepted for parity with `pipelex_tools.lint_mthds`; current
+ diagnostics do not yet include the filename.
+ type: object
+ required:
+ - content
+ title: LintRequest
+ description: Body of `POST /lint`.
+ LintResponse:
+ properties:
+ diagnostics:
+ items:
+ $ref: '#/components/schemas/Diagnostic'
+ type: array
+ title: Diagnostics
+ type: object
+ required:
+ - diagnostics
+ title: LintResponse
+ description: Response body of `POST /lint`.
+ ListField:
+ properties:
+ title:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Title
+ concept_ref:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Concept Ref
+ refines:
+ anyOf:
+ - items:
+ type: string
+ type: array
+ - type: 'null'
+ title: Refines
+ description:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Description
+ required:
+ type: boolean
+ title: Required
+ presence:
+ anyOf:
+ - $ref: '#/components/schemas/PresenceMarker'
+ - type: 'null'
+ gating:
+ anyOf:
+ - type: boolean
+ - type: 'null'
+ title: Gating
+ default_value:
+ title: Default Value
+ examples:
+ anyOf:
+ - items: {}
+ type: array
+ - type: 'null'
+ title: Examples
+ hints:
+ anyOf:
+ - additionalProperties:
+ type: string
+ type: object
+ - type: 'null'
+ title: Hints
+ kind:
+ type: string
+ const: list
+ title: Kind
+ default: list
+ item:
+ oneOf:
+ - $ref: '#/components/schemas/TextItem'
+ - $ref: '#/components/schemas/ProseItem'
+ - $ref: '#/components/schemas/DateItem'
+ - $ref: '#/components/schemas/NumberItem'
+ - $ref: '#/components/schemas/BooleanItem'
+ - $ref: '#/components/schemas/EnumItem'
+ - $ref: '#/components/schemas/DocumentItem'
+ - $ref: '#/components/schemas/ImageItem'
+ - $ref: '#/components/schemas/ObjectItem'
+ - $ref: '#/components/schemas/ListItem'
+ - $ref: '#/components/schemas/UnknownItem'
+ title: Item
+ discriminator:
+ propertyName: kind
+ mapping:
+ boolean: '#/components/schemas/BooleanItem'
+ date: '#/components/schemas/DateItem'
+ document: '#/components/schemas/DocumentItem'
+ enum: '#/components/schemas/EnumItem'
+ image: '#/components/schemas/ImageItem'
+ list: '#/components/schemas/ListItem'
+ number: '#/components/schemas/NumberItem'
+ object: '#/components/schemas/ObjectItem'
+ prose: '#/components/schemas/ProseItem'
+ text: '#/components/schemas/TextItem'
+ unknown: '#/components/schemas/UnknownItem'
+ item_count:
+ anyOf:
+ - type: integer
+ - type: 'null'
+ title: Item Count
+ name:
+ type: string
+ title: Name
+ additionalProperties: false
+ type: object
+ required:
+ - required
+ - item
+ - name
+ title: ListField
+ description: '`list` at a named position, recursing through a nameless `item`.'
+ ListItem:
+ properties:
+ title:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Title
+ concept_ref:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Concept Ref
+ refines:
+ anyOf:
+ - items:
+ type: string
+ type: array
+ - type: 'null'
+ title: Refines
+ description:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Description
+ required:
+ type: boolean
+ title: Required
+ presence:
+ anyOf:
+ - $ref: '#/components/schemas/PresenceMarker'
+ - type: 'null'
+ gating:
+ anyOf:
+ - type: boolean
+ - type: 'null'
+ title: Gating
+ default_value:
+ title: Default Value
+ examples:
+ anyOf:
+ - items: {}
+ type: array
+ - type: 'null'
+ title: Examples
+ hints:
+ anyOf:
+ - additionalProperties:
+ type: string
+ type: object
+ - type: 'null'
+ title: Hints
+ kind:
+ type: string
+ const: list
+ title: Kind
+ default: list
+ item:
+ oneOf:
+ - $ref: '#/components/schemas/TextItem'
+ - $ref: '#/components/schemas/ProseItem'
+ - $ref: '#/components/schemas/DateItem'
+ - $ref: '#/components/schemas/NumberItem'
+ - $ref: '#/components/schemas/BooleanItem'
+ - $ref: '#/components/schemas/EnumItem'
+ - $ref: '#/components/schemas/DocumentItem'
+ - $ref: '#/components/schemas/ImageItem'
+ - $ref: '#/components/schemas/ObjectItem'
+ - $ref: '#/components/schemas/ListItem'
+ - $ref: '#/components/schemas/UnknownItem'
+ title: Item
+ discriminator:
+ propertyName: kind
+ mapping:
+ boolean: '#/components/schemas/BooleanItem'
+ date: '#/components/schemas/DateItem'
+ document: '#/components/schemas/DocumentItem'
+ enum: '#/components/schemas/EnumItem'
+ image: '#/components/schemas/ImageItem'
+ list: '#/components/schemas/ListItem'
+ number: '#/components/schemas/NumberItem'
+ object: '#/components/schemas/ObjectItem'
+ prose: '#/components/schemas/ProseItem'
+ text: '#/components/schemas/TextItem'
+ unknown: '#/components/schemas/UnknownItem'
+ item_count:
+ anyOf:
+ - type: integer
+ - type: 'null'
+ title: Item Count
+ additionalProperties: false
+ type: object
+ required:
+ - required
+ - item
+ title: ListItem
+ description: '`list` — an array of one element type, recursing through its `item`.
+
+
+ An input slot authored `Concept[]` is a `list` with no `item_count`; one authored `Concept[N]`
+
+ carries `item_count: N`. `Concept[1]` is single — no list framing — so a stated count is always
+
+ at least 2. `concept_ref` and `refines` name the element concept, and the `item` carries the
+
+ same `concept_ref`; on a plural node the merged `hints` ride both the list and its item.'
+ MethodProvenance:
+ properties:
+ address:
+ type: string
+ title: Address
+ tag:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Tag
+ commit_sha:
+ type: string
+ title: Commit Sha
+ type: object
+ required:
+ - address
+ - commit_sha
+ title: MethodProvenance
+ description: 'What a fetched-method run must record: address, tag, and the resolved commit SHA.'
+ ModelCategory:
+ type: string
+ enum:
+ - llm
+ - extract
+ - img_gen
+ - search
+ title: ModelCategory
+ description: Model categories accepted by the protocol's `GET /models?type=` filter.
+ ModelInfo:
+ properties:
+ name:
+ type: string
+ title: Name
+ type:
+ anyOf:
+ - $ref: '#/components/schemas/ModelCategory'
+ - type: 'null'
+ additionalProperties: true
+ type: object
+ required:
+ - name
+ title: ModelInfo
+ description: One entry of the model deck (`ModelDeck.models[]`) — base fields + extensions.
+ ModelReference:
+ type: string
+ ModelReferenceKind:
+ type: string
+ enum:
+ - preset
+ - alias
+ - waterfall
+ - handle
+ title: ModelReferenceKind
+ description: The kind of model reference.
+ ModelUsageSpec:
+ properties:
+ inference_model_name:
+ type: string
+ title: Inference Model Name
+ inference_model_id:
+ type: string
+ title: Inference Model Id
+ model_type:
+ type: string
+ title: Model Type
+ inference_calls:
+ type: integer
+ title: Inference Calls
+ default: 0
+ rated_inference_calls:
+ type: integer
+ title: Rated Inference Calls
+ default: 0
+ cost:
+ anyOf:
+ - type: number
+ - type: 'null'
+ title: Cost
+ additionalProperties: false
+ type: object
+ required:
+ - inference_model_name
+ - inference_model_id
+ - model_type
+ title: ModelUsageSpec
+ description: 'What one inference model actually did for a node.
+
+
+ This is the only place the graph records the model that **ran**. Everything else
+
+ in a GraphSpec that names a model records what was *asked for*:
+
+ ``execution_data.resolved_model`` holds the handle the pipe resolved to — which may
+
+ still be an alias (``@default-premium``) — and the pipe blueprint holds the authored
+
+ choice (``$writing-factual``). Those are three rungs of one ladder, and only this
+
+ rung is the outcome: it survives alias resolution, deck defaults, and any fallback
+
+ or retry that landed somewhere other than what was requested.
+
+
+ A node genuinely uses more than one model in ordinary cases — a ``PipeLLM``''s text
+
+ pass and its object-structuring pass resolve separately — so a node''s models are a
+
+ LIST. Collapsing them to "the model" would be wrong in exactly the way a single
+
+ ``cost`` for mixed rated/unrated calls is wrong.
+
+
+ ``cost`` follows ``NodeUsageSpec`` invariant 2: ``None`` iff no call to this model
+
+ carried a rate table.'
+ MoveKeyOp:
+ properties:
+ table_path:
+ items:
+ type: string
+ type: array
+ title: Table Path
+ kind:
+ type: string
+ const: move_key
+ title: Kind
+ default: move_key
+ key:
+ type: string
+ title: Key
+ new_table_path:
+ items:
+ type: string
+ type: array
+ title: New Table Path
+ new_key:
+ type: string
+ title: New Key
+ additionalProperties: false
+ type: object
+ required:
+ - table_path
+ - key
+ - new_table_path
+ - new_key
+ title: MoveKeyOp
+ description: 'Relocate ``key`` from the addressed table into ``new_table_path``, under ``new_key``.
+
+
+ The moved key may be table-valued, in which case the whole subtree travels. Destination
+
+ parents that do not exist are created, as block tables, as part of the operation. Position
+
+ is preserved within a parent and never across parents — see ``docs/migration-ledger.md``
+
+ for the placement rule and for what happens to a moved table''s introducing comment.'
+ MthdsFileItem:
+ properties:
+ content:
+ type: string
+ title: Content
+ description: MTHDS bundle content.
+ source:
+ anyOf:
+ - type: string
+ maxLength: 1024
+ - type: 'null'
+ title: Source
+ description: Optional logical source for this bundle (e.g. its path relative to the submitted directory). Threaded
+ onto the blueprint so server-side diagnostics carry a `source` pointing at the owning file.
+ type: object
+ required:
+ - content
+ title: MthdsFileItem
+ description: 'One inline MTHDS bundle: its content plus an optional logical source for diagnostics.
+
+
+ The `files[]` envelope pairs each content with its source in one entry (the shape the codegen
+
+ spec pins for the resolve/codegen routes), unlike the legacy parallel
+
+ `mthds_contents[]`/`mthds_sources[]` lists on `/validate`.'
+ MthdsFilesRequest:
+ properties:
+ files:
+ anyOf:
+ - items:
+ $ref: '#/components/schemas/MthdsFileItem'
+ type: array
+ maxItems: 16
+ minItems: 1
+ - type: 'null'
+ title: Files
+ description: Inline MTHDS bundles forming the closure to resolve (content-passing — no server-side path reads).
+ method_ref:
+ anyOf:
+ - type: string
+ maxLength: 512
+ minLength: 1
+ - type: 'null'
+ title: Method Ref
+ description: Reference to a published method, resolving to its package's `.mthds` files. Address form (`github.com/<owner>/<repo>[/<selector>][@<tag>]`)
+ is fetched and resolved server-side; the registry form stays reserved (501 until a method registry exists).
+ type: object
+ title: MthdsFilesRequest
+ description: 'Shared closure selector for the resolve/codegen routes: inline `files[]` XOR a `method_ref`.
+
+
+ Exactly one of the two must be provided (spec''d envelope) — both or neither is a request-shape
+
+ 422. An **address-form** `method_ref` (`github.com/<owner>/<repo>[/<selector>][@<tag>]`) is
+
+ resolved by this server: the repository is fetched at the tag, the package is located by
+
+ manifest identity, and its `.mthds` files feed the closure with their real relative paths as
+
+ per-file sources. The **registry form** (any non-address reference) stays reserved and answers
+
+ 501 until server-side method-registry resolution exists.'
+ NodeIOSpec:
+ properties:
+ inputs:
+ items:
+ $ref: '#/components/schemas/IOSpec'
+ type: array
+ title: Inputs
+ outputs:
+ items:
+ $ref: '#/components/schemas/IOSpec'
+ type: array
+ title: Outputs
+ additionalProperties: false
+ type: object
+ title: NodeIOSpec
+ description: Input/output specification for a node.
+ NodeKind:
+ type: string
+ enum:
+ - pipe_call
+ - controller
+ - operator
+ - input
+ - output
+ - artifact
+ - error
+ title: NodeKind
+ description: Types of nodes in the execution graph.
+ NodeSpec:
+ properties:
+ id:
+ type: string
+ title: Id
+ kind:
+ $ref: '#/components/schemas/NodeKind'
+ pipe_code:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Pipe Code
+ pipe_type:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Pipe Type
+ description:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Description
+ domain_code:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Domain Code
+ status:
+ $ref: '#/components/schemas/NodeStatus'
+ skip_reason:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Skip Reason
+ timing:
+ anyOf:
+ - $ref: '#/components/schemas/TimingSpec'
+ - type: 'null'
+ io:
+ $ref: '#/components/schemas/NodeIOSpec'
+ error:
+ anyOf:
+ - $ref: '#/components/schemas/ErrorSpec'
+ - type: 'null'
+ tags:
+ additionalProperties:
+ type: string
+ type: object
+ title: Tags
+ metrics:
+ additionalProperties:
+ type: number
+ type: object
+ title: Metrics
+ usage:
+ anyOf:
+ - $ref: '#/components/schemas/NodeUsageSpec'
+ - type: 'null'
+ execution_data:
+ additionalProperties: true
+ type: object
+ title: Execution Data
+ additionalProperties: false
+ type: object
+ required:
+ - id
+ - kind
+ - status
+ title: NodeSpec
+ description: 'Specification for a node in the execution graph.
+
+
+ Each node represents a pipe invocation during execution.'
+ NodeStatus:
+ type: string
+ enum:
+ - scheduled
+ - running
+ - succeeded
+ - failed
+ - skipped
+ - canceled
+ title: NodeStatus
+ description: Execution status of a node.
+ NodeUsageSpec:
+ properties:
+ inference_calls:
+ type: integer
+ title: Inference Calls
+ default: 0
+ rated_inference_calls:
+ type: integer
+ title: Rated Inference Calls
+ default: 0
+ nb_tokens_by_category:
+ additionalProperties:
+ type: integer
+ type: object
+ title: Nb Tokens By Category
+ total_tokens:
+ type: integer
+ title: Total Tokens
+ default: 0
+ cost:
+ anyOf:
+ - type: number
+ - type: 'null'
+ title: Cost
+ cost_input:
+ anyOf:
+ - type: number
+ - type: 'null'
+ title: Cost Input
+ cost_output:
+ anyOf:
+ - type: number
+ - type: 'null'
+ title: Cost Output
+ by_model:
+ items:
+ $ref: '#/components/schemas/ModelUsageSpec'
+ type: array
+ title: By Model
+ subtree_inference_calls:
+ type: integer
+ title: Subtree Inference Calls
+ default: 0
+ subtree_rated_inference_calls:
+ type: integer
+ title: Subtree Rated Inference Calls
+ default: 0
+ subtree_nb_tokens_by_category:
+ additionalProperties:
+ type: integer
+ type: object
+ title: Subtree Nb Tokens By Category
+ subtree_total_tokens:
+ type: integer
+ title: Subtree Total Tokens
+ default: 0
+ subtree_cost:
+ anyOf:
+ - type: number
+ - type: 'null'
+ title: Subtree Cost
+ subtree_cost_input:
+ anyOf:
+ - type: number
+ - type: 'null'
+ title: Subtree Cost Input
+ subtree_cost_output:
+ anyOf:
+ - type: number
+ - type: 'null'
+ title: Subtree Cost Output
+ subtree_by_model:
+ items:
+ $ref: '#/components/schemas/ModelUsageSpec'
+ type: array
+ title: Subtree By Model
+ additionalProperties: false
+ type: object
+ title: NodeUsageSpec
+ description: "Inference usage attributed to one graph node.\n\nField names mirror the already-shipped client-facing\
+ \ ``TokensUsageRecord``\n(``reporting/usage_records.py``) so the graph does not introduce a fifth vocabulary\nfor\
+ \ numbers this codebase already names four ways (``TokenCategory``,\n``LLMTokenCostReportField``, ``GenAISpanAttr``,\
+ \ ``PostHogAttr``).\n\nINVARIANTS — the UI and every other consumer branch on these, not on guesses about\nwhy a number\
+ \ is missing:\n\n 1. ``NodeSpec.usage is None`` <=> no usage was reported anywhere in the run —\n either usage\
+ \ collection was off, or the run made zero inference calls. As soon\n as ONE usage event was seen, EVERY node\
+ \ carries a spec, zeroed where nothing\n ran. A controller, a lifted pipe, and a PipeFunc all get ``inference_calls=0``,\n\
+ \ never ``usage=None``. So the field is all-or-nothing across a graph: it never\n distinguishes \"this node\
+ \ was not measured\" from \"that node was\".\n\n 2. ``cost is None`` <=> ``rated_inference_calls == 0``. Nothing\
+ \ else. \"Made no\n call\" and \"made only unrated calls\" both land here and are told apart by\n ``inference_calls``.\n\
+ \n 3. ``inference_calls > rated_inference_calls > 0`` => ``cost`` is a LOWER BOUND,\n not a total: some of this\
+ \ node's calls carried no rate table. The UI must mark\n it (a leading \"≥\").\n\n 4. ``total_tokens`` is input_joined\
+ \ + output — the same definition as\n ``AggregatedCosts.total_nb_tokens``. It is NOT the sum of\n ``nb_tokens_by_category``:\
+ \ ``input_cached`` is a SUBSET of ``input``, not\n additive (see ``usage_records.py``), so summing double-counts.\
+ \ Never sum the\n dict; read this field.\n\n 5. ``cost_input`` + ``cost_output`` == ``cost`` (to float precision).\
+ \ They are\n the same number split by direction, not extra charges, and they are None on\n exactly the same\
+ \ condition.\n\n 6. ``by_model`` names the models that actually RAN, and its ``inference_calls``\n sum to this\
+ \ spec's own. It is a list because one node routinely uses more\n than one model (a PipeLLM's text pass and its\
+ \ object pass resolve\n separately). Ordered by descending calls, then by name, so a consumer can\n take the\
+ \ first entry as the dominant model without sorting.\n\nThe same invariants hold for the ``subtree_*`` half, which\
+ \ covers this node plus\nevery descendant (rolled up in the assembler, once, so no consumer re-derives it\nand disagrees)."
+ NumberField:
+ properties:
+ title:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Title
+ concept_ref:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Concept Ref
+ refines:
+ anyOf:
+ - items:
+ type: string
+ type: array
+ - type: 'null'
+ title: Refines
+ description:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Description
+ required:
+ type: boolean
+ title: Required
+ presence:
+ anyOf:
+ - $ref: '#/components/schemas/PresenceMarker'
+ - type: 'null'
+ gating:
+ anyOf:
+ - type: boolean
+ - type: 'null'
+ title: Gating
+ default_value:
+ title: Default Value
+ examples:
+ anyOf:
+ - items: {}
+ type: array
+ - type: 'null'
+ title: Examples
+ hints:
+ anyOf:
+ - additionalProperties:
+ type: string
+ type: object
+ - type: 'null'
+ title: Hints
+ kind:
+ type: string
+ const: number
+ title: Kind
+ default: number
+ integer:
+ type: boolean
+ title: Integer
+ minimum:
+ anyOf:
+ - type: integer
+ - type: number
+ - type: 'null'
+ title: Minimum
+ maximum:
+ anyOf:
+ - type: integer
+ - type: number
+ - type: 'null'
+ title: Maximum
+ exclusive_minimum:
+ anyOf:
+ - type: integer
+ - type: number
+ - type: 'null'
+ title: Exclusive Minimum
+ exclusive_maximum:
+ anyOf:
+ - type: integer
+ - type: number
+ - type: 'null'
+ title: Exclusive Maximum
+ name:
+ type: string
+ title: Name
+ additionalProperties: false
+ type: object
+ required:
+ - required
+ - integer
+ - name
+ title: NumberField
+ description: '`number` at a named position.'
+ NumberItem:
+ properties:
+ title:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Title
+ concept_ref:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Concept Ref
+ refines:
+ anyOf:
+ - items:
+ type: string
+ type: array
+ - type: 'null'
+ title: Refines
+ description:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Description
+ required:
+ type: boolean
+ title: Required
+ presence:
+ anyOf:
+ - $ref: '#/components/schemas/PresenceMarker'
+ - type: 'null'
+ gating:
+ anyOf:
+ - type: boolean
+ - type: 'null'
+ title: Gating
+ default_value:
+ title: Default Value
+ examples:
+ anyOf:
+ - items: {}
+ type: array
+ - type: 'null'
+ title: Examples
+ hints:
+ anyOf:
+ - additionalProperties:
+ type: string
+ type: object
+ - type: 'null'
+ title: Hints
+ kind:
+ type: string
+ const: number
+ title: Kind
+ default: number
+ integer:
+ type: boolean
+ title: Integer
+ minimum:
+ anyOf:
+ - type: integer
+ - type: number
+ - type: 'null'
+ title: Minimum
+ maximum:
+ anyOf:
+ - type: integer
+ - type: number
+ - type: 'null'
+ title: Maximum
+ exclusive_minimum:
+ anyOf:
+ - type: integer
+ - type: number
+ - type: 'null'
+ title: Exclusive Minimum
+ exclusive_maximum:
+ anyOf:
+ - type: integer
+ - type: number
+ - type: 'null'
+ title: Exclusive Maximum
+ additionalProperties: false
+ type: object
+ required:
+ - required
+ - integer
+ title: NumberItem
+ description: '`number` — an integer or a floating-point number, with its optional bounds.'
+ ObjectField:
+ properties:
+ title:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Title
+ concept_ref:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Concept Ref
+ refines:
+ anyOf:
+ - items:
+ type: string
+ type: array
+ - type: 'null'
+ title: Refines
+ description:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Description
+ required:
+ type: boolean
+ title: Required
+ presence:
+ anyOf:
+ - $ref: '#/components/schemas/PresenceMarker'
+ - type: 'null'
+ gating:
+ anyOf:
+ - type: boolean
+ - type: 'null'
+ title: Gating
+ default_value:
+ title: Default Value
+ examples:
+ anyOf:
+ - items: {}
+ type: array
+ - type: 'null'
+ title: Examples
+ hints:
+ anyOf:
+ - additionalProperties:
+ type: string
+ type: object
+ - type: 'null'
+ title: Hints
+ kind:
+ type: string
+ const: object
+ title: Kind
+ default: object
+ fields:
+ items:
+ oneOf:
+ - $ref: '#/components/schemas/TextField'
+ - $ref: '#/components/schemas/ProseField'
+ - $ref: '#/components/schemas/DateField'
+ - $ref: '#/components/schemas/NumberField'
+ - $ref: '#/components/schemas/BooleanField'
+ - $ref: '#/components/schemas/EnumField'
+ - $ref: '#/components/schemas/DocumentField'
+ - $ref: '#/components/schemas/ImageField'
+ - $ref: '#/components/schemas/ObjectField'
+ - $ref: '#/components/schemas/ListField'
+ - $ref: '#/components/schemas/UnknownField'
+ discriminator:
+ propertyName: kind
+ mapping:
+ boolean: '#/components/schemas/BooleanField'
+ date: '#/components/schemas/DateField'
+ document: '#/components/schemas/DocumentField'
+ enum: '#/components/schemas/EnumField'
+ image: '#/components/schemas/ImageField'
+ list: '#/components/schemas/ListField'
+ number: '#/components/schemas/NumberField'
+ object: '#/components/schemas/ObjectField'
+ prose: '#/components/schemas/ProseField'
+ text: '#/components/schemas/TextField'
+ unknown: '#/components/schemas/UnknownField'
+ type: array
+ title: Fields
+ name:
+ type: string
+ title: Name
+ additionalProperties: false
+ type: object
+ required:
+ - required
+ - fields
+ - name
+ title: ObjectField
+ description: '`object` at a named position, recursing through `fields` — themselves named.'
+ ObjectItem:
+ properties:
+ title:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Title
+ concept_ref:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Concept Ref
+ refines:
+ anyOf:
+ - items:
+ type: string
+ type: array
+ - type: 'null'
+ title: Refines
+ description:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Description
+ required:
+ type: boolean
+ title: Required
+ presence:
+ anyOf:
+ - $ref: '#/components/schemas/PresenceMarker'
+ - type: 'null'
+ gating:
+ anyOf:
+ - type: boolean
+ - type: 'null'
+ title: Gating
+ default_value:
+ title: Default Value
+ examples:
+ anyOf:
+ - items: {}
+ type: array
+ - type: 'null'
+ title: Examples
+ hints:
+ anyOf:
+ - additionalProperties:
+ type: string
+ type: object
+ - type: 'null'
+ title: Hints
+ kind:
+ type: string
+ const: object
+ title: Kind
+ default: object
+ fields:
+ items:
+ oneOf:
+ - $ref: '#/components/schemas/TextField'
+ - $ref: '#/components/schemas/ProseField'
+ - $ref: '#/components/schemas/DateField'
+ - $ref: '#/components/schemas/NumberField'
+ - $ref: '#/components/schemas/BooleanField'
+ - $ref: '#/components/schemas/EnumField'
+ - $ref: '#/components/schemas/DocumentField'
+ - $ref: '#/components/schemas/ImageField'
+ - $ref: '#/components/schemas/ObjectField'
+ - $ref: '#/components/schemas/ListField'
+ - $ref: '#/components/schemas/UnknownField'
+ discriminator:
+ propertyName: kind
+ mapping:
+ boolean: '#/components/schemas/BooleanField'
+ date: '#/components/schemas/DateField'
+ document: '#/components/schemas/DocumentField'
+ enum: '#/components/schemas/EnumField'
+ image: '#/components/schemas/ImageField'
+ list: '#/components/schemas/ListField'
+ number: '#/components/schemas/NumberField'
+ object: '#/components/schemas/ObjectField'
+ prose: '#/components/schemas/ProseField'
+ text: '#/components/schemas/TextField'
+ unknown: '#/components/schemas/UnknownField'
+ type: array
+ title: Fields
+ additionalProperties: false
+ type: object
+ required:
+ - required
+ - fields
+ title: ObjectItem
+ description: '`object` — a structured concept, recursing through its resolved payload fields.'
+ PipeBatchBlueprint:
+ properties:
+ source:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Source
+ pipe_category:
+ type: string
+ const: PipeController
+ title: Pipe Category
+ default: PipeController
+ type:
+ type: string
+ const: PipeBatch
+ title: Type
+ default: PipeBatch
+ description:
+ type: string
+ title: Description
+ inputs:
+ anyOf:
+ - additionalProperties:
+ anyOf:
+ - type: string
+ - $ref: '#/components/schemas/InputSlotBlueprint'
+ type: object
+ - type: 'null'
+ title: Inputs
+ output:
+ type: string
+ title: Output
+ branch_pipe_code:
+ type: string
+ title: Branch Pipe Code
+ input_list_name:
+ type: string
+ title: Input List Name
+ input_item_name:
+ type: string
+ title: Input Item Name
+ additionalProperties: false
+ type: object
+ required:
+ - description
+ - output
+ - branch_pipe_code
+ - input_list_name
+ - input_item_name
+ title: PipeBatchBlueprint
+ PipeComposeBlueprint:
+ properties:
+ source:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Source
+ pipe_category:
+ type: string
+ const: PipeOperator
+ title: Pipe Category
+ default: PipeOperator
+ type:
+ type: string
+ const: PipeCompose
+ title: Type
+ default: PipeCompose
+ description:
+ type: string
+ title: Description
+ inputs:
+ anyOf:
+ - additionalProperties:
+ anyOf:
+ - type: string
+ - $ref: '#/components/schemas/InputSlotBlueprint'
+ type: object
+ - type: 'null'
+ title: Inputs
+ output:
+ type: string
+ title: Output
+ template:
+ anyOf:
+ - type: string
+ - $ref: '#/components/schemas/TemplateBlueprint'
+ - type: 'null'
+ title: Template
+ construct:
+ anyOf:
+ - $ref: '#/components/schemas/ConstructBlueprint'
+ - type: 'null'
+ additionalProperties: false
+ type: object
+ required:
+ - description
+ - output
+ title: PipeComposeBlueprint
+ PipeConditionBlueprint:
+ properties:
+ source:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Source
+ pipe_category:
+ type: string
+ const: PipeController
+ title: Pipe Category
+ default: PipeController
+ type:
+ type: string
+ const: PipeCondition
+ title: Type
+ default: PipeCondition
+ description:
+ type: string
+ title: Description
+ inputs:
+ anyOf:
+ - additionalProperties:
+ anyOf:
+ - type: string
+ - $ref: '#/components/schemas/InputSlotBlueprint'
+ type: object
+ - type: 'null'
+ title: Inputs
+ output:
+ type: string
+ title: Output
+ expression_template:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Expression Template
+ expression:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Expression
+ outcomes:
+ additionalProperties:
+ type: string
+ type: object
+ title: Outcomes
+ x-schema-required: true
+ default_outcome:
+ anyOf:
+ - type: string
+ - $ref: '#/components/schemas/SpecialOutcome'
+ title: Default Outcome
+ add_alias_from_expression_to:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Add Alias From Expression To
+ additionalProperties: false
+ type: object
+ required:
+ - description
+ - output
+ - default_outcome
+ title: PipeConditionBlueprint
+ PipeDocGenBlueprint:
+ properties:
+ source:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Source
+ pipe_category:
+ type: string
+ const: PipeOperator
+ title: Pipe Category
+ default: PipeOperator
+ type:
+ type: string
+ const: PipeDocGen
+ title: Type
+ default: PipeDocGen
+ description:
+ type: string
+ title: Description
+ inputs:
+ anyOf:
+ - additionalProperties:
+ anyOf:
+ - type: string
+ - $ref: '#/components/schemas/InputSlotBlueprint'
+ type: object
+ - type: 'null'
+ title: Inputs
+ output:
+ type: string
+ title: Output
+ format:
+ $ref: '#/components/schemas/DocGenFormat'
+ model:
+ anyOf:
+ - $ref: '#/components/schemas/DocGenSetting'
+ - type: string
+ - $ref: '#/components/schemas/ModelReference'
+ - type: 'null'
+ title: Model
+ template:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Template
+ template_file:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Template File
+ filename:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Filename
+ additionalProperties: false
+ type: object
+ required:
+ - description
+ - output
+ - format
+ title: PipeDocGenBlueprint
+ description: 'Generate a document file from a method''s structured result: a PDF, an Excel workbook, a Word document
+ or a PowerPoint deck.
+
+
+ It calls no AI model: it lays out or fills what its inputs already hold. With no template, the pipe lays its inputs
+
+ out by itself (the auto-layout), for every format but `pptx`. `template` is an inline HTML and Jinja2 template, for
+
+ `pdf` only; `template_file` is a path relative to the bundle''s file: an `.html` for `pdf`, an `.xlsx` for `xlsx`,
+ a
+
+ `.docx` for `docx` and a `.pptx` for `pptx`, which `pptx` requires. `filename` is a Jinja expression over the
+
+ inputs; the suffix is added. The output must be a single `Document`, or a concept refining it. `model` names the
+
+ document engine that prints it, a model of the `doc_gen` family such as `reportlab-pdf` or, with the Pipelex
+
+ document generation plugin, `pipelex-pdf`; without it, the model deck''s default for the format and source prints
+
+ it. Which engines a runtime has depends on its plugins: open Pipelex prints a `pdf` without a template on
+
+ `reportlab-pdf`, and a runtime without the engine a step needs refuses the method when it loads.'
+ PipeExtractBlueprint:
+ properties:
+ source:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Source
+ pipe_category:
+ type: string
+ const: PipeOperator
+ title: Pipe Category
+ default: PipeOperator
+ type:
+ type: string
+ const: PipeExtract
+ title: Type
+ default: PipeExtract
+ description:
+ type: string
+ title: Description
+ inputs:
+ anyOf:
+ - additionalProperties:
+ anyOf:
+ - type: string
+ - $ref: '#/components/schemas/InputSlotBlueprint'
+ type: object
+ - type: 'null'
+ title: Inputs
+ output:
+ type: string
+ title: Output
+ model:
+ anyOf:
+ - $ref: '#/components/schemas/ExtractSetting'
+ - type: string
+ - $ref: '#/components/schemas/ModelReference'
+ - type: 'null'
+ title: Model
+ max_page_images:
+ anyOf:
+ - type: integer
+ - type: 'null'
+ title: Max Page Images
+ page_image_captions:
+ anyOf:
+ - type: boolean
+ - type: 'null'
+ title: Page Image Captions
+ page_views:
+ anyOf:
+ - type: boolean
+ - type: 'null'
+ title: Page Views
+ page_views_dpi:
+ anyOf:
+ - type: integer
+ - type: 'null'
+ title: Page Views Dpi
+ render_js:
+ anyOf:
+ - type: boolean
+ - type: 'null'
+ title: Render Js
+ include_raw_html:
+ anyOf:
+ - type: boolean
+ - type: 'null'
+ title: Include Raw Html
+ additionalProperties: false
+ type: object
+ required:
+ - description
+ - output
+ title: PipeExtractBlueprint
+ PipeFactoryErrorType:
+ type: string
+ enum:
+ - unknown_concept
+ - unknown_factory_error
+ title: PipeFactoryErrorType
+ description: 'Types of pipe factory errors.
+
+
+ These error types are raised during pipe creation from blueprints.'
+ PipeFuncBlueprint:
+ properties:
+ source:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Source
+ pipe_category:
+ type: string
+ const: PipeOperator
+ title: Pipe Category
+ default: PipeOperator
+ type:
+ type: string
+ const: PipeFunc
+ title: Type
+ default: PipeFunc
+ description:
+ type: string
+ title: Description
+ inputs:
+ anyOf:
+ - additionalProperties:
+ anyOf:
+ - type: string
+ - $ref: '#/components/schemas/InputSlotBlueprint'
+ type: object
+ - type: 'null'
+ title: Inputs
+ output:
+ type: string
+ title: Output
+ function_name:
+ type: string
+ title: Function Name
+ description: The name of the function to call.
+ additionalProperties: false
+ type: object
+ required:
+ - description
+ - output
+ - function_name
+ title: PipeFuncBlueprint
+ PipeIOArtifacts:
+ properties:
+ pipe_io_contracts:
+ additionalProperties:
+ $ref: '#/components/schemas/PipeIOContract'
+ type: object
+ title: Pipe Io Contracts
+ input_form:
+ additionalProperties:
+ $ref: '#/components/schemas/PipeInputFormDescriptor'
+ type: object
+ title: Input Form
+ output_form:
+ additionalProperties:
+ $ref: '#/components/schemas/PipeOutputFormDescriptor'
+ type: object
+ title: Output Form
+ additionalProperties: false
+ type: object
+ required:
+ - pipe_io_contracts
+ - input_form
+ - output_form
+ title: PipeIOArtifacts
+ description: 'The validate report''s three I/O artifacts, under the report''s names and types.
+
+
+ A grouping, not a new shape: each field is the standard''s artifact, keyed by `pipe_ref`.'
+ PipeIOContract:
+ properties:
+ inputs:
+ additionalProperties:
+ $ref: '#/components/schemas/PipeInputContract'
+ type: object
+ title: Inputs
+ output:
+ $ref: '#/components/schemas/PipeOutputContract'
+ additionalProperties: false
+ type: object
+ required:
+ - inputs
+ - output
+ title: PipeIOContract
+ description: 'The contract of one pipe — one `pipe_io_contracts` entry, with both members required.
+
+
+ `inputs` is a map from authored input name to input contract, and it deliberately contracts no
+
+ order: an ordered view of a pipe''s inputs is the input-form descriptor''s job, which keeps this
+
+ artifact byte-stable whatever a renderer needs. A pipe with no declared inputs carries
+
+ `inputs: {}` — a stated fact, never an omitted member. Closed shape (`extra="forbid"`).'
+ PipeIORequest:
+ properties:
+ files:
+ anyOf:
+ - items:
+ $ref: '#/components/schemas/MthdsFileItem'
+ type: array
+ maxItems: 16
+ minItems: 1
+ - type: 'null'
+ title: Files
+ description: Inline MTHDS bundles forming the closure to resolve (content-passing — no server-side path reads).
+ method_ref:
+ anyOf:
+ - type: string
+ maxLength: 512
+ minLength: 1
+ - type: 'null'
+ title: Method Ref
+ description: Reference to a published method, resolving to its package's `.mthds` files. Address form (`github.com/<owner>/<repo>[/<selector>][@<tag>]`)
+ is fetched and resolved server-side; the registry form stays reserved (501 until a method registry exists).
+ pipe_ref:
+ anyOf:
+ - type: string
+ maxLength: 256
+ minLength: 1
+ - type: 'null'
+ title: Pipe Ref
+ description: Qualified pipe ref (`domain.pipe_code`) to project. Optional — defaults to the fetched package manifest's
+ `main_pipe` on a `method_ref` request, else to the closure's declared `main_pipe`; a closure declaring none, or
+ several, with no manifest `main_pipe` to settle it, requires it explicitly.
+ all_pipes:
+ type: boolean
+ title: All Pipes
+ description: 'Describe every pipe the closure loads instead of the selected one. The artifact maps are then keyed
+ by every pipe, and the route never refuses for want of an entry pipe: `pipe_ref` on the valid arm is the requested
+ ref, else the method''s own entry pipe, else `null`.'
+ default: false
+ include_files:
+ type: boolean
+ title: Include Files
+ description: 'Echo the resolved closure''s `.mthds` files on the valid arm, in the request''s own `files[]` shape:
+ the request''s files for inline `files[]`, the fetched package''s `.mthds` files under their package-relative
+ paths for a `method_ref`. Absent from the response unless true.'
+ default: false
+ type: object
+ title: PipeIORequest
+ description: 'The pipe I/O request: the crate routes'' closure selector and pipe selector, plus the whole-method and
+ echo opt-ins.
+
+
+ The hosted catalog selector is replaced by `files` before the request reaches the runner, so this
+
+ request has no field for it. It takes no `views` either, since the valid arm always carries all
+
+ three artifacts.'
+ PipeIOValidReport:
+ properties:
+ is_valid:
+ type: boolean
+ const: true
+ title: Is Valid
+ default: true
+ pipe_ref:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Pipe Ref
+ description: The qualified `domain.pipe_code` the selection resolved, read back off the resolved pipe and never
+ echoed from the request. `null` only under `all_pipes` when no pipe was requested and the method declares no single
+ entry pipe.
+ pipe_io_contracts:
+ additionalProperties:
+ $ref: '#/components/schemas/PipeIOContract'
+ type: object
+ title: Pipe Io Contracts
+ description: The standard's pipe I/O contracts, keyed by qualified `pipe_ref`.
+ input_form:
+ additionalProperties:
+ $ref: '#/components/schemas/PipeInputFormDescriptor'
+ type: object
+ title: Input Form
+ description: The standard's input-form descriptors, keyed by qualified `pipe_ref`.
+ output_form:
+ additionalProperties:
+ $ref: '#/components/schemas/PipeOutputFormDescriptor'
+ type: object
+ title: Output Form
+ description: The standard's output-form descriptors, keyed by qualified `pipe_ref`.
+ default_pipe_ref:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Default Pipe Ref
+ description: 'The method''s own entry pipe: the selection chain without the request''s `pipe_ref` — the fetched
+ package manifest''s `main_pipe`, else the closure''s single `main_pipe` declaration. A stated `null` when that
+ chain finds none or several. Not `/validate`''s field of the same name, which is the run default.'
+ pending_signatures:
+ items:
+ type: string
+ type: array
+ title: Pending Signatures
+ description: The qualified refs of every pipe of the closure still declared as a signature, exactly as on `/validate`.
+ is_runnable:
+ type: boolean
+ title: Is Runnable
+ description: '`not pending_signatures`, exactly as on `/validate`. No dry run backs it.'
+ files:
+ items:
+ $ref: '#/components/schemas/MthdsFileItem'
+ type: array
+ title: Files
+ description: 'The resolved closure''s `.mthds` files, in the request''s `files[]` shape. Present only with `include_files:
+ true`.'
+ type: object
+ required:
+ - pipe_ref
+ - pipe_io_contracts
+ - input_form
+ - output_form
+ - default_pipe_ref
+ - pending_signatures
+ - is_runnable
+ title: PipeIOValidReport
+ description: 'The 200 **valid** arm: the method''s three I/O artifacts, with the selection and the runnability facts
+ beside them.
+
+
+ The three maps share one key set: the resolved `pipe_ref` alone by default, every pipe the
+
+ closure loads under `all_pipes`. Each map is the standard''s artifact under its neutral name, and
+
+ for a closure `/validate` also accepts it equals `/validate`''s same-named field restricted to the
+
+ same keys — both routes call the one builder, and both dump without dropping null members.
+
+ `is_valid: true` means what it means on `/resolve`: the closure parsed, loaded and passed static
+
+ validation. No dry run ran; that verdict stays `/validate`''s.'
+ PipeImgGenBlueprint:
+ properties:
+ source:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Source
+ pipe_category:
+ type: string
+ const: PipeOperator
+ title: Pipe Category
+ default: PipeOperator
+ type:
+ type: string
+ const: PipeImgGen
+ title: Type
+ default: PipeImgGen
+ description:
+ type: string
+ title: Description
+ inputs:
+ anyOf:
+ - additionalProperties:
+ anyOf:
+ - type: string
+ - $ref: '#/components/schemas/InputSlotBlueprint'
+ type: object
+ - type: 'null'
+ title: Inputs
+ output:
+ type: string
+ title: Output
+ prompt:
+ type: string
+ title: Prompt
+ negative_prompt:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Negative Prompt
+ model:
+ anyOf:
+ - $ref: '#/components/schemas/ImgGenSetting'
+ - type: string
+ - $ref: '#/components/schemas/ModelReference'
+ - type: 'null'
+ title: Model
+ aspect_ratio:
+ anyOf:
+ - $ref: '#/components/schemas/AspectRatio'
+ - type: 'null'
+ size:
+ anyOf:
+ - $ref: '#/components/schemas/SizeTier'
+ - $ref: '#/components/schemas/ImageSize'
+ - type: 'null'
+ title: Size
+ is_raw:
+ anyOf:
+ - type: boolean
+ - type: 'null'
+ title: Is Raw
+ seed:
+ anyOf:
+ - type: integer
+ - type: string
+ const: auto
+ - type: 'null'
+ title: Seed
+ background:
+ anyOf:
+ - $ref: '#/components/schemas/Background'
+ - type: 'null'
+ output_format:
+ anyOf:
+ - $ref: '#/components/schemas/ImageFormat'
+ - type: 'null'
+ additionalProperties: false
+ type: object
+ required:
+ - description
+ - output
+ - prompt
+ title: PipeImgGenBlueprint
+ PipeInputContract:
+ properties:
+ concept_ref:
+ type: string
+ title: Concept Ref
+ presence:
+ $ref: '#/components/schemas/PresenceMarker'
+ multiplicity:
+ $ref: '#/components/schemas/IOMultiplicity'
+ item_count:
+ anyOf:
+ - type: integer
+ - type: 'null'
+ title: Item Count
+ json_schema:
+ additionalProperties: true
+ type: object
+ title: Json Schema
+ additionalProperties: false
+ type: object
+ required:
+ - concept_ref
+ - presence
+ - multiplicity
+ - item_count
+ - json_schema
+ title: PipeInputContract
+ description: 'One declared input slot: the concept it expects, its presence, its plurality and the JSON Schema of its
+ content.
+
+
+ Keyed in `PipeIOContract.inputs` by the authored input name, dotted names included.
+
+ Every member is required: `item_count` is always on the wire, `null` off the fixed arm.
+
+ Closed shape (`extra="forbid"`): an unknown member is version drift, rejected at the parse.'
+ PipeInputFormDescriptor:
+ properties:
+ fields:
+ items:
+ oneOf:
+ - $ref: '#/components/schemas/TextField'
+ - $ref: '#/components/schemas/ProseField'
+ - $ref: '#/components/schemas/DateField'
+ - $ref: '#/components/schemas/NumberField'
+ - $ref: '#/components/schemas/BooleanField'
+ - $ref: '#/components/schemas/EnumField'
+ - $ref: '#/components/schemas/DocumentField'
+ - $ref: '#/components/schemas/ImageField'
+ - $ref: '#/components/schemas/ObjectField'
+ - $ref: '#/components/schemas/ListField'
+ - $ref: '#/components/schemas/UnknownField'
+ discriminator:
+ propertyName: kind
+ mapping:
+ boolean: '#/components/schemas/BooleanField'
+ date: '#/components/schemas/DateField'
+ document: '#/components/schemas/DocumentField'
+ enum: '#/components/schemas/EnumField'
+ image: '#/components/schemas/ImageField'
+ list: '#/components/schemas/ListField'
+ number: '#/components/schemas/NumberField'
+ object: '#/components/schemas/ObjectField'
+ prose: '#/components/schemas/ProseField'
+ text: '#/components/schemas/TextField'
+ unknown: '#/components/schemas/UnknownField'
+ type: array
+ title: Fields
+ additionalProperties: false
+ type: object
+ required:
+ - fields
+ title: PipeInputFormDescriptor
+ description: 'The input form of one pipe — one `input_form` entry.
+
+
+ `fields` holds one descriptor per declared input slot, in authored input order: the order is why
+
+ the descriptor is a sibling artifact of the contract rather than a decoration inside it. A pipe
+
+ with no inputs maps to `{"fields": []}` — an empty form is a valid form, not an omitted entry.
+
+ Closed shape (`extra="forbid"`).'
+ PipeLLMBlueprint:
+ properties:
+ source:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Source
+ pipe_category:
+ type: string
+ const: PipeOperator
+ title: Pipe Category
+ default: PipeOperator
+ type:
+ type: string
+ const: PipeLLM
+ title: Type
+ default: PipeLLM
+ description:
+ type: string
+ title: Description
+ inputs:
+ anyOf:
+ - additionalProperties:
+ anyOf:
+ - type: string
+ - $ref: '#/components/schemas/InputSlotBlueprint'
+ type: object
+ - type: 'null'
+ title: Inputs
+ output:
+ type: string
+ title: Output
+ model:
+ anyOf:
+ - $ref: '#/components/schemas/LLMSetting'
+ - type: string
+ - $ref: '#/components/schemas/ModelReference'
+ - type: 'null'
+ title: Model
+ model_to_structure:
+ anyOf:
+ - $ref: '#/components/schemas/LLMSetting'
+ - type: string
+ - $ref: '#/components/schemas/ModelReference'
+ - type: 'null'
+ title: Model To Structure
+ system_prompt:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: System Prompt
+ prompt:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Prompt
+ structuring_method:
+ anyOf:
+ - $ref: '#/components/schemas/StructuringMethod'
+ - type: 'null'
+ templating_style:
+ anyOf:
+ - $ref: '#/components/schemas/TagStyle'
+ - $ref: '#/components/schemas/TemplatingStyle'
+ - type: 'null'
+ title: Templating Style
+ additionalProperties: false
+ type: object
+ required:
+ - description
+ - output
+ title: PipeLLMBlueprint
+ PipeOutputContract:
+ properties:
+ concept_ref:
+ type: string
+ title: Concept Ref
+ multiplicity:
+ $ref: '#/components/schemas/IOMultiplicity'
+ item_count:
+ anyOf:
+ - type: integer
+ - type: 'null'
+ title: Item Count
+ optional:
+ type: boolean
+ title: Optional
+ json_schema:
+ additionalProperties: true
+ type: object
+ title: Json Schema
+ additionalProperties: false
+ type: object
+ required:
+ - concept_ref
+ - multiplicity
+ - item_count
+ - optional
+ - json_schema
+ title: PipeOutputContract
+ description: 'What the pipe resolves to: the concept it produces, how many items that is, whether it may be absent,
+ and the shape of its payload.
+
+
+ Deliberately asymmetric with the input side in exactly one place, and no longer in a second.
+
+ An output carries a two-valued `optional` where an input carries a three-valued `presence`,
+
+ because `!` MUST NOT appear on an output — a force marker is a use-site assertion about an
+
+ input, so a three-valued output slot would have an arm nothing can ever produce. That
+
+ asymmetry is a language fact and it stays.
+
+
+ The schema asymmetry was not. An output used to carry none, on the reasoning that "the payload
+
+ a run produces is the run''s own result" — which answers *what did this run produce?*, correctly
+
+ not a contract''s business, rather than the question a consumer actually asks: *what shape will
+
+ it be?* That is declared in the `.mthds` source and knowable before any run happens, exactly as
+
+ it is on the input side. Withholding it left every consumer inferring a payload''s shape by
+
+ inspecting it, which is guessing at the standard rather than reading it.
+
+
+ Closed shape (`extra="forbid"`).'
+ PipeOutputFormDescriptor:
+ properties:
+ field:
+ oneOf:
+ - $ref: '#/components/schemas/TextField'
+ - $ref: '#/components/schemas/ProseField'
+ - $ref: '#/components/schemas/DateField'
+ - $ref: '#/components/schemas/NumberField'
+ - $ref: '#/components/schemas/BooleanField'
+ - $ref: '#/components/schemas/EnumField'
+ - $ref: '#/components/schemas/DocumentField'
+ - $ref: '#/components/schemas/ImageField'
+ - $ref: '#/components/schemas/ObjectField'
+ - $ref: '#/components/schemas/ListField'
+ - $ref: '#/components/schemas/UnknownField'
+ title: Field
+ discriminator:
+ propertyName: kind
+ mapping:
+ boolean: '#/components/schemas/BooleanField'
+ date: '#/components/schemas/DateField'
+ document: '#/components/schemas/DocumentField'
+ enum: '#/components/schemas/EnumField'
+ image: '#/components/schemas/ImageField'
+ list: '#/components/schemas/ListField'
+ number: '#/components/schemas/NumberField'
+ object: '#/components/schemas/ObjectField'
+ prose: '#/components/schemas/ProseField'
+ text: '#/components/schemas/TextField'
+ unknown: '#/components/schemas/UnknownField'
+ additionalProperties: false
+ type: object
+ required:
+ - field
+ title: PipeOutputFormDescriptor
+ description: 'The output form of one pipe — one `output_form` entry, carrying the single output node.
+
+
+ Closed shape (`extra="forbid"`). The node itself is an `InputFormField`, so it is parsed by
+
+ the same discriminated union every input node is, and a consumer narrows it the same way.'
+ PipeOutputWire:
+ properties:
+ working_memory:
+ $ref: '#/components/schemas/WorkingMemory'
+ pipeline_run_id:
+ type: string
+ title: Pipeline Run Id
+ default: untitled
+ working_memory_raw:
+ anyOf:
+ - additionalProperties: true
+ type: object
+ - type: 'null'
+ title: Working Memory Raw
+ graph_spec:
+ anyOf:
+ - $ref: '#/components/schemas/GraphSpec'
+ - type: 'null'
+ graph_assembly_error:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Graph Assembly Error
+ pipe_io_artifacts:
+ anyOf:
+ - $ref: '#/components/schemas/PipeIOArtifacts'
+ - type: 'null'
+ pipe_io_artifacts_error:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Pipe Io Artifacts Error
+ tokens_usages:
+ anyOf:
+ - items:
+ $ref: '#/components/schemas/TokensUsageRecord'
+ type: array
+ - type: 'null'
+ title: Tokens Usages
+ usage_assembly_error:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Usage Assembly Error
+ additionalProperties: false
+ type: object
+ title: PipeOutputWire
+ description: '`PipeOutput` as it crosses the client boundary: usages trimmed to wire records.
+
+
+ The route applies pipelex''s `apply_tokens_usage_wire_shape` to the response dump, so
+
+ `tokens_usages` carries flat `TokensUsageRecord`s — not the internal usage models with
+
+ their `job_metadata` plumbing and `unit_costs` rate table.'
+ PipeParallelBlueprint:
+ properties:
+ source:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Source
+ pipe_category:
+ type: string
+ const: PipeController
+ title: Pipe Category
+ default: PipeController
+ type:
+ type: string
+ const: PipeParallel
+ title: Type
+ default: PipeParallel
+ description:
+ type: string
+ title: Description
+ inputs:
+ anyOf:
+ - additionalProperties:
+ anyOf:
+ - type: string
+ - $ref: '#/components/schemas/InputSlotBlueprint'
+ type: object
+ - type: 'null'
+ title: Inputs
+ output:
+ type: string
+ title: Output
+ branches:
+ items:
+ $ref: '#/components/schemas/SubPipeBlueprint'
+ type: array
+ title: Branches
+ add_each_output:
+ type: boolean
+ title: Add Each Output
+ default: false
+ additionalProperties: false
+ type: object
+ required:
+ - description
+ - output
+ - branches
+ title: PipeParallelBlueprint
+ PipeSearchBlueprint:
+ properties:
+ source:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Source
+ pipe_category:
+ type: string
+ const: PipeOperator
+ title: Pipe Category
+ default: PipeOperator
+ type:
+ type: string
+ const: PipeSearch
+ title: Type
+ default: PipeSearch
+ description:
+ type: string
+ title: Description
+ inputs:
+ anyOf:
+ - additionalProperties:
+ anyOf:
+ - type: string
+ - $ref: '#/components/schemas/InputSlotBlueprint'
+ type: object
+ - type: 'null'
+ title: Inputs
+ output:
+ type: string
+ title: Output
+ prompt:
+ type: string
+ title: Prompt
+ model:
+ anyOf:
+ - $ref: '#/components/schemas/SearchSetting'
+ - type: string
+ - $ref: '#/components/schemas/ModelReference'
+ - type: 'null'
+ title: Model
+ include_images:
+ anyOf:
+ - type: boolean
+ - type: 'null'
+ title: Include Images
+ max_results:
+ anyOf:
+ - type: integer
+ - type: 'null'
+ title: Max Results
+ from_date:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: From Date
+ to_date:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: To Date
+ include_domains:
+ anyOf:
+ - items:
+ type: string
+ type: array
+ - type: 'null'
+ title: Include Domains
+ exclude_domains:
+ anyOf:
+ - items:
+ type: string
+ type: array
+ - type: 'null'
+ title: Exclude Domains
+ additionalProperties: false
+ type: object
+ required:
+ - description
+ - output
+ - prompt
+ title: PipeSearchBlueprint
+ PipeSequenceBlueprint:
+ properties:
+ source:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Source
+ pipe_category:
+ type: string
+ const: PipeController
+ title: Pipe Category
+ default: PipeController
+ type:
+ type: string
+ const: PipeSequence
+ title: Type
+ default: PipeSequence
+ description:
+ type: string
+ title: Description
+ inputs:
+ anyOf:
+ - additionalProperties:
+ anyOf:
+ - type: string
+ - $ref: '#/components/schemas/InputSlotBlueprint'
+ type: object
+ - type: 'null'
+ title: Inputs
+ output:
+ type: string
+ title: Output
+ steps:
+ items:
+ $ref: '#/components/schemas/SubPipeBlueprint'
+ type: array
+ title: Steps
+ additionalProperties: false
+ type: object
+ required:
+ - description
+ - output
+ - steps
+ title: PipeSequenceBlueprint
+ PipeSignatureBlueprint:
+ properties:
+ source:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Source
+ description:
+ type: string
+ title: Description
+ inputs:
+ anyOf:
+ - additionalProperties:
+ anyOf:
+ - type: string
+ - $ref: '#/components/schemas/InputSlotBlueprint'
+ type: object
+ - type: 'null'
+ title: Inputs
+ output:
+ type: string
+ title: Output
+ signature_for:
+ anyOf:
+ - $ref: '#/components/schemas/PipeType'
+ - type: 'null'
+ description: Intended downstream pipe type when this signature is implemented (optional hint for agents).
+ additionalProperties: false
+ type: object
+ required:
+ - description
+ - output
+ title: PipeSignatureBlueprint
+ description: 'Contract-only pipe blueprint.
+
+
+ A `PipeSignature` declares inputs and output but has no implementation. It exists so
+
+ that an in-progress pipeline can be validated (dry-run mocks the declared output)
+
+ before all its pipes are implemented.'
+ PipeStructureBlueprint:
+ properties:
+ source:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Source
+ pipe_category:
+ type: string
+ const: PipeOperator
+ title: Pipe Category
+ default: PipeOperator
+ type:
+ type: string
+ const: PipeStructure
+ title: Type
+ default: PipeStructure
+ description:
+ type: string
+ title: Description
+ inputs:
+ anyOf:
+ - additionalProperties:
+ anyOf:
+ - type: string
+ - $ref: '#/components/schemas/InputSlotBlueprint'
+ type: object
+ - type: 'null'
+ title: Inputs
+ output:
+ type: string
+ title: Output
+ model:
+ anyOf:
+ - $ref: '#/components/schemas/LLMSetting'
+ - type: string
+ - $ref: '#/components/schemas/ModelReference'
+ - type: 'null'
+ title: Model
+ additionalProperties: false
+ type: object
+ required:
+ - description
+ - output
+ title: PipeStructureBlueprint
+ PipeType:
+ type: string
+ enum:
+ - PipeFunc
+ - PipeImgGen
+ - PipeCompose
+ - PipeLLM
+ - PipeExtract
+ - PipeSearch
+ - PipeStructure
+ - PipeDocGen
+ - PipeBatch
+ - PipeCondition
+ - PipeParallel
+ - PipeSequence
+ title: PipeType
+ PipeValidationErrorType:
+ type: string
+ enum:
+ - missing_input_variable
+ - extraneous_input_variable
+ - input_stuff_spec_mismatch
+ - inadequate_output_concept
+ - inadequate_output_multiplicity
+ - circular_dependency_error
+ - llm_output_cannot_be_image
+ - invalid_pipe_code_syntax
+ - unknown_pipe_type
+ - missing_pipe_type
+ - batch_item_name_collision
+ - optional_marker_invalid
+ - optional_not_handled
+ - optional_output_required
+ - optional_input_unguarded
+ - optional_branch_required_field
+ - template_private_name
+ - optional_force_redundant
+ - input_presence_vacuous
+ - native_concept_redeclaration
+ - unresolved_concept
+ - unresolved_pipe_dependency
+ - unknown_model
+ - unknown_validation_error
+ title: PipeValidationErrorType
+ description: 'Types of pipe validation errors.
+
+
+ These error types are raised during pipe validation from Pipe/Concept classes.'
+ PipelexApiExecuteResponse:
+ properties:
+ pipeline_run_id:
+ type: string
+ title: Pipeline Run Id
+ pipe_output:
+ $ref: '#/components/schemas/PipeOutputWire'
+ created_at:
+ type: string
+ title: Created At
+ state:
+ $ref: '#/components/schemas/RunState'
+ finished_at:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Finished At
+ main_stuff_name:
+ type: string
+ title: Main Stuff Name
+ method_provenance:
+ anyOf:
+ - $ref: '#/components/schemas/MethodProvenance'
+ - type: 'null'
+ description: 'PIPELEX-API EXTENSION (not part of the MTHDS Protocol) — provenance of a `method_ref` run: the package''s
+ resolved full address, the requested tag (null for a bare address), and the commit SHA that was actually fetched.
+ The SHA is what keeps the run explainable when a tag moves. Absent (or null) for runs from inline source or a
+ bundle.'
+ additionalProperties: true
+ type: object
+ required:
+ - pipeline_run_id
+ - pipe_output
+ - created_at
+ - state
+ - main_stuff_name
+ title: PipelexApiExecuteResponse
+ description: 'Documented 200 body of `POST /execute` — the run result with the wire-shaped `pipe_output`.
+
+
+ Used only to publish the OpenAPI response schema. `/execute` returns a `JSONResponse`
+
+ built from the trimmed dump, so FastAPI never serializes through this model; declaring it
+
+ is what keeps the published artifact honest about what the route actually emits
+
+ (`method_provenance` is attached to the dump by the route for `method_ref` runs, and is
+
+ absent otherwise).'
+ PipelexApiStartResponse:
+ properties:
+ pipeline_run_id:
+ type: string
+ title: Pipeline Run Id
+ created_at:
+ type: string
+ title: Created At
+ state:
+ $ref: '#/components/schemas/RunState'
+ finished_at:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Finished At
+ workflow_id:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Workflow Id
+ method_provenance:
+ anyOf:
+ - $ref: '#/components/schemas/MethodProvenance'
+ - type: 'null'
+ description: 'PIPELEX-API EXTENSION (not part of the MTHDS Protocol) — provenance of a `method_ref` run: the package''s
+ resolved full address, the requested tag (null for a bare address), and the commit SHA that was actually fetched.
+ The SHA is what keeps the run explainable when a tag moves. Absent (or null) for runs from inline source or a
+ bundle.'
+ additionalProperties: true
+ type: object
+ required:
+ - pipeline_run_id
+ - created_at
+ - state
+ title: PipelexApiStartResponse
+ description: 'The 202 body of `POST /start` — the protocol''s start ack plus this server''s `method_provenance` extension.
+
+
+ Unlike its `/execute` counterpart this model IS what the route returns (FastAPI serializes
+
+ through it): the ack is small, so wrapping it costs nothing and keeps the artifact and the
+
+ wire in lockstep. `method_provenance` is populated for `method_ref` runs and null otherwise.'
+ PipelexBundleBlueprint:
+ properties:
+ source:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Source
+ domain:
+ type: string
+ title: Domain
+ description:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Description
+ system_prompt:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: System Prompt
+ main_pipe:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Main Pipe
+ concept:
+ anyOf:
+ - additionalProperties:
+ anyOf:
+ - $ref: '#/components/schemas/ConceptBlueprint'
+ - type: string
+ type: object
+ - type: 'null'
+ title: Concept
+ pipe:
+ anyOf:
+ - additionalProperties:
+ oneOf:
+ - $ref: '#/components/schemas/PipeFuncBlueprint'
+ - $ref: '#/components/schemas/PipeImgGenBlueprint'
+ - $ref: '#/components/schemas/PipeComposeBlueprint'
+ - $ref: '#/components/schemas/PipeLLMBlueprint'
+ - $ref: '#/components/schemas/PipeExtractBlueprint'
+ - $ref: '#/components/schemas/PipeSearchBlueprint'
+ - $ref: '#/components/schemas/PipeStructureBlueprint'
+ - $ref: '#/components/schemas/PipeDocGenBlueprint'
+ - $ref: '#/components/schemas/PipeBatchBlueprint'
+ - $ref: '#/components/schemas/PipeConditionBlueprint'
+ - $ref: '#/components/schemas/PipeParallelBlueprint'
+ - $ref: '#/components/schemas/PipeSequenceBlueprint'
+ - $ref: '#/components/schemas/PipeSignatureBlueprint'
+ discriminator:
+ propertyName: type
+ mapping:
+ PipeBatch: '#/components/schemas/PipeBatchBlueprint'
+ PipeCompose: '#/components/schemas/PipeComposeBlueprint'
+ PipeCondition: '#/components/schemas/PipeConditionBlueprint'
+ PipeDocGen: '#/components/schemas/PipeDocGenBlueprint'
+ PipeExtract: '#/components/schemas/PipeExtractBlueprint'
+ PipeFunc: '#/components/schemas/PipeFuncBlueprint'
+ PipeImgGen: '#/components/schemas/PipeImgGenBlueprint'
+ PipeLLM: '#/components/schemas/PipeLLMBlueprint'
+ PipeParallel: '#/components/schemas/PipeParallelBlueprint'
+ PipeSearch: '#/components/schemas/PipeSearchBlueprint'
+ PipeSequence: '#/components/schemas/PipeSequenceBlueprint'
+ PipeSignature: '#/components/schemas/PipeSignatureBlueprint'
+ PipeStructure: '#/components/schemas/PipeStructureBlueprint'
+ type: object
+ - type: 'null'
+ title: Pipe
+ additionalProperties: false
+ type: object
+ required:
+ - domain
+ title: PipelexBundleBlueprint
+ PipelexModelDeck:
+ properties:
+ models:
+ items:
+ $ref: '#/components/schemas/ModelInfo'
+ type: array
+ title: Models
+ aliases:
+ additionalProperties:
+ additionalProperties:
+ type: string
+ type: object
+ type: object
+ title: Aliases
+ waterfalls:
+ additionalProperties:
+ additionalProperties:
+ items:
+ type: string
+ type: array
+ type: object
+ type: object
+ title: Waterfalls
+ additionalProperties: true
+ type: object
+ title: PipelexModelDeck
+ description: 'Pipelex''s model deck — the protocol base plus this implementation''s
+
+ routing metadata (aliases, waterfalls), keyed by model category.
+
+
+ The routing extensions are category-scoped on purpose: the same alias name
+
+ (e.g. `default-small`) legitimately exists in several categories pointing at
+
+ different models, so a flat map would silently lose entries on collision.'
+ PipelexVersionInfo:
+ properties:
+ protocol_version:
+ type: string
+ title: Protocol Version
+ runner_version:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Runner Version
+ implementation:
+ type: string
+ title: Implementation
+ implementation_version:
+ type: string
+ title: Implementation Version
+ runtime_version:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Runtime Version
+ additionalProperties: true
+ type: object
+ required:
+ - protocol_version
+ - implementation
+ - implementation_version
+ title: PipelexVersionInfo
+ description: 'Pipelex''s version handshake — the protocol base plus this
+
+ implementation''s identification.'
+ PipelineRef:
+ properties:
+ domain:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Domain
+ main_pipe:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Main Pipe
+ entrypoint:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Entrypoint
+ additionalProperties: false
+ type: object
+ title: PipelineRef
+ description: Reference to the pipeline that was executed.
+ PresenceMarker:
+ type: string
+ enum:
+ - plain
+ - optional
+ - force
+ title: PresenceMarker
+ description: 'The authored presence marker of a declared input slot, verbatim and three-valued.
+
+
+ `plain` (no marker) and `force` (`!`) are the same requirement on the caller — the slot
+
+ must be supplied — and differ only in what the author asserted; `optional` (`?`) means the
+
+ caller may omit the slot and the pipe handles the absence itself. The distinction is kept on
+
+ the wire because lint and graph surfaces read it, and a producer flattening it to a boolean
+
+ would destroy it for every consumer at once. A consumer that only needs "may this be absent?"
+
+ answers it as `is_optional`, in exactly one place.'
+ ProblemDocument:
+ properties:
+ type:
+ type: string
+ title: Type
+ description: 'Stable URI for the error class: `https://docs.pipelex.com/latest/errors/<kebab-class-name>/`.'
+ title:
+ type: string
+ title: Title
+ description: Short, human-readable summary of the error class.
+ status:
+ type: integer
+ title: Status
+ description: HTTP status code, repeated in the body per RFC 7807.
+ detail:
+ type: string
+ title: Detail
+ description: Human-readable explanation of this specific failure. Redacted under `ERROR_DISCLOSURE=strict`.
+ instance:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Instance
+ description: Path of the request that failed.
+ request_id:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Request Id
+ description: Correlation id, echoed in the `X-Request-ID` response header.
+ error_type:
+ type: string
+ title: Error Type
+ description: Stable class name of the originating error (e.g. `ValidateBundleError`, `Unauthenticated`).
+ error_domain:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Error Domain
+ description: '`input` (caller can fix it → 422), `config` or `runtime` (deployment must fix it → 500). Absent for
+ domain-less errors.'
+ retryable:
+ anyOf:
+ - type: boolean
+ - type: 'null'
+ title: Retryable
+ description: Whether retrying the same request can plausibly succeed. Always present on API-authored errors; on
+ pipelex errors only when the originating error classifies it.
+ error_category:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Error Category
+ description: Finer classification, when the originating error provides one (inference errors).
+ user_action:
+ anyOf:
+ - $ref: '#/components/schemas/UserAction'
+ - type: 'null'
+ description: Structured suggestion of what the caller should do next, when available.
+ model:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Model
+ description: Inference model that failed. Stripped under `ERROR_DISCLOSURE=strict`.
+ provider:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Provider
+ description: Inference provider that failed. Stripped under `ERROR_DISCLOSURE=strict`.
+ provider_metadata:
+ anyOf:
+ - $ref: '#/components/schemas/ProviderErrorMetadata'
+ - type: 'null'
+ description: Upstream provider error metadata. Stripped (bar a curated slice) under `ERROR_DISCLOSURE=strict`.
+ validation_errors:
+ anyOf:
+ - items:
+ $ref: '#/components/schemas/ValidationErrorItem'
+ type: array
+ - type: 'null'
+ title: Validation Errors
+ description: Structured per-error diagnostics, carried by a `ValidateBundleError`. Each item may carry a `suggested_fix`.
+ Retained under `ERROR_DISCLOSURE=strict` — it describes the caller's own bundle, not server internals. On `/validate`,
+ `/resolve`, `/codegen` and `/build/*` an invalid bundle is a **200** verdict instead, so the items ride the response
+ body there rather than a problem document.
+ additionalProperties: true
+ type: object
+ required:
+ - type
+ - title
+ - status
+ - detail
+ - error_type
+ title: ProblemDocument
+ description: 'An RFC 7807 `application/problem+json` error body — the shape of every failure response.
+
+
+ Standard RFC 7807 members (`type`, `title`, `status`, `detail`, `instance`)
+
+ plus the extension members pipelex''s classification adds. Only `type`,
+
+ `title`, `status`, `detail`, and `error_type` are always present: the rest
+
+ ride along when the originating error populates them, so a consumer must
+
+ treat them as optional. `extra="allow"` mirrors RFC 7807''s open-ended
+
+ extension-member rule.'
+ PromptImageDetail:
+ type: string
+ enum:
+ - high
+ - low
+ - auto
+ title: PromptImageDetail
+ ProseField:
+ properties:
+ title:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Title
+ concept_ref:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Concept Ref
+ refines:
+ anyOf:
+ - items:
+ type: string
+ type: array
+ - type: 'null'
+ title: Refines
+ description:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Description
+ required:
+ type: boolean
+ title: Required
+ presence:
+ anyOf:
+ - $ref: '#/components/schemas/PresenceMarker'
+ - type: 'null'
+ gating:
+ anyOf:
+ - type: boolean
+ - type: 'null'
+ title: Gating
+ default_value:
+ title: Default Value
+ examples:
+ anyOf:
+ - items: {}
+ type: array
+ - type: 'null'
+ title: Examples
+ hints:
+ anyOf:
+ - additionalProperties:
+ type: string
+ type: object
+ - type: 'null'
+ title: Hints
+ min_length:
+ anyOf:
+ - type: integer
+ - type: 'null'
+ title: Min Length
+ max_length:
+ anyOf:
+ - type: integer
+ - type: 'null'
+ title: Max Length
+ pattern:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Pattern
+ format:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Format
+ kind:
+ type: string
+ const: prose
+ title: Kind
+ default: prose
+ name:
+ type: string
+ title: Name
+ additionalProperties: false
+ type: object
+ required:
+ - required
+ - name
+ title: ProseField
+ description: '`prose` at a named position.'
+ ProseItem:
+ properties:
+ title:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Title
+ concept_ref:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Concept Ref
+ refines:
+ anyOf:
+ - items:
+ type: string
+ type: array
+ - type: 'null'
+ title: Refines
+ description:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Description
+ required:
+ type: boolean
+ title: Required
+ presence:
+ anyOf:
+ - $ref: '#/components/schemas/PresenceMarker'
+ - type: 'null'
+ gating:
+ anyOf:
+ - type: boolean
+ - type: 'null'
+ title: Gating
+ default_value:
+ title: Default Value
+ examples:
+ anyOf:
+ - items: {}
+ type: array
+ - type: 'null'
+ title: Examples
+ hints:
+ anyOf:
+ - additionalProperties:
+ type: string
+ type: object
+ - type: 'null'
+ title: Hints
+ min_length:
+ anyOf:
+ - type: integer
+ - type: 'null'
+ title: Min Length
+ max_length:
+ anyOf:
+ - type: integer
+ - type: 'null'
+ title: Max Length
+ pattern:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Pattern
+ format:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Format
+ kind:
+ type: string
+ const: prose
+ title: Kind
+ default: prose
+ additionalProperties: false
+ type: object
+ required:
+ - required
+ title: ProseItem
+ description: '`prose` — flowing free text.'
+ ProviderErrorMetadata:
+ properties:
+ provider:
+ $ref: '#/components/schemas/ProviderName'
+ sdk_exception_type:
+ type: string
+ title: Sdk Exception Type
+ message:
+ type: string
+ title: Message
+ default: ''
+ status_code:
+ anyOf:
+ - type: integer
+ - type: 'null'
+ title: Status Code
+ request_id:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Request Id
+ retry_after_seconds:
+ anyOf:
+ - type: number
+ - type: 'null'
+ title: Retry After Seconds
+ provider_error_code:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Provider Error Code
+ type: object
+ required:
+ - provider
+ - sdk_exception_type
+ title: ProviderErrorMetadata
+ description: 'Structured SDK metadata attached to inference errors.
+
+
+ Carries information downstream consumers (retry, temporal, CLI) need
+
+ without having to scrape it back from the exception chain.'
+ ProviderName:
+ type: string
+ enum:
+ - openai
+ - anthropic
+ - google
+ - mistral
+ - azure
+ - bedrock
+ - fal
+ - huggingface
+ - gateway
+ - linkup
+ - docling
+ - pypdfium2
+ title: ProviderName
+ description: Identifies the inference provider an SDK error originated from.
+ Quality:
+ type: string
+ enum:
+ - low
+ - medium
+ - high
+ title: Quality
+ Range:
+ properties:
+ start_offset:
+ type: integer
+ title: Start Offset
+ end_offset:
+ type: integer
+ title: End Offset
+ start_line:
+ type: integer
+ title: Start Line
+ start_col:
+ type: integer
+ title: Start Col
+ end_line:
+ type: integer
+ title: End Line
+ end_col:
+ type: integer
+ title: End Col
+ type: object
+ required:
+ - start_offset
+ - end_offset
+ - start_line
+ - start_col
+ - end_line
+ - end_col
+ title: Range
+ description: Byte offsets plus 1-based line/column coordinates from `pipelex-tools-py`.
+ ReasoningEffort:
+ type: string
+ enum:
+ - none
+ - minimal
+ - low
+ - medium
+ - high
+ - xhigh
+ - max
+ title: ReasoningEffort
+ RemapValueOp:
+ properties:
+ table_path:
+ items:
+ type: string
+ type: array
+ title: Table Path
+ kind:
+ type: string
+ const: remap_value
+ title: Kind
+ default: remap_value
+ key:
+ type: string
+ title: Key
+ mapping:
+ additionalProperties:
+ type: string
+ type: object
+ minProperties: 1
+ title: Mapping
+ additionalProperties: false
+ type: object
+ required:
+ - table_path
+ - key
+ - mapping
+ title: RemapValueOp
+ description: 'Rewrite ``key``''s value through ``mapping``, doing nothing when it is not a mapped value.
+
+
+ Only string values are remapped: the operation exists for renamed enumerated values, whose
+
+ TOML representation is always a string.
+
+
+ ``key`` may be the wildcard segment, and this is the one kind for which it means anything:
+
+ "each key of the addressed table". A mapping from the user''s own keys to an enumerated value
+
+ — ``dict[str, LogLevel]`` — keeps its spellings under keys only the document can enumerate,
+
+ so no fixed ``key`` reaches them and this is the only shape in which a member renamed beneath
+
+ an open mapping can be repaired at all.'
+ RenameTableKeyOp:
+ properties:
+ table_path:
+ items:
+ type: string
+ type: array
+ title: Table Path
+ kind:
+ type: string
+ const: rename_table_key
+ title: Kind
+ default: rename_table_key
+ key:
+ type: string
+ title: Key
+ new_key:
+ type: string
+ title: New Key
+ additionalProperties: false
+ type: object
+ required:
+ - table_path
+ - key
+ - new_key
+ title: RenameTableKeyOp
+ description: Rename ``key`` to ``new_key`` in place within the addressed table, keeping its position.
+ ResolveValidReport:
+ properties:
+ is_valid:
+ type: boolean
+ const: true
+ title: Is Valid
+ default: true
+ crate:
+ additionalProperties: true
+ type: object
+ title: Crate
+ description: The normalized library crate (canonical JSON encoding, `fingerprint` included).
+ message:
+ type: string
+ title: Message
+ description: Status message
+ default: MTHDS library resolved successfully
+ type: object
+ required:
+ - crate
+ title: ResolveValidReport
+ description: 'The 200 **valid** arm: the normalized library crate, ready for any consumer''s emitter.
+
+
+ The crate rides as the canonical JSON encoding''s object form (top-level maps key-sorted,
+
+ non-semantic provenance dropped) — the same bytes `pipelex resolve --format json` prints, so a
+
+ fingerprint computed from either surface agrees. Its `fingerprint` and `mthds_version` members
+
+ ride inside the crate payload itself.'
+ RunState:
+ type: string
+ enum:
+ - STARTED
+ - RUNNING
+ - COMPLETED
+ - FAILED
+ - CANCELLED
+ - ERROR
+ title: RunState
+ description: Run lifecycle state — a pipelex extension field on run responses (the protocol defines none).
+ RunnerStructures:
+ properties:
+ directory:
+ type: string
+ title: Directory
+ description: Directory (relative to the runner script) to write the artifacts and lock into.
+ default: structures
+ artifacts:
+ items:
+ $ref: '#/components/schemas/GeneratedArtifact'
+ type: array
+ title: Artifacts
+ description: The stamped generated files (paths relative to `directory`).
+ lock:
+ type: string
+ title: Lock
+ description: The lock content (TOML) tracking the artifact set — write verbatim inside `directory`.
+ lock_filename:
+ type: string
+ title: Lock Filename
+ description: Filename the lock content must be written as.
+ default: codegen.lock
+ type: object
+ required:
+ - lock
+ title: RunnerStructures
+ description: 'The typed-structures projection the runner script imports from (`from structures.structures import ...`).
+
+
+ The same stamped `python-structures` artifacts + `codegen.lock` a local `pipelex build runner`
+
+ scaffolds into `<output>/structures/` — write `artifacts` and the lock under `directory` and
+
+ the returned `python_code` runs against them, with the offline `codegen check` passing there.'
+ SearchSetting:
+ properties:
+ model:
+ type: string
+ title: Model
+ include_images:
+ type: boolean
+ title: Include Images
+ default: false
+ include_inline_citations:
+ type: boolean
+ title: Include Inline Citations
+ default: true
+ max_results:
+ anyOf:
+ - type: integer
+ minimum: 1.0
+ - type: 'null'
+ title: Max Results
+ description:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Description
+ additionalProperties: false
+ type: object
+ required:
+ - model
+ title: SearchSetting
+ ServiceIdentity:
+ properties:
+ message:
+ type: string
+ title: Message
+ description: Name of the service answering on this origin.
+ type: object
+ required:
+ - message
+ title: ServiceIdentity
+ description: Body of `GET /` — the service identity banner.
+ SetKeyOp:
+ properties:
+ table_path:
+ items:
+ type: string
+ type: array
+ title: Table Path
+ kind:
+ type: string
+ const: set_key
+ title: Kind
+ default: set_key
+ key:
+ type: string
+ title: Key
+ value:
+ anyOf:
+ - type: string
+ - type: integer
+ - type: number
+ - type: boolean
+ - additionalProperties:
+ anyOf:
+ - type: string
+ - type: integer
+ - type: number
+ - type: boolean
+ type: object
+ title: Value
+ additionalProperties: false
+ type: object
+ required:
+ - table_path
+ - key
+ - value
+ title: SetKeyOp
+ description: Write ``key = value`` in the addressed table, whatever it currently holds.
+ SizeTier:
+ type: string
+ enum:
+ - 0.5k
+ - 1k
+ - 2k
+ - 4k
+ title: SizeTier
+ description: 'Portable image size classes.
+
+
+ A tier promises a pixel class at the pipe''s chosen aspect ratio, not identical
+
+ pixel dimensions across providers: each provider maps the tier to its own grid
+
+ or computed dimensions.'
+ SpecialOutcome:
+ type: string
+ enum:
+ - fail
+ - continue
+ title: SpecialOutcome
+ StepRole:
+ type: string
+ enum:
+ - draft_text
+ - structure
+ title: StepRole
+ description: 'Role played by a synthetic pipe inside an elaborated bundle.
+
+
+ DRAFT_TEXT: step-1 of a `preliminary_text` elaboration — the pipe that produces the draft Text.
+
+ STRUCTURE: step-2 of a `preliminary_text` elaboration — the pipe that turns the draft Text into the structured concept.'
+ StructuringMethod:
+ type: string
+ enum:
+ - direct
+ - preliminary_text
+ title: StructuringMethod
+ Stuff:
+ properties:
+ stuff_code:
+ type: string
+ title: Stuff Code
+ stuff_name:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Stuff Name
+ concept:
+ type: string
+ content:
+ $ref: '#/components/schemas/StuffContent'
+ additionalProperties: false
+ type: object
+ required:
+ - stuff_code
+ - concept
+ - content
+ title: Stuff
+ StuffContent:
+ properties: {}
+ type: object
+ title: StuffContent
+ SubPipeBlueprint:
+ properties:
+ pipe:
+ type: string
+ title: Pipe
+ result:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Result
+ nb_output:
+ anyOf:
+ - type: integer
+ - type: 'null'
+ title: Nb Output
+ multiple_output:
+ anyOf:
+ - type: boolean
+ - type: 'null'
+ title: Multiple Output
+ batch_over:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Batch Over
+ batch_as:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Batch As
+ additionalProperties: false
+ type: object
+ required:
+ - pipe
+ title: SubPipeBlueprint
+ SuggestedFix:
+ properties:
+ fix_code:
+ type: string
+ title: Fix Code
+ description:
+ type: string
+ title: Description
+ safety:
+ $ref: '#/components/schemas/FixSafety'
+ source:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Source
+ ops:
+ items:
+ oneOf:
+ - $ref: '#/components/schemas/SetKeyOp'
+ - $ref: '#/components/schemas/EnsureTableOp'
+ - $ref: '#/components/schemas/DeleteKeyOp'
+ - $ref: '#/components/schemas/DeleteTableOp'
+ - $ref: '#/components/schemas/RenameTableKeyOp'
+ - $ref: '#/components/schemas/MoveKeyOp'
+ - $ref: '#/components/schemas/RemapValueOp'
+ discriminator:
+ propertyName: kind
+ mapping:
+ delete_key: '#/components/schemas/DeleteKeyOp'
+ delete_table: '#/components/schemas/DeleteTableOp'
+ ensure_table: '#/components/schemas/EnsureTableOp'
+ move_key: '#/components/schemas/MoveKeyOp'
+ remap_value: '#/components/schemas/RemapValueOp'
+ rename_table_key: '#/components/schemas/RenameTableKeyOp'
+ set_key: '#/components/schemas/SetKeyOp'
+ type: array
+ title: Ops
+ additionalProperties: false
+ type: object
+ required:
+ - fix_code
+ - description
+ - safety
+ - ops
+ title: SuggestedFix
+ description: 'A deterministic fix for one validation error, ready for a style-preserving applier.
+
+
+ ``fix_code`` is the kebab-case rule id (e.g. ``"match-sequence-output"``). ``source`` is
+
+ the file the ops target, when known (multi-file libraries) — an applier must only apply
+
+ ops to the file they target.'
+ TagStyle:
+ type: string
+ enum:
+ - no_tag
+ - ticks
+ - xml
+ - square_brackets
+ title: TagStyle
+ TemplateBlueprint:
+ properties:
+ template:
+ type: string
+ title: Template
+ description: Raw template source
+ templating_style:
+ anyOf:
+ - $ref: '#/components/schemas/TemplatingStyle'
+ - type: 'null'
+ description: How the tag and format filters render in this template; omit it to take the runtime default templating
+ style
+ category:
+ $ref: '#/components/schemas/TemplateCategory'
+ description: Category of the template (could also be HTML, MARKDOWN, MERMAID, etc.), influences template rendering
+ rules
+ extra_context:
+ anyOf:
+ - additionalProperties: true
+ type: object
+ - type: 'null'
+ title: Extra Context
+ description: Additional context variables for template rendering
+ additionalProperties: false
+ type: object
+ required:
+ - template
+ - category
+ title: TemplateBlueprint
+ description: 'The rich form of a template: its Jinja2 source and category, plus an optional templating style and extra
+ context.'
+ TemplateCategory:
+ type: string
+ enum:
+ - basic
+ - expression
+ - html
+ - markdown
+ - mermaid
+ - llm_prompt
+ - img_gen_prompt
+ title: TemplateCategory
+ TemplatingStyle:
+ properties:
+ tag_style:
+ $ref: '#/components/schemas/TagStyle'
+ text_format:
+ $ref: '#/components/schemas/TextFormat'
+ default: plain
+ additionalProperties: false
+ type: object
+ required:
+ - tag_style
+ title: TemplatingStyle
+ description: 'How a pipe''s inputs are tagged and formatted into its prompt: a tag style and a text format.'
+ TextField:
+ properties:
+ title:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Title
+ concept_ref:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Concept Ref
+ refines:
+ anyOf:
+ - items:
+ type: string
+ type: array
+ - type: 'null'
+ title: Refines
+ description:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Description
+ required:
+ type: boolean
+ title: Required
+ presence:
+ anyOf:
+ - $ref: '#/components/schemas/PresenceMarker'
+ - type: 'null'
+ gating:
+ anyOf:
+ - type: boolean
+ - type: 'null'
+ title: Gating
+ default_value:
+ title: Default Value
+ examples:
+ anyOf:
+ - items: {}
+ type: array
+ - type: 'null'
+ title: Examples
+ hints:
+ anyOf:
+ - additionalProperties:
+ type: string
+ type: object
+ - type: 'null'
+ title: Hints
+ min_length:
+ anyOf:
+ - type: integer
+ - type: 'null'
+ title: Min Length
+ max_length:
+ anyOf:
+ - type: integer
+ - type: 'null'
+ title: Max Length
+ pattern:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Pattern
+ format:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Format
+ kind:
+ type: string
+ const: text
+ title: Kind
+ default: text
+ name:
+ type: string
+ title: Name
+ additionalProperties: false
+ type: object
+ required:
+ - required
+ - name
+ title: TextField
+ description: '`text` at a named position — a top-level field or a structure field.'
+ TextFormat:
+ type: string
+ enum:
+ - plain
+ - markdown
+ - html
+ - json
+ title: TextFormat
+ TextItem:
+ properties:
+ title:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Title
+ concept_ref:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Concept Ref
+ refines:
+ anyOf:
+ - items:
+ type: string
+ type: array
+ - type: 'null'
+ title: Refines
+ description:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Description
+ required:
+ type: boolean
+ title: Required
+ presence:
+ anyOf:
+ - $ref: '#/components/schemas/PresenceMarker'
+ - type: 'null'
+ gating:
+ anyOf:
+ - type: boolean
+ - type: 'null'
+ title: Gating
+ default_value:
+ title: Default Value
+ examples:
+ anyOf:
+ - items: {}
+ type: array
+ - type: 'null'
+ title: Examples
+ hints:
+ anyOf:
+ - additionalProperties:
+ type: string
+ type: object
+ - type: 'null'
+ title: Hints
+ min_length:
+ anyOf:
+ - type: integer
+ - type: 'null'
+ title: Min Length
+ max_length:
+ anyOf:
+ - type: integer
+ - type: 'null'
+ title: Max Length
+ pattern:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Pattern
+ format:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Format
+ kind:
+ type: string
+ const: text
+ title: Kind
+ default: text
+ additionalProperties: false
+ type: object
+ required:
+ - required
+ title: TextItem
+ description: '`text` — a short single-line string.'
+ TimingSpec:
+ properties:
+ started_at:
+ type: string
+ format: date-time
+ title: Started At
+ ended_at:
+ type: string
+ format: date-time
+ title: Ended At
+ duration:
+ type: number
+ title: Duration
+ description: Duration in seconds, included in JSON serialization.
+ readOnly: true
+ additionalProperties: false
+ type: object
+ required:
+ - started_at
+ - ended_at
+ - duration
+ title: TimingSpec
+ description: Timing information for a node execution.
+ TokensUsageRecord:
+ properties:
+ model_type:
+ type: string
+ title: Model Type
+ inference_model_name:
+ type: string
+ title: Inference Model Name
+ inference_model_id:
+ type: string
+ title: Inference Model Id
+ pipe_code:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Pipe Code
+ job_category:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Job Category
+ unit_job_id:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Unit Job Id
+ nb_tokens_by_category:
+ additionalProperties:
+ type: integer
+ type: object
+ title: Nb Tokens By Category
+ cost:
+ anyOf:
+ - type: number
+ - type: 'null'
+ title: Cost
+ started_at:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Started At
+ completed_at:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Completed At
+ additionalProperties: false
+ type: object
+ required:
+ - model_type
+ - inference_model_name
+ - inference_model_id
+ - nb_tokens_by_category
+ title: TokensUsageRecord
+ description: 'One client-facing usage record per inference call.
+
+
+ ``extra="forbid"`` is deliberate: server-side emission is the shape authority, so an
+
+ accidental new field fails loudly here instead of silently widening the contract.
+
+ Enum-ish fields (``model_type``, ``job_category``, ``unit_job_id``, and the
+
+ ``nb_tokens_by_category`` keys) are open sets on the wire, typed as plain strings —
+
+ runtime enum churn is non-breaking for clients.'
+ UnknownField:
+ properties:
+ title:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Title
+ concept_ref:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Concept Ref
+ refines:
+ anyOf:
+ - items:
+ type: string
+ type: array
+ - type: 'null'
+ title: Refines
+ description:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Description
+ required:
+ type: boolean
+ title: Required
+ presence:
+ anyOf:
+ - $ref: '#/components/schemas/PresenceMarker'
+ - type: 'null'
+ gating:
+ anyOf:
+ - type: boolean
+ - type: 'null'
+ title: Gating
+ default_value:
+ title: Default Value
+ examples:
+ anyOf:
+ - items: {}
+ type: array
+ - type: 'null'
+ title: Examples
+ hints:
+ anyOf:
+ - additionalProperties:
+ type: string
+ type: object
+ - type: 'null'
+ title: Hints
+ kind:
+ type: string
+ const: unknown
+ title: Kind
+ default: unknown
+ name:
+ type: string
+ title: Name
+ additionalProperties: false
+ type: object
+ required:
+ - required
+ - name
+ title: UnknownField
+ description: '`unknown` at a named position.'
+ UnknownItem:
+ properties:
+ title:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Title
+ concept_ref:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Concept Ref
+ refines:
+ anyOf:
+ - items:
+ type: string
+ type: array
+ - type: 'null'
+ title: Refines
+ description:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Description
+ required:
+ type: boolean
+ title: Required
+ presence:
+ anyOf:
+ - $ref: '#/components/schemas/PresenceMarker'
+ - type: 'null'
+ gating:
+ anyOf:
+ - type: boolean
+ - type: 'null'
+ title: Gating
+ default_value:
+ title: Default Value
+ examples:
+ anyOf:
+ - items: {}
+ type: array
+ - type: 'null'
+ title: Examples
+ hints:
+ anyOf:
+ - additionalProperties:
+ type: string
+ type: object
+ - type: 'null'
+ title: Hints
+ kind:
+ type: string
+ const: unknown
+ title: Kind
+ default: unknown
+ additionalProperties: false
+ type: object
+ required:
+ - required
+ title: UnknownItem
+ description: '`unknown` — not honestly describable as any other kind.
+
+
+ The mandatory escape hatch that makes a total derivation truthful: a renderer falls back to raw
+
+ entry against the slot''s `json_schema` in the pipe I/O contract.'
+ UserAction:
+ properties:
+ kind:
+ $ref: '#/components/schemas/UserActionKind'
+ detail:
+ type: string
+ title: Detail
+ type: object
+ required:
+ - kind
+ - detail
+ title: UserAction
+ description: 'Structured user-facing advice attached to an inference error.
+
+
+ ``kind`` discriminates the type of action, ``detail`` is the free-form
+
+ provider-specific advice (e.g. a billing URL, a retry hint).'
+ UserActionKind:
+ type: string
+ enum:
+ - wait_and_retry
+ - check_billing
+ - check_credentials
+ - change_input
+ - change_model
+ - contact_support
+ - unknown
+ title: UserActionKind
+ description: 'Discrete categories of advice we surface to the user/agent.
+
+
+ Lets the CLI render consistent guidance and agent JSON stay typed across
+
+ providers. The free-form ``detail`` string carries provider-specific text.'
+ ValidReport:
+ properties:
+ is_valid:
+ type: boolean
+ const: true
+ title: Is Valid
+ default: true
+ bundle_blueprint:
+ $ref: '#/components/schemas/PipelexBundleBlueprint'
+ pipe_io_contracts:
+ additionalProperties:
+ $ref: '#/components/schemas/PipeIOContract'
+ type: object
+ title: Pipe Io Contracts
+ input_form:
+ additionalProperties:
+ $ref: '#/components/schemas/PipeInputFormDescriptor'
+ type: object
+ title: Input Form
+ description: 'Opt-in Pipelex-API structured view: per-pipe input-form descriptors keyed exactly like `pipe_io_contracts`,
+ present only when the request''s `views` includes `input_form`. Absent by default — the structured contract fields
+ remain the verdict; this is a projection of them.'
+ output_form:
+ additionalProperties:
+ $ref: '#/components/schemas/PipeOutputFormDescriptor'
+ type: object
+ title: Output Form
+ description: 'Opt-in Pipelex-API structured view: per-pipe output-form descriptors keyed exactly like `pipe_io_contracts`,
+ present only when the request''s `views` includes `output_form`. Absent by default. Read with the output contract''s
+ `json_schema`, which states the shape of the payload this descriptor describes.'
+ liftable_pipes:
+ items:
+ $ref: '#/components/schemas/LiftablePipeEntry'
+ type: array
+ title: Liftable Pipes
+ graph_spec:
+ anyOf:
+ - $ref: '#/components/schemas/GraphSpec'
+ - type: 'null'
+ validated_pipes:
+ items:
+ $ref: '#/components/schemas/ValidatedPipeEntry'
+ type: array
+ title: Validated Pipes
+ warnings:
+ items:
+ $ref: '#/components/schemas/ValidationErrorItem'
+ type: array
+ title: Warnings
+ pending_signatures:
+ items:
+ type: string
+ type: array
+ title: Pending Signatures
+ is_runnable:
+ type: boolean
+ title: Is Runnable
+ default: true
+ mthds_contents:
+ items:
+ type: string
+ type: array
+ title: Mthds Contents
+ description: The MTHDS contents that were validated (echo of the request)
+ message:
+ type: string
+ title: Message
+ description: Status message
+ default: MTHDS content validated successfully
+ default_pipe_ref:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Default Pipe Ref
+ description: 'The qualified `domain.pipe_code` a caller gets by omitting the pipe selector — the pipe a selector-less
+ run of THIS request would execute. On a `method_ref` request it is the fetched package manifest''s `main_pipe`
+ (the package author''s declared entry pipe, qualified against the closure); otherwise, and when the manifest declares
+ none, it is the closure''s primary blueprint''s `main_pipe` qualified by its domain. `null` when no entry pipe
+ is determined: no blueprint declares `main_pipe`, or a manifest names a pipe the closure does not declare (or
+ declares ambiguously), in which case a selector-less run by this address would fail to resolve it too.'
+ rendered_markdown:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Rendered Markdown
+ description: 'Opt-in Pipelex-API presentation extra: a server-rendered Markdown view of the valid verdict, present
+ only when the request''s `render` includes `markdown`. Absent by default — the structured fields remain the contract;
+ this is the view.'
+ additionalProperties: true
+ type: object
+ required:
+ - bundle_blueprint
+ - mthds_contents
+ title: ValidReport
+ description: 'The 200 **valid** arm: the canonical `PipelexValidationReport` plus this server''s wire-only extras.
+
+
+ The report fields are inherited — typed models, identical to what the local runtime
+
+ returns for the same bundle, with `is_valid: Literal[True]` (from the report) as the union
+
+ discriminant. The extras exist for HTTP clients only (the webapp reads back `mthds_contents`);
+
+ they are NOT part of the canonical report and no in-process consumer should depend on them.
+
+
+ Two inherited fields are deliberately re-declared: `input_form` and `output_form`. The canonical
+
+ report requires both (a backend that forgets to derive one must fail loudly rather than ship an
+
+ empty view), but on the wire each is an opt-in structured view gated by the request''s `views` —
+
+ so both are re-declared with defaults here, keeping them out of the published schema''s `required`
+
+ set. The values still always arrive from the report; the route pops each when its token was not
+
+ requested. They are separate tokens rather than one because they answer separate questions: a
+
+ caller building a fill-in form wants the inputs, a caller rendering a result or registering a
+
+ tool signature wants the output, and neither should pay for the other.'
+ ValidateRequest:
+ properties:
+ analytics_groups:
+ anyOf:
+ - additionalProperties:
+ type: string
+ type: object
+ - type: 'null'
+ title: Analytics Groups
+ description: 'PIPELEX-API EXTENSION (not part of the MTHDS Protocol) — the host-supplied groups the caller of this
+ request belongs to, as a mapping of group type to group key (e.g. `{"organization": "org_acme"}`), exactly as
+ a run request states them. The work this request does is not a run, but it still emits telemetry — the validation
+ sweep''s `pipe_dry_run` event and its dry runs — and that telemetry is attributed to the caller: the authenticated
+ user and these groups. Same rules and same 422 `InvalidAnalyticsGroups` refusal as on `/execute` and `/start`.
+ Omit it and the caller belongs to no group.'
+ mthds_contents:
+ anyOf:
+ - items:
+ type: string
+ type: array
+ maxItems: 16
+ minItems: 1
+ - type: 'null'
+ title: Mthds Contents
+ description: MTHDS contents to load (always an array, even for a single file). Exactly one of `mthds_contents` /
+ `method_ref`.
+ method_ref:
+ anyOf:
+ - type: string
+ maxLength: 512
+ minLength: 1
+ - type: 'null'
+ title: Method Ref
+ description: 'PIPELEX-API EXTENSION (not part of the MTHDS Protocol) — validate a published method by reference
+ instead of inline contents. Address form: `github.com/<owner>/<repo>[/<selector>][@<tag>]`, resolved by THIS runner
+ through the same fetch path as a `method_ref` run; the package''s `.mthds` files feed the validation with their
+ real relative paths as per-file sources. Exactly one of `mthds_contents` / `method_ref`. A resolution failure
+ (fetch, package location, the custom-Python policy) is a non-2xx `problem+json` — never an `is_valid: false` verdict,
+ which is reserved for actual MTHDS content.'
+ allow_signatures:
+ type: boolean
+ title: Allow Signatures
+ description: When true, the validation sweep tolerates unimplemented pipe signatures instead of rejecting the bundle
+ (signatures dry-run trivially by minting a mock). Defaults to false (strict).
+ default: false
+ mthds_sources:
+ anyOf:
+ - items:
+ type: string
+ type: array
+ - type: 'null'
+ title: Mthds Sources
+ description: Optional per-file sources, parallel to `mthds_contents`. When provided, each entry is threaded onto
+ the corresponding bundle's `source` so server-side validation errors carry a `source` pointing at the owning file.
+ Must match `mthds_contents` in length when present.
+ render:
+ items:
+ type: string
+ type: array
+ title: Render
+ description: 'Opt-in Pipelex-API presentation extra: view formats to render server-side. A supported token (`markdown`)
+ adds a `rendered_<format>` field (e.g. `rendered_markdown`) to the 200 verdict, on both the valid and invalid
+ arms. Unknown/unsupported tokens are silently ignored (presentation hint, not part of the verdict contract); the
+ default empty list renders nothing and the response is unchanged.'
+ views:
+ items:
+ type: string
+ type: array
+ title: Views
+ description: 'Opt-in Pipelex-API structured views: extra projections to attach to the 200 verdict. A supported token
+ (`input_form`, `output_form`) adds a **same-named** top-level field to the valid arm only. Unknown/unsupported
+ tokens are silently ignored (a view is a projection of facts the verdict already determined, not part of the verdict
+ contract); the default empty list attaches nothing and the response is byte-identical to a request that omits
+ the field. Independent of `render`: a request may carry both, each resolving its own tokens.'
+ orchestration_mode:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Orchestration Mode
+ description: 'Optional per-request orchestration-mode (backend) override for the validation dispatch (same plumbing
+ as `/start`). An OPEN string token: `direct` validates in-process; a `temporal` mode dispatches the whole job
+ to a worker; any plugin-provided token is accepted and an unregistered one is refused at dispatch. Honored only
+ when the deployment sets `allow_request_orchestration_mode_override = true` in its `api.toml`; otherwise a token
+ that differs from the deployment default is refused with a 403. Omitted → the default.'
+ type: object
+ title: ValidateRequest
+ description: 'The shared `mthds_contents` + `allow_signatures` payload, plus optional per-file sources.
+
+
+ `mthds_sources`, when provided, pairs each `mthds_contents[i]` with a logical source (e.g. the
+
+ file''s path relative to the submitted directory). The runner threads it onto
+
+ `blueprint.source`, so the structured `validation_errors` on a 200 `InvalidReport` carry a real
+
+ `source` the client maps back to the owning file — without it the in-memory load path leaves
+
+ `source` null and cross-file diagnostics misfire. Omit it and behavior is unchanged.'
+ ValidatedPipeEntry:
+ properties:
+ pipe_ref:
+ type: string
+ title: Pipe Ref
+ status:
+ $ref: '#/components/schemas/DryRunStatus'
+ additionalProperties: true
+ type: object
+ required:
+ - pipe_ref
+ - status
+ title: ValidatedPipeEntry
+ description: 'One entry in the ``validated_pipes`` JSON envelope returned by the validate surfaces.
+
+
+ The ``pipe_ref`` key carries the namespaced ``pipe_ref`` (``domain.code``) — never the bare code.
+
+ ``status`` is a ``DryRunStatus`` (a ``StrEnum``), so it serializes to its plain string value.'
+ ValidationErrorCategory:
+ type: string
+ enum:
+ - blueprint_validation
+ - pipe_factory
+ - pipe_validation
+ - dry_run
+ title: ValidationErrorCategory
+ description: 'Which validation stage produced a :class:`ValidationErrorItem`.
+
+
+ Mirrors the categorized error-data lists aggregated by ``ValidateBundleError``:
+
+ blueprint validation (from the interpreter), pipe-factory failures (e.g. a
+
+ missing concept), pipe/concept validation (e.g. a missing input variable
+
+ or a type mismatch), and ``dry_run`` — one item per pipe whose dry run failed,
+
+ located at the innermost failing pipe.'
+ ValidationErrorItem:
+ properties:
+ category:
+ $ref: '#/components/schemas/ValidationErrorCategory'
+ message:
+ type: string
+ title: Message
+ error_type:
+ anyOf:
+ - $ref: '#/components/schemas/PipeValidationErrorType'
+ - $ref: '#/components/schemas/PipeFactoryErrorType'
+ - $ref: '#/components/schemas/ValidationResidualErrorType'
+ - $ref: '#/components/schemas/HintLintErrorType'
+ - type: 'null'
+ title: Error Type
+ pipe_code:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Pipe Code
+ concept_code:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Concept Code
+ domain_code:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Domain Code
+ source:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Source
+ field_path:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Field Path
+ field_name:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Field Name
+ variable_names:
+ anyOf:
+ - items:
+ type: string
+ type: array
+ - type: 'null'
+ title: Variable Names
+ missing_concept_code:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Missing Concept Code
+ missing_pipe_code:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Missing Pipe Code
+ declared_concepts:
+ anyOf:
+ - items:
+ type: string
+ type: array
+ - type: 'null'
+ title: Declared Concepts
+ line:
+ anyOf:
+ - type: integer
+ - type: 'null'
+ title: Line
+ column:
+ anyOf:
+ - type: integer
+ - type: 'null'
+ title: Column
+ model_reference:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Model Reference
+ model_type:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Model Type
+ suggestions:
+ anyOf:
+ - items:
+ type: string
+ type: array
+ - type: 'null'
+ title: Suggestions
+ suggested_fix:
+ anyOf:
+ - $ref: '#/components/schemas/SuggestedFix'
+ - type: 'null'
+ additionalProperties: false
+ type: object
+ required:
+ - category
+ - message
+ title: ValidationErrorItem
+ description: 'One structured bundle-validation error, projected onto the error wire.
+
+
+ The typed wire item carried by :attr:`ErrorReport.validation_errors`. Its
+
+ fields are the *union* across the three ``ValidateBundleError`` error-data
+
+ models (``PipelexBundleBlueprintValidationErrorData``, ``PipeFactoryErrorData``,
+
+ ``PipesAndConceptValidationErrorData``); a given item only populates the
+
+ subset its :attr:`category` produces, and the unset fields drop out of the
+
+ ``exclude_none`` wire projection.
+
+
+ The error channel is built exclusively by
+
+ ``pipelex.pipeline.validation_errors.build_validation_error_items``, which both the agent
+
+ CLI (``extract_validation_errors``) and the API path
+
+ (``ValidateBundleError.to_error_report``) call — so the CLI''s structured
+
+ output and the API''s 422 ``validation_errors`` can never drift. The same
+
+ item type also carries the report''s advisory ``warnings``, built by
+
+ ``pipelex.pipeline.advisory_warnings``: a warning is the same shape of
+
+ diagnostic, differing only in that it does not make the verdict invalid.
+
+
+ ``source`` is the declaring file path (CLI) or the per-content source the API
+
+ threads onto the in-memory load path — it hands a consumer the owning file
+
+ for cross-file diagnostics. Lives here, alongside :class:`ErrorReport`,
+
+ rather than next to the source error-data models because ``ErrorReport``
+
+ references it as a typed field and ``base_exceptions`` must not import the
+
+ ``pipelex.core`` error modules (which import back into this module).'
+ ValidationResidualErrorType:
+ type: string
+ enum:
+ - DryRunError
+ title: ValidationResidualErrorType
+ description: 'The ``error_type`` of a failure no validation stage classifies into a code.
+
+
+ There is exactly one that names itself: a dry-run failure is raised as an error object, a
+
+ ``DryRunError`` carrying one located failure per pipe whose dry run failed, so each of its items is
+
+ tagged with that exception''s own class name.
+
+
+ The items no code identifies — the parse-level residual, for a bundle that could not be turned
+
+ into a blueprint at all (a TOML-syntax error, an empty blueprint, an elaborator failure), and a
+
+ pydantic error no categorizer knows — carry no ``error_type`` and therefore no member here. That
+
+ is not an omission: they stand for many distinct underlying errors, and inventing one code for all
+
+ of them would tell a consumer it knows which fault occurred when it does not. Their message is the
+
+ authoritative diagnostic.'
+ WorkingMemory:
+ properties:
+ root:
+ additionalProperties:
+ $ref: '#/components/schemas/Stuff'
+ type: object
+ title: Root
+ aliases:
+ additionalProperties:
+ type: string
+ type: object
+ title: Aliases
+ absences:
+ additionalProperties:
+ $ref: '#/components/schemas/AbsenceRecord'
+ type: object
+ title: Absences
+ additionalProperties: false
+ type: object
+ title: WorkingMemory
diff --git a/api/docs/pipe-builder.md b/api/docs/pipe-builder.md
new file mode 100644
index 000000000..99e5cfa13
--- /dev/null
+++ b/api/docs/pipe-builder.md
@@ -0,0 +1,184 @@
+# Pipe Builder
+
+Generate input templates, output representations, and Python runner code for a pipe of an MTHDS library closure.
+
+All three build endpoints speak the same verdict discipline as [`POST /v1/validate`](pipe-validate.md): a **produced verdict is always a `200`** discriminated on the body's `is_valid` field. The valid arm carries the built artifact; the invalid arm carries the structured `validation_errors[]` built by pipelex's one shared error builder. Non-2xx is reserved for *no verdict could be produced* — request-shape `422`, auth `401`/`403`, server `5xx` — rendered as RFC 7807 `application/problem+json` (see [Error Responses](error-responses.md)).
+
+## The shared request envelope
+
+All three take the same **closure selector** as [`POST /v1/resolve` and `POST /v1/codegen`](codegen.md) — inline `files[]` **XOR** a `method_ref` — plus a **pipe selector**:
+
+- `files` (list, required unless `method_ref`): the inline MTHDS bundles forming the closure. Each item is `{ "content": "<mthds text>", "source": "<optional logical path>" }`. The optional `source` is threaded onto the blueprint, so diagnostics point at the owning file.
+- `method_ref` (string): a reference to a published method. The **address form** — `github.com/<owner>/<repo>` plus an optional package selector and `@<tag>` — is resolved server-side through the same fetch path as a [`method_ref` run](pipe-run.md#running-a-method-by-address-method_ref): the package's `.mthds` files feed the closure (only `.mthds` data travels — the package's Python never loads here), and the package manifest's `main_pipe` becomes the default pipe selector. The **registry form** (any non-address reference) answers `501` (`MethodRefNotSupported`) until method-registry resolution lands.
+- `pipe_ref` (string, **optional**): the qualified pipe ref `domain.pipe_code` to project — the same selector as `pipelex codegen inputs --pipe`. Omitted, it defaults with the same precedence as a run by address: on a `method_ref` request, to the fetched package manifest's `main_pipe` (the package author's declared entry pipe); otherwise to the closure's own declared `main_pipe`. A closure that declares **no** `main_pipe`, or **several** across domains, cannot be defaulted from its declarations, so when no manifest `main_pipe` settles it an omitted `pipe_ref` is a `422` there. Inline `files[]` carry no manifest, so for them the default is always the closure's declaration. Every selection refusal is an input `422` whose `error_type` is the pipelex entry-lookup class that names the failure, not the `ValidationError` of a malformed request: `EntryPipeNotFoundError` for a `pipe_ref` that names no pipe, a manifest `main_pipe` the closure does not declare, or an omitted `pipe_ref` over a closure declaring no `main_pipe`; `EntryPipeAmbiguousError` for a bare code, whether the request or the manifest spelled it, that matches pipes in several domains, or an omitted `pipe_ref` over a closure declaring several `main_pipe`s. An ambiguity's `detail` names the qualified refs to choose from. An unknown or ambiguous `pipe_ref` answers the `error_type` the run routes answer for the same `pipe_code`; the two omitted-`pipe_ref` refusals follow the pipe-selector design, since a run over such a closure has no matching refusal today.
+
+Every valid arm echoes both `pipe_ref` (the ref actually projected) and `requested_pipe_ref` (the ref as submitted — **absent** when it was omitted and defaulted), so a caller can always see which pipe it got. The echoed `pipe_ref` is **always qualified**, read back off the resolved pipe: a bare code still resolves (the engine's lookup falls back across domains), but you are told `smoke.echo`, not the `echo` you sent.
+
+## Static projections vs. the runner
+
+`/build/inputs` and `/build/output` are **static**: they resolve the closure to its normalized crate and read the requested pipe's **declared** IO. There is no dry-run sweep, and therefore no `allow_signatures` flag (it only ever parameterized that sweep). A valid verdict from them says the closure is structurally sound and the projection matches what the pipe *declares* — it is **not** a promise the pipe runs. Runnability is [`/validate`](pipe-validate.md)'s vocabulary; ask it.
+
+`/build/runner` is the exception. A runner script *is* a promise the pipe can run, so it keeps the dry-run sweep and keeps `allow_signatures`.
+
+## Build Inputs
+
+Generate an example inputs template for a pipe — the same projection `pipelex codegen inputs` writes, on both of its axes.
+
+**Endpoint:** `POST /v1/build/inputs`
+
+**Request Body:**
+
+```json
+{
+ "files": [
+ { "content": "domain = \"cv_matching\"\nmain_pipe = \"analyze_cv_job_match\"\n\n[pipe.analyze_cv_job_match]\ntype = \"PipeLLM\"\ndescription = \"Analyze CV against job offer\"\ninputs = { cv_text = \"native.Text\", job_offer = \"native.Text\" }\noutput = \"MatchAnalysis\"", "source": "cv_matching.mthds" }
+ ],
+ "pipe_ref": "cv_matching.analyze_cv_job_match"
+}
+```
+
+**Request Fields:** the shared envelope above, plus:
+
+- `format` (string, optional): `"json"` (default) or `"toml"`.
+- `explicit` (boolean, optional, default `false`): when `true`, emit the ceremonial `{concept, content}` envelope for every input. The default is the *light*, signature-driven shape — a bare string for a Text-refining input, a bare number for a Number-refining one, and so on — which is what smart inputs accepts.
+
+**The template rides the field its `format` names.** JSON is a parsed object in `inputs`; TOML is raw text in `inputs_toml`. TOML cannot ride as a parsed object without losing the concept comments and key order that are the reason to ask for it, and the JSON case must stay a real object because that is what clients feed straight into a run. The field the format did not select is **omitted from the body entirely**.
+
+**Response (valid verdict, default light JSON):**
+
+```json
+{
+ "is_valid": true,
+ "pipe_ref": "cv_matching.analyze_cv_job_match",
+ "requested_pipe_ref": "cv_matching.analyze_cv_job_match",
+ "format": "json",
+ "explicit": false,
+ "inputs": {
+ "cv_text": "text_value",
+ "job_offer": "text_value"
+ },
+ "message": "Inputs template generated successfully"
+}
+```
+
+With `"explicit": true`, each value becomes its `{ "concept": "native.Text", "content": { "text": "text_value" } }` envelope instead. With `"format": "toml"`, the body carries `inputs_toml` (a string) in place of `inputs`.
+
+A pipe that declares **no inputs** is a *valid* verdict, not an error: the template is simply empty (`{}` / `""`) and `message` says so — mirroring the CLI, which exits 0 on it.
+
+**Response (invalid verdict):** `200` with `is_valid: false` and `validation_errors[]` — the same invalid arm every build endpoint returns:
+
+```json
+{
+ "is_valid": false,
+ "validation_errors": [
+ { "category": "blueprint_validation", "message": "...", "source": "cv_matching.mthds" }
+ ],
+ "message": "..."
+}
+```
+
+An item may also carry a `suggested_fix` — a structured, deterministic repair the runtime derived for that error. See [Error Responses → Suggested fixes](error-responses.md#suggested-fixes).
+
+---
+
+## Build Output
+
+Generate the output representation for a pipe in one of three formats.
+
+**Endpoint:** `POST /v1/build/output`
+
+**Request Body:**
+
+```json
+{
+ "files": [{ "content": "...your MTHDS content..." }],
+ "pipe_ref": "cv_matching.analyze_cv_job_match",
+ "format": "schema"
+}
+```
+
+**Request Fields:** the shared envelope above, plus:
+
+- `format` (string, optional): `"schema"` (default), `"json"`, or `"python"`. **Must be lowercase.**
+
+**Format Options:**
+
+- `schema` — JSON Schema representation of the output concept → parsed object in `output`
+- `json` — Example JSON instance of the output → parsed object in `output`
+- `python` — Python source defining the output class → raw text in `output_python`
+
+As with `/build/inputs`, the representation rides the field its `format` names, and the other is omitted.
+
+**Response (valid verdict, schema format):**
+
+```json
+{
+ "is_valid": true,
+ "pipe_ref": "cv_matching.analyze_cv_job_match",
+ "requested_pipe_ref": "cv_matching.analyze_cv_job_match",
+ "format": "schema",
+ "output": {
+ "concept": "MatchAnalysis",
+ "content": {
+ "type": "object",
+ "properties": {
+ "score": { "title": "Score", "type": "integer", "description": "Match score 0-100" }
+ },
+ "required": ["score"]
+ }
+ },
+ "message": "Output representation generated successfully"
+}
+```
+
+One no-verdict special case: a pipe whose output is `native.Anything` and whose concrete options cannot be determined has no representation to render — a request-shape `422`, since that is a fact about the requested pipe, not about the closure.
+
+The invalid verdict is the shared `is_valid: false` arm shown under Build Inputs.
+
+---
+
+## Build Runner
+
+Generate a Python runner script for executing a pipe. The script's imports, example inputs, and output cast are spelled with the **emitted** class names of the typed-structures projection, and the response carries that projection alongside the script — the same stamped `structures.py` + `codegen.lock` a local `pipelex build runner` scaffolds (see [Resolve & Codegen](codegen.md) for the stamp/lock trust chain).
+
+**Endpoint:** `POST /v1/build/runner`
+
+**Request Body:**
+
+```json
+{
+ "files": [{ "content": "...your MTHDS content..." }],
+ "pipe_ref": "cv_matching.analyze_cv_job_match"
+}
+```
+
+**Request Fields:** the shared envelope above, plus:
+
+- `allow_signatures` (boolean, optional): tolerate unimplemented pipe signatures in the dry-run sweep (default `false`). This is the only build route that takes it — the only one that still sweeps.
+- `analytics_groups` (object | null, optional): the groups the caller belongs to, with the same rules and the same 422 `InvalidAnalyticsGroups` as [on `/validate`](pipe-validate.md#who-the-validation-is-done-for). The sweep is done for the authenticated user and these groups, so its telemetry is attributed to them.
+
+The sweep is scoped to the requested pipe, so unrelated broken siblings do not block a good pipe. When `pipe_ref` is omitted the scope is not settled before the closure loads, so the **whole closure** is swept and the pipe then defaults as described in the shared envelope above — the fetched manifest's `main_pipe` on a `method_ref` request, else the closure's own — a stricter verdict, and the honest one for a caller who did not say which pipe they meant.
+
+**Response (valid verdict):**
+
+```json
+{
+ "is_valid": true,
+ "pipe_ref": "cv_matching.analyze_cv_job_match",
+ "requested_pipe_ref": "cv_matching.analyze_cv_job_match",
+ "python_code": "import sys\nfrom pathlib import Path\n...",
+ "structures": {
+ "directory": "structures",
+ "artifacts": [
+ { "path": "structures.py", "content": "# >>> pipelex-codegen-stamp >>>\n..." }
+ ],
+ "lock": "# codegen.lock — generated artifact set (Pipelex codegen). Do not edit by hand.\n...",
+ "lock_filename": "codegen.lock"
+ },
+ "message": "Runner code generated successfully"
+}
+```
+
+To materialize a runnable tree, write `python_code` as the runner script and each `structures.artifacts[]` entry (plus `structures.lock` as `structures.lock_filename`) into the `structures.directory` beside it — the script imports from there (`from structures.structures import ...`).
+
+The invalid verdict — including a failed dry-run of the requested pipe — is the shared `is_valid: false` arm shown under Build Inputs. One no-verdict special case: a requested pipe whose cross-package dependencies are absent from the request (recorded SKIPPED by the sweep) is a request-shape `422`, since no runner can be honestly generated without its dependency closure.
diff --git a/api/docs/pipe-io.md b/api/docs/pipe-io.md
new file mode 100644
index 000000000..6fd4ab6bf
--- /dev/null
+++ b/api/docs/pipe-io.md
@@ -0,0 +1,87 @@
+# Pipe I/O
+
+Return a method's I/O artifacts — its pipe I/O contracts, its input form and its output form — without validating it.
+
+**Endpoint:** `POST /v1/pipe-io`
+
+The route resolves the closure through the same static core as [`POST /v1/resolve`](codegen.md#resolve), selects a pipe the way the [per-pipe build routes](pipe-builder.md) do, and derives the three artifacts with the builder that [`POST /v1/validate`](pipe-validate.md) and every run already call. It runs **no dry-run sweep**, so a call costs one load and one derivation, where `/v1/validate` mock-runs every pipe of the method. A caller that shows a method, prepares its inputs or generates types for it reads this route; a caller that needs the dry-run verdict or the dry-run graph stays on `/v1/validate`, whose `views` still attach both forms beside the verdict.
+
+It is a **Pipelex API extension**, not an MTHDS Protocol route: it is not tagged `x-mthds-protocol` in the [OpenAPI artifact](openapi/pipelex-api.openapi.yaml). The artifacts it carries are the standard's, under their neutral names — see the MTHDS specification's pages on [pipe I/O contracts, the input-form descriptor and the output-form descriptor](https://mthds.ai).
+
+It speaks the `/v1/validate` verdict discipline: a **produced verdict is always a `200`** discriminated on `is_valid`, and a non-2xx is reserved for a request that produced no verdict.
+
+## Request
+
+The body is the [crate routes' closure selector](codegen.md#selecting-the-closure) plus a pipe selector and two opt-ins:
+
+- `files` (list) **or** `method_ref` (string), exactly one: the closure, as on `/v1/resolve`. Neither or both is a request-shape `422`.
+- `pipe_ref` (string, optional): the qualified ref `domain.pipe_code` of the pipe to describe. Omitted, the selection chain below decides.
+- `all_pipes` (boolean, default `false`): describe every pipe the closure loads instead of the selected one.
+- `include_files` (boolean, default `false`): echo the resolved closure's `.mthds` files on the valid arm.
+
+There is no `views` field, because the valid arm always carries all three artifacts. The hosted API also accepts a catalog `method_id`, which the platform resolves into `files[]` before forwarding, so this server never declares it.
+
+```json
+{
+ "files": [{ "content": "...bundle...", "source": "main.mthds" }],
+ "all_pipes": true,
+ "include_files": true
+}
+```
+
+## Pipe selection
+
+The selection chain is the one the build routes share: the request's `pipe_ref`; else a fetched package's manifest `main_pipe`; else the closure's own `main_pipe` declaration, when exactly one domain declares one. The chain stops at the first link that is present, so a manifest `main_pipe` the closure does not declare, or declares in several domains, is a failed selection rather than a fall-through to the closure's declarations.
+
+The closure is resolved first, so an invalid closure answers its invalid verdict whatever `pipe_ref` names. For a valid closure these selections are refused with an input `422` `problem+json`. Its `error_type` is the pipelex entry-lookup class that names the failure, never the `ValidationError` of a malformed request, so a client tells a selection refusal from a request-shape one by that field:
+
+- `EntryPipeNotFoundError` for a `pipe_ref` that names no pipe of the closure, for a manifest `main_pipe` the closure does not declare, and, without `all_pipes`, for a request with no `pipe_ref` whose closure declares no `main_pipe`;
+- `EntryPipeAmbiguousError` for a bare code that matches pipes in several domains, whether the request or the manifest spelled it, and, without `all_pipes`, for a request with no `pipe_ref` whose closure declares several `main_pipe`s.
+
+The `detail` says which case it is and, for an ambiguity, names the qualified refs to choose from; the candidates are in the `detail` alone, with no structured list, as on the run routes. The problem's `type` and `title` are the class's. Its `user_action` is the class's too, advising a check of the pipe code, except for a request with no `pipe_ref` whose closure declares no `main_pipe` or several, where it asks for a `pipe_ref` instead.
+
+An unknown or ambiguous `pipe_ref` answers the `error_type` the run routes answer for the same `pipe_code`. A closure declaring no `main_pipe`, or several, has no run-route twin: this route refuses both as the pipe-selector design classifies them, while a run over such a closure today fails with a `500` or runs the first declaration.
+
+A bare `pipe_ref` that matches one pipe (`echo` where `smoke.echo` is meant) is still resolved today, and the valid arm reports the qualified ref.
+
+**With `all_pipes: true` the route never refuses for want of an entry pipe**, so a method that declares no entry pipe, or several, is still describable. The valid arm's `pipe_ref` is then the requested ref (an unknown one is still a `422`), else the chain's answer, else `null`.
+
+## Response (valid verdict)
+
+```json
+{
+ "is_valid": true,
+ "pipe_ref": "smoke.echo",
+ "pipe_io_contracts": { "smoke.echo": { "inputs": { "…": {} }, "output": { "…": {} } } },
+ "input_form": { "smoke.echo": { "fields": [ { "kind": "prose", "name": "text", "…": "…" } ] } },
+ "output_form": { "smoke.echo": { "field": { "kind": "prose", "name": "output", "…": "…" } } },
+ "default_pipe_ref": "smoke.echo",
+ "pending_signatures": [],
+ "is_runnable": true,
+ "files": [{ "content": "...bundle...", "source": "main.mthds" }]
+}
+```
+
+- `is_valid` (`true`): the closure parsed, loaded and passed static validation. It does **not** mean a dry run passed; this route runs none.
+- `pipe_ref` (string | null): the qualified ref the selection resolved, read off the resolved pipe and never echoed from the request. `null` only under `all_pipes` when nothing resolves.
+- `pipe_io_contracts`, `input_form`, `output_form` (objects keyed by qualified `pipe_ref`): the three artifacts, sharing one key set — the resolved `pipe_ref` alone by default, every pipe the closure loads under `all_pipes`.
+- `default_pipe_ref` (string | null): the method's own entry pipe, the selection chain without the request's `pipe_ref`. A request that omits `pipe_ref` therefore always answers `pipe_ref == default_pipe_ref`. When the request named a pipe, or asked for `all_pipes`, and the chain finds no entry pipe or several, the field is a stated `null`.
+- `pending_signatures` (list of strings) and `is_runnable` (boolean): exactly what they mean on `/v1/validate` — the qualified refs of the pipes still declared as signatures, and `not pending_signatures`. Both come from the loaded library with no dry run, so a method whose dry run would fail is still reported runnable here.
+- `files` (list, only with `include_files: true`): the closure in the request's own `files[]` shape. For inline `files` it is the request's files echoed back; for a `method_ref` it is the fetched package's `.mthds` files, each `source` being the file's path relative to the package root. A package's other files are never included. Without `include_files` the field is absent, not empty.
+
+**The artifacts are pinned to `/v1/validate`.** For a closure both routes accept, each artifact map equals the same-named field of `/v1/validate`'s valid arm (requested with `views: ["input_form", "output_form"]`) restricted to the same keys: both routes derive them with the one builder and dump them the same way, keeping null members such as a contract's `item_count: null`. The two routes do not accept exactly the same closures: `/v1/validate` refuses a closure whose dry run fails, which this route accepts; this route refuses an address-based cross-package dependency, which `/v1/validate` loads; and `/v1/validate` by `method_ref` also loads a package's non-`.mthds` files, which this route never reads.
+
+`default_pipe_ref` is **not** `/v1/validate`'s field of the same name. That one is the run default: where several domains declare a `main_pipe`, it names the first declaring blueprint's, because a run would take it, while this route refuses to choose and states `null`.
+
+## Response (invalid verdict)
+
+An invalid closure is the `200` crate verdict `/v1/resolve` gives: `is_valid: false`, the structured `validation_errors[]` and a `message`. It carries no artifacts, no `pipe_ref` or `default_pipe_ref`, no runnability facts and no `files`, whatever the request asked for.
+
+## No verdict
+
+Every non-2xx is RFC 7807 `application/problem+json` (see [Error Responses](error-responses.md)):
+
+- **`422`** for a malformed body, neither or both closure selectors and an over-limit file, all `ValidationError`, and for the selection refusals above, `EntryPipeNotFoundError` or `EntryPipeAmbiguousError`.
+- **The `method_ref` fetch outcomes**, exactly as on `/v1/resolve`: `404` `MethodPackageNotFoundError` when no package in the fetched repository matches the address, `422` for a reference that does not parse or a fetch the server cannot accept, and `501` `MethodRefNotSupported` for a registry-form reference. The route reads only a package's `.mthds` files, so the custom-code and structures `403`s of `/v1/validate` and the run routes never arise here.
+- **`401` / `403`** for authentication, and **`413`** for a body over the size limit.
+- **`500`** when an artifact cannot be derived: a pipe whose input or output JSON Schema cannot be rendered raises `PipeIOContractError`, which answers `500` as it does on `/v1/validate` — a fault of the tool, not a verdict about the method.
diff --git a/api/docs/pipe-run.md b/api/docs/pipe-run.md
new file mode 100644
index 000000000..5503e74ce
--- /dev/null
+++ b/api/docs/pipe-run.md
@@ -0,0 +1,791 @@
+# Pipe Run
+
+Execute pipelines with flexible input formats. Choose between synchronous execution (wait for completion) or asynchronous execution (non-blocking). Both routes are part of the [MTHDS Protocol](https://mthds.ai) — this server is the protocol's reference implementation.
+
+> **About `mthds_contents` and MTHDS.** An "MTHDS file" is a Pipelex pipeline definition written in TOML (with the `.mthds` extension). The `mthds_contents` field on every endpoint below is a JSON array of those file contents as raw strings — typically `[open("my_pipe.mthds").read()]` from a client. You can either pass a `pipe_code` referring to a pipe already registered on the server, pass `mthds_contents` inline (the array must contain a file with a `main_pipe` property), or both.
+
+### Execute Pipeline
+
+Execute a Pipelex pipeline with flexible inputs and wait for completion.
+
+**Endpoint:** `POST /v1/execute`
+
+> **Backend selected by `orchestration_mode`.** `/execute` dispatches through the deployment's `orchestration_mode` (config default + optional policy-gated per-request `orchestration_mode` override), symmetric with `/start` — see [Configuration → Orchestration mode](configuration.md). On the orchestrator-agnostic base (`direct`, the default) it runs **in-process**; a `temporal` flavor dispatches the run to a worker and awaits it. `/execute` is **synchronous** (it returns the full output) and always uses `BLOCKING` delivery — wait-semantics is endpoint-set, never requestable, so there is no fire-and-forget option here (use `POST /v1/start`). A per-request backend override is honored only where the deployment sets `allow_request_orchestration_mode_override = true`; otherwise a token differing from the default is refused with a `403`.
+
+**Request Body:**
+
+```json
+{
+ "pipe_code": "your_pipeline_code",
+ "mthds_contents": null,
+ "inputs": {
+ "input_name": "simple text or object"
+ },
+ "output_name": null,
+ "output_multiplicity": null,
+ "dynamic_output_concept_ref": null
+}
+```
+
+**Request Fields:**
+
+- `pipe_code` (string, optional): The code identifying the pipeline to execute. Required if no `mthds_contents` is provided, or if `mthds_contents` doesn't have a `main_pipe` property. Can be combined with `mthds_contents` to specify which pipe to execute from the provided MTHDS definition.
+- `mthds_contents` (list[str], optional): Inline MTHDS file contents as raw strings (always an array, even for a single file). If provided without `pipe_code`, the bundle must contain a file with a `main_pipe` property.
+- `inputs` (PipelineInputs, optional): Flexible input format - see [Input Format: PipelineInputs](#input-format-pipelineinputs) below
+- `output_name` (string, optional): Name for the output slot
+- `output_multiplicity` (string, optional): Output multiplicity setting (`"single"`, `"variable"`, or a specific number)
+- `dynamic_output_concept_ref` (string, optional): Override output concept ref
+- `bundle_b64` (string, optional): **Pipelex-API extension.** Base64-encoded zip of a whole method bundle — see [Shipping a method bundle](#shipping-a-method-bundle-custom-pipefunc). Mutually exclusive with `files`.
+- `files` (dict[str, str], optional): **Pipelex-API extension.** The same bundle as a `{relative_path: text}` map (the unzipped equivalent of `bundle_b64`). Mutually exclusive with `bundle_b64`.
+- `method_ref` (string, optional): **Pipelex-API extension.** Run a published method by address instead of inline source — see [Running a method by address](#running-a-method-by-address-method_ref). Mutually exclusive with `mthds_contents` and with a method bundle; `pipe_code` may accompany it to override the package's `main_pipe`.
+- `storage_scope` (string, optional): **Pipelex-API extension.** The prefix every object this run writes lands under — see [Host-supplied run context](#host-supplied-run-context-storage_scope-and-analytics_groups).
+- `read_scope` (string, optional): **Pipelex-API extension.** The prefix every stored object this run reads must lie under — see [Host-supplied run context](#host-supplied-run-context-storage_scope-and-analytics_groups).
+- `analytics_groups` (dict[str, str], optional): **Pipelex-API extension.** The groups this run's telemetry belongs to, such as `{"organization": "org_acme"}` — see [Host-supplied run context](#host-supplied-run-context-storage_scope-and-analytics_groups).
+
+**Validation Rules:**
+
+- At least one of `pipe_code`, `mthds_contents`, a method bundle, or `method_ref` must be provided
+- If only `pipe_code`: Must reference a pipe already registered in the library
+- If only `mthds_contents`: Must contain a `main_pipe` property
+- If both: `pipe_code` specifies which pipe to execute from the `mthds_contents`
+
+**Response:**
+
+```json
+{
+ "pipeline_run_id": "abc123...",
+ "created_at": "2026-01-15T12:00:00Z",
+ "state": "COMPLETED",
+ "finished_at": "2026-01-15T12:00:05Z",
+ "main_stuff_name": "result",
+ "pipe_output": {
+ "working_memory": {
+ "root": { "result": { "content": { "...": "..." } } },
+ "aliases": { "main_stuff": "result" }
+ }
+ }
+}
+```
+
+**Response Fields:**
+
+- `pipeline_run_id` (string): Unique identifier for the run.
+- `created_at` (string): ISO timestamp when the pipeline was created.
+- `state` (string): One of `"RUNNING"`, `"COMPLETED"`, `"FAILED"`, `"CANCELLED"`, `"ERROR"`, `"STARTED"`.
+- `finished_at` (string | null): ISO timestamp when the pipeline finished, or `null` if still running.
+- `main_stuff_name` (string | null): Key under `pipe_output.working_memory.root` where the main result lives. Use this to extract the typed output: `pipe_output.working_memory.root[main_stuff_name].content`.
+- `pipe_output` (object): Result of the pipeline execution. Contains `working_memory` with `root` (every named stuff produced during the run) and `aliases` (built-in name mappings such as `main_stuff`).
+- `pipe_output.tokens_usages` (array | null): Per-inference-call token usage in the client wire shape (`TokensUsageRecord`): `model_type`, model name/id, `pipe_code`, job-kind fields, `nb_tokens_by_category`, computed USD `cost` (`null` when the model has no rate table), and ISO timestamps. `null` when usage assembly was off for the run, `[]` when no inference happened. `pipe_output.usage_assembly_error` (string | null) is non-null when usage assembly failed. See the pipelex runtime's [TokensUsage Wire Records](https://docs.pipelex.com/under-the-hood/tokens-usage-wire-records/) for the full field reference.
+- `pipe_output.graph_spec` (object | null): Best-effort execution graph of the run — the nodes and edges the run actually traversed. `null` when graph generation was off for the run, which is the `interpreter.pipeline_execution.is_generate_graph` setting (`true` in the packaged config); it does not depend on `runtime.tracing`, whose `is_enabled` selects a trace-emission backend rather than gating assembly. `pipe_output.graph_assembly_error` (string | null) is non-null when assembly ran and failed, which is what distinguishes a failed assembly from generation having been off.
+- `pipe_output.pipe_io_artifacts` (object | null): The I/O artifacts describing the graph's data, carried beside `graph_spec` so that wherever the graph travels its description travels with it. It groups the same artifacts `/validate` produces — `pipe_io_contracts`, `input_form` and `output_form` — each keyed by namespaced `pipe_ref`, over the **run library's own pipes**: a dependency package's pipes are keyed by alias in the library but by bare `pipe_ref` in the artifacts, where they would collide with the host's, so they are left out and a graph node contributed by a dependency has no entry here. Holding it with the graph is what lets a viewer show a data node's value rather than only its shape. It is built only when the run generated a graph **and** `interpreter.pipeline_execution.graph.graphs_inclusion.graphspec_json` is on (both default to `true`), and only when `graph_spec` itself came out non-null — so a run with `graphspec_json = false` returns a graph with no artifacts beside it and no error, which is the one case where the two fields disagree. `pipe_output.pipe_io_artifacts_error` (string | null) is non-null when the build ran and failed. See [Pipe Validate](pipe-validate.md) for the artifacts' own field reference.
+- `method_provenance` (object, only on `method_ref` runs): `{address, tag, commit_sha}` — the package's resolved full address, the requested tag (`null` for a bare address), and the commit SHA that was actually fetched. Absent for runs from inline source or a bundle. See [Running a method by address](#running-a-method-by-address-method_ref).
+
+**Errors** are returned as [RFC 7807 `application/problem+json`](error-responses.md) bodies with HTTP 4xx/5xx status codes. The successful response body has no `status`/`error` field — the HTTP status code is the source of truth. An invalid bundle is refused before any pipe runs with a `422` carrying the same located `validation_errors` validating it gives ([Structured validation errors](error-responses.md#structured-validation-errors)), and a run that fails reports its root fault at the pipe that failed ([Run failures](error-responses.md#run-failures-the-root-fault-located-at-the-failing-pipe)).
+
+---
+
+### Start Pipeline
+
+Start a pipeline execution and get its `pipeline_run_id` back with a `202` ack.
+
+**Endpoint:** `POST /v1/start`
+
+> **Fire-and-forget is a property of this endpoint, honored only by an async-capable backend.** `orchestration_mode` names only the deployment's backend; `/start` sets `FIRE_AND_FORGET` delivery and requires an orchestrator that can honor it. A Temporal deployment (`orchestration_mode = "temporal"`) enqueues the run and returns immediately with a `workflow_id`. On the orchestrator-agnostic base (`orchestration_mode = "direct"`, the default — see [Configuration → Orchestration mode](configuration.md)) the in-process orchestrator is blocking-only, so `/start` is **HONEST**: it refuses with a `400` (`StartRequiresAsyncOrchestration`) — use `POST /v1/execute` — rather than silently running blocking and acking. The completion callback fires on the async path.
+
+**Request Body:**
+
+```json
+{
+ "pipe_code": "your_pipeline_code",
+ "mthds_contents": null,
+ "inputs": {
+ "input_name": "simple text or object"
+ },
+ "output_name": null,
+ "output_multiplicity": null,
+ "dynamic_output_concept_ref": null
+}
+```
+
+**Request Fields:**
+
+- `pipe_code` (string, optional): The code identifying the pipeline to execute. Required if no `mthds_contents` is provided, or if `mthds_contents` doesn't have a `main_pipe` property.
+- `mthds_contents` (list[str], optional): Inline pipeline definitions (always an array, even for a single file). If provided without `pipe_code`, must have a `main_pipe` property.
+- `inputs` (PipelineInputs, optional): Flexible input format - see [Input Format: PipelineInputs](#input-format-pipelineinputs) below
+- `output_name` (string, optional): Name for the output slot
+- `output_multiplicity` (string, optional): Output multiplicity setting (`"single"`, `"variable"`, or a specific number)
+- `dynamic_output_concept_ref` (string, optional): Override output concept ref
+- `bundle_b64` (string, optional): **Pipelex-API extension.** Base64-encoded zip of a whole method bundle — see [Shipping a method bundle](#shipping-a-method-bundle-custom-pipefunc). Mutually exclusive with `files`.
+- `files` (dict[str, str], optional): **Pipelex-API extension.** The same bundle as a `{relative_path: text}` map (the unzipped equivalent of `bundle_b64`). Mutually exclusive with `bundle_b64`.
+- `method_ref` (string, optional): **Pipelex-API extension.** Run a published method by address instead of inline source — see [Running a method by address](#running-a-method-by-address-method_ref). Mutually exclusive with `mthds_contents` and with a method bundle; `pipe_code` may accompany it to override the package's `main_pipe`.
+- `storage_scope` (string, optional): **Pipelex-API extension.** The prefix every object this run writes lands under — see [Host-supplied run context](#host-supplied-run-context-storage_scope-and-analytics_groups).
+- `read_scope` (string, optional): **Pipelex-API extension.** The prefix every stored object this run reads must lie under — see [Host-supplied run context](#host-supplied-run-context-storage_scope-and-analytics_groups).
+- `analytics_groups` (dict[str, str], optional): **Pipelex-API extension.** The groups this run's telemetry belongs to, such as `{"organization": "org_acme"}` — see [Host-supplied run context](#host-supplied-run-context-storage_scope-and-analytics_groups).
+
+**Validation Rules:**
+
+- At least one of `pipe_code`, `mthds_contents`, a method bundle, or `method_ref` must be provided
+- If only `pipe_code`: Must reference a pipe already registered in the library
+- If only `mthds_contents`: Must contain a `main_pipe` property
+- If both: `pipe_code` specifies which pipe to execute from the `mthds_contents`
+
+**Important Notes:**
+
+- This endpoint answers `202 Accepted` immediately with a `StartAck` carrying the `pipeline_run_id`
+- The pipeline continues executing in the background
+- `pipe_output` will be `null` in the response (pipeline hasn't completed yet)
+- The request body MAY carry a client-supplied **`pipeline_run_id`** (max 128 chars): this server honors it, and the `StartAck.pipeline_run_id` echoes it back. When absent, the server generates one. (`StartAck.pipeline_run_id` is always authoritative — protocol rule.)
+
+**Response (202):**
+
+```json
+{
+ "pipeline_run_id": "abc123...",
+ "created_at": "2026-01-15T12:00:00Z",
+ "state": "STARTED",
+ "finished_at": null,
+ "main_stuff_name": null,
+ "pipe_output": null,
+ "workflow_id": "pipeline-abc123..."
+}
+```
+
+**Response Fields:**
+
+- `pipeline_run_id` (string): Unique identifier for the run. Use this to correlate callbacks (see below).
+- `created_at` (string): ISO timestamp when the pipeline was started.
+- `state` (string): Always `"STARTED"` from this endpoint — the pipeline is queued, not finished.
+- `finished_at` (null): Always `null`; the pipeline hasn't completed.
+- `main_stuff_name` (null): Always `null`; populated only on the eventual completion callback.
+- `pipe_output` (null): Always `null`; the result isn't ready yet.
+- `workflow_id` (string | null): The async orchestrator's workflow ID. A `202` ack is only ever returned by an async-capable backend (e.g. a Temporal flavor), so this carries that orchestrator's id; the in-process `direct` base never acks here — it returns a `400` (`StartRequiresAsyncOrchestration`) instead.
+- `method_provenance` (object | null): `{address, tag, commit_sha}` for a `method_ref` run — see [Running a method by address](#running-a-method-by-address-method_ref); `null` for runs from inline source or a bundle.
+
+**Errors** follow the same convention as `/execute`: HTTP 4xx/5xx with an [RFC 7807 `application/problem+json`](error-responses.md) body.
+
+#### Async Completion Callbacks (optional)
+
+`POST /v1/start` accepts an additional optional field in the request body, **`callback_urls`** — a list of HTTP(S) endpoints the server will POST to once the pipeline finishes. This is a **pipelex-api extension**, not part of the MTHDS Protocol (the protocol defines no completion channel; each implementation defines and documents its own extension args). SDK clients pass it through the generic `extra` mapping, e.g. `client.start(..., extra={"callback_urls": [...]})`.
+
+```json
+{
+ "pipe_code": "your_pipeline_code",
+ "inputs": { "input_name": "..." },
+ "callback_urls": ["https://my-app.example.com/pipelex-finished"]
+}
+```
+
+When the pipeline completes, each URL in the list receives a POST carrying:
+
+- A completion notice in the body, not the run's output: `pipeline_run_id`, the delivery `state` (`"COMPLETED"` or `"FAILED"`, also sent under the legacy `status` key), `result_url` (when results were stored: the storage key prefix under which the result files sit, not a fetchable URL) and `error` (the raw `ErrorReport` dict on failure). The receiver reads the results from storage under that prefix.
+- An **`X-Completion-Signature`** header — `HMAC-SHA256(secret, pipeline_run_id)` rendered as a hex digest
+
+**Verifying the signature on the receiver side**
+
+Your callback handler should recompute the same HMAC using its own copy of the shared secret and reject any request that doesn't match. Pseudocode:
+
+```python
+import hmac, hashlib
+
+expected = hmac.new(
+ SHARED_SECRET.encode("utf-8"),
+ pipeline_run_id.encode("utf-8"),
+ hashlib.sha256,
+).hexdigest()
+
+if not hmac.compare_digest(expected, request.headers["X-Completion-Signature"]):
+ return Response(status=401)
+```
+
+The signer (this server) and the verifier (your callback receiver) must share the same secret value. The secret never travels over the wire — only the per-run HMAC does — so even if a callback request is intercepted, the secret stays safe.
+
+**Server-side requirement**
+
+Set the `COMPLETION_CALLBACK_SECRET` environment variable on the API server **only if** you use `callback_urls`. The variable is read lazily — the server boots fine without it, and only requires it when actually signing a callback. If you call `/start` with `callback_urls` and the env var isn't set, you'll get a 500 with `EnvVarNotFoundError: Environment variable 'COMPLETION_CALLBACK_SECRET' is required but not set`.
+
+The receiver-side secret must be the same value. In typical deployments both sides pull from a shared secrets store (AWS Secrets Manager, Vault, etc.).
+
+---
+
+## Shipping a method bundle (custom PipeFunc)
+
+`mthds_contents` carries only the `.mthds` text. When your method uses a **custom `PipeFunc`** — your own Python function — the code has to travel with the method too. Both `/execute` and `/start` accept the whole bundle in one of two mutually-exclusive forms:
+
+- `bundle_b64`: a base64-encoded **zip** of the bundle directory (`.mthds` + `pipe_func.py` + an optional `requirements.txt`).
+- `files`: the same content as a `{relative_path: text}` **map** (the unzipped equivalent) — handy for JSON clients that would rather not zip.
+
+The server materializes the bundle into a temporary library directory for the run and tears it down afterward. The pipe to run comes from the bundle's `main_pipe` (or an explicit `pipe_code`, to pick which pipe in the bundle to run). A bundle carries its own `.mthds`, so it is **mutually exclusive with inline `mthds_contents`** — sending both is a `422` (they would load into one library with no dedup and a shared domain would collide).
+
+**Example (`files` form):**
+
+```json
+{
+ "files": {
+ "main.mthds": "domain = \"demo\"\nmain_pipe = \"crunch\"\n\n[pipe.crunch]\ntype = \"PipeFunc\"\ndescription = \"Crunch numbers\"\ninputs = { data = \"Text\" }\noutput = \"Text\"\nfunction_name = \"crunch\"\n",
+ "pipe_func.py": "def crunch(working_memory):\n return \"...\"\n"
+ },
+ "inputs": { "data": "1,2,3" }
+}
+```
+
+**Ingest guards.** Bundles are bounded at ingest and rejected with a clear error (never a silent truncation):
+
+- A hard **file-count** ceiling (`MAX_BUNDLE_FILES`) and a **total decompressed-size** ceiling (`MAX_BUNDLE_TOTAL_KIB`) → `413 PayloadTooLarge`. The zip path bounds actual decompression, so a zip bomb cannot expand past the ceiling, and an oversized `bundle_b64` is refused on its encoded length *before* it is decoded into memory.
+- **Path safety:** entry names that are absolute, use `..` traversal, use backslashes, or carry a Windows drive/`:` form → `422 InvalidBundle`.
+- Supplying **both** `bundle_b64` and `files`, an empty bundle, or a corrupt zip → `422 InvalidBundle`; invalid base64 → `400 InvalidBase64`.
+
+**Sandbox-hosted only for custom Python.** A bundle that ships any `.py` is honored **only on a sandbox-hosted deployment**, where the load path reads the source without importing it and execution happens in an isolated sandbox. On a non-hosted deployment such a bundle is refused with `403 CustomCodeRequiresSandbox` — running caller-supplied code in-process is never done implicitly. A bundle that carries only `.mthds` (no `.py`) is accepted on any deployment.
+
+**No Python structure classes.** A structure class (a `StructuredContent` subclass) can only be used by importing its module into the runner's own process, which a sandbox-hosted deployment never does, so a bundle whose Python declares one is refused with a `403` (`MethodStructuresRefusedError`) naming each file and class, before anything is loaded. The rule is the same however the method arrives: inline as a bundle, or fetched by `method_ref`. Declare the types as MTHDS concepts with inline structures instead; a PipeFunc returns them by importing the classes the sandbox generates from those concepts (`from structures import <domain>__<Concept>`). The `structures` module that `pipelex build structures` writes is accepted as long as it is left as generated, and it is not sent to the sandbox, which generates its own.
+
+---
+
+## Running a method by address (`method_ref`)
+
+Both `/execute` and `/start` accept **`method_ref`** — a globally resolvable address of a published method package, resolved **by this server** (a Pipelex-API extension; the hosted-only catalog selector `method_id` is a different, platform-resolved field that never reaches this runner):
+
+```json
+{
+ "method_ref": "github.com/Pipelex/methods/[email protected]",
+ "inputs": { "document": "https://example.com/report.pdf" }
+}
+```
+
+**The reference grammar is `<address>[@<tag>]`.** The address is `github.com/<owner>/<repo>` optionally followed by a package selector within the repository (`github.com` only for now). A bare address means the repository's default branch at HEAD; `@<tag>` pins the repository at that **git tag** (recommended form `vX.Y.Z`) — branch names are refused, so a reference can never silently track a moving branch. Full browser URLs (`https://github.com/...`, including `/tree/<branch>/...` deep links) are accepted and normalized.
+
+**Resolution.** The server fetches the repository (shallow clone, at the tag when one is named), records the **commit SHA** of what was fetched, and locates the requested package **by manifest identity**: it scans the clone for `METHODS.toml` manifests and selects the one whose declared address (plus `name`, for a package in a library repo) equals the requested address — never by directory path. The package's `.mthds` files then run exactly like an inline submission; its non-`.mthds` files travel like a bundle's.
+
+**Entry pipe.** The pipe to run defaults to the package manifest's `main_pipe`; an explicit `pipe_code` in the request overrides it (to run another pipe from the fetched package).
+
+**Provenance.** The response carries `method_provenance = {address, tag, commit_sha}` — on `/execute` only for `method_ref` runs, on the `/start` ack as a nullable field. Tags can move; the recorded SHA is what keeps a run explainable after the fact.
+
+**Custom Python follows the bundle rules, plus one more.** What decides is *where the code would execute*: `.mthds` content is data, always acceptable. On a deployment that is **not** sandbox-hosted, a fetched package carrying any `.py` is refused with `403 CustomCodeRequiresSandbox`. On a sandbox-hosted deployment, PipeFunc `.py` is accepted (captured as text, executed in the isolated sandbox) — but a package declaring **Python structure classes** (`StructuredContent` subclasses) is refused with a `403` (`MethodStructuresRefusedError`), exactly as a bundle is: see [No Python structure classes](#shipping-a-method-bundle-custom-pipefunc).
+
+**Errors.** Every resolution failure is a distinct RFC 7807 `problem+json` with the originating class as `error_type` (see [Error responses](error-responses.md)):
+
+| Failure | Status | `error_type` |
+|---|---|---|
+| Reference does not match the grammar | 422 | `MethodRefParseError` |
+| Repository could not be fetched, or `@<tag>` is not a tag | 422 | `MethodFetchError` |
+| No package matches the address (message lists what the repo contains) | 404 | `MethodPackageNotFoundError` |
+| More than one package matches | 422 | `MethodPackageAmbiguityError` |
+| Package exceeds the fetched-package ceilings | 422 | `MethodPackageTooLargeError` |
+| Package declares Python structure classes | 403 | `MethodStructuresRefusedError` |
+| Package ships `.py` on a non-sandbox deployment | 403 | `CustomCodeRequiresSandbox` |
+
+**The clone cache.** Fetched repositories are cached on local disk **keyed by resolved commit SHA** — never by tag. Each request first resolves the reference to its current SHA with a cheap `git ls-remote` (no clone); a cached SHA is reused, a new one (a moved tag, an advanced HEAD) triggers a fresh clone. The cache is per server instance and bounded by count, total bytes, and age.
+
+**Environment knobs.** The cache: `MAX_METHOD_CACHE_CLONES` (default 64), `MAX_METHOD_CACHE_TOTAL_KIB` (default 512 MiB), `MAX_METHOD_CACHE_AGE_HOURS` (default 24), `METHOD_CACHE_DIR` (default: a fixed directory under the system temp dir). The fetch itself is bounded by the pipelex runtime's fetched-package ceilings: `PIPELEX_MAX_FETCHED_PACKAGE_FILES` (default 256), `PIPELEX_MAX_FETCHED_PACKAGE_TOTAL_KIB` (default 8 MiB), and the manifest-scan bounds `PIPELEX_MAX_SCANNED_MANIFESTS` (default 100 manifests considered per fetched repository) and `PIPELEX_MAX_MANIFEST_FILE_KIB` (default 256 KiB per `METHODS.toml` read during package location). All are read once at process start.
+
+`method_ref` also selects the method on the tooling routes: natively on [`POST /v1/validate`](pipe-validate.md), and as the closure selector on [`/resolve` and `/codegen`](codegen.md) (address form resolved; the registry form stays a `501`).
+
+---
+
+## Host-supplied run context: `storage_scope` and `analytics_groups`
+
+Both `/execute` and `/start` accept optional fields that describe the run's tenancy rather than its method: `storage_scope`, `read_scope` and `analytics_groups`. All are **Pipelex-API extensions**, and all are **data the host computes**, which is why they ride in the body: the caller's *identity* arrives separately, on the trusted `X-User-Id` header or the bearer token (see [Authentication](index.md#authentication)), because it is something a proxy vouches for rather than something the caller chooses. The runtime carries them opaquely and never reads a value by name, so it has no notion of what an organization or a tenant is.
+
+```json
+{
+ "pipe_code": "your_pipeline_code",
+ "inputs": { "input_name": "..." },
+ "storage_scope": "org_acme/method_42/run_7",
+ "read_scope": "org_acme",
+ "analytics_groups": { "organization": "org_acme" }
+}
+```
+
+**`storage_scope`** is the prefix every object the run writes lands under: one to three path-safe segments, onto which the runtime composes its own leaves (`assets/`, `generated/`, `results/`, `payloads/`). Omit it and the run is scoped to the caller's own id, which is right for a single-tenant deployment and wrong for a multi-tenant one: a host serving many tenants must send it. Each segment is one or more characters from `A-Za-z0-9_-`, so an empty segment, a leading or trailing slash, a `.` or `..`, or a fourth segment is refused with a `422` whose `error_type` is `InvalidStorageScope`.
+
+**`read_scope`** bounds what the run may read: every `pipelex-storage://` key the run reads, whether an input, a URL a pipe builds or an image it shows a model, must lie under it, and a scoped run reads no local path at all. It follows the same segment rule as `storage_scope`, and the storage scope must be the read scope or lie under it, since a run reads back what it writes: `org_acme` covers `org_acme/method_42/run_7`, while `org_other` does not. Omit it and the run is scoped to the caller's own id when the deployment identifies its callers, which is also where their writes land by default, and unscoped when the deployment is single-tenant. A host serving many tenants must send it: a host that sends its own `storage_scope` but no `read_scope` is refused, since that storage scope lies under no caller's id. A malformed read scope, a storage scope outside it, or the local storage scope `local` beside one is a `422` whose `error_type` is `InvalidReadScope`, answered before any method is fetched or library loaded. A read the scope does not allow is refused when the run makes it, with the `error_type` `UriReadRefusedError`, whose message says where the URL sat without quoting it. On `/execute` it is a `422`. On `/start` it is a synchronous `422` when an input breaks the rule, and a run that ends `FAILED` with that error in its completion callback when a pipe reaches for the URL during the run.
+
+**`analytics_groups`** names the entities the run's telemetry belongs to, as a mapping of group type to group key. The runtime carries it on the run as its opaque `extras` and stamps it on every span of the run as the attribute `pipelex.run.extras`, so every OpenTelemetry exporter receives it, and the deployment's own PostHog stream, when `telemetry.toml` sets `mode = "identified"`, attaches it to each capture as PostHog groups. That is what lets a generation made for one of your customers appear inside that customer's organization instead of under one identity for the whole deployment. What Pipelex's own Gateway telemetry stream receives is the runtime's decision, not this server's; the runtime this server pins attributes that stream the same way, with the run's `user_id` and these groups. The rules are the runtime's own, imported rather than restated here:
+
+- A **group type** (a key of the mapping) is lowercase snake_case starting with a letter, at most 32 characters, such as `organization`.
+- A **group key** (a value) is 1 to 128 characters from `A-Za-z0-9_-`. Whitespace, control characters and separators are refused, because the key is quoted into log lines and capture payloads.
+- The mapping holds **at most five** entries, since a telemetry backend registers only a small fixed number of group types per project.
+- It is **optional**. Omitting it, sending `null` or sending `{}` all mean the run belongs to no group, which misattributes nothing.
+
+A mapping outside these rules is refused with a `422` whose `error_type` is `InvalidAnalyticsGroups`, before any method is fetched or any library loaded. A body that fails on more than one of the extension fields at once answers with the generic `ValidationError`, and its `detail` names every field that failed.
+
+The caller's id is the run's person on that same stream, with one exception: a deployment with no user model attributes every run to the literal `single-tenant`, which the runtime declines as a person and replaces with the `user_id` configured in `telemetry.toml`. The groups do not depend on it, so a single-tenant deployment that sends `analytics_groups` still has them on every capture.
+
+---
+
+## Input Format: PipelineInputs
+
+The `inputs` field accepts several shapes. Pipelex picks how to interpret each value from its structure — pass a string to a `Text` input and you get `TextContent`, pass a dict with `concept` and `content` keys and you get explicit concept resolution, etc. The cases below enumerate every supported form.
+
+**The request body is plain JSON.** The Python objects in Cases 1.3 to 1.5, and the `DictStuff` instances further down, are what a Python caller writes; a Python client of this API serializes each one to plain JSON before sending it, and the server never rebuilds a Python class from the request. The class name does not travel, so each value is read against the entry pipe's declared input. A structured object (Case 1.3) arrives as its fields and a list of them (Case 1.4) as a list of those, and both are read as intended; a `DictStuff` arrives as the Case 2 envelope. A `ListContent` wrapper (Case 1.5) arrives as `{"items": [...]}`, which the server reads as one item rather than a list, and a native `TextContent` arrives as `{"text": ...}`, which a `Text` input refuses: over HTTP, send the bare list of items or strings instead, or the `{"concept": ..., "content": [...]}` envelope of Cases 2.2, 2.4 and 2.6. A body carrying a `__class__` or `__module__` key, or a key starting with `__kajson`, in any object at any depth is refused with a `422 ReservedObjectKey` (see [Error Responses](error-responses.md#status-codes)).
+
+### How Input Formatting Works
+
+**Case 1: Direct Content** - Provide the value directly (simplest)
+
+- 1.1: String → `"my text"`
+- 1.2: List of strings → `["text1", "text2"]`
+- 1.3: StructuredContent object → `MyClass(arg1="value")`
+- 1.4: List of StuffContent objects → `[MyClass(...), MyClass(...)]`
+- 1.5: ListContent of StuffContent objects → `ListContent(items=[MyClass(...), MyClass(...)])`
+
+**Note:** Cases 1.3 and 1.5 are at the same level - both handle content types that inherit from `StuffContent`, but for different purposes (custom classes vs. list wrappers).
+
+**Case 2: Explicit Format** - Use `{"concept": "...", "content": "..."}` for control (plain dict or DictStuff instance)
+
+- 2.1: String with concept → `{"concept": "Text", "content": "my text"}`
+- 2.2: List of strings with concept → `{"concept": "Text", "content": ["text1", "text2"]}`
+- 2.3: StructuredContent object with concept → `{"concept": "Invoice", "content": InvoiceObject}`
+- 2.4: List of StructuredContent objects with concept → `{"concept": "Invoice", "content": [...]}`
+- 2.5: Dictionary (structured data) → `{"concept": "Invoice", "content": {"field": "value"}}`
+- 2.6: List of dictionaries → `{"concept": "Invoice", "content": [{...}, {...}]}`
+- 2.7: File / document URL → `{"concept": "Document", "content": {"url": "https://…/file.pdf"}}`
+
+**Pro Tip:** For **text inputs specifically**, skip the verbose format. Just provide the string directly: `"text": "Hello"` instead of `"text": {"concept": "Text", "content": "Hello"}`
+
+---
+
+## Case 1: Direct Content Format
+
+When you provide content directly (without the `concept` key), Pipelex intelligently infers the type.
+
+### 1.1: Simple String (Text)
+
+The simplest case - just provide a string directly:
+
+```json
+{
+ "inputs": {
+ "my_text": "my text"
+ }
+}
+```
+
+**Result:** At a `Text` input, automatically becomes `TextContent` with concept `native.Text`
+
+The input's declaration decides the reading for two native concepts. At an `Anything` input, the string becomes a `native.Anything` value holding the text, and a number, a boolean or an object is taken the same way, as a value of its own kind; a date sent as a string is read as text. An `Anything` input refuses `null` and a list, both with a `422`: a list is taken only by an `Anything[]` input, whose items are such values and can be neither `null` nor a list themselves. At a `JSON` input, a string is refused: a `JSON` input reads a JSON object literally, and a `JSON[]` input a list of objects. `NaN` and the infinities are refused at `Number`, `JSON` and `Anything` inputs, since JSON cannot carry them.
+
+### 1.2: List of Strings (Text List)
+
+Provide multiple text items as a list:
+
+```json
+{
+ "inputs": {
+ "my_texts": ["my text1", "my text2", "my text3"]
+ }
+}
+```
+
+**Result:** Becomes a `ListContent` containing multiple `TextContent` items
+
+**Note:** The concept must be compatible with `native.Text` or an error will be raised. The one exception is an `Anything[]` input, where the list keeps the `native.Anything` concept and holds each string as text.
+
+### 1.3: StructuredContent Object
+
+Provide a structured object directly (for Python clients):
+
+```python
+# Python client example
+from my_project.domain.domain_struct import MyConcept, MySubClass
+
+inputs = {
+ "invoice_data": MyConcept(arg1="arg1", arg2=1, arg3=MySubClass(arg4="arg4")),
+}
+```
+
+**What is StructuredContent?**
+
+- `StructuredContent` is the base class for user-defined data structures in Pipelex
+- You create your own classes by inheriting from `StructuredContent`
+- These classes are defined in your project's Python files
+- Learn more: [Python StructuredContent Classes](https://docs.pipelex.com/pages/build-reliable-ai-workflows-with-pipelex/define_your_concepts/#3-python-structuredcontent-classes)
+
+**Concept Resolution** (in-process calls only, where the object itself reaches the runtime; over HTTP the class name does not travel, and the declared input decides):
+
+- The system searches all available domains for a concept matching the class name
+- If multiple concepts with the same name exist in different domains → **Error**: Must specify domain
+- If no concept is found → **Error**
+
+### 1.4: List of StuffContent Objects
+
+Provide multiple content objects in a plain Python list:
+
+```python
+# Python client example
+inputs = {
+ "invoice_list": [
+ MyConcept(arg1="arg1", arg2=1, arg3=MySubClass(arg4="arg4")),
+ MyConcept(arg1="arg1_2", arg2=2, arg3=MySubClass(arg4="arg4_2")),
+ ],
+}
+```
+
+**What it accepts:**
+
+- Lists of `StructuredContent` objects (user-defined classes)
+- Lists of native content objects (`TextContent`, `ImageContent`, etc.), in in-process calls only (over HTTP, see the plain-JSON note above)
+
+**Requirements:**
+
+- All items must be of the same type
+- Concept resolution follows the same rules as 1.3
+- Creates a new `ListContent` wrapper internally
+
+### 1.5: ListContent of StuffContent Objects
+
+Provide an existing `ListContent` wrapper object (in-process Python calls only; over HTTP, send the bare list of items, as the plain-JSON note above explains):
+
+```python
+# Python client example
+from pipelex.core.stuffs.list_content import ListContent
+
+inputs = {
+ "invoice_list": ListContent(
+ items=[
+ MyConcept(arg1="arg1", arg2=1, arg3=MySubClass(arg4="arg4")),
+ MyConcept(arg1="arg1_2", arg2=2, arg3=MySubClass(arg4="arg4_2")),
+ ]
+ ),
+}
+```
+
+**Key Difference from Case 1.4:**
+
+- Case 1.4: Plain Python list `[item1, item2]` → **Creates** a new `ListContent` wrapper
+- Case 1.5: Already wrapped `ListContent(items=[item1, item2])` → **Uses** the wrapper directly
+
+**Why Case 1.5 is Separate from Case 1.3:**
+
+- `StructuredContent` and `ListContent` are **sibling classes** (both inherit from `StuffContent`)
+- Case 1.3 handles user-defined structured data classes
+- Case 1.5 handles list container wrappers
+- They're at the same inheritance level, not parent-child
+
+**Requirements:**
+
+- All items within the `ListContent` must be `StuffContent` objects (this includes both `StructuredContent` and native content like `TextContent`, `ImageContent`)
+- All items must be of the same type
+- The `ListContent` cannot be empty
+- Concept is inferred from the first item's class name (not from "ListContent")
+
+**Use Case:** This format is useful when you already have data wrapped in a `ListContent` object from a previous pipeline execution or when working with Pipelex's internal data structures.
+
+---
+
+## Case 2: Explicit Format (Concept and Content)
+
+Use the explicit format `{"concept": "...", "content": "..."}` when you need precise control over concept selection or when working with domain-specific concepts.
+
+### 2.1: Explicit String Input
+
+```json
+{
+ "inputs": {
+ "text": {
+ "concept": "Text",
+ "content": "my text"
+ }
+ }
+}
+```
+
+**Concept Options:**
+
+- `"Text"` or `"native.Text"` for native text
+- Any custom concept that is strictly compatible with `native.Text`
+
+### 2.2: Explicit List of Strings
+
+```json
+{
+ "inputs": {
+ "documents": {
+ "concept": "Text",
+ "content": ["text1", "text2", "text3"]
+ }
+ }
+}
+```
+
+**Result:** `ListContent` with multiple `TextContent` items
+
+### 2.3: Structured Object with Concept
+
+```json
+{
+ "inputs": {
+ "invoice_data": {
+ "concept": "Invoice",
+ "content": {
+ "invoice_number": "INV-001",
+ "amount": 1250.00,
+ "date": "2025-10-20"
+ }
+ }
+ }
+}
+```
+
+**Concept Resolution with Search Domains:**
+
+When you specify a concept name without a domain prefix:
+
+- ✅ If the concept exists in only one domain → Automatically found
+- ❌ If the concept exists in multiple domains → **Error**: "Multiple concepts found. Please specify domain as 'domain.Concept'"
+- ❌ If the concept doesn't exist → **Error**: "Concept not found"
+
+**Using Domain Prefix:**
+```json
+{
+ "concept": "accounting.Invoice"
+}
+```
+
+This explicitly tells Pipelex to use the `Invoice` concept from the `accounting` domain.
+
+### 2.4: List of Structured Objects
+
+```json
+{
+ "inputs": {
+ "invoices": {
+ "concept": "Invoice",
+ "content": [
+ {
+ "invoice_number": "INV-001",
+ "amount": 1250.00
+ },
+ {
+ "invoice_number": "INV-002",
+ "amount": 890.00
+ }
+ ]
+ }
+ }
+}
+```
+
+**Result:** `ListContent` with multiple structured content items
+
+### 2.5: Dictionary Content
+
+Provide structured data as a dictionary:
+
+```json
+{
+ "inputs": {
+ "person": {
+ "concept": "PersonInfo",
+ "content": {
+ "arg1": "something",
+ "arg2": 1,
+ "arg3": {
+ "arg4": "something else"
+ }
+ }
+ }
+ }
+}
+```
+
+The system will:
+1. Find the concept structure (with domain resolution as explained above)
+2. Validate the dictionary against the concept's structure
+3. Create the appropriate content object
+
+### 2.6: List of Dictionaries
+
+```json
+{
+ "inputs": {
+ "people": {
+ "concept": "PersonInfo",
+ "content": [
+ {
+ "arg1": "something",
+ "arg2": 1,
+ "arg3": {"arg4": "something else"}
+ },
+ {
+ "arg1": "something else",
+ "arg2": 2,
+ "arg3": {"arg4": "something else else"}
+ }
+ ]
+ }
+ }
+}
+```
+
+### 2.7: File / Document Input
+
+For pipes whose inputs declare `Document`, `Image`, or `PDF` (any URL-bearing native concept), provide a `url` inside `content`. The URL can be public HTTP(S), a `pipelex-storage://` URI, or a base64 data URL.
+
+```json
+{
+ "inputs": {
+ "cv": {
+ "concept": "Document",
+ "content": { "url": "https://example.com/resume.pdf" }
+ },
+ "headshot": {
+ "concept": "Image",
+ "content": { "url": "https://example.com/photo.jpg" }
+ }
+ }
+}
+```
+
+**Optional fields on `Document` content:**
+
+- `mime_type` (string) — e.g. `"application/pdf"`. Inferred from the URL when omitted.
+- `filename` (string) — the original filename. Auto-extracted from local-file URLs.
+- `title` (string) — display title for the document.
+- `snippet` (string) — text excerpt or description.
+- `public_url` (string) — public HTTPS URL when `url` is a private/storage URI.
+
+If you pass `Document` content as a list (`[{"url": "…"}, {"url": "…"}]`), Pipelex wraps it in a `ListContent` automatically — same rules as Case 2.4.
+
+### Using DictStuff Instances (Python Clients Only)
+
+For Python clients, you can also pass `DictStuff` instances instead of plain dicts. `DictStuff` is a Pydantic model with the same structure as the explicit format.
+
+```python
+from pipelex.client import PipelexClient
+from pipelex.core.stuffs.stuff import DictStuff
+
+client = PipelexClient(api_token="YOUR_API_KEY")
+
+# Using DictStuff instance with dict content
+response = await client.execute_pipeline(
+ pipe_code="process_invoice",
+ inputs={
+ "invoice": DictStuff(
+ concept="accounting.Invoice",
+ content={
+ "invoice_number": "INV-001",
+ "amount": 1250.00,
+ "date": "2025-10-20",
+ },
+ ),
+ },
+)
+
+# Using DictStuff instance with list of dicts content
+response = await client.execute_pipeline(
+ pipe_code="process_invoices",
+ inputs={
+ "invoices": DictStuff(
+ concept="accounting.Invoice",
+ content=[
+ {"invoice_number": "INV-001", "amount": 1250.00},
+ {"invoice_number": "INV-002", "amount": 890.00},
+ ],
+ ),
+ },
+)
+
+# Using DictStuff instance with list of strings (for Text concept)
+response = await client.execute_pipeline(
+ pipe_code="analyze_texts",
+ inputs={
+ "documents": DictStuff(
+ concept="Text",
+ content=["document 1", "document 2", "document 3"],
+ ),
+ },
+)
+```
+
+**DictStuff Structure:**
+
+- `concept` (str): The concept code (with optional domain prefix)
+- `content` (dict[str, Any] | list[Any]): The actual data content
+
+**Content Types:**
+
+- **Dictionary**: Single structured object → Creates a single Stuff
+- **List of dicts**: Multiple structured objects → Creates ListContent with validated items
+- **List of strings** (for Text-compatible concepts): Creates ListContent of TextContent
+
+**Note:** `DictStuff` instances are automatically converted to plain dicts and processed through the standard Case 2 logic.
+
+---
+
+## Search Domains Explained
+
+When you reference a concept by name (like `"Invoice"` or `"PersonInfo"`), Pipelex needs to find it in your loaded domains.
+
+### Automatic Search
+
+```json
+{
+ "concept": "Invoice"
+}
+```
+
+**What happens:**
+1. Pipelex searches all available domains for a concept named `"Invoice"`
+2. If found in **exactly one domain** → ✅ Uses that concept
+3. If found in **multiple domains** → ❌ Error: "Ambiguous concept: Found 'Invoice' in domains: accounting, billing. Use 'domain.Invoice' format."
+4. If **not found** → ❌ Error: "Concept 'Invoice' not found in any domain"
+
+### Explicit Domain Specification
+
+To avoid ambiguity, specify the domain explicitly:
+
+```json
+{
+ "concept": "accounting.Invoice"
+}
+```
+
+**Format:** `"domain_name.ConceptName"`
+
+This tells Pipelex exactly which concept to use, bypassing the search.
+
+### Best Practices
+
+- Use simple names (`"Invoice"`) when you have unique concept names across domains
+- Use domain-prefixed names (`"accounting.Invoice"`) when:
+ - You have concepts with the same name in different domains
+ - You want to be explicit about which concept to use
+ - You're building APIs that need to be unambiguous
+
+---
+
+## Multiple Input Combinations
+
+Combine different input types in a single request:
+
+```json
+{
+ "inputs": {
+ "text": "Analyze this contract for risks.",
+ "category": {
+ "concept": "Category",
+ "content": {"name": "legal", "priority": "high"}
+ },
+ "options": ["option1", "option2", "option3"],
+ "invoice": {
+ "concept": "accounting.Invoice",
+ "content": {
+ "invoice_number": "INV-001",
+ "amount": 1250.00
+ }
+ }
+ }
+}
+```
+
+In this example:
+
+- `text` uses direct string format (Case 1.1)
+- `category` uses explicit format with structured content (Case 2.5)
+- `options` uses direct list format (Case 1.2)
+- `invoice` uses explicit format with domain prefix and structured content (Case 2.5)
+
+---
+
+
+
diff --git a/api/docs/pipe-validate.md b/api/docs/pipe-validate.md
new file mode 100644
index 000000000..5570e7f65
--- /dev/null
+++ b/api/docs/pipe-validate.md
@@ -0,0 +1,178 @@
+# Pipe Validate
+
+Validate MTHDS content by parsing, loading, and dry-running pipes without executing them.
+
+**Endpoint:** `POST /v1/validate`
+
+`/validate` is a **diagnostic endpoint**: any verdict the validator can produce — valid, invalid, or valid-but-not-runnable — rides an HTTP **200**, discriminated in the body on `is_valid`. "Invalid, here are the problems" is the *successful product* of the call, not a transport failure. Non-2xx is reserved for the cases where **no verdict could be produced** (a malformed request body, an `mthds_sources` length mismatch, a `method_ref` that could not be resolved, auth, or a server fault).
+
+**Request Body:**
+
+```json
+{
+ "mthds_contents": ["domain = \"my_domain\"\ndescription = \"My domain\"\nmain_pipe = \"my_pipe\"\n\n[concept.MyResult]\ndescription = \"A result\"\n\n[pipe.my_pipe]\ntype = \"PipeLLM\"\ndescription = \"Process input\"\ninputs = { text = \"native.Text\" }\noutput = \"MyResult\""]
+}
+```
+
+**Request Fields:**
+
+- `mthds_contents` (list[str], optional): MTHDS contents to validate (always an array, even for a single file). Exactly one of `mthds_contents` / `method_ref` must be provided
+- `method_ref` (string, optional): **Pipelex-API extension.** Validate a published method by address — `github.com/<owner>/<repo>` plus an optional package selector and `@<tag>` — resolved by this server through the same fetch path as a [`method_ref` run](pipe-run.md#running-a-method-by-address-method_ref): the repository is fetched at the tag, the package located by manifest identity, and its `.mthds` files validated with their **real relative paths** feeding the per-file sources (so `validation_errors[].source` names the owning file). Exactly one of `mthds_contents` / `method_ref`; `mthds_sources` cannot accompany it
+- `allow_signatures` (boolean, optional, default `false`): controls only the **sweep mechanics** for `PipeSignature` placeholders — whether signature pipes are mock-run during the dry-run sweep and therefore listed in `validated_pipes`. It does **not** change the verdict: an unimplemented signature is never a rejection, it is a *runnability fact* reported via `pending_signatures` + `is_runnable` in both modes
+- `mthds_sources` (list[str] | null, optional): per-file sources, parallel to `mthds_contents` — see [Sourcing submitted files](#sourcing-submitted-files). When present it must match `mthds_contents` in length (a mismatch is a 422 request error)
+- `render` (list[str], optional, default `[]`): opt-in *rendered text* to attach to the verdict — see [Opt-in extras](#opt-in-extras-render-and-views)
+- `views` (list[str], optional, default `[]`): opt-in *structured views* to attach to the verdict — see [Opt-in extras](#opt-in-extras-render-and-views)
+- `orchestration_mode` (string | null, optional): per-request backend override for the validation dispatch — see [Where validation runs](#where-validation-runs). Honored only when the deployment allows it; a forbidden override is a 403
+- `analytics_groups` (object | null, optional): **Pipelex-API extension.** The groups the caller belongs to, as a mapping of group type to group key, with the same rules as on a run — see [Who the validation is done for](#who-the-validation-is-done-for). A mapping outside those rules is a 422 whose `error_type` is `InvalidAnalyticsGroups`
+
+**Response (the verdict union):**
+
+The 200 body is one of two arms, discriminated on the mandatory `is_valid` field. A consumer pattern-matches `is_valid` to learn the verdict — it never inspects a status code or catches an exception body.
+
+**Valid arm (`is_valid: true`)** — the canonical Pipelex validation report (the exact same artifact shapes `PipelexMTHDSProtocol.validate` returns when the runtime is used locally) plus this server's wire-only extras (`mthds_contents` echo, `message`, `default_pipe_ref`):
+
+```json
+{
+ "is_valid": true,
+ "bundle_blueprint": {
+ "domain": "my_domain",
+ "description": "My domain",
+ "main_pipe": "my_pipe",
+ "concept": { "...": "..." },
+ "pipe": { "...": "..." }
+ },
+ "pipe_io_contracts": {
+ "my_domain.my_pipe": {
+ "inputs": { "text": { "concept_ref": "native.Text", "presence": "plain", "multiplicity": "single", "item_count": null, "json_schema": { "...": "..." } } },
+ "output": { "concept_ref": "my_domain.MyResult", "multiplicity": "single", "item_count": null, "optional": false, "json_schema": { "...": "..." } }
+ }
+ },
+ "graph_spec": { "...": "..." },
+ "validated_pipes": [
+ { "pipe_ref": "my_domain.my_pipe", "status": "SUCCESS" }
+ ],
+ "pending_signatures": [],
+ "is_runnable": true,
+ "mthds_contents": ["..."],
+ "message": "MTHDS content validated successfully",
+ "default_pipe_ref": "my_domain.my_pipe"
+}
+```
+
+**Response Fields (canonical report — valid arm):**
+
+- `is_valid` (`true`): the discriminant of the valid arm — always `true` on this report
+- `bundle_blueprint` (object): the batch's primary blueprint — the first file declaring `main_pipe`, else the first file
+- `pipe_io_contracts` (object): per-pipe input/output contracts, keyed by the namespaced `pipe_ref` (`domain.code`). Each input carries its `concept_ref`, `presence`, `multiplicity` (`single` | `variable` | `fixed`), `item_count` and the JSON Schema of its content; the output carries its fully qualified `concept_ref`, `multiplicity`, `item_count`, `optional` and the JSON Schema of its payload. `item_count` is the exact count on `fixed`, always greater than one since `Concept[1]` reads as `single`, and `null` otherwise, so an output declared `Text[3]` reports `"multiplicity": "fixed", "item_count": 3`
+- `graph_spec` (object | null): best-effort execution graph of the pipe a selector-less run of this request would execute — the pipe [`default_pipe_ref`](#the-effective-entry-pipe) names — dry-run against the validated library; `null` when no entry pipe is determined or the graph dry-run degrades
+- `validated_pipes` (list): per-pipe sweep outcomes — `{pipe_ref, status}` entries with status `SUCCESS` | `FAILURE` | `SKIPPED`
+- `pending_signatures` (list[str]): namespaced refs of pipes still declared as signatures (contract-only pipes — `inputs`/`output` with no `type` and no implementation) in the assembled library — what remains to implement
+- `is_runnable` (boolean): `pending_signatures` is empty — whether the validated library is complete enough to run
+
+**Response Fields (wire extras, valid arm only, this server only):**
+
+- `mthds_contents` (list[str]): echo of the validated request contents
+- `message` (string): status message
+- `default_pipe_ref` (string | null): the qualified `domain.pipe_code` a caller gets by **omitting** the pipe selector — the pipe a selector-less run of this same request would execute. See [The effective entry pipe](#the-effective-entry-pipe) below
+
+**Response Fields (opt-in, present only when requested):**
+
+- `input_form` (object, valid arm only, requires `views: ["input_form"]`): per-pipe input-form descriptors, keyed by the same namespaced `pipe_ref` as `pipe_io_contracts`. Each entry carries an ordered `fields` list describing what a caller must collect to run that pipe — a field's `kind` (drawn from a closed vocabulary), its `name`, whether it is `required`, whether an empty value should `gate` the run, and the per-kind detail (`choices`, `item_count`, `default_value`, nested `concept_ref`, …). It is a **projection of facts the verdict already states**, derived from what the bundle authored rather than from the emitted JSON Schema, so a client can render a run form from the verdict alone
+- `output_form` (object, valid arm only, requires `views: ["output_form"]`): per-pipe output-form descriptors, keyed by the same namespaced `pipe_ref` as `pipe_io_contracts`. Each entry carries a single `field`, drawn from the same closed field vocabulary `input_form` uses, describing what that pipe produces — so a caller rendering a result, or registering a tool signature with a return type, reads the output's shape without inferring it from a value. Its JSON Schema is not here: that rides `pipe_io_contracts[…].output.json_schema`, and the pairing is the point — the descriptor states what the output IS, the schema names the property its payload arrives under
+- `rendered_markdown` (string, both arms, requires `render: ["markdown"]`): a server-rendered Markdown view of the verdict, produced by the same renderers the local CLI uses
+
+**Invalid arm (`is_valid: false`)** — the per-error diagnostics plus the runnability facts; the structural artifacts (`bundle_blueprint`, `pipe_io_contracts`, `graph_spec`, `validated_pipes`) and `mthds_contents` are **absent**, because they do not exist when load/parse/wiring failed:
+
+```json
+{
+ "is_valid": false,
+ "validation_errors": [
+ {
+ "category": "blueprint_validation",
+ "message": "Value error, Invalid main pipe syntax 'Not A Valid Pipe Code!'. Must be in snake_case.",
+ "error_type": "invalid_pipe_code_syntax",
+ "domain_code": "broken",
+ "source": "broken.mthds"
+ }
+ ],
+ "pending_signatures": [],
+ "is_runnable": false,
+ "message": "Value error, Invalid main pipe syntax 'Not A Valid Pipe Code!'. Must be in snake_case."
+}
+```
+
+**Response Fields (invalid arm):**
+
+- `is_valid` (`false`): the discriminant of the invalid arm
+- `validation_errors` (list): the structured per-error diagnostics a client maps to per-line problems — built by pipelex's one shared builder, so they are byte-for-byte the same items the agent CLI emits. Each item carries a `category` (the closed set `blueprint_validation` | `pipe_factory` | `pipe_validation` | `dry_run`), a `message`, and the locators the runtime can attribute (`error_type`, `pipe_code` / `concept_code` / `domain_code`, `field_path` / `field_name`, and `source`). Absent locators are omitted, not null. An item may also carry a **`suggested_fix`** — a structured, deterministic repair (`fix_code`, `description`, `safety: safe|unsafe`, and the `ops[]` of semantic TOML patch operations to apply). It is present only when the fix planner derived one from the typed error data; a client that ignores it behaves exactly as before. See [Error Responses → Structured validation errors](error-responses.md#structured-validation-errors) and [→ Suggested fixes](error-responses.md#suggested-fixes) for every field. The array is **never empty on an invalid verdict** (the structured-info invariant is total): a failing dry run becomes one `dry_run` item per failing pipe, located at the innermost pipe that failed (its `pipe_code`, `domain_code` and, when known, `source`), a TOML syntax error carries the `line` and `column` the parser stopped at, and a parse-level failure with no attributable locator (an empty blueprint, an elaborator failure) becomes one `blueprint_validation` residual item carrying the message (no `source`). Every refusal of the bundle while it loads is an item of the verdict, an unknown model included (an `unknown_model` item on the pipe's `model` field), never a no-verdict `5xx`
+- `pending_signatures` (list[str]): best-effort outstanding signatures (empty on the invalid arm, since no library was assembled)
+- `is_runnable` (`false`): an invalid bundle is never runnable
+- `message` (string): the human-readable verdict summary: the lone item's message when there is one item, `N validation errors (first: <the first item's message>)` when there are several, and the parser's own message for a parse-level failure
+
+## What This Endpoint Does
+
+The route wraps the runtime's protocol `validate`: parse → load → dry-run-sweep every pipe → build the per-pipe IO contracts → best-effort graph of the entry pipe → assemble the canonical report. The runner returns the verdict as a value — the canonical report on the valid arm, or a structured `ErrorReport` (a bundle the caller can fix) on the invalid arm — and the route maps the invalid verdict to the 200 invalid arm by matching the returned value, never by catching a transport error. A bundle that declares no `main_pipe`, when no manifest names one either, validates normally and simply carries `graph_spec: null` — there is no main-pipe precondition.
+
+## The effective entry pipe
+
+`default_pipe_ref` states which pipe this request's closure would run if the caller named none. It applies the run routes' own precedence, minus the request selector `/validate` does not have:
+
+1. a `method_ref`'s fetched package manifest (`METHODS.toml`) `main_pipe` — the package author's declared entry pipe, qualified against the closure;
+2. otherwise, and when the manifest declares none, the closure's primary blueprint's `main_pipe` (the first file declaring one), qualified by its domain.
+
+It is `null` when no entry pipe is determined — no blueprint declares `main_pipe`, or a manifest names a pipe the closure does not declare, or declares in several domains. In those last two cases a selector-less run by that address would fail to resolve the manifest's pipe too, so the field says nothing rather than naming the closure's pipe, which no such run would execute.
+
+The field exists because the canonical report is **manifest-blind**: `bundle_blueprint` is the batch's primary blueprint, so for a package whose `METHODS.toml` entry differs from — or exists without — a bundle-level `main_pipe`, a consumer deriving the entry pipe from `bundle_blueprint.main_pipe` alone gets the wrong pipe, or none. Reading `default_pipe_ref` is how a client projects an entry signature that matches what [`POST /v1/execute`](pipe-run.md#running-a-method-by-address-method_ref) and `POST /v1/start` actually default to.
+
+The graph follows the same precedence: on a `method_ref` request whose manifest names a `main_pipe`, the route hands that pipe to the runtime as the graph target, so `graph_spec` draws the pipe `default_pipe_ref` names — including for a package whose bundles declare no `main_pipe` at all, whose entry pipe only the manifest states. A manifest `main_pipe` the closure does not resolve leaves both fields `null` rather than graphing the closure's own `main_pipe`, which no run by that address executes. The target travels with the dispatch, so a validation sent to a worker is graphed the same way.
+
+It states the **run** default, which is looser than the `/build/*` routes' rule on one point: a closure whose domains each declare a `main_pipe` cannot be defaulted on `/build/*` (a `422`), but `/execute` and `/start` run its first declaring blueprint happily — so this field names that pipe rather than reporting `null`.
+
+The field rides the valid arm only. The invalid arm assembles no library, so there is no entry pipe to name and the field is absent, like the other structural artifacts.
+
+## Opt-in extras (`render` and `views`)
+
+A caller that wants the artifacts without the verdict — to show a method, prepare its inputs or generate types for it — reads [`POST /v1/pipe-io`](pipe-io.md) instead: it returns `pipe_io_contracts`, `input_form` and `output_form` for one pipe or every pipe, equal to this route's for a closure both accept, with no dry-run sweep.
+
+The verdict body is lean by default: a request that sends neither list gets exactly the structured contract described above, byte-identical to a request that omits both fields. This matters because the highest-frequency callers of `/validate` — editor hooks, CI gates, agent loops — read a handful of fields and discard the rest, and should never pay for bytes they throw away.
+
+Two independent opt-in axes attach more:
+
+- **`render`** produces *rendered text*, attached under a mechanical `rendered_<format>` key. The supported token is `markdown`, which attaches `rendered_markdown` on **both** 200 arms — failure text is exactly what a human-facing surface wants.
+- **`views`** attaches a *structured* artifact under a **same-named** top-level field. The supported tokens are `input_form` and `output_form`, each attaching a field of its own name on the **valid arm only**: the descriptors derive from a library that was never assembled when load/parse/wiring failed, so they follow `bundle_blueprint`, `pipe_io_contracts` and `graph_spec` into absence on the invalid arm.
+
+Both lists share the same mechanics, and both are deliberately typed as plain `list[str]` rather than closed enums at the request boundary:
+
+- Each token is resolved **independently** against the server's supported set. A known token is honored; an unknown or unsupported one is **silently dropped — never a 422**. A stale token from an older client must not fail the call, and one bad token in a list does not poison the good ones.
+- The lists are treated as **sets**: order-insensitive and deduped.
+- They are **independent of each other**. A request may carry both, and each resolves its own tokens against its own supported set. A token is unknown to the other list — sending `render: ["input_form"]` attaches nothing at all.
+- Neither ever appears on a no-verdict response. No verdict, no view.
+
+Neither axis is part of the verdict contract: a machine consumer branches on the structured fields, and an extra is a presentation or a projection layered on top. That is what keeps adding a token, or changing what one renders, a non-breaking change.
+
+## Sourcing submitted files
+
+The submit path carries bundle text, not file paths, so by default the runtime cannot tell the client which file an error belongs to — `source` comes back `null`. Send `mthds_sources` parallel to `mthds_contents` to fix this: each source is the logical identity of that content (e.g. the file's path relative to the submitted directory), and the runtime threads it onto the corresponding `blueprint.source`. The source then rides back on both arms — `bundle_blueprint.source` on the valid arm, and `validation_errors[].source` on the invalid arm — so a multi-file editor client can map a cross-file diagnostic to the file that owns it. Omit `mthds_sources` (or send `null`) and behavior is exactly as before. The list, when present, must be the same length as `mthds_contents`; a mismatch is a request-shape 422 (it is the caller's wiring bug, caught before the validation sweep runs).
+
+## Where validation runs
+
+Validation is **`orchestration_mode`-aware**, the same way `/start` is: the runner resolves the effective backend (the deployment default plus the optional per-request `orchestration_mode` override) and dispatches through the bundle-validator registry. Validation is inherently blocking, so there is no delivery axis here — only the backend varies. On the orchestrator-agnostic base — and for `orchestration_mode: direct` — the whole job runs **in-process in one library load on the API side**. On an orchestrator flavor whose mode is selected (e.g. `temporal`), the whole job is **dispatched to a worker** instead, and the API side assembles the same canonical report from the worker's result without loading a library. Either way the verdict is byte-identical: the backend changes, the contract does not. A per-request override the deployment forbids is refused with a 403.
+
+> **Resource note for deployment.** When validation runs in-process (the agnostic base, or `direct` mode), the API server loads the method library to validate, so a deployment that receives large or frequent in-process `/validate` traffic should be sized for that load (memory + CPU for library assembly and the graph dry-run). On a distributed-execution flavor that dispatches validation to a worker, the library work happens worker-side; size the workers accordingly.
+
+The graph is best-effort: a bundle that validates but whose graph dry-run fails still returns 200 on the valid arm with `graph_spec: null`.
+
+## Who the validation is done for
+
+A validation is not a run, but it still emits telemetry: the sweep's `pipe_dry_run` event and every dry run it performs. The route hands the runtime the caller it is working for — the authenticated user, exactly as a run states it (the single-tenant placeholder when the deployment has no user model), and the request's `analytics_groups`, or none — and the runtime attributes that telemetry to them rather than to the deployment's configured identity. The caller travels with the dispatch, so a validation sent to a worker is attributed the same way. How each telemetry stream then treats the caller is the runtime's decision, described with [`analytics_groups` on a run](pipe-run.md#host-supplied-run-context-storage_scope-and-analytics_groups).
+
+## No-verdict (non-2xx) responses
+
+Only conditions where the endpoint could not produce a verdict are non-2xx, rendered as [RFC 7807 problem documents](error-responses.md):
+
+- **422** — a malformed request body, an `mthds_sources` / `mthds_contents` length mismatch, both/neither of `mthds_contents` / `method_ref`, or a malformed `analytics_groups` (`error_type` `InvalidAnalyticsGroups`) — request-shape errors caught before the runtime.
+- **401 / 403** — unauthenticated / forbidden (including a per-request `orchestration_mode` override the deployment does not allow).
+- **`method_ref` resolution failures** — a selector that could not be resolved produced no verdict, so it is never rendered as `is_valid: false`: a malformed reference or a failed fetch is a **422**, no matching package in the repository a **404**, and the custom-Python policy (the sandbox gate, the structures refusal) a **403** — the same statuses and `error_type`s as on the run routes (see the [error table](pipe-run.md#running-a-method-by-address-method_ref)).
+- **5xx** — a server fault (including a host-wiring programmer error, surfaced as `PipelexUnexpectedError`).
+
+Read it as one rule: a non-2xx on `/validate` always means "the endpoint could not produce a verdict," never "your bundle is bad."
diff --git a/api/docs/storage-transport.md b/api/docs/storage-transport.md
new file mode 100644
index 000000000..69e0d17d8
--- /dev/null
+++ b/api/docs/storage-transport.md
@@ -0,0 +1,21 @@
+# Storage transport (`/upload`, `/resolve-storage-url`) — REMOVED
+
+**Both routes are gone from this server.** They were never part of the published Pipelex API contract — neither the MTHDS Protocol nor the build extensions — and their docstrings said so. The "Future ownership" section this page used to carry predicted the move; it has happened, and the removal decision it left open was taken with it.
+
+## Where they went
+
+To the hosted Pipelex platform, still at `POST /v1/upload` and `POST /v1/resolve-storage-url` on `api.pipelex.com`, with byte-identical request and response shapes. Released SDK versions keep working: `@pipelex/sdk`'s `uploadFile` / `prepareInputs` and `pipelex-sdk`'s `upload_file` / `prepare_inputs` are unchanged, and the `pipelex-storage://` scheme is unchanged.
+
+## Why they could not stay here
+
+Both keyed S3 objects under the caller's own id — `{user_id}/assets/{uuid}.{ext}` — and authorized a read by comparing that first path segment against the requester. That is an ownership model with no notion of a team, and on the hosted side those URIs get saved onto **organization-scoped** rows, so the second member of a team to open a shared method got a `403` on their own team's file.
+
+Fixing it means putting the organization at segment 0, and this server has no organization concept to put there. It is a generic execution engine: a single opaque caller id is its entire trusted identity surface, by design. So the routes belong where membership is already resolved before the request arrives.
+
+## What a self-hoster does now
+
+Nothing in the runtime changed — only the two HTTP routes are gone. The storage *provider* is untouched: `get_storage_provider()`, `pipelex-storage://` URIs, and everything the runtime does with them work exactly as before, and a pipeline still reads and writes assets through the configured backend.
+
+What a self-hosted deployment no longer gets is an HTTP surface for putting bytes in and getting them back out. If you need one, it is yours to build, and its authorization model is yours to choose — which is the honest outcome, since the one removed here only ever fit a single-user deployment.
+
+You can also skip storage entirely for most inputs: pass a public HTTP(S) URL or a base64 data URL directly as a `Document` / `Image` `url`.
diff --git a/api/docs/stylesheets/general.css b/api/docs/stylesheets/general.css
new file mode 100644
index 000000000..7446c0fa8
--- /dev/null
+++ b/api/docs/stylesheets/general.css
@@ -0,0 +1,75 @@
+/* ===== Pipelex Docs – globals.css (final & minimal) ===== */
+
+/* Brand colors */
+:root {
+ --md-accent-fg-color: #45BF9F;
+ --md-primary-fg-color: #45BF9F;
+ --md-primary-fg-color--light: #6CD4B6;
+ --md-primary-fg-color--dark: #2E9A7F;
+}
+
+/* Utilities */
+.equal-width { width: 100%; max-width: 300px; display: inline-block; }
+pre code { white-space: pre-wrap !important; word-wrap: break-word; overflow-wrap: break-word; }
+
+/* --- Sidebar nav --- */
+
+/* Ensure all link and label elements have no shadow */
+.md-nav__link,
+label.md-nav__link {
+ box-shadow: none !important;
+}
+
+/* 1) Baseline: non-active links = light grey (declare ONCE) */
+.md-nav--primary .md-nav__link:not(.md-nav__link--active) {
+ color: rgba(0, 0, 0, 0.6) !important;
+}
+[data-md-color-scheme="slate"] .md-nav--primary .md-nav__link:not(.md-nav__link--active) {
+ color: rgba(255, 255, 255, 0.4) !important;
+}
+
+/* 2) TOP-LEVEL SECTION HEADERS ONLY (dark & bold)
+ Works across Material versions:
+ - first-level <li> that contains a child <nav>
+ - OR first-level <li> that contains the toggle input
+ - OR items explicitly marked as section by Material */
+.md-sidebar__inner nav.md-nav--primary > ul.md-nav__list
+ > li.md-nav__item:has(> nav) > label.md-nav__link,
+.md-sidebar__inner nav.md-nav--primary > ul.md-nav__list
+ > li.md-nav__item:has(> input.md-nav__toggle) > label.md-nav__link,
+.md-nav--primary .md-nav__item.md-nav__item--section > label.md-nav__link {
+ color: #000 !important;
+ font-weight: 700 !important;
+}
+[data-md-color-scheme="slate"] .md-sidebar__inner nav.md-nav--primary > ul.md-nav__list
+ > li.md-nav__item:has(> nav) > label.md-nav__link,
+[data-md-color-scheme="slate"] .md-sidebar__inner nav.md-nav--primary > ul.md-nav__list
+ > li.md-nav__item:has(> input.md-nav__toggle) > label.md-nav__link,
+[data-md-color-scheme="slate"] .md-nav--primary .md-nav__item.md-nav__item--section > label.md-nav__link {
+ color: #fff !important;
+ font-weight: 700 !important;
+}
+/* Constant, small pill padding on ALL items (links + labels) */
+.md-nav--primary .md-nav__link,
+.md-nav--primary label.md-nav__link {
+ padding: 6px 10px; /* tighter than before */
+ margin: 0px 0px;
+ border-radius: 10px; /* softer, not huge */
+ box-sizing: border-box;
+ transition: background-color 120ms ease, color 120ms ease; /* color only, no layout props */
+}
+
+/* Hover: color only (no padding/radius changes) */
+.md-nav--primary a.md-nav__link:not(.md-nav__link--active):hover {
+ background-color: rgba(255, 255, 255, 0.08);
+}
+[data-md-color-scheme="default"] .md-nav--primary a.md-nav__link:not(.md-nav__link--active):hover {
+ background-color: rgba(0, 0, 0, 0.06);
+}
+
+/* Active: color only (no padding/radius changes) */
+.md-nav--primary .md-nav__link--active {
+ color: #45BF9F !important;
+ font-weight: 700 !important;
+ background-color: rgba(69, 191, 159, 0.12) !important;
+}
diff --git a/api/docs/stylesheets/mermaid.css b/api/docs/stylesheets/mermaid.css
new file mode 100644
index 000000000..d9052745b
--- /dev/null
+++ b/api/docs/stylesheets/mermaid.css
@@ -0,0 +1,36 @@
+/* docs/stylesheets/mermaid.css
+ Tweak the colours Material exposes for Mermaid */
+
+.mermaid {
+ --md-mermaid-edge-color: #000000;
+ --md-mermaid-label-bg-color: #ffdbfa;
+ --md-mermaid-label-fg-color: #000000;
+
+ --md-mermaid-node-bg-color: #fff9db;
+ --md-mermaid-node-fg-color: #000000;
+}
+
+/* Give the diagram itself a code-block like backdrop so it stands out
+ on both light and dark themes. */
+.md-typeset .mermaid {
+ padding: 0.3rem;
+ border-radius: 0.3rem;
+ overflow: auto;
+}
+
+/* --- Light color scheme ---------------------------------------------- */
+
+[data-md-color-scheme="default"] .md-typeset .mermaid {
+ background-color: hsla(140, 27%, 98%, 0.983);
+}
+
+/* --- Dark color scheme ------------------------------------------------ */
+
+[data-md-color-scheme="slate"] .md-typeset .mermaid {
+ background-color: hsla(140, 27%, 98%, 0.983);
+}
+
+/* Ensure text inside nodes and labels is black */
+.mermaid text {
+ fill: #000 !important;
+}
\ No newline at end of file
diff --git a/api/mkdocs.yml b/api/mkdocs.yml
new file mode 100644
index 000000000..eed60b07b
--- /dev/null
+++ b/api/mkdocs.yml
@@ -0,0 +1,124 @@
+site_name: Pipelex API Documentation
+
+site_url: https://pipelex.github.io/pipelex-api/
+site_description: "Official API documentation for Pipelex - REST API for executing Pipelex pipelines and validating MTHDS files"
+docs_dir: docs
+repo_url: "https://github.com/Pipelex/pipelex"
+repo_name: "Pipelex on GitHub"
+
+# `CONTRIBUTING.md` lives at the repository root, one level above this member, and is snippet-included into
+# `docs/contributing.md`. Its links (e.g. `docs/configuration.md`) are
+# authored to work from the repo root on GitHub; from mkdocs' perspective
+# the included content sits inside `docs/` and the same relative paths
+# can't resolve. Downgrade these specific link checks from `warn`
+# (which `mkdocs build --strict` treats as fatal) to `info` so we keep
+# the human-friendly GitHub links without the build failing.
+validation:
+ links:
+ not_found: info
+ unrecognized_links: info
+
+theme:
+ name: material
+ favicon: https://pipelex-web.s3.amazonaws.com/logo/pipelex-favicon-32.png
+ logo: https://pipelex-web.s3.amazonaws.com/logo/Pipelex-logo-wot-mono-560x176.png
+ features:
+ - navigation.footer
+ - navigation.tabs
+ - navigation.tabs.sticky
+ - navigation.sections
+ - navigation.top
+ palette:
+ - scheme: default
+ primary: teal
+ accent: deep purple
+ toggle:
+ icon: material/weather-night
+ name: Switch to dark mode
+ - scheme: slate
+ primary: teal
+ accent: purple
+ toggle:
+ icon: material/weather-sunny
+ name: Switch to light mode
+
+copyright: "© 2025-2026 Evotis S.A.S. <br/>Pipelex is a trademark of Evotis S.A.S."
+
+extra:
+ social:
+ - icon: fontawesome/brands/github
+ link: https://github.com/Pipelex/pipelex
+ name: Pipelex on GitHub
+ - icon: fontawesome/brands/python
+ link: https://pypi.org/project/pipelex/
+ name: pipelex on PyPI
+ - icon: fontawesome/brands/twitter
+ link: https://x.com/PipelexAI
+ name: Pipelex on X
+ - icon: fontawesome/brands/discord
+ link: https://go.pipelex.com/discord
+ name: Pipelex on Discord
+ generator: false
+
+plugins:
+ - search
+ - glightbox:
+ touchNavigation: true
+ loop: false
+ effect: zoom
+ slide_effect: slide
+ width: 100%
+ height: auto
+ zoomable: true
+ draggable: true
+ auto_caption: false
+ caption_position: bottom
+
+markdown_extensions:
+ - meta
+ - attr_list
+ - md_in_html
+ - pymdownx.blocks.caption
+ - pymdownx.highlight
+ - pymdownx.superfences:
+ custom_fences:
+ - name: mermaid
+ class: mermaid
+ format: !!python/name:pymdownx.superfences.fence_code_format
+ - pymdownx.emoji:
+ emoji_index: !!python/name:material.extensions.emoji.twemoji
+ emoji_generator: !!python/name:material.extensions.emoji.to_svg
+ # Snippets resolve in this member first (its CHANGELOG.md and LICENSE), then at the repository root,
+ # which holds the CONTRIBUTING.md and CODE_OF_CONDUCT.md that now cover the server too.
+ - pymdownx.snippets:
+ base_path: [".", ".."]
+ check_paths: true
+ - admonition
+ - pymdownx.details
+
+extra_css:
+ - stylesheets/mermaid.css
+ - stylesheets/general.css
+
+nav:
+ - Home: https://docs.pipelex.com/
+ - API:
+ - Overview: index.md
+ - Configuration: configuration.md
+ - Pipe Builder: pipe-builder.md
+ - Pipe Run: pipe-run.md
+ - Pipe Validate: pipe-validate.md
+ - Pipe I/O: pipe-io.md
+ - Resolve & Codegen: codegen.md
+ - MTHDS Tools: mthds-tools.md
+ - Storage Transport: storage-transport.md
+ - Error Responses: error-responses.md
+ - Logging: logging.md
+ - Contribute:
+ - Contributing: contributing.md
+ - Code of Conduct: CODE_OF_CONDUCT.md
+ - License: license.md
+ - Changelog: changelog.md
+ - n8n: https://pipelex.github.io/n8n-nodes-pipelex/
+ - Contribute: https://docs.pipelex.com/pages/contributing/
+ - Changelog: https://docs.pipelex.com/pages/changelog/
diff --git a/api/pipelex_api/__init__.py b/api/pipelex_api/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/api/pipelex_api/api.toml b/api/pipelex_api/api.toml
new file mode 100644
index 000000000..c5d3d5e6a
--- /dev/null
+++ b/api/pipelex_api/api.toml
@@ -0,0 +1,21 @@
+# Pipelex-API deployment config — the packaged default, loaded by `load_api_config()`
+# (pipelex_api/api_config.py) via core's env-aware `load_plugin_config` and validated into `ApiConfig`.
+# Keys live at the file root (no `[api]` wrapper) — `load_plugin_config` validates the whole merged
+# document against the schema, exactly like `pipelex-temporal`'s `temporal.toml`. The packaged
+# default here is deep-merged with an optional `api_{env}.toml` / `api_override.toml` at `~/.pipelex`
+# then the project `.pipelex` (env selected by `PIPELEX_ENV`). This source-available base names NO
+# orchestrator: it ships the in-process `direct` mode and refuses per-request override. A deployment
+# flavor bakes its own `.pipelex/api_{env}.toml` to flip this (e.g. `pipelex-api-hosted` sets
+# `orchestration_mode = "temporal"`).
+
+# Which orchestrator a top-level run dispatches to, through the orchestrator registry.
+# `orchestration_mode` is an OPEN string token: core owns "direct" (in-process); each orchestrator
+# plugin owns its own ("temporal" from pipelex-temporal, "mistral-workflows" from
+# pipelex-mistral-workflows). A token whose plugin is not installed fails loud at dispatch with the
+# plugin's install hint. The delivery axis (blocking vs fire-and-forget) is NOT configured here — it
+# is set by the endpoint (`/execute` and `/validate` block; `/start` is fire-and-forget).
+orchestration_mode = "direct"
+
+# Whether a caller may override `orchestration_mode` per request. Off on the base (and recommended off
+# on hosted flavors): a locked-down distributed runner must not be coercible into `direct`.
+allow_request_orchestration_mode_override = false
diff --git a/api/pipelex_api/api_config.py b/api/pipelex_api/api_config.py
new file mode 100644
index 000000000..7e3a83306
--- /dev/null
+++ b/api/pipelex_api/api_config.py
@@ -0,0 +1,144 @@
+"""Pipelex-API deployment config: the top-level orchestration mode + override policy.
+
+The runner is orchestrator-agnostic. WHICH orchestrator a top-level run dispatches
+to — ``direct`` in-process (the base default), ``temporal``, ``mistral-workflows``,
+… — is a *deployment* choice, never a property of this source-available base.
+``orchestration_mode`` is an open string token (core owns ``"direct"``; each plugin
+owns its own); the *delivery* axis (blocking vs fire-and-forget) is endpoint-set, not
+configured here. It is read from a packaged ``api.toml`` (keys at the file root — no
+``[api]`` wrapper, since :meth:`load_plugin_config` validates the whole document
+against the schema, exactly like ``temporal.toml``), env-layered like the main pipelex
+config and every plugin config (D2): the packaged default ``api.toml`` (shipped in this
+wheel) is deep-merged with the env-selected ``api_{environment}.toml`` and
+``api_override.toml`` from ``~/.pipelex`` then the project ``.pipelex``, with
+``PIPELEX_ENV`` (``runtime_manager.environment``) choosing the env file. One image
+bakes every env file; a deployment flavor (e.g. ``pipelex-api-hosted``) bakes
+``.pipelex/api_{env}.toml`` to flip the default. The base names no orchestrator and
+ships ``orchestration_mode = "direct"``.
+
+Why a separate ``api.toml`` and not the core ``pipelex_{env}.toml``: core's
+config is ``extra="forbid"``, so an ``[api]`` section there is rejected at load.
+Loading it via core's reusable :meth:`load_plugin_config` keeps this a pure
+pipelex-api concern while reusing the identical env-layering machinery — and
+keeps it symmetric with how ``pipelex-temporal`` self-loads ``temporal.toml``.
+"""
+
+from functools import cache
+from pathlib import Path
+
+from pipelex.runtime_bridge.orchestration_mode import DIRECT_ORCHESTRATION_MODE
+from pipelex.system.configuration.config_loader import config_manager
+from pydantic import BaseModel, ConfigDict
+
+from pipelex_api.error_types import ErrorType
+from pipelex_api.errors import raise_forbidden
+
+API_CONFIG_NAME = "api"
+
+# The packaged default ``api.toml`` ships in the wheel alongside this module.
+_PACKAGE_DIR = Path(__file__).resolve().parent
+
+
+class ApiConfig(BaseModel):
+ """The ``[api]`` deployment config: default orchestration mode + override policy.
+
+ No field defaults — the packaged ``api.toml`` is the single source of the
+ base defaults (mirroring core's "defaults live in the TOML, never in the
+ model" discipline). ``extra="forbid"`` so a typo'd key in a baked override
+ fails loud at load instead of being silently ignored.
+
+ ``orchestration_mode`` is an open string token (core owns ``"direct"``; each
+ plugin owns its own). It is NOT validated against a closed enum here — an
+ unregistered token is refused at dispatch by ``MissingOrchestratorError``,
+ the single validation point. The delivery axis (blocking vs fire-and-forget)
+ is endpoint-set, never configured, so nothing about wait-semantics lives here.
+ """
+
+ model_config = ConfigDict(extra="forbid")
+
+ orchestration_mode: str
+ allow_request_orchestration_mode_override: bool
+
+
+def load_api_config() -> ApiConfig:
+ """Load the ``[api]`` config from ``api.toml`` with env-aware layering (D2).
+
+ Delegates to core's reusable plugin-config loader: the packaged ``api.toml``
+ is deep-merged with the env-selected overrides. The packaged default alone is
+ a valid, fully-resolved config — every override tier is optional. Requires
+ Pipelex to be booted (``runtime_manager.environment`` must be resolved), so
+ it is called only after ``Pipelex.make`` — never at import.
+ """
+ return config_manager.load_plugin_config(name=API_CONFIG_NAME, package_dir=_PACKAGE_DIR, schema=ApiConfig)
+
+
+@cache
+def get_api_config() -> ApiConfig:
+ """Process-cached :class:`ApiConfig`.
+
+ The config is immutable for the life of the process (``PIPELEX_ENV`` is fixed
+ at boot), so it is loaded once and cached. ``pipelex_api.main`` warms this at startup
+ so a malformed ``api.toml`` / baked override fails the app fast — the same
+ fail-fast posture as ``ERROR_DISCLOSURE``. Tests that need a different mode
+ patch this getter (or call :func:`resolve_orchestration_mode` with a hand-built
+ config) rather than mutating the cache.
+ """
+ return load_api_config()
+
+
+def resolve_orchestration_mode(requested: str | None, *, config: ApiConfig) -> str:
+ """Resolve the effective orchestration mode for a top-level run, applying policy.
+
+ The deployment default (``config.orchestration_mode``) wins unless the caller
+ supplied a *different* token AND the deployment opted into per-request
+ override (``allow_request_orchestration_mode_override``). A caller-supplied
+ token equal to the default is always honored (it changes nothing). A caller
+ trying to FORCE a different mode on a runner whose policy forbids it is refused
+ with a 403 — so a locked-down Temporal runner can never be coerced into
+ ``direct`` (whose whole point would be to bypass distributed execution), and
+ vice versa. The token is a plain string compare; an *unregistered* token is
+ not rejected here — that surfaces at dispatch as ``MissingOrchestratorError``.
+ """
+ if requested is None or requested == config.orchestration_mode:
+ return config.orchestration_mode
+ if config.allow_request_orchestration_mode_override:
+ return requested
+ msg = (
+ f"This deployment does not allow overriding orchestration_mode per request "
+ f"(configured mode '{config.orchestration_mode}', requested '{requested}')."
+ )
+ raise_forbidden(msg, error_type=ErrorType.ORCHESTRATION_MODE_OVERRIDE_FORBIDDEN)
+
+
+class ApiBootConfigError(ValueError):
+ """Raised at startup when the deployment's orchestration config cannot boot coherently."""
+
+
+def resolve_boot_orchestrator(config: ApiConfig) -> str | None:
+ """The orchestrator plugin this process boots under, derived from the deployment config.
+
+ The base ``direct`` mode names no orchestrator and boots in-process (``None``); any other
+ mode (a plugin token like ``"temporal"``) boots the process under that orchestrator so its
+ execution-hub slots are claimed and async dispatch is enabled.
+
+ A process boots under exactly one orchestrator, so a ``direct`` default that ALSO enables
+ per-request override is incoherent: no async hub is claimed at boot, yet
+ :func:`resolve_orchestration_mode` would honor a request overriding to a non-direct mode and
+ resolve that orchestrator's dispatch arm — which then fails at dispatch with
+ ``AsyncExecutionNotEnabledError``. Refuse it here: fail loud at boot, where the operator sees
+ it, rather than on the first overriding request. The mirror case (a non-direct default with
+ override on) IS coherent — the async hub is claimed at boot, and a per-request ``direct``
+ override still runs in-process — so it boots normally under that orchestrator.
+ """
+ mode = config.orchestration_mode
+ if config.allow_request_orchestration_mode_override and mode == DIRECT_ORCHESTRATION_MODE:
+ msg = (
+ "allow_request_orchestration_mode_override=true with a 'direct' orchestration_mode default "
+ "cannot service a non-direct per-request override: no async execution hub is claimed at boot, "
+ "so such a request would fail at dispatch. Set a non-direct orchestration_mode default or "
+ "disable per-request override."
+ )
+ raise ApiBootConfigError(msg)
+ if mode == DIRECT_ORCHESTRATION_MODE:
+ return None
+ return mode
diff --git a/api/pipelex_api/bundle.py b/api/pipelex_api/bundle.py
new file mode 100644
index 000000000..1333ea153
--- /dev/null
+++ b/api/pipelex_api/bundle.py
@@ -0,0 +1,243 @@
+"""Materialize a caller-supplied method bundle into a temporary library directory.
+
+A run request may carry the whole method — the `.mthds` bundle plus its PipeFunc
+Python (`pipe_func.py`) and a `requirements.txt` — instead of only
+the inline `mthds_contents` text. Two transport forms are accepted, exactly one
+per request:
+
+ - `bundle_b64`: a base64-encoded zip archive of the bundle directory.
+ - `files`: a `{relative_path: text_content}` map (the zip's contents, unzipped).
+
+The two are equivalent: `files` ≡ the zip's entries. This module decodes either
+form, enforces the ingest guards (both transport forms are refused together; a
+hard file-count and total-size ceiling; per-entry path-safety against absolute
+paths and `..` traversal; a zip-bomb guard that bounds actual decompression),
+writes the surviving files into a fresh temp directory, and hands that directory
+back so the runner can load it via `library_dirs`. In a sandbox-hosted
+deployment the load path reads every `.py` as source text, never importing it:
+it refuses a bundle whose Python declares a structure class
+(`MethodStructuresRefusedError`, a 403) and captures the rest onto the crate for
+the sandbox. The caller is responsible for the hosted-mode gate.
+
+Nothing here imports or executes the bundle's Python — it only writes bytes to
+disk. The caller cleans the directory up via the `materialized_bundle` context
+manager's guaranteed teardown.
+"""
+
+from __future__ import annotations
+
+import base64
+import binascii
+import shutil
+import tempfile
+import zipfile
+from contextlib import contextmanager
+from io import BytesIO
+from pathlib import Path, PurePosixPath
+from typing import TYPE_CHECKING, NamedTuple
+
+from pipelex import log
+from pydantic import ConfigDict
+from pydantic.dataclasses import dataclass
+
+from pipelex_api.error_types import ErrorType
+from pipelex_api.errors import raise_bad_request, raise_payload_too_large, raise_validation_error
+from pipelex_api.limits import MAX_BUNDLE_FILES, MAX_BUNDLE_TOTAL_BYTES
+
+if TYPE_CHECKING:
+ from collections.abc import Generator
+
+
+@dataclass(frozen=True, config=ConfigDict(arbitrary_types_allowed=True))
+class MaterializedBundle:
+ """A bundle written to disk: the directory to load and the relpaths written."""
+
+ directory: Path
+ relpaths: tuple[str, ...]
+
+ @property
+ def has_python_sources(self) -> bool:
+ """True when the bundle ships any `.py` — the trigger for the hosted-mode gate."""
+ return any(relpath.endswith(".py") for relpath in self.relpaths)
+
+
+def _safe_relpath(name: str) -> PurePosixPath:
+ """Validate one bundle entry name and return it as a normalized relative POSIX path.
+
+ Rejects anything that could escape the destination directory: absolute paths,
+ Windows drive/backslash forms (a bare drive prefix like `C:foo` has no slash or
+ backslash yet is drive-relative on Windows, so `:` is rejected outright), and any
+ `..` component. Directory-only entries (trailing slash) return an empty path and
+ are filtered by the caller.
+ """
+ if not name or name in {".", "./"}:
+ return PurePosixPath()
+ if "\\" in name:
+ msg = f"Bundle entry {name!r} uses backslashes; use forward-slash relative paths only"
+ raise_validation_error(message=msg, error_type=ErrorType.INVALID_BUNDLE)
+ if ":" in name:
+ msg = f"Bundle entry {name!r} contains ':' (a Windows drive/stream form); use plain relative paths only"
+ raise_validation_error(message=msg, error_type=ErrorType.INVALID_BUNDLE)
+ pure = PurePosixPath(name)
+ if pure.is_absolute():
+ msg = f"Bundle entry {name!r} is an absolute path; only relative paths are allowed"
+ raise_validation_error(message=msg, error_type=ErrorType.INVALID_BUNDLE)
+ if any(part == ".." for part in pure.parts):
+ msg = f"Bundle entry {name!r} escapes the bundle root via '..'; not allowed"
+ raise_validation_error(message=msg, error_type=ErrorType.INVALID_BUNDLE)
+ return pure
+
+
+def _guard_count(count: int) -> None:
+ if count == 0:
+ raise_validation_error(message="Bundle is empty (no files)", error_type=ErrorType.INVALID_BUNDLE)
+ if count > MAX_BUNDLE_FILES:
+ raise_payload_too_large(message=f"Bundle exceeds the {MAX_BUNDLE_FILES}-file limit (got {count})")
+
+
+def _guard_running_total(total_bytes: int) -> None:
+ if total_bytes > MAX_BUNDLE_TOTAL_BYTES:
+ raise_payload_too_large(message=f"Bundle exceeds the {MAX_BUNDLE_TOTAL_BYTES // 1024} KiB decompressed-size limit")
+
+
+# Base64 inflates by 4/3; a zip is compressed, so a bundle whose DECOMPRESSED content is within
+# the ceiling encodes to well under this. Bounding the base64 string BEFORE decoding stops a
+# ~100 MiB request-body (the only other bound) from being expanded into ~75 MiB of heap just to
+# be rejected later by the decompressed-size guard. Slack (+4) covers padding.
+_MAX_BUNDLE_B64_CHARS = MAX_BUNDLE_TOTAL_BYTES * 4 // 3 + 4
+
+
+def _entries_from_zip(bundle_b64: str) -> list[tuple[PurePosixPath, bytes]]:
+ """Decode a base64 zip and return its (safe relpath, bytes) file entries.
+
+ Zip-bomb guard: each member is read through a bounded stream so a lying
+ uncompressed-size header cannot force unbounded decompression — the running
+ total is checked against `MAX_BUNDLE_TOTAL_BYTES` as bytes are pulled. A cheap
+ length check on the still-encoded string runs FIRST, so an oversized payload is
+ refused before it is buffered into memory as decoded bytes.
+ """
+ if len(bundle_b64) > _MAX_BUNDLE_B64_CHARS:
+ raise_payload_too_large(message=f"bundle_b64 exceeds the {MAX_BUNDLE_TOTAL_BYTES // 1024} KiB compressed-size limit")
+ try:
+ raw = base64.b64decode(bundle_b64, validate=True)
+ except (binascii.Error, ValueError) as decode_error:
+ log.warning(f"bundle: invalid base64 ({decode_error})")
+ raise_bad_request(message="bundle_b64 is not valid base64", error_type=ErrorType.INVALID_BASE64)
+
+ try:
+ archive = zipfile.ZipFile(BytesIO(raw))
+ except zipfile.BadZipFile as zip_error:
+ log.warning(f"bundle: corrupt zip ({zip_error})")
+ raise_validation_error(message="bundle_b64 is not a valid zip archive", error_type=ErrorType.INVALID_BUNDLE)
+
+ entries: list[tuple[PurePosixPath, bytes]] = []
+ total_bytes = 0
+ with archive:
+ members = [info for info in archive.infolist() if not info.is_dir()]
+ _guard_count(len(members))
+ budget = MAX_BUNDLE_TOTAL_BYTES
+ for info in members:
+ relpath = _safe_relpath(info.filename)
+ if not relpath.parts:
+ continue
+ # Bounded read: pull at most (remaining budget + 1) bytes so a zip bomb whose header
+ # under-reports its size still cannot decompress past the ceiling.
+ with archive.open(info) as member:
+ data = member.read(budget + 1)
+ total_bytes += len(data)
+ _guard_running_total(total_bytes)
+ budget = MAX_BUNDLE_TOTAL_BYTES - total_bytes
+ entries.append((relpath, data))
+ return entries
+
+
+def _entries_from_files(files: dict[str, str]) -> list[tuple[PurePosixPath, bytes]]:
+ """Validate a {relpath: text} map and return its (safe relpath, bytes) entries."""
+ _guard_count(len(files))
+ entries: list[tuple[PurePosixPath, bytes]] = []
+ total_bytes = 0
+ for name, content in files.items():
+ relpath = _safe_relpath(name)
+ if not relpath.parts:
+ msg = f"Bundle entry {name!r} has no filename"
+ raise_validation_error(message=msg, error_type=ErrorType.INVALID_BUNDLE)
+ data = content.encode("utf-8")
+ total_bytes += len(data)
+ _guard_running_total(total_bytes)
+ entries.append((relpath, data))
+ return entries
+
+
+class ParsedBundle(NamedTuple):
+ """A decoded-and-validated bundle held in memory, NOT yet written to disk.
+
+ Splitting parse from materialize lets the caller apply the sandbox-hosted gate
+ (which keys on `has_python_sources`) BEFORE any disk write — so a bundle destined
+ for a 403 never touches the filesystem. Entries are `(safe relpath, bytes)`.
+ """
+
+ entries: tuple[tuple[PurePosixPath, bytes], ...]
+
+ @property
+ def has_python_sources(self) -> bool:
+ """True when the bundle ships any `.py` — the trigger for the hosted-mode gate."""
+ return any(str(relpath).endswith(".py") for relpath, _ in self.entries)
+
+
+def parse_bundle(*, bundle_b64: str | None, files: dict[str, str] | None) -> ParsedBundle:
+ """Decode + guard a bundle into an in-memory `ParsedBundle` (no disk writes).
+
+ Exactly one of `bundle_b64` / `files` must be supplied; supplying both is a
+ caller mistake (they are the same content in two forms) and is refused. All
+ ingest guards (base64, size, count, path-safety, zip-bomb) run here, so the
+ caller can inspect `has_python_sources` and reject BEFORE materializing to disk.
+ """
+ if bundle_b64 is not None and files is not None:
+ msg = "Provide either bundle_b64 or files, not both"
+ raise_validation_error(message=msg, error_type=ErrorType.INVALID_BUNDLE)
+ if bundle_b64 is not None:
+ entries = _entries_from_zip(bundle_b64)
+ elif files is not None:
+ entries = _entries_from_files(files)
+ else:
+ msg = "No bundle supplied (bundle_b64 and files are both absent)"
+ raise_validation_error(message=msg, error_type=ErrorType.INVALID_BUNDLE)
+ return ParsedBundle(entries=tuple(entries))
+
+
+@contextmanager
+def materialize_parsed(parsed: ParsedBundle) -> Generator[MaterializedBundle, None, None]:
+ """Write an already-parsed bundle into a fresh temp directory, cleaned up on exit.
+
+ The yielded `MaterializedBundle.directory` is safe to pass as a `library_dirs`
+ entry; it is removed when the context exits, on both the happy and error path.
+ """
+ directory = Path(tempfile.mkdtemp(prefix="pipelex-bundle-"))
+ try:
+ root = directory.resolve()
+ relpaths: list[str] = []
+ for relpath, data in parsed.entries:
+ target = (directory / relpath).resolve()
+ # Defense-in-depth: even after per-part validation, confirm the resolved target stays
+ # under the temp root before writing (guards against symlink/edge normalization surprises).
+ if root != target and root not in target.parents:
+ msg = f"Bundle entry {str(relpath)!r} resolves outside the bundle root"
+ raise_validation_error(message=msg, error_type=ErrorType.INVALID_BUNDLE)
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_bytes(data)
+ relpaths.append(relpath.as_posix())
+ yield MaterializedBundle(directory=directory, relpaths=tuple(relpaths))
+ finally:
+ shutil.rmtree(directory, ignore_errors=True)
+
+
+@contextmanager
+def materialized_bundle(*, bundle_b64: str | None, files: dict[str, str] | None) -> Generator[MaterializedBundle, None, None]:
+ """Parse AND materialize a bundle in one step (convenience for callers that don't gate).
+
+ Equivalent to `parse_bundle(...)` followed by `materialize_parsed(...)`; a caller
+ that must apply the sandbox-hosted gate before disk writes should use the two
+ steps directly instead.
+ """
+ with materialize_parsed(parse_bundle(bundle_b64=bundle_b64, files=files)) as bundle:
+ yield bundle
diff --git a/api/pipelex_api/disclosure.py b/api/pipelex_api/disclosure.py
new file mode 100644
index 000000000..26fdc3ffc
--- /dev/null
+++ b/api/pipelex_api/disclosure.py
@@ -0,0 +1,43 @@
+"""Resolution of the `ERROR_DISCLOSURE` environment variable.
+
+`ERROR_DISCLOSURE` selects how much of an error report reaches the client:
+
+- `verbose` (default) — the full report, including the human-readable message.
+ The intended default for a self-hosted server, where the operator and the
+ debugging developer are usually the same person.
+- `strict` — the lossy projection pipelex's `DisclosureMode.STRICT` produces,
+ for hosted multi-tenant deployments.
+
+The value is resolved once, at app startup (`pipelex_api.main`). An unrecognized value
+fails the app at boot rather than silently degrading — a misconfigured
+disclosure mode is a security-relevant mistake the operator must see.
+"""
+
+from pipelex.base_exceptions import DisclosureMode
+from pipelex.system.environment import get_optional_env
+
+ERROR_DISCLOSURE_ENV_VAR = "ERROR_DISCLOSURE"
+
+
+class InvalidErrorDisclosureError(ValueError):
+ """Raised at startup when `ERROR_DISCLOSURE` holds an unrecognized value."""
+
+
+def resolve_disclosure_mode() -> DisclosureMode:
+ """Resolve `ERROR_DISCLOSURE` to a `DisclosureMode`.
+
+ Returns `DisclosureMode.VERBOSE` when the variable is unset, empty, or
+ whitespace-only. Raises `InvalidErrorDisclosureError` for any value other
+ than `verbose` or `strict` (matched case-insensitively, surrounding
+ whitespace ignored).
+ """
+ raw = get_optional_env(ERROR_DISCLOSURE_ENV_VAR)
+ normalized = (raw or "").strip().lower()
+ if not normalized:
+ return DisclosureMode.VERBOSE
+ try:
+ return DisclosureMode(normalized)
+ except ValueError as exc:
+ valid = ", ".join(f"'{mode}'" for mode in DisclosureMode)
+ msg = f"{ERROR_DISCLOSURE_ENV_VAR}={raw!r} is not a valid disclosure mode. Valid values: {valid}."
+ raise InvalidErrorDisclosureError(msg) from exc
diff --git a/api/pipelex_api/error_types.py b/api/pipelex_api/error_types.py
new file mode 100644
index 000000000..89afda8e4
--- /dev/null
+++ b/api/pipelex_api/error_types.py
@@ -0,0 +1,80 @@
+"""Centralized `error_type` symbols for API-authored error responses.
+
+Every fixed (non-dynamic) `error_type` an API-authored error emits lives here
+so call sites reference symbols, not literals — easier to grep, rename, and
+document. The `pipelex_api.errors` helpers stamp one of these onto the RFC 7807
+problem document as the `error_type` extension member.
+
+Pipelex domain errors carry their own open-ended `error_type` (the exception
+class name, from the `ErrorReport`) and are NOT enumerated here — they are
+deliberately not a fixed set.
+"""
+
+from enum import StrEnum
+
+
+class ErrorType(StrEnum):
+ # Authentication / authorization
+ UNAUTHENTICATED = "Unauthenticated"
+ FORBIDDEN = "Forbidden"
+ # A caller asked to run in an orchestration_mode this deployment forbids overriding
+ # (per-request override is off — see `allow_request_orchestration_mode_override` in api.toml).
+ # A 403: the deployment policy refuses to honor the requested mode.
+ ORCHESTRATION_MODE_OVERRIDE_FORBIDDEN = "OrchestrationModeOverrideForbidden"
+ INVALID_TOKEN = "InvalidToken"
+ TOKEN_EXPIRED = "TokenExpired"
+ SERVER_MISCONFIGURED = "ServerMisconfigured"
+
+ # A caller hit `/start` on a deployment whose resolved orchestration mode cannot do genuine
+ # async (its orchestrator's `supports_fire_and_forget` is False — e.g. the in-process `direct`
+ # base). `/start` is fire-and-forget by nature, so rather than silently running blocking and
+ # acking, it refuses HONESTLY with a 400: use `/execute` (synchronous) instead. Checked AFTER
+ # the override policy, so a forbidden per-request override still 403s first.
+ START_REQUIRES_ASYNC_ORCHESTRATION = "StartRequiresAsyncOrchestration"
+
+ # Request validation
+ BAD_REQUEST = "BadRequest"
+ VALIDATION_ERROR = "ValidationError"
+ INVALID_JSON = "InvalidJSON"
+ # A run request's body carries, at any depth, an object key a kajson decoder reads as a class
+ # marker: `__class__`, `__module__`, or anything starting with `__kajson`. A 422, not data: the
+ # run body is plain JSON, and such a key would make a later kajson round trip of the inputs
+ # import and instantiate whatever class the caller named.
+ RESERVED_OBJECT_KEY = "ReservedObjectKey"
+ INVALID_CALLBACK_URLS = "InvalidCallbackUrls"
+ # A run request's `storage_scope` extra is not one to three path-safe segments. A 422, not a
+ # 500 from deep in the run: the value becomes a storage key prefix, so a `..` escapes the tenant.
+ INVALID_STORAGE_SCOPE = "InvalidStorageScope"
+ # A run request's `read_scope` extra is not one to three path-safe segments, or the run's storage
+ # scope does not lie under it, so the run could not read back what it writes.
+ INVALID_READ_SCOPE = "InvalidReadScope"
+ # A run request's `analytics_groups` extra is not a mapping of group type to group key within
+ # the runtime's charset and entry cap (`pipelex.system.run_extras`).
+ INVALID_ANALYTICS_GROUPS = "InvalidAnalyticsGroups"
+ INVALID_MODEL_CATEGORY = "InvalidModelCategory"
+ INVALID_BASE64 = "InvalidBase64"
+ PAYLOAD_TOO_LARGE = "PayloadTooLarge"
+ # A run request carried a malformed method bundle (`bundle_b64` / `files`): a corrupt zip, an
+ # unsafe entry name (absolute path or `..` traversal), or both transport forms supplied at once.
+ INVALID_BUNDLE = "InvalidBundle"
+ # A method carrying custom Python (`.py` in a bundle, or in a fetched `method_ref` package)
+ # reached a deployment that is NOT sandbox-hosted. Running customer code in-process is
+ # refused (403): custom code is a sandbox-hosted capability only. Use a sandbox-hosted
+ # deployment. (On a sandbox-hosted deployment, a bundle or a fetched package declaring Python
+ # STRUCTURE classes is still refused — that is pipelex's `MethodStructuresRefusedError`, not this.)
+ CUSTOM_CODE_REQUIRES_SANDBOX = "CustomCodeRequiresSandbox"
+
+ # A caller selected a closure by a REGISTRY-FORM `method_ref` (not a `github.com/...`
+ # address) on a tooling route. Address-form refs resolve server-side (fetch at tag, package
+ # located by manifest identity); the registry form is the packaging program's closing phase,
+ # so it keeps an honest 501 until a method registry exists — never a silent empty verdict.
+ METHOD_REF_NOT_SUPPORTED = "MethodRefNotSupported"
+
+ # Misc
+ PACKAGE_NOT_FOUND = "PackageNotFound"
+ # The `error_type` for the catch-all 500 emitted by `handle_unexpected_error`
+ # (any failure matched by no more-specific handler — not an `ApiError`, a
+ # `RequestValidationError`, a `PipelexError`, or an orchestrator plugin's mapped
+ # transport exception). Stays in this enum so the same `build_problem_document_from_api_error`
+ # builder renders it — same shape as every other API-authored 500.
+ INTERNAL_SERVER_ERROR = "InternalServerError"
diff --git a/api/pipelex_api/error_uri.py b/api/pipelex_api/error_uri.py
new file mode 100644
index 000000000..99593e234
--- /dev/null
+++ b/api/pipelex_api/error_uri.py
@@ -0,0 +1,45 @@
+"""RFC 7807 `type` URI and `title` for API-authored errors.
+
+A pipelex `ErrorReport` always carries its own `type_uri` and `title` (set
+upstream by `PipelexError.type_uri()` / `PipelexError.title()`, both required
+fields), so the global exception handler never needs these helpers for a
+`PipelexError`.
+
+They exist for the *other* error source: the API's own 4xx responses
+(`raise_validation_error` and friends in `pipelex_api.errors`), authored from the
+static `pipelex_api.error_types.ErrorType` enum with no `ErrorReport` behind them.
+`build_problem_document_from_api_error` uses these to give an API-authored
+error the same RFC 7807 `type` / `title` shape as a pipelex one. They also
+serve as a defensive backstop should a future pipelex ever hand back a report
+with an absent identity pair.
+
+The URI namespace and the kebab / humanize transforms are deliberately the
+same ones pipelex uses (`URLs.error_docs_base`, `pascal_case_to_kebab`,
+`pascal_case_to_sentence`), so an API-authored error and a pipelex error are
+indistinguishable in shape on the wire. Both functions are pure.
+"""
+
+from pipelex.tools.misc.string_utils import pascal_case_to_kebab, pascal_case_to_sentence
+from pipelex.urls import URLs
+
+
+def error_type_uri(error_type: str) -> str:
+ """Return the RFC 7807 `type` URI for an error type name.
+
+ `EnvVarNotFoundError` -> `https://docs.pipelex.com/latest/errors/env-var-not-found-error/`.
+ The trailing slash matches the canonical docs URL form, exactly as
+ `PipelexError.type_uri()` produces it upstream.
+ """
+ return f"{URLs.error_docs_base}/{pascal_case_to_kebab(error_type)}/"
+
+
+def error_type_title(error_type: str) -> str:
+ """Return a human-readable RFC 7807 `title` for an error type name.
+
+ `ValidationError` -> `Validation error`; `BadRequest` -> `Bad request`.
+ Sentence case via the same `pascal_case_to_sentence` transform pipelex uses
+ in `PipelexError.title()`. Unlike `PipelexError.title()` it does NOT strip a
+ trailing `Error`: an API `ErrorType` such as `ValidationError` must keep the
+ suffix — `"Validation"` alone would be a worse label than `"Validation error"`.
+ """
+ return pascal_case_to_sentence(error_type)
diff --git a/api/pipelex_api/errors.py b/api/pipelex_api/errors.py
new file mode 100644
index 000000000..e50238bdc
--- /dev/null
+++ b/api/pipelex_api/errors.py
@@ -0,0 +1,130 @@
+"""API-authored error helpers — RFC 7807 problem responses for the 4xx/5xx the API owns.
+
+These cover failures the API detects at its own boundary — request validation,
+auth, payload-size limits, server misconfiguration — as opposed to pipelex
+domain errors, which carry an `ErrorReport` and are translated by the global
+`PipelexError` handler in `pipelex_api.exception_handlers`.
+
+Each helper builds an RFC 7807 problem document (`build_problem_document_from_api_error`)
+and raises `ApiError`. The `handle_api_error` handler registered in
+`pipelex_api.exception_handlers` renders it as `application/problem+json`. Routes do
+NOT catch pipelex exceptions themselves — anything that is not an
+API-authored `ApiError` propagates to the global handlers. There are no
+catch tuples here anymore: the global `PipelexError` / `Exception` handlers
+are the single translation point for everything the API does not author
+itself.
+"""
+
+from typing import Any, NoReturn
+
+from pipelex.base_exceptions import ErrorDomain
+
+from pipelex_api.error_types import ErrorType
+from pipelex_api.problem_document import build_problem_document_from_api_error
+
+
+class ApiError(Exception):
+ """An API-authored error carrying a ready-rendered RFC 7807 problem document.
+
+ Raised by the `raise_*` helpers below; rendered by `handle_api_error` in
+ `pipelex_api.exception_handlers` as `application/problem+json`. Distinct from a pipelex
+ `PipelexError`: there is no `ErrorReport` behind it — the failure is the
+ API's own request validation, auth, or configuration check. The problem
+ document is built at raise time, less the request context: `instance` and
+ `request_id` are stamped by the handler, which is the frame that holds the
+ `Request`.
+ """
+
+ def __init__(self, *, status_code: int, document: dict[str, Any], headers: dict[str, str] | None = None) -> None:
+ self.status_code = status_code
+ self.document = document
+ self.headers: dict[str, str] = headers or {}
+ super().__init__(str(document.get("detail", "")))
+
+
+def _raise_api_error(
+ *,
+ error_type: ErrorType,
+ message: str,
+ status: int,
+ error_domain: ErrorDomain,
+ headers: dict[str, str] | None = None,
+) -> NoReturn:
+ """Build the RFC 7807 document and raise `ApiError`.
+
+ The document is built without the request context: `instance` and
+ `request_id` are stamped by `handle_api_error`, from the `Request` it is
+ handed. That keeps these helpers parameter-clean — a call site deep inside
+ a route still needs no `Request` — while leaving the API with no ambient
+ request state of its own, and it is how the three error paths end up
+ reading the route and the id from exactly one place.
+ """
+ document = build_problem_document_from_api_error(
+ error_type,
+ message,
+ status,
+ instance=None,
+ request_id=None,
+ error_domain=error_domain,
+ )
+ raise ApiError(status_code=status, document=document, headers=headers)
+
+
+def raise_validation_error(message: str, error_type: ErrorType = ErrorType.VALIDATION_ERROR) -> NoReturn:
+ """Raise a 422 RFC 7807 problem response for invalid caller input."""
+ _raise_api_error(error_type=error_type, message=message, status=422, error_domain=ErrorDomain.INPUT)
+
+
+def raise_bad_request(message: str, error_type: ErrorType = ErrorType.BAD_REQUEST) -> NoReturn:
+ """Raise a 400 RFC 7807 problem response for a malformed request."""
+ _raise_api_error(error_type=error_type, message=message, status=400, error_domain=ErrorDomain.INPUT)
+
+
+def raise_payload_too_large(message: str) -> NoReturn:
+ """Raise a 413 RFC 7807 problem response for an over-limit payload."""
+ _raise_api_error(error_type=ErrorType.PAYLOAD_TOO_LARGE, message=message, status=413, error_domain=ErrorDomain.INPUT)
+
+
+def raise_forbidden(message: str, error_type: ErrorType = ErrorType.FORBIDDEN) -> NoReturn:
+ """Raise a 403 RFC 7807 problem response for an authorization failure."""
+ _raise_api_error(error_type=error_type, message=message, status=403, error_domain=ErrorDomain.INPUT)
+
+
+def raise_unauthenticated(message: str, error_type: ErrorType = ErrorType.UNAUTHENTICATED) -> NoReturn:
+ """Raise a 401 RFC 7807 problem response, with the `WWW-Authenticate: Bearer` challenge.
+
+ RFC 7807 fully supports the challenge header: moving the body to
+ `application/problem+json` does not break an OAuth/JWT client that parses
+ `WWW-Authenticate`.
+ """
+ _raise_api_error(
+ error_type=error_type,
+ message=message,
+ status=401,
+ error_domain=ErrorDomain.INPUT,
+ headers={"WWW-Authenticate": "Bearer"},
+ )
+
+
+def raise_not_implemented(message: str, error_type: ErrorType) -> NoReturn:
+ """Raise a 501 RFC 7807 problem response for a spec'd capability this server does not implement yet.
+
+ For request shapes the published contract accepts but this deployment cannot serve (e.g. a
+ `method_ref` closure selector before the method registry exists). A no-verdict condition —
+ distinct from a 422 (the request is well-formed per the contract) and from a 200 invalid
+ verdict (nothing was diagnosed). Classified `CONFIG` domain: neither the request nor the
+ content is at fault.
+ """
+ _raise_api_error(error_type=error_type, message=message, status=501, error_domain=ErrorDomain.CONFIG)
+
+
+def raise_internal_server_error(message: str, error_type: ErrorType) -> NoReturn:
+ """Raise a 500 RFC 7807 problem response for an API-owned server fault.
+
+ For the API's own configuration / invariant failures — a missing secret, a
+ storage backend that cannot presign, absent package metadata. NOT for
+ pipelex domain errors, which carry an `ErrorReport` and are handled by the
+ global `PipelexError` handler. Classified `CONFIG` domain: an operator, not
+ the caller, fixes it.
+ """
+ _raise_api_error(error_type=error_type, message=message, status=500, error_domain=ErrorDomain.CONFIG)
diff --git a/api/pipelex_api/exception_handlers.py b/api/pipelex_api/exception_handlers.py
new file mode 100644
index 000000000..c3b93e10f
--- /dev/null
+++ b/api/pipelex_api/exception_handlers.py
@@ -0,0 +1,669 @@
+"""Global FastAPI exception handlers that translate any failure into RFC 7807.
+
+The single place the API renders a failure into an HTTP response. Every
+handler produces the same `application/problem+json` shape: an `ApiError`
+(raised by the `pipelex_api.errors` 4xx/5xx helpers) carries a pre-built problem
+document; a FastAPI `RequestValidationError` from automatic request
+validation is rendered into one; every `PipelexError` is turned into a
+problem document built from its `ErrorReport`; each orchestrator plugin's
+transport-fault mapper (contributed through the plugin SPI's
+`add_http_error_mapper`, discovered at app construction) gets its own handler
+rendering the `ErrorReport` it produces; everything else collapses to a
+catch-all 500 that discloses under VERBOSE and is sanitized under STRICT, like
+every other response here. The base names no orchestrator and imports no orchestrator SDK
+— the Temporal transport classification that used to live here is now owned by
+the `pipelex-temporal` plugin and reaches us only as a mapper. Routes
+therefore no longer need to catch and shape errors themselves.
+
+This module is deliberately import-side-effect-free — no env var reads, no
+app construction. `pipelex_api/main.py` calls `register_exception_handlers(app,
+disclosure_mode=...)` at startup with the already-resolved disclosure mode
+(its own fail-fast read is what keeps production strict on a bad
+`ERROR_DISCLOSURE` value). Keeping the handlers in their own module lets
+tests import `register_exception_handlers` without dragging in the
+production app's startup chain (`Pipelex.make`, `get_auth_dependency`,
+router wiring), so a misconfigured env var can't crash test collection of
+every module that imports a handler at once.
+"""
+
+import math
+from collections.abc import Awaitable, Callable, Mapping
+from typing import TYPE_CHECKING, Any, cast
+
+from fastapi import FastAPI, Request, Response
+from fastapi.exceptions import RequestValidationError
+from fastapi.responses import JSONResponse
+from pipelex import log
+from pipelex.base_exceptions import DisclosureMode, ErrorDomain, ErrorReport, PipelexError
+from pipelex.plugins.registrar import HttpErrorMapperFn
+
+from pipelex_api.error_types import ErrorType
+from pipelex_api.errors import ApiError
+from pipelex_api.middleware import request_id_of
+from pipelex_api.problem_document import (
+ PROBLEM_JSON_MEDIA_TYPE,
+ build_problem_document,
+ build_problem_document_from_api_error,
+ with_request_context,
+)
+
+if TYPE_CHECKING:
+ from pipelex_api.security import RequestUser
+
+# A Starlette/FastAPI async exception handler: `(request, exc) -> response`.
+_ExceptionHandler = Callable[[Request, Exception], Awaitable[Response]]
+
+# The value of the `event` field every error record carries: the one key a log sink filters this
+# server's error stream on, whichever of the three handlers below produced the record.
+API_ERROR_EVENT = "api_error"
+
+
+def _user_id_of(request: Request) -> str | None:
+ """Return the authenticated caller's id, when one is on the request.
+
+ `pipelex_api.security._set_request_user` stores a `RequestUser` on
+ `request.state.user` after a successful auth check (jwt, or
+ `TRUST_FORWARDED_IDENTITY_HEADERS=true`). The global error-log sites read
+ that here so an operator can tie a failure to a caller without grepping
+ multiple log lines by `request_id` — and without each route having to log
+ `user=<id>` itself before raising (which Phase 3 removed). Returns `None`
+ pre-auth, on the static-API-key surface (no per-caller identity), or for
+ `AUTH_MODE=none` without the forwarded-identity opt-in: `_emit_api_error`
+ drops `None`-valued fields, so the attribute is absent from the record
+ rather than carried as `user_id: null`.
+ """
+ user: RequestUser | None = getattr(request.state, "user", None)
+ return user.user_id if user is not None else None
+
+
+def _pipe_code_of(request: Request) -> str | None:
+ """Return the body-derived `pipe_code` when `_parse_request` bound one.
+
+ `pipelex_api.routes.pipelex.pipeline._parse_request` writes `pipe_code` onto
+ `request.state` right after the body decodes (before
+ `_validate_extras` / `from_body`), normalized through
+ `_coerce_correlation_field` — empty / non-string / oversized inputs become
+ `None`, so a caller cannot inflate every record the request emits. Returns
+ `None` for routes that don't use `_parse_request`, for requests whose body
+ never decoded (`_decode_body` raised 422), and for bodies that legitimately
+ omitted `pipe_code` (the `mthds_contents`-only invocation).
+ `_emit_api_error` drops `None`-valued fields.
+ """
+ return getattr(request.state, "pipe_code", None)
+
+
+def _pipeline_run_id_of(request: Request) -> str | None:
+ """Return the parsed `pipeline_run_id` when `_parse_request` bound one on the request.
+
+ Same shape as `_pipe_code_of`. Source: the raw body's `pipeline_run_id` (the
+ protocol wire field — the pipelex runtime internals keep calling it
+ `pipeline_run_id`), normalized through `_coerce_correlation_field` at the
+ binding site (empty string → `None`, oversized → truncated). Letting the
+ field ride every error log lets an operator correlate the API-side failure
+ with the worker-side traces that share the same run id, without each
+ backend frame having to forward it.
+ """
+ return getattr(request.state, "pipeline_run_id", None)
+
+
+def _request_fields(request: Request) -> dict[str, Any]:
+ """Return the request-scoped attributes every error record carries.
+
+ Single source of truth for the `route` / `user_id` / `pipe_code` /
+ `pipeline_run_id` set, so the three log paths (`_log_error_report`,
+ `_log_api_authored_error`, `handle_unexpected_error`) cannot drift.
+
+ `request_id` is deliberately NOT here. `RequestIdMiddleware` binds it on the
+ runtime's log context for the whole request, so it is already an attribute of
+ every record emitted underneath — including the ones pipelex emits from inside
+ a run, which this module never sees. Repeating it would give one value two
+ sources. `route` is here rather than on that context because the runtime
+ reserves the context for its three run identifiers, and a route path is not
+ one of them; a field is the seam it offers for everything else.
+
+ Each value is `None` when the corresponding state is not bound on this request;
+ `_emit_api_error` drops those, so an unbound identifier is absent from the
+ record rather than carried as `pipe_code: null`.
+ """
+ return {
+ "route": request.url.path,
+ "user_id": _user_id_of(request),
+ "pipe_code": _pipe_code_of(request),
+ "pipeline_run_id": _pipeline_run_id_of(request),
+ }
+
+
+def _retry_after_header(report: ErrorReport) -> dict[str, str]:
+ """Return a `Retry-After` header dict when a retry hint applies to this response.
+
+ Emitted only when the response is itself a retry invitation — the
+ provider-429 passthrough (`report.http_status == 429`) — so a hint never
+ rides a 500/422 where `Retry-After` is meaningless. The provider's
+ `retry_after_seconds` is rounded up and clamped to a non-negative integer;
+ a non-finite value (a provider sending `Retry-After: inf` / `nan`) is
+ dropped rather than crashing `math.ceil`. Empty dict when no usable hint
+ applies.
+ """
+ if report.http_status != 429:
+ return {}
+ metadata = report.provider_metadata
+ if metadata is None:
+ return {}
+ seconds = metadata.retry_after_seconds
+ if seconds is None or not math.isfinite(seconds):
+ return {}
+ return {"Retry-After": str(max(0, math.ceil(seconds)))}
+
+
+def _error_summary(attributes: Mapping[str, Any]) -> str:
+ """Return the human-readable message an `api_error` record carries.
+
+ Built from server-authored values only — the HTTP status and the error type,
+ both of which the API or pipelex chose. Nothing a caller supplied ever reaches
+ the message: `detail` is caller-controlled on several routes, and the route
+ path is percent-decoded from the request line, so both ride fields instead,
+ where a structured sink serializes them as values and a crafted newline stays
+ inside one. The message says which failure it is; the fields say everything
+ about it.
+ """
+ status = attributes.get("status")
+ error_type = attributes.get("error_type")
+ return f"API error {status}: {error_type}" if error_type else f"API error {status}"
+
+
+def _emit_api_error(*, fields: dict[str, Any], as_error: bool) -> None:
+ """Emit one `event=api_error` record: a summary message, everything else a record attribute.
+
+ The fields are handed to the runtime's log call as `fields=`, so each one
+ becomes an attribute of the record and the selected sink decides how it goes
+ on the wire — a key of its own on the JSON sink's line, an OTLP attribute on
+ the collector's. Nothing is flattened into the message here any more, which
+ is what retires the API's own `key=value` rendering and its escaping with it.
+
+ `None`-valued fields are dropped, so an identifier this request never bound is
+ absent rather than carried as a null. `as_error` picks the level — `error`
+ (with the traceback) for operator-actionable failures, `warning` for
+ `INPUT`-domain caller mistakes.
+ """
+ attributes = {key: value for key, value in fields.items() if value is not None}
+ summary = _error_summary(attributes)
+ if as_error:
+ log.error(summary, fields=attributes, include_exception=True)
+ else:
+ log.warning(summary, fields=attributes)
+
+
+def _emit_at_error_level(status: int) -> bool:
+ """Decide the log disposition from the final HTTP status, not the error domain.
+
+ A 5xx is a server fault — log at `error` with a traceback. A 4xx is
+ client-facing (a caller mistake or a benign conflict) — log at `warning`
+ without a traceback. Keying off the post-override status (see
+ ``_ERROR_TYPE_STATUS_OVERRIDES``) is what keeps an API-level 4xx override —
+ e.g. ``PipelineManagerAlreadyExistsError`` mapped to 409 — out of the error
+ dashboards, while still covering the `INPUT`-domain 422 caller mistakes and
+ the provider-429 passthrough without a second per-error-type registry.
+ """
+ return status >= 500
+
+
+def _log_error_report(report: ErrorReport, *, request: Request, status: int | None = None) -> None:
+ """Emit the structured error record for a handled `ErrorReport`.
+
+ Disposition follows the final HTTP status (see ``_emit_at_error_level``):
+ a 4xx is client-facing and logs at `warning` without a traceback (caller
+ mistakes, the provider-429 passthrough, and API-level 4xx overrides like
+ the 409 conflict), a 5xx logs at `error` with the traceback. The fields
+ mirror the response so the two never drift.
+ `user_id` rides every record when auth bound a caller — without it, the
+ storage / pipeline-backend leg of a failure carries only `request_id` and
+ `route`, and tying the failure to the caller requires correlating the
+ request id across unrelated records (Phase 3 deleted the per-route
+ `log.error(... user=...)` lines those failures used to emit).
+
+ ``status`` defaults to ``report.http_status`` and exists so the caller can
+ pass the post-override value (see ``_ERROR_TYPE_STATUS_OVERRIDES``) — the
+ record then agrees with the HTTP status actually sent rather than the
+ domain default.
+ """
+ effective_status = status if status is not None else report.http_status
+ fields: dict[str, Any] = {
+ "event": API_ERROR_EVENT,
+ **_request_fields(request),
+ "error_type": report.error_type,
+ "error_category": report.error_category,
+ "error_domain": report.error_domain,
+ "retryable": report.retryable,
+ "status": effective_status,
+ "provider": report.provider,
+ "model": report.model,
+ }
+ metadata = report.provider_metadata
+ if metadata is not None:
+ fields["provider_status_code"] = metadata.status_code
+ fields["provider_request_id"] = metadata.request_id
+ _emit_api_error(fields=fields, as_error=_emit_at_error_level(effective_status))
+
+
+def _log_api_authored_error(*, document: dict[str, Any], status: int, request: Request) -> None:
+ """Emit the structured error record for an API-authored error response.
+
+ Shares the disposition rule and the common-key set of `_log_error_report`
+ so every error response — a pipelex `ErrorReport` translated to RFC 7807
+ *or* an API-authored 4xx/5xx raised by an `pipelex_api.errors` helper — produces
+ one `event=api_error` record a downstream sink can filter uniformly on
+ `event`, `request_id`, `route`, `error_type`, `error_domain`, `retryable`,
+ and `status`. Without this, an API-owned 500 (a `raise_internal_server_error`
+ site — `/version`'s missing-package case is the canonical example)
+ would land with zero operator output, since `handle_api_error` only
+ serializes the response.
+
+ Where the two helpers differ — by design, matching what each side actually
+ has to log:
+ - API-authored docs add `detail`, always safe because
+ `build_problem_document_from_api_error` does not apply strict-disclosure
+ redaction (only `build_problem_document` does for pipelex domain errors).
+ Carrying the message preserves the operator-facing cause in the record.
+ - API-authored docs omit `error_category`, `provider`, `model`, and
+ `provider_metadata.*` — those are inference-domain classifiers pipelex
+ sets only on classifiable failures and the API never authors itself.
+
+ A 4xx logs at `warning` without a traceback; a 5xx logs at `error` with
+ the traceback — same status-keyed disposition rule `_log_error_report`
+ uses (see ``_emit_at_error_level``), so a sink dedup'ing by level sees one
+ shape.
+ """
+ fields: dict[str, Any] = {
+ "event": API_ERROR_EVENT,
+ **_request_fields(request),
+ "error_type": document.get("error_type"),
+ "error_domain": document.get("error_domain"),
+ "retryable": document.get("retryable"),
+ "status": status,
+ "detail": document.get("detail"),
+ }
+ _emit_api_error(fields=fields, as_error=_emit_at_error_level(status))
+
+
+def _json_safe_report(report: ErrorReport) -> ErrorReport:
+ """Return a report whose floats Starlette's JSON encoder can render.
+
+ `JSONResponse` encodes with `allow_nan=False`, so a non-finite
+ `provider_metadata.retry_after_seconds` — a provider sending `Retry-After:
+ inf` / `nan`, which pipelex's header parser passes through unchecked —
+ would crash the whole response render, not just the `Retry-After` header.
+ Null the unusable hint out; the rest of the report renders intact.
+ """
+ metadata = report.provider_metadata
+ if metadata is None:
+ return report
+ seconds = metadata.retry_after_seconds
+ if seconds is None or math.isfinite(seconds):
+ return report
+ safe_metadata = metadata.model_copy(update={"retry_after_seconds": None})
+ return report.model_copy(update={"provider_metadata": safe_metadata})
+
+
+_ERROR_TYPE_STATUS_OVERRIDES: dict[str, int] = {
+ # Async execution disabled is a deliberate deployment configuration, not
+ # an unexpected runtime fault. Mapping it to 501 Not Implemented (rather
+ # than the CONFIG-domain default of 500) tells clients "this server does
+ # not provide this functionality" without inviting retries.
+ "AsyncExecutionNotEnabledError": 501,
+ # A submission reusing a pipeline_run_id that is still registered (a
+ # genuinely concurrent duplicate — completed/failed runs free their entry
+ # on the way out) is a client-visible conflict, not a server fault.
+ # Mapping it to 409 Conflict (rather than the no-domain default of 500)
+ # tells clients "this id is currently in use": resubmit after the
+ # in-flight run finishes, or pick a fresh id.
+ "PipelineManagerAlreadyExistsError": 409,
+ # The `method_ref` resolution failures (pipelex `MethodRefError` subclasses). The library
+ # declares no `error_domain` on them, so without an override each would default to 500 —
+ # wrong for what are overwhelmingly caller-fixable conditions. Each entry keeps the class
+ # name as the distinct `error_type` the caller (or an agent) branches on:
+ # - A reference that does not match the `<address>[@<tag>]` grammar: the caller's own
+ # input, plainly fixable → 422.
+ "MethodRefParseError": 422,
+ # - The repository could not be fetched (nonexistent repo, a `@tag` that is not a tag,
+ # network refusal). The dominant cause is a mistyped address or tag — caller-fixable —
+ # so 422; the message carries git's own explanation for the rarer upstream faults.
+ "MethodFetchError": 422,
+ # - The repository was fetched but holds no package matching the address by manifest
+ # identity: the referenced resource does not exist → 404 (mirroring the hosted
+ # platform's unknown-`method_id` mapping); the message lists what the repo does contain.
+ "MethodPackageNotFoundError": 404,
+ # - More than one package matches the address: the caller must disambiguate with the
+ # package's full address → 422.
+ "MethodPackageAmbiguityError": 422,
+ # - The selected package exceeds the fetched-package ceilings: the referenced content
+ # cannot be processed under this deployment's bounds → 422 (not 413, which is about
+ # the request entity itself).
+ "MethodPackageTooLargeError": 422,
+ # - The method's Python declares structure classes, whether it was sent as a bundle or
+ # fetched by `method_ref`: a policy refusal (hosted execution accepts MTHDS concepts and
+ # sandboxed PipeFuncs, not in-process Python) → 403, the same status as the bundle
+ # transport's custom-code gate.
+ "MethodStructuresRefusedError": 403,
+}
+
+
+def _http_status_for(report: ErrorReport) -> int:
+ """Return the HTTP status to use for this report.
+
+ Defers to ``report.http_status`` for the standard mapping (provider-429
+ passthrough + ``error_domain`` -> 4xx/5xx) and applies a per-error-type
+ override last. Overrides live in ``_ERROR_TYPE_STATUS_OVERRIDES`` so the
+ decisions are discoverable in one place — keep the dict small and each
+ entry justified.
+ """
+ return _ERROR_TYPE_STATUS_OVERRIDES.get(report.error_type, report.http_status)
+
+
+def _problem_response(report: ErrorReport, *, request: Request, disclosure_mode: DisclosureMode) -> JSONResponse:
+ """Build the RFC 7807 `JSONResponse` for an `ErrorReport` and log the entry.
+
+ Shared by the `PipelexError` handler and every orchestrator-mapper handler:
+ both produce an `ErrorReport`, so both render and log it identically. The report is first
+ made JSON-safe (see `_json_safe_report`); the status code then comes from
+ `_http_status_for(report)` (the report's own mapping plus any API-layer
+ override registered in ``_ERROR_TYPE_STATUS_OVERRIDES``), and the response
+ body from the Phase 1 problem-document builder under the caller-supplied
+ `disclosure_mode` (`register_exception_handlers` binds the app's effective
+ mode into the handlers it registers).
+ """
+ report = _json_safe_report(report)
+ request_id = request_id_of(request)
+ status = _http_status_for(report)
+ document = build_problem_document(
+ report,
+ instance=request.url.path,
+ request_id=request_id,
+ disclosure_mode=disclosure_mode,
+ )
+ # Keep the RFC 7807 ``status`` member aligned with the actual HTTP status
+ # when an API-layer override has bumped it away from ``report.http_status``;
+ # otherwise the two surfaces (header vs body) would silently disagree.
+ document["status"] = status
+ _log_error_report(report, request=request, status=status)
+ return JSONResponse(
+ status_code=status,
+ content=document,
+ media_type=PROBLEM_JSON_MEDIA_TYPE,
+ headers=_retry_after_header(report),
+ )
+
+
+def problem_response_from_error_report(report: ErrorReport, *, request: Request) -> JSONResponse:
+ """Render an `ErrorReport` value through the same RFC 7807 path as raised errors.
+
+ Most `ErrorReport`s reach this module by raising a `PipelexError` or by an
+ orchestrator transport mapper. `/validate` can also receive an `ErrorReport`
+ as a registry-returned value; when that value is a backend/config/runtime
+ fault rather than a validation verdict, it must still keep the same status,
+ disclosure, logging, and retry headers as the global handler path.
+ """
+ disclosure_mode = getattr(request.app.state, "error_disclosure_mode", DisclosureMode.VERBOSE)
+ return _problem_response(report, request=request, disclosure_mode=disclosure_mode)
+
+
+async def handle_pipelex_error(request: Request, exc: Exception, *, disclosure_mode: DisclosureMode) -> Response:
+ """Translate any pipelex `PipelexError` into an RFC 7807 problem response.
+
+ The single place in the API that consumes a `PipelexError`'s `ErrorReport`.
+ `to_error_report()` walks the `__cause__` chain, so a wrapper exception
+ still surfaces the classification of the underlying failure. `exc` is typed
+ `Exception` to match Starlette's handler contract; FastAPI only routes a
+ `PipelexError` here, so the cast is sound. An orchestrator's workflow
+ failure that is itself a `PipelexError` (e.g. the Temporal plugin's
+ `WorkflowExecutionError`, which already carries a structured `ErrorReport`)
+ resolves here via Starlette's MRO walk; only a *bare* orchestrator-SDK
+ transport error (no `PipelexError` in its MRO) is routed to that plugin's
+ own mapper-backed handler instead.
+ """
+ report = cast("PipelexError", exc).to_error_report()
+ return _problem_response(report, request=request, disclosure_mode=disclosure_mode)
+
+
+def _make_orchestrator_error_handler(mapper: HttpErrorMapperFn, *, disclosure_mode: DisclosureMode) -> "_ExceptionHandler":
+ """Wrap one plugin-contributed error mapper into a FastAPI exception handler.
+
+ The plugin owns the *classification* (it maps its bare transport/runtime
+ exception — e.g. `temporalio.TemporalError` — to a structured `ErrorReport`);
+ core owns the *transport* exception type (resolved lazily by the registrar);
+ the API owns the *presentation* (the same RFC 7807 + `DisclosureMode`
+ rendering every `ErrorReport` gets via `_problem_response`). This is what
+ lets the base render an orchestrator's transport fault correctly while
+ naming — and importing — no orchestrator SDK. `exc` is typed `Exception` to
+ match Starlette's handler contract; FastAPI only routes the mapper's
+ registered `exc_type` here.
+ """
+
+ async def _handler(request: Request, exc: Exception) -> Response:
+ report = mapper(exc)
+ return _problem_response(report, request=request, disclosure_mode=disclosure_mode)
+
+ return _handler
+
+
+async def handle_unexpected_error(request: Request, exc: Exception) -> Response:
+ """Catch-all for any failure matched by no more-specific handler.
+
+ Covers anything that is not an `ApiError`, a `RequestValidationError`, a
+ `PipelexError`, or an orchestrator plugin's mapped transport exception — so on
+ the orchestrator-agnostic base (which installs no mapper), an *unmapped* bare
+ transport/runtime error collapses here to a 500.
+
+ One of the two `except Exception`-equivalent sites the project sanctions —
+ the outermost handler of an API. Disclosure follows the app's
+ `disclosure_mode`, exactly like every other handler in this module: VERBOSE
+ puts `Class: message` in `detail` so a caller can see what actually broke;
+ STRICT keeps the fully sanitized body (no exception class, no `str(exc)`).
+ A traceback reaches the client in neither mode — the class name and full
+ traceback go to the operator log, correlated by request id.
+
+ Honoring the mode here is what stops the catch-all from being a silent hole.
+ An unclassified failure is *precisely* the one a caller cannot diagnose from
+ a request id alone, and it is the only response in the API that used to
+ contradict a deployment's explicit choice to disclose: a VERBOSE deployment
+ got real messages for every classified error and a dead end for the one
+ error nobody classified. STRICT still redacts, so a deployment that wants
+ nothing leaked keeps that.
+
+ The mode is read off `app.state` (like `problem_response_from_error_report`)
+ rather than bound as a parameter, so registering this handler stays
+ signature-free.
+
+ This handler also covers a failure *inside* another handler (e.g. a corrupt
+ `to_error_report()`): Starlette's `ServerErrorMiddleware` wraps the others,
+ so such a failure still lands here rather than a bodyless default.
+ """
+ request_id = request_id_of(request)
+ _emit_api_error(
+ fields={
+ "event": API_ERROR_EVENT,
+ **_request_fields(request),
+ "error_type": type(exc).__name__,
+ "error_category": "unknown",
+ "error_domain": ErrorDomain.RUNTIME,
+ "status": 500,
+ },
+ as_error=True,
+ )
+ disclosure_mode = getattr(request.app.state, "error_disclosure_mode", DisclosureMode.VERBOSE)
+ if disclosure_mode is DisclosureMode.STRICT:
+ detail = "An unexpected error occurred. The request id is included for support."
+ else:
+ detail = f"{type(exc).__name__}: {exc}"
+ # Route through the same builder every other API-authored 500 uses, so the
+ # catch-all shape never drifts from `handle_api_error`'s output. The one
+ # catch-all-specific addition is `error_category: "unknown"` — by definition
+ # the failure was not classifiable, and the marker lets a downstream sink
+ # tell a catch-all 500 apart from a classified `CONFIG`-domain one.
+ document = build_problem_document_from_api_error(
+ ErrorType.INTERNAL_SERVER_ERROR,
+ detail,
+ 500,
+ instance=request.url.path,
+ request_id=request_id,
+ error_domain=ErrorDomain.RUNTIME,
+ )
+ document["error_category"] = "unknown"
+ return JSONResponse(status_code=500, content=document, media_type=PROBLEM_JSON_MEDIA_TYPE)
+
+
+async def handle_api_error(request: Request, exc: Exception) -> Response:
+ """Render an API-authored `ApiError` as an RFC 7807 problem response.
+
+ `ApiError` is raised by the `raise_*` helpers in `pipelex_api.errors` for the API's
+ own 4xx/5xx — request validation, auth, payload limits, misconfiguration.
+ The helper builds the problem document at raise time, where it holds no
+ `Request`, so this handler stamps the two request-scoped members (`instance`
+ and `request_id`) onto a copy of it — the same two values, read from the same
+ place, as the pipelex-error and request-validation paths use. It then
+ serializes that document, re-attaches any `WWW-Authenticate` challenge header,
+ and emits the structured `event=api_error` record so an API-owned 500 from any
+ route is observable (a `raise_internal_server_error` site like `version.py`'s
+ missing-package case is the canonical example — it has no preceding
+ `log.error` at the call site). `exc` is typed `Exception` to match Starlette's
+ handler contract; FastAPI only routes an `ApiError` here, so the cast is sound.
+ """
+ api_error = cast("ApiError", exc)
+ document = with_request_context(
+ api_error.document,
+ instance=request.url.path,
+ request_id=request_id_of(request),
+ )
+ _log_api_authored_error(document=document, status=api_error.status_code, request=request)
+ return JSONResponse(
+ status_code=api_error.status_code,
+ content=document,
+ media_type=PROBLEM_JSON_MEDIA_TYPE,
+ headers=api_error.headers,
+ )
+
+
+def _summarize_request_validation_error(exc: RequestValidationError) -> str:
+ """Render FastAPI's per-field validation failures as one human-readable string.
+
+ `RequestValidationError.errors()` is a list of per-field dicts; RFC 7807's
+ `detail` is a single human-readable string, so each entry is rendered as
+ `<location>: <message>` and the lot joined. Only `loc` and `msg` are read —
+ both are plain strings / ints — so nothing unserializable from a crafted
+ request body can reach the response.
+ """
+ parts: list[str] = []
+ for error in exc.errors():
+ location = ".".join(str(item) for item in error.get("loc", ()))
+ message = error.get("msg") or "Invalid input"
+ parts.append(f"{location}: {message}" if location else message)
+ return "; ".join(parts) or "Request validation failed"
+
+
+# The `error_type` a FastAPI-validated body failing on exactly one of these fields carries,
+# so a client branches on the same value whichever route refused the field. `/execute` and
+# `/start` read their extras by hand and classify them the same way in `pipelex_api.routes.pipelex.pipeline`.
+_BODY_FIELD_ERROR_TYPES: dict[str, ErrorType] = {
+ "analytics_groups": ErrorType.INVALID_ANALYTICS_GROUPS,
+}
+
+
+def _request_validation_error_type(exc: RequestValidationError) -> ErrorType:
+ """Classify a request validation failure by the body field that failed.
+
+ Only a failure confined to one classified body field gets that field's type; anything
+ else — several fields, a query parameter, a model-level validator — keeps the generic
+ `ValidationError`, because naming one field would hide the others.
+ """
+ failed_fields: set[str] = set()
+ for error in exc.errors():
+ location = tuple(error.get("loc", ()))
+ if len(location) < 2 or location[0] != "body":
+ return ErrorType.VALIDATION_ERROR
+ failed_fields.add(str(location[1]))
+ if len(failed_fields) != 1:
+ return ErrorType.VALIDATION_ERROR
+ return _BODY_FIELD_ERROR_TYPES.get(failed_fields.pop(), ErrorType.VALIDATION_ERROR)
+
+
+async def handle_request_validation_error(request: Request, exc: Exception) -> Response:
+ """Translate FastAPI's automatic request validation failure into RFC 7807.
+
+ FastAPI raises `RequestValidationError` when a request body, query, or path
+ parameter fails the endpoint's declared Pydantic model — an extra field
+ under `extra="forbid"`, a `min_length` / `max_length` breach, a missing or
+ mistyped field, a `field_validator` raising `ValueError`, malformed JSON. Its
+ built-in handler would answer with a bare `{"detail": [...]}` /
+ `application/json` body; registering this handler overrides that so an
+ endpoint's caller-input rejection is the same `application/problem+json`
+ shape as an explicit `raise_validation_error` — one error contract across
+ every endpoint. `exc` is typed `Exception` to match Starlette's handler
+ contract; FastAPI only routes a `RequestValidationError` here, so the cast
+ is sound.
+ """
+ validation_error = cast("RequestValidationError", exc)
+ document = build_problem_document_from_api_error(
+ _request_validation_error_type(validation_error),
+ _summarize_request_validation_error(validation_error),
+ 422,
+ instance=request.url.path,
+ request_id=request_id_of(request),
+ error_domain=ErrorDomain.INPUT,
+ )
+ # Same `event=api_error` record as an explicit `raise_validation_error`,
+ # so FastAPI's automatic-validation 422s aren't silent in operator logs.
+ _log_api_authored_error(document=document, status=422, request=request)
+ return JSONResponse(status_code=422, content=document, media_type=PROBLEM_JSON_MEDIA_TYPE)
+
+
+def register_exception_handlers(
+ app: FastAPI,
+ *,
+ disclosure_mode: DisclosureMode = DisclosureMode.VERBOSE,
+ http_error_mappers: dict[type[Exception], HttpErrorMapperFn] | None = None,
+) -> None:
+ """Register the app-level exception handlers on `app`.
+
+ Resolution is most-specific-first: an API-authored `ApiError` →
+ `handle_api_error`; a FastAPI `RequestValidationError` (automatic
+ request-body / parameter validation) → `handle_request_validation_error`; a
+ `PipelexError` (including an orchestrator plugin's `PipelexError`-derived
+ workflow failure) → `handle_pipelex_error`; a bare orchestrator-SDK transport
+ error → that plugin's mapper-backed handler (see `http_error_mappers`);
+ anything else → `handle_unexpected_error`. Registering `RequestValidationError`
+ overrides FastAPI's built-in handler so its automatic-validation failures answer
+ in the same `application/problem+json` shape as every other error, not the
+ default `{"detail": [...]}`. Shared by the production app and by the unit
+ tests, which register the same handlers on a throwaway app.
+
+ `http_error_mappers` is the `{exc_type: to_error_report}` map an orchestrator
+ plugin contributes through the plugin SPI (`PluginRegistrar.add_http_error_mapper`,
+ read back via `get_http_error_mappers`). The caller resolves it at app
+ construction — `pipelex_api.main` builds the registrar and passes it; the base resolves
+ an empty map (it installs no orchestrator plugin), so no transport handler is
+ registered and the only fallback for an unclassified failure stays the catch-all
+ 500. Each entry registers one handler that runs the mapper and renders the
+ resulting `ErrorReport` through the shared RFC 7807 + disclosure path — so core
+ and the API name no orchestrator SDK. Keeping the parameter explicit (rather than
+ calling `build_registrar` in here) preserves this module's import-side-effect-free
+ contract: tests register handlers on a throwaway app without a booted Pipelex, and
+ a test contributes a synthetic mapper to prove the seam without installing a plugin.
+
+ `disclosure_mode` is captured by the handlers that render a pipelex `ErrorReport`
+ (`handle_pipelex_error` and every mapper handler) via the closures below —
+ production passes the startup-resolved value (`pipelex_api.main.ERROR_DISCLOSURE_MODE`);
+ tests pass whatever the test needs and the default (`VERBOSE`) covers the common
+ case. The other three handlers don't render an `ErrorReport`, so they register
+ directly — `handle_unexpected_error` still honors the mode, reading it back off
+ `app.state` (set below) rather than through a closure.
+ """
+ app.state.error_disclosure_mode = disclosure_mode
+
+ async def _pipelex_error(request: Request, exc: Exception) -> Response:
+ return await handle_pipelex_error(request, exc, disclosure_mode=disclosure_mode)
+
+ app.add_exception_handler(ApiError, handle_api_error)
+ app.add_exception_handler(RequestValidationError, handle_request_validation_error)
+ app.add_exception_handler(PipelexError, _pipelex_error)
+ for exc_type, mapper in (http_error_mappers or {}).items():
+ app.add_exception_handler(exc_type, _make_orchestrator_error_handler(mapper, disclosure_mode=disclosure_mode))
+ app.add_exception_handler(Exception, handle_unexpected_error)
diff --git a/api/pipelex_api/limits.py b/api/pipelex_api/limits.py
new file mode 100644
index 000000000..3e3c3e562
--- /dev/null
+++ b/api/pipelex_api/limits.py
@@ -0,0 +1,58 @@
+"""Centralized, env-tunable size limits for incoming requests.
+
+Every endpoint that accepts user-supplied content bounds it via constants
+imported from this module. Values are read once at import time — change
+requires a process restart.
+"""
+
+from pipelex import log
+from pipelex.system.environment import get_optional_env
+
+DEFAULT_MAX_REQUEST_BODY_MIB = 100
+DEFAULT_MAX_MTHDS_FILE_KIB = 1024 # 1 MiB per .mthds file
+DEFAULT_MAX_MTHDS_FILES_PER_REQUEST = 16
+DEFAULT_MAX_PIPE_CODE_LEN = 256
+MAX_METHOD_REF_LEN = 512 # `method_ref` selector strings; a fixed schema bound, not env-tunable
+DEFAULT_MAX_CALLBACK_URLS = 5
+DEFAULT_MAX_CALLBACK_URL_LEN = 2048
+DEFAULT_MAX_AGENT_SPEC_KIB = 256 # 256 KiB for JSON concept/pipe specs
+DEFAULT_MAX_BUNDLE_FILES = 128 # entries in a materialized method bundle (.mthds + .py + requirements.txt)
+DEFAULT_MAX_BUNDLE_TOTAL_KIB = 8 * 1024 # 8 MiB decompressed across the whole bundle (zip-bomb guard)
+DEFAULT_MAX_METHOD_CACHE_CLONES = 64 # cached method-package clones (one per resolved commit SHA)
+DEFAULT_MAX_METHOD_CACHE_TOTAL_KIB = 512 * 1024 # 512 MiB across all cached clones
+DEFAULT_MAX_METHOD_CACHE_AGE_HOURS = 24 # a cached clone unused for this long is evicted
+
+
+def _read_positive_int(env_var: str, default: int) -> int:
+ raw = get_optional_env(env_var)
+ if not raw:
+ return default
+ try:
+ parsed = int(raw)
+ except ValueError:
+ log.warning(f"Invalid {env_var}={raw!r}, falling back to {default}")
+ return default
+ if parsed <= 0:
+ log.warning(f"{env_var} must be positive (got {parsed}), falling back to {default}")
+ return default
+ return parsed
+
+
+MAX_REQUEST_BODY_MIB = _read_positive_int("MAX_REQUEST_BODY_MIB", DEFAULT_MAX_REQUEST_BODY_MIB)
+MAX_REQUEST_BODY_BYTES = MAX_REQUEST_BODY_MIB * 1024 * 1024
+
+MAX_MTHDS_FILE_BYTES = _read_positive_int("MAX_MTHDS_FILE_KIB", DEFAULT_MAX_MTHDS_FILE_KIB) * 1024
+MAX_MTHDS_FILES_PER_REQUEST = _read_positive_int("MAX_MTHDS_FILES_PER_REQUEST", DEFAULT_MAX_MTHDS_FILES_PER_REQUEST)
+MAX_PIPE_CODE_LEN = _read_positive_int("MAX_PIPE_CODE_LEN", DEFAULT_MAX_PIPE_CODE_LEN)
+
+MAX_CALLBACK_URLS = _read_positive_int("MAX_CALLBACK_URLS", DEFAULT_MAX_CALLBACK_URLS)
+MAX_CALLBACK_URL_LEN = _read_positive_int("MAX_CALLBACK_URL_LEN", DEFAULT_MAX_CALLBACK_URL_LEN)
+
+MAX_AGENT_SPEC_BYTES = _read_positive_int("MAX_AGENT_SPEC_KIB", DEFAULT_MAX_AGENT_SPEC_KIB) * 1024
+
+MAX_BUNDLE_FILES = _read_positive_int("MAX_BUNDLE_FILES", DEFAULT_MAX_BUNDLE_FILES)
+MAX_BUNDLE_TOTAL_BYTES = _read_positive_int("MAX_BUNDLE_TOTAL_KIB", DEFAULT_MAX_BUNDLE_TOTAL_KIB) * 1024
+
+MAX_METHOD_CACHE_CLONES = _read_positive_int("MAX_METHOD_CACHE_CLONES", DEFAULT_MAX_METHOD_CACHE_CLONES)
+MAX_METHOD_CACHE_TOTAL_BYTES = _read_positive_int("MAX_METHOD_CACHE_TOTAL_KIB", DEFAULT_MAX_METHOD_CACHE_TOTAL_KIB) * 1024
+MAX_METHOD_CACHE_AGE_SECONDS = _read_positive_int("MAX_METHOD_CACHE_AGE_HOURS", DEFAULT_MAX_METHOD_CACHE_AGE_HOURS) * 3600
diff --git a/api/pipelex_api/main.py b/api/pipelex_api/main.py
new file mode 100644
index 000000000..d8dd65cd2
--- /dev/null
+++ b/api/pipelex_api/main.py
@@ -0,0 +1,221 @@
+"""FastAPI app init, middleware, and router registration.
+
+App construction lives here; the failure → HTTP response mapping lives in
+`pipelex_api.exception_handlers` (registered against this app below). Routes
+therefore no longer need to catch and shape errors themselves — anything
+they raise lands in the right handler by exception class.
+"""
+
+from collections.abc import AsyncGenerator
+from contextlib import asynccontextmanager
+from importlib.metadata import PackageNotFoundError
+from importlib.metadata import version as package_version
+
+from fastapi import Depends, FastAPI
+from fastapi.middleware.cors import CORSMiddleware
+from mthds.protocol.protocol import PROTOCOL_VERSION
+from pipelex.interpreter_plugins.builtins import BUILTIN_PLUGINS, CORE_UNCONDITIONAL_PLUGIN_NAMES, ENTRY_POINT_GROUPS
+from pipelex.pipelex import Pipelex
+from pipelex.plugins.discovery import build_registrar
+from pipelex.plugins.registrar import HttpErrorMapperFn
+from pipelex.system.configuration.config_loader import config_manager
+from pipelex.system.configuration.configs import PipelexConfig
+from pipelex.system.environment import get_optional_env
+from pipelex.system.runtime import IntegrationMode
+from pydantic import BaseModel, Field
+from starlette.middleware.base import BaseHTTPMiddleware
+
+from pipelex_api.api_config import get_api_config, resolve_boot_orchestrator
+from pipelex_api.disclosure import resolve_disclosure_mode
+from pipelex_api.exception_handlers import register_exception_handlers
+from pipelex_api.middleware import RequestIdMiddleware, request_body_size_middleware
+from pipelex_api.openapi_schema import PipelexFastAPI
+from pipelex_api.routes import router as api_router
+from pipelex_api.routes.health import router as health_router
+from pipelex_api.routes.version import router as version_router
+from pipelex_api.security import get_auth_dependency
+
+
+@asynccontextmanager
+async def lifespan(_app: FastAPI) -> AsyncGenerator[None]:
+ # Resolve the deployment's orchestration mode BEFORE booting, so the process can boot
+ # under the matching orchestrator. `orchestration_mode` selects the dispatch arm; a
+ # non-`direct` (async/boot) orchestrator — e.g. "temporal" — must additionally claim the
+ # process-global execution hub slots at boot, which the shared WorkflowExecutor requires
+ # (`is_*_boot_active()`): without it, a `temporal`-mode runner resolves the Temporal
+ # dispatch arm but the underlying pipe-run stack is still in-process, and dispatch fails
+ # with AsyncExecutionNotEnabledError. The base `direct` mode names no orchestrator and
+ # boots in-process (boot_orchestrator=None). `resolve_boot_orchestrator` derives boot from
+ # the deployment config and refuses a config whose single boot can't service its own
+ # per-request override policy (a `direct` default with override on) — so boot and dispatch
+ # can never be set inconsistently.
+ #
+ # Loading `api.toml` here also fails the app fast on a malformed config / baked override
+ # (the same posture as ERROR_DISCLOSURE), now even before the singleton exists. The loader
+ # only needs `runtime_manager.environment` (from PIPELEX_ENV), which resolves without a
+ # live singleton. get_api_config() is @cache'd, so the warm here is reused everywhere.
+ boot_orchestrator = resolve_boot_orchestrator(get_api_config())
+ Pipelex.make(integration_mode=IntegrationMode.FASTAPI, boot_orchestrator=boot_orchestrator)
+ try:
+ yield
+ finally:
+ Pipelex.teardown_if_needed()
+
+
+def _resolve_cors_origins() -> tuple[list[str], bool]:
+ """Read CORS_ALLOW_ORIGINS env var. Returns (origins, allow_credentials).
+
+ Default: wildcard origins, credentials disabled — the only valid combination
+ when origins is `*` (browsers reject credentials with wildcard). To enable
+ credentials, set CORS_ALLOW_ORIGINS to a comma-separated allowlist.
+ """
+ raw = get_optional_env("CORS_ALLOW_ORIGINS")
+ if not raw or raw.strip() == "*":
+ return ["*"], False
+ origins = [origin.strip() for origin in raw.split(",") if origin.strip()]
+ if not origins:
+ return ["*"], False
+ return origins, True
+
+
+# Resolve and validate ERROR_DISCLOSURE once, at module/startup: an unrecognized
+# value raises here and the production app fails to boot rather than silently
+# defaulting. Passed into `register_exception_handlers` below; the resolved
+# mode drives how much of an error report reaches a client. Kept module-level
+# so the production fail-fast lives on this single import path — only this
+# module triggers it, not `pipelex_api.exception_handlers` (which lets tests register
+# the handlers without inheriting the env-validation crash).
+ERROR_DISCLOSURE_MODE = resolve_disclosure_mode()
+
+
+def _resolve_http_error_mappers() -> dict[type[Exception], HttpErrorMapperFn]:
+ """Resolve the orchestrator plugins' HTTP-error mappers for this deployment.
+
+ Runs the pure, repeatable `build_registrar` against the loaded config (the same
+ standalone pattern `pipelex plugins list` uses) and reads back the
+ `{exc_type: to_error_report}` map each installed orchestrator plugin contributed
+ via `PluginRegistrar.add_http_error_mapper`. The base installs no orchestrator
+ plugin, so this is an empty map and no transport-error handler is registered; a
+ flavor (e.g. the Temporal one) contributes its plugin's mapper here, and only at
+ this point — at app construction, where the plugin (and therefore its SDK) is by
+ definition installed — is the plugin's exc-type provider thunk run. Resolved once
+ at module import so a duplicate/broken plugin fails the app fast, mirroring the
+ `ERROR_DISCLOSURE` fail-fast above.
+
+ Safe at import because the map is a pure function of *installed* plugins (entry
+ points + `config.runtime.plugins.disabled`) — never of the `boot_orchestrator` that
+ `Pipelex.make` selects at boot — so an import-time resolution yields the identical
+ map a post-boot one would. `boot_orchestrator=None` is passed for exactly that
+ reason: it gates only a plugin's hub-slot claims, which this throwaway registrar
+ never applies, while the HTTP-error mapper a plugin contributes is unconditional.
+ Naming the deployment's real orchestrator here would change nothing in the map and
+ would drag `api.toml` loading onto the import path.
+
+ `load_config_validated` rather than a load followed by a `model_validate`, because
+ that is the tolerant entry point the boot itself uses: a configuration a pipelex
+ schema change left behind is replayed through its migration ledger in memory and
+ re-validated, so a stale-but-explainable config warns instead of stopping the boot.
+ Validating the raw dict here would refuse, at import, a config the very next step
+ (`Pipelex.make` in `lifespan`) accepts — the app would never start over a file
+ pipelex offers to migrate.
+ """
+ config = config_manager.load_config_validated(config_cls=PipelexConfig)
+ return build_registrar(
+ config=config,
+ boot_orchestrator=None,
+ builtin_plugins=BUILTIN_PLUGINS,
+ core_unconditional_plugin_names=CORE_UNCONDITIONAL_PLUGIN_NAMES,
+ entry_point_groups=ENTRY_POINT_GROUPS,
+ ).get_http_error_mappers()
+
+
+HTTP_ERROR_MAPPERS = _resolve_http_error_mappers()
+
+
+def _own_version() -> str:
+ """This server package's version — best-effort for app metadata."""
+ try:
+ return package_version("pipelex-api")
+ except PackageNotFoundError:
+ return "0.0.0"
+
+
+fastapi_app = PipelexFastAPI(
+ redirect_slashes=False,
+ lifespan=lifespan,
+ title="Pipelex API",
+ version=_own_version(),
+ summary=f"The source-available Pipelex runner — implements MTHDS Protocol v{PROTOCOL_VERSION}.",
+ description=(
+ f"This server implements the [MTHDS Protocol](https://mthds.ai) v{PROTOCOL_VERSION} "
+ "(`POST /execute`, `POST /start`, `POST /validate`, `GET /models`, `GET /version` — "
+ "marked `x-mthds-protocol: true`) plus the Pipelex API extensions: resolve and codegen "
+ "(`/resolve`, `/codegen`), build tooling (`/build/*`), and editor tooling (`/lint`, `/format`). "
+ "Contract layering: MTHDS Protocol ⊂ Pipelex API (this server) ⊂ Pipelex hosted API. "
+ "All endpoints are served under the `/v1` base path; "
+ "every error is an RFC 7807 `application/problem+json` problem document, documented per "
+ "operation as a `ProblemDocument`."
+ ),
+ license_info={"name": "Elastic License 2.0", "identifier": "Elastic-2.0"},
+)
+
+# Order matters: Starlette's `add_middleware` PREPENDS (see
+# `user_middleware.insert(0, ...)` in `starlette.applications`), so the LAST
+# `add_middleware` call becomes the OUTERMOST wrapper. Body-size is registered
+# first so CORS ends up wrapping it: a 413 short-circuit from the body-size
+# middleware still passes back through CORSMiddleware on the way out, so a
+# cross-origin browser POST sees the RFC 7807 413 with the
+# `Access-Control-Allow-Origin` header it needs — not a generic CORS error
+# that swallows the response.
+fastapi_app.add_middleware(BaseHTTPMiddleware, dispatch=request_body_size_middleware)
+
+cors_origins, cors_allow_credentials = _resolve_cors_origins()
+fastapi_app.add_middleware(
+ CORSMiddleware,
+ allow_origins=cors_origins,
+ allow_credentials=cors_allow_credentials,
+ allow_methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"],
+ allow_headers=["*"],
+ expose_headers=["*"],
+)
+
+fastapi_app.include_router(health_router)
+
+# `GET /v1/version` is the protocol handshake — ALWAYS public, mounted without
+# the auth dependency exactly like `/health` (clients call it for feature
+# detection before they have credentials).
+fastapi_app.include_router(version_router, prefix="/v1")
+
+# Register all other routes WITH authentication (auto-selects based on AUTH_MODE env var: none/jwt/api_key).
+# The API mounts at `/v1` — the SDKs compose `{MTHDS_BASE_URL}/v1/{endpoint}` (master D10); no `/api/v1`
+# mount and no alias remain.
+auth_dependency = get_auth_dependency()
+fastapi_app.include_router(api_router, prefix="/v1", dependencies=[Depends(auth_dependency)])
+
+
+class ServiceIdentity(BaseModel):
+ """Body of `GET /` — the service identity banner."""
+
+ message: str = Field(..., description="Name of the service answering on this origin.")
+
+
+@fastapi_app.get("/", summary="Service identity banner", tags=["health"])
+async def root() -> ServiceIdentity:
+ """Identify the service answering on this origin. No auth required.
+
+ A human-facing banner for someone who lands on the bare origin — not a
+ liveness probe (that is `GET /health`) and not the protocol handshake
+ (`GET /v1/version`). It reads nothing and can only succeed.
+ """
+ return ServiceIdentity(message="Pipelex API")
+
+
+register_exception_handlers(fastapi_app, disclosure_mode=ERROR_DISCLOSURE_MODE, http_error_mappers=HTTP_ERROR_MAPPERS)
+
+
+# RequestIdMiddleware wraps the *entire* FastAPI app — including Starlette's
+# ServerErrorMiddleware, which `add_middleware` could only ever nest inside.
+# This is what makes it genuinely outermost: the request-id contextvars are
+# bound, and `X-Request-ID` is echoed, on every response — the catch-all 500
+# included. `app` is the ASGI entrypoint (uvicorn loads `pipelex_api.main:app`).
+app = RequestIdMiddleware(fastapi_app)
diff --git a/api/pipelex_api/method_cache.py b/api/pipelex_api/method_cache.py
new file mode 100644
index 000000000..e43294ad5
--- /dev/null
+++ b/api/pipelex_api/method_cache.py
@@ -0,0 +1,241 @@
+"""Per-instance on-disk clone cache for fetched method packages, keyed by resolved commit SHA.
+
+A `method_ref` run fetches a public git repository. Cloning on every request would hammer
+GitHub's anonymous-clone rate limits and add seconds of latency, so this server keeps the
+clones on local disk — but **never keyed by tag**: tags can move, and a moved tag must
+change what runs. Instead, each request first resolves the reference to its commit SHA with
+a cheap `git ls-remote` (no clone), then looks the clone up by that SHA. A repointed tag or
+an advanced default branch resolves to a new SHA and therefore a fresh clone; the cached
+copy of the old SHA ages out on its own.
+
+The cache is per server instance (a directory under the system temp dir by default,
+`METHOD_CACHE_DIR` to override) and bounded three ways — clone count, total bytes, and age —
+via the `MAX_METHOD_CACHE_*` knobs in `pipelex_api.limits`. Eviction runs on insert, oldest-first by
+last use, and never evicts the most recently used entry. Package location, bounds, and the
+structures scan are NOT cached: they re-run against the cached clone on every request, so a
+deployment-mode change (or a ceiling change) applies immediately.
+
+Concurrency: clones land in a per-request staging directory and are installed with an atomic
+`rename`, so two concurrent requests for the same SHA cannot corrupt each other — the loser
+of the rename race discards its staging copy and uses the winner's. The resolution seam
+(`pipelex_api.method_source`) copies everything it needs out of the cached clone before the run
+starts, so eviction can never pull a directory out from under a running pipeline.
+"""
+
+import os
+import shutil
+import subprocess
+import tempfile
+import threading
+import time
+import uuid
+from functools import cache
+from pathlib import Path
+
+from pipelex import log
+from pipelex.methods.exceptions import MethodFetchError
+from pipelex.methods.fetching import FetchedMethodPackage, ensure_package_within_bounds, fetch_method_package
+from pipelex.methods.method_ref import MethodRef
+from pipelex.methods.package_locator import locate_package_in_clone
+from pipelex.system.environment import get_optional_env
+
+from pipelex_api.limits import MAX_METHOD_CACHE_AGE_SECONDS, MAX_METHOD_CACHE_CLONES, MAX_METHOD_CACHE_TOTAL_BYTES
+
+LS_REMOTE_TIMEOUT_SECONDS = 60
+
+_STAGING_DIR_NAME = ".staging"
+_DEFAULT_CACHE_DIR_NAME = "pipelex-api-method-cache"
+
+
+def _run_ls_remote(*, clone_url: str, ref_patterns: list[str], ref_str: str) -> list[tuple[str, str]]:
+ """Run `git ls-remote` for the given ref patterns and return `(sha, ref_name)` pairs.
+
+ Raises:
+ MethodFetchError: If git is unavailable, the remote cannot be reached, or the call times out.
+ """
+ try:
+ result = subprocess.run( # noqa: S603 — fixed argv, no shell; the URL is derived from the validated address grammar
+ ["git", "ls-remote", clone_url, *ref_patterns], # noqa: S607
+ capture_output=True,
+ text=True,
+ check=True,
+ timeout=LS_REMOTE_TIMEOUT_SECONDS,
+ )
+ except FileNotFoundError as exc:
+ msg = "git is not installed or not found on PATH"
+ raise MethodFetchError(msg) from exc
+ except subprocess.CalledProcessError as exc:
+ msg = f"Failed to fetch method '{ref_str}': could not reach the repository ({exc.stderr.strip()})"
+ raise MethodFetchError(msg) from exc
+ except subprocess.TimeoutExpired as exc:
+ msg = f"Timed out resolving method '{ref_str}' against the remote repository"
+ raise MethodFetchError(msg) from exc
+
+ pairs: list[tuple[str, str]] = []
+ for line in result.stdout.strip().splitlines():
+ parts = line.split("\t")
+ if len(parts) == 2:
+ pairs.append((parts[0], parts[1]))
+ return pairs
+
+
+def resolve_remote_commit_sha(*, ref: MethodRef, clone_url: str | None = None) -> str:
+ """Resolve a method reference to the commit SHA it currently points at, without cloning.
+
+ For a `@<tag>` reference, only `refs/tags/<tag>` is consulted — a branch of the same
+ name does not count, so `@main` is refused here, before any clone (the same tags-only
+ rule `pipelex.methods.fetching.ensure_cloned_at_tag` enforces after a clone). For an
+ annotated tag the peeled (`^{}`) commit SHA is returned, matching what `rev-parse HEAD`
+ reports inside a clone at that tag. A bare reference resolves the default branch `HEAD`.
+
+ Args:
+ ref: The parsed method reference.
+ clone_url: Override for the derived clone URL (tests, non-default remotes).
+
+ Returns:
+ The full commit SHA the reference resolves to right now.
+
+ Raises:
+ MethodFetchError: If the remote cannot be reached, or `@<tag>` does not name a tag.
+ """
+ effective_clone_url = clone_url or ref.clone_url
+ if ref.tag:
+ pairs = _run_ls_remote(
+ clone_url=effective_clone_url,
+ ref_patterns=[f"refs/tags/{ref.tag}", f"refs/tags/{ref.tag}^{{}}"],
+ ref_str=ref.ref_str,
+ )
+ peeled = [sha for sha, name in pairs if name.endswith("^{}")]
+ if peeled:
+ return peeled[0]
+ direct = [sha for sha, name in pairs if name == f"refs/tags/{ref.tag}"]
+ if direct:
+ return direct[0]
+ msg = (
+ f"'{ref.tag}' in method reference '{ref.ref_str}' does not name a git tag on the repository — "
+ f"`@<tag>` pins a git tag (recommended form vX.Y.Z); branch names are not accepted."
+ )
+ raise MethodFetchError(msg)
+ pairs = _run_ls_remote(clone_url=effective_clone_url, ref_patterns=["HEAD"], ref_str=ref.ref_str)
+ head = [sha for sha, name in pairs if name == "HEAD"]
+ if not head:
+ msg = f"The repository behind method reference '{ref.ref_str}' has no HEAD (empty repository?)"
+ raise MethodFetchError(msg)
+ return head[0]
+
+
+def _directory_size_bytes(directory: Path) -> int:
+ total = 0
+ for file_path in directory.rglob("*"):
+ if file_path.is_file() and not file_path.is_symlink():
+ total += file_path.stat().st_size
+ return total
+
+
+class MethodCloneCache:
+ """SHA-keyed, bounded, on-disk cache of method-package clones (see the module docstring)."""
+
+ def __init__(self, *, root_dir: Path) -> None:
+ self._root = root_dir
+ self._lock = threading.Lock()
+
+ def get_or_fetch(self, *, ref: MethodRef, clone_url: str | None = None) -> FetchedMethodPackage:
+ """Return the package a reference points at, cloning only when its SHA is not cached.
+
+ Always re-runs package location and the bounds check against the (possibly cached)
+ clone — only the clone itself is cached, never a verdict about it.
+
+ Args:
+ ref: The parsed method reference.
+ clone_url: Override for the derived clone URL (tests, non-default remotes).
+
+ Returns:
+ The fetched package, rooted inside the cache directory.
+
+ Raises:
+ MethodFetchError: If SHA resolution or the clone fails, or `@<tag>` is not a tag.
+ MethodPackageNotFoundError: If no package matches the requested address.
+ MethodPackageAmbiguityError: If more than one package matches.
+ MethodPackageTooLargeError: If the selected package exceeds the ceilings.
+ """
+ commit_sha = resolve_remote_commit_sha(ref=ref, clone_url=clone_url)
+ clone_dir = self._root / commit_sha
+ with self._lock:
+ if clone_dir.is_dir():
+ os.utime(clone_dir) # LRU bookkeeping: mtime is the eviction order
+ return self._package_from_clone(ref=ref, clone_dir=clone_dir, commit_sha=commit_sha)
+
+ # Miss: clone into a per-request staging dir (outside the lock — clones are slow),
+ # then install atomically. A tag repointed between ls-remote and clone resolves to the
+ # clone's ACTUAL commit SHA — that is what gets recorded and keyed, never the stale one.
+ staging_root = self._root / _STAGING_DIR_NAME
+ staging_root.mkdir(parents=True, exist_ok=True)
+ staging_dir = staging_root / uuid.uuid4().hex
+ try:
+ fetched = fetch_method_package(ref=ref, dest_dir=staging_dir, clone_url=clone_url)
+ target_dir = self._root / fetched.commit_sha
+ with self._lock:
+ if not target_dir.exists():
+ try:
+ staging_dir.rename(target_dir)
+ except OSError:
+ # A concurrent request installed the same SHA between the check and the
+ # rename; its copy is identical (same commit), so use it.
+ log.debug(f"Method clone cache: lost the install race for {fetched.commit_sha}, reusing the winner's copy")
+ self._evict()
+ return self._package_from_clone(ref=ref, clone_dir=target_dir, commit_sha=fetched.commit_sha)
+ finally:
+ shutil.rmtree(staging_dir, ignore_errors=True)
+
+ def _package_from_clone(self, *, ref: MethodRef, clone_dir: Path, commit_sha: str) -> FetchedMethodPackage:
+ """Locate + bound the requested package inside a cached clone (never cached themselves)."""
+ located = locate_package_in_clone(clone_root=clone_dir, requested_address=ref.address)
+ ensure_package_within_bounds(package_dir=located.package_dir, package_address=located.full_address)
+ return FetchedMethodPackage(
+ ref=ref,
+ full_address=located.full_address,
+ commit_sha=commit_sha,
+ clone_dir=clone_dir,
+ package_dir=located.package_dir,
+ manifest=located.manifest,
+ )
+
+ def _evict(self) -> None:
+ """Enforce the age, count, and byte bounds — oldest-first, keeping the newest entry.
+
+ Called with the lock held, right after an install. Best-effort by design: a clone
+ directory another process already removed is simply skipped.
+ """
+ entries = sorted(
+ (entry for entry in self._root.iterdir() if entry.is_dir() and entry.name != _STAGING_DIR_NAME),
+ key=lambda entry: entry.stat().st_mtime,
+ )
+ if not entries:
+ return
+ newest = entries[-1]
+ now = time.time()
+ survivors: list[Path] = []
+ for entry in entries:
+ if entry != newest and now - entry.stat().st_mtime > MAX_METHOD_CACHE_AGE_SECONDS:
+ shutil.rmtree(entry, ignore_errors=True)
+ else:
+ survivors.append(entry)
+ total_bytes = sum(_directory_size_bytes(entry) for entry in survivors)
+ while len(survivors) > 1 and (len(survivors) > MAX_METHOD_CACHE_CLONES or total_bytes > MAX_METHOD_CACHE_TOTAL_BYTES):
+ oldest = survivors.pop(0)
+ total_bytes -= _directory_size_bytes(oldest)
+ shutil.rmtree(oldest, ignore_errors=True)
+
+
+@cache
+def get_method_clone_cache() -> MethodCloneCache:
+ """The per-instance clone cache singleton.
+
+ The root directory is `METHOD_CACHE_DIR` when set, else a fixed directory under the
+ system temp dir — per instance, surviving requests but not the host, which is exactly
+ the cache's contract (a cold instance re-clones once per SHA).
+ """
+ configured = get_optional_env("METHOD_CACHE_DIR")
+ root_dir = Path(configured) if configured else Path(tempfile.gettempdir()) / _DEFAULT_CACHE_DIR_NAME
+ root_dir.mkdir(parents=True, exist_ok=True)
+ return MethodCloneCache(root_dir=root_dir)
diff --git a/api/pipelex_api/method_source.py b/api/pipelex_api/method_source.py
new file mode 100644
index 000000000..e74be9d8a
--- /dev/null
+++ b/api/pipelex_api/method_source.py
@@ -0,0 +1,215 @@
+"""Resolve a `method_ref` into run/validate/tooling inputs: fetch → locate → refuse → materialize.
+
+The wire field `method_ref` carries a globally resolvable address —
+`github.com/<owner>/<repo>[/<selector>][@<tag>]` — and THIS runner is its resolver (the
+layered extension policy's Rule 3: an address needs no catalog, so it is a layer-2 concept;
+the hosted-only `method_id` never reaches this server). The grammar, the fetch-at-tag, the
+manifest-identity package location, the bounds, and the structures check all live in
+`pipelex.methods`; this module composes them behind the SHA-keyed clone cache
+(`pipelex_api.method_cache`) and shapes the result for each route family:
+
+- The run routes and `/validate` use :func:`fetched_method_source`: the package's `.mthds`
+ files travel as `mthds_contents` (paired with their real relative paths as
+ `mthds_sources`, so diagnostics carry true per-file labels), and only the non-`.mthds`
+ files are materialized into a temporary `library_dirs` entry — exactly the split the
+ method-bundle transport uses, so a fetched package runs the same proven path.
+- The tooling routes (`/resolve`, `/codegen`, `/build/*`) use
+ :func:`fetch_method_mthds_files`: only the `.mthds` files, as `files[]` items, paired with
+ the manifest's `main_pipe` so the per-pipe projections default their selector exactly as a
+ run does. No Python ever loads there, so the execution-locus gate does not apply.
+
+The security gate (packaging invariant 7 — execution locus decides): `.mthds` content is
+data, always acceptable. On a deployment that is NOT sandbox-hosted, a fetched package
+carrying ANY `.py` is refused with the same 403 the bundle transport uses
+(`CustomCodeRequiresSandbox`) — running it would import customer code in-process. On a
+sandbox-hosted deployment, PipeFunc `.py` is acceptable (captured as text, executed in the
+network-blocked sandbox) but a package declaring `StructuredContent` subclasses is refused
+loudly (`MethodStructuresRefusedError` → 403): structure classes would have to be imported into
+the runner's own process, and the rule-naming error teaches authors to express types as MTHDS
+concepts. The library load refuses the same classes again, for a bundle as for a package.
+
+Everything a run needs is copied OUT of the cached clone before this module yields — the
+`.mthds` text into memory, the rest into a per-request temp directory — so cache eviction
+can never race a running pipeline.
+"""
+
+from collections.abc import Generator
+from contextlib import contextmanager
+from pathlib import Path, PurePosixPath
+from typing import NamedTuple
+
+from mthds.package.discovery import MANIFEST_FILENAME
+from pipelex import log
+from pipelex.config import is_pipe_func_sandbox_hosted
+from pipelex.methods.fetching import FetchedMethodPackage, MethodProvenance
+from pipelex.methods.method_ref import parse_method_ref
+from pipelex.methods.structures_check import ensure_no_structured_content_python
+from pydantic import BaseModel, ConfigDict, Field
+
+from pipelex_api.bundle import ParsedBundle, materialize_parsed
+from pipelex_api.error_types import ErrorType
+from pipelex_api.errors import raise_forbidden, raise_validation_error
+from pipelex_api.limits import MAX_MTHDS_FILE_BYTES
+from pipelex_api.method_cache import get_method_clone_cache
+from pipelex_api.schemas.models import MthdsFileItem
+
+_SKIPPED_DIR_NAMES = {".git", "__pycache__"}
+
+
+class FetchedMethodSource(BaseModel):
+ """A fetched package shaped for the run/validate path (see the module docstring)."""
+
+ model_config = ConfigDict(frozen=True)
+
+ mthds_contents: list[str]
+ mthds_sources: list[str]
+ library_dirs: list[str] | None = None
+ main_pipe: str | None = Field(default=None, description="The manifest's declared entry pipe; a request `pipe_code` overrides it.")
+ provenance: MethodProvenance
+
+
+class FetchedMthdsFiles(NamedTuple):
+ """A fetched package shaped for the tooling path: its `.mthds` files plus the manifest's entry pipe."""
+
+ files: list[MthdsFileItem]
+ """The package's `.mthds` files as `files[]` items, each labelled with its real relative path."""
+
+ main_pipe: str | None
+ """The manifest's declared `main_pipe` (a bare pipe code), or None when the manifest declares none."""
+
+
+def _fetch_package(method_ref: str) -> FetchedMethodPackage:
+ """Parse the reference and fetch its package through the SHA-keyed clone cache.
+
+ Every failure mode is a distinct pipelex `MethodRefError` subclass, rendered by the
+ global handler as RFC 7807 `problem+json` with the class name as `error_type` and the
+ status the API maps for it (`pipelex_api.exception_handlers._ERROR_TYPE_STATUS_OVERRIDES`).
+ """
+ ref = parse_method_ref(method_ref)
+ package = get_method_clone_cache().get_or_fetch(ref=ref)
+ log.info(
+ f"Resolved method_ref '{ref.ref_str}': address={package.provenance.address} "
+ f"tag={package.provenance.tag} commit_sha={package.provenance.commit_sha}"
+ )
+ return package
+
+
+def _package_files(package: FetchedMethodPackage) -> list[Path]:
+ """The package's files, deterministically ordered, with VCS/tooling residue skipped."""
+ files: list[Path] = []
+ for file_path in sorted(package.package_dir.rglob("*")):
+ relative_parts = file_path.relative_to(package.package_dir).parts
+ if any(part in _SKIPPED_DIR_NAMES for part in relative_parts):
+ continue
+ if file_path.is_file():
+ files.append(file_path)
+ return files
+
+
+def _read_mthds_text(file_path: Path, *, relative: str, package_address: str) -> str:
+ try:
+ content = file_path.read_text(encoding="utf-8")
+ except UnicodeDecodeError:
+ raise_validation_error(message=f"File '{relative}' in method package '{package_address}' is not valid UTF-8.")
+ if len(content.encode("utf-8")) > MAX_MTHDS_FILE_BYTES:
+ msg = f"File '{relative}' in method package '{package_address}' exceeds the {MAX_MTHDS_FILE_BYTES // 1024} KiB per-file limit."
+ raise_validation_error(message=msg)
+ return content
+
+
+def _apply_execution_locus_gate(package: FetchedMethodPackage, *, python_relpaths: list[str]) -> None:
+ """Refuse Python that would execute where it must not (see the module docstring)."""
+ if not python_relpaths:
+ return
+ if not is_pipe_func_sandbox_hosted():
+ msg = f"Method package '{package.full_address}' ships custom Python (.py); running it requires a sandbox-hosted deployment."
+ raise_forbidden(message=msg, error_type=ErrorType.CUSTOM_CODE_REQUIRES_SANDBOX)
+ ensure_no_structured_content_python(package_dir=package.package_dir, package_address=package.full_address)
+
+
+@contextmanager
+def fetched_method_source(method_ref: str) -> Generator[FetchedMethodSource, None, None]:
+ """Fetch a `method_ref`'s package and shape it for the run/validate path.
+
+ Yields the package's `.mthds` files as `(mthds_contents, mthds_sources)` pairs and its
+ non-`.mthds` files (PipeFunc `.py`, `requirements.txt`, …) materialized into a temporary
+ `library_dirs` entry, cleaned up on exit. The execution-locus gate runs before anything
+ touches disk.
+
+ Args:
+ method_ref: The raw `method_ref` string from the request.
+
+ Raises:
+ MethodRefError subclasses: parse, fetch, location, bounds, and structures failures —
+ each rendered as `problem+json` by the global handler.
+ ApiError: the 403 custom-code gate on a non-sandbox deployment, and 422s for a
+ package whose `.mthds` content this server cannot accept.
+ """
+ package = _fetch_package(method_ref)
+ files = _package_files(package)
+ python_relpaths = [file_path.relative_to(package.package_dir).as_posix() for file_path in files if file_path.suffix == ".py"]
+ _apply_execution_locus_gate(package, python_relpaths=python_relpaths)
+
+ mthds_contents: list[str] = []
+ mthds_sources: list[str] = []
+ other_entries: list[tuple[PurePosixPath, bytes]] = []
+ for file_path in files:
+ relative = file_path.relative_to(package.package_dir).as_posix()
+ if file_path.suffix == ".mthds":
+ mthds_contents.append(_read_mthds_text(file_path, relative=relative, package_address=package.full_address))
+ mthds_sources.append(relative)
+ elif file_path.name != MANIFEST_FILENAME:
+ # The manifest is already consumed (identity + `main_pipe`); materializing it into
+ # the library dir would hand the local loader a package boundary it must not see.
+ other_entries.append((PurePosixPath(relative), file_path.read_bytes()))
+ if not mthds_contents:
+ raise_validation_error(message=f"Method package '{package.full_address}' contains no .mthds file.")
+
+ if not other_entries:
+ yield FetchedMethodSource(
+ mthds_contents=mthds_contents,
+ mthds_sources=mthds_sources,
+ library_dirs=None,
+ main_pipe=package.manifest.main_pipe,
+ provenance=package.provenance,
+ )
+ return
+ with materialize_parsed(ParsedBundle(entries=tuple(other_entries))) as bundle:
+ yield FetchedMethodSource(
+ mthds_contents=mthds_contents,
+ mthds_sources=mthds_sources,
+ library_dirs=[str(bundle.directory)],
+ main_pipe=package.manifest.main_pipe,
+ provenance=package.provenance,
+ )
+
+
+def fetch_method_mthds_files(method_ref: str) -> FetchedMthdsFiles:
+ """Fetch a `method_ref`'s package and return its `.mthds` files as `files[]` items, plus its `main_pipe`.
+
+ The tooling-route shape: each item pairs the file's content with its real relative path
+ as `source`, so crate provenance and diagnostics carry true per-file labels. Only
+ `.mthds` data travels — the package's Python (if any) never loads on these routes, so
+ the execution-locus gate does not apply here. The manifest's `main_pipe` rides beside the
+ files so a per-pipe projection can default its selector the way a run does — the manifest
+ is the package author's declaration of the entry pipe, and dropping it here would make
+ `main_pipe` buy them nothing on the tooling routes.
+
+ Args:
+ method_ref: The raw `method_ref` string from the request.
+
+ Raises:
+ MethodRefError subclasses: parse, fetch, location, and bounds failures.
+ ApiError: 422 for a package with no `.mthds` file or one this server cannot accept.
+ """
+ package = _fetch_package(method_ref)
+ items: list[MthdsFileItem] = []
+ for file_path in _package_files(package):
+ if file_path.suffix != ".mthds":
+ continue
+ relative = file_path.relative_to(package.package_dir).as_posix()
+ content = _read_mthds_text(file_path, relative=relative, package_address=package.full_address)
+ items.append(MthdsFileItem(content=content, source=relative))
+ if not items:
+ raise_validation_error(message=f"Method package '{package.full_address}' contains no .mthds file.")
+ return FetchedMthdsFiles(files=items, main_pipe=package.manifest.main_pipe)
diff --git a/api/pipelex_api/middleware.py b/api/pipelex_api/middleware.py
new file mode 100644
index 000000000..42bf94026
--- /dev/null
+++ b/api/pipelex_api/middleware.py
@@ -0,0 +1,209 @@
+"""ASGI middleware shared across the FastAPI app."""
+
+import re
+import secrets
+import time
+from collections.abc import Awaitable, Callable
+
+from fastapi import Request, Response
+from fastapi.responses import JSONResponse
+from pipelex import log
+from starlette.datastructures import MutableHeaders
+from starlette.types import ASGIApp, Message, Receive, Scope, Send
+
+from pipelex_api.error_types import ErrorType
+from pipelex_api.limits import MAX_REQUEST_BODY_BYTES, MAX_REQUEST_BODY_MIB
+from pipelex_api.problem_document import PROBLEM_JSON_MEDIA_TYPE, build_problem_document_from_api_error
+
+
+def request_id_of(request: Request) -> str | None:
+ """Return the correlation id `RequestIdMiddleware` stored on this request, or `None` when it did not run.
+
+ `getattr` rather than attribute access: a request that never went through the middleware — a unit
+ test issuing a bare ASGI call, a non-HTTP scope — simply has no id, and a reader of the id is not
+ the place to discover that. This is the one way the API reads the id back; the runtime's bound log
+ context carries the same value onto every record but is not a lookup table for anyone else.
+ """
+ return getattr(request.state, "request_id", None)
+
+
+def _too_large_response(*, request: Request) -> JSONResponse:
+ """Build the 413 RFC 7807 problem response for an over-limit request body.
+
+ The body-size check runs in middleware, before routing, so it cannot go
+ through the `pipelex_api.errors` helpers — a middleware must `return` a response,
+ not raise. It builds the same problem document directly, reading the request
+ context off the `Request` it was handed. `RequestIdMiddleware` runs outermost,
+ so the id is already on `request.state` by the time this is reached; that
+ middleware's `send` wrapper also stamps the `X-Request-ID` header onto this
+ response.
+ """
+ document = build_problem_document_from_api_error(
+ ErrorType.PAYLOAD_TOO_LARGE,
+ f"Request body exceeds {MAX_REQUEST_BODY_MIB} MiB limit",
+ 413,
+ instance=request.url.path,
+ request_id=request_id_of(request),
+ )
+ return JSONResponse(status_code=413, content=document, media_type=PROBLEM_JSON_MEDIA_TYPE)
+
+
+async def request_body_size_middleware(request: Request, call_next: Callable[[Request], Awaitable[Response]]) -> Response:
+ """Reject requests whose body exceeds MAX_REQUEST_BODY_BYTES.
+
+ Two layers of defense:
+ 1. Trust `Content-Length` header when present — fast reject before any body is read.
+ 2. For chunked / missing-header requests, wrap `receive` so we count bytes as
+ they arrive. When the cumulative count crosses the cap, the over-limit
+ chunk is NOT forwarded: it is replaced with an end-of-stream marker so
+ `await request.body()` returns a bounded (often empty) body rather than
+ the full oversized payload, and any further read keeps returning the
+ same terminator (NOT `http.disconnect`, which would raise
+ `ClientDisconnect` and escape past the 413 override). The 413 response
+ then overrides whatever the route returned on its truncated input.
+ """
+ content_length = request.headers.get("content-length")
+ if content_length is not None:
+ try:
+ declared = int(content_length)
+ except ValueError:
+ declared = -1
+ if declared > MAX_REQUEST_BODY_BYTES:
+ return _too_large_response(request=request)
+
+ original_receive = request.receive
+ bytes_seen = 0
+ too_large = False
+
+ async def counting_receive() -> Message:
+ nonlocal bytes_seen, too_large
+ if too_large:
+ # Idempotent end-of-stream on every subsequent read. Returning
+ # `http.disconnect` instead would raise `ClientDisconnect` in
+ # Starlette's body reader, which would escape `call_next` as an
+ # exception and bypass the 413 override below — the request would
+ # land as a sanitized 500 instead of 413.
+ return {"type": "http.request", "body": b"", "more_body": False}
+ message = await original_receive()
+ if message.get("type") == "http.request":
+ body = message.get("body", b"")
+ if isinstance(body, (bytes, bytearray)):
+ bytes_seen += len(body)
+ if bytes_seen > MAX_REQUEST_BODY_BYTES:
+ too_large = True
+ return {"type": "http.request", "body": b"", "more_body": False}
+ return message
+
+ request._receive = counting_receive # type: ignore[assignment] # noqa: SLF001
+
+ response = await call_next(request)
+ if too_large:
+ return _too_large_response(request=request)
+ return response
+
+
+# --- Request correlation -----------------------------------------------------
+
+REQUEST_ID_HEADER = "X-Request-ID"
+
+# Crockford's Base32 alphabet — the ULID encoding. Excludes I, L, O, U so a
+# request id stays unambiguous if a human transcribes it out of a log.
+_CROCKFORD_BASE32 = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"
+_ULID_LENGTH = 26
+_ULID_RANDOM_BITS = 80
+_ULID_TIMESTAMP_MASK = (1 << 48) - 1
+
+# An inbound X-Request-ID is reflected into response headers, logs, and error
+# bodies, so a client-supplied value is never trusted verbatim: it must be a
+# bounded run of injection-safe characters or it is discarded. ULIDs and UUIDs
+# both satisfy this.
+_REQUEST_ID_MAX_LENGTH = 128
+_REQUEST_ID_CHARSET = re.compile(r"\A[A-Za-z0-9_-]+\Z")
+
+
+def generate_request_id() -> str:
+ """Generate a fresh ULID: a 26-char, time-sortable, URL-safe identifier.
+
+ The high 48 bits encode a millisecond Unix timestamp, so ids sort by
+ creation time; the low 80 bits are cryptographically random. The 128-bit
+ value is rendered in Crockford Base32.
+ """
+ timestamp_ms = (time.time_ns() // 1_000_000) & _ULID_TIMESTAMP_MASK
+ value = (timestamp_ms << _ULID_RANDOM_BITS) | secrets.randbits(_ULID_RANDOM_BITS)
+ digits = [""] * _ULID_LENGTH
+ for index in range(_ULID_LENGTH - 1, -1, -1):
+ value, remainder = divmod(value, 32)
+ digits[index] = _CROCKFORD_BASE32[remainder]
+ return "".join(digits)
+
+
+def _is_valid_request_id(candidate: str) -> bool:
+ """Return whether a client-supplied request id is safe to reflect back verbatim."""
+ return 0 < len(candidate) <= _REQUEST_ID_MAX_LENGTH and _REQUEST_ID_CHARSET.match(candidate) is not None
+
+
+def _resolve_request_id(scope: Scope) -> str:
+ """Return the request id for this request.
+
+ Reuses a valid inbound `X-Request-ID` header; otherwise — absent,
+ malformed, or over-long — mints a fresh ULID.
+ """
+ for name, value in scope.get("headers", []):
+ if name == b"x-request-id":
+ candidate: str = value.decode("latin-1").strip()
+ if _is_valid_request_id(candidate):
+ return candidate
+ break
+ return generate_request_id()
+
+
+class RequestIdMiddleware:
+ """Pure-ASGI middleware that assigns a correlation id to every HTTP request.
+
+ For each request it reuses a valid inbound `X-Request-ID` or mints a fresh
+ ULID, stores it on `request.state.request_id`, binds the runtime's log
+ context to that id for the duration of the request, and echoes
+ `X-Request-ID` on the response (success and error alike).
+
+ Binding the runtime's context rather than an API-owned contextvar is what
+ puts `request_id` on *every* record emitted underneath — the API's own
+ error lines, and equally the ones pipelex emits from inside a run — as an
+ attribute a structured sink indexes, with no call site having to pass it
+ and no message having to interpolate it. The binding is in-process only: a
+ run dispatched to a worker gets the id from its `RunMetadata`, where the
+ run routes put it by passing `request_id_of(request)` to the runner.
+
+ Applied in `pipelex_api.main` by wrapping the whole FastAPI app
+ (`app = RequestIdMiddleware(app)`), NOT via `app.add_middleware()`.
+ `add_middleware` always nests a middleware *inside* Starlette's
+ `ServerErrorMiddleware`, which would leave it unable to bind the context
+ for — or set a header on — the catch-all 500 that `ServerErrorMiddleware`
+ emits. Wrapping the app puts this middleware genuinely outermost, outside
+ `ServerErrorMiddleware`, so the context is bound and `X-Request-ID` is
+ echoed on every response, the catch-all 500 included. Raw ASGI (rather than
+ `BaseHTTPMiddleware`) keeps a single contextvar context across the whole
+ stack and lets the `send` wrapper inject the header on any response.
+ """
+
+ def __init__(self, app: ASGIApp) -> None:
+ self.app = app
+
+ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
+ if scope["type"] != "http":
+ await self.app(scope, receive, send)
+ return
+
+ request_id = _resolve_request_id(scope)
+ scope.setdefault("state", {})["request_id"] = request_id
+
+ async def send_with_request_id(message: Message) -> None:
+ if message["type"] == "http.response.start":
+ MutableHeaders(scope=message)[REQUEST_ID_HEADER] = request_id
+ await send(message)
+
+ # The runtime's own context, not an API-owned one: `request_id` is one of the three run
+ # identifiers it reserves, so every record emitted underneath carries it as an attribute.
+ # The route path is deliberately not bound here — it is not a run identifier, and the API
+ # ships it as a `route` field on the lines that want it (see `pipelex_api.exception_handlers`).
+ with log.context(request_id=request_id):
+ await self.app(scope, receive, send_with_request_id)
diff --git a/api/pipelex_api/openapi_responses.py b/api/pipelex_api/openapi_responses.py
new file mode 100644
index 000000000..9cb892083
--- /dev/null
+++ b/api/pipelex_api/openapi_responses.py
@@ -0,0 +1,186 @@
+"""Documentation-only models and shared `responses=` declarations for the API's RFC 7807 errors.
+
+Every failure this server emits is an `application/problem+json` document built
+by the global handlers in `pipelex_api.exception_handlers` — from a pipelex
+`ErrorReport` (`build_problem_document`) or from an API-authored `ApiError`
+(`build_problem_document_from_api_error`). Neither path validates through a
+Pydantic model: they build plain dicts. The models here exist **only** so the
+committed OpenAPI artifact can publish that shape with a real schema instead of
+an untyped `additionalProperties: true` blob — nothing in the request path
+imports them, and adding a field here does not change a single response byte.
+Keep them in step with `docs/error-responses.md`, which is the prose contract.
+
+`ProblemDocument.validation_errors` reuses pipelex's own `ValidationErrorItem`,
+so the item shape published on the error wire is the same one `/validate`'s 200
+invalid arm publishes — including `suggested_fix`, which rides along for free.
+
+The response dicts below are attached two ways:
+
+- `COMMON_PROBLEM_RESPONSES` goes on the composite router in `pipelex_api.routes`, so
+ every auth-wrapped `/v1` operation documents the four failures any of them can
+ produce. Declaring a `422` there also suppresses FastAPI's automatic
+ `HTTPValidationError` response, which advertised the wrong media type and the
+ wrong schema on nearly every route.
+- The single-status constants go on the routes that can additionally produce
+ them (`responses=` on the decorator merges over the router-level set).
+
+The media type is NOT set here. FastAPI renders a `responses` entry's `model`
+under the route's own response-class media type (`application/json`), with no
+per-response override; `PipelexFastAPI.openapi()` in `pipelex_api.openapi_schema`
+re-keys every 4xx/5xx response onto `application/problem+json` (via
+`use_problem_json_media_type`) after the schema is generated.
+"""
+
+from typing import Any
+
+from pipelex.base_exceptions import ValidationErrorItem
+from pipelex.cogt.inference.error_classification import ProviderErrorMetadata, UserAction
+from pydantic import BaseModel, ConfigDict, Field
+
+
+class ProblemDocument(BaseModel):
+ """An RFC 7807 `application/problem+json` error body — the shape of every failure response.
+
+ Standard RFC 7807 members (`type`, `title`, `status`, `detail`, `instance`)
+ plus the extension members pipelex's classification adds. Only `type`,
+ `title`, `status`, `detail`, and `error_type` are always present: the rest
+ ride along when the originating error populates them, so a consumer must
+ treat them as optional. `extra="allow"` mirrors RFC 7807's open-ended
+ extension-member rule.
+ """
+
+ model_config = ConfigDict(extra="allow")
+
+ type: str = Field(..., description="Stable URI for the error class: `https://docs.pipelex.com/latest/errors/<kebab-class-name>/`.")
+ title: str = Field(..., description="Short, human-readable summary of the error class.")
+ status: int = Field(..., description="HTTP status code, repeated in the body per RFC 7807.")
+ detail: str = Field(..., description="Human-readable explanation of this specific failure. Redacted under `ERROR_DISCLOSURE=strict`.")
+ instance: str | None = Field(default=None, description="Path of the request that failed.")
+ request_id: str | None = Field(default=None, description="Correlation id, echoed in the `X-Request-ID` response header.")
+ error_type: str = Field(..., description="Stable class name of the originating error (e.g. `ValidateBundleError`, `Unauthenticated`).")
+ error_domain: str | None = Field(
+ default=None,
+ description="`input` (caller can fix it → 422), `config` or `runtime` (deployment must fix it → 500). Absent for domain-less errors.",
+ )
+ retryable: bool | None = Field(
+ default=None,
+ description=(
+ "Whether retrying the same request can plausibly succeed. Always present on API-authored errors; "
+ "on pipelex errors only when the originating error classifies it."
+ ),
+ )
+ error_category: str | None = Field(default=None, description="Finer classification, when the originating error provides one (inference errors).")
+ user_action: UserAction | None = Field(default=None, description="Structured suggestion of what the caller should do next, when available.")
+ model: str | None = Field(default=None, description="Inference model that failed. Stripped under `ERROR_DISCLOSURE=strict`.")
+ provider: str | None = Field(default=None, description="Inference provider that failed. Stripped under `ERROR_DISCLOSURE=strict`.")
+ provider_metadata: ProviderErrorMetadata | None = Field(
+ default=None,
+ description="Upstream provider error metadata. Stripped (bar a curated slice) under `ERROR_DISCLOSURE=strict`.",
+ )
+ validation_errors: list[ValidationErrorItem] | None = Field(
+ default=None,
+ description=(
+ "Structured per-error diagnostics, carried by a `ValidateBundleError`. Each item may carry a `suggested_fix`. "
+ "Retained under `ERROR_DISCLOSURE=strict` — it describes the caller's own bundle, not server internals. "
+ "On `/validate`, `/resolve`, `/codegen` and `/build/*` an invalid bundle is a **200** verdict instead, so the "
+ "items ride the response body there rather than a problem document."
+ ),
+ )
+
+
+def _problem(description: str, *, headers: dict[str, Any] | None = None) -> dict[str, Any]:
+ """Build one `responses=` entry documenting a `ProblemDocument` failure.
+
+ `model` registers `ProblemDocument` in the artifact's components and emits a
+ `$ref` to it; `PipelexFastAPI.openapi()` (`pipelex_api.openapi_schema`) then moves
+ the schema onto the `application/problem+json` media type.
+ """
+ response: dict[str, Any] = {"description": description, "model": ProblemDocument}
+ if headers is not None:
+ response["headers"] = headers
+ return response
+
+
+PROBLEM_400_START_REQUIRES_ASYNC: dict[str, Any] = _problem(
+ "`StartRequiresAsyncOrchestration` — this deployment's orchestrator is blocking-only and cannot honor "
+ "fire-and-forget delivery. Use `POST /execute` instead.",
+)
+
+PROBLEM_401: dict[str, Any] = _problem(
+ "Missing or invalid bearer token. Only reachable when the deployment enables auth (`AUTH_MODE=api_key` or `AUTH_MODE=jwt`).",
+ headers={
+ "WWW-Authenticate": {
+ "description": "Authentication challenge — always `Bearer`.",
+ "schema": {"type": "string"},
+ }
+ },
+)
+
+PROBLEM_403_RUN_POLICY: dict[str, Any] = _problem(
+ "A deployment-policy refusal: `OrchestrationModeOverrideForbidden` — the request asked for an "
+ "`orchestration_mode` this deployment does not allow overriding per request "
+ "(`allow_request_orchestration_mode_override = false`); `CustomCodeRequiresSandbox` — the method (a bundle, or a "
+ "fetched `method_ref` package) ships custom Python and this deployment is not sandbox-hosted; or "
+ "`MethodStructuresRefusedError` — the method's Python declares structure classes (`StructuredContent` "
+ "subclasses), whether it arrived as a bundle (`files` or `bundle_b64`) or as a fetched `method_ref` package: "
+ "a sandbox-hosted deployment imports no caller Python into its own process, so it refuses them before "
+ "loading anything (express the types as MTHDS concepts instead).",
+)
+
+PROBLEM_409_DUPLICATE_RUN: dict[str, Any] = _problem(
+ "`PipelineManagerAlreadyExistsError` — the submitted `pipeline_run_id` is still registered for an in-flight run. "
+ "Completed and failed runs free their id, so this only fires for genuinely concurrent duplicates.",
+)
+
+PROBLEM_413: dict[str, Any] = _problem(
+ "Request body exceeds the deployment's size limit (`MAX_REQUEST_BODY_MIB`, 100 MiB by default).",
+)
+
+PROBLEM_422: dict[str, Any] = _problem(
+ "The request could not be processed: a malformed body, a field failing validation, or an `input`-domain pipelex "
+ "error (a `.mthds` bundle the caller must fix). Note that on the diagnostic routes an *invalid bundle* is a **200** "
+ "verdict, not a 422 — see each route's response contract.",
+)
+
+PROBLEM_429: dict[str, Any] = _problem(
+ "An upstream inference provider rate-limited the run. Passed through from the provider; `Retry-After` is set when the provider supplied a hint.",
+ headers={
+ "Retry-After": {
+ "description": "Seconds to wait before retrying, when the upstream provider supplied a hint.",
+ "schema": {"type": "integer"},
+ }
+ },
+)
+
+PROBLEM_500: dict[str, Any] = _problem(
+ "A `config`-domain or `runtime`-domain failure the caller cannot fix (a missing env var, a bad TOML override, a "
+ "backend fault), or an unclassified error sanitized by the catch-all handler. Report the `request_id`.",
+)
+
+PROBLEM_501_ASYNC_NOT_ENABLED: dict[str, Any] = _problem(
+ "`AsyncExecutionNotEnabledError` — this deployment does not provide async pipeline execution. Permanent under the "
+ "current deployment; do not retry.",
+)
+
+PROBLEM_404_METHOD_PACKAGE: dict[str, Any] = _problem(
+ "`MethodPackageNotFoundError` — the `method_ref` repository was fetched, but no package in it matches the "
+ "requested address by manifest identity. The message lists the packages the repository does contain.",
+)
+
+PROBLEM_501_METHOD_REF: dict[str, Any] = _problem(
+ "`MethodRefNotSupported` — the request selected its closure by a **registry-form** `method_ref` (not a "
+ "`github.com/...` address), and no server-side method registry resolves those yet. Use an address-form reference "
+ "or submit inline `files[]` instead.",
+)
+
+
+# Attached to the composite `/v1` router (`pipelex_api.routes`), so every auth-wrapped operation documents
+# the failures any of them can produce: the router-level auth check (401), the body-size middleware
+# (413), request-shape and input-domain rejections (422), and the server-fault floor (500). Declaring
+# the 422 here is also what suppresses FastAPI's automatic `HTTPValidationError` response.
+COMMON_PROBLEM_RESPONSES: dict[int | str, dict[str, Any]] = {
+ 401: PROBLEM_401,
+ 413: PROBLEM_413,
+ 422: PROBLEM_422,
+ 500: PROBLEM_500,
+}
diff --git a/api/pipelex_api/openapi_schema.py b/api/pipelex_api/openapi_schema.py
new file mode 100644
index 000000000..202e2b079
--- /dev/null
+++ b/api/pipelex_api/openapi_schema.py
@@ -0,0 +1,83 @@
+"""The FastAPI subclass that publishes this API's error responses under the right media type.
+
+Every failure the API emits is an RFC 7807 `application/problem+json` document — that is the
+whole contract of `pipelex_api.exception_handlers`. But FastAPI renders a `responses` entry's `model`
+under the **route's** response-class media type (`application/json` for every route here) and
+offers no per-response override (`route_response_media_type` in `fastapi.openapi.utils`). Left
+alone, the published artifact would therefore promise `application/json` on every error — a
+contract the server never honors.
+
+Hand-writing the media type into each `responses` entry would mean hand-writing a `$ref` too,
+forfeiting FastAPI's component registration for `ProblemDocument` (`pipelex_api.openapi_responses`). So
+the schema is generated normally and the error responses are re-keyed afterwards, in
+`PipelexFastAPI.openapi()` — FastAPI's documented "Extending OpenAPI" seam, and the single place
+the API asserts the error media type. It holds for the live `/openapi.json` and for the committed
+YAML alike: both go through `openapi()`.
+
+Deliberately import-side-effect-free, mirroring `pipelex_api.exception_handlers`: no env var reads, no app
+construction, no router wiring. That is what lets a test build a production-faithful app —
+one that renders the error media type the way the real server does — without dragging in
+`pipelex_api.main`'s startup chain (`Pipelex.make`, `get_auth_dependency`, the `ERROR_DISCLOSURE`
+fail-fast), so a misconfigured env var cannot crash collection of every module that needs the
+app class.
+"""
+
+from typing import Any
+
+from fastapi import FastAPI
+from typing_extensions import override
+
+from pipelex_api.problem_document import PROBLEM_JSON_MEDIA_TYPE
+
+# HTTP methods that carry an operation object in an OpenAPI path item. A path item can also hold
+# non-operation keys (`parameters`, `summary`, `servers`), so the pass below iterates this set
+# rather than every key it finds.
+_OPENAPI_OPERATION_KEYS = frozenset({"get", "put", "post", "delete", "options", "head", "patch", "trace"})
+
+
+def _is_error_status(status_code: str) -> bool:
+ """Whether an OpenAPI response key denotes a 4xx/5xx status.
+
+ Response keys are strings, and beyond the numeric ones OpenAPI allows the wildcard forms
+ (`4XX`, `5XX`) and `default`. This server declares only numeric statuses, so anything
+ non-numeric is left alone rather than guessed at.
+ """
+ return status_code.isdigit() and int(status_code) >= 400
+
+
+def use_problem_json_media_type(schema: dict[str, Any]) -> None:
+ """Re-key every documented 4xx/5xx response onto `application/problem+json`, in place.
+
+ See the module docstring for why this is a post-pass rather than a per-response declaration.
+ """
+ for path_item in schema.get("paths", {}).values():
+ for method, operation in path_item.items():
+ if method not in _OPENAPI_OPERATION_KEYS:
+ continue
+ for status_code, response in operation.get("responses", {}).items():
+ if not _is_error_status(status_code):
+ continue
+ content: dict[str, Any] | None = response.get("content")
+ if content is None:
+ continue
+ json_content = content.pop("application/json", None)
+ if json_content is not None:
+ content[PROBLEM_JSON_MEDIA_TYPE] = json_content
+
+
+class PipelexFastAPI(FastAPI):
+ """The app class. Stock FastAPI, extended only to publish errors as `application/problem+json`."""
+
+ @override
+ def openapi(self) -> dict[str, Any]:
+ """The OpenAPI schema, with every documented 4xx/5xx moved onto `application/problem+json`.
+
+ The early return keeps the rewrite a one-shot: the base builds the schema and caches it on
+ `self.openapi_schema`, returning that same dict, so mutating it in place fixes up the cached
+ copy and every later call short-circuits here.
+ """
+ if self.openapi_schema is not None:
+ return self.openapi_schema
+ schema = super().openapi()
+ use_problem_json_media_type(schema)
+ return schema
diff --git a/api/pipelex_api/problem_document.py b/api/pipelex_api/problem_document.py
new file mode 100644
index 000000000..3ba009187
--- /dev/null
+++ b/api/pipelex_api/problem_document.py
@@ -0,0 +1,134 @@
+"""RFC 7807 problem-document construction.
+
+A pure module — no FastAPI imports, no I/O. It turns the two error sources of
+the API into the single `application/problem+json` body shape clients see:
+
+- `build_problem_document` — for a pipelex `ErrorReport`. Delegates to
+ `ErrorReport.to_problem_document(...)`: pipelex owns the field mapping
+ (standard RFC 7807 slots plus classification extension members) and the
+ `disclosure_mode` redaction. The API only chooses the disclosure mode and
+ supplies the request context.
+- `build_problem_document_from_api_error` — for an API-authored 4xx that has
+ no `ErrorReport` behind it (`raise_validation_error` and friends in
+ `pipelex_api.errors`). Built from the static `ErrorType` enum; always `INPUT` domain.
+
+Both return a plain `dict` the caller serializes as `application/problem+json`.
+"""
+
+from typing import Any
+
+from pipelex.base_exceptions import DisclosureMode, ErrorDomain, ErrorReport
+
+from pipelex_api.error_types import ErrorType
+from pipelex_api.error_uri import error_type_title, error_type_uri
+
+# Content type for every error response — RFC 7807 problem documents. Lives
+# here, the module that builds them, so the FastAPI app, the middleware, and
+# the error handlers can all reference one constant without a circular import.
+PROBLEM_JSON_MEDIA_TYPE = "application/problem+json"
+
+
+def build_problem_document(
+ report: ErrorReport,
+ *,
+ instance: str | None,
+ request_id: str | None,
+ disclosure_mode: DisclosureMode,
+) -> dict[str, Any]:
+ """Build an RFC 7807 problem document from a pipelex `ErrorReport`.
+
+ Thin wrapper over `ErrorReport.to_problem_document(...)`: the field mapping
+ and the `disclosure_mode` redaction both live upstream in pipelex. The
+ API's only responsibility is to choose the disclosure mode and pass the
+ request context through.
+ """
+ return report.to_problem_document(
+ instance=instance,
+ request_id=request_id,
+ disclosure_mode=disclosure_mode,
+ )
+
+
+def build_problem_document_from_api_error(
+ error_type: ErrorType,
+ message: str,
+ status: int,
+ *,
+ instance: str | None,
+ request_id: str | None,
+ error_domain: ErrorDomain | None = ErrorDomain.INPUT,
+ retryable: bool = False,
+) -> dict[str, Any]:
+ """Build an RFC 7807 problem document for an API-authored error.
+
+ Used by the `pipelex_api.errors` 4xx/5xx helpers, whose failures are the API's own
+ request validation, auth, or configuration checks rather than a pipelex
+ domain error — there is no `ErrorReport` to delegate to. The `type` URI and
+ `title` are derived from the static `ErrorType` enum the same way pipelex
+ derives them for its own classes, so the standard RFC 7807 slots and the
+ `error_type` / `error_domain` members line up with what a pipelex error
+ renders.
+
+ Extension-member parity with a pipelex `ErrorReport` is by-field, not
+ wholesale, with two distinct rules:
+
+ - `retryable` is emitted unconditionally here (every API-authored error is
+ non-retryable; see below). pipelex emits it only when the source error
+ populated it, so a non-inference pipelex report (`PipelexConfigError`,
+ `EnvVarNotFoundError`) renders with no `retryable`. Asymmetric by design:
+ the API knows the answer for every error it authors, and clients can
+ drive retry logic uniformly without branching on field presence.
+ - Classification fields pipelex sets only on classifiable failures
+ (`error_category`, `user_action`, `model`, `provider`, `provider_metadata`)
+ are NOT manufactured here. The same omission rule pipelex applies to its
+ own non-inference reports (`PipelexConfigError`, `EnvVarNotFoundError`
+ carry no `error_category` either) — surfacing a fake category for an
+ API-authored validation or auth failure would lie about what the API
+ actually classified.
+
+ `error_domain` defaults to `INPUT` — the caller can fix a 4xx. API-owned
+ 5xx (a missing secret, a misconfigured backend) pass `CONFIG`: an operator,
+ not the caller, fixes those. `None` omits the member entirely, matching how
+ a domain-less pipelex error renders.
+
+ `retryable` defaults to `False`: every error this builder authors is a
+ caller-input mistake or a server misconfiguration, neither of which a blind
+ retry fixes. Carried as a positional contract member rather than dropped on
+ `None`, so clients can drive retry logic uniformly without branching on
+ field presence.
+
+ `None`-valued context (`instance`, `request_id`) is dropped rather than
+ emitted as `null`, matching `ErrorReport.to_problem_document` semantics.
+ """
+ document: dict[str, Any] = {
+ "type": error_type_uri(error_type),
+ "title": error_type_title(error_type),
+ "status": status,
+ "detail": message,
+ }
+ if instance is not None:
+ document["instance"] = instance
+ if request_id is not None:
+ document["request_id"] = request_id
+ document["error_type"] = error_type
+ if error_domain is not None:
+ document["error_domain"] = error_domain
+ document["retryable"] = retryable
+ return document
+
+
+def with_request_context(document: dict[str, Any], *, instance: str | None, request_id: str | None) -> dict[str, Any]:
+ """Return a copy of a problem document carrying the two request-scoped members.
+
+ The `pipelex_api.errors` helpers build their document where no `Request` is in hand — a validation
+ check deep inside a route, an auth refusal — so `instance` and `request_id` are stamped later,
+ by the handler that renders the response and does hold the request. A copy rather than an
+ in-place edit, because the `ApiError` a caller catches and inspects must read exactly as it was
+ raised. `None` is dropped rather than emitted as `null`, the rule every builder here follows.
+ """
+ stamped = dict(document)
+ if instance is not None:
+ stamped["instance"] = instance
+ if request_id is not None:
+ stamped["request_id"] = request_id
+ return stamped
diff --git a/api/pipelex_api/py.typed b/api/pipelex_api/py.typed
new file mode 100644
index 000000000..e69de29bb
diff --git a/api/pipelex_api/routes/__init__.py b/api/pipelex_api/routes/__init__.py
new file mode 100644
index 000000000..94ffe3bc7
--- /dev/null
+++ b/api/pipelex_api/routes/__init__.py
@@ -0,0 +1,23 @@
+from fastapi import APIRouter
+
+from pipelex_api.openapi_responses import COMMON_PROBLEM_RESPONSES
+
+from .pipelex import router as pipelex_router
+
+# NOTE: the version router is NOT composed here — `GET /version` is always
+# public (protocol handshake), so `pipelex_api.main` mounts it under `/v1` directly,
+# WITHOUT the auth dependency this composite router gets wrapped in.
+#
+# `responses=` here merges into EVERY operation composed below (FastAPI's
+# `include_router` folds the including router's `responses` into each route's
+# own, route-level entries winning on a status collision). It documents the four
+# failures every auth-wrapped `/v1` route shares — 401 from the router-level auth
+# dependency `pipelex_api.main` wraps this in, 413 from the body-size middleware, 422 for
+# request-shape/input-domain rejections, 500 for the server-fault floor — so each
+# route only has to declare the extra statuses it alone can produce. Declaring the
+# 422 is also what suppresses FastAPI's automatic `HTTPValidationError` response,
+# whose media type (`application/json`) and schema both contradict the RFC 7807
+# document the global handlers actually emit.
+router = APIRouter(responses=COMMON_PROBLEM_RESPONSES)
+
+router.include_router(pipelex_router)
diff --git a/api/pipelex_api/routes/health.py b/api/pipelex_api/routes/health.py
new file mode 100644
index 000000000..f6b885b23
--- /dev/null
+++ b/api/pipelex_api/routes/health.py
@@ -0,0 +1,24 @@
+from fastapi import APIRouter
+from pydantic import BaseModel, Field
+
+router = APIRouter(tags=["health"])
+
+
+class HealthResponse(BaseModel):
+ """Body of `GET /health`."""
+
+ status: str = Field(..., description="Always `ok` — the endpoint answers only when the process is serving.")
+ message: str = Field(..., description="Human-readable confirmation that the server is up.")
+
+
[email protected]("/health", summary="Liveness probe")
+async def get_health() -> HealthResponse:
+ """Report that this server process is up and serving. No auth required.
+
+ A pure liveness probe for load balancers and orchestrators: it touches no
+ dependency (no pipelex library load, no storage, no inference provider), so
+ a 200 means "the process is serving", never "the deployment is correctly
+ configured". It is mounted outside the `/v1` base path and outside the auth
+ dependency, and cannot fail.
+ """
+ return HealthResponse(status="ok", message="Pipelex API is running")
diff --git a/api/pipelex_api/routes/pipelex/__init__.py b/api/pipelex_api/routes/pipelex/__init__.py
new file mode 100644
index 000000000..69de2873d
--- /dev/null
+++ b/api/pipelex_api/routes/pipelex/__init__.py
@@ -0,0 +1,21 @@
+from fastapi import APIRouter
+
+from .agent import router as agent_router
+from .build import router as build_router
+from .codegen import router as codegen_router
+from .pipe_io import router as pipe_io_router
+from .pipeline import router as pipeline_router
+from .resolve import router as resolve_router
+from .tools import router as tools_router
+from .validate import router as validate_router
+
+router = APIRouter()
+
+router.include_router(build_router)
+router.include_router(pipeline_router)
+router.include_router(validate_router)
+router.include_router(resolve_router)
+router.include_router(pipe_io_router)
+router.include_router(codegen_router)
+router.include_router(tools_router)
+router.include_router(agent_router)
diff --git a/api/pipelex_api/routes/pipelex/agent/__init__.py b/api/pipelex_api/routes/pipelex/agent/__init__.py
new file mode 100644
index 000000000..c4d4e56de
--- /dev/null
+++ b/api/pipelex_api/routes/pipelex/agent/__init__.py
@@ -0,0 +1,11 @@
+from fastapi import APIRouter
+
+from .concept import router as concept_router
+from .models import router as models_router
+from .pipe_spec import router as pipe_spec_router
+
+router = APIRouter()
+
+router.include_router(models_router)
+router.include_router(concept_router)
+router.include_router(pipe_spec_router)
diff --git a/api/pipelex_api/routes/pipelex/agent/concept.py b/api/pipelex_api/routes/pipelex/agent/concept.py
new file mode 100644
index 000000000..c7711479a
--- /dev/null
+++ b/api/pipelex_api/routes/pipelex/agent/concept.py
@@ -0,0 +1,59 @@
+"""Concept endpoint — convert JSON concept spec to TOML."""
+
+import json
+from typing import Any
+
+from fastapi import APIRouter
+from pipelex.builder.operations.concept_ops import concept_spec_to_toml, parse_concept_spec
+from pydantic import BaseModel, Field, ValidationError, field_validator
+
+from pipelex_api.errors import raise_validation_error
+from pipelex_api.limits import MAX_AGENT_SPEC_BYTES
+
+router = APIRouter(tags=["agent"])
+
+
+class BuildConceptRequest(BaseModel):
+ spec: dict[str, Any] = Field(..., description="JSON concept specification.")
+
+ @field_validator("spec")
+ @classmethod
+ def _bound_spec_size(cls, value: dict[str, Any]) -> dict[str, Any]:
+ if len(json.dumps(value).encode("utf-8")) > MAX_AGENT_SPEC_BYTES:
+ msg = f"spec exceeds {MAX_AGENT_SPEC_BYTES // 1024} KiB limit"
+ raise ValueError(msg)
+ return value
+
+
+class BuildConceptResponse(BaseModel):
+ success: bool = Field(default=True, description="Whether the operation was successful")
+ concept_code: str = Field(..., description="The concept code that was generated")
+ toml: str = Field(..., description="Generated TOML content for the concept")
+
+
[email protected]("/build/concept")
+async def build_concept(request_data: BuildConceptRequest) -> BuildConceptResponse:
+ """Convert a JSON concept spec to TOML format.
+
+ A malformed spec surfaces as a Pydantic `ValidationError` — an API-owned
+ 422. Pipelex domain failures propagate untouched to the global
+ `PipelexError` handler in `pipelex_api.exception_handlers`.
+
+ A malformed shape — a non-mapping `structure` (`{"structure": "string"}`)
+ or a `structure` field that is neither a string nor a mapping
+ (`{"structure": {"f": 42}}`) — is refused by `parse_concept_spec` itself
+ with a typed `ConceptSpecError`, which that same handler answers. Nothing
+ broader is caught here: a bare exception from pipelex is the signal of a
+ real programming bug, and a route-level catch would mask it.
+ """
+ try:
+ concept_spec = parse_concept_spec(request_data.spec)
+ toml_content = concept_spec_to_toml(concept_spec)
+
+ return BuildConceptResponse(
+ success=True,
+ concept_code=concept_spec.concept_code,
+ toml=toml_content,
+ )
+ except ValidationError as exc:
+ raise_validation_error(message=str(exc))
diff --git a/api/pipelex_api/routes/pipelex/agent/models.py b/api/pipelex_api/routes/pipelex/agent/models.py
new file mode 100644
index 000000000..37b5ca83f
--- /dev/null
+++ b/api/pipelex_api/routes/pipelex/agent/models.py
@@ -0,0 +1,49 @@
+"""Models endpoint — the MTHDS Protocol model deck this runner routes to."""
+
+from typing import Annotated
+
+from fastapi import APIRouter, Query, Request
+from mthds.protocol.models import ModelCategory
+from pipelex.pipeline.runner import PipelexModelDeck
+
+from pipelex_api.error_types import ErrorType
+from pipelex_api.errors import raise_validation_error
+from pipelex_api.routes.pipelex.pipeline import ApiRunner
+
+router = APIRouter(tags=["agent"])
+
+
[email protected]("/models", openapi_extra={"x-mthds-protocol": True})
+async def get_models(
+ request: Request,
+ model_type: Annotated[
+ str | None,
+ Query(alias="type", description="Filter by model category: llm, extract, img_gen, search. Single value (protocol arity)."),
+ ] = None,
+) -> PipelexModelDeck:
+ """List the model deck this runner can route to (MTHDS Protocol `GET /models`).
+
+ Answers the protocol `ModelDeck` as produced by `PipelexMTHDSProtocol.models` —
+ the flat `models` list (`{name, type}` entries) plus this implementation's
+ category-keyed routing extensions (`aliases`, `waterfalls`). The `type` query
+ param is a SINGLE protocol `ModelCategory` value: repeated `?type=` values
+ (arity, `ValidationError`) and unknown categories (`InvalidModelCategory`) are
+ both 422s (RFC 7807).
+ """
+ # Protocol arity: `type` is a plain single-value enum. FastAPI silently keeps one of
+ # several repeated scalar query params, so the multi-value rejection must be explicit.
+ # Generic ValidationError, not InvalidModelCategory: the values may all be valid —
+ # what's wrong is the arity.
+ if len(request.query_params.getlist("type")) > 1:
+ raise_validation_error(message="The `type` query parameter accepts a single value")
+ category: ModelCategory | None = None
+ if model_type is not None:
+ try:
+ category = ModelCategory(model_type)
+ except ValueError:
+ valid = ", ".join(sorted(member.value for member in ModelCategory))
+ raise_validation_error(
+ message=f"Invalid model category. Valid values: {valid}",
+ error_type=ErrorType.INVALID_MODEL_CATEGORY,
+ )
+ return await ApiRunner().models(category=category)
diff --git a/api/pipelex_api/routes/pipelex/agent/pipe_spec.py b/api/pipelex_api/routes/pipelex/agent/pipe_spec.py
new file mode 100644
index 000000000..55c961324
--- /dev/null
+++ b/api/pipelex_api/routes/pipelex/agent/pipe_spec.py
@@ -0,0 +1,58 @@
+"""Pipe spec endpoint — convert JSON pipe spec to TOML."""
+
+import json
+from typing import Any
+
+from fastapi import APIRouter
+from pipelex.builder.operations.pipe_ops import parse_pipe_spec, pipe_spec_to_toml
+from pydantic import BaseModel, Field, ValidationError, field_validator
+
+from pipelex_api.errors import raise_validation_error
+from pipelex_api.limits import MAX_AGENT_SPEC_BYTES
+
+router = APIRouter(tags=["agent"])
+
+
+class BuildPipeSpecRequest(BaseModel):
+ pipe_type: str = Field(..., min_length=1, max_length=128, description="The pipe type (e.g. PipeLLM, PipeSequence, etc.).")
+ spec: dict[str, Any] = Field(..., description="JSON pipe specification.")
+
+ @field_validator("spec")
+ @classmethod
+ def _bound_spec_size(cls, value: dict[str, Any]) -> dict[str, Any]:
+ if len(json.dumps(value).encode("utf-8")) > MAX_AGENT_SPEC_BYTES:
+ msg = f"spec exceeds {MAX_AGENT_SPEC_BYTES // 1024} KiB limit"
+ raise ValueError(msg)
+ return value
+
+
+class BuildPipeSpecResponse(BaseModel):
+ success: bool = Field(default=True, description="Whether the operation was successful")
+ pipe_code: str = Field(..., description="The pipe code that was generated")
+ pipe_type: str = Field(..., description="The pipe type")
+ toml: str = Field(..., description="Generated TOML content for the pipe")
+
+
[email protected]("/build/pipe-spec")
+async def build_pipe_spec(request_data: BuildPipeSpecRequest) -> BuildPipeSpecResponse:
+ """Convert a JSON pipe spec to TOML format.
+
+ Two caller-mistake paths surface as a 422 here: a `ValidationError` from
+ Pydantic when the spec shape doesn't match the chosen pipe type, and a
+ `ValueError` from `parse_pipe_spec` when `pipe_type` is not one of the
+ known pipe types (documented in `parse_pipe_spec`'s docstring; raised at
+ exactly one site). Pipelex domain failures propagate untouched to the
+ global `PipelexError` handler in `pipelex_api.exception_handlers`.
+ """
+ try:
+ pipe_spec = parse_pipe_spec(request_data.spec, pipe_type=request_data.pipe_type)
+ toml_content = pipe_spec_to_toml(pipe_spec)
+
+ return BuildPipeSpecResponse(
+ success=True,
+ pipe_code=pipe_spec.pipe_code,
+ pipe_type=request_data.pipe_type,
+ toml=toml_content,
+ )
+ except (ValidationError, ValueError) as exc:
+ raise_validation_error(message=str(exc))
diff --git a/api/pipelex_api/routes/pipelex/build/__init__.py b/api/pipelex_api/routes/pipelex/build/__init__.py
new file mode 100644
index 000000000..979ea6b5f
--- /dev/null
+++ b/api/pipelex_api/routes/pipelex/build/__init__.py
@@ -0,0 +1,11 @@
+from fastapi import APIRouter
+
+from .inputs import router as inputs_router
+from .output import router as output_router
+from .runner import router as runner_router
+
+router = APIRouter()
+
+router.include_router(inputs_router)
+router.include_router(output_router)
+router.include_router(runner_router)
diff --git a/api/pipelex_api/routes/pipelex/build/inputs.py b/api/pipelex_api/routes/pipelex/build/inputs.py
new file mode 100644
index 000000000..71d39e838
--- /dev/null
+++ b/api/pipelex_api/routes/pipelex/build/inputs.py
@@ -0,0 +1,191 @@
+import json
+from typing import Annotated, Any, Literal, Self, Union
+
+from fastapi import APIRouter
+from fastapi.responses import JSONResponse
+from pipelex.core.pipes.inputs.exceptions import NoInputsRequiredError
+from pipelex.pipe_machinery.rendering.input_renderer import InputsTemplateFormat, render_inputs, render_inputs_toml
+from pipelex.pipeline.exceptions import ValidateBundleError
+from pydantic import BaseModel, Field, model_validator
+
+from pipelex_api.openapi_responses import PROBLEM_404_METHOD_PACKAGE, PROBLEM_501_METHOD_REF
+from pipelex_api.routes.pipelex.crate_ops import (
+ CrateInvalidReport,
+ RequestedPipe,
+ invalid_crate_report_response,
+ resolve_requested_crate,
+ resolve_requested_pipe,
+ teardown_current_library,
+)
+from pipelex_api.schemas.models import MthdsPipeRequest
+
+router = APIRouter(tags=["build"])
+
+INPUTS_GENERATED_MESSAGE = "Inputs template generated successfully"
+NO_INPUTS_MESSAGE = "This pipe declares no inputs — the template is empty."
+
+
+class BuildInputsRequest(MthdsPipeRequest):
+ """The inputs-template request: the shared closure + pipe selectors, plus the two rendering axes.
+
+ Both axes mirror `pipelex codegen inputs` exactly — `--format` and `--explicit` — and every
+ combination of them is served, as on the CLI.
+ """
+
+ format: InputsTemplateFormat = Field(
+ default=InputsTemplateFormat.JSON,
+ description="Template encoding. `json` returns the parsed template in `inputs`; `toml` returns the raw text in `inputs_toml`.",
+ )
+ explicit: bool = Field(
+ default=False,
+ description=(
+ "When true, emit the ceremonial `{concept, content}` envelope for every input. Defaults to false — the light, "
+ "signature-driven shape that smart inputs accepts (a bare string for a Text input, and so on)."
+ ),
+ )
+
+
+class BuildInputsValidReport(BaseModel):
+ """The 200 **valid** arm: the example inputs template for the requested pipe.
+
+ The template rides **one of two fields, chosen by `format`** — `inputs` (parsed object) for
+ `json`, `inputs_toml` (raw text) for `toml`. TOML cannot be carried as a parsed object without
+ losing what makes it worth asking for (its concept comments and key order), and the JSON case
+ must stay a real object, since that is what the deploy dialog and the SDKs consume. So the two
+ are separate, honestly-typed fields, and the unused one is omitted from the body entirely.
+
+ A pipe that declares no inputs is a *valid* verdict, not an error (the CLI likewise exits 0):
+ the template is simply empty, and `message` says so.
+ """
+
+ is_valid: Literal[True] = True
+ pipe_ref: str = Field(..., description="The qualified pipe the template was generated for — the resolved selector.")
+ requested_pipe_ref: str | None = Field(
+ default=None,
+ description=(
+ "The `pipe_ref` as submitted. Absent when it was omitted and defaulted — to the fetched package manifest's "
+ "`main_pipe` on a `method_ref` request, else to the closure's declared `main_pipe`."
+ ),
+ )
+ format: InputsTemplateFormat = Field(..., description="The template encoding (echo of the request).")
+ explicit: bool = Field(..., description="Whether the ceremonial envelope shape was emitted (echo of the request).")
+ inputs: dict[str, Any] | None = Field(
+ default=None,
+ description="The parsed inputs template — present exactly when `format` is `json`.",
+ )
+ inputs_toml: str | None = Field(
+ default=None,
+ description="The inputs template as TOML text — present exactly when `format` is `toml`.",
+ )
+ message: str = Field(default=INPUTS_GENERATED_MESSAGE, description="Status message")
+
+ @model_validator(mode="after")
+ def _template_field_matches_format(self) -> Self:
+ # The invariant the two-field shape exists to keep: the caller can read the field its own
+ # `format` names, without probing. A route bug that set the other one would be a silent
+ # contract break, so it fails loudly here instead.
+ match self.format:
+ case InputsTemplateFormat.JSON:
+ if self.inputs is None or self.inputs_toml is not None:
+ msg = "format='json' must carry `inputs` and no `inputs_toml`"
+ raise ValueError(msg)
+ case InputsTemplateFormat.TOML:
+ if self.inputs_toml is None or self.inputs is not None:
+ msg = "format='toml' must carry `inputs_toml` and no `inputs`"
+ raise ValueError(msg)
+ return self
+
+
+# Discriminated 200 response union: the `/validate` discipline — the verdict rides `is_valid`, never
+# the HTTP status.
+BuildInputsResponse = Annotated[Union[BuildInputsValidReport, CrateInvalidReport], Field(discriminator="is_valid")]
+
+
+def _render_report(*, requested: BuildInputsRequest, requested_pipe: RequestedPipe) -> BuildInputsValidReport:
+ """Render the requested pipe's declared inputs into the valid arm, on the `format` axis.
+
+ A pipe with no inputs raises `NoInputsRequiredError` out of the engine renderers. That is not a
+ failure — it is the honest answer "run this with nothing" — so it lands on the valid arm as an
+ empty template, mirroring the CLI's exit-0.
+ """
+ inputs: dict[str, Any] | None = None
+ inputs_toml: str | None = None
+ message: str = INPUTS_GENERATED_MESSAGE
+ match requested.format:
+ case InputsTemplateFormat.JSON:
+ try:
+ inputs = json.loads(render_inputs(requested_pipe.pipe, explicit=requested.explicit))
+ except NoInputsRequiredError:
+ inputs = {}
+ message = NO_INPUTS_MESSAGE
+ case InputsTemplateFormat.TOML:
+ try:
+ inputs_toml = render_inputs_toml(requested_pipe.pipe, explicit=requested.explicit)
+ except NoInputsRequiredError:
+ inputs_toml = ""
+ message = NO_INPUTS_MESSAGE
+ return BuildInputsValidReport(
+ pipe_ref=requested_pipe.ref,
+ requested_pipe_ref=requested.pipe_ref,
+ format=requested.format,
+ explicit=requested.explicit,
+ inputs=inputs,
+ inputs_toml=inputs_toml,
+ message=message,
+ )
+
+
+ "/build/inputs",
+ response_model=BuildInputsResponse,
+ # On top of the composite router's shared 401/413/422/500: the `method_ref` closure selector the
+ # envelope accepts but no server-side method registry resolves yet (shared with /resolve, /codegen).
+ responses={404: PROBLEM_404_METHOD_PACKAGE, 501: PROBLEM_501_METHOD_REF},
+)
+async def build_inputs(request_data: BuildInputsRequest) -> JSONResponse:
+ """Generate an example inputs template for a pipe (the inputs projection, per pipe).
+
+ Rides the **same static core** as `POST /resolve` and `POST /codegen`: the closure is resolved to
+ its normalized crate, the requested pipe is read live from the library that leaves loaded, and its
+ *declared* inputs are rendered — the exact projection `pipelex codegen inputs` writes, on both of
+ its axes (`format`, `explicit`).
+
+ Static is the point: a template is a read of the pipe's declared IO, so there is **no dry-run
+ sweep** here (that is `/validate`'s vocabulary, and `/build/runner`'s need). A valid verdict says
+ the closure is structurally sound and the template matches what the pipe declares — it is *not* a
+ promise the pipe runs. Ask `/validate` for that.
+
+ This projection is deliberately **not** a `/codegen` kind: the templates are user-editable
+ scaffolds, never stamped or locked, so they cannot ride the trust chain `/codegen`'s valid arm
+ promises (see `CodegenRouteKind`).
+
+ Response contract (the `/validate` discipline):
+
+ - **Valid verdict (200, `is_valid: true`):** the template, in `inputs` or `inputs_toml` per `format`.
+ - **Invalid verdict (200, `is_valid: false`):** the closure could not be parsed, loaded, or
+ validated — `validation_errors[]` from pipelex's one shared builder; no template exists.
+ - **No verdict (non-2xx):** a selection refusal — an unknown pipe ref, or an omitted `pipe_ref` that
+ nothing defaults (no fetched-manifest `main_pipe`, and a closure declaring no — or several —
+ `main_pipe`) — is an input 422 whose `error_type` is `EntryPipeNotFoundError` or
+ `EntryPipeAmbiguousError`; a malformed closure selector is a request-shape 422 problem+json; a
+ registry-form `method_ref` is a 501 until server-side method-registry resolution exists.
+
+ An omitted `pipe_ref` defaults the way a run by address does: to the fetched package manifest's
+ `main_pipe` on a `method_ref` request, else to the closure's own declared `main_pipe`.
+ """
+ try:
+ resolved = resolve_requested_crate(request_data)
+ except ValidateBundleError as validate_error:
+ return invalid_crate_report_response(validate_error.to_error_report())
+ try:
+ requested_pipe = resolve_requested_pipe(
+ resolved.crate,
+ pipe_ref=request_data.pipe_ref,
+ manifest_main_pipe=resolved.manifest_main_pipe,
+ )
+ report = _render_report(requested=request_data, requested_pipe=requested_pipe)
+ # exclude_none drops the template field the `format` did not select (and an absent
+ # `requested_pipe_ref`), so exactly the fields the caller's own request implies are present.
+ return JSONResponse(content=report.model_dump(mode="json", by_alias=True, exclude_none=True))
+ finally:
+ teardown_current_library()
diff --git a/api/pipelex_api/routes/pipelex/build/output.py b/api/pipelex_api/routes/pipelex/build/output.py
new file mode 100644
index 000000000..bb8f4c2ff
--- /dev/null
+++ b/api/pipelex_api/routes/pipelex/build/output.py
@@ -0,0 +1,162 @@
+import json
+from typing import Annotated, Any, Literal, Self, Union
+
+from fastapi import APIRouter
+from fastapi.responses import JSONResponse
+from pipelex.core.concepts.concept_representation_generator import ConceptRepresentationFormat
+from pipelex.pipe_machinery.rendering.output_renderer import render_output
+from pipelex.pipeline.exceptions import ValidateBundleError
+from pydantic import BaseModel, Field, model_validator
+
+from pipelex_api.errors import raise_validation_error
+from pipelex_api.openapi_responses import PROBLEM_404_METHOD_PACKAGE, PROBLEM_501_METHOD_REF
+from pipelex_api.routes.pipelex.crate_ops import (
+ CrateInvalidReport,
+ RequestedPipe,
+ invalid_crate_report_response,
+ resolve_requested_crate,
+ resolve_requested_pipe,
+ teardown_current_library,
+)
+from pipelex_api.schemas.models import MthdsPipeRequest
+
+router = APIRouter(tags=["build"])
+
+
+class BuildOutputRequest(MthdsPipeRequest):
+ """The output-representation request: the shared closure + pipe selectors, plus the format axis."""
+
+ format: ConceptRepresentationFormat = Field(
+ default=ConceptRepresentationFormat.SCHEMA,
+ description=(
+ "Representation to render. `schema` (JSON Schema) and `json` (example value) return a parsed object in "
+ "`output`; `python` returns Python source in `output_python`."
+ ),
+ )
+
+
+class BuildOutputValidReport(BaseModel):
+ """The 200 **valid** arm: the example output representation for the requested pipe.
+
+ The representation rides **one of two fields, chosen by `format`**, for the same reason
+ `/build/inputs` splits `inputs` / `inputs_toml`: `schema` and `json` are objects, `python` is
+ source text. (Before this split the route parsed *every* format as JSON, so `format=python` was a
+ hard 500 — it fed Python source to `json.loads`.)
+ """
+
+ is_valid: Literal[True] = True
+ pipe_ref: str = Field(..., description="The qualified pipe the representation was generated for — the resolved selector.")
+ requested_pipe_ref: str | None = Field(
+ default=None,
+ description=(
+ "The `pipe_ref` as submitted. Absent when it was omitted and defaulted — to the fetched package manifest's "
+ "`main_pipe` on a `method_ref` request, else to the closure's declared `main_pipe`."
+ ),
+ )
+ format: ConceptRepresentationFormat = Field(..., description="The representation format (echo of the request).")
+ output: dict[str, Any] | None = Field(
+ default=None,
+ description="The parsed output representation — present exactly when `format` is `schema` or `json`.",
+ )
+ output_python: str | None = Field(
+ default=None,
+ description="The output representation as Python source — present exactly when `format` is `python`.",
+ )
+ message: str = Field(default="Output representation generated successfully", description="Status message")
+
+ @model_validator(mode="after")
+ def _representation_field_matches_format(self) -> Self:
+ # Same invariant as `/build/inputs`: the caller reads the field its own `format` names.
+ match self.format:
+ case ConceptRepresentationFormat.SCHEMA | ConceptRepresentationFormat.JSON:
+ if self.output is None or self.output_python is not None:
+ msg = "format='schema'/'json' must carry `output` and no `output_python`"
+ raise ValueError(msg)
+ case ConceptRepresentationFormat.PYTHON:
+ if self.output_python is None or self.output is not None:
+ msg = "format='python' must carry `output_python` and no `output`"
+ raise ValueError(msg)
+ return self
+
+
+# Discriminated 200 response union: the `/validate` discipline — the verdict rides `is_valid`, never
+# the HTTP status.
+BuildOutputResponse = Annotated[Union[BuildOutputValidReport, CrateInvalidReport], Field(discriminator="is_valid")]
+
+
+def _render_report(*, requested: BuildOutputRequest, requested_pipe: RequestedPipe) -> BuildOutputValidReport:
+ """Render the requested pipe's declared output into the valid arm, on the `format` axis.
+
+ `render_output` raises a bare `ValueError` (documented in its docstring) when the pipe's output is
+ `native.Anything` and no concrete option can be determined — a fact about the *requested pipe*,
+ not about the closure, so it is a no-verdict 422 rather than an invalid-crate verdict.
+ """
+ output: dict[str, Any] | None = None
+ output_python: str | None = None
+ try:
+ rendered = render_output(requested_pipe.pipe, output_format=requested.format)
+ except ValueError as exc:
+ raise_validation_error(f"Cannot render the output representation of pipe '{requested_pipe.ref}': {exc}")
+ match requested.format:
+ case ConceptRepresentationFormat.SCHEMA | ConceptRepresentationFormat.JSON:
+ output = json.loads(rendered)
+ case ConceptRepresentationFormat.PYTHON:
+ output_python = rendered
+ return BuildOutputValidReport(
+ pipe_ref=requested_pipe.ref,
+ requested_pipe_ref=requested.pipe_ref,
+ format=requested.format,
+ output=output,
+ output_python=output_python,
+ )
+
+
+ "/build/output",
+ response_model=BuildOutputResponse,
+ # On top of the composite router's shared 401/413/422/500: the `method_ref` closure selector the
+ # envelope accepts but no server-side method registry resolves yet (shared with /resolve, /codegen).
+ responses={404: PROBLEM_404_METHOD_PACKAGE, 501: PROBLEM_501_METHOD_REF},
+)
+async def build_output(request_data: BuildOutputRequest) -> JSONResponse:
+ """Generate an example output representation for a pipe (the output projection, per pipe).
+
+ Rides the **same static core** as `POST /resolve`, `POST /codegen` and `POST /build/inputs`: the
+ closure is resolved to its normalized crate, the requested pipe is read live from the library that
+ leaves loaded, and its *declared* output is rendered.
+
+ Static is the point: the representation is a read of the pipe's declared IO, so there is **no
+ dry-run sweep** here. A valid verdict says the closure is structurally sound and the shape matches
+ what the pipe declares — it is *not* a promise the pipe runs. Ask `/validate` for that.
+
+ Response contract (the `/validate` discipline):
+
+ - **Valid verdict (200, `is_valid: true`):** the representation, in `output` or `output_python` per `format`.
+ - **Invalid verdict (200, `is_valid: false`):** the closure could not be parsed, loaded, or
+ validated — `validation_errors[]`; no representation exists.
+ - **No verdict (non-2xx):** a selection refusal — an unknown pipe ref, or an omitted `pipe_ref` that
+ nothing defaults (no fetched-manifest `main_pipe`, and a closure declaring no — or several —
+ `main_pipe`) — is an input 422 whose `error_type` is `EntryPipeNotFoundError` or
+ `EntryPipeAmbiguousError`; a pipe whose `native.Anything` output has no determinable shape, or a
+ malformed closure selector, is a request-shape 422 problem+json; a registry-form `method_ref` is a 501 until server-side
+ method-registry resolution exists.
+
+ An omitted `pipe_ref` defaults the way a run by address does: to the fetched package manifest's
+ `main_pipe` on a `method_ref` request, else to the closure's own declared `main_pipe`.
+ """
+ try:
+ resolved = resolve_requested_crate(request_data)
+ except ValidateBundleError as validate_error:
+ return invalid_crate_report_response(validate_error.to_error_report())
+ try:
+ requested_pipe = resolve_requested_pipe(
+ resolved.crate,
+ pipe_ref=request_data.pipe_ref,
+ manifest_main_pipe=resolved.manifest_main_pipe,
+ )
+ report = _render_report(requested=request_data, requested_pipe=requested_pipe)
+ # exclude_none drops the representation field the `format` did not select (and an absent
+ # `requested_pipe_ref`), so exactly the fields the caller's own request implies are present.
+ return JSONResponse(content=report.model_dump(mode="json", by_alias=True, exclude_none=True))
+ finally:
+ teardown_current_library()
diff --git a/api/pipelex_api/routes/pipelex/build/runner.py b/api/pipelex_api/routes/pipelex/build/runner.py
new file mode 100644
index 000000000..4b03209b9
--- /dev/null
+++ b/api/pipelex_api/routes/pipelex/build/runner.py
@@ -0,0 +1,235 @@
+from typing import Annotated, Literal, Union
+
+from fastapi import APIRouter, Request
+from fastapi.responses import JSONResponse
+from mthds.package.manifest.schema import MTHDS_STANDARD_VERSION
+from pipelex.base_exceptions import PipelexUnexpectedError
+from pipelex.builder.runner_code import generate_runner_code
+from pipelex.codegen.emission import build_stamped_projection
+from pipelex.codegen.emitters.naming import runtime_to_emitted_class_names
+from pipelex.codegen.emitters.target import CodegenKind, CodegenTarget
+from pipelex.codegen.emitters.types_emitter import emit_types
+from pipelex.codegen.lock import CODEGEN_LOCK_FILENAME
+from pipelex.codegen.resolved_concepts import resolve_concepts_from_crate
+from pipelex.core.pipes.variable_multiplicity import parse_concept_with_multiplicity
+from pipelex.interpreter_hub import get_current_library_id_or_none, get_library_manager
+from pipelex.libraries.crate_normalization import normalize_crate
+from pipelex.libraries.pipe.exceptions import EntryPipeNotFoundError, PipeNotFoundError
+from pipelex.mthds_parsing.pipelex_bundle_blueprint import PipelexBundleBlueprint
+from pipelex.pipeline.bundle_validator import DryRunOutput, DryRunStatus
+from pipelex.pipeline.exceptions import ValidateBundleError
+from pipelex.pipeline.validate_bundle import validate_bundle
+from pipelex.system.caller_identity import CallerIdentity
+from pipelex.tools.misc.package_utils import get_package_version
+from pipelex.tools.typing.pydantic_utils import empty_list_factory_of
+from pydantic import BaseModel, Field
+
+from pipelex_api.errors import raise_validation_error
+from pipelex_api.openapi_responses import PROBLEM_404_METHOD_PACKAGE, PROBLEM_501_METHOD_REF
+from pipelex_api.routes.pipelex.crate_ops import (
+ CrateInvalidReport,
+ GeneratedArtifact,
+ invalid_crate_report_response,
+ resolve_requested_pipe,
+ selected_files,
+ teardown_current_library,
+)
+from pipelex_api.routes.pipelex.pipeline import get_request_user_id
+from pipelex_api.schemas.models import ALLOW_SIGNATURES_DESCRIPTION, CallerAnalyticsGroupsMixin, MthdsPipeRequest
+
+router = APIRouter(tags=["build"])
+
+
+class BuildRunnerRequest(MthdsPipeRequest, CallerAnalyticsGroupsMixin):
+ """The runner-script request: the shared closure + pipe selectors, plus the sweep's `allow_signatures`.
+
+ Alone among the `/build/*` projections this route keeps `allow_signatures`, because alone among
+ them it still runs the dry-run sweep — the flag only ever parameterized that sweep.
+ """
+
+ allow_signatures: bool = Field(default=False, description=ALLOW_SIGNATURES_DESCRIPTION)
+
+
+class RunnerStructures(BaseModel):
+ """The typed-structures projection the runner script imports from (`from structures.structures import ...`).
+
+ The same stamped `python-structures` artifacts + `codegen.lock` a local `pipelex build runner`
+ scaffolds into `<output>/structures/` — write `artifacts` and the lock under `directory` and
+ the returned `python_code` runs against them, with the offline `codegen check` passing there.
+ """
+
+ directory: str = Field(default="structures", description="Directory (relative to the runner script) to write the artifacts and lock into.")
+ artifacts: list[GeneratedArtifact] = Field(
+ default_factory=empty_list_factory_of(GeneratedArtifact),
+ description="The stamped generated files (paths relative to `directory`).",
+ )
+ lock: str = Field(..., description="The lock content (TOML) tracking the artifact set — write verbatim inside `directory`.")
+ lock_filename: str = Field(default=CODEGEN_LOCK_FILENAME, description="Filename the lock content must be written as.")
+
+
+class BuildRunnerValidReport(BaseModel):
+ """The 200 **valid** arm: the runner script plus the structures projection it imports from."""
+
+ is_valid: Literal[True] = True
+ pipe_ref: str = Field(..., description="The qualified pipe the runner was generated for — the resolved selector.")
+ requested_pipe_ref: str | None = Field(
+ default=None,
+ description=(
+ "The `pipe_ref` as submitted. Absent when it was omitted and defaulted — to the fetched package manifest's "
+ "`main_pipe` on a `method_ref` request, else to the closure's declared `main_pipe`."
+ ),
+ )
+ python_code: str = Field(..., description="Generated Python script for running the pipeline, imports spelled with the emitted class names.")
+ structures: RunnerStructures = Field(..., description="The typed-structures projection the script imports from.")
+ message: str = Field(default="Runner code generated successfully", description="Status message")
+
+
+# Discriminated 200 response union: the `/validate` discipline — the verdict rides `is_valid`,
+# never the HTTP status (breaking change from the previous `success`-bool body + 422-on-invalid).
+BuildRunnerResponse = Annotated[Union[BuildRunnerValidReport, CrateInvalidReport], Field(discriminator="is_valid")]
+
+
+def _reject_if_requested_pipe_skipped(sweep_result: dict[str, DryRunOutput], *, pipe_ref: str) -> None:
+ """Reject when the *requested* pipe was SKIPPED (its cross-package dependency is unresolved).
+
+ `validate_pipes` records a pipe SKIPPED — rather than failing the whole sweep — when a controller
+ references a sub-pipe in a package not included in the request (the cross-package tolerance shared
+ with `/validate`). For a code-generation endpoint that is a footgun: `generate_runner_code` reads
+ only the pipe's own inputs/output and never resolves sub-pipes, so it would happily emit runner
+ code for a pipeline that cannot actually run. A SKIPPED requested pipe is a no-verdict condition
+ (its dependency closure is absent from the request, so nothing could be diagnosed) → request-shape
+ 422; unrelated SKIPPED pipes elsewhere in the bundle stay tolerated.
+ """
+ for output in sweep_result.values():
+ if pipe_ref != output.pipe_ref:
+ continue
+ match output.status:
+ case DryRunStatus.SKIPPED:
+ detail = output.error_message or "its dependencies could not be resolved"
+ raise_validation_error(f"Cannot generate runner code for pipe '{pipe_ref}': {detail}")
+ case DryRunStatus.SUCCESS | DryRunStatus.FAILURE:
+ return
+
+
+def _output_is_list(blueprints: list[PipelexBundleBlueprint], *, pipe_ref: str) -> bool:
+ """Whether the requested pipe's declared output carries a list multiplicity marker (mirrors the CLI).
+
+ Matched on the **qualified** ref. A blueprint's `pipe` map is keyed by bare code, so scanning by
+ bare code alone would return the first blueprint declaring that code — which in a multi-domain
+ closure can be a *different* pipe that merely shares the name, and whose multiplicity may differ.
+ The runner would then be generated with the wrong output handling. Compare the owning domain too.
+ """
+ domain_code, _, pipe_code = pipe_ref.rpartition(".")
+ for blueprint in blueprints:
+ if blueprint.domain != domain_code or not blueprint.pipe or pipe_code not in blueprint.pipe:
+ continue
+ output_parse = parse_concept_with_multiplicity(blueprint.pipe[pipe_code].output)
+ return output_parse.multiplicity is not None
+ return False
+
+
+ "/build/runner",
+ response_model=BuildRunnerResponse,
+ # On top of the composite router's shared 401/413/422/500: the `method_ref` closure selector the
+ # envelope accepts but no server-side method registry resolves yet (shared with /resolve, /codegen).
+ responses={404: PROBLEM_404_METHOD_PACKAGE, 501: PROBLEM_501_METHOD_REF},
+)
+async def build_runner(request: Request, request_data: BuildRunnerRequest) -> JSONResponse:
+ """Generate a Python runner script for a pipe, riding the codegen types projection.
+
+ The one `/build/*` projection that is **not** static: a runner script is a promise the pipe can
+ actually run, so this route keeps the dry-run sweep its siblings dropped (and with it
+ `allow_signatures`, which only ever parameterized that sweep). `validate_bundle` opens a single
+ library, loads the closure, sweeps, and on success leaves the library loaded + current; on failure
+ it tears it down itself. On the success path the crate is read from that library, the
+ `python-structures` projection is emitted and stamped, and the runner script is generated with the
+ **emitted** class names — the same flow as a local `pipelex build runner`.
+
+ The sweep is scoped to the requested pipe, so unrelated broken siblings do not block a good pipe.
+ When `pipe_ref` is omitted the scope is not settled before the closure loads, so the whole closure
+ is swept and the pipe then defaults the way a run by address does — to the fetched package
+ manifest's `main_pipe` on a `method_ref` request, else to the closure's own declared `main_pipe` —
+ a stricter verdict, and the honest one for a caller who did not say which pipe they meant.
+
+ Response contract (the `/validate` discipline): an invalid closure — including a failed dry-run of
+ the requested pipe — is a produced verdict: a **200** `is_valid: false` with the structured
+ `validation_errors[]`. Non-2xx is reserved for no-verdict conditions: a selection refusal (an
+ unknown pipe ref, an omitted `pipe_ref` that nothing defaults — no fetched-manifest `main_pipe`,
+ and a closure declaring no, or several, `main_pipe`), an input 422 whose `error_type` is
+ `EntryPipeNotFoundError` or `EntryPipeAmbiguousError`; a request-shape 422 for a requested pipe
+ whose cross-package dependencies are absent from the request; a 501 for a registry-form `method_ref`, auth, server
+ fault — RFC 7807 via the global handlers.
+ """
+ library_manager = get_library_manager()
+ selection = selected_files(request_data)
+
+ try:
+ # If this raises, validate_bundle has already torn down its own library — nothing to clean up here.
+ validate_result = await validate_bundle(
+ mthds_contents=[item.content for item in selection.files],
+ mthds_sources=[item.source for item in selection.files],
+ allow_signatures=request_data.allow_signatures,
+ dry_run_pipe_codes=[request_data.pipe_ref] if request_data.pipe_ref else None,
+ # The sweep is done for the caller, so its dry runs and `pipe_dry_run` event name them.
+ caller_identity=CallerIdentity.make_from_host(user_id=get_request_user_id(request), extras=request_data.analytics_groups),
+ )
+ except ValidateBundleError as validate_error:
+ return invalid_crate_report_response(validate_error.to_error_report())
+ except PipeNotFoundError as exc:
+ # The engine deliberately lets this one through untranslated (see `translate_to_validate_bundle_error`)
+ # so the caller can own it: a pipe ref naming nothing in the closure is an input 422, not an
+ # invalid-closure verdict — nothing about the closure is wrong. It is re-raised as the entry-lookup
+ # class the slice miss already is, so its `error_type` matches `resolve_requested_pipe`'s refusals.
+ msg = f"Pipe '{request_data.pipe_ref}' not found in the submitted closure: {exc}"
+ raise EntryPipeNotFoundError(msg) from exc
+
+ # Success: validate_bundle left its library loaded + current. Build everything from it, then own its teardown.
+ library_id = get_current_library_id_or_none()
+ try:
+ crate = library_manager.get_crate(library_id) if library_id else None
+ if crate is None:
+ # Unreachable after a successful in-memory validate (the blueprints were accumulated),
+ # so a None crate is an internal invariant break — a server fault (5xx), never a
+ # caller-facing verdict (mirrors resolve_crate_from_contents's identical guard).
+ msg = "library crate unavailable after a successful bundle load"
+ raise PipelexUnexpectedError(msg)
+ normalized_crate = normalize_crate(crate, mthds_version=MTHDS_STANDARD_VERSION)
+ requested_pipe = resolve_requested_pipe(
+ normalized_crate,
+ pipe_ref=request_data.pipe_ref,
+ manifest_main_pipe=selection.manifest_main_pipe,
+ )
+
+ # The sweep tolerates a cross-package unresolved dependency by recording the pipe SKIPPED
+ # instead of failing. Don't hand back runner code for the *requested* pipe in that state.
+ _reject_if_requested_pipe_skipped(validate_result.dry_run_result, pipe_ref=requested_pipe.ref)
+
+ emitted = emit_types(normalized_crate, target=CodegenTarget.PYTHON_STRUCTURES)
+ projection = build_stamped_projection(
+ emitted,
+ crate_fingerprint=normalized_crate.fingerprint,
+ engine_version=get_package_version(),
+ kind=CodegenKind.TYPES,
+ target=CodegenTarget.PYTHON_STRUCTURES,
+ )
+ class_name_overrides = runtime_to_emitted_class_names(resolve_concepts_from_crate(normalized_crate))
+
+ python_code = generate_runner_code(
+ pipe=requested_pipe.pipe,
+ output_multiplicity=_output_is_list(validate_result.blueprints, pipe_ref=requested_pipe.ref),
+ class_name_overrides=class_name_overrides,
+ )
+
+ report = BuildRunnerValidReport(
+ pipe_ref=requested_pipe.ref,
+ requested_pipe_ref=request_data.pipe_ref,
+ python_code=python_code,
+ structures=RunnerStructures(
+ artifacts=[GeneratedArtifact(path=stamped.filename, content=stamped.content) for stamped in projection.files],
+ lock=projection.lock_content,
+ ),
+ )
+ return JSONResponse(content=report.model_dump(mode="json", by_alias=True, exclude_none=True))
+ finally:
+ teardown_current_library()
diff --git a/api/pipelex_api/routes/pipelex/codegen.py b/api/pipelex_api/routes/pipelex/codegen.py
new file mode 100644
index 000000000..9deed3be4
--- /dev/null
+++ b/api/pipelex_api/routes/pipelex/codegen.py
@@ -0,0 +1,163 @@
+from enum import StrEnum
+from typing import Annotated, Literal, Self, Union
+
+from fastapi import APIRouter
+from fastapi.responses import JSONResponse
+from pipelex.codegen.emission import build_stamped_projection
+from pipelex.codegen.emitters.target import CodegenKind, CodegenTarget
+from pipelex.codegen.emitters.types_emitter import emit_types
+from pipelex.codegen.lock import CODEGEN_LOCK_FILENAME
+from pipelex.pipeline.exceptions import ValidateBundleError
+from pipelex.tools.misc.package_utils import get_package_version
+from pipelex.tools.typing.pydantic_utils import empty_list_factory_of
+from pydantic import BaseModel, Field, model_validator
+
+from pipelex_api.openapi_responses import PROBLEM_404_METHOD_PACKAGE, PROBLEM_501_METHOD_REF
+from pipelex_api.routes.pipelex.crate_ops import (
+ CrateInvalidReport,
+ GeneratedArtifact,
+ invalid_crate_report_response,
+ resolve_requested_crate,
+ teardown_current_library,
+)
+from pipelex_api.schemas.models import MthdsFilesRequest
+
+router = APIRouter(tags=["codegen"])
+
+
+class CodegenRouteKind(StrEnum):
+ """The projection kinds this route serves — the `kind` axis of the codegen request.
+
+ Membership follows the **trust chain**: a kind is served here exactly when its artifacts are
+ stamped and locked, so a client can write them verbatim and pass the offline `codegen check` —
+ the promise this route's valid arm makes by carrying a `lock`. Input templates are user-editable
+ scaffolds, never stamped or locked, so they cannot make that promise; they ride
+ `POST /build/inputs` instead and `inputs` is therefore not a kind here. Future per-pipe kinds
+ (`docs`, `tools`, `tests`) do emit tracked artifacts, so they join this enum and select their
+ pipe via `pipe_ref`. An unknown kind is a request-shape 422 listing the served set.
+ """
+
+ TYPES = "types"
+
+ @property
+ def engine_kind(self) -> CodegenKind:
+ """The engine-side `CodegenKind` this route kind projects."""
+ match self:
+ case CodegenRouteKind.TYPES:
+ return CodegenKind.TYPES
+
+
+class CodegenRequest(MthdsFilesRequest):
+ """The codegen request: the shared closure selector plus the two explicit projection axes."""
+
+ kind: CodegenRouteKind = Field(..., description="What to project. `types` projects the crate's concept set into typed models.")
+ target: CodegenTarget = Field(
+ ...,
+ description=(
+ "For whom: `ts-zod` (zod schemas + inferred types), `python-pydantic` (self-contained BaseModels), or "
+ "`python-structures` (runtime StructuredContent classes, for a Pipelex host)."
+ ),
+ )
+ pipe_ref: str | None = Field(
+ default=None,
+ max_length=512,
+ description="Pipe selector for per-pipe projection kinds. Not accepted for `types` (a concept-set-wide projection).",
+ )
+
+ @model_validator(mode="after")
+ def _pipe_ref_only_for_per_pipe_kinds(self) -> Self:
+ # `types` is concept-set-wide: silently ignoring a pipe_ref would mislead the caller into
+ # believing the artifacts were narrowed to one pipe. Request-shape error → 422. A future
+ # per-pipe kind adds its arm here and accepts the selector. The `return self` is
+ # unconditional so a non-raising future arm can never make pydantic take None as the model.
+ match self.kind:
+ case CodegenRouteKind.TYPES:
+ if self.pipe_ref is not None:
+ msg = "pipe_ref is not accepted for kind='types' (a concept-set-wide projection)"
+ raise ValueError(msg)
+ return self
+
+
+class CodegenValidReport(BaseModel):
+ """The 200 **valid** arm: the stamped artifact set plus its lock.
+
+ A client that writes each artifact and the lock verbatim reproduces a local
+ `pipelex codegen types` run byte-for-byte — the same stamps, the same `codegen.lock` — so the
+ offline `codegen check` passes on the written tree exactly as it would locally.
+ """
+
+ is_valid: Literal[True] = True
+ kind: CodegenRouteKind = Field(..., description="The projected kind (echo of the request).")
+ target: CodegenTarget = Field(..., description="The projection target (echo of the request).")
+ crate_fingerprint: str = Field(..., description="Fingerprint of the normalized crate the artifacts were generated from.")
+ engine_version: str = Field(..., description="The pipelex engine version that generated the artifacts.")
+ artifacts: list[GeneratedArtifact] = Field(
+ default_factory=empty_list_factory_of(GeneratedArtifact),
+ description="The stamped generated files.",
+ )
+ lock: str = Field(
+ ..., description=f"The `{CODEGEN_LOCK_FILENAME}` content (TOML) tracking the artifact set — write verbatim beside the artifacts."
+ )
+ lock_filename: str = Field(default=CODEGEN_LOCK_FILENAME, description="Filename the lock content must be written as.")
+ message: str = Field(default="Codegen artifacts generated successfully", description="Status message")
+
+
+# Discriminated 200 response union: the `/validate` discipline (see `POST /resolve`).
+CodegenResponse = Annotated[Union[CodegenValidReport, CrateInvalidReport], Field(discriminator="is_valid")]
+
+
+ "/codegen",
+ response_model=CodegenResponse,
+ # On top of the composite router's shared 401/413/422/500: the `method_ref` closure selector
+ # the envelope accepts but no server-side method registry resolves yet (shared with `/resolve`).
+ responses={404: PROBLEM_404_METHOD_PACKAGE, 501: PROBLEM_501_METHOD_REF},
+ # NOT tagged `x-mthds-protocol` — a Pipelex API extension, like `/resolve`. The MTHDS standard
+ # specifies the crate this reads (the Library Crate Format); it specifies no type projection, so
+ # every `target` here — `ts-zod` and `python-pydantic` no less than `python-structures` — is ours.
+)
+async def codegen_mthds(request_data: CodegenRequest) -> JSONResponse:
+ """Generate typed artifacts from a library closure (Pipelex API extension).
+
+ Resolves the closure to its normalized crate (exactly like `POST /resolve`), then projects it
+ through the requested `kind`/`target` axes and returns the **stamped** artifact set plus its
+ `codegen.lock` — everything a client needs to materialize a byte-identical local projection
+ and run the offline drift check. There is deliberately **no** server-side check route: the
+ check is offline by design.
+
+ Response contract (the `/validate` discipline):
+
+ - **Valid verdict (200, `is_valid: true`):** the artifacts + lock on the valid arm.
+ - **Invalid verdict (200, `is_valid: false`):** the library could not be parsed, loaded, or
+ validated — `validation_errors[]` from pipelex's one shared builder; no artifacts exist.
+ - **No verdict (non-2xx):** an unknown projection `kind`/`target`, a `pipe_ref` on a
+ concept-set-wide kind, or a malformed closure selector is a request-shape 422 problem+json;
+ `method_ref` is a 501 until server-side method registry resolution exists; auth is 401/403;
+ server fault is 5xx.
+ """
+ try:
+ # `types` is concept-set-wide: no pipe is selected, so the manifest's `main_pipe` beside the crate is unused.
+ # A future per-pipe kind takes it from the `ResolvedClosure` and hands it to `resolve_requested_pipe`.
+ crate = resolve_requested_crate(request_data).crate
+ except ValidateBundleError as validate_error:
+ return invalid_crate_report_response(validate_error.to_error_report())
+ try:
+ emitted = emit_types(crate, target=request_data.target)
+ projection = build_stamped_projection(
+ emitted,
+ crate_fingerprint=crate.fingerprint,
+ engine_version=get_package_version(),
+ kind=request_data.kind.engine_kind,
+ target=request_data.target,
+ )
+ report = CodegenValidReport(
+ kind=request_data.kind,
+ target=request_data.target,
+ crate_fingerprint=crate.fingerprint,
+ engine_version=get_package_version(),
+ artifacts=[GeneratedArtifact(path=stamped.filename, content=stamped.content) for stamped in projection.files],
+ lock=projection.lock_content,
+ )
+ return JSONResponse(content=report.model_dump(mode="json", by_alias=True))
+ finally:
+ teardown_current_library()
diff --git a/api/pipelex_api/routes/pipelex/crate_ops.py b/api/pipelex_api/routes/pipelex/crate_ops.py
new file mode 100644
index 000000000..4062f3874
--- /dev/null
+++ b/api/pipelex_api/routes/pipelex/crate_ops.py
@@ -0,0 +1,331 @@
+"""Shared crate-resolution plumbing for the `/resolve`, `/codegen`, `/pipe-io` and `/build/*` routes.
+
+They all select a closure the same way (inline `files[]` XOR `method_ref`), resolve it through the
+same engine core (`pipelex.pipeline.resolve_bundle.resolve_crate_from_contents`), and speak the same
+verdict vocabulary as `POST /validate`: a produced verdict is a 200 discriminated on `is_valid`, with
+the invalid arm carrying the structured `validation_errors[]` built by pipelex's one shared builder.
+This module holds the pieces they share so the envelopes cannot drift.
+
+The invalid arm here is the *crate* verdict: it deliberately omits `/validate`'s runnability facts
+(`pending_signatures`, `is_runnable`) — resolution is static (no dry-run sweep, matching
+`pipelex resolve`), so runnability is not part of its vocabulary. The per-pipe projections
+(`/build/{inputs,output}`) ride that same static core: a template is a read of the pipe's *declared*
+IO, so a valid verdict there says the closure is structurally sound, never that the pipe runs.
+`/build/runner` is the exception — it needs the dry-run sweep, so it keeps `validate_bundle`.
+"""
+
+from enum import StrEnum
+from typing import Literal, NamedTuple, NoReturn
+
+from fastapi.responses import JSONResponse
+from pipelex.base_exceptions import ErrorReport, ValidationErrorItem
+from pipelex.cogt.inference.error_classification import UserAction, UserActionKind
+from pipelex.interpreter_hub import clear_current_library, get_current_library_id_or_none, get_library_manager, get_required_entry_pipe
+from pipelex.libraries.library_crate import LibraryCrate
+from pipelex.libraries.pipe.exceptions import EntryPipeAmbiguousError, EntryPipeNotFoundError, PipeNotFoundError
+from pipelex.methods.method_ref import looks_like_method_ref
+from pipelex.pipe_machinery.pipe_abstract import PipeAbstract
+from pipelex.pipeline.resolve_bundle import resolve_crate_from_contents
+from pipelex.tools.typing.pydantic_utils import empty_list_factory_of
+from pydantic import BaseModel, Field
+
+from pipelex_api.error_types import ErrorType
+from pipelex_api.errors import raise_not_implemented
+from pipelex_api.method_source import fetch_method_mthds_files
+from pipelex_api.schemas.models import MthdsFileItem, MthdsFilesRequest
+
+
+class GeneratedArtifact(BaseModel):
+ """One generated file: its path relative to the client's chosen output root, and its full content."""
+
+ path: str = Field(..., description="Artifact path, relative to the output root the client writes into.")
+ content: str = Field(..., description="Complete file content, stamp header included — write verbatim.")
+
+
+class CrateInvalidReport(BaseModel):
+ """The 200 **invalid** arm shared by `/resolve` and `/codegen` — the crate-verdict vocabulary.
+
+ Same discipline as `/validate`'s `InvalidReport`: an invalid library is the *successful
+ product* of a diagnostic call (the request was well-formed; the library was not), so it rides
+ a 200 discriminated on `is_valid`, carrying the same structured `ValidationErrorItem`s the
+ local CLI and `/validate` emit for the identical failure.
+ """
+
+ is_valid: Literal[False] = False
+ """Discriminant of the invalid arm (mirrors the valid arms' `Literal[True]`)."""
+
+ validation_errors: list[ValidationErrorItem] = Field(
+ default_factory=empty_list_factory_of(ValidationErrorItem),
+ description="Per-error diagnostics, built by pipelex's one shared builder — non-empty on every invalid verdict.",
+ )
+ message: str = Field(default="MTHDS library could not be resolved", description="Human-readable summary of the verdict.")
+
+
+def invalid_crate_report_response(error_report: ErrorReport) -> JSONResponse:
+ """Render a produced "could not resolve" verdict as a 200 `CrateInvalidReport`.
+
+ `exclude_none` drops each item's unset locators so the wire items match the agent CLI's
+ byte-for-byte — the "one error item, two surfaces" guarantee `/validate` already keeps.
+ """
+ invalid_report = CrateInvalidReport(
+ validation_errors=error_report.validation_errors or [],
+ message=error_report.message,
+ )
+ return JSONResponse(content=invalid_report.model_dump(mode="json", serialize_as_any=True, by_alias=True, exclude_none=True))
+
+
+class SelectedFiles(NamedTuple):
+ """What the closure selector resolved to: the files, plus the fetched manifest's entry pipe when there is one."""
+
+ files: list[MthdsFileItem]
+ """The `.mthds` files forming the closure — inline `files[]` verbatim, or the fetched package's."""
+
+ manifest_main_pipe: str | None
+ """The fetched package manifest's `main_pipe` (a bare pipe code). Always None for inline `files[]`, which carry no manifest."""
+
+
+def selected_files(request_data: MthdsFilesRequest) -> SelectedFiles:
+ """The files the closure selector names: inline `files[]`, or an address `method_ref`'s package.
+
+ Shared by every route on the `files[]` envelope — including `/build/runner`, which cannot use
+ `resolve_requested_crate` (it needs `validate_bundle`'s dry-run sweep) but owes the caller the
+ same answer on every selector.
+
+ An **address-form** `method_ref` (`github.com/<owner>/<repo>[/<selector>][@<tag>]`) resolves
+ through the same fetch path the run routes use: the package's `.mthds` files come back as
+ `files[]` items with their real relative paths as per-file sources, and the manifest's
+ `main_pipe` rides beside them so the per-pipe projections can default their selector the way
+ a run by address does. Only `.mthds` data travels — the package's Python (if any) never loads
+ on these routes. The **registry form** (any non-address reference) stays reserved and keeps
+ its 501 until the packaging program's registry phase.
+
+ Raises:
+ ApiError: 501 for a registry-form `method_ref`; 422 for a fetched package this server
+ cannot accept.
+ MethodRefError subclasses: parse, fetch, location, and bounds failures on the address
+ form, rendered as `problem+json` by the global handler.
+ """
+ if request_data.method_ref is not None:
+ if looks_like_method_ref(request_data.method_ref):
+ fetched = fetch_method_mthds_files(request_data.method_ref)
+ return SelectedFiles(files=fetched.files, manifest_main_pipe=fetched.main_pipe)
+ raise_not_implemented(
+ "Registry-form method_ref resolution is not available on this server: no method registry is wired. "
+ "Use an address-form reference (a `github.com/...` address, e.g. `github.com/Pipelex/methods/[email protected]`) "
+ "or submit inline `files[]`.",
+ error_type=ErrorType.METHOD_REF_NOT_SUPPORTED,
+ )
+ return SelectedFiles(files=request_data.files or [], manifest_main_pipe=None)
+
+
+class ResolvedClosure(NamedTuple):
+ """A resolved closure: its normalized crate, the files it was resolved from, and the fetched manifest's entry pipe."""
+
+ crate: LibraryCrate
+ """The normalized library crate the closure resolved to."""
+
+ files: list[MthdsFileItem]
+ """The `.mthds` files the crate was resolved from, carried through from `selected_files` so no route fetches twice."""
+
+ manifest_main_pipe: str | None
+ """The fetched package manifest's `main_pipe`, carried through from `selected_files` (None for inline `files[]`)."""
+
+
+def resolve_requested_crate(request_data: MthdsFilesRequest) -> ResolvedClosure:
+ """Resolve the request's closure selector into a normalized library crate.
+
+ Inherits the engine core's **loaded-on-success contract**: on success the freshly opened
+ library is loaded and current (so a route can read live pipes from it) and the route owns its
+ teardown — call `teardown_current_library()` in a `finally`. On failure the core has already
+ torn down and restored.
+
+ The fetched manifest's `main_pipe` (when the selector was a `method_ref`) rides beside the
+ crate so a per-pipe route can hand it to `resolve_requested_pipe` — the crate itself only
+ knows the domains' own `main_pipe` declarations. The selected files ride beside it too, so a
+ route that echoes the closure (`/pipe-io` with `include_files`) reads them here rather than
+ calling `selected_files` again, which would fetch a `method_ref` a second time.
+
+ Raises:
+ ValidateBundleError: the produced negative verdict (route maps it to the 200 invalid arm).
+ ApiError: 501 for a registry-form `method_ref` (see `selected_files`).
+ MethodRefError subclasses: address-form fetch/location failures (see `selected_files`).
+ """
+ selection = selected_files(request_data)
+ crate = resolve_crate_from_contents(
+ mthds_contents=[item.content for item in selection.files],
+ mthds_sources=[item.source for item in selection.files],
+ )
+ return ResolvedClosure(crate=crate, files=selection.files, manifest_main_pipe=selection.manifest_main_pipe)
+
+
+class RequestedPipe(NamedTuple):
+ """The pipe a per-pipe projection was asked for: its resolved qualified ref and the live pipe."""
+
+ ref: str
+ """The qualified `domain.pipe_code` actually projected — always qualified, whatever the request spelled."""
+
+ pipe: PipeAbstract
+ """The live pipe, read from the library `resolve_requested_crate` left loaded + current."""
+
+
+class PipeSelectionMissKind(StrEnum):
+ """Why a selection chain link selected no pipe: the two failures the engine's entry lookup names."""
+
+ NOT_FOUND = "not_found"
+ AMBIGUOUS = "ambiguous"
+
+
+class PipeSelectionMiss(NamedTuple):
+ """A link of the pipe selection chain that selected no pipe, with the refusal a selection answers."""
+
+ kind: PipeSelectionMissKind
+ """Which entry-lookup failure this is, which picks the pipelex error class the refusal is raised as."""
+
+ message: str
+ """The detail of the `422` a selection that depends on this link raises."""
+
+ user_action: UserAction | None = None
+ """The fix to name instead of the error class's own, when the class's is wrong for this miss."""
+
+
+class _SelectorOrigin(StrEnum):
+ """Where a pipe selector came from, which is what its refusal must tell the caller."""
+
+ REQUEST = "request"
+ MANIFEST = "manifest"
+ CLOSURE = "closure"
+
+
+def resolve_requested_pipe(crate: LibraryCrate, *, pipe_ref: str | None, manifest_main_pipe: str | None) -> RequestedPipe:
+ """Select the pipe a per-pipe projection targets, defaulting to the manifest's, then the closure's, `main_pipe`.
+
+ The request's `pipe_ref` wins; omitted, the default chain (`select_default_pipe`) decides. Every
+ failed selection — an unknown ref, an ambiguous one, a chain that finds no entry pipe or several —
+ is an input-domain 422 rather than an invalid-crate verdict, since nothing about the *closure* is
+ wrong in any of them. It is raised as the engine's own entry-lookup error class (see
+ `_raise_selection_refusal`), so an unknown or ambiguous ref carries the `error_type` the run routes
+ answer for the same `pipe_code`. A chain finding no entry pipe or several has no run-route twin to
+ match: this route refuses both the way the pipe-selector design classifies them.
+
+ Must be called while the library `resolve_requested_crate` opened is still loaded + current.
+ """
+ if pipe_ref is not None:
+ selected = _select_entry_pipe(pipe_ref, origin=_SelectorOrigin.REQUEST)
+ else:
+ selected = select_default_pipe(crate, manifest_main_pipe=manifest_main_pipe)
+ if isinstance(selected, PipeSelectionMiss):
+ _raise_selection_refusal(selected)
+ return selected
+
+
+def _raise_selection_refusal(miss: PipeSelectionMiss) -> NoReturn:
+ """Raise a selection miss as the pipelex entry-lookup error class that names its failure.
+
+ A selection refusal must not share `ValidationError` with a malformed request, or a client has no
+ field to tell the two apart. So it is raised as `EntryPipeNotFoundError` or
+ `EntryPipeAmbiguousError`, the classes the engine's entry lookup raises and the run routes answer
+ with for an unknown or ambiguous `pipe_code`. The global `PipelexError` handler then renders it —
+ the class name as `error_type`, the INPUT domain as a 422, the class's `user_action` — exactly as
+ it renders the run routes' refusal. Both classes declare their messages caller-facing, which every
+ message built here honours: it names the caller's selector, the manifest's `main_pipe`, or the
+ qualified refs of the closure the caller submitted, and nothing from a host library.
+
+ The no-entry-pipe miss is a not-found and the several-`main_pipe`s miss an ambiguity, the way the
+ pipe-selector design classifies them. Neither is a typo in a pipe code, so each carries its own
+ `user_action`, which replaces the class's code-typo advice for that one error.
+ """
+ match miss.kind:
+ case PipeSelectionMissKind.NOT_FOUND:
+ raise EntryPipeNotFoundError(miss.message).as_caller_fault(user_action=miss.user_action)
+ case PipeSelectionMissKind.AMBIGUOUS:
+ raise EntryPipeAmbiguousError(miss.message).as_caller_fault(user_action=miss.user_action)
+
+
+def select_default_pipe(crate: LibraryCrate, *, manifest_main_pipe: str | None) -> RequestedPipe | PipeSelectionMiss:
+ """The selection chain without the request's `pipe_ref`: the method's own entry pipe, or why there is none.
+
+ The precedence is the run routes' (`pipeline.py`: `pipe_code or fetched.main_pipe`): a fetched
+ package's manifest `main_pipe` is the package author's declared entry pipe and is taken first;
+ only without one does the closure's own declaration decide. That last step mirrors `pipelex
+ codegen inputs` (`inputs_cmd.py::_default_main_pipe_ref`): the single declared `main_pipe`, with
+ **both** un-defaultable arms missed — a closure declaring none, and one declaring several across
+ domains. The chain stops at the first link present, so a manifest `main_pipe` the closure does
+ not declare, or declares in several domains, is a miss rather than a fall-through to the
+ closure's declarations. Inline `files[]` carry no manifest, so for them the chain is exactly the
+ closure-declared default.
+
+ It returns the miss instead of raising, so the one chain serves both `resolve_requested_pipe`
+ (which refuses with the miss's message) and `/pipe-io`'s `default_pipe_ref` (which states `null`),
+ and the selection and the reported default cannot drift apart. It is deliberately NOT
+ `/validate`'s `default_pipe_ref`, which is the run default and names the first of several
+ declaring domains where this chain refuses to choose.
+
+ Must be called while the library `resolve_requested_crate` opened is still loaded + current.
+ """
+ if manifest_main_pipe:
+ return _select_entry_pipe(manifest_main_pipe, origin=_SelectorOrigin.MANIFEST)
+ candidates = [f"{domain_code}.{domain.main_pipe}" for domain_code, domain in crate.domains.items() if domain.main_pipe]
+ if not candidates:
+ return PipeSelectionMiss(
+ kind=PipeSelectionMissKind.NOT_FOUND,
+ message="No `pipe_ref` was given and the closure declares no `main_pipe` — name the pipe explicitly.",
+ user_action=UserAction(
+ kind=UserActionKind.CHANGE_INPUT,
+ detail="Send a `pipe_ref` naming the pipe to select, since the closure declares no `main_pipe` to default to.",
+ ),
+ )
+ if len(candidates) > 1:
+ joined = ", ".join(sorted(candidates))
+ return PipeSelectionMiss(
+ kind=PipeSelectionMissKind.AMBIGUOUS,
+ message=f"No `pipe_ref` was given and the closure declares several `main_pipe`s ({joined}) — name the pipe explicitly.",
+ user_action=UserAction(
+ kind=UserActionKind.CHANGE_INPUT,
+ detail="Send a `pipe_ref` naming one of the declared `main_pipe`s.",
+ ),
+ )
+ return _select_entry_pipe(candidates[0], origin=_SelectorOrigin.CLOSURE)
+
+
+def _select_entry_pipe(selector: str, *, origin: _SelectorOrigin) -> RequestedPipe | PipeSelectionMiss:
+ """Look one selector up through the engine's entry lookup, the way every selection chain link does.
+
+ The returned `ref` is read back off the **resolved pipe**, never echoed from the selector: the
+ engine's entry lookup accepts a bare code too (falling back across domains), so a caller that
+ submits `"echo"` must still be told `"smoke.echo"` — the valid arms promise a qualified ref, and
+ echoing the request back would quietly break that promise for exactly the callers who leaned on
+ the fallback. A manifest `main_pipe` is always a bare code, so it rides that same fallback.
+
+ A bare code declared in several domains resolves to no pipe rather than to a first match, and
+ the miss says so — it names the candidates the engine lists — instead of calling the pipe
+ missing, which would contradict the candidates in the same sentence.
+ """
+ match origin:
+ case _SelectorOrigin.REQUEST:
+ described = f"Pipe '{selector}'"
+ scope = "the submitted closure"
+ case _SelectorOrigin.MANIFEST:
+ # The caller never spelled this selector — say where it came from, or the 422 names a pipe out of nowhere.
+ described = f"Pipe '{selector}' (the fetched package manifest's `main_pipe`)"
+ scope = "the package's closure"
+ case _SelectorOrigin.CLOSURE:
+ described = f"Pipe '{selector}' (the closure's declared `main_pipe`)"
+ scope = "the submitted closure"
+ try:
+ the_pipe = get_required_entry_pipe(pipe_code=selector)
+ except EntryPipeAmbiguousError as exc:
+ return PipeSelectionMiss(
+ kind=PipeSelectionMissKind.AMBIGUOUS,
+ message=f"{described} matches pipes in several domains of {scope}, so it selects none: {exc}",
+ )
+ except PipeNotFoundError as exc:
+ return PipeSelectionMiss(kind=PipeSelectionMissKind.NOT_FOUND, message=f"{described} not found in {scope}: {exc}")
+ return RequestedPipe(ref=the_pipe.pipe_ref, pipe=the_pipe)
+
+
+def teardown_current_library() -> None:
+ """Tear down the library `resolve_requested_crate` left loaded + current (success-path cleanup)."""
+ library_id = get_current_library_id_or_none()
+ clear_current_library()
+ if library_id is not None:
+ get_library_manager().teardown(library_id=library_id)
diff --git a/api/pipelex_api/routes/pipelex/pipe_io.py b/api/pipelex_api/routes/pipelex/pipe_io.py
new file mode 100644
index 000000000..849731916
--- /dev/null
+++ b/api/pipelex_api/routes/pipelex/pipe_io.py
@@ -0,0 +1,185 @@
+from typing import TYPE_CHECKING, Annotated, Any, Literal, Union
+
+from fastapi import APIRouter
+from fastapi.responses import JSONResponse
+from pipelex.interpreter_hub import get_own_pipes, get_pipe_library
+from pipelex.pipeline.build_pipe_io_artifacts import build_pipe_io_artifacts
+from pipelex.pipeline.exceptions import ValidateBundleError
+from pipelex.pipeline.input_form import InputForm, OutputForm
+from pipelex.pipeline.pipe_io_contracts import PipeIOContracts
+from pipelex.pipeline.validate_bundle import build_pending_signatures
+from pipelex.tools.typing.pydantic_utils import empty_list_factory_of
+from pydantic import BaseModel, Field
+
+from pipelex_api.openapi_responses import PROBLEM_404_METHOD_PACKAGE, PROBLEM_501_METHOD_REF
+from pipelex_api.routes.pipelex.crate_ops import (
+ CrateInvalidReport,
+ RequestedPipe,
+ invalid_crate_report_response,
+ resolve_requested_crate,
+ resolve_requested_pipe,
+ select_default_pipe,
+ teardown_current_library,
+)
+from pipelex_api.schemas.models import MthdsFileItem, MthdsPipeRequest
+
+if TYPE_CHECKING:
+ from pipelex.pipe_machinery.pipe_abstract import PipeAbstract
+
+router = APIRouter(tags=["pipe-io"])
+
+
+class PipeIORequest(MthdsPipeRequest):
+ """The pipe I/O request: the crate routes' closure selector and pipe selector, plus the whole-method and echo opt-ins.
+
+ The hosted catalog selector is replaced by `files` before the request reaches the runner, so this
+ request has no field for it. It takes no `views` either, since the valid arm always carries all
+ three artifacts.
+ """
+
+ # This docstring is published as the schema's description, so it must never name the hosted
+ # selector field: the runner's OpenAPI declares no such field, not even in prose, and
+ # `test_openapi_contract.py` pins the whole document free of that name.
+
+ all_pipes: bool = Field(
+ default=False,
+ description=(
+ "Describe every pipe the closure loads instead of the selected one. The artifact maps are then keyed by every "
+ "pipe, and the route never refuses for want of an entry pipe: `pipe_ref` on the valid arm is the requested ref, "
+ "else the method's own entry pipe, else `null`."
+ ),
+ )
+ include_files: bool = Field(
+ default=False,
+ description=(
+ "Echo the resolved closure's `.mthds` files on the valid arm, in the request's own `files[]` shape: the request's "
+ "files for inline `files[]`, the fetched package's `.mthds` files under their package-relative paths for a "
+ "`method_ref`. Absent from the response unless true."
+ ),
+ )
+
+
+class PipeIOValidReport(BaseModel):
+ """The 200 **valid** arm: the method's three I/O artifacts, with the selection and the runnability facts beside them.
+
+ The three maps share one key set: the resolved `pipe_ref` alone by default, every pipe the
+ closure loads under `all_pipes`. Each map is the standard's artifact under its neutral name, and
+ for a closure `/validate` also accepts it equals `/validate`'s same-named field restricted to the
+ same keys — both routes call the one builder, and both dump without dropping null members.
+ `is_valid: true` means what it means on `/resolve`: the closure parsed, loaded and passed static
+ validation. No dry run ran; that verdict stays `/validate`'s.
+ """
+
+ is_valid: Literal[True] = True
+ pipe_ref: str | None = Field(
+ ...,
+ description=(
+ "The qualified `domain.pipe_code` the selection resolved, read back off the resolved pipe and never echoed from "
+ "the request. `null` only under `all_pipes` when no pipe was requested and the method declares no single entry pipe."
+ ),
+ )
+ pipe_io_contracts: PipeIOContracts = Field(..., description="The standard's pipe I/O contracts, keyed by qualified `pipe_ref`.")
+ input_form: InputForm = Field(..., description="The standard's input-form descriptors, keyed by qualified `pipe_ref`.")
+ output_form: OutputForm = Field(..., description="The standard's output-form descriptors, keyed by qualified `pipe_ref`.")
+ default_pipe_ref: str | None = Field(
+ ...,
+ description=(
+ "The method's own entry pipe: the selection chain without the request's `pipe_ref` — the fetched package "
+ "manifest's `main_pipe`, else the closure's single `main_pipe` declaration. A stated `null` when that chain finds "
+ "none or several. Not `/validate`'s field of the same name, which is the run default."
+ ),
+ )
+ pending_signatures: list[str] = Field(
+ ...,
+ description="The qualified refs of every pipe of the closure still declared as a signature, exactly as on `/validate`.",
+ )
+ is_runnable: bool = Field(..., description="`not pending_signatures`, exactly as on `/validate`. No dry run backs it.")
+ # Never serialized from the model: the route attaches the echo itself, and only when asked, so the
+ # field is absent — not empty, not null — otherwise. Declared here so the published schema names it.
+ files: list[MthdsFileItem] = Field(
+ default_factory=empty_list_factory_of(MthdsFileItem),
+ description="The resolved closure's `.mthds` files, in the request's `files[]` shape. Present only with `include_files: true`.",
+ )
+
+
+# Discriminated 200 response union: a consumer pattern-matches the one mandatory `is_valid`
+# field to learn the verdict — the same discipline as `POST /validate` and `POST /resolve`.
+PipeIOResponse = Annotated[Union[PipeIOValidReport, CrateInvalidReport], Field(discriminator="is_valid")]
+
+
+ "/pipe-io",
+ response_model=PipeIOResponse,
+ # On top of the composite router's shared 401/413/422/500: the `method_ref` fetch outcomes it
+ # shares with `/resolve`. No structures 403: the route reads only a package's `.mthds` files.
+ responses={404: PROBLEM_404_METHOD_PACKAGE, 501: PROBLEM_501_METHOD_REF},
+ # NOT tagged `x-mthds-protocol`: it carries the standard's artifacts under their neutral names,
+ # but the route is a Pipelex API extension, and the flag marks the standard's five operations alone.
+)
+async def pipe_io(request_data: PipeIORequest) -> JSONResponse:
+ """Return a method's pipe I/O contracts, input form and output form, with no dry run (Pipelex API extension).
+
+ The closure resolves through the static core `/resolve` rides, a pipe is selected the way the
+ per-pipe routes select one, and the three artifacts are derived with `build_pipe_io_artifacts`,
+ the builder `/validate` and every run call — so a call costs one load and one derivation where
+ `/validate` dry-runs every pipe.
+
+ Response contract (the `/validate` discipline):
+
+ - **Valid verdict (200, `is_valid: true`):** the three artifact maps keyed by qualified `pipe_ref`,
+ beside `pipe_ref`, `default_pipe_ref`, `pending_signatures`, `is_runnable`, and `files` when
+ `include_files` is true.
+ - **Invalid verdict (200, `is_valid: false`):** the closure could not be parsed, loaded, or
+ statically validated — the crate verdict, carrying no artifact, no selection and no files.
+ - **No verdict (non-2xx):** a malformed body and neither or both closure selectors are
+ request-shape 422s (`ValidationError`); a selection refusal is an input 422 named for its failure,
+ `EntryPipeNotFoundError` for an unknown `pipe_ref` or a single-pipe request whose chain finds no
+ entry pipe, `EntryPipeAmbiguousError` for an ambiguous one or a chain that finds several; the
+ `method_ref` fetch outcomes are those of `/resolve` (404, 422, 501);
+ an artifact that cannot be derived (`PipeIOContractError`) is a 500. All RFC 7807
+ `application/problem+json` via the global handlers.
+ """
+ try:
+ resolved = resolve_requested_crate(request_data)
+ except ValidateBundleError as validate_error:
+ return invalid_crate_report_response(validate_error.to_error_report())
+ try:
+ default_pipe = select_default_pipe(resolved.crate, manifest_main_pipe=resolved.manifest_main_pipe)
+ default_pipe_ref = default_pipe.ref if isinstance(default_pipe, RequestedPipe) else None
+ pipe_ref: str | None
+ described_pipes: list[PipeAbstract]
+ if request_data.all_pipes:
+ # A whole-method answer needs no selection: a requested ref is still resolved (and refused
+ # when it names nothing), but a method with no single entry pipe is described all the same.
+ if request_data.pipe_ref is not None:
+ pipe_ref = resolve_requested_pipe(resolved.crate, pipe_ref=request_data.pipe_ref, manifest_main_pipe=resolved.manifest_main_pipe).ref
+ else:
+ pipe_ref = default_pipe_ref
+ # The closure's own pipes in load order, the order `/validate`'s report walks.
+ described_pipes = get_own_pipes()
+ else:
+ requested = resolve_requested_pipe(resolved.crate, pipe_ref=request_data.pipe_ref, manifest_main_pipe=resolved.manifest_main_pipe)
+ pipe_ref = requested.ref
+ described_pipes = [requested.pipe]
+ # Raises `PipeIOContractError` when a pipe's input or output JSON Schema cannot be rendered;
+ # it reaches the global handler as a no-verdict 500, exactly as on `/validate`.
+ artifacts = build_pipe_io_artifacts(described_pipes)
+ pending_signatures = build_pending_signatures(get_pipe_library().get_pipes_dict())
+ report = PipeIOValidReport(
+ pipe_ref=pipe_ref,
+ pipe_io_contracts=artifacts.pipe_io_contracts,
+ input_form=artifacts.input_form,
+ output_form=artifacts.output_form,
+ default_pipe_ref=default_pipe_ref,
+ pending_signatures=pending_signatures,
+ is_runnable=not pending_signatures,
+ )
+ # Dumped as `/validate` dumps its valid arm, never with `exclude_none`: that would strip the
+ # contracts' `item_count: null` and break the byte equality with `/validate`'s maps.
+ content: dict[str, Any] = report.model_dump(mode="json", serialize_as_any=True, by_alias=True, exclude={"files"})
+ if request_data.include_files:
+ # Each file is echoed in the request's own shape: a `source` the request omitted stays omitted.
+ content["files"] = [item.model_dump(mode="json", exclude_none=True) for item in resolved.files]
+ return JSONResponse(content=content)
+ finally:
+ teardown_current_library()
diff --git a/api/pipelex_api/routes/pipelex/pipeline.py b/api/pipelex_api/routes/pipelex/pipeline.py
new file mode 100644
index 000000000..83c61c248
--- /dev/null
+++ b/api/pipelex_api/routes/pipelex/pipeline.py
@@ -0,0 +1,946 @@
+from __future__ import annotations
+
+import hashlib
+import hmac
+import json
+from contextlib import contextmanager
+from pathlib import Path, PurePosixPath
+from typing import TYPE_CHECKING, Annotated, Any, NamedTuple, cast
+
+from fastapi import APIRouter, Depends, Request
+from fastapi.responses import JSONResponse
+from mthds.protocol.exceptions import PipelineRequestError
+from pipelex.config import get_config, is_pipe_func_sandbox_hosted
+from pipelex.core.pipes.pipe_output import PipeOutput
+from pipelex.pipe_run.delivery_assignment import DeliveryAssignment, StorageTarget, WebhookTarget
+from pipelex.pipe_run.pipe_run_protocol import PipeRunProtocol
+from pipelex.pipeline.pipeline_response import PipelexRunResultExecute, PipelexRunResultStart, RunState
+from pipelex.pipeline.pipeline_run_setup import pipeline_run_setup
+from pipelex.pipeline.runner import PipelexMTHDSProtocol
+from pipelex.reporting.usage_records import apply_tokens_usage_wire_shape
+from pipelex.runtime_bridge.exceptions import MissingBundleValidatorError, MissingOrchestratorError
+from pipelex.runtime_bridge.primitives.hydration import hydrate_working_memory
+from pipelex.runtime_hub import get_bundle_validator_registry, get_orchestrator_registry
+from pipelex.system.environment import get_required_env
+from pipelex.system.storage_scope import LOCAL_STORAGE_SCOPE, SINGLE_TENANT_USER_ID, validate_storage_scope_within_read_scope
+from pydantic import ValidationError
+from typing_extensions import override
+
+from pipelex_api.api_config import get_api_config, resolve_orchestration_mode
+from pipelex_api.bundle import ParsedBundle, materialize_parsed, parse_bundle
+from pipelex_api.error_types import ErrorType
+from pipelex_api.errors import raise_bad_request, raise_forbidden, raise_validation_error
+from pipelex_api.method_source import fetched_method_source
+from pipelex_api.middleware import request_id_of
+from pipelex_api.openapi_responses import (
+ PROBLEM_400_START_REQUIRES_ASYNC,
+ PROBLEM_403_RUN_POLICY,
+ PROBLEM_404_METHOD_PACKAGE,
+ PROBLEM_409_DUPLICATE_RUN,
+ PROBLEM_429,
+ PROBLEM_501_ASYNC_NOT_ENABLED,
+)
+from pipelex_api.routes.pipelex.utils import get_current_iso_timestamp
+from pipelex_api.schemas.models import (
+ PipelexApiExecuteRequest,
+ PipelexApiExecuteResponse,
+ PipelexApiStartRequest,
+ PipelexApiStartResponse,
+ PipelineApiExtras,
+ RunRequest,
+)
+
+if TYPE_CHECKING:
+ from collections.abc import Generator
+
+ from mthds.protocol.pipe_output import VariableMultiplicity
+ from mthds.protocol.pipeline_inputs import PipelineInputs
+ from mthds.protocol.working_memory import WorkingMemoryAbstract
+ from pipelex.base_exceptions import ErrorReport
+ from pipelex.core.memory.working_memory import WorkingMemory
+ from pipelex.methods.fetching import MethodProvenance
+ from pipelex.pipe_run.pipe_job import PipeJob
+ from pipelex.pipeline.validation_report import PipelexValidationReport
+ from pipelex.plugins.orchestrator_registry import OrchestratorProtocol
+ from pipelex.runtime_bridge.payloads import PipelexPipeRunOutput
+
+ from pipelex_api.security import RequestUser
+
+
+router = APIRouter(tags=["run"])
+
+
+def get_request_user_id(request: Request) -> str:
+ """The caller this run is attributed to, and the owner its storage is keyed by.
+
+ **There is no `anonymous` fallback any more, and its removal is the point.**
+ This used to return the literal `"anonymous"` whenever `request.state.user`
+ was unset, which is reached on every auth path that establishes no
+ per-caller identity. That string then became the first segment of every
+ storage key the run wrote, so a deployment serving many callers put all of
+ them in one namespace where each could read the others' outputs — and it
+ looked like a working request the whole way through.
+
+ An identity-bearing deployment cannot get here without a user: `verify_jwt`
+ and `verify_api_key` raise on a bad token, and `no_auth` now raises when
+ `TRUST_FORWARDED_IDENTITY_HEADERS` is on and no id was forwarded. So a
+ missing user means the deployment declared it has no user model
+ (`AUTH_MODE=none` with no trusted proxy, or the shared static key), which is
+ a single tenant by configuration rather than an unknown caller.
+ """
+ user: RequestUser | None = getattr(request.state, "user", None)
+ return user.user_id if user else SINGLE_TENANT_USER_ID
+
+
+def _resolve_storage_scope(request: Request, *, requested: str | None) -> str:
+ """Where this run's bytes go — the host's value, or the caller's own id.
+
+ **Scope is data, not identity**, which is why it arrives in the BODY while
+ `user_id` arrives on a trusted header. The runtime needs to know where to
+ write, not who to trust, so a multi-tenant host computes this where it knows
+ its own tenancy (`<org>/<method>/<run>` on hosted Pipelex) and sends it.
+
+ The fallback is the CALLER'S OWN ID, deliberately, and not a shared constant.
+ This runner used to derive the prefix from `user_id` internally; removing
+ that coupling is the point of the change, but the safe default when a
+ deployment says nothing is still one namespace per caller. A shared literal
+ here would recreate the `anonymous/` bug in a new spelling — every caller of
+ an identity-bearing deployment writing into one namespace, each able to read
+ the others' outputs, and looking like a working request throughout.
+
+ A single-tenant deployment therefore gets `single-tenant/…` by configuration
+ rather than by accident, and a multi-tenant one that forgets to send a scope
+ still isolates its callers.
+ """
+ return requested or get_request_user_id(request)
+
+
+def _resolve_read_scope(request: Request, *, requested: str | None) -> str | None:
+ """What this run may read — the host's value, the caller's own id, or everything.
+
+ A sent value is the host's and is taken as it is. The fallback mirrors the storage
+ scope's (design DR2 of the read-scope campaign): when the field is omitted, a deployment
+ that identifies its callers scopes the run to the caller's own id, which is also where
+ their writes land by default, and a single-tenant deployment runs unscoped. That default
+ bounds a caller only where the host writes the body: a caller reaching a `jwt`
+ deployment directly can send any read scope, as it can send any storage scope. On a
+ multi-tenant host that forgets the field, the fallback fails closed: the host's own
+ storage scope lies under no caller's id, so the run is refused rather than reading
+ across tenants.
+ """
+ if requested is not None:
+ return requested
+ user: RequestUser | None = getattr(request.state, "user", None)
+ return user.user_id if user else None
+
+
+class _RunScopes(NamedTuple):
+ storage_scope: str
+ read_scope: str | None
+
+
+def _resolve_run_scopes(request: Request, *, extras: PipelineApiExtras) -> _RunScopes:
+ """Resolve the run's storage and read scopes, and refuse a pair the run could not work under.
+
+ The runtime refuses a storage scope outside the read scope, and the local storage
+ sentinel beside any read scope, with a bare `ValueError` from inside the run, which
+ would answer 500. Checking the resolved pair here answers the caller's mistake with a
+ 422 naming the field, before any method is fetched or library loaded.
+ """
+ storage_scope = _resolve_storage_scope(request, requested=extras.storage_scope)
+ read_scope = _resolve_read_scope(request, requested=extras.read_scope)
+ if read_scope is not None:
+ if storage_scope == LOCAL_STORAGE_SCOPE:
+ raise_validation_error(
+ message=f"A run with a read_scope must pass its own storage_scope, not the local sentinel {LOCAL_STORAGE_SCOPE!r}.",
+ error_type=ErrorType.INVALID_READ_SCOPE,
+ )
+ try:
+ validate_storage_scope_within_read_scope(storage_scope=storage_scope, read_scope=read_scope)
+ except ValueError as exc:
+ origin = "sent" if extras.read_scope is not None else "defaulted to the caller's id"
+ raise_validation_error(
+ message=f"{exc} The read_scope {read_scope!r} was {origin}, and the storage_scope is {storage_scope!r}.",
+ error_type=ErrorType.INVALID_READ_SCOPE,
+ )
+ return _RunScopes(storage_scope=storage_scope, read_scope=read_scope)
+
+
+def _completion_signature(pipeline_run_id: str) -> str:
+ """Compute the HMAC-SHA256 signature for an async completion callback.
+
+ The signer (this server) and the verifier (your callback receiver) must
+ share the same `COMPLETION_CALLBACK_SECRET`. The signature is per-run and
+ the secret never travels — only the one-way hash does.
+ """
+ secret = get_required_env("COMPLETION_CALLBACK_SECRET")
+ return hmac.new(
+ secret.encode("utf-8"),
+ pipeline_run_id.encode("utf-8"),
+ hashlib.sha256,
+ ).hexdigest()
+
+
+def _pipe_output_from_run_output(run_output: PipelexPipeRunOutput) -> PipeOutput:
+ """Rehydrate an orchestrator's JSON-safe `PipelexPipeRunOutput` into a typed `PipeOutput`.
+
+ The `OrchestratorRegistry` answers with the JSON-safe boundary payload (the same shape
+ that crosses the Temporal worker boundary), produced by `serialize_completed_output`.
+ `/execute` returns the FULL output, so the synchronous path reverses that serialization
+ here, restoring the rich `PipeOutput` the base `execute` then wraps in
+ `PipelexRunResultExecute`:
+
+ - `working_memory` is rebuilt via `hydrate_working_memory` — the same routine the
+ Temporal workers use — so it must run while the run library (hence the scoped
+ `ClassRegistry`) is still open; the base `execute` keeps it open until after the run
+ returns, which is exactly this call site.
+ - `graph_spec` / `pipe_io_artifacts` / `tokens_usages` are validated back from their
+ `model_dump(mode="json")` dumps with `strict=False`: the orchestrator dumped them in JSON mode (e.g.
+ `GraphSpec.created_at` became an ISO string), and those models are `strict=True`, so a
+ strict re-validation would reject the string. `strict=False` is the correct tool for
+ reversing our own trusted JSON dump — it is a round-trip, not untrusted ingest.
+
+ Routing DIRECT through this serialize→rehydrate round-trip is intentional: it keeps
+ `/execute` on the SAME per-call dispatch seam as `/start` and `/validate` (no per-mode
+ branch), at the cost of one in-process re-serialization of the working memory.
+ """
+ return PipeOutput.model_validate(
+ {
+ "working_memory": hydrate_working_memory(run_output.output_dict),
+ "pipeline_run_id": run_output.pipeline_run_id,
+ "graph_spec": run_output.graph_spec_dump,
+ "graph_assembly_error": run_output.graph_assembly_error,
+ "pipe_io_artifacts": run_output.pipe_io_artifacts_dump,
+ "pipe_io_artifacts_error": run_output.pipe_io_artifacts_error,
+ "tokens_usages": run_output.tokens_usages_dump,
+ "usage_assembly_error": run_output.usage_assembly_error,
+ },
+ strict=False,
+ )
+
+
+class _OrchestratorPipeRun(PipeRunProtocol):
+ """Adapts a mode-selected orchestrator to the `PipeRunProtocol` the base `execute` drives.
+
+ `ApiRunner.execute` injects one of these as `self._pipe_run` so the base `execute` retains
+ ALL of its run lifecycle (library setup/teardown, tracer close, pipeline-manager cleanup,
+ telemetry, error mapping) while the actual dispatch goes through the per-request
+ `orchestration_mode`'s orchestrator instead of the boot-global pipe-run slot. The
+ orchestrator's JSON-safe output is rehydrated back into the rich `PipeOutput` the base expects.
+
+ The blocking wait-semantics is intrinsic to `orchestrator.execute` (the protocol's BLOCKING arm —
+ it awaits completion and returns the completed-run `PipelexPipeRunOutput`); `/execute` is
+ synchronous and always drives this arm, so there is no delivery axis to thread here.
+ """
+
+ def __init__(self, *, orchestrator: OrchestratorProtocol) -> None:
+ self._orchestrator = orchestrator
+
+ @override
+ async def run(self, pipe_job: PipeJob, *, delivery_assignment: DeliveryAssignment | None = None) -> PipeOutput:
+ run_output = await self._orchestrator.execute(pipe_job=pipe_job, delivery_assignment=delivery_assignment)
+ return _pipe_output_from_run_output(run_output)
+
+
+class ApiRunner(PipelexMTHDSProtocol):
+ """API runner that dispatches `execute`, `start`, and `validate` through the per-call plugin registries.
+
+ Every surface resolves the deployment's `orchestration_mode` (config default + optional
+ per-request override) and dispatches through a per-call hub registry: `execute` runs a
+ top-level pipe through the `OrchestratorRegistry`'s blocking `execute` arm and returns the
+ full output, `start` enqueues one through the same registry's fire-and-forget `start` arm,
+ `validate_verdict` produces a validation verdict through the `BundleValidatorRegistry`. On the
+ orchestrator-agnostic base that means `direct` in-process; a `temporal` mode dispatches to a
+ worker when `pipelex-temporal` is installed and selected. The base names no orchestrator and
+ imports no orchestrator SDK; a mode with no registered arm fails loud with the matching
+ `Missing*Error` (carrying the install hint). Delivery is endpoint-intrinsic — the caller never
+ chooses it; only the backend is resolved per request. Dispatch changes the BACKEND, never the
+ artifact shapes — every operation answers with the same canonical models as the local runtime.
+ """
+
+ @override
+ async def execute(
+ self,
+ pipe_code: str | None = None,
+ mthds_contents: list[str] | None = None,
+ inputs: PipelineInputs | WorkingMemoryAbstract[Any] | None = None,
+ output_name: str | None = None,
+ output_multiplicity: VariableMultiplicity | None = None,
+ dynamic_output_concept_ref: str | None = None,
+ extra: dict[str, Any] | None = None,
+ delivery_assignment: DeliveryAssignment | None = None,
+ request_id: str | None = None,
+ requested_orchestration_mode: str | None = None,
+ ) -> PipelexRunResultExecute:
+ """Execute a method synchronously, dispatching by the resolved `orchestration_mode`.
+
+ Symmetric with `start`: the effective `orchestration_mode` is resolved FIRST (config default
+ + optional per-request override, so a forbidden override is refused with a 403 before any
+ library load), then the run is dispatched through the hub's `OrchestratorRegistry` instead
+ of the boot-global pipe-run slot. `direct` runs in-process on this agnostic base; a
+ `temporal` mode dispatches the whole job to a worker and awaits it. A mode with no registered
+ orchestrator fails loud with `MissingOrchestratorError` (carrying the install hint).
+
+ `/execute` is synchronous — it returns the full output — so it drives the orchestrator's
+ blocking `execute` arm regardless of backend. Wait-semantics is endpoint-intrinsic, never
+ requestable, so there is nothing for the caller to get wrong here (the fire-and-forget arm
+ is `/start`'s, gated there by an honest capability check).
+
+ The orchestrator is injected as this runner's `_pipe_run` so the inherited base `execute`
+ keeps the entire run lifecycle (library setup/teardown, tracer close, pipeline-manager
+ cleanup, telemetry, error mapping); only the dispatch backend and the output rehydration
+ (`_OrchestratorPipeRun`) change. `request_id` is an API-layer extra threaded into
+ `RunMetadata.request_id` for log correlation, so it reaches the job a worker is handed.
+ `requested_orchestration_mode` is the optional per-request backend override
+ (`PipelineApiExtras.orchestration_mode`).
+ """
+ # Resolve the effective orchestration mode FIRST — a per-request override the deployment
+ # policy forbids is refused (403) here, before any library load / run registration. Mirrors start().
+ orchestration_mode = resolve_orchestration_mode(requested_orchestration_mode, config=get_api_config())
+ orchestrator = get_orchestrator_registry().get_optional(mode=orchestration_mode)
+ if orchestrator is None:
+ raise MissingOrchestratorError(mode=orchestration_mode)
+
+ # Dispatch the run through the mode-selected orchestrator by injecting it as this runner's
+ # PipeRun, then delegate to the base execute, which owns the full run lifecycle. The
+ # ApiRunner is constructed per request, so mutating _pipe_run here is request-scoped.
+ # `/execute` is synchronous, so it drives the orchestrator's BLOCKING `execute` arm.
+ self._pipe_run = _OrchestratorPipeRun(orchestrator=orchestrator)
+ return await super().execute(
+ pipe_code=pipe_code,
+ mthds_contents=mthds_contents,
+ inputs=inputs,
+ output_name=output_name,
+ output_multiplicity=output_multiplicity,
+ dynamic_output_concept_ref=dynamic_output_concept_ref,
+ extra=extra,
+ delivery_assignment=delivery_assignment,
+ request_id=request_id,
+ )
+
+ @override
+ async def start(
+ self,
+ pipe_code: str | None = None,
+ mthds_contents: list[str] | None = None,
+ inputs: PipelineInputs | WorkingMemoryAbstract[Any] | None = None,
+ output_name: str | None = None,
+ output_multiplicity: VariableMultiplicity | None = None,
+ dynamic_output_concept_ref: str | None = None,
+ extra: dict[str, Any] | None = None,
+ pipeline_run_id: str | None = None,
+ callback_urls: list[str] | None = None,
+ request_id: str | None = None,
+ requested_orchestration_mode: str | None = None,
+ ) -> PipelexRunResultStart:
+ """Start a method execution asynchronously without waiting for completion.
+
+ Dispatch is orchestrator-agnostic: the rich `PipeJob` is built locally (so
+ `request_id`, `output_multiplicity`, `dynamic_output_concept_ref`, the run
+ registration, and telemetry all survive) and then handed to the resolved
+ `orchestration_mode`'s orchestrator via its fire-and-forget `start` arm, through the
+ hub's `OrchestratorRegistry`. The base imports no `temporalio` / orchestrator SDK; the
+ async-capable Temporal arm (returning a `workflow_id` immediately) is contributed by the
+ `pipelex-temporal` plugin when installed.
+
+ `/start` is genuinely fire-and-forget, so it is HONEST about its capability: the resolved
+ mode's orchestrator is looked up and its `supports_fire_and_forget` checked BEFORE any
+ library load. A blocking-only orchestrator (the in-process `direct` base) cannot honor
+ async delivery, so it is refused with a 400 (`START_REQUIRES_ASYNC_ORCHESTRATION`) — use
+ `/execute` — rather than silently running blocking and acking. A mode with no registered
+ orchestrator fails loud with `MissingOrchestratorError` (carrying the install hint), also
+ before any library load.
+
+ `pipeline_run_id` is the client-supplied run identifier — this source-available runner
+ honors it (protocol: implementations MAY decline it, but then MUST 422;
+ we accept it, and `StartAck.pipeline_run_id` echoes it back as authoritative).
+ `callback_urls` is THIS server's extension (completion webhooks) — the wire
+ layer validates it (`PipelineApiExtras`) and passes it here by name.
+ `extra` is the protocol's generic extension slot; this runner's wire
+ extras are parsed by the route layer, so nothing reaches it — a
+ non-empty value is an in-process misuse and is rejected. `request_id`
+ is an API-layer extra threaded into `RunMetadata.request_id` for log
+ correlation, so it reaches the job a worker is handed. `requested_orchestration_mode` is the optional per-request backend override
+ (`PipelineApiExtras.orchestration_mode`); it is resolved against the deployment's
+ `api.toml` policy and a forbidden override is refused with a 403.
+ """
+ if extra:
+ msg = f"ApiRunner defines no extension args beyond its named ones; got {sorted(extra)}."
+ raise PipelineRequestError(msg)
+ # Resolve the effective orchestration mode FIRST — a per-request override the deployment
+ # policy forbids is refused (403) here. Then look up the orchestrator and check its async
+ # capability: `/start` is fire-and-forget, so a blocking-only orchestrator (direct on the
+ # agnostic base) is refused HONESTLY with a 400 instead of silently running blocking and
+ # acking. Both gates run BEFORE pipeline_run_setup so a doomed request never loads a library.
+ orchestration_mode = resolve_orchestration_mode(requested_orchestration_mode, config=get_api_config())
+ orchestrator = get_orchestrator_registry().get_optional(mode=orchestration_mode)
+ if orchestrator is None:
+ raise MissingOrchestratorError(mode=orchestration_mode)
+ if not orchestrator.supports_fire_and_forget:
+ msg = (
+ f"Orchestration mode '{orchestration_mode}' cannot honor fire-and-forget delivery: /start requires an "
+ f"async-capable orchestration, and this deployment has none. Use /execute (synchronous) instead."
+ )
+ raise_bad_request(msg, error_type=ErrorType.START_REQUIRES_ASYNC_ORCHESTRATION)
+ created_at = get_current_iso_timestamp()
+ pipelex_inputs: PipelineInputs | WorkingMemory | None = cast("PipelineInputs | WorkingMemory | None", inputs)
+
+ execution_config = self.execution_config or get_config().interpreter.pipeline_execution
+ # Wire and runtime share the `pipeline_run_id` name (master D1 as
+ # revised — the id rename was reversed).
+ pipe_job, resolved_pipeline_run_id, _ = await pipeline_run_setup(
+ execution_config=execution_config,
+ library_id=self.library_id,
+ library_dirs=self.library_dirs,
+ pipe_code=pipe_code,
+ mthds_contents=mthds_contents,
+ bundle_uris=self.bundle_uris,
+ inputs=pipelex_inputs,
+ output_name=output_name,
+ output_multiplicity=output_multiplicity,
+ dynamic_output_concept_ref=dynamic_output_concept_ref,
+ pipe_run_mode=self.pipe_run_mode,
+ user_id=self.user_id,
+ storage_scope=self.storage_scope,
+ read_scope=self.read_scope,
+ # The base `execute` threads this itself; `start` builds its job
+ # here, so a group left out of this call is dropped with no error
+ # and the run's spans lose their groups while the ack still says 202.
+ extras=self.extras,
+ pipeline_run_id=pipeline_run_id,
+ request_id=request_id,
+ )
+
+ delivery_assignment = DeliveryAssignment(
+ # NO `key_prefix` — the runtime owns the `results/` leaf.
+ #
+ # This used to say `key_prefix="results"`, from the layout where the
+ # executor built `{user_id}/{key_prefix}{pipeline_run_id}` and the
+ # caller supplied the leaf. It now builds
+ # `{storage_scope}/{key_prefix}results`, so passing it here wrote
+ # every run's output to `<scope>/results/results/` — valid, stable,
+ # and wrong, with nothing failing to say so.
+ #
+ # `key_prefix` remains the caller's slot for an EXTRA level between
+ # the scope and the leaf; it is not where the leaf itself comes from.
+ storage=StorageTarget(),
+ # The completion payload's wire fields (`pipeline_run_id`/`state`,
+ # plus the transitional `status` alias) are written per delivery by
+ # pipelex's DeliveryExecutor — they are reserved keys on
+ # WebhookTarget.payload, so nothing is injected here.
+ webhooks=[
+ WebhookTarget(
+ url=url,
+ headers={"X-Completion-Signature": _completion_signature(resolved_pipeline_run_id)},
+ )
+ for url in callback_urls
+ ]
+ if callback_urls
+ else [],
+ )
+
+ # Dispatch the locally-built job through the resolved mode's orchestrator (looked up and
+ # capability-checked above) via its fire-and-forget `start` arm — the same final dispatch
+ # `run_pipe_via_bridge` performs, but fed the rich PipeJob instead of the lossy
+ # `PipelexPipeRunInput` (which carries no request_id / output_multiplicity /
+ # dynamic_output_concept_ref and skips run registration + telemetry). `start` genuinely
+ # enqueues the job and returns a `PipelexPipeDispatchAck` (ids only) immediately.
+ dispatch_ack = await orchestrator.start(pipe_job=pipe_job, delivery_assignment=delivery_assignment)
+
+ return PipelexRunResultStart(
+ pipeline_run_id=resolved_pipeline_run_id,
+ created_at=created_at,
+ state=RunState.STARTED,
+ workflow_id=dispatch_ack.workflow_id,
+ )
+
+ async def validate_verdict(
+ self,
+ *,
+ mthds_contents: list[str],
+ mthds_sources: list[str] | None,
+ allow_signatures: bool,
+ requested_orchestration_mode: str | None,
+ graph_pipe_code: str | None,
+ ) -> PipelexValidationReport | ErrorReport:
+ """Validate MTHDS bundles, returning the verdict as a value (the route maps it to a 200).
+
+ Mode-aware, mirroring `start`: the effective `orchestration_mode` is resolved FIRST (config
+ default + optional per-request override, so a forbidden override is refused with a 403
+ before any library load), then dispatched through the hub's `BundleValidatorRegistry`.
+ `direct` validates in-process on this agnostic base; a `temporal` mode dispatches the
+ whole job to a worker (`pipelex-temporal`). A mode with no registered validator fails
+ loud with `MissingBundleValidatorError` (carrying the install hint). Validation is inherently
+ blocking, so there is no delivery axis here — the registry holds one validator per mode.
+
+ Returns the verdict, not a raise: the valid `PipelexValidationReport`, or the structured
+ `ErrorReport` an invalid bundle produces (carrying `validation_errors`). A genuine
+ no-verdict infra fault propagates to the global problem+json handler (5xx). The route
+ discriminates on `isinstance(verdict, PipelexValidationReport)`.
+
+ `mthds_sources` is the optional per-content source-threading hook: each source lands on
+ the corresponding `blueprint.source`, so the structured `validation_errors` on a failure —
+ and the `bundle_blueprint` on success — carry a real `source` instead of `None`. The route
+ maps a length mismatch to a 422 before we get here; `None` keeps the sourceless behavior.
+ `library_dirs` is host context the in-process arm needs; a dispatched arm ignores it (the
+ worker loads its own library). A bundle without a declared `main_pipe` validates fine and
+ simply carries `graph_spec=None` (D2 — no precondition).
+
+ `graph_pipe_code` is the pipe the best-effort graph is drawn from, resolved the way a run
+ resolves its entry pipe; `None` keeps the runtime's default, the primary blueprint's
+ `main_pipe`. The route passes a fetched package manifest's `main_pipe`, so the graph shows
+ the pipe a selector-less run by that address executes.
+ """
+ # Resolve the effective mode FIRST — a per-request override the deployment policy forbids
+ # is refused (403) here, before any validator dispatch / library load. Mirrors start().
+ orchestration_mode = resolve_orchestration_mode(requested_orchestration_mode, config=get_api_config())
+ validator = get_bundle_validator_registry().get_optional(mode=orchestration_mode)
+ if validator is None:
+ raise MissingBundleValidatorError(mode=orchestration_mode)
+ library_dirs = [Path(library_dir) for library_dir in self.library_dirs] if self.library_dirs else None
+ verdict = await validator.validate_bundles(
+ mthds_contents=mthds_contents,
+ mthds_sources=mthds_sources,
+ allow_signatures=allow_signatures,
+ library_dirs=library_dirs,
+ # A validation is not a run, but its dry runs and its `pipe_dry_run` event are still
+ # done for the caller this runner was built for — the user and groups a run would state.
+ caller_identity=self.caller_identity,
+ graph_pipe_code=graph_pipe_code,
+ )
+ # The core seam types its valid arm at the protocol-level ValidationReport (a leaf type)
+ # to stay import-acyclic in core; every registered validator in fact produces the canonical
+ # PipelexValidationReport. Recover the precise type here — the single narrowing point — so
+ # the route's `isinstance(verdict, PipelexValidationReport)` yields ErrorReport on the else arm.
+ return cast("PipelexValidationReport | ErrorReport", verdict)
+
+
+# The object keys a kajson decoder reads as class markers: `__class__` and `__module__` name a class to
+# import and instantiate, and kajson reserves every key starting with `__kajson` for itself. The same set
+# the hosted platform refuses before it forwards a run body.
+_RESERVED_OBJECT_KEYS = frozenset({"__class__", "__module__"})
+_RESERVED_OBJECT_KEY_PREFIX = "__kajson"
+
+
+def _find_reserved_object_key(payload: object) -> str | None:
+ """Return the first reserved object key found at any depth of a parsed JSON value, or `None`.
+
+ Walks every object key at every depth with an explicit stack, so a deeply nested body cannot
+ exhaust the interpreter's recursion budget here. Values are never inspected: a string that
+ merely contains `__class__` is data, not a marker.
+ """
+ stack: list[object] = [payload]
+ while stack:
+ current = stack.pop()
+ if isinstance(current, dict):
+ for key, value in cast("dict[str, object]", current).items():
+ if key in _RESERVED_OBJECT_KEYS or key.startswith(_RESERVED_OBJECT_KEY_PREFIX):
+ return key
+ stack.append(value)
+ elif isinstance(current, list):
+ stack.extend(cast("list[object]", current))
+ return None
+
+
+def _decode_body(body: bytes) -> dict[str, Any]:
+ """Parse the run body as plain JSON and confirm it is an object free of class markers. Raises 422 if not.
+
+ The body is parsed with `json.loads`, never with kajson. kajson reads a
+ `{"__class__": ..., "__module__": ...}` object as an order to import that module and
+ instantiate that class, so decoding a caller's body with it let any caller run code on the
+ server (`subprocess.Popen` included) before a single field was validated. The MTHDS Protocol
+ wire is plain JSON, and no client sends class markers.
+
+ Parsing as plain data is not enough on its own: a marker accepted as an ordinary dict comes
+ back to life the moment the runtime round-trips the inputs through kajson. So a key a kajson
+ decoder treats as a marker is refused at any depth with a 422 `ReservedObjectKey`.
+
+ The parse failures are caller mistakes, so they map to a 422 `InvalidJSON` rather than a
+ sanitized 500:
+ - `UnicodeDecodeError` — the body bytes are not valid UTF-8.
+ - `ValueError` — `json.JSONDecodeError` (it subclasses `ValueError`).
+ - `RecursionError` — a deeply nested JSON array or object exhausts the parser's
+ recursion budget.
+ """
+ try:
+ decoded = json.loads(body.decode("utf-8"))
+ except (UnicodeDecodeError, ValueError, RecursionError) as exc:
+ raise_validation_error(
+ message=f"Request body is not valid JSON: {exc!s}",
+ error_type=ErrorType.INVALID_JSON,
+ )
+ if not isinstance(decoded, dict):
+ raise_validation_error(
+ message="Request body must be a JSON object",
+ error_type=ErrorType.INVALID_JSON,
+ )
+ request_data = cast("dict[str, Any]", decoded)
+ reserved_key = _find_reserved_object_key(request_data)
+ if reserved_key is not None:
+ # The key is the caller's, as long as the body allows (any `__kajson…` key matches), and the
+ # detail is logged as a field: echo it bounded, as the correlation fields are.
+ shown_key = reserved_key if len(reserved_key) <= _MAX_CORRELATION_FIELD_LEN else f"{reserved_key[:_MAX_CORRELATION_FIELD_LEN]}…"
+ raise_validation_error(
+ message=(
+ f"Request body contains the reserved object key '{shown_key}'. A run request is plain JSON: "
+ f"no object in it may carry a '__class__' or '__module__' key, or a key starting with '{_RESERVED_OBJECT_KEY_PREFIX}'."
+ ),
+ error_type=ErrorType.RESERVED_OBJECT_KEY,
+ )
+ return request_data
+
+
+# The `error_type` a 422 on one extras field carries. A field absent from this map
+# (`pipeline_run_id`, `orchestration_mode`) answers with the generic `ValidationError`.
+_EXTRAS_FIELD_ERROR_TYPES: dict[str, ErrorType] = {
+ "callback_urls": ErrorType.INVALID_CALLBACK_URLS,
+ "storage_scope": ErrorType.INVALID_STORAGE_SCOPE,
+ "read_scope": ErrorType.INVALID_READ_SCOPE,
+ "analytics_groups": ErrorType.INVALID_ANALYTICS_GROUPS,
+}
+
+
+def _extras_error_type(exc: ValidationError) -> ErrorType:
+ """Classify an extras failure by the field that failed, so a client can branch on `error_type`.
+
+ Every extras failure used to answer `InvalidCallbackUrls`, including a traversal in
+ `storage_scope` on a request that carried no callback at all. A body failing on
+ more than one field gets the generic `ValidationError`: naming one of them would
+ send the caller to fix that field and leave the other one for the next request.
+ """
+ failed_fields = {str(error["loc"][0]) for error in exc.errors() if error["loc"]}
+ if len(failed_fields) != 1:
+ return ErrorType.VALIDATION_ERROR
+ return _EXTRAS_FIELD_ERROR_TYPES.get(failed_fields.pop(), ErrorType.VALIDATION_ERROR)
+
+
+def _validate_extras(request_data: dict[str, Any]) -> PipelineApiExtras:
+ """Validate the API-server-only fields `PipelineApiExtras` declares, read straight off the body.
+
+ The whole body is validated rather than a hand-copied subset of its keys: the model
+ ignores keys it does not declare, so a field added to it is read off the wire with no
+ second list to keep in step. Such a list would drop a forgotten key SILENTLY, and for
+ `storage_scope` that is worse than an error: the run falls back to the caller's own id
+ and writes to the wrong prefix while reporting success.
+ """
+ try:
+ return PipelineApiExtras.model_validate(request_data)
+ except ValidationError as exc:
+ raise_validation_error(
+ message=str(exc),
+ error_type=_extras_error_type(exc),
+ )
+
+
+# Per-field bound applied at the request.state binding site so an oversized
+# caller-supplied `pipe_code` cannot blow up the size of every record the request emits.
+# `RunRequest.pipe_code` carries no Pydantic `max_length`; this is the
+# narrow cap that protects the structured error log without changing the
+# upstream type contract. 256 covers any realistic pipe code (kebab-case
+# identifier, typically tens of chars) with headroom.
+_MAX_CORRELATION_FIELD_LEN = 256
+
+
+def _coerce_correlation_field(value: Any) -> str | None:
+ """Normalize a body-derived correlation identifier for `request.state` binding.
+
+ Returns `None` when the value is missing, empty, or non-string — so the
+ handler's `_pipe_code_of` / `_pipeline_run_id_of` getters see a uniform
+ `None` and the error record carries no attribute at all, rather than an
+ empty string a downstream query would read as a real value. Truncates
+ oversized strings to `_MAX_CORRELATION_FIELD_LEN` so a caller cannot
+ inflate every error record the request emits by sending a megabyte-long
+ pipe_code.
+ """
+ if not isinstance(value, str) or not value:
+ return None
+ return value[:_MAX_CORRELATION_FIELD_LEN]
+
+
+async def _parse_request(request: Request) -> tuple[RunRequest, PipelineApiExtras]:
+ """Parse and validate the request body.
+
+ Splits the body into:
+ 1. The upstream `RunRequest` (pipe_code, mthds_contents, inputs, …),
+ parsed as plain JSON by `_decode_body`, which refuses class markers.
+ 2. `PipelineApiExtras` (pipeline_run_id, callback_urls, orchestration_mode,
+ storage_scope, analytics_groups) validated by Pydantic — callback_urls
+ are checked for scheme + private/loopback hosts to harden against SSRF.
+
+ Body size is capped upstream by `request_body_size_middleware`.
+ """
+ body = await request.body()
+ request_data = _decode_body(body)
+ # Bind body-derived correlation identifiers onto `request.state` as soon as
+ # the raw dict is in hand — before `_validate_extras` or `from_body`, so a
+ # later validation failure (a rejected callback URL, a Pydantic coercion
+ # error on a sibling field) still rides the identifiers the caller named.
+ # `_coerce_correlation_field` normalizes empty / non-string / oversized.
+ # Mirrors the `_set_request_user` pattern in `pipelex_api.security` (binding the
+ # earliest known identity onto the request).
+ request.state.pipe_code = _coerce_correlation_field(request_data.get("pipe_code"))
+ request.state.pipeline_run_id = _coerce_correlation_field(request_data.get("pipeline_run_id"))
+ extras = _validate_extras(request_data)
+ try:
+ run_request = RunRequest.from_body(request_data)
+ except (PipelineRequestError, ValidationError) as exc:
+ # `from_body` rejects a body where neither `pipe_code` nor
+ # `mthds_contents` is supplied (PipelineRequestError) and a body whose
+ # fields fail Pydantic coercion (ValidationError) — both are caller
+ # mistakes, not server faults, so they map to a 422 rather than
+ # escaping to the generic-500 fallback.
+ raise_validation_error(message=str(exc))
+ return run_request, extras
+
+
+@contextmanager
+def _bundle_run_source(run_request: RunRequest) -> Generator[tuple[list[str] | None, list[str] | None], None, None]:
+ """Resolve a run's `(mthds_contents, library_dirs)` from the request.
+
+ A method bundle KEEPS the proven run path rather than replacing it: its `.mthds`
+ text travels as `mthds_contents` — so `main_pipe` resolves exactly as it does for a
+ plain (non-bundle) run — and ONLY the non-`.mthds` files (custom PipeFunc `.py`,
+ `requirements.txt`) are materialized into a temp `library_dirs` entry, where the
+ load path reads them without importing them. This mirrors "a normal run, plus the Python", instead of
+ handing the engine a bare directory with no `mthds_contents` (which never resolves
+ `main_pipe`, since that is only derived from `mthds_contents`).
+
+ No bundle → yields the request's own `mthds_contents` and no library dir (the
+ classic path, unchanged). Bundle with no non-`.mthds` files → yields the `.mthds`
+ texts and no library dir. The temp dir (when created) is cleaned up on exit.
+
+ Security gate (decision 5): a bundle that ships custom Python (`.py`) is only
+ honored on a sandbox-hosted deployment, where the load path reads the source
+ without importing it and refuses, with a 403 `MethodStructuresRefusedError`, a
+ bundle whose Python declares a structure class; PipeFunc source is captured for
+ the sandbox. On a non-hosted deployment, running that code would import it
+ in-process — refused with a 403 rather than executing untrusted code.
+ """
+ if run_request.bundle_b64 is None and run_request.files is None:
+ yield run_request.mthds_contents, None
+ return
+ # Parse + guard in memory FIRST, then apply the sandbox-hosted gate BEFORE any disk write —
+ # a bundle destined for a 403 on a non-hosted deployment never touches the filesystem.
+ parsed = parse_bundle(bundle_b64=run_request.bundle_b64, files=run_request.files)
+ if parsed.has_python_sources and not is_pipe_func_sandbox_hosted():
+ msg = "This bundle ships custom Python (.py); running it requires a sandbox-hosted deployment."
+ raise_forbidden(message=msg, error_type=ErrorType.CUSTOM_CODE_REQUIRES_SANDBOX)
+ # Split: `.mthds` text → `mthds_contents` (the proven main_pipe path); everything else
+ # (`.py`, `requirements.txt`) → a temp `library_dirs` entry the load path source-captures.
+ mthds_contents: list[str] = []
+ other_entries: list[tuple[PurePosixPath, bytes]] = []
+ for relpath, content in parsed.entries:
+ if str(relpath).endswith(".mthds"):
+ try:
+ mthds_contents.append(content.decode("utf-8"))
+ except UnicodeDecodeError:
+ raise_validation_error(message=f"Bundle .mthds file '{relpath}' is not valid UTF-8.", error_type=ErrorType.INVALID_BUNDLE)
+ else:
+ other_entries.append((relpath, content))
+ if not mthds_contents:
+ raise_validation_error(message="Method bundle contains no .mthds file.", error_type=ErrorType.INVALID_BUNDLE)
+ if not other_entries:
+ yield mthds_contents, None
+ return
+ with materialize_parsed(ParsedBundle(entries=tuple(other_entries))) as bundle:
+ yield mthds_contents, [str(bundle.directory)]
+
+
+class _ResolvedRunSource(NamedTuple):
+ """What the run routes hand the runner, whatever the request's source form was."""
+
+ mthds_contents: list[str] | None
+ library_dirs: list[str] | None
+ pipe_code: str | None
+ method_provenance: MethodProvenance | None
+
+
+@contextmanager
+def _run_source(run_request: RunRequest) -> Generator[_ResolvedRunSource, None, None]:
+ """Resolve the request's run source: a `method_ref` fetch, a bundle, or the inline contents.
+
+ A `method_ref` resolves through `pipelex_api.method_source.fetched_method_source` (fetch → locate →
+ execution-locus gate → materialize) into exactly the shape a bundle produces — `.mthds` text
+ as `mthds_contents`, non-`.mthds` files in a temp `library_dirs` entry — so the engine runs
+ the same proven path. The entry pipe defaults to the fetched manifest's `main_pipe`; a
+ request `pipe_code` overrides it. Provenance `(address, tag, commit_sha)` rides back so the
+ routes can put it on the response. The other two forms delegate to `_bundle_run_source`,
+ unchanged.
+ """
+ if run_request.method_ref is not None:
+ with fetched_method_source(run_request.method_ref) as fetched:
+ yield _ResolvedRunSource(
+ mthds_contents=fetched.mthds_contents,
+ library_dirs=fetched.library_dirs,
+ pipe_code=run_request.pipe_code or fetched.main_pipe,
+ method_provenance=fetched.provenance,
+ )
+ return
+ with _bundle_run_source(run_request) as (mthds_contents, library_dirs):
+ yield _ResolvedRunSource(
+ mthds_contents=mthds_contents,
+ library_dirs=library_dirs,
+ pipe_code=run_request.pipe_code,
+ method_provenance=None,
+ )
+
+
+ "/execute",
+ # Documented 200 = the run result with the WIRE-shaped `pipe_output`: the handler returns a
+ # `JSONResponse` built from a trimmed dump, so FastAPI never serializes through this model —
+ # it is purely what the artifact publishes, and it must match `apply_tokens_usage_wire_shape`.
+ response_model=PipelexApiExecuteResponse,
+ # On top of the composite router's shared 401/413/422/500: the policy 403s (a forbidden
+ # per-request `orchestration_mode` override, the custom-code sandbox gate, the structures
+ # refusal on a bundle or a fetched package), the `method_ref` package-not-found 404, and the provider
+ # rate-limit passthrough (429) — `/execute` is the only route that runs inference, so it is
+ # the only one that can be rate-limited upstream. NO 409: unlike `/start`, `/execute` takes
+ # no client-supplied `pipeline_run_id` (the base runner generates one per call), so a caller
+ # cannot collide with an in-flight run.
+ responses={403: PROBLEM_403_RUN_POLICY, 404: PROBLEM_404_METHOD_PACKAGE, 429: PROBLEM_429},
+ # Documented body = the protocol's RunRequest plus THIS server's own
+ # `orchestration_mode` extension (the route honors a per-request override). The
+ # body is read through the raw Request (plain JSON with the reserved-key
+ # refusal — see `_parse_request`), so FastAPI cannot infer a typed body parameter;
+ # document it explicitly so the committed OpenAPI artifact (and protocol
+ # conformance tooling) publishes the request schema. `responses=` and
+ # `openapi_extra` touch different members of the operation object, so both land.
+ openapi_extra={
+ "x-mthds-protocol": True,
+ "requestBody": {
+ "required": True,
+ "content": {"application/json": {"schema": PipelexApiExecuteRequest.model_json_schema()}},
+ },
+ },
+)
+async def execute(request: Request) -> JSONResponse:
+ """Execute a method synchronously and return its full output (MTHDS Protocol `POST /execute`).
+
+ The backend is selected by the resolved `orchestration_mode` (deployment default + optional
+ policy-gated per-request override via the `orchestration_mode` extra), symmetric with `/start` —
+ not by `boot_orchestrator`. `/execute` is synchronous, so it dispatches with `BLOCKING` delivery
+ regardless of backend (wait-semantics is endpoint-set, never requestable). Pipelex domain
+ failures propagate untouched: the global `PipelexError` handler in `pipelex_api.exception_handlers`
+ turns them into an RFC 7807 problem response.
+ """
+ run_request, extras = await _parse_request(request)
+ scopes = _resolve_run_scopes(request, extras=extras)
+ with _run_source(run_request) as source:
+ runner = ApiRunner(
+ user_id=get_request_user_id(request),
+ storage_scope=scopes.storage_scope,
+ read_scope=scopes.read_scope,
+ extras=extras.analytics_groups,
+ library_dirs=source.library_dirs,
+ )
+ response = await runner.execute(
+ pipe_code=source.pipe_code,
+ mthds_contents=source.mthds_contents,
+ inputs=run_request.inputs,
+ output_name=run_request.output_name,
+ output_multiplicity=run_request.output_multiplicity,
+ dynamic_output_concept_ref=run_request.dynamic_output_concept_ref,
+ request_id=request_id_of(request),
+ requested_orchestration_mode=extras.orchestration_mode,
+ )
+ # The response dump carries the full internal usage models on
+ # `pipe_output.tokens_usages`; the client boundary gets the trimmed
+ # `TokensUsageRecord` wire shape instead (pipelex owns the shape authority).
+ response_dump = response.model_dump(mode="json", serialize_as_any=True, by_alias=True)
+ apply_tokens_usage_wire_shape(response_dump, pipe_output=response.pipe_output)
+ # Provenance of a `method_ref` run (address, tag, resolved commit SHA) — attached only when
+ # the run was selected by reference, so the classic response stays byte-identical.
+ if source.method_provenance is not None:
+ response_dump["method_provenance"] = source.method_provenance.model_dump(mode="json")
+ return JSONResponse(content=response_dump)
+
+
+ "/start",
+ response_model=PipelexApiStartResponse,
+ status_code=202,
+ # On top of the composite router's shared 401/413/422/500. `/start` is fire-and-forget, so
+ # its extra failures are all about the backend's ability to honor that and about the
+ # client-supplied run id it (alone) accepts:
+ # 400 — the resolved orchestrator is blocking-only (the in-process `direct` base): refuse
+ # honestly rather than block-and-ack. Use `/execute`.
+ # 403 — a per-request `orchestration_mode` override the deployment forbids, the
+ # custom-code sandbox gate, or the structures refusal on a bundle or a fetched package.
+ # 404 — a `method_ref` whose repository holds no matching package.
+ # 409 — the submitted `pipeline_run_id` is still registered for an in-flight run.
+ # 501 — an async-capable deployment whose async execution is not enabled.
+ responses={
+ 400: PROBLEM_400_START_REQUIRES_ASYNC,
+ 403: PROBLEM_403_RUN_POLICY,
+ 404: PROBLEM_404_METHOD_PACKAGE,
+ 409: PROBLEM_409_DUPLICATE_RUN,
+ 501: PROBLEM_501_ASYNC_NOT_ENABLED,
+ },
+ # Documented body = the protocol's StartRequest plus THIS server's own
+ # extensions (callback_urls) — the protocol model no longer advertises
+ # implementation extensions, so the server documents what it implements.
+ # Raw-Request parsing prevents FastAPI from inferring it — see the
+ # /execute note.
+ openapi_extra={
+ "x-mthds-protocol": True,
+ "requestBody": {
+ "required": True,
+ "content": {"application/json": {"schema": PipelexApiStartRequest.model_json_schema()}},
+ },
+ },
+)
+async def start(
+ request: Request,
+ parsed: Annotated[tuple[RunRequest, PipelineApiExtras], Depends(_parse_request)],
+) -> PipelexApiStartResponse:
+ """Start a method run and return its pipeline_run_id with a 202 ack (MTHDS Protocol `POST /start`).
+
+ Answers `202 Accepted` with a `StartAck`. A client-supplied `pipeline_run_id` is
+ honored (the protocol lets an implementation decline it; this runner accepts it, and
+ `StartAck.pipeline_run_id` is always authoritative). Pipelex domain failures propagate untouched: the global
+ `PipelexError` handler in `pipelex_api.exception_handlers` turns them into an
+ RFC 7807 problem response.
+
+ Fire-and-forget is a property of THIS endpoint (its delivery axis), honored only by an
+ async-capable backend. A deployment configures the backend (`orchestration_mode`) once; `/start`
+ sets `FIRE_AND_FORGET` delivery and checks the resolved orchestrator can honor it. A Temporal
+ deployment (`orchestration_mode = "temporal"`) enqueues the run and returns immediately with a
+ `workflow_id`. On the orchestrator-agnostic base (`orchestration_mode = "direct"`, the default)
+ the in-process orchestrator is blocking-only, so `/start` is HONEST: it refuses with a `400`
+ (`StartRequiresAsyncOrchestration`) — use `/execute` — rather than silently blocking and acking.
+ The completion callback (`callback_urls` / storage delivery) fires on the async path.
+ """
+ run_request, extras = parsed
+ scopes = _resolve_run_scopes(request, extras=extras)
+ # The run source is materialized only for the synchronous setup phase: `start` builds the
+ # PipeJob (crate carrying the captured `python_sources`) before it enqueues, so the temp dir
+ # (a bundle's, or a fetched package's) is no longer needed once `start` returns — cleanup on
+ # context exit is safe for the async path.
+ with _run_source(run_request) as source:
+ runner = ApiRunner(
+ user_id=get_request_user_id(request),
+ storage_scope=scopes.storage_scope,
+ read_scope=scopes.read_scope,
+ extras=extras.analytics_groups,
+ library_dirs=source.library_dirs,
+ )
+ start_result = await runner.start(
+ pipe_code=source.pipe_code,
+ mthds_contents=source.mthds_contents,
+ inputs=run_request.inputs,
+ output_name=run_request.output_name,
+ output_multiplicity=run_request.output_multiplicity,
+ dynamic_output_concept_ref=run_request.dynamic_output_concept_ref,
+ pipeline_run_id=extras.pipeline_run_id,
+ callback_urls=extras.callback_urls,
+ request_id=request_id_of(request),
+ requested_orchestration_mode=extras.orchestration_mode,
+ )
+ # The ack plus this server's provenance extension: `(address, tag, commit_sha)` for a
+ # `method_ref` run, null otherwise — the caller (and, on hosted, the platform's Run row)
+ # learns exactly what was fetched and at which commit.
+ return PipelexApiStartResponse(
+ **dict(start_result),
+ method_provenance=source.method_provenance,
+ )
diff --git a/api/pipelex_api/routes/pipelex/resolve.py b/api/pipelex_api/routes/pipelex/resolve.py
new file mode 100644
index 000000000..8676063cd
--- /dev/null
+++ b/api/pipelex_api/routes/pipelex/resolve.py
@@ -0,0 +1,80 @@
+import json
+from typing import Annotated, Any, Literal, Union
+
+from fastapi import APIRouter
+from fastapi.responses import JSONResponse
+from pipelex.codegen.crate_encoding import encode_crate_json
+from pipelex.pipeline.exceptions import ValidateBundleError
+from pydantic import BaseModel, Field
+
+from pipelex_api.openapi_responses import PROBLEM_404_METHOD_PACKAGE, PROBLEM_501_METHOD_REF
+from pipelex_api.routes.pipelex.crate_ops import (
+ CrateInvalidReport,
+ invalid_crate_report_response,
+ resolve_requested_crate,
+ teardown_current_library,
+)
+from pipelex_api.schemas.models import MthdsFilesRequest
+
+router = APIRouter(tags=["resolve"])
+
+
+class ResolveValidReport(BaseModel):
+ """The 200 **valid** arm: the normalized library crate, ready for any consumer's emitter.
+
+ The crate rides as the canonical JSON encoding's object form (top-level maps key-sorted,
+ non-semantic provenance dropped) — the same bytes `pipelex resolve --format json` prints, so a
+ fingerprint computed from either surface agrees. Its `fingerprint` and `mthds_version` members
+ ride inside the crate payload itself.
+ """
+
+ is_valid: Literal[True] = True
+ crate: dict[str, Any] = Field(..., description="The normalized library crate (canonical JSON encoding, `fingerprint` included).")
+ message: str = Field(default="MTHDS library resolved successfully", description="Status message")
+
+
+# Discriminated 200 response union: a consumer pattern-matches the one mandatory `is_valid`
+# field to learn the verdict — the same discipline as `POST /validate`.
+ResolveResponse = Annotated[Union[ResolveValidReport, CrateInvalidReport], Field(discriminator="is_valid")]
+
+
+ "/resolve",
+ response_model=ResolveResponse,
+ # On top of the composite router's shared 401/413/422/500: the `method_ref` closure selector
+ # the envelope accepts but no server-side method registry resolves yet.
+ responses={404: PROBLEM_404_METHOD_PACKAGE, 501: PROBLEM_501_METHOD_REF},
+ # NOT tagged `x-mthds-protocol`: the MTHDS Protocol is the five operations `execute`, `start`,
+ # `validate`, `models`, `version`. `/resolve` is a Pipelex API extension. The *artifact* it
+ # emits — the normalized library crate — IS standard-owned (the MTHDS Library Crate Format), so
+ # its wire fields stay brand-neutral; the route that serves it over HTTP is ours.
+)
+async def resolve_mthds(request_data: MthdsFilesRequest) -> JSONResponse:
+ """Resolve a library closure into its normalized crate (Pipelex API extension).
+
+ Resolution is a first-class language operation alongside validation: assemble the closure from
+ the inline `files[]`, load + statically validate the library, and emit the **normalized
+ library crate** (fully qualified refs, refinement flattened, natives materialized, fingerprint
+ set) — the artifact shape the MTHDS standard specifies as the Library Crate Format. It runs no
+ dry-run sweep — runnability is `/validate`'s vocabulary.
+
+ Response contract (the `/validate` discipline):
+
+ - **Valid verdict (200, `is_valid: true`):** the crate on the valid arm.
+ - **Invalid verdict (200, `is_valid: false`):** the library could not be parsed, loaded, or
+ validated — `validation_errors[]` from pipelex's one shared builder.
+ - **No verdict (non-2xx):** a malformed request body (neither/both closure selectors, an
+ over-limit file) is a request-shape 422; `method_ref` is a 501 until server-side method
+ registry resolution exists; auth is 401/403; server fault is 5xx. All RFC 7807
+ `application/problem+json` via the global handlers.
+ """
+ try:
+ # Whole-closure route: no pipe is selected here, so the manifest's `main_pipe` beside the crate is unused.
+ crate = resolve_requested_crate(request_data).crate
+ except ValidateBundleError as validate_error:
+ return invalid_crate_report_response(validate_error.to_error_report())
+ try:
+ report = ResolveValidReport(crate=json.loads(encode_crate_json(crate)))
+ return JSONResponse(content=report.model_dump(mode="json", by_alias=True))
+ finally:
+ teardown_current_library()
diff --git a/api/pipelex_api/routes/pipelex/tools.py b/api/pipelex_api/routes/pipelex/tools.py
new file mode 100644
index 000000000..17df2b848
--- /dev/null
+++ b/api/pipelex_api/routes/pipelex/tools.py
@@ -0,0 +1,110 @@
+from __future__ import annotations
+
+from typing import Any, Literal
+
+import pipelex_tools
+from fastapi import APIRouter
+from pydantic import BaseModel, Field, field_validator
+
+from pipelex_api.errors import raise_validation_error
+from pipelex_api.limits import MAX_MTHDS_FILE_BYTES
+
+router = APIRouter(tags=["tools"])
+
+
+class MthdsToolRequest(BaseModel):
+ """Shared single-file request body for lightweight MTHDS editor tooling."""
+
+ content: str = Field(..., description="Single .mthds file content to lint or format.")
+
+ @field_validator("content")
+ @classmethod
+ def _bound_content(cls, value: str) -> str:
+ if len(value.encode("utf-8")) > MAX_MTHDS_FILE_BYTES:
+ msg = f"MTHDS file exceeds {MAX_MTHDS_FILE_BYTES // 1024} KiB limit"
+ raise ValueError(msg)
+ return value
+
+
+class LintRequest(MthdsToolRequest):
+ """Body of `POST /lint`."""
+
+ source: str | None = Field(
+ default=None,
+ description=(
+ "Optional logical filename for the content. Accepted for parity with `pipelex_tools.lint_mthds`; "
+ "current diagnostics do not yet include the filename."
+ ),
+ )
+
+
+class FormatRequest(MthdsToolRequest):
+ """Body of `POST /format`."""
+
+ options: dict[str, Any] | None = Field(
+ default=None,
+ description=(
+ "Optional formatter options passed through to `pipelex_tools.format_mthds`, such as "
+ "`column_width`. Malformed option values return a 422 problem response."
+ ),
+ )
+
+
+class Range(BaseModel):
+ """Byte offsets plus 1-based line/column coordinates from `pipelex-tools-py`."""
+
+ start_offset: int
+ end_offset: int
+ start_line: int
+ start_col: int
+ end_line: int
+ end_col: int
+
+
+class Diagnostic(BaseModel):
+ """Structured lint/format diagnostic returned by `pipelex-tools-py`."""
+
+ kind: Literal["syntax", "semantic", "schema"]
+ severity: str
+ message: str
+ location: str | None
+ range: Range | None
+
+
+class LintResponse(BaseModel):
+ """Response body of `POST /lint`."""
+
+ diagnostics: list[Diagnostic]
+
+
+class FormatResponse(BaseModel):
+ """Response body of `POST /format`."""
+
+ formatted: str
+ changed: bool
+ diagnostics: list[Diagnostic]
+
+
[email protected]("/lint", response_model=LintResponse)
+async def lint_mthds(request_data: LintRequest) -> LintResponse:
+ """Lint one .mthds file with the embedded MTHDS schema.
+
+ Malformed .mthds content is a produced diagnostic verdict and returns 200.
+ Request-shape problems remain RFC 7807 422 responses through the global handlers.
+ """
+ result = pipelex_tools.lint_mthds(request_data.content, source=request_data.source)
+ return LintResponse.model_validate(result)
+
+
[email protected]("/format", response_model=FormatResponse)
+async def format_mthds(request_data: FormatRequest) -> FormatResponse:
+ """Format one .mthds file with the canonical MTHDS formatter.
+
+ Syntax errors return 200 with diagnostics and unchanged content. Malformed
+ formatter options are caller input errors and return RFC 7807 422.
+ """
+ try:
+ result = pipelex_tools.format_mthds(request_data.content, options=request_data.options)
+ except ValueError as exc:
+ raise_validation_error(str(exc))
+ return FormatResponse.model_validate(result)
diff --git a/api/pipelex_api/routes/pipelex/utils.py b/api/pipelex_api/routes/pipelex/utils.py
new file mode 100644
index 000000000..665c921dd
--- /dev/null
+++ b/api/pipelex_api/routes/pipelex/utils.py
@@ -0,0 +1,6 @@
+from datetime import UTC, datetime
+
+
+def get_current_iso_timestamp() -> str:
+ """Get the current ISO timestamp."""
+ return datetime.now(UTC).isoformat()
diff --git a/api/pipelex_api/routes/pipelex/validate.py b/api/pipelex_api/routes/pipelex/validate.py
new file mode 100644
index 000000000..7dad0c313
--- /dev/null
+++ b/api/pipelex_api/routes/pipelex/validate.py
@@ -0,0 +1,472 @@
+from enum import StrEnum
+from typing import Annotated, Literal, Self, Union
+
+from fastapi import APIRouter, Request
+from fastapi.responses import JSONResponse
+from pipelex.base_exceptions import ErrorReport, ValidationErrorItem
+from pipelex.core.qualified_ref import QualifiedRef
+from pipelex.pipe_machinery.pipe_factory import PipeFactory
+from pipelex.pipeline.input_form import PipeInputFormDescriptor, PipeOutputFormDescriptor
+from pipelex.pipeline.validation_render import format_validate_markdown, render_invalid_validation_markdown
+from pipelex.pipeline.validation_report import PipelexValidationReport
+from pipelex.tools.typing.pydantic_utils import empty_list_factory_of
+from pydantic import BaseModel, Field, model_validator
+
+from pipelex_api.errors import raise_validation_error
+from pipelex_api.exception_handlers import problem_response_from_error_report
+from pipelex_api.method_source import fetched_method_source
+from pipelex_api.openapi_responses import PROBLEM_403_RUN_POLICY, PROBLEM_404_METHOD_PACKAGE
+from pipelex_api.routes.pipelex.pipeline import ApiRunner, get_request_user_id
+from pipelex_api.schemas.models import CallerAnalyticsGroupsMixin, MthdsContentsRequest
+
+router = APIRouter(tags=["validate"])
+
+
+class RenderFormat(StrEnum):
+ """The closed set of server-side **supported** presentation formats for `/validate`.
+
+ This is the supported-set vocabulary the route resolves request `render` tokens against —
+ NOT the request-body type (the request stays `list[str]` so an unknown token is lenient-ignored,
+ not 422'd). A Pipelex-API presentation concern (D-D): never the neutral protocol body.
+ """
+
+ MARKDOWN = "markdown"
+
+
+def _resolve_render_formats(render: list[str]) -> set[RenderFormat]:
+ """Resolve raw `render` tokens to the supported `RenderFormat` set (deduped, order-insensitive).
+
+ Unknown/unsupported tokens are silently dropped (lenient-ignore, per-token): `render` is a
+ presentation hint, not part of the verdict contract, so a stale view token never fails the call.
+ """
+ supported_values = {render_format.value for render_format in RenderFormat}
+ return {RenderFormat(token) for token in render if token in supported_values}
+
+
+class ValidationView(StrEnum):
+ """The closed set of server-side **supported** structured views for `/validate`.
+
+ The second opt-in axis beside `render`, with identical mechanics (raw `list[str]` request field,
+ per-token resolution, lenient-ignore) but a different product: `render` yields *rendered text*
+ under a mechanical `rendered_<format>` key, while a view attaches a *structured* artifact under a
+ **same-named** top-level field. The two lists stay separate and independent — a request may carry
+ both, and each resolves its own tokens against its own supported set.
+ """
+
+ INPUT_FORM = "input_form"
+ OUTPUT_FORM = "output_form"
+
+
+def _resolve_validation_views(views: list[str]) -> set[ValidationView]:
+ """Resolve raw `views` tokens to the supported `ValidationView` set (deduped, order-insensitive).
+
+ Unknown/unsupported tokens are silently dropped (lenient-ignore, per-token), exactly as for
+ `render`: a view is an opt-in projection of facts the verdict already determined, never part of
+ the verdict contract, so a stale view token must never fail the call with a 422.
+ """
+ supported_values = {view.value for view in ValidationView}
+ return {ValidationView(token) for token in views if token in supported_values}
+
+
+class ValidateRequest(MthdsContentsRequest, CallerAnalyticsGroupsMixin):
+ """The shared `mthds_contents` + `allow_signatures` payload, plus optional per-file sources.
+
+ `mthds_sources`, when provided, pairs each `mthds_contents[i]` with a logical source (e.g. the
+ file's path relative to the submitted directory). The runner threads it onto
+ `blueprint.source`, so the structured `validation_errors` on a 200 `InvalidReport` carry a real
+ `source` the client maps back to the owning file — without it the in-memory load path leaves
+ `source` null and cross-file diagnostics misfire. Omit it and behavior is unchanged.
+ """
+
+ mthds_sources: list[str] | None = Field(
+ default=None,
+ description=(
+ "Optional per-file sources, parallel to `mthds_contents`. When provided, each entry is threaded "
+ "onto the corresponding bundle's `source` so server-side validation errors carry a `source` pointing "
+ "at the owning file. Must match `mthds_contents` in length when present."
+ ),
+ )
+ render: list[str] = Field(
+ default_factory=list,
+ description=(
+ "Opt-in Pipelex-API presentation extra: view formats to render server-side. A supported token "
+ "(`markdown`) adds a `rendered_<format>` field (e.g. `rendered_markdown`) to the 200 verdict, on both "
+ "the valid and invalid arms. Unknown/unsupported tokens are silently ignored (presentation hint, not "
+ "part of the verdict contract); the default empty list renders nothing and the response is unchanged."
+ ),
+ )
+ views: list[str] = Field(
+ default_factory=list,
+ description=(
+ "Opt-in Pipelex-API structured views: extra projections to attach to the 200 verdict. A supported token "
+ "(`input_form`, `output_form`) adds a **same-named** top-level field to the valid arm only. Unknown/unsupported tokens are "
+ "silently ignored (a view is a projection of facts the verdict already determined, not part of the verdict "
+ "contract); the default empty list attaches nothing and the response is byte-identical to a request that "
+ "omits the field. Independent of `render`: a request may carry both, each resolving its own tokens."
+ ),
+ )
+ orchestration_mode: str | None = Field(
+ default=None,
+ description=(
+ "Optional per-request orchestration-mode (backend) override for the validation dispatch (same plumbing as "
+ "`/start`). An OPEN string token: `direct` validates in-process; a `temporal` mode dispatches the whole "
+ "job to a worker; any plugin-provided token is accepted and an unregistered one is refused at dispatch. "
+ "Honored only when the deployment sets `allow_request_orchestration_mode_override = true` in its `api.toml`; "
+ "otherwise a token that differs from the deployment default is refused with a 403. Omitted → the default."
+ ),
+ )
+
+ @model_validator(mode="after")
+ def _sources_match_contents(self) -> Self:
+ # `mthds_sources` labels INLINE contents; a `method_ref`'s sources are the package's own
+ # file names, so pairing the two is a request-shape bug → 422.
+ if self.mthds_sources is not None and self.method_ref is not None:
+ msg = "mthds_sources accompanies inline mthds_contents; a method_ref's sources are the package's own file names"
+ raise ValueError(msg)
+ # A caller-supplied length mismatch is a request-shape bug → caught here as a 422.
+ # Without this guard it reaches the runtime's `validate_bundle`, which treats the
+ # mismatch as an internal host error (500) — the wrong status for caller input.
+ if self.mthds_sources is not None and self.mthds_contents is not None and len(self.mthds_sources) != len(self.mthds_contents):
+ msg = "mthds_sources, when provided, must be a per-item source list matching mthds_contents in length"
+ raise ValueError(msg)
+ return self
+
+
+def _qualify_manifest_main_pipe(main_pipe: str, *, pipe_refs: list[str]) -> str | None:
+ """Qualify a manifest's bare `main_pipe` against the pipes the verdict actually saw.
+
+ A `METHODS.toml` `main_pipe` is a bare pipe code, and the runner resolves it exactly as it
+ resolves a human-supplied selector (`get_optional_entry_pipe`): an already-qualified ref matches
+ outright, a bare code is matched across the library's own domains, and an ambiguous bare code
+ resolves to nothing rather than picking a winner. That rule is mirrored here against
+ `pipe_io_contracts`' keys — the verdict's own complete, qualified pipe set — because the
+ validate path holds no loaded library to ask (the Temporal-dispatched arm never loaded one in
+ this process at all).
+
+ Cross-package keys (`alias->domain.code`) are excluded, as they are in the engine: an installed
+ dependency must never make a host package's own entry pipe ambiguous.
+
+ Returns:
+ The qualified ref, or None when the closure declares no such pipe or declares it in several
+ domains — both cases in which a selector-less run by this address would fail to resolve it.
+ """
+ own_refs = [ref for ref in pipe_refs if not QualifiedRef.has_cross_package_prefix(ref)]
+ if main_pipe in own_refs:
+ return main_pipe
+ matches = sorted({ref for ref in own_refs if ref.rpartition(".")[2] == main_pipe})
+ if len(matches) == 1:
+ return matches[0]
+ return None
+
+
+def _effective_default_pipe_ref(report: PipelexValidationReport, *, manifest_main_pipe: str | None) -> str | None:
+ """The qualified ref of the pipe a selector-less run of THIS request would execute.
+
+ The run routes' precedence, minus the request selector `/validate` does not have
+ (`pipeline.py`: `pipe_code or fetched.main_pipe`, then the batch's primary blueprint via
+ `select_primary_blueprint`): a fetched package's manifest `main_pipe` wins, and only when there
+ is none does the closure's own declaration decide. The per-pipe tooling routes apply that same
+ chain in `crate_ops.resolve_requested_pipe`, so a caller reading this field and a caller omitting
+ `pipe_ref` on `/build/*` are told about the same pipe wherever `/build/*` defaults at all — see
+ the one case below where it refuses to.
+
+ It deliberately states the RUN default, not the build routes' stricter one: a closure whose
+ domains each declare a `main_pipe` is refused by `/build/*` but runs happily — `execute` and
+ `start` take the first declaring blueprint — so reporting `null` for it would make a consumer
+ refuse to prepare a method the server would run. The report's `bundle_blueprint` IS that first
+ declaring blueprint (`build_validation_report` selects it through the same
+ `select_primary_blueprint`), so qualifying its `main_pipe` reproduces the run's own choice.
+
+ Inline `mthds_contents` carry no manifest, so for them the chain is exactly the closure's
+ declaration.
+ """
+ if manifest_main_pipe is not None:
+ # A manifest entry that does not resolve yields None rather than falling through to the
+ # closure's declaration: the run would pass the manifest's code and fail, so naming the
+ # closure's pipe here would report a pipe no selector-less run of this address executes.
+ return _qualify_manifest_main_pipe(manifest_main_pipe, pipe_refs=list(report.pipe_io_contracts))
+ blueprint = report.bundle_blueprint
+ if not blueprint.main_pipe:
+ return None
+ return PipeFactory.make_pipe_ref_with_domain(domain_code=blueprint.domain, pipe_code=blueprint.main_pipe)
+
+
+class ValidReport(PipelexValidationReport):
+ """The 200 **valid** arm: the canonical `PipelexValidationReport` plus this server's wire-only extras.
+
+ The report fields are inherited — typed models, identical to what the local runtime
+ returns for the same bundle, with `is_valid: Literal[True]` (from the report) as the union
+ discriminant. The extras exist for HTTP clients only (the webapp reads back `mthds_contents`);
+ they are NOT part of the canonical report and no in-process consumer should depend on them.
+
+ Two inherited fields are deliberately re-declared: `input_form` and `output_form`. The canonical
+ report requires both (a backend that forgets to derive one must fail loudly rather than ship an
+ empty view), but on the wire each is an opt-in structured view gated by the request's `views` —
+ so both are re-declared with defaults here, keeping them out of the published schema's `required`
+ set. The values still always arrive from the report; the route pops each when its token was not
+ requested. They are separate tokens rather than one because they answer separate questions: a
+ caller building a fill-in form wants the inputs, a caller rendering a result or registering a
+ tool signature wants the output, and neither should pay for the other.
+ """
+
+ mthds_contents: list[str] = Field(..., description="The MTHDS contents that were validated (echo of the request)")
+ message: str = Field(default="MTHDS content validated successfully", description="Status message")
+ default_pipe_ref: str | None = Field(
+ default=None,
+ description=(
+ "The qualified `domain.pipe_code` a caller gets by omitting the pipe selector — the pipe a "
+ "selector-less run of THIS request would execute. On a `method_ref` request it is the fetched "
+ "package manifest's `main_pipe` (the package author's declared entry pipe, qualified against the "
+ "closure); otherwise, and when the manifest declares none, it is the closure's primary blueprint's "
+ "`main_pipe` qualified by its domain. `null` when no entry pipe is determined: no blueprint declares "
+ "`main_pipe`, or a manifest names a pipe the closure does not declare (or declares ambiguously), in "
+ "which case a selector-less run by this address would fail to resolve it too."
+ ),
+ )
+ input_form: dict[str, PipeInputFormDescriptor] = Field(
+ default_factory=dict,
+ description=(
+ "Opt-in Pipelex-API structured view: per-pipe input-form descriptors keyed exactly like `pipe_io_contracts`, "
+ "present only when the request's `views` includes `input_form`. Absent by default — the structured contract "
+ "fields remain the verdict; this is a projection of them."
+ ),
+ )
+ output_form: dict[str, PipeOutputFormDescriptor] = Field(
+ default_factory=dict,
+ description=(
+ "Opt-in Pipelex-API structured view: per-pipe output-form descriptors keyed exactly like `pipe_io_contracts`, "
+ "present only when the request's `views` includes `output_form`. Absent by default. Read with the output "
+ "contract's `json_schema`, which states the shape of the payload this descriptor describes."
+ ),
+ )
+ rendered_markdown: str | None = Field(
+ default=None,
+ description=(
+ "Opt-in Pipelex-API presentation extra: a server-rendered Markdown view of the valid verdict, "
+ "present only when the request's `render` includes `markdown`. Absent by default — the structured fields "
+ "remain the contract; this is the view."
+ ),
+ )
+
+
+class InvalidReport(BaseModel):
+ """The 200 **invalid** arm: a produced "invalid" verdict, discriminated on `is_valid: false`.
+
+ An invalid bundle is the *successful product* of a diagnostic call, not a transport failure
+ (the request was well-formed; the bundle was not), so it rides a **200** — the global
+ `problem+json` 422/5xx is reserved for the no-verdict conditions (malformed request body,
+ `mthds_sources` length mismatch, auth, server fault). The structural artifacts
+ (`bundle_blueprint`, `pipe_io_contracts`, `graph_spec`, `validated_pipes`) do not exist when
+ load/parse/wiring failed, so this arm omits them and carries only the per-error diagnostics
+ plus the runnability facts. The `input_form` and `output_form` views follow them into absence for
+ the same reason — both derive from a crate that was never assembled — so neither is declared here and `views`
+ has no effect on this arm (unlike `rendered_markdown`, which rides both arms because failure
+ text is exactly what a human surface wants).
+ """
+
+ is_valid: Literal[False] = False
+ """Discriminant of the invalid arm (mirrors `ValidReport`/`PipelexValidationReport`'s `Literal[True]`)."""
+
+ validation_errors: list[ValidationErrorItem] = Field(
+ default_factory=empty_list_factory_of(ValidationErrorItem),
+ description="Per-error diagnostics, built by pipelex's one shared builder — non-empty on every invalid verdict.",
+ )
+ pending_signatures: list[str] = Field(
+ default_factory=list,
+ description="Best-effort outstanding signatures; empty on the invalid arm since no library was assembled.",
+ )
+ is_runnable: Literal[False] = False
+ """An invalid bundle is never runnable."""
+
+ message: str = Field(default="MTHDS validation found errors", description="Human-readable summary of the verdict.")
+ rendered_markdown: str | None = Field(
+ default=None,
+ description=(
+ "Opt-in Pipelex-API presentation extra: a server-rendered Markdown view of the invalid verdict's "
+ "`validation_errors`, present only when the request's `render` includes `markdown`. Absent by default."
+ ),
+ )
+
+
+# Discriminated 200 response union (D-C): a consumer pattern-matches the one mandatory `is_valid`
+# field to learn the verdict, without inspecting a status code or catching an exception body.
+ValidationResponse = Annotated[Union[ValidReport, InvalidReport], Field(discriminator="is_valid")]
+
+
+ "/validate",
+ response_model=ValidationResponse,
+ # On top of the composite router's shared 401/413/422/500: the policy 403s (the
+ # `orchestration_mode` override gate it shares with `/start`, plus — for a `method_ref` —
+ # the custom-code sandbox gate and the structures refusal) and the `method_ref`
+ # package-not-found 404. Note what is deliberately NOT here: an *invalid bundle* is a
+ # produced verdict on a 200, never a 4xx — and a selector-resolution failure is a non-2xx
+ # problem+json, never an `is_valid: false` verdict.
+ responses={403: PROBLEM_403_RUN_POLICY, 404: PROBLEM_404_METHOD_PACKAGE},
+ openapi_extra={"x-mthds-protocol": True},
+)
+async def validate_mthds(request: Request, request_data: ValidateRequest) -> JSONResponse:
+ """Validate MTHDS content by parsing, loading, and dry-running pipes (MTHDS Protocol `POST /validate`).
+
+ `/validate` is a **diagnostic endpoint**: any verdict the validator can produce — valid,
+ invalid, or valid-but-not-runnable — rides a **200** discriminated in the body on `is_valid`.
+ Non-2xx is reserved for the cases where *no verdict could be produced*.
+
+ Response contract:
+
+ - **Valid verdict (200, `is_valid: true`):** the `ValidReport` arm — the canonical report
+ (primary `bundle_blueprint`, `pipe_io_contracts` keyed by namespaced `pipe_ref`, per-pipe
+ `validated_pipes` sweep outcomes, `pending_signatures` + `is_runnable` runnability verdict,
+ best-effort `graph_spec`) plus the wire extras (`mthds_contents` echo, `message`,
+ `default_pipe_ref`). The graph is drawn from the pipe a selector-less run of this request
+ would execute: on a `method_ref` request whose manifest names a `main_pipe`, that pipe;
+ otherwise the primary blueprint's `main_pipe`. A bundle that declares no `main_pipe`, with
+ no manifest naming one, validates fine and carries `graph_spec=null`, and so does a
+ manifest `main_pipe` the closure does not resolve. Pending signatures are reported as `pending_signatures` +
+ `is_runnable: false`, never as an error. `default_pipe_ref` names the pipe a selector-less
+ run of this same request would execute — on a `method_ref` request that is the fetched
+ manifest's `main_pipe`, which the canonical report cannot see, so the field is the only
+ signal a consumer can project a by-address entry signature from.
+ The opt-in `views` tokens `input_form` and `output_form` additionally attach the per-pipe
+ input-form and output-form descriptors as same-named top-level fields, keyed like
+ `pipe_io_contracts`; without a token the matching field is absent and the body is
+ byte-identical to a request that omits `views`. They are separate tokens because they answer
+ separate questions — a caller building a fill-in form wants the inputs, a caller rendering a
+ result or registering a tool signature with a return type wants the output.
+ - **Invalid verdict (200, `is_valid: false`):** the `InvalidReport` arm — `validation_errors[]`
+ (the structured per-error diagnostics, built by pipelex's one shared builder, incl. one
+ located `dry_run` item per pipe whose dry run failed) + `message`, with the structural artifacts absent. The runner
+ returns this as a value (`ErrorReport` with `validation_errors`) regardless of backend — the
+ in-process arm from the bundle's `ValidateBundleError`, the dispatched arm recovered from the
+ worker — so the route maps it to a 200 by matching validation diagnostics, never by catching an
+ exception. Returned `ErrorReport`s without validation diagnostics are backend/config/runtime
+ faults and keep the global RFC 7807 problem response path.
+ - **No verdict (non-2xx):** a malformed request body, an `mthds_sources` length mismatch, or
+ both/neither of `mthds_contents` / `method_ref` is a request-shape **422**; a forbidden
+ `orchestration_mode` override is a **403**; a host-wiring programmer error or a genuine
+ orchestrator fault is a **5xx**; auth is **401/403**. A `method_ref` **resolution failure**
+ is also a no-verdict condition — never an `is_valid: false`: a malformed reference or a
+ failed fetch is a **422**, no matching package in the repository a **404**, and the
+ custom-Python policy (the sandbox gate, the structures refusal) a **403**, each with the
+ originating error class as `error_type`. All are RFC 7807 `application/problem+json`
+ rendered by the global handler in `pipelex_api.exception_handlers` — routes never shape them.
+ """
+ # Opt-in presentation formats (D-D): resolved once, threaded into both 200 arms. Empty by
+ # default → no `rendered_*` field, response byte-identical to the no-`render` request.
+ requested_formats = _resolve_render_formats(request_data.render)
+ # Opt-in structured views (D-D, the `views` axis): resolved once, applied to the valid arm only.
+ # Empty by default → neither view field, response byte-identical to the no-`views` request.
+ requested_views = _resolve_validation_views(request_data.views)
+ # The validation is done for the caller: its dry runs and `pipe_dry_run` event carry the
+ # authenticated user and the body's groups, exactly as a run of this request would.
+ user_id = get_request_user_id(request)
+ # Verdict-as-value: the runner resolves the orchestration mode and dispatches through the bundle
+ # validator registry, returning either a validation verdict or a classified fault report.
+ # Only `ErrorReport`s with validation diagnostics are invalid-bundle verdicts (→ 200
+ # InvalidReport); backend/config/runtime reports keep the global problem+json mapping.
+ if request_data.method_ref is not None:
+ # Validate-by-address (the addressing design's Phase 2 delta): the runner resolves the
+ # `method_ref` through the SAME fetch path as a `method_ref` run, and the package's real
+ # file names feed `mthds_sources` so diagnostics carry true per-file labels. Every
+ # selector-resolution failure — parse, fetch, no package, ambiguity, the custom-Python
+ # policy — raises OUT of this block as a non-2xx problem+json: no verdict was produced,
+ # so it is never rendered as `is_valid: false` (that verdict is about MTHDS content).
+ with fetched_method_source(request_data.method_ref) as fetched:
+ validated_contents = fetched.mthds_contents
+ # The manifest's declared entry pipe outranks the closure's own in the run/build default
+ # chain, so it must reach `default_pipe_ref` — the report itself is manifest-blind — and
+ # the graph arm, which would otherwise draw the primary blueprint's `main_pipe`: a
+ # different pipe when the two disagree, and no graph at all when the bundles declare none.
+ # The bare code is passed as is, so the graph arm resolves it exactly as the run does.
+ manifest_main_pipe = fetched.main_pipe
+ verdict = await ApiRunner(
+ library_dirs=fetched.library_dirs,
+ user_id=user_id,
+ extras=request_data.analytics_groups,
+ ).validate_verdict(
+ mthds_contents=fetched.mthds_contents,
+ mthds_sources=fetched.mthds_sources,
+ allow_signatures=request_data.allow_signatures,
+ requested_orchestration_mode=request_data.orchestration_mode,
+ graph_pipe_code=manifest_main_pipe,
+ )
+ elif request_data.mthds_contents is not None:
+ validated_contents = request_data.mthds_contents
+ # Inline contents carry no manifest, so the closure's own declaration is the whole chain.
+ manifest_main_pipe = None
+ verdict = await ApiRunner(user_id=user_id, extras=request_data.analytics_groups).validate_verdict(
+ mthds_contents=request_data.mthds_contents,
+ mthds_sources=request_data.mthds_sources,
+ allow_signatures=request_data.allow_signatures,
+ requested_orchestration_mode=request_data.orchestration_mode,
+ graph_pipe_code=None,
+ )
+ else:
+ # Unreachable: the envelope's XOR validator already 422'd this shape. Kept for the type
+ # checker (and as a defensive backstop should the envelope ever loosen).
+ raise_validation_error(message="provide exactly one of `mthds_contents` or `method_ref`")
+ if not isinstance(verdict, PipelexValidationReport):
+ if verdict.validation_errors:
+ return _invalid_report_response(verdict, requested_formats=requested_formats)
+ return problem_response_from_error_report(verdict, request=request)
+ report = verdict
+
+ # Splat the report's own field/value pairs so a future canonical field rides the wire
+ # automatically — the wrapper never enumerates (and silently drops) report fields. `is_valid`
+ # rides through from the report as the valid-arm discriminant (True).
+ response_data = ValidReport.model_validate(
+ {
+ **dict(report),
+ "mthds_contents": validated_contents,
+ "default_pipe_ref": _effective_default_pipe_ref(report, manifest_main_pipe=manifest_main_pipe),
+ }
+ )
+ content = response_data.model_dump(mode="json", serialize_as_any=True, by_alias=True)
+ # `rendered_markdown` is a presentation extra (D-D), not part of the report: attach it only when
+ # `markdown` was requested, else pop it so the response stays byte-identical to a no-`render` call
+ # (the valid arm is dumped without `exclude_none`, so the default `null` would otherwise linger).
+ # Rendered from the canonical report dict — the same shape the local agent CLI feeds the renderer,
+ # so the valid-arm Markdown shares one source of truth and cannot drift in format/structure.
+ if RenderFormat.MARKDOWN in requested_formats:
+ content["rendered_markdown"] = format_validate_markdown(report.model_dump(mode="json"))
+ else:
+ content.pop("rendered_markdown", None)
+ # `input_form` is an opt-in structured view (D-D), not part of the default verdict: the canonical
+ # report always carries it (required there, so a backend that forgets to derive it fails loudly),
+ # so absence on the wire is an explicit pop — never a serialization side effect, since the field
+ # is a populated dict rather than a `None` `exclude_none` would drop. Popping keeps the default
+ # response byte-identical for the high-frequency callers (hook pipelines, CI gates, agent loops)
+ # that would otherwise pay for a form they discard.
+ if ValidationView.INPUT_FORM not in requested_views:
+ content.pop("input_form", None)
+ if ValidationView.OUTPUT_FORM not in requested_views:
+ content.pop("output_form", None)
+ return JSONResponse(content=content)
+
+
+def _invalid_report_response(error_report: ErrorReport, *, requested_formats: set[RenderFormat]) -> JSONResponse:
+ """Render a produced "invalid" verdict as a 200 `InvalidReport` (D-A / D-C / D-D).
+
+ The `validation_errors[]` come straight from pipelex's one shared builder via
+ `ValidateBundleError.to_error_report()`, so the hosted invalid arm carries the same typed
+ items the agent CLI emits (including one located `dry_run` item per pipe whose dry run failed —
+ the structured-info invariant, which the parse-level `blueprint_validation` residual makes total,
+ guarantees this list is non-empty on every invalid verdict that reaches the wire,
+ since the empty-`mthds_contents` edge case is a request-shape 422 via `min_length=1`).
+ `message` is the caller-facing summary the error report already carries.
+ """
+ invalid_report = InvalidReport(
+ validation_errors=error_report.validation_errors or [],
+ message=error_report.message,
+ )
+ # `exclude_none` drops each item's unset locators, so the wire items match the agent CLI's
+ # `extract_validation_errors` byte-for-byte (it dumps items the same way) — the "one error item,
+ # two surfaces" guarantee. The invalid arm's own fields are all non-None, so none are lost; and
+ # `rendered_markdown` stays absent here unless explicitly requested below.
+ content = invalid_report.model_dump(mode="json", serialize_as_any=True, by_alias=True, exclude_none=True)
+ # Opt-in presentation extra (D-D): a faithful render of the structured `validation_errors`,
+ # attached only when `markdown` was requested. Built from the just-dumped content so the renderer
+ # reads the same items the wire carries.
+ if RenderFormat.MARKDOWN in requested_formats:
+ content["rendered_markdown"] = render_invalid_validation_markdown(content)
+ return JSONResponse(content=content)
diff --git a/api/pipelex_api/routes/version.py b/api/pipelex_api/routes/version.py
new file mode 100644
index 000000000..4143e2782
--- /dev/null
+++ b/api/pipelex_api/routes/version.py
@@ -0,0 +1,51 @@
+"""`GET /version` — the MTHDS Protocol version handshake.
+
+Replaces the former `GET /pipelex_version` and `GET /api_version` routes with
+the single protocol route. ALWAYS PUBLIC: `pipelex_api.main` mounts this router under
+`/v1` WITHOUT the auth dependency (exactly like `/health`), because clients use
+it for handshake / feature detection before they have credentials.
+"""
+
+from importlib.metadata import PackageNotFoundError, version
+
+from fastapi import APIRouter
+from mthds.protocol.protocol import PROTOCOL_VERSION
+from pipelex.pipeline.runner import PipelexVersionInfo
+
+from pipelex_api.error_types import ErrorType
+from pipelex_api.errors import raise_internal_server_error
+from pipelex_api.openapi_responses import PROBLEM_500
+
+router = APIRouter(tags=["discovery"])
+
+IMPLEMENTATION_NAME = "pipelex-api"
+
+
+ "/version",
+ # This router mounts OUTSIDE the composite `/v1` router (public handshake — see the module
+ # docstring), so it inherits none of that router's shared problem responses. It takes no
+ # request body and no parameters, so there is nothing to reject: 500 (absent package
+ # metadata) is the only failure it can produce, and it never answers 401.
+ responses={500: PROBLEM_500},
+ openapi_extra={"x-mthds-protocol": True},
+)
+async def get_version() -> PipelexVersionInfo:
+ """Protocol and implementation versions (MTHDS Protocol `GET /version`).
+
+ The handshake clients use for feature detection: `implementation`
+ identifies this runner, `implementation_version` is this server package's
+ version, and `runtime_version` is the underlying pipelex runtime version.
+ """
+ try:
+ implementation_version = version(IMPLEMENTATION_NAME)
+ runtime_version = version("pipelex")
+ except PackageNotFoundError as exc:
+ raise_internal_server_error(f"Package metadata is not available: {exc}", error_type=ErrorType.PACKAGE_NOT_FOUND)
+ return PipelexVersionInfo(
+ protocol_version=PROTOCOL_VERSION,
+ runner_version=implementation_version,
+ implementation=IMPLEMENTATION_NAME,
+ implementation_version=implementation_version,
+ runtime_version=runtime_version,
+ )
diff --git a/api/pipelex_api/schemas/__init__.py b/api/pipelex_api/schemas/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/api/pipelex_api/schemas/models.py b/api/pipelex_api/schemas/models.py
new file mode 100644
index 000000000..bfb94a1ef
--- /dev/null
+++ b/api/pipelex_api/schemas/models.py
@@ -0,0 +1,653 @@
+"""Shared request/response models for API routes.
+
+These are API-server-only models. As of the MTHDS Protocol unification the
+protocol itself defines no request model (the SDK runners take the basic args
+as named parameters), so a server that wants a typed request body — like this
+one — owns it. `RunRequest` / `StartRequest` are defined here, not imported.
+"""
+
+from __future__ import annotations
+
+from ipaddress import ip_address
+from typing import Annotated, Any, Self
+from urllib.parse import urlparse
+
+from mthds.protocol.exceptions import PipelineRequestError
+from mthds.protocol.pipe_output import VariableMultiplicity
+from mthds.protocol.pipeline_inputs import PipelineInputs
+from pipelex.core.pipes.pipe_output import PipeOutput
+from pipelex.methods.fetching import MethodProvenance
+from pipelex.pipeline.pipeline_response import PipelexRunResultExecute, PipelexRunResultStart
+from pipelex.reporting.usage_records import TokensUsageRecord
+from pipelex.system.run_extras import validate_run_extras
+from pipelex.system.storage_scope import validate_read_scope, validate_storage_scope
+from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
+from pydantic.functional_validators import SkipValidation
+
+from pipelex_api.limits import (
+ MAX_CALLBACK_URL_LEN,
+ MAX_CALLBACK_URLS,
+ MAX_METHOD_REF_LEN,
+ MAX_MTHDS_FILE_BYTES,
+ MAX_MTHDS_FILES_PER_REQUEST,
+ MAX_PIPE_CODE_LEN,
+)
+
+
+def _ensure_mthds_file_within_bytes_limit(content: str) -> None:
+ """Enforce the per-file size bound shared by every route that accepts inline MTHDS content."""
+ if len(content.encode("utf-8")) > MAX_MTHDS_FILE_BYTES:
+ msg = f"MTHDS file exceeds {MAX_MTHDS_FILE_BYTES // 1024} KiB limit"
+ raise ValueError(msg)
+
+
+class RunRequest(BaseModel):
+ """Body of `POST /execute` — this server's typed request model.
+
+ The MTHDS Protocol has no request model (`mthds` deleted `RunRequest`: the
+ request body is just the basic args the runner already takes as named
+ parameters). pipelex-api keeps a typed model so it can publish the request
+ schema in its OpenAPI artifact and parse the body once.
+
+ The declared fields are the protocol's **basic** arguments. The model is
+ deliberately open (`extra="allow"`): a caller may send extra request
+ properties, and they are kept rather than silently dropped. Openness is not
+ a waiver, though — an unknown key never satisfies the run-source
+ precondition. Under the layered extension policy (the Pipelex workspace
+ spec `docs/specs/pipelex-platform-api.md` → "Layered extension policy"), an
+ extension-borne method selector is resolved by the layer that owns it
+ BEFORE the request reaches this one, so a body arriving here with no source
+ this server understands is an error whatever else it carries.
+
+ Attributes:
+ pipe_code: Code of the pipe to execute.
+ mthds_contents: List of MTHDS bundle contents to load.
+ inputs: Inputs in PipelineInputs format, as plain JSON — Pydantic validation is
+ skipped to preserve the flexible format (strings, lists, objects); the runtime
+ shapes each value against the entry pipe's declared input.
+ output_name: Name of the output slot to write to.
+ output_multiplicity: Output multiplicity setting.
+ dynamic_output_concept_ref: Override for the dynamic output concept ref.
+ bundle_b64: PIPELEX-API EXTENSION — base64-encoded zip of the whole method
+ bundle (`.mthds` + `.py` + `structures/*.py` + `requirements.txt`). Lets a
+ caller ship custom PipeFunc Python alongside the method; materialized into a
+ temporary library directory before the run. Mutually exclusive with `files`.
+ files: PIPELEX-API EXTENSION — the bundle as a `{relative_path: text}` map (the
+ unzipped equivalent of `bundle_b64`). Mutually exclusive with `bundle_b64`.
+ method_ref: PIPELEX-API EXTENSION — run a published method by address instead of
+ inline source. Resolved by THIS runner (git fetch at the tag, package located
+ by manifest identity); mutually exclusive with `mthds_contents` and with a
+ method bundle. `pipe_code` may accompany it to override the manifest's
+ `main_pipe`.
+ """
+
+ model_config = ConfigDict(extra="allow")
+
+ pipe_code: str | None = None
+ mthds_contents: list[str] | None = None
+ inputs: Annotated[PipelineInputs | None, SkipValidation] = None
+ output_name: str | None = None
+ output_multiplicity: VariableMultiplicity | None = None
+ dynamic_output_concept_ref: str | None = None
+ bundle_b64: str | None = Field(
+ default=None,
+ description=(
+ "PIPELEX-API EXTENSION (not part of the MTHDS Protocol) — base64-encoded zip of the whole "
+ "method bundle (`.mthds` + `.py` + `structures/*.py` + `requirements.txt`), materialized into a "
+ "temporary library directory before the run so custom PipeFunc Python travels with the method. "
+ "Mutually exclusive with `files`. Custom `.py` is only honored on a sandbox-hosted deployment."
+ ),
+ )
+ files: dict[str, str] | None = Field(
+ default=None,
+ description=(
+ "PIPELEX-API EXTENSION (not part of the MTHDS Protocol) — the method bundle as a "
+ "`{relative_path: text}` map (the unzipped equivalent of `bundle_b64`). Mutually exclusive with `bundle_b64`."
+ ),
+ )
+ method_ref: str | None = Field(
+ default=None,
+ min_length=1,
+ max_length=MAX_METHOD_REF_LEN,
+ description=(
+ "PIPELEX-API EXTENSION (not part of the MTHDS Protocol) — run a published method by reference instead of "
+ "inline source. Address form: `github.com/<owner>/<repo>[/<selector>][@<tag>]` (e.g. "
+ "`github.com/Pipelex/methods/[email protected]`) — resolved by THIS runner: the repository is fetched at the "
+ "tag (a bare address means the default branch at HEAD), the package is located by manifest identity, and "
+ "the resolved commit SHA is recorded as `method_provenance` on the response. Mutually exclusive with "
+ "`mthds_contents` and with a method bundle (`bundle_b64` / `files`); `pipe_code` may accompany it to "
+ "override the manifest's `main_pipe`. A package shipping custom Python is only honored on a sandbox-hosted "
+ "deployment, and a package declaring Python structure classes is always refused — hosted execution accepts "
+ "MTHDS concepts and sandboxed PipeFuncs, not in-process Python."
+ ),
+ )
+
+ @model_validator(mode="before")
+ @classmethod
+ def validate_request(cls, values: dict[str, Any]) -> dict[str, Any]:
+ # The protocol requires at least one of pipe_code / mthds_contents. A method bundle
+ # (`bundle_b64` / `files`) carries its own `.mthds` — so it satisfies the precondition
+ # on its own (the pipe to run comes from the bundle's `main_pipe`). Extension args carry
+ # NO waiver: see the class docstring and `_refuse_source_less_extension_body`, which
+ # authors the better message for that case where the raw body is still in hand.
+ has_bundle = values.get("bundle_b64") is not None or values.get("files") is not None
+ has_method_ref = values.get("method_ref") is not None
+ # A bundle carries its own `.mthds`; combining it with inline `mthds_contents` would load
+ # both into one library with no dedup, so a shared domain collides deep in the run with an
+ # opaque duplicate-domain error. Refuse the combination up front (a bundle + `pipe_code` — to
+ # pick which pipe in the bundle to run — is still fine).
+ if has_bundle and values.get("mthds_contents"):
+ msg = "A method bundle (bundle_b64 / files) and inline mthds_contents are mutually exclusive; send one or the other."
+ raise PipelineRequestError(msg)
+ # `method_ref` is a complete run source of its own (the fetched package carries its
+ # `.mthds` and its entry pipe): exactly one source per request, so it excludes both
+ # inline contents and a bundle. `pipe_code` beside it is fine — it overrides the
+ # manifest's `main_pipe` to pick which pipe in the fetched package to run.
+ if has_method_ref and values.get("mthds_contents"):
+ msg = "method_ref and inline mthds_contents are mutually exclusive; send one or the other."
+ raise PipelineRequestError(msg)
+ if has_method_ref and has_bundle:
+ msg = "method_ref and a method bundle (bundle_b64 / files) are mutually exclusive; send one or the other."
+ raise PipelineRequestError(msg)
+ if values.get("pipe_code") is None and not values.get("mthds_contents") and not has_bundle and not has_method_ref:
+ msg = (
+ "pipe_code and mthds_contents cannot both be empty. Either: both are provided, or if there are no mthds_contents, "
+ "then pipe_code must be provided and must reference a pipe already registered in the library. "
+ "If mthds_contents is provided but no pipe_code, the first content must have a main_pipe property."
+ )
+ raise PipelineRequestError(msg)
+ return values
+
+ @classmethod
+ def _refuse_source_less_extension_body(cls, *, request_body: dict[str, Any], mthds_contents: list[str] | None) -> None:
+ """Diagnose "a hosted client was pointed at this runner" before the generic precondition fires.
+
+ This lives here, and not in `validate_request`, because only the RAW body still
+ holds the keys the message needs to name: the model copies the declared fields
+ only, so by the time the validator runs the unknown keys are already gone.
+
+ Fires only when the body carries NO run source this server understands AND at
+ least one key it does not handle. A source-less body whose every key IS handled
+ falls through to `validate_request`'s base guidance — there is no extension to
+ name there. Wording stays deployment-neutral: the runner does not know whether
+ it is hosted, so it reports what it handles, never what the caller "should have"
+ deployed.
+
+ Precedence: `_parse_request` validates `PipelineApiExtras` before calling
+ `from_body`, so a body that is BOTH source-less and carries a malformed handled
+ extra (a non-http(s) `callback_urls` entry, say) gets the extras 422 and never
+ reaches this diagnostic. That ordering is deliberate — both are caller mistakes
+ answered with the same status and error domain, and demoting a concrete malformed
+ value to surface a second message would be the worse trade. The naming guarantee
+ therefore covers the single-fault case.
+ """
+ has_bundle = request_body.get("bundle_b64") is not None or request_body.get("files") is not None
+ if request_body.get("pipe_code") is not None or mthds_contents or has_bundle or request_body.get("method_ref") is not None:
+ return
+ # `PipelineApiExtras` is defined below in this module — resolved at call time, which is
+ # always after import. Its fields are the API-server-only keys the routes DO handle —
+ # `_validate_extras` validates the body against this very model — so naming one of them
+ # as "not handled" would be a lie.
+ handled_keys = set(cls.model_fields) | set(PipelineApiExtras.model_fields) | {"mthds_content"}
+ unhandled_keys = sorted(key for key in request_body if key not in handled_keys)
+ if not unhandled_keys:
+ return
+ named = ", ".join(f"`{key}`" for key in unhandled_keys)
+ msg = (
+ "This request carries no run source this server understands (pipe_code, mthds_contents, "
+ f"or a method bundle). The extension args it does carry ({named}) are not handled by this "
+ "deployment — a hosted-only selector such as `method_id` must be sent to the hosted API, "
+ "which resolves it into a run source before any runner sees the request."
+ )
+ raise PipelineRequestError(msg)
+
+ @classmethod
+ def from_body(cls, request_body: dict[str, Any]) -> RunRequest:
+ """Build a RunRequest from the raw request-body dictionary.
+
+ Supports both the singular `mthds_content` (legacy) and plural
+ `mthds_contents`. `inputs` defaults to `{}` so a body that omits it
+ still parses.
+ """
+ mthds_contents = request_body.get("mthds_contents")
+ if mthds_contents is None:
+ mthds_content = request_body.get("mthds_content")
+ if mthds_content is not None:
+ mthds_contents = [mthds_content]
+ cls._refuse_source_less_extension_body(request_body=request_body, mthds_contents=mthds_contents)
+ return cls(
+ pipe_code=request_body.get("pipe_code"),
+ mthds_contents=mthds_contents,
+ inputs=request_body.get("inputs", {}),
+ output_name=request_body.get("output_name"),
+ output_multiplicity=request_body.get("output_multiplicity"),
+ dynamic_output_concept_ref=request_body.get("dynamic_output_concept_ref"),
+ bundle_b64=request_body.get("bundle_b64"),
+ files=request_body.get("files"),
+ method_ref=request_body.get("method_ref"),
+ )
+
+
+class StartRequest(RunRequest):
+ """Body of `POST /start` — `RunRequest` plus the optional `pipeline_run_id`.
+
+ `pipeline_run_id` is the client-supplied run identifier; this source-available
+ runner accepts it (the server-generated id echoed in the start ack is always
+ authoritative). Extension args pass through `extra="allow"` exactly as on
+ `RunRequest`.
+ """
+
+ pipeline_run_id: str | None = Field(default=None, max_length=128)
+
+
+_STORAGE_SCOPE_DESCRIPTION = (
+ "PIPELEX-API EXTENSION (not part of the MTHDS Protocol) — the host-supplied prefix every object "
+ "this run writes lands under. One to three path-safe segments (e.g. `tenant/run` or "
+ "`org/method/run`); the runtime composes its own leaves (`assets/`, `generated/`, `results/`, "
+ "`payloads/`) onto "
+ "it and never interprets the value. Omit it and the run is scoped to the caller's own id, which "
+ "is correct for a single-tenant deployment and wrong for a multi-tenant one — a host serving many "
+ "tenants MUST send this."
+)
+
+_READ_SCOPE_DESCRIPTION = (
+ "PIPELEX-API EXTENSION (not part of the MTHDS Protocol) — the host-supplied prefix every stored object "
+ "this run reads must lie under, and on a scoped run no local path is read at all. One to three "
+ "path-safe segments, which must be the `storage_scope` or one of its leading segments, since a run "
+ "reads back what it writes. Omit it and the run is scoped to the caller's own id when the deployment "
+ "identifies callers, and unscoped when it is single-tenant — a host serving many tenants MUST send this."
+)
+
+_ANALYTICS_GROUPS_DESCRIPTION = (
+ "PIPELEX-API EXTENSION (not part of the MTHDS Protocol) — the host-supplied groups this run's "
+ 'telemetry belongs to, as a mapping of group type to group key (e.g. `{"organization": "org_acme"}`). '
+ "The runtime never reads a key by name: it carries the mapping on the run as its `extras` and stamps it on every span as "
+ "`pipelex.run.extras`, so every OpenTelemetry exporter receives it, and the deployment's own "
+ "PostHog stream, in `identified` mode, forwards it as the capture's groups. What Pipelex's own Gateway telemetry "
+ "stream receives is the runtime's decision, not this server's: the pinned runtime attributes it the same way, "
+ "with the run's `user_id` and these groups. Group types are lowercase snake_case starting with a letter, at most 32 characters; group keys "
+ "are 1 to 128 characters from `[A-Za-z0-9_-]`; at most five entries. Omit it and the run belongs to no "
+ "group, which is right for a single-tenant deployment."
+)
+
+_CALLER_ANALYTICS_GROUPS_DESCRIPTION = (
+ "PIPELEX-API EXTENSION (not part of the MTHDS Protocol) — the host-supplied groups the caller of this request "
+ 'belongs to, as a mapping of group type to group key (e.g. `{"organization": "org_acme"}`), exactly as a run '
+ "request states them. The work this request does is not a run, but it still emits telemetry — the validation "
+ "sweep's `pipe_dry_run` event and its dry runs — and that telemetry is attributed to the caller: the "
+ "authenticated user and these groups. Same rules and same 422 `InvalidAnalyticsGroups` refusal as on "
+ "`/execute` and `/start`. Omit it and the caller belongs to no group."
+)
+
+
+class CallerAnalyticsGroupsMixin(BaseModel):
+ """The optional `analytics_groups` of a request whose work is done for a caller without being a run.
+
+ `/validate` and `/build/runner` dry-run the submitted pipes, and the runtime attributes that
+ telemetry to the caller it is handed (`pipelex.system.caller_identity.CallerIdentity`). The user
+ comes from the trusted auth layer, as on a run; the groups come from the body, as on a run, and are
+ refused at the wire with the runtime's own rules.
+ """
+
+ analytics_groups: dict[str, str] | None = Field(default=None, description=_CALLER_ANALYTICS_GROUPS_DESCRIPTION)
+
+ @field_validator("analytics_groups")
+ @classmethod
+ def _validate_caller_analytics_groups(cls, value: dict[str, str] | None) -> dict[str, str] | None:
+ if value is None:
+ return None
+ return validate_run_extras(value=value)
+
+
+_ORCHESTRATION_MODE_DESCRIPTION = (
+ "PIPELEX-API EXTENSION (not part of the MTHDS Protocol) — request the orchestration mode (the backend) "
+ "for this run. An OPEN string token: `direct` (in-process, the base default), `temporal`, and any other "
+ "plugin-provided token are accepted; an unregistered token is refused at dispatch. The delivery axis "
+ "(blocking vs fire-and-forget) is endpoint-set, never requestable. Honored ONLY when the deployment sets "
+ "`allow_request_orchestration_mode_override = true` in its `api.toml`; otherwise a token that differs from "
+ "the deployment default is refused with a 403. Omit it to use the deployment default."
+)
+
+
+_ALLOWED_CALLBACK_SCHEMES = frozenset({"http", "https"})
+
+
+def _is_disallowed_host(host: str) -> bool:
+ """True if `host` looks like a private/loopback/link-local address.
+
+ Used to harden /start callback_urls against SSRF — a malicious
+ client could otherwise aim webhooks at internal services or cloud metadata
+ endpoints (e.g. 169.254.169.254). Best-effort: hostnames that resolve to
+ private addresses at fire time aren't blocked here, only literal IPs.
+ """
+ if not host:
+ return True
+ if host in {"localhost", "metadata.google.internal", "metadata"}:
+ return True
+ try:
+ addr = ip_address(host)
+ except ValueError:
+ return False
+ return addr.is_private or addr.is_loopback or addr.is_link_local or addr.is_multicast or addr.is_reserved or addr.is_unspecified
+
+
+class PipelineApiExtras(BaseModel):
+ """Validates the API-server-only fields on `/execute` and `/start` requests.
+
+ `pipeline_run_id` is the protocol's optional start arg; `callback_urls` is
+ THIS server's extension (the MTHDS Protocol defines no completion channel —
+ extension args are defined and handled by the implementation that owns
+ them). The upstream protocol models don't know about `callback_urls`.
+
+ `storage_scope`, `read_scope` and `analytics_groups` are the host-computed run
+ context: data a multi-tenant host knows about its own tenancy and sends in the
+ body, as opposed to the caller's identity, which arrives on a trusted header. The
+ runtime carries them opaquely and validates them again at its own seam.
+ """
+
+ model_config = ConfigDict(extra="ignore")
+
+ pipeline_run_id: str | None = Field(default=None, max_length=128)
+ callback_urls: list[str] | None = Field(default=None, max_length=MAX_CALLBACK_URLS)
+ orchestration_mode: str | None = Field(default=None, description=_ORCHESTRATION_MODE_DESCRIPTION)
+ storage_scope: str | None = Field(default=None, description=_STORAGE_SCOPE_DESCRIPTION)
+ read_scope: str | None = Field(default=None, description=_READ_SCOPE_DESCRIPTION)
+ analytics_groups: dict[str, str] | None = Field(default=None, description=_ANALYTICS_GROUPS_DESCRIPTION)
+
+ @field_validator("read_scope")
+ @classmethod
+ def _validate_read_scope(cls, value: str | None) -> str | None:
+ """Refuse a malformed read scope at the WIRE, with the runtime's own segment rule.
+
+ Its relation to the storage scope is checked once both are resolved, since either may
+ fall back to the caller's id (`pipelex_api.routes.pipelex.pipeline._resolve_run_scopes`).
+ """
+ if value is None:
+ return None
+ return validate_read_scope(value=value)
+
+ @field_validator("storage_scope")
+ @classmethod
+ def _validate_storage_scope(cls, value: str | None) -> str | None:
+ """Reject a traversal at the WIRE, not just at `JobMetadata`.
+
+ `validate_storage_scope` guards the runtime seam too, so this is a
+ second gate rather than the only one — but it is the one that answers a
+ bad request with a 422 naming the field, instead of a 500 from deep in
+ the run. The value becomes a storage key prefix, so a `..` in it escapes
+ the tenant it is supposed to confine.
+ """
+ if value is None:
+ return None
+ return validate_storage_scope(value=value)
+
+ @field_validator("analytics_groups")
+ @classmethod
+ def _validate_analytics_groups(cls, value: dict[str, str] | None) -> dict[str, str] | None:
+ """Refuse a malformed mapping at the WIRE, with the runtime's own rules.
+
+ The runtime validates the mapping again at the top of `pipeline_run_setup`
+ and on `RunMetadata`, so this is not the only gate. It is the one that
+ answers with a 422 naming the field before a method is fetched or a
+ library loaded. The rules are imported rather than restated: a second
+ spelling of the charset here would drift from the one the runtime
+ enforces, and the drift would surface as a 500 from inside the run.
+ """
+ if value is None:
+ return None
+ return validate_run_extras(value=value)
+
+ @field_validator("callback_urls")
+ @classmethod
+ def _validate_callback_urls(cls, value: list[str] | None) -> list[str] | None:
+ if not value:
+ return value
+ for url in value:
+ if not url:
+ msg = "callback_urls must be non-empty strings"
+ raise ValueError(msg)
+ if len(url) > MAX_CALLBACK_URL_LEN:
+ msg = f"callback URL exceeds {MAX_CALLBACK_URL_LEN} chars"
+ raise ValueError(msg)
+ parsed = urlparse(url)
+ if parsed.scheme not in _ALLOWED_CALLBACK_SCHEMES:
+ msg = f"callback URL scheme must be http or https (got {parsed.scheme!r})"
+ raise ValueError(msg)
+ if _is_disallowed_host(parsed.hostname or ""):
+ msg = f"callback URL host {parsed.hostname!r} is not allowed (private/loopback/metadata addresses are blocked)"
+ raise ValueError(msg)
+ return value
+
+
+class PipelexApiStartRequest(StartRequest):
+ """Documented body of `POST /start` — the protocol's `StartRequest` plus THIS server's extensions.
+
+ Used only to publish the OpenAPI request schema: the protocol model no
+ longer advertises implementation extensions, so this server documents the
+ ones it implements itself. Wire validation happens in `PipelineApiExtras`.
+ """
+
+ callback_urls: list[str] | None = Field(
+ default=None,
+ description=(
+ "PIPELEX-API EXTENSION (not part of the MTHDS Protocol) — completion webhooks. "
+ "When the run finishes, the runner POSTs a completion notice to each URL, with an "
+ "X-Completion-Signature header holding the HMAC-SHA256 of the run id (not of the body). "
+ "The body carries `pipeline_run_id`, `state` (with the legacy `status` alias), `result_url` "
+ "(the storage key prefix of the stored results, when results were stored) and `error` on "
+ "failure; it does not carry the run's output. http/https only; private, loopback, link-local "
+ "and cloud-metadata hosts are rejected."
+ ),
+ )
+ orchestration_mode: str | None = Field(default=None, description=_ORCHESTRATION_MODE_DESCRIPTION)
+ storage_scope: str | None = Field(default=None, description=_STORAGE_SCOPE_DESCRIPTION)
+ read_scope: str | None = Field(default=None, description=_READ_SCOPE_DESCRIPTION)
+ analytics_groups: dict[str, str] | None = Field(default=None, description=_ANALYTICS_GROUPS_DESCRIPTION)
+
+
+class PipelexApiExecuteRequest(RunRequest):
+ """Documented body of `POST /execute` — the protocol's `RunRequest` plus THIS server's run extensions.
+
+ Used only to publish the OpenAPI request schema: `/execute` reads the body through the raw
+ `Request` (plain JSON, parsed by the route), so FastAPI cannot infer the body type; this model documents the
+ extensions the route actually honors (`orchestration_mode`, `storage_scope`, `read_scope`, `analytics_groups`,
+ all parsed by `PipelineApiExtras`).
+ """
+
+ orchestration_mode: str | None = Field(default=None, description=_ORCHESTRATION_MODE_DESCRIPTION)
+ storage_scope: str | None = Field(default=None, description=_STORAGE_SCOPE_DESCRIPTION)
+ read_scope: str | None = Field(default=None, description=_READ_SCOPE_DESCRIPTION)
+ analytics_groups: dict[str, str] | None = Field(default=None, description=_ANALYTICS_GROUPS_DESCRIPTION)
+
+
+class PipeOutputWire(PipeOutput):
+ """`PipeOutput` as it crosses the client boundary: usages trimmed to wire records.
+
+ The route applies pipelex's `apply_tokens_usage_wire_shape` to the response dump, so
+ `tokens_usages` carries flat `TokensUsageRecord`s — not the internal usage models with
+ their `job_metadata` plumbing and `unit_costs` rate table.
+ """
+
+ # Narrows the inherited `list[AnyTokensUsage] | None`. `list` is invariant, so neither
+ # type checker accepts the override; this is a schema declaration, not an assignment a
+ # `cast()` could carry.
+ tokens_usages: list[TokensUsageRecord] | None = None # type: ignore[assignment]
+
+
+_METHOD_PROVENANCE_DESCRIPTION = (
+ "PIPELEX-API EXTENSION (not part of the MTHDS Protocol) — provenance of a `method_ref` run: the package's "
+ "resolved full address, the requested tag (null for a bare address), and the commit SHA that was actually "
+ "fetched. The SHA is what keeps the run explainable when a tag moves. Absent (or null) for runs from inline "
+ "source or a bundle."
+)
+
+
+class PipelexApiExecuteResponse(PipelexRunResultExecute):
+ """Documented 200 body of `POST /execute` — the run result with the wire-shaped `pipe_output`.
+
+ Used only to publish the OpenAPI response schema. `/execute` returns a `JSONResponse`
+ built from the trimmed dump, so FastAPI never serializes through this model; declaring it
+ is what keeps the published artifact honest about what the route actually emits
+ (`method_provenance` is attached to the dump by the route for `method_ref` runs, and is
+ absent otherwise).
+ """
+
+ pipe_output: PipeOutputWire # type: ignore[assignment]
+ method_provenance: MethodProvenance | None = Field(default=None, description=_METHOD_PROVENANCE_DESCRIPTION)
+
+
+class PipelexApiStartResponse(PipelexRunResultStart):
+ """The 202 body of `POST /start` — the protocol's start ack plus this server's `method_provenance` extension.
+
+ Unlike its `/execute` counterpart this model IS what the route returns (FastAPI serializes
+ through it): the ack is small, so wrapping it costs nothing and keeps the artifact and the
+ wire in lockstep. `method_provenance` is populated for `method_ref` runs and null otherwise.
+ """
+
+ method_provenance: MethodProvenance | None = Field(default=None, description=_METHOD_PROVENANCE_DESCRIPTION)
+
+
+class MthdsFileItem(BaseModel):
+ """One inline MTHDS bundle: its content plus an optional logical source for diagnostics.
+
+ The `files[]` envelope pairs each content with its source in one entry (the shape the codegen
+ spec pins for the resolve/codegen routes), unlike the legacy parallel
+ `mthds_contents[]`/`mthds_sources[]` lists on `/validate`.
+ """
+
+ content: str = Field(..., description="MTHDS bundle content.")
+ source: str | None = Field(
+ default=None,
+ max_length=1024,
+ description=(
+ "Optional logical source for this bundle (e.g. its path relative to the submitted directory). "
+ "Threaded onto the blueprint so server-side diagnostics carry a `source` pointing at the owning file."
+ ),
+ )
+
+ @field_validator("content")
+ @classmethod
+ def _bound_content(cls, value: str) -> str:
+ _ensure_mthds_file_within_bytes_limit(value)
+ return value
+
+
+class MthdsFilesRequest(BaseModel):
+ """Shared closure selector for the resolve/codegen routes: inline `files[]` XOR a `method_ref`.
+
+ Exactly one of the two must be provided (spec'd envelope) — both or neither is a request-shape
+ 422. An **address-form** `method_ref` (`github.com/<owner>/<repo>[/<selector>][@<tag>]`) is
+ resolved by this server: the repository is fetched at the tag, the package is located by
+ manifest identity, and its `.mthds` files feed the closure with their real relative paths as
+ per-file sources. The **registry form** (any non-address reference) stays reserved and answers
+ 501 until server-side method-registry resolution exists.
+ """
+
+ files: list[MthdsFileItem] | None = Field(
+ default=None,
+ min_length=1,
+ max_length=MAX_MTHDS_FILES_PER_REQUEST,
+ description="Inline MTHDS bundles forming the closure to resolve (content-passing — no server-side path reads).",
+ )
+ method_ref: str | None = Field(
+ default=None,
+ min_length=1,
+ max_length=MAX_METHOD_REF_LEN,
+ description=(
+ "Reference to a published method, resolving to its package's `.mthds` files. Address form "
+ "(`github.com/<owner>/<repo>[/<selector>][@<tag>]`) is fetched and resolved server-side; the registry "
+ "form stays reserved (501 until a method registry exists)."
+ ),
+ )
+
+ @model_validator(mode="after")
+ def _exactly_one_selector(self) -> Self:
+ if (self.files is None) == (self.method_ref is None):
+ msg = "provide exactly one of `files` or `method_ref`"
+ raise ValueError(msg)
+ return self
+
+
+class MthdsPipeRequest(MthdsFilesRequest):
+ """Shared base for the per-pipe `/build/*` projections: the closure selector plus a pipe selector.
+
+ The pipe selector is the **qualified** ref `domain.pipe_code`, mirroring `pipelex codegen inputs
+ --pipe`. It is optional, and an omitted selector defaults with the run routes' precedence: on a
+ `method_ref` request, to the fetched package manifest's `main_pipe` (the package author's declared
+ entry pipe); otherwise to the closure's declared `main_pipe`, which is what a single-bundle caller
+ almost always wants. A closure that declares no `main_pipe` — or several, across domains — cannot
+ be defaulted from its own declarations, so an omitted selector is a request-shape 422 there when
+ no manifest `main_pipe` settles it (the same two arms the CLI rejects on).
+ """
+
+ pipe_ref: str | None = Field(
+ default=None,
+ min_length=1,
+ max_length=MAX_PIPE_CODE_LEN,
+ description=(
+ "Qualified pipe ref (`domain.pipe_code`) to project. Optional — defaults to the fetched package manifest's "
+ "`main_pipe` on a `method_ref` request, else to the closure's declared `main_pipe`; a closure declaring none, "
+ "or several, with no manifest `main_pipe` to settle it, requires it explicitly."
+ ),
+ )
+
+
+ALLOW_SIGNATURES_DESCRIPTION = (
+ "When true, the validation sweep tolerates unimplemented pipe signatures instead of rejecting the "
+ "bundle (signatures dry-run trivially by minting a mock). Defaults to false (strict)."
+)
+"""Shared by the two routes that still run the dry-run sweep (`/validate`, `/build/runner`) — the flag only
+parameterizes that sweep, so the static `/build/{inputs,output}` projections do not accept it."""
+
+
+class MthdsContentsRequest(BaseModel):
+ """The `POST /validate` request envelope: `mthds_contents` XOR `method_ref`, plus the sweep's `allow_signatures`.
+
+ This is the flat-list envelope. `/validate` uses it through this class (its `ValidateRequest`
+ subclass adds a parallel `mthds_sources` for per-file source labels), and the run routes
+ `/execute` and `/start` carry the same `mthds_contents` field independently on `RunRequest`.
+ The newer Pipelex-API extension routes (`/resolve`, `/codegen`, `/build/*`) use
+ `MthdsFilesRequest` instead (`files[]` pairing each content with its `source`, XOR a
+ `method_ref`), which folds the source label into each entry. `/validate` keeps the flat-list
+ shape deliberately: it is an MTHDS Protocol route, so changing its inline envelope is a
+ protocol-level decision owned by the `mthds/` spec, not this server's to take. `method_ref` is
+ this server's layer-2 extension beside that inline shape — an address is resolved by the
+ runner, so validate-by-address belongs here (the hosted-only `method_id` does not).
+ """
+
+ mthds_contents: list[str] | None = Field(
+ default=None,
+ min_length=1,
+ max_length=MAX_MTHDS_FILES_PER_REQUEST,
+ description="MTHDS contents to load (always an array, even for a single file). Exactly one of `mthds_contents` / `method_ref`.",
+ )
+ method_ref: str | None = Field(
+ default=None,
+ min_length=1,
+ max_length=MAX_METHOD_REF_LEN,
+ description=(
+ "PIPELEX-API EXTENSION (not part of the MTHDS Protocol) — validate a published method by reference "
+ "instead of inline contents. Address form: `github.com/<owner>/<repo>[/<selector>][@<tag>]`, resolved by "
+ "THIS runner through the same fetch path as a `method_ref` run; the package's `.mthds` files feed the "
+ "validation with their real relative paths as per-file sources. Exactly one of `mthds_contents` / "
+ "`method_ref`. A resolution failure (fetch, package location, the custom-Python policy) is a non-2xx "
+ "`problem+json` — never an `is_valid: false` verdict, which is reserved for actual MTHDS content."
+ ),
+ )
+ allow_signatures: bool = Field(default=False, description=ALLOW_SIGNATURES_DESCRIPTION)
+
+ @field_validator("mthds_contents")
+ @classmethod
+ def _bound_each_file(cls, value: list[str] | None) -> list[str] | None:
+ for content in value or []:
+ _ensure_mthds_file_within_bytes_limit(content)
+ return value
+
+ @model_validator(mode="after")
+ def _exactly_one_content_selector(self) -> Self:
+ # Strict XOR (the addressing design's tooling-route rule): a stateless diagnostic call
+ # has no linkage slot, so a second selector could only be ignored — refuse it instead.
+ if (self.mthds_contents is None) == (self.method_ref is None):
+ msg = "provide exactly one of `mthds_contents` or `method_ref`"
+ raise ValueError(msg)
+ return self
diff --git a/api/pipelex_api/security.py b/api/pipelex_api/security.py
new file mode 100644
index 000000000..2383b6934
--- /dev/null
+++ b/api/pipelex_api/security.py
@@ -0,0 +1,284 @@
+"""Authentication module with configurable AUTH_MODE (none, jwt, api_key).
+
+User identity is extracted during auth and stored on request.state.user as a RequestUser.
+Route handlers access it via the get_request_user dependency.
+"""
+
+import re
+from enum import StrEnum
+from typing import Annotated, Any
+
+import jwt
+from fastapi import Depends, Request
+from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
+from pipelex import log
+from pipelex.system.environment import get_optional_env
+from pipelex.system.storage_scope import SINGLE_TENANT_USER_ID
+from pydantic import BaseModel, Field
+
+from pipelex_api.error_types import ErrorType
+from pipelex_api.errors import raise_bad_request, raise_internal_server_error, raise_unauthenticated
+
+# JWT Configuration (only used when AUTH_MODE=jwt)
+JWT_ALGORITHM = "HS256"
+
+# A caller's `user_id` is the first path segment of every `pipelex-storage://`
+# URI and S3 key (`<user_id>/...`). The runner treats it as an OPAQUE id and
+# does NOT validate its identity/shape: a self-hosted deployment may use any id
+# scheme (uuid, `user_<uuid>`, …), and a hosted deployment behind a trusted
+# proxy receives the *authenticated* id the gateway injects (derived from the
+# JWT / API key — never client-chosen). The only constraint is that the id be a
+# single, UNAMBIGUOUS path segment, because it is embedded into a
+# `pipelex-storage://<user_id>/...` URI / S3 key:
+# - PATH-SAFE: no `/`, `\`, NUL/control chars, DEL; and not `.`/`..` (no traversal).
+# - URI-UNAMBIGUOUS: no URI gen-delims (`:`, `?`, `#`, `[`, `]`, `@`). These
+# parse differently under a raw split vs a standard URI parser — e.g.
+# `pipelex-storage://google#abc/...` has owner `google#abc` by raw split but
+# `google` (with `abc/...` as the fragment) under `urlparse`, so a consumer
+# could resolve a different owner than the one this server authorized.
+_PATH_UNSAFE_CHARS = re.compile(r"[/\\:?#\[\]@\x00-\x1f\x7f]")
+
+
+def is_safe_user_id(value: str) -> bool:
+ """True if `value` is usable as a single, path-safe, URI-unambiguous key segment (opaque id)."""
+ return bool(value) and value not in (".", "..") and _PATH_UNSAFE_CHARS.search(value) is None
+
+
+# `SINGLE_TENANT_USER_ID`, imported above from the runtime, is the caller id for
+# a deployment that has declared it has NO user model: `AUTH_MODE=none` with
+# `TRUST_FORWARDED_IDENTITY_HEADERS` off. Such a server has exactly one tenant by
+# configuration, so one namespace is correct rather than accidental.
+#
+# **This is not the `anonymous` sentinel under another name, and the difference
+# is the whole point.** `anonymous` was reached by FALLBACK — a deployment that
+# expected an identity, did not get one, and silently continued under a shared
+# owner. Every tenant of such a server wrote into the same prefix and could read
+# each other's outputs, and it looked exactly like a working request. There is
+# no fallback to this value: it is used only where the deployment has said, in
+# its own configuration, that it has no users. A deployment that expects
+# identity and lacks one now fails with 401.
+#
+# A token may never bind it (`verify_jwt` below), or an authenticated caller
+# could land in the single-tenant namespace on a server that does have users.
+#
+# It is the runtime's constant rather than a literal of our own because the
+# runtime recognises it: every deployment configured this way sends the same
+# string, so telemetry declines it as a person and attributes the run to the
+# stream's configured fallback instead. A second spelling here would drift from
+# that one, and every single-tenant deployment would then merge onto one
+# PostHog person with nothing failing to say so.
+
+
+# `auto_error=False` so a missing/empty/non-Bearer `Authorization` header
+# does NOT raise FastAPI's default `HTTPException` (which would emit
+# `application/json` `{"detail": "Not authenticated"}` — the old, pre-RFC-7807
+# shape) before our verifiers run. With `auto_error=False`, `HTTPBearer`
+# returns `None` in that case, and the verifiers below raise
+# `raise_unauthenticated(...)` so the response is the same RFC 7807
+# `application/problem+json` document as every other 401 on the surface.
+security = HTTPBearer(auto_error=False)
+
+
+class AuthMode(StrEnum):
+ NONE = "none"
+ JWT = "jwt"
+ API_KEY = "api_key"
+
+
+class ForwardedIdentityHeader(StrEnum):
+ """HTTP headers a trusted reverse proxy may forward to authenticate
+ a caller when `TRUST_FORWARDED_IDENTITY_HEADERS=true`.
+
+ The runner is a generic execution engine: the ONLY piece of identity
+ it consumes is an opaque user id, which it scopes S3 storage keys
+ under (`<user_id>/...`). Anything else a proxy might want to forward
+ (email, OAuth subject, auth method) is metadata the runner has no
+ use for — handlers that need it look it up by `user_id` against the
+ deployment's own user store.
+ """
+
+ USER_ID = "X-User-Id"
+
+
+class RequestUser(BaseModel):
+ """Authenticated caller identity available to route handlers.
+
+ Holds only `user_id` by design — the runner is a generic execution engine
+ and does not own user metadata (email, name, OAuth subject). Deployments
+ that need that data look it up by `user_id` against their own user store.
+ """
+
+ user_id: str = Field(..., description="Opaque caller identifier supplied by the auth layer or the trusted proxy")
+
+
+def _set_request_user(request: Request, user_id: str) -> None:
+ """Store caller identity on request.state for downstream handlers."""
+ request.state.user = RequestUser(user_id=user_id)
+
+
+def get_auth_mode() -> AuthMode:
+ """Read AUTH_MODE from environment. Defaults to 'none'."""
+ raw = get_optional_env("AUTH_MODE")
+ if not raw:
+ return AuthMode.NONE
+ try:
+ return AuthMode(raw)
+ except ValueError:
+ log.warning(f"Unknown AUTH_MODE '{raw}', falling back to 'none'")
+ return AuthMode.NONE
+
+
+async def verify_jwt(
+ request: Request,
+ credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)],
+) -> dict[str, Any]:
+ """Validate JWT token from Authorization header using JWT_SECRET_KEY."""
+ if credentials is None:
+ # Missing, empty, or non-Bearer `Authorization` header. `HTTPBearer`
+ # is configured with `auto_error=False` so this branch (rather than
+ # FastAPI's default `HTTPException`) shapes the response — same RFC
+ # 7807 `application/problem+json` as every other 401.
+ log.warning("JWT auth requested without a Bearer token")
+ raise_unauthenticated("Missing or malformed Authorization header")
+
+ jwt_secret = get_optional_env("JWT_SECRET_KEY")
+ if not jwt_secret:
+ log.error("JWT_SECRET_KEY environment variable is not set")
+ raise_internal_server_error("Server configuration error: JWT_SECRET_KEY not configured", error_type=ErrorType.SERVER_MISCONFIGURED)
+
+ token = credentials.credentials
+
+ try:
+ payload = jwt.decode( # type: ignore[reportUnknownMemberType]
+ token,
+ jwt_secret,
+ algorithms=[JWT_ALGORITHM],
+ )
+
+ # The caller identifier MUST be supplied as an explicit `user_id`
+ # claim. We deliberately do NOT fall back to the standard `sub`
+ # claim. The id is opaque (any scheme is fine — see `is_safe_user_id`);
+ # we only reject values that aren't a single path-safe segment, since
+ # the id becomes the owner segment of every storage key.
+ user_id = payload.get("user_id")
+ if not user_id:
+ log.warning("JWT missing user_id claim")
+ raise_unauthenticated("Invalid token: missing user_id claim", error_type=ErrorType.INVALID_TOKEN)
+ if not isinstance(user_id, str) or not is_safe_user_id(user_id):
+ log.warning(f"JWT user_id claim is not a path-safe segment: {user_id!r}")
+ raise_unauthenticated("Invalid token: user_id claim must be a single path-safe segment", error_type=ErrorType.INVALID_TOKEN)
+ if user_id == SINGLE_TENANT_USER_ID:
+ # Path-safe, but reserved for the no-user-model deployment. An
+ # authenticated token must not claim it, or that caller's runs would
+ # land in the single-tenant namespace of a server that DOES have
+ # users — beside whatever a no-auth deployment of the same image
+ # wrote there.
+ log.warning("JWT user_id claim is the reserved single-tenant id")
+ raise_unauthenticated(
+ f"Invalid token: user_id claim must not be the reserved {SINGLE_TENANT_USER_ID!r} value",
+ error_type=ErrorType.INVALID_TOKEN,
+ )
+ _set_request_user(request, user_id=user_id)
+
+ return payload
+
+ except jwt.ExpiredSignatureError:
+ log.warning("JWT token has expired")
+ raise_unauthenticated("Token expired", error_type=ErrorType.TOKEN_EXPIRED)
+ except jwt.InvalidTokenError as exc:
+ log.warning(f"JWT validation failed: {exc!s}")
+ raise_unauthenticated("Invalid token", error_type=ErrorType.INVALID_TOKEN)
+
+
+async def verify_api_key(credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)]) -> str:
+ """Validate static API key from Authorization header against API_KEY env var.
+
+ No user identity is available with static API keys — this is a shared developer key.
+ """
+ if credentials is None:
+ # Missing, empty, or non-Bearer `Authorization` header. See the
+ # matching branch in `verify_jwt` for why this lives here and not
+ # in `HTTPBearer`'s default `auto_error=True` behavior.
+ log.warning("API key auth requested without a Bearer token")
+ raise_unauthenticated("Missing or malformed Authorization header")
+
+ api_key = get_optional_env("API_KEY")
+
+ if not api_key:
+ log.error("API_KEY environment variable is not set")
+ raise_internal_server_error("Server configuration error: API_KEY not configured", error_type=ErrorType.SERVER_MISCONFIGURED)
+
+ if credentials.credentials != api_key:
+ log.warning("API key mismatch")
+ raise_unauthenticated("Invalid authentication token", error_type=ErrorType.INVALID_TOKEN)
+
+ return credentials.credentials
+
+
+async def no_auth(request: Request) -> None:
+ """No-op auth dependency for AUTH_MODE=none.
+
+ With no trusted proxy configured this binds no identity, and the deployment
+ is treated as single-tenant (see `SINGLE_TENANT_USER_ID`). If the API sits behind a trusted
+ reverse proxy / API gateway that authenticates callers and forwards the
+ caller identifier via the `X-User-Id` header, set
+ TRUST_FORWARDED_IDENTITY_HEADERS=true to read it. That single header is
+ the only thing the runner trusts from a forwarded request — any other
+ `X-User-*` headers a caller might attach are ignored.
+
+ The header is NOT trusted unless that env var is set, because any
+ external client could otherwise forge it when the API is reachable
+ directly. With the flag enabled, you are responsible for ensuring your
+ proxy strips `X-User-Id` from inbound requests before adding its own.
+ """
+ if get_optional_env("TRUST_FORWARDED_IDENTITY_HEADERS") != "true":
+ return
+
+ user_id = request.headers.get(ForwardedIdentityHeader.USER_ID)
+ if not user_id:
+ # **This used to stay anonymous, and that was the bug.** Turning this flag
+ # on is a deployment stating "a proxy in front of me authenticates every
+ # caller". A request arriving without the header therefore means the proxy
+ # is missing, misconfigured, or bypassed — and continuing under a shared
+ # owner is how a multi-tenant server silently becomes a single namespace
+ # where every tenant reads the others' outputs. It is now a hard failure.
+ log.warning("TRUST_FORWARDED_IDENTITY_HEADERS is on but no X-User-Id was forwarded")
+ raise_unauthenticated("Identity required: no X-User-Id was forwarded", error_type=ErrorType.INVALID_TOKEN)
+ if not is_safe_user_id(user_id):
+ # A non-empty but path-unsafe id: the proxy intended to authenticate
+ # someone and sent a malformed value. Fail closed.
+ log.warning(f"Forwarded X-User-Id is not a path-safe segment, rejecting: {user_id!r}")
+ raise_bad_request("Forwarded X-User-Id must be a single path-safe segment", error_type=ErrorType.BAD_REQUEST)
+
+ _set_request_user(request, user_id=user_id)
+
+
+async def get_request_user(request: Request) -> RequestUser | None:
+ """Dependency to retrieve the authenticated user identity.
+
+ Returns the RequestUser if identity was established during auth, or None
+ if no identity is available (e.g. static API key, or no auth).
+
+ Usage in route handlers:
+ async def my_endpoint(user: Annotated[RequestUser | None, Depends(get_request_user)]):
+ if user:
+ log.info(f"Request from {user.user_id}")
+ """
+ return getattr(request.state, "user", None)
+
+
+def get_auth_dependency() -> Any:
+ """Select authentication dependency based on AUTH_MODE env var.
+
+ - none: No authentication (self-hosted default, or behind API Gateway)
+ - jwt: Validate JWT tokens
+ - api_key: Validate static API key
+ """
+ auth_mode = get_auth_mode()
+ match auth_mode:
+ case AuthMode.NONE:
+ return no_auth
+ case AuthMode.JWT:
+ return verify_jwt
+ case AuthMode.API_KEY:
+ return verify_api_key
diff --git a/api/postman/sample-bundles/README.md b/api/postman/sample-bundles/README.md
new file mode 100644
index 000000000..87bc374f4
--- /dev/null
+++ b/api/postman/sample-bundles/README.md
@@ -0,0 +1,30 @@
+# Postman sample bundles
+
+The `.mthds` bodies behind the test requests in the **Pipelex FastAPI** Postman collection (the `Validate` and `Pipeline` folders). Keeping them here as files — rather than only embedded in Postman — makes them reviewable, diffable, and editable. The collection requests carry a copy of each body inline; if you edit a file here, re-push it with the `postman-bundle` skill (or by hand) to keep the request in sync.
+
+Each verdict below was confirmed against a live `POST /v1/validate`.
+
+## Valid
+
+| File | `/validate` verdict | Notes |
+|---|---|---|
+| `hello_greeting.mthds` | valid · **runnable** | Trivial one-pipe `PipeLLM` (text → text). Cheap to actually run. |
+| `cv_job_match.mthds` | valid · **runnable** | The workhorse used across the `Pipeline` examples (structured `MatchAnalysis` output). |
+| `fashion_moodboard.mthds` | valid · **runnable** | Real demo bundle (search → LLM → image gen). Validates free; executing it is expensive. |
+| `batch_candidate_screening.mthds` | valid · **runnable** | Real demo bundle (inline structures; PDF `Document` inputs needed to actually run). |
+| `draft_with_signature.mthds` | valid · **NOT runnable** | One step is a forward-declared `PipeSignature` → `is_runnable:false`, `pending_signatures` lists it. Running it raises `PipeSignatureNotExecutableError`. |
+| `invalid/missing_main_pipe.mthds` | valid (no `main_pipe`) | Kept here for reference: a bundle with **no `main_pipe` still validates** (`graph_spec:null`). It is *not* an invalid case. |
+
+## Invalid — one distinct error type each
+
+| File | `validation_errors[].error_type` / category | What it shows |
+|---|---|---|
+| `invalid/syntax_error.mthds` | TOML parse error | Malformed bundle text — fails before blueprint validation. |
+| `invalid/missing_pipe_ref.mthds` | dependency pipe not found | A `PipeSequence` step references a pipe that is never defined. |
+| `invalid/unknown_concept.mthds` | concept reference unresolved | A pipe `output` names a concept that is never declared and is not native. |
+| `invalid/prompt_input_mismatch.mthds` | `missing_input_variable` (blueprint_validation) | The prompt uses `$city`, which is not a declared input. |
+| `invalid/bad_pipe_type.mthds` | `union_tag_invalid` | `type = "PipeWizardry"` — not a real pipe type. |
+
+## Inputs
+
+`*.inputs.json` files hold the run inputs for the runnable bundles (`hello_greeting`, `cv_job_match`, `draft_with_signature`). `/validate` ignores inputs; they are used by the `Pipeline` (execute/start) requests.
diff --git a/api/postman/sample-bundles/batch_candidate_screening.mthds b/api/postman/sample-bundles/batch_candidate_screening.mthds
new file mode 100644
index 000000000..afe1a0157
--- /dev/null
+++ b/api/postman/sample-bundles/batch_candidate_screening.mthds
@@ -0,0 +1,146 @@
+domain = "batch_candidate_screening"
+description = "Analyzing Candidate Profiles and job offer compatibility and generating interview questions"
+system_prompt = "None"
+main_pipe = "batch_analyze_cvs_for_job_offer"
+
+[concept.CandidateProfile]
+description = "A structured summary of a job candidate's professional background extracted from their CV."
+
+[concept.CandidateProfile.structure]
+skills = { type = "text", description = "Technical and soft skills possessed by the candidate", required = true }
+experience = { type = "text", description = "Work history and professional experience", required = true }
+education = { type = "text", description = "Educational background and qualifications", required = true }
+achievements = { type = "text", description = "Notable accomplishments and certifications" }
+
+[concept.JobRequirements]
+description = "A structured summary of what a job position requires from candidates."
+
+[concept.JobRequirements.structure]
+required_skills = { type = "text", description = "Skills that are mandatory for the position", required = true }
+responsibilities = { type = "text", description = "Main duties and tasks of the role", required = true }
+qualifications = { type = "text", description = "Required education, certifications, or experience levels", required = true }
+nice_to_haves = { type = "text", description = "Preferred but not mandatory qualifications" }
+
+[concept.CandidateMatch]
+description = "An evaluation of how well a candidate fits a job position."
+
+[concept.CandidateMatch.structure]
+match_score = { type = "number", description = "Numerical score representing overall fit percentage between 0 and 100", required = true }
+strengths = { type = "text", description = "Areas where the candidate meets or exceeds requirements", required = true }
+gaps = { type = "text", description = "Areas where the candidate falls short of requirements", required = true }
+overall_assessment = { type = "text", description = "Summary evaluation of the candidate's suitability", required = true }
+
+[pipe.batch_analyze_cvs_for_job_offer]
+type = "PipeSequence"
+description = """
+Main orchestrator pipe that takes a bunch of CVs and a job offer in PDF format, and analyzes how they match.
+"""
+inputs = { cvs = "Document[]", job_offer_pdf = "Document" }
+output = "CandidateMatch[]"
+steps = [
+ { pipe = "prepare_job_offer", result = "job_requirements" },
+ { pipe = "process_cv", batch_over = "cvs", batch_as = "cv_pdf", result = "match_analyses" },
+]
+
+[pipe.prepare_job_offer]
+type = "PipeSequence"
+description = """
+Extracts the job offer PDF and analyzes it into structured job requirements.
+"""
+inputs = { job_offer_pdf = "Document" }
+output = "JobRequirements"
+steps = [
+ { pipe = "extract_one_job_offer", result = "job_offer_pages" },
+ { pipe = "analyze_job_requirements", result = "job_requirements" },
+]
+
+[pipe.extract_one_job_offer]
+type = "PipeExtract"
+description = "Extracts text content from the job offer PDF document"
+inputs = { job_offer_pdf = "Document" }
+output = "Page[]"
+model = "@default-extract-document"
+
+[pipe.analyze_job_requirements]
+type = "PipeLLM"
+description = """
+Parses and summarizes the job requirements from the extracted job offer content, identifying required skills, responsibilities, qualifications, and nice-to-haves
+"""
+inputs = { job_offer_pages = "Page" }
+output = "JobRequirements"
+model = "$writing-factual"
+system_prompt = """
+You are an expert HR analyst specializing in parsing job descriptions. Your task is to extract and summarize job requirements into a structured format.
+"""
+prompt = """
+Analyze the following job offer content and extract the key requirements for the position.
+
+@job_offer_pages
+"""
+
+[pipe.process_cv]
+type = "PipeSequence"
+description = "Processes one application"
+inputs = { cv_pdf = "Document", job_requirements = "JobRequirements" }
+output = "CandidateMatch"
+steps = [
+ { pipe = "extract_one_cv", result = "cv_pages" },
+ { pipe = "analyze_one_cv", result = "candidate_profile" },
+ { pipe = "search_candidate_online", result = "online_info" },
+ { pipe = "analyze_match", result = "match_analysis" },
+]
+
+[pipe.extract_one_cv]
+type = "PipeExtract"
+description = "Extracts text content from the CV PDF document"
+inputs = { cv_pdf = "Document" }
+output = "Page[]"
+model = "@default-extract-document"
+
+[pipe.analyze_one_cv]
+type = "PipeLLM"
+description = """
+Parses and summarizes the candidate's professional profile from the extracted CV content, identifying skills, experience, education, and achievements
+"""
+inputs = { cv_pages = "Page" }
+output = "CandidateProfile"
+model = "$writing-factual"
+system_prompt = """
+You are an expert HR analyst specializing in parsing and summarizing candidate CVs. Your task is to extract and structure the candidate's professional profile into a structured format.
+"""
+prompt = """
+Analyze the following CV content and extract the candidate's professional profile.
+
+@cv_pages
+"""
+
+[pipe.search_candidate_online]
+type = "PipeSearch"
+description = "Searches the web for relevant professional information about the candidate based on their profile"
+inputs = { candidate_profile = "CandidateProfile" }
+output = "SearchResult"
+model = "$standard"
+prompt = "Professional background and online presence of $candidate_profile.skills $candidate_profile.experience"
+
+[pipe.analyze_match]
+type = "PipeLLM"
+description = """
+Evaluates how well the candidate matches the job requirements, calculating a match score and identifying strengths and gaps
+"""
+inputs = { candidate_profile = "CandidateProfile", job_requirements = "JobRequirements", online_info = "SearchResult" }
+output = "CandidateMatch"
+model = "$writing-factual"
+system_prompt = """
+You are an expert HR analyst specializing in candidate-job fit evaluation. Your task is to produce a structured match analysis comparing a candidate's profile against job requirements, enriched with information found online about the candidate.
+"""
+prompt = """
+Analyze how well the candidate matches the job requirements. Evaluate their fit by comparing their skills, experience, and qualifications against what the position demands. Also consider the following online research about the candidate:
+
+@online_info
+
+@candidate_profile
+
+@job_requirements
+
+Provide a comprehensive match analysis including a numerical score, identified strengths, gaps, and an overall assessment.
+"""
diff --git a/api/postman/sample-bundles/cv_job_match.inputs.json b/api/postman/sample-bundles/cv_job_match.inputs.json
new file mode 100644
index 000000000..9bb64b5ba
--- /dev/null
+++ b/api/postman/sample-bundles/cv_job_match.inputs.json
@@ -0,0 +1,4 @@
+{
+ "cv_text": "Jane Doe — Senior Software Engineer\n5 years of experience in Python, FastAPI, and cloud infrastructure (AWS).\nLed a team of 4 engineers to build a real-time data pipeline processing 10M events/day.\nSkills: Python, TypeScript, PostgreSQL, Docker, Kubernetes, CI/CD, Terraform.\nEducation: M.Sc. Computer Science, MIT (2019).\nCertifications: AWS Solutions Architect Associate.",
+ "job_offer_text": "Senior Backend Engineer — Acme Corp\nWe are looking for a Senior Backend Engineer to design and scale our API platform.\nRequirements: 4+ years Python, experience with FastAPI or Django, strong SQL skills, cloud infrastructure (AWS or GCP), familiarity with containerization (Docker/K8s).\nNice to have: Terraform, CI/CD pipelines, real-time data processing.\nStack: Python, FastAPI, PostgreSQL, AWS, Docker, Kubernetes."
+}
diff --git a/api/postman/sample-bundles/cv_job_match.mthds b/api/postman/sample-bundles/cv_job_match.mthds
new file mode 100644
index 000000000..77b06f68e
--- /dev/null
+++ b/api/postman/sample-bundles/cv_job_match.mthds
@@ -0,0 +1,32 @@
+domain = "cv_job_match"
+description = "Analyze the match between a candidate CV and a job offer."
+main_pipe = "analyze_cv_job_match"
+
+[concept.MatchAnalysis]
+description = "Structured assessment of how well a candidate CV matches a job offer."
+
+[concept.MatchAnalysis.structure]
+is_match = { type = "boolean", description = "Whether the candidate is a good match for the job", required = true }
+match_score = { type = "integer", description = "Score from 0 to 100 indicating how well the CV matches the job offer", required = true }
+key_strengths = { type = "text", description = "Candidate strengths relevant to the job requirements", required = true }
+gaps = { type = "text", description = "Notable gaps or missing qualifications", required = true }
+recommendation = { type = "text", description = "Final recommendation: proceed to interview, reject, or further review", required = true }
+
+[pipe.analyze_cv_job_match]
+type = "PipeLLM"
+description = "Analyze a CV against a job offer and produce a structured match assessment."
+inputs = { cv_text = "Text", job_offer_text = "Text" }
+output = "MatchAnalysis"
+model = "$writing-factual"
+system_prompt = """
+You are a senior HR expert with 20+ years of recruitment experience. Your task is to objectively assess how well a candidate's CV matches a given job offer. Be thorough, fair, and data-driven. A candidate with a score >= 60 who meets the core requirements should be considered a match.
+"""
+prompt = """
+Analyze the following CV against the job offer and produce a structured match analysis.
+
+## Candidate CV
+@cv_text
+
+## Job Offer
+@job_offer_text
+"""
diff --git a/api/postman/sample-bundles/draft_with_signature.inputs.json b/api/postman/sample-bundles/draft_with_signature.inputs.json
new file mode 100644
index 000000000..77ef3c97f
--- /dev/null
+++ b/api/postman/sample-bundles/draft_with_signature.inputs.json
@@ -0,0 +1,3 @@
+{
+ "document": "Pipelex is a runtime that executes MTHDS methods. MTHDS is an open standard for declaring AI pipelines as data."
+}
diff --git a/api/postman/sample-bundles/draft_with_signature.mthds b/api/postman/sample-bundles/draft_with_signature.mthds
new file mode 100644
index 000000000..81eeff18a
--- /dev/null
+++ b/api/postman/sample-bundles/draft_with_signature.mthds
@@ -0,0 +1,30 @@
+domain = "draft_with_signature"
+description = "In-progress method — one step is still a forward-declared PipeSignature, so it is valid but not runnable"
+main_pipe = "summarize_then_translate"
+
+[concept.Summary]
+description = "A short summary of a document"
+refines = "Text"
+
+[pipe.summarize_then_translate]
+type = "PipeSequence"
+description = "Summarize a document, then translate the summary to French"
+inputs = { document = "Text" }
+output = "Summary"
+steps = [
+ { pipe = "summarize_document", result = "summary" },
+ { pipe = "translate_summary", result = "translated" },
+]
+
+[pipe.summarize_document]
+type = "PipeLLM"
+description = "Summarize the document in two sentences"
+inputs = { document = "Text" }
+output = "Summary"
+prompt = "Summarize the following document in two sentences:\n\n@document"
+
+[pipe.translate_summary]
+description = "Translate the summary to French (contract only — not yet implemented)"
+inputs = { summary = "Summary" }
+output = "Summary"
+signature_for = "PipeLLM"
diff --git a/api/postman/sample-bundles/fashion_moodboard.mthds b/api/postman/sample-bundles/fashion_moodboard.mthds
new file mode 100644
index 000000000..0d064a1cd
--- /dev/null
+++ b/api/postman/sample-bundles/fashion_moodboard.mthds
@@ -0,0 +1,134 @@
+domain = "fashion_moodboard"
+description = "From a fashion market and season, generate 5 inspiration-driven composite moodboard images"
+main_pipe = "create_collection_moodboards"
+
+[concept.MoodboardPrompt]
+description = "A single image generation prompt for one moodboard panel"
+refines = "Text"
+
+[concept.FashionInspiration]
+description = "A single fashion aesthetic direction or inspiration brief"
+refines = "Text"
+
+[concept.FashionTarget]
+description = "A fashion market and season target, e.g. Women Spring/Summer 2027 or Men FW27"
+refines = "Text"
+
+[pipe.create_collection_moodboards]
+type = "PipeSequence"
+description = "From a fashion target, research trends then generate distinct inspiration-driven moodboards"
+inputs = { fashion_target = "FashionTarget" }
+output = "Image[]"
+steps = [
+ { pipe = "search_trends", result = "trends" },
+ { pipe = "generate_inspirations", result = "inspirations" },
+ { pipe = "create_moodboards", result = "moodboards" },
+]
+
+[pipe.search_trends]
+type = "PipeSearch"
+description = "Search the web for current and upcoming fashion trends matching the target"
+inputs = { fashion_target = "FashionTarget" }
+output = "SearchResult"
+prompt = "current and upcoming fashion trends, runway reports, and editorial coverage for $fashion_target"
+from_date = "2026-01-01"
+
+[pipe.generate_inspirations]
+type = "PipeLLM"
+description = "Generate distinct fashion inspiration directions grounded in researched trends"
+inputs = { fashion_target = "FashionTarget", trends = "SearchResult" }
+output = "FashionInspiration[5]"
+prompt = """
+You are a fashion trend forecaster. Your target is:
+$fashion_target
+
+Interpret shorthand like SS/FW and gender codes (e.g. "Men FW27" = Men Fall/Winter 2027).
+
+Researched trend signals:
+@trends
+
+Grounded in these signals, propose exactly 5 distinct, compelling fashion aesthetic directions that could each anchor a separate moodboard.
+Each inspiration should be a short paragraph (3-5 sentences) capturing a unique mood, silhouette direction, color story, and cultural reference. Make the directions feel meaningfully different — different moods, palettes, and references.
+"""
+
+[pipe.create_moodboards]
+type = "PipeBatch"
+description = "Create one moodboard image per inspiration"
+inputs = { inspirations = "FashionInspiration[]", fashion_target = "FashionTarget" }
+output = "Image[]"
+branch_pipe_code = "create_moodboard"
+input_list_name = "inspirations"
+input_item_name = "inspiration"
+
+[pipe.create_moodboard]
+type = "PipeSequence"
+description = "Create a fashion moodboard from inspiration"
+inputs = { inspiration = "FashionInspiration", fashion_target = "FashionTarget" }
+output = "Image"
+steps = [
+ { pipe = "craft_prompts", result = "prompts" },
+ { pipe = "craft_moodboard_prompt", result = "moodboard_prompt" },
+ { pipe = "generate_moodboard", result = "moodboard_image" },
+]
+
+[pipe.craft_prompts]
+type = "PipeLLM"
+description = "Generate diverse moodboard image prompts from fashion inspiration"
+inputs = { inspiration = "FashionInspiration", fashion_target = "FashionTarget" }
+output = "MoodboardPrompt[]"
+model = "@default-small-creative"
+prompt = """
+You are a fashion art director creating a moodboard for the following target:
+$fashion_target
+
+Given the fashion inspiration below, generate exactly 5 distinct image generation prompts. Each prompt should capture a different visual facet of the aesthetic.
+
+The 5 facets:
+1. A hero outfit or look
+2. A texture or fabric close-up
+3. A color palette scene
+4. A setting or environment that evokes the mood
+5. An accessory or detail shot
+
+Fashion inspiration:
+@inspiration
+
+For each prompt, write a vivid, detailed image generation prompt that would produce a beautiful moodboard panel. Focus on colors, textures, lighting, and composition.
+"""
+
+[pipe.craft_moodboard_prompt]
+type = "PipeLLM"
+description = "Synthesize element descriptions into a single moodboard image prompt"
+inputs = { prompts = "MoodboardPrompt[]", fashion_target = "FashionTarget" }
+output = "Text"
+model = "@default-small-creative"
+prompt = """
+You are a fashion art director composing a single moodboard image for the following target:
+$fashion_target.
+
+You previously identified these visual elements:
+@prompts
+
+Now write ONE image generation prompt that combines all these elements into a single cohesive moodboard composition in 16:9 landscape format. Preserve any market/season references already present in the elements above — do not strip them out. The image should be a collage-style moodboard that includes:
+- The key outfit/look
+- Texture and fabric details
+- The color palette
+- The mood/setting atmosphere
+- Accessory details
+
+Also overlay 1 or 2 short words or expressions (like a fashion editorial tagline) that capture the feeling of this aesthetic. These words should feel handwritten or editorial.
+
+Write only the image generation prompt, nothing else.
+"""
+
+[pipe.generate_moodboard]
+type = "PipeImgGen"
+description = "Generate the final composite moodboard image in 16:9"
+inputs = { moodboard_prompt = "Text", fashion_target = "FashionTarget" }
+output = "Image"
+model = "nano-banana-2"
+prompt = """
+Target: $fashion_target.
+$moodboard_prompt
+"""
+aspect_ratio = "landscape_16_9"
diff --git a/api/postman/sample-bundles/hello_greeting.inputs.json b/api/postman/sample-bundles/hello_greeting.inputs.json
new file mode 100644
index 000000000..52f22bf9c
--- /dev/null
+++ b/api/postman/sample-bundles/hello_greeting.inputs.json
@@ -0,0 +1,3 @@
+{
+ "name": "Ada Lovelace"
+}
diff --git a/api/postman/sample-bundles/hello_greeting.mthds b/api/postman/sample-bundles/hello_greeting.mthds
new file mode 100644
index 000000000..eca015614
--- /dev/null
+++ b/api/postman/sample-bundles/hello_greeting.mthds
@@ -0,0 +1,10 @@
+domain = "hello_greeting"
+description = "Minimal runnable method — turn a name into a short greeting"
+main_pipe = "write_greeting"
+
+[pipe.write_greeting]
+type = "PipeLLM"
+description = "Write a short, friendly greeting for the given name"
+inputs = { name = "Text" }
+output = "Text"
+prompt = "Write a short, friendly one-sentence greeting for $name."
diff --git a/api/postman/sample-bundles/invalid/bad_pipe_type.mthds b/api/postman/sample-bundles/invalid/bad_pipe_type.mthds
new file mode 100644
index 000000000..335b2cdc8
--- /dev/null
+++ b/api/postman/sample-bundles/invalid/bad_pipe_type.mthds
@@ -0,0 +1,10 @@
+domain = "bad_pipe_type"
+description = "Uses a pipe type that does not exist"
+main_pipe = "mystery"
+
+[pipe.mystery]
+type = "PipeWizardry"
+description = "Not a real pipe type"
+inputs = { text = "Text" }
+output = "Text"
+prompt = "Do something magical with $text"
diff --git a/api/postman/sample-bundles/invalid/missing_main_pipe.mthds b/api/postman/sample-bundles/invalid/missing_main_pipe.mthds
new file mode 100644
index 000000000..f36ae42ba
--- /dev/null
+++ b/api/postman/sample-bundles/invalid/missing_main_pipe.mthds
@@ -0,0 +1,13 @@
+domain = "missing_main_pipe"
+description = "Declares a pipe but no main_pipe"
+
+[concept.Greeting]
+description = "A greeting"
+refines = "Text"
+
+[pipe.greet]
+type = "PipeLLM"
+description = "Say hello to the given name"
+inputs = { name = "Text" }
+output = "Greeting"
+prompt = "Say hello to $name"
diff --git a/api/postman/sample-bundles/invalid/missing_pipe_ref.mthds b/api/postman/sample-bundles/invalid/missing_pipe_ref.mthds
new file mode 100644
index 000000000..27af69aa3
--- /dev/null
+++ b/api/postman/sample-bundles/invalid/missing_pipe_ref.mthds
@@ -0,0 +1,20 @@
+domain = "missing_pipe_ref"
+description = "A sequence step references a pipe that is never defined"
+main_pipe = "do_two_steps"
+
+[pipe.do_two_steps]
+type = "PipeSequence"
+description = "Two-step sequence whose second step does not exist"
+inputs = { text = "Text" }
+output = "Text"
+steps = [
+ { pipe = "first_step", result = "interim" },
+ { pipe = "second_step_missing", result = "final" },
+]
+
+[pipe.first_step]
+type = "PipeLLM"
+description = "Echo the text"
+inputs = { text = "Text" }
+output = "Text"
+prompt = "Repeat verbatim: $text"
diff --git a/api/postman/sample-bundles/invalid/prompt_input_mismatch.mthds b/api/postman/sample-bundles/invalid/prompt_input_mismatch.mthds
new file mode 100644
index 000000000..9d803ac7b
--- /dev/null
+++ b/api/postman/sample-bundles/invalid/prompt_input_mismatch.mthds
@@ -0,0 +1,10 @@
+domain = "prompt_input_mismatch"
+description = "The prompt references a variable that is not a declared input"
+main_pipe = "greet_person"
+
+[pipe.greet_person]
+type = "PipeLLM"
+description = "Greeting whose prompt uses an undeclared variable ($city)"
+inputs = { name = "Text" }
+output = "Text"
+prompt = "Write a greeting for $name who lives in $city."
diff --git a/api/postman/sample-bundles/invalid/syntax_error.mthds b/api/postman/sample-bundles/invalid/syntax_error.mthds
new file mode 100644
index 000000000..787326f64
--- /dev/null
+++ b/api/postman/sample-bundles/invalid/syntax_error.mthds
@@ -0,0 +1,2 @@
+this is not valid TOML content at all {{{{
+domain =
diff --git a/api/postman/sample-bundles/invalid/unknown_concept.mthds b/api/postman/sample-bundles/invalid/unknown_concept.mthds
new file mode 100644
index 000000000..cea8ad575
--- /dev/null
+++ b/api/postman/sample-bundles/invalid/unknown_concept.mthds
@@ -0,0 +1,10 @@
+domain = "unknown_concept"
+description = "A pipe outputs a concept that is never declared"
+main_pipe = "make_thing"
+
+[pipe.make_thing]
+type = "PipeLLM"
+description = "Produce an undeclared concept"
+inputs = { topic = "Text" }
+output = "NonExistentConcept"
+prompt = "Write a paragraph about $topic"
diff --git a/api/pyproject.toml b/api/pyproject.toml
new file mode 100644
index 000000000..b3c49af64
--- /dev/null
+++ b/api/pyproject.toml
@@ -0,0 +1,393 @@
+[project]
+name = "pipelex-api"
+# The server is released with the library under one version number, read from the root `pyproject.toml`
+# (`[tool.hatch.version]` below), so a release bumps one file.
+dynamic = ["version"]
+description = "Pipelex API"
+authors = [{ name = "Evotis S.A.S.", email = "[email protected]" }]
+maintainers = [{ name = "Pipelex staff", email = "[email protected]" }]
+license = "Elastic-2.0"
+# A copy of the repository's `LICENSE`: a distribution can only carry license files from inside its own
+# directory, and a symlink would dangle in the sdist. `tests/unit/test_license_copy.py` keeps the two equal.
+license-files = ["LICENSE"]
+readme = "README.md"
+requires-python = ">=3.11,<3.15"
+classifiers = [
+ "Programming Language :: Python :: 3.11",
+ "Programming Language :: Python :: 3.12",
+ "Programming Language :: Python :: 3.13",
+ "Programming Language :: Python :: 3.14",
+]
+
+dependencies = [
+ # The extras deliberately leave out `cli`: the runner selects the `json` log sink and a Rich-free
+ # pretty-print mode, so nothing it does on a request renders a terminal.
+ #
+ # pipelex resolves from this repository's workspace (`[tool.uv.sources]` below), so the server always
+ # runs the library of the same commit, and no version is written here: uv ignores a version specifier
+ # on a workspace source, so a pin would only go stale.
+ "pipelex[mistralai,anthropic,google,google-genai,bedrock,fal]",
+ "fastapi>=0.118.0",
+ "pyjwt>=2.10.1",
+ "uvicorn>=0.37.0",
+]
+
+[build-system]
+requires = ["hatchling>=1.27"]
+build-backend = "hatchling.build"
+
+[project.urls]
+Homepage = "https://pipelex.com"
+Repository = "https://github.com/Pipelex/pipelex"
+Documentation = "https://docs.pipelex.com/pages/api/"
+Changelog = "https://docs.pipelex.com/changelog/"
+
+[project.optional-dependencies]
+dev = [
+ "boto3-stubs>=1.35.24",
+ # starlette>=1.3 's TestClient imports `httpx2 as httpx` under TYPE_CHECKING and at
+ # runtime, falling back to httpx only with a deprecation warning. Installing httpx2
+ # lets pyright resolve the TestClient signatures (otherwise every `client.post(...)`
+ # is Unknown) and silences the runtime warning.
+ "httpx2>=2.4.0",
+ "mypy>=1.11.2",
+ "pyright>=1.1.405",
+ "pandas-stubs>=2.2.3.241126",
+ "pylint>=3.3.8",
+ "pytest>=8.3.3",
+ "pytest-asyncio>=0.24.0",
+ "pytest-cov>=6.1.1",
+ "pytest-mock>=3.14.0",
+ "pytest-sugar>=1.0.0",
+ "pytest-xdist>= 3.6.1",
+ "ruff>=0.6.8",
+ "types-aiobotocore[bedrock,bedrock-runtime]>=3.0.0",
+ "types-aiofiles>=24.1.0.20240626",
+ "types-beautifulsoup4>=4.12.0.20240907",
+ "types-markdown>=3.6.0.20240316",
+ "types-networkx>=3.3.0.20241020",
+ "types-openpyxl>=3.1.5.20250306",
+ "types-requests>=2.32.0.2024091",
+ "types-PyYAML>=6.0.12.20250326",
+ "types-toml>=0.10.8.20240310",
+]
+# One lock resolves every workspace member's extras together, so these floors follow pipelex's own `docs`
+# extra rather than pinning versions of their own.
+docs = [
+ "mkdocs>=1.6.1",
+ "mkdocs-glightbox>=0.4.0",
+ "mkdocs-material>=9.7.7",
+ "mkdocs-meta-manager>=1.1.0",
+]
+
+[tool.hatch.metadata]
+allow-direct-references = true
+
+[tool.hatch.build.targets.wheel]
+packages = ["pipelex_api"]
+
+[tool.hatch.build.targets.sdist]
+packages = ["pipelex_api"]
+
+[tool.hatch.version]
+path = "../pyproject.toml"
+pattern = '(?m)^version = "(?P<version>[^"]+)"'
+
+[tool.uv]
+# The version comes from the root `pyproject.toml`, so uv has to rebuild this member's metadata when that
+# file changes, not only when this one does.
+cache-keys = [{ file = "pyproject.toml" }, { file = "../pyproject.toml" }]
+
+[tool.uv.sources]
+pipelex = { workspace = true }
+
+[tool.mypy]
+check_untyped_defs = true
+exclude = "^.*\\.venv/.*$"
+mypy_path = "."
+packages = ["pipelex_api", "tests"]
+plugins = ["pydantic.mypy"]
+python_version = "3.11"
+warn_return_any = true
+warn_unused_configs = true
+
+[[tool.mypy.overrides]]
+ignore_missing_imports = true
+module = ["pipelex_api", "tests"]
+
+[tool.pyright]
+venvPath = "."
+venv = ".venv"
+pythonVersion = "3.11"
+include = ["pipelex_api", "tests"]
+exclude = [
+ "**/__pycache__",
+ ".venv",
+ ".git",
+ "build",
+ "dist",
+ "**/node_modules",
+ "**/.*",
+]
+analyzeUnannotatedFunctions = true
+deprecateTypingAliases = false
+disableBytesTypePromotions = true
+enableExperimentalFeatures = false
+enableTypeIgnoreComments = true
+extraPaths = ["./tests"]
+reportAbstractUsage = "error"
+reportArgumentType = "error"
+reportAssertAlwaysTrue = "error"
+reportAssertTypeFailure = "error"
+reportAssignmentType = "error"
+reportAttributeAccessIssue = "error"
+reportCallInDefaultInitializer = true
+reportCallIssue = "error"
+reportConstantRedefinition = "error"
+reportDeprecated = "error"
+reportDuplicateImport = "error"
+reportFunctionMemberAccess = "error"
+reportGeneralTypeIssues = "error"
+reportImplicitOverride = true
+reportImplicitStringConcatenation = false
+reportImportCycles = true
+reportIncompatibleMethodOverride = "error"
+reportIncompatibleVariableOverride = "error"
+reportIncompleteStub = "error"
+reportInconsistentConstructor = "error"
+reportInconsistentOverload = "error"
+reportIndexIssue = "error"
+reportInvalidStringEscapeSequence = "error"
+reportInvalidStubStatement = "error"
+reportInvalidTypeArguments = "error"
+reportInvalidTypeForm = "error"
+reportInvalidTypeVarUse = "error"
+reportMatchNotExhaustive = "error"
+reportMissingImports = "error"
+reportMissingModuleSource = "warning"
+reportMissingParameterType = "error"
+reportMissingSuperCall = "none"
+reportMissingTypeArgument = "error"
+reportMissingTypeStubs = false
+reportNoOverloadImplementation = "error"
+reportOperatorIssue = "error"
+reportOptionalCall = "error"
+reportOptionalContextManager = "error"
+reportOptionalIterable = "error"
+reportOptionalMemberAccess = "error"
+reportOptionalOperand = "error"
+reportOptionalSubscript = "error"
+reportOverlappingOverload = "error"
+reportPossiblyUnboundVariable = "error"
+reportPrivateImportUsage = "error"
+reportPrivateUsage = "error"
+reportPropertyTypeMismatch = true
+reportRedeclaration = "error"
+reportReturnType = "error"
+reportSelfClsParameterName = "error"
+reportTypeCommentUsage = "error"
+reportTypedDictNotRequiredAccess = "error"
+reportUnboundVariable = "error"
+reportUndefinedVariable = "error"
+reportUninitializedInstanceVariable = "none"
+reportUnknownArgumentType = "error"
+reportUnknownLambdaType = "error"
+reportUnknownMemberType = "error"
+reportUnknownParameterType = "error"
+reportUnknownVariableType = "error"
+reportUnnecessaryCast = "error"
+reportUnnecessaryComparison = "error"
+reportUnnecessaryContains = "error"
+reportUnnecessaryIsInstance = "error"
+reportUnnecessaryTypeIgnoreComment = "none"
+reportUnsupportedDunderAll = "error"
+reportUntypedBaseClass = "error"
+reportUntypedClassDecorator = "error"
+reportUntypedFunctionDecorator = "error"
+reportUntypedNamedTuple = "error"
+reportUnusedCallResult = "none"
+reportUnusedClass = "error"
+reportUnusedCoroutine = "error"
+reportUnusedExcept = "error"
+reportUnusedExpression = "error"
+reportUnusedFunction = "error"
+reportUnusedImport = "none"
+reportUnusedVariable = "error"
+reportWildcardImportFromLibrary = "error"
+strictDictionaryInference = true
+strictListInference = true
+strictParameterNoneValue = true
+strictSetInference = true
+typeCheckingMode = "strict"
+
+[tool.pytest.ini_options]
+addopts = "--import-mode=importlib -ra -m 'not gha_disabled'"
+asyncio_default_fixture_loop_scope = "session"
+markers = ["gha_disabled: tests that should not run in GitHub Actions"]
+minversion = "8.0"
+xfail_strict = true
+
+[tool.coverage.run]
+source = ["pipelex_api"]
+omit = ["tests/*", "**/__init__.py"]
+
+[tool.coverage.report]
+exclude_lines = [
+ "pragma: no cover",
+ "def __repr__",
+ "raise NotImplementedError",
+ "if __name__ == .__main__.:",
+ "pass",
+ "raise ImportError",
+]
+
+[tool.ruff]
+exclude = [
+ ".claude",
+ ".cursor",
+ ".git",
+ ".github",
+ ".mypy_cache",
+ ".ruff_cache",
+ ".venv",
+ ".vscode",
+ "trigger_pipeline",
+]
+line-length = 150
+target-version = "py311"
+
+[tool.ruff.format]
+
+[tool.ruff.lint]
+select = ["ALL"]
+ignore = [
+ "ANN201", # Missing return type annotation for public function `my_func`
+ "ANN202", # Missing return type annotation for private function `my_func`
+ "ANN204", # Missing return type annotation for special method `my_func`
+ "ANN206", # Missing return type annotation for classmethod `my_func`
+ "ANN401", # Dynamically typed expressions (typing.Any) are disallowed in `...`
+ "ASYNC230", # Async functions should not open files with blocking methods like `open`
+
+ "C901", # Is to complex
+
+ "CPY001", # Missing copyright notice at top of file: the repository's LICENSE covers every file, as in pipelex
+ "COM812", # Checks for the absence of trailing commas.
+
+ "D100", # Missing docstring in public module
+ "D101", # Missing docstring in public class
+ "D102", # Missing docstring in public method
+ "D103", # Missing docstring in public function
+ "D104", # Missing docstring in public package
+ "D105", # Missing docstring in magic method
+ "D107", # Missing docstring in __init__
+ "D205", # 1 blank line required between summary line and description
+ "D400", # First line should end with a period
+ "D401", # First line of docstring should be in imperative mood: "My docstring...."
+ "D404", # First word of the docstring should not be "This"
+ "D415", # First line should end with a period, question mark, or exclamation point
+
+ "DTZ001", # `datetime.datetime()` called without a `tzinfo` argument
+ "DTZ005", # `datetime.datetime.now()` called without a `tz` argument
+
+ "ERA001", # Found commented-out code
+
+ "FBT001", # Boolean-typed positional argument in function definition
+ "FBT002", # Boolean default positional argument in function definition
+ "FBT003", #Boolean positional value in function call
+
+ "FIX002", # Line contains TODO, consider resolving the issue
+
+ "PLC0105", # `TypeVar` name "SomethingType" does not reflect its covariance; consider renaming it to "SomethingType_co"
+
+ "PLR0911", # Too many return statements (/6)
+ "PLR0912", # Too many branches (/12)
+ "PLR0913", # Too many arguments in function definition (/5)
+ "PLR0915", # Too many statements (/50)
+ "PLR2004", # Magic value used in comparison, consider replacing `2` with a constant variable
+
+ "PT013", # Incorrect import of `pytest`; use `import pytest` instead
+
+ "PTH100", # `os.path.abspath()` should be replaced by `Path.resolve()`
+ "PTH103", # `os.makedirs()` should be replaced by `Path.mkdir(parents=True)`
+ "PTH107", # `os.remove()` should be replaced by `Path.unlink()`
+ "PTH109", # `os.getcwd()` should be replaced by `Path.cwd()`
+ "PTH118", # `os.path.join()` should be replaced by `Path` with `/` operator
+ "PTH120", # `os.path.dirname()` should be replaced by `Path.parent`
+ "PTH110", # `os.path.exists()` should be replaced by `Path.exists()`
+ "PTH112", # `os.path.isdir()` should be replaced by `Path.is_dir()`
+ "PTH119", # `os.path.basename()` should be replaced by `Path.name`
+ "PTH123", # `open()` should be replaced by `Path.open()`
+ "PTH208", # Use `pathlib.Path.iterdir()` instead.
+
+ "PYI051", # `Literal["auto"]` is redundant in a union with `str`
+
+ "RET505", # superfluous-else-return
+
+ "RUF001", # String contains ambiguous `′` (PRIME). Did you mean ``` (GRAVE ACCENT)?
+ "RUF003", # Comment contains ambiguous `’` (RIGHT SINGLE QUOTATION MARK). Did you mean ``` (GRAVE ACCENT)?
+
+ "SIM105", # Use `contextlib.suppress(ValueError)` instead of `try`-`except`-`pass`
+ "SIM108", # Use ternary operator `description = func.__doc__.strip().split("\n")[0] if func.__doc__ else func.__name__` instead of `if`-`else`-block
+
+ "S101", # Use of `assert` detected
+ "S102", # Use of `exec` detected
+ "S106", # Possible hardcoded password assigned to argument: "secret"
+ "S105", # Possible hardcoded password assigned to: "child_secret"
+
+ "TD002", # Missing author in TODO; try: `# TODO(<author_name>): ...` or `# TODO @<author_name>: ...`
+ "TD003", # Missing issue link for this TODO
+
+ "T201", # `print` found
+
+ # TODO: stop ignoring these rules
+ "B027", # Checks for empty methods in abstract base classes without an abstract decorator.
+ "UP007", # Use `X | Y` for type annotations
+ "UP036", # Version block is outdated for minimum Python version
+ "SIM102", # Use a single `if` statement instead of nested `if` statements
+ "S701", # Using jinja2 templates with `autoescape=False` is dangerous and can lead to XSS. Ensure `autoescape=True` or use the `select_autoescape` function.
+ "N818", # Exception name `RootException` should be named with an Error suffix
+ "TRY301", # Abstract `raise` to an inner function
+ "PERF401", # Use a list comprehension to create a transformed list
+ "PLW2901", # `for` loop variable `line` overwritten by assignment target
+ "TRY300", # Consider moving this statement to an `else` block
+ "UP035", # `typing.List` is deprecated, use `list` instead
+ "RET503", # Missing explicit `return` at the end of function able to return non-`None` value
+]
+
+[tool.ruff.lint.pydocstyle]
+convention = "google"
+
+[tool.ruff.lint.flake8-type-checking]
+# Pydantic resolves field annotations at runtime (model build / validation), so
+# imports used only in annotations on a BaseModel subclass must stay at module
+# scope — TC001/TC002/TC003 would otherwise push them into a TYPE_CHECKING block
+# and break model construction.
+# The pipelex bases below are themselves BaseModel subclasses, but ruff resolves this
+# list by name and cannot see through the inheritance — so a model that documents the
+# wire shape by subclassing one of them needs its base listed here explicitly too.
+runtime-evaluated-base-classes = [
+ "pydantic.BaseModel",
+ "pipelex.core.pipes.pipe_output.PipeOutput",
+ "pipelex.pipeline.pipeline_response.PipelexRunResultExecute",
+ "pipelex.pipeline.pipeline_response.PipelexRunResultStart",
+]
+
+[tool.ruff.lint.per-file-ignores]
+"tests/**/*.py" = [
+ "T201", # Allow print statements in test files
+ "INP001", # Allow test files to not have __init__.py in their directories (avoids namespace collisions)
+]
+"scripts/**/*.py" = [
+ "INP001", # scripts/ is a directory of standalone entry points, not a package
+]
+
+[tool.pylint.main]
+py-version = "3.11"
+reports = false
+
+[tool.pylint.messages_control]
+disable = ["all"]
+enable = [
+ "W0101", # Unreachable code: Used when there is some code behind a "return" or "raise" statement, which will never be accessed.
+]
+ignore = [".venv", "__pycache__", "build", "dist", ".git"]
diff --git a/api/scripts/export_openapi.py b/api/scripts/export_openapi.py
new file mode 100644
index 000000000..777dd66f5
--- /dev/null
+++ b/api/scripts/export_openapi.py
@@ -0,0 +1,63 @@
+"""Export the FastAPI-generated OpenAPI schema to the committed YAML artifact.
+
+The committed file (`docs/openapi/pipelex-api.openapi.yaml`) is the layer-2
+contract of the MTHDS Protocol nesting (MTHDS Protocol ⊂ Pipelex API ⊂ Pipelex
+hosted API): the five protocol routes are tagged `x-mthds-protocol: true`, the
+build tooling extensions ride alongside, and the non-contract storage routes
+(`/upload`, `/resolve-storage-url`) are documented as such in their
+descriptions.
+
+Usage:
+ python scripts/export_openapi.py docs/openapi/pipelex-api.openapi.yaml
+ python scripts/export_openapi.py --check docs/openapi/pipelex-api.openapi.yaml
+
+`--check` exits non-zero when the committed artifact drifts from the schema the
+app currently generates — `make openapi-check`, which the gate (`make agent-check`, here or at the
+repository root) runs.
+"""
+
+import argparse
+import sys
+from pathlib import Path
+
+import yaml
+
+from pipelex_api.main import fastapi_app
+
+_GENERATED_HEADER = "# GENERATED FILE — do not edit by hand. Regenerate with `make openapi-export`.\n"
+_EXPORT_HINT = "`make openapi-export` in api/ (`make -C api openapi-export` from the repository root)"
+
+
+def render_openapi_yaml() -> str:
+ schema = fastapi_app.openapi()
+ body = yaml.safe_dump(schema, sort_keys=False, allow_unicode=True, width=120)
+ return _GENERATED_HEADER + body
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description="Export (or drift-check) the committed OpenAPI artifact.")
+ parser.add_argument("target", type=Path, help="Path of the committed OpenAPI YAML artifact")
+ parser.add_argument("--check", action="store_true", help="Compare a fresh export against the committed artifact; exit 1 on drift")
+ args = parser.parse_args()
+
+ rendered = render_openapi_yaml()
+ target: Path = args.target
+
+ if args.check:
+ if not target.exists():
+ print(f"OpenAPI drift check FAILED: {target} does not exist. Run {_EXPORT_HINT}.")
+ return 1
+ if target.read_text(encoding="utf-8") != rendered:
+ print(f"OpenAPI drift check FAILED: {target} is stale. Run {_EXPORT_HINT} and commit the result.")
+ return 1
+ print(f"OpenAPI artifact is up to date: {target}")
+ return 0
+
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_text(rendered, encoding="utf-8")
+ print(f"Wrote {target}")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/api/scripts/sync_vendored_kit.py b/api/scripts/sync_vendored_kit.py
new file mode 100644
index 000000000..b964dd3a9
--- /dev/null
+++ b/api/scripts/sync_vendored_kit.py
@@ -0,0 +1,330 @@
+"""Keep the server's vendored `.pipelex/inference/` tree in step with the kit of the pipelex beside it.
+
+The image serves the models its `/root/.pipelex/inference/` tree declares, and that tree is the
+member's `api/.pipelex/inference/`, copied in by the Dockerfile; `make run` and the tests read the
+same tree. Once a config directory exists, pipelex never reads the kit shipped inside its own
+package, so a kit change reaches the server only when these files move with it. The server runs the
+pipelex of the same commit, so the tree is kept in step in the same change as the kit: the root
+`make up-kit-configs` (`ukc`), the step a kit change already takes, runs this script too, and
+`make -C api kit-check`, part of the member's `agent-check`, fails a change that left the tree
+behind. This script owns the whole tree, under four rules:
+
+- `inference/backends/` mirrors the kit's directory: every kit file byte for byte, the kit's
+ `.kit_manifest.json` included, and no other file. What `pipelex migrate` leaves beside the files
+ it rewrites is never counted or deleted.
+- `inference/routing_profiles.toml` is the kit's, byte for byte.
+- `inference/backends.toml` is the kit's except for each backend's `enabled` switch, which is this
+ image's own choice: the switch is carried over from the current file, read the way pipelex reads
+ it (a table with no `enabled` key is on), and a backend the kit adds arrives disabled. The current
+ file is the only record of those choices, so when it is missing or unreadable, or lacks the table
+ of a backend whose file is already vendored, both modes stop rather than invent a switch.
+- `inference/deck/`: the numbered files and the `.kit_manifest.json` are the kit's, byte for byte.
+ The `x_custom_*` overrides are this server's own and are never touched.
+
+The manifests are mirrored rather than recomputed so that nothing here depends on the version
+number: a release moves the version and leaves this tree as it is.
+
+Usage:
+ python scripts/sync_vendored_kit.py .pipelex
+ python scripts/sync_vendored_kit.py --check .pipelex
+
+`--check` exits non-zero when the vendored tree has drifted from the kit. Both modes also fail when
+the kit ships an `inference/` entry none of the rules above covers, since only a person can decide
+what this image does with it.
+"""
+
+import argparse
+import re
+import sys
+import tomllib
+from pathlib import Path
+from typing import cast
+
+from pipelex.cogt.models.deck_manifest import (
+ MANIFEST_FILENAME,
+ KitManagedArea,
+ kit_deck_dir,
+ list_managed_installed_files,
+ list_managed_kit_files,
+)
+from pipelex.kit.paths import get_kit_configs_dir
+from pipelex.migration.backup import BACKUP_INFIX, RESCUE_INFIX
+from pipelex.tools.misc.package_utils import get_package_version
+from pydantic import BaseModel, ConfigDict, Field
+
+_BACKENDS_DIR = "backends"
+_DECK_DIR = "deck"
+_BACKENDS_TOML = "backends.toml"
+_ROUTING_PROFILES_TOML = "routing_profiles.toml"
+_HANDLED_KIT_ENTRIES = frozenset({_BACKENDS_DIR, _DECK_DIR, _BACKENDS_TOML, _ROUTING_PROFILES_TOML})
+
+# `pipelex migrate` can leave three kinds of file beside each file it rewrites: `<file>.bak.<stamp>`
+# backups, `<file>.rescue.<stamp>` copies whose removal pipelex leaves to the user, and the
+# `.<file>.pipelex-fix-<label>.<random>.tmp` staging files a crash can strand. The mirror neither
+# counts nor deletes any of them, nor a hand-made `*.bak`, nor a Finder `.DS_Store`.
+_MIGRATION_LEFTOVER_MARKERS = (BACKUP_INFIX, RESCUE_INFIX, ".pipelex-fix-")
+_IGNORED_NAMES = frozenset({".DS_Store"})
+
+_TABLE_HEADER = re.compile(r"^\[([^\[\]]+)\]")
+_ENABLED_SWITCH = re.compile(r"^(enabled\s*=\s*)(true|false)\b")
+
+_BACKENDS_TOML_PREAMBLE = """\
+# pipelex-api: this is the kit's `inference/backends.toml` from the pipelex of this repository, re-synced
+# by `make kit-sync`. Only the `enabled` switches are this image's own choice, and the sync keeps them;
+# any other edit is reported as drift by `make kit-check`.
+#
+"""
+
+
+class KitShapeError(Exception):
+ """The kit no longer has the shape these rules were written for."""
+
+
+class SwitchSourceError(Exception):
+ """The vendored backends.toml cannot say which backends this image enables."""
+
+
+class Drift(BaseModel):
+ """One vendored file that differs from what the kit says it should be."""
+
+ model_config = ConfigDict(frozen=True, extra="forbid")
+
+ path: Path
+ reason: str
+ content: bytes | None = Field(description="What the file should hold, or None when it should not exist")
+
+
+class SyncPlan(BaseModel):
+ model_config = ConfigDict(extra="forbid")
+
+ drifts: list[Drift] = Field(default_factory=list[Drift])
+ unhandled_kit_entries: list[str] = Field(default_factory=list)
+ dropped_backend_switches: dict[str, bool] = Field(default_factory=dict)
+
+ @property
+ def is_clean(self) -> bool:
+ return not self.drifts and not self.unhandled_kit_entries
+
+
+def _is_mirrored_name(name: str) -> bool:
+ if name in _IGNORED_NAMES or name.endswith(".bak"):
+ return False
+ return not any(marker in name for marker in _MIGRATION_LEFTOVER_MARKERS)
+
+
+def _compare_file(*, target: Path, expected: bytes | None, plan: SyncPlan) -> None:
+ if expected is None:
+ if target.exists():
+ plan.drifts.append(Drift(path=target, reason="absent from the kit", content=None))
+ return
+ if not target.is_file():
+ plan.drifts.append(Drift(path=target, reason="added in the kit", content=expected))
+ elif target.read_bytes() != expected:
+ plan.drifts.append(Drift(path=target, reason="differs from the kit", content=expected))
+
+
+def _plan_backends_dir(*, kit_dir: Path, vendored_dir: Path, plan: SyncPlan) -> None:
+ kit_files = {entry.name: entry for entry in kit_dir.iterdir() if entry.is_file() and _is_mirrored_name(entry.name)}
+ vendored_names: set[str] = set()
+ if vendored_dir.is_dir():
+ vendored_names = {entry.name for entry in vendored_dir.iterdir() if entry.is_file() and _is_mirrored_name(entry.name)}
+ for name in sorted(set(kit_files) | vendored_names):
+ kit_file = kit_files.get(name)
+ _compare_file(target=vendored_dir / name, expected=kit_file.read_bytes() if kit_file is not None else None, plan=plan)
+
+
+def read_enabled_switches(backends_toml: Path) -> dict[str, bool]:
+ """Read each backend's `enabled` switch from the vendored backends.toml, as pipelex reads it.
+
+ Args:
+ backends_toml: The vendored `inference/backends.toml`, the only record of this image's switches.
+
+ Returns:
+ The switch per backend table. A table with no `enabled` key is on, which is pipelex's default.
+
+ Raises:
+ SwitchSourceError: The file is missing, is not valid TOML, holds no backend table, or sets an
+ `enabled` that is not a boolean. Rendering from it would invent this image's switches.
+ """
+ if not backends_toml.is_file():
+ msg = f"{backends_toml} is missing, and it is the only record of which backends this image enables. Restore it from git and run again."
+ raise SwitchSourceError(msg)
+ try:
+ document = tomllib.loads(backends_toml.read_text(encoding="utf-8"))
+ except tomllib.TOMLDecodeError as exc:
+ msg = f"{backends_toml} is not valid TOML ({exc}), so this image's `enabled` switches cannot be read from it."
+ raise SwitchSourceError(msg) from exc
+ switches: dict[str, bool] = {}
+ for backend_name, table in document.items():
+ if not isinstance(table, dict):
+ continue
+ switch = cast("dict[str, object]", table).get("enabled", True)
+ if not isinstance(switch, bool):
+ msg = (
+ f"{backends_toml} sets `enabled` on [{backend_name}] to {switch!r}, which is not a boolean, so this image's switch for it is unknown."
+ )
+ raise SwitchSourceError(msg)
+ switches[backend_name] = switch
+ if not switches:
+ msg = f"{backends_toml} holds no backend table, so which backends this image enables is unknown. Restore it from git and run again."
+ raise SwitchSourceError(msg)
+ return switches
+
+
+def _table_names(toml_text: str) -> set[str]:
+ return {name for name, value in tomllib.loads(toml_text).items() if isinstance(value, dict)}
+
+
+def render_backends_toml(*, kit_text: str, enabled_switches: dict[str, bool]) -> str:
+ """Render the kit's backends.toml with this image's `enabled` switches in place of the kit's.
+
+ Args:
+ kit_text: The kit's `inference/backends.toml`.
+ enabled_switches: This image's switch per backend. A backend missing from it is disabled.
+
+ Returns:
+ The file the vendored tree should hold.
+
+ Raises:
+ KitShapeError: A kit table carries no `enabled` line, so a switch has nowhere to go.
+ """
+ rendered_lines = [_BACKENDS_TOML_PREAMBLE]
+ current_table: str | None = None
+ switched_tables: set[str] = set()
+ for line in kit_text.splitlines(keepends=True):
+ rendered_line = line
+ header_match = _TABLE_HEADER.match(line)
+ if header_match is not None:
+ current_table = header_match.group(1).strip().strip('"')
+ elif current_table is not None:
+ switch_match = _ENABLED_SWITCH.match(line)
+ if switch_match is not None:
+ switch_value = "true" if enabled_switches.get(current_table, False) else "false"
+ rendered_line = f"{switch_match.group(1)}{switch_value}{line[switch_match.end() :]}"
+ switched_tables.add(current_table)
+ rendered_lines.append(rendered_line)
+ unswitched_tables = sorted(_table_names(kit_text) - switched_tables)
+ if unswitched_tables:
+ msg = f"The kit's backends.toml has tables with no `enabled` line, so this image's switch cannot be carried: {', '.join(unswitched_tables)}"
+ raise KitShapeError(msg)
+ return "".join(rendered_lines)
+
+
+def _plan_backends_toml(*, kit_file: Path, vendored_file: Path, vendored_backends_dir: Path, plan: SyncPlan) -> None:
+ kit_text = kit_file.read_text(encoding="utf-8")
+ enabled_switches = read_enabled_switches(vendored_file)
+ kit_backends = _table_names(kit_text)
+ # A kit backend with no table here is new only if its backend file is new too. One whose file is
+ # already vendored had a table, so the switch record was cut short and its switch is unknown.
+ unrecorded_backends = sorted(name for name in kit_backends - set(enabled_switches) if (vendored_backends_dir / f"{name}.toml").is_file())
+ if unrecorded_backends:
+ msg = (
+ f"{vendored_file} has no table for {', '.join(unrecorded_backends)}, whose backend files are already vendored, "
+ "so this image's switch for them is unknown. Restore the file from git and run again."
+ )
+ raise SwitchSourceError(msg)
+ plan.dropped_backend_switches = {name: value for name, value in enabled_switches.items() if name not in kit_backends}
+ rendered = render_backends_toml(kit_text=kit_text, enabled_switches=enabled_switches)
+ _compare_file(target=vendored_file, expected=rendered.encode("utf-8"), plan=plan)
+
+
+def _plan_deck(*, vendored_deck_dir: Path, plan: SyncPlan) -> None:
+ kit_dir = kit_deck_dir()
+ kit_names = set(list_managed_kit_files(area=KitManagedArea.DECK))
+ vendored_names = set(list_managed_installed_files(vendored_deck_dir, area=KitManagedArea.DECK))
+ for name in sorted(kit_names | vendored_names):
+ expected = (kit_dir / name).read_bytes() if name in kit_names else None
+ _compare_file(target=vendored_deck_dir / name, expected=expected, plan=plan)
+ kit_manifest = kit_dir / MANIFEST_FILENAME
+ _compare_file(
+ target=vendored_deck_dir / MANIFEST_FILENAME,
+ expected=kit_manifest.read_bytes() if kit_manifest.is_file() else None,
+ plan=plan,
+ )
+
+
+def plan_sync(config_dir: Path) -> SyncPlan:
+ """Compare a vendored config dir's `inference/` tree against the installed pipelex's kit."""
+ kit_inference_dir = Path(str(get_kit_configs_dir())) / "inference"
+ vendored_inference_dir = config_dir / "inference"
+ plan = SyncPlan()
+ plan.unhandled_kit_entries = sorted(
+ entry.name for entry in kit_inference_dir.iterdir() if entry.name not in _HANDLED_KIT_ENTRIES and _is_mirrored_name(entry.name)
+ )
+ _plan_backends_dir(kit_dir=kit_inference_dir / _BACKENDS_DIR, vendored_dir=vendored_inference_dir / _BACKENDS_DIR, plan=plan)
+ routing_profiles = (kit_inference_dir / _ROUTING_PROFILES_TOML).read_bytes()
+ _compare_file(target=vendored_inference_dir / _ROUTING_PROFILES_TOML, expected=routing_profiles, plan=plan)
+ _plan_backends_toml(
+ kit_file=kit_inference_dir / _BACKENDS_TOML,
+ vendored_file=vendored_inference_dir / _BACKENDS_TOML,
+ vendored_backends_dir=vendored_inference_dir / _BACKENDS_DIR,
+ plan=plan,
+ )
+ _plan_deck(vendored_deck_dir=vendored_inference_dir / _DECK_DIR, plan=plan)
+ return plan
+
+
+def apply_plan(plan: SyncPlan) -> None:
+ for drift in plan.drifts:
+ if drift.content is None:
+ drift.path.unlink()
+ else:
+ drift.path.parent.mkdir(parents=True, exist_ok=True)
+ drift.path.write_bytes(drift.content)
+
+
+def _describe(plan: SyncPlan) -> list[str]:
+ return [f" {drift.path}: {drift.reason}" for drift in plan.drifts]
+
+
+def _describe_unhandled(plan: SyncPlan) -> str:
+ entries = ", ".join(f"inference/{name}" for name in plan.unhandled_kit_entries)
+ return f"The kit ships {entries}, which no rule in scripts/sync_vendored_kit.py covers. Decide what this image does with it and add the rule."
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description="Re-sync (or drift-check) the vendored inference tree against the installed pipelex kit.")
+ parser.add_argument("config_dir", type=Path, help="The vendored pipelex config dir, normally .pipelex")
+ parser.add_argument("--check", action="store_true", help="Report drift and exit 1 instead of re-syncing")
+ args = parser.parse_args()
+
+ config_dir: Path = args.config_dir
+ kit_version = get_package_version()
+ mode = "drift check" if args.check else "sync"
+ try:
+ plan = plan_sync(config_dir)
+ except (KitShapeError, SwitchSourceError) as exc:
+ print(f"Vendored kit {mode} FAILED against pipelex {kit_version}: {exc}")
+ return 1
+
+ if args.check:
+ if plan.is_clean:
+ print(f"Vendored inference tree matches the pipelex {kit_version} kit: {config_dir / 'inference'}")
+ return 0
+ print(f"Vendored kit drift check FAILED against pipelex {kit_version}:")
+ for line in _describe(plan):
+ print(line)
+ if plan.unhandled_kit_entries:
+ print(_describe_unhandled(plan))
+ if plan.drifts:
+ print("Run `make kit-sync` in api/, or `make up-kit-configs` at the repository root, and commit the result.")
+ return 1
+
+ for backend_name, enabled in sorted(plan.dropped_backend_switches.items()):
+ state = "enabled" if enabled else "disabled"
+ print(f"Note: backend '{backend_name}' is no longer in the kit, so its switch ({state}) is dropped.")
+ if plan.drifts:
+ apply_plan(plan)
+ print(f"Re-synced the vendored inference tree to the pipelex {kit_version} kit:")
+ for line in _describe(plan):
+ print(line)
+ else:
+ print(f"Vendored inference tree already matches the pipelex {kit_version} kit.")
+ if plan.unhandled_kit_entries:
+ print(_describe_unhandled(plan))
+ return 1
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/api/tests/__init__.py b/api/tests/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/api/tests/conftest.py b/api/tests/conftest.py
new file mode 100644
index 000000000..cd63503d9
--- /dev/null
+++ b/api/tests/conftest.py
@@ -0,0 +1,13 @@
+import os
+
+# Set a placeholder for COMPLETION_CALLBACK_SECRET so tests that exercise /start
+# never depend on the developer's shell env. CAVEAT: `make` test targets export
+# every `.env` key NAME into the child env (including commented-out ones) as
+# EMPTY strings, and `setdefault` cannot replace an existing empty value — so
+# tests that verify the callback signature must pin the secret themselves via
+# `mocker.patch.dict(os.environ, ...)` (see tests/unit/test_protocol_conformance.py).
+os.environ.setdefault("COMPLETION_CALLBACK_SECRET", "test-placeholder-completion-callback-secret")
+
+pytest_plugins = [
+ "pipelex.test_extras.shared_pytest_plugins",
+]
diff --git a/api/tests/py.typed b/api/tests/py.typed
new file mode 100644
index 000000000..e69de29bb
diff --git a/api/tests/unit/__init__.py b/api/tests/unit/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/api/tests/unit/_constants.py b/api/tests/unit/_constants.py
new file mode 100644
index 000000000..dad43a078
--- /dev/null
+++ b/api/tests/unit/_constants.py
@@ -0,0 +1,384 @@
+"""Shared constants for unit tests.
+
+Each test class assembles a tiny FastAPI app with a couple of throwaway
+routes used purely to exercise the auth dependencies through `TestClient`.
+Centralising the path strings here means the route names never drift out
+of sync between the `add_api_route` call and the `client.get(...)` call.
+"""
+
+from enum import StrEnum
+
+
+class RoutePath(StrEnum):
+ """Route paths registered by the test helper apps.
+
+ Named `RoutePath` (not `TestRoute`) so pytest's `Test*` class-collection
+ scanner doesn't try to collect this StrEnum.
+ """
+
+ WHOAMI = "/whoami"
+ PING = "/ping"
+
+
+# The stubbed method-package fixtures (`install_method_package` in conftest.py) present a fake
+# fetched clone in the library-repo layout: `methods/documents/METHODS.toml` declaring this
+# manifest, so the package's full address is `github.com/pipelex/methods/documents`.
+STUB_METHOD_ADDRESS = "github.com/pipelex/methods/documents"
+STUB_METHOD_COMMIT_SHA = "0123456789abcdef0123456789abcdef01234567"
+STUB_METHOD_MANIFEST = """\
+[package]
+name = "documents"
+address = "github.com/pipelex/methods"
+version = "0.1.0"
+description = "A stub package for method_ref route tests."
+main_pipe = "echo"
+
+[exports.smoke]
+pipes = ["echo"]
+"""
+
+# The same stub manifest with `main_pipe` naming `shout` — a pipe the closure's own declarations
+# would NOT default to (and, beside a second declared main_pipe, could not default at all). Exercises
+# the manifest outranking the closure in the tooling routes' pipe-default chain.
+STUB_METHOD_MANIFEST_MAIN_PIPE_SHOUT = """\
+[package]
+name = "documents"
+address = "github.com/pipelex/methods"
+version = "0.1.0"
+description = "A stub package whose manifest names an entry pipe the closure would not default to."
+main_pipe = "shout"
+
+[exports.smoke]
+pipes = ["echo"]
+
+[exports.other]
+pipes = ["shout"]
+"""
+
+# The same stub manifest declaring NO `main_pipe` — the chain then falls through to the closure's
+# own declaration, exactly as for inline `files[]`.
+STUB_METHOD_MANIFEST_NO_MAIN_PIPE = """\
+[package]
+name = "documents"
+address = "github.com/pipelex/methods"
+version = "0.1.0"
+description = "A stub package whose manifest declares no entry pipe."
+
+[exports.smoke]
+pipes = ["echo"]
+"""
+
+# A stub manifest naming `echo` as the entry pipe of a package whose only bundle is
+# `NO_MAIN_PIPE_MTHDS` (domain `nomain`): the manifest is then the only place the entry pipe is
+# declared, as in a published package whose bundles leave `main_pipe` to `METHODS.toml`.
+STUB_METHOD_MANIFEST_NOMAIN_ENTRY = """\
+[package]
+name = "documents"
+address = "github.com/pipelex/methods"
+version = "0.1.0"
+description = "A stub package whose entry pipe only its manifest declares."
+main_pipe = "echo"
+
+[exports.nomain]
+pipes = ["echo"]
+"""
+
+# A minimal, valid single-pipe bundle used across the build/validate/pipeline route tests.
+VALID_MTHDS = """\
+domain = "smoke"
+main_pipe = "echo"
+
+[pipe.echo]
+type = "PipeLLM"
+description = "Echo"
+inputs = { text = "Text" }
+output = "Text"
+prompt = "@text"
+"""
+
+# A second bundle in the `smoke` domain, referencing VALID_MTHDS's pipe — proves the closure is
+# merged across files[] entries before resolution, and gives the closure a second, non-entry pipe.
+SIBLING_MTHDS = """\
+domain = "smoke"
+
+[pipe.wrap_echo]
+type = "PipeSequence"
+description = "Wrap the echo pipe"
+inputs = { text = "Text" }
+output = "Text"
+steps = [{ pipe = "echo", result = "echoed" }]
+"""
+
+# One pipe whose contracts and forms carry multiplicity (a variable list input, a fixed-count
+# output) and a structured concept with an optional field — the shapes an I/O artifact must carry.
+SHAPES_MTHDS = """\
+domain = "shapes"
+main_pipe = "digest"
+
+[concept]
+Brief = "A short brief"
+Note = "A working note"
+
+[concept.Card]
+description = "A structured card"
+
+[concept.Card.structure]
+title = { type = "text", description = "The card title", required = true }
+score = { type = "number", description = "A score" }
+
+[pipe.digest]
+type = "PipeLLM"
+description = "Digest a brief and some notes into two cards"
+inputs = { brief = "Brief", notes = "Note[]" }
+output = "Card[2]"
+prompt = '''
+Digest this brief: $brief
+
+@notes
+'''
+"""
+
+# A valid single-pipe bundle that declares NO main_pipe — validates fine (D2: no main-pipe
+# precondition on /validate) and simply yields no graph. On the per-pipe `/build/*` projections it is
+# also the closure that cannot default its pipe selector: an omitted `pipe_ref` is a 422 there.
+NO_MAIN_PIPE_MTHDS = """\
+domain = "nomain"
+
+[pipe.echo]
+type = "PipeLLM"
+description = "Echo"
+inputs = { text = "Text" }
+output = "Text"
+prompt = "@text"
+"""
+
+# A second domain declaring its own main_pipe. Submitted alongside VALID_MTHDS it makes the closure's
+# main_pipe *ambiguous* — the other arm an omitted `pipe_ref` must reject with a 422.
+SECOND_MAIN_PIPE_MTHDS = """\
+domain = "other"
+main_pipe = "shout"
+
+[pipe.shout]
+type = "PipeLLM"
+description = "Shout"
+inputs = { text = "Text" }
+output = "Text"
+prompt = "@text"
+"""
+
+# A pipe that declares no inputs at all. Its inputs template is empty — a valid verdict, not an error
+# (the engine renderers raise NoInputsRequiredError; the CLI exits 0 on it).
+NO_INPUTS_MTHDS = """\
+domain = "noinputs"
+main_pipe = "greet"
+
+[pipe.greet]
+type = "PipeLLM"
+description = "Greet nobody in particular"
+output = "Text"
+prompt = "Say hello"
+"""
+
+# A pipe whose BARE code collides with VALID_MTHDS's `echo`, in a different domain, and whose output
+# carries the opposite multiplicity (a list). Submitted alongside VALID_MTHDS it catches any lookup
+# that matches a pipe by bare code alone: `/build/runner` reads the requested pipe's output
+# multiplicity out of the blueprints, and a bare-code scan would return whichever `echo` came first.
+COLLIDING_ECHO_LIST_MTHDS = """\
+domain = "twin"
+
+[pipe.echo]
+type = "PipeLLM"
+description = "Echo, but many"
+inputs = { text = "Text" }
+output = "Text[]"
+prompt = "@text"
+"""
+
+# An invalid `main_pipe` deterministically fails blueprint validation, producing a categorized
+# BLUEPRINT_VALIDATION error that carries the blueprint's `source` — the cheapest way to exercise
+# the structured `validation_errors` 422 and its `source` threading. (Mirrors the pipelex
+# integration fixture in `tests/integration/pipelex/pipeline/test_validate_bundle_source_threading.py`.)
+INVALID_MAIN_PIPE_MTHDS = """\
+domain = "broken"
+description = "Invalid main_pipe"
+main_pipe = "Not A Valid Pipe Code!"
+
+[concept.Customer]
+description = "A customer"
+"""
+
+# Multi-file batches mirroring pipelex's additive-multi-file-library E2E fixtures
+# (`tests/e2e/pipelex/pipes/additive_multi_file_library/` in the pipelex repo) — the same
+# scenarios the protocol-alignment baseline snapshots were captured from. Copied, not read
+# from the pipelex checkout: the suite must stay self-contained once the editable pin is
+# replaced by the PyPI pin (whose wheel ships no tests).
+
+# signature_only/: concepts + a PipeSignature header referenced by a sibling controller —
+# valid only in lenient mode (`allow_signatures=True`), reports the pending signature.
+SIGNATURE_ONLY_BATCH: list[str] = [
+ """\
+domain = "research"
+description = "Research method domain"
+
+[concept]
+KeyFinding = "A key finding extracted from a source document"
+""",
+ """\
+domain = "research"
+description = "Research method headers"
+
+[pipe.find_key_findings]
+description = "Find the key findings in a document (contract only)."
+inputs = { doc = "Text" }
+output = "KeyFinding"
+
+[pipe.research_brief]
+type = "PipeSequence"
+description = "Produce a research brief from a document."
+inputs = { doc = "Text" }
+output = "KeyFinding"
+steps = [{ pipe = "find_key_findings", result = "findings" }]
+""",
+]
+
+# header_and_definition/: the same header plus a concrete definition satisfying it —
+# valid in strict mode, nothing pending.
+HEADER_AND_DEFINITION_BATCH: list[str] = [
+ """\
+domain = "research"
+description = "Research method domain"
+
+[concept]
+KeyFinding = "A key finding extracted from a source document"
+""",
+ """\
+domain = "research"
+description = "Research method headers"
+
+[pipe.find_key_findings]
+description = "Find the key findings in a document (contract only)."
+inputs = { doc = "Text" }
+output = "KeyFinding"
+""",
+ """\
+domain = "research"
+description = "Research method definitions"
+
+[pipe.find_key_findings]
+type = "PipeLLM"
+description = "Find the key findings in a document."
+inputs = { doc = "native.Text" }
+output = "research.KeyFinding"
+model = "$quick-reasoning"
+prompt = "List the key findings in $doc."
+""",
+]
+
+# VALID_MTHDS with its output concept misspelled: the load refuses it as an `unresolved_concept`
+# item located on `pipe.echo.output`. A run of it used to escape the load as a raw 500.
+MISSPELLED_CONCEPT_MTHDS = """\
+domain = "smoke"
+main_pipe = "echo"
+
+[pipe.echo]
+type = "PipeLLM"
+description = "Echo"
+inputs = { text = "Text" }
+output = "Summry"
+prompt = "@text"
+"""
+
+# VALID_MTHDS naming a model the model deck does not define: the load refuses it as an
+# `unknown_model` item located on `pipe.echo.model`. A run of it used to raise the raw
+# `PipeOperatorModelChoiceError`, with no validation item.
+UNKNOWN_MODEL_MTHDS = """\
+domain = "smoke"
+main_pipe = "echo"
+
+[pipe.echo]
+type = "PipeLLM"
+description = "Echo"
+inputs = { text = "Text" }
+output = "Text"
+model = "no-such-model-in-any-deck"
+prompt = "@text"
+"""
+
+# A bundle that loads but whose run fails one step down, in a live run and a dry run alike since no
+# pipe calls a model: `review_topic` runs the parallel `analyze_topic`, whose branch `draft_idea` gives
+# one `Idea` for the field `ideas`, which `TopicReview` declares as a list. The combine of the branch
+# results refuses it at `analyze_topic`, and the refusal is the caller's own method to fix.
+MISMATCHED_PARALLEL_MTHDS = """\
+domain = "brainstorm"
+description = "A parallel feeding a single branch into a list field"
+main_pipe = "review_topic"
+
+[concept.Idea]
+description = "One idea about a topic"
+refines = "Text"
+
+[concept.Overview]
+description = "A one-line overview"
+refines = "Text"
+
+[concept.TopicReview]
+description = "Ideas and an overview"
+
+[concept.TopicReview.structure]
+ideas = { type = "list", item_type = "concept", item_concept_ref = "Idea", description = "The ideas", required = true }
+overview = { type = "concept", concept_ref = "Overview", description = "The overview", required = true }
+
+[pipe.review_topic]
+type = "PipeSequence"
+description = "Review a topic"
+inputs = { topic = "Text" }
+output = "TopicReview"
+steps = [ { pipe = "analyze_topic", result = "review" } ]
+
+[pipe.analyze_topic]
+type = "PipeParallel"
+description = "Draft the idea and the overview at the same time"
+inputs = { topic = "Text" }
+output = "TopicReview"
+branches = [
+ { pipe = "draft_idea", result = "ideas" },
+ { pipe = "write_overview", result = "overview" },
+]
+
+[pipe.draft_idea]
+type = "PipeCompose"
+description = "Draft one idea about the topic"
+inputs = { topic = "Text" }
+output = "Idea"
+template = "An idea worth exploring about $topic"
+
+[pipe.write_overview]
+type = "PipeCompose"
+description = "Write a one-line overview"
+output = "Overview"
+template = "One idea."
+"""
+
+# A bundle whose PipeSequence references an unimplemented PipeSignature step. It loads and wires
+# cleanly, so the only thing that rejects it in strict mode is the signature pre-pass — isolating
+# the `allow_signatures` behavior from any other validation failure.
+SIGNATURE_MTHDS = """\
+domain = "sig_api"
+main_pipe = "caller_seq"
+
+[concept]
+ApiDoc = "A document used in API signature tests."
+ApiSummary = "A summary used in API signature tests."
+
+[pipe.caller_seq]
+type = "PipeSequence"
+description = "Caller sequence referencing a signature step."
+inputs = { doc = "ApiDoc" }
+output = "ApiSummary"
+steps = [ { pipe = "summary_sig", result = "summary" } ]
+
+[pipe.summary_sig]
+description = "Signature placeholder for the summary step."
+inputs = { doc = "ApiDoc" }
+output = "ApiSummary"
+"""
diff --git a/api/tests/unit/conftest.py b/api/tests/unit/conftest.py
new file mode 100644
index 000000000..d9eaf0b1e
--- /dev/null
+++ b/api/tests/unit/conftest.py
@@ -0,0 +1,89 @@
+from collections.abc import Callable
+from pathlib import Path
+
+import pytest
+from pipelex.methods.fetching import FetchedMethodPackage, ensure_package_within_bounds
+from pipelex.methods.method_ref import MethodRef
+from pipelex.methods.package_locator import locate_package_in_clone
+from pipelex.pipelex import Pipelex
+from pipelex.system.runtime import IntegrationMode
+from pipelex.test_extras.shared_pytest_plugins import needs_inference_in_pipelex
+from pytest import FixtureRequest
+from pytest_mock import MockerFixture
+
+from pipelex_api.api_config import get_api_config
+from tests.unit._constants import STUB_METHOD_COMMIT_SHA, STUB_METHOD_MANIFEST
+
+
[email protected](autouse=True)
+def reset_api_config_fixture(request: FixtureRequest):
+ # Code to run before each test
+ print("\n[magenta] Api setup[/magenta]")
+ # The base runner is orchestrator-agnostic: with no orchestrator plugin installed and no
+ # `boot_orchestrator` set, every pipeline (incl. dry-run validation) runs DIRECT in-process,
+ # which is exactly what the hermetic suite needs. The former `temporal_enabled=False` knob is
+ # gone — Temporal is now an external plugin, absent from this repo's deps entirely.
+ pipelex_instance = Pipelex.make(
+ integration_mode=IntegrationMode.PYTEST,
+ needs_inference=needs_inference_in_pipelex(request),
+ )
+ # Drop the process-cached `[api]` config so a test that patches its env / loader cannot leak a
+ # mutated config into later tests through the `@cache`d `get_api_config()` (the suite otherwise
+ # relies on the packaged `direct` default — e.g. the `POST /start` override-policy 403 test).
+ get_api_config.cache_clear()
+ yield
+ # Code to run after each test
+ print("\n[magenta] Api teardown[/magenta]")
+ get_api_config.cache_clear()
+ pipelex_instance.teardown()
+
+
+class _StubCloneCache:
+ """A method clone cache whose network fetch is replaced by a local directory tree.
+
+ Only the fetch is stubbed: package location by manifest identity and the bounds check run
+ for real against the stub clone, so route tests exercise the true not-found / ambiguity
+ behavior (and their status mapping) without touching the network.
+ """
+
+ def __init__(self, *, clone_root: Path, commit_sha: str) -> None:
+ self._clone_root = clone_root
+ self._commit_sha = commit_sha
+
+ def get_or_fetch(self, *, ref: MethodRef, clone_url: str | None = None) -> FetchedMethodPackage: # noqa: ARG002
+ located = locate_package_in_clone(clone_root=self._clone_root, requested_address=ref.address)
+ ensure_package_within_bounds(package_dir=located.package_dir, package_address=located.full_address)
+ return FetchedMethodPackage(
+ ref=ref,
+ full_address=located.full_address,
+ commit_sha=self._commit_sha,
+ clone_dir=self._clone_root,
+ package_dir=located.package_dir,
+ manifest=located.manifest,
+ )
+
+
+def install_method_package(mocker: MockerFixture, tmp_path: Path) -> Callable[..., Path]:
+ """Factory fixture: present a fake fetched method package to the `method_ref` routes.
+
+ Writes the given `{relative_path: text}` files (plus `STUB_METHOD_MANIFEST` as
+ `METHODS.toml`, overridable) into a stub clone in the library-repo layout
+ (`methods/documents/`), and patches `pipelex_api.method_source.get_method_clone_cache` to serve
+ it. Returns the package directory.
+ """
+
+ def _install(*, files: dict[str, str], manifest_toml: str = STUB_METHOD_MANIFEST, commit_sha: str = STUB_METHOD_COMMIT_SHA) -> Path:
+ clone_root = tmp_path / "stub-clone"
+ package_dir = clone_root / "methods" / "documents"
+ package_dir.mkdir(parents=True, exist_ok=True)
+ (package_dir / "METHODS.toml").write_text(manifest_toml, encoding="utf-8")
+ for relative_path, content in files.items():
+ target = package_dir / relative_path
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_text(content, encoding="utf-8")
+ stub = _StubCloneCache(clone_root=clone_root, commit_sha=commit_sha)
+ mocker.patch("pipelex_api.method_source.get_method_clone_cache", return_value=stub)
+ return package_dir
+
+ return _install
diff --git a/api/tests/unit/test_allow_signatures.py b/api/tests/unit/test_allow_signatures.py
new file mode 100644
index 000000000..343bbe710
--- /dev/null
+++ b/api/tests/unit/test_allow_signatures.py
@@ -0,0 +1,94 @@
+"""`allow_signatures` is sweep-mechanics, not a gate (D-B: signatures-as-data).
+
+After the signatures-as-data reframe, an unimplemented `PipeSignature` is **never** a validation
+error — it is a *runnability fact*. `allow_signatures` no longer gates acceptance; it only controls
+whether signature pipes are mock-run during the dry-run sweep (and therefore listed in
+`validated_pipes`). So a bundle containing a signature is accepted in BOTH modes on the two routes
+that still run that sweep — `/validate` and `/build/runner`. On `/validate` the outstanding signature
+surfaces as `pending_signatures` + `is_runnable: false` (a 200 `ValidReport`, since the verdict is
+"sound but not runnable"), and the only mode difference is whether the signature pipe appears in
+`validated_pipes`.
+
+The static projections (`/build/{inputs,output}`) dropped the sweep entirely, so they no longer take
+the flag at all — a signature bundle is simply accepted there, and that is asserted in
+`test_build_routes_envelope.py`, not here.
+
+(`SignaturesNotAllowedError` — the strict-mode rejection this module used to assert — was removed
+with the de-raise; the build routes no longer reject a signature bundle.)
+"""
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+from pipelex_api.exception_handlers import register_exception_handlers
+from pipelex_api.routes import router as api_router
+from tests.unit._constants import SIGNATURE_MTHDS
+
+
+def _build_client() -> TestClient:
+ app = FastAPI()
+ app.include_router(api_router, prefix="/v1")
+ register_exception_handlers(app)
+ return TestClient(app)
+
+
+class TestAllowSignatures:
+ @pytest.mark.parametrize(
+ ("path", "payload_base"),
+ [
+ ("/v1/validate", {"mthds_contents": [SIGNATURE_MTHDS]}),
+ ("/v1/build/runner", {"files": [{"content": SIGNATURE_MTHDS}], "pipe_ref": "sig_api.caller_seq"}),
+ ],
+ )
+ @pytest.mark.parametrize("allow_signatures", [False, True], ids=["strict", "lenient"])
+ def test_signature_bundle_accepted_in_both_modes(self, path: str, payload_base: dict[str, object], allow_signatures: bool):
+ # An unimplemented signature is never a rejection (D-B): both modes answer 200 on the two routes
+ # that still sweep. Strict no longer differs from lenient on acceptance.
+ client = _build_client()
+ response = client.post(path, json={**payload_base, "allow_signatures": allow_signatures})
+ assert response.status_code == 200, response.text
+
+ @pytest.mark.parametrize("allow_signatures", [False, True], ids=["strict", "lenient"])
+ def test_validate_reports_pending_signature_in_both_modes(self, allow_signatures: bool):
+ # The verdict is "valid but not runnable" regardless of the flag: the outstanding signature
+ # rides `pending_signatures` + `is_runnable: false` on a 200 `ValidReport` (is_valid: true).
+ client = _build_client()
+ response = client.post("/v1/validate", json={"mthds_contents": [SIGNATURE_MTHDS], "allow_signatures": allow_signatures})
+ assert response.status_code == 200, response.text
+ body = response.json()
+ assert body["is_valid"] is True
+ assert body["is_runnable"] is False
+ assert body["pending_signatures"] == ["sig_api.summary_sig"]
+
+ def test_allow_signatures_only_changes_validated_pipes_inclusion(self):
+ # The single behavioral effect of the flag (D-B): the signature pipe is mock-run and listed in
+ # `validated_pipes` only in lenient mode. The verdict (`pending_signatures`, `is_runnable`) is
+ # identical either way — `allow_signatures` is sweep-mechanics, not a verdict knob.
+ client = _build_client()
+ strict = client.post("/v1/validate", json={"mthds_contents": [SIGNATURE_MTHDS]}).json()
+ lenient = client.post("/v1/validate", json={"mthds_contents": [SIGNATURE_MTHDS], "allow_signatures": True}).json()
+
+ strict_refs = {entry["pipe_ref"] for entry in strict["validated_pipes"]}
+ lenient_refs = {entry["pipe_ref"] for entry in lenient["validated_pipes"]}
+ assert strict_refs == {"sig_api.caller_seq"}
+ assert lenient_refs == {"sig_api.caller_seq", "sig_api.summary_sig"}
+ # The verdict is the same in both modes.
+ assert strict["pending_signatures"] == lenient["pending_signatures"] == ["sig_api.summary_sig"]
+ assert strict["is_runnable"] is False
+ assert lenient["is_runnable"] is False
+
+ def test_build_runner_generates_code_for_bundle_with_signatures_when_opted_in(self):
+ # The most concrete proof the flag threads through to the runner build: with allow_signatures
+ # the dry-run sweep mock-runs the signature, the library stays open, and runner code is
+ # generated for the caller pipe.
+ client = _build_client()
+ response = client.post(
+ "/v1/build/runner",
+ json={"files": [{"content": SIGNATURE_MTHDS}], "pipe_ref": "sig_api.caller_seq", "allow_signatures": True},
+ )
+ assert response.status_code == 200, response.text
+ body = response.json()
+ assert body["is_valid"] is True
+ assert body["pipe_ref"] == "sig_api.caller_seq"
+ assert body["python_code"]
diff --git a/api/tests/unit/test_analytics_groups_extras.py b/api/tests/unit/test_analytics_groups_extras.py
new file mode 100644
index 000000000..13884f3e8
--- /dev/null
+++ b/api/tests/unit/test_analytics_groups_extras.py
@@ -0,0 +1,164 @@
+"""`analytics_groups` must survive the wire -> extras -> runner -> `RunMetadata` hop on both run routes.
+
+Every failure on this path is SILENT by construction. The route hands the validated extras to
+`ApiRunner` field by field, so a keyword left out there is dropped with no error; `ApiRunner.start`
+builds its job by calling `pipeline_run_setup` itself, so a keyword left out there is dropped too. Either way the run still
+answers 200 or 202, and the only symptom is that every span of it arrives in PostHog with no
+organization. So these tests run the real `pipeline_run_setup` and read the groups off the
+`RunMetadata` the runtime built, rather than off a mocked constructor call.
+
+A stub orchestrator stands in for the backend, registered under an async-capable mode so that
+`/execute` (the blocking arm) and `/start` (the fire-and-forget arm) both dispatch to it.
+"""
+
+from typing import TYPE_CHECKING, Any
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+from pipelex.core.memory.working_memory import MAIN_STUFF_NAME
+from pipelex.core.pipes.pipe_output import PipeOutput
+from pipelex.pipe_run.delivery_assignment import DeliveryAssignment
+from pipelex.pipe_run.pipe_job import PipeJob
+from pipelex.plugins.orchestrator_registry import OrchestratorRegistry
+from pipelex.runtime_bridge.payloads import PipelexPipeDispatchAck, PipelexPipeRunOutput
+from pipelex.runtime_bridge.serialization import serialize_completed_output
+from pytest_mock import MockerFixture
+
+from pipelex_api.api_config import ApiConfig
+from pipelex_api.exception_handlers import register_exception_handlers
+from pipelex_api.routes import router as api_router
+from tests.unit._constants import VALID_MTHDS
+
+if TYPE_CHECKING:
+ from pipelex.system.job_metadata import RunMetadata
+
+_PIPELINE_NS = "pipelex_api.routes.pipelex.pipeline"
+_MODE = "temporal"
+_ROUTES = ["/v1/execute", "/v1/start"]
+_SUCCESS_STATUS = {"/v1/execute": 200, "/v1/start": 202}
+
+
+class _RecordingOrchestrator:
+ """Records the `RunMetadata` of every job it is handed, on either arm.
+
+ `execute` echoes the job's input back as the completed output, through the real
+ `serialize_completed_output`, so the route's rehydration runs as it does in production. Both arms
+ take `delivery_assignment` because the orchestrator protocol does; what the route delivers is
+ not what these tests are about.
+ """
+
+ supports_fire_and_forget = True
+
+ def __init__(self) -> None:
+ self.run_metadatas: list[RunMetadata] = []
+
+ async def execute(self, *, pipe_job: PipeJob, delivery_assignment: DeliveryAssignment | None) -> PipelexPipeRunOutput: # noqa: ARG002
+ self.run_metadatas.append(pipe_job.job_metadata.run_metadata)
+ working_memory = pipe_job.get_working_memory()
+ working_memory.set_alias(alias=MAIN_STUFF_NAME, target=next(iter(working_memory.root)))
+ return serialize_completed_output(
+ pipe_output=PipeOutput(
+ working_memory=working_memory,
+ pipeline_run_id=pipe_job.job_metadata.run_metadata.pipeline_run_id,
+ ),
+ workflow_id=None,
+ )
+
+ async def start(self, *, pipe_job: PipeJob, delivery_assignment: DeliveryAssignment | None) -> PipelexPipeDispatchAck: # noqa: ARG002
+ self.run_metadatas.append(pipe_job.job_metadata.run_metadata)
+ return PipelexPipeDispatchAck(
+ pipeline_run_id=pipe_job.job_metadata.run_metadata.pipeline_run_id,
+ workflow_id="wf-analytics-groups",
+ )
+
+
+def _build_client(mocker: MockerFixture) -> tuple[TestClient, _RecordingOrchestrator]:
+ config = ApiConfig(orchestration_mode=_MODE, allow_request_orchestration_mode_override=False)
+ mocker.patch(f"{_PIPELINE_NS}.get_api_config", return_value=config)
+ orchestrator = _RecordingOrchestrator()
+ mocker.patch(f"{_PIPELINE_NS}.get_orchestrator_registry", return_value=OrchestratorRegistry({_MODE: orchestrator}))
+ app = FastAPI()
+ app.include_router(api_router, prefix="/v1")
+ register_exception_handlers(app)
+ return TestClient(app), orchestrator
+
+
+def _run_body(**extras: Any) -> dict[str, Any]:
+ return {"pipe_code": "echo", "mthds_contents": [VALID_MTHDS], "inputs": {"text": "hello"}, **extras}
+
+
+class TestAnalyticsGroupsReachTheRun:
+ @pytest.mark.parametrize("route", _ROUTES)
+ def test_groups_reach_the_run_metadata(self, mocker: MockerFixture, route: str) -> None:
+ client, orchestrator = _build_client(mocker)
+ groups = {"organization": "org_acme", "workspace": "ws-42"}
+
+ response = client.post(route, json=_run_body(analytics_groups=groups))
+
+ assert response.status_code == _SUCCESS_STATUS[route], response.text
+ assert len(orchestrator.run_metadatas) == 1
+ assert orchestrator.run_metadatas[0].extras == groups
+
+ @pytest.mark.parametrize("route", _ROUTES)
+ @pytest.mark.parametrize(
+ "extras",
+ [
+ pytest.param({}, id="absent"),
+ pytest.param({"analytics_groups": None}, id="null"),
+ pytest.param({"analytics_groups": {}}, id="empty"),
+ ],
+ )
+ def test_no_groups_means_an_empty_mapping(self, mocker: MockerFixture, route: str, extras: dict[str, Any]) -> None:
+ # A run with no groups belongs to no group; it is not refused and nothing is invented.
+ client, orchestrator = _build_client(mocker)
+
+ response = client.post(route, json=_run_body(**extras))
+
+ assert response.status_code == _SUCCESS_STATUS[route], response.text
+ assert len(orchestrator.run_metadatas) == 1
+ assert orchestrator.run_metadatas[0].extras == {}
+
+ @pytest.mark.parametrize("route", _ROUTES)
+ @pytest.mark.parametrize(
+ "bad_groups",
+ [
+ pytest.param({"Organization": "org_acme"}, id="type-not-snake-case"),
+ pytest.param({"organization": "org acme"}, id="key-with-space"),
+ pytest.param({"organization": "org_acme\n"}, id="key-with-trailing-newline"),
+ pytest.param({"organization": ""}, id="empty-key"),
+ pytest.param({"organization": "a" * 129}, id="overlong-key"),
+ pytest.param({f"group_{idx}": "org_acme" for idx in range(6)}, id="over-the-entry-cap"),
+ pytest.param({"organization": 42}, id="non-string-key"),
+ pytest.param(["organization"], id="not-a-mapping-list"),
+ pytest.param("organization", id="not-a-mapping-string"),
+ ],
+ )
+ def test_malformed_groups_are_a_422_naming_the_field(self, mocker: MockerFixture, route: str, bad_groups: Any) -> None:
+ # Refused at the wire, before any method is loaded or any job dispatched: the value is
+ # quoted into log lines and forwarded to a telemetry backend as a group key.
+ client, orchestrator = _build_client(mocker)
+
+ response = client.post(route, json=_run_body(analytics_groups=bad_groups))
+
+ assert response.status_code == 422, response.text
+ assert response.headers["content-type"] == "application/problem+json"
+ body = response.json()
+ assert body["error_type"] == "InvalidAnalyticsGroups"
+ assert "analytics_groups" in body["detail"]
+ assert orchestrator.run_metadatas == []
+
+ def test_a_body_failing_on_two_extras_gets_the_generic_error_type(self, mocker: MockerFixture) -> None:
+ # Naming one of the two fields would send the caller to fix that one and leave the other
+ # for the next request, so the classification falls back to the generic type and the
+ # detail names both.
+ client, orchestrator = _build_client(mocker)
+
+ response = client.post("/v1/start", json=_run_body(storage_scope="../escape", analytics_groups={"Organization": "org_acme"}))
+
+ assert response.status_code == 422, response.text
+ body = response.json()
+ assert body["error_type"] == "ValidationError"
+ assert "storage_scope" in body["detail"]
+ assert "analytics_groups" in body["detail"]
+ assert orchestrator.run_metadatas == []
diff --git a/api/tests/unit/test_api_config.py b/api/tests/unit/test_api_config.py
new file mode 100644
index 000000000..83a8ed27a
--- /dev/null
+++ b/api/tests/unit/test_api_config.py
@@ -0,0 +1,106 @@
+"""`[api]` deployment config — the default orchestration mode + the per-request override policy.
+
+The orchestrator-agnostic base reads WHICH backend a top-level run dispatches to from a packaged
+`api.toml` (`ApiConfig`), and gates per-request overrides behind a deployment policy. `orchestration_mode`
+is an OPEN string token (core owns `"direct"`; each plugin owns its own); the delivery axis is
+endpoint-set, never configured. These tests pin the packaged default (`direct`, override off) and the
+resolver's policy: the default wins, a caller may only change the backend when the deployment opted in,
+and a forbidden override is a 403 — asserted both at the resolver and end-to-end on `POST /start`.
+"""
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+from pipelex_api.api_config import ApiBootConfigError, ApiConfig, get_api_config, resolve_boot_orchestrator, resolve_orchestration_mode
+from pipelex_api.errors import ApiError
+from pipelex_api.exception_handlers import register_exception_handlers
+from pipelex_api.middleware import RequestIdMiddleware
+from pipelex_api.routes.pipelex.pipeline import router as pipeline_router
+from tests.unit._constants import VALID_MTHDS
+
+
+def _temporal_locked_config() -> ApiConfig:
+ """A hosted-style config: the `temporal` backend, override OFF.
+
+ `orchestration_mode` names only the backend; the delivery axis (blocking vs fire-and-forget) is
+ endpoint-set, never configured, so there is no fire-and-forget token to reject here.
+ """
+ return ApiConfig(orchestration_mode="temporal", allow_request_orchestration_mode_override=False)
+
+
+class TestApiConfigDefault:
+ def test_packaged_default_is_direct_no_override(self):
+ # The source-available base names no orchestrator: it ships `direct` and refuses overrides.
+ config = get_api_config()
+ assert config.orchestration_mode == "direct"
+ assert config.allow_request_orchestration_mode_override is False
+
+
+class TestResolveOrchestrationMode:
+ def test_none_request_uses_deployment_default(self):
+ assert resolve_orchestration_mode(None, config=_temporal_locked_config()) == "temporal"
+
+ def test_request_equal_to_default_is_honored(self):
+ # A no-op override (same as the default) is always accepted, override policy or not.
+ config = _temporal_locked_config()
+ assert resolve_orchestration_mode("temporal", config=config) == "temporal"
+
+ def test_forbidden_override_is_refused(self):
+ # A caller must not be able to force `direct` on a locked-down distributed runner.
+ with pytest.raises(ApiError) as exc_info:
+ resolve_orchestration_mode("direct", config=_temporal_locked_config())
+ assert exc_info.value.status_code == 403
+ assert exc_info.value.document["error_type"] == "OrchestrationModeOverrideForbidden"
+
+ def test_allowed_override_is_honored(self):
+ config = ApiConfig(orchestration_mode="temporal", allow_request_orchestration_mode_override=True)
+ assert resolve_orchestration_mode("direct", config=config) == "direct"
+
+
+class TestResolveBootOrchestrator:
+ """`resolve_boot_orchestrator` derives the single orchestrator the process boots under from the
+ deployment config, and refuses a config whose single boot can't service its own override policy.
+ """
+
+ def test_direct_default_boots_in_process(self):
+ # The base `direct` mode names no orchestrator: it boots in-process (None).
+ config = ApiConfig(orchestration_mode="direct", allow_request_orchestration_mode_override=False)
+ assert resolve_boot_orchestrator(config) is None
+
+ def test_non_direct_default_boots_under_that_orchestrator(self):
+ config = ApiConfig(orchestration_mode="temporal", allow_request_orchestration_mode_override=False)
+ assert resolve_boot_orchestrator(config) == "temporal"
+
+ def test_non_direct_default_with_override_still_boots_under_that_orchestrator(self):
+ # Coherent: the async hub is claimed at boot, so a per-request `direct` override still runs
+ # in-process while `temporal` requests use the claimed hub.
+ config = ApiConfig(orchestration_mode="temporal", allow_request_orchestration_mode_override=True)
+ assert resolve_boot_orchestrator(config) == "temporal"
+
+ def test_direct_default_with_override_is_refused_at_boot(self):
+ # Incoherent: a `direct` boot claims no async hub, so a request overriding to a non-direct mode
+ # would fail at dispatch. Fail loud at boot instead of on the first overriding request.
+ config = ApiConfig(orchestration_mode="direct", allow_request_orchestration_mode_override=True)
+ with pytest.raises(ApiBootConfigError):
+ resolve_boot_orchestrator(config)
+
+
+class TestStartOverridePolicyEndToEnd:
+ def _client(self) -> TestClient:
+ app = FastAPI()
+ app.include_router(pipeline_router, prefix="/v1")
+ register_exception_handlers(app)
+ return TestClient(RequestIdMiddleware(app))
+
+ def test_forbidden_per_request_mode_on_start_is_403(self):
+ # The base config is `direct` with override off, so a caller forcing a different backend on
+ # `POST /start` is refused with a 403 BEFORE any library load / dispatch — the policy gate
+ # is the first thing `ApiRunner.start` checks.
+ response = self._client().post(
+ "/v1/start",
+ json={"pipe_code": "echo", "mthds_contents": [VALID_MTHDS], "orchestration_mode": "temporal"},
+ )
+ assert response.status_code == 403, response.text
+ assert response.headers["content-type"].startswith("application/problem+json")
+ assert response.json()["error_type"] == "OrchestrationModeOverrideForbidden"
diff --git a/api/tests/unit/test_build_and_agent_routes.py b/api/tests/unit/test_build_and_agent_routes.py
new file mode 100644
index 000000000..fbfb9fd4f
--- /dev/null
+++ b/api/tests/unit/test_build_and_agent_routes.py
@@ -0,0 +1,377 @@
+"""Smoke + validation tests for /validate, /build/* and /build/{concept,pipe-spec,models}."""
+
+from typing import Any
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+from pipelex.interpreter_hub import get_library_manager
+from pipelex.pipe_run.exceptions import DryRunError
+from pipelex.pipeline.bundle_validator import DryRunOutput, DryRunStatus
+from pytest_mock import MockerFixture
+
+from pipelex_api.exception_handlers import register_exception_handlers
+from pipelex_api.routes import router as api_router
+from tests.unit._constants import VALID_MTHDS
+
+
+def _build_client() -> TestClient:
+ app = FastAPI()
+ app.include_router(api_router, prefix="/v1")
+ register_exception_handlers(app)
+ return TestClient(app)
+
+
+class TestBuildAndAgentRoutes:
+ def test_validate_rejects_oversized_mthds(self):
+ client = _build_client()
+ oversized = "a" * (2 * 1024 * 1024) # 2 MiB > 1 MiB cap
+ response = client.post(
+ "/v1/validate",
+ json={"mthds_contents": [oversized]},
+ )
+ assert response.status_code == 422
+ assert response.headers["content-type"] == "application/problem+json"
+ assert response.json()["error_type"] == "ValidationError"
+
+ def test_validate_rejects_too_many_files(self):
+ client = _build_client()
+ response = client.post(
+ "/v1/validate",
+ json={"mthds_contents": [VALID_MTHDS] * 32},
+ )
+ assert response.status_code == 422
+ assert response.headers["content-type"] == "application/problem+json"
+ assert response.json()["error_type"] == "ValidationError"
+
+ def test_validate_invalid_mthds_returns_200_invalid_report(self):
+ # `/validate` is a diagnostic endpoint: an invalid bundle is a produced verdict, so it rides
+ # a 200 `InvalidReport` (discriminated on `is_valid: false`) — NOT a 422 problem document,
+ # and NOT the older `{success, mthds_contents, message}` 422 envelope. Invalid TOML reliably
+ # triggers a `ValidateBundleError` from the interpreter, which the route converts to the
+ # invalid arm. The verdict is carried by `is_valid`/`message`, not the status code.
+ client = _build_client()
+ response = client.post(
+ "/v1/validate",
+ json={"mthds_contents": ["this is not valid TOML !!!"]},
+ )
+ assert response.status_code == 200, response.text
+ assert response.headers["content-type"].startswith("application/json")
+ body = response.json()
+ assert body["is_valid"] is False
+ assert body["is_runnable"] is False
+ # The pipelex message is preserved (caller-facing under `_authors_caller_facing_message`) so
+ # the client gets the actual interpreter complaint, not a generic placeholder.
+ assert "TOML" in body["message"]
+ # The diagnostics list is non-empty on every invalid arm — the structured-info invariant is
+ # total. A raw TOML-syntax error is a parse-level failure the interpreter raises with no
+ # categorized error-data, but the shared builder's last-resort residual still emits one
+ # `blueprint_validation` item carrying the message (no `source` at this layer). A categorized
+ # failure (e.g. an invalid `main_pipe`) yields richer items; that path is pinned in
+ # test_validate_errors.py.
+ assert isinstance(body["validation_errors"], list)
+ assert body["validation_errors"], "an invalid verdict must carry a non-empty validation_errors[]"
+ assert body["validation_errors"][0]["category"] == "blueprint_validation"
+ assert body["validation_errors"][0]["message"]
+ # The valid arm's structural artifacts + the retired `success` extra are absent.
+ assert "bundle_blueprint" not in body
+ assert "success" not in body
+
+ # NOTE: the former `main_pipe` precondition on /validate is deleted (protocol alignment
+ # D2) — a bundle without `main_pipe` now answers 200 with `graph_spec=null`. The
+ # regression pin for that behavior (both backends) lives in `test_validate_envelope.py`.
+
+ def test_build_inputs_rejects_oversized_pipe_ref(self):
+ client = _build_client()
+ long_ref = "x" * 1024
+ response = client.post(
+ "/v1/build/inputs",
+ json={"files": [{"content": VALID_MTHDS}], "pipe_ref": long_ref},
+ )
+ assert response.status_code == 422
+ assert response.headers["content-type"] == "application/problem+json"
+ assert response.json()["error_type"] == "ValidationError"
+
+ def test_build_concept_rejects_oversized_spec(self):
+ client = _build_client()
+ big_spec = {"description": "x" * (512 * 1024)} # 512 KiB > 256 KiB cap
+ response = client.post("/v1/build/concept", json={"spec": big_spec})
+ assert response.status_code == 422
+ assert response.headers["content-type"] == "application/problem+json"
+ assert response.json()["error_type"] == "ValidationError"
+
+ @pytest.mark.parametrize("structure", ["string", {"f": 42}])
+ def test_build_concept_refuses_malformed_structure_with_a_typed_error(self, structure: Any):
+ # `parse_concept_spec` validates the raw shape of `structure` and raises the
+ # typed `ConceptSpecError`, so the route answers a problem document rather
+ # than an opaque 500 from a bare AttributeError / TypeError.
+ client = _build_client()
+ response = client.post(
+ "/v1/build/concept",
+ json={"spec": {"concept_code": "Thing", "description": "d", "structure": structure}},
+ )
+ assert response.status_code == 422
+ assert response.headers["content-type"] == "application/problem+json"
+ body = response.json()
+ assert body["error_type"] == "ConceptSpecError"
+ assert body["error_domain"] == "input"
+
+ def test_build_pipe_spec_rejects_unknown_pipe_type(self):
+ # `parse_pipe_spec` raises a bare `ValueError` for an unknown pipe_type
+ # (documented in its docstring). The route must classify that as a
+ # caller-input 422 — not let it escape as an opaque 500 through the
+ # global `Exception` fallback. Regression for `TODOS.md` Q4.
+ client = _build_client()
+ response = client.post(
+ "/v1/build/pipe-spec",
+ json={"pipe_type": "NotARealPipeType", "spec": {"pipe_code": "x", "description": "d", "output": "Text"}},
+ )
+ assert response.status_code == 422
+ assert response.headers["content-type"] == "application/problem+json"
+ body = response.json()
+ assert body["error_type"] == "ValidationError"
+ assert "NotARealPipeType" in body["detail"]
+
+ @pytest.mark.parametrize("bad_type", ["not-a-real-category", ""])
+ def test_models_rejects_invalid_category(self, bad_type: str):
+ # The empty string is an explicitly-supplied (invalid) filter value, not an absent
+ # param — it must fail loudly like any other unknown category, not silently return
+ # the unfiltered deck.
+ client = _build_client()
+ response = client.get(f"/v1/models?type={bad_type}")
+ assert response.status_code == 422
+ assert response.headers["content-type"] == "application/problem+json"
+ assert response.json()["error_type"] == "InvalidModelCategory"
+
+ def test_models_rejects_repeated_type_param(self):
+ # D11: the protocol's `type` filter is a single plain value. The old route accepted
+ # repeated `?type=` values (list[str] Query) — that extension is dropped, and FastAPI
+ # would otherwise silently keep one of the values, so the rejection is explicit.
+ # Generic ValidationError (not InvalidModelCategory): both values are valid
+ # categories — what's wrong is the arity.
+ client = _build_client()
+ response = client.get("/v1/models?type=llm&type=extract")
+ assert response.status_code == 422
+ assert response.headers["content-type"] == "application/problem+json"
+ assert response.json()["error_type"] == "ValidationError"
+
+ def test_models_returns_protocol_deck(self):
+ # The deck is the protocol `ModelDeck` shape produced by `PipelexMTHDSProtocol.models`:
+ # a non-empty flat `models` list (regression for the silently-empty deck the old raw
+ # per-category payload caused in the SDK — F2) plus this implementation's routing
+ # extensions, keyed by category (the same alias name exists in several categories —
+ # a flat map would silently drop entries on collision). The old raw keys (`presets`
+ # by category, `success`) are gone.
+ client = _build_client()
+ response = client.get("/v1/models")
+ assert response.status_code == 200, response.text
+ body = response.json()
+ assert body["models"], "the protocol deck must carry a non-empty models list"
+ first_model = body["models"][0]
+ assert first_model["name"]
+ assert first_model["type"]
+ valid_categories = {"llm", "extract", "img_gen", "search"}
+ assert set(body["aliases"]) <= valid_categories
+ assert all(isinstance(category_aliases, dict) for category_aliases in body["aliases"].values())
+ assert set(body["waterfalls"]) <= valid_categories
+ assert "presets" not in body
+ assert "success" not in body
+
+ def test_models_single_type_filter(self):
+ client = _build_client()
+ response = client.get("/v1/models?type=llm")
+ assert response.status_code == 200, response.text
+ body = response.json()
+ assert body["models"]
+ assert {model["type"] for model in body["models"]} == {"llm"}
+ assert set(body["aliases"]) <= {"llm"}
+
+ def test_empty_mthds_contents_rejected(self):
+ # `/validate` is the last route on the `mthds_contents` envelope (it is protocol-owned; the
+ # build routes moved to `files[]`, whose empty-selector rejection lives in the envelope suite).
+ client = _build_client()
+ response = client.post("/v1/validate", json={"mthds_contents": []})
+ assert response.status_code == 422
+ assert response.headers["content-type"] == "application/problem+json"
+ assert response.json()["error_type"] == "ValidationError"
+
+ def test_build_runner_tears_down_library_when_success_path_raises(self, mocker: MockerFixture):
+ # The loaded-on-success contract makes the route own teardown of validate_bundle's library.
+ # A failure anywhere in the success window (here: the SKIPPED guard, the first statement
+ # inside the try) must NOT leak that library — the finally tears down the exact id
+ # validate_bundle opened.
+ library_manager = get_library_manager()
+ open_spy = mocker.spy(library_manager, "open_library")
+ teardown_spy = mocker.spy(library_manager, "teardown")
+ mocker.patch(
+ "pipelex_api.routes.pipelex.build.runner._reject_if_requested_pipe_skipped",
+ side_effect=RuntimeError("synthetic success-path failure"),
+ )
+
+ # raise_server_exceptions=False: the synthetic RuntimeError reaches the
+ # catch-all `Exception` handler, but Starlette's ServerErrorMiddleware
+ # would otherwise re-raise it through the TestClient in test mode. The
+ # convention matches `test_exception_handlers.py`.
+ app = FastAPI()
+ app.include_router(api_router, prefix="/v1")
+ register_exception_handlers(app)
+ client = TestClient(app, raise_server_exceptions=False)
+ response = client.post(
+ "/v1/build/runner",
+ json={"files": [{"content": VALID_MTHDS}], "pipe_ref": "smoke.echo"},
+ )
+
+ # The synthetic RuntimeError propagates to the global Exception handler.
+ assert response.status_code == 500
+ # validate_bundle DID open a library and leave it current — capture its id.
+ assert open_spy.spy_return is not None
+ created_library_id, _ = open_spy.spy_return
+ # The fix: teardown runs anyway, with the exact id open_library returned.
+ teardown_spy.assert_called_once_with(library_id=created_library_id)
+
+ def test_build_runner_none_crate_is_a_server_fault_not_a_verdict(self, mocker: MockerFixture):
+ # The "unreachable" None-crate guard is an internal invariant break — a server fault (5xx),
+ # never a caller-facing verdict. Before the fix it raised ValidateBundleError OUTSIDE the
+ # except that maps it to the 200 invalid arm, so it rendered as a request-shape-style 422,
+ # contradicting the route's own contract. The library must still be torn down (no leak).
+ library_manager = get_library_manager()
+ open_spy = mocker.spy(library_manager, "open_library")
+ teardown_spy = mocker.spy(library_manager, "teardown")
+ mocker.patch.object(library_manager, "get_crate", return_value=None)
+
+ app = FastAPI()
+ app.include_router(api_router, prefix="/v1")
+ register_exception_handlers(app)
+ client = TestClient(app, raise_server_exceptions=False)
+ response = client.post(
+ "/v1/build/runner",
+ json={"files": [{"content": VALID_MTHDS}], "pipe_ref": "smoke.echo"},
+ )
+
+ assert response.status_code == 500, response.text
+ assert response.headers["content-type"] == "application/problem+json"
+ assert open_spy.call_count >= 1
+ assert open_spy.call_count == teardown_spy.call_count
+
+ def test_build_runner_succeeds_and_returns_python_code_and_structures(self):
+ # /build/runner rides validate_bundle (loaded-on-success) and the codegen types projection
+ # (D9): a 200 valid arm proves the sweep passed, the library survived for code generation,
+ # and the response carries BOTH the runner script and the stamped structures projection the
+ # script imports from (structures.py + codegen.lock), the retired `success` bool gone.
+ client = _build_client()
+ response = client.post(
+ "/v1/build/runner",
+ json={"files": [{"content": VALID_MTHDS}], "pipe_ref": "smoke.echo"},
+ )
+ assert response.status_code == 200, response.text
+ body = response.json()
+ assert body["is_valid"] is True
+ assert "success" not in body
+ assert body["pipe_ref"] == "smoke.echo"
+ assert body["python_code"]
+ assert "echo" in body["python_code"]
+ structures = body["structures"]
+ assert structures["directory"] == "structures"
+ artifact_paths = [artifact["path"] for artifact in structures["artifacts"]]
+ assert artifact_paths == ["structures.py"]
+ assert structures["artifacts"][0]["content"].startswith("# >>> pipelex-codegen-stamp >>>")
+ assert structures["lock_filename"] == "codegen.lock"
+ assert "crate_fingerprint" in structures["lock"]
+
+ def test_build_runner_keeps_library_open_for_codegen_then_tears_down_once(self, mocker: MockerFixture):
+ # The loaded-on-success contract (D6): the inner sweep must NOT tear the library down — if it
+ # did, get_required_pipe + generate_runner_code would have failed before the response. Teardown
+ # happens exactly once, in the route's finally, after code generation.
+ library_manager = get_library_manager()
+ teardown_spy = mocker.spy(library_manager, "teardown")
+ client = _build_client()
+ response = client.post(
+ "/v1/build/runner",
+ json={"files": [{"content": VALID_MTHDS}], "pipe_ref": "smoke.echo"},
+ )
+ assert response.status_code == 200, response.text
+ teardown_spy.assert_called_once()
+
+ # NOTE: the "opens exactly one library, tears down that same id" property (C-2 / Q-5) is pinned for
+ # all three build routes in `test_build_routes_envelope.py`, which covers both cores they now ride.
+
+ def test_build_runner_rejects_when_requested_pipe_is_skipped(self, mocker: MockerFixture):
+ # C-3: a cross-package unresolved dependency makes validate_pipes record the requested pipe
+ # SKIPPED (not a hard failure), so the sweep returns normally. generate_runner_code reads only
+ # the pipe's own inputs/output, so without a guard the route would emit runner code for a
+ # pipeline that cannot run. The guard must reject the requested-pipe-SKIPPED case with a 422
+ # and never reach code generation. (Other, unrelated SKIPPED pipes stay tolerated.)
+ skipped_result = {
+ "smoke.echo": DryRunOutput(
+ pipe_code="echo",
+ pipe_ref="smoke.echo",
+ status=DryRunStatus.SKIPPED,
+ error_message="Skipped dry run for pipe 'smoke.echo': unresolved dependency: other_pkg.missing",
+ )
+ }
+ # The sweep now runs inside validate_bundle (the route no longer calls it directly), so the
+ # SKIPPED outcome is planted at its source module.
+ mocker.patch(
+ "pipelex.pipeline.validate_bundle.BundleValidator.validate_pipes",
+ new=mocker.AsyncMock(return_value=skipped_result),
+ )
+ generate_spy = mocker.patch("pipelex_api.routes.pipelex.build.runner.generate_runner_code")
+
+ client = _build_client()
+ response = client.post(
+ "/v1/build/runner",
+ json={"files": [{"content": VALID_MTHDS}], "pipe_ref": "smoke.echo"},
+ )
+
+ assert response.status_code == 422, response.text
+ assert response.headers["content-type"] == "application/problem+json"
+ body = response.json()
+ assert body["error_type"] == "ValidationError"
+ assert body["error_domain"] == "input"
+ assert "echo" in body["detail"]
+ # The guard short-circuits before code generation.
+ generate_spy.assert_not_called()
+
+ def test_build_runner_dry_run_failure_is_a_200_invalid_verdict(self, mocker: MockerFixture):
+ # The `/validate` discipline on the build routes: a failed dry-run of a caller-submitted
+ # bundle is a *produced negative verdict*, not a transport failure. validate_bundle's shared
+ # cascade translates the DryRunError to ValidateBundleError, which the route renders as the
+ # 200 invalid arm (is_valid: false + structured validation_errors[]) — the same wire shape
+ # /build/inputs and /build/output return for the identical failure. (Breaking change from
+ # the previous 422 problem+json.)
+ mocker.patch(
+ "pipelex.pipeline.validate_bundle.BundleValidator.validate_pipes",
+ new=mocker.AsyncMock(side_effect=DryRunError("Dry run failed with 1 unexpected pipe failure(s): 'smoke.echo'")),
+ )
+ generate_spy = mocker.patch("pipelex_api.routes.pipelex.build.runner.generate_runner_code")
+
+ client = _build_client()
+ response = client.post(
+ "/v1/build/runner",
+ json={"files": [{"content": VALID_MTHDS}], "pipe_ref": "smoke.echo"},
+ )
+
+ assert response.status_code == 200, response.text
+ body = response.json()
+ assert body["is_valid"] is False
+ assert body["validation_errors"], "an invalid verdict must carry a non-empty validation_errors[]"
+ assert "python_code" not in body
+ # The failure short-circuits before code generation.
+ generate_spy.assert_not_called()
+
+ def test_validate_tears_down_validate_bundle_library_without_leaking(self, mocker: MockerFixture):
+ # validate_bundle opens a library and leaves it loaded + current on success (the D6 contract);
+ # /validate must own that teardown. Before the fix the route never tore it down, orphaning it on
+ # every successful call (the best-effort graph dry-run opens + tears down its OWN library via
+ # PipelexRunner, so that one was balanced). Assert the conservation property: every library opened
+ # during the request is torn down — open count == teardown count. A leak shows up as opens > teardowns.
+ library_manager = get_library_manager()
+ open_spy = mocker.spy(library_manager, "open_library")
+ teardown_spy = mocker.spy(library_manager, "teardown")
+
+ client = _build_client()
+ response = client.post("/v1/validate", json={"mthds_contents": [VALID_MTHDS]})
+
+ assert response.status_code == 200, response.text
+ assert open_spy.call_count >= 1
+ assert open_spy.call_count == teardown_spy.call_count
diff --git a/api/tests/unit/test_build_routes_envelope.py b/api/tests/unit/test_build_routes_envelope.py
new file mode 100644
index 000000000..9a81384fa
--- /dev/null
+++ b/api/tests/unit/test_build_routes_envelope.py
@@ -0,0 +1,427 @@
+"""Envelope tests for the migrated `/v1/build/*` projections.
+
+Pins the Phase-2/3 migration: the three build routes ride the shared `files[]` XOR `method_ref`
+closure selector (`MthdsFilesRequest`) plus an optional qualified `pipe_ref` that defaults with the
+run routes' precedence — the fetched package manifest's `main_pipe` on a `method_ref` request, else
+the closure's declared `main_pipe`; `/build/{inputs,output}` resolve their crate **statically** (no
+dry-run sweep, so no `allow_signatures`), while `/build/runner` keeps both. Verdicts stay on the
+`/validate` discipline — 200 discriminated on `is_valid`, non-2xx only for no-verdict conditions.
+"""
+
+from collections.abc import Callable
+from pathlib import Path
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+from pipelex.interpreter_hub import get_library_manager
+from pytest_mock import MockerFixture
+
+from pipelex_api.exception_handlers import register_exception_handlers
+from pipelex_api.routes import router as api_router
+from tests.unit._constants import (
+ COLLIDING_ECHO_LIST_MTHDS,
+ INVALID_MAIN_PIPE_MTHDS,
+ NO_INPUTS_MTHDS,
+ NO_MAIN_PIPE_MTHDS,
+ SECOND_MAIN_PIPE_MTHDS,
+ SIGNATURE_MTHDS,
+ STUB_METHOD_ADDRESS,
+ STUB_METHOD_MANIFEST_MAIN_PIPE_SHOUT,
+ STUB_METHOD_MANIFEST_NO_MAIN_PIPE,
+ VALID_MTHDS,
+)
+
+BUILD_PATHS = ["/v1/build/inputs", "/v1/build/output", "/v1/build/runner"]
+
+# The address-form reference the stubbed clone (`install_method_package`) answers to.
+STUB_METHOD_REF = f"{STUB_METHOD_ADDRESS}@v0.1.0"
+
+
+def _build_client() -> TestClient:
+ app = FastAPI()
+ app.include_router(api_router, prefix="/v1")
+ register_exception_handlers(app)
+ return TestClient(app)
+
+
+class TestBuildRoutesEnvelope:
+ @pytest.mark.parametrize("path", BUILD_PATHS)
+ def test_pipe_ref_defaults_to_the_closures_main_pipe(self, path: str):
+ # D1: the selector is optional. Omitted, it resolves to the closure's declared main_pipe, and
+ # the valid arm echoes BOTH the resolved ref and (absent) the requested one, so a caller can
+ # see what it was defaulted to.
+ client = _build_client()
+ response = client.post(path, json={"files": [{"content": VALID_MTHDS}]})
+ assert response.status_code == 200, response.text
+ body = response.json()
+ assert body["is_valid"] is True
+ assert body["pipe_ref"] == "smoke.echo"
+ assert "requested_pipe_ref" not in body, "an omitted selector must not be echoed back as if it were requested"
+
+ @pytest.mark.parametrize("path", BUILD_PATHS)
+ def test_explicit_qualified_pipe_ref_is_echoed_as_requested_and_resolved(self, path: str):
+ client = _build_client()
+ response = client.post(path, json={"files": [{"content": VALID_MTHDS}], "pipe_ref": "smoke.echo"})
+ assert response.status_code == 200, response.text
+ body = response.json()
+ assert body["pipe_ref"] == "smoke.echo"
+ assert body["requested_pipe_ref"] == "smoke.echo"
+
+ @pytest.mark.parametrize("path", BUILD_PATHS)
+ def test_unknown_pipe_ref_is_a_422_not_an_invalid_verdict(self, path: str):
+ # Nothing about the *closure* is wrong — the caller named a pipe that isn't in it. That is a
+ # no-verdict condition (422), never a 200 `is_valid: false`.
+ # It carries the entry-lookup `error_type` the run routes answer for an unknown `pipe_code`, never
+ # a request-shape `ValidationError` — `/build/runner` included, whose sliced sweep reaches it first.
+ client = _build_client()
+ response = client.post(path, json={"files": [{"content": VALID_MTHDS}], "pipe_ref": "smoke.does_not_exist"})
+ assert response.status_code == 422, response.text
+ assert response.headers["content-type"] == "application/problem+json"
+ problem = response.json()
+ assert problem["error_type"] == "EntryPipeNotFoundError"
+ assert problem["error_domain"] == "input"
+ assert "not found" in problem["detail"]
+
+ @pytest.mark.parametrize("path", BUILD_PATHS)
+ def test_an_ambiguous_pipe_ref_is_a_422_that_says_ambiguous_not_missing(self, path: str):
+ # `echo` is declared by both `smoke` and `twin`, so the engine's entry lookup refuses to pick one.
+ # The 422 must say so and name the candidates — calling the pipe "not found" beside a list of
+ # the pipes it matched would contradict itself.
+ client = _build_client()
+ payload = {"files": [{"content": VALID_MTHDS}, {"content": COLLIDING_ECHO_LIST_MTHDS}], "pipe_ref": "echo"}
+ response = client.post(path, json=payload)
+ assert response.status_code == 422, response.text
+ assert response.headers["content-type"] == "application/problem+json"
+ assert response.json()["error_type"] == "EntryPipeAmbiguousError"
+ detail = response.json()["detail"]
+ assert "several domains" in detail
+ assert "smoke.echo" in detail
+ assert "twin.echo" in detail
+ assert "not found" not in detail, detail
+
+ @pytest.mark.parametrize("path", BUILD_PATHS)
+ def test_omitted_pipe_ref_on_a_closure_with_no_main_pipe_is_422(self, path: str):
+ # First of the two arms `inputs_cmd.py::_default_main_pipe_ref` rejects: nothing to default to.
+ client = _build_client()
+ response = client.post(path, json={"files": [{"content": NO_MAIN_PIPE_MTHDS}]})
+ assert response.status_code == 422, response.text
+ assert response.headers["content-type"] == "application/problem+json"
+ assert response.json()["error_type"] == "EntryPipeNotFoundError"
+ assert "main_pipe" in response.json()["detail"]
+
+ @pytest.mark.parametrize("path", BUILD_PATHS)
+ def test_omitted_pipe_ref_on_an_ambiguous_closure_is_422(self, path: str):
+ # The second arm — the one the plan's D1 originally missed: two domains, two main_pipes, so the
+ # default is ambiguous. Naming the pipe explicitly resolves it (asserted below).
+ client = _build_client()
+ payload = {"files": [{"content": VALID_MTHDS}, {"content": SECOND_MAIN_PIPE_MTHDS}]}
+ response = client.post(path, json=payload)
+ assert response.status_code == 422, response.text
+ assert response.json()["error_type"] == "EntryPipeAmbiguousError"
+ assert "several" in response.json()["detail"]
+
+ named = client.post(path, json={**payload, "pipe_ref": "other.shout"})
+ assert named.status_code == 200, named.text
+ assert named.json()["pipe_ref"] == "other.shout"
+
+ @pytest.mark.parametrize("path", BUILD_PATHS)
+ def test_invalid_closure_is_a_200_invalid_verdict(self, path: str):
+ client = _build_client()
+ response = client.post(path, json={"files": [{"content": INVALID_MAIN_PIPE_MTHDS}]})
+ assert response.status_code == 200, response.text
+ body = response.json()
+ assert body["is_valid"] is False
+ assert body["validation_errors"], "an invalid verdict must carry a non-empty validation_errors[]"
+
+ @pytest.mark.parametrize("path", BUILD_PATHS)
+ def test_method_ref_is_501_until_the_registry_exists(self, path: str):
+ # The build routes inherit the closure selector whole — including the arm this server does not
+ # serve yet. `/build/runner` reaches it through `selected_files` despite not using the crate core.
+ client = _build_client()
+ response = client.post(path, json={"method_ref": "acme/methods/x"})
+ assert response.status_code == 501, response.text
+ assert response.headers["content-type"] == "application/problem+json"
+ assert response.json()["error_type"] == "MethodRefNotSupported"
+
+ @pytest.mark.parametrize("path", BUILD_PATHS)
+ def test_method_ref_omitted_pipe_ref_defaults_to_the_manifest_main_pipe(self, path: str, install_method_package: Callable[..., Path]):
+ # The fetched package's closure declares NO main_pipe — on its own it cannot default the
+ # selector (the 422 pinned above for inline files). But the package manifest declares one
+ # (`STUB_METHOD_MANIFEST`: `main_pipe = "echo"`), and that is the package author's entry pipe:
+ # the run routes already honor it, so an omitted `pipe_ref` here resolves to it too, and is
+ # echoed qualified — a manifest `main_pipe` is a bare code riding the cross-domain fallback.
+ install_method_package(files={"documents.mthds": NO_MAIN_PIPE_MTHDS})
+ client = _build_client()
+ response = client.post(path, json={"method_ref": STUB_METHOD_REF})
+ assert response.status_code == 200, response.text
+ body = response.json()
+ assert body["is_valid"] is True
+ assert body["pipe_ref"] == "nomain.echo"
+ assert "requested_pipe_ref" not in body, "a manifest-defaulted selector must not be echoed back as if it were requested"
+
+ @pytest.mark.parametrize("path", BUILD_PATHS)
+ def test_manifest_main_pipe_outranks_the_closures_own_declarations(self, path: str, install_method_package: Callable[..., Path]):
+ # Two domains, two declared main_pipes: by the closure's own declarations the default is
+ # ambiguous (the 422 pinned above for inline files). The manifest names `shout`, and it sits
+ # above the closure in the chain — `pipe_ref or manifest main_pipe or closure main_pipe`, the
+ # run routes' `pipe_code or fetched.main_pipe` — so it both settles the ambiguity and wins
+ # over `smoke`'s own `echo`.
+ install_method_package(
+ files={"smoke.mthds": VALID_MTHDS, "other.mthds": SECOND_MAIN_PIPE_MTHDS},
+ manifest_toml=STUB_METHOD_MANIFEST_MAIN_PIPE_SHOUT,
+ )
+ client = _build_client()
+ response = client.post(path, json={"method_ref": STUB_METHOD_REF})
+ assert response.status_code == 200, response.text
+ body = response.json()
+ assert body["pipe_ref"] == "other.shout"
+ assert "requested_pipe_ref" not in body
+
+ @pytest.mark.parametrize("path", BUILD_PATHS)
+ def test_explicit_pipe_ref_outranks_the_manifest_main_pipe(self, path: str, install_method_package: Callable[..., Path]):
+ # The request's own selector stays first in the chain: the manifest says `echo`, the caller
+ # says `other.shout`, and the caller wins — echoed as requested and resolved.
+ install_method_package(files={"smoke.mthds": VALID_MTHDS, "other.mthds": SECOND_MAIN_PIPE_MTHDS})
+ client = _build_client()
+ response = client.post(path, json={"method_ref": STUB_METHOD_REF, "pipe_ref": "other.shout"})
+ assert response.status_code == 200, response.text
+ body = response.json()
+ assert body["pipe_ref"] == "other.shout"
+ assert body["requested_pipe_ref"] == "other.shout"
+
+ @pytest.mark.parametrize("path", BUILD_PATHS)
+ def test_a_manifest_without_main_pipe_falls_back_to_the_closures_declaration(self, path: str, install_method_package: Callable[..., Path]):
+ # A manifest may declare no `main_pipe`. Then the chain falls through to the closure's own
+ # declaration — the same default inline `files[]` get — rather than refusing.
+ install_method_package(files={"documents.mthds": VALID_MTHDS}, manifest_toml=STUB_METHOD_MANIFEST_NO_MAIN_PIPE)
+ client = _build_client()
+ response = client.post(path, json={"method_ref": STUB_METHOD_REF})
+ assert response.status_code == 200, response.text
+ body = response.json()
+ assert body["pipe_ref"] == "smoke.echo"
+ assert "requested_pipe_ref" not in body
+
+ @pytest.mark.parametrize("path", BUILD_PATHS)
+ def test_method_ref_with_nothing_to_default_from_is_still_422(self, path: str, install_method_package: Callable[..., Path]):
+ # The whole chain empty: no `pipe_ref`, a manifest with no `main_pipe`, a closure declaring
+ # none. The closure-declaration arm's 422 is unchanged — the manifest only ever ADDS a default.
+ install_method_package(files={"documents.mthds": NO_MAIN_PIPE_MTHDS}, manifest_toml=STUB_METHOD_MANIFEST_NO_MAIN_PIPE)
+ client = _build_client()
+ response = client.post(path, json={"method_ref": STUB_METHOD_REF})
+ assert response.status_code == 422, response.text
+ assert response.headers["content-type"] == "application/problem+json"
+ assert "main_pipe" in response.json()["detail"]
+
+ @pytest.mark.parametrize("path", BUILD_PATHS)
+ def test_a_manifest_main_pipe_absent_from_the_closure_is_a_422_naming_its_origin(self, path: str, install_method_package: Callable[..., Path]):
+ # The manifest names `echo` but the package's closure only contains `other.shout`. Nothing
+ # about the closure is wrong, so it is the same request-shape 422 as an unknown explicit ref —
+ # but the caller never spelled `echo`, so the detail must say where it came from.
+ install_method_package(files={"other.mthds": SECOND_MAIN_PIPE_MTHDS})
+ client = _build_client()
+ response = client.post(path, json={"method_ref": STUB_METHOD_REF})
+ assert response.status_code == 422, response.text
+ assert response.headers["content-type"] == "application/problem+json"
+ assert response.json()["error_type"] == "EntryPipeNotFoundError"
+ detail = response.json()["detail"]
+ assert "'echo'" in detail
+ assert "manifest" in detail, f"the 422 must say the selector came from the manifest: {detail}"
+ assert "not found" in detail
+
+ @pytest.mark.parametrize("path", BUILD_PATHS)
+ def test_an_ambiguous_manifest_main_pipe_is_a_422_that_says_ambiguous_not_missing(self, path: str, install_method_package: Callable[..., Path]):
+ # The manifest names `echo`, which both `smoke` and `twin` declare. The caller never spelled it,
+ # so the detail names the manifest as its origin, and it says the code is ambiguous, not missing.
+ install_method_package(files={"smoke.mthds": VALID_MTHDS, "twin.mthds": COLLIDING_ECHO_LIST_MTHDS})
+ client = _build_client()
+ response = client.post(path, json={"method_ref": STUB_METHOD_REF})
+ assert response.status_code == 422, response.text
+ assert response.headers["content-type"] == "application/problem+json"
+ assert response.json()["error_type"] == "EntryPipeAmbiguousError"
+ detail = response.json()["detail"]
+ assert "manifest" in detail
+ assert "several domains" in detail
+ assert "smoke.echo" in detail
+ assert "twin.echo" in detail
+ assert "not found" not in detail, detail
+
+ @pytest.mark.parametrize("path", BUILD_PATHS)
+ def test_source_labels_ride_through_to_diagnostics(self, path: str):
+ # The point of the envelope migration for the build routes: a per-file `source` label reaches the
+ # engine, so an invalid closure's diagnostics can name the owning file. (Before Phase 2 the build
+ # routes took bare strings and could not carry one — `/build/runner` needed the widened
+ # `validate_bundle(mthds_sources=...)` to get here.)
+ client = _build_client()
+ response = client.post(path, json={"files": [{"content": INVALID_MAIN_PIPE_MTHDS, "source": "bundles/broken.mthds"}]})
+ assert response.status_code == 200, response.text
+ body = response.json()
+ assert body["is_valid"] is False
+ sources = [error.get("source") for error in body["validation_errors"]]
+ assert "bundles/broken.mthds" in sources, f"no diagnostic carried the submitted source: {body['validation_errors']}"
+
+ @pytest.mark.parametrize("path", ["/v1/build/inputs", "/v1/build/output"])
+ def test_static_routes_ignore_allow_signatures(self, path: str):
+ # `allow_signatures` only ever parameterized the dry-run sweep. The static projections dropped
+ # the sweep, so the flag is gone from their request models — and since the envelope does not
+ # forbid extras, a client still sending it is simply ignored rather than rejected.
+ client = _build_client()
+ response = client.post(path, json={"files": [{"content": VALID_MTHDS}], "allow_signatures": True})
+ assert response.status_code == 200, response.text
+ assert "allow_signatures" not in response.json()
+
+ @pytest.mark.parametrize("path", ["/v1/build/inputs", "/v1/build/output"])
+ @pytest.mark.parametrize("pipe_ref", ["sig_api.caller_seq", "sig_api.summary_sig"], ids=["caller", "the-signature-itself"])
+ def test_static_routes_accept_a_signature_bundle_unconditionally(self, path: str, pipe_ref: str):
+ # The corollary of dropping the sweep: an unimplemented `PipeSignature` is a *runnability*
+ # fact, and these routes no longer speak runnability. So a signature bundle projects fine with
+ # no flag to set — where `/validate` and `/build/runner` still surface it (see
+ # test_allow_signatures.py, whose docstring points here for exactly this assertion).
+ # Both the caller *and* the signature pipe itself: a signature declares inputs/output, so it is
+ # statically projectable precisely because these routes read only the declaration.
+ client = _build_client()
+ response = client.post(path, json={"files": [{"content": SIGNATURE_MTHDS}], "pipe_ref": pipe_ref})
+ assert response.status_code == 200, response.text
+ assert response.json()["is_valid"] is True
+
+ @pytest.mark.parametrize("path", BUILD_PATHS)
+ def test_a_bare_pipe_code_still_resolves_but_is_echoed_qualified(self, path: str):
+ # The engine's pipe lookup accepts a bare code, falling back across domains. A caller who leans
+ # on that must still be told the QUALIFIED ref — the valid arms promise one, so echoing the
+ # request's own bare spelling back would quietly break that promise. The resolved ref is read
+ # off the live pipe, never off the request.
+ client = _build_client()
+ response = client.post(path, json={"files": [{"content": VALID_MTHDS}], "pipe_ref": "echo"})
+ assert response.status_code == 200, response.text
+ body = response.json()
+ assert body["pipe_ref"] == "smoke.echo", "the resolved ref must be qualified, not the bare code the caller sent"
+ assert body["requested_pipe_ref"] == "echo", "the echo of the request must stay verbatim"
+
+ @pytest.mark.parametrize("path", BUILD_PATHS)
+ def test_empty_files_rejected(self, path: str):
+ client = _build_client()
+ response = client.post(path, json={"files": []})
+ assert response.status_code == 422
+ assert response.headers["content-type"] == "application/problem+json"
+ assert response.json()["error_type"] == "ValidationError"
+
+ @pytest.mark.parametrize("path", BUILD_PATHS)
+ def test_routes_open_exactly_one_library_and_tear_it_down(self, path: str, mocker: MockerFixture):
+ # The loaded-on-success contract: whichever core a route rides (the static
+ # `resolve_requested_crate` for inputs/output, `validate_bundle` for runner), it opens exactly
+ # ONE library, leaves it loaded + current, and the route owns its teardown. A second open would
+ # orphan the first; a missing teardown would leak it.
+ library_manager = get_library_manager()
+ open_spy = mocker.spy(library_manager, "open_library")
+ teardown_spy = mocker.spy(library_manager, "teardown")
+
+ client = _build_client()
+ response = client.post(path, json={"files": [{"content": VALID_MTHDS}], "pipe_ref": "smoke.echo"})
+
+ assert response.status_code == 200, response.text
+ assert open_spy.call_count == 1
+ created_library_id, _ = open_spy.spy_return
+ teardown_spy.assert_called_once_with(library_id=created_library_id)
+
+ def test_inputs_json_returns_the_parsed_light_template(self):
+ client = _build_client()
+ response = client.post("/v1/build/inputs", json={"files": [{"content": VALID_MTHDS}]})
+ assert response.status_code == 200, response.text
+ body = response.json()
+ assert body["format"] == "json"
+ assert body["explicit"] is False
+ # The light shape: a Text-refining input is a bare string, not a {concept, content} envelope.
+ assert isinstance(body["inputs"]["text"], str)
+ assert "inputs_toml" not in body, "the format the caller did not ask for must be absent"
+
+ def test_inputs_explicit_returns_the_ceremonial_envelope(self):
+ client = _build_client()
+ response = client.post("/v1/build/inputs", json={"files": [{"content": VALID_MTHDS}], "explicit": True})
+ assert response.status_code == 200, response.text
+ body = response.json()
+ assert body["explicit"] is True
+ assert set(body["inputs"]["text"]) == {"concept", "content"}
+
+ @pytest.mark.parametrize("explicit", [False, True], ids=["light", "explicit"])
+ def test_inputs_toml_returns_raw_text_not_a_parsed_dict(self, explicit: bool):
+ # D3's response-shape consequence: TOML cannot ride as a parsed dict (it would lose the concept
+ # comments and key order that are the reason to ask for TOML), so it rides its own string field.
+ client = _build_client()
+ response = client.post("/v1/build/inputs", json={"files": [{"content": VALID_MTHDS}], "format": "toml", "explicit": explicit})
+ assert response.status_code == 200, response.text
+ body = response.json()
+ assert body["format"] == "toml"
+ assert isinstance(body["inputs_toml"], str)
+ assert "text" in body["inputs_toml"]
+ assert "inputs" not in body, "the JSON field must be absent on a TOML request"
+
+ @pytest.mark.parametrize("template_format", ["json", "toml"])
+ def test_a_pipe_with_no_inputs_is_a_valid_verdict_with_an_empty_template(self, template_format: str):
+ # NoInputsRequiredError out of the engine renderers is not a failure — it is the honest answer
+ # "run this with nothing". The CLI exits 0 on it; the route answers a valid arm.
+ client = _build_client()
+ response = client.post("/v1/build/inputs", json={"files": [{"content": NO_INPUTS_MTHDS}], "format": template_format})
+ assert response.status_code == 200, response.text
+ body = response.json()
+ assert body["is_valid"] is True
+ assert "no inputs" in body["message"]
+ empty = body["inputs"] if template_format == "json" else body["inputs_toml"]
+ assert not empty
+
+ @pytest.mark.parametrize(
+ ("output_format", "expected_field"),
+ [("schema", "output"), ("json", "output"), ("python", "output_python")],
+ )
+ def test_output_formats_land_on_the_field_the_format_implies(self, output_format: str, expected_field: str):
+ # Regression: `format=python` used to be a hard 500 — the route fed Python source to json.loads
+ # and typed the field `dict`. The structured formats stay objects; python is source text.
+ client = _build_client()
+ response = client.post("/v1/build/output", json={"files": [{"content": VALID_MTHDS}], "format": output_format})
+ assert response.status_code == 200, response.text
+ body = response.json()
+ assert body["format"] == output_format
+ assert expected_field in body
+ if expected_field == "output":
+ assert isinstance(body["output"], dict)
+ assert "output_python" not in body
+ else:
+ assert isinstance(body["output_python"], str)
+ assert "output" not in body
+
+ @pytest.mark.parametrize(
+ ("pipe_ref", "expects_list"),
+ [("smoke.echo", False), ("twin.echo", True)],
+ ids=["scalar-output", "list-output"],
+ )
+ def test_runner_reads_output_multiplicity_from_the_right_domain(self, pipe_ref: str, expects_list: bool):
+ # Two domains declare a pipe with the same BARE code `echo`, with OPPOSITE output multiplicity.
+ # The runner reads the requested pipe's multiplicity out of the blueprints, whose `pipe` maps are
+ # keyed by bare code — so a bare-code scan returns whichever blueprint came first and can emit a
+ # runner with the wrong output handling. The lookup must compare the owning domain too.
+ client = _build_client()
+ response = client.post(
+ "/v1/build/runner",
+ json={"files": [{"content": VALID_MTHDS}, {"content": COLLIDING_ECHO_LIST_MTHDS}], "pipe_ref": pipe_ref},
+ )
+ assert response.status_code == 200, response.text
+ body = response.json()
+ assert body["pipe_ref"] == pipe_ref
+ # The multiplicity decides the script's result cast: `main_stuff_as_items(item_type=...)` for a
+ # list output vs `main_stuff_as(content_type=...)` for a scalar one.
+ python_code = body["python_code"]
+ assert ("main_stuff_as_items(" in python_code) is expects_list, f"wrong output multiplicity for {pipe_ref}:\n{python_code}"
+
+ def test_runner_still_sweeps_and_still_takes_allow_signatures(self, mocker: MockerFixture):
+ # `/build/runner` is the one projection that keeps the dry-run (a runner script is a promise the
+ # pipe runs), so it alone still accepts the flag that parameterizes that sweep.
+ spy = mocker.spy(get_library_manager(), "open_library")
+ client = _build_client()
+ response = client.post(
+ "/v1/build/runner",
+ json={"files": [{"content": VALID_MTHDS}], "pipe_ref": "smoke.echo", "allow_signatures": True},
+ )
+ assert response.status_code == 200, response.text
+ body = response.json()
+ assert body["python_code"]
+ assert body["structures"]["artifacts"]
+ assert spy.call_count == 1
diff --git a/api/tests/unit/test_bundle_materialize.py b/api/tests/unit/test_bundle_materialize.py
new file mode 100644
index 000000000..6dcffb843
--- /dev/null
+++ b/api/tests/unit/test_bundle_materialize.py
@@ -0,0 +1,182 @@
+"""Unit tests for `pipelex_api.bundle` — method-bundle materialization and its ingest guards.
+
+Covers both transport forms (`bundle_b64` zip and the `files` map), their
+equivalence, and every guard: both-forms/empty rejection, path traversal
+(absolute / `..` / backslash), the file-count and total-size ceilings, the
+zip-bomb bounded-decompression guard, corrupt-zip and invalid-base64 handling,
+and the guaranteed temp-dir cleanup on context exit.
+"""
+
+import base64
+import io
+import zipfile
+from pathlib import Path
+
+import pytest
+from pytest_mock import MockerFixture
+
+from pipelex_api.bundle import materialized_bundle, parse_bundle
+from pipelex_api.errors import ApiError
+
+_MAIN_MTHDS = """\
+domain = "b"
+main_pipe = "echo"
+
+[pipe.echo]
+type = "PipeFunc"
+description = "e"
+inputs = { text = "Text" }
+output = "Text"
+function_name = "echo"
+"""
+_PIPE_FUNC_PY = "def echo(working_memory):\n return 'hi'\n"
+
+
+def _zip_b64(files: dict[str, str]) -> str:
+ buffer = io.BytesIO()
+ with zipfile.ZipFile(buffer, "w", zipfile.ZIP_DEFLATED) as archive:
+ for name, content in files.items():
+ archive.writestr(name, content)
+ return base64.b64encode(buffer.getvalue()).decode("ascii")
+
+
+class TestBundleMaterialize:
+ def test_files_map_materializes_to_disk(self):
+ files = {"main.mthds": _MAIN_MTHDS, "pipe_func.py": _PIPE_FUNC_PY}
+ with materialized_bundle(bundle_b64=None, files=files) as bundle:
+ assert bundle.directory.is_dir()
+ assert bundle.has_python_sources is True
+ assert set(bundle.relpaths) == {"main.mthds", "pipe_func.py"}
+ assert (bundle.directory / "main.mthds").read_text() == _MAIN_MTHDS
+ assert (bundle.directory / "pipe_func.py").read_text() == _PIPE_FUNC_PY
+
+ def test_zip_equivalent_to_files_map(self):
+ files = {"main.mthds": _MAIN_MTHDS, "structures/models.py": "class Foo: ...\n"}
+ with materialized_bundle(bundle_b64=None, files=files) as from_files:
+ files_listing = {relpath: (from_files.directory / relpath).read_text() for relpath in from_files.relpaths}
+ with materialized_bundle(bundle_b64=_zip_b64(files), files=None) as from_zip:
+ zip_listing = {relpath: (from_zip.directory / relpath).read_text() for relpath in from_zip.relpaths}
+ assert files_listing == zip_listing == files
+
+ def test_nested_subdir_materializes(self):
+ files = {"main.mthds": _MAIN_MTHDS, "structures/models.py": "class Foo: ...\n"}
+ with materialized_bundle(bundle_b64=None, files=files) as bundle:
+ nested = bundle.directory / "structures" / "models.py"
+ assert nested.is_file()
+ assert "structures/models.py" in bundle.relpaths
+
+ def test_no_python_sources_flag_when_only_mthds(self):
+ with materialized_bundle(bundle_b64=None, files={"main.mthds": _MAIN_MTHDS}) as bundle:
+ assert bundle.has_python_sources is False
+
+ def test_directory_cleaned_up_on_exit(self):
+ with materialized_bundle(bundle_b64=None, files={"main.mthds": _MAIN_MTHDS}) as bundle:
+ directory = bundle.directory
+ assert directory.exists()
+ assert not directory.exists()
+
+ def test_directory_cleaned_up_on_error(self):
+ captured: dict[str, object] = {}
+
+ class _Boom(RuntimeError):
+ pass
+
+ def _run() -> None:
+ with materialized_bundle(bundle_b64=None, files={"main.mthds": _MAIN_MTHDS}) as bundle:
+ captured["dir"] = bundle.directory
+ raise _Boom
+
+ with pytest.raises(_Boom):
+ _run()
+ directory = captured["dir"]
+ assert isinstance(directory, Path)
+ assert not directory.exists()
+
+ def test_both_forms_rejected(self):
+ with (
+ pytest.raises(ApiError) as exc,
+ materialized_bundle(bundle_b64=_zip_b64({"main.mthds": _MAIN_MTHDS}), files={"main.mthds": _MAIN_MTHDS}),
+ ):
+ pass
+ assert exc.value.status_code == 422
+ assert exc.value.document["error_type"] == "InvalidBundle"
+
+ def test_neither_form_rejected(self):
+ with pytest.raises(ApiError) as exc, materialized_bundle(bundle_b64=None, files=None):
+ pass
+ assert exc.value.status_code == 422
+ assert exc.value.document["error_type"] == "InvalidBundle"
+
+ def test_empty_files_rejected(self):
+ with pytest.raises(ApiError) as exc, materialized_bundle(bundle_b64=None, files={}):
+ pass
+ assert exc.value.status_code == 422
+ assert exc.value.document["error_type"] == "InvalidBundle"
+
+ @pytest.mark.parametrize("bad_name", ["/etc/passwd", "../evil.py", "sub/../../evil.py", "a\\b.py", "C:passwd"])
+ def test_unsafe_entry_names_rejected(self, bad_name: str):
+ with pytest.raises(ApiError) as exc, materialized_bundle(bundle_b64=None, files={bad_name: "x"}):
+ pass
+ assert exc.value.status_code == 422
+ assert exc.value.document["error_type"] == "InvalidBundle"
+
+ def test_unsafe_entry_names_rejected_in_zip(self):
+ with pytest.raises(ApiError) as exc, materialized_bundle(bundle_b64=_zip_b64({"../evil.py": "x"}), files=None):
+ pass
+ assert exc.value.status_code == 422
+ assert exc.value.document["error_type"] == "InvalidBundle"
+
+ def test_file_count_ceiling(self, mocker: MockerFixture):
+ mocker.patch("pipelex_api.bundle.MAX_BUNDLE_FILES", 2)
+ files = {f"file_{index}.py": "x" for index in range(3)}
+ with pytest.raises(ApiError) as exc, materialized_bundle(bundle_b64=None, files=files):
+ pass
+ assert exc.value.status_code == 413
+ assert exc.value.document["error_type"] == "PayloadTooLarge"
+
+ def test_total_size_ceiling_files(self, mocker: MockerFixture):
+ mocker.patch("pipelex_api.bundle.MAX_BUNDLE_TOTAL_BYTES", 64)
+ with pytest.raises(ApiError) as exc, materialized_bundle(bundle_b64=None, files={"big.py": "x" * 128}):
+ pass
+ assert exc.value.status_code == 413
+ assert exc.value.document["error_type"] == "PayloadTooLarge"
+
+ def test_zip_bomb_bounded_by_total_size(self, mocker: MockerFixture):
+ # A highly compressible entry that decompresses well past the (patched) ceiling must be
+ # refused by the bounded read, not silently expanded into memory.
+ mocker.patch("pipelex_api.bundle.MAX_BUNDLE_TOTAL_BYTES", 1024)
+ bomb = _zip_b64({"bomb.txt": "A" * (1024 * 64)})
+ with pytest.raises(ApiError) as exc, materialized_bundle(bundle_b64=bomb, files=None):
+ pass
+ assert exc.value.status_code == 413
+ assert exc.value.document["error_type"] == "PayloadTooLarge"
+
+ def test_corrupt_zip_rejected(self):
+ not_a_zip = base64.b64encode(b"this is definitely not a zip archive").decode("ascii")
+ with pytest.raises(ApiError) as exc, materialized_bundle(bundle_b64=not_a_zip, files=None):
+ pass
+ assert exc.value.status_code == 422
+ assert exc.value.document["error_type"] == "InvalidBundle"
+
+ def test_invalid_base64_rejected(self):
+ with pytest.raises(ApiError) as exc, materialized_bundle(bundle_b64="!!! not base64 !!!", files=None):
+ pass
+ assert exc.value.status_code == 400
+ assert exc.value.document["error_type"] == "InvalidBase64"
+
+ def test_parse_reports_python_sources_without_writing(self):
+ # parse_bundle decodes + guards in memory only; nothing is written to disk yet.
+ with_py = parse_bundle(bundle_b64=None, files={"main.mthds": _MAIN_MTHDS, "pipe_func.py": _PIPE_FUNC_PY})
+ assert with_py.has_python_sources is True
+ without_py = parse_bundle(bundle_b64=None, files={"main.mthds": _MAIN_MTHDS})
+ assert without_py.has_python_sources is False
+
+ def test_oversized_base64_rejected_before_decode(self, mocker: MockerFixture):
+ # The cheap length check on the still-encoded string fires before any b64decode.
+ mocker.patch("pipelex_api.bundle._MAX_BUNDLE_B64_CHARS", 16)
+ decode_spy = mocker.spy(base64, "b64decode")
+ with pytest.raises(ApiError) as exc, materialized_bundle(bundle_b64="A" * 64, files=None):
+ pass
+ assert exc.value.status_code == 413
+ assert exc.value.document["error_type"] == "PayloadTooLarge"
+ decode_spy.assert_not_called()
diff --git a/api/tests/unit/test_bundle_structures_refusal.py b/api/tests/unit/test_bundle_structures_refusal.py
new file mode 100644
index 000000000..18dd7dfc6
--- /dev/null
+++ b/api/tests/unit/test_bundle_structures_refusal.py
@@ -0,0 +1,144 @@
+"""A sandbox-hosted deployment refuses a bundle whose Python declares a structure class, and never imports it.
+
+The run routes load the bundle for real here: only the orchestrator is a recording stub, so the refusal
+is the runtime's own, raised while the bundle loads. A module-level sentinel in the structure file proves
+the file was never imported, which is the point of the refusal: hosted execution imports no caller Python
+into the runner's process. A PipeFunc-only bundle passes the same load and reaches the orchestrator.
+"""
+
+from collections.abc import Generator
+from pathlib import Path
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+from pipelex.base_exceptions import DisclosureMode
+from pipelex.config import get_config
+from pipelex.pipe_run.delivery_assignment import DeliveryAssignment
+from pipelex.pipe_run.pipe_job import PipeJob
+from pipelex.plugins.orchestrator_registry import OrchestratorRegistry
+from pipelex.runtime_bridge.payloads import PipelexPipeDispatchAck, PipelexPipeRunOutput
+from pytest_mock import MockerFixture
+
+from pipelex_api.api_config import ApiConfig
+from pipelex_api.exception_handlers import register_exception_handlers
+from pipelex_api.routes import router as api_router
+from tests.unit._constants import VALID_MTHDS
+
+_PIPELINE_NS = "pipelex_api.routes.pipelex.pipeline"
+
+_PIPE_FUNC_MTHDS = """\
+domain = "crunch_demo"
+main_pipe = "crunch"
+
+[pipe.crunch]
+type = "PipeFunc"
+description = "Crunch numbers in caller code"
+inputs = { data = "Text" }
+output = "Text"
+function_name = "crunch"
+"""
+
+_PIPE_FUNC_PY = """\
+from pipelex.core.memory.working_memory import WorkingMemory
+from pipelex.core.stuffs.text_content import TextContent
+from pipelex.system.registries.func_registry import pipe_func
+
+
+@pipe_func(name="crunch")
+async def crunch(working_memory: WorkingMemory) -> TextContent:
+ return TextContent(text="crunched")
+"""
+
+
+def _structures_py(*, sentinel: Path) -> str:
+ """A structure class whose module, if it were ever imported, would write the sentinel file."""
+ return f"""\
+from pathlib import Path
+
+from pipelex.core.stuffs.structured_content import StructuredContent
+
+Path({str(sentinel)!r}).write_text("imported", encoding="utf-8")
+
+
+class Invoice(StructuredContent):
+ total: float
+"""
+
+
+class _RecordingOrchestrator:
+ """Records every dispatch; `start` acknowledges it, `execute` is never expected to be reached."""
+
+ supports_fire_and_forget = True
+
+ def __init__(self) -> None:
+ self.dispatches: list[str] = []
+
+ async def execute(self, *, pipe_job: PipeJob, delivery_assignment: DeliveryAssignment | None) -> PipelexPipeRunOutput: # noqa: ARG002
+ self.dispatches.append(pipe_job.pipe.code)
+ msg = "These tests dispatch through /start only."
+ raise AssertionError(msg)
+
+ async def start(self, *, pipe_job: PipeJob, delivery_assignment: DeliveryAssignment | None) -> PipelexPipeDispatchAck: # noqa: ARG002
+ self.dispatches.append(pipe_job.pipe.code)
+ return PipelexPipeDispatchAck(pipeline_run_id="run-1", workflow_id="wf-1")
+
+
[email protected](name="sandbox_hosted_mode")
+def sandbox_hosted_mode_fixture() -> Generator[None, None, None]:
+ """Select a non-`direct` PipeFunc execution mode, which is what makes a deployment sandbox-hosted.
+
+ Flipping the config rather than patching a helper makes the route's gate and pipelex's loader read
+ the same answer. The token is neutral: no sandbox plugin is installed, and nothing here runs a PipeFunc.
+ """
+ pipe_func_config = get_config().interpreter.pipe_func
+ previous = pipe_func_config.execution_mode
+ pipe_func_config.execution_mode = "sandbox"
+ try:
+ yield
+ finally:
+ pipe_func_config.execution_mode = previous
+
+
+def _build_client(mocker: MockerFixture, *, orchestrator: _RecordingOrchestrator) -> TestClient:
+ mocker.patch(
+ f"{_PIPELINE_NS}.get_api_config", return_value=ApiConfig(orchestration_mode="direct", allow_request_orchestration_mode_override=False)
+ )
+ mocker.patch(f"{_PIPELINE_NS}.get_orchestrator_registry", return_value=OrchestratorRegistry({"direct": orchestrator}))
+ app = FastAPI()
+ app.include_router(api_router, prefix="/v1")
+ register_exception_handlers(app, disclosure_mode=DisclosureMode.STRICT)
+ return TestClient(app)
+
+
[email protected]("sandbox_hosted_mode")
+class TestBundleStructuresRefusal:
+ @pytest.mark.parametrize("path", ["/v1/execute", "/v1/start"])
+ def test_bundle_declaring_a_structure_class_is_refused_unimported(self, mocker: MockerFixture, tmp_path: Path, path: str):
+ sentinel = tmp_path / "structures-module-ran"
+ orchestrator = _RecordingOrchestrator()
+ client = _build_client(mocker, orchestrator=orchestrator)
+
+ files = {"main.mthds": VALID_MTHDS, "structures/invoice.py": _structures_py(sentinel=sentinel)}
+ response = client.post(path, json={"files": files, "inputs": {"text": "hello"}})
+
+ assert response.status_code == 403, response.text
+ assert response.headers["content-type"].startswith("application/problem+json")
+ body = response.json()
+ assert body["error_type"] == "MethodStructuresRefusedError"
+ # Caller-facing even under STRICT disclosure: it names the file and the class, and gives the route.
+ assert "structures/invoice.py" in body["detail"]
+ assert "Invoice" in body["detail"]
+ assert "MTHDS concepts" in body["detail"]
+ assert not sentinel.exists(), "the structure module was imported"
+ assert orchestrator.dispatches == []
+
+ def test_pipe_func_only_bundle_still_dispatches(self, mocker: MockerFixture):
+ orchestrator = _RecordingOrchestrator()
+ client = _build_client(mocker, orchestrator=orchestrator)
+
+ files = {"main.mthds": _PIPE_FUNC_MTHDS, "funcs/pipe_func.py": _PIPE_FUNC_PY}
+ response = client.post("/v1/start", json={"files": files, "inputs": {"data": "1,2,3"}})
+
+ assert response.status_code in {200, 202}, response.text
+ assert orchestrator.dispatches == ["crunch"]
diff --git a/api/tests/unit/test_codegen_route.py b/api/tests/unit/test_codegen_route.py
new file mode 100644
index 000000000..dcf2806c6
--- /dev/null
+++ b/api/tests/unit/test_codegen_route.py
@@ -0,0 +1,155 @@
+"""Envelope tests for `POST /v1/codegen` — the typed-artifact projection route.
+
+Pins `docs/specs/pipelex-codegen.md#route-envelopes` (workspace root): the two explicit projection
+axes (`kind`, `target`); a produced verdict is a 200 discriminated on `is_valid` with the stamped
+artifacts + lock on the valid arm; an unknown `kind`/`target` is a request-shape 422 problem+json;
+the artifacts a client writes verbatim pass the offline `codegen check` byte-for-byte.
+"""
+
+from pathlib import Path
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+from pipelex.codegen.check import run_codegen_check
+from pipelex.codegen.stamp import comment_prefix_for, parse_stamped
+from pipelex.interpreter_hub import get_library_manager
+from pytest_mock import MockerFixture
+
+from pipelex_api.exception_handlers import register_exception_handlers
+from pipelex_api.routes import router as api_router
+from tests.unit._constants import INVALID_MAIN_PIPE_MTHDS, VALID_MTHDS
+
+
+def _build_client() -> TestClient:
+ app = FastAPI()
+ app.include_router(api_router, prefix="/v1")
+ register_exception_handlers(app)
+ return TestClient(app)
+
+
+class TestCodegenRoute:
+ @pytest.mark.parametrize(
+ ("target", "expected_filename"),
+ [
+ ("python-pydantic", "models.py"),
+ ("python-structures", "structures.py"),
+ ("ts-zod", "types.ts"),
+ ],
+ )
+ def test_types_projection_returns_stamped_artifacts_and_lock(self, target: str, expected_filename: str):
+ client = _build_client()
+ response = client.post(
+ "/v1/codegen",
+ json={"files": [{"content": VALID_MTHDS}], "kind": "types", "target": target},
+ )
+ assert response.status_code == 200, response.text
+ body = response.json()
+ assert body["is_valid"] is True
+ assert body["kind"] == "types"
+ assert body["target"] == target
+ assert body["crate_fingerprint"]
+ assert body["engine_version"]
+ artifact_paths = [artifact["path"] for artifact in body["artifacts"]]
+ assert expected_filename in artifact_paths
+ # Every artifact is stamped and the stamp agrees with the envelope's fingerprint.
+ first_artifact = body["artifacts"][0]
+ stamped = parse_stamped(first_artifact["content"], comment_prefix=comment_prefix_for(first_artifact["path"]))
+ assert stamped is not None
+ assert stamped.stamp.crate_fingerprint == body["crate_fingerprint"]
+ assert body["lock_filename"] == "codegen.lock"
+ assert body["crate_fingerprint"] in body["lock"]
+
+ def test_artifacts_written_verbatim_pass_the_offline_check(self, tmp_path: Path):
+ # The trust-chain guarantee over HTTP: a client that writes the artifacts and the lock
+ # verbatim reproduces a local projection — the offline drift check reports it current.
+ client = _build_client()
+ response = client.post(
+ "/v1/codegen",
+ json={"files": [{"content": VALID_MTHDS}], "kind": "types", "target": "python-pydantic"},
+ )
+ assert response.status_code == 200, response.text
+ body = response.json()
+ for artifact in body["artifacts"]:
+ (tmp_path / artifact["path"]).write_text(artifact["content"], encoding="utf-8")
+ (tmp_path / body["lock_filename"]).write_text(body["lock"], encoding="utf-8")
+
+ drift_report = run_codegen_check(root=tmp_path)
+ assert not drift_report.drifts, f"client-written artifacts must be drift-free, got: {drift_report.drifts}"
+
+ def test_invalid_files_return_200_invalid_arm(self):
+ client = _build_client()
+ response = client.post(
+ "/v1/codegen",
+ json={"files": [{"content": INVALID_MAIN_PIPE_MTHDS}], "kind": "types", "target": "ts-zod"},
+ )
+ assert response.status_code == 200, response.text
+ body = response.json()
+ assert body["is_valid"] is False
+ assert body["validation_errors"], "an invalid verdict must carry a non-empty validation_errors[]"
+ assert "artifacts" not in body
+
+ @pytest.mark.parametrize(
+ "payload_patch",
+ [
+ {"kind": "does_not_exist"},
+ {"target": "not-a-target"},
+ {"kind": "inputs"}, # served by /build/inputs, deliberately not by this route
+ {"pipe_ref": "smoke.echo"}, # types is concept-set-wide; a pipe selector is a shape error
+ ],
+ ids=["unknown-kind", "unknown-target", "unserved-kind", "pipe-ref-on-types"],
+ )
+ def test_request_shape_errors_are_422_problem_json(self, payload_patch: dict[str, str]):
+ client = _build_client()
+ payload: dict[str, object] = {"files": [{"content": VALID_MTHDS}], "kind": "types", "target": "ts-zod"}
+ payload.update(payload_patch)
+ response = client.post("/v1/codegen", json=payload)
+ assert response.status_code == 422, response.text
+ assert response.headers["content-type"] == "application/problem+json"
+ assert response.json()["error_type"] == "ValidationError"
+
+ def test_method_ref_is_501_problem_json_until_registry_exists(self):
+ client = _build_client()
+ response = client.post("/v1/codegen", json={"method_ref": "acme/methods/x", "kind": "types", "target": "ts-zod"})
+ assert response.status_code == 501, response.text
+ assert response.headers["content-type"] == "application/problem+json"
+ assert response.json()["error_type"] == "MethodRefNotSupported"
+
+ def test_codegen_tears_down_its_library(self, mocker: MockerFixture):
+ # The engine core leaves the library loaded + current on success; the route owns teardown.
+ # Conservation property: opens == teardowns (mirrors /resolve's analog).
+ library_manager = get_library_manager()
+ open_spy = mocker.spy(library_manager, "open_library")
+ teardown_spy = mocker.spy(library_manager, "teardown")
+
+ client = _build_client()
+ response = client.post("/v1/codegen", json={"files": [{"content": VALID_MTHDS}], "kind": "types", "target": "python-pydantic"})
+
+ assert response.status_code == 200, response.text
+ assert open_spy.call_count >= 1
+ assert open_spy.call_count == teardown_spy.call_count
+
+ def test_codegen_tears_down_library_when_emission_raises(self, mocker: MockerFixture):
+ # Leak canary: a failure in the success window — after resolve_requested_crate left its
+ # library loaded + current, before the finally — must NOT leak that library. The synthetic
+ # RuntimeError propagates to the global Exception handler (500), and the conservation
+ # property still holds: opens == teardowns.
+ library_manager = get_library_manager()
+ open_spy = mocker.spy(library_manager, "open_library")
+ teardown_spy = mocker.spy(library_manager, "teardown")
+ mocker.patch(
+ "pipelex_api.routes.pipelex.codegen.emit_types",
+ side_effect=RuntimeError("synthetic emission failure"),
+ )
+
+ # raise_server_exceptions=False: Starlette's ServerErrorMiddleware would otherwise re-raise
+ # the synthetic RuntimeError through the TestClient (convention of test_exception_handlers.py).
+ app = FastAPI()
+ app.include_router(api_router, prefix="/v1")
+ register_exception_handlers(app)
+ client = TestClient(app, raise_server_exceptions=False)
+ response = client.post("/v1/codegen", json={"files": [{"content": VALID_MTHDS}], "kind": "types", "target": "python-pydantic"})
+
+ assert response.status_code == 500
+ assert open_spy.call_count >= 1
+ assert open_spy.call_count == teardown_spy.call_count
diff --git a/api/tests/unit/test_disclosure.py b/api/tests/unit/test_disclosure.py
new file mode 100644
index 000000000..df85388d8
--- /dev/null
+++ b/api/tests/unit/test_disclosure.py
@@ -0,0 +1,38 @@
+"""Unit tests for ERROR_DISCLOSURE env var resolution."""
+
+import pytest
+from pipelex.base_exceptions import DisclosureMode
+
+from pipelex_api.disclosure import ERROR_DISCLOSURE_ENV_VAR, InvalidErrorDisclosureError, resolve_disclosure_mode
+
+
+class TestDisclosure:
+ def test_defaults_to_verbose_when_unset(self, monkeypatch: pytest.MonkeyPatch):
+ monkeypatch.delenv(ERROR_DISCLOSURE_ENV_VAR, raising=False)
+ assert resolve_disclosure_mode() is DisclosureMode.VERBOSE
+
+ @pytest.mark.parametrize("raw", ["", " ", "\t"])
+ def test_blank_value_defaults_to_verbose(self, monkeypatch: pytest.MonkeyPatch, raw: str):
+ # An empty or whitespace-only value is treated the same as unset — never
+ # rejected as invalid.
+ monkeypatch.setenv(ERROR_DISCLOSURE_ENV_VAR, raw)
+ assert resolve_disclosure_mode() is DisclosureMode.VERBOSE
+
+ @pytest.mark.parametrize(
+ ("raw", "expected"),
+ [
+ ("verbose", DisclosureMode.VERBOSE),
+ ("strict", DisclosureMode.STRICT),
+ ("STRICT", DisclosureMode.STRICT),
+ (" Verbose ", DisclosureMode.VERBOSE),
+ ],
+ )
+ def test_resolves_valid_values(self, monkeypatch: pytest.MonkeyPatch, raw: str, expected: DisclosureMode):
+ monkeypatch.setenv(ERROR_DISCLOSURE_ENV_VAR, raw)
+ assert resolve_disclosure_mode() is expected
+
+ @pytest.mark.parametrize("raw", ["loud", "quiet", "true", "0", "verbos"])
+ def test_rejects_unknown_value(self, monkeypatch: pytest.MonkeyPatch, raw: str):
+ monkeypatch.setenv(ERROR_DISCLOSURE_ENV_VAR, raw)
+ with pytest.raises(InvalidErrorDisclosureError):
+ resolve_disclosure_mode()
diff --git a/api/tests/unit/test_error_log_records.py b/api/tests/unit/test_error_log_records.py
new file mode 100644
index 000000000..633f64801
--- /dev/null
+++ b/api/tests/unit/test_error_log_records.py
@@ -0,0 +1,178 @@
+"""What an error record actually carries, and what it looks like once the `json` sink has written it.
+
+The tests in `test_exception_handlers.py` read the `fields=` mapping the handlers hand the runtime,
+with the runtime's `log` replaced by a spy. These ones let the real thing run end to end: a request
+goes through `RequestIdMiddleware`, the handler emits, `caplog` catches the record the runtime built,
+and the runner's configured sink formatter renders it. That is the whole path this server's operator
+output takes in production, minus the process stream it is written to.
+"""
+
+import json
+import logging
+from pathlib import Path
+from typing import Any, cast
+
+import pytest
+from fastapi import APIRouter, FastAPI
+from fastapi.testclient import TestClient
+from pipelex.base_exceptions import PipelexConfigError
+from pipelex.system.console_target import ConsoleTarget
+from pipelex.tools.log.json_log_sink import JsonLogFormatter
+from pipelex.tools.log.log_sink import LogSinkMethod
+from pipelex.tools.misc.pretty import PrettyPrintMode
+from pipelex.tools.misc.toml_utils import load_toml_from_path
+
+from pipelex_api.error_types import ErrorType
+from pipelex_api.errors import raise_validation_error
+from pipelex_api.exception_handlers import API_ERROR_EVENT, register_exception_handlers
+from pipelex_api.middleware import REQUEST_ID_HEADER, RequestIdMiddleware
+
+_SHIPPED_PIPELEX_CONFIG = Path(__file__).parents[2] / ".pipelex" / "pipelex.toml"
+
+_router = APIRouter()
+
+
+@_router.get("/pipelex-failure")
+async def pipelex_failure_route() -> None:
+ # An operator-actionable 500 — the `error`-level branch, with a traceback on the record.
+ msg = "the gateway config is missing"
+ raise PipelexConfigError(msg)
+
+
+@_router.get("/caller-mistake")
+async def caller_mistake_route(detail: str) -> None:
+ # A caller-input 422 whose `detail` is exactly what the caller sent — the `warning`-level
+ # branch, and the one field on the record that a caller controls.
+ raise_validation_error(detail, ErrorType.VALIDATION_ERROR)
+
+
+def _build_client() -> TestClient:
+ """Wire a throwaway app with the production handlers and the request-id middleware."""
+ app = FastAPI()
+ register_exception_handlers(app)
+ app.include_router(_router)
+ return TestClient(RequestIdMiddleware(app))
+
+
+def _api_error_record(caplog: pytest.LogCaptureFixture) -> logging.LogRecord:
+ """The one `api_error` record the request emitted."""
+ records = [record for record in caplog.records if getattr(record, "event", None) == API_ERROR_EVENT]
+ assert len(records) == 1, f"expected exactly one api_error record, got {len(records)}"
+ return records[0]
+
+
+def _rendered_json(record: logging.LogRecord) -> dict[str, Any]:
+ """The record as the `json` sink writes it: one line, parsed back."""
+ line = JsonLogFormatter().format(record)
+ assert "\n" not in line, f"the sink wrote more than one line: {line!r}"
+ assert "\r" not in line, f"the sink wrote a carriage return: {line!r}"
+ payload = json.loads(line)
+ assert isinstance(payload, dict)
+ return cast("dict[str, Any]", payload)
+
+
+class TestErrorLogRecords:
+ def test_the_runner_ships_a_configuration_that_selects_the_json_sink(self):
+ # Reads the shipped file rather than `get_config()`, deliberately. The runtime layers
+ # `_local`, `_{environment}` and `_override` files over a base, so the merged config is
+ # partly this machine's: a developer who sets `sink = "console"` locally for a readable
+ # `make run` would red this test while CI, which has no such file, stayed green. What the
+ # image boots on is this file, because nothing mounts an override into it.
+ #
+ # The json sink writes to stderr so stdout stays the data channel, and the pretty-print
+ # mode is silent because a server has no terminal and must not render on the request
+ # thread. Neither is a claim that Rich is absent: `typer` and `instructor` require it
+ # unconditionally, so it is installed and reachable — these keys are what keeps it unused.
+ log_section = load_toml_from_path(_SHIPPED_PIPELEX_CONFIG)["runtime"]["log"]
+ assert log_section["sink"] == LogSinkMethod.JSON
+ assert log_section["console_log_target"] == ConsoleTarget.STDERR
+ assert log_section["pretty_print_mode"] == PrettyPrintMode.SILENT
+
+ def test_request_id_and_route_ride_the_error_record(self, caplog: pytest.LogCaptureFixture):
+ # The two identifiers an operator starts from. `request_id` arrives from the log context
+ # the middleware bound for the request; `route` from the field set the handler ships.
+ # Neither is interpolated into the message, which is the whole point of the change.
+ with caplog.at_level(logging.WARNING):
+ response = _build_client().get("/pipelex-failure")
+ assert response.status_code == 500
+ record = _api_error_record(caplog)
+ assert record.levelno == logging.ERROR
+ assert getattr(record, "request_id", None) == response.headers[REQUEST_ID_HEADER]
+ assert getattr(record, "route", None) == "/pipelex-failure"
+ assert getattr(record, "error_type", None) == "PipelexConfigError"
+ assert record.getMessage() == "API error 500: PipelexConfigError"
+
+ def test_a_caller_mistake_records_a_warning_carrying_the_same_identifiers(self, caplog: pytest.LogCaptureFixture):
+ # A 4xx is a caller mistake, so it lands at `warning` — but it carries the same two
+ # identifiers, so one query over `event` returns the whole error stream of a request.
+ with caplog.at_level(logging.WARNING):
+ response = _build_client().get("/caller-mistake", params={"detail": "the input is malformed"})
+ assert response.status_code == 422
+ record = _api_error_record(caplog)
+ assert record.levelno == logging.WARNING
+ assert getattr(record, "request_id", None) == response.headers[REQUEST_ID_HEADER]
+ assert getattr(record, "route", None) == "/caller-mistake"
+ assert getattr(record, "status", None) == 422
+
+ def test_the_json_sink_writes_one_object_per_line_with_the_fields_flat(self, caplog: pytest.LogCaptureFixture):
+ # The shape the runner's configured sink puts on stderr: the sink's own keys, then every
+ # field and the bound context identifiers flat beside them, one JSON object on one line.
+ with caplog.at_level(logging.WARNING):
+ response = _build_client().get("/pipelex-failure")
+ payload = _rendered_json(_api_error_record(caplog))
+ assert payload["severity"] == "ERROR"
+ assert payload["message"] == "API error 500: PipelexConfigError"
+ assert payload["event"] == API_ERROR_EVENT
+ assert payload["request_id"] == response.headers[REQUEST_ID_HEADER]
+ assert payload["route"] == "/pipelex-failure"
+ assert payload["status"] == 500
+ assert payload["error_type"] == "PipelexConfigError"
+ assert payload["error_domain"] == "config"
+ # `retryable` is absent rather than false: pipelex populates it only on a classifiable
+ # failure, and a field with no value is dropped rather than written as a null a query
+ # filtering on presence would read as an answer.
+ assert "retryable" not in payload
+ # `time` and `logger` come from the sink itself; an operator-actionable failure carries
+ # its traceback under `exception` rather than spilling it across the line.
+ assert payload["time"].endswith("Z")
+ assert "PipelexConfigError" in payload["exception"]
+
+ @pytest.mark.parametrize(
+ ("crafted_detail", "logged_detail"),
+ [
+ # Back when the API flattened its own fields into a `key=value` run, each of these
+ # forged either a sibling field or a whole second line. The API renders nothing now:
+ # the runtime escapes a control character in a field's value and the sink escapes what
+ # it writes, so each must survive as one field's value.
+ ("legit\nstatus=200 event=auth_success", "legit\\nstatus=200 event=auth_success"),
+ ("hijack status=200 event=fake", "hijack status=200 event=fake"),
+ ("legit\rstatus=200", "legit\\rstatus=200"),
+ ('has " a quote = inside', 'has " a quote = inside'),
+ ],
+ )
+ def test_a_crafted_detail_survives_as_one_value_and_forges_nothing(
+ self, caplog: pytest.LogCaptureFixture, crafted_detail: str, logged_detail: str
+ ):
+ # The escaping the API used to do itself is the runtime's job now, in two layers. The
+ # redaction processor every sink sits behind turns a control character in a field's value
+ # into its printable escape, so a newline the caller sent reads `\n` in `detail`; then
+ # `json.dumps` writes each value inside one string, so a quote or an `=` stays part of it.
+ # Either way the line stays one object and the value comes back as one field.
+ with caplog.at_level(logging.WARNING):
+ response = _build_client().get("/caller-mistake", params={"detail": crafted_detail})
+ assert response.status_code == 422
+ payload = _rendered_json(_api_error_record(caplog))
+ assert payload["detail"] == logged_detail
+ assert payload["event"] == API_ERROR_EVENT, "a crafted detail forged or overwrote a field"
+ assert payload["status"] == 422, "a crafted detail forged or overwrote a field"
+ assert crafted_detail not in payload["message"], "caller input reached the message"
+
+ def test_a_credential_echoed_into_a_detail_is_redacted_on_the_line(self, caplog: pytest.LogCaptureFixture):
+ # A validation message can echo what the caller sent, header text included. The runtime's
+ # redaction processor scrubs the credential out of the field before the sink writes it, and
+ # keeps the scheme, so the line still says which kind of credential went.
+ with caplog.at_level(logging.WARNING):
+ response = _build_client().get("/caller-mistake", params={"detail": "rejected Authorization: Bearer placeholder-not-a-token"})
+ assert response.status_code == 422
+ payload = _rendered_json(_api_error_record(caplog))
+ assert payload["detail"] == "rejected Authorization: Bearer [REDACTED]"
diff --git a/api/tests/unit/test_error_responses.py b/api/tests/unit/test_error_responses.py
new file mode 100644
index 000000000..68c9471db
--- /dev/null
+++ b/api/tests/unit/test_error_responses.py
@@ -0,0 +1,219 @@
+"""Phase 3 regression tests — every API error path emits one RFC 7807 shape.
+
+Builds a production-faithful app (the real routers, the global exception
+handlers, `RequestIdMiddleware`, the body-size middleware) and asserts that
+4xx/5xx responses across the surface are `application/problem+json` with the
+RFC 7807 fields and an `X-Request-ID` header — never the old
+`{"detail": {...}}` envelope, and never FastAPI's default `{"detail": [...]}`
+for automatic request validation. Covers regression checks T1 (413), T2
+(a route-level 403) and T5 (`X-Request-ID` on every error response).
+
+The 400/403/401 vehicles used to be the storage and upload routes. Those moved
+to the hosted platform, so each assertion now rides a different route that
+raises through the same helper — the envelope is what is under test, never the
+route that produced it.
+"""
+
+from collections.abc import Iterator
+from importlib.metadata import PackageNotFoundError
+
+from fastapi import Depends, FastAPI, Request
+from fastapi.responses import JSONResponse
+from fastapi.testclient import TestClient
+from pytest_mock import MockerFixture
+from starlette.middleware.base import BaseHTTPMiddleware
+
+from pipelex_api.exception_handlers import register_exception_handlers
+from pipelex_api.middleware import REQUEST_ID_HEADER, RequestIdMiddleware, request_body_size_middleware
+from pipelex_api.problem_document import PROBLEM_JSON_MEDIA_TYPE
+from pipelex_api.routes import router as api_router
+from pipelex_api.routes.version import router as version_router
+from pipelex_api.security import RequestUser, get_request_user, verify_api_key
+
+USER_A = "aaaaaaaa-aaaa-4aaa-aaaa-aaaaaaaaaaaa"
+USER_B = "bbbbbbbb-bbbb-4bbb-bbbb-bbbbbbbbbbbb"
+FILE_HASH = "cccccccc-cccc-4ccc-cccc-cccccccccccc"
+
+
+def _build_client(*, user: RequestUser | None = None, with_auth: bool = False) -> TestClient:
+ """Wire a production-faithful app: real routers, handlers, both middlewares.
+
+ `RequestIdMiddleware` wraps the whole app exactly as in `pipelex_api.main`, so the
+ request-id contextvars are bound and `X-Request-ID` is stamped on every
+ response. `get_request_user` is overridden so routes see the caller
+ identity the test wants.
+
+ `with_auth` mounts the composite router behind the SAME `auth_dependency`
+ `pipelex_api.main` uses, which is the only way to reach a real 401 — every
+ `raise_unauthenticated` lives in the verifiers that dependency runs, not in
+ a route body.
+ """
+ app = FastAPI(redirect_slashes=False)
+ app.add_middleware(BaseHTTPMiddleware, dispatch=request_body_size_middleware)
+ app.include_router(version_router, prefix="/v1")
+ if with_auth:
+ app.include_router(api_router, prefix="/v1", dependencies=[Depends(verify_api_key)])
+ else:
+ app.include_router(api_router, prefix="/v1")
+ register_exception_handlers(app)
+
+ async def _override_user() -> RequestUser | None:
+ return user
+
+ app.dependency_overrides[get_request_user] = _override_user
+ return TestClient(RequestIdMiddleware(app))
+
+
+class TestErrorResponses:
+ def test_validation_error_is_rfc7807_input_domain(self):
+ # /models with an unknown category → raise_validation_error → 422.
+ response = _build_client().get("/v1/models?type=not-a-real-category")
+ assert response.status_code == 422
+ assert response.headers["content-type"] == PROBLEM_JSON_MEDIA_TYPE
+ body = response.json()
+ assert body["error_type"] == "InvalidModelCategory"
+ assert body["error_domain"] == "input"
+ assert body["instance"] == "/v1/models"
+ assert body["status"] == 422
+ assert body["request_id"] == response.headers[REQUEST_ID_HEADER]
+ # API-authored caller-input errors are non-retryable across the surface.
+ assert body["retryable"] is False
+
+ def test_request_validation_error_is_rfc7807(self):
+ # FastAPI's automatic body validation (here: mthds_contents below its
+ # min_length) must answer in the same RFC 7807 shape as every other
+ # path — not FastAPI's default {"detail": [...]} / application/json.
+ response = _build_client().post("/v1/validate", json={"mthds_contents": []})
+ assert response.status_code == 422
+ assert response.headers["content-type"] == PROBLEM_JSON_MEDIA_TYPE
+ body = response.json()
+ assert body["error_type"] == "ValidationError"
+ assert body["error_domain"] == "input"
+ assert body["status"] == 422
+ assert body["instance"] == "/v1/validate"
+ assert isinstance(body["detail"], str)
+ assert "mthds_contents" in body["detail"]
+ assert body["request_id"] == response.headers[REQUEST_ID_HEADER]
+ assert body["retryable"] is False
+
+ def test_bad_request_is_rfc7807(self):
+ # A `bundle_b64` that is not valid base64 → raise_bad_request → 400.
+ client = _build_client(user=RequestUser(user_id=USER_A))
+ response = client.post("/v1/execute", json={"bundle_b64": "not!base64", "pipe_code": "smoke"})
+ assert response.status_code == 400
+ assert response.headers["content-type"] == PROBLEM_JSON_MEDIA_TYPE
+ body = response.json()
+ assert body["error_type"] == "InvalidBase64"
+ assert body["error_domain"] == "input"
+ assert body["request_id"] == response.headers[REQUEST_ID_HEADER]
+ assert body["retryable"] is False
+
+ def test_forbidden_is_rfc7807(self):
+ # REGRESSION T2: a per-request orchestration-mode override the
+ # deployment forbids → raise_forbidden → 403.
+ client = _build_client(user=RequestUser(user_id=USER_A))
+ response = client.post(
+ "/v1/execute",
+ json={"mthds_contents": ['domain = "smoke"'], "pipe_code": "smoke", "orchestration_mode": "definitely-not-the-default"},
+ )
+ assert response.status_code == 403
+ assert response.headers["content-type"] == PROBLEM_JSON_MEDIA_TYPE
+ body = response.json()
+ assert body["error_type"] == "OrchestrationModeOverrideForbidden"
+ assert body["status"] == 403
+ assert body["request_id"] == response.headers[REQUEST_ID_HEADER]
+ assert body["retryable"] is False
+
+ def test_payload_too_large_is_rfc7807(self):
+ # REGRESSION T1: a body over the cap → 413 via the body-size middleware.
+ response = _build_client().get(
+ "/v1/version",
+ headers={"content-length": str(200 * 1024 * 1024)},
+ )
+ assert response.status_code == 413
+ assert response.headers["content-type"] == PROBLEM_JSON_MEDIA_TYPE
+ body = response.json()
+ assert body["error_type"] == "PayloadTooLarge"
+ assert body["error_domain"] == "input"
+ assert body["status"] == 413
+ # The body-size middleware has to return a response rather than raise, so it builds its own
+ # problem document — and it reads the route and the id off the `Request` it was handed,
+ # like every other error path.
+ assert body["instance"] == "/v1/version"
+ assert body["request_id"] == response.headers[REQUEST_ID_HEADER]
+ assert body["retryable"] is False
+
+ def test_payload_too_large_chunked_does_not_buffer_oversized_body(self, mocker: MockerFixture):
+ # REGRESSION T1b: a chunked / no-content-length over-limit body must reject
+ # before the route can buffer or process it. Without the fix, the middleware
+ # only flips `too_large` after `call_next` returns, leaving the route free to
+ # fully `await request.body()` on the oversized stream — defeating memory/CPU
+ # protection and allowing route side effects to run before the 413.
+ mocker.patch("pipelex_api.middleware.MAX_REQUEST_BODY_BYTES", 1024)
+
+ bytes_seen_by_route: list[int] = []
+
+ async def echo(request: Request) -> JSONResponse:
+ body = await request.body()
+ bytes_seen_by_route.append(len(body))
+ return JSONResponse({"length": len(body)})
+
+ app = FastAPI(redirect_slashes=False)
+ app.add_middleware(BaseHTTPMiddleware, dispatch=request_body_size_middleware)
+ app.add_api_route("/echo", echo, methods=["POST"])
+ register_exception_handlers(app)
+
+ client = TestClient(RequestIdMiddleware(app))
+
+ # 4 KiB body, 4x the patched 1 KiB cap. A generator forces httpx to use
+ # chunked transfer encoding, exercising the counting branch instead of
+ # the fast Content-Length reject.
+ def streaming_body() -> Iterator[bytes]:
+ yield b"x" * 4096
+
+ response = client.post("/echo", content=streaming_body())
+
+ assert response.status_code == 413
+ assert response.headers["content-type"] == PROBLEM_JSON_MEDIA_TYPE
+ assert response.json()["error_type"] == "PayloadTooLarge"
+ # With the fix, the over-limit first chunk is replaced with an end-of-stream
+ # marker, so the route observes an empty body. Without the fix, the route
+ # would see all 4096 bytes.
+ assert bytes_seen_by_route == [0]
+
+ def test_internal_server_error_is_rfc7807_config_domain(self, mocker: MockerFixture):
+ # Absent package metadata → raise_internal_server_error → 500 CONFIG.
+ mocker.patch("pipelex_api.routes.version.version", side_effect=PackageNotFoundError("pipelex"))
+ response = _build_client().get("/v1/version")
+ assert response.status_code == 500
+ assert response.headers["content-type"] == PROBLEM_JSON_MEDIA_TYPE
+ body = response.json()
+ assert body["error_type"] == "PackageNotFound"
+ assert body["error_domain"] == "config"
+ assert body["status"] == 500
+ assert body["request_id"] == response.headers[REQUEST_ID_HEADER]
+ # An API-owned 5xx is non-retryable: the operator, not the caller,
+ # fixes a missing package; the symmetry with the 4xx paths is the
+ # uniform retry contract clients can rely on.
+ assert body["retryable"] is False
+
+ def test_unauthenticated_carries_www_authenticate_challenge(self):
+ # No Authorization header on an auth-wrapped route → 401 + challenge.
+ response = _build_client(user=None, with_auth=True).post("/v1/validate", json={"mthds_contents": ['domain = "smoke"']})
+ assert response.status_code == 401
+ assert response.headers["content-type"] == PROBLEM_JSON_MEDIA_TYPE
+ assert response.headers["WWW-Authenticate"] == "Bearer"
+ body = response.json()
+ assert body["error_type"] == "Unauthenticated"
+ assert body["request_id"] == response.headers[REQUEST_ID_HEADER]
+ assert body["retryable"] is False
+
+ def test_inbound_request_id_is_echoed_into_error_body(self):
+ # A caller-supplied X-Request-ID rides through to the response body.
+ response = _build_client().get(
+ "/v1/models?type=not-a-real-category",
+ headers={REQUEST_ID_HEADER: "inbound-correlation-303"},
+ )
+ assert response.status_code == 422
+ assert response.headers[REQUEST_ID_HEADER] == "inbound-correlation-303"
+ assert response.json()["request_id"] == "inbound-correlation-303"
diff --git a/api/tests/unit/test_error_uri.py b/api/tests/unit/test_error_uri.py
new file mode 100644
index 000000000..04ecb1916
--- /dev/null
+++ b/api/tests/unit/test_error_uri.py
@@ -0,0 +1,35 @@
+"""Unit tests for the RFC 7807 type-URI and title helpers."""
+
+import pytest
+
+from pipelex_api.error_uri import error_type_title, error_type_uri
+
+
+class TestErrorUri:
+ @pytest.mark.parametrize(
+ ("error_type", "expected"),
+ [
+ ("EnvVarNotFoundError", "https://docs.pipelex.com/latest/errors/env-var-not-found-error/"),
+ ("ValidationError", "https://docs.pipelex.com/latest/errors/validation-error/"),
+ ("PayloadTooLarge", "https://docs.pipelex.com/latest/errors/payload-too-large/"),
+ ("InvalidJSON", "https://docs.pipelex.com/latest/errors/invalid-json/"),
+ ("LLMCompletionError", "https://docs.pipelex.com/latest/errors/llm-completion-error/"),
+ ],
+ )
+ def test_error_type_uri(self, error_type: str, expected: str):
+ assert error_type_uri(error_type) == expected
+
+ @pytest.mark.parametrize(
+ ("error_type", "expected"),
+ [
+ ("EnvVarNotFoundError", "Env var not found error"),
+ ("ValidationError", "Validation error"),
+ ("PayloadTooLarge", "Payload too large"),
+ ("BadRequest", "Bad request"),
+ # A trailing acronym is preserved by pipelex's pascal_case_to_sentence
+ # (`InvalidJSON` → `Invalid JSON`); pinned so the behavior is visible.
+ ("InvalidJSON", "Invalid JSON"),
+ ],
+ )
+ def test_error_type_title(self, error_type: str, expected: str):
+ assert error_type_title(error_type) == expected
diff --git a/api/tests/unit/test_exception_handlers.py b/api/tests/unit/test_exception_handlers.py
new file mode 100644
index 000000000..da7eb671a
--- /dev/null
+++ b/api/tests/unit/test_exception_handlers.py
@@ -0,0 +1,904 @@
+"""Integration tests for the global FastAPI exception handlers.
+
+These tests register the production handlers on a throwaway FastAPI app whose
+routes raise straight through — `ApiError`, `RequestValidationError`,
+`PipelexError`, a bare orchestrator-SDK transport error (handled via a synthetic
+plugin-contributed mapper, proving the F3 seam without importing any orchestrator
+SDK), and uncaught `Exception` each end up at their respective handler exactly
+the way the real app routes them.
+"""
+
+import re
+from typing import Any, cast
+
+import pytest
+from fastapi import APIRouter, FastAPI, Request
+from fastapi.testclient import TestClient
+from pipelex.base_exceptions import (
+ INTERNAL_ERROR_PLACEHOLDER,
+ DisclosureMode,
+ ErrorDomain,
+ ErrorReport,
+ PipelexConfigError,
+ PipelexError,
+)
+from pipelex.cogt.inference.error_classification import ProviderErrorMetadata, UserAction, UserActionKind
+from pipelex.cogt.inference.provider_name import ProviderName
+from pipelex.config import get_config
+from pipelex.pipe_run.exceptions import AsyncExecutionNotEnabledError
+from pipelex.pipeline.exceptions import PipelineManagerAlreadyExistsError
+from pipelex.plugins.contract import PLUGIN_API_VERSION
+from pipelex.plugins.registrar import HttpErrorMapperFn, PluginOrigin, PluginRegistrar
+from pipelex.system.exceptions import EnvVarNotFoundError
+from pydantic import BaseModel, ConfigDict
+from pytest_mock import MockerFixture
+from typing_extensions import override
+
+from pipelex_api.error_types import ErrorType
+from pipelex_api.errors import raise_internal_server_error, raise_validation_error
+from pipelex_api.exception_handlers import API_ERROR_EVENT, register_exception_handlers
+from pipelex_api.middleware import REQUEST_ID_HEADER, RequestIdMiddleware
+from pipelex_api.problem_document import PROBLEM_JSON_MEDIA_TYPE
+from pipelex_api.security import RequestUser
+
+# Crockford Base32, 26 chars — the ULID alphabet RequestIdMiddleware mints.
+_ULID_RE = re.compile(r"\A[0-9A-HJKMNP-TV-Z]{26}\Z")
+
+
+def _emitted_fields(log_spy: Any, *, as_error: bool) -> dict[str, Any]:
+ """The record attributes the handler shipped on its one `api_error` call.
+
+ The handlers hand everything but the summary message to the runtime as `fields=`, so the
+ assertions below read that mapping rather than parsing a rendered line: there is no rendering
+ left to parse, and a sink is what decides how an attribute reaches the wire.
+ """
+ call = log_spy.error.call_args if as_error else log_spy.warning.call_args
+ fields = call.kwargs["fields"]
+ assert isinstance(fields, dict)
+ return cast("dict[str, Any]", fields)
+
+
+class _SimulatedLLMError(PipelexError):
+ """A `PipelexError` whose report mimics a provider rate-limit (429) failure."""
+
+ @override
+ def to_error_report(self) -> ErrorReport:
+ return ErrorReport(
+ error_type="LLMCompletionError",
+ message="OpenAI returned 429 (rate_limit_exceeded)",
+ title="LLM completion error",
+ type_uri="https://docs.pipelex.com/latest/errors/llm-completion-error/",
+ error_category="transient",
+ error_domain="runtime",
+ retryable=True,
+ user_action=UserAction(kind=UserActionKind.WAIT_AND_RETRY, detail="Retry after 12s."),
+ model="gpt-4o-mini",
+ provider="openai",
+ provider_metadata=ProviderErrorMetadata(
+ provider=ProviderName.OPENAI,
+ sdk_exception_type="RateLimitError",
+ status_code=429,
+ retry_after_seconds=12.0,
+ request_id="req_provider_abc",
+ ),
+ )
+
+
+class _CorruptReportError(PipelexError):
+ """A `PipelexError` whose `to_error_report` itself fails — the handler-of-handlers case."""
+
+ @override
+ def to_error_report(self) -> ErrorReport:
+ msg = "to_error_report is deliberately broken"
+ raise RuntimeError(msg)
+
+
+class _CallerFacingInputError(PipelexError):
+ """An `INPUT`-domain error whose message is genuine caller-facing copy.
+
+ `_authors_caller_facing_message` makes STRICT disclosure keep the message
+ verbatim — the projection pipelex applies to a `.mthds` syntax error.
+ """
+
+ error_domain = ErrorDomain.INPUT
+ _authors_caller_facing_message = True
+
+
+class _SyntheticTransportError(Exception):
+ """A bare orchestrator-SDK-style transport error — NOT a `PipelexError`, no `temporalio`.
+
+ Stands in for the kind of exception an orchestrator plugin contributes a mapper for (e.g.
+ `temporalio.TemporalError`), so the F3 seam — plugin maps a bare transport exception to a
+ structured `ErrorReport`, the API renders it — is exercised without importing any orchestrator SDK.
+ """
+
+
+class _SyntheticOrchestratorError(PipelexError):
+ """An orchestrator failure that IS a `PipelexError` (carries its own `ErrorReport`).
+
+ Stands in for e.g. the Temporal plugin's `WorkflowExecutionError`: Starlette's MRO walk resolves
+ it to `handle_pipelex_error`, never to the transport mapper handler registered for a bare
+ transport exception.
+ """
+
+
+def _synthetic_transport_to_report(exc: Exception) -> ErrorReport:
+ """The mapper an orchestrator plugin would contribute: classify the bare transport fault.
+
+ Mirrors the classification the (now plugin-owned) Temporal transport mapper produces — a
+ retryable, `RUNTIME`-domain `transient` failure.
+ """
+ return ErrorReport(
+ error_type="SyntheticTransportError",
+ message=str(exc),
+ title="Synthetic transport error",
+ type_uri="https://docs.pipelex.com/latest/errors/synthetic-transport-error/",
+ error_category="transient",
+ error_domain=ErrorDomain.RUNTIME,
+ retryable=True,
+ )
+
+
+def _synthetic_http_error_mappers() -> dict[type[Exception], HttpErrorMapperFn]:
+ """Resolve a mapper the way an installed orchestrator plugin would — through the registrar SPI.
+
+ Builds a `PluginRegistrar`, has a synthetic plugin contribute the mapper via
+ `add_http_error_mapper`, and reads it back with `get_http_error_mappers` — exercising the real
+ producer→consumer seam (the same one `pipelex_api.main` drives at app construction) without installing a
+ plugin or importing an orchestrator SDK.
+ """
+ registrar = PluginRegistrar(config=get_config())
+ # `group=None` is what a built-in carries: the entry-point group is how an *external* plugin
+ # declares its layer, and a built-in arrives under none — it is filed by layer in-tree instead.
+ registrar.begin_plugin(name="synthetic-transport-plugin", origin=PluginOrigin.BUILTIN, targets_api=PLUGIN_API_VERSION, group=None)
+ registrar.add_http_error_mapper(exc_type_provider=lambda: _SyntheticTransportError, to_error_report=_synthetic_transport_to_report)
+ return registrar.get_http_error_mappers()
+
+
+def _report_with_retry(*, status_code: int, retry_after_seconds: float | None) -> ErrorReport:
+ """Build a provider-error report carrying a `retry_after_seconds` hint."""
+ return ErrorReport(
+ error_type="LLMCompletionError",
+ message="provider error",
+ title="LLM completion error",
+ type_uri="https://docs.pipelex.com/latest/errors/llm-completion-error/",
+ error_category="transient",
+ error_domain="runtime",
+ retryable=True,
+ provider_metadata=ProviderErrorMetadata(
+ provider=ProviderName.OPENAI,
+ sdk_exception_type="RateLimitError",
+ status_code=status_code,
+ retry_after_seconds=retry_after_seconds,
+ ),
+ )
+
+
+# Reports exercising every branch of `_retry_after_header`: a finite hint, the
+# two non-finite values a provider could emit, a negative value, and a hint
+# carried on a non-429 status (where `Retry-After` must not be emitted).
+_RETRY_REPORTS: dict[str, ErrorReport] = {
+ "finite": _report_with_retry(status_code=429, retry_after_seconds=12.4),
+ "infinite": _report_with_retry(status_code=429, retry_after_seconds=float("inf")),
+ "nan": _report_with_retry(status_code=429, retry_after_seconds=float("nan")),
+ "negative": _report_with_retry(status_code=429, retry_after_seconds=-5.0),
+ "non_429": _report_with_retry(status_code=503, retry_after_seconds=30.0),
+}
+
+
+class _CraftedRetryError(PipelexError):
+ """A `PipelexError` whose report is selected by key — exercises `_retry_after_header`."""
+
+ def __init__(self, report_key: str) -> None:
+ super().__init__("crafted retry-after scenario")
+ self._report = _RETRY_REPORTS[report_key]
+
+ @override
+ def to_error_report(self) -> ErrorReport:
+ return self._report
+
+
+# Route handlers are deliberately not underscore-prefixed: a private,
+# decorator-only function reads as unused to the type checker.
+_router = APIRouter()
+
+
+@_router.get("/config-error")
+async def config_error_route() -> None:
+ msg = "the gateway config is missing"
+ raise PipelexConfigError(msg)
+
+
+@_router.get("/env-error")
+async def env_error_route() -> None:
+ msg = "Environment variable 'COMPLETION_CALLBACK_SECRET' is required but not set"
+ raise EnvVarNotFoundError(msg)
+
+
+@_router.get("/input-error")
+async def input_error_route() -> None:
+ msg = "your .mthds file has a syntax error on line 4"
+ raise _CallerFacingInputError(msg)
+
+
+@_router.get("/llm-error")
+async def llm_error_route() -> None:
+ msg = "simulated provider rate limit"
+ raise _SimulatedLLMError(msg)
+
+
+@_router.get("/corrupt-error")
+async def corrupt_error_route() -> None:
+ msg = "its report builder is broken"
+ raise _CorruptReportError(msg)
+
+
+@_router.get("/orchestrator-pipelex-error")
+async def orchestrator_pipelex_error_route() -> None:
+ msg = "the workflow failed"
+ raise _SyntheticOrchestratorError(msg)
+
+
+@_router.get("/async-execution-not-enabled")
+async def async_execution_not_enabled_route() -> None:
+ # Pipelex raises this when an async dispatch site is reached on a
+ # deployment without an async execution backend enabled. The API maps it
+ # to 501 Not Implemented (see ``_ERROR_TYPE_STATUS_OVERRIDES``).
+ msg = "Asynchronous pipeline execution is not enabled on this deployment."
+ raise AsyncExecutionNotEnabledError(msg)
+
+
+@_router.get("/pipeline-run-id-conflict")
+async def pipeline_run_id_conflict_route() -> None:
+ # Pipelex raises this from ``add_new_pipeline`` when a submission reuses a
+ # ``pipeline_run_id`` that is still registered (a genuinely concurrent
+ # duplicate — completed/failed runs free their entry on the way out). The
+ # API maps it to 409 Conflict (see ``_ERROR_TYPE_STATUS_OVERRIDES``).
+ msg = "Pipeline some-run-id already exists"
+ raise PipelineManagerAlreadyExistsError(msg)
+
+
+@_router.get("/synthetic-transport-error")
+async def synthetic_transport_error_route() -> None:
+ msg = "orchestrator cluster unreachable"
+ raise _SyntheticTransportError(msg)
+
+
+@_router.get("/unexpected-error")
+async def unexpected_error_route() -> None:
+ msg = "something nobody anticipated"
+ raise RuntimeError(msg)
+
+
+@_router.get("/crafted-retry/{report_key}")
+async def crafted_retry_route(report_key: str) -> None:
+ raise _CraftedRetryError(report_key)
+
+
+@_router.get("/api-input-error")
+async def api_input_error_route() -> None:
+ # An API-authored 422 — the INPUT-domain branch of `handle_api_error`.
+ raise_validation_error("a caller-side mistake")
+
+
+@_router.get("/crafted-detail")
+async def crafted_detail_route(detail: str) -> None:
+ # An API-authored 422 whose `detail` is exactly what the caller sent — the real shape of the
+ # `raise_validation_error(str(exc))` sites, where the message is built from caller input.
+ raise_validation_error(detail)
+
+
+@_router.get("/api-config-error")
+async def api_config_error_route() -> None:
+ # An API-authored 500 — the CONFIG-domain branch of `handle_api_error`
+ # (the `version.py` `PackageNotFoundError → raise_internal_server_error`
+ # path goes through this same code).
+ raise_internal_server_error("the configuration is broken", error_type=ErrorType.SERVER_MISCONFIGURED)
+
+
+class _RequestValidationBody(BaseModel):
+ """Trivial schema for `test_request_validation_error_emits_structured_warning_log`.
+
+ A POST that is both missing `field` and carries an unknown key triggers
+ FastAPI's automatic `RequestValidationError`, which is what we want to
+ log-test. `extra="forbid"` matches the strictest production schemas
+ (`UploadRequest`, `ResolveStorageUrlRequest`) and ensures both the
+ missing-field and the extra-field branches of the validation surface
+ fire on a single request — Pydantic's default `extra="ignore"` would
+ silently drop the unknown key.
+ """
+
+ model_config = ConfigDict(extra="forbid")
+
+ field: str
+
+
+@_router.post("/needs-body")
+async def needs_body_route(_body: _RequestValidationBody) -> None:
+ return None
+
+
+# A canonical user_id for the authenticated test routes — a realistic
+# path-safe id (`pipelex_api.security.is_safe_user_id`), so the routes mirror real
+# auth state rather than a placeholder string.
+_TEST_USER_ID = "00000000-0000-0000-0000-000000000001"
+
+
+def _bind_test_user(request: Request) -> None:
+ """Set `request.state.user` the same shape `pipelex_api.security._set_request_user` would.
+
+ The throwaway app does not run the real auth dependency — these routes stand
+ in for "auth succeeded" so the error-log enrichment can be exercised
+ without dragging in JWT validation.
+ """
+ request.state.user = RequestUser(user_id=_TEST_USER_ID)
+
+
+# Canonical body-derived identifiers for the pipeline-state routes — bound on
+# `request.state` the same way `pipelex_api.routes.pipelex.pipeline._parse_request`
+# binds them in production.
+_TEST_PIPE_CODE = "echo"
+_TEST_RUN_ID = "run-00000000-0000-0000-0000-000000000099"
+
+
+def _bind_test_run_state(request: Request) -> None:
+ """Set `request.state.pipe_code` / `pipeline_run_id` the same shape `_parse_request` would.
+
+ Stand-in for "the body was parsed and the two identifiers were bound" so
+ the error-log enrichment can be exercised against the handler functions
+ without driving a real `/execute` body through `_parse_request`.
+ """
+ request.state.pipe_code = _TEST_PIPE_CODE
+ request.state.pipeline_run_id = _TEST_RUN_ID
+
+
+@_router.get("/authenticated-config-error")
+async def authenticated_config_error_route(request: Request) -> None:
+ _bind_test_user(request)
+ msg = "the gateway config is missing"
+ raise PipelexConfigError(msg)
+
+
+@_router.get("/authenticated-api-input-error")
+async def authenticated_api_input_error_route(request: Request) -> None:
+ _bind_test_user(request)
+ raise_validation_error("a caller-side mistake")
+
+
+@_router.get("/authenticated-unexpected-error")
+async def authenticated_unexpected_error_route(request: Request) -> None:
+ _bind_test_user(request)
+ msg = "something nobody anticipated"
+ raise RuntimeError(msg)
+
+
+@_router.get("/pipeline-state-pipelex-error")
+async def run_state_pipelex_error_route(request: Request) -> None:
+ # Stand-in for the production flow: a body went through `_parse_request`
+ # (state bound), then pipelex raised a `PipelexError` further down the
+ # stack. Exercises `_log_error_report`.
+ _bind_test_run_state(request)
+ msg = "the gateway config is missing"
+ raise PipelexConfigError(msg)
+
+
+@_router.get("/pipeline-state-api-input-error")
+async def run_state_api_input_error_route(request: Request) -> None:
+ # An API-authored 4xx raised after `_parse_request` bound state — exercises
+ # `_log_api_authored_error`.
+ _bind_test_run_state(request)
+ raise_validation_error("a caller-side mistake")
+
+
+@_router.get("/pipeline-state-unexpected-error")
+async def run_state_unexpected_error_route(request: Request) -> None:
+ # An unclassified exception escaping after `_parse_request` bound state —
+ # exercises the catch-all `handle_unexpected_error` log path. The most
+ # operationally expensive case: by definition the failure was not
+ # classifiable upstream, so carrying the pipe-state identifiers is what
+ # gives the operator a starting point for debugging.
+ _bind_test_run_state(request)
+ msg = "something nobody anticipated"
+ raise RuntimeError(msg)
+
+
+def _build_client(
+ *,
+ raise_server_exceptions: bool = True,
+ disclosure_mode: DisclosureMode = DisclosureMode.VERBOSE,
+ http_error_mappers: dict[type[Exception], HttpErrorMapperFn] | None = None,
+) -> TestClient:
+ """Wire a throwaway app with the production handlers and request-id middleware.
+
+ `raise_server_exceptions` must be `False` for tests that hit the catch-all
+ handler: Starlette's `ServerErrorMiddleware` always re-raises after running
+ its handler, so the `TestClient` would otherwise surface the exception
+ instead of the sanitized response. `disclosure_mode` is the value
+ `register_exception_handlers` captures in the closures it registers for
+ `PipelexError` / the mapper handlers; the default mirrors production
+ (VERBOSE), tests that exercise STRICT redaction pass it explicitly.
+ `http_error_mappers` are the orchestrator-plugin mappers to register a
+ transport handler per `exc_type` for — defaults to none (the agnostic base).
+ """
+ app = FastAPI()
+ register_exception_handlers(app, disclosure_mode=disclosure_mode, http_error_mappers=http_error_mappers)
+ app.include_router(_router)
+ return TestClient(RequestIdMiddleware(app), raise_server_exceptions=raise_server_exceptions)
+
+
+class TestExceptionHandlers:
+ def test_pipelex_error_produces_problem_json(self):
+ response = _build_client().get("/config-error")
+ assert response.status_code == 500
+ assert response.headers["content-type"] == PROBLEM_JSON_MEDIA_TYPE
+ body = response.json()
+ assert body["type"].endswith("/pipelex-config-error/")
+ assert body["title"] == "Pipelex config"
+ assert body["status"] == 500
+ assert body["detail"] == "the gateway config is missing"
+ assert body["error_type"] == "PipelexConfigError"
+ assert body["error_domain"] == "config"
+ assert body["instance"] == "/config-error"
+ assert body["request_id"] == response.headers[REQUEST_ID_HEADER]
+
+ def test_env_var_not_found_error_is_config_500(self):
+ # EnvVarNotFoundError is a ToolError that pipelex classifies under the
+ # config domain: a missing required env var is an operator-fixable
+ # misconfiguration, so it maps to HTTP 500 with error_domain "config".
+ response = _build_client().get("/env-error")
+ assert response.status_code == 500
+ body = response.json()
+ assert "COMPLETION_CALLBACK_SECRET" in body["detail"]
+ assert body["error_type"] == "EnvVarNotFoundError"
+ assert body["error_domain"] == "config"
+
+ def test_strict_disclosure_redacts_config_preserves_input(self):
+ # The handler forwards the disclosure mode it was registered under
+ # unchanged; pipelex owns the redaction. STRICT redacts a
+ # non-caller-facing message and keeps a caller-facing one.
+ client = _build_client(disclosure_mode=DisclosureMode.STRICT)
+
+ config_response = client.get("/config-error")
+ assert config_response.status_code == 500
+ assert config_response.json()["detail"] == INTERNAL_ERROR_PLACEHOLDER
+ assert "the gateway config is missing" not in config_response.text
+
+ input_response = client.get("/input-error")
+ assert input_response.status_code == 422
+ assert input_response.json()["detail"] == "your .mthds file has a syntax error on line 4"
+
+ def test_provider_rate_limit_emits_retry_after(self):
+ response = _build_client().get("/llm-error")
+ assert response.status_code == 429
+ assert response.headers["Retry-After"] == "12"
+ body = response.json()
+ assert body["error_type"] == "LLMCompletionError"
+ assert body["retryable"] is True
+ assert body["provider_metadata"]["status_code"] == 429
+
+ @pytest.mark.parametrize(
+ ("report_key", "expected_status", "expected_retry_after"),
+ [
+ ("finite", 429, "13"), # 12.4 rounds up
+ ("infinite", 429, None), # non-finite is dropped — no crash, no header
+ ("nan", 429, None), # non-finite is dropped — no crash, no header
+ ("negative", 429, "0"), # clamped to a non-negative integer
+ ("non_429", 500, None), # the hint never rides a non-429 response
+ ],
+ )
+ def test_retry_after_header_is_guarded(self, report_key: str, expected_status: int, expected_retry_after: str | None):
+ response = _build_client().get(f"/crafted-retry/{report_key}")
+ assert response.status_code == expected_status
+ if expected_retry_after is None:
+ assert "retry-after" not in response.headers
+ else:
+ assert response.headers["Retry-After"] == expected_retry_after
+
+ def test_unexpected_error_discloses_class_and_message_under_verbose(self):
+ # The catch-all honors the disclosure mode like every other handler.
+ # Under VERBOSE an unclassified failure is the one error a caller cannot
+ # diagnose from a request id alone, so `detail` names it outright —
+ # otherwise a deployment that opted into disclosure would still hit a
+ # dead end here.
+ response = _build_client(raise_server_exceptions=False).get("/unexpected-error")
+ assert response.status_code == 500
+ assert response.headers["content-type"] == PROBLEM_JSON_MEDIA_TYPE
+ body = response.json()
+ assert body["error_type"] == "InternalServerError"
+ assert body["error_domain"] == "runtime"
+ assert body["retryable"] is False
+ assert body["type"].endswith("/internal-server-error/")
+ assert body["instance"] == "/unexpected-error"
+ assert body["error_category"] == "unknown"
+ assert body["detail"] == "RuntimeError: something nobody anticipated"
+
+ def test_unexpected_error_is_sanitized_under_strict(self):
+ # STRICT still redacts: a deployment that wants nothing leaked keeps
+ # exactly the old sanitized body — no class name, no `str(exc)`.
+ client = _build_client(disclosure_mode=DisclosureMode.STRICT, raise_server_exceptions=False)
+ response = client.get("/unexpected-error")
+ assert response.status_code == 500
+ body = response.json()
+ assert body["error_type"] == "InternalServerError"
+ assert body["error_category"] == "unknown"
+ assert body["detail"] == "An unexpected error occurred. The request id is included for support."
+ assert "RuntimeError" not in response.text
+ assert "something nobody anticipated" not in response.text
+
+ def test_unexpected_error_never_leaks_a_traceback(self):
+ # Disclosure is the message, never the stack: a traceback stays an
+ # operator-log artifact in BOTH modes.
+ for mode in (DisclosureMode.VERBOSE, DisclosureMode.STRICT):
+ response = _build_client(disclosure_mode=mode, raise_server_exceptions=False).get("/unexpected-error")
+ assert "Traceback" not in response.text
+ assert "unexpected_error_route" not in response.text
+
+ def test_orchestrator_error_dispatch(self):
+ # The F3 seam: a synthetic plugin contributes a transport mapper through the registrar SPI,
+ # the app registers one handler per mapped exc_type, and a bare transport error renders the
+ # plugin's classified ErrorReport — all without importing any orchestrator SDK.
+ client = _build_client(http_error_mappers=_synthetic_http_error_mappers())
+
+ # An orchestrator failure that IS a PipelexError — routed to the PipelexError handler (its
+ # error_type is the class name), NOT the transport mapper handler.
+ pipelex_response = client.get("/orchestrator-pipelex-error")
+ assert pipelex_response.status_code == 500
+ assert pipelex_response.json()["error_type"] == "_SyntheticOrchestratorError"
+
+ # A bare transport error — routed to the plugin's mapper-backed handler, which renders the
+ # transport-transient classification the mapper produced.
+ transport_response = client.get("/synthetic-transport-error")
+ assert transport_response.status_code == 500
+ transport_body = transport_response.json()
+ assert transport_body["error_type"] == "SyntheticTransportError"
+ assert transport_body["error_category"] == "transient"
+ assert transport_body["retryable"] is True
+
+ def test_unmapped_transport_error_falls_back_to_catch_all_500(self):
+ # Without the orchestrator plugin's mapper (the agnostic base), the same bare transport error
+ # has no dedicated handler and collapses to the catch-all 500 — which under VERBOSE still
+ # tells the caller which transport class failed and why.
+ response = _build_client(raise_server_exceptions=False).get("/synthetic-transport-error")
+ assert response.status_code == 500
+ body = response.json()
+ assert body["error_type"] == "InternalServerError"
+ assert body["detail"] == "_SyntheticTransportError: orchestrator cluster unreachable"
+
+ def test_handler_of_handlers_catches_corrupt_report(self):
+ # When to_error_report() itself raises, the failure escapes the
+ # PipelexError handler; ServerErrorMiddleware funnels it into the
+ # catch-all — a real 500 body, never a bodyless default. The disclosed
+ # class is the one raised *by the broken handler*, not the original.
+ response = _build_client(raise_server_exceptions=False).get("/corrupt-error")
+ assert response.status_code == 500
+ body = response.json()
+ assert body["error_type"] == "InternalServerError"
+ assert body["error_category"] == "unknown"
+
+ @pytest.mark.parametrize(
+ ("method", "path", "json_body", "expected_status"),
+ [
+ ("GET", "/config-error", None, 500),
+ ("GET", "/env-error", None, 500),
+ ("GET", "/input-error", None, 422),
+ ("GET", "/llm-error", None, 429),
+ ("GET", "/orchestrator-pipelex-error", None, 500),
+ ("GET", "/synthetic-transport-error", None, 500),
+ ("GET", "/corrupt-error", None, 500),
+ ("GET", "/unexpected-error", None, 500),
+ # Cover the API-authored paths (`handle_api_error`) and FastAPI's
+ # automatic-validation path (`handle_request_validation_error`):
+ # the request-id propagation is the same structural property, but
+ # the three branches build the response document differently and
+ # are worth sweeping.
+ ("GET", "/api-input-error", None, 422),
+ ("GET", "/api-config-error", None, 500),
+ ("POST", "/needs-body", {"wrong": 1}, 422),
+ ],
+ )
+ def test_request_id_present_on_every_error_response(
+ self,
+ method: str,
+ path: str,
+ json_body: dict[str, Any] | None,
+ expected_status: int,
+ ):
+ response = _build_client(raise_server_exceptions=False).request(method, path, json=json_body)
+ assert response.status_code == expected_status
+ request_id = response.headers[REQUEST_ID_HEADER]
+ assert _ULID_RE.match(request_id) is not None
+ assert response.json()["request_id"] == request_id
+
+ def test_inbound_request_id_is_echoed(self):
+ response = _build_client().get("/config-error", headers={REQUEST_ID_HEADER: "inbound-correlation-007"})
+ assert response.headers[REQUEST_ID_HEADER] == "inbound-correlation-007"
+ assert response.json()["request_id"] == "inbound-correlation-007"
+
+ def test_api_authored_500_emits_structured_error_record(self, mocker: MockerFixture):
+ # Without `handle_api_error` logging, an `ApiError`-shaped 500 produces
+ # zero operator output (`/version`'s `PackageNotFoundError →
+ # raise_internal_server_error` is the canonical silent case). Assert
+ # the handler emits one `api_error` record at `error` level whose fields
+ # mirror the response — the same set `_log_error_report` ships for a
+ # pipelex-derived 500, so a downstream sink queries them uniformly.
+ log_spy = mocker.patch("pipelex_api.exception_handlers.log")
+ response = _build_client().get("/api-config-error")
+ assert response.status_code == 500
+ log_spy.error.assert_called_once()
+ fields = _emitted_fields(log_spy, as_error=True)
+ assert fields["event"] == API_ERROR_EVENT
+ assert fields["status"] == 500
+ assert fields["error_type"] == "ServerMisconfigured"
+ assert fields["error_domain"] == "config"
+ assert fields["retryable"] is False
+ assert fields["route"] == "/api-config-error"
+ # The operator-facing cause rides a field of its own and never reaches the message, which
+ # is what stops a crafted value from shaping the rendered line at all.
+ assert fields["detail"] == "the configuration is broken"
+ assert log_spy.error.call_args.kwargs["include_exception"] is True
+ log_spy.warning.assert_not_called()
+
+ def test_api_authored_4xx_emits_structured_warning_record(self, mocker: MockerFixture):
+ # Mirror at the warning level: an INPUT-domain `ApiError` is a caller
+ # mistake, not an operator fault, so it logs at `warning` without a
+ # traceback — same disposition rule `_log_error_report` uses.
+ log_spy = mocker.patch("pipelex_api.exception_handlers.log")
+ response = _build_client().get("/api-input-error")
+ assert response.status_code == 422
+ log_spy.warning.assert_called_once()
+ fields = _emitted_fields(log_spy, as_error=False)
+ assert fields["event"] == API_ERROR_EVENT
+ assert fields["status"] == 422
+ assert fields["error_type"] == "ValidationError"
+ assert fields["error_domain"] == "input"
+ assert fields["retryable"] is False
+ assert fields["detail"] == "a caller-side mistake"
+ log_spy.error.assert_not_called()
+
+ def test_the_summary_message_names_the_status_and_the_error_type(self, mocker: MockerFixture):
+ # The message is built from server-authored values alone, so it stays a stable sentence
+ # whatever a caller sent; everything variable is a field beside it.
+ log_spy = mocker.patch("pipelex_api.exception_handlers.log")
+ assert _build_client().get("/api-config-error").status_code == 500
+ assert log_spy.error.call_args.args[0] == "API error 500: ServerMisconfigured"
+
+ def test_user_id_rides_authenticated_pipelex_error_record(self, mocker: MockerFixture):
+ # Phase 3 deleted the per-route `log.error(... user=...)` lines on
+ # storage / pipeline-backend failures; the global handler now reads
+ # `request.state.user` so the operator can still tie a `PipelexError`
+ # to the caller through the record alone — no correlating across
+ # records on `request_id` required.
+ log_spy = mocker.patch("pipelex_api.exception_handlers.log")
+ response = _build_client().get("/authenticated-config-error")
+ assert response.status_code == 500
+ log_spy.error.assert_called_once()
+ fields = _emitted_fields(log_spy, as_error=True)
+ assert fields["user_id"] == _TEST_USER_ID
+ assert fields["error_type"] == "PipelexConfigError"
+
+ def test_user_id_rides_authenticated_api_authored_record(self, mocker: MockerFixture):
+ # `handle_api_error` covers the API-authored 4xx surface (storage's
+ # `raise_bad_request`, `raise_forbidden`, `raise_payload_too_large`;
+ # uploader's same set). It must ride the same `user_id` correlation
+ # `_log_error_report` does so the contract is uniform — a caller
+ # mistake and a backend failure both name the caller.
+ log_spy = mocker.patch("pipelex_api.exception_handlers.log")
+ response = _build_client().get("/authenticated-api-input-error")
+ assert response.status_code == 422
+ log_spy.warning.assert_called_once()
+ fields = _emitted_fields(log_spy, as_error=False)
+ assert fields["user_id"] == _TEST_USER_ID
+ assert fields["error_type"] == "ValidationError"
+
+ def test_user_id_rides_authenticated_unexpected_error_record(self, mocker: MockerFixture):
+ # The catch-all 500 (`handle_unexpected_error`) is the one place a
+ # missing `user_id` is most expensive — by definition the failure
+ # was not classifiable upstream — so the same enrichment fires here.
+ log_spy = mocker.patch("pipelex_api.exception_handlers.log")
+ response = _build_client(raise_server_exceptions=False).get("/authenticated-unexpected-error")
+ assert response.status_code == 500
+ log_spy.error.assert_called_once()
+ fields = _emitted_fields(log_spy, as_error=True)
+ assert fields["user_id"] == _TEST_USER_ID
+ assert fields["error_type"] == "RuntimeError"
+
+ def test_user_id_absent_from_unauthenticated_error_record(self, mocker: MockerFixture):
+ # Pre-auth paths, and a deployment with no user model, have no `request.state.user`;
+ # `_user_id_of` returns `None` and `_emit_api_error` drops `None`-valued fields, so the
+ # record carries no `user_id` attribute at all — never a null, which a query filtering on
+ # presence would read as an answer.
+ log_spy = mocker.patch("pipelex_api.exception_handlers.log")
+ response = _build_client().get("/config-error")
+ assert response.status_code == 500
+ log_spy.error.assert_called_once()
+ assert "user_id" not in _emitted_fields(log_spy, as_error=True)
+
+ def test_run_state_rides_pipelex_error_record(self, mocker: MockerFixture):
+ # `_parse_request` binds `pipe_code` / `pipeline_run_id` on
+ # `request.state` so a downstream pipelex failure is tied to the
+ # specific pipe and run id without each backend frame having to forward
+ # them. Same mechanism as `user_id` (request.state + a `_*_of` getter
+ # in the handler), now extended to the body-derived identifiers — the
+ # last piece of Checkpoint B reconciliation #4.
+ log_spy = mocker.patch("pipelex_api.exception_handlers.log")
+ response = _build_client().get("/pipeline-state-pipelex-error")
+ assert response.status_code == 500
+ log_spy.error.assert_called_once()
+ fields = _emitted_fields(log_spy, as_error=True)
+ assert fields["pipe_code"] == _TEST_PIPE_CODE
+ assert fields["pipeline_run_id"] == _TEST_RUN_ID
+ assert fields["error_type"] == "PipelexConfigError"
+
+ def test_run_state_rides_api_authored_record(self, mocker: MockerFixture):
+ # API-authored 4xx surface: `raise_validation_error` raised from a
+ # route that has already bound pipe state must ship the same fields,
+ # so the operator record is uniform across the validation and the
+ # pipelex-domain failure surfaces.
+ log_spy = mocker.patch("pipelex_api.exception_handlers.log")
+ response = _build_client().get("/pipeline-state-api-input-error")
+ assert response.status_code == 422
+ log_spy.warning.assert_called_once()
+ fields = _emitted_fields(log_spy, as_error=False)
+ assert fields["pipe_code"] == _TEST_PIPE_CODE
+ assert fields["pipeline_run_id"] == _TEST_RUN_ID
+ assert fields["error_type"] == "ValidationError"
+
+ def test_run_state_rides_unexpected_error_record(self, mocker: MockerFixture):
+ # The catch-all 500 is the most operationally expensive case for a
+ # missing pipe-state field — by definition the failure was not
+ # classifiable upstream, so the identifiers on the record are the
+ # operator's only starting point for which pipe and which run were
+ # in flight.
+ log_spy = mocker.patch("pipelex_api.exception_handlers.log")
+ response = _build_client(raise_server_exceptions=False).get("/pipeline-state-unexpected-error")
+ assert response.status_code == 500
+ log_spy.error.assert_called_once()
+ fields = _emitted_fields(log_spy, as_error=True)
+ assert fields["pipe_code"] == _TEST_PIPE_CODE
+ assert fields["pipeline_run_id"] == _TEST_RUN_ID
+ assert fields["error_type"] == "RuntimeError"
+
+ def test_run_state_absent_when_parse_request_did_not_bind(self, mocker: MockerFixture):
+ # A route that didn't go through `_parse_request` (here: `/config-error`,
+ # a GET that never touches the body) has no `pipe_code` /
+ # `pipeline_run_id` on `request.state`. The getters return `None` and
+ # `_emit_api_error` drops those, so the record carries neither attribute.
+ # Same defensive posture as `test_user_id_absent_from_unauthenticated_error_record`.
+ log_spy = mocker.patch("pipelex_api.exception_handlers.log")
+ response = _build_client().get("/config-error")
+ assert response.status_code == 500
+ log_spy.error.assert_called_once()
+ fields = _emitted_fields(log_spy, as_error=True)
+ assert "pipe_code" not in fields
+ assert "pipeline_run_id" not in fields
+
+ def test_request_validation_error_emits_structured_warning_record(self, mocker: MockerFixture):
+ # FastAPI's automatic-validation 422 goes through
+ # `handle_request_validation_error`, not `handle_api_error`, but emits
+ # the same `api_error` record so the surface is uniform — whichever code
+ # path rejects a caller-input failure, the operator record is identical.
+ log_spy = mocker.patch("pipelex_api.exception_handlers.log")
+ # `{"wrong": 1}` triggers FastAPI's automatic validation failure on
+ # `_RequestValidationBody`: `field` is missing AND `wrong` is an
+ # extra key (the body uses `extra="forbid"`, so the extra-key path
+ # actually fires — Pydantic's default `extra="ignore"` would have
+ # left only the missing-field error).
+ response = _build_client().post("/needs-body", json={"wrong": 1})
+ assert response.status_code == 422
+ log_spy.warning.assert_called_once()
+ fields = _emitted_fields(log_spy, as_error=False)
+ assert fields["event"] == API_ERROR_EVENT
+ assert fields["status"] == 422
+ assert fields["error_type"] == "ValidationError"
+ assert fields["error_domain"] == "input"
+ # The summary covers both per-field failures the request triggered.
+ assert "field" in fields["detail"]
+ assert "wrong" in fields["detail"]
+ log_spy.error.assert_not_called()
+
+ @pytest.mark.parametrize(
+ "crafted_detail",
+ [
+ # A newline in the detail used to forge a second log line entirely — the worst case
+ # for newline-delimited shippers (Loki, journald, CloudWatch) back when the API
+ # flattened its own fields into one `key=value` run.
+ "legit\nstatus=200 event=auth_success",
+ # Whitespace plus `key=value` runs were the canonical logfmt forge.
+ "hijack status=200 event=fake",
+ # A carriage return alone was enough to corrupt a CRLF shipper.
+ "legit\rstatus=200",
+ # A bare quote used to close the quoted region early in a permissive parser.
+ 'has " a quote = inside',
+ ],
+ )
+ def test_crafted_detail_stays_one_field_and_shapes_no_other(self, mocker: MockerFixture, crafted_detail: str) -> None:
+ # `_log_api_authored_error` ships `document["detail"]`, and `detail` originates from caller
+ # input on several routes (`raise_validation_error(str(exc))`, callback-URL rejections,
+ # `_summarize_request_validation_error`'s per-field messages). The API renders none of it
+ # any more: the value is handed to the runtime as one field, so it cannot forge a sibling
+ # field and cannot reach the message, and the selected sink is what escapes it on the way
+ # out. Pin that at the handler, so a route shipping some new caller-controlled field later
+ # is covered without re-auditing this surface.
+ log_spy = mocker.patch("pipelex_api.exception_handlers.log")
+ response = _build_client().get("/crafted-detail", params={"detail": crafted_detail})
+ assert response.status_code == 422
+ fields = _emitted_fields(log_spy, as_error=False)
+ assert fields["detail"] == crafted_detail, f"the value was altered on the way to the record: {fields['detail']!r}"
+ assert fields["event"] == API_ERROR_EVENT, "a crafted detail overwrote a legitimate field"
+ assert fields["status"] == 422, "a crafted detail overwrote a legitimate field"
+ message = log_spy.warning.call_args.args[0]
+ assert crafted_detail not in message, f"caller input reached the message: {message!r}"
+
+ def test_async_execution_not_enabled_maps_to_501(self):
+ # The pipelex-side ``AsyncExecutionNotEnabledError`` reports as
+ # ``CONFIG``-domain (-> 500 under the default mapping), but the
+ # API layer overrides it to 501 Not Implemented. 501 is more precise
+ # for "this server does not provide async execution": it tells clients
+ # the failure is permanent under the current deployment rather than a
+ # transient runtime fault.
+ response = _build_client().get("/async-execution-not-enabled")
+ assert response.status_code == 501
+ assert response.headers["content-type"] == PROBLEM_JSON_MEDIA_TYPE
+ body = response.json()
+ # The body's ``status`` member must agree with the HTTP status — if
+ # the override path only bumped the header status and left the body at
+ # 500, RFC 7807-aware clients would see a contradictory document.
+ assert body["status"] == 501
+ assert body["title"] == "Async execution not enabled"
+ assert body["error_type"] == "AsyncExecutionNotEnabledError"
+ assert body["error_domain"] == "config"
+ assert body["instance"] == "/async-execution-not-enabled"
+ assert body["type"].endswith("/async-execution-not-enabled-error/")
+ assert body["request_id"] == response.headers[REQUEST_ID_HEADER]
+
+ def test_async_execution_not_enabled_logs_post_override_status(self, mocker: MockerFixture):
+ # ``_log_error_report`` receives the overridden status so the operator
+ # record agrees with what the client actually saw. Without the
+ # ``status=`` plumbing the record would carry 500 (the report's domain
+ # default) while the response shipped 501 — a silent disagreement
+ # between the two surfaces. Pin the alignment.
+ log_spy = mocker.patch("pipelex_api.exception_handlers.log")
+ response = _build_client().get("/async-execution-not-enabled")
+ assert response.status_code == 501
+ log_spy.error.assert_called_once()
+ fields = _emitted_fields(log_spy, as_error=True)
+ assert fields["event"] == API_ERROR_EVENT
+ assert fields["status"] == 501
+ assert fields["error_type"] == "AsyncExecutionNotEnabledError"
+ assert fields["error_domain"] == "config"
+
+ def test_pipeline_run_id_conflict_maps_to_409(self):
+ # ``PipelineManagerAlreadyExistsError`` carries no ``error_domain``
+ # (-> 500 under the default mapping), but a duplicate ``pipeline_run_id``
+ # is a client-visible conflict, not a server fault: the API overrides it
+ # to 409 Conflict so callers can tell "this id is currently in use"
+ # (resubmit after the in-flight run finishes, or pick a fresh id) apart
+ # from a real internal failure.
+ response = _build_client().get("/pipeline-run-id-conflict")
+ assert response.status_code == 409
+ assert response.headers["content-type"] == PROBLEM_JSON_MEDIA_TYPE
+ body = response.json()
+ # The body's ``status`` member must agree with the HTTP status (same
+ # RFC 7807 agreement contract as the 501 override above).
+ assert body["status"] == 409
+ assert body["error_type"] == "PipelineManagerAlreadyExistsError"
+ assert body["title"] == "Pipeline manager already exists"
+ assert body["instance"] == "/pipeline-run-id-conflict"
+ assert body["type"].endswith("/pipeline-manager-already-exists-error/")
+ assert body["request_id"] == response.headers[REQUEST_ID_HEADER]
+
+ def test_pipeline_run_id_conflict_logs_at_warning_post_override_status(self, mocker: MockerFixture):
+ # A duplicate pipeline_run_id is a client-visible 409 conflict, not a
+ # server fault: disposition is keyed off the final HTTP status, so it
+ # logs at `warning` without a traceback — never `error` (which would
+ # page or pollute error dashboards for a normal conflict). The record
+ # still agrees with the status the client saw.
+ log_spy = mocker.patch("pipelex_api.exception_handlers.log")
+ response = _build_client().get("/pipeline-run-id-conflict")
+ assert response.status_code == 409
+ log_spy.warning.assert_called_once()
+ log_spy.error.assert_not_called()
+ fields = _emitted_fields(log_spy, as_error=False)
+ assert fields["event"] == API_ERROR_EVENT
+ assert fields["status"] == 409
+ assert fields["error_type"] == "PipelineManagerAlreadyExistsError"
diff --git a/api/tests/unit/test_execute_dispatch.py b/api/tests/unit/test_execute_dispatch.py
new file mode 100644
index 000000000..3c444f042
--- /dev/null
+++ b/api/tests/unit/test_execute_dispatch.py
@@ -0,0 +1,374 @@
+"""`/execute` dispatches by orchestration_mode through the OrchestratorRegistry (full synchronous output).
+
+Pins the dispatch + output-mapping independent of any real backend, with a stub orchestrator: the
+runner resolves the deployment's orchestration_mode, dispatches the locally-built PipeJob through the
+orchestrator the registry holds for it with `DeliveryMode.BLOCKING`, and rehydrates the orchestrator's
+JSON-safe output back into the full PipeOutput the `/execute` response wraps — exercising the real
+serialize -> rehydrate round-trip (`serialize_completed_output` -> `hydrate_working_memory`), including
+the `graph_spec` and `pipe_io_artifacts` `strict=False` re-validation branches. Also pins the policy-gated per-request override
+(symmetric with `/start`), the no-orchestrator case (`MissingOrchestratorError`), and the request id reaching the job the
+orchestrator is handed, which is the payload a Temporal worker deserializes and binds its log context from. The boot slot is
+never used — every mode dispatches through the per-call registry. (Delivery is endpoint-set, never
+requestable, so `/execute` has no fire-and-forget refusal — that axis is `/start`'s.)
+"""
+
+from datetime import UTC, datetime
+from typing import Any
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+from mthds.protocol.input_form import PipeInputFormDescriptor, TextField
+from mthds.protocol.output_form import PipeOutputFormDescriptor
+from mthds.protocol.pipe_io_contracts import (
+ IOMultiplicity,
+ PipeInputContract,
+ PipeIOContract,
+ PipeOutputContract,
+ PresenceMarker,
+)
+from pipelex.core.memory.working_memory import MAIN_STUFF_NAME
+from pipelex.core.pipes.pipe_io_artifacts import PipeIOArtifacts
+from pipelex.core.pipes.pipe_output import PipeOutput
+from pipelex.graph.graphspec import GraphSpec
+from pipelex.pipe_run.delivery_assignment import DeliveryAssignment
+from pipelex.pipe_run.pipe_job import PipeJob
+from pipelex.plugins.orchestrator_registry import OrchestratorRegistry
+from pipelex.runtime_bridge.exceptions import MissingOrchestratorError
+from pipelex.runtime_bridge.payloads import PipelexPipeDispatchAck, PipelexPipeRunOutput
+from pipelex.runtime_bridge.serialization import serialize_completed_output
+from pytest_mock import MockerFixture
+
+from pipelex_api.api_config import ApiConfig
+from pipelex_api.exception_handlers import register_exception_handlers
+from pipelex_api.middleware import REQUEST_ID_HEADER, RequestIdMiddleware
+from pipelex_api.routes import router as api_router
+from pipelex_api.routes.pipelex.pipeline import ApiRunner
+from tests.unit._constants import VALID_MTHDS
+
+_PIPELINE_NS = "pipelex_api.routes.pipelex.pipeline"
+
+
+class _StubOrchestrator:
+ """A backend-agnostic stand-in orchestrator: echoes the job's working memory back as completed output.
+
+ Returning via `serialize_completed_output` is the point — it produces the real JSON-safe
+ `PipelexPipeRunOutput` (the same shape that crosses the Temporal worker boundary), so the route
+ exercises the production serialize -> rehydrate round-trip instead of a hand-built payload. It
+ records each dispatch so a test can assert `/execute` drove the blocking `execute` arm, and what the
+ dispatched job's `RunMetadata` carries, since that is all a worker ever learns of the request. `start` (the
+ fire-and-forget arm) is present only to satisfy the protocol — `/execute` never calls it.
+ """
+
+ def __init__(
+ self,
+ *,
+ graph_spec: GraphSpec | None = None,
+ pipe_io_artifacts: PipeIOArtifacts | None = None,
+ pipe_io_artifacts_error: str | None = None,
+ supports_fire_and_forget: bool = False,
+ ) -> None:
+ self.calls: list[dict[str, Any]] = []
+ self._graph_spec = graph_spec
+ self._pipe_io_artifacts = pipe_io_artifacts
+ self._pipe_io_artifacts_error = pipe_io_artifacts_error
+ self.supports_fire_and_forget = supports_fire_and_forget
+
+ async def execute(self, *, pipe_job: PipeJob, delivery_assignment: DeliveryAssignment | None) -> PipelexPipeRunOutput:
+ self.calls.append(
+ {
+ "pipe_code": pipe_job.pipe.code,
+ "delivery_assignment": delivery_assignment,
+ "request_id": pipe_job.job_metadata.run_metadata.request_id,
+ }
+ )
+ # A completed run always delivers a main stuff (pipelex invariant; enforced by
+ # `resolve_main_stuff_root_key` in both `serialize_completed_output` and `from_pipe_output`).
+ # This stub is an echo: promote the job's input stuff to the run's main stuff via the
+ # `main_stuff` alias, so the serialize -> rehydrate round-trip yields a valid completed memory.
+ working_memory = pipe_job.get_working_memory()
+ working_memory.set_alias(alias=MAIN_STUFF_NAME, target=next(iter(working_memory.root)))
+ return serialize_completed_output(
+ pipe_output=PipeOutput(
+ working_memory=working_memory,
+ pipeline_run_id=pipe_job.job_metadata.run_metadata.pipeline_run_id,
+ graph_spec=self._graph_spec,
+ pipe_io_artifacts=self._pipe_io_artifacts,
+ pipe_io_artifacts_error=self._pipe_io_artifacts_error,
+ ),
+ workflow_id=None,
+ )
+
+ async def start(self, *, pipe_job: PipeJob, delivery_assignment: DeliveryAssignment | None) -> PipelexPipeDispatchAck:
+ msg = "/execute drives the blocking `execute` arm; `start` must not be reached."
+ raise NotImplementedError(msg)
+
+
+def _echo_pipe_io_artifacts() -> PipeIOArtifacts:
+ """The I/O artifacts a run of the echo bundle would carry, keyed by its `pipe_ref`.
+
+ Minimal but real: each of the carrier's members is the standard's own artifact type, so the
+ dump the orchestrator produces is the shape a live run produces, not a stand-in dict.
+ """
+ return PipeIOArtifacts(
+ pipe_io_contracts={
+ "echo.echo": PipeIOContract(
+ inputs={
+ "text": PipeInputContract(
+ concept_ref="native.Text",
+ presence=PresenceMarker.PLAIN,
+ multiplicity=IOMultiplicity.SINGLE,
+ item_count=None,
+ json_schema={"type": "string"},
+ )
+ },
+ output=PipeOutputContract(
+ concept_ref="native.Text",
+ multiplicity=IOMultiplicity.SINGLE,
+ item_count=None,
+ optional=False,
+ json_schema={"type": "string"},
+ ),
+ )
+ },
+ input_form={
+ "echo.echo": PipeInputFormDescriptor(fields=[TextField(name="text", required=True, presence=PresenceMarker.PLAIN, gating=False)])
+ },
+ output_form={"echo.echo": PipeOutputFormDescriptor(field=TextField(name="result", required=True))},
+ )
+
+
+def _build_client(*, with_request_id_middleware: bool = False) -> TestClient:
+ """Wire the real routes; `with_request_id_middleware` wraps the app the way `pipelex_api.main` does."""
+ app = FastAPI()
+ app.include_router(api_router, prefix="/v1")
+ register_exception_handlers(app)
+ return TestClient(RequestIdMiddleware(app) if with_request_id_middleware else app)
+
+
+def _register_stub(mocker: MockerFixture, *, mode: str, stub: _StubOrchestrator) -> None:
+ """Patch the orchestrator registry so the route's mode lookup finds `stub` for `mode`."""
+ registry = OrchestratorRegistry({mode: stub})
+ mocker.patch(f"{_PIPELINE_NS}.get_orchestrator_registry", return_value=registry)
+
+
+def _force_config(mocker: MockerFixture, *, mode: str, allow_override: bool) -> None:
+ """Patch the api config so `resolve_orchestration_mode` sees `mode` as the deployment default + policy."""
+ config = ApiConfig(orchestration_mode=mode, allow_request_orchestration_mode_override=allow_override)
+ mocker.patch(f"{_PIPELINE_NS}.get_api_config", return_value=config)
+
+
+class TestExecuteDispatch:
+ def test_direct_dispatch_returns_rehydrated_full_output(self, mocker: MockerFixture) -> None:
+ """`direct` (the packaged default) dispatches through the registry and returns the full output."""
+ stub = _StubOrchestrator()
+ _register_stub(mocker, mode="direct", stub=stub)
+
+ client = _build_client()
+ response = client.post(
+ "/v1/execute",
+ json={"pipe_code": "echo", "mthds_contents": [VALID_MTHDS], "inputs": {"text": "hello"}},
+ )
+
+ assert response.status_code == 200, response.text
+ body = response.json()
+ assert body["state"] == "COMPLETED"
+ # The full output survived the serialize -> rehydrate round-trip: the echo input is in the
+ # rehydrated working memory the /execute response wraps.
+ root = body["pipe_output"]["working_memory"]["root"]
+ assert root["text"]["content"]["text"] == "hello"
+ # The dispatch reached the registered orchestrator's blocking `execute` arm; /execute is
+ # synchronous, so no delivery target (never the caller's to choose).
+ assert len(stub.calls) == 1
+ assert stub.calls[0]["delivery_assignment"] is None
+
+ def test_graph_spec_survives_strict_false_rehydration(self, mocker: MockerFixture) -> None:
+ """A non-None graph_spec round-trips through the helper's `strict=False` reverse of `model_dump(mode="json")`.
+
+ Pins the most subtle line of `_pipe_output_from_run_output`: the orchestrator dumps `graph_spec`
+ in JSON mode (so `GraphSpec.created_at`, a `strict=True` datetime, becomes an ISO string), and the
+ helper must re-validate it with `strict=False` to restore the typed `GraphSpec`. Without the
+ graph_spec branch exercised, a regression there (strict default, wrong key) would stay green.
+ """
+ graph_spec = GraphSpec(graph_id="g-1", created_at=datetime(2026, 1, 2, 3, 4, 5, tzinfo=UTC))
+ stub = _StubOrchestrator(graph_spec=graph_spec)
+ _register_stub(mocker, mode="direct", stub=stub)
+
+ client = _build_client()
+ response = client.post(
+ "/v1/execute",
+ json={"pipe_code": "echo", "mthds_contents": [VALID_MTHDS], "inputs": {"text": "hello"}},
+ )
+
+ assert response.status_code == 200, response.text
+ # The graph_spec survived the dump -> strict=False re-validation: it is present in the response.
+ assert response.json()["pipe_output"]["graph_spec"]["graph_id"] == "g-1"
+
+ def test_pipe_io_artifacts_survive_strict_false_rehydration(self, mocker: MockerFixture) -> None:
+ """A non-None `pipe_io_artifacts` reaches the `/execute` response beside `graph_spec`.
+
+ The rule the design ratified is "wherever the graph travels, its description travels with
+ it": the runtime fills `pipe_io_artifacts_dump` on the SPI payload exactly as it fills
+ `graph_spec_dump`, and this repo is the only reader that puts it back on the public wire.
+ Pins the carrier under its own key, so a dropped or misnamed key cannot stay green while
+ the OpenAPI artifact still advertises the field. The error slot is `null` here only
+ because the build succeeded; what pins *that* key is the failed-build test below, since a
+ `null` assertion alone is also satisfied by the field's own default.
+ """
+ stub = _StubOrchestrator(pipe_io_artifacts=_echo_pipe_io_artifacts())
+ _register_stub(mocker, mode="direct", stub=stub)
+
+ client = _build_client()
+ response = client.post(
+ "/v1/execute",
+ json={"pipe_code": "echo", "mthds_contents": [VALID_MTHDS], "inputs": {"text": "hello"}},
+ )
+
+ assert response.status_code == 200, response.text
+ pipe_output = response.json()["pipe_output"]
+ artifacts = pipe_output["pipe_io_artifacts"]
+ # All three members survived the dump -> strict=False re-validation, under the standard's names.
+ assert artifacts["pipe_io_contracts"]["echo.echo"]["output"]["concept_ref"] == "native.Text"
+ assert artifacts["input_form"]["echo.echo"]["fields"][0]["name"] == "text"
+ assert artifacts["output_form"]["echo.echo"]["field"]["name"] == "result"
+ # The error slot rides along, null when the build succeeded (a host must tell that apart
+ # from "the build failed", exactly as it does for the graph).
+ assert pipe_output["pipe_io_artifacts_error"] is None
+
+ def test_pipe_io_artifacts_error_reaches_the_wire(self, mocker: MockerFixture) -> None:
+ """A failed artifact build is reported on the wire, and does not cost the run its result.
+
+ Upstream builds the artifacts best-effort in a `finally` ahead of delivery and swallows
+ whatever the builders raise onto `pipe_io_artifacts_error`, so the only way a caller can
+ tell "the build failed" from "no artifacts were requested" is that field arriving non-null
+ beside a `null` carrier. This is what actually pins the key through the SPI round-trip:
+ asserting it is `null` on a successful run would pass just as well if the route stopped
+ mapping it altogether.
+ """
+ message = "Failed to build the I/O artifacts for pipeline_run_id=run-1: contract will not render"
+ stub = _StubOrchestrator(pipe_io_artifacts_error=message)
+ _register_stub(mocker, mode="direct", stub=stub)
+
+ client = _build_client()
+ response = client.post(
+ "/v1/execute",
+ json={"pipe_code": "echo", "mthds_contents": [VALID_MTHDS], "inputs": {"text": "hello"}},
+ )
+
+ assert response.status_code == 200, response.text
+ pipe_output = response.json()["pipe_output"]
+ assert pipe_output["pipe_io_artifacts_error"] == message
+ # A failed description never invalidates the run: the carrier is null and the result stands.
+ assert pipe_output["pipe_io_artifacts"] is None
+ assert response.json()["state"] == "COMPLETED"
+
+ def test_pipe_io_artifacts_absent_when_the_run_carried_none(self, mocker: MockerFixture) -> None:
+ """A run that built no artifacts yields a null carrier, not a missing key or a fabricated empty one."""
+ stub = _StubOrchestrator()
+ _register_stub(mocker, mode="direct", stub=stub)
+
+ client = _build_client()
+ response = client.post(
+ "/v1/execute",
+ json={"pipe_code": "echo", "mthds_contents": [VALID_MTHDS], "inputs": {"text": "hello"}},
+ )
+
+ assert response.status_code == 200, response.text
+ pipe_output = response.json()["pipe_output"]
+ assert pipe_output["pipe_io_artifacts"] is None
+ assert pipe_output["pipe_io_artifacts_error"] is None
+
+ def test_per_request_override_honored_when_policy_allows(self, mocker: MockerFixture) -> None:
+ """With override ON, a per-request orchestration_mode is resolved and dispatched (symmetric with /start)."""
+ _force_config(mocker, mode="direct", allow_override=True)
+ stub = _StubOrchestrator()
+ _register_stub(mocker, mode="temporal", stub=stub)
+
+ client = _build_client()
+ response = client.post(
+ "/v1/execute",
+ json={
+ "pipe_code": "echo",
+ "mthds_contents": [VALID_MTHDS],
+ "inputs": {"text": "hello"},
+ "orchestration_mode": "temporal",
+ },
+ )
+
+ assert response.status_code == 200, response.text
+ # The requested (non-default) backend was honored: dispatch reached the temporal-keyed stub.
+ assert len(stub.calls) == 1
+
+ def test_forbidden_orchestration_mode_override_is_a_403(self) -> None:
+ """The route threads orchestration_mode into the same override policy /start uses: a forbidden override is a 403."""
+ client = _build_client()
+ # Packaged default is `direct` with override OFF; forcing a different backend is refused before dispatch.
+ response = client.post(
+ "/v1/execute",
+ json={
+ "pipe_code": "echo",
+ "mthds_contents": [VALID_MTHDS],
+ "inputs": {"text": "hello"},
+ "orchestration_mode": "temporal",
+ },
+ )
+
+ assert response.status_code == 403, response.text
+ assert response.headers["content-type"].startswith("application/problem+json")
+ assert response.json()["error_type"] == "OrchestrationModeOverrideForbidden"
+
+ def test_inbound_request_id_reaches_the_dispatched_job(self, mocker: MockerFixture) -> None:
+ """On a `temporal` deployment, the inbound `X-Request-ID` rides the job the orchestrator is handed.
+
+ A worker never sees the request: it binds its log context from the deserialized job's
+ `RunMetadata.request_id`, and the middleware's in-process binding does not cross to it. So
+ the proof is the payload, not the runner call — a route that passed the id to a runner which
+ dropped it would still leave every worker line of the run without one.
+ """
+ _force_config(mocker, mode="temporal", allow_override=False)
+ stub = _StubOrchestrator()
+ _register_stub(mocker, mode="temporal", stub=stub)
+ inbound_request_id = "01HNJZ4XR7K3Q9D8MWAQ7FY2E5"
+
+ client = _build_client(with_request_id_middleware=True)
+ response = client.post(
+ "/v1/execute",
+ json={"pipe_code": "echo", "mthds_contents": [VALID_MTHDS], "inputs": {"text": "hello"}},
+ headers={REQUEST_ID_HEADER: inbound_request_id},
+ )
+
+ assert response.status_code == 200, response.text
+ assert response.headers[REQUEST_ID_HEADER] == inbound_request_id
+ assert len(stub.calls) == 1
+ assert stub.calls[0]["request_id"] == inbound_request_id
+
+ def test_minted_request_id_reaches_the_dispatched_job(self, mocker: MockerFixture) -> None:
+ """Without an inbound header, the job carries the id the middleware minted, which the response echoes."""
+ stub = _StubOrchestrator()
+ _register_stub(mocker, mode="direct", stub=stub)
+
+ client = _build_client(with_request_id_middleware=True)
+ response = client.post(
+ "/v1/execute",
+ json={"pipe_code": "echo", "mthds_contents": [VALID_MTHDS], "inputs": {"text": "hello"}},
+ )
+
+ assert response.status_code == 200, response.text
+ minted_request_id = response.headers[REQUEST_ID_HEADER]
+ assert minted_request_id
+ assert len(stub.calls) == 1
+ assert stub.calls[0]["request_id"] == minted_request_id
+
+ @pytest.mark.asyncio
+ async def test_missing_orchestrator_for_resolved_mode_raises(self, mocker: MockerFixture) -> None:
+ """A resolved mode with no registered orchestrator fails loud with MissingOrchestratorError."""
+ mocker.patch(f"{_PIPELINE_NS}.get_orchestrator_registry", return_value=OrchestratorRegistry({}))
+
+ with pytest.raises(MissingOrchestratorError) as exc_info:
+ await ApiRunner().execute(
+ pipe_code="echo",
+ mthds_contents=[VALID_MTHDS],
+ inputs={"text": "hello"},
+ )
+ # The packaged default is `direct`; the empty registry holds no orchestrator for it.
+ assert exc_info.value.mode == "direct"
diff --git a/api/tests/unit/test_license_copy.py b/api/tests/unit/test_license_copy.py
new file mode 100644
index 000000000..a9dcf73ec
--- /dev/null
+++ b/api/tests/unit/test_license_copy.py
@@ -0,0 +1,20 @@
+"""The server's `LICENSE` is a copy of the repository's, and must stay one.
+
+A distribution carries license files only from inside its own project directory, and a symlink would
+dangle in the sdist, so `pipelex-api` ships a real copy of the repository's `LICENSE` beside its
+`pyproject.toml`. This keeps the copy from drifting when the original changes.
+"""
+
+from pathlib import Path
+
+_MEMBER_ROOT = Path(__file__).resolve().parents[2]
+_REPOSITORY_ROOT = _MEMBER_ROOT.parent
+
+
+class TestLicenseCopy:
+ def test_member_license_is_the_repository_license(self) -> None:
+ member_license = _MEMBER_ROOT / "LICENSE"
+ repository_license = _REPOSITORY_ROOT / "LICENSE"
+ assert member_license.read_bytes() == repository_license.read_bytes(), (
+ f"{member_license} differs from {repository_license}: copy the repository's LICENSE over it."
+ )
diff --git a/api/tests/unit/test_method_cache.py b/api/tests/unit/test_method_cache.py
new file mode 100644
index 000000000..0fc08cafa
--- /dev/null
+++ b/api/tests/unit/test_method_cache.py
@@ -0,0 +1,148 @@
+"""Unit tests for the SHA-keyed method clone cache, against real local git repositories.
+
+Everything runs on-disk (`file://` remotes) — no network. Pins the cache's contract: the
+reference is resolved to its commit SHA by `ls-remote` before any clone (tags-only for
+`@<tag>`), a cached SHA is never re-cloned, a moved tag resolves to a new SHA and a fresh
+clone (never cache by tag alone), and the bounds evict oldest-first while keeping the newest
+entry.
+"""
+
+import os
+import subprocess
+import time
+from pathlib import Path
+
+import pytest
+from pipelex.methods.exceptions import MethodFetchError
+from pipelex.methods.fetching import fetch_method_package
+from pipelex.methods.method_ref import parse_method_ref
+from pytest_mock import MockerFixture
+
+from pipelex_api.method_cache import MethodCloneCache, resolve_remote_commit_sha
+from tests.unit._constants import STUB_METHOD_MANIFEST, VALID_MTHDS
+
+_REF = parse_method_ref("github.com/pipelex/methods/[email protected]")
+_BARE_REF = parse_method_ref("github.com/pipelex/methods/documents")
+
+
+def _git(*args: str, cwd: Path) -> str:
+ result = subprocess.run( # noqa: S603 — fixed argv against the test's own tmp repo
+ ["git", "-c", "[email protected]", "-c", "user.name=Test", "-c", "commit.gpgsign=false", *args], # noqa: S607
+ cwd=cwd,
+ capture_output=True,
+ text=True,
+ check=True,
+ timeout=60,
+ )
+ return result.stdout.strip()
+
+
+def origin(tmp_path: Path) -> tuple[str, Path]:
+ """A local origin repository holding the stub package, tagged `v0.1.0`; returns (clone_url, repo_dir)."""
+ repo = tmp_path / "origin"
+ package_dir = repo / "methods" / "documents"
+ package_dir.mkdir(parents=True)
+ (package_dir / "METHODS.toml").write_text(STUB_METHOD_MANIFEST, encoding="utf-8")
+ (package_dir / "documents.mthds").write_text(VALID_MTHDS, encoding="utf-8")
+ _git("init", "-b", "main", cwd=repo)
+ _git("add", "-A", cwd=repo)
+ _git("commit", "-m", "seed package", cwd=repo)
+ _git("tag", "-a", "v0.1.0", "-m", "first tag", cwd=repo)
+ return f"file://{repo}", repo
+
+
+class TestMethodCloneCache:
+ def test_resolve_remote_commit_sha_for_tag_and_head(self, origin: tuple[str, Path]):
+ clone_url, repo = origin
+ head_sha = _git("rev-parse", "HEAD", cwd=repo)
+ # An annotated tag resolves to its PEELED commit SHA — the same value `rev-parse HEAD`
+ # reports inside a clone at that tag — not the tag object's own SHA.
+ assert resolve_remote_commit_sha(ref=_REF, clone_url=clone_url) == head_sha
+ # A bare reference resolves the default branch HEAD.
+ assert resolve_remote_commit_sha(ref=_BARE_REF, clone_url=clone_url) == head_sha
+
+ def test_branch_names_are_refused_as_tags(self, origin: tuple[str, Path]):
+ clone_url, _ = origin
+ branch_ref = parse_method_ref("github.com/pipelex/methods/documents@main")
+ with pytest.raises(MethodFetchError, match="does not name a git tag"):
+ resolve_remote_commit_sha(ref=branch_ref, clone_url=clone_url)
+
+ def test_a_cached_sha_is_never_recloned(self, origin: tuple[str, Path], tmp_path: Path, mocker: MockerFixture):
+ clone_url, repo = origin
+ head_sha = _git("rev-parse", "HEAD", cwd=repo)
+ cache = MethodCloneCache(root_dir=tmp_path / "cache")
+ fetch_spy = mocker.spy(cache, "_package_from_clone")
+ clone_spy = mocker.patch("pipelex_api.method_cache.fetch_method_package", wraps=fetch_method_package)
+
+ first = cache.get_or_fetch(ref=_REF, clone_url=clone_url)
+ second = cache.get_or_fetch(ref=_REF, clone_url=clone_url)
+
+ assert clone_spy.call_count == 1, "the second request must be served from the cache"
+ assert fetch_spy.call_count == 2, "location + bounds re-run on every request"
+ assert first.commit_sha == head_sha
+ assert second.commit_sha == head_sha
+ assert first.package_dir == second.package_dir
+ assert (tmp_path / "cache" / head_sha).is_dir()
+ # Provenance is the honest record: address, tag, and the resolved SHA.
+ assert first.provenance.address == "github.com/pipelex/methods/documents"
+ assert first.provenance.tag == "v0.1.0"
+
+ def test_a_moved_tag_resolves_to_a_fresh_clone(self, origin: tuple[str, Path], tmp_path: Path):
+ clone_url, repo = origin
+ cache = MethodCloneCache(root_dir=tmp_path / "cache")
+ first = cache.get_or_fetch(ref=_REF, clone_url=clone_url)
+
+ # Move the tag: a new commit, and v0.1.0 forced onto it. Never cache by tag alone —
+ # the same reference must now fetch the NEW commit.
+ (repo / "methods" / "documents" / "extra.mthds").write_text(VALID_MTHDS.replace('"smoke"', '"extra"'), encoding="utf-8")
+ _git("add", "-A", cwd=repo)
+ _git("commit", "-m", "move the tag", cwd=repo)
+ _git("tag", "-f", "-a", "v0.1.0", "-m", "moved tag", cwd=repo)
+
+ second = cache.get_or_fetch(ref=_REF, clone_url=clone_url)
+ assert second.commit_sha != first.commit_sha
+ assert (tmp_path / "cache" / first.commit_sha).is_dir()
+ assert (tmp_path / "cache" / second.commit_sha).is_dir()
+
+ def test_count_bound_evicts_oldest_keeping_newest(self, origin: tuple[str, Path], tmp_path: Path, mocker: MockerFixture):
+ clone_url, repo = origin
+ mocker.patch("pipelex_api.method_cache.MAX_METHOD_CACHE_CLONES", 1)
+ cache = MethodCloneCache(root_dir=tmp_path / "cache")
+ first = cache.get_or_fetch(ref=_REF, clone_url=clone_url)
+
+ (repo / "methods" / "documents" / "extra.mthds").write_text(VALID_MTHDS.replace('"smoke"', '"extra"'), encoding="utf-8")
+ _git("add", "-A", cwd=repo)
+ _git("commit", "-m", "second version", cwd=repo)
+ _git("tag", "-a", "v0.2.0", "-m", "second tag", cwd=repo)
+ # Make the first entry visibly older than the newcomer (mtime is the eviction order).
+ old = time.time() - 120
+ os.utime(tmp_path / "cache" / first.commit_sha, (old, old))
+
+ second_ref = parse_method_ref("github.com/pipelex/methods/[email protected]")
+ second = cache.get_or_fetch(ref=second_ref, clone_url=clone_url)
+
+ assert not (tmp_path / "cache" / first.commit_sha).exists(), "the oldest entry is evicted past the count bound"
+ assert (tmp_path / "cache" / second.commit_sha).is_dir(), "the newest entry always survives"
+
+ def test_age_bound_evicts_stale_entries(self, origin: tuple[str, Path], tmp_path: Path, mocker: MockerFixture):
+ clone_url, repo = origin
+ mocker.patch("pipelex_api.method_cache.MAX_METHOD_CACHE_AGE_SECONDS", 3600)
+ cache = MethodCloneCache(root_dir=tmp_path / "cache")
+ first = cache.get_or_fetch(ref=_REF, clone_url=clone_url)
+ stale = time.time() - 7200
+ os.utime(tmp_path / "cache" / first.commit_sha, (stale, stale))
+
+ (repo / "methods" / "documents" / "extra.mthds").write_text(VALID_MTHDS.replace('"smoke"', '"extra"'), encoding="utf-8")
+ _git("add", "-A", cwd=repo)
+ _git("commit", "-m", "second version", cwd=repo)
+ _git("tag", "-a", "v0.2.0", "-m", "second tag", cwd=repo)
+ second_ref = parse_method_ref("github.com/pipelex/methods/[email protected]")
+ second = cache.get_or_fetch(ref=second_ref, clone_url=clone_url)
+
+ assert not (tmp_path / "cache" / first.commit_sha).exists(), "an entry unused past the age bound is evicted"
+ assert (tmp_path / "cache" / second.commit_sha).is_dir()
+
+ def test_nonexistent_repository_is_a_fetch_error(self, tmp_path: Path):
+ with pytest.raises(MethodFetchError, match="could not reach the repository"):
+ resolve_remote_commit_sha(ref=_BARE_REF, clone_url=f"file://{tmp_path}/no-such-repo")
diff --git a/api/tests/unit/test_method_ref_run.py b/api/tests/unit/test_method_ref_run.py
new file mode 100644
index 000000000..6f9540764
--- /dev/null
+++ b/api/tests/unit/test_method_ref_run.py
@@ -0,0 +1,207 @@
+"""Route-level tests for `method_ref` as a run source on /execute and /start.
+
+The pipeline runner is mocked (as in `test_pipeline_bundle`) and the clone cache is stubbed
+with a local directory tree (`install_method_package` in conftest), so these pin the API
+layer's contract: the fetched package's `.mthds` files ride `mthds_contents`, the entry pipe
+defaults to the manifest's `main_pipe` (a request `pipe_code` overrides), provenance
+`{address, tag, commit_sha}` lands on the response, the exclusivity rules 422, the
+execution-locus gate refuses Python where it must, and each resolution failure maps to its
+distinct `error_type` + status as RFC 7807 `problem+json`.
+"""
+
+from collections.abc import Callable
+from pathlib import Path
+from typing import Any
+
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+from pipelex.methods.exceptions import MethodFetchError
+from pipelex.pipeline.pipeline_response import PipelexRunResultStart, RunState
+from pytest_mock import MockerFixture
+
+from pipelex_api.exception_handlers import register_exception_handlers
+from pipelex_api.routes.pipelex.pipeline import router as pipeline_router
+from tests.unit._constants import STUB_METHOD_ADDRESS, STUB_METHOD_COMMIT_SHA, VALID_MTHDS
+
+_METHOD_REF = f"{STUB_METHOD_ADDRESS}@v0.1.0"
+
+_PIPE_FUNC_PY = "def echo(working_memory):\n return 'hi'\n"
+
+_STRUCTURES_PY = """\
+from pipelex.core.stuffs.structured_content import StructuredContent
+
+
+class Invoice(StructuredContent):
+ total: float
+"""
+
+
+def _build_client(mocker: MockerFixture) -> tuple[TestClient, dict[str, Any]]:
+ """Wire an app whose ApiRunner is mocked and records what the run actually saw."""
+ app = FastAPI()
+ app.include_router(pipeline_router, prefix="/v1")
+ register_exception_handlers(app)
+
+ snapshot: dict[str, Any] = {}
+
+ fake_execute_response = mocker.MagicMock()
+ fake_execute_response.model_dump.return_value = {
+ "pipeline_run_id": "run-1",
+ "state": "COMPLETED",
+ "pipe_output": {"working_memory": {"root": {}, "aliases": {}}},
+ }
+ fake_execute_response.pipe_output.tokens_usages = None
+
+ def _record(library_dirs: list[str] | None, run_kwargs: dict[str, Any]) -> None:
+ snapshot["library_dirs"] = library_dirs
+ snapshot["mthds_contents"] = run_kwargs.get("mthds_contents")
+ snapshot["pipe_code"] = run_kwargs.get("pipe_code")
+ if library_dirs:
+ root = Path(library_dirs[0])
+ snapshot["files"] = sorted(path.relative_to(root).as_posix() for path in root.rglob("*") if path.is_file())
+ else:
+ snapshot["files"] = None
+
+ def _make_runner(**kwargs: Any) -> Any:
+ library_dirs: list[str] | None = kwargs.get("library_dirs")
+ runner = mocker.MagicMock()
+
+ async def _execute(**run_kwargs: Any) -> Any:
+ _record(library_dirs, run_kwargs)
+ return fake_execute_response
+
+ async def _start(**run_kwargs: Any) -> Any:
+ _record(library_dirs, run_kwargs)
+ return PipelexRunResultStart(
+ pipeline_run_id="run-1",
+ created_at="2026-01-15T12:00:00Z",
+ state=RunState.STARTED,
+ workflow_id="wf-1",
+ )
+
+ runner.execute = _execute
+ runner.start = _start
+ return runner
+
+ mocker.patch("pipelex_api.routes.pipelex.pipeline.ApiRunner", side_effect=_make_runner)
+ return TestClient(app), snapshot
+
+
+class TestMethodRefRun:
+ def test_execute_rides_fetched_contents_defaults_main_pipe_and_carries_provenance(
+ self, mocker: MockerFixture, install_method_package: Callable[..., Path]
+ ):
+ install_method_package(files={"documents.mthds": VALID_MTHDS})
+ client, snapshot = _build_client(mocker)
+ response = client.post("/v1/execute", json={"method_ref": _METHOD_REF, "inputs": {"text": "hi"}})
+ assert response.status_code == 200, response.text
+ # The package's `.mthds` took the proven inline path; no Python → no library dir.
+ assert snapshot["mthds_contents"] == [VALID_MTHDS]
+ assert snapshot["library_dirs"] is None
+ # The entry pipe came from the manifest's `main_pipe`.
+ assert snapshot["pipe_code"] == "echo"
+ # Provenance: resolved full address, the requested tag, the fetched commit SHA.
+ assert response.json()["method_provenance"] == {
+ "address": STUB_METHOD_ADDRESS,
+ "tag": "v0.1.0",
+ "commit_sha": STUB_METHOD_COMMIT_SHA,
+ }
+
+ def test_request_pipe_code_overrides_manifest_main_pipe(self, mocker: MockerFixture, install_method_package: Callable[..., Path]):
+ install_method_package(files={"documents.mthds": VALID_MTHDS})
+ client, snapshot = _build_client(mocker)
+ response = client.post("/v1/execute", json={"method_ref": _METHOD_REF, "pipe_code": "smoke.echo", "inputs": {"text": "hi"}})
+ assert response.status_code == 200, response.text
+ assert snapshot["pipe_code"] == "smoke.echo"
+
+ def test_start_carries_provenance_on_the_ack(self, mocker: MockerFixture, install_method_package: Callable[..., Path]):
+ install_method_package(files={"documents.mthds": VALID_MTHDS})
+ client, snapshot = _build_client(mocker)
+ response = client.post("/v1/start", json={"method_ref": STUB_METHOD_ADDRESS, "inputs": {"text": "hi"}})
+ assert response.status_code == 202, response.text
+ assert snapshot["mthds_contents"] == [VALID_MTHDS]
+ body = response.json()
+ assert body["pipeline_run_id"] == "run-1"
+ # A bare address: provenance records tag=None and the resolved HEAD commit.
+ assert body["method_provenance"] == {"address": STUB_METHOD_ADDRESS, "tag": None, "commit_sha": STUB_METHOD_COMMIT_SHA}
+
+ def test_inline_runs_carry_no_provenance(self, mocker: MockerFixture):
+ client, _ = _build_client(mocker)
+ execute_response = client.post("/v1/execute", json={"mthds_contents": [VALID_MTHDS], "inputs": {"text": "hi"}})
+ assert execute_response.status_code == 200
+ assert "method_provenance" not in execute_response.json()
+ start_response = client.post("/v1/start", json={"mthds_contents": [VALID_MTHDS], "inputs": {"text": "hi"}})
+ assert start_response.status_code == 202
+ assert start_response.json()["method_provenance"] is None
+
+ def test_method_ref_is_exclusive_with_inline_contents_and_bundles(self, mocker: MockerFixture, install_method_package: Callable[..., Path]):
+ install_method_package(files={"documents.mthds": VALID_MTHDS})
+ client, _ = _build_client(mocker)
+ with_contents = client.post("/v1/execute", json={"method_ref": _METHOD_REF, "mthds_contents": [VALID_MTHDS]})
+ with_bundle = client.post("/v1/execute", json={"method_ref": _METHOD_REF, "files": {"main.mthds": VALID_MTHDS}})
+ for response in (with_contents, with_bundle):
+ assert response.status_code == 422, response.text
+ assert "mutually exclusive" in response.json()["detail"]
+
+ def test_malformed_ref_is_422_with_parse_error_type(self, mocker: MockerFixture, install_method_package: Callable[..., Path]):
+ install_method_package(files={"documents.mthds": VALID_MTHDS})
+ client, _ = _build_client(mocker)
+ response = client.post("/v1/execute", json={"method_ref": "gitlab.com/acme/tools", "inputs": {}})
+ assert response.status_code == 422, response.text
+ assert response.headers["content-type"] == "application/problem+json"
+ assert response.json()["error_type"] == "MethodRefParseError"
+
+ def test_unknown_package_is_404_problem_json(self, mocker: MockerFixture, install_method_package: Callable[..., Path]):
+ install_method_package(files={"documents.mthds": VALID_MTHDS})
+ client, _ = _build_client(mocker)
+ response = client.post("/v1/execute", json={"method_ref": "github.com/pipelex/methods/nonexistent", "inputs": {}})
+ assert response.status_code == 404, response.text
+ assert response.headers["content-type"] == "application/problem+json"
+ body = response.json()
+ assert body["error_type"] == "MethodPackageNotFoundError"
+ # The message teaches: it lists the packages the repository does contain.
+ assert STUB_METHOD_ADDRESS in body["detail"]
+
+ def test_fetch_failure_is_422_with_fetch_error_type(self, mocker: MockerFixture):
+ stub_cache = mocker.MagicMock()
+ stub_cache.get_or_fetch.side_effect = MethodFetchError("Failed to fetch method 'github.com/pipelex/methods/documents': boom")
+ mocker.patch("pipelex_api.method_source.get_method_clone_cache", return_value=stub_cache)
+ client, _ = _build_client(mocker)
+ response = client.post("/v1/execute", json={"method_ref": STUB_METHOD_ADDRESS, "inputs": {}})
+ assert response.status_code == 422, response.text
+ assert response.headers["content-type"] == "application/problem+json"
+ assert response.json()["error_type"] == "MethodFetchError"
+
+ def test_python_package_forbidden_when_not_sandbox_hosted(self, mocker: MockerFixture, install_method_package: Callable[..., Path]):
+ install_method_package(files={"documents.mthds": VALID_MTHDS, "funcs/pipe_func.py": _PIPE_FUNC_PY})
+ mocker.patch("pipelex_api.method_source.is_pipe_func_sandbox_hosted", return_value=False)
+ client, _ = _build_client(mocker)
+ response = client.post("/v1/execute", json={"method_ref": _METHOD_REF, "inputs": {}})
+ assert response.status_code == 403, response.text
+ assert response.headers["content-type"] == "application/problem+json"
+ assert response.json()["error_type"] == "CustomCodeRequiresSandbox"
+
+ def test_python_package_splits_mthds_from_py_when_sandbox_hosted(self, mocker: MockerFixture, install_method_package: Callable[..., Path]):
+ install_method_package(files={"documents.mthds": VALID_MTHDS, "funcs/pipe_func.py": _PIPE_FUNC_PY})
+ mocker.patch("pipelex_api.method_source.is_pipe_func_sandbox_hosted", return_value=True)
+ client, snapshot = _build_client(mocker)
+ response = client.post("/v1/execute", json={"method_ref": _METHOD_REF, "inputs": {}})
+ assert response.status_code == 200, response.text
+ # `.mthds` rides mthds_contents; ONLY the Python lands in the temp library dir — the
+ # manifest is consumed (identity + main_pipe) and deliberately NOT materialized.
+ assert snapshot["mthds_contents"] == [VALID_MTHDS]
+ assert snapshot["files"] == ["funcs/pipe_func.py"]
+ # The temp dir is cleaned once the request returns.
+ assert not Path(snapshot["library_dirs"][0]).exists()
+
+ def test_structures_package_refused_even_when_sandbox_hosted(self, mocker: MockerFixture, install_method_package: Callable[..., Path]):
+ install_method_package(files={"documents.mthds": VALID_MTHDS, "structures/models.py": _STRUCTURES_PY})
+ mocker.patch("pipelex_api.method_source.is_pipe_func_sandbox_hosted", return_value=True)
+ client, _ = _build_client(mocker)
+ response = client.post("/v1/execute", json={"method_ref": _METHOD_REF, "inputs": {}})
+ assert response.status_code == 403, response.text
+ assert response.headers["content-type"] == "application/problem+json"
+ body = response.json()
+ assert body["error_type"] == "MethodStructuresRefusedError"
+ # The refusal names the rule and teaches the fix.
+ assert "MTHDS concepts" in body["detail"]
diff --git a/api/tests/unit/test_method_ref_validate.py b/api/tests/unit/test_method_ref_validate.py
new file mode 100644
index 000000000..bfdfb8fa7
--- /dev/null
+++ b/api/tests/unit/test_method_ref_validate.py
@@ -0,0 +1,81 @@
+"""Route-level tests for `method_ref` on /validate — validate-by-address.
+
+The clone cache is stubbed with a local directory tree (`install_method_package` in
+conftest); validation itself runs for real, in-process. Pins the addressing design's Phase 2
+delta: `/validate` accepts `method_ref` natively, resolved through the same fetch path as a
+`method_ref` run, with the package's real file names feeding `mthds_sources` — and the
+verdict discipline holds: a selector-resolution failure is a non-2xx `problem+json`, never
+an `is_valid: false` verdict.
+"""
+
+from collections.abc import Callable
+from pathlib import Path
+
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+from pipelex_api.exception_handlers import register_exception_handlers
+from pipelex_api.routes import router as api_router
+from tests.unit._constants import INVALID_MAIN_PIPE_MTHDS, STUB_METHOD_ADDRESS, VALID_MTHDS
+
+_METHOD_REF = f"{STUB_METHOD_ADDRESS}@v0.1.0"
+
+
+def _build_client() -> TestClient:
+ app = FastAPI()
+ app.include_router(api_router, prefix="/v1")
+ register_exception_handlers(app)
+ return TestClient(app)
+
+
+class TestMethodRefValidate:
+ def test_valid_package_returns_200_valid_arm_echoing_fetched_contents(self, install_method_package: Callable[..., Path]):
+ install_method_package(files={"documents.mthds": VALID_MTHDS})
+ client = _build_client()
+ response = client.post("/v1/validate", json={"method_ref": _METHOD_REF})
+ assert response.status_code == 200, response.text
+ body = response.json()
+ assert body["is_valid"] is True
+ # The echo carries what was actually validated: the fetched package's contents.
+ assert body["mthds_contents"] == [VALID_MTHDS]
+ assert "smoke.echo" in body["pipe_io_contracts"]
+
+ def test_invalid_package_diagnostics_carry_the_real_file_names(self, install_method_package: Callable[..., Path]):
+ install_method_package(files={"broken.mthds": INVALID_MAIN_PIPE_MTHDS})
+ client = _build_client()
+ response = client.post("/v1/validate", json={"method_ref": _METHOD_REF})
+ assert response.status_code == 200, response.text
+ body = response.json()
+ assert body["is_valid"] is False
+ assert body["validation_errors"], "an invalid verdict must carry a non-empty validation_errors[]"
+ # The package's real relative file name fed `mthds_sources`, so the diagnostic points
+ # at the owning file rather than carrying a null source.
+ assert body["validation_errors"][0]["source"] == "broken.mthds"
+
+ def test_resolution_failure_is_non_2xx_problem_json_never_a_false_verdict(self, install_method_package: Callable[..., Path]):
+ install_method_package(files={"documents.mthds": VALID_MTHDS})
+ client = _build_client()
+ response = client.post("/v1/validate", json={"method_ref": "github.com/pipelex/methods/nonexistent"})
+ assert response.status_code == 404, response.text
+ assert response.headers["content-type"] == "application/problem+json"
+ body = response.json()
+ assert body["error_type"] == "MethodPackageNotFoundError"
+ # The verdict discipline: no verdict was produced, so nothing here says `is_valid`.
+ assert "is_valid" not in body
+
+ def test_method_ref_and_mthds_contents_are_a_422_xor_violation(self, install_method_package: Callable[..., Path]):
+ install_method_package(files={"documents.mthds": VALID_MTHDS})
+ client = _build_client()
+ both = client.post("/v1/validate", json={"method_ref": _METHOD_REF, "mthds_contents": [VALID_MTHDS]})
+ neither = client.post("/v1/validate", json={})
+ for response in (both, neither):
+ assert response.status_code == 422, response.text
+ assert response.headers["content-type"] == "application/problem+json"
+ assert "exactly one of" in response.json()["detail"]
+
+ def test_mthds_sources_do_not_accompany_a_method_ref(self, install_method_package: Callable[..., Path]):
+ install_method_package(files={"documents.mthds": VALID_MTHDS})
+ client = _build_client()
+ response = client.post("/v1/validate", json={"method_ref": _METHOD_REF, "mthds_sources": ["main.mthds"]})
+ assert response.status_code == 422, response.text
+ assert "package's own file names" in response.json()["detail"]
diff --git a/api/tests/unit/test_openapi_contract.py b/api/tests/unit/test_openapi_contract.py
new file mode 100644
index 000000000..141153fe1
--- /dev/null
+++ b/api/tests/unit/test_openapi_contract.py
@@ -0,0 +1,255 @@
+"""The published error contract — every `/v1` operation documents RFC 7807, with real schemas.
+
+Guards what the committed artifact (`docs/openapi/pipelex-api.openapi.yaml`, regenerated from
+this same `fastapi_app.openapi()`) tells a client about failures:
+
+- Every failure this server can emit is an `application/problem+json` problem document
+ (`pipelex_api.exception_handlers`), so every documented 4xx/5xx must say so — with a `$ref` to the
+ typed `ProblemDocument`, not FastAPI's default `HTTPValidationError` on `application/json`.
+- The statuses a given route can additionally produce (`/execute`'s provider-429, `/start`'s
+ 409 duplicate run, `/resolve`'s 501 `method_ref`, …) are documented on that route.
+- The `suggested_fix` surface pipelex's codegen work added reaches the wire: a client reading
+ the artifact can find it from a problem document, not just from `/validate`'s 200 arm.
+- `x-mthds-protocol` marks exactly the MTHDS Protocol operations and nothing else — the flag is
+ how a conformance suite or a third-party runner extracts the portable subset of this artifact,
+ so a Pipelex extension wearing it would misrepresent the standard.
+
+`pipelex_api.main` is imported inside the fixture rather than at module scope so a bad env var fails
+THESE tests rather than the collection of every module that transitively imports the app.
+"""
+
+from __future__ import annotations
+
+import json
+from typing import Any
+
+import pytest
+
+from pipelex_api.problem_document import PROBLEM_JSON_MEDIA_TYPE
+
+# Methods that carry an operation object in an OpenAPI path item.
+_OPERATION_KEYS = frozenset({"get", "put", "post", "delete", "options", "head", "patch", "trace"})
+
+# Documented on EVERY auth-wrapped `/v1` operation, via the composite router in `pipelex_api.routes`:
+# the auth dependency (401), the body-size middleware (413), request-shape / input-domain
+# rejections (422), and the server-fault floor (500).
+COMMON_STATUSES = (401, 413, 422, 500)
+
+# `GET /v1/version` is the public protocol handshake: `pipelex_api.main` mounts it OUTSIDE the composite
+# router (and outside the auth dependency), so it inherits none of the shared responses.
+PUBLIC_PATHS = ("/v1/version",)
+
+# The MTHDS Protocol operations — and nothing else — carry `x-mthds-protocol: true`. This is the
+# standard's five-operation surface (`execute`, `start`, `validate`, `models`, `version`; see the
+# normative `mthds/docs/spec/openapi/mthds-protocol.openapi.yaml`), NOT everything this server
+# serves. `/resolve` and `/codegen` are deliberately absent: they are Pipelex API extensions. The
+# crate `/resolve` emits is standard-owned (the MTHDS Library Crate Format), but the route serving
+# it is ours, and the standard specifies no type projection at all.
+MTHDS_PROTOCOL_OPERATIONS = {
+ ("/v1/execute", "post"),
+ ("/v1/start", "post"),
+ ("/v1/validate", "post"),
+ ("/v1/models", "get"),
+ ("/v1/version", "get"),
+}
+
+# The extra statuses each route can produce on top of COMMON_STATUSES.
+ROUTE_EXTRA_STATUSES = {
+ ("/v1/execute", "post"): (403, 429),
+ ("/v1/start", "post"): (400, 403, 409, 501),
+ ("/v1/validate", "post"): (403,),
+ ("/v1/resolve", "post"): (404, 501),
+ ("/v1/pipe-io", "post"): (404, 501),
+ ("/v1/codegen", "post"): (501,),
+}
+
+
[email protected](scope="class")
+def openapi_schema() -> dict[str, Any]:
+ from pipelex_api.main import fastapi_app # noqa: PLC0415 — see the module docstring
+
+ return fastapi_app.openapi()
+
+
+class TestOpenApiErrorContract:
+ def _operations(self, schema: dict[str, Any], *, prefix: str = "") -> list[tuple[str, str, dict[str, Any]]]:
+ """Every (path, method, operation) in the schema, optionally filtered by path prefix."""
+ return [
+ (path, method, operation)
+ for path, path_item in schema["paths"].items()
+ if path.startswith(prefix)
+ for method, operation in path_item.items()
+ if method in _OPERATION_KEYS
+ ]
+
+ def test_no_operation_documents_fastapi_default_validation_error(self, openapi_schema: dict[str, Any]):
+ """FastAPI's automatic `HTTPValidationError` 422 contradicts the RFC 7807 wire — declaring
+ our own 422 must suppress it everywhere, and the component must not even be generated.
+ """
+ assert "HTTPValidationError" not in openapi_schema["components"]["schemas"]
+ for path, method, operation in self._operations(openapi_schema):
+ for status_code, response in operation["responses"].items():
+ content = response.get("content", {})
+ for media_type, body in content.items():
+ ref = body.get("schema", {}).get("$ref", "")
+ assert "HTTPValidationError" not in ref, f"{method.upper()} {path} {status_code} ({media_type}) still refs HTTPValidationError"
+
+ def test_every_v1_operation_documents_the_common_problem_responses(self, openapi_schema: dict[str, Any]):
+ """Auth (401), payload cap (413), request shape (422), server fault (500) — on every
+ auth-wrapped `/v1` route, each an `application/problem+json` `ProblemDocument`.
+ """
+ operations = [
+ (path, method, operation) for path, method, operation in self._operations(openapi_schema, prefix="/v1") if path not in PUBLIC_PATHS
+ ]
+ assert operations, "no /v1 operations found — the schema or the path filter is wrong"
+ for path, method, operation in operations:
+ for status in COMMON_STATUSES:
+ response = operation["responses"].get(str(status))
+ assert response is not None, f"{method.upper()} {path} does not document {status}"
+ content = response.get("content", {})
+ assert list(content) == [PROBLEM_JSON_MEDIA_TYPE], f"{method.upper()} {path} {status} media type is {list(content)}"
+ assert content[PROBLEM_JSON_MEDIA_TYPE]["schema"]["$ref"] == "#/components/schemas/ProblemDocument"
+
+ def test_public_version_route_has_no_auth_response(self, openapi_schema: dict[str, Any]):
+ """`GET /v1/version` is the pre-credential handshake: it must never advertise a 401."""
+ responses = openapi_schema["paths"]["/v1/version"]["get"]["responses"]
+ assert "401" not in responses
+ assert responses["500"]["content"][PROBLEM_JSON_MEDIA_TYPE]["schema"]["$ref"] == "#/components/schemas/ProblemDocument"
+
+ @pytest.mark.parametrize(
+ ("path", "method", "extra_statuses"), [(path, method, extras) for (path, method), extras in ROUTE_EXTRA_STATUSES.items()]
+ )
+ def test_route_documents_its_own_extra_statuses(self, openapi_schema: dict[str, Any], path: str, method: str, extra_statuses: tuple[int, ...]):
+ """The failures a specific route alone can produce ride that route's operation."""
+ responses = openapi_schema["paths"][path][method]["responses"]
+ for status in extra_statuses:
+ response = responses.get(str(status))
+ assert response is not None, f"{method.upper()} {path} does not document {status}"
+ assert list(response.get("content", {})) == [PROBLEM_JSON_MEDIA_TYPE]
+
+ def test_x_mthds_protocol_tags_exactly_the_protocol_operations(self, openapi_schema: dict[str, Any]):
+ """The flag is how a conformance suite extracts the portable subset of this artifact, so it
+ must mark the standard's operations and nothing else. Asserted as an exact set — a route that
+ silently joins OR leaves the protocol surface fails here, in both directions.
+ """
+ tagged = {(path, method) for path, method, operation in self._operations(openapi_schema) if operation.get("x-mthds-protocol")}
+ assert tagged == MTHDS_PROTOCOL_OPERATIONS
+
+ def test_resolve_codegen_and_pipe_io_are_pipelex_extensions(self, openapi_schema: dict[str, Any]):
+ """Spelled out separately from the set assertion above, because this is the easy mistake:
+ `/resolve`, `/codegen` and `/pipe-io` look protocol-shaped (they speak the `/validate` verdict
+ discipline and emit the standard's crate or I/O artifacts) but they are Pipelex API extensions
+ and must not be tagged.
+ """
+ for path in ("/v1/resolve", "/v1/codegen", "/v1/pipe-io"):
+ assert "x-mthds-protocol" not in openapi_schema["paths"][path]["post"]
+
+ def test_the_document_never_names_the_hosted_selector(self, openapi_schema: dict[str, Any]):
+ """The runner declares nothing of the hosted layer, not even in prose: `method_id` is the hosted
+ catalog selector, which the platform replaces with `files` before a request reaches the runner,
+ so the name appears nowhere in the document — no field, no description, no example.
+ """
+ assert "method_id" not in json.dumps(openapi_schema)
+
+ def test_pipe_io_request_declares_no_hosted_selector_and_no_views(self, openapi_schema: dict[str, Any]):
+ """The platform resolves the hosted `method_id` into `files[]` before forwarding, so the runner
+ never declares it; and the route always carries all three artifacts, so it takes no `views`.
+ """
+ schemas = openapi_schema["components"]["schemas"]
+ body_ref = openapi_schema["paths"]["/v1/pipe-io"]["post"]["requestBody"]["content"]["application/json"]["schema"]["$ref"]
+ properties = set(schemas[body_ref.rsplit("/", 1)[-1]]["properties"])
+ assert properties >= {"files", "method_ref", "pipe_ref", "all_pipes", "include_files"}
+ assert "method_id" not in properties
+ assert "views" not in properties
+
+ def test_auth_challenge_and_retry_hint_headers_are_documented(self, openapi_schema: dict[str, Any]):
+ """A 401 carries `WWW-Authenticate: Bearer`; the provider-429 passthrough carries `Retry-After`."""
+ unauthenticated = openapi_schema["paths"]["/v1/validate"]["post"]["responses"]["401"]
+ assert "WWW-Authenticate" in unauthenticated["headers"]
+ rate_limited = openapi_schema["paths"]["/v1/execute"]["post"]["responses"]["429"]
+ assert "Retry-After" in rate_limited["headers"]
+
+ def test_problem_document_carries_the_structured_validation_errors(self, openapi_schema: dict[str, Any]):
+ """A problem document publishes `validation_errors[]` of the SAME `ValidationErrorItem`
+ the 200 invalid arms publish — so `suggested_fix` reaches every surface that carries the
+ items, and the two can never drift into separate schemas.
+ """
+ schemas = openapi_schema["components"]["schemas"]
+ validation_errors = schemas["ProblemDocument"]["properties"]["validation_errors"]
+ item_refs = [option["items"]["$ref"] for option in validation_errors["anyOf"] if option.get("type") == "array"]
+ assert item_refs == ["#/components/schemas/ValidationErrorItem"]
+
+ def test_suggested_fix_surface_is_published(self, openapi_schema: dict[str, Any]):
+ """The codegen fix planner's output is part of the published contract: a `ValidationErrorItem`
+ may carry a `SuggestedFix`, whose `ops[]` are the machine contract (the rendered diff is not).
+
+ An op is a union discriminated on `kind`, one member model per kind — so a client picks the
+ member off the wire value rather than reading a single open shape whose fields depend on a
+ `kind` enum beside them. The whole vocabulary is published here: this is the `.mthds` fix
+ path, which carries every kind (a ledger carries only the structural subset).
+ """
+ schemas = openapi_schema["components"]["schemas"]
+ suggested_fix = schemas["ValidationErrorItem"]["properties"]["suggested_fix"]
+ assert any(option.get("$ref") == "#/components/schemas/SuggestedFix" for option in suggested_fix["anyOf"])
+ fix_properties = schemas["SuggestedFix"]["properties"]
+ assert {"fix_code", "description", "safety", "ops"} <= set(fix_properties)
+
+ op_schema = fix_properties["ops"]["items"]
+ assert op_schema["discriminator"]["propertyName"] == "kind"
+ kind_mapping = op_schema["discriminator"]["mapping"]
+ assert set(kind_mapping) == {"set_key", "ensure_table", "delete_key", "delete_table", "rename_table_key", "move_key", "remap_value"}
+ # Every member the discriminator names is a `oneOf` option AND a published schema, so a
+ # client that resolves a `kind` off the wire always lands on a shape the artifact defines.
+ member_refs = {option["$ref"] for option in op_schema["oneOf"]}
+ assert set(kind_mapping.values()) == member_refs
+ assert all(ref.rsplit("/", 1)[-1] in schemas for ref in member_refs)
+
+ assert set(schemas["FixSafety"]["enum"]) == {"safe", "unsafe"}
+
+ def test_execute_publishes_the_tokens_usage_wire_records(self, openapi_schema: dict[str, Any]):
+ """`/execute` returns a `JSONResponse` built from a trimmed dump, so FastAPI never validates
+ the body against `response_model` — nothing but this test keeps the published 200 schema
+ honest about what `apply_tokens_usage_wire_shape` actually emits. The runtime guard in
+ `test_pipeline_routes.py` pins the body; this pins the artifact, so the two fail together.
+ """
+ schemas = openapi_schema["components"]["schemas"]
+ body_ref = openapi_schema["paths"]["/v1/execute"]["post"]["responses"]["200"]["content"]["application/json"]["schema"]["$ref"]
+ assert body_ref == "#/components/schemas/PipelexApiExecuteResponse"
+
+ pipe_output_ref = schemas["PipelexApiExecuteResponse"]["properties"]["pipe_output"]["$ref"]
+ tokens_usages = schemas[pipe_output_ref.rsplit("/", 1)[-1]]["properties"]["tokens_usages"]
+ item_refs = [option["items"]["$ref"] for option in tokens_usages["anyOf"] if option.get("type") == "array"]
+ assert item_refs == ["#/components/schemas/TokensUsageRecord"]
+
+ record_properties = set(schemas["TokensUsageRecord"]["properties"])
+ assert {"model_type", "pipe_code", "nb_tokens_by_category", "cost"} <= record_properties
+ # The runtime internals the wire shape drops must not reappear in the published record.
+ assert {"job_metadata", "unit_costs"}.isdisjoint(record_properties)
+
+ # Nothing else references the internal usage models, so they leave the artifact entirely.
+ assert {"LLMTokensUsage", "ImgGenTokensUsage", "JobMetadata"}.isdisjoint(schemas)
+
+ def test_input_form_fields_are_a_kind_discriminated_union_of_closed_shapes(self, openapi_schema: dict[str, Any]):
+ """`PipeInputFormDescriptor.fields` publishes the standard's per-kind field models as a
+ union discriminated on `kind` — one member model per kind, the flat `InputFormField`
+ gone. The arms must stay closed shapes with real properties: the standard's field models
+ share a wrap serializer, and an imprecise return annotation on it silently erases every
+ arm to an open `{"additionalProperties": true}` object (validation-mode schemas and
+ `model_dump()` both stay correct, so nothing else notices). This is what would catch an
+ upstream regression to the flat or opaque shape.
+ """
+ schemas = openapi_schema["components"]["schemas"]
+ field_schema = schemas["PipeInputFormDescriptor"]["properties"]["fields"]["items"]
+ assert field_schema["discriminator"]["propertyName"] == "kind"
+ kind_mapping = field_schema["discriminator"]["mapping"]
+ assert set(kind_mapping) == {"text", "prose", "date", "number", "boolean", "enum", "document", "image", "object", "list", "unknown"}
+ member_refs = {option["$ref"] for option in field_schema["oneOf"]}
+ assert set(kind_mapping.values()) == member_refs
+
+ for ref in member_refs:
+ member = schemas[ref.rsplit("/", 1)[-1]]
+ assert member["additionalProperties"] is False
+ assert {"kind", "name", "required"} <= set(member["properties"])
+
+ # The flat pre-union models must not resurface beside the per-kind ones.
+ assert {"InputFormField", "FieldKind"}.isdisjoint(schemas)
diff --git a/api/tests/unit/test_orchestration_mode_schema.py b/api/tests/unit/test_orchestration_mode_schema.py
new file mode 100644
index 000000000..a4dd7aacc
--- /dev/null
+++ b/api/tests/unit/test_orchestration_mode_schema.py
@@ -0,0 +1,30 @@
+"""The `orchestration_mode` per-request override is documented on every run surface that honors it.
+
+`/execute` and `/start` both thread a per-request `orchestration_mode` override into the same
+override policy (`PipelineApiExtras.orchestration_mode` -> `resolve_orchestration_mode`), so the
+committed OpenAPI artifact must advertise the field on BOTH — otherwise a client generated from the
+artifact can drive the override on `/execute` but not on `/start`, even though the runtime honors it.
+Their bodies are published via inline `openapi_extra` schemas (raw-`Request` parsing, so FastAPI
+cannot infer the body), so this asserts the generated `app.openapi()` request-body schema directly.
+"""
+
+import pytest
+from fastapi import FastAPI
+
+from pipelex_api.routes import router as api_router
+
+
+def _build_app() -> FastAPI:
+ app = FastAPI()
+ app.include_router(api_router, prefix="/v1")
+ return app
+
+
+class TestOrchestrationModeSchema:
+ @pytest.mark.parametrize("path", ["/v1/execute", "/v1/start"])
+ def test_request_body_documents_orchestration_mode(self, path: str) -> None:
+ schema = _build_app().openapi()
+ request_schema = schema["paths"][path]["post"]["requestBody"]["content"]["application/json"]["schema"]
+ properties = request_schema["properties"]
+ assert "orchestration_mode" in properties, f"{path} request schema must document orchestration_mode"
+ assert properties["orchestration_mode"]["description"], f"{path} orchestration_mode must carry a description"
diff --git a/api/tests/unit/test_pipe_io_route.py b/api/tests/unit/test_pipe_io_route.py
new file mode 100644
index 000000000..805fdbf2f
--- /dev/null
+++ b/api/tests/unit/test_pipe_io_route.py
@@ -0,0 +1,472 @@
+"""Tests for `POST /v1/pipe-io` — a method's three I/O artifacts off the resolved crate, with no dry run.
+
+Pins `docs/specs/pipelex-codegen.md#the-pipe-io-route` (workspace root): the route resolves the
+closure through the crate routes' static core, selects a pipe with the per-pipe routes' chain, and
+returns `pipe_io_contracts`, `input_form` and `output_form` keyed by qualified `pipe_ref`, beside
+`pipe_ref`, `default_pipe_ref`, `pending_signatures`, `is_runnable` and, on request, the closure's
+files. The pinning cases hold each artifact equal to `/v1/validate`'s same-named view for the same
+closure and pipe; the teardown cases hold the loaded-on-success contract on every exit.
+"""
+
+from collections.abc import Callable
+from pathlib import Path
+from typing import Any
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+from pipelex.interpreter_hub import get_library_manager
+from pipelex.pipeline.exceptions import PipeIOContractError
+from pytest_mock import MockerFixture
+
+from pipelex_api.exception_handlers import register_exception_handlers
+from pipelex_api.routes import router as api_router
+from tests.unit._constants import (
+ COLLIDING_ECHO_LIST_MTHDS,
+ HEADER_AND_DEFINITION_BATCH,
+ INVALID_MAIN_PIPE_MTHDS,
+ NO_MAIN_PIPE_MTHDS,
+ SECOND_MAIN_PIPE_MTHDS,
+ SHAPES_MTHDS,
+ SIBLING_MTHDS,
+ SIGNATURE_MTHDS,
+ SIGNATURE_ONLY_BATCH,
+ STUB_METHOD_ADDRESS,
+ STUB_METHOD_MANIFEST_MAIN_PIPE_SHOUT,
+ STUB_METHOD_MANIFEST_NOMAIN_ENTRY,
+ VALID_MTHDS,
+)
+
+PIPE_IO_PATH = "/v1/pipe-io"
+
+# The address-form reference the stubbed clone (`install_method_package`) answers to.
+STUB_METHOD_REF = f"{STUB_METHOD_ADDRESS}@v0.1.0"
+
+# The three artifact maps the valid arm carries, sharing one key set.
+ARTIFACT_FIELDS = ("pipe_io_contracts", "input_form", "output_form")
+
+# The `error_type`s of a no-verdict 422: a malformed request, and the two pipe-selection refusals,
+# which carry the pipelex entry-lookup class names the run routes answer for the same failure.
+REQUEST_SHAPE_ERROR = "ValidationError"
+PIPE_NOT_FOUND_ERROR = "EntryPipeNotFoundError"
+PIPE_AMBIGUOUS_ERROR = "EntryPipeAmbiguousError"
+
+# Every field only the valid arm carries: the invalid arm is the crate verdict alone.
+VALID_ARM_ONLY_FIELDS = ("pipe_ref", "default_pipe_ref", *ARTIFACT_FIELDS, "pending_signatures", "is_runnable", "files")
+
+
+def _build_client() -> TestClient:
+ app = FastAPI()
+ app.include_router(api_router, prefix="/v1")
+ register_exception_handlers(app)
+ return TestClient(app)
+
+
+def _files(*contents: str) -> list[dict[str, str]]:
+ """Inline `files[]` items, each with a distinct `source` so `/v1/validate` can be sent the same labels."""
+ return [{"content": content, "source": f"bundle_{index}.mthds"} for index, content in enumerate(contents)]
+
+
+def _valid_arm(client: TestClient, payload: dict[str, Any]) -> dict[str, Any]:
+ response = client.post(PIPE_IO_PATH, json=payload)
+ assert response.status_code == 200, response.text
+ body: dict[str, Any] = response.json()
+ assert body["is_valid"] is True, response.text
+ assert "validation_errors" not in body
+ return body
+
+
+def _assert_keys(body: dict[str, Any], expected: set[str]) -> None:
+ for field_name in ARTIFACT_FIELDS:
+ assert set(body[field_name]) == expected, f"`{field_name}` keyed by {sorted(body[field_name])}, expected {sorted(expected)}"
+
+
+def _assert_input_422(response: Any, *, error_type: str) -> str:
+ """Assert a no-verdict input 422 of the given `error_type`, and return its detail."""
+ assert response.status_code == 422, response.text
+ assert response.headers["content-type"] == "application/problem+json"
+ problem = response.json()
+ assert problem["error_type"] == error_type, response.text
+ assert problem["error_domain"] == "input"
+ assert "is_valid" not in problem
+ detail: str = problem["detail"]
+ return detail
+
+
+class TestPipeIoRoute:
+ def test_one_pipe_by_default(self):
+ client = _build_client()
+ body = _valid_arm(client, {"files": _files(VALID_MTHDS, SIBLING_MTHDS)})
+ assert body["pipe_ref"] == "smoke.echo"
+ assert body["default_pipe_ref"] == "smoke.echo", "an omitted pipe_ref always answers pipe_ref == default_pipe_ref"
+ _assert_keys(body, {"smoke.echo"})
+ assert body["pending_signatures"] == []
+ assert body["is_runnable"] is True
+ assert "files" not in body, "files is absent, not empty, without include_files"
+
+ def test_a_named_pipe_is_described_beside_the_methods_own_entry_pipe(self):
+ client = _build_client()
+ body = _valid_arm(client, {"files": _files(VALID_MTHDS, SIBLING_MTHDS), "pipe_ref": "smoke.wrap_echo"})
+ assert body["pipe_ref"] == "smoke.wrap_echo"
+ assert body["default_pipe_ref"] == "smoke.echo"
+ _assert_keys(body, {"smoke.wrap_echo"})
+
+ def test_the_dump_keeps_null_members(self):
+ # Never `exclude_none`: the contracts' `item_count: null` must survive, or the maps stop
+ # equalling `/v1/validate`'s, which keeps it.
+ client = _build_client()
+ body = _valid_arm(client, {"files": _files(VALID_MTHDS)})
+ output_contract = body["pipe_io_contracts"]["smoke.echo"]["output"]
+ assert "item_count" in output_contract
+ assert output_contract["item_count"] is None
+
+ @pytest.mark.parametrize(
+ ("contents", "request_fields", "expected_pipe_ref", "expected_default", "expected_keys"),
+ [
+ pytest.param(
+ (VALID_MTHDS, SIBLING_MTHDS),
+ {},
+ "smoke.echo",
+ "smoke.echo",
+ {"smoke.echo", "smoke.wrap_echo"},
+ id="with-entry-pipe",
+ ),
+ pytest.param(
+ (VALID_MTHDS, SIBLING_MTHDS),
+ {"pipe_ref": "smoke.wrap_echo"},
+ "smoke.wrap_echo",
+ "smoke.echo",
+ {"smoke.echo", "smoke.wrap_echo"},
+ id="with-entry-pipe-and-named-pipe",
+ ),
+ pytest.param((NO_MAIN_PIPE_MTHDS,), {}, None, None, {"nomain.echo"}, id="without-entry-pipe"),
+ pytest.param((VALID_MTHDS, SECOND_MAIN_PIPE_MTHDS), {}, None, None, {"smoke.echo", "other.shout"}, id="with-several-entry-pipes"),
+ pytest.param(
+ (VALID_MTHDS, SECOND_MAIN_PIPE_MTHDS),
+ {"pipe_ref": "other.shout"},
+ "other.shout",
+ None,
+ {"smoke.echo", "other.shout"},
+ id="with-several-entry-pipes-and-named-pipe",
+ ),
+ ],
+ )
+ def test_all_pipes_describes_every_pipe_and_never_demands_an_entry_pipe(
+ self,
+ contents: tuple[str, ...],
+ request_fields: dict[str, Any],
+ expected_pipe_ref: str | None,
+ expected_default: str | None,
+ expected_keys: set[str],
+ ):
+ client = _build_client()
+ body = _valid_arm(client, {"files": _files(*contents), "all_pipes": True, **request_fields})
+ assert "pipe_ref" in body
+ assert body["pipe_ref"] == expected_pipe_ref
+ assert "default_pipe_ref" in body
+ assert body["default_pipe_ref"] == expected_default
+ _assert_keys(body, expected_keys)
+
+ @pytest.mark.parametrize(
+ ("contents", "pipe_ref"),
+ [
+ pytest.param((NO_MAIN_PIPE_MTHDS,), "nomain.echo", id="no-main-pipe"),
+ pytest.param((VALID_MTHDS, SECOND_MAIN_PIPE_MTHDS), "other.shout", id="several-main-pipes"),
+ ],
+ )
+ def test_default_pipe_ref_is_a_stated_null_without_one_entry_pipe(self, contents: tuple[str, ...], pipe_ref: str):
+ # Where several domains declare a `main_pipe`, `/v1/validate`'s run default names the first;
+ # this route's chain refuses to choose, so its field is null rather than a guess.
+ client = _build_client()
+ body = _valid_arm(client, {"files": _files(*contents), "pipe_ref": pipe_ref})
+ assert body["pipe_ref"] == pipe_ref
+ assert "default_pipe_ref" in body
+ assert body["default_pipe_ref"] is None
+ _assert_keys(body, {pipe_ref})
+
+ def test_default_pipe_ref_is_the_manifest_main_pipe(self, install_method_package: Callable[..., Path]):
+ # The package's bundle declares no main_pipe; only its manifest names the entry pipe.
+ install_method_package(files={"documents.mthds": NO_MAIN_PIPE_MTHDS}, manifest_toml=STUB_METHOD_MANIFEST_NOMAIN_ENTRY)
+ client = _build_client()
+ body = _valid_arm(client, {"method_ref": STUB_METHOD_REF})
+ assert body["pipe_ref"] == "nomain.echo"
+ assert body["default_pipe_ref"] == "nomain.echo"
+ _assert_keys(body, {"nomain.echo"})
+
+ def test_the_manifest_main_pipe_outranks_the_closures_declarations(self, install_method_package: Callable[..., Path]):
+ # Two declaring domains would leave the closure without a default; the manifest settles it,
+ # and it stays the default when the caller names another pipe.
+ install_method_package(
+ files={"smoke.mthds": VALID_MTHDS, "other.mthds": SECOND_MAIN_PIPE_MTHDS},
+ manifest_toml=STUB_METHOD_MANIFEST_MAIN_PIPE_SHOUT,
+ )
+ client = _build_client()
+ defaulted = _valid_arm(client, {"method_ref": STUB_METHOD_REF})
+ assert defaulted["pipe_ref"] == "other.shout"
+ assert defaulted["default_pipe_ref"] == "other.shout"
+ named = _valid_arm(client, {"method_ref": STUB_METHOD_REF, "pipe_ref": "smoke.echo"})
+ assert named["pipe_ref"] == "smoke.echo"
+ assert named["default_pipe_ref"] == "other.shout"
+
+ def test_a_manifest_main_pipe_the_closure_lacks_is_no_default_even_beside_a_declaration(self, install_method_package: Callable[..., Path]):
+ # The chain stops at the manifest link: `echo` is not in the closure, and `other`'s own
+ # declared `main_pipe` is not a fall-through. A whole-method request still answers.
+ install_method_package(files={"other.mthds": SECOND_MAIN_PIPE_MTHDS})
+ client = _build_client()
+ body = _valid_arm(client, {"method_ref": STUB_METHOD_REF, "all_pipes": True})
+ assert body["pipe_ref"] is None
+ assert body["default_pipe_ref"] is None
+ _assert_keys(body, {"other.shout"})
+ detail = _assert_input_422(client.post(PIPE_IO_PATH, json={"method_ref": STUB_METHOD_REF}), error_type=PIPE_NOT_FOUND_ERROR)
+ assert "manifest" in detail
+ assert "not found" in detail
+
+ def test_an_ambiguous_manifest_main_pipe_says_ambiguous(self, install_method_package: Callable[..., Path]):
+ # The manifest names `echo`, declared by both `smoke` and `twin`: the selection refuses it as
+ # ambiguous, naming both candidates, and a whole-method request states no default.
+ install_method_package(files={"smoke.mthds": VALID_MTHDS, "twin.mthds": COLLIDING_ECHO_LIST_MTHDS})
+ client = _build_client()
+ detail = _assert_input_422(client.post(PIPE_IO_PATH, json={"method_ref": STUB_METHOD_REF}), error_type=PIPE_AMBIGUOUS_ERROR)
+ assert "manifest" in detail
+ assert "several domains" in detail
+ assert "smoke.echo" in detail
+ assert "twin.echo" in detail
+ assert "not found" not in detail, f"an ambiguous selector must not read as a missing pipe: {detail}"
+ body = _valid_arm(client, {"method_ref": STUB_METHOD_REF, "all_pipes": True})
+ assert body["pipe_ref"] is None
+ assert body["default_pipe_ref"] is None
+
+ @pytest.mark.parametrize("all_pipes", [False, True], ids=["one-pipe", "all-pipes"])
+ def test_an_ambiguous_pipe_ref_says_ambiguous(self, all_pipes: bool):
+ client = _build_client()
+ payload = {"files": _files(VALID_MTHDS, COLLIDING_ECHO_LIST_MTHDS), "pipe_ref": "echo", "all_pipes": all_pipes}
+ detail = _assert_input_422(client.post(PIPE_IO_PATH, json=payload), error_type=PIPE_AMBIGUOUS_ERROR)
+ assert "Pipe 'echo'" in detail
+ assert "several domains" in detail
+ assert "smoke.echo" in detail
+ assert "twin.echo" in detail
+ assert "not found" not in detail, f"an ambiguous selector must not read as a missing pipe: {detail}"
+
+ def test_runnability_facts_match_validate(self):
+ client = _build_client()
+ body = _valid_arm(client, {"files": _files(SIGNATURE_MTHDS)})
+ assert body["pipe_ref"] == "sig_api.caller_seq"
+ assert body["pending_signatures"] == ["sig_api.summary_sig"]
+ assert body["is_runnable"] is False
+
+ validate_response = client.post("/v1/validate", json={"mthds_contents": [SIGNATURE_MTHDS], "allow_signatures": True})
+ assert validate_response.status_code == 200, validate_response.text
+ validate_body = validate_response.json()
+ assert body["pending_signatures"] == validate_body["pending_signatures"]
+ assert body["is_runnable"] == validate_body["is_runnable"]
+
+ @pytest.mark.parametrize("include_files", [False, None], ids=["declined", "omitted"])
+ def test_files_are_absent_unless_requested(self, include_files: bool | None):
+ client = _build_client()
+ payload: dict[str, Any] = {"files": _files(VALID_MTHDS)}
+ if include_files is not None:
+ payload["include_files"] = include_files
+ body = _valid_arm(client, payload)
+ assert "files" not in body
+
+ def test_include_files_echoes_the_inline_files_in_the_request_shape(self):
+ # A `source` the request omitted stays omitted: the echo is the request's own shape.
+ client = _build_client()
+ files = [{"content": VALID_MTHDS, "source": "main.mthds"}, {"content": SIBLING_MTHDS}]
+ body = _valid_arm(client, {"files": files, "include_files": True})
+ assert body["files"] == files
+
+ def test_include_files_echoes_a_method_refs_mthds_files_with_relative_paths(self, install_method_package: Callable[..., Path]):
+ # Only the package's `.mthds` files travel, each under its path relative to the package root.
+ install_method_package(files={"documents.mthds": VALID_MTHDS, "steps/wrap.mthds": SIBLING_MTHDS, "README.md": "# Not a bundle\n"})
+ client = _build_client()
+ body = _valid_arm(client, {"method_ref": STUB_METHOD_REF, "include_files": True})
+ assert sorted(body["files"], key=lambda item: item["source"]) == [
+ {"content": VALID_MTHDS, "source": "documents.mthds"},
+ {"content": SIBLING_MTHDS, "source": "steps/wrap.mthds"},
+ ]
+
+ @pytest.mark.parametrize(
+ "request_fields",
+ [
+ pytest.param({}, id="default-selection"),
+ pytest.param({"pipe_ref": "broken.not_a_pipe", "include_files": True}, id="unknown-ref-and-files"),
+ pytest.param({"all_pipes": True, "include_files": True}, id="all-pipes-and-files"),
+ ],
+ )
+ def test_invalid_closure_is_the_crate_verdict_carrying_nothing_else(self, request_fields: dict[str, Any]):
+ # The closure is resolved before any pipe is selected, so even a pipe_ref naming nothing
+ # answers the invalid verdict rather than a 422.
+ client = _build_client()
+ response = client.post(PIPE_IO_PATH, json={"files": [{"content": INVALID_MAIN_PIPE_MTHDS, "source": "broken.mthds"}], **request_fields})
+ assert response.status_code == 200, response.text
+ body = response.json()
+ assert body["is_valid"] is False
+ assert body["validation_errors"]
+ assert body["validation_errors"][0]["source"] == "broken.mthds"
+ assert body["message"]
+ for field_name in VALID_ARM_ONLY_FIELDS:
+ assert field_name not in body, f"the invalid arm never carries `{field_name}`"
+
+ @pytest.mark.parametrize(
+ ("contents", "request_fields", "error_type", "detail_fragment", "fix_fragment"),
+ [
+ pytest.param(
+ (VALID_MTHDS,), {"pipe_ref": "smoke.not_a_pipe"}, PIPE_NOT_FOUND_ERROR, "not found", "Check the pipe code", id="unknown-ref"
+ ),
+ pytest.param(
+ (VALID_MTHDS,),
+ {"pipe_ref": "smoke.not_a_pipe", "all_pipes": True},
+ PIPE_NOT_FOUND_ERROR,
+ "not found",
+ "Check the pipe code",
+ id="unknown-ref-under-all-pipes",
+ ),
+ pytest.param(
+ (NO_MAIN_PIPE_MTHDS,),
+ {},
+ PIPE_NOT_FOUND_ERROR,
+ "declares no `main_pipe`",
+ "Send a `pipe_ref` naming the pipe to select",
+ id="no-entry-pipe",
+ ),
+ pytest.param(
+ (VALID_MTHDS, SECOND_MAIN_PIPE_MTHDS),
+ {},
+ PIPE_AMBIGUOUS_ERROR,
+ "several `main_pipe`s",
+ "one of the declared `main_pipe`s",
+ id="several-entry-pipes",
+ ),
+ ],
+ )
+ def test_selection_refusals_carry_the_entry_lookup_error_type(
+ self, contents: tuple[str, ...], request_fields: dict[str, Any], error_type: str, detail_fragment: str, fix_fragment: str
+ ):
+ # A selection refusal is an input 422 like a malformed request, but its `error_type` is the
+ # pipelex entry-lookup class that names the failure, so a client branches on it; its problem
+ # `type` names the selection too, and its `user_action` names the fix for this very miss —
+ # a default chain that finds no entry pipe, or several, is no pipe-code typo.
+ client = _build_client()
+ response = client.post(PIPE_IO_PATH, json={"files": _files(*contents), **request_fields})
+ detail = _assert_input_422(response, error_type=error_type)
+ assert detail_fragment in detail
+ problem = response.json()
+ assert problem["type"] != client.post(PIPE_IO_PATH, json={}).json()["type"], "a selection refusal must not share the request-shape type"
+ assert problem["user_action"]["kind"] == "change_input"
+ assert fix_fragment in problem["user_action"]["detail"]
+
+ @pytest.mark.parametrize(
+ "payload",
+ [
+ pytest.param({}, id="neither"),
+ pytest.param({"pipe_ref": "smoke.echo"}, id="neither-with-pipe-ref"),
+ pytest.param({"files": [{"content": VALID_MTHDS}], "method_ref": STUB_METHOD_REF}, id="both"),
+ ],
+ )
+ def test_closure_selector_xor_is_a_request_shape_422(self, payload: dict[str, Any]):
+ client = _build_client()
+ _assert_input_422(client.post(PIPE_IO_PATH, json=payload), error_type=REQUEST_SHAPE_ERROR)
+
+ @pytest.mark.parametrize(
+ ("contents", "request_fields"),
+ [
+ pytest.param((VALID_MTHDS,), {}, id="entry-pipe"),
+ pytest.param((VALID_MTHDS, SIBLING_MTHDS), {"pipe_ref": "smoke.wrap_echo"}, id="named-pipe"),
+ pytest.param((VALID_MTHDS, SIBLING_MTHDS), {"all_pipes": True}, id="all-pipes"),
+ pytest.param((VALID_MTHDS, SECOND_MAIN_PIPE_MTHDS), {"all_pipes": True}, id="several-main-pipes"),
+ pytest.param((NO_MAIN_PIPE_MTHDS,), {"pipe_ref": "nomain.echo"}, id="no-main-pipe"),
+ pytest.param((SHAPES_MTHDS,), {}, id="multiplicity-and-structure"),
+ pytest.param((SIGNATURE_MTHDS,), {"all_pipes": True}, id="pending-signature"),
+ pytest.param(tuple(SIGNATURE_ONLY_BATCH), {"all_pipes": True}, id="signature-only-batch"),
+ pytest.param(tuple(HEADER_AND_DEFINITION_BATCH), {"all_pipes": True}, id="header-and-definition"),
+ ],
+ )
+ def test_artifacts_equal_validate_views(self, contents: tuple[str, ...], request_fields: dict[str, Any]):
+ # The pinning test: each map equals `/v1/validate`'s same-named view restricted to the same
+ # keys. Validate is asked first, so a closure it would refuse fails here rather than passing
+ # vacuously; `allow_signatures` lets it accept the signature closures this route accepts.
+ files = _files(*contents)
+ client = _build_client()
+ validate_response = client.post(
+ "/v1/validate",
+ json={
+ "mthds_contents": [item["content"] for item in files],
+ "mthds_sources": [item["source"] for item in files],
+ "views": ["input_form", "output_form"],
+ "allow_signatures": True,
+ },
+ )
+ assert validate_response.status_code == 200, validate_response.text
+ validate_body = validate_response.json()
+ assert validate_body["is_valid"] is True, validate_response.text
+
+ body = _valid_arm(client, {"files": files, **request_fields})
+ self._assert_maps_equal_validate(body, validate_body)
+
+ def test_artifacts_equal_validate_views_by_method_ref(self, install_method_package: Callable[..., Path]):
+ # The stub package holds `.mthds` files alone, so validate by `method_ref` loads exactly the
+ # closure this route reads (validate would also load a package's other files).
+ install_method_package(files={"documents.mthds": VALID_MTHDS, "steps/wrap.mthds": SIBLING_MTHDS})
+ client = _build_client()
+ validate_response = client.post("/v1/validate", json={"method_ref": STUB_METHOD_REF, "views": ["input_form", "output_form"]})
+ assert validate_response.status_code == 200, validate_response.text
+ validate_body = validate_response.json()
+ assert validate_body["is_valid"] is True, validate_response.text
+
+ body = _valid_arm(client, {"method_ref": STUB_METHOD_REF, "all_pipes": True})
+ _assert_keys(body, {"smoke.echo", "smoke.wrap_echo"})
+ self._assert_maps_equal_validate(body, validate_body)
+
+ def _assert_maps_equal_validate(self, body: dict[str, Any], validate_body: dict[str, Any]) -> None:
+ keys = set(body["pipe_io_contracts"])
+ assert keys, "the valid arm describes at least one pipe"
+ _assert_keys(body, keys)
+ for field_name in ARTIFACT_FIELDS:
+ validate_map = validate_body[field_name]
+ assert keys <= set(validate_map), f"`{field_name}` names pipes /v1/validate does not: {sorted(keys - set(validate_map))}"
+ assert body[field_name] == {ref: validate_map[ref] for ref in keys}, f"`{field_name}` diverges from /v1/validate's view"
+
+ @pytest.mark.parametrize(
+ ("payload", "expected_status"),
+ [
+ pytest.param({"files": [{"content": VALID_MTHDS}]}, 200, id="valid-arm"),
+ pytest.param({"files": [{"content": NO_MAIN_PIPE_MTHDS}], "all_pipes": True, "include_files": True}, 200, id="all-pipes"),
+ pytest.param({"files": [{"content": VALID_MTHDS}], "pipe_ref": "smoke.not_a_pipe"}, 422, id="selection-422"),
+ pytest.param({"files": [{"content": NO_MAIN_PIPE_MTHDS}]}, 422, id="no-entry-pipe-422"),
+ ],
+ )
+ def test_every_exit_tears_its_library_down(self, mocker: MockerFixture, payload: dict[str, Any], expected_status: int):
+ # The engine core leaves the library loaded + current on success; the route owns teardown on
+ # every exit after it, a selection refusal included. Conservation: opens == teardowns.
+ library_manager = get_library_manager()
+ open_spy = mocker.spy(library_manager, "open_library")
+ teardown_spy = mocker.spy(library_manager, "teardown")
+
+ client = _build_client()
+ response = client.post(PIPE_IO_PATH, json=payload)
+
+ assert response.status_code == expected_status, response.text
+ assert open_spy.call_count == 1
+ created_library_id, _ = open_spy.spy_return
+ teardown_spy.assert_called_once_with(library_id=created_library_id)
+
+ def test_an_underivable_artifact_is_a_no_verdict_500_and_still_tears_down(self, mocker: MockerFixture):
+ # `PipeIOContractError` is left to the global handler, exactly as on `/v1/validate`: a fault of
+ # the tool, not a verdict about the method. The library is still torn down.
+ mocker.patch(
+ "pipelex_api.routes.pipelex.pipe_io.build_pipe_io_artifacts",
+ side_effect=PipeIOContractError(message="Failed to render the JSON Schema for the output of pipe 'smoke.echo'"),
+ )
+ library_manager = get_library_manager()
+ open_spy = mocker.spy(library_manager, "open_library")
+ teardown_spy = mocker.spy(library_manager, "teardown")
+
+ client = _build_client()
+ response = client.post(PIPE_IO_PATH, json={"files": [{"content": VALID_MTHDS}]})
+
+ assert response.status_code == 500, response.text
+ assert response.headers["content-type"] == "application/problem+json"
+ assert "is_valid" not in response.json()
+ assert open_spy.call_count == 1
+ assert teardown_spy.call_count == 1
diff --git a/api/tests/unit/test_pipeline_bundle.py b/api/tests/unit/test_pipeline_bundle.py
new file mode 100644
index 000000000..61dd87175
--- /dev/null
+++ b/api/tests/unit/test_pipeline_bundle.py
@@ -0,0 +1,171 @@
+"""Route-level tests for the method-bundle transport on /execute and /start.
+
+The pipeline runner is mocked (as in `test_pipeline_routes`); these assert that
+the API layer KEEPS the proven run path for a bundle — the bundle's `.mthds` text
+is passed as `mthds_contents` (so the engine resolves `main_pipe` exactly as for a
+plain run) — while ONLY the non-`.mthds` files (custom PipeFunc `.py`, etc.) are
+materialized into a temporary `library_dirs` directory for source capture. They
+also assert the custom-Python sandbox gate and the both-forms guard.
+"""
+
+import base64
+import io
+import zipfile
+from pathlib import Path
+from typing import Any
+
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+from pipelex.pipeline.pipeline_response import PipelexRunResultStart, RunState
+from pytest_mock import MockerFixture
+
+from pipelex_api.exception_handlers import register_exception_handlers
+from pipelex_api.routes.pipelex.pipeline import router as pipeline_router
+from tests.unit._constants import VALID_MTHDS
+
+_PIPE_FUNC_PY = "def echo(working_memory):\n return 'hi'\n"
+
+
+def _zip_b64(files: dict[str, str]) -> str:
+ buffer = io.BytesIO()
+ with zipfile.ZipFile(buffer, "w", zipfile.ZIP_DEFLATED) as archive:
+ for name, content in files.items():
+ archive.writestr(name, content)
+ return base64.b64encode(buffer.getvalue()).decode("ascii")
+
+
+def _build_client(mocker: MockerFixture) -> tuple[TestClient, dict[str, Any]]:
+ """Wire an app whose ApiRunner is mocked and records what the run actually saw.
+
+ The `snapshot` captures BOTH what the runner was asked to run — the
+ `mthds_contents` passed to `execute`/`start` — and the `library_dirs` it was
+ constructed with plus the files on disk at run time. Together they prove the
+ split: the `.mthds` travels as `mthds_contents`, only the `.py` hits disk, and
+ the temp dir is torn down after the request.
+ """
+ app = FastAPI()
+ app.include_router(pipeline_router, prefix="/v1")
+ register_exception_handlers(app)
+
+ snapshot: dict[str, Any] = {}
+
+ fake_execute_response = mocker.MagicMock()
+ # `/execute` now applies pipelex's `apply_tokens_usage_wire_shape` to the dump, which
+ # rewrites `pipe_output.tokens_usages` — so the dump needs a `pipe_output` and the
+ # response a `tokens_usages` (None here: these tests assert on the run path, not usage).
+ fake_execute_response.model_dump.return_value = {
+ "pipeline_run_id": "run-1",
+ "state": "COMPLETED",
+ "pipe_output": {"working_memory": {"root": {}, "aliases": {}}},
+ }
+ fake_execute_response.pipe_output.tokens_usages = None
+
+ def _record(library_dirs: list[str] | None, run_kwargs: dict[str, Any]) -> None:
+ snapshot["library_dirs"] = library_dirs
+ snapshot["mthds_contents"] = run_kwargs.get("mthds_contents")
+ if library_dirs:
+ root = Path(library_dirs[0])
+ snapshot["dir_exists"] = root.exists()
+ snapshot["files"] = sorted(path.relative_to(root).as_posix() for path in root.rglob("*") if path.is_file())
+ else:
+ snapshot["files"] = None
+
+ def _make_runner(**kwargs: Any) -> Any:
+ library_dirs: list[str] | None = kwargs.get("library_dirs")
+ runner = mocker.MagicMock()
+
+ async def _execute(**run_kwargs: Any) -> Any:
+ _record(library_dirs, run_kwargs)
+ return fake_execute_response
+
+ async def _start(**run_kwargs: Any) -> Any:
+ _record(library_dirs, run_kwargs)
+ return PipelexRunResultStart(
+ pipeline_run_id="run-1",
+ created_at="2026-01-15T12:00:00Z",
+ state=RunState.STARTED,
+ workflow_id="wf-1",
+ )
+
+ runner.execute = _execute
+ runner.start = _start
+ return runner
+
+ mocker.patch("pipelex_api.routes.pipelex.pipeline.ApiRunner", side_effect=_make_runner)
+ return TestClient(app), snapshot
+
+
+class TestPipelineBundle:
+ def test_mthds_only_bundle_rides_mthds_contents_no_library_dir(self, mocker: MockerFixture):
+ """A `.mthds`-only bundle takes the proven path: its text becomes `mthds_contents`
+ (so `main_pipe` resolves as always) and NO temp library dir is created.
+ """
+ client, snapshot = _build_client(mocker)
+ response = client.post("/v1/execute", json={"files": {"main.mthds": VALID_MTHDS}, "inputs": {"text": "hi"}})
+ assert response.status_code == 200
+ assert snapshot["mthds_contents"] == [VALID_MTHDS]
+ assert snapshot["library_dirs"] is None
+
+ def test_zip_bundle_rides_mthds_contents(self, mocker: MockerFixture):
+ client, snapshot = _build_client(mocker)
+ bundle = _zip_b64({"main.mthds": VALID_MTHDS})
+ response = client.post("/v1/execute", json={"bundle_b64": bundle, "inputs": {"text": "hi"}})
+ assert response.status_code == 200
+ assert snapshot["mthds_contents"] == [VALID_MTHDS]
+ assert snapshot["library_dirs"] is None
+
+ def test_no_bundle_passes_request_mthds_contents(self, mocker: MockerFixture):
+ client, snapshot = _build_client(mocker)
+ response = client.post("/v1/execute", json={"pipe_code": "echo", "mthds_contents": [VALID_MTHDS], "inputs": {}})
+ assert response.status_code == 200
+ assert snapshot["library_dirs"] is None
+ assert snapshot["mthds_contents"] == [VALID_MTHDS]
+
+ def test_python_bundle_forbidden_when_not_hosted(self, mocker: MockerFixture):
+ mocker.patch("pipelex_api.routes.pipelex.pipeline.is_pipe_func_sandbox_hosted", return_value=False)
+ client, _ = _build_client(mocker)
+ response = client.post("/v1/execute", json={"files": {"main.mthds": VALID_MTHDS, "funcs/pipe_func.py": _PIPE_FUNC_PY}})
+ assert response.status_code == 403
+ assert response.headers["content-type"] == "application/problem+json"
+ assert response.json()["error_type"] == "CustomCodeRequiresSandbox"
+
+ def test_python_bundle_splits_mthds_from_py_when_hosted(self, mocker: MockerFixture):
+ """The key fix: `.mthds` → `mthds_contents` (main_pipe path), ONLY the `.py`
+ is materialized to the temp `library_dirs` for source capture.
+ """
+ mocker.patch("pipelex_api.routes.pipelex.pipeline.is_pipe_func_sandbox_hosted", return_value=True)
+ client, snapshot = _build_client(mocker)
+ response = client.post("/v1/execute", json={"files": {"main.mthds": VALID_MTHDS, "funcs/pipe_func.py": _PIPE_FUNC_PY}})
+ assert response.status_code == 200
+ # The .mthds took the proven path, not the disk.
+ assert snapshot["mthds_contents"] == [VALID_MTHDS]
+ # Only the Python landed in the library dir.
+ assert snapshot["files"] == ["funcs/pipe_func.py"]
+ assert snapshot["dir_exists"] is True
+ # Temp dir is cleaned once the request returns.
+ assert not Path(snapshot["library_dirs"][0]).exists()
+
+ def test_both_forms_rejected_via_route(self, mocker: MockerFixture):
+ client, _ = _build_client(mocker)
+ response = client.post(
+ "/v1/execute",
+ json={"files": {"main.mthds": VALID_MTHDS}, "bundle_b64": _zip_b64({"main.mthds": VALID_MTHDS})},
+ )
+ assert response.status_code == 422
+ assert response.json()["error_type"] == "InvalidBundle"
+
+ def test_start_bundle_rides_mthds_contents(self, mocker: MockerFixture):
+ client, snapshot = _build_client(mocker)
+ response = client.post("/v1/start", json={"files": {"main.mthds": VALID_MTHDS}, "inputs": {"text": "hi"}})
+ assert response.status_code == 202
+ assert snapshot["mthds_contents"] == [VALID_MTHDS]
+ assert snapshot["library_dirs"] is None
+
+ def test_bundle_and_mthds_contents_are_mutually_exclusive(self, mocker: MockerFixture):
+ client, _ = _build_client(mocker)
+ response = client.post(
+ "/v1/execute",
+ json={"files": {"main.mthds": VALID_MTHDS}, "mthds_contents": [VALID_MTHDS]},
+ )
+ assert response.status_code == 422
+ assert "mutually exclusive" in response.text
diff --git a/api/tests/unit/test_pipeline_routes.py b/api/tests/unit/test_pipeline_routes.py
new file mode 100644
index 000000000..452e1db2e
--- /dev/null
+++ b/api/tests/unit/test_pipeline_routes.py
@@ -0,0 +1,495 @@
+"""Smoke + hardening tests for /execute and /start (MTHDS Protocol run routes).
+
+The actual pipeline runner is mocked: we only assert that the API layer
+parses, validates, dispatches, and shapes responses correctly.
+"""
+
+from typing import Any, cast
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+from pipelex.base_exceptions import PipelexConfigError
+from pipelex.cogt.llm.llm_report import LLMTokensUsage
+from pipelex.cogt.usage.cost_category import CostCategory
+from pipelex.cogt.usage.token_category import TokenCategory
+from pipelex.pipeline.pipeline_response import PipelexRunResultStart, RunState
+from pipelex.system.job_metadata import JobMetadata, RunMetadata
+from pipelex.system.storage_scope import SINGLE_TENANT_USER_ID
+from pytest_mock import MockerFixture
+
+import pipelex_api.routes.pipelex.pipeline as pipeline_module
+from pipelex_api.exception_handlers import register_exception_handlers
+from pipelex_api.middleware import REQUEST_ID_HEADER, RequestIdMiddleware
+from pipelex_api.routes.pipelex.pipeline import router as pipeline_router
+from tests.unit._constants import VALID_MTHDS
+
+
+def _build_client(mocker: MockerFixture, *, with_request_id_middleware: bool = False) -> tuple[TestClient, Any, Any]:
+ """Wire a FastAPI app whose pipeline runner is fully mocked.
+
+ Returns (client, execute_mock, start_mock). `with_request_id_middleware`
+ wraps the ASGI app in `RequestIdMiddleware` so an inbound `X-Request-ID`
+ header binds the request-scoped contextvar the route reads.
+ """
+ app = FastAPI()
+ app.include_router(pipeline_router, prefix="/v1")
+ register_exception_handlers(app)
+
+ fake_execute_response = mocker.MagicMock()
+ fake_execute_response.model_dump.return_value = {
+ "pipeline_run_id": "test-run-1",
+ "created_at": "2026-01-15T12:00:00Z",
+ "state": "COMPLETED",
+ "finished_at": "2026-01-15T12:00:01Z",
+ "main_stuff_name": "main_stuff",
+ "pipe_output": {"working_memory": {"root": {}, "aliases": {}}},
+ }
+
+ fake_start_response = PipelexRunResultStart(
+ pipeline_run_id="test-run-1",
+ created_at="2026-01-15T12:00:00Z",
+ state=RunState.STARTED,
+ workflow_id="wf-1",
+ )
+
+ fake_runner = mocker.MagicMock()
+ fake_runner.execute = mocker.AsyncMock(return_value=fake_execute_response)
+ fake_runner.start = mocker.AsyncMock(return_value=fake_start_response)
+ mocker.patch("pipelex_api.routes.pipelex.pipeline.ApiRunner", return_value=fake_runner)
+
+ asgi_app = RequestIdMiddleware(app) if with_request_id_middleware else app
+ return TestClient(asgi_app), fake_runner.execute, fake_runner.start
+
+
+class TestPipelineRoutes:
+ def test_execute_happy_path(self, mocker: MockerFixture):
+ client, execute_mock, _ = _build_client(mocker)
+ response = client.post(
+ "/v1/execute",
+ json={"pipe_code": "echo", "mthds_contents": [VALID_MTHDS], "inputs": {"text": "hello"}},
+ )
+ assert response.status_code == 200
+ execute_mock.assert_awaited_once()
+
+ def test_execute_trims_tokens_usages_to_wire_records(self, mocker: MockerFixture):
+ """/execute emits TokensUsageRecord wire records on pipe_output.tokens_usages — never
+ the internal usage models with their job_metadata plumbing and unit_costs rate table.
+ """
+ client, execute_mock, _ = _build_client(mocker)
+ tokens_usage = LLMTokensUsage(
+ job_metadata=JobMetadata(
+ run_metadata=RunMetadata(user_id="user-1", storage_scope="user-1", read_scope=None, pipeline_run_id="plr-1"), pipe_code="echo"
+ ),
+ inference_model_name="test-model",
+ inference_model_id="test-model-id",
+ nb_tokens_by_category={TokenCategory.INPUT: 10, TokenCategory.OUTPUT: 5},
+ unit_costs={CostCategory.INPUT: 1.0, CostCategory.OUTPUT: 2.0},
+ )
+ # The route reads the usages off the response object and writes the trimmed
+ # records into the dump, so seeding the object alone is what drives the assertions.
+ execute_mock.return_value.pipe_output.tokens_usages = [tokens_usage]
+
+ response = client.post(
+ "/v1/execute",
+ json={"pipe_code": "echo", "mthds_contents": [VALID_MTHDS], "inputs": {"text": "hello"}},
+ )
+ assert response.status_code == 200
+ records = response.json()["pipe_output"]["tokens_usages"]
+ assert len(records) == 1
+ record = records[0]
+ assert record["model_type"] == "llm"
+ assert record["pipe_code"] == "echo"
+ assert record["nb_tokens_by_category"] == {"input": 10, "output": 5}
+ assert record["cost"] == 10 * (1.0 / 1_000_000) + 5 * (2.0 / 1_000_000)
+ assert "job_metadata" not in record
+ assert "unit_costs" not in record
+
+ def test_execute_rejects_non_object_body(self, mocker: MockerFixture):
+ client, _, _ = _build_client(mocker)
+ response = client.post(
+ "/v1/execute",
+ content=b'"just a string"',
+ headers={"content-type": "application/json"},
+ )
+ assert response.status_code == 422
+ assert response.headers["content-type"] == "application/problem+json"
+ assert response.json()["error_type"] == "InvalidJSON"
+
+ def test_execute_rejects_invalid_json(self, mocker: MockerFixture):
+ client, _, _ = _build_client(mocker)
+ response = client.post(
+ "/v1/execute",
+ content=b"{not json",
+ headers={"content-type": "application/json"},
+ )
+ assert response.status_code == 422
+ assert response.headers["content-type"] == "application/problem+json"
+ assert response.json()["error_type"] == "InvalidJSON"
+
+ def test_execute_rejects_recursion_error(self, mocker: MockerFixture):
+ # A deeply nested JSON array exhausts the parser's recursion budget and raises
+ # `RecursionError` inside `json.loads`. That is a caller-input failure and must map
+ # to 422 InvalidJSON, not escape to the catch-all 500 handler.
+ client, _, _ = _build_client(mocker)
+ depth = 100_000
+ response = client.post(
+ "/v1/execute",
+ content=b'{"inputs": ' + b"[" * depth + b"]" * depth + b"}",
+ headers={"content-type": "application/json"},
+ )
+ assert response.status_code == 422
+ assert response.headers["content-type"] == "application/problem+json"
+ problem = response.json()
+ assert problem["error_type"] == "InvalidJSON"
+ assert problem["error_domain"] == "input"
+ # The opaque-500 sentinel must never appear for a caller-input failure.
+ assert problem["error_type"] != "InternalServerError"
+
+ @pytest.mark.parametrize("route", ["/v1/execute", "/v1/start"])
+ def test_run_routes_never_instantiate_a_class_the_body_names(self, mocker: MockerFixture, route: str):
+ """The kajson remote-code-execution gadget: a body naming `subprocess.Popen` used to make
+ the runner import it and call it with the body's arguments at decode time. The run body is
+ now plain JSON, so the marker is refused with a 422 and nothing is ever called.
+ """
+ client, execute_mock, start_mock = _build_client(mocker)
+ popen_mock = mocker.patch("subprocess.Popen")
+ response = client.post(
+ route,
+ json={
+ "pipe_code": "echo",
+ "mthds_contents": [VALID_MTHDS],
+ "inputs": {"text": {"__class__": "Popen", "__module__": "subprocess", "args": ["touch", "pipelex-api-rce-probe"]}},
+ },
+ )
+ assert response.status_code == 422
+ assert response.headers["content-type"] == "application/problem+json"
+ problem = response.json()
+ assert problem["error_type"] == "ReservedObjectKey"
+ assert problem["error_domain"] == "input"
+ popen_mock.assert_not_called()
+ execute_mock.assert_not_awaited()
+ start_mock.assert_not_awaited()
+
+ @pytest.mark.parametrize(
+ ("label", "body", "reserved_key"),
+ [
+ ("top_level_marker", {"__class__": "X", "__module__": "json", "pipe_code": "echo"}, "__class__"),
+ ("module_key_alone_in_an_input", {"pipe_code": "echo", "inputs": {"doc": {"__module__": "subprocess"}}}, "__module__"),
+ ("marker_inside_a_list_item", {"pipe_code": "echo", "inputs": {"docs": [{"text": "a"}, {"__class__": "Popen"}]}}, "__class__"),
+ ("kajson_class_source_key", {"pipe_code": "echo", "__kajson_class_source__": "class X: pass"}, "__kajson_class_source__"),
+ ("any_kajson_prefixed_key", {"pipe_code": "echo", "inputs": {"doc": {"__kajson_hint": 1}}}, "__kajson_hint"),
+ ("marker_inside_an_extension_field", {"pipe_code": "echo", "analytics_groups": {"__class__": "X"}}, "__class__"),
+ ],
+ )
+ def test_execute_refuses_reserved_object_keys(self, mocker: MockerFixture, label: str, body: dict[str, Any], reserved_key: str):
+ """A key a kajson decoder reads as a class marker is refused at any depth of the body, the
+ extension fields included, even though the body is parsed as plain JSON: accepted as data,
+ it would come back to life when the runtime round-trips the inputs through kajson.
+ """
+ client, execute_mock, _ = _build_client(mocker)
+ response = client.post("/v1/execute", json=body)
+ assert response.status_code == 422, label
+ assert response.headers["content-type"] == "application/problem+json", label
+ problem = response.json()
+ assert problem["error_type"] == "ReservedObjectKey", label
+ assert problem["error_domain"] == "input", label
+ assert f"'{reserved_key}'" in problem["detail"], label
+ execute_mock.assert_not_awaited()
+
+ def test_execute_bounds_the_reserved_key_it_echoes(self, mocker: MockerFixture):
+ """Any key starting with `__kajson` is refused, so the caller picks its length. The `detail`
+ names it cut to the correlation-field bound, since the detail is also logged as a field.
+ """
+ client, _, _ = _build_client(mocker)
+ long_key = "__kajson" + "k" * 100_000
+ response = client.post("/v1/execute", json={"pipe_code": "echo", "inputs": {"doc": {long_key: 1}}})
+ assert response.status_code == 422
+ problem = response.json()
+ assert problem["error_type"] == "ReservedObjectKey"
+ assert "'__kajsonkkkk" in problem["detail"]
+ assert "…'" in problem["detail"]
+ assert len(problem["detail"]) < 1_000
+
+ def test_execute_accepts_marker_lookalikes_as_plain_data(self, mocker: MockerFixture):
+ """Only the reserved keys themselves are refused: a value that mentions `__class__`, and a
+ key that merely resembles a marker, are data and reach the runner exactly as sent.
+ """
+ client, execute_mock, _ = _build_client(mocker)
+ inputs = {
+ "text": "__class__ and __module__ are only words here",
+ "doc": {"__classic__": "not a marker", "kajson": "neither is this"},
+ }
+ response = client.post(
+ "/v1/execute",
+ json={"pipe_code": "echo", "mthds_contents": [VALID_MTHDS], "inputs": inputs},
+ )
+ assert response.status_code == 200
+ execute_mock.assert_awaited_once()
+ assert execute_mock.await_args.kwargs["inputs"] == inputs
+
+ def test_start_happy_path_returns_202(self, mocker: MockerFixture):
+ client, _, start_mock = _build_client(mocker)
+ response = client.post(
+ "/v1/start",
+ json={
+ "pipe_code": "echo",
+ "mthds_contents": [VALID_MTHDS],
+ "inputs": {"text": "hello"},
+ "callback_urls": ["https://example.com/done"],
+ },
+ )
+ # Protocol: `POST /start` answers 202 Accepted with a StartAck.
+ assert response.status_code == 202
+ body = response.json()
+ assert body["pipeline_run_id"] == "test-run-1"
+ assert body["state"] == "STARTED"
+ start_mock.assert_awaited_once()
+ kwargs = start_mock.await_args.kwargs
+ assert kwargs["callback_urls"] == ["https://example.com/done"]
+
+ def test_start_forwards_client_pipeline_run_id(self, mocker: MockerFixture):
+ # D11: the source-available runner ACCEPTS a client-supplied pipeline_run_id and
+ # forwards it to the runner's `start` as the `pipeline_run_id` kwarg.
+ client, _, start_mock = _build_client(mocker)
+ response = client.post(
+ "/v1/start",
+ json={
+ "pipe_code": "echo",
+ "mthds_contents": [VALID_MTHDS],
+ "inputs": {"text": "hello"},
+ "pipeline_run_id": "client-chosen-run-42",
+ },
+ )
+ assert response.status_code == 202
+ start_mock.assert_awaited_once()
+ assert start_mock.await_args.kwargs["pipeline_run_id"] == "client-chosen-run-42"
+
+ def test_parse_request_binds_pipe_code_and_pipeline_run_id_to_state(self, mocker: MockerFixture):
+ # End-to-end: a real POST that goes through `_parse_request` must bind
+ # `pipe_code` / `pipeline_run_id` on `request.state` so that a
+ # downstream failure (here: `start` raising `PipelexConfigError`)
+ # is logged with both fields. The unit-level tests pin the
+ # handler->getter->log path; this one pins that `_parse_request` itself
+ # actually writes to `request.state` against the production route.
+ # The two values reach the record as attributes of their own, so nothing about their
+ # spelling matters here any more — the assertions read the `fields=` mapping the handler
+ # handed the runtime, not a rendered line.
+ client, _, start_mock = _build_client(mocker)
+ body_pipe_code = "echo"
+ body_pipeline_run_id = "run-end-to-end-0001"
+ start_mock.side_effect = PipelexConfigError("simulated config fault inside the runner")
+ log_spy = mocker.patch("pipelex_api.exception_handlers.log")
+ response = client.post(
+ "/v1/start",
+ json={
+ "pipe_code": body_pipe_code,
+ "mthds_contents": [VALID_MTHDS],
+ "inputs": {"text": "hello"},
+ "pipeline_run_id": body_pipeline_run_id,
+ },
+ )
+ assert response.status_code == 500
+ log_spy.error.assert_called_once()
+ fields = log_spy.error.call_args.kwargs["fields"]
+ assert fields["pipe_code"] == body_pipe_code
+ assert fields["pipeline_run_id"] == body_pipeline_run_id
+
+ def test_parse_request_drops_empty_correlation_fields(self, mocker: MockerFixture):
+ # An empty-string `pipe_code` / `pipeline_run_id` in the body must NOT reach the record
+ # as an empty attribute, which a downstream query filtering on presence would read as a
+ # real value. `_coerce_correlation_field` normalizes empty strings to `None`, and
+ # `_emit_api_error` drops those.
+ client, _, start_mock = _build_client(mocker)
+ start_mock.side_effect = PipelexConfigError("simulated config fault")
+ log_spy = mocker.patch("pipelex_api.exception_handlers.log")
+ response = client.post(
+ "/v1/start",
+ json={
+ "pipe_code": "",
+ "mthds_contents": [VALID_MTHDS],
+ "inputs": {"text": "hello"},
+ "pipeline_run_id": "",
+ },
+ )
+ assert response.status_code == 500
+ log_spy.error.assert_called_once()
+ fields = log_spy.error.call_args.kwargs["fields"]
+ assert "pipe_code" not in fields
+ assert "pipeline_run_id" not in fields
+
+ def test_parse_request_caps_oversized_pipe_code(self, mocker: MockerFixture):
+ # `RunRequest.pipe_code` carries no Pydantic max_length, so a
+ # caller can in principle send a megabyte-long string. The binding
+ # site caps the value that reaches the operator record, so a single failed request cannot
+ # blow a log sink's per-record budget. 256 is the limit; anything longer is silently
+ # truncated for the log surface (the actual `run_request.pipe_code` passed to the runner
+ # is unchanged — only the `request.state` mirror is capped).
+ client, _, start_mock = _build_client(mocker)
+ start_mock.side_effect = PipelexConfigError("simulated config fault")
+ log_spy = mocker.patch("pipelex_api.exception_handlers.log")
+ oversized = "x" * 5000
+ response = client.post(
+ "/v1/start",
+ json={
+ "pipe_code": oversized,
+ "mthds_contents": [VALID_MTHDS],
+ "inputs": {"text": "hello"},
+ },
+ )
+ assert response.status_code == 500
+ log_spy.error.assert_called_once()
+ fields = log_spy.error.call_args.kwargs["fields"]
+ # The capped value carries; the original oversized string does not — proof the cap fires
+ # and bounds what one request costs a sink.
+ assert fields["pipe_code"] == "x" * 256
+
+ def test_parse_request_binds_pipe_code_before_extras_validation(self, mocker: MockerFixture):
+ # The binding must run BEFORE `_validate_extras` so an SSRF-rejected
+ # callback URL (or any other extras-validation 422) still rides the
+ # caller's `pipe_code` onto the operator record. The unit-level tests
+ # cannot exercise this ordering — only an end-to-end POST does.
+ client, _, _ = _build_client(mocker)
+ log_spy = mocker.patch("pipelex_api.exception_handlers.log")
+ body_pipe_code = "echo"
+ response = client.post(
+ "/v1/start",
+ json={
+ "pipe_code": body_pipe_code,
+ # An AWS-metadata URL — blocked by `_is_disallowed_host`, so
+ # `_validate_extras` raises 422 before `from_body` runs.
+ "callback_urls": ["http://169.254.169.254/latest/meta-data/"],
+ },
+ )
+ assert response.status_code == 422
+ # An INPUT-domain 422 logs at `warning`, not `error`.
+ log_spy.warning.assert_called_once()
+ assert log_spy.warning.call_args.kwargs["fields"]["pipe_code"] == body_pipe_code
+
+ def test_start_propagates_request_id_to_runner(self, mocker: MockerFixture):
+ # The middleware stores the inbound `X-Request-ID` on `request.state`; the route reads it
+ # back via `request_id_of(request)` and passes it as
+ # `request_id=` to `ApiRunner.start`, which forwards it to
+ # `pipeline_run_setup(...)` so it lands on `RunMetadata.request_id`.
+ # Without this hop the worker's lines for the run would carry no `request_id`.
+ client, _, start_mock = _build_client(mocker, with_request_id_middleware=True)
+ inbound_request_id = "01HNJZ4XR7K3Q9D8MWAQ7FY2E5"
+ response = client.post(
+ "/v1/start",
+ json={"pipe_code": "echo", "mthds_contents": [VALID_MTHDS], "inputs": {"text": "hello"}},
+ headers={REQUEST_ID_HEADER: inbound_request_id},
+ )
+ assert response.status_code == 202
+ assert response.headers[REQUEST_ID_HEADER] == inbound_request_id
+ start_mock.assert_awaited_once()
+ assert start_mock.await_args.kwargs["request_id"] == inbound_request_id
+
+ def test_execute_propagates_request_id_to_runner(self, mocker: MockerFixture):
+ # The `/execute` twin of the `/start` hop above: `ApiRunner.execute` forwards the id to the
+ # runtime's `execute`, which puts it on `RunMetadata.request_id`. On a Temporal deployment
+ # the whole run happens on a worker, which reads the id from that payload and nowhere else.
+ client, execute_mock, _ = _build_client(mocker, with_request_id_middleware=True)
+ inbound_request_id = "01HNJZ4XR7K3Q9D8MWAQ7FY2E5"
+ response = client.post(
+ "/v1/execute",
+ json={"pipe_code": "echo", "mthds_contents": [VALID_MTHDS], "inputs": {"text": "hello"}},
+ headers={REQUEST_ID_HEADER: inbound_request_id},
+ )
+ assert response.status_code == 200
+ assert response.headers[REQUEST_ID_HEADER] == inbound_request_id
+ execute_mock.assert_awaited_once()
+ assert execute_mock.await_args.kwargs["request_id"] == inbound_request_id
+
+ @pytest.mark.parametrize(
+ "bad_url",
+ [
+ "http://169.254.169.254/latest/meta-data/", # AWS metadata
+ "http://127.0.0.1:8081/internal", # loopback
+ "http://10.0.0.5/private", # private RFC1918
+ "http://localhost/x", # localhost name
+ "file:///etc/passwd", # disallowed scheme
+ "ftp://example.com/x", # disallowed scheme
+ ],
+ )
+ def test_start_rejects_ssrf_callbacks(self, mocker: MockerFixture, bad_url: str):
+ client, _, start_mock = _build_client(mocker)
+ response = client.post(
+ "/v1/start",
+ json={"pipe_code": "echo", "callback_urls": [bad_url]},
+ )
+ assert response.status_code == 422
+ assert response.headers["content-type"] == "application/problem+json"
+ assert response.json()["error_type"] == "InvalidCallbackUrls"
+ start_mock.assert_not_awaited()
+
+ def test_start_rejects_too_many_callbacks(self, mocker: MockerFixture):
+ client, _, start_mock = _build_client(mocker)
+ response = client.post(
+ "/v1/start",
+ json={
+ "pipe_code": "echo",
+ "callback_urls": [f"https://example.com/{idx}" for idx in range(20)],
+ },
+ )
+ # `callback_urls` exceeds `PipelineApiExtras.max_length`. The route
+ # validates extras explicitly (`_validate_extras`) and re-raises the
+ # resulting Pydantic `ValidationError` via `raise_validation_error`
+ # with the more-specific `InvalidCallbackUrls` error_type — so the
+ # response is RFC 7807 422 / `application/problem+json` but classified
+ # one level finer than the generic FastAPI automatic-validation path.
+ assert response.status_code == 422
+ assert response.headers["content-type"] == "application/problem+json"
+ assert response.json()["error_type"] == "InvalidCallbackUrls"
+ start_mock.assert_not_awaited()
+
+
+class TestStorageScopeReachesTheRun:
+ """`storage_scope` must survive the wire -> extras -> runner hop.
+
+ Every failure on this path is SILENT by construction, which is why the
+ constructor kwarg is asserted rather than just the status code.
+ The route hands the validated extras to `ApiRunner` field by field, so a
+ keyword left out there is dropped with no error; the run then falls back to
+ the caller's own id, writes under
+ the wrong prefix, and still answers 202. On the hosted platform that is
+ exactly the org-scoped storage bug — one tenant's output under another
+ tenant's key — reported as success.
+ """
+
+ def test_body_storage_scope_reaches_the_runner(self, mocker: MockerFixture):
+ client, _, start_mock = _build_client(mocker)
+ response = client.post(
+ "/v1/start",
+ json={"pipe_code": "echo", "storage_scope": "org_a/mt_b/run_c"},
+ )
+ assert response.status_code == 202
+ start_mock.assert_awaited_once()
+ runner_cls = cast("Any", pipeline_module.ApiRunner)
+ assert runner_cls.call_args.kwargs["storage_scope"] == "org_a/mt_b/run_c"
+
+ def test_absent_scope_falls_back_to_the_caller_not_a_shared_literal(self, mocker: MockerFixture):
+ # The fallback must be per-caller. A shared constant would pool every
+ # caller of an identity-bearing deployment into one namespace — the
+ # `anonymous/` collision in a new spelling.
+ client, _, _ = _build_client(mocker)
+ response = client.post("/v1/start", json={"pipe_code": "echo"})
+ assert response.status_code == 202
+ runner_cls = cast("Any", pipeline_module.ApiRunner)
+ kwargs = runner_cls.call_args.kwargs
+ assert kwargs["storage_scope"] == kwargs["user_id"] == SINGLE_TENANT_USER_ID
+
+ @pytest.mark.parametrize(
+ "bad_scope",
+ ["../etc/passwd", "/absolute", "org//empty", "org/../escape", "", "a/b/c/d"],
+ )
+ def test_traversal_and_overlong_scopes_are_refused_at_the_wire(self, mocker: MockerFixture, bad_scope: str):
+ # A 422 naming the field, not a 500 from deep inside the run: the value
+ # becomes a storage key prefix, so a traversal in it escapes the tenant.
+ client, _, start_mock = _build_client(mocker)
+ response = client.post("/v1/start", json={"pipe_code": "echo", "storage_scope": bad_scope})
+ assert response.status_code == 422
+ assert response.headers["content-type"] == "application/problem+json"
+ # Classified by the field that failed: this used to answer `InvalidCallbackUrls`
+ # on a request that carried no callback at all.
+ assert response.json()["error_type"] == "InvalidStorageScope"
+ start_mock.assert_not_awaited()
diff --git a/api/tests/unit/test_problem_document.py b/api/tests/unit/test_problem_document.py
new file mode 100644
index 000000000..c2de44dfd
--- /dev/null
+++ b/api/tests/unit/test_problem_document.py
@@ -0,0 +1,152 @@
+"""Unit tests for the RFC 7807 problem-document builder."""
+
+import pytest
+from pipelex.base_exceptions import DisclosureMode, ErrorDomain, ErrorReport, PipelexConfigError
+from pipelex.cogt.inference.error_classification import ProviderErrorMetadata, UserAction, UserActionKind
+from pipelex.cogt.inference.provider_name import ProviderName
+from pipelex.system.exceptions import EnvVarNotFoundError
+from pytest_mock import MockerFixture
+
+from pipelex_api.error_types import ErrorType
+from pipelex_api.problem_document import build_problem_document, build_problem_document_from_api_error
+
+
+def _synthetic_llm_report() -> ErrorReport:
+ """A fully-populated report standing in for a provider rate-limit failure."""
+ return ErrorReport(
+ error_type="LLMCompletionError",
+ message="OpenAI returned 429 (rate_limit_exceeded)",
+ title="LLM completion error",
+ type_uri="https://docs.pipelex.com/latest/errors/llm-completion-error/",
+ error_category="transient",
+ error_domain="runtime",
+ retryable=True,
+ user_action=UserAction(kind=UserActionKind.WAIT_AND_RETRY, detail="Retry after 12s."),
+ model="gpt-4o-mini",
+ provider="openai",
+ provider_metadata=ProviderErrorMetadata(
+ provider=ProviderName.OPENAI,
+ sdk_exception_type="RateLimitError",
+ status_code=429,
+ retry_after_seconds=12.0,
+ request_id="req_provider_abc",
+ ),
+ )
+
+
+class TestProblemDocument:
+ def test_builds_from_config_error(self):
+ report = PipelexConfigError("the gateway config is missing").to_error_report()
+ doc = build_problem_document(report, instance="/v1/validate", request_id="REQ2", disclosure_mode=DisclosureMode.VERBOSE)
+ assert doc["status"] == 500
+ assert doc["error_domain"] == "config"
+ assert doc["error_type"] == "PipelexConfigError"
+ assert doc["detail"] == "the gateway config is missing"
+ assert doc["title"] == "Pipelex config"
+ assert doc["type"].endswith("/pipelex-config-error/")
+ assert doc["instance"] == "/v1/validate"
+ assert doc["request_id"] == "REQ2"
+
+ def test_builds_from_env_var_not_found_error(self):
+ # The original bug: /start with a required env var unset.
+ report = EnvVarNotFoundError("Environment variable 'COMPLETION_CALLBACK_SECRET' is required but not set").to_error_report()
+ doc = build_problem_document(report, instance="/v1/start", request_id="REQ1", disclosure_mode=DisclosureMode.VERBOSE)
+ assert doc["status"] == 500
+ assert doc["type"] == "https://docs.pipelex.com/latest/errors/env-var-not-found-error/"
+ assert doc["title"] == "Environment variable not set"
+ assert "COMPLETION_CALLBACK_SECRET" in doc["detail"]
+ assert doc["error_type"] == "EnvVarNotFoundError"
+ assert doc["instance"] == "/v1/start"
+ assert doc["request_id"] == "REQ1"
+ # EnvVarNotFoundError is a ToolError that pipelex classifies under the
+ # config domain — a missing required env var is an operator-fixable
+ # misconfiguration, so it maps to HTTP 500 with error_domain "config".
+ assert doc["error_domain"] == "config"
+
+ def test_builds_from_report_with_provider_metadata(self):
+ report = _synthetic_llm_report()
+ doc = build_problem_document(report, instance="/v1/execute", request_id="REQ7", disclosure_mode=DisclosureMode.VERBOSE)
+ assert doc["status"] == 429 # provider-429 passthrough
+ assert doc["type"] == "https://docs.pipelex.com/latest/errors/llm-completion-error/"
+ assert doc["title"] == "LLM completion error"
+ assert doc["detail"] == "OpenAI returned 429 (rate_limit_exceeded)"
+ assert doc["error_type"] == "LLMCompletionError"
+ assert doc["error_category"] == "transient"
+ assert doc["error_domain"] == "runtime"
+ assert doc["retryable"] is True
+ assert doc["model"] == "gpt-4o-mini"
+ assert doc["provider"] == "openai"
+ assert doc["user_action"]["kind"] == "wait_and_retry"
+ assert doc["provider_metadata"]["status_code"] == 429
+ assert doc["provider_metadata"]["retry_after_seconds"] == 12.0
+ # provider_metadata.body is excluded from serialization by pipelex.
+ assert "body" not in doc["provider_metadata"]
+
+ @pytest.mark.parametrize("disclosure_mode", [DisclosureMode.VERBOSE, DisclosureMode.STRICT])
+ def test_forwards_disclosure_mode(self, mocker: MockerFixture, disclosure_mode: DisclosureMode):
+ # The API only proves it forwards the mode unchanged; pipelex owns the
+ # redaction rules and tests them upstream.
+ report = PipelexConfigError("bad config").to_error_report()
+ spy = mocker.patch.object(ErrorReport, "to_problem_document", wraps=report.to_problem_document)
+ build_problem_document(report, instance="/x", request_id="r", disclosure_mode=disclosure_mode)
+ assert spy.call_args.kwargs["disclosure_mode"] is disclosure_mode
+
+ def test_api_error_variant_is_input_domain(self):
+ doc = build_problem_document_from_api_error(
+ ErrorType.VALIDATION_ERROR,
+ "field 'pipe_code' is required",
+ 422,
+ instance="/v1/execute",
+ request_id="REQ9",
+ )
+ assert doc["type"] == "https://docs.pipelex.com/latest/errors/validation-error/"
+ assert doc["title"] == "Validation error"
+ assert doc["status"] == 422
+ assert doc["detail"] == "field 'pipe_code' is required"
+ assert doc["instance"] == "/v1/execute"
+ assert doc["request_id"] == "REQ9"
+ assert doc["error_type"] == "ValidationError"
+ assert doc["error_domain"] == "input"
+ # Every API-authored error is non-retryable: a caller mistake is not
+ # fixed by a blind retry. Carried as a uniform contract member so
+ # clients drive retry logic without branching on field presence.
+ assert doc["retryable"] is False
+ # Pipelex's `error_category` set is inference-domain; the API does not
+ # manufacture a category for a non-inference failure — same omission
+ # rule pipelex itself applies to `PipelexConfigError` etc.
+ assert "error_category" not in doc
+
+ def test_api_error_variant_config_domain_for_server_fault(self):
+ # An API-owned 5xx (a missing secret, an unconfigured backend) classifies
+ # CONFIG, not INPUT — an operator, not the caller, fixes it.
+ doc = build_problem_document_from_api_error(
+ ErrorType.SERVER_MISCONFIGURED,
+ "Server configuration error: API_KEY not configured",
+ 500,
+ instance="/v1/upload",
+ request_id="REQ-CFG",
+ error_domain=ErrorDomain.CONFIG,
+ )
+ assert doc["status"] == 500
+ assert doc["title"] == "Server misconfigured"
+ assert doc["error_type"] == "ServerMisconfigured"
+ assert doc["error_domain"] == "config"
+ # An API-owned 5xx is no more retryable than a 4xx — the operator, not
+ # the caller, fixes a missing secret; a blind retry does nothing.
+ assert doc["retryable"] is False
+
+ def test_none_valued_fields_dropped(self):
+ report = EnvVarNotFoundError("missing X").to_error_report()
+ doc = build_problem_document(report, instance=None, request_id=None, disclosure_mode=DisclosureMode.VERBOSE)
+ assert None not in doc.values()
+ assert "instance" not in doc
+ assert "request_id" not in doc
+ assert "error_category" not in doc # never set on this report
+
+ api_doc = build_problem_document_from_api_error(ErrorType.BAD_REQUEST, "bad request", 400, instance=None, request_id=None)
+ assert None not in api_doc.values()
+ assert "instance" not in api_doc
+ assert "request_id" not in api_doc
+ # `retryable` is a contract member, not a drop-on-None one — present
+ # even when `instance`/`request_id` are absent.
+ assert api_doc["retryable"] is False
diff --git a/api/tests/unit/test_protocol_conformance.py b/api/tests/unit/test_protocol_conformance.py
new file mode 100644
index 000000000..d7f4ce7af
--- /dev/null
+++ b/api/tests/unit/test_protocol_conformance.py
@@ -0,0 +1,265 @@
+"""MTHDS Protocol conformance gate — verifies this server against the normative spec.
+
+Pipelex authors both the MTHDS Protocol spec (`mthds-protocol.openapi.yaml` in
+the mthds repo) and this reference implementation, so this suite is the
+mechanism that prevents first-party spec drift (master plan, eng review):
+
+- The five protocol routes answer under `/v1/{execute,start,validate,models,version}`
+ with the spec's status codes; no `/api/v1` mount or alias remains.
+- `RunRequest` anyOf rule: a body with neither `pipe_code` nor `mthds_contents`
+ is rejected with 422.
+- `GET /version` is public (no auth) and returns the `VersionInfo` shape.
+- A client-supplied `pipeline_run_id` on `/start` is honored (master D11 — this
+ source-available runner accepts it; `StartAck.pipeline_run_id` echoes it back).
+- The completion-callback E2E (eng-review 5A): `/start` with `callback_urls`
+ delivers a signed POST to a local in-test receiver. The orchestrator is replaced
+ by a fake whose `start` performs the real `DeliveryExecutor` delivery in-process, so
+ the wire bytes (headers + JSON payload) are the production delivery path's.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import hmac
+import json
+import os
+import threading
+from http.server import BaseHTTPRequestHandler, HTTPServer
+from typing import TYPE_CHECKING, Any, ClassVar
+
+import httpx
+import pytest
+from fastapi import Depends, FastAPI
+from fastapi.routing import APIRoute
+from fastapi.testclient import TestClient
+from mthds.protocol.protocol import PROTOCOL_VERSION
+from pipelex.pipe_run.delivery_assignment import DeliveryAssignment, DeliveryStatus
+from pipelex.pipe_run.delivery_executor import DeliveryExecutor
+from pipelex.pipeline.pipeline_response import RunState
+from pipelex.runtime_bridge.payloads import PipelexPipeDispatchAck
+from typing_extensions import override
+
+from pipelex_api.exception_handlers import register_exception_handlers
+from pipelex_api.routes import router as api_router
+from pipelex_api.routes.version import router as version_router
+from pipelex_api.security import verify_api_key
+from tests.unit._constants import VALID_MTHDS
+
+if TYPE_CHECKING:
+ from pytest_mock import MockerFixture
+
+PROTOCOL_PATHS = {
+ "/v1/execute": "POST",
+ "/v1/start": "POST",
+ "/v1/validate": "POST",
+ "/v1/models": "GET",
+ "/v1/version": "GET",
+}
+
+
+class _CallbackReceiver(BaseHTTPRequestHandler):
+ """Minimal in-test HTTP receiver capturing completion-callback deliveries."""
+
+ captured: ClassVar[list[dict[str, Any]]] = []
+
+ def do_POST(self) -> None:
+ body = self.rfile.read(int(self.headers.get("Content-Length", "0")))
+ type(self).captured.append({"headers": dict(self.headers.items()), "body": body})
+ self.send_response(200)
+ self.end_headers()
+
+ @override
+ def log_message(self, format: str, *args: Any) -> None:
+ """Silence per-request stderr logging."""
+
+
+def _build_protocol_client(mocker: MockerFixture) -> TestClient:
+ """A production-faithful `/v1` app with a mocked runner (no inference)."""
+ app = FastAPI(redirect_slashes=False)
+ app.include_router(version_router, prefix="/v1")
+ app.include_router(api_router, prefix="/v1")
+ register_exception_handlers(app)
+
+ fake_execute_response = mocker.MagicMock()
+ fake_execute_response.model_dump.return_value = {
+ "pipeline_run_id": "conformance-run-1",
+ "created_at": "2026-01-15T12:00:00Z",
+ "state": "COMPLETED",
+ "finished_at": "2026-01-15T12:00:01Z",
+ "main_stuff_name": "main_stuff",
+ "pipe_output": {"working_memory": {"root": {}, "aliases": {}}},
+ }
+ fake_runner = mocker.MagicMock()
+ fake_runner.execute = mocker.AsyncMock(return_value=fake_execute_response)
+ mocker.patch("pipelex_api.routes.pipelex.pipeline.ApiRunner", return_value=fake_runner)
+ return TestClient(app)
+
+
+class TestProtocolConformance:
+ def test_production_app_serves_protocol_paths_under_v1_only(self):
+ """The production app mounts every protocol route under `/v1` — no `/api/v1`, no aliases."""
+ # Imported in-test so a bad env var fails THIS test, not collection of the whole module.
+ from pipelex_api.main import fastapi_app # noqa: PLC0415
+
+ served_paths = {route.path for route in fastapi_app.routes if isinstance(route, APIRoute)}
+ for protocol_path in PROTOCOL_PATHS:
+ assert protocol_path in served_paths, f"protocol route {protocol_path} is not served"
+ legacy = [path for path in served_paths if path.startswith("/api/v1") or "/pipeline/" in path or "_version" in path]
+ assert legacy == [], f"legacy paths must not be served: {legacy}"
+
+ def test_version_is_public_and_protocol_shaped(self):
+ """`GET /v1/version` answers WITHOUT credentials even when every other route requires auth."""
+ app = FastAPI(redirect_slashes=False)
+ # Mirror `pipelex_api.main` wiring under AUTH_MODE=api_key: version mounts
+ # outside the auth dependency, everything else inside it.
+ app.include_router(version_router, prefix="/v1")
+ app.include_router(api_router, prefix="/v1", dependencies=[Depends(verify_api_key)])
+ register_exception_handlers(app)
+ client = TestClient(app)
+
+ # No Authorization header: the auth-gated surface rejects...
+ assert client.get("/v1/models").status_code == 401
+ # ...but the protocol handshake stays open.
+ response = client.get("/v1/version")
+ assert response.status_code == 200
+ body = response.json()
+ assert body["protocol_version"] == PROTOCOL_VERSION
+ assert body["implementation"] == "pipelex-api"
+ assert body["implementation_version"]
+ assert body["runtime_version"]
+
+ def test_validate_and_models_answer_200(self, mocker: MockerFixture):
+ client = _build_protocol_client(mocker)
+ validate_response = client.post("/v1/validate", json={"mthds_contents": [VALID_MTHDS]})
+ assert validate_response.status_code == 200, validate_response.text
+ models_response = client.get("/v1/models")
+ assert models_response.status_code == 200, models_response.text
+
+ def test_execute_answers_200(self, mocker: MockerFixture):
+ client = _build_protocol_client(mocker)
+ response = client.post(
+ "/v1/execute",
+ json={"pipe_code": "echo", "mthds_contents": [VALID_MTHDS], "inputs": {"text": "hi"}},
+ )
+ assert response.status_code == 200, response.text
+
+ @pytest.mark.parametrize("path", ["/v1/execute", "/v1/start"])
+ def test_run_request_anyof_rule_empty_body_is_422(self, mocker: MockerFixture, path: str):
+ """Protocol `RunRequest`: at least one of pipe_code / mthds_contents is required."""
+ client = _build_protocol_client(mocker)
+ response = client.post(path, json={})
+ assert response.status_code == 422
+ assert response.headers["content-type"] == "application/problem+json"
+
+ def test_start_accepts_client_pipeline_run_id_and_delivers_signed_callback(self, mocker: MockerFixture):
+ """D11 + eng-review 5A: `/start` honors the client `pipeline_run_id`, answers 202,
+ and the completion callback reaches the receiver with a valid
+ `X-Completion-Signature` and a payload carrying the protocol `pipeline_run_id`.
+
+ The orchestrator is replaced by a fake whose `start` immediately runs the REAL
+ `DeliveryExecutor` delivery against the captured `DeliveryAssignment`
+ (storage skipped — no pipe output), so headers and payload bytes come
+ from the production delivery code path. The SSRF guards are relaxed for
+ the loopback receiver: the request-time host check in
+ `pipelex_api.schemas.models` and the connect-time guarded transport in
+ `pipelex.pipe_run.delivery_executor` both block loopback by design.
+ """
+ # --- local HTTP receiver -------------------------------------------------
+ _CallbackReceiver.captured = []
+ server = HTTPServer(("127.0.0.1", 0), _CallbackReceiver)
+ server_thread = threading.Thread(target=server.serve_forever, daemon=True)
+ server_thread.start()
+ callback_url = f"http://127.0.0.1:{server.server_port}/completion"
+
+ # --- relax both SSRF layers for the loopback receiver (test-only) --------
+ mocker.patch("pipelex_api.schemas.models._is_disallowed_host", return_value=False)
+ mocker.patch("pipelex.pipe_run.delivery_executor.SsrfGuardedTransport", httpx.AsyncHTTPTransport)
+
+ # The signing secret is pinned HERE rather than relying on the ambient
+ # env: `make agent-test` exports every `.env` key name (including
+ # commented ones) into the child env as EMPTY strings, and
+ # `os.environ.setdefault` in tests/conftest.py cannot replace an
+ # existing empty value.
+ test_secret = "conformance-shared-callback-secret"
+ mocker.patch.dict(os.environ, {"COMPLETION_CALLBACK_SECRET": test_secret})
+
+ # --- fake orchestrator: deliver the completion in-process -----------------
+ # The runner now dispatches the locally-built PipeJob through the hub's
+ # OrchestratorRegistry via its fire-and-forget `start` arm. Stand in a fake orchestrator
+ # whose `start` performs the REAL DeliveryExecutor delivery and returns a
+ # `PipelexPipeDispatchAck` (ids only, workflow_id set), so the delivery wire bytes still
+ # come from the production path without needing a Temporal cluster or the
+ # `pipelex-temporal` plugin.
+ async def fake_start(*, pipe_job: Any, delivery_assignment: DeliveryAssignment) -> PipelexPipeDispatchAck:
+ await DeliveryExecutor().execute(
+ pipe_output=None,
+ storage_scope="conformance-caller",
+ pipeline_run_id=pipe_job.job_metadata.run_metadata.pipeline_run_id,
+ delivery_assignment=delivery_assignment,
+ status=DeliveryStatus.COMPLETED,
+ )
+ return PipelexPipeDispatchAck(
+ pipeline_run_id=pipe_job.job_metadata.run_metadata.pipeline_run_id,
+ workflow_id="wf-conformance-1",
+ )
+
+ # The fake stands in for an async-capable backend so `/start`'s capability gate passes (it
+ # checks `supports_fire_and_forget` BEFORE dispatch — a blocking-only orchestrator would 400).
+ fake_orchestrator = mocker.MagicMock()
+ fake_orchestrator.supports_fire_and_forget = True
+ fake_orchestrator.start = mocker.AsyncMock(side_effect=fake_start)
+ fake_registry = mocker.MagicMock()
+ fake_registry.get_optional.return_value = fake_orchestrator
+ mocker.patch("pipelex_api.routes.pipelex.pipeline.get_orchestrator_registry", return_value=fake_registry)
+
+ app = FastAPI(redirect_slashes=False)
+ app.include_router(api_router, prefix="/v1")
+ register_exception_handlers(app)
+ client = TestClient(app)
+
+ client_pipeline_run_id = "conformance-client-run-0001"
+ try:
+ response = client.post(
+ "/v1/start",
+ json={
+ "pipe_code": "echo",
+ "mthds_contents": [VALID_MTHDS],
+ "inputs": {"text": "hello"},
+ "pipeline_run_id": client_pipeline_run_id,
+ "callback_urls": [callback_url],
+ },
+ )
+ finally:
+ server.shutdown()
+ server_thread.join(timeout=5)
+ server.server_close()
+
+ # Protocol: 202 + StartAck; D11: the client-supplied pipeline_run_id is authoritative.
+ assert response.status_code == 202, response.text
+ ack = response.json()
+ assert ack["pipeline_run_id"] == client_pipeline_run_id
+ assert ack["state"] == RunState.STARTED
+
+ # The runner resolved the deployment's orchestration mode and dispatched under it: with the
+ # packaged-default config (`direct`) and no per-request override, the registry is asked for the
+ # `direct` orchestrator by keyword `mode=` — so a regression that resolved/threaded the wrong
+ # mode would be caught here, not silently dispatched.
+ fake_registry.get_optional.assert_called_once_with(mode="direct")
+ fake_orchestrator.start.assert_awaited_once()
+
+ # Exactly one delivery reached the receiver.
+ assert len(_CallbackReceiver.captured) == 1
+ delivery = _CallbackReceiver.captured[0]
+
+ # Signature: HMAC-SHA256(secret, pipeline_run_id) hex digest — the signing scheme
+ # `_completion_signature` implements with the shared
+ # COMPLETION_CALLBACK_SECRET.
+ expected_signature = hmac.new(test_secret.encode("utf-8"), client_pipeline_run_id.encode("utf-8"), hashlib.sha256).hexdigest()
+ assert delivery["headers"].get("X-Completion-Signature") == expected_signature
+
+ # Payload: carries the protocol `pipeline_run_id` (static injection by ApiRunner)
+ # plus the runtime's own delivery fields; `status` is a RunState value.
+ payload = json.loads(delivery["body"])
+ assert payload["pipeline_run_id"] == client_pipeline_run_id
+ assert payload["pipeline_run_id"] == client_pipeline_run_id
+ assert payload["status"] == RunState.COMPLETED
diff --git a/api/tests/unit/test_protocol_parity.py b/api/tests/unit/test_protocol_parity.py
new file mode 100644
index 000000000..50f045e20
--- /dev/null
+++ b/api/tests/unit/test_protocol_parity.py
@@ -0,0 +1,133 @@
+"""Local ↔ hosted parity of the MTHDS Protocol surfaces (the Phase 3a E2E diff).
+
+The alignment's end-to-end claim: a client of the Pipelex family can write portable code
+across the local runtime and the hosted API. Each scenario here calls the local
+`PipelexMTHDSProtocol` directly AND the HTTP route with the same payload, then asserts the
+shared report keys are byte-identical and the wire extras (`mthds_contents`, `message`,
+`default_pipe_ref`) appear on the HTTP envelope only. `is_valid` is a canonical report field on both backends (not a
+wire extra — the `success` extra is retired). `graph_spec` is compared by presence/absence,
+not value: it carries run-specific identity (graph id, node timings, random dry-run data),
+so two runs never serialize identically.
+
+Two report fields are gated on the wire rather than dropped: `input_form` and `output_form` are
+opt-in structured views the route attaches only when the request's `views` names them. So the parity
+call opts into both — the claim is that each projection is byte-identical to the local report's, not
+that a default call carries them — and a second assertion pins the gate itself: a default call omits
+exactly the opt-in views and nothing else.
+
+The validate fixtures mirror the protocol-alignment baseline scenarios: the lenient
+signature batch, the strict header+definition batch, the no-`main_pipe` batch (the D2
+regression surface), and a complete main-pipe bundle (the only one producing a graph).
+"""
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+from mthds.protocol.models import ModelCategory
+from pipelex.pipeline.runner import PipelexMTHDSProtocol
+
+from pipelex_api.exception_handlers import register_exception_handlers
+from pipelex_api.routes import router as api_router
+from tests.unit._constants import HEADER_AND_DEFINITION_BATCH, NO_MAIN_PIPE_MTHDS, SIGNATURE_ONLY_BATCH, VALID_MTHDS
+
+# The hosted /validate envelope = canonical report + exactly these wire-only extras.
+# `default_pipe_ref` is one of them by necessity, not omission: it states the pipe a selector-less
+# run of THIS request would execute, and on a `method_ref` request that comes from the fetched
+# package's manifest — a fact the local runtime never sees, so the canonical report cannot carry it.
+VALIDATE_WIRE_EXTRAS = {"mthds_contents", "message", "default_pipe_ref"}
+
+# Canonical report fields the route carries only when the request's `views` names them. They are
+# report fields (present in the local dump), so they are subtracted from the wire key set on a
+# default call rather than being extras added to it.
+VALIDATE_OPT_IN_VIEWS = {"input_form", "output_form"}
+
+
+def _build_client() -> TestClient:
+ app = FastAPI()
+ app.include_router(api_router, prefix="/v1")
+ register_exception_handlers(app)
+ return TestClient(app)
+
+
[email protected](loop_scope="class")
+class TestProtocolParity:
+ @pytest.mark.parametrize(
+ ("mthds_contents", "allow_signatures"),
+ [
+ pytest.param(SIGNATURE_ONLY_BATCH, True, id="signature_only-lenient"),
+ pytest.param(HEADER_AND_DEFINITION_BATCH, False, id="header_and_definition-strict"),
+ pytest.param([NO_MAIN_PIPE_MTHDS], False, id="no_main_pipe-strict"),
+ pytest.param([VALID_MTHDS], False, id="complete_main_pipe-strict"),
+ ],
+ )
+ async def test_validate_parity(self, mthds_contents: list[str], allow_signatures: bool):
+ local_report = await PipelexMTHDSProtocol().validate(mthds_contents=mthds_contents, allow_signatures=allow_signatures)
+ # Same serialization options as the route's JSONResponse path.
+ local_dump = local_report.model_dump(mode="json", serialize_as_any=True, by_alias=True)
+
+ client = _build_client()
+ # Opt into every gated view so the parity claim covers the whole canonical report: a view is
+ # a projection of report facts, and it must match the local dump exactly when it does ride.
+ response = client.post(
+ "/v1/validate",
+ json={"mthds_contents": mthds_contents, "allow_signatures": allow_signatures, "views": sorted(VALIDATE_OPT_IN_VIEWS)},
+ )
+ assert response.status_code == 200, response.text
+ body = response.json()
+
+ # The wire extras are HTTP-only — and they are the ONLY divergence in key sets.
+ assert VALIDATE_WIRE_EXTRAS.isdisjoint(local_dump)
+ assert set(local_dump) >= VALIDATE_OPT_IN_VIEWS, "an opt-in view must be a canonical report field, not a wire-only invention"
+ assert set(body) == set(local_dump) | VALIDATE_WIRE_EXTRAS
+
+ # graph_spec: presence parity (run-specific content — see module docstring).
+ assert (body["graph_spec"] is None) == (local_dump["graph_spec"] is None)
+
+ # Every other shared key is identical between the two backends.
+ for key in sorted(set(local_dump) - {"graph_spec"}):
+ assert body[key] == local_dump[key], f"local/hosted divergence on shared key {key!r}"
+
+ # The extras carry what the webapp depends on; `is_valid` is the canonical valid-arm discriminant.
+ assert body["mthds_contents"] == mthds_contents
+ assert body["is_valid"] is True
+ assert body["message"]
+
+ # The gate itself: a default call drops exactly the opt-in views and keeps everything else,
+ # so a caller that does not ask pays for no extra bytes.
+ default_response = client.post("/v1/validate", json={"mthds_contents": mthds_contents, "allow_signatures": allow_signatures})
+ assert default_response.status_code == 200, default_response.text
+ default_body = default_response.json()
+ assert set(default_body) == set(body) - VALIDATE_OPT_IN_VIEWS
+ # Gating a view must not perturb what it leaves behind: every retained key keeps its opt-in
+ # value (graph_spec excluded — run-specific content, see the module docstring).
+ for key in sorted(set(default_body) - {"graph_spec"}):
+ assert default_body[key] == body[key], f"default/opt-in divergence on retained key {key!r}"
+
+ async def test_models_parity_unfiltered(self):
+ local_deck = await PipelexMTHDSProtocol().models()
+ local_dump = local_deck.model_dump(mode="json", serialize_as_any=True, by_alias=True)
+
+ client = _build_client()
+ response = client.get("/v1/models")
+ assert response.status_code == 200, response.text
+ body = response.json()
+
+ # /models has no wire extras: the HTTP body IS the local deck, byte-identical.
+ assert body == local_dump
+ # Guard against vacuous parity (two empty decks would also be "identical").
+ assert body["models"]
+ assert body["aliases"]
+ assert body["waterfalls"]
+
+ async def test_models_parity_filtered(self):
+ local_deck = await PipelexMTHDSProtocol().models(category=ModelCategory.LLM)
+ local_dump = local_deck.model_dump(mode="json", serialize_as_any=True, by_alias=True)
+
+ client = _build_client()
+ response = client.get("/v1/models", params={"type": "llm"})
+ assert response.status_code == 200, response.text
+ body = response.json()
+
+ assert body == local_dump
+ assert body["models"]
+ assert all(entry["type"] == "llm" for entry in body["models"])
diff --git a/api/tests/unit/test_published_run_extras.py b/api/tests/unit/test_published_run_extras.py
new file mode 100644
index 000000000..31f78615d
--- /dev/null
+++ b/api/tests/unit/test_published_run_extras.py
@@ -0,0 +1,20 @@
+"""The published run request schemas carry every extension field the routes read.
+
+`/execute` and `/start` read their extensions through `PipelineApiExtras`, while the OpenAPI
+artifact publishes them from two separate documentation models. A field added to the first and
+not the second is honored on the wire yet absent from the contract, so no generated client can
+send it, and nothing else fails.
+"""
+
+from pipelex_api.schemas.models import PipelexApiExecuteRequest, PipelexApiStartRequest, PipelineApiExtras
+
+# `/execute` generates its own run id and delivers nothing asynchronously, so it reads neither.
+_START_ONLY_EXTRAS = {"pipeline_run_id", "callback_urls"}
+
+
+class TestPublishedRunExtras:
+ def test_start_request_publishes_every_extra(self) -> None:
+ assert set(PipelineApiExtras.model_fields) <= set(PipelexApiStartRequest.model_fields)
+
+ def test_execute_request_publishes_every_extra_it_reads(self) -> None:
+ assert set(PipelineApiExtras.model_fields) - _START_ONLY_EXTRAS <= set(PipelexApiExecuteRequest.model_fields)
diff --git a/api/tests/unit/test_read_scope_extras.py b/api/tests/unit/test_read_scope_extras.py
new file mode 100644
index 000000000..8e522d72d
--- /dev/null
+++ b/api/tests/unit/test_read_scope_extras.py
@@ -0,0 +1,163 @@
+"""`read_scope` must survive the wire -> extras -> runner -> `RunMetadata` hop on both run routes.
+
+Like the storage scope, a read scope dropped on the way is silent: the run still answers 200 or 202,
+and the only symptom is a run that reads every tenant's keys. So these tests run the real
+`pipeline_run_setup` and read the scope off the `RunMetadata` the runtime built. They also pin the
+fallback (the caller's own id when the deployment identifies callers, unscoped when it is
+single-tenant) and the 422 that replaces the runtime's bare `ValueError` when the storage scope does
+not lie under the read scope.
+"""
+
+from collections.abc import Awaitable, Callable
+from typing import TYPE_CHECKING, Any
+
+import pytest
+from fastapi import FastAPI, Request, Response
+from fastapi.testclient import TestClient
+from pipelex.core.memory.working_memory import MAIN_STUFF_NAME
+from pipelex.core.pipes.pipe_output import PipeOutput
+from pipelex.pipe_run.delivery_assignment import DeliveryAssignment
+from pipelex.pipe_run.pipe_job import PipeJob
+from pipelex.plugins.orchestrator_registry import OrchestratorRegistry
+from pipelex.runtime_bridge.payloads import PipelexPipeDispatchAck, PipelexPipeRunOutput
+from pipelex.runtime_bridge.serialization import serialize_completed_output
+from pipelex.system.storage_scope import LOCAL_STORAGE_SCOPE, SINGLE_TENANT_USER_ID
+from pytest_mock import MockerFixture
+
+from pipelex_api.api_config import ApiConfig
+from pipelex_api.exception_handlers import register_exception_handlers
+from pipelex_api.routes import router as api_router
+from pipelex_api.security import RequestUser
+from tests.unit._constants import VALID_MTHDS
+
+if TYPE_CHECKING:
+ from pipelex.system.job_metadata import RunMetadata
+
+_PIPELINE_NS = "pipelex_api.routes.pipelex.pipeline"
+_MODE = "temporal"
+_ROUTES = ["/v1/execute", "/v1/start"]
+_SUCCESS_STATUS = {"/v1/execute": 200, "/v1/start": 202}
+_USER_ID = "user_a"
+
+
+class _RecordingOrchestrator:
+ """Records the `RunMetadata` of every job it is handed, on either arm."""
+
+ supports_fire_and_forget = True
+
+ def __init__(self) -> None:
+ self.run_metadatas: list[RunMetadata] = []
+
+ async def execute(self, *, pipe_job: PipeJob, delivery_assignment: DeliveryAssignment | None) -> PipelexPipeRunOutput: # noqa: ARG002
+ self.run_metadatas.append(pipe_job.job_metadata.run_metadata)
+ working_memory = pipe_job.get_working_memory()
+ working_memory.set_alias(alias=MAIN_STUFF_NAME, target=next(iter(working_memory.root)))
+ return serialize_completed_output(
+ pipe_output=PipeOutput(working_memory=working_memory, pipeline_run_id=pipe_job.job_metadata.run_metadata.pipeline_run_id),
+ workflow_id=None,
+ )
+
+ async def start(self, *, pipe_job: PipeJob, delivery_assignment: DeliveryAssignment | None) -> PipelexPipeDispatchAck: # noqa: ARG002
+ self.run_metadatas.append(pipe_job.job_metadata.run_metadata)
+ return PipelexPipeDispatchAck(pipeline_run_id=pipe_job.job_metadata.run_metadata.pipeline_run_id, workflow_id="wf-read-scope")
+
+
+def _build_client(mocker: MockerFixture, *, user_id: str | None = None) -> tuple[TestClient, _RecordingOrchestrator]:
+ """An app on a stub async-capable orchestrator; `user_id` makes it a deployment that identifies callers."""
+ config = ApiConfig(orchestration_mode=_MODE, allow_request_orchestration_mode_override=False)
+ mocker.patch(f"{_PIPELINE_NS}.get_api_config", return_value=config)
+ orchestrator = _RecordingOrchestrator()
+ mocker.patch(f"{_PIPELINE_NS}.get_orchestrator_registry", return_value=OrchestratorRegistry({_MODE: orchestrator}))
+ app = FastAPI()
+ app.include_router(api_router, prefix="/v1")
+ register_exception_handlers(app)
+ if user_id is not None:
+ # The shape `pipelex_api.security` binds on an authenticated request.
+ async def _bind_user(request: Request, call_next: Callable[[Request], Awaitable[Response]]) -> Response:
+ request.state.user = RequestUser(user_id=user_id)
+ return await call_next(request)
+
+ app.middleware("http")(_bind_user)
+
+ return TestClient(app), orchestrator
+
+
+def _run_body(**extras: Any) -> dict[str, Any]:
+ return {"pipe_code": "echo", "mthds_contents": [VALID_MTHDS], "inputs": {"text": "hello"}, **extras}
+
+
[email protected]("route", _ROUTES)
+class TestReadScopeReachesTheRun:
+ def test_body_read_scope_reaches_the_run_metadata(self, mocker: MockerFixture, route: str) -> None:
+ client, orchestrator = _build_client(mocker)
+
+ response = client.post(route, json=_run_body(storage_scope="org_acme/mt_1/run_7", read_scope="org_acme"))
+
+ assert response.status_code == _SUCCESS_STATUS[route], response.text
+ assert len(orchestrator.run_metadatas) == 1
+ assert orchestrator.run_metadatas[0].read_scope == "org_acme"
+ assert orchestrator.run_metadatas[0].storage_scope == "org_acme/mt_1/run_7"
+
+ def test_single_tenant_default_is_unscoped(self, mocker: MockerFixture, route: str) -> None:
+ client, orchestrator = _build_client(mocker)
+
+ response = client.post(route, json=_run_body())
+
+ assert response.status_code == _SUCCESS_STATUS[route], response.text
+ assert orchestrator.run_metadatas[0].read_scope is None
+ assert orchestrator.run_metadatas[0].storage_scope == SINGLE_TENANT_USER_ID
+
+ def test_identified_caller_default_is_their_own_id(self, mocker: MockerFixture, route: str) -> None:
+ client, orchestrator = _build_client(mocker, user_id=_USER_ID)
+
+ response = client.post(route, json=_run_body())
+
+ assert response.status_code == _SUCCESS_STATUS[route], response.text
+ assert orchestrator.run_metadatas[0].read_scope == _USER_ID
+ assert orchestrator.run_metadatas[0].storage_scope == _USER_ID
+
+
[email protected]("route", _ROUTES)
+class TestReadScopeRefusals:
+ @pytest.mark.parametrize("bad_scope", ["../etc", "/absolute", "org//empty", "", "a/b/c/d"])
+ def test_malformed_read_scope_is_refused_at_the_wire(self, mocker: MockerFixture, route: str, bad_scope: str) -> None:
+ client, orchestrator = _build_client(mocker)
+
+ response = client.post(route, json=_run_body(read_scope=bad_scope))
+
+ assert response.status_code == 422, response.text
+ assert response.json()["error_type"] == "InvalidReadScope"
+ assert orchestrator.run_metadatas == []
+
+ def test_storage_scope_outside_the_read_scope_is_a_422(self, mocker: MockerFixture, route: str) -> None:
+ client, orchestrator = _build_client(mocker)
+
+ response = client.post(route, json=_run_body(storage_scope="org_other/mt_1/run_7", read_scope="org_acme"))
+
+ assert response.status_code == 422, response.text
+ body = response.json()
+ assert body["error_type"] == "InvalidReadScope"
+ assert "was sent" in body["detail"]
+ assert orchestrator.run_metadatas == []
+
+ def test_host_storage_scope_without_a_read_scope_fails_closed(self, mocker: MockerFixture, route: str) -> None:
+ # A multi-tenant host that forgets the read scope gets the caller's id as the default, under
+ # which its own storage scope does not lie: refused, rather than reading across tenants.
+ client, orchestrator = _build_client(mocker, user_id=_USER_ID)
+
+ response = client.post(route, json=_run_body(storage_scope="org_acme/mt_1/run_7"))
+
+ assert response.status_code == 422, response.text
+ body = response.json()
+ assert body["error_type"] == "InvalidReadScope"
+ assert "defaulted to the caller's id" in body["detail"]
+ assert orchestrator.run_metadatas == []
+
+ def test_local_storage_sentinel_beside_a_read_scope_is_a_422(self, mocker: MockerFixture, route: str) -> None:
+ client, orchestrator = _build_client(mocker)
+
+ response = client.post(route, json=_run_body(storage_scope=LOCAL_STORAGE_SCOPE, read_scope=LOCAL_STORAGE_SCOPE))
+
+ assert response.status_code == 422, response.text
+ assert response.json()["error_type"] == "InvalidReadScope"
+ assert orchestrator.run_metadatas == []
diff --git a/api/tests/unit/test_request_id_middleware.py b/api/tests/unit/test_request_id_middleware.py
new file mode 100644
index 000000000..c92642c74
--- /dev/null
+++ b/api/tests/unit/test_request_id_middleware.py
@@ -0,0 +1,166 @@
+"""Unit tests for RequestIdMiddleware and request-id propagation."""
+
+import logging
+import re
+import time
+
+import pytest
+from fastapi import APIRouter, FastAPI, HTTPException, Request
+from fastapi.testclient import TestClient
+from pipelex import log
+from pipelex.tools.log.log_context import get_log_context
+from starlette.middleware.base import BaseHTTPMiddleware
+from starlette.types import Message, Receive, Scope, Send
+
+from pipelex_api.middleware import REQUEST_ID_HEADER, RequestIdMiddleware, generate_request_id, request_body_size_middleware, request_id_of
+
+# Crockford Base32, 26 chars — the ULID alphabet (no I, L, O, U).
+_ULID_RE = re.compile(r"\A[0-9A-HJKMNP-TV-Z]{26}\Z")
+
+# The message the `/emits-a-log-line` route logs, matched back out of the captured records.
+_ROUTE_LOG_MESSAGE = "a line emitted from inside the request"
+
+_router = APIRouter()
+
+
+@_router.get("/probe")
+async def probe(request: Request) -> dict[str, str | None]:
+ bound = get_log_context()
+ return {
+ "ctx_request_id": bound.request_id if bound is not None else None,
+ "state_request_id": request.state.request_id,
+ "helper_request_id": request_id_of(request),
+ }
+
+
+@_router.get("/emits-a-log-line")
+async def emits_a_log_line() -> dict[str, str]:
+ log.warning(_ROUTE_LOG_MESSAGE)
+ return {"status": "logged"}
+
+
+@_router.get("/boom")
+async def boom() -> None:
+ raise HTTPException(status_code=400, detail="deliberate")
+
+
+@_router.get("/explode")
+async def explode() -> None:
+ msg = "deliberate unhandled error"
+ raise RuntimeError(msg)
+
+
+def _build_client(*, raise_server_exceptions: bool = True) -> TestClient:
+ """Build a client over the production middleware composition.
+
+ `RequestIdMiddleware` wraps a FastAPI app that itself carries the body-size
+ `BaseHTTPMiddleware` — mirroring `pipelex_api.main`, so the tests exercise contextvar
+ survival across the `BaseHTTPMiddleware` child-task boundary and the
+ catch-all 500 emitted by Starlette's `ServerErrorMiddleware`.
+ """
+ inner = FastAPI()
+ inner.add_middleware(BaseHTTPMiddleware, dispatch=request_body_size_middleware)
+ inner.include_router(_router)
+ return TestClient(RequestIdMiddleware(inner), raise_server_exceptions=raise_server_exceptions)
+
+
+class TestRequestIdMiddleware:
+ def test_generates_ulid_when_absent(self):
+ response = _build_client().get("/probe")
+ assert response.status_code == 200
+ request_id = response.headers[REQUEST_ID_HEADER]
+ assert _ULID_RE.match(request_id) is not None
+ body = response.json()
+ assert body["ctx_request_id"] == request_id
+ assert body["state_request_id"] == request_id
+ assert body["helper_request_id"] == request_id
+
+ def test_bound_context_puts_the_request_id_on_every_record(self, caplog: pytest.LogCaptureFixture):
+ # The middleware binds the runtime's own log context for the request, so a record emitted
+ # anywhere underneath — a route's own line here, but equally one from deep inside pipelex —
+ # carries `request_id` as a record attribute. The runner no longer interpolates the id into
+ # a message, which is what makes the id a field a structured sink indexes.
+ with caplog.at_level(logging.WARNING):
+ response = _build_client().get("/emits-a-log-line")
+ assert response.status_code == 200
+ request_id = response.headers[REQUEST_ID_HEADER]
+ emitted = [record for record in caplog.records if record.getMessage() == _ROUTE_LOG_MESSAGE]
+ assert len(emitted) == 1, f"expected exactly one captured record, got {[record.getMessage() for record in caplog.records]}"
+ assert getattr(emitted[0], "request_id", None) == request_id
+ # The id rides the record, never the message — a sink indexes the field, and an operator
+ # grepping the text of a line is not the contract any more.
+ assert request_id not in emitted[0].getMessage()
+
+ @pytest.mark.asyncio
+ async def test_bound_context_is_released_when_the_request_ends(self):
+ # The binding is per-request: once the request is over, nothing emitted afterwards may inherit
+ # its id, or a shared worker would attribute later work to it. The middleware is driven on this
+ # test's own event loop rather than through `TestClient`, which runs the app in a portal thread
+ # whose context never reaches the test's — through it, a binding that leaked would look released.
+ bound_while_running: list[str | None] = []
+
+ async def inner(_scope: Scope, _receive: Receive, send: Send) -> None:
+ bound = get_log_context()
+ bound_while_running.append(bound.request_id if bound is not None else None)
+ await send({"type": "http.response.start", "status": 200, "headers": []})
+ await send({"type": "http.response.body", "body": b""})
+
+ async def receive() -> Message:
+ return {"type": "http.request", "body": b"", "more_body": False}
+
+ async def send(message: Message) -> None:
+ pass
+
+ scope: Scope = {"type": "http", "method": "GET", "path": "/", "headers": []}
+ assert get_log_context() is None
+ await RequestIdMiddleware(inner)(scope, receive, send)
+
+ assert len(bound_while_running) == 1
+ assert bound_while_running[0] is not None, "the id must be bound while the request runs"
+ assert get_log_context() is None, "the binding outlived the request"
+
+ def test_echoes_valid_inbound_id(self):
+ response = _build_client().get("/probe", headers={REQUEST_ID_HEADER: "client-supplied-123"})
+ assert response.headers[REQUEST_ID_HEADER] == "client-supplied-123"
+ assert response.json()["ctx_request_id"] == "client-supplied-123"
+
+ def test_replaces_malformed_inbound_id(self):
+ response = _build_client().get("/probe", headers={REQUEST_ID_HEADER: "bad id with spaces"})
+ returned = response.headers[REQUEST_ID_HEADER]
+ assert returned != "bad id with spaces"
+ assert _ULID_RE.match(returned) is not None
+
+ def test_replaces_overlong_inbound_id(self):
+ overlong = "a" * 200
+ response = _build_client().get("/probe", headers={REQUEST_ID_HEADER: overlong})
+ returned = response.headers[REQUEST_ID_HEADER]
+ assert returned != overlong
+ assert _ULID_RE.match(returned) is not None
+
+ def test_header_present_on_handled_error_response(self):
+ response = _build_client().get("/boom")
+ assert response.status_code == 400
+ assert _ULID_RE.match(response.headers[REQUEST_ID_HEADER]) is not None
+
+ def test_header_present_on_unhandled_500(self):
+ # Because RequestIdMiddleware wraps the whole app, even the 500 that
+ # Starlette's ServerErrorMiddleware emits flows through the send wrapper.
+ response = _build_client(raise_server_exceptions=False).get("/explode")
+ assert response.status_code == 500
+ assert _ULID_RE.match(response.headers[REQUEST_ID_HEADER]) is not None
+
+ def test_generate_request_id_is_unique(self):
+ first = generate_request_id()
+ second = generate_request_id()
+ assert first != second
+ assert len(first) == 26
+ assert _ULID_RE.match(first) is not None
+
+ def test_generate_request_id_is_time_sortable(self):
+ # The ULID's high 48 bits are a millisecond timestamp and Crockford
+ # Base32 is ASCII-ascending, so ids minted across a time gap sort
+ # lexicographically — the property that makes ULID preferable to UUIDv4.
+ first = generate_request_id()
+ time.sleep(0.002)
+ second = generate_request_id()
+ assert first < second
diff --git a/api/tests/unit/test_resolve_route.py b/api/tests/unit/test_resolve_route.py
new file mode 100644
index 000000000..f45de5b63
--- /dev/null
+++ b/api/tests/unit/test_resolve_route.py
@@ -0,0 +1,118 @@
+"""Envelope tests for `POST /v1/resolve` — the normalized-crate resolution route.
+
+Pins `docs/specs/pipelex-codegen.md#route-envelopes` (workspace root): the request accepts inline
+`files[]` XOR a `method_ref`; a produced verdict is a 200 discriminated on `is_valid` with the
+crate on the valid arm; request-shape errors are 422 problem+json; an address-form `method_ref`
+resolves the fetched package's `.mthds` files into the closure, while the registry form keeps its
+honest 501 until the method registry exists.
+"""
+
+from collections.abc import Callable
+from pathlib import Path
+
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+from mthds.package.manifest.schema import MTHDS_STANDARD_VERSION
+from pipelex.interpreter_hub import get_library_manager
+from pytest_mock import MockerFixture
+
+from pipelex_api.exception_handlers import register_exception_handlers
+from pipelex_api.routes import router as api_router
+from tests.unit._constants import INVALID_MAIN_PIPE_MTHDS, SIBLING_MTHDS, VALID_MTHDS
+
+
+def _build_client() -> TestClient:
+ app = FastAPI()
+ app.include_router(api_router, prefix="/v1")
+ register_exception_handlers(app)
+ return TestClient(app)
+
+
+class TestResolveRoute:
+ def test_valid_files_return_200_crate_on_valid_arm(self):
+ client = _build_client()
+ response = client.post(
+ "/v1/resolve",
+ json={"files": [{"content": VALID_MTHDS, "source": "main.mthds"}, {"content": SIBLING_MTHDS, "source": "sibling.mthds"}]},
+ )
+ assert response.status_code == 200, response.text
+ body = response.json()
+ assert body["is_valid"] is True
+ crate = body["crate"]
+ # The canonical crate encoding: qualified refs, materialized natives, fingerprint + version.
+ assert crate["fingerprint"]
+ assert crate["mthds_version"] == MTHDS_STANDARD_VERSION
+ assert "smoke.echo" in crate["pipes"]
+ assert "smoke.wrap_echo" in crate["pipes"]
+ assert "native.Text" in crate["concepts"], "referenced natives must be materialized into the crate"
+ # Sources threaded per file[] entry surface in the crate's provenance map.
+ assert crate["source_map"]["smoke.echo"] == "main.mthds"
+ assert crate["source_map"]["smoke.wrap_echo"] == "sibling.mthds"
+
+ def test_invalid_files_return_200_invalid_arm_with_structured_errors(self):
+ client = _build_client()
+ response = client.post("/v1/resolve", json={"files": [{"content": INVALID_MAIN_PIPE_MTHDS, "source": "broken.mthds"}]})
+ assert response.status_code == 200, response.text
+ body = response.json()
+ assert body["is_valid"] is False
+ assert body["validation_errors"], "an invalid verdict must carry a non-empty validation_errors[]"
+ assert body["validation_errors"][0]["message"]
+ # The per-file source threads through to the diagnostics.
+ assert body["validation_errors"][0]["source"] == "broken.mthds"
+ # No crate exists on the invalid arm; the runnability facts are /validate vocabulary, absent here.
+ assert "crate" not in body
+ assert "is_runnable" not in body
+
+ def test_address_method_ref_resolves_the_fetched_package(self, install_method_package: Callable[..., Path]):
+ # The address-form un-reserve (run-by-address MVP Phase 2): a `github.com/...` ref
+ # resolves through the same fetch path as a `method_ref` run, and the package's
+ # `.mthds` files feed the closure with their real relative paths as sources.
+ install_method_package(files={"documents.mthds": VALID_MTHDS})
+ client = _build_client()
+ response = client.post("/v1/resolve", json={"method_ref": "github.com/pipelex/methods/[email protected]"})
+ assert response.status_code == 200, response.text
+ body = response.json()
+ assert body["is_valid"] is True
+ crate = body["crate"]
+ assert "smoke.echo" in crate["pipes"]
+ # The package's real file name rides the crate's provenance map.
+ assert crate["source_map"]["smoke.echo"] == "documents.mthds"
+
+ def test_registry_form_method_ref_keeps_the_501(self):
+ # The registry form (any non-address reference) stays reserved for the packaging
+ # program's closing phase — an honest 501, never a silent empty verdict.
+ client = _build_client()
+ response = client.post("/v1/resolve", json={"method_ref": "acme/invoice-tools"})
+ assert response.status_code == 501, response.text
+ assert response.headers["content-type"] == "application/problem+json"
+ assert response.json()["error_type"] == "MethodRefNotSupported"
+
+ def test_neither_or_both_selectors_is_422_problem_json(self):
+ client = _build_client()
+ neither = client.post("/v1/resolve", json={})
+ both = client.post("/v1/resolve", json={"files": [{"content": VALID_MTHDS}], "method_ref": "acme/x"})
+ for response in (neither, both):
+ assert response.status_code == 422, response.text
+ assert response.headers["content-type"] == "application/problem+json"
+ assert response.json()["error_type"] == "ValidationError"
+
+ def test_oversized_file_is_422_problem_json(self):
+ client = _build_client()
+ response = client.post("/v1/resolve", json={"files": [{"content": "a" * (2 * 1024 * 1024)}]})
+ assert response.status_code == 422, response.text
+ assert response.headers["content-type"] == "application/problem+json"
+ assert response.json()["error_type"] == "ValidationError"
+
+ def test_resolve_tears_down_its_library(self, mocker: MockerFixture):
+ # The engine core leaves the library loaded + current on success (so /codegen can read live
+ # pipes); the route owns teardown. Conservation property: opens == teardowns.
+ library_manager = get_library_manager()
+ open_spy = mocker.spy(library_manager, "open_library")
+ teardown_spy = mocker.spy(library_manager, "teardown")
+
+ client = _build_client()
+ response = client.post("/v1/resolve", json={"files": [{"content": VALID_MTHDS}]})
+
+ assert response.status_code == 200, response.text
+ assert open_spy.call_count >= 1
+ assert open_spy.call_count == teardown_spy.call_count
diff --git a/api/tests/unit/test_run_refusals.py b/api/tests/unit/test_run_refusals.py
new file mode 100644
index 000000000..421b9d6ea
--- /dev/null
+++ b/api/tests/unit/test_run_refusals.py
@@ -0,0 +1,149 @@
+"""What the run routes answer when the caller's own method refuses the run.
+
+Two moments, both the caller's to fix, so both are a 422 that STRICT disclosure keeps readable:
+
+- **An invalid bundle is refused before any pipe runs, with the validation verdict.** A run loads
+ its bundle before it dispatches anything, and the runtime turns every refusal of that load into a
+ `ValidateBundleError` carrying the same located `validation_errors` validating the bundle gives,
+ whatever check refused it: a misspelled concept used to escape as a 500, and an unknown model as a
+ raw model-choice error with no item. The orchestrator is a recording stub here, so the tests also
+ pin that nothing was dispatched.
+- **A run that fails reports its root fault, located at the failing pipe.** The problem document's
+ `error_type`, `title` and `type` are the innermost Pipelex error's, never the run-level wrapper's,
+ and its `detail` names the failing pipe and its path from the entry pipe. This one runs the real
+ in-process orchestrator on a bundle whose pipes call no model, so it fails the same way whether
+ the run is live or dry.
+"""
+
+from typing import Any
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+from pipelex.base_exceptions import DisclosureMode, ValidationErrorCategory
+from pipelex.pipe_run.delivery_assignment import DeliveryAssignment
+from pipelex.pipe_run.pipe_job import PipeJob
+from pipelex.plugins.orchestrator_registry import OrchestratorRegistry
+from pipelex.runtime_bridge.payloads import PipelexPipeDispatchAck, PipelexPipeRunOutput
+from pytest_mock import MockerFixture
+
+from pipelex_api.api_config import ApiConfig
+from pipelex_api.exception_handlers import register_exception_handlers
+from pipelex_api.routes import router as api_router
+from tests.unit._constants import MISMATCHED_PARALLEL_MTHDS, MISSPELLED_CONCEPT_MTHDS, UNKNOWN_MODEL_MTHDS
+
+_PIPELINE_NS = "pipelex_api.routes.pipelex.pipeline"
+
+
+class _RecordingOrchestrator:
+ """An async-capable orchestrator that records every dispatch; an invalid bundle must reach neither arm."""
+
+ supports_fire_and_forget = True
+
+ def __init__(self) -> None:
+ self.dispatches: list[tuple[str, DeliveryAssignment | None]] = []
+
+ async def execute(self, *, pipe_job: PipeJob, delivery_assignment: DeliveryAssignment | None) -> PipelexPipeRunOutput:
+ self.dispatches.append((pipe_job.pipe.code, delivery_assignment))
+ msg = "An invalid bundle must be refused before the run is dispatched."
+ raise AssertionError(msg)
+
+ async def start(self, *, pipe_job: PipeJob, delivery_assignment: DeliveryAssignment | None) -> PipelexPipeDispatchAck:
+ self.dispatches.append((pipe_job.pipe.code, delivery_assignment))
+ msg = "An invalid bundle must be refused before the run is dispatched."
+ raise AssertionError(msg)
+
+
+def _build_client(mocker: MockerFixture, *, disclosure_mode: DisclosureMode, orchestrator: _RecordingOrchestrator | None = None) -> TestClient:
+ """An app on the `direct` mode; `orchestrator` replaces the registered one when given."""
+ mocker.patch(
+ f"{_PIPELINE_NS}.get_api_config", return_value=ApiConfig(orchestration_mode="direct", allow_request_orchestration_mode_override=False)
+ )
+ if orchestrator is not None:
+ mocker.patch(f"{_PIPELINE_NS}.get_orchestrator_registry", return_value=OrchestratorRegistry({"direct": orchestrator}))
+ app = FastAPI()
+ app.include_router(api_router, prefix="/v1")
+ register_exception_handlers(app, disclosure_mode=disclosure_mode)
+ return TestClient(app)
+
+
+class TestRunRefusals:
+ @pytest.mark.parametrize("disclosure_mode", [DisclosureMode.VERBOSE, DisclosureMode.STRICT])
+ @pytest.mark.parametrize("path", ["/v1/execute", "/v1/start"])
+ @pytest.mark.parametrize(
+ ("mthds_content", "expected_item"),
+ [
+ (
+ MISSPELLED_CONCEPT_MTHDS,
+ {
+ "error_type": "unresolved_concept",
+ "concept_code": "Summry",
+ "field_path": "pipe.echo.output",
+ "field_name": "output",
+ },
+ ),
+ (
+ UNKNOWN_MODEL_MTHDS,
+ {
+ "error_type": "unknown_model",
+ "model_reference": "no-such-model-in-any-deck",
+ "model_type": "llm",
+ "field_path": "pipe.echo.model",
+ "field_name": "model",
+ },
+ ),
+ ],
+ ids=["misspelled_concept", "unknown_model"],
+ )
+ def test_invalid_bundle_is_a_422_with_located_items(
+ self,
+ mocker: MockerFixture,
+ disclosure_mode: DisclosureMode,
+ path: str,
+ mthds_content: str,
+ expected_item: dict[str, Any],
+ ):
+ orchestrator = _RecordingOrchestrator()
+ client = _build_client(mocker, disclosure_mode=disclosure_mode, orchestrator=orchestrator)
+
+ response = client.post(path, json={"pipe_code": "echo", "mthds_contents": [mthds_content], "inputs": {"text": "hello"}})
+
+ assert response.status_code == 422, response.text
+ assert response.headers["content-type"].startswith("application/problem+json")
+ body = response.json()
+ assert body["error_type"] == "ValidateBundleError"
+ assert body["error_domain"] == "input"
+ assert body["user_action"]["kind"] == "change_input"
+ items: list[dict[str, Any]] = body["validation_errors"]
+ assert len(items) == 1, items
+ item = items[0]
+ assert item["category"] == ValidationErrorCategory.PIPE_VALIDATION
+ assert item["pipe_code"] == "echo"
+ assert item["domain_code"] == "smoke"
+ for field_name, expected_value in expected_item.items():
+ assert item[field_name] == expected_value, item
+ # The verdict is the caller's own bundle: STRICT keeps the human summary, which is the item's message.
+ assert body["detail"] == item["message"]
+ # Refused while the bundle loads: nothing reached the orchestrator.
+ assert orchestrator.dispatches == []
+
+ @pytest.mark.parametrize("disclosure_mode", [DisclosureMode.VERBOSE, DisclosureMode.STRICT])
+ def test_run_failure_reports_its_root_fault_at_the_failing_pipe(self, mocker: MockerFixture, disclosure_mode: DisclosureMode):
+ client = _build_client(mocker, disclosure_mode=disclosure_mode)
+
+ response = client.post("/v1/execute", json={"mthds_contents": [MISMATCHED_PARALLEL_MTHDS], "inputs": {"topic": "tides"}})
+
+ assert response.status_code == 422, response.text
+ assert response.headers["content-type"].startswith("application/problem+json")
+ body = response.json()
+ # The root fault's class, not the run-level `PipelineExecutionError` that wraps it.
+ assert body["error_type"] == "StuffFactoryError"
+ assert body["type"] == "https://docs.pipelex.com/latest/errors/stuff-factory-error/"
+ assert body["error_domain"] == "input"
+ # Located at the failing step, with its path from the entry pipe, and kept under STRICT
+ # because the fault is the caller's own method.
+ assert body["detail"].startswith("Pipe 'analyze_topic' failed (review_topic → analyze_topic): "), body["detail"]
+ # The next step says which of the two multiplicities to change.
+ assert body["user_action"]["kind"] == "change_input"
+ assert "Branch 'draft_idea' gives result 'ideas' as a single 'Idea'" in body["user_action"]["detail"]
+ assert "validation_errors" not in body
diff --git a/api/tests/unit/test_run_source_precondition.py b/api/tests/unit/test_run_source_precondition.py
new file mode 100644
index 000000000..bc86adfd3
--- /dev/null
+++ b/api/tests/unit/test_run_source_precondition.py
@@ -0,0 +1,137 @@
+"""Route-level tests for the run-source precondition on /execute and /start.
+
+Pins the layered extension policy's Rule 4 (the Pipelex workspace spec
+`docs/specs/pipelex-platform-api.md` → "Layered extension policy"): an unknown
+extension key never waives the requirement that a run request carry a source
+this server understands, and a source-less body whose keys this deployment does
+not handle gets a message that NAMES them — so "a hosted client was pointed at
+a source-available runner" reads as that, instead of as a generic precondition
+failure.
+
+The runner is mocked as in `test_pipeline_routes`; nothing here reaches inference,
+because every assertion lands on a request-shape 422 raised during body parsing.
+"""
+
+from typing import Any
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+from pipelex.pipeline.pipeline_response import PipelexRunResultStart, RunState
+from pytest_mock import MockerFixture
+
+from pipelex_api.exception_handlers import register_exception_handlers
+from pipelex_api.routes.pipelex.pipeline import router as pipeline_router
+from tests.unit._constants import VALID_MTHDS
+
+_BASE_PRECONDITION_FRAGMENT = "pipe_code and mthds_contents cannot both be empty"
+
+
+def _build_client(mocker: MockerFixture) -> tuple[TestClient, Any]:
+ """Wire a FastAPI app whose pipeline runner is fully mocked; return (client, runner_mock).
+
+ The whole runner comes back rather than just `execute`, because `/v1/start` dispatches
+ through `runner.start`: a test that asserts only on `execute` pins nothing on that route.
+ """
+ app = FastAPI()
+ app.include_router(pipeline_router, prefix="/v1")
+ register_exception_handlers(app)
+
+ fake_execute_response = mocker.MagicMock()
+ fake_execute_response.model_dump.return_value = {
+ "pipeline_run_id": "test-run-1",
+ "state": "COMPLETED",
+ "pipe_output": {"working_memory": {"root": {}, "aliases": {}}},
+ }
+ fake_runner = mocker.MagicMock()
+ fake_runner.execute = mocker.AsyncMock(return_value=fake_execute_response)
+ fake_runner.start = mocker.AsyncMock(
+ return_value=PipelexRunResultStart(
+ pipeline_run_id="test-run-1",
+ created_at="2026-01-15T12:00:00Z",
+ state=RunState.STARTED,
+ workflow_id="wf-1",
+ )
+ )
+ mocker.patch("pipelex_api.routes.pipelex.pipeline.ApiRunner", return_value=fake_runner)
+ return TestClient(app), fake_runner
+
+
+class TestRunSourcePrecondition:
+ """A run source is required; extension args never waive it, and they are named when they are all the body has."""
+
+ @pytest.mark.parametrize("route", ["/v1/execute", "/v1/start"])
+ def test_extension_only_body_is_refused_and_names_the_unhandled_keys(self, mocker: MockerFixture, route: str):
+ # The hosted catalog selector resolved on the platform and never crosses down to a
+ # runner (Rule 3), so a body carrying it alone means a hosted client reached the
+ # wrong deployment. The 422 must diagnose exactly that, by name.
+ client, runner = _build_client(mocker)
+ response = client.post(route, json={"method_id": "mt_abc123"})
+ assert response.status_code == 422
+ assert response.headers["content-type"] == "application/problem+json"
+ problem = response.json()
+ assert problem["error_domain"] == "input"
+ detail = problem["detail"]
+ assert "`method_id`" in detail
+ assert "not handled by this deployment" in detail
+ assert "hosted API" in detail
+ # The run never dispatched: this is a request-shape refusal, not a failed run.
+ # Both dispatch methods are asserted because the two routes use different ones
+ # (`/v1/execute` → `runner.execute`, `/v1/start` → `runner.start`).
+ runner.execute.assert_not_awaited()
+ runner.start.assert_not_awaited()
+
+ def test_every_unhandled_key_is_named_sorted(self, mocker: MockerFixture):
+ client, _ = _build_client(mocker)
+ response = client.post("/v1/execute", json={"method_id": "mt_abc123", "future_arg": "x"})
+ assert response.status_code == 422
+ detail = response.json()["detail"]
+ assert "`future_arg`, `method_id`" in detail
+
+ def test_empty_body_keeps_the_base_guidance(self, mocker: MockerFixture):
+ # Nothing to name — the caller sent no extension at all, so the message stays the
+ # one that explains what a run source IS.
+ client, _ = _build_client(mocker)
+ response = client.post("/v1/execute", json={})
+ assert response.status_code == 422
+ detail = response.json()["detail"]
+ assert _BASE_PRECONDITION_FRAGMENT in detail
+ assert "not handled by this deployment" not in detail
+
+ def test_server_handled_extras_are_never_named_as_unhandled(self, mocker: MockerFixture):
+ # `callback_urls` / `orchestration_mode` / `storage_scope` / `pipeline_run_id` ARE
+ # handled here (`PipelineApiExtras`). A source-less body carrying only those is still
+ # a 422, but naming them as unhandled would be a lie.
+ client, _ = _build_client(mocker)
+ response = client.post(
+ "/v1/start",
+ json={"pipeline_run_id": "run-1", "callback_urls": ["https://example.com/hook"], "storage_scope": "tenant/run"},
+ )
+ assert response.status_code == 422
+ detail = response.json()["detail"]
+ assert _BASE_PRECONDITION_FRAGMENT in detail
+ assert "not handled by this deployment" not in detail
+
+ @pytest.mark.parametrize(
+ ("label", "body"),
+ [
+ ("pipe_code", {"pipe_code": "echo", "method_id": "mt_abc123", "inputs": {"text": "hi"}}),
+ ("mthds_contents", {"mthds_contents": [VALID_MTHDS], "method_id": "mt_abc123", "inputs": {"text": "hi"}}),
+ ("bundle_files", {"files": {"main.mthds": VALID_MTHDS}, "method_id": "mt_abc123", "inputs": {"text": "hi"}}),
+ ],
+ )
+ def test_a_body_with_a_source_still_accepts_unknown_extensions(self, mocker: MockerFixture, label: str, body: dict[str, Any]):
+ # Rule 1: the model stays extension-open. Rule 4 tightens the SOURCE-LESS case only —
+ # an unknown key alongside a real run source is still forwarded untouched.
+ client, runner = _build_client(mocker)
+ response = client.post("/v1/execute", json=body)
+ assert response.status_code == 200, f"{label}: {response.text[:300]!r}"
+ runner.execute.assert_awaited_once()
+
+ def test_legacy_singular_mthds_content_is_still_a_source(self, mocker: MockerFixture):
+ # `mthds_content` (singular) is the legacy alias `from_body` folds into the plural
+ # field — it is a source, so it must not be reported as an unhandled extension arg.
+ client, runner = _build_client(mocker)
+ response = client.post("/v1/execute", json={"mthds_content": VALID_MTHDS, "inputs": {"text": "hi"}})
+ assert response.status_code == 200, response.text[:300]
+ runner.execute.assert_awaited_once()
diff --git a/api/tests/unit/test_security_no_auth.py b/api/tests/unit/test_security_no_auth.py
new file mode 100644
index 000000000..0fb87704b
--- /dev/null
+++ b/api/tests/unit/test_security_no_auth.py
@@ -0,0 +1,151 @@
+from typing import Annotated
+
+import pytest
+from fastapi import Depends, FastAPI
+from fastapi.testclient import TestClient
+from pipelex.system.storage_scope import SINGLE_TENANT_USER_ID
+from pytest_mock import MockerFixture
+
+from pipelex_api.exception_handlers import register_exception_handlers
+from pipelex_api.security import ForwardedIdentityHeader, RequestUser, get_request_user, no_auth
+from tests.unit._constants import RoutePath
+
+USER_ID = "11111111-1111-4111-1111-111111111111"
+
+
+async def _whoami(user: Annotated[RequestUser | None, Depends(get_request_user)]) -> dict[str, str | None]:
+ if user is None:
+ return {"user_id": None}
+ return {"user_id": user.user_id}
+
+
+def _build_client() -> TestClient:
+ app = FastAPI()
+ app.add_api_route(RoutePath.WHOAMI, _whoami, methods=["GET"], dependencies=[Depends(no_auth)])
+ register_exception_handlers(app)
+ return TestClient(app)
+
+
+class TestNoAuthForwardedHeaders:
+ def test_header_ignored_by_default(self, mocker: MockerFixture):
+ """No TRUST_FORWARDED_IDENTITY_HEADERS env → X-User-Id is not trusted."""
+ mocker.patch("pipelex_api.security.get_optional_env", return_value=None)
+ client = _build_client()
+ headers: dict[str, str] = {ForwardedIdentityHeader.USER_ID: USER_ID}
+ response = client.get(RoutePath.WHOAMI, headers=headers)
+ assert response.status_code == 200
+ assert response.json() == {"user_id": None}
+
+ def test_header_ignored_when_flag_not_true(self, mocker: MockerFixture):
+ mocker.patch("pipelex_api.security.get_optional_env", return_value="false")
+ client = _build_client()
+ headers: dict[str, str] = {ForwardedIdentityHeader.USER_ID: USER_ID}
+ response = client.get(RoutePath.WHOAMI, headers=headers)
+ assert response.status_code == 200
+ assert response.json() == {"user_id": None}
+
+ def test_user_id_honored_when_flag_true(self, mocker: MockerFixture):
+ """With the trust flag enabled, the runner reads X-User-Id and only that."""
+ mocker.patch("pipelex_api.security.get_optional_env", return_value="true")
+ client = _build_client()
+ # Extra X-User-* headers are noise — the runner ignores them by design.
+ headers: dict[str, str] = {
+ ForwardedIdentityHeader.USER_ID: USER_ID,
+ "x-user-email": "[email protected]",
+ "x-user-sub": "spoofed#1",
+ "x-auth-method": "gateway",
+ }
+ response = client.get(RoutePath.WHOAMI, headers=headers)
+ assert response.status_code == 200
+ assert response.json() == {"user_id": USER_ID}
+
+ @pytest.mark.parametrize("user_id", ["", None])
+ def test_a_missing_forwarded_user_id_is_rejected(self, mocker: MockerFixture, user_id: str | None):
+ """**This used to stay anonymous, and that was the bug.**
+
+ Turning `TRUST_FORWARDED_IDENTITY_HEADERS` on is a deployment asserting
+ "a proxy in front of me authenticates every caller". A request arriving
+ without the header therefore means that proxy is absent, misconfigured
+ or bypassed — and the old behaviour was to continue under a shared
+ owner, which put every caller of a multi-tenant server into one storage
+ namespace where each could read the others' outputs. It looked like a
+ working request the whole way through.
+
+ There is no `anonymous` sentinel any more: an empty header and an absent
+ one are the same failure, and both are 401.
+ """
+ mocker.patch("pipelex_api.security.get_optional_env", return_value="true")
+ client = _build_client()
+ headers: dict[str, str] = {} if user_id is None else {ForwardedIdentityHeader.USER_ID: user_id}
+ response = client.get(RoutePath.WHOAMI, headers=headers)
+ assert response.status_code == 401
+ assert response.headers["content-type"] == "application/problem+json"
+
+ def test_the_reserved_single_tenant_id_is_not_special_on_the_wire(self, mocker: MockerFixture):
+ """`single-tenant` forwarded by a proxy is an ordinary path-safe id here.
+
+ The reservation is enforced where it matters — `verify_jwt` refuses a
+ token claiming it — not by giving the string a second meaning on the
+ forwarded path. A proxy that genuinely wants to forward it is asserting
+ an identity, which is what this flag means.
+ """
+ mocker.patch("pipelex_api.security.get_optional_env", return_value="true")
+ client = _build_client()
+ headers: dict[str, str] = {ForwardedIdentityHeader.USER_ID: SINGLE_TENANT_USER_ID}
+ response = client.get(RoutePath.WHOAMI, headers=headers)
+ assert response.status_code == 200
+ assert response.json() == {"user_id": SINGLE_TENANT_USER_ID}
+
+ @pytest.mark.parametrize(
+ "unsafe_user_id",
+ [
+ "../etc/passwd",
+ "a/b",
+ "..",
+ ".",
+ "with\x00null", # C0 control (NUL)
+ "with\x7fdel", # DEL is a control char too — must be rejected
+ "google#abc", # URI fragment delimiter — ambiguous owner segment
+ "[email protected]", # URI userinfo delimiter
+ "a:99999", # URI port delimiter
+ ],
+ )
+ def test_path_unsafe_forwarded_user_id_rejected(self, mocker: MockerFixture, unsafe_user_id: str):
+ r"""A forwarded `X-User-Id` that is not a single path-safe segment fails closed.
+
+ `user_id` is the owner segment of every storage key, so a value
+ containing `/`, `\`, control chars, or being `.`/`..` could enable
+ traversal. The proxy intended to authenticate someone but forwarded a
+ malformed value — we reject the request (400) rather than silently
+ downgrade to a shared owner and scope the caller's outputs into someone
+ else's namespace.
+ """
+ mocker.patch("pipelex_api.security.get_optional_env", return_value="true")
+ client = _build_client()
+ headers: dict[str, str] = {ForwardedIdentityHeader.USER_ID: unsafe_user_id}
+ response = client.get(RoutePath.WHOAMI, headers=headers)
+ assert response.status_code == 400
+ assert response.headers["content-type"] == "application/problem+json"
+ assert response.json()["error_type"] == "BadRequest"
+
+ @pytest.mark.parametrize(
+ "opaque_user_id",
+ [
+ "user-123",
+ "user_11111111-1111-4111-8111-111111111111", # the prefixed id scheme
+ "a" * 36,
+ ],
+ )
+ def test_opaque_forwarded_user_id_honored(self, mocker: MockerFixture, opaque_user_id: str):
+ """The runner treats `user_id` as opaque — any path-safe value is honored.
+
+ Identity is enforced upstream (the trusted proxy / gateway injects the
+ authenticated id); the runner only requires path-safety, so a non-UUID
+ but safe id (incl. the `user_<uuid>` prefixed scheme) is used as-is.
+ """
+ mocker.patch("pipelex_api.security.get_optional_env", return_value="true")
+ client = _build_client()
+ headers: dict[str, str] = {ForwardedIdentityHeader.USER_ID: opaque_user_id}
+ response = client.get(RoutePath.WHOAMI, headers=headers)
+ assert response.status_code == 200
+ assert response.json() == {"user_id": opaque_user_id}
diff --git a/api/tests/unit/test_security_verifiers.py b/api/tests/unit/test_security_verifiers.py
new file mode 100644
index 000000000..dd9dc3976
--- /dev/null
+++ b/api/tests/unit/test_security_verifiers.py
@@ -0,0 +1,254 @@
+"""Tests for verify_jwt and verify_api_key in api/security."""
+
+from typing import Annotated
+
+import jwt
+import pytest
+from fastapi import Depends, FastAPI, Request
+from fastapi.testclient import TestClient
+from pipelex.system.storage_scope import SINGLE_TENANT_USER_ID
+from pytest_mock import MockerFixture
+
+from pipelex_api.exception_handlers import register_exception_handlers
+from pipelex_api.security import RequestUser, get_request_user, verify_api_key, verify_jwt
+from tests.unit._constants import RoutePath
+
+JWT_SECRET = "test-jwt-secret-do-not-use-in-prod"
+API_KEY = "test-api-key-static"
+USER_ID_UUID = "11111111-1111-4111-1111-111111111111"
+
+
+async def _whoami_jwt(
+ request: Request,
+ _payload: Annotated[dict[str, object], Depends(verify_jwt)],
+ user: Annotated[RequestUser | None, Depends(get_request_user)],
+) -> dict[str, str | None]:
+ _ = request
+ if user is None:
+ return {"user_id": None}
+ return {"user_id": user.user_id}
+
+
+async def _ping_api_key(_token: Annotated[str, Depends(verify_api_key)]) -> dict[str, str]:
+ return {"ok": "yes"}
+
+
+def _build_jwt_client() -> TestClient:
+ app = FastAPI()
+ app.add_api_route(RoutePath.WHOAMI, _whoami_jwt, methods=["GET"])
+ register_exception_handlers(app)
+ return TestClient(app)
+
+
+def _build_api_key_client() -> TestClient:
+ app = FastAPI()
+ app.add_api_route(RoutePath.PING, _ping_api_key, methods=["GET"])
+ register_exception_handlers(app)
+ return TestClient(app)
+
+
+class TestSecurityVerifiers:
+ def test_jwt_happy_path_user_id_claim(self, mocker: MockerFixture):
+ """Preferred claim: explicit `user_id` containing a UUID."""
+ mocker.patch("pipelex_api.security.get_optional_env", return_value=JWT_SECRET)
+ client = _build_jwt_client()
+ token = jwt.encode({"user_id": USER_ID_UUID}, JWT_SECRET, algorithm="HS256")
+ response = client.get(RoutePath.WHOAMI, headers={"Authorization": f"Bearer {token}"})
+ assert response.status_code == 200
+ assert response.json() == {"user_id": USER_ID_UUID}
+
+ def test_jwt_sub_only_is_rejected(self, mocker: MockerFixture):
+ """A JWT with only `sub` (and no `user_id`) is rejected.
+
+ We deliberately do NOT fall back to `sub`: storage URIs require the
+ owner segment to be a UUID, and OAuth providers' `sub` values
+ (e.g. `"google#abc"`) would let a caller write to S3 keys that
+ `/resolve-storage-url` would later refuse to resolve. Deployments
+ using OAuth must mint their own `user_id` claim.
+ """
+ mocker.patch("pipelex_api.security.get_optional_env", return_value=JWT_SECRET)
+ client = _build_jwt_client()
+ token = jwt.encode({"sub": "google#abc"}, JWT_SECRET, algorithm="HS256")
+ response = client.get(RoutePath.WHOAMI, headers={"Authorization": f"Bearer {token}"})
+ assert response.status_code == 401
+ assert response.headers["content-type"] == "application/problem+json"
+ assert response.json()["error_type"] == "InvalidToken"
+
+ def test_jwt_missing_user_id_claim_rejected(self, mocker: MockerFixture):
+ """No `user_id` claim means no caller identifier — reject."""
+ mocker.patch("pipelex_api.security.get_optional_env", return_value=JWT_SECRET)
+ client = _build_jwt_client()
+ token = jwt.encode({"iat": 0}, JWT_SECRET, algorithm="HS256")
+ response = client.get(RoutePath.WHOAMI, headers={"Authorization": f"Bearer {token}"})
+ assert response.status_code == 401
+ assert response.headers["content-type"] == "application/problem+json"
+ assert response.headers["WWW-Authenticate"] == "Bearer"
+ assert response.json()["error_type"] == "InvalidToken"
+
+ @pytest.mark.parametrize(
+ "unsafe_user_id",
+ [
+ "../etc/passwd",
+ "a/b",
+ "..",
+ ".",
+ "with\x00null", # C0 control (NUL)
+ "with\x7fdel", # DEL is a control char too — must be rejected
+ "google#abc", # URI fragment delimiter — ambiguous owner segment
+ "[email protected]", # URI userinfo delimiter
+ "a:99999", # URI port delimiter
+ ],
+ )
+ def test_jwt_path_unsafe_user_id_rejected(self, mocker: MockerFixture, unsafe_user_id: str):
+ r"""A `user_id` claim that isn't a single path-safe segment is rejected.
+
+ The id becomes the owner segment of every storage key, so a value with
+ `/`, `\`, or being `.`/`..` could enable traversal — reject at the auth
+ boundary. (Identity/shape is otherwise the issuer's concern; the runner
+ treats `user_id` as opaque.)
+ """
+ mocker.patch("pipelex_api.security.get_optional_env", return_value=JWT_SECRET)
+ client = _build_jwt_client()
+ token = jwt.encode({"user_id": unsafe_user_id}, JWT_SECRET, algorithm="HS256")
+ response = client.get(RoutePath.WHOAMI, headers={"Authorization": f"Bearer {token}"})
+ assert response.status_code == 401
+ assert response.headers["content-type"] == "application/problem+json"
+ assert response.headers["WWW-Authenticate"] == "Bearer"
+ assert response.json()["error_type"] == "InvalidToken"
+
+ @pytest.mark.parametrize(
+ "opaque_user_id",
+ [
+ "user-123",
+ "user_11111111-1111-4111-8111-111111111111", # the prefixed id scheme
+ "a" * 36,
+ ],
+ )
+ def test_jwt_opaque_user_id_accepted(self, mocker: MockerFixture, opaque_user_id: str):
+ """An opaque, path-safe `user_id` claim is accepted as-is (no shape check)."""
+ mocker.patch("pipelex_api.security.get_optional_env", return_value=JWT_SECRET)
+ client = _build_jwt_client()
+ token = jwt.encode({"user_id": opaque_user_id}, JWT_SECRET, algorithm="HS256")
+ response = client.get(RoutePath.WHOAMI, headers={"Authorization": f"Bearer {token}"})
+ assert response.status_code == 200
+ assert response.json() == {"user_id": opaque_user_id}
+
+ def test_jwt_claiming_the_reserved_single_tenant_id_is_rejected(self, mocker: MockerFixture):
+ """A JWT claiming the reserved single-tenant id is rejected.
+
+ The value is path-safe, so it passes the segment check — but it is the
+ owner id a deployment with NO user model runs under. An authenticated
+ token binding it would land that caller's runs in the single-tenant
+ namespace, beside whatever a no-auth deployment of the same image wrote
+ there.
+
+ (This case previously guarded the `anonymous` sentinel, which no longer
+ exists: identity is required wherever a deployment claims to have one.)
+ """
+ mocker.patch("pipelex_api.security.get_optional_env", return_value=JWT_SECRET)
+ client = _build_jwt_client()
+ token = jwt.encode({"user_id": SINGLE_TENANT_USER_ID}, JWT_SECRET, algorithm="HS256")
+ response = client.get(RoutePath.WHOAMI, headers={"Authorization": f"Bearer {token}"})
+ assert response.status_code == 401
+ assert response.headers["content-type"] == "application/problem+json"
+ assert response.headers["WWW-Authenticate"] == "Bearer"
+ assert response.json()["error_type"] == "InvalidToken"
+
+ def test_jwt_invalid_token_rejected(self, mocker: MockerFixture):
+ mocker.patch("pipelex_api.security.get_optional_env", return_value=JWT_SECRET)
+ client = _build_jwt_client()
+ response = client.get(RoutePath.WHOAMI, headers={"Authorization": "Bearer not.a.real.token"})
+ assert response.status_code == 401
+ assert response.headers["content-type"] == "application/problem+json"
+ assert response.headers["WWW-Authenticate"] == "Bearer"
+ assert response.json()["error_type"] == "InvalidToken"
+
+ def test_jwt_wrong_secret_rejected(self, mocker: MockerFixture):
+ mocker.patch("pipelex_api.security.get_optional_env", return_value=JWT_SECRET)
+ client = _build_jwt_client()
+ token = jwt.encode({"user_id": USER_ID_UUID}, "different-secret", algorithm="HS256")
+ response = client.get(RoutePath.WHOAMI, headers={"Authorization": f"Bearer {token}"})
+ assert response.status_code == 401
+ assert response.headers["content-type"] == "application/problem+json"
+ assert response.headers["WWW-Authenticate"] == "Bearer"
+ assert response.json()["error_type"] == "InvalidToken"
+
+ def test_jwt_missing_secret_returns_500(self, mocker: MockerFixture):
+ mocker.patch("pipelex_api.security.get_optional_env", return_value=None)
+ client = _build_jwt_client()
+ token = jwt.encode({"user_id": USER_ID_UUID}, "anything", algorithm="HS256")
+ response = client.get(RoutePath.WHOAMI, headers={"Authorization": f"Bearer {token}"})
+ assert response.status_code == 500
+ assert response.headers["content-type"] == "application/problem+json"
+ assert response.json()["error_type"] == "ServerMisconfigured"
+
+ def test_api_key_happy_path(self, mocker: MockerFixture):
+ mocker.patch("pipelex_api.security.get_optional_env", return_value=API_KEY)
+ client = _build_api_key_client()
+ response = client.get(RoutePath.PING, headers={"Authorization": f"Bearer {API_KEY}"})
+ assert response.status_code == 200
+ assert response.json() == {"ok": "yes"}
+
+ def test_api_key_wrong_key_rejected(self, mocker: MockerFixture):
+ mocker.patch("pipelex_api.security.get_optional_env", return_value=API_KEY)
+ client = _build_api_key_client()
+ response = client.get(RoutePath.PING, headers={"Authorization": "Bearer wrong-key"})
+ assert response.status_code == 401
+ assert response.headers["content-type"] == "application/problem+json"
+ assert response.headers["WWW-Authenticate"] == "Bearer"
+ assert response.json()["error_type"] == "InvalidToken"
+
+ def test_api_key_missing_env_returns_500(self, mocker: MockerFixture):
+ mocker.patch("pipelex_api.security.get_optional_env", return_value=None)
+ client = _build_api_key_client()
+ response = client.get(RoutePath.PING, headers={"Authorization": "Bearer anything"})
+ assert response.status_code == 500
+ assert response.headers["content-type"] == "application/problem+json"
+ assert response.json()["error_type"] == "ServerMisconfigured"
+
+ @pytest.mark.parametrize(
+ "authorization",
+ [
+ None, # header absent
+ "", # header present but empty
+ "Bearer", # bare scheme, no token
+ "Basic dXNlcjpwYXNz", # wrong scheme entirely
+ ],
+ )
+ def test_api_key_missing_or_malformed_header_rejected(self, mocker: MockerFixture, authorization: str | None):
+ """Missing / empty / non-Bearer Authorization → RFC 7807 401, not the old shape.
+
+ `HTTPBearer(auto_error=False)` means none of these branches go through
+ FastAPI's default `HTTPException` handler (which would emit
+ `application/json` `{"detail": "Not authenticated"}`). Instead
+ `verify_api_key` sees `credentials is None` and calls
+ `raise_unauthenticated(...)` — same problem document as every other 401.
+ """
+ mocker.patch("pipelex_api.security.get_optional_env", return_value=API_KEY)
+ client = _build_api_key_client()
+ headers: dict[str, str] = {} if authorization is None else {"Authorization": authorization}
+ response = client.get(RoutePath.PING, headers=headers)
+ assert response.status_code == 401
+ assert response.headers["content-type"] == "application/problem+json"
+ assert response.headers["WWW-Authenticate"] == "Bearer"
+ assert response.json()["error_type"] == "Unauthenticated"
+
+ @pytest.mark.parametrize(
+ "authorization",
+ [
+ None,
+ "",
+ "Bearer",
+ "Basic dXNlcjpwYXNz",
+ ],
+ )
+ def test_jwt_missing_or_malformed_header_rejected(self, mocker: MockerFixture, authorization: str | None):
+ """JWT counterpart of the API-key case: same RFC 7807 401 shape."""
+ mocker.patch("pipelex_api.security.get_optional_env", return_value=JWT_SECRET)
+ client = _build_jwt_client()
+ headers: dict[str, str] = {} if authorization is None else {"Authorization": authorization}
+ response = client.get(RoutePath.WHOAMI, headers=headers)
+ assert response.status_code == 401
+ assert response.headers["content-type"] == "application/problem+json"
+ assert response.headers["WWW-Authenticate"] == "Bearer"
+ assert response.json()["error_type"] == "Unauthenticated"
diff --git a/api/tests/unit/test_simple_routes.py b/api/tests/unit/test_simple_routes.py
new file mode 100644
index 000000000..54a073997
--- /dev/null
+++ b/api/tests/unit/test_simple_routes.py
@@ -0,0 +1,59 @@
+"""Smoke tests for /health and /v1/version endpoints + request-body size middleware."""
+
+from importlib.metadata import PackageNotFoundError
+from importlib.metadata import version as package_version
+
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+from mthds.protocol.protocol import PROTOCOL_VERSION
+from pytest_mock import MockerFixture
+from starlette.middleware.base import BaseHTTPMiddleware
+
+from pipelex_api.exception_handlers import register_exception_handlers
+from pipelex_api.middleware import request_body_size_middleware
+from pipelex_api.routes.health import router as health_router
+from pipelex_api.routes.version import router as version_router
+
+
+def _build_client_with_body_cap() -> TestClient:
+ app = FastAPI()
+ app.add_middleware(BaseHTTPMiddleware, dispatch=request_body_size_middleware)
+ app.include_router(health_router)
+ app.include_router(version_router, prefix="/v1")
+ register_exception_handlers(app)
+ return TestClient(app)
+
+
+class TestSimpleRoutes:
+ def test_health(self):
+ client = _build_client_with_body_cap()
+ response = client.get("/health")
+ assert response.status_code == 200
+ assert response.json() == {"status": "ok", "message": "Pipelex API is running"}
+
+ def test_version_shape(self):
+ """`GET /v1/version` returns the protocol VersionInfo shape with real versions."""
+ client = _build_client_with_body_cap()
+ response = client.get("/v1/version")
+ assert response.status_code == 200
+ body = response.json()
+ assert body["protocol_version"] == PROTOCOL_VERSION
+ assert body["implementation"] == "pipelex-api"
+ assert body["implementation_version"] == package_version("pipelex-api")
+ assert body["runtime_version"] == package_version("pipelex")
+
+ def test_version_handles_missing_metadata(self, mocker: MockerFixture):
+ mocker.patch("pipelex_api.routes.version.version", side_effect=PackageNotFoundError("pipelex"))
+ client = _build_client_with_body_cap()
+ response = client.get("/v1/version")
+ assert response.status_code == 500
+ assert response.headers["content-type"] == "application/problem+json"
+ assert response.json()["error_type"] == "PackageNotFound"
+
+ def test_request_body_size_rejects_oversized_via_content_length(self):
+ client = _build_client_with_body_cap()
+ # 200 MiB declared > 100 MiB default cap.
+ response = client.get("/health", headers={"content-length": str(200 * 1024 * 1024)})
+ assert response.status_code == 413
+ assert response.headers["content-type"] == "application/problem+json"
+ assert response.json()["error_type"] == "PayloadTooLarge"
diff --git a/api/tests/unit/test_start_dispatch.py b/api/tests/unit/test_start_dispatch.py
new file mode 100644
index 000000000..cf08e41c5
--- /dev/null
+++ b/api/tests/unit/test_start_dispatch.py
@@ -0,0 +1,112 @@
+"""`/start` is HONEST about fire-and-forget: it acks only when the resolved backend is async-capable.
+
+Fire-and-forget vs blocking is the ENDPOINT's delivery axis, never configured: `/execute` and
+`/validate` dispatch with `BLOCKING`, while `/start` dispatches with `FIRE_AND_FORGET`. So `/start`
+checks the resolved `orchestration_mode`'s orchestrator BEFORE any library load: an async-capable
+orchestrator (`supports_fire_and_forget=True`, e.g. `temporal`) acks `202` with its `workflow_id`,
+while a blocking-only orchestrator (`supports_fire_and_forget=False`, e.g. the in-process `direct`
+base) is refused HONESTLY with a `400` (`StartRequiresAsyncOrchestration`) instead of silently
+running blocking and acking. This pins both arms end-to-end on `POST /start`, with a stub orchestrator
+registered under the resolved mode (the boot slot is never used).
+"""
+
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+from pipelex.pipe_run.delivery_assignment import DeliveryAssignment
+from pipelex.pipe_run.pipe_job import PipeJob
+from pipelex.plugins.orchestrator_registry import OrchestratorRegistry
+from pipelex.runtime_bridge.payloads import PipelexPipeDispatchAck, PipelexPipeRunOutput
+from pytest_mock import MockerFixture
+
+from pipelex_api.api_config import ApiConfig
+from pipelex_api.exception_handlers import register_exception_handlers
+from pipelex_api.routes import router as api_router
+from tests.unit._constants import VALID_MTHDS
+
+_PIPELINE_NS = "pipelex_api.routes.pipelex.pipeline"
+
+
+class _RecordingStub:
+ """Stand-in orchestrator that records its dispatch and returns the configured `workflow_id`.
+
+ `supports_fire_and_forget` is the capability `/start` reads BEFORE dispatch: a True stub models
+ an async-capable backend (Temporal) that acks immediately with a `workflow_id`; a False stub
+ models a blocking-only backend (`direct`) that `/start` must refuse honestly. `start` records its
+ dispatch and returns the `PipelexPipeDispatchAck` (ids only) an async backend acks with; `execute`
+ (the blocking arm) is present only to satisfy the protocol — `/start` never drives it.
+ """
+
+ def __init__(self, *, workflow_id: str, supports_fire_and_forget: bool) -> None:
+ self.calls: list[dict[str, object]] = []
+ self._workflow_id = workflow_id
+ self.supports_fire_and_forget = supports_fire_and_forget
+
+ async def execute(self, *, pipe_job: PipeJob, delivery_assignment: DeliveryAssignment | None) -> PipelexPipeRunOutput:
+ msg = "/start drives the fire-and-forget `start` arm; `execute` must not be reached."
+ raise NotImplementedError(msg)
+
+ async def start(self, *, pipe_job: PipeJob, delivery_assignment: DeliveryAssignment | None) -> PipelexPipeDispatchAck:
+ self.calls.append({"delivery_assignment": delivery_assignment})
+ return PipelexPipeDispatchAck(
+ pipeline_run_id=pipe_job.job_metadata.run_metadata.pipeline_run_id,
+ workflow_id=self._workflow_id,
+ )
+
+
+def _build_client() -> TestClient:
+ app = FastAPI()
+ app.include_router(api_router, prefix="/v1")
+ register_exception_handlers(app)
+ return TestClient(app)
+
+
+def _force_config(mocker: MockerFixture, *, mode: str) -> None:
+ config = ApiConfig(orchestration_mode=mode, allow_request_orchestration_mode_override=False)
+ mocker.patch(f"{_PIPELINE_NS}.get_api_config", return_value=config)
+
+
+def _register_stub(mocker: MockerFixture, *, mode: str, stub: _RecordingStub) -> None:
+ mocker.patch(f"{_PIPELINE_NS}.get_orchestrator_registry", return_value=OrchestratorRegistry({mode: stub}))
+
+
+class TestStartCapabilityGate:
+ """End-to-end: `POST /start` acks only when the resolved backend can honor fire-and-forget."""
+
+ def test_start_acks_when_orchestrator_is_async_capable(self, mocker: MockerFixture) -> None:
+ # A `temporal` deployment whose orchestrator is async-capable: /start drives the fire-and-forget
+ # `start` arm and acks 202 with the workflow_id the orchestrator returns immediately.
+ _force_config(mocker, mode="temporal")
+ stub = _RecordingStub(workflow_id="wf-123", supports_fire_and_forget=True)
+ _register_stub(mocker, mode="temporal", stub=stub)
+
+ response = _build_client().post(
+ "/v1/start",
+ json={"pipe_code": "echo", "mthds_contents": [VALID_MTHDS], "inputs": {"text": "hello"}},
+ )
+
+ assert response.status_code == 202, response.text
+ body = response.json()
+ assert body["state"] == "STARTED"
+ assert body["workflow_id"] == "wf-123"
+ # /start drives the fire-and-forget `start` arm exactly once — the caller never chooses delivery.
+ assert len(stub.calls) == 1
+
+ def test_start_honestly_400s_when_orchestrator_is_blocking_only(self, mocker: MockerFixture) -> None:
+ # The orchestrator-agnostic base (`direct`) is blocking-only: /start refuses honestly with a
+ # 400 BEFORE any dispatch (the capability check runs before pipeline_run_setup), so the stub's
+ # `execute` is never awaited — no silent block-and-ack.
+ _force_config(mocker, mode="direct")
+ # workflow_id is a placeholder: the blocking-only backend is refused before `start` is ever
+ # reached, so this value is never observed.
+ stub = _RecordingStub(workflow_id="wf-unused", supports_fire_and_forget=False)
+ _register_stub(mocker, mode="direct", stub=stub)
+
+ response = _build_client().post(
+ "/v1/start",
+ json={"pipe_code": "echo", "mthds_contents": [VALID_MTHDS], "inputs": {"text": "hello"}},
+ )
+
+ assert response.status_code == 400, response.text
+ assert response.headers["content-type"].startswith("application/problem+json")
+ assert response.json()["error_type"] == "StartRequiresAsyncOrchestration"
+ assert stub.calls == []
diff --git a/api/tests/unit/test_sync_vendored_kit.py b/api/tests/unit/test_sync_vendored_kit.py
new file mode 100644
index 000000000..82ff1eea9
--- /dev/null
+++ b/api/tests/unit/test_sync_vendored_kit.py
@@ -0,0 +1,136 @@
+"""`scripts/sync_vendored_kit.py` carries this image's backend switches and never invents them.
+
+The vendored `backends.toml` is the only record of which backends the image enables, so the sync
+must keep every switch across a re-sync, disable a backend the kit adds, and stop when that record
+is missing or unreadable rather than render every backend off. The script is a standalone entry
+point, not a package module, so it is loaded from its path.
+"""
+
+import importlib.util
+import shutil
+from pathlib import Path
+from types import ModuleType
+
+import pytest
+
+_REPO_ROOT = Path(__file__).resolve().parents[2]
+_SCRIPT_PATH = _REPO_ROOT / "scripts" / "sync_vendored_kit.py"
+_VENDORED_CONFIG_DIR = _REPO_ROOT / ".pipelex"
+
+
+def _load_script() -> ModuleType:
+ spec = importlib.util.spec_from_file_location("sync_vendored_kit", _SCRIPT_PATH)
+ assert spec is not None
+ assert spec.loader is not None
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
+
+
+sync_vendored_kit = _load_script()
+
+KIT_BACKENDS_TOML = """\
+[kept_on]
+enabled = true
+api_key = "${KEPT_ON_API_KEY}"
+
+[kept_off] # a comment on the header
+enabled = true # the kit enables it, this image does not
+
+[new_in_kit]
+enabled = true
+"""
+
+
+def vendored_copy(tmp_path: Path) -> Path:
+ config_dir = tmp_path / ".pipelex"
+ shutil.copytree(_VENDORED_CONFIG_DIR, config_dir)
+ return config_dir
+
+
+class TestSyncVendoredKit:
+ def test_render_carries_each_switch_and_disables_a_new_backend(self) -> None:
+ rendered: str = sync_vendored_kit.render_backends_toml(
+ kit_text=KIT_BACKENDS_TOML,
+ enabled_switches={"kept_on": True, "kept_off": False},
+ )
+ assert rendered.startswith("# pipelex-api:")
+ assert rendered.endswith(
+ """\
+[kept_on]
+enabled = true
+api_key = "${KEPT_ON_API_KEY}"
+
+[kept_off] # a comment on the header
+enabled = false # the kit enables it, this image does not
+
+[new_in_kit]
+enabled = false
+"""
+ )
+
+ def test_render_refuses_a_kit_table_without_a_switch(self) -> None:
+ with pytest.raises(sync_vendored_kit.KitShapeError, match="no_switch"):
+ sync_vendored_kit.render_backends_toml(kit_text="[no_switch]\napi_key = 'x'\n", enabled_switches={})
+
+ def test_committed_tree_is_in_sync(self) -> None:
+ plan = sync_vendored_kit.plan_sync(_VENDORED_CONFIG_DIR)
+ assert plan.drifts == []
+ assert plan.is_clean
+
+ def test_committed_tree_enables_the_gateway(self) -> None:
+ switches: dict[str, bool] = sync_vendored_kit.read_enabled_switches(_VENDORED_CONFIG_DIR / "inference" / "backends.toml")
+ assert switches["pipelex_gateway"] is True
+ assert switches["internal"] is True
+
+ def test_a_table_without_a_switch_is_read_as_on(self, tmp_path: Path) -> None:
+ backends_toml = tmp_path / "backends.toml"
+ backends_toml.write_text("[acme]\napi_key = 'x'\n\n[other]\nenabled = false\n", encoding="utf-8")
+ assert sync_vendored_kit.read_enabled_switches(backends_toml) == {"acme": True, "other": False}
+
+ def test_a_backend_new_in_the_kit_arrives_disabled(self, vendored_copy: Path) -> None:
+ inference_dir = vendored_copy / "inference"
+ backends_toml = inference_dir / "backends.toml"
+ backends_toml.write_text(_without_table(backends_toml.read_text(encoding="utf-8"), "minimax"), encoding="utf-8")
+ (inference_dir / "backends" / "minimax.toml").unlink()
+ plan = sync_vendored_kit.plan_sync(vendored_copy)
+ rendered = next(drift.content for drift in plan.drifts if drift.path == backends_toml)
+ assert '[minimax]\ndisplay_name = "MiniMax"\nenabled = false\n' in rendered.decode("utf-8")
+
+ @pytest.mark.parametrize(
+ ("backends_toml_text", "reason"),
+ [
+ (None, "is missing"),
+ ("[pipelex_gateway\nenabled = true\n", "is not valid TOML"),
+ ("", "holds no backend table"),
+ ("[pipelex_gateway]\nenabled = 'yes'\n", "is not a boolean"),
+ ("[pipelex_gateway]\nenabled = true\n", "has no table for"),
+ ],
+ )
+ def test_sync_stops_when_the_switch_record_is_unusable(self, vendored_copy: Path, backends_toml_text: str | None, reason: str) -> None:
+ backends_toml = vendored_copy / "inference" / "backends.toml"
+ backends_toml.unlink()
+ if backends_toml_text is not None:
+ backends_toml.write_text(backends_toml_text, encoding="utf-8")
+ with pytest.raises(sync_vendored_kit.SwitchSourceError, match=reason):
+ sync_vendored_kit.plan_sync(vendored_copy)
+
+ def test_sync_stops_when_a_vendored_backend_lost_its_table(self, vendored_copy: Path) -> None:
+ backends_toml = vendored_copy / "inference" / "backends.toml"
+ backends_toml.write_text(_without_table(backends_toml.read_text(encoding="utf-8"), "internal"), encoding="utf-8")
+ with pytest.raises(sync_vendored_kit.SwitchSourceError, match=r"has no table for internal,"):
+ sync_vendored_kit.plan_sync(vendored_copy)
+
+
+def _without_table(toml_text: str, table_name: str) -> str:
+ """Cut one table, from its header to the next one, out of a TOML document."""
+ kept_lines: list[str] = []
+ skipping = False
+ for line in toml_text.splitlines(keepends=True):
+ if line.startswith("["):
+ skipping = line.startswith(f"[{table_name}]")
+ if not skipping:
+ kept_lines.append(line)
+ assert len(kept_lines) < len(toml_text.splitlines())
+ return "".join(kept_lines)
diff --git a/api/tests/unit/test_tools_routes.py b/api/tests/unit/test_tools_routes.py
new file mode 100644
index 000000000..684d389d1
--- /dev/null
+++ b/api/tests/unit/test_tools_routes.py
@@ -0,0 +1,126 @@
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+from pipelex_api.exception_handlers import register_exception_handlers
+from pipelex_api.limits import MAX_MTHDS_FILE_BYTES
+from pipelex_api.openapi_schema import PipelexFastAPI
+from pipelex_api.problem_document import PROBLEM_JSON_MEDIA_TYPE
+from pipelex_api.routes import router as api_router
+from tests.unit._constants import VALID_MTHDS
+
+SCHEMA_INVALID_MTHDS = """\
+domain = "broken"
+main_pipe = "echo"
+
+[pipe.echo]
+type = "Nope"
+description = "Bad"
+"""
+
+
+def _build_client() -> TestClient:
+ app = FastAPI()
+ app.include_router(api_router, prefix="/v1")
+ register_exception_handlers(app)
+ return TestClient(app)
+
+
+def _build_app() -> FastAPI:
+ # `PipelexFastAPI`, not a bare `FastAPI`: the problem+json media type on error responses is
+ # asserted by the app class's `openapi()` override (see `pipelex_api.openapi_schema`), so a schema
+ # built off a stock app would not be the one this server publishes.
+ app = PipelexFastAPI()
+ app.include_router(api_router, prefix="/v1")
+ return app
+
+
+class TestLintRoute:
+ def test_valid_content_returns_no_diagnostics(self):
+ response = _build_client().post("/v1/lint", json={"content": VALID_MTHDS})
+
+ assert response.status_code == 200, response.text
+ assert response.json() == {"diagnostics": []}
+
+ def test_syntax_error_returns_200_with_diagnostic(self):
+ response = _build_client().post("/v1/lint", json={"content": "key = "})
+
+ assert response.status_code == 200, response.text
+ body = response.json()
+ assert body["diagnostics"]
+ assert body["diagnostics"][0]["kind"] == "syntax"
+ assert body["diagnostics"][0]["range"]["start_line"] == 1
+
+ def test_schema_error_returns_200_with_diagnostic(self):
+ response = _build_client().post("/v1/lint", json={"content": SCHEMA_INVALID_MTHDS, "source": "broken.mthds"})
+
+ assert response.status_code == 200, response.text
+ diagnostics = response.json()["diagnostics"]
+ assert diagnostics
+ assert any(diagnostic["kind"] == "schema" for diagnostic in diagnostics)
+
+ def test_oversized_content_returns_rfc7807_422(self):
+ response = _build_client().post("/v1/lint", json={"content": "a" * (MAX_MTHDS_FILE_BYTES + 1)})
+
+ assert response.status_code == 422, response.text
+ assert response.headers["content-type"] == PROBLEM_JSON_MEDIA_TYPE
+ body = response.json()
+ assert body["error_type"] == "ValidationError"
+ assert "MTHDS file exceeds" in body["detail"]
+
+
+class TestFormatRoute:
+ def test_unformatted_valid_content_returns_changed_output(self):
+ response = _build_client().post("/v1/format", json={"content": "a=1"})
+
+ assert response.status_code == 200, response.text
+ body = response.json()
+ assert body == {"formatted": "a = 1\n", "changed": True, "diagnostics": []}
+
+ def test_already_formatted_content_returns_unchanged_output(self):
+ response = _build_client().post("/v1/format", json={"content": "a = 1\n"})
+
+ assert response.status_code == 200, response.text
+ body = response.json()
+ assert body["formatted"] == "a = 1\n"
+ assert body["changed"] is False
+ assert body["diagnostics"] == []
+
+ def test_syntax_error_returns_200_with_unchanged_content_and_diagnostic(self):
+ response = _build_client().post("/v1/format", json={"content": "key = "})
+
+ assert response.status_code == 200, response.text
+ body = response.json()
+ assert body["formatted"] == "key = "
+ assert body["changed"] is False
+ assert body["diagnostics"]
+ assert body["diagnostics"][0]["kind"] == "syntax"
+
+ def test_malformed_options_return_rfc7807_422(self):
+ response = _build_client().post("/v1/format", json={"content": "a = 1\n", "options": {"column_width": "wide"}})
+
+ assert response.status_code == 422, response.text
+ assert response.headers["content-type"] == PROBLEM_JSON_MEDIA_TYPE
+ body = response.json()
+ assert body["error_type"] == "ValidationError"
+ assert "column_width" in body["detail"]
+
+
+class TestToolsRouteSchema:
+ def test_tools_routes_are_served_under_v1(self):
+ schema = _build_app().openapi()
+
+ assert "/v1/lint" in schema["paths"]
+ assert "/v1/format" in schema["paths"]
+
+ def test_tools_routes_are_not_mthds_protocol_tagged(self):
+ schema = _build_app().openapi()
+
+ assert "x-mthds-protocol" not in schema["paths"]["/v1/lint"]["post"]
+ assert "x-mthds-protocol" not in schema["paths"]["/v1/format"]["post"]
+
+ def test_tools_routes_advertise_problem_json_422(self):
+ schema = _build_app().openapi()
+
+ for path in ("/v1/lint", "/v1/format"):
+ error_content = schema["paths"][path]["post"]["responses"]["422"]["content"]
+ assert set(error_content) == {PROBLEM_JSON_MEDIA_TYPE}
diff --git a/api/tests/unit/test_user_id_safety.py b/api/tests/unit/test_user_id_safety.py
new file mode 100644
index 000000000..932e8203a
--- /dev/null
+++ b/api/tests/unit/test_user_id_safety.py
@@ -0,0 +1,48 @@
+"""Unit tests for `is_safe_user_id` — the single-segment, URI-safe id invariant.
+
+`user_id` is the first path segment of every `pipelex-storage://<user_id>/...`
+URI and S3 key. It must therefore be path-safe (no traversal) AND an
+unambiguous single URI segment: a value carrying a URI gen-delim (`: / ? # [ ] @`)
+parses differently under a raw split vs a standard URI parser, so the owner a
+consumer resolves could disagree with the owner this server authorized.
+"""
+
+import pytest
+
+from pipelex_api.security import is_safe_user_id
+
+
+class TestIsSafeUserId:
+ @pytest.mark.parametrize(
+ "user_id",
+ [
+ "11111111-1111-4111-8111-111111111111", # bare uuid
+ "user_11111111-1111-4111-8111-111111111111", # prefixed scheme
+ "user-123",
+ "google.abc", # dot is fine — not a URI delimiter, not a traversal segment
+ "a" * 36,
+ ],
+ )
+ def test_accepts_unambiguous_segments(self, user_id: str):
+ assert is_safe_user_id(user_id) is True
+
+ @pytest.mark.parametrize(
+ "user_id",
+ [
+ "", # empty
+ ".", # traversal
+ "..", # traversal
+ "a/b", # path separator
+ "a\\b", # backslash
+ "with\x00null", # C0 control
+ "with\x7fdel", # DEL
+ # URI gen-delims — ambiguous when embedded in pipelex-storage://<id>/...
+ "google#abc", # fragment delimiter (urlparse owner -> "google")
+ "[email protected]", # userinfo delimiter (urlparse hostname -> "example.com")
+ "a:99999", # port delimiter
+ "a?b", # query delimiter
+ "a[b]", # IPv6-literal brackets
+ ],
+ )
+ def test_rejects_unsafe_or_ambiguous_segments(self, user_id: str):
+ assert is_safe_user_id(user_id) is False
diff --git a/api/tests/unit/test_validate_caller_identity.py b/api/tests/unit/test_validate_caller_identity.py
new file mode 100644
index 000000000..030402258
--- /dev/null
+++ b/api/tests/unit/test_validate_caller_identity.py
@@ -0,0 +1,232 @@
+"""`/validate` and `/build/runner` hand the runtime the caller their validation sweep is done for.
+
+A validation is not a run, but its dry runs and its `pipe_dry_run` event are still telemetry, and
+the runtime attributes them to the `CallerIdentity` it is handed. Every failure on this path is
+SILENT by construction: a keyword left out of `ApiRunner(...)` or `validate_bundle(...)` still
+answers 200, and the only symptom is that the sweep lands in PostHog under the deployment's
+constant id instead of the caller. So these tests read the caller off the call the runtime
+actually received — a recording validator for the dispatched `/validate`, the real in-process
+entry points (wrapped, not replaced) for the direct path and for `/build/runner`.
+
+The user comes from `request.state.user`, which the auth layer sets; a tiny middleware stands in
+for it here. The groups come from the body and are refused at the wire exactly as on a run.
+"""
+
+from collections.abc import Awaitable, Callable, Sequence
+from pathlib import Path
+from typing import Any
+
+import pytest
+from fastapi import FastAPI, Request, Response
+from fastapi.testclient import TestClient
+from pipelex.base_exceptions import ErrorReport, ValidationErrorCategory, ValidationErrorItem
+from pipelex.pipeline.validate_bundle import validate_bundle
+from pipelex.pipeline.validate_in_process import validate_bundles_in_process
+from pipelex.plugins.bundle_validator_registry import BundleValidatorRegistry
+from pipelex.system.caller_identity import CallerIdentity
+from pipelex.system.storage_scope import SINGLE_TENANT_USER_ID
+from pytest_mock import MockerFixture
+
+from pipelex_api.api_config import ApiConfig
+from pipelex_api.exception_handlers import register_exception_handlers
+from pipelex_api.routes import router as api_router
+from pipelex_api.security import RequestUser
+from tests.unit._constants import STUB_METHOD_ADDRESS, VALID_MTHDS
+
+_PIPELINE_NS = "pipelex_api.routes.pipelex.pipeline"
+_RUNNER_NS = "pipelex_api.routes.pipelex.build.runner"
+_DIRECT_VALIDATOR_NS = "pipelex.pipeline.direct_bundle_validator"
+_MODE = "temporal"
+_USER_ID = "user_42"
+_GROUPS = {"organization": "org_acme", "workspace": "ws-42"}
+_METHOD_REF = f"{STUB_METHOD_ADDRESS}@v0.1.0"
+
+_BAD_GROUPS = [
+ pytest.param({"Organization": "org_acme"}, id="type-not-snake-case"),
+ pytest.param({"organization": "org acme"}, id="key-with-space"),
+ pytest.param({"organization": ""}, id="empty-key"),
+ pytest.param({f"group_{idx}": "org_acme" for idx in range(6)}, id="over-the-entry-cap"),
+ pytest.param({"organization": 42}, id="non-string-key"),
+ pytest.param(["organization"], id="not-a-mapping"),
+]
+
+
+class _RecordingBundleValidator:
+ """Records the caller of every validation dispatched to it, then answers an invalid verdict."""
+
+ def __init__(self) -> None:
+ self.caller_identities: list[CallerIdentity | None] = []
+
+ async def validate_bundles(
+ self,
+ *,
+ mthds_contents: list[str], # noqa: ARG002
+ mthds_sources: list[str] | None, # noqa: ARG002
+ allow_signatures: bool, # noqa: ARG002
+ library_dirs: Sequence[Path] | None, # noqa: ARG002
+ caller_identity: CallerIdentity | None,
+ graph_pipe_code: str | None, # noqa: ARG002
+ ) -> ErrorReport:
+ self.caller_identities.append(caller_identity)
+ return ErrorReport(
+ error_type="ValidateBundleError",
+ message="bundle is invalid",
+ title="Validate bundle error",
+ type_uri="https://errors.pipelex.com/validate-bundle-error/",
+ validation_errors=[ValidationErrorItem(category=ValidationErrorCategory.BLUEPRINT_VALIDATION, message="bad ref")],
+ )
+
+
+def _build_client(*, user_id: str | None) -> TestClient:
+ app = FastAPI()
+
+ if user_id is not None:
+ authenticated_user = RequestUser(user_id=user_id)
+
+ async def authenticate(request: Request, call_next: Callable[[Request], Awaitable[Response]]) -> Response:
+ request.state.user = authenticated_user
+ return await call_next(request)
+
+ app.middleware("http")(authenticate)
+
+ app.include_router(api_router, prefix="/v1")
+ register_exception_handlers(app)
+ return TestClient(app)
+
+
+def _register_recording_validator(mocker: MockerFixture) -> _RecordingBundleValidator:
+ config = ApiConfig(orchestration_mode=_MODE, allow_request_orchestration_mode_override=False)
+ mocker.patch(f"{_PIPELINE_NS}.get_api_config", return_value=config)
+ validator = _RecordingBundleValidator()
+ mocker.patch(f"{_PIPELINE_NS}.get_bundle_validator_registry", return_value=BundleValidatorRegistry({_MODE: validator}))
+ return validator
+
+
+def _caller_of(mock_call: Any) -> CallerIdentity | None:
+ caller_identity: CallerIdentity | None = mock_call.kwargs["caller_identity"]
+ return caller_identity
+
+
+class TestValidationCallerIdentity:
+ def test_validate_hands_the_dispatched_validator_the_user_and_groups(self, mocker: MockerFixture) -> None:
+ validator = _register_recording_validator(mocker)
+ client = _build_client(user_id=_USER_ID)
+
+ response = client.post("/v1/validate", json={"mthds_contents": [VALID_MTHDS], "analytics_groups": _GROUPS})
+
+ assert response.status_code == 200, response.text
+ assert validator.caller_identities == [CallerIdentity(user_id=_USER_ID, extras=_GROUPS)]
+
+ @pytest.mark.parametrize(
+ "extras",
+ [
+ pytest.param({}, id="absent"),
+ pytest.param({"analytics_groups": None}, id="null"),
+ pytest.param({"analytics_groups": {}}, id="empty"),
+ ],
+ )
+ def test_validate_without_groups_or_user_states_the_single_tenant_caller(self, mocker: MockerFixture, extras: dict[str, Any]) -> None:
+ # No user on the request is a deployment with no user model, so the caller is the
+ # single-tenant placeholder (which telemetry never attributes to a person), and no groups
+ # means an empty mapping — nothing is invented.
+ validator = _register_recording_validator(mocker)
+ client = _build_client(user_id=None)
+
+ response = client.post("/v1/validate", json={"mthds_contents": [VALID_MTHDS], **extras})
+
+ assert response.status_code == 200, response.text
+ assert validator.caller_identities == [CallerIdentity(user_id=SINGLE_TENANT_USER_ID, extras={})]
+
+ def test_validate_by_method_ref_hands_the_validator_the_caller(self, mocker: MockerFixture, install_method_package: Callable[..., Path]) -> None:
+ install_method_package(files={"documents.mthds": VALID_MTHDS})
+ validator = _register_recording_validator(mocker)
+ client = _build_client(user_id=_USER_ID)
+
+ response = client.post("/v1/validate", json={"method_ref": _METHOD_REF, "analytics_groups": _GROUPS})
+
+ assert response.status_code == 200, response.text
+ assert validator.caller_identities == [CallerIdentity(user_id=_USER_ID, extras=_GROUPS)]
+
+ def test_direct_validate_reaches_the_in_process_sweep_with_the_caller(self, mocker: MockerFixture) -> None:
+ # The deployment default (`direct`) through the real in-process validator: the caller must
+ # arrive at `validate_bundles_in_process`, which opens the caller scope for the whole sweep.
+ sweep = mocker.patch(f"{_DIRECT_VALIDATOR_NS}.validate_bundles_in_process", wraps=validate_bundles_in_process)
+ client = _build_client(user_id=_USER_ID)
+
+ response = client.post("/v1/validate", json={"mthds_contents": [VALID_MTHDS], "analytics_groups": _GROUPS})
+
+ assert response.status_code == 200, response.text
+ assert response.json()["is_valid"] is True
+ assert sweep.call_count == 1
+ assert _caller_of(sweep.call_args) == CallerIdentity(user_id=_USER_ID, extras=_GROUPS)
+
+ @pytest.mark.parametrize("bad_groups", _BAD_GROUPS)
+ def test_validate_refuses_malformed_groups_with_a_422_naming_the_field(self, mocker: MockerFixture, bad_groups: Any) -> None:
+ validator = _register_recording_validator(mocker)
+ client = _build_client(user_id=_USER_ID)
+
+ response = client.post("/v1/validate", json={"mthds_contents": [VALID_MTHDS], "analytics_groups": bad_groups})
+
+ assert response.status_code == 422, response.text
+ assert response.headers["content-type"] == "application/problem+json"
+ body = response.json()
+ assert body["error_type"] == "InvalidAnalyticsGroups"
+ assert "analytics_groups" in body["detail"]
+ assert validator.caller_identities == []
+
+ def test_validate_failing_on_two_fields_gets_the_generic_error_type(self, mocker: MockerFixture) -> None:
+ # Naming one field would send the caller to fix that one and leave the other for the next
+ # request, so the classification falls back to the generic type and the detail names both.
+ validator = _register_recording_validator(mocker)
+ client = _build_client(user_id=_USER_ID)
+
+ response = client.post(
+ "/v1/validate",
+ json={"mthds_contents": [VALID_MTHDS], "allow_signatures": "not-a-bool", "analytics_groups": {"Organization": "org_acme"}},
+ )
+
+ assert response.status_code == 422, response.text
+ body = response.json()
+ assert body["error_type"] == "ValidationError"
+ assert "analytics_groups" in body["detail"]
+ assert "allow_signatures" in body["detail"]
+ assert validator.caller_identities == []
+
+ def test_build_runner_sweeps_for_the_caller(self, mocker: MockerFixture) -> None:
+ sweep = mocker.patch(f"{_RUNNER_NS}.validate_bundle", wraps=validate_bundle)
+ client = _build_client(user_id=_USER_ID)
+
+ response = client.post(
+ "/v1/build/runner",
+ json={"files": [{"content": VALID_MTHDS}], "pipe_ref": "smoke.echo", "analytics_groups": _GROUPS},
+ )
+
+ assert response.status_code == 200, response.text
+ assert response.json()["is_valid"] is True
+ assert sweep.call_count == 1
+ assert _caller_of(sweep.call_args) == CallerIdentity(user_id=_USER_ID, extras=_GROUPS)
+
+ def test_build_runner_without_groups_or_user_states_the_single_tenant_caller(self, mocker: MockerFixture) -> None:
+ sweep = mocker.patch(f"{_RUNNER_NS}.validate_bundle", wraps=validate_bundle)
+ client = _build_client(user_id=None)
+
+ response = client.post("/v1/build/runner", json={"files": [{"content": VALID_MTHDS}], "pipe_ref": "smoke.echo"})
+
+ assert response.status_code == 200, response.text
+ assert _caller_of(sweep.call_args) == CallerIdentity(user_id=SINGLE_TENANT_USER_ID, extras={})
+
+ @pytest.mark.parametrize("bad_groups", _BAD_GROUPS)
+ def test_build_runner_refuses_malformed_groups_with_a_422_naming_the_field(self, mocker: MockerFixture, bad_groups: Any) -> None:
+ sweep = mocker.patch(f"{_RUNNER_NS}.validate_bundle", wraps=validate_bundle)
+ client = _build_client(user_id=_USER_ID)
+
+ response = client.post(
+ "/v1/build/runner",
+ json={"files": [{"content": VALID_MTHDS}], "pipe_ref": "smoke.echo", "analytics_groups": bad_groups},
+ )
+
+ assert response.status_code == 422, response.text
+ body = response.json()
+ assert body["error_type"] == "InvalidAnalyticsGroups"
+ assert "analytics_groups" in body["detail"]
+ assert sweep.call_count == 0
diff --git a/api/tests/unit/test_validate_default_pipe_ref.py b/api/tests/unit/test_validate_default_pipe_ref.py
new file mode 100644
index 000000000..6caf405c1
--- /dev/null
+++ b/api/tests/unit/test_validate_default_pipe_ref.py
@@ -0,0 +1,136 @@
+"""`default_pipe_ref` on the /validate valid arm — the pipe a selector-less run would execute.
+
+The canonical `PipelexValidationReport` is manifest-blind: its `bundle_blueprint` is the batch's
+primary blueprint, so a package whose `METHODS.toml` names an entry pipe the closure would not
+default to validates with a report from which a consumer can only derive the WRONG entry pipe, or
+none. These tests pin the route's own field, which applies the run routes' precedence — the fetched
+manifest's `main_pipe`, else the closure's primary blueprint — so a by-address consumer projects a
+signature for the pipe `/execute` actually defaults to.
+"""
+
+from collections.abc import Callable
+from pathlib import Path
+
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+from pipelex_api.exception_handlers import register_exception_handlers
+from pipelex_api.routes import router as api_router
+from tests.unit._constants import (
+ COLLIDING_ECHO_LIST_MTHDS,
+ INVALID_MAIN_PIPE_MTHDS,
+ NO_MAIN_PIPE_MTHDS,
+ SECOND_MAIN_PIPE_MTHDS,
+ STUB_METHOD_ADDRESS,
+ STUB_METHOD_MANIFEST_MAIN_PIPE_SHOUT,
+ STUB_METHOD_MANIFEST_NO_MAIN_PIPE,
+ VALID_MTHDS,
+)
+
+_METHOD_REF = f"{STUB_METHOD_ADDRESS}@v0.1.0"
+
+
+def _build_client() -> TestClient:
+ app = FastAPI()
+ app.include_router(api_router, prefix="/v1")
+ register_exception_handlers(app)
+ return TestClient(app)
+
+
+class TestValidateDefaultPipeRef:
+ def test_inline_contents_report_the_closures_declaration_qualified(self):
+ client = _build_client()
+ response = client.post("/v1/validate", json={"mthds_contents": [VALID_MTHDS]})
+ assert response.status_code == 200, response.text
+ body = response.json()
+ assert body["is_valid"] is True
+ # The bundle declares `main_pipe = "echo"` in domain `smoke`; the field qualifies it, where
+ # `bundle_blueprint.main_pipe` leaves the caller to reconstruct the domain.
+ assert body["default_pipe_ref"] == "smoke.echo"
+
+ def test_a_closure_declaring_no_main_pipe_reports_null(self):
+ client = _build_client()
+ response = client.post("/v1/validate", json={"mthds_contents": [NO_MAIN_PIPE_MTHDS]})
+ assert response.status_code == 200, response.text
+ body = response.json()
+ assert body["is_valid"] is True
+ assert body["default_pipe_ref"] is None
+
+ def test_several_declared_main_pipes_report_the_run_default_not_null(self):
+ # The field states the RUN default (`select_primary_blueprint`: first blueprint declaring
+ # `main_pipe`), NOT the build routes' stricter rule that 422s on several. `/execute` and
+ # `/start` run this closure happily, so reporting null would make a consumer refuse to
+ # prepare a method the server would run.
+ client = _build_client()
+ response = client.post("/v1/validate", json={"mthds_contents": [VALID_MTHDS, SECOND_MAIN_PIPE_MTHDS]})
+ assert response.status_code == 200, response.text
+ body = response.json()
+ assert body["is_valid"] is True
+ assert body["default_pipe_ref"] == "smoke.echo"
+
+ def test_the_invalid_arm_carries_no_default_pipe_ref(self):
+ # No library was assembled, so there is no entry pipe to name — the field follows the other
+ # structural artifacts into absence rather than riding as a null.
+ client = _build_client()
+ response = client.post("/v1/validate", json={"mthds_contents": [INVALID_MAIN_PIPE_MTHDS]})
+ assert response.status_code == 200, response.text
+ body = response.json()
+ assert body["is_valid"] is False
+ assert "default_pipe_ref" not in body
+
+ def test_method_ref_reports_the_manifests_entry_pipe_over_the_closures(self, install_method_package: Callable[..., Path]):
+ # The gap this field closes: the manifest names `shout`, the closure's own primary blueprint
+ # declares `echo`. A run by this address executes `other.shout`; a consumer reading
+ # `bundle_blueprint.main_pipe` would project `echo` and type a call site nothing runs.
+ # The package's files are read in sorted order, so `a_smoke.mthds` is the batch's primary
+ # blueprint — the one whose `main_pipe` the canonical report reports.
+ install_method_package(
+ files={"a_smoke.mthds": VALID_MTHDS, "b_other.mthds": SECOND_MAIN_PIPE_MTHDS},
+ manifest_toml=STUB_METHOD_MANIFEST_MAIN_PIPE_SHOUT,
+ )
+ client = _build_client()
+ response = client.post("/v1/validate", json={"method_ref": _METHOD_REF})
+ assert response.status_code == 200, response.text
+ body = response.json()
+ assert body["is_valid"] is True
+ assert body["default_pipe_ref"] == "other.shout"
+ # The report itself stays manifest-blind — which is exactly why the field has to exist.
+ assert body["bundle_blueprint"]["main_pipe"] == "echo"
+
+ def test_method_ref_qualifies_the_manifests_bare_code(self, install_method_package: Callable[..., Path]):
+ # A `METHODS.toml` `main_pipe` is a bare code; the wire field is always qualified.
+ install_method_package(files={"documents.mthds": VALID_MTHDS})
+ client = _build_client()
+ response = client.post("/v1/validate", json={"method_ref": _METHOD_REF})
+ assert response.status_code == 200, response.text
+ assert response.json()["default_pipe_ref"] == "smoke.echo"
+
+ def test_a_manifest_without_main_pipe_falls_back_to_the_closures_declaration(self, install_method_package: Callable[..., Path]):
+ install_method_package(files={"documents.mthds": VALID_MTHDS}, manifest_toml=STUB_METHOD_MANIFEST_NO_MAIN_PIPE)
+ client = _build_client()
+ response = client.post("/v1/validate", json={"method_ref": _METHOD_REF})
+ assert response.status_code == 200, response.text
+ assert response.json()["default_pipe_ref"] == "smoke.echo"
+
+ def test_a_manifest_naming_a_pipe_the_closure_lacks_reports_null(self, install_method_package: Callable[..., Path]):
+ # The manifest names `shout`; the package's closure holds only `smoke.echo`. A selector-less
+ # run would pass `shout` and fail to resolve it, so the field must not fall back to the
+ # closure's `echo` — that names a pipe no run of this address executes.
+ install_method_package(files={"smoke.mthds": VALID_MTHDS}, manifest_toml=STUB_METHOD_MANIFEST_MAIN_PIPE_SHOUT)
+ client = _build_client()
+ response = client.post("/v1/validate", json={"method_ref": _METHOD_REF})
+ assert response.status_code == 200, response.text
+ body = response.json()
+ assert body["is_valid"] is True
+ assert body["default_pipe_ref"] is None
+
+ def test_an_ambiguous_manifest_bare_code_reports_null(self, install_method_package: Callable[..., Path]):
+ # The manifest names `echo`, declared by both `smoke` and `twin`. The engine's entry lookup
+ # raises on an ambiguous bare code rather than picking a winner, so the field says nothing.
+ install_method_package(files={"smoke.mthds": VALID_MTHDS, "twin.mthds": COLLIDING_ECHO_LIST_MTHDS})
+ client = _build_client()
+ response = client.post("/v1/validate", json={"method_ref": _METHOD_REF})
+ assert response.status_code == 200, response.text
+ body = response.json()
+ assert body["is_valid"] is True
+ assert body["default_pipe_ref"] is None
diff --git a/api/tests/unit/test_validate_dispatch.py b/api/tests/unit/test_validate_dispatch.py
new file mode 100644
index 000000000..24454ae3f
--- /dev/null
+++ b/api/tests/unit/test_validate_dispatch.py
@@ -0,0 +1,175 @@
+"""`/validate` dispatches by orchestration_mode through the BundleValidatorRegistry (verdict-as-value).
+
+Pins the dispatch+route mapping independent of any real backend, with a stub validator registered
+for a non-direct mode (no `temporalio` import): the runner resolves the deployment's orchestration_mode,
+dispatches to the validator the registry holds for it, and the route maps the *returned* verdict —
+an `ErrorReport` with validation diagnostics to a 200 `InvalidReport`, a returned backend fault report
+to problem+json, and a raised fault to a 5xx. Also pins the no-validator case (`MissingBundleValidatorError`)
+and that the route threads `orchestration_mode` into the same override policy `/start` uses (a forbidden
+override is a 403). The `direct` path is covered end-to-end by the existing `/validate` suite; this proves
+the dispatch is backend-agnostic, not direct-only.
+"""
+
+from collections.abc import Sequence
+from pathlib import Path
+from typing import Any
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+from pipelex.base_exceptions import ErrorDomain, ErrorReport, PipelexConfigError, ValidationErrorCategory, ValidationErrorItem
+from pipelex.plugins.bundle_validator_registry import BundleValidatorRegistry
+from pipelex.runtime_bridge.exceptions import MissingBundleValidatorError
+from pipelex.system.caller_identity import CallerIdentity
+from pytest_mock import MockerFixture
+
+from pipelex_api.api_config import ApiConfig
+from pipelex_api.exception_handlers import register_exception_handlers
+from pipelex_api.routes import router as api_router
+from pipelex_api.routes.pipelex.pipeline import ApiRunner
+from tests.unit._constants import VALID_MTHDS
+
+_PIPELINE_NS = "pipelex_api.routes.pipelex.pipeline"
+
+
+class _StubBundleValidator:
+ """A backend-agnostic stand-in validator: records its call, then returns or raises as configured."""
+
+ def __init__(self, *, verdict: ErrorReport | None = None, error: Exception | None = None) -> None:
+ self._verdict = verdict
+ self._error = error
+ self.calls: list[dict[str, Any]] = []
+
+ async def validate_bundles(
+ self,
+ *,
+ mthds_contents: list[str],
+ mthds_sources: list[str] | None,
+ allow_signatures: bool,
+ library_dirs: Sequence[Path] | None,
+ caller_identity: CallerIdentity | None,
+ graph_pipe_code: str | None,
+ ) -> ErrorReport:
+ self.calls.append(
+ {
+ "mthds_contents": mthds_contents,
+ "mthds_sources": mthds_sources,
+ "allow_signatures": allow_signatures,
+ "library_dirs": library_dirs,
+ "caller_identity": caller_identity,
+ "graph_pipe_code": graph_pipe_code,
+ }
+ )
+ if self._error is not None:
+ raise self._error
+ assert self._verdict is not None
+ return self._verdict
+
+
+def _build_client() -> TestClient:
+ app = FastAPI()
+ app.include_router(api_router, prefix="/v1")
+ register_exception_handlers(app)
+ return TestClient(app)
+
+
+def _register_stub_for_temporal(mocker: MockerFixture, stub: _StubBundleValidator) -> None:
+ """Make the deployment default to the `temporal` mode and register `stub` for it — no temporalio import.
+
+ Patches the api config (so the real `resolve_orchestration_mode` returns the temporal mode by default)
+ and the bundle-validator registry (so the route's mode lookup finds the stub).
+ """
+ temporal_config = ApiConfig(orchestration_mode="temporal", allow_request_orchestration_mode_override=False)
+ mocker.patch(f"{_PIPELINE_NS}.get_api_config", return_value=temporal_config)
+ registry = BundleValidatorRegistry({"temporal": stub})
+ mocker.patch(f"{_PIPELINE_NS}.get_bundle_validator_registry", return_value=registry)
+
+
+class TestValidateDispatch:
+ def test_non_direct_validators_invalid_verdict_maps_to_200_invalid_report(self, mocker: MockerFixture) -> None:
+ """A non-direct validator's returned ErrorReport is mapped to a 200 InvalidReport, threading the request."""
+ invalid_verdict = ErrorReport(
+ error_type="ValidateBundleError",
+ message="bundle is invalid",
+ title="Validate bundle error",
+ type_uri="https://errors.pipelex.com/validate-bundle-error/",
+ validation_errors=[ValidationErrorItem(category=ValidationErrorCategory.BLUEPRINT_VALIDATION, message="bad ref")],
+ )
+ stub = _StubBundleValidator(verdict=invalid_verdict)
+ _register_stub_for_temporal(mocker, stub)
+
+ client = _build_client()
+ response = client.post("/v1/validate", json={"mthds_contents": [VALID_MTHDS], "allow_signatures": True})
+
+ assert response.status_code == 200, response.text
+ body = response.json()
+ assert body["is_valid"] is False
+ assert any(item["category"] == ValidationErrorCategory.BLUEPRINT_VALIDATION for item in body["validation_errors"])
+ # The dispatch reached the registered non-direct validator, with the request threaded through.
+ assert len(stub.calls) == 1
+ assert stub.calls[0]["mthds_contents"] == [VALID_MTHDS]
+ assert stub.calls[0]["allow_signatures"] is True
+
+ def test_validator_fault_propagates_as_5xx(self, mocker: MockerFixture) -> None:
+ """A validator that raises a genuine fault (no verdict produced) propagates to the global 5xx handler."""
+ stub = _StubBundleValidator(error=PipelexConfigError("backend wiring fault"))
+ _register_stub_for_temporal(mocker, stub)
+
+ client = _build_client()
+ response = client.post("/v1/validate", json={"mthds_contents": [VALID_MTHDS]})
+
+ assert response.status_code >= 500, response.text
+ assert response.headers["content-type"].startswith("application/problem+json")
+ assert "is_valid" not in response.json()
+
+ def test_returned_non_verdict_error_report_maps_to_problem_json(self, mocker: MockerFixture) -> None:
+ """A registry-backed validator can return a classified backend fault report, not an invalid-bundle verdict."""
+ backend_fault = ErrorReport(
+ error_type="TemporalTransportError",
+ message="validator backend unavailable",
+ title="Temporal transport error",
+ type_uri="https://errors.pipelex.com/temporal-transport-error/",
+ error_domain=ErrorDomain.CONFIG,
+ )
+ stub = _StubBundleValidator(verdict=backend_fault)
+ _register_stub_for_temporal(mocker, stub)
+
+ client = _build_client()
+ response = client.post("/v1/validate", json={"mthds_contents": [VALID_MTHDS]})
+
+ assert response.status_code == 500, response.text
+ assert response.headers["content-type"].startswith("application/problem+json")
+ body = response.json()
+ assert body["error_type"] == "TemporalTransportError"
+ assert body["error_domain"] == ErrorDomain.CONFIG
+ assert body["status"] == 500
+ assert "is_valid" not in body
+ assert "validation_errors" not in body
+
+ @pytest.mark.asyncio
+ async def test_missing_validator_for_resolved_mode_raises(self, mocker: MockerFixture) -> None:
+ """A resolved mode with no registered validator fails loud with MissingBundleValidatorError."""
+ mocker.patch(f"{_PIPELINE_NS}.get_bundle_validator_registry", return_value=BundleValidatorRegistry({}))
+
+ with pytest.raises(MissingBundleValidatorError) as exc_info:
+ await ApiRunner().validate_verdict(
+ mthds_contents=[VALID_MTHDS],
+ mthds_sources=None,
+ allow_signatures=False,
+ requested_orchestration_mode=None,
+ graph_pipe_code=None,
+ )
+ assert exc_info.value.mode == "direct"
+
+ def test_forbidden_orchestration_mode_override_is_a_403(self) -> None:
+ """The route threads orchestration_mode into the same override policy /start uses: a forbidden override is a 403."""
+ client = _build_client()
+ # Packaged default is `direct` with override OFF; forcing a different backend is refused before dispatch.
+ response = client.post(
+ "/v1/validate",
+ json={"mthds_contents": [VALID_MTHDS], "orchestration_mode": "temporal"},
+ )
+
+ assert response.status_code == 403, response.text
+ assert response.headers["content-type"].startswith("application/problem+json")
+ assert response.json()["error_type"] == "OrchestrationModeOverrideForbidden"
diff --git a/api/tests/unit/test_validate_envelope.py b/api/tests/unit/test_validate_envelope.py
new file mode 100644
index 000000000..2565675b7
--- /dev/null
+++ b/api/tests/unit/test_validate_envelope.py
@@ -0,0 +1,90 @@
+"""`/validate` envelope contract — the canonical report + wire extras.
+
+Phase 2 of the MTHDS Protocol surface alignment: `/validate` routes through
+`ApiRunner.validate`, so the HTTP envelope is the canonical `PipelexValidationReport`
+(`bundle_blueprint`, `pipe_io_contracts` keyed by namespaced `pipe_ref`, `validated_pipes`,
+`pending_signatures` + `is_runnable`, best-effort `graph_spec`) plus this server's
+wire-only extras (`mthds_contents` echo, `message`). The valid verdict carries `is_valid: true`
+(the discriminant of the 200 response union — the `success` extra is retired). Validation runs
+DIRECT in-process on the orchestrator-agnostic base (F2): the real in-process validation, with no
+orchestrator-backend selection.
+
+Includes the D2 regression pin: a bundle that declares no `main_pipe` validates with 200 and
+`graph_spec=null` — the former 422 precondition is deleted.
+"""
+
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+from pipelex.pipeline.bundle_validator import DryRunStatus
+
+from pipelex_api.exception_handlers import register_exception_handlers
+from pipelex_api.routes import router as api_router
+from tests.unit._constants import NO_MAIN_PIPE_MTHDS, SIGNATURE_MTHDS, VALID_MTHDS
+
+
+def _build_client() -> TestClient:
+ app = FastAPI()
+ app.include_router(api_router, prefix="/v1")
+ register_exception_handlers(app)
+ return TestClient(app)
+
+
+class TestValidateEnvelope:
+ def test_direct_success_envelope_is_canonical_report_plus_wire_extras(self):
+ client = _build_client()
+ response = client.post("/v1/validate", json={"mthds_contents": [VALID_MTHDS]})
+ assert response.status_code == 200, response.text
+ body = response.json()
+
+ # Canonical report (D1/D3/D7/D8): primary blueprint under `bundle_blueprint` —
+ # the pipelex_-prefixed field and the old local `blueprint` dump are both gone.
+ assert "pipelex_bundle_blueprint" not in body
+ assert "blueprint" not in body
+ assert body["bundle_blueprint"]["domain"] == "smoke"
+ assert body["bundle_blueprint"]["main_pipe"] == "echo"
+
+ # `pipe_io_contracts` keyed by namespaced pipe_ref with typed IO contracts.
+ io_contract = body["pipe_io_contracts"]["smoke.echo"]
+ assert io_contract["output"]["multiplicity"] == "single"
+ assert io_contract["output"]["concept_ref"]
+ assert "text" in io_contract["inputs"]
+ assert io_contract["inputs"]["text"]["concept_ref"]
+
+ # Per-pipe sweep outcomes, entries keyed `pipe_ref` (D7) — never `pipe_code`.
+ assert body["validated_pipes"] == [{"pipe_ref": "smoke.echo", "status": DryRunStatus.SUCCESS}]
+
+ # Runnability verdict + best-effort graph (main_pipe declared → graph produced).
+ assert body["pending_signatures"] == []
+ assert body["is_runnable"] is True
+ assert body["graph_spec"] is not None
+
+ # Wire extras the webapp depends on.
+ assert body["mthds_contents"] == [VALID_MTHDS]
+ assert body["is_valid"] is True
+ assert body["message"]
+
+ def test_direct_lenient_signatures_report_verdict(self):
+ client = _build_client()
+ response = client.post("/v1/validate", json={"mthds_contents": [SIGNATURE_MTHDS], "allow_signatures": True})
+ assert response.status_code == 200, response.text
+ body = response.json()
+ # The runnability verdict crosses the HTTP surface at last (F5 closed).
+ assert body["pending_signatures"] == ["sig_api.summary_sig"]
+ assert body["is_runnable"] is False
+ # The signature placeholder is a first-class pipe on every artifact.
+ assert set(body["pipe_io_contracts"]) == {"sig_api.caller_seq", "sig_api.summary_sig"}
+ validated_refs = {entry["pipe_ref"] for entry in body["validated_pipes"]}
+ assert validated_refs == {"sig_api.caller_seq", "sig_api.summary_sig"}
+
+ def test_direct_no_main_pipe_returns_200_without_graph(self):
+ # D2 regression pin (direct backend): this used to be a 422 route precondition.
+ client = _build_client()
+ response = client.post("/v1/validate", json={"mthds_contents": [NO_MAIN_PIPE_MTHDS]})
+ assert response.status_code == 200, response.text
+ body = response.json()
+ assert body["graph_spec"] is None
+ assert body["bundle_blueprint"]["domain"] == "nomain"
+ assert body["pipe_io_contracts"]["nomain.echo"]["output"]["multiplicity"] == "single"
+ assert body["validated_pipes"] == [{"pipe_ref": "nomain.echo", "status": DryRunStatus.SUCCESS}]
+ assert body["is_runnable"] is True
+ assert body["is_valid"] is True
diff --git a/api/tests/unit/test_validate_errors.py b/api/tests/unit/test_validate_errors.py
new file mode 100644
index 000000000..c7286003a
--- /dev/null
+++ b/api/tests/unit/test_validate_errors.py
@@ -0,0 +1,292 @@
+"""`/validate` 200-diagnostic verdict + structured error envelope + per-file `source` threading.
+
+`/validate` is a **diagnostic endpoint**: a produced verdict — valid or invalid — always rides a
+**200**, discriminated in the body on `is_valid`. An invalid bundle answers a 200 `InvalidReport`
+carrying a structured `validation_errors[]` list (the per-error diagnostics the VS Code extension
+maps to per-line problems), built by pipelex's one shared builder; the structural artifacts
+(`bundle_blueprint`, `pipe_io_contracts`, `graph_spec`, `validated_pipes`) are absent on the invalid
+arm. Non-2xx is reserved for *no-verdict* conditions: a malformed body or an
+`mthds_sources`/`mthds_contents` length mismatch is a request-shape **422**; a server fault that
+is not a produced verdict (a host-wiring `PipelexError` / `PipelexUnexpectedError`) is a **5xx**.
+
+When the caller sends `mthds_sources` parallel to `mthds_contents`, each name is threaded onto
+`blueprint.source`, so pipe/concept and blueprint errors name the owning file on BOTH the invalid
+arm (`validation_errors[].source`) and the valid arm (`bundle_blueprint.source`).
+
+Asserts the in-process wire response via `TestClient`; the conformance HTTP arm asserts the same
+200-diagnostic contract on the REAL wire (the spec's `<!-- unverified -->` markers point there).
+"""
+
+from typing import Any
+
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+from pipelex.base_exceptions import PipelexConfigError, ValidationErrorCategory
+from pipelex.core.exceptions import (
+ DryRunFailureErrorData,
+ PipeFactoryErrorData,
+ PipelexBundleBlueprintValidationErrorData,
+ PipesAndConceptValidationErrorData,
+)
+from pipelex.pipeline.exceptions import ValidateBundleError
+from pipelex.validation_error_types import PipeFactoryErrorType, PipeValidationErrorType
+from pytest_mock import MockerFixture
+
+from pipelex_api.exception_handlers import register_exception_handlers
+from pipelex_api.routes import router as api_router
+from pipelex_api.routes.pipelex.pipeline import ApiRunner
+from tests.unit._constants import INVALID_MAIN_PIPE_MTHDS, UNKNOWN_MODEL_MTHDS, VALID_MTHDS
+
+# Structural artifacts that exist only on the valid arm — the invalid arm must NOT carry them.
+_STRUCTURAL_FIELDS = ("bundle_blueprint", "pipe_io_contracts", "graph_spec", "validated_pipes")
+
+
+def _build_client() -> TestClient:
+ app = FastAPI()
+ app.include_router(api_router, prefix="/v1")
+ register_exception_handlers(app)
+ return TestClient(app)
+
+
+def _multi_category_error() -> ValidateBundleError:
+ """A `ValidateBundleError` carrying one item per structured category, fields fully populated.
+
+ The shared builder projects these onto `validation_errors[]`; collectively the three items
+ exercise every field of `ValidationErrorItem` (the blueprint item carries `variable_names`,
+ the factory item `missing_concept_code` / `declared_concepts`, the pipe item
+ `field_path` / `field_name`). Mocked rather than provoked from a crafted bundle so the
+ envelope projection is asserted independently of which bundle happens to trip which category.
+ """
+ return ValidateBundleError(
+ message="Bundle has multiple validation problems.",
+ pipelex_bundle_blueprint_validation_errors=[
+ PipelexBundleBlueprintValidationErrorData(
+ error_type=PipeValidationErrorType.MISSING_INPUT_VARIABLE,
+ domain_code="legal",
+ source="blueprint.mthds",
+ pipe_code="summarize",
+ concept_code="Contract",
+ message="Blueprint validation failed.",
+ variable_names=["contract"],
+ )
+ ],
+ pipe_factory_errors=[
+ PipeFactoryErrorData(
+ error_type=PipeFactoryErrorType.UNKNOWN_CONCEPT,
+ domain_code="legal",
+ pipe_code="summarize",
+ missing_concept_code="Summari",
+ declared_concepts=["Contract", "Summary"],
+ message="Pipe references an unknown concept.",
+ )
+ ],
+ pipe_validation_errors=[
+ PipesAndConceptValidationErrorData(
+ error_type=PipeValidationErrorType.INADEQUATE_OUTPUT_CONCEPT,
+ domain_code="legal",
+ source="pipe.mthds",
+ pipe_code="summarize",
+ concept_code="Summary",
+ field_name="output",
+ field_path="pipe.summarize.output",
+ message="Output concept is inadequate.",
+ )
+ ],
+ )
+
+
+class TestValidateErrors:
+ def test_invalid_bundle_returns_200_invalid_report(self):
+ client = _build_client()
+ response = client.post("/v1/validate", json={"mthds_contents": [INVALID_MAIN_PIPE_MTHDS]})
+
+ # A produced "invalid" verdict is a 200 InvalidReport, not a transport failure (422).
+ assert response.status_code == 200, response.text
+ assert response.headers["content-type"].startswith("application/json")
+ body = response.json()
+ assert body["is_valid"] is False
+ assert body["is_runnable"] is False
+ # The discriminated invalid arm carries diagnostics, not the valid arm's structural artifacts.
+ for field in _STRUCTURAL_FIELDS:
+ assert field not in body, f"invalid arm leaked structural field {field!r}: {body}"
+ # The retired wire extra is gone — the verdict is `is_valid`, never `success`.
+ assert "success" not in body
+ items: list[dict[str, Any]] = body["validation_errors"]
+ assert isinstance(items, list)
+ assert items, body
+ assert all(item["category"] in set(ValidationErrorCategory) and "message" in item for item in items)
+
+ def test_validation_errors_carry_threaded_source(self):
+ client = _build_client()
+ response = client.post(
+ "/v1/validate",
+ json={"mthds_contents": [INVALID_MAIN_PIPE_MTHDS], "mthds_sources": ["broken.mthds"]},
+ )
+
+ assert response.status_code == 200, response.text
+ body = response.json()
+ assert body["is_valid"] is False
+ items: list[dict[str, Any]] = body["validation_errors"]
+ # Pins that the dict-seeded blueprint-validation item carries the threaded name (not some
+ # coincidental other item): a regression that stopped seeding `source` would fail here.
+ sourced = [item for item in items if item.get("source") == "broken.mthds"]
+ assert sourced, f"no validation_errors item carried the threaded source: {items}"
+ assert any(item["category"] == ValidationErrorCategory.BLUEPRINT_VALIDATION for item in sourced)
+
+ def test_toml_syntax_errors_carry_threaded_source(self):
+ client = _build_client()
+ response = client.post(
+ "/v1/validate",
+ json={
+ "mthds_contents": ['domain = "broken" trailing'],
+ "mthds_sources": ["broken.mthds"],
+ },
+ )
+
+ assert response.status_code == 200, response.text
+ body = response.json()
+ assert body["is_valid"] is False
+ items: list[dict[str, Any]] = body["validation_errors"]
+ sourced = [item for item in items if item.get("source") == "broken.mthds"]
+ assert sourced, f"no validation_errors item carried the threaded source: {items}"
+ assert any(item["category"] == ValidationErrorCategory.BLUEPRINT_VALIDATION for item in sourced)
+ assert any("TOML syntax error" in item["message"] for item in sourced)
+
+ def test_unknown_model_is_a_located_item_of_the_invalid_verdict(self):
+ # A model the deck does not define is refused while the pipe is built. That refusal is an
+ # item of the verdict like any other, located on the pipe's `model` field and carrying the
+ # reference as written, not a no-verdict fault.
+ client = _build_client()
+ response = client.post(
+ "/v1/validate",
+ json={"mthds_contents": [UNKNOWN_MODEL_MTHDS], "mthds_sources": ["echo.mthds"]},
+ )
+
+ assert response.status_code == 200, response.text
+ body = response.json()
+ assert body["is_valid"] is False
+ items: list[dict[str, Any]] = body["validation_errors"]
+ assert len(items) == 1, items
+ item = items[0]
+ assert item["category"] == ValidationErrorCategory.PIPE_VALIDATION
+ assert item["error_type"] == "unknown_model"
+ assert item["pipe_code"] == "echo"
+ assert item["source"] == "echo.mthds"
+ assert item["field_path"] == "pipe.echo.model"
+ assert item["model_reference"] == "no-such-model-in-any-deck"
+ assert item["model_type"] == "llm"
+
+ def test_all_categories_project_onto_invalid_report(self, mocker: MockerFixture):
+ # Every structured category lands on the 200 InvalidReport, and collectively the items cover
+ # the full ValidationErrorItem field set (so a dropped field would fail here, not silently
+ # vanish at the verdict->wire boundary). The runner returns the invalid verdict as a value
+ # (an ErrorReport) — here the ValidateBundleError's own `to_error_report()` projection.
+ mocker.patch.object(ApiRunner, "validate_verdict", new=mocker.AsyncMock(return_value=_multi_category_error().to_error_report()))
+ client = _build_client()
+ response = client.post("/v1/validate", json={"mthds_contents": [VALID_MTHDS]})
+
+ assert response.status_code == 200, response.text
+ body = response.json()
+ assert body["is_valid"] is False
+ assert body["is_runnable"] is False
+ items: list[dict[str, Any]] = body["validation_errors"]
+ categories = {item["category"] for item in items}
+ assert categories == {
+ ValidationErrorCategory.BLUEPRINT_VALIDATION,
+ ValidationErrorCategory.PIPE_FACTORY,
+ ValidationErrorCategory.PIPE_VALIDATION,
+ }
+ # The union of populated fields across the items covers every ValidationErrorItem field.
+ populated = {key for item in items for key, value in item.items() if value is not None}
+ assert populated.issuperset(
+ {
+ "category",
+ "message",
+ "error_type",
+ "pipe_code",
+ "concept_code",
+ "domain_code",
+ "source",
+ "field_path",
+ "field_name",
+ "variable_names",
+ "missing_concept_code",
+ "declared_concepts",
+ }
+ ), f"missing fields: {populated}"
+
+ def test_dry_run_failures_become_one_located_item_per_failing_pipe(self, mocker: MockerFixture):
+ # A failing dry run is one `dry_run` item per failing pipe, located at the innermost pipe
+ # that failed (its `pipe_code`, `domain_code` and `source`), never one item holding the whole
+ # sweep. A failure the sweep could not locate still becomes its own item carrying only the
+ # message — the structured-info invariant (never a bare detail with an empty list) — and so
+ # carries no locator.
+ failing_dry_run = ValidateBundleError(
+ message="Dry run failed.",
+ dry_run_failures=[
+ DryRunFailureErrorData(pipe_code="summarize", domain_code="legal", source="pipe.mthds", message="Pipe 'summarize' failed: boom."),
+ DryRunFailureErrorData(message="Dry run failed: unlocated."),
+ ],
+ )
+ mocker.patch.object(ApiRunner, "validate_verdict", new=mocker.AsyncMock(return_value=failing_dry_run.to_error_report()))
+ client = _build_client()
+ response = client.post("/v1/validate", json={"mthds_contents": [VALID_MTHDS]})
+
+ assert response.status_code == 200, response.text
+ body = response.json()
+ assert body["is_valid"] is False
+ items: list[dict[str, Any]] = body["validation_errors"]
+ assert len(items) == 2, items
+ assert all(item["category"] == ValidationErrorCategory.DRY_RUN for item in items)
+ assert all(item["error_type"] == "DryRunError" for item in items)
+ located_item, unlocated_item = items
+ assert located_item["pipe_code"] == "summarize"
+ assert located_item["domain_code"] == "legal"
+ assert located_item["source"] == "pipe.mthds"
+ assert located_item["message"] == "Pipe 'summarize' failed: boom."
+ assert unlocated_item["message"] == "Dry run failed: unlocated."
+ for locator in ("pipe_code", "domain_code", "source"):
+ assert locator not in unlocated_item, unlocated_item
+
+ def test_non_verdict_failure_is_not_a_200_verdict(self, mocker: MockerFixture):
+ # The runner returns a produced verdict (valid report | invalid ErrorReport) as a value; only
+ # a no-verdict fault propagates. A genuine host-wiring/server fault must reach the global
+ # problem+json handler as a 5xx, never be masqueraded as a 200 verdict. (Route invariant: the
+ # route maps the returned verdict and lets a raised fault propagate.)
+ mocker.patch.object(ApiRunner, "validate_verdict", new=mocker.AsyncMock(side_effect=PipelexConfigError("host wiring fault")))
+ client = _build_client()
+ response = client.post("/v1/validate", json={"mthds_contents": [VALID_MTHDS]})
+
+ assert response.status_code >= 500, response.text
+ assert response.headers["content-type"].startswith("application/problem+json")
+ # Not a verdict body: the discriminated-union arms always carry `is_valid`; a no-verdict
+ # problem document does not.
+ assert "is_valid" not in response.json()
+
+ def test_valid_bundle_threads_source_onto_blueprint(self):
+ client = _build_client()
+ response = client.post(
+ "/v1/validate",
+ json={"mthds_contents": [VALID_MTHDS], "mthds_sources": ["api://smoke.mthds"]},
+ )
+
+ assert response.status_code == 200, response.text
+ body = response.json()
+ assert body["is_valid"] is True
+ # Valid arm threads the same name, so a client can correlate the report's primary blueprint to
+ # its file exactly as it would a failure's `validation_errors[].source`.
+ assert body["bundle_blueprint"]["source"] == "api://smoke.mthds"
+
+ def test_length_mismatch_is_a_request_error(self):
+ client = _build_client()
+ response = client.post(
+ "/v1/validate",
+ json={"mthds_contents": [VALID_MTHDS], "mthds_sources": ["a.mthds", "b.mthds"]},
+ )
+
+ # Caught at request validation as a 422 — never reaches the runtime (which would 500 on the
+ # mismatch). The validator message rides the problem `detail`. This is a no-verdict
+ # request-shape condition, NOT a content verdict.
+ assert response.status_code == 422, response.text
+ assert response.headers["content-type"].startswith("application/problem+json")
+ assert "mthds_sources" in response.text
diff --git a/api/tests/unit/test_validate_graph_target.py b/api/tests/unit/test_validate_graph_target.py
new file mode 100644
index 000000000..2db29b62e
--- /dev/null
+++ b/api/tests/unit/test_validate_graph_target.py
@@ -0,0 +1,173 @@
+"""The /validate graph is drawn from the pipe a selector-less run of the request would execute.
+
+The runtime's graph arm defaults to the primary blueprint's `main_pipe`, which is manifest-blind:
+a fetched package whose `METHODS.toml` names the entry pipe would be graphed from another pipe, or
+not at all when its bundles declare no `main_pipe` of their own. The route hands the runtime the
+manifest's `main_pipe` as the graph target, so `graph_spec` and `default_pipe_ref` name the same
+pipe. These tests read the target twice: off the graph the real in-process validator draws, and
+off the call a dispatched validator receives.
+"""
+
+from collections.abc import Callable, Sequence
+from pathlib import Path
+from typing import Any
+
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+from pipelex.base_exceptions import ErrorReport, ValidationErrorCategory, ValidationErrorItem
+from pipelex.plugins.bundle_validator_registry import BundleValidatorRegistry
+from pipelex.system.caller_identity import CallerIdentity
+from pytest_mock import MockerFixture
+
+from pipelex_api.api_config import ApiConfig
+from pipelex_api.exception_handlers import register_exception_handlers
+from pipelex_api.routes import router as api_router
+from tests.unit._constants import (
+ NO_MAIN_PIPE_MTHDS,
+ SECOND_MAIN_PIPE_MTHDS,
+ STUB_METHOD_ADDRESS,
+ STUB_METHOD_MANIFEST_MAIN_PIPE_SHOUT,
+ STUB_METHOD_MANIFEST_NO_MAIN_PIPE,
+ STUB_METHOD_MANIFEST_NOMAIN_ENTRY,
+ VALID_MTHDS,
+)
+
+_PIPELINE_NS = "pipelex_api.routes.pipelex.pipeline"
+_MODE = "temporal"
+_METHOD_REF = f"{STUB_METHOD_ADDRESS}@v0.1.0"
+
+
+class _RecordingBundleValidator:
+ """Records the graph target of every validation dispatched to it, then answers an invalid verdict."""
+
+ def __init__(self) -> None:
+ self.graph_pipe_codes: list[str | None] = []
+
+ async def validate_bundles(
+ self,
+ *,
+ mthds_contents: list[str], # noqa: ARG002
+ mthds_sources: list[str] | None, # noqa: ARG002
+ allow_signatures: bool, # noqa: ARG002
+ library_dirs: Sequence[Path] | None, # noqa: ARG002
+ caller_identity: CallerIdentity | None, # noqa: ARG002
+ graph_pipe_code: str | None,
+ ) -> ErrorReport:
+ self.graph_pipe_codes.append(graph_pipe_code)
+ return ErrorReport(
+ error_type="ValidateBundleError",
+ message="bundle is invalid",
+ title="Validate bundle error",
+ type_uri="https://errors.pipelex.com/validate-bundle-error/",
+ validation_errors=[ValidationErrorItem(category=ValidationErrorCategory.BLUEPRINT_VALIDATION, message="bad ref")],
+ )
+
+
+def _build_client() -> TestClient:
+ app = FastAPI()
+ app.include_router(api_router, prefix="/v1")
+ register_exception_handlers(app)
+ return TestClient(app)
+
+
+def _register_recording_validator(mocker: MockerFixture) -> _RecordingBundleValidator:
+ config = ApiConfig(orchestration_mode=_MODE, allow_request_orchestration_mode_override=False)
+ mocker.patch(f"{_PIPELINE_NS}.get_api_config", return_value=config)
+ validator = _RecordingBundleValidator()
+ mocker.patch(f"{_PIPELINE_NS}.get_bundle_validator_registry", return_value=BundleValidatorRegistry({_MODE: validator}))
+ return validator
+
+
+def _graphed_pipe_ref(body: dict[str, Any]) -> str:
+ """The qualified ref of the pipe the valid arm's `graph_spec` was drawn from."""
+ pipeline_ref: dict[str, str] = body["graph_spec"]["pipeline_ref"]
+ return f"{pipeline_ref['domain']}.{pipeline_ref['main_pipe']}"
+
+
+class TestValidateGraphTarget:
+ def test_a_package_whose_manifest_alone_names_the_entry_pipe_is_graphed(self, install_method_package: Callable[..., Path]) -> None:
+ # The bundle declares no `main_pipe`, so the runtime's default target is nothing and the
+ # graph used to be null although `default_pipe_ref` named the manifest's pipe.
+ install_method_package(files={"documents.mthds": NO_MAIN_PIPE_MTHDS}, manifest_toml=STUB_METHOD_MANIFEST_NOMAIN_ENTRY)
+ client = _build_client()
+
+ response = client.post("/v1/validate", json={"method_ref": _METHOD_REF})
+
+ assert response.status_code == 200, response.text
+ body = response.json()
+ assert body["is_valid"] is True
+ assert body["bundle_blueprint"]["main_pipe"] is None
+ assert body["default_pipe_ref"] == "nomain.echo"
+ assert _graphed_pipe_ref(body) == "nomain.echo"
+
+ def test_the_manifests_entry_pipe_is_graphed_over_the_closures(self, install_method_package: Callable[..., Path]) -> None:
+ # The manifest names `shout`; the primary blueprint (`a_smoke.mthds`, read first) declares
+ # `echo`. A run by this address executes `other.shout`, so that is the pipe to draw.
+ install_method_package(
+ files={"a_smoke.mthds": VALID_MTHDS, "b_other.mthds": SECOND_MAIN_PIPE_MTHDS},
+ manifest_toml=STUB_METHOD_MANIFEST_MAIN_PIPE_SHOUT,
+ )
+ client = _build_client()
+
+ response = client.post("/v1/validate", json={"method_ref": _METHOD_REF})
+
+ assert response.status_code == 200, response.text
+ body = response.json()
+ assert body["bundle_blueprint"]["main_pipe"] == "echo"
+ assert body["default_pipe_ref"] == "other.shout"
+ assert _graphed_pipe_ref(body) == "other.shout"
+
+ def test_a_manifest_without_main_pipe_graphs_the_closures_declaration(self, install_method_package: Callable[..., Path]) -> None:
+ install_method_package(files={"documents.mthds": VALID_MTHDS}, manifest_toml=STUB_METHOD_MANIFEST_NO_MAIN_PIPE)
+ client = _build_client()
+
+ response = client.post("/v1/validate", json={"method_ref": _METHOD_REF})
+
+ assert response.status_code == 200, response.text
+ assert _graphed_pipe_ref(response.json()) == "smoke.echo"
+
+ def test_a_manifest_naming_a_pipe_the_closure_lacks_gets_no_graph(self, install_method_package: Callable[..., Path]) -> None:
+ # The manifest names `shout`; the closure holds only `smoke.echo`. No run by this address
+ # executes `echo`, so drawing it would disagree with `default_pipe_ref`; the unresolved
+ # target degrades the graph and leaves the verdict valid.
+ install_method_package(files={"smoke.mthds": VALID_MTHDS}, manifest_toml=STUB_METHOD_MANIFEST_MAIN_PIPE_SHOUT)
+ client = _build_client()
+
+ response = client.post("/v1/validate", json={"method_ref": _METHOD_REF})
+
+ assert response.status_code == 200, response.text
+ body = response.json()
+ assert body["is_valid"] is True
+ assert body["default_pipe_ref"] is None
+ assert body["graph_spec"] is None
+
+ def test_inline_contents_graph_the_closures_declaration(self) -> None:
+ client = _build_client()
+
+ response = client.post("/v1/validate", json={"mthds_contents": [VALID_MTHDS]})
+
+ assert response.status_code == 200, response.text
+ assert _graphed_pipe_ref(response.json()) == "smoke.echo"
+
+ def test_the_dispatched_validator_receives_the_manifests_bare_code(
+ self, mocker: MockerFixture, install_method_package: Callable[..., Path]
+ ) -> None:
+ # A worker-dispatched validator draws its graph on the worker, so the target must travel
+ # through the seam; it is the manifest's bare code, resolved there as a run resolves it.
+ install_method_package(files={"documents.mthds": NO_MAIN_PIPE_MTHDS}, manifest_toml=STUB_METHOD_MANIFEST_NOMAIN_ENTRY)
+ validator = _register_recording_validator(mocker)
+ client = _build_client()
+
+ response = client.post("/v1/validate", json={"method_ref": _METHOD_REF})
+
+ assert response.status_code == 200, response.text
+ assert validator.graph_pipe_codes == ["echo"]
+
+ def test_the_dispatched_validator_keeps_its_default_target_for_inline_contents(self, mocker: MockerFixture) -> None:
+ validator = _register_recording_validator(mocker)
+ client = _build_client()
+
+ response = client.post("/v1/validate", json={"mthds_contents": [VALID_MTHDS]})
+
+ assert response.status_code == 200, response.text
+ assert validator.graph_pipe_codes == [None]
diff --git a/api/tests/unit/test_validate_render.py b/api/tests/unit/test_validate_render.py
new file mode 100644
index 000000000..41886defd
--- /dev/null
+++ b/api/tests/unit/test_validate_render.py
@@ -0,0 +1,80 @@
+"""`/validate` opt-in `rendered_markdown` extra (D-D) — a Pipelex-API presentation layer.
+
+The neutral 200 verdict body is unchanged by default; when the request's `render` includes the
+supported `markdown` token, the response gains a `rendered_markdown` field on BOTH 200 arms (valid
+and invalid). An unknown/unsupported token is silently ignored (lenient-ignore, NOT a 422) because
+`render` is a presentation hint, not part of the verdict contract. The markdown is rendered
+server-side by the shared pipelex renderers (`format_validate_markdown` / `render_invalid_validation_markdown`),
+so the API and the local CLI cannot drift in format/structure.
+"""
+
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+from pipelex_api.exception_handlers import register_exception_handlers
+from pipelex_api.routes import router as api_router
+from tests.unit._constants import INVALID_MAIN_PIPE_MTHDS, VALID_MTHDS
+
+
+def _build_client() -> TestClient:
+ app = FastAPI()
+ app.include_router(api_router, prefix="/v1")
+ register_exception_handlers(app)
+ return TestClient(app)
+
+
+class TestValidateRenderedMarkdown:
+ def test_default_request_has_no_rendered_markdown(self):
+ # Off by default: the response is the plain structured verdict, byte-parity with today.
+ client = _build_client()
+ response = client.post("/v1/validate", json={"mthds_contents": [VALID_MTHDS]})
+ assert response.status_code == 200, response.text
+ body = response.json()
+ assert body["is_valid"] is True
+ assert "rendered_markdown" not in body
+
+ def test_markdown_requested_valid_arm_carries_rendered_markdown(self):
+ client = _build_client()
+ response = client.post("/v1/validate", json={"mthds_contents": [VALID_MTHDS], "render": ["markdown"]})
+ assert response.status_code == 200, response.text
+ body = response.json()
+ assert body["is_valid"] is True
+ assert body["rendered_markdown"].startswith("# Validation passed")
+ # The view rides alongside the structured fields, which remain the contract.
+ assert "validated_pipes" in body
+
+ def test_markdown_requested_invalid_arm_carries_rendered_markdown(self):
+ client = _build_client()
+ response = client.post("/v1/validate", json={"mthds_contents": [INVALID_MAIN_PIPE_MTHDS], "render": ["markdown"]})
+ assert response.status_code == 200, response.text
+ body = response.json()
+ assert body["is_valid"] is False
+ assert body["rendered_markdown"].startswith("# Validation failed")
+ # The structured verdict is still present; markdown is the view, not a replacement.
+ assert body["validation_errors"]
+
+ def test_invalid_arm_without_render_has_no_rendered_markdown(self):
+ client = _build_client()
+ response = client.post("/v1/validate", json={"mthds_contents": [INVALID_MAIN_PIPE_MTHDS]})
+ assert response.status_code == 200, response.text
+ body = response.json()
+ assert body["is_valid"] is False
+ assert "rendered_markdown" not in body
+
+ def test_unknown_render_token_is_ignored_not_422(self):
+ # Lenient-ignore: an unsupported token yields the 200 verdict with NO rendered field —
+ # the one place the request-shape-422 contract deliberately does not apply.
+ client = _build_client()
+ response = client.post("/v1/validate", json={"mthds_contents": [VALID_MTHDS], "render": ["bogus"]})
+ assert response.status_code == 200, response.text
+ body = response.json()
+ assert body["is_valid"] is True
+ assert "rendered_markdown" not in body
+
+ def test_mixed_known_and_unknown_tokens_render_the_known_one(self):
+ # Per-token resolution: a known token renders, the unknown one is dropped (not poisoning).
+ client = _build_client()
+ response = client.post("/v1/validate", json={"mthds_contents": [VALID_MTHDS], "render": ["markdown", "bogus"]})
+ assert response.status_code == 200, response.text
+ body = response.json()
+ assert body["rendered_markdown"].startswith("# Validation passed")
diff --git a/api/tests/unit/test_validate_views.py b/api/tests/unit/test_validate_views.py
new file mode 100644
index 000000000..fafe9605e
--- /dev/null
+++ b/api/tests/unit/test_validate_views.py
@@ -0,0 +1,165 @@
+"""`/validate` opt-in `input_form` structured view (D-D) — the `views` axis.
+
+The second opt-in axis beside `render`, with identical mechanics and a different product: `render`
+yields *rendered text* under a mechanical `rendered_<format>` key, a view attaches a *structured*
+artifact under a **same-named** top-level field. The canonical `PipelexValidationReport` always
+carries `input_form` (required there, so a backend that forgets to derive it fails loudly), which is
+exactly why the wire gate has to be an explicit pop rather than a serialization side effect: the
+field is a populated dict, not a `None` that `exclude_none` would drop.
+
+What is pinned here: absent by default on both 200 arms (so the high-frequency callers — hook
+pipelines, CI gates, agent loops — never pay for a form they discard); present on the valid arm when
+the token is requested, keyed exactly like `pipe_io_contracts`; never on the invalid arm, whose
+crate was never assembled; unknown tokens lenient-ignored rather than 422'd; and `views` / `render`
+resolving independently.
+"""
+
+from typing import Any
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+from pipelex_api.exception_handlers import register_exception_handlers
+from pipelex_api.routes import router as api_router
+from tests.unit._constants import INVALID_MAIN_PIPE_MTHDS, VALID_MTHDS
+
+
+def _build_client() -> TestClient:
+ app = FastAPI()
+ app.include_router(api_router, prefix="/v1")
+ register_exception_handlers(app)
+ return TestClient(app)
+
+
+class TestValidateInputFormView:
+ def test_default_request_has_no_input_form(self):
+ # Off by default: the valid arm stays byte-lean, carrying the structured contract only.
+ client = _build_client()
+ response = client.post("/v1/validate", json={"mthds_contents": [VALID_MTHDS]})
+ assert response.status_code == 200, response.text
+ body = response.json()
+ assert body["is_valid"] is True
+ assert "input_form" not in body, f"`input_form` must be absent by default, got keys: {sorted(body)}"
+ # The facts the view projects are still there — the view is opt-in, the contract is not.
+ assert "pipe_io_contracts" in body
+
+ def test_empty_views_list_has_no_input_form(self):
+ # An explicit empty list is the same as omitting the field — no view, no field.
+ client = _build_client()
+ response = client.post("/v1/validate", json={"mthds_contents": [VALID_MTHDS], "views": []})
+ assert response.status_code == 200, response.text
+ assert "input_form" not in response.json()
+
+ def test_input_form_requested_valid_arm_carries_the_view(self):
+ client = _build_client()
+ response = client.post("/v1/validate", json={"mthds_contents": [VALID_MTHDS], "views": ["input_form"]})
+ assert response.status_code == 200, response.text
+ body = response.json()
+ assert body["is_valid"] is True
+ input_form: dict[str, Any] = body["input_form"]
+ # Keyed exactly like `pipe_io_contracts` — the namespaced `pipe_ref`, same set.
+ assert set(input_form) == set(body["pipe_io_contracts"]), (
+ f"`input_form` must map the same pipe_ref keys as `pipe_io_contracts`, got {sorted(input_form)} vs {sorted(body['pipe_io_contracts'])}"
+ )
+ descriptor = input_form["smoke.echo"]
+ field_names = [field["name"] for field in descriptor["fields"]]
+ assert field_names == ["text"], f"The descriptor states the pipe's authored inputs, got {field_names}"
+
+ def test_duplicate_token_is_deduped_not_an_error(self):
+ # Resolved as a set: order-insensitive and deduped, so a repeated token is inert.
+ client = _build_client()
+ response = client.post("/v1/validate", json={"mthds_contents": [VALID_MTHDS], "views": ["input_form", "input_form"]})
+ assert response.status_code == 200, response.text
+ assert "input_form" in response.json()
+
+ def test_invalid_arm_without_views_has_no_input_form(self):
+ client = _build_client()
+ response = client.post("/v1/validate", json={"mthds_contents": [INVALID_MAIN_PIPE_MTHDS]})
+ assert response.status_code == 200, response.text
+ body = response.json()
+ assert body["is_valid"] is False
+ assert "input_form" not in body
+
+ def test_invalid_arm_never_carries_input_form_even_when_requested(self):
+ # The descriptor derives from a crate that does not exist when load/parse/wiring failed, so
+ # it follows `bundle_blueprint` / `pipe_io_contracts` / `graph_spec` into absence here.
+ client = _build_client()
+ response = client.post("/v1/validate", json={"mthds_contents": [INVALID_MAIN_PIPE_MTHDS], "views": ["input_form"]})
+ assert response.status_code == 200, response.text
+ body = response.json()
+ assert body["is_valid"] is False
+ assert "input_form" not in body, f"The invalid arm never carries `input_form`, got keys: {sorted(body)}"
+ assert body["validation_errors"]
+
+ def test_unknown_view_token_is_ignored_not_422(self):
+ # Lenient-ignore: a stale view token must never fail the call.
+ client = _build_client()
+ response = client.post("/v1/validate", json={"mthds_contents": [VALID_MTHDS], "views": ["bogus"]})
+ assert response.status_code == 200, response.text
+ body = response.json()
+ assert body["is_valid"] is True
+ assert "input_form" not in body
+
+ @pytest.mark.parametrize("views", [["bogus", "input_form"], ["input_form", "bogus"]], ids=["unknown_first", "known_first"])
+ def test_mixed_known_and_unknown_tokens_attach_the_known_one(self, views: list[str]):
+ # Per-token resolution: the known token attaches, the unknown one is dropped (not poisoning).
+ # Both orders, since the tokens resolve as a set — position must not decide the outcome.
+ client = _build_client()
+ response = client.post("/v1/validate", json={"mthds_contents": [VALID_MTHDS], "views": views})
+ assert response.status_code == 200, response.text
+ assert "input_form" in response.json()
+
+ def test_no_verdict_422_carries_no_input_form(self):
+ # No verdict, no view: a request-shape 422 is an RFC 7807 problem document, nothing else.
+ client = _build_client()
+ response = client.post(
+ "/v1/validate",
+ json={"mthds_contents": [VALID_MTHDS], "mthds_sources": ["a.mthds", "b.mthds"], "views": ["input_form"]},
+ )
+ assert response.status_code == 422, response.text
+ assert "input_form" not in response.json()
+
+
+class TestViewsAndRenderAreIndependent:
+ """The two opt-in lists resolve their own tokens against their own supported sets."""
+
+ def test_render_alone_does_not_attach_the_view(self):
+ client = _build_client()
+ response = client.post("/v1/validate", json={"mthds_contents": [VALID_MTHDS], "render": ["markdown"]})
+ assert response.status_code == 200, response.text
+ body = response.json()
+ assert body["rendered_markdown"].startswith("# Validation passed")
+ assert "input_form" not in body
+
+ def test_views_alone_does_not_render(self):
+ client = _build_client()
+ response = client.post("/v1/validate", json={"mthds_contents": [VALID_MTHDS], "views": ["input_form"]})
+ assert response.status_code == 200, response.text
+ body = response.json()
+ assert "input_form" in body
+ assert "rendered_markdown" not in body
+
+ def test_both_lists_populate_their_own_fields(self):
+ client = _build_client()
+ response = client.post(
+ "/v1/validate",
+ json={"mthds_contents": [VALID_MTHDS], "render": ["markdown"], "views": ["input_form"]},
+ )
+ assert response.status_code == 200, response.text
+ body = response.json()
+ assert body["rendered_markdown"].startswith("# Validation passed")
+ assert "input_form" in body
+
+ def test_tokens_do_not_cross_axes(self):
+ # `input_form` is not a render format and `markdown` is not a view: each is unknown to the
+ # other list, and an unknown token is dropped rather than 422'd.
+ client = _build_client()
+ response = client.post(
+ "/v1/validate",
+ json={"mthds_contents": [VALID_MTHDS], "render": ["input_form"], "views": ["markdown"]},
+ )
+ assert response.status_code == 200, response.text
+ body = response.json()
+ assert "rendered_markdown" not in body
+ assert "input_form" not in body
diff --git a/api/tests/unit/test_webhook_recovery.py b/api/tests/unit/test_webhook_recovery.py
new file mode 100644
index 000000000..6fd5984c7
--- /dev/null
+++ b/api/tests/unit/test_webhook_recovery.py
@@ -0,0 +1,193 @@
+"""Cross-path consistency regression for the API's two error surfaces.
+
+The API surfaces a pipelex `ErrorReport` to clients along two paths:
+
+1. The **synchronous HTTP path** — `POST /execute` (and every other
+ route that propagates a `PipelexError`) renders the report via
+ `build_problem_document(...)` → RFC 7807 `application/problem+json`.
+2. The **asynchronous webhook path** — `POST /start` schedules a
+ Temporal workflow; on completion (success or `FAILED`), pipelex's
+ `DeliveryExecutor._notify_webhook(...)` posts a JSON payload to the
+ caller's callback URL. On `FAILED`, the payload carries
+ `error: <ErrorReport.to_dict(disclosure_mode=VERBOSE)>` — a flat dict, not
+ an RFC 7807 envelope (the receiver chooses how to render it).
+
+This module pins the **T6 cross-path consistency** invariant: given the same
+source `ErrorReport`, both renderings must surface the same classification
+fields. A client that branches on `error_type` / `error_domain` /
+`retryable` / `user_action` must not get one classification synchronously
+and a different one over the webhook.
+
+The webhook payload itself is composed entirely upstream in
+`pipelex.pipe_run.delivery_executor`; the API never touches the bytes that
+go over the wire. So this test exercises the two rendering helpers directly
+and asserts the classification overlap is exact. Drift here would imply
+either pipelex's `to_dict` / `to_problem_document` diverged in their field
+selection, or the API's `build_problem_document` wrapper started shaping
+the document.
+"""
+
+from typing import Any
+
+import pytest
+from pipelex.base_exceptions import DisclosureMode, ErrorDomain, ErrorReport
+from pipelex.cogt.inference.error_classification import ProviderErrorMetadata, UserAction, UserActionKind
+from pipelex.cogt.inference.provider_name import ProviderName
+
+from pipelex_api.problem_document import build_problem_document
+
+# Classification fields that, when populated on the source `ErrorReport`,
+# must appear with identical values in both renderings. Excluded from this
+# list are: (a) `message` — present in both but under different keys
+# (`message` in `to_dict`, `detail` in `to_problem_document`); checked
+# separately. (b) the RFC 7807 standard slots `type`/`title`/`status` and
+# the request-scoped extension members `instance`/`request_id` — those are
+# rightfully envelope-only.
+_CLASSIFICATION_FIELDS_PRESERVED = (
+ "error_type",
+ "error_domain",
+ "error_category",
+ "retryable",
+ "user_action",
+ "model",
+ "provider",
+ "provider_metadata",
+)
+
+
+def _fully_populated_llm_report() -> ErrorReport:
+ """A provider-429 report exercising every classification field at once.
+
+ Provider/model/provider_metadata ride on `RUNTIME`-domain inference
+ failures, so an `LLMCompletionError` stand-in is the broadest single
+ fixture: it pins the parity contract on the maximum field set the API
+ ever surfaces.
+ """
+ return ErrorReport(
+ error_type="LLMCompletionError",
+ message="OpenAI returned 429 (rate_limit_exceeded)",
+ title="LLM completion error",
+ type_uri="https://docs.pipelex.com/latest/errors/llm-completion-error/",
+ error_domain=ErrorDomain.RUNTIME,
+ error_category="rate_limit",
+ retryable=True,
+ user_action=UserAction(
+ kind=UserActionKind.WAIT_AND_RETRY,
+ detail="The provider is rate-limiting your account. Retry after the indicated delay.",
+ ),
+ model="gpt-4o-mini",
+ provider="openai",
+ provider_metadata=ProviderErrorMetadata(
+ provider=ProviderName.OPENAI,
+ sdk_exception_type="RateLimitError",
+ status_code=429,
+ retry_after_seconds=12.0,
+ request_id="req_provider_abc",
+ ),
+ )
+
+
+def _caller_facing_input_report() -> ErrorReport:
+ """A caller-facing INPUT-domain report (the other half of the STRICT contract).
+
+ Complements the LLM fixture: minimal classification but
+ `caller_facing_message=True`, which is the trigger STRICT projection
+ keys its `message` passthrough on. Used here to verify that the parity
+ contract holds across both message-disclosure provenances.
+ """
+ return ErrorReport(
+ error_type="MthdsParserError",
+ message="Your .mthds file has a syntax error on line 4",
+ title="Pipelex interpreter error",
+ type_uri="https://docs.pipelex.com/latest/errors/pipelex-interpreter-error/",
+ error_domain=ErrorDomain.INPUT,
+ retryable=False,
+ caller_facing_message=True,
+ )
+
+
+class TestWebhookRecoveryCrossPath:
+ @pytest.mark.parametrize(
+ ("label", "report_factory"),
+ [
+ ("llm_provider_429", _fully_populated_llm_report),
+ ("caller_facing_input", _caller_facing_input_report),
+ ],
+ )
+ def test_classification_fields_match_between_sync_and_webhook(self, label: str, report_factory: Any) -> None:
+ """T6 regression: webhook `error` and sync RFC 7807 body must agree.
+
+ For every classification field that pipelex populates on the source
+ report, the value in `ErrorReport.to_dict(VERBOSE)` (what the webhook
+ carries under `error`) must be byte-identical to the value rendered
+ in the RFC 7807 problem document (what the sync handler returns).
+ """
+ report = report_factory()
+ webhook_payload = report.to_dict(disclosure_mode=DisclosureMode.VERBOSE)
+ problem_doc = build_problem_document(
+ report,
+ instance="/v1/execute",
+ request_id="REQ_T6",
+ disclosure_mode=DisclosureMode.VERBOSE,
+ )
+
+ for field in _CLASSIFICATION_FIELDS_PRESERVED:
+ in_webhook = field in webhook_payload
+ in_problem = field in problem_doc
+ assert in_webhook == in_problem, f"{label}: field `{field}` presence mismatch (webhook={in_webhook}, problem={in_problem})"
+ if in_webhook:
+ assert webhook_payload[field] == problem_doc[field], f"{label}: field `{field}` value drift between paths"
+
+ # `message` rides under different keys by design — pin the bridge.
+ assert problem_doc["detail"] == webhook_payload["message"], (
+ f"{label}: sync `detail` and webhook `message` must carry identical text under VERBOSE"
+ )
+
+ def test_sync_only_envelope_members_are_isolated_to_problem_document(self) -> None:
+ """The RFC 7807 envelope is the sync path's contract, not the webhook's.
+
+ `type` / `status` / `detail` / `instance` / `request_id` are the
+ envelope-only members: pipelex's `to_problem_document` maps them from
+ report fields (`type_uri` → `type`, `http_status` → `status`,
+ `message` → `detail`) or sources them from the caller (`instance`,
+ `request_id`). They never appear on the raw `to_dict` output the
+ webhook carries — the webhook is the structured-data layer (per
+ Phase 4b decision); receivers that want an envelope render one
+ themselves. Pin the asymmetry so a refactor of either path doesn't
+ quietly leak envelope members into the webhook payload or strip them
+ from the sync body. (`title` and `type_uri` ARE direct fields on
+ `ErrorReport`, so they appear in both — not envelope-only.)
+ """
+ report = _fully_populated_llm_report()
+ webhook_payload = report.to_dict(disclosure_mode=DisclosureMode.VERBOSE)
+ problem_doc = build_problem_document(
+ report,
+ instance="/v1/execute",
+ request_id="REQ_T6",
+ disclosure_mode=DisclosureMode.VERBOSE,
+ )
+
+ for envelope_member in ("type", "status", "detail", "instance", "request_id"):
+ assert envelope_member in problem_doc, f"sync path must carry RFC 7807 envelope member `{envelope_member}`"
+ assert envelope_member not in webhook_payload, (
+ f"webhook payload must NOT carry RFC 7807 envelope member `{envelope_member}` (use `to_problem_document` if you need an envelope)"
+ )
+
+ def test_webhook_carries_raw_report_regardless_of_disclosure_mode(self) -> None:
+ """The webhook always renders the report VERBOSE, even when sync is STRICT.
+
+ The receiver decides what to re-expose downstream — pipelex hardcodes
+ `DisclosureMode.VERBOSE` in `_notify_webhook` for exactly this reason.
+ Pin it here so a future refactor that introduces a `disclosure_mode`
+ knob on the webhook path is caught by this test.
+ """
+ report = _fully_populated_llm_report()
+ verbose_payload = report.to_dict(disclosure_mode=DisclosureMode.VERBOSE)
+ strict_payload = report.to_dict(disclosure_mode=DisclosureMode.STRICT)
+
+ # The provider-identifying fields are the cheapest signal that the
+ # projection actually fired: VERBOSE keeps them, STRICT drops them.
+ assert verbose_payload.get("provider") == "openai"
+ assert verbose_payload.get("model") == "gpt-4o-mini"
+ assert "provider" not in strict_payload
+ assert "model" not in strict_payload
diff --git a/docs/contribute/api-server.md b/docs/contribute/api-server.md
new file mode 100644
index 000000000..ed18e81e5
--- /dev/null
+++ b/docs/contribute/api-server.md
@@ -0,0 +1,50 @@
+---
+title: "The API Server"
+description: "The Pipelex API server lives in this repository as the api/ workspace member: how it depends on the library, its environment, the gate that covers it, its vendored inference tree and its image."
+---
+
+# The API server
+
+The Pipelex API server, the FastAPI runner published as the `pipelex/pipelex-api` image, lives in this repository as the `api/` directory. It is the reference implementation of the MTHDS Protocol, and the base the hosted runner composes. Its own guide is `api/CLAUDE.md`, and its reference documentation is under `api/docs/`.
+
+## A workspace member
+
+The repository is a uv workspace. The root project is the `pipelex` library, untouched, and `api/` is a second member, the `pipelex-api` distribution, whose import package is `pipelex_api`. The root `pyproject.toml` declares it:
+
+```toml
+[tool.uv.workspace]
+members = ["api"]
+```
+
+The member depends on the library through the workspace (`pipelex = { workspace = true }` in its `[tool.uv.sources]`), so the server always runs the library of the same commit, and the repository keeps a single `uv.lock` at its root. The `pipelex` wheel and sdist are unaffected: both restrict themselves to `packages = ["pipelex"]`.
+
+The two are released together, under one version number. The member declares its version dynamic and hatch reads it from the root `pyproject.toml` (`[tool.hatch.version]` in `api/pyproject.toml`), so a release bumps one file, and the member's `[tool.uv] cache-keys` name the root file so that uv notices the bump. Its dependency on `pipelex` names no version, because uv ignores a version specifier on a workspace source and a pin there would only go stale.
+
+## Its own environment
+
+The server is tested with exactly the dependencies it declares, which are not the library's development set: pipelex with the server's extras and without `cli`, plus FastAPI, uvicorn and the server's own tools. Its Makefile therefore points every uv command at `api/.venv` (`UV_PROJECT_ENVIRONMENT`), where pipelex is an editable install of this repository's source, so a library edit reaches the server without a reinstall. The targets that need that environment provision it themselves.
+
+## The gate covers it
+
+The root `make agent-check` ends with `make api-agent-check`, which runs `make -C api agent-check`: the member's install, ruff, pyright and mypy under its own configuration, then two drift checks. The root `make agent-test` ends with `make api-agent-test`, the server's unit tests. A library change that breaks the server therefore fails the gate in the change that makes it, and so does one that moves the server's wire or its inference tree. pipelex's pull-request workflows run the library's checks only, so it is this gate, run before pushing, that catches them:
+
+- **`make -C api openapi-check`** compares the committed OpenAPI artifact, `api/docs/openapi/pipelex-api.openapi.yaml`, with what the app generates. pipelex's own models ride the server's wire (the run result, the bundle blueprint, the validation error vocabulary), so a library change can move the artifact with no change to the server's code. Regenerate it with `make -C api openapi-export` and read the diff: it is what the change did to the server's callers.
+- **`make -C api kit-check`** compares the server's vendored inference tree with the kit.
+
+The root ruff configuration excludes `api/`, which the member's gate lints under its own. The root plxt configuration formats and lints the member's TOML and MTHDS files like any other, except its vendored inference tree, which the sync keeps byte-identical to the kit, and its deliberately invalid sample bundles.
+
+## The vendored inference tree
+
+The image serves the models its `/root/.pipelex/inference/` tree declares, which is `api/.pipelex/inference/`, and pipelex never falls back to the kit in its own package once a config directory exists. `api/scripts/sync_vendored_kit.py` keeps that tree in step with `pipelex/kit/configs/inference/`: the backend files, the routing profiles, the numbered deck files and the manifests are mirrored byte for byte, and only the `enabled` switches in `backends.toml` and the `x_custom_*` deck overrides are the server's own choice.
+
+`make up-kit-configs` (`ukc`), the step a kit change already takes, runs that sync after mirroring `.pipelex/` into the kit, so the server's tree moves in the same change. The tree stays committed rather than generated when the image is built, because `make run` and the server's tests read it, and because the sync can refuse a kit entry it has no rule for, which a person has to resolve before a release rather than during one.
+
+## The image
+
+The image is built with the repository root as its context, so it installs the pipelex of the same commit:
+
+```bash
+docker build -f api/Dockerfile .
+```
+
+`make -C api docker-build` runs exactly that. The root `.dockerignore` keeps the context down to the files the build reads. It is an allowlist, and it sits at the root rather than beside the Dockerfile because the legacy builder reads no other ignore file, and without one it would copy local override files, which can hold credentials, into the image.
diff --git a/docs/contribute/keyword-only-arguments.md b/docs/contribute/keyword-only-arguments.md
index 7994d642d..45dd1e7ff 100644
--- a/docs/contribute/keyword-only-arguments.md
+++ b/docs/contribute/keyword-only-arguments.md
@@ -116,7 +116,7 @@ A def is skipped when it is registered with a framework whose calling convention
- pytest fixtures — `fixture`, matched on the bare decorator name so both `@pytest.fixture` and bare `@fixture` (`from pytest import fixture`) are covered (the only src-side fixtures live in the shipped `pipelex/test_extras/shared_pytest_plugins.py` plugin module).
- Jinja2 filters/tests/globals — `pass_context`, `pass_environment`, `pass_eval_context`, matched on the bare decorator name (covers both `@pass_context` from `from jinja2 import pass_context` and the attributed `@jinja2.pass_context`). The Jinja2 engine invokes a filter POSITIONALLY from template syntax — `{{ value | tag("name") }}` calls `tag(context, value, "name")` — so the wrapped callable's arguments cannot be made keyword-only. This is the same framework-entrypoint category as Typer/pytest. A multi-argument filter without one of these decorators (rare) is covered by the `# kw-only: ignore` escape hatch; single-argument filters (`escape_script_tag(value)`) have an ordinary lone subject and take a grant like any other def.
-FastAPI is intentionally absent: there are no route handlers in `pipelex/` source — the FastAPI server lives in the separate `pipelex-api/` repo.
+FastAPI is intentionally absent: there are no route handlers in `pipelex/` source — the FastAPI server lives in the `api/` workspace member, outside `pipelex/` and outside this convention's scope (see [The API Server](api-server.md)).
Known coverage gap (documented, not silently ignored): some Typer commands are registered by call-style `app.command(name=...)(some_fn)` against functions defined in separate modules that carry NO decorator, so a decorator-keyed guard cannot see them via the framework carve-out. These target functions consistently type their parameters as `Annotated[T, typer.Argument(...)]` / `Annotated[T, typer.Option(...)]`. The guard treats a def as a framework entrypoint when any of its parameters carry `Argument`/`Option` metadata in their `Annotated[...]` annotation — matched on the trailing callee name, so both the qualified `typer.Option(...)` form and the bare `Option(...)` form (`from typer import Option`) are recognized — which closes the gap without resorting to a broad path-based exclusion of CLI modules.
diff --git a/docs/under-the-hood/codegen-projections.md b/docs/under-the-hood/codegen-projections.md
index b962a0c9c..f0f67bb43 100644
--- a/docs/under-the-hood/codegen-projections.md
+++ b/docs/under-the-hood/codegen-projections.md
@@ -167,7 +167,7 @@ The remaining findings are artifacts of *how* you lint, not of file content. Non
## Serving the engine over HTTP
-The same engine backs the `pipelex-api` routes (`POST /v1/resolve`, `POST /v1/codegen`, and the re-pointed `/v1/build/*` — the route envelopes are documented in `pipelex-api`'s `docs/codegen.md`). Two host-facing cores make that possible without any CLI plumbing:
+The same engine backs the `pipelex-api` routes (`POST /v1/resolve`, `POST /v1/codegen`, and the re-pointed `/v1/build/*` — the route envelopes are documented in the server's `api/docs/codegen.md`). Two host-facing cores make that possible without any CLI plumbing:
- **`pipelex.pipeline.resolve_bundle.resolve_crate_from_contents`** resolves **in-memory** MTHDS contents (strings, with optional per-content sources) into the normalized crate. It mirrors `validate_bundle`'s in-memory arm — the same `translate_to_validate_bundle_error` cascade, so an invalid library raises the one shared `ValidateBundleError` and a resolve verdict cannot drift from a validate verdict — and the same **loaded-on-success contract**: the library is left loaded and current for the host to read live pipes from, and the host owns its teardown. Resolution is static (no dry-run sweep), matching `pipelex resolve`.
- **`build_stamped_projection`** (above) gives the host the stamped artifact set plus the lock as pure content. A client that writes the served files and lock verbatim reproduces a local run byte-for-byte — the offline `codegen check` passes on the written tree exactly as it would locally. There is deliberately no server-side check route: the check is offline by design.
diff --git a/docs/under-the-hood/error-model.md b/docs/under-the-hood/error-model.md
index bf2a70862..9940d22ae 100644
--- a/docs/under-the-hood/error-model.md
+++ b/docs/under-the-hood/error-model.md
@@ -141,7 +141,7 @@ The **fix planner** (`pipelex/pipeline/fixes/planner.py`) translates enriched ty
Applying fixes is the runtime's job too: the **applier** (`pipelex/pipeline/fixes/applier.py`) mutates a tomlkit DOM in place per op (guarded — an op whose target table is absent is skipped and reported, never raised) and then reflows the whole file to canonical MTHDS style, and the **convergence loop** (`pipelex/pipeline/fixes/fix_loop.py`) runs validate → apply SAFE fixes → re-validate to a fixed point, reporting non-convergence loudly. The user-facing surface is [`pipelex fix bundle`](../tools/cli/fix.md).
-On the hosted API the same payload rides the wire verbatim as `validation_errors[].suggested_fix`; how it appears in HTTP error responses is documented on the API side, in `pipelex-api`'s `docs/error-responses.md` → "Suggested fixes".
+On the hosted API the same payload rides the wire verbatim as `validation_errors[].suggested_fix`; how it appears in HTTP error responses is documented on the API side, in the server's `api/docs/error-responses.md` → "Suggested fixes".
---
diff --git a/mkdocs.yml b/mkdocs.yml
index d610575c6..442d46857 100644
--- a/mkdocs.yml
+++ b/mkdocs.yml
@@ -372,6 +372,7 @@ plugins:
- contribute/trace-input-semantics.md: "Tracing Input Semantics"
- contribute/generate-projection-corpus.md: "Projection Fixture Corpus"
- contribute/typescript-emission-gates.md: "TypeScript Emission Gates"
+ - contribute/api-server.md: "The API Server"
- migration-ledger.md: "Migration Ledger"
- changelog.md: "Changelog"
@@ -611,6 +612,7 @@ nav:
- Tracing Input Semantics: contribute/trace-input-semantics.md
- Projection Fixture Corpus: contribute/generate-projection-corpus.md
- TypeScript Emission Gates: contribute/typescript-emission-gates.md
+ - The API Server: contribute/api-server.md
- Migration Ledger: migration-ledger.md
- Code of Conduct: CODE_OF_CONDUCT.md
- License: license.md
diff --git a/pipelex/kit/agent_rules/codex_commands.md b/pipelex/kit/agent_rules/codex_commands.md
index bea72f961..5e1696ef3 100644
--- a/pipelex/kit/agent_rules/codex_commands.md
+++ b/pipelex/kit/agent_rules/codex_commands.md
@@ -7,7 +7,7 @@
```bash
make agent-check
# If the current system doesn't have the `make` command,
- # lookup the "agent-check" target in the Makefile and run the commands one by one (targets fix-unused-imports fix-keyword-only format lint pyright mypy check-ledger check-keyword-only check-hub-layering check-rich-imports drift-check)
+ # lookup the "agent-check" target in the Makefile and run the commands one by one (targets fix-unused-imports fix-keyword-only format lint pyright mypy check-ledger check-keyword-only check-hub-layering check-rich-imports drift-check api-agent-check)
```
This runs multiple code quality tools:
@@ -17,6 +17,7 @@
- plxt: Format and lint TOML, MTHDS, and PLX files
- Migration ledgers: every checked-in ledger must be legal and replay harmlessly over its reference documents (`make check-ledger`, alias `cl`)
- Drift contracts: open code↔docs review obligations fail the gate (note the digest reads the git index, so stage your changes for the check to see them)
+ - The Pipelex API server's own gate (`make -C api agent-check`): the server lives in `api/` as a uv workspace member with its own environment, and its checks include the drift of its OpenAPI artifact and of its vendored inference tree
Always fix any issues reported by these tools before proceeding.
diff --git a/pipelex/kit/agent_rules/commands.md b/pipelex/kit/agent_rules/commands.md
index 5120f3bb7..6b4fb6c01 100644
--- a/pipelex/kit/agent_rules/commands.md
+++ b/pipelex/kit/agent_rules/commands.md
@@ -2,10 +2,11 @@
`make` targets activate the virtual environment themselves; anything else (`pytest`, `pipelex`, `pipelex-dev`) runs from `.venv/bin/` (`.venv\Scripts\` on Windows), never bare. The Makefile is the reference for every target and alias; without `make`, read the target there and run its prerequisites one by one.
-- **`make agent-check` after every code change, and fix everything it reports.** Its prerequisites are `fix-unused-imports fix-keyword-only format lint pyright mypy check-ledger check-keyword-only check-hub-layering check-rich-imports drift-check`: the import and keyword-only fixers, ruff, pyright, mypy, `plxt` over TOML/MTHDS/PLX, the migration-ledger replay (`cl`), the hub-layering check, the Rich import check (`cri`: Rich is the `cli` extra, so no module outside `pipelex/cli/` imports it at module level or reaches it through a CLI module) and the drift contracts. The drift digest reads the git index, so stage your changes before the check.
+- **`make agent-check` after every code change, and fix everything it reports.** Its prerequisites are `fix-unused-imports fix-keyword-only format lint pyright mypy check-ledger check-keyword-only check-hub-layering check-rich-imports drift-check api-agent-check`: the import and keyword-only fixers, ruff, pyright, mypy, `plxt` over TOML/MTHDS/PLX, the migration-ledger replay (`cl`), the hub-layering check, the Rich import check (`cri`: Rich is the `cli` extra, so no module outside `pipelex/cli/` imports it at module level or reaches it through a CLI module), the drift contracts, and the server's own gate. The drift digest reads the git index, so stage your changes before the check.
+- **The Pipelex API server is the `api/` workspace member** (the `pipelex-api` distribution, package `pipelex_api`; its guide is `api/CLAUDE.md`). It runs the pipelex of the same commit from its own environment, `api/.venv`, which its targets provision themselves. `make agent-check` ends with `api-agent-check` (`make -C api agent-check`: its install, ruff, pyright, mypy, and the drift checks of its OpenAPI artifact and of its vendored inference tree) and `make agent-test` with `api-agent-test`, so a library change that breaks the server, moves its wire or leaves its inference tree behind fails in the same change. A kit change reaches the server's tree through `make up-kit-configs` (`ukc`); a change to the server's wire is committed with `make -C api openapi-export`.
- **Keyword-only arguments** (the convention is in the standards and in `docs/contribute/keyword-only-arguments.md`): `make check-keyword-only` (`cko`) is the gate, `make fix-keyword-only` (`fko`) inserts the bare `*` where it can — on ungranted subjects too — and reports the shapes it cannot fix, and `make subject-grant FUNC="<path>::<qualname>" RATIONALE="…"` (`sgr`) grants a positional subject. Grant before `make agent-check`, which runs the fixer.
- **Drift contracts.** When `make drift-check` reports an open contract: `make drift-plan`, review and fix the stale targets, `git add` the trigger files, then `make drift-ack CONTRACT=<id> RATIONALE="<verdict>: …"`, the rationale opening with its verdict, `real-catch`, `clean-pass` or `friction`. No bypass flag; "clean-pass: reviewed, no doc change needed" is a legitimate rationale. See `docs/contribute/drift-contracts.md` and the `/drift-review` skill.
-- **`make agent-test` at the end of every coding session.** Heartbeat lines while running, full output only on failure. If it hangs or fails opaquely, `make agent-test-debug` (`atd`) adds stale-process cleanup, an outer timeout and a live log; the methodology is `docs/agents/debugging-hanging-pytest-runs.md`. At intermediate steps in a local setup, running only the relevant tests is fine: `.venv/bin/pytest -x -q tests/unit/path/to/test_module.py`, or `make t TEST=<name>` (pytest `-k` substring matching; `TEST=LF` reruns the last failures). `make tp` / `make test-with-prints` are for a human at a terminal; an agent in the cloud or in a sandbox uses `make agent-test` only.
+- **`make agent-test` at the end of every coding session.** Heartbeat lines while running, full output only on failure; the server's unit tests run after the library's. If it hangs or fails opaquely, `make agent-test-debug` (`atd`) adds stale-process cleanup, an outer timeout and a live log; the methodology is `docs/agents/debugging-hanging-pytest-runs.md`. At intermediate steps in a local setup, running only the relevant tests is fine: `.venv/bin/pytest -x -q tests/unit/path/to/test_module.py`, or `make t TEST=<name>` (pytest `-k` substring matching; `TEST=LF` reruns the last failures). `make tp` / `make test-with-prints` are for a human at a terminal; an agent in the cloud or in a sandbox uses `make agent-test` only.
- **`make test-ts-gates` (`ttg`) after touching anything under `pipelex/codegen/emitters/`, or moving the pinned prettier version.** `make agent-test` does not cover the TypeScript emission: the two gates that read the emitted TypeScript as TypeScript need a node toolchain and skip silently without one. This target provisions a pinned prettier and zod into `.ts-toolchain/` (npm, node >= 22.6) and makes those gates fail instead of skip, as CI does. See `docs/contribute/typescript-emission-gates.md`.
- **`make cleanderived`** when linters or pytest collection get confused after files were erased or moved.
- **`CLAUDE.md` and `AGENTS.md` are generated.** Edit the sources in `pipelex/kit/agent_rules/` (assembled per `pipelex/kit/index.toml`) and run `make rules`; `make check-rules` is the CI gate, and `make agent-check` does not include it.
diff --git a/pyproject.toml b/pyproject.toml
index 221ff6f16..dd35ee9c1 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -336,6 +336,8 @@ exclude_lines = [
[tool.ruff]
exclude = [
+ # The `api/` workspace member runs ruff under its own configuration (`make -C api agent-check`).
+ "api",
".cursor",
".git",
".github",
@@ -520,6 +522,13 @@ banned-module-level-imports = ["rich"]
[tool.uv]
required-version = ">=0.7.2"
+# The Pipelex API server lives in `api/` as a second workspace member, the `pipelex-api` distribution.
+# It depends on this package through the workspace, so it always runs the library of the same commit,
+# and the repository keeps one `uv.lock`. Nothing of it reaches the `pipelex` wheel or sdist, which
+# the hatch targets below restrict to `packages = ["pipelex"]`. See `api/CLAUDE.md`.
+[tool.uv.workspace]
+members = ["api"]
+
[tool.hatch.build.targets.wheel]
packages = ["pipelex"]
diff --git a/uv.lock b/uv.lock
index 58443358f..cae5d407c 100644
--- a/uv.lock
+++ b/uv.lock
@@ -20,6 +20,12 @@ resolution-markers = [
"python_full_version < '3.12' and sys_platform != 'darwin' and sys_platform != 'emscripten' and sys_platform != 'win32'",
]
+[manifest]
+members = [
+ "pipelex",
+ "pipelex-api",
+]
+
[[package]]
name = "accelerate"
version = "1.13.0"
@@ -1160,6 +1166,22 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/06/ae/2f1ec97492ced94256acfc39040fe979cb6f96e2ba4602ac59b6fd548538/fal_client-1.0.0-py3-none-any.whl", hash = "sha256:0e8a611fde2363c15cd26de8eadfada72a6fdf5077211e95120d7c870a233b2b", size = 22632, upload-time = "2026-04-28T22:42:31.035Z" },
]
+[[package]]
+name = "fastapi"
+version = "0.136.3"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "annotated-doc" },
+ { name = "pydantic" },
+ { name = "starlette" },
+ { name = "typing-extensions" },
+ { name = "typing-inspection" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/81/2d/ff8d91d7b564d464629a0fd50a4489c97fcb836ac230bf3a7269232a9b1f/fastapi-0.136.3.tar.gz", hash = "sha256:e487fae93ad408e6f47641ee4dfe389864fd7bec92e547ea8498fc13f43e83ab", size = 396410, upload-time = "2026-05-23T18:53:15.192Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/e0/82/45359b62a067409bd929ae8a56b8ed13e5a8c8a61194b3c236920999ab83/fastapi-0.136.3-py3-none-any.whl", hash = "sha256:3d2a69bdf04b7e9f3afa292c3bc7a98816bbfafa10bc9b45f3f3700d2f761620", size = 117481, upload-time = "2026-05-23T18:53:16.924Z" },
+]
+
[[package]]
name = "filelock"
version = "3.29.0"
@@ -1659,6 +1681,19 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/7e/f5/f66802a942d491edb555dd61e3a9961140fd64c90bce1eafd741609d334d/httpcore-1.0.9-py3-none-any.whl", hash = "sha256:2d400746a40668fc9dec9810239072b40b4484b640a8c38fd654a024c7a1bf55", size = 78784, upload-time = "2025-04-24T22:06:20.566Z" },
]
+[[package]]
+name = "httpcore2"
+version = "2.13.1"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "h11" },
+ { name = "truststore" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/cb/f3/1db7aa2bc2524062192bb0e0323969492d1883152a232fe36eea65f4e35c/httpcore2-2.13.1.tar.gz", hash = "sha256:e0aa977abe17e69a3b820a24542a6fa88702676d83880b8d194dcd18408e5103", size = 68071, upload-time = "2026-09-23T07:47:22.372Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/09/ba/a4568248771ce81957bfb7cc600264a40fbcda092391ee1c415c50be4bea/httpcore2-2.13.1-py3-none-any.whl", hash = "sha256:e1e05d4f25f7d7d496bfb96748f6f4b67657b03da069b3a68c36069f3db73d0a", size = 83423, upload-time = "2026-09-23T07:47:19.365Z" },
+]
+
[[package]]
name = "httpx"
version = "0.28.1"
@@ -1683,6 +1718,32 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/d2/fd/6668e5aec43ab844de6fc74927e155a3b37bf40d7c3790e49fc0406b6578/httpx_sse-0.4.3-py3-none-any.whl", hash = "sha256:0ac1c9fe3c0afad2e0ebb25a934a59f4c7823b60792691f779fad2c5568830fc", size = 8960, upload-time = "2025-10-10T21:48:21.158Z" },
]
+[[package]]
+name = "httpx2"
+version = "2.13.1"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "anyio", marker = "sys_platform != 'emscripten'" },
+ { name = "httpcore2", marker = "sys_platform != 'emscripten'" },
+ { name = "httpx2-jsfetch", marker = "python_full_version >= '3.12' and sys_platform == 'emscripten'" },
+ { name = "idna" },
+ { name = "truststore", marker = "sys_platform != 'emscripten'" },
+ { name = "typing-extensions", marker = "python_full_version < '3.13'" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/d5/44/474bef2a0e9d90f1715d32cb98b0738695ca17ba324095fb2497ed7fbd59/httpx2-2.13.1.tar.gz", hash = "sha256:e48744a19e3af5ee48313d0ce5fe941d5422fae5705ea922a4aabf94d7800dfa", size = 100405, upload-time = "2026-09-23T07:47:23.052Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/d8/9c/6fe8931fd9f381042a9e4c7d5a7b4cbf7016b252bec0c99a49fce42c3326/httpx2-2.13.1-py3-none-any.whl", hash = "sha256:6dff50fabc270ee5fd25d845d0b078ed20564579744d6d962850975996d2f9a4", size = 95597, upload-time = "2026-09-23T07:47:20.995Z" },
+]
+
+[[package]]
+name = "httpx2-jsfetch"
+version = "1.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/cd/c4/0e5636363151a2a1795e0a77617168b9ca438e1748ec05fc9b5687f93d64/httpx2_jsfetch-1.0.tar.gz", hash = "sha256:70a0e3eabfef7cce5ad9c629f7d01ca05e418f586646f4ddf14782e4c1454c60", size = 6872, upload-time = "2026-08-07T00:13:07.492Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/9b/43/832f631d32e4f1211caa2ba368317739fe71f0b8530e4c9d15dc454bac2a/httpx2_jsfetch-1.0-py3-none-any.whl", hash = "sha256:cb916b707601e69a07721aabc8f3f6659be3a6893bc1ff5c6f9e02241df2da32", size = 6382, upload-time = "2026-08-07T00:13:06.567Z" },
+]
+
[[package]]
name = "huggingface-hub"
version = "1.16.1"
@@ -3382,6 +3443,18 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/cb/2b/f8434233fab2bd66a02ec014febe4e5adced20e2693e0e90a07d118ed30e/pandas-3.0.2-cp314-cp314t-win_arm64.whl", hash = "sha256:5371b72c2d4d415d08765f32d689217a43227484e81b2305b52076e328f6f482", size = 9455341, upload-time = "2026-03-31T06:48:28.418Z" },
]
+[[package]]
+name = "pandas-stubs"
+version = "3.0.5.260914"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "numpy" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/c1/93/8948ae6c1e1e3d6833596fd266f7be2d27c1451b8be094975ad42c5e842e/pandas_stubs-3.0.5.260914.tar.gz", hash = "sha256:3f6fc1f147f68fd89c007105e7c94a948acb4ecd7eb20dc1c02e153c4ed5c250", size = 117622, upload-time = "2026-09-14T16:42:35.065Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/9a/cb/5ad79e02a556cc23fed5816de0109fa8af660c66cfa5f4af74c3e8d4cd26/pandas_stubs-3.0.5.260914-py3-none-any.whl", hash = "sha256:39a1300c5c5c55fdf609e3476805decce5d5015539a4dcb683449f8feaeee2fb", size = 177344, upload-time = "2026-09-14T16:42:33.771Z" },
+]
+
[[package]]
name = "pathspec"
version = "1.1.1"
@@ -3681,6 +3754,83 @@ requires-dist = [
]
provides-extras = ["anthropic", "bedrock", "cli", "docling", "fal", "gcp-logging", "gcp-storage", "google", "google-genai", "huggingface", "linkup", "mistralai", "dynamodb", "s3", "docs", "dev"]
+[[package]]
+name = "pipelex-api"
+source = { editable = "api" }
+dependencies = [
+ { name = "fastapi" },
+ { name = "pipelex", extra = ["anthropic", "bedrock", "fal", "google", "google-genai", "mistralai"] },
+ { name = "pyjwt" },
+ { name = "uvicorn" },
+]
+
+[package.optional-dependencies]
+dev = [
+ { name = "boto3-stubs" },
+ { name = "httpx2" },
+ { name = "mypy" },
+ { name = "pandas-stubs" },
+ { name = "pylint" },
+ { name = "pyright" },
+ { name = "pytest" },
+ { name = "pytest-asyncio" },
+ { name = "pytest-cov" },
+ { name = "pytest-mock" },
+ { name = "pytest-sugar" },
+ { name = "pytest-xdist" },
+ { name = "ruff" },
+ { name = "types-aiobotocore", extra = ["bedrock", "bedrock-runtime"] },
+ { name = "types-aiofiles" },
+ { name = "types-beautifulsoup4" },
+ { name = "types-markdown" },
+ { name = "types-networkx" },
+ { name = "types-openpyxl" },
+ { name = "types-pyyaml" },
+ { name = "types-requests" },
+ { name = "types-toml" },
+]
+docs = [
+ { name = "mkdocs" },
+ { name = "mkdocs-glightbox" },
+ { name = "mkdocs-material" },
+ { name = "mkdocs-meta-manager" },
+]
+
+[package.metadata]
+requires-dist = [
+ { name = "boto3-stubs", marker = "extra == 'dev'", specifier = ">=1.35.24" },
+ { name = "fastapi", specifier = ">=0.118.0" },
+ { name = "httpx2", marker = "extra == 'dev'", specifier = ">=2.4.0" },
+ { name = "mkdocs", marker = "extra == 'docs'", specifier = ">=1.6.1" },
+ { name = "mkdocs-glightbox", marker = "extra == 'docs'", specifier = ">=0.4.0" },
+ { name = "mkdocs-material", marker = "extra == 'docs'", specifier = ">=9.7.7" },
+ { name = "mkdocs-meta-manager", marker = "extra == 'docs'", specifier = ">=1.1.0" },
+ { name = "mypy", marker = "extra == 'dev'", specifier = ">=1.11.2" },
+ { name = "pandas-stubs", marker = "extra == 'dev'", specifier = ">=2.2.3.241126" },
+ { name = "pipelex", extras = ["anthropic", "bedrock", "fal", "google", "google-genai", "mistralai"], editable = "." },
+ { name = "pyjwt", specifier = ">=2.10.1" },
+ { name = "pylint", marker = "extra == 'dev'", specifier = ">=3.3.8" },
+ { name = "pyright", marker = "extra == 'dev'", specifier = ">=1.1.405" },
+ { name = "pytest", marker = "extra == 'dev'", specifier = ">=8.3.3" },
+ { name = "pytest-asyncio", marker = "extra == 'dev'", specifier = ">=0.24.0" },
+ { name = "pytest-cov", marker = "extra == 'dev'", specifier = ">=6.1.1" },
+ { name = "pytest-mock", marker = "extra == 'dev'", specifier = ">=3.14.0" },
+ { name = "pytest-sugar", marker = "extra == 'dev'", specifier = ">=1.0.0" },
+ { name = "pytest-xdist", marker = "extra == 'dev'", specifier = ">=3.6.1" },
+ { name = "ruff", marker = "extra == 'dev'", specifier = ">=0.6.8" },
+ { name = "types-aiobotocore", extras = ["bedrock", "bedrock-runtime"], marker = "extra == 'dev'", specifier = ">=3.0.0" },
+ { name = "types-aiofiles", marker = "extra == 'dev'", specifier = ">=24.1.0.20240626" },
+ { name = "types-beautifulsoup4", marker = "extra == 'dev'", specifier = ">=4.12.0.20240907" },
+ { name = "types-markdown", marker = "extra == 'dev'", specifier = ">=3.6.0.20240316" },
+ { name = "types-networkx", marker = "extra == 'dev'", specifier = ">=3.3.0.20241020" },
+ { name = "types-openpyxl", marker = "extra == 'dev'", specifier = ">=3.1.5.20250306" },
+ { name = "types-pyyaml", marker = "extra == 'dev'", specifier = ">=6.0.12.20250326" },
+ { name = "types-requests", marker = "extra == 'dev'", specifier = ">=2.32.0.2024091" },
+ { name = "types-toml", marker = "extra == 'dev'", specifier = ">=0.10.8.20240310" },
+ { name = "uvicorn", specifier = ">=0.37.0" },
+]
+provides-extras = ["dev", "docs"]
+
[[package]]
name = "pipelex-tools"
version = "0.7.2"
@@ -4148,6 +4298,15 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/f4/7e/a72dd26f3b0f4f2bf1dd8923c85f7ceb43172af56d63c7383eb62b332364/pygments-2.20.0-py3-none-any.whl", hash = "sha256:81a9e26dd42fd28a23a2d169d86d7ac03b46e2f8b59ed4698fb4785f946d0176", size = 1231151, upload-time = "2026-03-29T13:29:30.038Z" },
]
+[[package]]
+name = "pyjwt"
+version = "2.15.1"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/43/ea/5194e52748b0da83d71e082d75496eaec6e58f419f5e184786ded517e6a9/pyjwt-2.15.1.tar.gz", hash = "sha256:4f259e80cdfb6b3fc18a7de51fd1ef9ec79652f25019bae68975ca2468a34df8", size = 121252, upload-time = "2026-09-28T18:40:42.598Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/50/ca/44de4e75f8aadc457f0634be3b542815078ded46dca30efb960edeecad6e/pyjwt-2.15.1-py3-none-any.whl", hash = "sha256:42d59d631f7768a1028a64c7ff581a9bf7519804daf91fc5b6c56e30eec5e193", size = 33860, upload-time = "2026-09-28T18:40:41.429Z" },
+]
+
[[package]]
name = "pylatexenc"
version = "2.10"
@@ -5166,6 +5325,19 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/eb/dc/ad025c1ee131eba60c69f4dd5779b18fcf1e6b21a343e2162a84d5d133c7/soupsieve-2.9.2-py3-none-any.whl", hash = "sha256:8089a26fd974ca7a1f30276d3d8492ab266ab15af581642dfe8aa162e0c1c823", size = 37370, upload-time = "2026-08-07T00:57:23.524Z" },
]
+[[package]]
+name = "starlette"
+version = "1.7.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "anyio" },
+ { name = "typing-extensions", marker = "python_full_version < '3.13'" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/7b/2b/3850dc6bf7ef71b088962eba31dafc6cffd2f96e577ebb0bb316df96da3e/starlette-1.7.0.tar.gz", hash = "sha256:c79f74ea63cff761804fbbfb182f1e0b440c2d07b164d24700c5a1bab5d6ff5d", size = 2736246, upload-time = "2026-09-23T07:30:26.35Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/4e/d6/1ec1b290f9e0fb067899b61e1d37a30c923068bad260b216dbe37a7d2967/starlette-1.7.0-py3-none-any.whl", hash = "sha256:67f8e99895493dd2911a03f11314af6ceebeae4e704bb9f43dfc6a9db151c93e", size = 78980, upload-time = "2026-09-23T07:30:24.567Z" },
+]
+
[[package]]
name = "sympy"
version = "1.14.0"
@@ -5567,6 +5739,15 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/f6/56/6113c23ff46c00aae423333eb58b3e60bdfe9179d542781955a5e1514cb3/triton-3.6.0-cp314-cp314t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:46bd1c1af4b6704e554cad2eeb3b0a6513a980d470ccfa63189737340c7746a7", size = 188397994, upload-time = "2026-01-20T16:01:14.236Z" },
]
+[[package]]
+name = "truststore"
+version = "0.10.4"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/53/a3/1585216310e344e8102c22482f6060c7a6ea0322b63e026372e6dcefcfd6/truststore-0.10.4.tar.gz", hash = "sha256:9d91bd436463ad5e4ee4aba766628dd6cd7010cf3e2461756b3303710eebc301", size = 26169, upload-time = "2025-08-12T18:49:02.73Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/19/97/56608b2249fe206a67cd573bc93cd9896e1efb9e98bce9c163bcdc704b88/truststore-0.10.4-py3-none-any.whl", hash = "sha256:adaeaecf1cbb5f4de3b1959b42d41f6fab57b2b1666adb59e89cb0b53361d981", size = 18660, upload-time = "2025-08-12T18:49:01.46Z" },
+]
+
[[package]]
name = "typeguard"
version = "4.5.1"
@@ -5657,6 +5838,30 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/3e/e5/47a573bbbd0a790f8f9fe452f7188ea72b212d21c9be57d5fc0cbc442075/types_awscrt-0.31.3-py3-none-any.whl", hash = "sha256:e5ce65a00a2ab4f35eacc1e3d700d792338d56e4823ee7b4dbe017f94cfc4458", size = 43340, upload-time = "2026-03-08T02:31:13.38Z" },
]
+[[package]]
+name = "types-beautifulsoup4"
+version = "4.12.0.20250516"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "types-html5lib" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/6d/d1/32b410f6d65eda94d3dfb0b3d0ca151f12cb1dc4cef731dcf7cbfd8716ff/types_beautifulsoup4-4.12.0.20250516.tar.gz", hash = "sha256:aa19dd73b33b70d6296adf92da8ab8a0c945c507e6fb7d5db553415cc77b417e", size = 16628, upload-time = "2025-05-16T03:09:09.93Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/7c/79/d84de200a80085b32f12c5820d4fd0addcbe7ba6dce8c1c9d8605e833c8e/types_beautifulsoup4-4.12.0.20250516-py3-none-any.whl", hash = "sha256:5923399d4a1ba9cc8f0096fe334cc732e130269541d66261bb42ab039c0376ee", size = 16879, upload-time = "2025-05-16T03:09:09.051Z" },
+]
+
+[[package]]
+name = "types-html5lib"
+version = "1.1.11.20260518"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "types-webencodings" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/b8/5a/0c708d1b0d35ad48b6a223c77c4a882fd016b40c25becb082a92e02a9c00/types_html5lib-1.1.11.20260518.tar.gz", hash = "sha256:4f33c087cb1119d65c4c80eca4323c2b501f9eaf8af9616b8b732ed4d8eae8fa", size = 18420, upload-time = "2026-05-18T06:07:23.662Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/4d/d0/b088b9f11eb69637d6826843f06caaff60247156735a25512922d3dc2c13/types_html5lib-1.1.11.20260518-py3-none-any.whl", hash = "sha256:9baa7912224ebb37027c5ccb7e3768e43ea47b1dfdd977e7ddc4b0a4a550584d", size = 24339, upload-time = "2026-05-18T06:07:22.876Z" },
+]
+
[[package]]
name = "types-jsonschema"
version = "4.26.0.20260518"
@@ -5669,6 +5874,15 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/07/d5/134f8a147dcecda10db7f60cfc6af0578a25a5c53c87b3907a64385e0184/types_jsonschema-4.26.0.20260518-py3-none-any.whl", hash = "sha256:30b30a518c7fe335df85c919fcbcc631b69c03d4a4b5b632fa916bea03065307", size = 16072, upload-time = "2026-05-18T06:06:43.264Z" },
]
+[[package]]
+name = "types-markdown"
+version = "3.10.2.20260712"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/19/eb/9520ed01687401b47265594955c0a9202a4f547795176de61bff77c8dfda/types_markdown-3.10.2.20260712.tar.gz", hash = "sha256:25aea17282490f35ab6b17a87771abd2f479185aaff8e8f4a0035043f02f2c52", size = 20185, upload-time = "2026-07-12T05:13:53.537Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/9f/ea/a8dc2c8977870d27b8b44c4ba2952d765f9d39626e42d0083c871c1c1ebf/types_markdown-3.10.2.20260712-py3-none-any.whl", hash = "sha256:a551ddedde46e0eaca7059aa3d0e42db71afe2b53d8b58f72f2de63f3284f625", size = 25842, upload-time = "2026-07-12T05:13:52.702Z" },
+]
+
[[package]]
name = "types-networkx"
version = "3.6.1.20260408"
@@ -5681,6 +5895,15 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/60/1d/870a15630dc37a85aa0364bf623fad6ef9ef7cad14be62a0bab7541839f5/types_networkx-3.6.1.20260408-py3-none-any.whl", hash = "sha256:dc957f12bc9ffe7cab6704ccb719722fc5e508a491273c49b45c8786162a6f08", size = 162537, upload-time = "2026-04-08T04:34:37.385Z" },
]
+[[package]]
+name = "types-openpyxl"
+version = "3.1.5.20260827"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/8e/6b/ce650ce7754a2bce3ca1dfbce7f7441df092e2dc6047d00e04f840c2b56e/types_openpyxl-3.1.5.20260827.tar.gz", hash = "sha256:be8b605fb99cfd7d5f5576d4a508e8ec44be2dd15b85157c559080de6384be34", size = 101985, upload-time = "2026-08-27T12:06:18.927Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/12/23/9708c0895d237205ab2b31c06f97d72294f69789ff9923ff7f4aa2126d6b/types_openpyxl-3.1.5.20260827-py3-none-any.whl", hash = "sha256:94e176d871d12e3cbc34f8fb03dc14db2a4245a6690791daf16fc7b08fd67869", size = 165885, upload-time = "2026-08-27T12:06:17.88Z" },
+]
+
[[package]]
name = "types-pyyaml"
version = "6.0.12.20260408"
@@ -5711,6 +5934,24 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/98/27/e88220fe6274eccd3bdf95d9382918716d312f6f6cef6a46332d1ee2feff/types_s3transfer-0.16.0-py3-none-any.whl", hash = "sha256:1c0cd111ecf6e21437cb410f5cddb631bfb2263b77ad973e79b9c6d0cb24e0ef", size = 19247, upload-time = "2025-12-08T08:13:08.426Z" },
]
+[[package]]
+name = "types-toml"
+version = "0.10.8.20260518"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/4b/11/6ece999e91f2ccb848ab4420f3f4816e78ac0541f739e6864affdaaa5737/types_toml-0.10.8.20260518.tar.gz", hash = "sha256:80e10facd24fdeda9d5c672187d72be3ac284843788d67f5aae59e3e016db6fe", size = 9419, upload-time = "2026-05-18T06:02:16.719Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/91/25/489751806bf5c95e4007f8e17409199c54d31e49ffbea07c5729b1286c8e/types_toml-0.10.8.20260518-py3-none-any.whl", hash = "sha256:0e564ab05f6fde62a315b3b5a9b6624fda569399795d30a37e64705a70459303", size = 9669, upload-time = "2026-05-18T06:02:15.86Z" },
+]
+
+[[package]]
+name = "types-webencodings"
+version = "0.6.0.20260907"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/01/74/b83cf1d523516bc818ffe6fa7c2f5504e0eeee7c5c394ecc1b404f95fe92/types_webencodings-0.6.0.20260907.tar.gz", hash = "sha256:efa85bc5114419ed45aec227ca5051cca63fa3e2bd13fcf79017ee4107603efc", size = 7748, upload-time = "2026-09-07T06:43:22.142Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/42/e7/dc1ea506e123c437c4551c35498eaade289f52d7f7ddf3f77cf94f0675dc/types_webencodings-0.6.0.20260907-py3-none-any.whl", hash = "sha256:86dc9b5a14665b24d5d7d061149c8c3f50355243df5ef285bf816c2e2cc093d5", size = 8584, upload-time = "2026-09-07T06:43:21.177Z" },
+]
+
[[package]]
name = "typing-extensions"
version = "4.15.0"
@@ -5750,6 +5991,19 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/7f/3e/5db95bcf282c52709639744ca2a8b149baccf648e39c8cc87553df9eae0c/urllib3-2.7.0-py3-none-any.whl", hash = "sha256:9fb4c81ebbb1ce9531cce37674bbc6f1360472bc18ca9a553ede278ef7276897", size = 131087, upload-time = "2026-05-07T16:13:17.151Z" },
]
+[[package]]
+name = "uvicorn"
+version = "0.54.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "click" },
+ { name = "h11" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/da/34/30e9280707135d2cfc589dfff3cb796bd07a3aeb1a3e415ba09dd89d7bb4/uvicorn-0.54.0.tar.gz", hash = "sha256:a2e33cbfaa0306f8e6b0c13e0cb89d7d7a2da3e62b90c66e18c33d9807b28620", size = 112283, upload-time = "2026-09-25T06:52:37.601Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/38/0c/b54a4fdd7f90a3af8b02ebc9ce6712c2c208b7926a2f7bad95c33ebbe943/uvicorn-0.54.0-py3-none-any.whl", hash = "sha256:505bdb0f318731d45f1f712071fc781a8981f6847a31c902c9f5e652d4f67faf", size = 87427, upload-time = "2026-09-25T06:52:35.829Z" },
+]
+
[[package]]
name = "verspec"
version = "0.1.0"