For AI agents: the documentation index is at /docs/interbox/llms.txt. A Markdown version of this page is available at /docs/interbox/reference/built-in-stages.md or by requesting it with the Accept: text/markdown header.
Interbox Docs

Built-in sources, steps and senders

Reference for the SDK's MLLP and webhook sources, the HL7v2 parsing step and the Aidbox steps and sender. The file source is on /files, and the pull sender on A queue consumers poll.

Sources: mllpSource and webhookSource

import { mllpSource, webhookSource } from "@health-samurai/interbox/chain";

function mllpSource(config: MllpSourceConfig): ChainSource<string>;
function webhookSource(config: WebhookSourceConfig): ChainSource<string>;

interface MllpSourceConfig {
  port: Num;
  host?: Str;
  maxBytes?: number;
  idleTimeoutSeconds?: number;
}

interface WebhookSourceConfig {
  path: Str;
  secret?: Str;
  maxBytes?: number;
}

An MLLP source listens on a port of its own. Every webhook source listens on the engine's one webhook port, each at its own path. A source turns each input into one row, a string decoded as UTF-8: an MLLP frame, or the body of an HTTP POST. The steps before the store run on that row, and the engine answers the sending side once the input commits or is refused. A pipeline fed by another pipeline has no source of its own. It reads fromPipeline.

An MLLP source's port and host, and a webhook source's path and secret, may be env() references. The engine checks every field when it loads the workspace, so an unset variable with no default, or a value out of range, parks the pipeline. An MLLP source reads them again when it starts. A webhook source keeps the values read at load until the next reload.

mllpSource

fielddefaultwhat it does
portrequiredthe TCP port to listen on
host0.0.0.0the address to listen on
maxBytes16 MiBthe largest frame, in bytes, at most 64 MiB
idleTimeoutSeconds300closes a connection that has sent nothing for this long. 0 keeps idle connections open. At most 86 400, a day
  • Each frame is one input. It is answered AA once it commits, and AE with the reason when it is refused (see Failures). The frames of one connection are answered in the order they arrived.
  • MSH-18 picks the character set a frame is decoded by. Only its first repetition counts. A frame with no MSH-18 must be valid UTF-8. The names are those of HL7 table 0211 that map to a decoder (ASCII, ISO IR6, 8859/1 to 8859/9, 8859/15, UNICODE, UNICODE UTF-8, GB 18030-2000, KS X 1001, BIG-5, JIS X 0202), plus ISO IR100, UTF-8, ISO-8859-1 and its siblings, Windows-1252 and CP1252, in any case. A character set whose decoder the runtime does not ship counts as one that cannot be decoded. Interbox decodes 8859/1 (and ISO IR100) as windows-1252 and 8859/9 as windows-1254, so bytes 0x80-0x9F become the characters of those code pages: 0x85 is … (U+2026).
  • A frame that cannot be decoded is stored at error. When MSH-18 names a character set that cannot be decoded, or a byte is not valid for the character set in effect, Interbox decodes the frame as windows-1252. That code page gives each byte its own character, so the frame's bytes can be recovered from the text. The text goes through the steps before the store like any frame, and its unit ends at error with engine/undecodable before any step after the store runs. The frame is answered AA, because a sending system that moves on after AE would lose it. Retry the unit to process the windows-1252 text, or Defer it (see Errors). The warning in the log holds no message text.
  • A frame over maxBytes. It gets no answer: the connection is closed, and the refusal is counted as too_large (see Errors).
  • On a stop. The source takes no new frame. A frame whose steps have not started when the stop begins is neither stored nor answered, and idle connections are closed. An input already in its steps has until the stop's grace period ends to commit and get its AA. After that it is abandoned: nothing of it is stored, no answer goes out, and its connection is closed. The sending system resends.

webhookSource

fielddefaultwhat it does
pathrequiredthe path a request must be sent to, starting with /
secretnonewhen set, a request must carry it in the x-interbox-secret header, or as the password of Authorization: Basic. An empty string parks the pipeline
maxBytes16 MiBthe largest request body, in bytes, at most 64 MiB

