---
title: OpenFlange CLI Protocol
spec: openflange.org/cli/v0.1
version: 0.1.0-draft
status: experimental
updated: 2026-12-03
summary: How a runner executes a pipe as a local process — stdin/stdout for simple pipes, a configuration file and authenticated loopback endpoints for extra ports — and the command surface of the standalone openflange CLI.
---

# OpenFlange CLI Protocol v0.1

This specification defines how a runner executes an OpenFlange pipe as a local process: standard input and output carry the primary streams, standard error carries diagnostics, and the exit status reports the outcome. It also defines the configuration file and authenticated loopback HTTP endpoints used for additional ports, and the command surface of the standalone `openflange` runner.

This document is published at <https://openflange.org/cli/v0.1>. Its identifier, `openflange.org/cli/v0.1`, is that URL without the scheme, and is the value documents of this kind carry in `spec:`.

## At a glance

- **Identifier:** `openflange.org/cli/v0.1` — the value of `spec:` in documents of this kind
- **Published at:** <https://openflange.org/cli/v0.1> (raw Markdown: <https://openflange.org/cli/v0.1.md>)
- **Version:** 0.1.0-draft
- **Status:** experimental (feature maturity labels are listed in the document)
- **Updated:** 2026-12-03
- **JSON Schemas (2020-12):**
  - <https://openflange.org/schemas/cli-config-v0.1.schema.json>
  - <https://openflange.org/schemas/error-v0.1.schema.json>
- **Related specifications:**
  - Pipe: <https://openflange.org/pipe/v0.1>
  - Pipeline: <https://openflange.org/pipeline/v0.1>
  - HTTP Pipe Protocol: <https://openflange.org/http/v0.1>
  - Portable tests: <https://openflange.org/test/v0.1>
  - Lockfile: <https://openflange.org/lock/v0.1>

## Minimal example

A simple pipe is any program that reads NDJSON on standard input and
writes NDJSON on standard output; no OpenFlange software is involved:

```sh
printf '%s\n' '{"value":10}' '{"value":20}' '{"value":30}' | Rscript --vanilla summary.R
# {"count":3,"mean":20,"median":20,"sd":10}
```

The smallest configuration file a runner passes (through
`OPENFLANGE_CONFIG`) to such a process:

```json openflange:cli-config
{"spec": "openflange.org/cli/v0.1",
 "pipe": {"id": "r-summary", "version": "0.1.0"},
 "parameters": {},
 "inputs": {"records": {"enabled": true, "transport": "stdin", "mediaType": "application/x-ndjson"}},
 "outputs": {"summary": {"enabled": true, "transport": "stdout", "mediaType": "application/x-ndjson"}}}
```

## 1. Introduction

Most data tools already speak the simplest protocol there is: read standard
input, write standard output, complain on standard error, exit with a
status. The CLI protocol keeps that protocol intact for simple pipes —
`cat records.ndjson | Rscript transform.R | jq .` works with no OpenFlange
software involved — and adds the minimum needed for pipes with more than
one input or output: a configuration file naming the ports, and
authenticated loopback HTTP endpoints for the additional streams. **No
proprietary multiplexing is required for simple tools.**

This document has two parts:

