> For the complete documentation index, see [llms.txt](https://www.health-samurai.io/docs/interbox/llms.txt).
> Use it to discover all available pages before guessing URLs.

---
# 1.x API

These exports and stage descriptors belong to the 1.x pipeline DSL. They remain in `@health-samurai/interbox` for workspaces still on a 1.x engine: the 2.x engine does not run them and refuses to load a workspace that registers a 1.x pipeline or mapper. To move a workspace to 2.x, see [Upgrading from 1.x](../upgrade/from-1x.md). For the 2.x API, see [`@health-samurai/interbox`](index.md) and [`/builtins`](builtins.md).

## Root exports

The root exports the 1.x pipeline DSL: `pipeline`, `PipelineRegistry`, `defineMapper`,
`MapperRegistry`, `provenanceFor`, `defineSource`, `SourceRegistry`,
`definePreprocessor`, `PreprocessorRegistry`, `defineParser`, `ParserRegistry`,
`defineInboundTable`, `InboundTableRegistry`, their declaration and descriptor
types, and the payload helpers below. The 2.x engine loads only the
pipelines in `ChainRegistry`. A workspace that registers a pipeline with the
root's `pipeline()` or a mapper with `defineMapper` is refused: the 2.x engine
does not load it, and the failure names each one.

### Sources

On 1.x, a source you define with `defineSource` receives a `SourceContext`:
`writeBatch` to hand messages to the pipeline, `state` to remember what it has
already taken (the 1.x source's own store, not 2.0's
[pipeline state](step-context.md#state-definestate-and-ctxstate)), and
[`preprocess`](#preprocessing-what-a-source-read) to split or unpack bytes it
read. The source reads its input itself, from a directory, an HTTP endpoint or a
queue, with whatever client suits it. A source logs with `console`, like every
stage (see [Logging](index.md#logging)):

```ts
interface SourceContext<T> {
  writeBatch(batch: T[]): Promise<unknown>;
  state: SourceStateStore;
  preprocess(
    chain: readonly (ConfiguredPreprocessor | Preprocessor)[],
    items: AsyncIterable<PayloadItem> | readonly PayloadItem[],
    limits?: { maxInputBytes?: number; maxExpandedBytes?: number; maxItems?: number },
  ): AsyncIterable<PayloadItem>;
}
```

#### Preprocessing what a source read

`preprocess` runs a chain over items your source built. An entry is either a
descriptor or a plain function, and the two mix freely. A descriptor is the engine's built-in `unpack`, `hl7v2Batch` or `lines` from
[built-in preprocessors](#preprocessors), the same stages `sftpSource` runs, or
one you declared with [`definePreprocessor`](#defining-a-preprocessor). Entries run in the order you list
them:

```ts
type Preprocessor = (items: AsyncIterable<PayloadItem>) => AsyncIterable<PayloadItem>;

interface PayloadItem {
  name: string;
  body: PayloadBody;
}

interface PayloadBody {
  bytes(): Promise<Uint8Array>;             // reads the body once and keeps it
  stream(): ReadableStream<Uint8Array>;     // readable once, unless bytes() ran first
  readonly size?: number;
}

function bodyFromBytes(bytes: Uint8Array): PayloadBody;
function bodyFromStream(
  source: ReadableStream<Uint8Array>,
  size?: number,
  budget?: { charge(newlyAllocatedBytes: number): void },  // charged per chunk bytes() reads; a throw rejects bytes()
): PayloadBody;

class PayloadBodyConsumed extends Error {}  // name: "InterboxPayloadBodyConsumed"
```

- **The chain is checked on every call.** Each descriptor's config is
  validated the way the workspace load validates an `sftpSource` chain, and a
  type the engine does not know is refused by name. A refused chain throws
  from the `preprocess` call itself, before any item is read. A function entry
  is taken as it is.
- **Nothing is read until you iterate.** Items flow one at a time: the
  first record of a `lines` chain reaches you before the file has been read to
  the end. The chain runs once for each item you pass in, so everything it
  emits is counted against the item it came from.
- **What each item produces is capped.** `maxExpandedBytes` (default 16 MiB)
  bounds the bytes the chain finally emits for one item you passed in, and
  `maxItems` (default 10 000) the number of items. Both are counted outside the
  stages, on the chain's output only: an item as it is emitted, bytes as you
  read each body, through `bytes()` or `stream()`. A
  streaming chain gets no exemption, so `[lines()]` over a big file needs both raised. Over either
  cap the iteration throws `PayloadBudgetExceeded`, and the chain is not pulled
  again. A later step of the same iteration throws the same error.
- **Each item you pass in is bounded on its own when a stage holds it whole.**
  `unpack` and `hl7v2Batch` read an item into memory before they split it.
  `maxInputBytes` (default 16 MiB) is the most any one item you passed in may
  hold, counted as it is read, and past it the iteration throws
  `PayloadRejected` naming that item. The items are not summed: two 10 MiB
  files in one call both pass under the default. With an empty chain the items
  come back to you, and your own `bytes()` call on one is what throws. A chain
  that starts with `lines` never holds an item whole, so this bound never
  applies to it.
- **Stopping early releases what `preprocess` took.** Leave the loop with
  `break`, call the iterator's `return()`, or let an error end it, and every
  item body it took and did not read to the end is cancelled, so a stream you
  opened is released. An array is taken whole at the first step, so every item in it is covered. An
  async iterable is taken one item at a time: `preprocess` calls its
  `return()`, and items it had not yielded yet are never seen, so release
  those in the iterable's own `finally`. When the chain runs to its end,
  nothing is cancelled.
- **Read what you need inside the loop.** A cancelled body reads as zero
  bytes, with no error. With an empty chain the items you receive carry the
  bodies you passed in, so one kept past an early stop and read afterwards
  resolves to zero bytes. So does a body of your own whose `stream()` returns
  the same stream each time. A `bodyFromStream` body is not readable again
  once `preprocess` has taken it, early stop or not: its stream is gone, and
  reading it throws `PayloadBodyConsumed`.
- **A body is read once.** Calling `stream()` twice, or `stream()` while
  `bytes()` is reading, throws `PayloadBodyConsumed`. That is a bug in the code
  reading the body, not bad input, so `payloadErrorName` returns `undefined`
  for it.

Classify a failure with `payloadErrorName(err)`, never `instanceof`: your
workspace is bundled with its own copy of the SDK, so an error the engine's
stages raise is not an instance of the class your code imports.

#### Defining a preprocessor

```ts
import { definePreprocessor } from "@health-samurai/interbox";

interface PreprocessorDefinition<K extends string = string, Cfg = Record<string, unknown>> {
  readonly type: K;
  prepareConfig?(config: Record<string, unknown>): Record<string, unknown>;
  create(config: Cfg): Preprocessor;
}

function definePreprocessor<K extends string, Cfg extends Record<string, unknown> = Record<string, unknown>>(
  definition: PreprocessorDefinition<K, Cfg>,
): (config?: Cfg) => ConfiguredPreprocessor<K>;

const PreprocessorRegistry: {
  get(type: string): PreprocessorDefinition | undefined;
  getAll(): PreprocessorDefinition[];
  // plus register() and clear(), as on the other registries
};
```

A plain function is enough where your own source's code builds the chain.
A chain that comes from a source's config carries names instead, because a function cannot travel in a config. Such a chain is an `sftpSource` `preprocess` list, or a list in your own source's config, like `labDrop`'s below. `definePreprocessor`
registers the definition under its `type` and returns a factory. Calling it gives the `{ type, config }` descriptor that goes in the list, with the config you
passed, unchanged. Export `PreprocessorRegistry` from your workspace's
`src/index.ts`, as you do `MapperRegistry`, so the engine can resolve the type:

```ts
import { bodyFromBytes, definePreprocessor } from "@health-samurai/interbox";

export const stripNulls = definePreprocessor({
  type: "strip-nulls",
  prepareConfig: (config) => ({ replacement: " ", ...config }),
  create: (config) =>
    async function* (items) {
      const replacement = new TextEncoder().encode(String(config.replacement));
      for await (const item of items) {
        const bytes = await item.body.bytes();
        const out: number[] = [];
        for (const byte of bytes) {
          if (byte === 0) out.push(...replacement);
          else out.push(byte);
        }
        yield { name: item.name, body: bodyFromBytes(Uint8Array.from(out)) };
      }
    },
});

// in a pipeline: sftpSource({ ..., preprocess: [unpack(), stripNulls()] })
```

The engine runs `prepareConfig` when it loads the workspace, after `env()`
values are resolved, and a throw refuses the load, naming the source. An
`sftpSource` runs it only then, and turns the prepared config into the
function the chain runs with `create` once, when the source starts. A
`preprocess` call handed the descriptor runs `prepareConfig` again, on every
call, so a descriptor your own source passes to `ctx.preprocess` needs a
`prepareConfig` that accepts its own output. Throw from `prepareConfig` naming
the refused field, never its value.

A stage yields each item as soon as it has it, and needs no limits of its own:
the engine counts what the chain emits, and stops pulling it past `maxItems`
or `maxExpandedBytes`. What a stage holds in memory while it works on one item
is its own to bound: `unpack`'s `maxEntryBytes` and `lines`'s
`maxRecordBytes` are those bounds for the built-ins. Raise a refusal as one of the
payload errors (`PayloadRejected`, …) when the input cannot ingest as it
stands, so a source records it rather than retrying it.

#### Validating a chain at load

```ts
import { normalizePreprocessChain } from "@health-samurai/interbox/builtins";

function normalizePreprocessChain(raw: unknown): ConfiguredPreprocessor[];
```

Returns the chain with each stage's config prepared: a built-in's defaults
filled in, and a type you declared with `definePreprocessor` passed through its own
`prepareConfig`. It throws an `Error` naming the refused field, never its
value, or naming a stage type that is neither built in nor declared. A type you
declared under a built-in's name is prepared as yours, as the engine runs it.
Call it from your source's `prepareConfig` so a bad chain refuses the workspace
load instead of failing the first poll.

#### Example

A source that polls a local drop directory, reads each new file itself, and
runs it through the chain its config declares:

```ts
import { readdir, stat } from "node:fs/promises";
import { join } from "node:path";
import { bodyFromStream, defineSource, payloadErrorName } from "@health-samurai/interbox";
import { normalizePreprocessChain } from "@health-samurai/interbox/builtins";
import type { ConfiguredPreprocessor } from "@health-samurai/interbox/builtins";

interface LabDropConfig {
  dir: string;
  preprocess: ConfiguredPreprocessor[];   // e.g. [unpack({ entryPattern: "*.hl7" }), stripNulls(), hl7v2Batch()]
}

export const labDrop = defineSource<"lab-drop", LabDropConfig, string>({
  type: "lab-drop",
  kind: "pull",

  prepareConfig(config) {
    return { ...config, preprocess: normalizePreprocessChain(config.preprocess) };
  },

  async start(cfg, ctx) {
    return async () => {
      for (const name of await readdir(cfg.dir)) {
        const path = join(cfg.dir, name);
        const info = await stat(path);
        if (!info.isFile()) continue;
        const version = `${info.mtimeMs}:${info.size}`;
        if ((await ctx.state.get(name)) === version) continue;
        const root = { name, body: bodyFromStream(Bun.file(path).stream(), info.size) };
        const messages: string[] = [];
        try {
          for await (const item of ctx.preprocess(cfg.preprocess, [root])) {
            messages.push(new TextDecoder().decode(await item.body.bytes()));
          }
        } catch (err) {
          if (payloadErrorName(err) === undefined) throw err;
          console.error("file refused", { name, reason: payloadErrorName(err) });
          await ctx.state.set(name, version);
          continue;
        }
        await ctx.writeBatch(messages);
        await ctx.state.set(name, version);
      }
    };
  },
});
```

A file the chain refuses is recorded and never read again. Anything else
propagates and the next poll retries it.

The example has no stability gate: a file still being written upstream is
read as it stands, and read again once its size or modification time changes.
The built-in [`sftpSource`](#sftpsource-sftp-polling-source-read-only) waits for two listings to agree before
it reads a file.

## Stage descriptors

Import these from `@health-samurai/interbox/builtins`. On 1.x, a pipeline references a stage descriptor by value, and the engine resolves it by `type` at runtime.

### `mllpSource`: MLLP TCP listener source

```ts
interface MllpSourceConfig {
  host?: Str;
  port: Num;
}

const mllpSource: SourceDescriptor<"mllp", MllpSourceConfig>;
```

```ts
mllpSource({
  id: "mllp-default",
  port: env("MLLP_PORT"),
  parser: hl7v2Parser({ skipZSegments: false }),
});
```

### `sftpSource`: SFTP polling source (read-only)

{% hint style="warning" %}
**Breaking in 2.0.** The 2.0 engine does not run `sftpSource`. A 2.0 pipeline
reads SFTP with `fileDropSource({ transport: sftp({ … }) })` from
`@health-samurai/interbox/files`, where each file directly in `dir` is a
delivery of its own. See [`/files`](files.md) and the table below.
{% endhint %}

| 1.x `sftpSource` | 2.0 `fileDropSource` with `sftp()` |
|---|---|
| `id` | the pipeline's name |
| `parser` | steps after the source |
| `pattern` | a step that skips a file by its `file` attr |
| `pollIntervalMs` | `pollInterval` on `fileDropSource`, a duration such as `"30s"` |
| `timeoutMs`, `minFileAgeMs` | `timeout` and `minFileAge` on `sftp()`, durations |
| `maxFileBytes` (default 16 MiB) | `maxFileBytes` on `fileDropSource`, 64 MiB by default, as stored |
| `maxExpandedBytes`, `maxItems` | removed |
| `encoding` | an option of the step that splits the file (`csvRows()`, `hl7v2Batch()`); a file in another encoding can be stored with `codec: "bytes"` |
| `preprocess` | steps before the store, such as `unpack()` |
| files read oldest modification time first | files read in delivery order |

```ts
interface SftpSourceConfig {
  host: Str;
  port?: Num;
  username: Str;
  password?: Str;
  privateKey?: Str;
  passphrase?: Str;
  hostKey: Str;
  dir: Str;
  pattern?: Str;
  pollIntervalMs?: Num;
  minFileAgeMs?: Num;
  timeoutMs?: Num;
  legacyAlgorithms?: boolean;
  maxFileBytes?: Num;
  maxExpandedBytes?: Num;
  maxItems?: Num;
  encoding?: Str;
  preprocess?: ConfiguredPreprocessor[];
}

const sftpSource: SourceDescriptor<"sftp", SftpSourceConfig>;
```

Polls a directory on a remote SFTP server and ingests each new file as one
message. **The source is read-only: the engine never writes, moves, or
deletes anything on the remote server.** The engine tracks which files it has
already ingested in its own database, so nothing on the remote side needs
to change for a file to count as processed, and that record survives engine
restarts.

```ts
sftpSource({
  id: "sftp-drop",
  host: env("SFTP_HOST"),
  username: env("SFTP_USERNAME"),
  password: env("SFTP_PASSWORD"),
  hostKey: "ssh-ed25519 SHA256:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
  dir: "/upload",
  pattern: "*.hl7",
  parser: hl7v2Parser(),
});
```

#### Config

| field | type | default | notes |
|---|---|---|---|
| `id` | `string` | required | must be unique across every pipeline in the workspace |
| `host` | `Str` | required | e.g. `sftp.example.com` |
| `port` | `Num` | `22` | |
| `username` | `Str` | required | |
| `password` | `Str` | none | exactly one of `password` / `privateKey` |
| `privateKey` | `Str` | none | the key content, not a path; see below |
| `passphrase` | `Str` | none | only valid together with `privateKey` |
| `hostKey` | `Str` | required | `<algorithm> SHA256:<fingerprint>` pin, or `accept-unverified`; see below |
| `dir` | `Str` | required | remote directory; not recursive: subdirectories are ignored, and a symlink is read only when it resolves to a file inside `dir`. A `dir` that does not exist, or is not a directory, fails every poll with an error naming it, and never reads as an empty directory |
| `pattern` | `Str` | all files | glob over the file name; `*` and `?` only |
| `pollIntervalMs` | `Num` | `30000` | at least `1000` |
| `minFileAgeMs` | `Num` | `0` | a file is read only once its size and modification time are unchanged since the previous poll and its modification time is at least this long ago; set it when a producer can pause mid-write for longer than `pollIntervalMs`. Measured against the engine's clock, so a server clock running ahead delays files by the difference |
| `timeoutMs` | `Num` | `30000` | bounds the connect and every remote operation |
| `legacyAlgorithms` | `boolean` | `false` | also offer the SHA-1 key exchanges `diffie-hellman-group14-sha1` and `diffie-hellman-group-exchange-sha1`, after every modern one, for an older server that offers nothing newer. SHA-1 key exchange is deprecated. Turn this on only when the connection otherwise fails with no matching key exchange algorithm |
| `maxFileBytes` | `Num` | `16777216` (16 MiB) | files listed larger are skipped unread, with a log line, whatever the `preprocess` chain |
| `maxExpandedBytes` | `Num` | = `maxFileBytes` | caps the total bytes of the messages one file may produce; see below |
| `maxItems` | `Num` | `10000` | caps the number of messages one file may produce; see below |
| `encoding` | `Str` | `"utf-8"` | decodes file bytes into the message string; any `TextDecoder` encoding |
| `preprocess` | `ConfiguredPreprocessor[]` | none | chain of preprocessors run between download and decode; see below |
| `parser` | `ParserDescriptor` | required | the bound parser, exactly as on `mllpSource` |

Every `Str`/`Num` field accepts an `env()` ref. The engine coerces and
validates the whole config when it loads the workspace, so a bad value fails
the load, with the source id and the reason, instead of failing a poll cycle later.

#### Authentication

Set exactly one of `password` or `privateKey`. Supplying both or neither is a
config error, and `passphrase` is accepted only alongside `privateKey`.

`privateKey` is the key content, not a path to a key file. Put the whole
key, newlines included, in the environment variable your `env()` ref names:

```ts
sftpSource({
  id: "sftp-drop",
  host: env("SFTP_HOST"),
  username: env("SFTP_USERNAME"),
  privateKey: env("SFTP_PRIVATE_KEY"),
  hostKey: "ssh-ed25519 SHA256:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
  dir: "/upload",
  parser: hl7v2Parser(),
});
```

The key must be in OpenSSH format, which `ssh-keygen` produces by default and
which starts with `-----BEGIN OPENSSH PRIVATE KEY-----`. PKCS8 PEM
(`-----BEGIN PRIVATE KEY-----`) is rejected. Convert it with
`ssh-keygen -p -f <keyfile>` first.

#### Host key verification

`hostKey` is required and has no default: either a pin of the server's
public key, written `<algorithm> SHA256:<fingerprint>`, or the literal
`"accept-unverified"`. The algorithm is the key type (`ssh-ed25519`,
`ecdsa-sha2-nistp256`, `ecdsa-sha2-nistp384`, `ecdsa-sha2-nistp521` or
`ssh-rsa`), and the fingerprint is the SHA-256 one `ssh-keygen -lf` prints:

```sh
ssh-keyscan -t ed25519 sftp.example.com | ssh-keygen -lf -
# 256 SHA256:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA sftp.example.com (ED25519)
```

gives the pin `ssh-ed25519 SHA256:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA`.
The source offers the server only the pinned key type, so a server holding
keys of several types presents the one you pinned. A pin without its
algorithm fails the workspace load with an error showing the expected form.

To bootstrap a pin, connect once with a placeholder of the right key type
(the all-`A` fingerprint from the examples will do). The source fails to
start, and the error names the key type and fingerprint the server actually
presented, or says the server holds no key of that type. Verify that
fingerprint with whoever runs the server, then put it in the config.

`"accept-unverified"` disables server authentication: the engine
sends credentials to whatever answers at `host:port`, including an
impostor. It is spelled as a literal so that the decision is greppable,
and production configs should carry a pin. While it is set, the source logs a
warning naming itself and the server once, after its first successful
connection each time the source starts. It does not log on every poll.

#### Preprocessors

`preprocess` is a chain of transforms the source runs on each downloaded
file, between download and decode. The file enters as bytes, each
preprocessor maps bytes to bytes in declaration order, and every item the
chain ends with becomes one message for the bound parser. Without a chain,
one file is one message.

The common case is a drop directory of zipped HL7v2 batch files:

```ts
sftpSource({
  id: "sftp-drop",
  host: env("SFTP_HOST"),
  username: env("SFTP_USERNAME"),
  password: env("SFTP_PASSWORD"),
  hostKey: "ssh-ed25519 SHA256:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
  dir: "/upload",
  pattern: "*.zip",
  preprocess: [unpack({ entryPattern: "*.hl7" }), hl7v2Batch()],
  parser: hl7v2Parser(),
});
```

`unpack` turns each zip into its `.hl7` entries, `hl7v2Batch` turns each
entry into one message per `MSH`, so one nightly file becomes individual
rows in the queue.

Three preprocessors ship today:

`unpack({ format?, entryPattern?, maxEntryBytes? })` expands archives. `format` defaults
to `"auto"`, which detects zip and gzip by content and passes everything
else through untouched. Force `"zip"` or `"gzip"` when the drop must contain
only that format. A file that then is not one fails the chain (see the
failure rules below). `entryPattern` is a glob (`*` and `?`) over each zip
entry's file name without its folder path, because archives routinely prefix a
folder and a full-path pattern would match nothing. It applies to
zip only: combining it with `format: "gzip"` is a config error, and on a
gzip file under `"auto"` it does nothing, since a gzip holds a single stream,
which comes out named after the file minus its `.gz` suffix. Directory
entries are ignored. Encrypted and corrupt archives fail the chain whole:
the file is never partially ingested, and it is dropped under the failure
rules below. A truncated archive counts as corrupt: each zip entry is
checked against the uncompressed size its header declares, and a gzip
against the length in its trailer, so a drop that was cut short in
transit is refused instead of ingested as a short message. Neither check
reads the stored checksum, so corruption that preserves the length still
gets through. A zip entry written by a producer that streams its
entries without declaring their sizes up front carries nothing to check
against and is not checked. `maxEntryBytes` (default 16 MiB) bounds each zip
entry, and a gzip file as a whole, while it inflates: an entry that inflates
past it fails the chain before any of it is emitted, so the memory one entry
takes stays within about that bound.

`hl7v2Batch()` splits an HL7v2 batch file into one message per `MSH`
segment. The `FHS`/`BHS`/`BTS`/`FTS` batch envelope lines are dropped, and a
blank line never ends a message: a message runs from its `MSH` line to the
next `MSH` or envelope line or to the end of the file, so segments after a
blank line stay in their message, as in a file whose writer terminates every
segment with `\r\r\n`. `\r`, `\n` and `\r\n` line endings all
work, and the field separator can be any character, because MSH-1 defines it and
the parser honors it. It splits raw bytes, so any ASCII-compatible `encoding` works
(UTF-8, Latin-1, …), and a UTF-16 file fails the chain. A file with content but
not a single `MSH` line fails it too, because recording that as "done, zero
messages" would lose the data with no error.

`lines({ delimiter?, skipFirst?, maxRecordBytes?, trimTrailingCR? })` splits
the file into one message per delimited record. It was written for NDJSON, one
JSON object per line:

```ts
sftpSource({
  ...,
  pattern: "*.ndjson",
  preprocess: [lines()],
});
```

`delimiter` defaults to `"\n"` and is matched across the boundaries of whatever
chunks arrive, so no record is lost to a split read. `trimTrailingCR` (default
`true`) drops a single trailing `\r`, so a CRLF file yields clean records.
`skipFirst` (default `0`) drops that many leading records. Set it to `1` for a
file that opens with a header row. Empty records are skipped and not emitted
as empty messages, a last record with no trailing delimiter is still emitted, and
a trailing delimiter at end of file does not produce an empty one.
`maxRecordBytes` (default 1 MiB) is the memory bound: a record longer than it
fails the chain, naming the record's position in the file.

It is not a CSV reader. A quoted CSV field containing a newline is split
through the middle, with no error and nothing in the logs.
Use `lines` only where a record can never contain the delimiter.

`lines` streams: it reads the file as it arrives and holds one record at a
time, never the whole file. No limit is raised for it, though: a
file listed past `maxFileBytes` is still skipped unread, and the records still
count against `maxExpandedBytes` and `maxItems`. To ingest large files through
`[lines()]`, raise all three to fit the largest file you expect:

```ts
sftpSource({
  ...,
  pattern: "*.ndjson",
  preprocess: [lines()],
  maxFileBytes: 512 * 1024 * 1024,
  maxExpandedBytes: 512 * 1024 * 1024,
  maxItems: 2_000_000,
});
```

Memory stays bounded by `maxRecordBytes` and the source's own flush batches
however high those three go, because the file is streamed and never held whole. In
`[unpack(), lines()]` the archive is held whole to be expanded, so there
`maxFileBytes` is also the memory it may take.

The failure rules:

- **A failure in the chain skips the rest of the remote file.** What
  happens next depends on whether the same bytes would fail the same way
  next time:
  - a deterministic failure (a typo'd `entryPattern`, an encrypted or
    corrupt archive, a record over `maxRecordBytes`, bytes that do not
    decode in the configured `encoding`, a cap exceeded) is logged as an
    error naming the file and the reason, and the file is then marked
    done carrying that reason. It is never read again, so the feed keeps
    moving instead of re-downloading a file that cannot work. No error row
    appears in the queue, because no row was ever written for it;
  - a transient failure (a dropped connection, a server-side error,
    anything the engine does not recognise) is logged as a warn, the file
    is left unmarked, and the next poll retries it.
- **A pattern that selects nothing is a failure, not an empty result.** A
  zip with entries where `entryPattern` matches none is deterministic: the
  file is marked done with that reason. Correcting the pattern does not
  bring it back on its own. Re-drop the file so it arrives with a new
  mtime or name.
- **Genuinely empty is done.** A zero-byte file, a zip with no file entries,
  or a batch that is only envelope lines produces zero messages and is
  recorded as done, with one info log, so a quiet night converges instead of
  retrying forever.
- **What a file produces is capped.** `maxExpandedBytes` bounds the total
  bytes of the messages the chain emits for one file and defaults to
  `maxFileBytes`. It bounds what is emitted, not what is inflated: `unpack`
  inflates each archive entry whole before it emits it, bounded only by its
  own `maxEntryBytes` (default 16 MiB, whatever `maxFileBytes` is), and an
  entry a later stage drops is never counted. It is a separate knob from
  `maxFileBytes`: a high-compression drop can raise what it may emit without
  also allowing bigger downloads. `maxItems` (default 10 000) bounds how many
  messages one file may produce. Both are counted on what the chain finally
  emits, as it emits it, for every chain, streaming or not, so a stage in the
  middle is not counted twice. Over either cap the chain is stopped where it
  crossed, and the file is marked done with that reason.
- **A file refused over a cap may already be partly ingested.** The batches
  written before the chain crossed the cap stay written, as described next.
  How many messages that was is in the error log, in its `written` field, and
  at the end of the reason the file is recorded with:
  `…; 1000 messages written`. A file refused before anything was written
  records the reason alone.
  Raising the cap does not bring the rest of the file back on its own:
  re-drop the file so it arrives with a new mtime or name, and it is ingested
  from its first message, so the part already written arrives a second time.
- **A big file fails in the middle after some of it was ingested.** A file
  that produced more than 500 messages has already written them when a later
  record fails the chain. If that failure is deterministic the file is marked
  done, so the prefix is written once and the rest of the file never
  arrives. That is a partial ingest you have to notice in the error log. If it is
  transient, the next poll re-ingests the prefix as it retries. Keep the
  mapper's ids stable and the duplicates overwrite instead of accumulating.

`encoding` applies after the chain, to each item it emits. The chain itself
works on bytes.

The same three preprocessors are open to a source you define yourself: pass a
chain to its context's `preprocess`, and validate it at load with
`normalizePreprocessChain`. See
[Preprocessing what a source read](#preprocessing-what-a-source-read).
A preprocessor of your own, declared with
[`definePreprocessor`](#defining-a-preprocessor), goes in an
`sftpSource` chain beside these, or in your own source's, and
`normalizePreprocessChain` accepts it.
Each descriptor also has its own config validator:
`normalizeUnpackConfig`, `normalizeHl7v2BatchConfig` and `normalizeLinesConfig`.
Each returns the config with its defaults filled in, or throws naming the
refused field.

#### What gets ingested, and when

- A file is picked up once its size and mtime are stable across two
  consecutive listings, so a file still being uploaded waits a cycle. After
  an engine restart every file waits one cycle for the same reason.
- A server that will not open a file because it is still being uploaded
  (Windows-based servers lock it) does not fail the cycle: that file is
  tried again on the next one, and the rest are read.
- An entry the server lists without a type, size or modification time is
  never read.
- A file's identity is its path + mtime + size. A file that changes after
  ingestion is a new identity and is ingested again.
- With no `preprocess` chain, one file becomes exactly one message, handed
  as-is to the bound parser; with one, each item the chain emits becomes one
  message; see "Preprocessors" above.
- Delivery is at-least-once: after a crash the same file can arrive
  twice, and with a `preprocess` chain that means every message it expanded
  to. Handling duplicates is the pipeline's job: make the mapper derive
  stable ids so a re-send overwrites instead of duplicating.
- A file that is oversize for `maxFileBytes`, or that could not be read this
  time, is skipped with a log line and retried on the next cycle. A file
  whose bytes do not decode in the configured `encoding` is marked done with
  that reason instead, like any other deterministic failure. Neither ever
  blocks the rest of the directory.

#### When the server misbehaves

A connection failure, an authentication failure, a host-key mismatch, or any
operation exceeding `timeoutMs` restarts the source worker with exponential
backoff, and the engine keeps retrying. After a rejected login the source
does not try that server and user again for 1 minute, doubling up to 1 hour,
so a wrong password does not lock the account on servers that lock after
repeated failures. A successful login resets the wait. A server that lists
files modified more than 5 minutes in the future gets one warning per cycle:
its clock is ahead or it reports local time, and such files wait. The dashboard shows the source as
down with its restart count and last error. A wrong password and an
unreachable host look the same there, so read the error text. A stalled
server appears as a timeout, never as a hang.

### `webhookSource`: HTTP webhook source

```ts
interface WebhookSourceConfig {
  port: Num;     // accepts POST on any path of this port
  secret?: Str;  // when set, a request without a matching x-interbox-secret header is 401
}

const webhookSource: SourceDescriptor<"webhook", WebhookSourceConfig>;
```

```ts
webhookSource({
  id: "inbound-webhook",
  port: env("WEBHOOK_PORT"),
  secret: env("WEBHOOK_SECRET"),
  parser: hl7v2Parser(),
});
```

An HTTP endpoint. Each `POST` body becomes one inbound row exactly as it arrived, and the request
is answered `200` once the row is committed. A body the parser rejects is stored as an error row
and still answered `200`. A failed write answers `500`, so a sender that retries delivers again.
Any other method is `405`, and a body over 16 MB is `413`.

An Aidbox topic destination can point here: its notification Bundle arrives as one row, and the
workspace's parser or mapper picks the resources out of it.
With `secret` set, give the destination a `header` parameter carrying it:

```json
{ "name": "header", "valueString": "x-interbox-secret: <secret>" }
```

Aidbox does not allow a topic destination to be modified, so adding the header means deleting the
destination and creating it again.

Not to be confused with [webhooks](../guides/webhooks.md), which Interbox sends out.

### `aidboxSender`: Aidbox FHIR sender

```ts
type AidboxAuth =
  | { kind: "basic"; user: Str; password: Str }
  | { kind: "bearer"; token: Str };

interface AidboxSenderConfig {
  url: Str;
  auth: AidboxAuth;
  batchSize?: number;  // max rows claimed per loop
  // consecutive transient failures to retry before the batch is recorded errored
  maxRetries?: number;
  // ceiling of the retry backoff for resources deferred on a missing reference
  // target: retries start at 5s and double per attempt up to this (default 5 min)
  retryDelayMs?: number;
}

const aidboxSender: SenderDescriptor<"aidbox", AidboxSenderConfig>;
```

```ts
aidboxSender({
  url: env("AIDBOX_URL"),
  auth: { kind: "basic", user: env("AIDBOX_CLIENT_ID", "root"), password: env("AIDBOX_CLIENT_SECRET") },
});
```

### `hl7v2Parser`: HL7v2 parser

```ts
interface Hl7v2ParserConfig {
  skipZSegments?: boolean;
}

const hl7v2Parser: ParserDescriptor<"hl7v2", Hl7v2ParserConfig>;
```

```ts
hl7v2Parser();                          // config optional, defaults to {}
hl7v2Parser({ skipZSegments: true });
```

Bound to a 1.x source's `parser` field. A 2.0 pipeline parses HL7v2 with the
`hl7v2Parser()` step from `@health-samurai/interbox/hl7v2` instead. See
[Built-in sources, steps and senders](built-in-stages.md#hl7v2-hl7v2parser-and-frommsh7).