The engine listens for every webhook source on one port: 3002, or the port the operator sets in INTERBOX_WEBHOOK_PORT (see Operating pipelines). The workspace chooses paths only. Give one pipeline path: "/vendor-a/response" and another path: "/vendor-b/response", and each POST goes to its own pipeline's store.

  • Paths match exactly. The match includes case. Trailing slashes are ignored on both sides, so /vendor-a/response/ and /vendor-a/response// reach /vendor-a/response. The query string is not part of the route. A path that does not start with /, or holds ? or #, parks the pipeline. So does a path a request URL would carry in another form, such as /a b or /données: declare the percent-encoded form the error names (/a%20b).
  • A source without path parks its pipeline. So does a source that names a port. The error names the pipeline.
  • Two sources on one path refuse the load. The error names both pipelines.
  • An MLLP source on the webhook port parks its pipeline. The error names INTERBOX_WEBHOOK_PORT. With INTERBOX_WEBHOOK_PORT=0 the system picks a free port for the webhook sources, so an MLLP source on port 0 loads.
  • The secret and maxBytes belong to the route. Each pipeline keeps its own. With Authorization: Basic, the user name is ignored and only the password is compared. A sending system that cannot add a header can send the secret this way.

Each POST body is one input. The engine answers:

answerwhen
200the input committed, and the body is ok
400the request body could not be read
401the route has a secret, and the request carries it in neither header. It is counted as an unauthorized refusal while the pipeline's source runs
404no webhook source has the request's path. It is counted for no pipeline
405the method is not POST
413the body is over the route's maxBytes. It is counted as a too_large refusal while the pipeline's source runs
500the input was refused (see Failures), or a stop's grace period ended before it committed, or the engine failed on the request. The body is a fixed text. The engine's log names the pipeline (only the port when the request matched no route), the error's kind and the code location it was thrown at, never its message, which can hold the input
503the route's pipeline is not running, it stopped or did not answer in time, or the engine is stopping
  • The engine retries a webhook port it cannot bind. The waits grow. Until it is bound, every webhook source reports backoff and its pipeline reads degraded. Pipelines with other sources run on.
  • A client that disconnects abandons its input. The ctx.signal of the steps before the store fires, nothing of the input is stored, and it is not counted as a refusal.
  • On a stop. The engine takes no new request. One that still reaches it is answered 503 with Connection: close, without running a step. An input already in its steps has until the stop's grace period ends to commit and get its 200. After that it is abandoned, nothing of it is stored, and it is answered 500. The sending side resends either.

HL7v2: hl7v2Parser() and fromMsh7

import { fromMsh7, hl7v2Parser } from "@health-samurai/interbox/hl7v2";

function hl7v2Parser(options?: { skipZSegments?: boolean }): NamedStep<string, HL7v2Message>;
function fromMsh7(msg: HL7v2Message, timeZone: string): Date;

hl7v2Parser() is the step hl7v2.parse. It parses each raw message, and sets these attrs on its unit:

attrfrom
message_typeMSH-9.1
event_typeMSH-9.2
patient_idPID-3
patient_namePID-5, given then family name
sending_applicationMSH-3
sending_facilityMSH-4
send_timeMSH-7, read as UTC unless it carries an offset

A message that does not parse fails its unit with parse/missing_msh when the text has segment lines, and parse/not_hl7 when it has none. skipZSegments: true drops every Z segment. The parser does not set order_at.

fromMsh7(msg, timeZone) reads MSH-7 as an instant. A time without an offset is read in timeZone, an IANA zone such as America/New_York, because only you know the sender's clock. It throws field/missing_msh7, field/malformed_msh7 or field/unknown_time_zone, so the unit ends at error without retrying. Use it to order a feed's messages by their own time:

import { env } from "@health-samurai/interbox";
import { mllpSource, pipeline, postgresStore } from "@health-samurai/interbox/chain";
import { fromMsh7, hl7v2Parser } from "@health-samurai/interbox/hl7v2";
import { fhirItems, skipUnchanged } from "@health-samurai/interbox/aidbox";

pipeline("adt")
  .source(mllpSource({ port: env("MLLP_PORT") }))
  .store(postgresStore({ codec: "text" }))
  .step(hl7v2Parser())
  .step((msgs) => msgs.withOrder((m) => fromMsh7(m, "America/New_York")))
  .step(adtToFhir)
  .step(fhirItems())
  .step(skipUnchanged())
  .sender(toAidbox);

Storing the raw message and parsing after the store, as above, lets a Retry after a parser fix parse the original again. Parsing before the store stores the parsed form instead, and a parse failure then refuses the input with AE.

Aidbox: fhirItems(), skipUnchanged() and aidbox()

import { aidbox, fhirItems, skipUnchanged } from "@health-samurai/interbox/aidbox";

The mapping from your input to FHIR resources is a step of your own, usually a flatMap after the store that turns each unit into its resources. The SDK ships no HL7v2-to-FHIR mapping step. adtToFhir above stands for yours:

const adtToFhir = defineStep("adt-to-fhir", (msgs: Batch<HL7v2Message>) =>
  msgs.flatMap((msg, ctx) => {
    const patient = patientOf(msg);
    const encounter = encounterOf(msg, patient);
    return [patient, encounter, provenanceOf(ctx, [patient, encounter])];
  }),
);

fhirItems()

function fhirItems(): NamedStep<Resource, FhirItem>;

The step aidbox.fhir-items. It gives each resource the item meta the Aidbox sender reads: key (Type/id), refs (the Type/id references the resource holds) and hash (a hash of its content, ignoring meta and key order). A resource with no string resourceType or id, or whose key holds the NUL character or a lone surrogate, fails its unit with mapper/exception.

Put it after every step that changes a resource, because the hash it stores is what skipUnchanged() compares. aidbox() takes only FhirItems, so a pipeline that leaves it out does not compile.

skipUnchanged()

function skipUnchanged(): NamedStep<FhirItem, FhirItem>;

The step aidbox.skip-unchanged. It skips, with the reason unchanged, a resource identical to the newest version of its key already queued in this pipeline, or, when none is queued, to the version this pipeline last delivered to its current Aidbox destination. A unit whose resources are all unchanged closes sent without sending anything. Consecutive versions within one unit are compared in their output order, so A → B → A retains the restoring A.

The step retains resources when mapping order is uncertain: unfinished mapping or staged outputs in another unit, later queued items, multi-unit takes, streamed mapping, or an engine without the safety check. Sender deduplication still applies.

Fingerprints include the normalized destination URL and optional destinationScope. For a URL serving several tenants, set the scope to the tenant's stable identity in business configuration. Changing URL or scope, adding scope, or upgrading a legacy fingerprint causes delivery again. Credential rotation for the same URL and scope does not. Scope neither routes requests nor verifies credentials. Operators must match the token to the declared tenant.

Guarded Aidbox writes

By default the sender writes without version conditions and reads nothing, so its client needs write permission only. That leaves a late write possible: a request that times out can still be running at Aidbox when the item is retried, and if a newer version of the same resource is delivered before it is applied, it restores the older values. One engine can hit this through a timeout and a retry. A failover can too, since the new active replica retries an item whose request the old one still had in flight.

Set versionGuard: true to fence late writes. Every write then carries a version condition: If-Match for an update, If-None-Match: * for a creation. Aidbox must enforce these atomically. A delayed request with an outdated version fails with 412 instead of overwriting a newer value.

The sender keeps the version Aidbox returns for each successful write, with the resource's fingerprint. With versionGuard, the next change to that resource on the same destination is written with If-Match on that version, without a read. The sender reads the current version first only when it has none stored for this destination: a resource it has not written there yet, a fingerprint from an earlier release or another destination, or a write whose answer carried no version. A write with a stored version that fails with 412 (another writer changed or deleted the resource, or an earlier answer was lost) is read and written once more in the same send. If that write fails with 412 too, the item waits as sender/edit_conflict for a later attempt.

With versionGuard, the client needs read and write permissions, and reads are needed for those cases only. A failed read or missing version blocks affected resources. Other resources can proceed, and matching delivered fingerprints retain their sent outcome. There is no unconditional-write fallback.

A timeout can leave a request running at Aidbox. Retrying may create another history version or repeat a trigger. Version guards protect resource state. Exactly-once effects require destination idempotency committed with the effect.

aidbox()

function aidbox(cfg: AidboxConfig): Sender<FhirItem>;

interface AidboxConfig {
  readonly id?: string;
  readonly url: Str;
  readonly destinationScope?: Str;
  readonly auth: { kind: "basic"; user: Str; password: Str } | { kind: "bearer"; token: Str };
  readonly batch?: number;
  readonly maxRetries?: number;    // default 10
  readonly retryDelayMs?: number;  // default 30 000
  readonly runTimeoutMs?: number;  // default 300 000
  readonly validateFirst?: boolean;
  readonly versionGuard?: boolean; // default false
}
const toAidbox = aidbox({
  url: env("AIDBOX_URL"),
  auth: { kind: "basic", user: env("AIDBOX_CLIENT_ID"), password: env("AIDBOX_CLIENT_SECRET") },
});

A sender that writes fhirItems() output to <url>/fhir in batch bundles, each seed with the resources it references that are still queued.