- **Part I (sections 3–8)** — the protocol between a runner and an
  executable that implements a pipe (`implementation.type: executable`, and
  `script` in languages other than Starlark; see the
  [Pipe specification](https://openflange.org/pipe/v0.1)).
- **Part II (section 9)** — the command surface of the standalone runner,
  the `openflange` binary.

### 1.1 Conventions

The key words MUST, MUST NOT, REQUIRED, SHALL, SHALL NOT, SHOULD, SHOULD NOT,
RECOMMENDED, MAY and OPTIONAL are to be interpreted as described in RFC 2119
and RFC 8174 when, and only when, they appear in capitals.

Fenced examples whose info string contains `openflange:<kind>` are normative
and machine-checked against the schemas in [`schemas/`](https://openflange.org/schemas/); the
configuration file schema is
`https://openflange.org/schemas/cli-config-v0.1.schema.json`.

### 1.2 Citing this document

Normative statements are cited by **section number**, for example
`cli/v0.1 §4.2`, and numbered or bulleted rules within a section by their
position, for example `cli/v0.1 §4.2(3)`. Section numbers are stable
within v0.1: sections are appended, never renumbered. Every heading has a
stable fragment identifier derived from its text (lower-cased; characters
other than letters, digits, spaces, hyphens and underscores removed; spaces
replaced by hyphens), so a section is addressable as
`https://openflange.org/cli/v0.1#<fragment>`. Cross-references to other
OpenFlange specifications are absolute URLs of that form. This document
does not rely on images; its diagrams are text.

## 2. Terminology and maturity

The terms **pipe**, **source**, **sink**, **pipeline**, **subpipeline**,
**node**, **port**, **stream**, **run** and **dataset** are defined in the
[Pipe specification, section 2](https://openflange.org/pipe/v0.1#2-terminology); **workflow**
is reserved and not used here. In this document:

- **runner** — the process that starts and supervises the executable.
- **executable** — the child process implementing one node execution.
- **primary streams** — the ports bound to standard input and standard
  output.
- **additional ports** — enabled ports not bound to a standard stream.
- **endpoint** — a loopback HTTP URL, owned by the runner, for one
  additional port.

| Feature | Maturity |
|---|---|
| Simple pipes: stdin, stdout, stderr, exit status (3) | experimental |
| Parameters as environment variables (4) | experimental |
| Configuration file `OPENFLANGE_CONFIG` (5) | experimental |
| Additional ports over authenticated loopback HTTP (6) | experimental |
| Lifecycle, cancellation (7) and minimal environment (8) | experimental |
| `openflange` commands (9) | experimental (proposed interfaces; the binary's own help is authoritative for flags not listed here) |
| `windows` streams on any transport | proposed (window framing) |
| Usage reporting endpoint: `usage.url` in the configuration (5.3) | experimental |
| `windows` input in batch mode: one window frame is one item (5.1, 5.2) | proposed (window framing) |
| Batch framing: one JSON array per line, in both directions, for pipes in batch mode (5.1) | experimental (feature `batch`) |
| Batch files: `delivery: file`, long-running process or one process per batch (5.2) | experimental (feature `batch`) |

Nothing is `stable` or `deprecated` in v0.1.

# Part I — executing a pipe as a process

## 3. Simple pipes

A pipe with at most one input bound to standard input and at most one
output bound to standard output needs nothing else:

| Channel | Use |
|---|---|
| standard input | the input stream, in the port's negotiated media type (NDJSON by default) |
| standard output | the output stream |
| standard error | diagnostics only; never data |
| exit status | `0` = the node completed; non-zero = the node failed |

- End of input is end of file on standard input. End of output is the
  process closing standard output or exiting.
- A **source** reads no standard input; the runner provides an empty one.
- A **sink** writes no standard output; anything it writes there is treated
  as diagnostics, not data.
- An executable MAY exit with status 0 without having read all of its
  input (as `head` does). This is a normal completion; the runner discards
  the unread remainder for this node.
- An executable MUST write only stream data to standard output: no banners,
  prompts or progress output.
- A non-zero exit status, or death by signal, fails the node with
  `E_RUNTIME`; the runner records the status in the error `details`. Output
  already produced is not rolled back (Pipeline specification, section 8.7).
- Data on standard output that violates the stream format (for NDJSON: a
  blank line, invalid JSON) fails the node with `E_FORMAT`.

Which ports are bound to the standard streams is decided by the manifest.
An `executable` names them with `stdin` and `stdout`; by default the sole
input and the sole output are bound, and with several ports and no binding
none is bound to that stream (Pipe specification, section 8.4). A `script`
in `r`, `python` or `node` binds its first-declared input and its
first-declared output (Pipe specification, section 8.3); it has no `stdin` or
`stdout` key. Every other enabled port uses the loopback endpoints (6), and
the configuration file names each port's `transport` (5), so the binding is
never implicit to the program.

## 4. Parameters

Resolved parameters are passed in **two** ways, so that the simplest tools
can use the environment and richer ones a file:

1. as environment variables `OPENFLANGE_PARAM_<NAME>`;
2. in the `parameters` object of the configuration file (5).

**Variable names.** `<NAME>` is the parameter name converted to upper snake
case: an underscore is inserted between a lower-case letter or digit and a
following upper-case letter, and the result is upper-cased.
`preserveFirst` → `OPENFLANGE_PARAM_PRESERVE_FIRST`; `character` →
`OPENFLANGE_PARAM_CHARACTER`; `max_keys` → `OPENFLANGE_PARAM_MAX_KEYS`. A
manifest in which two parameters map to the same variable is invalid.

**Values.** A parameter of type `string` is passed verbatim. Every other
type is passed JSON-encoded (`3`, `true`, `[1,2]`, `{"a":1}`). A parameter
that has neither a value nor a default is not set. Parameters are immutable
for the lifetime of the process.

Secrets are not parameters; granted secrets arrive as environment variables
under their declared names (8).

## 5. Execution configuration

The runner describes the node execution in a JSON file and passes its path
in the environment variable **`OPENFLANGE_CONFIG`** — never on the command
line.

- The file MUST be created with mode `0600` (owner read/write only), in a
  directory not writable by other users, before the process starts, and
  MUST be removed by the runner after the process exits.
- The runner MUST always provide it, including for simple pipes, which are
  free to ignore it.
- An executable MUST ignore members it does not know.

```json openflange:cli-config
{"spec":"openflange.org/cli/v0.1",
 "pipe":{"id":"validate-email","version":"0.1.0"},
 "parameters":{},
 "inputs":{"records":{"enabled":true,"transport":"stdin","mediaType":"application/x-ndjson"},
           "lookup":{"enabled":true,"transport":"http","url":"http://127.0.0.1:41873/inputs/lookup","mediaType":"application/x-ndjson"}},
 "outputs":{"valid":{"enabled":true,"transport":"stdout","mediaType":"application/x-ndjson"},
            "rejected":{"enabled":true,"transport":"http","url":"http://127.0.0.1:41873/outputs/rejected","mediaType":"application/x-ndjson"},
            "stats":{"enabled":false}},
 "token":"<opaque, scoped to this node execution>"}
```

| Member | Meaning |
|---|---|
| `spec` | The constant `openflange.org/cli/v0.1`. |
| `pipe` | `id` and `version` of the pipe being executed. |
| `parameters` | Resolved parameters as JSON values (defaults applied). |
| `inputs`, `outputs` | One entry per **declared** port, keyed by port name. |
| `enabled` | Whether the port is part of this execution. The complete enabled-port set is therefore known before any data is processed. |
| `transport` | For an enabled port: `stdin` (inputs) or `stdout` (outputs) for the primary streams, `http` for an additional port. |
| `url` | For `http` transport: the endpoint. Always a loopback URL. |
| `mediaType` | The negotiated media type of the stream. |
| `token` | Opaque bearer token for the endpoints, scoped to this node execution. Present whenever any port uses `http`. |
| `batch` | Present exactly when the pipe runs in batch mode: `{"maxItems": <n>, "maxWaitMs": <n>, "delivery": "lines" \| "file"}` — the effective settings of this node execution (5.1) — and, with file delivery, `"dir"`: the absolute path of the directory that holds the batch files (5.2). |
| `usage` | OPTIONAL: `{"url": "<loopback URL>"}` — an endpoint for usage counters (5.3). |

A disabled port has `{"enabled": false}` and nothing else. An executable
MUST NOT attempt to use a disabled port and MUST work without it.

### 5.1 Batch framing

> **Maturity: experimental** (feature `batch`). This is the wire form of
> batch mode
> ([Pipe specification, section 5.7](https://openflange.org/pipe/v0.1#57-batch-mode);
> RFC 0003, `rfcs/0003-batch-mode.md` in the specification repository) for
> `executable` implementations and for `script` implementations in `r`,
> `python` and `node`. A runner that does not implement it MUST reject such
> a pipe with `E_UNSUPPORTED`; it MUST NOT run it unbatched.

When the manifest of the executed pipe declares `batch`, the runner forms
slices according to the delivery rule of the
[Pipeline specification, section 8.11](https://openflange.org/pipeline/v0.1#811-batch-mode)
and both directions of the process change from "one item per line" to
**one JSON array per line**. The media type is unchanged
(`application/x-ndjson`): every line is still exactly one JSON value.

**Input.** On the pipe's single input (standard input, unless the manifest
binds it elsewhere):

1. Each line is one slice: a JSON array of **1 to `maxItems` items**, in
   stream order. The runner never writes an empty array.
2. The runner writes a line when the slice is due under the delivery rule
   and **flushes it at once**; it does not hold a finished line back for
   more data. With `maxWaitMs: 1000` and a slow producer the executable
   therefore sees about one line per second; with a fast producer, lines of
   `maxItems` items as fast as it reads them.
3. End of input is end of file, as always.

On an input of kind `windows` (**proposed**, like window framing itself)
one **window frame** is one item: an input line is an array of 1 to
`maxItems` whole frames, a batch file has one frame per line, and
`maxItems` counts frames, not the items inside them. A window is never
split across batches, and a batch says nothing about windows.

**Answer.** On standard output:

4. The executable MUST answer **each input line with exactly one output
   line**, in order, and **every output line MUST be a JSON array**: the
   output items of that batch for the output port bound to standard
   output, possibly none (`[]`). The runner **flattens exactly one level**:
   the elements of the array are the output items, in order.
5. Because every line is a batch, there is no ambiguity about an item that
   is itself an array: the line `[[1,2,3]]` is one item, `[1,2,3]`; the
   line `[1,2,3]` is three items. A line that is not a JSON array fails the
   node with `E_FORMAT`.
6. **The answer line is the acknowledgement.** The runner writes the next
   input line only after it has read the answer to the previous one — one
   batch is in flight — and meanwhile accumulates the next batch itself
   (Pipeline specification, section 8.11); it does not use the operating
   system's pipe buffer as a queue. An output line that answers no input
   line, or the end of standard output while a batch is unanswered and the
   process exited with status 0, fails the node with `E_RUNTIME`.
7. With **`cardinality: one-to-one`** the answer MUST have **the same
   number of elements as the input line, in the same order**: its i-th
   element corresponds to the line's i-th item. Any other length is
   `E_RUNTIME`. Without it the answer may have any number of elements.
8. An executable MUST flush its output after each answer line; the runner
   cannot proceed on what is still in the executable's buffer.
9. If no output port is bound to standard output (a sink, or a pipe whose
   outputs all use additional ports), every answer is `[]`. An output of
   kind `text`, `binary` or `batches` MUST NOT be bound to standard output
   in batch mode (`E_MANIFEST`).

Additional output ports (6) are not affected: they carry ordinary streams,
one item per line. Record counters count items, never lines.

**Configuration.** `OPENFLANGE_CONFIG` carries
`"batch": {"maxItems": <n>, "maxWaitMs": <n>, "delivery": "lines"}` at
its top level, with the *effective* settings of the node execution,
exactly when the pipe runs in batch mode. That is how a program that supports both modes knows which one
it is in; a program written only for batch mode MAY ignore it.

```json openflange:cli-config
{"spec":"openflange.org/cli/v0.1",
 "pipe":{"id":"zscore","version":"0.1.0"},
 "parameters":{},
 "inputs":{"records":{"enabled":true,"transport":"stdin","mediaType":"application/x-ndjson"}},
 "outputs":{"records":{"enabled":true,"transport":"stdout","mediaType":"application/x-ndjson"}},
 "batch":{"maxItems":1000,"maxWaitMs":200,"delivery":"lines"}}
```

**Without a runner.** A batch-mode executable is still an ordinary Unix
filter; whoever runs it by hand feeds it array lines. In R, with
`jsonlite`, a vectorised pipe is three lines:

```r
# upper.R (one JSON array of strings per line in, one per line out)
library(jsonlite)
con <- file("stdin", open = "r")
while (length(line <- readLines(con, n = 1)) > 0) cat(toJSON(toupper(fromJSON(line))), "\n", sep = "")
```

```sh
printf '%s\n' '["a","b"]' '["c"]' | Rscript --vanilla upper.R
# ["A","B"]
# ["C"]
```

`toupper` is called once per slice on a character vector, not once per
record.

### 5.2 Batch files

> **Maturity: experimental** (feature `batch`). The second delivery mode of
> batch mode: the manifest declares `batch: {…, delivery: file}`
> ([Pipe specification, section 5.7](https://openflange.org/pipe/v0.1#57-batch-mode)).
> A runner that does not implement it MUST reject such a pipe with
> `E_UNSUPPORTED`.

With `delivery: file` the runner stores each batch in a file and gives the
program the file's path. It suits large batches and tools that read files
anyway. Slices are formed by the same delivery rule
([Pipeline specification, section 8.11](https://openflange.org/pipeline/v0.1#811-batch-mode)).

**The files.**

1. A batch input file is **plain NDJSON: one item per line** (not an array
   per line), UTF-8, every line terminated by a line feed, in stream
   order. Any tool that reads NDJSON reads it. Other file formats (CSV,
   Arrow, Parquet) are not part of v0.1.
2. A batch output file has the same format: the output items of the batch
   for the output port bound to standard output, in order; an empty file
   for no output. The runner validates it like any NDJSON stream — a blank
   line or invalid JSON is `E_FORMAT` — and bounds its size by a
   configurable limit (`E_RESOURCE` beyond it).
3. The runner owns a **directory per node execution**, created under the
   system's temporary directory (`TMPDIR`) with a random name and mode
   `0700`; files in it have mode `0600`. Its absolute path contains no
   whitespace, quote or shell metacharacters. A runner that cannot arrange
   that — the temporary directory is missing, not writable, or its path
   has such characters — MUST refuse to run with `E_UNSUPPORTED` before
   any data is read, and SHOULD say which directory it tried and how to
   choose another (for example `TMPDIR=/tmp`). File names are chosen by
   the runner.
4. The runner writes the input file of the *accumulating* batch while the
   batch in flight is being processed, so that handing a batch over is
   handing over a path. It deletes a batch's files once its output has
   been consumed, and removes the directory when the node execution ends —
   on completion, on failure and on cancellation. At most three batch
   files exist at a time: input and output of the batch in flight, input
   of the accumulating batch. A runner SHOULD NOT also keep in memory the
   items it has written to a batch file: with file delivery the bound of
   the delivery rule is then a bound on disk space, and the runner's
   memory does not grow with `maxItems`.
5. The program may read its input files and create its output files in
   that directory by virtue of this protocol; no `filesystem` permission
   is declared or granted for it (11).
6. With `cardinality: one-to-one` the output file MUST have exactly as
   many items as the input file (`E_RUNTIME` otherwise). Counters count
   items and bytes as for any stream.

`OPENFLANGE_CONFIG` carries `"batch": {"maxItems": <n>, "maxWaitMs": <n>,
"delivery": "file", "dir": "<absolute path>"}`.

How the path reaches the program depends on how `command` is written.

**A. One process per batch (placeholders).** If any element of `command`
contains `{batch.input}`, the runner starts the command **once per batch**:

7. In every element of `command`, `{batch.input}` is replaced by the
   absolute path of the batch's input file and `{batch.output}` by the
   path where the output file is expected. This is plain text substitution
   inside the element; no shell is involved and nothing else is
   substituted. `{{` stands for a literal `{`. Any other
   `{batch.<name>}` is an error of the manifest (`E_MANIFEST`), as are
   placeholders without `delivery: file`, `{batch.output}` without
   `{batch.input}`, and a placeholder in `command[0]`.
8. Standard input is empty. The process is given the same environment and
   configuration file as any executable (5, 8).
9. If `command` uses `{batch.output}`, the program writes its output to
   that path and MUST NOT write to standard output (`E_PROTOCOL` if it
   does); the output file MUST exist when the process exits (`E_RUNTIME`
   otherwise). If `command` does not use `{batch.output}`, the program's
   standard output is the batch's output, as plain NDJSON.
10. Exit status 0 means the batch is done; any other status fails the node
    (`E_RUNTIME`, 7). The next process is started as soon as the previous
    one has exited and the next batch is ready.

```yaml
batch: {maxItems: 50000, maxWaitMs: 1000, delivery: file}
implementation:
  type: executable
  command: ["sh", "-c", "tr a-z A-Z < {batch.input} > {batch.output}"]
```

A process is started for every batch, so this form suits large batches;
with small ones the start-up cost dominates.

**B. A long-running process (path lines).** If `command` contains no
placeholder — and always for a `script` implementation — the process is
started once:

11. For each batch the runner writes **one line** to standard input:
    `{"input": "<absolute path>", "output": "<absolute path>", "items": <n>}`
    — the batch's input file, the path where its output file is expected,
    and the number of items in the input file. The executable MUST ignore
    members it does not know.
12. The program reads the input file, writes its output as NDJSON to the
    `output` path, and then **acknowledges** by writing exactly one line to
    standard output: `{"ok": true}`, optionally with `"usage": {…}`, a
    JSON object of usage counters for the run report. `{"ok": false,
    "error": "<message>"}` fails the node with `E_RUNTIME`. Any other line
    is `E_PROTOCOL`.
13. Only after the acknowledgement does the runner read the output file,
    delete the batch's files and send the next line: one batch is in
    flight. A missing output file is `E_RUNTIME`. If no output port is
    bound to standard output, the output file is not read.
14. End of file on standard input means that there are no more batches.

```json openflange:cli-config
{"spec":"openflange.org/cli/v0.1",
 "pipe":{"id":"tidy","version":"0.1.0"},
 "parameters":{},
 "inputs":{"records":{"enabled":true,"transport":"stdin","mediaType":"application/x-ndjson"}},
 "outputs":{"records":{"enabled":true,"transport":"stdout","mediaType":"application/x-ndjson"}},
 "batch":{"maxItems":50000,"maxWaitMs":1000,"delivery":"file","dir":"/tmp/openflange-node-8f3a1c/batch"}}
```

```r
# tidy.R: a long-running R process over batch files (requires jsonlite)
library(jsonlite)
con <- file("stdin", open = "r")
while (length(line <- readLines(con, n = 1)) > 0) {
  req <- fromJSON(line)
  df <- stream_in(file(req$input), verbose = FALSE)      # NDJSON file -> data frame
  df$name <- toupper(df$name)                            # vectorised
  stream_out(df, file(req$output), verbose = FALSE)
  cat('{"ok":true}\n'); flush(stdout())
}
```

**Batch boundaries are not semantic** in either form (Pipe specification,
section 5.7). A query or script that aggregates, ranks or sorts *across a
batch file* gives a different answer for every way the stream happens to
be cut; such work belongs in a `scope: dataset` pipe or behind a window.
Batch files are for row-wise work on many rows at once.

### 5.3 Usage reporting

> **Maturity: experimental.** A runner need not offer the endpoint; an
> executable MUST work without it.

Some executables know what a run cost — the tokens a language model
billed, the requests made to a paid service — and the run report has a
place for it (`usage`, Pipeline specification, section 10). The usage
endpoint lets an executable report such counters without mixing them into
its data or its diagnostics.

1. When the runner offers the endpoint, the configuration carries
   `"usage": {"url": "http://127.0.0.1:<port>/usage"}` and a `token`. The
   URL is always a loopback URL. The member is absent otherwise.
2. A runner that implements the endpoint MUST offer it to every executable
   that uses additional ports (6): the listener exists anyway. For an
   executable without additional ports it MUST offer it exactly when the
   manifest asks for it with **`usage: true`** in `implementation`
   (`executable`, and `script` in a language that runs as a subprocess),
   so that single-port pipes that report nothing do not pay for a
   listener. `usage: true` requires nothing of a runner that does not
   implement the endpoint: it runs the pipe without it.
3. The executable MAY `POST` to the URL at any time before it exits, any
   number of times, with `Authorization: Bearer <token>` and
   `Content-Type: application/json` or `application/x-ndjson`. The body is
   **one or more JSON objects** (concatenated or one per line), at most
   64 KiB in total, each with at most 64 members:

   ```json
   {"requests": 3, "inputTokens": 1200, "outputTokens": 340, "model": "example-1"}
   ```

   Member names are the executable's own. A **number** is a counter: the
   runner **adds** it to the value reported before under the same name. A
   **string** of at most 256 bytes is a label: the last value reported
   wins. Other value types are not allowed.
4. The runner answers `204` and merges the counters into the node's
   `usage` in the run report. Other answers: `401` without the right
   token, `405` for a method other than `POST`, `415` for another content
   type, `413` for a body over the limit, `400` for a body that is not as
   described in 3 (nothing of such a body is merged).
5. A report never fails the run: the runner MUST NOT fail a node because
   of a rejected report, and an executable MUST NOT treat a failed report
   as an error of its own. An executable SHOULD send one report at its
   end, or one per call it paid for; it SHOULD NOT send one per record.
6. The body is **not data and not a log**. A runner MUST NOT write it to
   its diagnostics, and an executable MUST NOT put prompts, record
   contents or secrets in it (Pipeline specification, section 10).

An executable that also wants to work with runners that lack the endpoint
MAY fall back to whatever that runner documents; the reference runner
reads one diagnostic line `usage {…}` on standard error at the end of the
run, and the acknowledgement of a batch file may carry `"usage"` (5.2).

## 6. Additional ports

### 6.1 Direction

For additional ports **the executable is the HTTP client and the runner is
the server**:

- the executable **GETs** each additional **input** — the response body is
  the stream;
- the executable **POSTs** each additional **output** — the request body is
  the stream.

This is the mirror image of the [HTTP Pipe Protocol](https://openflange.org/http/v0.1), where
a client POSTs inputs to a remote pipe and GETs its outputs: in both
protocols, the party that *has* the data sends it as a body.

### 6.2 Requests

Every request carries `Authorization: Bearer <token>`.

**Input.** `GET <url>` → `200 OK`, `Content-Type` = the port's media type,
streaming (chunked) body. End of the body is end of the stream.

**Output.** `POST <url>` with `Content-Type` = the port's media type and a
streaming (chunked) request body. End of the body is end of the stream; the
runner then replies `204 No Content`. The executable SHOULD send
`Expect: 100-continue` or simply start streaming; the runner MUST read the
body as it arrives and apply backpressure by not reading.

| Status | Condition |
|---|---|
| `200` / `204` | Input attached / output completed. |
| `401` | Missing or wrong token. |
| `404` | Unknown path, or the port is not enabled. |
| `405` | Wrong method for the port's direction. |
| `409` | The port already has an attachment: the runner accepts **exactly one attachment per port**. There is no reconnect in v0.1. |
| `415` | `Content-Type` of an output does not match the configured media type. |

Error responses carry a structured error object (Pipeline specification,
section 11) as `application/json`.

### 6.3 Endpoint lifecycle

The **runner owns the endpoint lifecycle**:

1. **Startup ordering.** The runner binds a listener on the loopback
   address `127.0.0.1` (or `::1`), on an ephemeral port, generates the
   token, writes the configuration file, and only then starts the process.
   The endpoints are ready before the first instruction of the executable
   runs; the executable need not retry.
2. The executable attaches its ports in any order, at any time, typically
   concurrently with reading standard input. A runner MUST NOT require a
   particular order and MUST NOT wait for one attachment before serving
   another.
3. An enabled additional **input** that is never attached is simply not
   read; when the process exits with status 0 the runner discards it, as
   for unread standard input. The runner SHOULD report a connected input
   that was never attached as a warning that names the port, so that a
   program which reads only standard input does not lose a stream
   unnoticed.
4. An enabled additional **output** that was never POSTed when the process
   exits with status 0 is an **empty, completed stream**.
5. An output whose request body ends abnormally (connection closed before
   the final chunk) is a failed stream; the node fails with `E_PROTOCOL`.
6. When the process exits, the runner closes the listener and every open
   connection, and removes the configuration file. The token is invalid
   from that moment.

The listener MUST NOT be reachable from other hosts. The token MUST be
unpredictable (at least 128 bits of entropy), MUST be scoped to one node
execution, and MUST NOT appear in argument vectors, logs, reports or error
messages.

## 7. Lifecycle and cancellation

1. The runner prepares endpoints and configuration (6.3), then starts the
   process with the argument vector from the manifest, **without a shell**,
   with the environment of section 8, and with the directory containing the
   manifest as working directory.
2. The node is `running` until the process has exited **and** all its
   enabled outputs have ended.
3. Exit status 0 with all streams well-formed → `completed`. Anything else
   → `failed` (`E_RUNTIME`, `E_FORMAT` or `E_PROTOCOL`).
4. **Cancellation.** To cancel, the runner sends `SIGTERM`, closes the
   process's standard input, and aborts the endpoint connections. If the
   process has not exited after a grace period of **5 seconds**, the runner
   sends `SIGKILL`. On platforms without these signals the runner uses the
   closest equivalent (terminate, then kill). The runner SHOULD place the
   executable in its own process group and signal the group, so that
   grandchildren do not outlive the run.
5. An executable SHOULD treat `SIGTERM` and a closed standard output
   (`EPIPE`) as a request to stop promptly, and SHOULD NOT report them as
   errors of its own.

Backpressure is the operating system's: the runner reads standard output
and the POST bodies only as fast as downstream consumers allow, and writes
standard input and the GET bodies only as fast as the executable reads.
An executable that writes one output while not reading an input can
therefore stall itself; multi-port executables SHOULD service their ports
concurrently.

## 8. Environment

The process receives a **minimal environment**, never the runner's own:

- `PATH`, `HOME`, `LANG`, `TMPDIR`;
- `OPENFLANGE_CONFIG` and the `OPENFLANGE_PARAM_*` variables;
- the literal `env` entries of the manifest's implementation;
- the variables named in a granted `environment` permission, with the
  runner's values;
- granted secrets, each under its declared name.

Nothing else — in particular no ambient credentials, tokens, database
connection strings or cloud configuration. A runner MUST NOT log the values
of secrets or of the token.

# Part II — the standalone runner

## 9. The `openflange` command

The standalone runner executes pipes and pipelines without any other
product. It deliberately contains no database management, no scheduler and
no cache management.

The commands below are the v0.1 surface. They are `experimental`: where
this section and the binary's built-in help disagree about a flag, that is
a defect to report.

| Command | Purpose |
|---|---|
| `openflange search <query>` | Search the configured registry index. |
| `openflange inspect <pipe>` | Show a pipe's contract: ports, parameters, permissions, implementation, maturity. |
| `openflange validate <pipe\|pipeline> [--plan] [--json]` | Compile without running; report every error; with `--plan` print the execution plan. |
| `openflange resolve` | Resolve references and create or complete `openflange.lock.yaml`. |
| `openflange update [ref]` | Re-resolve all references, or one. |
| `openflange run <pipe\|pipeline> [options]` | Execute. |
| `openflange serve <pipe\|pipeline\|dir> [--addr 127.0.0.1:8080] [--token …]` | Serve over the HTTP Pipe Protocol. |
| `openflange test <pipe\|dir>` | Run portable tests. |
| `openflange version [--capabilities]` | Print the version; with `--capabilities`, the supported spec versions, adapters, languages, standard pipes and features. |

`<pipe>` and `<pipeline>` are references as defined by the Pipeline
specification (a path to a directory, a manifest or a pipeline file; a
`std:` name; a registry reference; …).

### 9.1 `run`

```
openflange run <pipe|pipeline> [--locked]
    [--input name=path|-]... [--output name=path|-]...
    [--param k=v]... [--batch [node=]maxItems[,maxWaitMs]]...
    [--grant ...]... [--trusted] [--report path|-]
```

- **Default bindings.** If the target has exactly one external input and it
  is not bound by `--input`, it is bound to standard input. If it has
  exactly one external output and it is not bound by `--output`, it is
  bound to standard output. `-` names the corresponding standard stream
  explicitly. At most one input may be bound to standard input and one
  output to standard output.
- `--output name=path` creates the file, and any missing parent
  directories, before the run starts; an existing file is replaced. The
  same holds for `--report path`.
- Every **required** external input and output MUST end up bound; otherwise
  the command fails with a usage error. An unbound required output is not
  silently discarded. Unbound optional ports are disconnected.
- `--param k=v` sets a parameter of the target. For a parameter of type
  `string` the value is taken verbatim; for other types it is parsed as
  JSON.
- `--batch [<node>=]<maxItems>[,<maxWaitMs>]` (experimental, feature
  `batch`) **tightens** the batch settings of one consumer for this run.
  Without `<node>=`, or with `.=`, it applies to the target itself when the
  target is a pipe that declares batch mode; `<node>` names a node of a
  pipeline target (a path with `/` for a node inside a subpipeline). It is
  applied after the node's own `batch` settings and follows their rule
  ([Pipeline specification, section 3.8](https://openflange.org/pipeline/v0.1#38-node-batch-settings)):
  a value that would loosen what the pipe declares or the node sets, a
  node that does not exist, and a target or node that does not run in
  batch mode are `E_PARAM`. `,<maxWaitMs>` alone (an empty `maxItems`)
  tightens only the wait. The effective settings appear in the plan
  (`validate --plan` accepts the same option). `openflange test` accepts
  `--batch <maxItems>[,<maxWaitMs>]` and applies it to every test that
  pins no `batch` of its own and whose target declares batch mode
  (Test specification, section 3.4).
- `--locked` requires every reference to be present in the lockfile with
  matching integrity (`E_LOCK` otherwise) and forbids network resolution.
- `--grant` and `--trusted`: see 9.2.
- `--report path` writes the run report (Pipeline specification, section
  10) to a file; `--report -` writes it to **standard error**, after the
  diagnostics, because standard output may carry data.
- Diagnostics go to standard error. Standard output carries only the data
  of the output bound to it.
- On `SIGINT` or `SIGTERM` the runner cancels the run (Pipeline
  specification, section 8.8) and exits with status 1.

### 9.2 Grants

`--grant <key>[=<value>]` grants a permission to **every node of the run**,
in addition to the per-node `grants` of pipeline files. Keys mirror the
permission keys of the Pipe specification:

```
--grant subprocess
--grant network=api.example.com:443
--grant remoteData=api.example.com
--grant filesystem.read=./data
--grant filesystem.write=./out
--grant environment=HOME
--grant secrets=OPENAI_API_KEY
```

Relative paths resolve against the current directory. Anything a node
requires that is neither granted per node nor by `--grant` makes the run
fail before it starts, with `E_PERMISSION` (exit status 2).

`--trusted` is **explicit trusted mode**: it grants everything every node
declares or implies. The runner MUST print, on standard error, a notice
that trusted mode is active and that restrictions are **not
sandbox-enforced**. `--trusted` MUST NOT be implied by configuration files,
environment variables or the absence of a terminal.

`validate` accepts the same `--grant` and `--trusted` options, so that a
pipeline can be checked under the grants it will run with; without them,
`validate` reports `E_PERMISSION` for nodes that rely on run-level grants.

### 9.3 `validate`

Prints every error and warning as `code: message (location)` lines on
standard error, or, with `--json`, a JSON object
`{"valid": <bool>, "errors": [...], "warnings": [...], "plan": {...}}` on
standard output whose `errors` and `warnings` are structured errors and
whose `plan` is present with `--plan` when the target compiles. A manifest
target is validated as a pipe (including attribution and paths); a pipeline
target is compiled.

### 9.4 `serve`

Serves the target — one pipe, one pipeline, or every pipe in a directory —
with the [HTTP Pipe Protocol](https://openflange.org/http/v0.1). The default address is
loopback. If `--token` is given, every request must carry it as a bearer
token. Because command-line arguments are visible to other local users, a
runner SHOULD also accept the token from the environment variable
`OPENFLANGE_SERVE_TOKEN`, and operators SHOULD prefer that. Serving on a
non-loopback address without TLS termination in front and without a token
SHOULD be refused unless explicitly forced. Grants for served pipes are
given with `--grant`/`--trusted` at start-up; a client cannot widen them.

### 9.5 Registry selection

`--registry <url|path>` or the environment variable `OPENFLANGE_REGISTRY`
select the registry index used by `search`, `inspect`, `resolve` and
`update`. The default is `https://openflange.com/index.json`. Offline use with a local
index path is a supported, first-class mode, and no command other than
`search` and registry-reference resolution needs a registry at all.

### 9.6 Exit status

| Status | Meaning |
|---|---|
| `0` | Success: the run completed, the target is valid, all tests passed. |
| `1` | The run failed or was cancelled; at least one test failed. |
| `2` | Usage error or validation error (nothing was executed). |

### 9.7 Examples

```sh
openflange search email
openflange inspect ./pipes/lowercase
openflange validate ./pipeline.yaml --plan
openflange resolve
openflange update
printf '"Alice@Example.COM"\n' | openflange run ./pipeline.yaml --locked
# "a***e@example.com"
openflange run ./branching --input email=in.ndjson \
    --output masked=masked.ndjson --output normalized=- --report report.json
openflange serve ./pipeline.yaml
openflange test ./pipes/lowercase
```

## 10. Examples for implementers

A simple pipe needs no SDK. This R script is a complete `dataset`-scope
pipe (its manifest is in the Pipe specification, section 14.5):

```sh
printf '%s\n' '{"value":10}' '{"value":20}' '{"value":30}' | Rscript --vanilla summary.R
# {"count":3,"mean":20,"median":20,"sd":10}
```

A multi-port executable, in shell, for the configuration of section 5 —
`records` on stdin, `valid` on stdout, `rejected` POSTed to its endpoint:

```sh
#!/bin/sh
# Illustrative only: records containing "@" are valid.
url=$(jq -r '.outputs.rejected.url' "$OPENFLANGE_CONFIG")
auth="Authorization: Bearer $(jq -r '.token' "$OPENFLANGE_CONFIG")"
mkfifo rejected.fifo
curl -sS -X POST -H "$auth" -H 'Content-Type: application/x-ndjson' \
     -T rejected.fifo "$url" &
exec 3>rejected.fifo
while IFS= read -r line; do
  case "$line" in
    *@*) printf '%s\n' "$line" ;;
    *)   printf '%s\n' "$line" >&3 ;;
  esac
done
exec 3>&-
wait
```

The token is read from the file and passed to `curl` in a header variable;
a production tool would use `curl -H @file` or a library so that the token
is not visible in the process list.

## 11. Security considerations

- **A subprocess is not a sandbox.** The executable runs with the
  authority of the user running the runner. The minimal environment and the
  permission checks limit accidental exposure; they do not confine hostile
  code. A runner MUST require the `subprocess` grant, MUST NOT describe
  process execution as isolation, and in trusted mode MUST say that
  restrictions are not sandbox-enforced.
- **Enforce or refuse.** A runner that cannot enforce a declared
  restriction (for example a network destination list for a subprocess)
  MUST treat granting it as trusting the code, and say so; it MUST refuse
  to run when the grant is absent.
- **No shell.** Argument vectors are executed directly. Parameters and
  record data are never interpolated into a command line. The only
  substitution is that of `{batch.input}` and `{batch.output}` (5.2), by
  paths the runner generated itself.
- **Batch files.** The batch directory is created by the runner with mode
  `0700` and its files with `0600`; it holds record data, so it is removed
  however the node ends. Using it requires no `filesystem` grant — the
  protocol hands the program exactly that directory — and it confines
  nothing: the program can open whatever its user can. Output files are
  size-bounded (`E_RESOURCE`). Paths of batch files do not appear in run
  reports or error messages.
- **Secret leakage.** The token and secrets are never placed in argument
  vectors, logs, reports or error messages. The configuration file is
  `0600` and removed after exit. Ambient secrets are not inherited (8).
- **Loopback endpoints.** Bound to loopback only, protected by an
  unguessable per-execution token, one attachment per port, closed at
  exit. Other local users can reach a loopback port, which is why the token
  is mandatory even on loopback.
- **Path traversal.** `command[0]` and script paths are checked against
  the package root on the real path (Pipe specification, section 12);
  `--input`/`--output` paths are the invoker's own and are not restricted,
  but pipes never choose them.
- **Resource exhaustion.** Streams are bounded and back-pressured; the
  runner bounds line length and SHOULD support time limits (`E_TIMEOUT`).
  Cancellation always ends in `SIGKILL` if needed.
- **SSRF, redirects, lifecycle scripts, malicious manifests.** These arise
  when resolving and installing pipes, not in this protocol; see the
  Pipeline and Lockfile specifications. `openflange` never executes package
  lifecycle scripts.

## 12. Compatibility and versioning

- The protocol is identified by `openflange.org/cli/v0.1`, carried in the
  configuration file's `spec`. An executable written for the simple-pipe
  protocol of section 3 depends on nothing version-specific.
- Executables MUST ignore unknown configuration members and unknown
  `OPENFLANGE_*` variables; runners MUST NOT require executables to read
  the configuration file unless they use additional ports.
- While `experimental`, a later 0.x version MAY change the configuration
  format or the command surface, with a `CHANGELOG.md` entry.
- Exit statuses 0, 1 and 2 keep their meaning; further statuses may be
  added.

See `COMPATIBILITY.md` in the specification repository.

## 13. Deferred

Not part of v0.1: Unix-domain sockets or named pipes as an alternative
transport for additional ports; reconnecting to an endpoint; dynamic ports;
long-lived worker processes reused across node executions; batch files in
CSV, Arrow or Parquet; several batches in flight at once; **WASM**
executables; sandbox profiles; distributed scheduling; checkpointing;
event-time watermarks and session windows; a Windows-specific signalling
contract; scheduling, cache and database management commands.
