Skip to content

Ports and hooks

OpenDecuma ships no AI feature: no model provider, no prompts, no agent, no chat (ADR 0049). It ships the toolbox to build them: ports with typed request and result schemas, the Events of the outbox and webhooks, the tool catalogue with dry run and Freigaberichtlinie (SDKs), deterministic fakes for tests and decuma dev, and the SDKs. Without a provider every core workflow works by hand: a Beleg is stored unread and captured by typing its lines, a Kategorie is chosen by the person or a Kontierungsregel.

Which model, endpoint, instructions and threshold you use is yours. Everything you send a provider leaves the installation: Belege, their content and the facts of a question go wherever your implementation sends them.

There are two ways in. Both see the same Commands, the same Freigaberichtlinie and the same Command-Log.

Port (trait in decuma_ports) Service you register Asked when Answer
Lesen::read_with_context(&[Seite], &MandantContext) (default: lesen(&[Seite])) Lesung(Arc<dyn Lesen>) inside beleg.deliver, once per Beleg, with what the reader may know about the Mandant (MandantContext: Kleinunternehmer status today, own names, USt-IdNr.; nothing else), with all its pages; a picture as its prepared copy (ADR 0053), never one below the quality limits Lesergebnis { felder, verbrauch, outcome }: felder in the shape of Belegdaten.felder (REST), each field {wert, zustand} with zustand gelesen or bitte_pruefen; None when nothing was read. outcome (ReadingOutcome, default filled) is what you understood beside the fields, typed and closed: question (one ReadingQuestion: kind, field, options, proposed, free_text, and flags to point out beside it), not_a_beleg (reason: the kind of document), recapture (page, CaptureProblem code), flagged (ReadingFlag codes)
Entscheiden::entscheiden(&Frage) Entscheidung { port, schwelle } after the Regeln on case.ready, when a read line has no Kategorie and no Kontierungsregel acted (ADR 0045) Antwort { wahrscheinlichkeiten, verbrauch }: a probability per option of Frage.optionen, 0 to 1
HinweisQuelle::hinweise(jahr, angaben, &[Seite]) Hinweisquelle(Arc<dyn HinweisQuelle>) notice.create_from_beleg Vec<HinweisVorschlag>: title, norm and the proposed Angabe; the effect in euro is computed by the engine