fieldwhat it does
idan optional name, kept in the pipeline's definition, with the same rule as a pipeline name
url, authread from the environment as each send starts, so an unset env() fails that send rather than the load
destinationScopeoptional stable tenant or logical destination identity, literal or env(). It extends fingerprint scope without changing request routing
batchhow many items one send picks to start from, 100 by default
maxRetriesafter this many errors an item's unit ends at error
retryDelayMsthe fixed wait before an item's next try
runTimeoutMshow long one send may take before every item in it counts an error
validateFirstruns $validate on the batch before sending it
versionGuardwrites with version conditions and reads versions where it must; off by default. See Guarded Aidbox writes

How it answers for each resource:

Aidbox answersoutcomekind
2xxdeliverednone
a reference to a resource that does not existwaits, and counts no errorsender/reference_missing
409 with an edit conflict, or 412waits, and counts no errorsender/edit_conflict
5xx, no answer, or a 408, 425, 429 or redirect to the whole requestan error, tried again after retryDelayMssender/aidbox_unreachable
any other refusalthe unit ends at error at oncesender/aidbox_rejected

A refusal's message holds every error issue Aidbox, or $validate, reported for the resource: <n> errors: <path>: <diagnostics> [<codes>]; …, or the one line alone, cut at 2,000 characters with … and <n> more. A resource waits for a missing reference only when that is all that is wrong with it, and the wait's message names every missing reference, the first ten and a count of the rest.

A resource whose content matches what this pipeline last delivered is answered delivered without being sent. A resource this pipeline has not delivered before is a PUT. One that changed since it was delivered is a PATCH. To remove an element from a resource delivered before, map it as null: a PATCH removes it, and the first send, a PUT, drops nulls. A PATCH on a resource deleted in Aidbox is sent again at once as a PUT in a request of its own: Aidbox answers it 404, or with versionGuard 412, after which the sender reads the resource and finds it gone. A wait has no limit: a unit whose resource waits for a reference that never comes stays processed, and is closed from the dashboard (see Operating pipelines).

These environment variables tune every aidbox() sender in the engine:

variabledefaultwhat it bounds
INTERBOX_AIDBOX_MAX_BODY_BYTES8 MiBthe body of one request
INTERBOX_AIDBOX_MAX_ENTRIES_PER_REQUESTnonethe entries of one request
INTERBOX_AIDBOX_CONCURRENCY4requests in flight within one send
INTERBOX_AIDBOX_REQUEST_TIMEOUT_MSnoneone request. The send's own deadline still applies

One send of n resources splits them over min(INTERBOX_AIDBOX_CONCURRENCY, n / 50 rounded down) requests that go out at the same time, about n / INTERBOX_AIDBOX_CONCURRENCY each and at least 50 where the send allows it. For example, 500 resources with no reference between them are four requests of 125, 120 are two of 60, and fewer than 100 are one request. Resources joined by a reference stay in one request, or in requests sent one after another, with the referenced resource first, so a request can come out smaller or larger than the others. INTERBOX_AIDBOX_MAX_BODY_BYTES and INTERBOX_AIDBOX_MAX_ENTRIES_PER_REQUEST split a request further. Set INTERBOX_AIDBOX_CONCURRENCY to 1 to send one request at a time.

Upgrade note. Earlier engines sent a whole send as one request unless a cap split it, so INTERBOX_AIDBOX_CONCURRENCY rarely had anything to overlap. Now a send of about 100 resources or more goes out as up to INTERBOX_AIDBOX_CONCURRENCY (4 by default) parallel requests, per sender and per worker, which raises the load on Aidbox and its database. A slow answer that times out counts toward maxRetries. Set INTERBOX_AIDBOX_CONCURRENCY=1 to keep the earlier behaviour.

contentHash and extractRefs, the two functions behind fhirItems(), are exported from /aidbox as well.

fingerprints

const fingerprints: StateHandle<{ hash: string }>;

The state handle of the namespace aidbox.fingerprints: for each resource aidbox() delivered, keyed Type/id, the content hash of the version Aidbox holds. Like all state it is per pipeline. aidbox() writes it after each delivery and reads it to choose between PUT, PATCH and skipping. skipUnchanged() reads it. The admin library's deliveredKeys, deliveredSummary and forgetDelivered list, count and clear it (see Admin scripts). A step may read it with ctx.state(fingerprints). Leave the writes to the sender: a wrong hash turns the next send of that resource into a PUT that replaces it, or skips a change. To force a resource out again, use forgetDelivered. The 1.x import fills it from 1.x's resource hashes (see Upgrading from 1.x).

Last updated: