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.
fix(cli): use injected ctx, not global click context (typer ≥0.26 crash) (#973)
Thomas Hebrard69968a259073
diff --git a/.github/workflows/dependency-canary.yml b/.github/workflows/dependency-canary.ymlnew file mode 100644index 000000000..ffd45a77e--- /dev/null+++ b/.github/workflows/dependency-canary.yml@@ -0,0 +1,85 @@+name: Dependency canary++# Early warning for the failure mode that broke the CLI when typer 0.26 shipped:+# an upstream release that a fresh `pip install pipelex` would pull, but our+# committed uv.lock masks. Runs DAILY against newer-than-locked dependencies and+# exercises the REAL CLI (it's the CLI that broke), so such a break shows up here+# — on our dashboard — instead of in a user's install or a deploy.++on:+ schedule:+ - cron: "0 6 * * *" # every day, 06:00 UTC+ workflow_dispatch:++concurrency:+ group: ${{ github.workflow }}+ cancel-in-progress: true++jobs:+ # 1. Resolve every dependency to the latest version still allowed by our+ # declared ranges, then run the suite AND real CLI commands. Catches+ # breakage from any floor-only / uncapped dependency the moment it releases.+ latest-within-ranges:+ name: Latest deps within ranges (py${{ matrix.python-version }})+ runs-on: [aca-runner-test]+ strategy:+ fail-fast: false+ matrix:+ python-version: ["3.11", "3.13"]+ permissions:+ contents: read+ id-token: write+ env:+ VIRTUAL_ENV: ${{ github.workspace }}/.venv+ ENV: dev+ PIPELEX_NO_DECK_NOTICE: "1"+ steps:+ - uses: actions/checkout@v4++ - name: Install+ run: PYTHON_VERSION=${{ matrix.python-version }} make install++ - name: Upgrade dependencies to latest within ranges+ run: uv lock --upgrade && uv sync --all-extras++ - name: Run tests+ run: make gha-tests++ - name: Exercise the real CLI (config-free, no secrets)+ run: |+ .venv/bin/pipelex --version+ .venv/bin/pipelex validate bundle tests/data/packages/analytics_dep/analytics.mthds+ .venv/bin/pipelex run bundle tests/data/packages/analytics_dep/analytics.mthds --dry-run --mock-inputs++ # 2. Force the typer/click family PAST its pyproject cap, then run the CLI+ # smoke test and the real CLI commands. This is the signal to bump the cap:+ # when it goes red, a new typer/click broke the CLI -- validate, fix if+ # needed, then raise the bound in pyproject.toml. `uv pip install` ignores+ # the cap on purpose.+ beyond-typer-cap:+ name: Beyond typer cap (real CLI)+ runs-on: [aca-runner-test]+ permissions:+ contents: read+ id-token: write+ env:+ VIRTUAL_ENV: ${{ github.workspace }}/.venv+ ENV: dev+ PIPELEX_NO_DECK_NOTICE: "1"+ steps:+ - uses: actions/checkout@v4++ - name: Install+ run: make install++ - name: Force latest typer/click (ignores the cap)+ run: uv pip install --upgrade typer click++ - name: CLI smoke test (every subcommand starts)+ run: .venv/bin/pytest tests/unit/pipelex/cli/test_cli_entrypoint_smoke.py -q++ - name: Exercise the real CLI (validate + dry-run a real pipeline)+ run: |+ .venv/bin/pipelex --version+ .venv/bin/pipelex validate bundle tests/data/packages/analytics_dep/analytics.mthds+ .venv/bin/pipelex run bundle tests/data/packages/analytics_dep/analytics.mthds --dry-run --mock-inputsdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 97527b819..e7d4801de 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -12,7 +12,7 @@ This cycle reworks **cost reporting** so it survives distributed execution and s### Added-- **`--temporal` / `--no-temporal` on `pipelex validate`.** The `bundle`, `pipe`, and `method` validate subcommands (and `validate --all`) gain the same boot override `run` already had — it sets `temporal.is_enabled` for the process. Today the validation sweep always runs in-process regardless of backend (it scopes its own in-process router), so the flag does not change *what* validation does; it is the lever for booting validation under a Temporal-enabled hub — e.g. to verify the sweep stays in-process and never dispatches nested controller sub-pipes to Temporal. It is also forward-looking: once validation can run as a standalone Temporal activity, this flag becomes the switch that dispatches the sweep through that activity.+- **`--temporal` / `--no-temporal` on `pipelex validate`.** The `bundle`, `pipe`, and `method` validate subcommands (and `validate --all`) gain the same boot override `run` already had — it sets `temporal.is_enabled` for the process. Today the validation sweep always runs in-process regardless of backend (it scopes its own in-process router), so the flag does not change _what_ validation does; it is the lever for booting validation under a Temporal-enabled hub — e.g. to verify the sweep stays in-process and never dispatches nested controller sub-pipes to Temporal. It is also forward-looking: once validation can run as a standalone Temporal activity, this flag becomes the switch that dispatches the sweep through that activity.- **`--costs` / `--no-costs` (default on).** `pipelex run pipe|method|bundle` gains a dedicated cost switch that emits usage tracing events and renders the end-of-run cost report. It rides the shared trace-event transport independently of `--graph`, so `--no-graph --costs` reports cost without building a graph and `--graph --no-costs` builds a graph with no cost report. It replaces the removed `--cost-report` (see Changed).@@ -38,17 +38,21 @@ This cycle reworks **cost reporting** so it survives distributed execution and s- **Temporal `act_assemble_graph` renamed to `act_assemble_tracing`.** It now assembles both the graph (`GraphSpec`) and usage (`tokens_usages`) from a single trace-event read, gated per concern by the run's `--graph` / `--costs` flags.+- **`typer` is now capped (`>=0.16,<0.27`).** pipelex subclasses typer's `TyperGroup` and overrides `make_context`, so it is coupled to typer/click internals and a future typer minor can break the CLI. The cap is tested through 0.26; a new dependency-canary CI job resolves the latest dependencies on a schedule so the bound is bumped deliberately rather than discovered in a user's install.+### Fixed+- **CLI no longer crashes under newer typer/click.** Every `pipelex` subcommand (`build`, `run`, `validate`, `init`, `worker`, …) raised `RuntimeError: There is no active click context` and exited 1 when run against `typer >= 0.26` / `click >= 8.4` — the versions a fresh `pip install pipelex` resolves. The root `app_callback` fetched the context via the global `click.get_current_context()` instead of the `ctx` Typer already injects; the global context stack isn't populated when a subcommand is dispatched under those versions. It now uses the injected `ctx`, which is version-robust. The sibling `--traceback` flag had the same flaw — `is_traceback_requested()` read it via `click.get_current_context()`, so under those versions it was silently ignored on handled errors — and is now recorded at parse time in a context-independent flag. A subprocess CLI smoke test (`tests/unit/pipelex/cli/test_cli_entrypoint_smoke.py`) guards every subcommand against regressing.+- **Docs deploy crashed on a fresh runner with `InferenceSetupRequiredError`.** `pipelex-dev generate-error-pages` (a prerequisite of every `docs-*` make target) bootstrapped Pipelex with `needs_inference=True`, so on a CI runner with the gateway enabled but no on-disk service config it hit the first-run inference-setup gate and exited non-zero — breaking the `Deploy docs` workflow on `main`. The command only introspects `PipelexError` subclasses to write markdown and never calls inference, so it now bootstraps with `needs_inference=False`.- **`UsageRegistry` success-path leak.** The per-run cost registry was opened during run setup but closed only on the failure path, so every successful run leaked its registry — and in a long-lived process (e.g. the Pipelex API) reusing a `pipeline_run_id` could collide on the orphaned registry. The registry is removed entirely, so the leak is structurally impossible.-- **Temporal silent-hang fail-safe.** A pipelex domain error raised *inline* in workflow code — never dispatched through an activity — was neither an `ActivityError` nor an `ApplicationError`, so Temporal treated it as a workflow-task failure and retried it indefinitely: a silent, resource-burning hang that only surfaced (as a generic timeout) after the workflow execution timeout. `WfPipeRouter` and `WfPipeRun` now end their boundary handling with a `PipelexError` catch-all that converts a genuine inline error to a terminal, classified failure (the parent also still fires the FAILED webhook), and the worker registers `PipelexError` in `workflow_failure_exception_types` as a backstop so any uncaught domain error fails the workflow terminally instead of hanging. Scoped to domain errors only — transient Temporal/infra errors keep their (correct) task-retry behavior.+- **Temporal silent-hang fail-safe.** A pipelex domain error raised _inline_ in workflow code — never dispatched through an activity — was neither an `ActivityError` nor an `ApplicationError`, so Temporal treated it as a workflow-task failure and retried it indefinitely: a silent, resource-burning hang that only surfaced (as a generic timeout) after the workflow execution timeout. `WfPipeRouter` and `WfPipeRun` now end their boundary handling with a `PipelexError` catch-all that converts a genuine inline error to a terminal, classified failure (the parent also still fires the FAILED webhook), and the worker registers `PipelexError` in `workflow_failure_exception_types` as a backstop so any uncaught domain error fails the workflow terminally instead of hanging. Scoped to domain errors only — transient Temporal/infra errors keep their (correct) task-retry behavior.- **`PipeSearch` on Temporal no longer hangs.** Web search was the only inference operator that ran its leaf inline instead of through the `ContentGenerator` seam, so it had no Temporal activity. Run through the Temporal path, a search step executed its real HTTP call inside the workflow event loop, and on failure raised a raw `SearchJobFailureError` (neither an `ActivityError` nor a `WorkflowExecutionError`) that Temporal treated as a workflow-task failure and retried forever — the submitter hung instead of getting a result. Even on success it was replay-unsafe (the search re-ran on every workflow replay). `PipeSearch` now dispatches its leaf through new `act_search_gen_sourced_answer` / `act_search_gen_structured` activities like every other operator: results are recorded in workflow history (replay-safe) and failures cross the workflow boundary as a terminal `WorkflowExecutionError` carrying the structured `ErrorReport` — identical classification to the local path. A `runner-search` worker scope and per-activity routing entries are available for split deployments.-- **Bundle validation no longer leaks nested controller sub-pipes to Temporal.** With Temporal enabled, the in-process dry-run sweep (`BundleValidator`) ran the top-level pipe in-process but dispatched every *nested* controller sub-pipe through the hub-default router — the Temporal router — turning a no-cost dry run into real top-level workflow dispatches. A standalone `PipeBatch` / `PipeParallel` swept directly fanned out N concurrent same-id top-level dispatches and collided (`WorkflowAlreadyStartedError`), surfacing as **HTTP 422** on the runner's `/validate` route; other shapes silently round-tripped Temporal. The sweep now scopes its in-process router for the whole sweep (mirroring the DIRECT-mode runtime bridge), so nested controllers resolve the in-process router and validation stays fully in-process regardless of the configured backend.+- **Bundle validation no longer leaks nested controller sub-pipes to Temporal.** With Temporal enabled, the in-process dry-run sweep (`BundleValidator`) ran the top-level pipe in-process but dispatched every _nested_ controller sub-pipe through the hub-default router — the Temporal router — turning a no-cost dry run into real top-level workflow dispatches. A standalone `PipeBatch` / `PipeParallel` swept directly fanned out N concurrent same-id top-level dispatches and collided (`WorkflowAlreadyStartedError`), surfacing as **HTTP 422** on the runner's `/validate` route; other shapes silently round-tripped Temporal. The sweep now scopes its in-process router for the whole sweep (mirroring the DIRECT-mode runtime bridge), so nested controllers resolve the in-process router and validation stays fully in-process regardless of the configured backend.## [v0.31.0] - 2026-06-04@@ -177,7 +181,7 @@ This release hardens Pipelex at its edges. The headliners: a full **error-handli- **`AMBIGUOUS` inference-error category for outcome-uncertain failures.** New `InferenceErrorCategory.AMBIGUOUS` for failures where the error type is known but the outcome is not — the operation may or may not have committed (e.g. a connection dropped mid-request). It is non-retryable, like `CONFIGURATION` / `CONTENT` / `CAPACITY`, but semantically distinct from `UNKNOWN`, which means the error could not be classified at all. The `azure_rest` image-generation worker now raises `AMBIGUOUS` for mid-request transport failures — `ReadError` / `WriteError` / `RemoteProtocolError` and `ReadTimeout` / `WriteTimeout` — so Temporal does not auto-retry a non-idempotent, billable image submit whose outcome is unknown; pre-request failures (`ConnectError` / `ConnectTimeout` / `PoolTimeout`) stay `TRANSIENT` and retryable.-- **Explicit, uniform Tier 1 transport retry across every inference worker.** A new `[cogt]` setting `transport_max_retries` (default `2`) is now wired explicitly into every inference SDK client factory — Anthropic, OpenAI / Azure OpenAI, the Portkey-backed gateway clients, Mistral, and Google — instead of each factory silently inheriting whatever retry posture its SDK happens to default to. The two SDK families that default to *no* transport retry are brought up to the same floor: the Mistral client gets a bounded-backoff `RetryConfig` (`retry_connection_errors=True`) and the Google GenAI client gets `HttpOptions(retry_options=...)`. The genuinely SDK-less path — the `azure_rest` image-generation worker, which talks to Azure over raw `httpx` — gets a `tenacity`-based transport-retry wrapper (new module `pipelex/cogt/inference/transport_retry.py`) that retries connection failures and transient HTTP statuses (408/409/429/5xx) and honors `Retry-After`. When no `Retry-After` header is present, the fallback backoff uses full jitter (`wait_random_exponential`) so a burst of failures retried together does not re-fire in lockstep. On a non-idempotent submit-style POST it narrows the retry to failures that prove the server did no billable work — a request that was never delivered, or a 408/429 rejection — withholding an ambiguous 5xx, a 409 conflict, and a post-delivery timeout such as a `ReadTimeout`. Transport retry is now a deliberate, configured, uniform policy rather than a per-provider accident. This is "Tier 1" of the retry model — direct (non-Temporal) execution still makes a single pipeline-level attempt on top of this transport floor; durable resilience remains the Temporal track. (The `portkey-ai` SDK does not expose a retry knob — it carries its own internal retry — so the gateway's `AsyncPortkey` client is left as-is; only its underlying OpenAI clients are wired.)+- **Explicit, uniform Tier 1 transport retry across every inference worker.** A new `[cogt]` setting `transport_max_retries` (default `2`) is now wired explicitly into every inference SDK client factory — Anthropic, OpenAI / Azure OpenAI, the Portkey-backed gateway clients, Mistral, and Google — instead of each factory silently inheriting whatever retry posture its SDK happens to default to. The two SDK families that default to _no_ transport retry are brought up to the same floor: the Mistral client gets a bounded-backoff `RetryConfig` (`retry_connection_errors=True`) and the Google GenAI client gets `HttpOptions(retry_options=...)`. The genuinely SDK-less path — the `azure_rest` image-generation worker, which talks to Azure over raw `httpx` — gets a `tenacity`-based transport-retry wrapper (new module `pipelex/cogt/inference/transport_retry.py`) that retries connection failures and transient HTTP statuses (408/409/429/5xx) and honors `Retry-After`. When no `Retry-After` header is present, the fallback backoff uses full jitter (`wait_random_exponential`) so a burst of failures retried together does not re-fire in lockstep. On a non-idempotent submit-style POST it narrows the retry to failures that prove the server did no billable work — a request that was never delivered, or a 408/429 rejection — withholding an ambiguous 5xx, a 409 conflict, and a post-delivery timeout such as a `ReadTimeout`. Transport retry is now a deliberate, configured, uniform policy rather than a per-provider accident. This is "Tier 1" of the retry model — direct (non-Temporal) execution still makes a single pipeline-level attempt on top of this transport floor; durable resilience remains the Temporal track. (The `portkey-ai` SDK does not expose a retry knob — it carries its own internal retry — so the gateway's `AsyncPortkey` client is left as-is; only its underlying OpenAI clients are wired.)- **Offline mode for Pipelex Gateway setup and dry-run.** When the gateway is enabled but the remote config service is temporarily unreachable, Pipelex now falls back to a previously primed on-disk cache (`~/.pipelex/cache/remote_config.json`, schema-versioned) instead of failing setup outright. Dry-run, validation, and `pipelex-agent run bundle --dry-run` complete normally; only the actual inference call still needs the network at runtime. The cache is primed on every successful fetch and on `pipelex init` while online. When the gateway is disabled (BYOK), no remote fetch is attempted at all — setup is fully offline. A new `RemoteConfigStaleWarning` (`UserWarning`) is emitted whenever stale cache is in use; the agent CLI surfaces it on the JSON envelope as `warnings: [{"type": "RemoteConfigStale", ...}]`. Telemetry is suppressed (no-op) when running on a cached config so stale model identities don't pollute metrics. The doc/fixture generators (`pipelex-dev update-gateway-models`, `preprocess_test_models_cmd`) refuse the cache fallback via a new `require_fresh=True` flag, so committed reference docs and test fixtures never bake in stale data.@@ -191,9 +195,9 @@ This release hardens Pipelex at its edges. The headliners: a full **error-handli- **Inference error handling refactored to Extract / Classify / Render (internal).** Every inference worker's SDK-exception block now collapses to `metadata = extract_*_metadata(exc); classification = classify_inference_error(metadata); raise render_*_error(...) from exc`. New modules: `pipelex/cogt/inference/error_classify.py` (single shared `classify_inference_error()` returning `ClassificationResult(category, user_action_kind, is_model_not_found)`), `pipelex/cogt/inference/error_render.py` (single shared `render_llm_error` / `render_img_gen_error` / `render_extract_error` / `render_search_error`, picking the `CogtError` subclass from an `InferenceErrorFamily` tag plus the `is_model_not_found` flag), and `pipelex/cogt/inference/provider_name.py` (the `ProviderName` enum keying the extract-fn registry). `ProviderErrorMetadata` gains a `message` field plus `is_quota_exhaustion` / `is_content_policy_violation` / `is_network_error` `@property` accessors; the per-provider `extract_*_metadata` functions are now the only plugin-local piece — Classify and Render live once. Mistral and the gateway-search worker specialize HTTP 404 to `ExtractModelNotFoundError` / `SearchModelNotFoundError`; Azure img-gen keeps two worker-specific `AMBIGUOUS` branches for mid-request transport failures. Removed: the per-provider `*_error_classification.py` modules and their tests, `AnthropicCredentialsError`, `GatewayFactory.classify_error_category` / `make_user_action_from_portkey_error` / `make_error_summary_from_portkey_error`, and every inline `_classify_*_error` / `_raise_categorized_*` worker method. New unit-test `tests/unit/pipelex/cogt/inference/test_provider_classification_parity.py` walks every `ProviderName` against the extract-fn registry + worker-family map, so an unwired new provider fails fast. No user-facing API change — the structured `ErrorReport` contract is unchanged. Documented at [under-the-hood/error-model.md](under-the-hood/error-model.md).-- **`instructor`'s structured-output retry no longer re-runs completions on transport errors.** Passed a bare `int`, `instructor`'s `max_retries` builds a retry loop whose predicate retries *any* exception — so the structured-output path (`PipeLLM` / `PipeStructure`) was re-running the whole completion on transport / API errors, a second retry loop nested on top of the SDK client's own transport retry. Each `instructor` call site now passes a `tenacity.AsyncRetrying` (built by the new `pipelex/cogt/llm/instructor_retry.py` helper) whose retry predicate matches only validation failures (`pydantic.ValidationError`, `json.JSONDecodeError`, and `instructor`'s own validation-error types). A transport error now propagates immediately as the raw SDK exception for the worker's `except` clause to classify — transport retry is the SDK client floor (Tier 1) alone, and `instructor`'s retry is confined to genuine schema re-ask. As part of this the Google and Mistral structured-generation workers gained an `httpx.TransportError` `except` clause: those SDKs let raw connection / timeout errors propagate outside their own exception hierarchies, so with `instructor` no longer wrapping them they must be caught and classified directly. The Mistral structured path also now gets schema re-ask at all — it previously passed no `max_retries`.+- **`instructor`'s structured-output retry no longer re-runs completions on transport errors.** Passed a bare `int`, `instructor`'s `max_retries` builds a retry loop whose predicate retries _any_ exception — so the structured-output path (`PipeLLM` / `PipeStructure`) was re-running the whole completion on transport / API errors, a second retry loop nested on top of the SDK client's own transport retry. Each `instructor` call site now passes a `tenacity.AsyncRetrying` (built by the new `pipelex/cogt/llm/instructor_retry.py` helper) whose retry predicate matches only validation failures (`pydantic.ValidationError`, `json.JSONDecodeError`, and `instructor`'s own validation-error types). A transport error now propagates immediately as the raw SDK exception for the worker's `except` clause to classify — transport retry is the SDK client floor (Tier 1) alone, and `instructor`'s retry is confined to genuine schema re-ask. As part of this the Google and Mistral structured-generation workers gained an `httpx.TransportError` `except` clause: those SDKs let raw connection / timeout errors propagate outside their own exception hierarchies, so with `instructor` no longer wrapping them they must be caught and classified directly. The Mistral structured path also now gets schema re-ask at all — it previously passed no `max_retries`.-- **Inference schema-retry setting moved and renamed: `[cogt.llm_config.llm_job_config] max_retries` → `[cogt.llm_config] schema_reask_max_attempts` (breaking).** The setting is `instructor`'s schema re-ask budget for structured-output validation failures. The old name `max_retries` gave no hint of that scope and collided conceptually with the new top-level `cogt.transport_max_retries` — which counts retries *beyond* the initial attempt, whereas this one is a *total* attempt count (`stop_after_attempt`). The new name makes both the scope (schema re-ask) and the unit (attempts, not retries) explicit. The single-key `[cogt.llm_config.llm_job_config]` sub-table is also dropped — the setting now sits directly under `[cogt.llm_config]`. Projects that override this key in their own `pipelex.toml` must move and rename it.+- **Inference schema-retry setting moved and renamed: `[cogt.llm_config.llm_job_config] max_retries` → `[cogt.llm_config] schema_reask_max_attempts` (breaking).** The setting is `instructor`'s schema re-ask budget for structured-output validation failures. The old name `max_retries` gave no hint of that scope and collided conceptually with the new top-level `cogt.transport_max_retries` — which counts retries _beyond_ the initial attempt, whereas this one is a _total_ attempt count (`stop_after_attempt`). The new name makes both the scope (schema re-ask) and the unit (attempts, not retries) explicit. The single-key `[cogt.llm_config.llm_job_config]` sub-table is also dropped — the setting now sits directly under `[cogt.llm_config]`. Projects that override this key in their own `pipelex.toml` must move and rename it.- **Agent CLI `run` / `validate` / `init` default to markdown output, with independent success/error format options (breaking).** These commands previously always emitted JSON; they now accept `--format markdown|json` and default to markdown, matching `models` / `check-model` / `doctor`. A second flag `--error-format markdown|json` controls error reporting on stderr independently from success output — it defaults to the value of `--format`, so `--format json` still flips both, but the two can now be set separately (e.g. `--format markdown --error-format json` for human-readable success with machine-parseable errors). Internally, only the error format is carried in a `ContextVar`; the success format is threaded explicitly to `agent_success_formatted()`. The `inputs` / `concept` / `pipe` / `fmt` / `lint` / `accept-gateway-terms` commands are unaffected (always JSON / raw passthrough).@@ -279,7 +283,7 @@ This release hardens Pipelex at its edges. The headliners: a full **error-handli- **Template preprocessor: `$<var>` no longer substitutes when `$` is adjacent to a word character on the left** (e.g. `micro$oft`, `user$host.com`, `P@ssw$rd123`, `a$b$c` now pass through unchanged instead of producing mid-word `{{ ... }}` substitutions), and no longer emits invalid Jinja for shapes like `$name..` (now renders `{{ name|format() }}..` with both trailing dots preserved as literal punctuation). The `$` arm now mirrors the `@` candidate pattern's word-boundary lookbehind (`(?<!\w)`) and uses a strict segmented identifier `[a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z_][a-zA-Z0-9_]*)*` that rules out a leading digit and consecutive dots structurally. The trailing-dot kludge in the `$` replacement function is gone (unreachable under the strict identifier shape). `$var` keeps its silent pass-through posture for non-candidate shapes — it does not raise like the `@` arm does.- **Project `.pipelex/telemetry.toml` created by `pipelex init` no longer silently disables globally-enabled telemetry.** The kit previously shipped one `telemetry.toml` template carrying explicit `enabled = false` / `mode = "off"` defaults, and `pipelex init telemetry` copied it into both `~/.pipelex/` and the project's `.pipelex/`. Because the layered loader appends the project base file after `~/.pipelex/telemetry_override.toml`, a user who enabled Langfuse/PostHog globally in their override still had it turned off in every initialized project. The kit now ships a separate `telemetry.project.toml` template with every setting commented out, used only by project-level init. The global init still copies the active `telemetry.toml`. As a safety net, `telemetry_allowed_modes` defaults (`ci=False`, `cli=True`, `docker=True`, `fastapi=True`, `mcp=True`, `n8n=True`, `pytest=False`, `python=False`) now live in the `TelemetryConfig` Pydantic model rather than the TOML template, so a project file that omits the section can't disable custom telemetry for everyone.-- **Global `pipelex.toml` and `telemetry.toml` overrides no longer silently disappear when a project `.pipelex/` exists.** `ConfigLoader.load_config()` previously sourced *all* override files (`pipelex_local.toml`, `pipelex_{env}.toml`, `pipelex_{run_mode}.toml`, `pipelex_override.toml`, `pipelex_temporary_override.toml`) from a single "effective config dir" — project `.pipelex/` if present, else `~/.pipelex/`. As a result, the user's machine-wide overrides in `~/.pipelex/` were ignored entirely the moment a project shipped its own `.pipelex/`. `load_telemetry_config` had the same shadowing behavior for `telemetry.toml` and `telemetry_override.toml`, which was particularly painful because telemetry holds Langfuse/PostHog/OTLP secrets that users typically set once globally. Both loaders now layer global → project: package defaults → global base → global overrides → project base → project overrides, deep-merged so machine-wide personal preferences keep applying unless explicitly overridden by the project. The unit-testing run_mode behavior is preserved: `./tests/pipelex_{run_mode}.toml` is still the only run_mode file loaded under unit testing, replacing both layers to keep test runs hermetic. **Migration:** if a project previously relied on its `.pipelex/` to fully *replace* the user's global config rather than merging over it, the project must now redeclare any keys it wants to set explicitly — silent inheritance from `~/.pipelex/` is the new default.+- **Global `pipelex.toml` and `telemetry.toml` overrides no longer silently disappear when a project `.pipelex/` exists.** `ConfigLoader.load_config()` previously sourced _all_ override files (`pipelex_local.toml`, `pipelex_{env}.toml`, `pipelex_{run_mode}.toml`, `pipelex_override.toml`, `pipelex_temporary_override.toml`) from a single "effective config dir" — project `.pipelex/` if present, else `~/.pipelex/`. As a result, the user's machine-wide overrides in `~/.pipelex/` were ignored entirely the moment a project shipped its own `.pipelex/`. `load_telemetry_config` had the same shadowing behavior for `telemetry.toml` and `telemetry_override.toml`, which was particularly painful because telemetry holds Langfuse/PostHog/OTLP secrets that users typically set once globally. Both loaders now layer global → project: package defaults → global base → global overrides → project base → project overrides, deep-merged so machine-wide personal preferences keep applying unless explicitly overridden by the project. The unit-testing run*mode behavior is preserved: `./tests/pipelex*{run_mode}.toml`is still the only run_mode file loaded under unit testing, replacing both layers to keep test runs hermetic. **Migration:** if a project previously relied on its`.pipelex/`to fully *replace* the user's global config rather than merging over it, the project must now redeclare any keys it wants to set explicitly — silent inheritance from`~/.pipelex/` is the new default.- **`pipelex build structures` now emits domain-qualified class names and cross-references.** `ConceptFactory` registers each concept's structure class under `make_qualified_structure_class_name(domain, concept_code)` (e.g. `expense_validator__SpendingLimitCheck`), but the CLI generator was passing the bare `concept_code` to `StructureGenerator`. Generated files therefore contained `class ConceptCode(StructuredContent)` and unqualified cross-imports/types, while the registry expected the qualified name. `PipeFunc` validation against `concept.structure_class_name` then rejected the mismatch with `output concept expects structure class 'domain__X', but the function return type is 'X'`, breaking library load for any project that had regenerated structures. Fixed in `pipelex/cli/commands/build/structures_cmd.py`: the class-definition call sites now call `make_qualified_structure_class_name(blueprint.domain, concept_code)`; `_build_concept_ref_to_class_info` qualifies cross-reference class names while keeping the file stem unqualified so output filenames stay `domain__concept_code.py`; the `refines:` branch resolves the refined concept's domain via `QualifiedRef.parse_stripping_cross_package` and qualifies the base-class name for non-native refines, mirroring `ConceptFactory._handle_refines`.- **`pipelex build structures` cross-package refines now emit the base-class import.** A concept that refines a class defined in another already-installed package (e.g. `RefiningConcept` with `refines: some_alias->other_domain.OtherConcept`) was generating a file that inherited from `other_domain__OtherConcept` without importing it. `StructureGenerator._validate_execution` injects the base class into `exec_globals` from the class registry, so codegen-time validation passed; the failure surfaced only when the generated structures module was later loaded via the normal Python import system, raising `NameError: name 'other_domain__OtherConcept' is not defined`. The generator now falls back to the class registry's `__module__` when `concept_ref_to_class_info` has no entry for the base class and emits the corresponding import (guarded on `cls.__name__ == base_class` so we never emit a name the target module won't expose). Regression test in `tests/unit/pipelex/cli/commands/build/test_structures_cmd_cross_package_refines.py` was tightened to assert the import statement is present.diff --git a/pipelex/cli/_cli.py b/pipelex/cli/_cli.pyindex 1bb3e67e2..e74421c52 100644--- a/pipelex/cli/_cli.py+++ b/pipelex/cli/_cli.py@@ -1,6 +1,5 @@from typing import Annotated-import clickimport typerfrom click import Command, Contextfrom typer.core import TyperGroup@@ -20,6 +19,7 @@ from pipelex.cli.commands.validate.app import validate_appfrom pipelex.cli.commands.which_cmd import which_cmdfrom pipelex.cli.commands.worker_cmd import worker_cmdfrom pipelex.cli.deck_notice import warn_if_deck_stale+from pipelex.cli.error_handlers import set_traceback_requestedfrom pipelex.cli.readiness import check_readinessfrom pipelex.hub import get_consolefrom pipelex.tools.misc.package_utils import get_package_version@@ -81,6 +81,9 @@ class PipelexCLI(TyperGroup):ctx.ensure_object(dict)ctx.obj["no_logo"] = no_logoctx.obj["traceback"] = traceback+ # Record at parse time so error handlers honor --traceback without relying on+ # an active global Click context (absent under typer >= 0.26 / click >= 8.4).+ set_traceback_requested(traceback)return ctx@@ -117,9 +120,11 @@ def app_callback(console = get_console()package_version = get_package_version()- # Get no_logo flag from context (set by PipelexCLI.make_context)- click_ctx = click.get_current_context()- no_logo = click_ctx.obj.get("no_logo", False) if click_ctx.obj else False+ # Get no_logo flag from context (set by PipelexCLI.make_context). Use the+ # ctx parameter Typer injects rather than click.get_current_context(): the+ # global context stack is not populated when a subcommand is dispatched+ # under typer >= 0.26 / click >= 8.4, which made every subcommand crash.+ no_logo = ctx.obj.get("no_logo", False) if ctx.obj else Falseif no_logo:console.print(f"Pipelex v{package_version}")diff --git a/pipelex/cli/error_handlers.py b/pipelex/cli/error_handlers.pyindex 4f846cfff..c58716f03 100644--- a/pipelex/cli/error_handlers.py+++ b/pipelex/cli/error_handlers.py@@ -1,3 +1,4 @@+from contextvars import ContextVarfrom pathlib import Pathfrom typing import NoReturn@@ -46,8 +47,24 @@ class ErrorContext(StrEnum):KIT = "Kit operation"+# Whether --traceback was passed, recorded at parse time by PipelexCLI.make_context.+# This is a ContextVar (mirroring set_agent_cli_error_format) rather than a read of the+# global Click context: typer >= 0.26 / click >= 8.4 do not push a global context during+# subcommand dispatch, so reading the flag there silently lost it on handled errors.+_traceback_requested: ContextVar[bool] = ContextVar("pipelex_cli_traceback_requested", default=False)+++def set_traceback_requested(value: bool) -> None:+ """Record whether --traceback was passed, independent of the Click context."""+ _traceback_requested.set(value)++def is_traceback_requested() -> bool:"""Check whether the --traceback global flag was passed on the CLI invocation."""+ # Authoritative path: the flag recorded at parse time, context-independent.+ if _traceback_requested.get():+ return True+ # Fallback for callers that push a Click context directly (tests / embedders).try:ctx = click.get_current_context(silent=True)except RuntimeError:diff --git a/pyproject.toml b/pyproject.tomlindex e8d991f3b..761df5de8 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -53,7 +53,10 @@ dependencies = ["shortuuid>=1.0.13","tomli>=2.3.0","tomlkit>=0.13.2",- "typer>=0.16.0",+ # Capped: pipelex subclasses typer's TyperGroup and overrides make_context, so+ # it is coupled to typer/click internals. Tested through 0.26; the dependency+ # canary flags new releases to validate before raising this bound.+ "typer>=0.16.0,<0.27","typing-extensions>=4.13.2","urllib3>=2.7.0",]diff --git a/tests/unit/pipelex/cli/conftest.py b/tests/unit/pipelex/cli/conftest.pyindex 77b803a5b..820b1ded1 100644--- a/tests/unit/pipelex/cli/conftest.py+++ b/tests/unit/pipelex/cli/conftest.py@@ -7,11 +7,25 @@ from typing import TYPE_CHECKINGimport pytestfrom pipelex.cli.agent_cli.commands.agent_output import CliOutputFormat, set_agent_cli_error_format+from pipelex.cli.error_handlers import set_traceback_requestedif TYPE_CHECKING:from collections.abc import Iterator[email protected](autouse=True)+def reset_traceback_requested() -> Iterator[None]:+ """Keep the --traceback ContextVar from leaking between cli/ tests.++ ``PipelexCLI.make_context`` (and tests that call ``set_traceback_requested``) set+ this flag; without a reset a leaked ``True`` would make a sibling test's "no flag"+ assertion order-dependent.+ """+ set_traceback_requested(False)+ yield+ set_traceback_requested(False)++@pytest.fixture(autouse=True)def reset_agent_cli_error_format() -> Iterator[None]:"""Keep the module-level error-format ContextVar from leaking between cli/ tests.diff --git a/tests/unit/pipelex/cli/test_cli_entrypoint_smoke.py b/tests/unit/pipelex/cli/test_cli_entrypoint_smoke.pynew file mode 100644index 000000000..65befddcc--- /dev/null+++ b/tests/unit/pipelex/cli/test_cli_entrypoint_smoke.py@@ -0,0 +1,80 @@+"""Smoke test: the pipelex CLI must start under whatever typer/click is installed.++Regression guard for the "no active click context" crash. Under+typer >= 0.26 / click >= 8.4 the group callback (`app_callback`) ran without an+active *global* click context, so it raised `RuntimeError: There is no active+click context` and **every subcommand exited 1 before doing anything** — root+`--help` happened to survive, but `pipelex build --help`, `pipelex worker --help`,+etc. did not. A fresh `pip install pipelex` pulls those versions, so the shipped+CLI was broken for end users while our `uv.lock` (older typer) masked it locally.++Two things make this test catch the bug where the existing CLI tests did not:++1. It invokes the **real console-script entry point via subprocess** — not+ typer's ``CliRunner``. ``CliRunner.invoke`` pushes its own click context, so+ it would pass even when the global context is missing; only the real entry+ point reproduces the failure.+2. It uses **subcommand** ``--help``, which exercises ``app_callback`` (so it+ reproduces the crash) while needing no pipelex config or inference — keeping+ it cheap enough to run in the normal CI suite, not gated behind a marker.+"""++from __future__ import annotations++import shutil+import subprocess # noqa: S404 -- invokes the real pipelex binary on purpose+import sys+from pathlib import Path++import pytest+++def _resolve_pipelex_bin() -> str | None:+ """Locate the installed `pipelex` console script.++ Prefer the one next to the running interpreter (the test venv) so it's correct+ under tox/nox/uv venvs regardless of PATH; fall back to PATH. Returns None when+ not found, so the test can fail with a clear message instead of letting+ subprocess raise FileNotFoundError.+ """+ bin_dir = Path(sys.executable).parent+ for name in ("pipelex", "pipelex.exe"): # .exe covers Windows venvs+ candidate = bin_dir / name+ if candidate.exists():+ return str(candidate)+ return shutil.which("pipelex") # PATH fallback (resolves .exe via PATHEXT on Windows)+++PIPELEX_BIN = _resolve_pipelex_bin()+++class TestCliEntrypointStarts:+ """The installed `pipelex` entry point must start for every subcommand."""++ @pytest.mark.parametrize(+ "args",+ [+ ["--help"],+ ["build", "--help"],+ ["run", "--help"],+ ["validate", "--help"],+ ["init", "--help"],+ ["worker", "--help"],+ ],+ )+ def test_subcommand_starts_and_exits_zero(self, args: list[str]) -> None:+ bin_path = PIPELEX_BIN+ if bin_path is None:+ pytest.fail("`pipelex` console script not found next to the interpreter or on PATH; install the package before running this test.")+ result = subprocess.run( # noqa: S603 -- fixed, trusted argv+ [bin_path, *args],+ capture_output=True,+ text=True,+ timeout=120,+ check=False,+ )+ combined = f"{result.stdout}\n{result.stderr}"+ assert result.returncode == 0, (+ f"`pipelex {' '.join(args)}` exited {result.returncode}; the CLI failed to start under the installed typer/click.\n{combined}"+ )+ assert "no active click context" not in combined.lower(), f"`pipelex {' '.join(args)}` hit the click-context regression.\n{combined}"diff --git a/tests/unit/pipelex/cli/test_is_traceback_requested.py b/tests/unit/pipelex/cli/test_is_traceback_requested.pyindex ae5d2a7f0..0b4407671 100644--- a/tests/unit/pipelex/cli/test_is_traceback_requested.py+++ b/tests/unit/pipelex/cli/test_is_traceback_requested.py@@ -1,20 +1,30 @@"""Tests for is_traceback_requested().-Verifies that the function correctly reads the --traceback flag from the Click context.+Verifies that the function honors the parse-time flag (set via set_traceback_requested)+and, as a fallback, the --traceback flag carried on an explicitly-pushed Click context."""from __future__ import annotationsimport click-from pipelex.cli.error_handlers import is_traceback_requested+from pipelex.cli.error_handlers import is_traceback_requested, set_traceback_requestedclass TestIsTracebackRequested:"""Unit tests for is_traceback_requested()."""+ def test_returns_true_from_parse_time_flag_without_click_context(self) -> None:+ """Regression: the flag recorded at parse time is honored with NO active Click+ context. typer >= 0.26 / click >= 8.4 do not push a global context during+ subcommand dispatch, which silently disabled --traceback when the flag was read+ through click.get_current_context().+ """+ set_traceback_requested(True)+ assert is_traceback_requested() is True+def test_returns_false_when_no_click_context(self) -> None:- """Outside a Click context, should return False."""+ """Outside a Click context and with no parse-time flag, should return False."""assert is_traceback_requested() is Falsedef test_returns_false_when_flag_not_set(self) -> None:diff --git a/uv.lock b/uv.lockindex 4a2ae23b1..d42cbc249 100644--- a/uv.lock+++ b/uv.lock@@ -3901,7 +3901,7 @@ requires-dist = [{ name = "temporalio", marker = "extra == 'temporal'", specifier = "==1.24.0" },{ name = "tomli", specifier = ">=2.3.0" },{ name = "tomlkit", specifier = ">=0.13.2" },- { name = "typer", specifier = ">=0.16.0" },+ { name = "typer", specifier = ">=0.16.0,<0.27" },{ name = "types-aioboto3", extras = ["bedrock", "bedrock-runtime"], marker = "extra == 'dev'", specifier = ">=13.4.0" },{ name = "types-aiofiles", marker = "extra == 'dev'", specifier = ">=24.1.0.20240626" },{ name = "types-jsonschema", marker = "extra == 'dev'", specifier = ">=4.20.0" },