The guarantees stay above the port, whatever you implement:

  • A picture is prepared before any port sees it (deskewed, cropped to the page, contrast; ADR 0053) and checked against the quality limits (file.quality_limits, DECUMA_CAPTURE_LIMITS): a page below them gets “Bitte neu aufnehmen” with one sentence why, and the port is not asked. Seite.hash is the content hash of what you receive; a page you read before has the same hash.
  • A provider never books. A reading becomes a Vorschlag the person confirms; a decision becomes a Vorschlag only when the most probable option of the closed set reaches your schwelle, else a Rückfrage (kategorie_waehlen) with the same options. An option outside the set is ignored; there is no default answer.
  • An Err, or an answer that is not Belegdaten, leaves the Beleg stored unread with the warning not_read, exactly as without a provider.
  • Every reading, yours or a structured E-Rechnung, passes the checks without a provider (decuma_buchhaltung::reading::reading_checks, public): net plus tax is gross per line and in total, tax is net times rate to the cent, the rate exists on the day of the supply, the USt-IdNr. format, dates not after today nor far back, issuer known, issuer not the Mandant itself. Every field a finding names is set to bitte_pruefen whatever you said; a finding that decides whether or where an amount is declared holds the case for the person (no case.ready). The kind rechnung or kleinbetragsrechnung follows from the total and the rule data’s limit, not from your answer. The codes come back as warnings of the delivering Command and as hints of beleg.get and case.get.
  • The invoice checks of the capture run at reading too: above the small-amount limit each missing datum of § 14 Abs. 4 Satz 1 UStG is a warning invoice_detail_missing.<requirement> (rechnungsnummer, leistungszeitpunkt, …) and holds the case; an invoice from an issuer at home that should have been an e-invoice warns e_invoice_required, opens a question with the three ways (wait for the e-invoice, objektiver_nachweis, uebergangsregel_angenommen, without Vorsteuer) and gets no Vorschlag and no case.ready before its answer. case.get held names what holds a case ({codes: [...]}, null when released, booked or closed). beleg.get e_invoice says whether a Beleg is an E-Rechnung or a sonstige Rechnung, with the profile of a structured file and the validation report of a file that failed the syntax or schema check; credit_note gives the kind of a received credit note and the booked invoice it corrects.
  • Your outcome reaches the person only through sentences the open layer writes: a question becomes one Rückfrage reading_question (its options’ texts are what the Beleg shows), answered with question.answer (an option key, or the typed text when free_text), which writes the field as the person’s record and continues the case; the kinds missing_supply_date and other_recipient are questions whose answers are legal choices the open layer defines (choices[] with code, text and the inputs a choice takes, a note on a proposal, a warning that stays): missing_supply_date offers deduct (input leistungsdatum, the Belegdatum as proposal), wait_for_amendment and without_vorsteuer above the small-amount limit, the day only below it; other_recipient opens the Rückfrage empfaenger_weicht_ab of the capture; question.answer takes the code as answer and the values as inputs; not_a_beleg writes nothing and asks what happens with the file (Rückfrage not_a_beleg: keep_as_attachment with buchung_id, close_not_relevant with reason, or is_a_beleg); recapture leaves the Beleg unread with the warning retake naming the page; flagged codes are Hinweise of the case. beleg.get reading_outcome keeps what you answered.
  • verbrauch (Verbrauch { einheiten, kosten, modell }, your provider’s own count) becomes the Event reading.usage or decision.usage, so you meter from the outbox exactly once.
  • Without a registered decision port its consumer does not exist: nothing is asked, nothing changes.
  • In the dry run of a Command (dry_run: true, SDKs) no port with an outside effect acts: decuma_server::dry_run_services fails closed. It keeps only the services it knows to be safe (settings, the clock zone, the Belegablage), accepts mail without sending it and hands a transmission over as by hand; every other service (the reading, decision, Hinweis, bank, USt-IdNr. and push ports, and any service it does not know) is absent. A build that registers a port of its own with an outside effect registers its own decuma_commands::DryRunServices(fn(&Services) -> Services) (it may call dry_run_services and swap its own port too); a handler that writes outside its transaction checks ctx.dry_run.
  • A build that registers its reading port per Command instead of on the installation (behind a feature flag, a balance or a limit) registers ReadingOffered(Arc<dyn ReadingCheck>) (decuma_buchhaltung::eingang): it answers whether beleg.read_again would read for the caller now, which beleg.get reports as can_read_again. Without it, reading is offered when the installation has a reading port.

Build a binary that compiles the open crates together with your crate (ADR 0008: composition at compile time, no plugin loading) and register your implementation on the installation before it serves:

use std::sync::Arc;
use decuma_ports::{Antwort, BoxFuture, Entscheiden, Entscheidung, Frage, Lesen, Lesergebnis, Lesung, Seite};
struct MyReader;
impl Lesen for MyReader {
fn lesen<'a>(&'a self, seiten: &'a [Seite]) -> BoxFuture<'a, Result<Lesergebnis, String>> {
Box::pin(async move {
// Your provider: seiten[i].inhalt (bytes), .medientyp, .hash (SHA-256 of inhalt:
// the same bytes give the same hash, a cache key), .stored_hash (the page as stored).
todo!("read the fields of the Beleg")
})
}
}
struct MyDecider;
impl Entscheiden for MyDecider {
fn entscheiden<'a>(&'a self, frage: &'a Frage) -> BoxFuture<'a, Result<Antwort, String>> {
Box::pin(async move {
// frage.frage (text), frage.optionen (the closed set of keys), frage.kontext (facts, JSON).
todo!("a probability per option")
})
}
}
// In your build's Build::open (below), after decuma_server::App::open(..):
let services = (*app.exec.services)
.clone()
.with(Lesung(Arc::new(MyReader)))
.with(Entscheidung { port: Arc::new(MyDecider), schwelle: MY_THRESHOLD });
app.exec.services = Arc::new(services);

Test against the fakes first: App::mit_lesung_fake(), App::mit_entscheidung_fake(schwelle) and App::mit_hinweisquelle_fake() give you the same flow with answers you set (LesungFake::setzen, EntscheidungFake::setzen or danach). Under decuma dev, DECUMA_READING=fake answers what PUT /dev/lesung/{hash} set, DECUMA_DECISION=fake registers a decision port that answers nothing (every question becomes the Rückfrage), and DECUMA_NOTICE_SOURCE=fake answers what PUT /dev/hinweisquelle/{hash} set. Outside dev these values stop the start.

Way 2: an external service on the SDK (out of process)

Section titled “Way 2: an external service on the SDK (out of process)”

A separate program with an API-Schlüssel does what a person would do in the app, through the same Commands (SDKs). It needs no Rust and no rebuild:

  1. Find work: inbox.list with zustand neu (stored unread), or the Events case.ready and question.opened by webhook or event.poll.
  2. Read the pages: beleg.get for the page hashes (seiten[].hash), datei(hash) for the bytes.
  3. Write the result as a Command with a Begründung: beleg_data.correct with the values you read (a new Belegdaten record; the earlier stays readable; a field you leave out keeps its recorded value, clear removes one), or question.answer with one of the Rückfrage’s antworten.
  4. Dry-run first with command.check, or with dry_run: true on the Command to see its handler’s answer too (SDKs); whatever the Freigaberichtlinie of the key does not allow alone waits for a person. command.basis tells what stands behind a proposal (a Regel that would issue it, an identical case a person booked, the one candidate of the Abgleich), so the person is shown why it is proposed.
from decuma import Decuma
d = Decuma.from_env() # DECUMA_URL, DECUMA_API_KEY
def read(pages: list[bytes]) -> dict:
raise NotImplementedError("your provider: return BelegdatenEingabe")
for zeile in d.zeilen("inbox.list", {"filter": {"zustand": ["neu"]}}):
for beleg_id in zeile["beleg_ids"]:
beleg = d.query("beleg.get", {"beleg_id": beleg_id})
pages = [d.datei(s["hash"]) for s in beleg["seiten"]]
d.command("beleg_data.correct", {"beleg_id": beleg_id, "belegdaten": read(pages)},
begruendung="read by my provider")

The field names of the list and the Beleg are in the API reference and the SDK types; meter your provider on your side.

decuma_ports::bank::BankData (ADR 0051), registered as Bank(Arc<dyn BankData>) the same way as the ports above (Way 1):

Method Answer
accounts() Vec<BankAccountInfo>: {iban, name?, currency}
statement(iban, from, to) BankStatement: {currency, opening_balance: {date, amount}, closing_balance: {date, amount}, transactions: [BankTransaction]}, the booked lines from from to to (inclusive); BankTransaction = {booking_date, value_date?, amount, name?, iban?, reference_text?, bank_reference?, end_to_end_reference?}, amount credit positive with at most two decimals, name and iban of the other side

bank_transaction.fetch {bank_account_id, first_day, last_day} asks the port and hands the statement to bank_transaction.deliver: it is kept as a Beleg, known lines are skipped, and the opening balance must continue the lines held (REST, Books 2: bank import). A statement in another currency than EUR is refused; the port never books. bank_connection.accounts lists what accounts() gives.

Without Rust: the HTTP provider. DECUMA_BANK=http with DECUMA_BANK_URL (and optionally DECUMA_BANK_API_KEY, sent as Authorization: Bearer) asks a service you run in front of your bank:

  • GET {DECUMA_BANK_URL}/accounts answers {"accounts": [BankAccountInfo]}.
  • GET {DECUMA_BANK_URL}/accounts/{iban}/statement?from=YYYY-MM-DD&to=YYYY-MM-DD answers one BankStatement.

Field names as above; dates YYYY-MM-DD, amounts as decimal strings ("-19.50"); unknown fields are ignored. Any status other than 2xx is a failure, refused with conflict and the file import as next step. For example:

{
"currency": "EUR",
"opening_balance": { "date": "2026-01-15", "amount": "10000.00" },
"closing_balance": { "date": "2026-01-16", "amount": "10750.00" },
"transactions": [
{ "booking_date": "2026-01-15", "amount": "800.00", "name": "Beispiel AG", "reference_text": "Rechnung 1", "bank_reference": "R1" },
{ "booking_date": "2026-01-16", "amount": "-50.00", "reference_text": "Kontoführung", "bank_reference": "R2" }
]
}

Under decuma dev, DECUMA_BANK=fake offers what PUT /dev/bank with {account: BankAccountInfo, statement?: BankStatement} set; in tests App::mit_bank_fake().

decuma_ports::bank::BankConsent (ADR 0058), next to BankData and registered as Consent(Arc<dyn BankConsent>): live, read-only access per Mandant through a consent the account holder gives at the bank, valid for a limited time. Each consent is a Bankzugang (bank_connection.*, App contract). No method calls a payment endpoint.

Method Answer
provider() the provider key stored with each Bankzugang
banks(country, psu_type?) Vec<BankInfo>: {name, country, logo?}, the banks of the bank picker (bank_connection.banks); a provider may cache the list for a day
start(aspsp, psu_type, redirect_url, valid_until, state) the URL the account holder opens; the bank sends them back to redirect_url ({installation}/bank/callback) with state and code, or error. aspsp = {name, country}, psu_type business or personal; valid_until the longest validity asked for (180 days), the provider grants at most what the bank allows
complete(code) ConsentSession {session_id, accounts, valid_until}
accounts(session_id) Vec<ConsentAccount>: {identification_hash, uid, iban?, currency, name?, cash_account_type?}; identification_hash is the account’s identity across sessions (the binding key), uid its id in this session
statement(session_id, account_uid, range, psu?) ConsentStatement: {currency, opening_balance?, closing_balance?, transactions, rows_refused}, balances absent when the bank states none (delivered without a balance check), rows_refused the lines the provider could not read (no booking day, another currency, incomplete); range Longest (all history) or Days {from, to}; psu the headers of the person in front of the screen, given only on a read a person started
status(session_id) Active, Expired, Closed or Revoked (at the bank), read after a failed read
revoke(session_id) ends the session at the provider

Errors are ConsentError {code, http_status?, rate_limited}: the provider’s code and status only, never a response body, a session id, a code or a token, since the code reaches last_error, logs and refusals. The session id goes to the secret store (kind bank_session, with the Mandant, the kind and the Bankzugang as associated data; left out of the Mandant export, so DECUMA_SECRET_KEY is needed); callback code, state and session id never enter a payload that is logged, an Event, a log line or an error text; the Command-Log keeps sha256(code); ConsentSession prints its session id as ***.

Wrapping a provider. A provider is extended by another implementation of the trait that holds it and delegates: steps before start (such as registering the account with the provider first) or after revoke. Register the wrapper as the Consent service; nothing else changes.

Under decuma dev, DECUMA_BANK_CONSENT=fake offers the fake (ConsentFake): banks lists five synthetic banks (four in DE, one in FR); start answers the redirect URL itself with state and a fake code, so the whole flow runs without a bank; PUT /dev/bank_consent with {account: ConsentAccount, opening_balance: BankBalance, transactions?: [BankTransaction]} sets an account every session offers. In tests App::mit_consent_fake().

