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/Agent-hosted-caller-view · L-261018-4a9497 (#1459)

Louis Choqueladea564f79f1
diff --git a/.drift/acks/cli-docs.toml b/.drift/acks/cli-docs.toml
index e0382c013..e643c6306 100644
--- a/.drift/acks/cli-docs.toml
+++ b/.drift/acks/cli-docs.toml
@@ -1,8 +1,8 @@
contract = "cli-docs"
-digest = "sha256:e697942345f3ef2a23b12d9c8e04b92e534335ce22bdffe43b60b20ac7533b09"
+digest = "sha256:e2503f6e69a587a26fd9c9c8e856e158b359b2cbbc5285f680e1c427ea5486f4"
reviewed_by = "Louis Choquel"
-reviewed_at = "2026-10-19T11:06:53Z"
-rationale = "clean-pass: absorbing Runner-speaks-problem, which carries pipelex#1457's agent CLI reading of the runner's problem, keeps this branch's install refusal reasons (package_name_invalid, manifest_missing) in installed_methods.py; docs/tools/cli/agent-cli.md takes #1457's Markdown wording and keeps this branch's method.identifier_invalid item and params facts, and nothing else is stale."
+reviewed_at = "2026-10-19T11:41:17Z"
+rationale = "clean-pass: merging #1458's head (Runner-problem-params, 9578055b3) into this branch, whose own _run_hosted.py and bundle_cmd.py changes are the triggers, keeps both edits to docs/tools/cli/agent-cli.md, #1458's validate-bundle verdict paragraph and this branch's run-on-a-runner paragraph, which touch different passages; pipelex/cli/agent_cli/CLAUDE.md, which #1458 did not change, still describes the hosted caller-view refusals as this branch wrote them, and nothing else under docs/tools/cli/ is stale."
[trigger_files]
"pipelex/cli/__init__.py" = "blob:8b137891791fe96927ad78e64b0aad7bded08bdc"
@@ -38,9 +38,9 @@ rationale = "clean-pass: absorbing Runner-speaks-problem, which carries pipelex#
"pipelex/cli/agent_cli/commands/run/__init__.py" = "blob:e69de29bb2d1d6434b8b29ae775ad8c2e48c5391"
"pipelex/cli/agent_cli/commands/run/_output_helpers.py" = "blob:40ed1700e0d5e86d7696eadd7f9887baeb8059f6"
"pipelex/cli/agent_cli/commands/run/_run_core.py" = "blob:d71aee873856cfa72eb0ff18eb82c79e348f124a"
-"pipelex/cli/agent_cli/commands/run/_run_hosted.py" = "blob:cd2b8dda59e076f1023d3b20d7c239b3674c3f2e"
+"pipelex/cli/agent_cli/commands/run/_run_hosted.py" = "blob:8d2e819c44d5669756e931b9f3fc83741d54a1df"
"pipelex/cli/agent_cli/commands/run/app.py" = "blob:7546d9b31ea2dc22b1ddae538edfbc8e7f7d08df"
-"pipelex/cli/agent_cli/commands/run/bundle_cmd.py" = "blob:e8976dd91908262d8d7d5bf2d2e4e11c978a3f3b"
+"pipelex/cli/agent_cli/commands/run/bundle_cmd.py" = "blob:fd02137f1286cb4293cdc5dc2b03c31d5c87454b"
"pipelex/cli/agent_cli/commands/run/method_cmd.py" = "blob:0df77aa1e35c22ceffdcefd7f4c12f28fda366c7"
"pipelex/cli/agent_cli/commands/run/pipe_cmd.py" = "blob:1a5a2f86ac80fb86cb53376202bad05ffd19e9f6"
"pipelex/cli/agent_cli/commands/run/stdin_resolver.py" = "blob:db0176d7de1e074fd6eefd787c10e71b891eeb32"
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ef6eb7b28..e3a5c6be8 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -46,7 +46,7 @@
- **A truncated completion says which limit cut it**: `LLMCompletionTruncatedError` carries `model.output_truncated` when the method's `max_tokens` cut the answer and `model.context_exceeded` when the context window did, both the method's to change.
- **`ModelDeckPresetValidationError` is spelt right (Breaking)**: the error a model deck preset that fails validation raises was `ModelDeckPresetValidatonError`, and its reports carried that `error_type`; a consumer that branched on the old name branches on the new one, or on its code, `pipelex.config.invalid`.
- **Usage statistics carry the error's code (Breaking)**: a failed `command_completed` or `run_completed` carries the code of its error in `error_code` and that code's domain in `error_domain`, now one of `input`, `method`, `account`, `operator` and `runtime` where it read `input`, `config`, `runtime` or `other`, and a `model_used` counts its failed calls by the domain of their code, in `failures_input`, `failures_method`, `failures_account`, `failures_operator` and `failures_runtime`, where it counted them by the runtime's inference category, which no event carries any more. A failed hosted run's `command_completed` carries the code and the domain the hosted API sent, and none when it sent none, and every surface reads a refusal a server answered by that rule, a run's `run_completed` reading the catch-all where nothing was sent rather than the code the client infers from the status. Every event's `schema` is 2, so a receiver tells these events from an earlier release's.
-- **`pipelex-agent` reports a failure as its problem (Breaking)**: the agent CLI's error stream is the failure's problem in the operator's view, Markdown by default and JSON with `--error-format json`: its `code`, `domain`, `retry` verdict and `next_step`, its `params`, `location` and `errors`, its `request_id` and `pipeline_run_id`, and `diagnostics` with the error's class, the model and the provider of a failed call and a pending configuration migration, which rides `diagnostics.migration` where it rode `migration`, beside the command's own `message` and members. The envelope's `error`, `error_type`, `error_domain`, `error_code`, `error_category`, `retryable`, `hint`, `validation_errors`, `error_source`, and a failed run's `pipe_code`, `pipe_stack`, `cause_type` and `cause_message`, are gone, and so are `AGENT_ERROR_HINTS`, `AGENT_ERROR_DOMAINS`, `AGENT_INIT_FAILURE_HINT`, `run_failure_fields()` and `extract_validation_errors()`: an agent branches on `code`, an invalid verdict's items are the problem's `errors`, a failed run is located by `location.pipe` and `location.path`, and the advice an error's chain gives is a Markdown tip, a boot that fails with no advice of its own tipping the recovery path through `doctor`, `migrate` and `init`. A refusal the CLI makes itself carries its own code, `client.argument_invalid` for an argument, `client.file_unreadable` for a file it cannot read, the bundle file of every bundle command included, `client.tool_missing` when `plxt` is not installed, and `pipelex.config.file_missing` when `init` finds a configuration file it should have written missing, and an exception that is no Pipelex error reads `runtime.unexpected`, an error of the system that names no file, such as a refused connection or a timeout, included. A bundle file that is not UTF-8 text does not parse, so `run bundle` and `fix bundle` report it as `validate bundle` does, the invalid verdict with a `method.syntax` item, where `run bundle` read it as a file it could not read; `fix bundle` codes the errors left as `validate bundle` codes them, where an item no stage classified read `method.schema_violation`, and a fix it cannot write is `client.write_failed`. The Markdown lists the problem's items one per line, each with its code, sentence, location, suggestions and suggested fix, an invalid verdict's included, where it rendered a verdict's items as `validate`'s category-grouped prose. A run on a runner (`--runner hosted`) that fails reports the problem the runner answered or the client decided, as it came, by the members the standard and Pipelex declare alone, in the caller's view: the runner's problem document with its `errors`, `client.unreachable` naming the base URL for a runner that cannot be reached, `client.outcome_unknown` for a server fault on the run request, and `run.failed` naming the run for a run that started and failed, the client's own sentence as `message`, nesting the run's own problem as `run_error` in the caller's view, read off its stored report whatever its shape; an answer in the shape that predates the standard's reads as the core code its status and the hosted plane's own code name, `auth.invalid_credential`, `auth.missing_credential` when no key was sent, `auth.forbidden` for an operation the platform refuses a key it accepted, under one of its authorization codes, `request.not_found`, `run.not_found` or `method.not_found`, or `account.rate_limited` with its `retry_after`, a runner's refusal of a method that does not validate lists its validation items under `method.invalid`, and any other such answer keeps the client's `client.response_unreadable` with the reason it gave; each takes the next step `pipelex run --hosted` gives, of the kind the answer's advice names when it gave one, and so does a failure the client meets on its own side; what the CLI refuses before sending it is a problem in the operator's view, and so is a failure of its own, under its own code.
+- **`pipelex-agent` reports a failure as its problem (Breaking)**: the agent CLI's error stream is the failure's problem in the operator's view, Markdown by default and JSON with `--error-format json`: its `code`, `domain`, `retry` verdict and `next_step`, its `params`, `location` and `errors`, its `request_id` and `pipeline_run_id`, and `diagnostics` with the error's class, the model and the provider of a failed call and a pending configuration migration, which rides `diagnostics.migration` where it rode `migration`, beside the command's own `message` and members. The envelope's `error`, `error_type`, `error_domain`, `error_code`, `error_category`, `retryable`, `hint`, `validation_errors`, `error_source`, and a failed run's `pipe_code`, `pipe_stack`, `cause_type` and `cause_message`, are gone, and so are `AGENT_ERROR_HINTS`, `AGENT_ERROR_DOMAINS`, `AGENT_INIT_FAILURE_HINT`, `run_failure_fields()` and `extract_validation_errors()`: an agent branches on `code`, an invalid verdict's items are the problem's `errors`, a failed run is located by `location.pipe` and `location.path`, and the advice an error's chain gives is a Markdown tip, a boot that fails with no advice of its own tipping the recovery path through `doctor`, `migrate` and `init`. A refusal the CLI makes itself carries its own code, `client.argument_invalid` for an argument, `client.file_unreadable` for a file it cannot read, the bundle file of every bundle command included, `client.tool_missing` when `plxt` is not installed, and `pipelex.config.file_missing` when `init` finds a configuration file it should have written missing, and an exception that is no Pipelex error reads `runtime.unexpected`, an error of the system that names no file, such as a refused connection or a timeout, included. A bundle file that is not UTF-8 text does not parse, so `run bundle` and `fix bundle` report it as `validate bundle` does, the invalid verdict with a `method.syntax` item, where `run bundle` read it as a file it could not read; `fix bundle` codes the errors left as `validate bundle` codes them, where an item no stage classified read `method.schema_violation`, and a fix it cannot write is `client.write_failed`. The Markdown lists the problem's items one per line, each with its code, sentence, location, suggestions and suggested fix, an invalid verdict's included, where it rendered a verdict's items as `validate`'s category-grouped prose. A run on a runner (`--runner hosted`) that fails reports the problem the runner answered or the client decided, as it came, by the members the standard and Pipelex declare alone, in the caller's view: the runner's problem document with its `errors`, `client.unreachable` naming the base URL for a runner that cannot be reached, `client.outcome_unknown` for a server fault on the run request, and `run.failed` naming the run for a run that started and failed, the client's own sentence as `message`, nesting the run's own problem as `run_error` in the caller's view, read off its stored report whatever its shape; an answer in the shape that predates the standard's reads as the core code its status and the hosted plane's own code name, `auth.invalid_credential`, `auth.missing_credential` when no key was sent, `auth.forbidden` for an operation the platform refuses a key it accepted, under one of its authorization codes, `request.not_found`, `run.not_found` or `method.not_found`, or `account.rate_limited` with its `retry_after`, a runner's refusal of a method that does not validate lists its validation items under `method.invalid`, and any other such answer keeps the client's `client.response_unreadable` with the reason it gave; each takes the next step `pipelex run --hosted` gives, of the kind the answer's advice names when it gave one, and so does a failure the client meets on its own side; what the CLI refuses before sending it is a problem in the operator's view, and so is a failure of its own, under its own code, except a method `run bundle` refuses while reading it, a bundle that does not parse or validate or a bundle file or folder with no pipe to start at, which reads in the caller's view as the runner's refusal of the same method would, with its code, items, locations and next step and neither `diagnostics` nor `message`.
- **The `pipelex` error panels print the problem**: a panel names the problem's title, its detail, its next step, its code with its domain and retry verdict, its location and its request id beside the fields it printed, and a run that fails, or any failure a command root catches, prints its problem the same way on stderr, where it printed one line with the message. Every panel, an invalid bundle's, an unavailable model's or a telemetry file's included, and the stack trace `--traceback` adds to it, now goes to stderr, where the panels and their stack traces went to stdout, so a command's piped output holds only what it produced.
- **A configuration refusal names its setting and its file**: `pipelex.config.invalid` raised for a configuration that does not validate, a telemetry configuration, a tracing sink or what a former release left in the inference configuration names the setting, its file and the configuration it belongs to in the operator's next step, a file the refusal can single out, a former release's or one that does not parse (`pipelex.config.syntax`, where `pipelex show config` named `pipelex.toml` whichever layer failed), named relative to the working directory or as `~/…` under the home directory, never with the home directory's account, and its advice, the tip a CLI prints, follows the pending migration, `pipelex migrate` when it would rewrite the files and a correction by hand when it would not, and else the refusal's code: `pipelex init` for a missing file, setting the variable for one that is not set, and `pipelex doctor` for a configuration that does not validate or parse. The refusal of what a former release left carries in `diagnostics.migration` what `pipelex migrate` would do about it, from the cleanup's dry run, so a JSON reader, who gets no tip, reads the remedy too.
- **A pipe's failure line carries its code, not its text**: `The execution of a pipe failed` carries the problem's `error.code` beside `error.type` and no longer `error.message`, so a log query selects failed pipes by code, and the line holds neither the caller's own text, a function's message or a template's source, nor a refused host.
diff --git a/docs/tools/cli/agent-cli.md b/docs/tools/cli/agent-cli.md
index ccc0e3ae6..f5dd40b36 100644
--- a/docs/tools/cli/agent-cli.md
+++ b/docs/tools/cli/agent-cli.md
@@ -228,7 +228,7 @@ In Markdown, the default, the problem reads as a `## <title>` heading, the detai
**A failed run** (`run pipe`, `run bundle`, `run method`) reports the problem of the root fault, the innermost Pipelex error behind the failure, located at the pipe that failed: `location.pipe` names it and `location.path` its path from the entry pipe. The `message` is that root fault's message prefixed with the failing pipe and its path (`Pipe 'summarize' failed (two_steps → summarize): …`), and the code, the domain, the retry verdict and the next step are the root fault's, so branch on `code` to tell, say, a model that is not available from a failure to combine a parallel's results. A failed inference call carries its model and its provider in `diagnostics.model` and `diagnostics.provider`.
-**A run on a runner** (`--runner hosted`, on the hosted Pipelex API or on the runner `--base-url` names) that fails reports the problem the runner answered or the client decided, as it came, in the caller's view, since the runner is someone else's runtime: no `diagnostics`, and the next step the runner gave its caller. It is Markdown by default and JSON with `--error-format json`, like any other failure. What this CLI refuses before anything is sent, a `--runner` that contradicts `--hosted`, a `--base-url` on a local run, a local-only flag, a configuration that cannot be read, is a problem like any local refusal, in the operator's view. The failures of the run itself read as follows.
+**A run on a runner** (`--runner hosted`, on the hosted Pipelex API or on the runner `--base-url` names) that fails reports the problem the runner answered or the client decided, as it came, in the caller's view, since the runner is someone else's runtime: no `diagnostics`, and the next step the runner gave its caller. It is Markdown by default and JSON with `--error-format json`, like any other failure. What this CLI refuses before anything is sent, a `--runner` that contradicts `--hosted`, a `--base-url` on a local run, a local-only flag, a configuration that cannot be read, is a problem like any local refusal, in the operator's view. The method itself is the exception: `run bundle` reads its bundle before it sends it, and a bundle that does not parse or does not validate (`method.invalid`, its faults in `errors`, each with its file and its place in it), or a bundle file or folder with no pipe to start at (`request.pipe_unspecified`, its `params.candidates` the pipes it could start at), is refused then, in the caller's view, as the runner would refuse the same method: no `diagnostics` and no `message`, so no class name and none of the text only an operator reads, while the code, the items, their locations and the next step stay. A run on this machine reports the same refusal in the operator's view, with the command's own sentence. The failures of the run itself read as follows.
- **A run the runner refuses** reports the runner's problem document by the members the standard and Pipelex declare: its `code`, `domain`, `retry`, `next_step`, `params`, `location`, its `errors` items, each with its `code`, `detail`, `params`, `location`, `suggestions` and `suggested_fix`, its `status` and its `request_id`, which is what to quote when the fault is the runner's. A member no reader declares, at any level, such as the `error_type`, `error_domain` and `retryable` a runner's own refusals may still carry, is left out, and so is a member of Pipelex's (`request_id`, `run_error`) in a shape this version does not read, alone, so the problem around it is still reported. An answer that carries `diagnostics`, which a runner answers only to its operator, is projected onto the caller's view, its next step re-aimed at the caller, and so is the run's problem an answer nests as `run_error`, which is the run's stored record, whatever view the answer around it is in. A run that failed at a pipe is located there, `location.pipe` and `location.path`. A method refused before any pipe ran is `method.invalid`, its faults in `errors`.
- **A refusal the hosted plane answers in its own shape**, which predates the standard's problem document, reads as the core code its status and the plane's own `code` name, with the plane's own `detail`, its `request_id` and the next step `pipelex run --hosted` gives: `auth.missing_credential` for a `401` or a `403` when no key was sent, telling how to get one with `pipelex login`; `auth.invalid_credential` for a `401`, and for the bare `403` the hosted API's edge answers without a reason, an unknown key among its causes, telling to run `pipelex login` or correct `PIPELEX_API_KEY`; `auth.forbidden` for a `403` the platform answers with one of its authorization codes, `forbidden` or `role_not_permitted`, for a key it accepted and an operation that key may not do, while a `403` with any other code, such as one for a key that expired, is `auth.invalid_credential`; `run.not_found` or `method.not_found` for a `404` whose code names the run or the method's version, and `request.not_found` for any other, telling to check the method's address and the origin; and `account.rate_limited` for a `429`, with `retry: yes` and the delay its `Retry-After` header or its body states as `retry_after`.
diff --git a/docs/under-the-hood/error-model.md b/docs/under-the-hood/error-model.md
index 9af56919f..3580ea96e 100644
--- a/docs/under-the-hood/error-model.md
+++ b/docs/under-the-hood/error-model.md
@@ -497,7 +497,7 @@ A refusal is reported once per process, however many of these boundaries it cros
### CLI
-The agent CLI (`pipelex-agent`) reports a failure on **stderr** as its problem in the operator's view, markdown by default and JSON with `--error-format json`: the problem document's members, `code`, `domain`, `retry`, `next_step`, `params`, `location`, `errors`, `request_id`, `pipeline_run_id` and `diagnostics` (a pending configuration migration in `diagnostics.migration`), and beside them the command's own `message` and members. The error format is the command's `--error-format`, else the program's `--error-format` given before the command, else the command's `--format` (so `--format json` still flips both as it did before the split), else JSON. The Markdown reads the same problem as a `## <title>` heading, the detail, the next step, the advice the error's chain gives as a `💡` tip, the code with its domain and verdict, the location, the faults one per line with their code, sentence, location, suggestions and suggested fix, and the diagnostics. A refusal the command makes itself is coded too, `client.argument_invalid`, `client.file_unreadable` or `client.tool_missing`, and an exception that is no Pipelex error is `runtime.unexpected`. A run on a runner (`--runner hosted`) that fails reports the problem the runner answered or the client decided (`exc.problem`), as it came, by its declared members alone, in the caller's view: the runner's own problem document with its items, `client.unreachable` for a runner that cannot be reached, `client.outcome_unknown` for a server fault on the run request, `run.failed` for a run that started and failed; an answer in a shape that predates the standard's reads as the core code its status and the hosted plane's own code name (`auth.invalid_credential`, `auth.missing_credential`, `auth.forbidden`, `request.not_found`, `run.not_found`, `method.not_found`, `account.rate_limited`), lists its validation items under `method.invalid`, or keeps the client's `client.response_unreadable` with the reason it gave, with the next step the human CLI gives, as does a failure the client meets on its own side; a failed run's own problem rides as `run_error` in the caller's view, a stored report in the former shape included; the refusals this CLI makes before anything is sent stay in the operator's view.
+The agent CLI (`pipelex-agent`) reports a failure on **stderr** as its problem in the operator's view, markdown by default and JSON with `--error-format json`: the problem document's members, `code`, `domain`, `retry`, `next_step`, `params`, `location`, `errors`, `request_id`, `pipeline_run_id` and `diagnostics` (a pending configuration migration in `diagnostics.migration`), and beside them the command's own `message` and members. The error format is the command's `--error-format`, else the program's `--error-format` given before the command, else the command's `--format` (so `--format json` still flips both as it did before the split), else JSON. The Markdown reads the same problem as a `## <title>` heading, the detail, the next step, the advice the error's chain gives as a `💡` tip, the code with its domain and verdict, the location, the faults one per line with their code, sentence, location, suggestions and suggested fix, and the diagnostics. A refusal the command makes itself is coded too, `client.argument_invalid`, `client.file_unreadable` or `client.tool_missing`, and an exception that is no Pipelex error is `runtime.unexpected`. A run on a runner (`--runner hosted`) that fails reports the problem the runner answered or the client decided (`exc.problem`), as it came, by its declared members alone, in the caller's view: the runner's own problem document with its items, `client.unreachable` for a runner that cannot be reached, `client.outcome_unknown` for a server fault on the run request, `run.failed` for a run that started and failed; an answer in a shape that predates the standard's reads as the core code its status and the hosted plane's own code name (`auth.invalid_credential`, `auth.missing_credential`, `auth.forbidden`, `request.not_found`, `run.not_found`, `method.not_found`, `account.rate_limited`), lists its validation items under `method.invalid`, or keeps the client's `client.response_unreadable` with the reason it gave, with the next step the human CLI gives, as does a failure the client meets on its own side; a failed run's own problem rides as `run_error` in the caller's view, a stored report in the former shape included; the refusals this CLI makes before anything is sent stay in the operator's view, except a refusal of the method it would send, a bundle that does not parse or validate or a bundle file or folder with no pipe to start at, which is the refusal the runner would answer for it and reads in the caller's view.
| Command | Error output |
|---------|--------------|
diff --git a/pipelex/cli/agent_cli/CLAUDE.md b/pipelex/cli/agent_cli/CLAUDE.md
index 1240b147d..a3f1fb7b3 100644
--- a/pipelex/cli/agent_cli/CLAUDE.md
+++ b/pipelex/cli/agent_cli/CLAUDE.md
@@ -105,9 +105,9 @@ commands/
- **Async core**: Run and validate are async — commands use `asyncio.run()`.
- **File convention**: Generated outputs go to `mthds-wip/` with incremental naming (`pipeline_01/`, `pipeline_02/`). A `run` writes into a new numbered folder, `results/<pipe_code>_output_<NN>/`, made by `make_run_output_folder` (`pipelex/cli/commands/run/_run_output_folder.py`) beside the bundle it ran, else under `mthds-wip/`; the folder holds a `.gitignore` of `*`, so a run's outputs never join the method tree and two runs read the same tree, with the same `method_tree_digest`. `run_pipeline_core`'s `output_dir_override` replaces the directory the folder is made under: `run method` on a fetched target (a method address or GitHub URL) passes `results/` under the caller's CWD, since the fetched clone is an ephemeral temp dir deleted at process exit, and `run bundle <folder> --pipe` passes the folder's `results/`, having no entry bundle to write beside.
- **Validate refusals of the method are verdicts**: the `validate` commands run their library load inside `translate_to_validate_bundle_error` (`pipelex/pipeline/validate_bundle_translation.py`), so every refusal raised while loading a bundle whose code is in the `method` domain, the unknown model (`PipeOperatorModelChoiceError`, an `unknown_model` item) included, reaches the command as a `ValidateBundleError` and leaves with the invalid verdict's problem and exit 1. A refusal of another actor, the request's or the input's included, keeps its own class and code, and so does a dry run none of whose failures is the method's. No `validate` command keeps an arm of its own for a model-choice error; exit 2 stays for a failure of the tool or its environment (config, runtime, security).
-- **Run refusals are verdicts too**: a run loads its bundle inside the same translation (`acquire_library`), so an invalid bundle leaves `run pipe` / `run bundle` / `run method` as a `ValidateBundleError` with exit 1, through the generic `agent_error` arm, and its problem (`method.invalid`) carries the verdict's items as `errors`, and the Markdown lists the same errors one per line, so both formats list the one problem's errors and a foreign exception raised while handling an earlier verdict lists none of its items. `run_pipeline_core` sets `library_dirs_are_callers=True`, so a refusal in a `-L` directory (or the bundle's own directory) is the same verdict; `run bundle`'s own parse of a bundle without `--pipe` goes through the translation too, and so does its reading of the method tree: a folder resolves through `pipelex/cli/bundle_target_resolution.py` (`resolve_method_folder_run`, the protocol's entry rule in `pipelex/pipeline/method_entry.py`) and a lone file through `list_bundle_file_tree`, listed before the file is read, so a tree past its limits, a symbolic link or a special file such as a FIFO is a `ValidateBundleError` too, refused unread, and a bundle file the listing cannot read is `client.file_unreadable`, while a folder with no single `main_pipe` is the run's own refusal, a `MethodEntryError` coded `request.pipe_unspecified` or `request.pipe_ambiguous`, no verdict on a method that may be valid. So no `run` command keeps an arm of its own for a model-choice error either: an unknown model reaches it as the verdict's `unknown_model` item.
+- **Run refusals are verdicts too**: a run loads its bundle inside the same translation (`acquire_library`), so an invalid bundle leaves `run pipe` / `run bundle` / `run method` as a `ValidateBundleError` with exit 1, through the generic `agent_error` arm (`run bundle`'s own reading of its bundle through `agent_error_method_refusal()`, in the caller's view on a runner), and its problem (`method.invalid`) carries the verdict's items as `errors`, and the Markdown lists the same errors one per line, so both formats list the one problem's errors and a foreign exception raised while handling an earlier verdict lists none of its items. `run_pipeline_core` sets `library_dirs_are_callers=True`, so a refusal in a `-L` directory (or the bundle's own directory) is the same verdict; `run bundle`'s own parse of a bundle without `--pipe` goes through the translation too, and so does its reading of the method tree: a folder resolves through `pipelex/cli/bundle_target_resolution.py` (`resolve_method_folder_run`, the protocol's entry rule in `pipelex/pipeline/method_entry.py`) and a lone file through `list_bundle_file_tree`, listed before the file is read, so a tree past its limits, a symbolic link or a special file such as a FIFO is a `ValidateBundleError` too, refused unread, and a bundle file the listing cannot read is `client.file_unreadable`, while a folder with no single `main_pipe` is the run's own refusal, a `MethodEntryError` coded `request.pipe_unspecified` or `request.pipe_ambiguous`, no verdict on a method that may be valid. So no `run` command keeps an arm of its own for a model-choice error either: an unknown model reaches it as the verdict's `unknown_model` item.
- **Two readings of a folder, one resolution path**: `run bundle`, `validate bundle`, `fix bundle` and `inputs bundle` read a folder through `pipelex/cli/bundle_target_resolution.py` (`run` through `resolve_method_folder_run`, the others through `resolve_bundle_target_core`, validate and fix by way of `pipelex/cli/judged_target.py`, whose `JudgedBundleTarget.judged_path` is the path the verdict names and whose `fix_judged_target` is the one fix dispatch both CLIs call, and of `commands/bundle_path_resolver.py`), as its method tree, but with the `FolderReading` their job asks for. `validate` and `fix` take `WHOLE_TREE`, the MTHDS protocol's validation (`mthds/docs/spec/protocol.md`): every bundle of the tree is judged (`validate_bundle(method_dir=..., library_dirs_are_callers=True)`, `fix_method_folder`), with no pipe to start at, so a folder whose bundles declare several `main_pipe`s, or none, is validated like any other; mthds-js's local runner calls `pipelex validate bundle <dir>` to validate a whole method at install and relies on this. `--pipe` there only narrows the dry run, and `--graph` / `--view` draw from the pipe named, else from the entry (`locate_folder_pipe`), or, when the folder decides none, put `graph_unavailable` in the envelope and leave the verdict alone. `run` and `inputs` take `ENTRY_PIPE`, acting on one pipe: the one `--pipe` names, else the protocol's entry (`select_method_entry` in `pipelex/pipeline/method_entry.py`); no single `main_pipe` is the `MethodEntryError` with exit 1 on both, coded `request.pipe_unspecified` or `request.pipe_ambiguous`, the message the same, and no verdict on a method that may be valid. A folder holding no bundle is `EmptyMethodTreeError` with exit 2 on `validate` and `fix`, and a `MethodEntryError` saying it has no pipe to start at on the others, each problem coded `method.invalid`. A folder whose tree is refused at resolution (past its limits, a symbolic link) is the invalid verdict: `ValidateBundleError` on `validate`, and on `fix` the still-invalid `method.invalid` problem of a fix that could not start (`unfixable_method_result`, through `agent_error_fix_bundle`), exit 1 both. A fix of a folder writes anywhere in its method tree, from the root (`method_tree_root`) down, and the human `--diff` preview mirrors that root, so a fix landing in a bundle above the folder named is proposed and written alike. Only the tree's own pipes are judged: `validate_bundle(method_dir=...)` keeps the blueprints its tree lists (`_is_member_blueprint`), so a nested package, a dependency or a `-L` directory loads without being judged; `dirs_beside_method` is the one place the `-L` directories naming the folder itself are dropped, compared resolved. Reading the tree's limits loads the configuration before the boot, so each resolution site catches `PipelexConfigError` and reports it through `report_agent_init_failure` (`agent_cli_factory.py`), the problem a failed boot gives.
-- **Hosted runs**: every `run` subcommand takes `--runner local|hosted`, `--hosted/--local` and `--base-url`; `resolve_agent_run_execution()` (`run/_run_hosted.py`) settles them through `pipelex.hosted.execution.resolve_run_execution` (the flag, then `[run] execution`, then local), refusing a `--runner` that contradicts the flag pair and a `--base-url` on a local run as `client.argument_invalid` problems; a configuration that cannot be read there reports its own problem, as a failed boot does (`agent_cli_factory.py`). Every refusal made before anything is sent is a problem in the operator's view; what the run itself fails with is the problem the runner or the client produced, in the caller's view (below). A hosted run boots nothing: it builds a `HostedRunRequest` from what `pipelex/cli/commands/run/_hosted_sources.py` resolves (the bundle and its library's `.mthds` files, a pipe's library, or a method's files; an address or a catalog id as `method_ref` / `method_id`, never fetched) and `run_hosted_for_agent()` runs it through `pipelex.hosted.hosted_run.run_hosted`, which reads the signature and uploads local input files (only when some input string names an existing local file, so a method with an address-based dependency runs with any other inputs), then drives the lifecycle `start_and_wait` drives step by step (the `/v1/version` handshake, `start`, `wait_for_result`, and the blocking `execute` on a server with no run store), so a failure while following an acknowledged run is a `HostedRunPollingError` naming the run, and a transport failure after the run request was sent is a `HostedRunOutcomeUnknownError` rather than an `ApiUnreachableError`. `run_hosted`'s `on_started` callback records the acknowledged run's id, so Ctrl-C (`KeyboardInterrupt`, or the `CancelledError` of a cancelled task) leaves as the problem of a `HostedRunInterruptedError`, `client.follow_failed` carrying `pipeline_run_id` once the run was acknowledged and `client.outcome_unknown` before, with exit code 130. `run bundle` on a file with no `-L` sends `PIPELEXPATH`'s files (`hosted_library_dirs`), and an installed method named like a catalog id is that method. An exception no hosted arm names is this process's own failure and leaves through the command-boundary catch-all as a local run's does, in the operator's view: a Pipelex error under its own code, any other exception as `runtime.unexpected`. Its success envelope is `build_run_output()`'s, with the main output's content as `json`, an empty `markdown`, the working memory dump and `pipeline_run_id`; nothing is written to disk. `--dry-run` / `--mock-inputs` are refused on it, while `--graph` and `--costs` are accepted and ignored. There is no global `--runner` any more, and no `ctx.obj`.
+- **Hosted runs**: every `run` subcommand takes `--runner local|hosted`, `--hosted/--local` and `--base-url`; `resolve_agent_run_execution()` (`run/_run_hosted.py`) settles them through `pipelex.hosted.execution.resolve_run_execution` (the flag, then `[run] execution`, then local), refusing a `--runner` that contradicts the flag pair and a `--base-url` on a local run as `client.argument_invalid` problems; a configuration that cannot be read there reports its own problem, as a failed boot does (`agent_cli_factory.py`). Every refusal made before anything is sent is a problem in the operator's view, except a refusal of the method the run would send; what the run itself fails with is the problem the runner or the client produced, in the caller's view (below). `run bundle` reads its bundle before it runs it, wherever it runs, so it settles where the run executes first (`resolve_agent_run_execution()`, then `refuse_local_only_flags()`), and reports a bundle that does not parse or validate (`ValidateBundleError`) or a bundle file or folder with no pipe to start at (`MethodEntryError`, `request.pipe_unspecified`, which a lone file with no `main_pipe` raises too, naming its pipes as `candidates`) through `agent_error_method_refusal()` (`run/_run_hosted.py`): on this machine's runtime through `agent_error`, in the operator's view with the command's sentence; on a runner as the refusal the runner would answer for the same method, `to_problem(view=ProblemView.CALLER)` printed through `agent_error_problem()`, with no `diagnostics` and no `message`, since both carry the raise site's classes and text, the items, their locations, the caller's step and the Markdown tip kept. A hosted run boots nothing: it builds a `HostedRunRequest` from what `pipelex/cli/commands/run/_hosted_sources.py` resolves (the bundle and its library's `.mthds` files, a pipe's library, or a method's files; an address or a catalog id as `method_ref` / `method_id`, never fetched) and `run_hosted_for_agent()` runs it through `pipelex.hosted.hosted_run.run_hosted`, which reads the signature and uploads local input files (only when some input string names an existing local file, so a method with an address-based dependency runs with any other inputs), then drives the lifecycle `start_and_wait` drives step by step (the `/v1/version` handshake, `start`, `wait_for_result`, and the blocking `execute` on a server with no run store), so a failure while following an acknowledged run is a `HostedRunPollingError` naming the run, and a transport failure after the run request was sent is a `HostedRunOutcomeUnknownError` rather than an `ApiUnreachableError`. `run_hosted`'s `on_started` callback records the acknowledged run's id, so Ctrl-C (`KeyboardInterrupt`, or the `CancelledError` of a cancelled task) leaves as the problem of a `HostedRunInterruptedError`, `client.follow_failed` carrying `pipeline_run_id` once the run was acknowledged and `client.outcome_unknown` before, with exit code 130. `run bundle` on a file with no `-L` sends `PIPELEXPATH`'s files (`hosted_library_dirs`), and an installed method named like a catalog id is that method. An exception no hosted arm names is this process's own failure and leaves through the command-boundary catch-all as a local run's does, in the operator's view: a Pipelex error under its own code, any other exception as `runtime.unexpected`. Its success envelope is `build_run_output()`'s, with the main output's content as `json`, an empty `markdown`, the working memory dump and `pipeline_run_id`; nothing is written to disk. `--dry-run` / `--mock-inputs` are refused on it, while `--graph` and `--costs` are accepted and ignored. There is no global `--runner` any more, and no `ctx.obj`.
- **A run on a runner that fails** reports the problem the runner or the client produced, in the caller's view, as it came: `agent_error_hosted()` (`run/_run_hosted.py`) builds it with `hosted_failure_problem()` and prints it through `agent_error_problem()` (`agent_output.py`), which neither rebuilds nor reclassifies it, in Markdown by default and JSON with `--error-format json`. A refusal the runner answered (pipelex-sdk's `ApiResponseError`), a runner that cannot be reached (`ApiUnreachableError`, `client.unreachable` naming `params.base_url`) and every other request error of pipelex-sdk or the MTHDS client carries the standard client's problem as `exc.problem`: the runner's own problem document when the answer is one, its `errors` items, its next step and its `request_id` included (`received_problem()`, which keeps only the members the standard and Pipelex declare, at every level, leaves out alone one of Pipelex's members that does not read, fills `request_id` from the answer when the document names none, and projects an answer carrying diagnostics onto the caller's view, deciding it from the document as it came, and a nested `run_error` always, since it is the run's stored record), else the code the client reads from the answer, such as `client.response_unreadable` naming the status, or `client.outcome_unknown` for an answer that leaves a run possibly started, which pipelex-sdk reads for every 5xx on the run request but a 501 and a 503 coded `pipeline_start_unavailable`, whatever the body. An answer in a shape that predates the standard's, which the client reads by its status alone, goes through `hosted_refusal_problem()` (`pipelex/hosted/error_rendering.py`): a refusal of the hosted plane reads as the core code its status and the plane's own `code` name, built by `make_problem` in the caller's view, `auth.missing_credential` for a `401` or `403` with no key sent (`HOSTED_MISSING_KEY_NEXT_STEP`), `auth.invalid_credential` for a `401` and for the edge's bare `403`, `auth.forbidden` for a `403` the platform codes with one of its authorization codes, `forbidden` or `role_not_permitted` (`HOSTED_FORBIDDEN_NEXT_STEP`), and `auth.invalid_credential` for a `403` with any other code, `run.not_found` or `method.not_found` for a `404` coded `run_not_found` or `method_version_not_found` and `request.not_found` for any other, `account.rate_limited` with its `retry_after` for a `429`, with the plane's own `detail` and the next step the human CLI gives (`HOSTED_REFUSAL_NEXT_STEPS_BY_STATUS`); a runner's own refusal in the former shape that lists validation items, the `422` of a method that does not validate on `/v1/start` or `/v1/execute`, is read first, by `_former_refusal_problem()` in `run/_run_hosted.py`, as `method.invalid` with those items, its reason, its advice and its status, through the builder a stored report in the same shape goes through (`_former_problem()`); any other such answer that gives its reason, a runner's own `422` for a reserved input key included, keeps the client's `client.response_unreadable`, read by the standard's members alone so a member beside them that does not read never stops it (`_client_reading()`), with that reason as its `detail` and the human CLI's step (`hosted_refusal_next_step()`), of the kind its advice names through `FORMER_ADVICE_KINDS` (`pipelex/hosted/error_rendering.py`), else `change_input` for a `4xx`; an answer that may have started a run keeps its `client.outcome_unknown`. A run that started and failed (`RunFailedError`) is `run.failed` naming the run and its status, with the client's sentence as `message`, which quotes the stored report's reason, and nests the run's own problem as `run_error`: a stored report that is a problem document is read as a runner's answer is, so a member it holds beside the problem is left out, and one in the former `RunErrorReport` shape is `method.invalid` with its validation items (`hosted_method_problem_items()`) or `runtime.unexpected`, its message, its advice (kind through `FORMER_ADVICE_KINDS`) and its `retryable` carried (`_former_run_problem()`). Markdown renders the nested problem with the head `render_problem_markdown` uses, one heading level down (`_problem_head_lines`). Every error of pipelex-sdk's own but an answer's refusal and an unreachable runner adds its sentence as `message`, since it says what its code's parameters cannot (how long the client waited, that a completed run delivered no main output), and every one but an answer's refusal and a failed run takes the next step the human CLI tailors for it (`tailored_next_step()`, the step `describe_hosted_error()` gives when it is not `HOSTED_RUN_REQUEST_NEXT_STEP`), keeping its code's kind. pipelex's own `HostedRunError`s report their problem in the caller's view with their sentence as `message` and their advice as the Markdown tip, `pipeline_run_id` included for `HostedRunPollingError` and `HostedRunInterruptedError`; a `HostedMethodInvalidError` lists pipe-io's items as `errors`, each coded as a local verdict codes it (`hosted_method_problem_items()`, through `validation_item_code` and `problem_item_of`, `method.schema_violation` with the item's sentence as its finding for an item of a type this version does not read, each item read by the fields this version declares, so a field it does not keeps nothing from being typed, and a declared field whose value it cannot read, such as a newer runner's fix, is left out alone, so the item keeps its type, its locators and its dependency facts), its file in `location.file`. Nothing of the envelope this CLI wrote before it reported problems is left (`error`, `error_type`, `error_source`, `hint`, `error_domain`, `retryable`, `error_code`, `http_status`, …), which `tests/unit/pipelex/cli/test_agent_output_drift.py` guards in the source and in the emitted document.
- **Method-reference failures**: the `run`/`validate`/`inputs` method commands call `resolve_method_target(..., raise_ref_errors=True)` and report the typed `MethodRefError` subclasses through `agent_error(...)` themselves, each with its own code (validate uses `exit_code=2`, its no-verdict convention) — the human CLI's red-text rendering stays in `resolve_method_target`'s default arm.
- **Usage statistics**: the root callback runs every command through `run_with_usage_stats` (`pipelex/cli/usage_stats_cli.py`) with surface `pipelex-agent`, which reads the switches before the command does anything and sends one `command_completed` when it ends. Stderr is a machine contract when the invocation's errors are JSON (the command's `--error-format json`, else the program's given before the command, else a presentation `--format json`, as `use_agent_cli_error_format` resolves it), so the anonymous-statistics notice is then neither printed nor recorded, though the events are still sent. `_emit_problem` notes the problem's code and domain as the command's error (`note_command_error(error=usage_stats_error_of_problem(...))`); a run on a runner notes its problem's code too, except a refusal a server answered, noted by the code and domain its body sent alone (`sent_usage_stats_error`) and not at all when it sent none, never by the client's reading of its status. `fmt` and `lint` start `plxt` with `PIPELEX_USAGE_STATS=0`, since the command's statistics are this CLI's own. There is no `usage-stats` group here: `pipelex usage-stats` serves both CLIs. The contract is `conformance/specs/usage-statistics.md`; the user docs are `docs/setup/usage-statistics.md`.
diff --git a/pipelex/cli/agent_cli/commands/run/_run_hosted.py b/pipelex/cli/agent_cli/commands/run/_run_hosted.py
index cd2b8dda5..8d2e819c4 100644
--- a/pipelex/cli/agent_cli/commands/run/_run_hosted.py
+++ b/pipelex/cli/agent_cli/commands/run/_run_hosted.py
@@ -4,7 +4,10 @@ The run commands share this module for every step that differs from a local run:
flags, then `[run] execution`), the flags a hosted run refuses, the run itself through `pipelex.hosted`, the envelope
its result is reported in, and the problem its failure is reported as. Nothing here boots the local runtime.
-A refusal decided here, before anything is sent, is a problem like any local failure, in the operator's view. A failure
+A refusal decided here, before anything is sent, is a problem like any local failure, in the operator's view, except a
+refusal of the method the run would send, a bundle that does not parse or validate or a bundle file or folder with no
+pipe to start at: that is the refusal the runner would answer for the same method, and it is reported in the caller's view
+(:func:`agent_error_method_refusal`). A failure
of the run itself is the problem the runner answered or the client decided, in the caller's view, since the runner is
someone else's runtime: pipelex-sdk's errors and the MTHDS client's carry it, by its declared members alone, with the
next step the human CLI tailors for a failure of the client's own; an answer in a shape that predates the standard's
@@ -110,6 +113,29 @@ def refuse_local_only_flags(*, dry_run: bool, mock_inputs: bool) -> None:
)
+def agent_error_method_refusal(*, error: PipelexError, message: str, execution: RunExecution) -> NoReturn:
+ """Report a refusal of the method a run would start, found on this machine before the run, and exit 1.
+
+ A run reads its method before it starts it, wherever it executes: a bundle that does not parse or does not
+ validate, or a bundle file or folder with no pipe to start at, is refused then. On this machine's runtime that is a local
+ failure, reported in the operator's view with the command's own sentence (`message`). On a runner, the method is
+ refused before it is sent, and the refusal is the one the runner would answer its caller for the same method, so it
+ is reported as the runner's answer is, in the caller's view (:meth:`PipelexError.to_problem`): its code, its items
+ with their locations and fixes, and the caller's next step, with neither the operator's `diagnostics`, which name the
+ error's classes, nor the raise site's own message, which only an operator reads. The Markdown keeps the advice the
+ error gives as its tip.
+
+ Args:
+ error: The refusal: the invalid verdict, or the lack of a pipe to start at in a bundle file or folder.
+ message: The command's own sentence, which a local run reports beside the problem.
+ execution: Where the run executes.
+ """
+ if not execution.is_hosted:
+ agent_error(message, cause=error)
+ problem = error.to_problem(view=ProblemView.CALLER)
+ agent_error_problem(problem=problem, cause=error, noted_error=usage_stats_error(error=error))
+
+
#: The parts of a problem, each read against the model that declares its members, so that a member neither the standard
#: nor Pipelex declares is left out at every level. A problem's `params` and a fix's `ops` are the code's and the
#: operation's own and are kept whole; the nested `run_error` and Pipelex's other members are read apart.
diff --git a/pipelex/cli/agent_cli/commands/run/bundle_cmd.py b/pipelex/cli/agent_cli/commands/run/bundle_cmd.py
index e8976dd91..fd02137f1 100644
--- a/pipelex/cli/agent_cli/commands/run/bundle_cmd.py
+++ b/pipelex/cli/agent_cli/commands/run/bundle_cmd.py
@@ -9,7 +9,6 @@ from pathlib import Path
from typing import TYPE_CHECKING, Annotated, Any
import typer
-from mthds.protocol.problem.registry import CoreCode
from pipelex.base_exceptions import PipelexConfigError, iter_cause_chain
from pipelex.cli.agent_cli.commands.agent_cli_factory import make_pipelex_for_agent_cli, report_agent_init_failure
@@ -28,6 +27,7 @@ from pipelex.cli.agent_cli.commands.run._run_hosted import (
BASE_URL_OPTION_HELP,
HOSTED_OPTION_HELP,
RUNNER_OPTION_HELP,
+ agent_error_method_refusal,
refuse_local_only_flags,
resolve_agent_run_execution,
run_hosted_for_agent,
@@ -135,6 +135,12 @@ def run_bundle_cmd(
if mock_inputs and not dry_run:
agent_argument_error("--mock-inputs requires --dry-run", argument="--mock-inputs", reason="requires --dry-run")
+ # Where the run executes is settled before the method is read: a refusal of the method found while reading it is the
+ # one a runner would answer for it, and a run on a runner reports it as the runner would, in the caller's view.
+ execution = resolve_agent_run_execution(runner=runner, hosted=hosted, base_url=base_url)
+ if execution.is_hosted:
+ refuse_local_only_flags(dry_run=dry_run, mock_inputs=mock_inputs)
+
pipe_code: str | None = pipe
bundle_path: str | None = None
auto_inputs_dir: Path | None = None
@@ -153,10 +159,10 @@ def run_bundle_cmd(
try:
folder_run = resolve_method_folder_run(directory=target_path, pipe_override=pipe)
except ValidateBundleError as exc:
- agent_error(exc.message, cause=exc)
+ agent_error_method_refusal(error=exc, message=exc.message, execution=execution)
except MethodEntryError as exc:
# No pipe to start at is the run's refusal and no verdict: its problem carries its own code.
- agent_error(exc.message, cause=exc)
+ agent_error_method_refusal(error=exc, message=exc.message, execution=execution)
except PipelexConfigError as exc:
# Listing the tree reads its limits from the configuration, before the boot would.
report_agent_init_failure(error=exc)
@@ -207,7 +213,7 @@ def run_bundle_cmd(
agent_file_error(f"Bundle file not found: {missing}", path=missing, reason="not found", cause=read_error)
if read_error is not None:
agent_unreadable_file_error(error=read_error)
- agent_error(exc.message, cause=exc)
+ agent_error_method_refusal(error=exc, message=exc.message, execution=execution)
except PipelexConfigError as exc:
# Listing the tree reads its limits from the configuration, before the boot would.
report_agent_init_failure(error=exc)
@@ -229,23 +235,20 @@ def run_bundle_cmd(
bundle_blueprint = MthdsParser.make_pipelex_bundle_blueprint(mthds_content=mthds_content, mthds_source=bundle_path)
main_pipe_code = bundle_blueprint.main_pipe
if not main_pipe_code:
- agent_error(
- f"Bundle '{bundle_path}' does not declare a main_pipe. Specify a pipe code with --pipe.",
- code=CoreCode.REQUEST_PIPE_UNSPECIFIED,
- params={"candidates": sorted(bundle_blueprint.pipe or {})},
- )
+ # No pipe to start at, as a folder with no main_pipe has none: the same refusal, `request.pipe_unspecified`.
+ no_entry_msg = f"Bundle '{bundle_path}' does not declare a main_pipe. Specify a pipe code with --pipe."
+ no_entry = MethodEntryError(no_entry_msg).with_params(candidates=sorted(bundle_blueprint.pipe or {}))
+ agent_error_method_refusal(error=no_entry, message=no_entry_msg, execution=execution)
pipe_code = main_pipe_code
hosted_pipe_code = main_pipe_code
except ValidateBundleError as exc:
- agent_error(f"Failed to parse bundle '{bundle_path}': {exc.message}", cause=exc)
+ agent_error_method_refusal(error=exc, message=f"Failed to parse bundle '{bundle_path}': {exc.message}", execution=execution)
# Load inputs: --inputs flag takes priority, then stdin fallback, then auto-detected
parsed_inputs = parse_cli_inputs(inputs_arg=inputs, stdin_fallback=True, auto_inputs_dir=auto_inputs_dir)
pipeline_inputs: dict[str, Any] | None = parsed_inputs.pipeline_inputs
- execution = resolve_agent_run_execution(runner=runner, hosted=hosted, base_url=base_url)
if execution.is_hosted:
- refuse_local_only_flags(dry_run=dry_run, mock_inputs=mock_inputs)
# The bundle goes first, then the rest of the library a local run would load with it: -L, else PIPELEXPATH.
try:
bundle_files = collect_mthds_files(
diff --git a/tests/unit/pipelex/cli/agent_cli/test_data.py b/tests/unit/pipelex/cli/agent_cli/test_data.py
index eed362904..248f11495 100644
--- a/tests/unit/pipelex/cli/agent_cli/test_data.py
+++ b/tests/unit/pipelex/cli/agent_cli/test_data.py
@@ -533,3 +533,87 @@ class RunnerOwnMethodRefusals:
"validation_errors": HostedMethodItems.SENT[:2],
}
)
+
+
+class RefusedBundles:
+ """Bundles `run bundle` refuses while it reads them, before a run on a runner sends them.
+
+ Each case is its bundle, the codes of the verdict's items in order, and where each item places its fault beside
+ the file it names.
+ """
+
+ # A table header TOML cannot parse: the verdict's `method.syntax` item, at its line and column.
+ PARSE_FAILURE: ClassVar[str] = 'domain = "broken_syntax"\nmain_pipe = "say"\n\n[pipe.say\ntype = "PipeCompose"\n'
+ # A native concept redeclared, an input read but not declared, and an input declared but never read.
+ VALIDATION_FAILURE: ClassVar[str] = (
+ 'domain = "probe_invalid"\n'
+ 'description = "A method with several faults"\n'
+ 'main_pipe = "summarize"\n'
+ "\n"
+ "[concept.Rating]\n"
+ 'description = "A rating of a summary"\n'
+ "\n"
+ "[pipe.summarize]\n"
+ 'type = "PipeLLM"\n'
+ 'description = "Summarize the text"\n'
+ 'inputs = { text = "Text" }\n'
+ 'output = "Text"\n'
+ 'prompt = "Summarize $text in the style of $author."\n'
+ "\n"
+ "[pipe.rate]\n"
+ 'type = "PipeLLM"\n'
+ 'description = "Rate the summary"\n'
+ 'inputs = { summary = "Text", audience = "Text" }\n'
+ 'output = "Text"\n'
+ 'prompt = "Rate this summary from 1 to 10: $summary"\n'
+ )
+ # A template Jinja2 cannot parse, which the bundle's own validation refuses, so no run ever renders it.
+ TEMPLATE_REFUSAL: ClassVar[str] = (
+ 'domain = "broken_template"\n'
+ 'description = "A template that does not parse"\n'
+ 'main_pipe = "say"\n'
+ "\n"
+ "[pipe.say]\n"
+ 'type = "PipeCompose"\n'
+ 'description = "Say something"\n'
+ 'inputs = { topic = "Text" }\n'
+ 'output = "Text"\n'
+ 'template = "Talk about {{ topic[ }}"\n'
+ )
+ # A bundle that declares no main pipe: named alone, or as a folder's one bundle, it has no pipe to start at, and its
+ # one pipe, `say`, is what it could start at.
+ NO_MAIN_PIPE: ClassVar[str] = (
+ 'domain = "probe"\n'
+ "\n"
+ "[pipe.say]\n"
+ 'type = "PipeCompose"\n'
+ 'description = "Say"\n'
+ 'inputs = { topic = "Text" }\n'
+ 'output = "Text"\n'
+ 'template = "About $topic"\n'
+ )
+ CASES: ClassVar[list[tuple[str, str, list[str], list[dict[str, Any]]]]] = [
+ ("parse_failure", PARSE_FAILURE, ["method.syntax"], [{"line": 4, "column": 10}]),
+ (
+ "validation_failure",
+ VALIDATION_FAILURE,
+ ["method.name_conflict", "method.input_undeclared", "method.input_unused"],
+ [{"field": "concept.Rating"}, {"pipe": "summarize"}, {"pipe": "rate"}],
+ ),
+ ("template_refusal", TEMPLATE_REFUSAL, ["method.schema_violation"], [{"pipe": "say", "field": "pipe.say"}]),
+ ]
+ # What only the operator's view of these refusals holds, none of which a caller may read: the diagnostics' members,
+ # the classes along the refusal's chain, and the command's sentence quoting the raise site's message.
+ OPERATOR_ONLY: ClassVar[tuple[str, ...]] = (
+ "diagnostics",
+ "error_class",
+ "runtime_version",
+ "ValidateBundleError",
+ "MthdsParserError",
+ "MethodEntryError",
+ "ValidationError",
+ "TomlError",
+ "TOMLDecodeError",
+ "Jinja2TemplateSyntaxError",
+ "Failed to parse bundle",
+ )
diff --git a/tests/unit/pipelex/cli/agent_cli/test_run_hosted_method_refusal.py b/tests/unit/pipelex/cli/agent_cli/test_run_hosted_method_refusal.py
new file mode 100644
index 000000000..f09b0bba2
--- /dev/null
+++ b/tests/unit/pipelex/cli/agent_cli/test_run_hosted_method_refusal.py
@@ -0,0 +1,238 @@
+from __future__ import annotations
+
+import io
+import json
+from typing import TYPE_CHECKING, Any
+
+import pytest
+import typer
+
+from pipelex.cli.agent_cli.commands.agent_output import CliOutputFormat
+from pipelex.cli.agent_cli.commands.run.bundle_cmd import run_bundle_cmd
+from pipelex.hosted.client_factory import PIPELEX_API_KEY_ENV_KEY, PIPELEX_BASE_URL_ENV_KEY
+from pipelex.hosted.run_config import RunExecution
+from pipelex.system.usage_stats.usage_stats_contract import UsageStatsError, UsageStatsErrorDomain
+from tests.unit.pipelex.cli.agent_cli.test_data import RefusedBundles, RetiredEnvelope
+
+if TYPE_CHECKING:
+ from pathlib import Path
+ from unittest.mock import AsyncMock
+
+ from pytest_mock import MockerFixture
+
+AGENT_RUN_HOSTED_MODULE = "pipelex.cli.agent_cli.commands.run._run_hosted"
+AGENT_OUTPUT_MODULE = "pipelex.cli.agent_cli.commands.agent_output"
+#: The caller's step of `method.invalid`, the verdict's code.
+VERDICT_STEP: dict[str, str] = {"kind": "change_method", "detail": "Fix each fault the problem's errors list, then validate the method again."}
+
+
+def _assert_nothing_only_an_operator_reads(*, reported: str) -> None:
+ """No Pipelex class name, no member of the operator's view and no source path in what the caller reads."""
+ for operator_only in RefusedBundles.OPERATOR_ONLY:
+ assert operator_only not in reported, operator_only
+ assert ".py" not in reported
+
+
+def _item_entries(*, markdown: str) -> list[str]:
+ """The entries of the Markdown's `### Errors` section, one per item, each from its code to the next item.
+
+ An item's sentence may quote text on several lines, such as a template's source, so an entry is cut at the next
+ item's bullet rather than at the end of its first line.
+ """
+ errors_section = markdown.split("### Errors\n\n", 1)[1]
+ return [f"- `{entry}" if index_entry else entry for index_entry, entry in enumerate(errors_section.split("\n- `"))]
+
+
+def _write_bundle(*, directory: Path, source: str) -> Path:
+ bundle_path = directory / "bundle.mthds"
+ bundle_path.write_text(source, encoding="utf-8")
+ return bundle_path
+
+
+class TestRunHostedMethodRefusal:
+ @pytest.fixture(autouse=True)
+ def hosted_env(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv(PIPELEX_API_KEY_ENV_KEY, "plx_sk_test_not_a_secret")
+ monkeypatch.delenv(PIPELEX_BASE_URL_ENV_KEY, raising=False)
+ mock_stdin = io.StringIO("")
+ mock_stdin.isatty = lambda: True # type: ignore[assignment]
+ monkeypatch.setattr("sys.stdin", mock_stdin)
+
+ @pytest.fixture
+ def run_hosted(self, mocker: MockerFixture) -> AsyncMock:
+ """The run on the runner, which a method refused before it is sent never reaches."""
+ mocked: AsyncMock = mocker.patch(f"{AGENT_RUN_HOSTED_MODULE}.run_hosted", new=mocker.AsyncMock())
+ return mocked
+
+ @pytest.mark.parametrize(("case_id", "source", "item_codes", "item_places"), RefusedBundles.CASES, ids=[case[0] for case in RefusedBundles.CASES])
+ def test_json_is_the_caller_s_view_of_the_verdict(
+ self,
+ run_hosted: AsyncMock,
+ capsys: pytest.CaptureFixture[str],
+ tmp_path: Path,
+ case_id: str,
+ source: str,
+ item_codes: list[str],
+ item_places: list[dict[str, Any]],
+ ) -> None:
+ """The JSON keeps the code, the items with their places and the caller's step, and holds nothing only an operator reads."""
+ bundle_path = _write_bundle(directory=tmp_path, source=source)
+
+ with pytest.raises(typer.Exit) as exc_info:
+ run_bundle_cmd(path=str(bundle_path), inputs="{}", runner=RunExecution.HOSTED, error_format=CliOutputFormat.JSON)
+
+ assert exc_info.value.exit_code == 1, case_id
+ run_hosted.assert_not_awaited()
+ captured = capsys.readouterr()
+ assert not captured.out
+ problem = json.loads(captured.err)
+ assert problem["code"] == "method.invalid"
+ assert problem["domain"] == "method"
+ assert problem["retry"] == "no"
+ assert problem["next_step"] == VERDICT_STEP
+ assert [item["code"] for item in problem["errors"]] == item_codes
+ for item, place in zip(problem["errors"], item_places, strict=True):
+ assert item["location"] == {**place, "file": str(bundle_path)}
+ assert item["detail"]
+ assert "message" not in problem
+ for retired in RetiredEnvelope.MEMBERS:
+ assert retired not in problem
+ _assert_nothing_only_an_operator_reads(reported=captured.err)
+
+ @pytest.mark.parametrize(("case_id", "source", "item_codes", "item_places"), RefusedBundles.CASES, ids=[case[0] for case in RefusedBundles.CASES])
+ def test_markdown_is_the_caller_s_view_of_the_verdict(
+ self,
+ run_hosted: AsyncMock,
+ capsys: pytest.CaptureFixture[str],
+ tmp_path: Path,
+ case_id: str,
+ source: str,
+ item_codes: list[str],
+ item_places: list[dict[str, Any]],
+ ) -> None:
+ """The default Markdown lists the same items in their places, under the caller's step, with no Diagnostics section."""
+ bundle_path = _write_bundle(directory=tmp_path, source=source)
+
+ with pytest.raises(typer.Exit) as exc_info:
+ run_bundle_cmd(path=str(bundle_path), inputs="{}", runner=RunExecution.HOSTED)
+
+ assert exc_info.value.exit_code == 1, case_id
+ run_hosted.assert_not_awaited()
+ captured = capsys.readouterr()
+ assert not captured.out
+ markdown = captured.err
+ # The step follows the detail at once: the raise site's message, which the command quotes on a local run, is not
+ # the caller's to read.
+ assert markdown.startswith(
+ f"## The method does not validate\n\nThe method does not validate.\n\n**Next step** (`change_method`): {VERDICT_STEP['detail']}\n"
+ )
+ assert "- Code: `method.invalid` (domain method, retry no)" in markdown
+ entries = _item_entries(markdown=markdown)
+ assert [entry.split("`", 2)[1] for entry in entries] == item_codes
+ for entry, place in zip(entries, item_places, strict=True):
+ assert f"file '{bundle_path}'" in entry
+ if "pipe" in place:
+ assert f"pipe '{place['pipe']}'" in entry
+ if "line" in place:
+ assert f"line {place['line']}, column {place['column']}" in entry
+ assert "### Diagnostics" not in markdown
+ assert "Error class" not in markdown
+ _assert_nothing_only_an_operator_reads(reported=markdown)
+
+ def test_a_folder_with_no_pipe_to_start_at_reads_in_the_caller_s_view(
+ self, run_hosted: AsyncMock, capsys: pytest.CaptureFixture[str], tmp_path: Path
+ ) -> None:
+ """A method with no single main pipe is refused before it is sent, as the runner would refuse it, naming no class."""
+ _write_bundle(directory=tmp_path, source=RefusedBundles.NO_MAIN_PIPE)
+
+ with pytest.raises(typer.Exit) as exc_info:
+ run_bundle_cmd(path=str(tmp_path), inputs="{}", runner=RunExecution.HOSTED, error_format=CliOutputFormat.JSON)
+
+ assert exc_info.value.exit_code == 1
+ run_hosted.assert_not_awaited()
+ reported = capsys.readouterr().err
+ problem = json.loads(reported)
+ assert problem["code"] == "request.pipe_unspecified"
+ assert problem["next_step"]["kind"] == "change_input"
+ assert "message" not in problem
+ _assert_nothing_only_an_operator_reads(reported=reported)
+
+ @pytest.mark.parametrize("error_format", [CliOutputFormat.JSON, CliOutputFormat.MARKDOWN])
+ def test_a_bundle_file_with_no_main_pipe_reads_in_the_caller_s_view(
+ self, run_hosted: AsyncMock, capsys: pytest.CaptureFixture[str], tmp_path: Path, error_format: CliOutputFormat
+ ) -> None:
+ """A bundle file named alone with no main pipe is the folder's refusal: its candidates kept, no message, no path."""
+ bundle_path = _write_bundle(directory=tmp_path, source=RefusedBundles.NO_MAIN_PIPE)
+
+ with pytest.raises(typer.Exit) as exc_info:
+ run_bundle_cmd(path=str(bundle_path), inputs="{}", runner=RunExecution.HOSTED, error_format=error_format)
+
+ assert exc_info.value.exit_code == 1
+ run_hosted.assert_not_awaited()
+ captured = capsys.readouterr()
+ assert not captured.out
+ reported = captured.err
+ assert str(tmp_path) not in reported
+ assert "does not declare a main_pipe" not in reported
+ _assert_nothing_only_an_operator_reads(reported=reported)
+ match error_format:
+ case CliOutputFormat.JSON:
+ problem = json.loads(reported)
+ assert problem["code"] == "request.pipe_unspecified"
+ assert problem["domain"] == "input"
+ assert problem["next_step"]["kind"] == "change_input"
+ assert problem["params"] == {"candidates": ["say"]}
+ assert "message" not in problem
+ case CliOutputFormat.MARKDOWN:
+ assert reported.startswith(
+ "## No pipe is selected\n\n"
+ "The request selects no pipe, and the method gives no main pipe to start from.\n\n"
+ "**Next step** (`change_input`): "
+ )
+ assert "- Code: `request.pipe_unspecified` (domain input, retry no)" in reported
+ assert "### Diagnostics" not in reported
+
+ def test_a_bundle_file_with_no_main_pipe_run_locally_keeps_its_sentence(
+ self, run_hosted: AsyncMock, capsys: pytest.CaptureFixture[str], tmp_path: Path
+ ) -> None:
+ """On this machine's runtime the same refusal keeps its code, its candidates and the command's sentence naming the file."""
+ bundle_path = _write_bundle(directory=tmp_path, source=RefusedBundles.NO_MAIN_PIPE)
+
+ with pytest.raises(typer.Exit) as exc_info:
+ run_bundle_cmd(path=str(bundle_path), inputs="{}", runner=RunExecution.LOCAL, error_format=CliOutputFormat.JSON)
+
+ assert exc_info.value.exit_code == 1
+ run_hosted.assert_not_awaited()
+ problem = json.loads(capsys.readouterr().err)
+ assert problem["code"] == "request.pipe_unspecified"
+ assert problem["params"] == {"candidates": ["say"]}
+ assert problem["message"] == f"Bundle '{bundle_path}' does not declare a main_pipe. Specify a pipe code with --pipe."
+ assert problem["diagnostics"]["error_class"] == "MethodEntryError"
+
+ def test_the_statistics_record_the_verdict_s_code(
+ self, run_hosted: AsyncMock, mocker: MockerFixture, capsys: pytest.CaptureFixture[str], tmp_path: Path
+ ) -> None:
+ bundle_path = _write_bundle(directory=tmp_path, source=RefusedBundles.VALIDATION_FAILURE)
+ noted = mocker.patch(f"{AGENT_OUTPUT_MODULE}.note_command_error")
+
+ with pytest.raises(typer.Exit):
+ run_bundle_cmd(path=str(bundle_path), inputs="{}", runner=RunExecution.HOSTED, error_format=CliOutputFormat.JSON)
+
+ capsys.readouterr()
+ run_hosted.assert_not_awaited()
+ noted.assert_called_once_with(error=UsageStatsError(code="method.invalid", domain=UsageStatsErrorDomain.METHOD))
+
+ def test_a_local_run_keeps_the_operator_s_view(self, run_hosted: AsyncMock, capsys: pytest.CaptureFixture[str], tmp_path: Path) -> None:
+ """On this machine's runtime the same refusal is a local failure, with the operator's diagnostics and the command's sentence."""
+ bundle_path = _write_bundle(directory=tmp_path, source=RefusedBundles.PARSE_FAILURE)
+
+ with pytest.raises(typer.Exit) as exc_info:
+ run_bundle_cmd(path=str(bundle_path), inputs="{}", runner=RunExecution.LOCAL, error_format=CliOutputFormat.JSON)
+
+ assert exc_info.value.exit_code == 1
+ run_hosted.assert_not_awaited()
+ problem = json.loads(capsys.readouterr().err)
+ assert problem["code"] == "method.invalid"
+ assert [item["code"] for item in problem["errors"]] == ["method.syntax"]
+ assert problem["diagnostics"]["error_class"] == "ValidateBundleError"
+ assert problem["message"].startswith(f"Failed to parse bundle '{bundle_path}': ")