decuma_ports::enable_banking::EnableBanking (ADR 0059) reads accounts, balances and booked lines through Enable Banking’s documented account-information API (https://enablebanking.com/docs/api/reference/), the provider of the consent port of ADR 0058. Bring your own application: register one with Enable Banking for account information, keep its private key on the server, and set DECUMA_BANK_CONSENT=enable_banking with

Variable Meaning
DECUMA_BANK_EB_APP_ID the application id (sent as kid of the request token)
DECUMA_BANK_EB_KEY_FILE path of the application’s private key, PEM (PKCS#8 or PKCS#1); readable only by the server’s user

Every request carries a JWT RS256 (iss enablebanking.com, aud api.enablebanking.com, valid one hour). The provider calls only GET /aspsps, POST /auth, POST /sessions, GET/DELETE /sessions/{id} and GET /accounts/{uid}/details|balances|transactions; no payment endpoint can be built (a test guards it). Redirects are not followed; a proxy from the environment (HTTPS_PROXY) is used.

  • Consent: POST /auth with access.valid_until = the valid_until asked, at most now + the bank’s maximum_consent_validity, and transactions_extended_history: true; the callback code becomes a session (POST /sessions); accounts without an identification_hash are left out. Session status AUTHORIZED is Active, EXPIRED Expired, CLOSED and INVALID Closed, REVOKED Revoked, likewise when the provider refuses the read with EXPIRED_SESSION, CLOSED_SESSION or REVOKED_SESSION; any other status is an error (SESSION_NOT_AUTHORIZED), so the read stays transient.
  • Bank list: EnableBanking::aspsps(country, psu_type?), GET /aspsps, read once a day: name, logo, PSU types, consent length, required PSU headers; banks (the bank picker) gives name, country and logo of the same list.
  • Statements: the first read strategy=longest, later ones strategy=default with date_from/date_to; pages until continuation_key is null; WRONG_CONTINUATION_KEY restarts the range once. PSU headers only on a sync a user started, and then every header the bank requires or none.
  • Mapping, the same for every bank, every optional field may be missing: only BOOK lines; booking date, else value date, else transaction date (none: refused and counted); amount from the decimal string, credit positive (CRDT), debit negative (DBIT); another currency than the account’s: refused and counted; name and IBAN of the debtor for a credit, of the creditor for a debit, the own IBAN dropped; reference text = remittance_information joined by newlines, plus reference_number when not contained; entry_reference is the bank reference; the end-to-end reference from an EREF+ tag; transaction_id is never used. Closing balance from CLBD, else ITBD (never XPCD, CLAV, ITAV), walked to the range (a CLBD without reference_date is not used, an ITBD without one counts as now); without one, or with one dated outside the range, the statement has no balances. Refused lines are counted in rows_refused and in the log line of each read.
  • Errors: a ConsentError with the provider’s error code and HTTP status (HTTP_ERROR when it named none), UNREACHABLE or TIMEOUT without an answer; session ids, code, state and keys never appear in it. ASPSP_RATE_LIMIT_EXCEEDED or 429 sets rate_limited.

decuma_ports::runtime::AgentRuntime (ADR 0051) is for a runtime that runs in the same process. The installation calls on_event(event, toolbox) for each Event of a Mandant that its Agent may read (RuntimeEvent {mandant_id, id, type, data, at}, the body a webhook receives), at least once and in order: none of a Mandant the Account it acts for has no access to, and, without “Sieht Lohn”, none naming a payroll row, as event.poll decides (Policy::event_visible). The Toolbox is bound to the runtime’s Agent on that Mandant and is its only way in:

Method What it is
tools() the tool catalogue (access.tools): name, kind, schemas, Freigabeklasse, marks
query(name, payload) a query, read-only
check(&ToolCall) the dry run (command.check): Verdict::Executable, NeedsHuman(Refusal) or Refused(Refusal); nothing changes, nothing is logged
execute(&ToolCall) the Command as the Agent: Outcome::Executed {output}, NeedsHuman(Refusal) (a confirmation is queued where the Command allows) or Refused(Refusal)

ToolCall = {command, payload, rationale, idempotency_key?, origin?}; rationale is the Begründung stored in the Verlauf, and a Command without one is refused. origin {kind, id, display_name} names what the call comes from (your automation): it is logged with the entry and the Verlauf shows it as the subtitle of the Agent (REST). Refusal = {code, detail, next_step?}. Every call passes the Freigaberichtlinie of the Agent and lands in the Command-Log like a call over REST or MCP.

The Agent acts for an Account: on_behalf_of of AgentToolbox and RuntimeConsumer (in the Actor Agent {id, on_behalf_of}). Every call holds exactly that Account’s rights on the Mandant, as a key it created would: the Inhaber’s are unlimited; a team member’s are those of their Zugriff, “Sieht Lohn” included (payroll queries refused, payroll rows hidden on every surface); on a Mandant the Account has no access to, every call is not_found. Set it to the person the run works for (the one who asked, or who set up a scheduled run). Without one (None) the Agent holds a team member’s standard rights without “Sieht Lohn” and never reads payroll. A Regel or webhook the Agent creates acts within the same Account’s rights.

without_payroll (on AgentToolbox, RuntimeConsumer and the Actor) takes “Sieht Lohn” away from those rights and changes nothing else, also for the Inhaber: payroll queries are refused (not_allowed), payroll rows hidden on every surface (queries, files, exports, history, event.poll) and Commands naming one not_found, as for a team member without the right. Set it for a run no person watches whose results every member of the Mandant sees (a scheduled run acting for the Inhaber); leave it off for a run a person started and reads themselves. Such an Agent sets up no Regel and no webhook (not_allowed): they would act later with the Account’s full rights. A Regel a person set up earlier keeps acting with its owners’ rights as they are, also when a Command of this Agent sets it off; the Agent sees its outcome only through its own reads, without payroll. The Command-Log stores the switch with the Actor ("without_payroll": true), and replays are keyed by it.

Register it as an outbox consumer of your build, as below.

What the runtime does with an Event (which Events it acts on, how it plans, which model it asks, how it avoids reacting to the Events its own Commands cause) is yours; the open build ships no runtime. Test against AgentRuntimeFake, which dry-runs and executes a scripted list of calls on the first Event of a type and keeps every verdict and outcome.

Out of process a runtime needs no port: the same tools are reachable over the wire with an API-Schlüssel, Events by webhook or event.poll (SDKs, the agent loop).

Registering consumers and services at start-up

Section titled “Registering consumers and services at start-up”

A build that compiles the open crates with its own implements decuma_server::Build and calls decuma_server::run(&MyBuild { .. }) from its main; serve and dev then start it without a fork of serve():

  • consumers(&app): outbox consumers (decuma_commands::outbox::Consumer) run by the same dispatcher after the built-in ones (Regeln, decision, webhooks, notifications). Each receives every Event of every Mandant and Account at least once and in order per Mandant, with its own delivery state and dead letters under its name(), so a new consumer starts with the Events already held. Deduplicate by event id. Two consumers under one name stop the start.
  • A service decuma_meldung::eric::EricGuard(Arc<dyn EricAllowed>) in open(..): asked at run time whether a Mandant may use the way eric now (a feature flag as it stands, a Tarif). Its refusal is shown on the way before a Freigabe and refuses every transmission on it before anything begins, also with a certificate stored earlier; without it the way is open wherever the flag eric is on and a certificate is stored.
  • jobs(&app): background services that run while the server runs (the open build’s: the instance clock, once a minute). A job or worker that serves many Mandanten from one queue waits shortly for a busy one with decuma_commands::turn::patient(at_most, future): a Command inside it waits for the turn of its Mandant (or Account) at most at_most, then answers busy (nothing was done, try again later), and never longer than the installation’s TurnWait (30 seconds). Without it one Mandant with a long Command (a transmission takes minutes) holds each of your workers that reaches it for 30 seconds, and the other Mandanten wait behind them. The outbox consumers run inside it already (two seconds, longer after some busy passes).
  • open(..): the App with the services of the build (ports such as Lesung, Entscheidung, Bank) and its extra routes.

The open build registers no consumer of its own: without one, nothing changes. With the agent-runtime port above:

use std::sync::Arc;
use decuma_commands::outbox::Consumer;
use decuma_commands::runtime::RuntimeConsumer;
use decuma_ports::runtime::AgentRuntime;
use decuma_server::{App, Build, Open};
/// The open build plus a runtime of your own.
struct MyBuild {
runtime: Arc<dyn AgentRuntime>,
agent: decuma_core::Uuid,
/// The Account the Agent acts for: its rights, "Sieht Lohn" included, on every Mandant.
on_behalf_of: Option<decuma_core::AccountId>,
}
impl Build for MyBuild {
fn consumers(&self, app: &App) -> Vec<Arc<dyn Consumer>> {
vec![Arc::new(RuntimeConsumer {
name: "my_runtime",
exec: app.exec.clone(),
runtime: self.runtime.clone(),
agent: self.agent,
on_behalf_of: self.on_behalf_of,
// True for a run no person watches whose results every member sees.
without_payroll: false,
})]
}
// Everything else as the open build has it.
fn entries(&self) -> Vec<decuma_commands::Entry> {
Open.entries()
}
fn flags(&self) -> Vec<decuma_commands::Flag> {
Open.flags()
}
fn migrator(&self) -> decuma_store::Migrator {
Open.migrator()
}
fn registrierung(&self) -> decuma_mandant::Registrierung {
Open.registrierung()
}
fn open(
&self,
db: sqlx::PgPool,
clock: Arc<dyn decuma_core::Clock>,
registry: decuma_commands::Registry,
ablage: decuma_belege::Ablage,
dev: bool,
) -> anyhow::Result<(App, axum::Router)> {
Open.open(db, clock, registry, ablage, dev)
}
}

This example is compiled and run by crates/decuma-server/tests/startup.rs.