Skip to navigation
Machines

Machine language

Beta

The procedure document (bm-procedure/2): inputs, tools, values, steps, errors and lints.

View as Markdown

Machines are in beta. The language can get new keys and new lints before general availability. A saved version never changes.

A procedure is a JSON document that says what a Machine does, step by step. The compiler checks it against the schemas of its tools and writes a program, the IR. The engine runs the IR. Read Machines for the run loop.

This page is the reference for a person or a model that writes a procedure. POST /v2/machines/lint checks a procedure and gives each problem with its path. Read Lints.

The examples on this page use an equipment rental company. Its tools are examples only.

The procedure document

{
"language": "bm-procedure/2",
"procedure": "rental-return",
"description": "Close a rental contract from a return form, with its extra charges.",
"inputs": {
"user_message": { "type": "string" },
"f1": { "type": "file", "description": "the return form" }
},
"tables": { "fees": { "fuel": "FEE-FUEL", "cleaning": "FEE-CLEAN", "damage": "FEE-DAMAGE" } },
"invariants": [],
"steps": [],
"finish": { "status": "done", "report": "Contract {{@contract.contract_id}} is closed." }
}
KeyRequiredMeaning
languageYesAlways "bm-procedure/2".
procedureYesThe id of the procedure: ^[a-z0-9][a-z0-9-]{0,79}$.
descriptionNoA text for people.
inputsYesThe inputs of a run, by name. Read Inputs.
tablesNoFixed lookup tables, by name. Read Table lookup.
invariantsNoRules that the engine checks before each write. Read Invariants.
stepsYesThe list of steps. Read Steps.
finishYesWhat happens at the end of steps: status (default done) and a report template.

Names

Step ids, input names, table names and as names match ^[a-z][a-z0-9_]{0,39}$. Each name is unique in the procedure. These names are reserved: input, tables, result, args, error, self, item, true, false and null.

Inputs

Each input has a type: "file", "string", "number", "boolean" or "object". An input can also give a JSON Schema in schema.

  • A file input has the type {file_id, name, content_type, bytes}. Read the id with @input.f1.file_id. A run gets a file as a URL or as the id of a file of the organization.
  • "later": true marks an input that arrives after the start, for example a second message. Read a later input only after an await step that names it.
  • The message of turn 1 is the string input user_message. The message of turn n is user_message<n> (user_message2, and so on), declared later. No other name carries a user message. A step id cannot be a message name.
  • The exception model and a person get the messages that arrived, by these names.

Tools and types

The compiler gets a tool list in the MCP shape: a JSON array, or {"tools": [...]}.

{
"name": "rent_find_contract",
"description": "Find a rental contract by its number.",
"inputSchema": {
"type": "object",
"properties": { "contract_number": { "type": "string" } },
"required": ["contract_number"]
},
"outputSchema": {
"type": "object",
"properties": {
"contract_id": { "type": "string" },
"status": { "type": "string", "enum": ["open", "closed"] },
"balance": { "type": "number" }
},
"required": ["contract_id", "status", "balance"]
},
"annotations": { "readOnlyHint": true },
"x-errors": {
"contract_not_found": {
"type": "object",
"properties": { "code": { "const": "contract_not_found" }, "message": { "type": "string" } }
}
}
}
KeyMeaning
nameThe tool name. The prefix machine_ is reserved. A file_ name of a Paperwork tool is reserved too.
inputSchema (or input_schema)Required. The JSON Schema of the arguments.
outputSchema (or output_schema)The JSON Schema of a success output. A reference into the output of a tool with no output schema does not compile (ref-untyped).
x-errorsThe error codes of the tool, each with the schema of its error output {code, message, ...}. With x-errors, an on_error case for an unknown code does not compile (error-code).
annotations.readOnlyHinttrue sets the default effect read.
x-effectread, write or irreversible. It replaces the default effect. With no annotation and no x-effect, the effect is write.

A step can raise the effect of its tool, for example from write to irreversible. A step cannot lower it.

The compiler reads this subset of JSON Schema: type, properties, required, items, enum, const, anyOf, additionalProperties, pattern and format. It accepts other keys and ignores them.

An output schema can depend on an argument. The node {"x-from-arg": "schema"} takes the type of that literal argument. The output of file_extract is {file_id, value}, and value has the shape of the schema argument. So the compiler checks @form.value.contract_number against the extraction schema that the step sends.

Paperwork tools

The engine runs the file_* tools itself, with the Paperwork API of your organization. The tool list does not repeat them. Their effect is read, and a step cannot raise it (builtin-effect). A Paperwork step bills as a Paperwork call.

ToolArgumentsOutput
file_parsefile_id{file_id, name, format, text}: the file as markdown.
file_extractfile_id, schema, instructions{file_id, value}: value has the shape of schema.
file_classifyfile_id, classes (2 to 50 {id, description}), granularity, instructions{file_id, granularity, class_id, confidence, reasoning, segments, unassigned_pages}
file_splitfile_id, segments ({start_page, end_page, class_id?})A list of {file_id, name, start_page, end_page, class_id}.
file_filltemplate_file_id, values or source_file_ids, instructions{file_id, name, fields}
file_redactfile_id, categories, instructions{file_id, name, content_type, bytes, entities}
file_convert_pdffile_id{file_id, name}
file_render_pagefile_id, page, scale{file_id, name}: a PNG image of the page.
file_mergefile_ids (2 to 20), name{file_id, name}

Values

An argument value (in args, retry_with, use, context, attach and the input of a code step) is one of the forms below.

You wantWrite
A fixed valueThe literal: "CAD", 12, true
A field of an earlier result"@contract.contract_id", "@form.value.charges[0].amount"
A file or a message"@input.f1.file_id", "@input.user_message"
The current item of a loop"@charge.amount" (the as name of the foreach)
A value from a table{"lookup": "fees", "key": "@charge.category"}
A row of a list{"find": "@depot.contacts", "where": {"role": "manager"}, "take": "phone"}
A text with values{"template": "Contract {{@contract.contract_id}} is on hold."}
A computed value{"expr": "contract.balance - contract.deposit", "schema": {"type": "number"}}
An argument that a step sent"@sent.book.slot"

Literal

Any JSON value is a literal. A string that starts with @ is a reference: write @@x for the text @x. An object with the key lookup, find, template or expr is a value form. To send such an object as data, wrap it: {"literal": {...}}.

Reference

A reference is "@<name><path>".

  • <name> is a step id, input, the as name of an enclosing foreach, error (in an on_error case), self (in compensate: the output of the step), tables or sent.
  • <path> is zero or more of .key, [n], ["any key"] and [*] (each item of a list).
  • The reference replaces the whole string. There is no interpolation in a reference: use a template.
  • The compiler checks each key against the schema of its level. A key that the tool does not return does not compile. The message lists the keys that exist.
  • A key that the schema does not list in required gives the warning ref-optional.

@sent.<step>.<arg> reads the arguments that a tool step sent. After a retry_with, it reads the last call. In an error case of that step, it reads the call that failed. Use it when a later step needs a value that the tool does not return. In an expression, write sent.<step>.<arg>.

Order of references

The referenced step must run before the value on every path (ref-order).

  • A step inside a when case is visible in that case. After the when, an expression can read it: it is null when its case did not run. An argument can read it only when each path that continues defines it.
  • A step is tested inside a when case whose if reads the step, and after a check step that reads it. An argument can read a tested step, also when it ran only on some paths or when an error case can skip it. The engine still gives the error ref_error when the value is null at run time.

Scope of foreach

  • In the body of a foreach, the as name is the current item. A step of the body, read in the body, is the output for the current item.
  • Outside the body, a step of the body is a list: one entry per item, in item order. An item that where skipped, or a when that did not run the step, gives null. Loop over such a list with a where that tests != null.
  • Nested loops apply the same rule at each level.

Table lookup

  • {"lookup": "fees", "key": <value>} gives the value of the key in the table fees. Keys match after trim and lower case. "default": <literal> gives the value when no key matches.
  • {"lookup": {"a": 1, "b": 2}, "key": <value>} uses an inline table.
  • {"find": <list>, "where": {"<key>": <value>}, "take": "<path>"} gives the first item where each key equals the value (strings after trim and lower case), then the path in that item. With no take, it gives the whole item. default applies as above.
  • A miss with no default is a step error with the code lookup_miss. The on_error of the step applies, and the default is a hold.

Template

{"template": "Charge {{@add.charge_id}} is on contract {{@contract.contract_id}}."} gives a string. Each {{@ref}} is a reference. A string shows as it is, and another value shows as JSON.

The report of finish is a template string. In a report, a placeholder can read a step that ran only on some paths, or a step in a loop ({{@add[*].charge_id}}). A value that is null or absent shows as -.

Expression

{"expr": "<expression>", "schema": <JSON Schema of the result>}. The expression language is RakeXL (@cloudraker/rakexl 1.4.6), a JEXL dialect.

  • Names in an expression: step ids, input, as names and tables. By place, also result (in expect), args (in require) and error (in an on_error case if). A step that did not run is null.
  • The compiler checks each identifier path as it checks a reference.
  • In the expression string of filter, map or find, only value, index and array exist. To compare with an outer value, use a code step.
  • A function that is not deterministic does not compile (expr-nondeterministic): now, millis, uuid, uid, random, shuffle and the date functions with no input.

Steps

A step is an object with an id and exactly one kind key: tool, ask, code, check, when, foreach, await, hold or finish. Each step can also have a note, a text for the person who reads the procedure. Steps run in the order of the list.

Tool step

{
"id": "add",
"tool": "rent_add_charge",
"args": { "contract_id": "@contract.contract_id", "fee_code": "FEE-FUEL", "amount": "@form.value.fuel" },
"effect": "write",
"limit": 2,
"require": [{ "check": "args.amount > 0", "message": "the charge is positive" }],
"expect": [{ "check": "result.charge_id != null", "message": "the ERP gave a charge id" }],
"on_error": {
"cases": [{ "code": "contract_locked", "then": { "retry_with": { "contract_id": "@error.open_contract_id" } } }]
},
"compensate": { "tool": "rent_remove_charge", "args": { "charge_id": "@self.charge_id" } }
}
KeyMeaning
argsThe arguments, by name. The compiler checks them against inputSchema: required arguments, unknown arguments, types and literals.
effectread, write or irreversible. The default comes from the tool. A step can raise it, not lower it.
limitThe most calls of the tool in one activation of the step (one item of a loop) that can have run. Read Limit.
requireChecks before the call, on args and earlier steps. A failure does not call the tool: the step fails with the code require_failed.
expectChecks after a success, on result. A failure makes the step fail with the code check_failed.
on_errorWhat to do when the call fails. Read Errors and the exception ladder.
compensateA tool call that undoes this step. @self is the output of this step. Read Compensation.
idempotenttrue when the tool accepts an idempotency key, so the engine can send the call again after a timeout.
allow_repeattrue when the step can call its tool two times in one run with the same arguments. Read Repeated writes.

A check is an expression string, or {"check": expr, "message": text}. It passes only when its value is truthy and nothing throws.

Limit

limit counts the first call, each retry after a timeout or a network error, and each retry_with. A call that got a 429 or 503 answer did not run, so it does not count. The default is 1 + retry.max for a read or idempotent step, else 1. Add 1 when a case has retry_with. An irreversible step must have "limit": 1.

Ask step

An ask step gets one value that the procedure cannot compute: a label, a choice or a short text.

{
"id": "fee",
"ask": "The fee code of the charge {{@charge.description}}.",
"context": ["@charge"],
"answer": { "enum": { "table": "fees", "of": "values" } },
"rung": ["decide", "model", "person"],
"min_confidence": 0.8
}
  • ask is the question: a text with optional {{@ref}} parts, or {"template": text}.
  • answer (required) is the JSON Schema of the answer, with a type or an enum. An empty schema {} does not compile. {"enum": {"table": t, "of": "values"}} takes the enum from a table ("keys" takes its keys). The output of the step has this type.
  • rung is the list of answerers, in order. The default is ["model", "person"].
    • decide: a decision model. It answers an enum or a boolean only (ask-decide).
    • model: the exception model, with a grammar made from answer.
    • person: the run stops with a hold. The client sends the answer. Read Answer a hold.
  • The engine goes to the next rung when a rung gives no valid answer, or a confidence under min_confidence.
  • context lists the values that the answerer sees. The exception model and a person also see the receipts of the run.
  • A string answer with no enum and no pattern gives the warning ask-enum.

An answer that can come from model is unchecked data, as an extraction is. A document can steer a model to a wrong value, also inside an enum. A closed answer (an enum or a boolean) counts as checked only when the rungs start with decide and min_confidence is set. Otherwise, a check that reads the answer must run before a write uses it (write-unchecked).

Code step

A code step maps data when an expression cannot: it merges two lists, removes duplicates or picks the row whose dates cover a date.

{
"id": "rate",
"code": "export default function ({ cards, date }) {\n const hit = cards.find((c) => c.valid_from <= date && date <= c.valid_to);\n return hit ? hit.rate_card_id : null;\n}",
"input": { "cards": "@cards.rate_cards", "date": "@form.value.pickup_date" },
"returns": { "type": ["string", "null"] },
"timeout_ms": 50
}
  • The code is a JavaScript module with a default export. It gets input and gives a JSON value.
  • It runs in an isolated sandbox with no network. JSON goes in and JSON comes out.
  • returns (required) is the type of the output. An output that does not match is a step error with the code code_failed.
  • The effect of a code step is always read.
  • Limits: 64 KiB of source, 256 KiB of input and of output, and timeout_ms of at most 1000.

Check step

{ "id": "is_open", "check": "contract.status == 'open'", "message": "the contract is open", "else": [] }

A false check runs else. The default else is a hold with the message as the reason. A check step that reads an extraction or a model answer marks those values as checked.

When block

{
"id": "route",
"when": [
{ "if": "contract.balance > 1000", "then": [{ "id": "hold_balance", "hold": "The balance is over 1,000." }] }
],
"else": []
}

The first case whose if is truthy runs. else is required (when-else): a list of steps, [] for “nothing to do”, or {"hold": "reason"}. An if that throws counts as false.

Foreach block

{
"id": "each_charge",
"foreach": "@form.value.charges",
"as": "charge",
"where": "charge.amount > 0",
"distinct": "charge.category",
"max_items": 20,
"do": []
}
  • foreach is a list value: a reference, an expr or the output of a code step.
  • as (required) is the name of the item. where is a filter expression.
  • distinct is an expression on the item. The loop skips an item whose value it saw before, and logs it.
  • max_items: more items is a step error with the code too_many_items, and the default is a hold. With no max_items, the compiler gives the warning foreach-max.
  • Items run in order, one at a time.

Hold

{ "id": "hold_rate", "hold": "The quoted rate is not the rate of the rate card.", "attach": ["@form", "@ratecard"] }

A hold step ends the run with the outcome held. A person gets the reason (a text or a template) and the attached values, and finishes the work outside the run. The reason is required (hold-reason). A hold step does not run the compensations.

An ask with the rung person also stops the run, but that hold can resume: the client sends the answer and the run continues.

Await

{ "id": "second_turn", "await": ["user_message2", "f2"] }

The run waits until each named later input arrives. Read a later input only after its await (await-order).

Finish

{ "id": "refuse", "finish": "refused", "report": "The return is refused: the contract is closed." }

The status is done, refused or aborted. The run ends. aborted runs the compensations.

Order and reachability

A step after a hold or a finish in the same list never runs, so it does not compile (unreachable). The top-level finish applies when the run gets to the end of steps.

Invariants

"invariants": [
{ "name": "no close with an open damage claim",
"check": "!(call.tool == 'rent_close_contract' && calls|any('value.tool == \"rent_open_claim\"'))" }
]

The engine checks each invariant before each write or irreversible call. call is {tool, step, args}, and calls is the list of the done calls [{tool, step, args, output}]. A false invariant does not run the call: the run holds.

Errors and the exception ladder

on_error

"on_error": {
"retry": { "max": 2, "codes": ["contract_busy"] },
"cases": [
{ "code": "contract_not_found",
"do": [{ "id": "byplate", "tool": "rent_find_by_plate", "args": { "plate": "@form.value.plate" } }],
"then": { "use": "@byplate" } },
{ "code": "unit_retired", "then": { "retry_with": { "unit_number": "@error.replacement_unit" } } },
{ "code": "duplicate", "if": "error.message|contains('closed')", "then": "skip" }
],
"else": { "patch": "model", "max": 1 }
}

Transient errors

retry is {"max": n, "codes": [...]}. The default max is 2. The engine knows two classes of transient error:

  • Not run: HTTP 429 and 503, with the codes rate_limited and unavailable. The answer proves that the call did not run. The engine retries it on every effect, at most retry.max times, with backoff. These retries do not count toward limit.
  • Unknown outcome: a timeout, a network error, HTTP 500, 502 and 504, with the codes timeout and network. The call can have run. The engine retries only a read step or an idempotent step, within retry.max and limit. Another step holds at once with the code unknown_outcome.

codes adds codes of the tool to the not-run class, for example a code that the tool documents as “nothing changed”. timeout or network in codes of an irreversible step does not compile (irreversible-retry).

Do not write cases for transient errors. The engine does that work.

Cases

The engine tries the cases in order. A case matches the error code, and its optional if. The steps of its do run, then its then applies:

thenWhat happens
{"retry_with": {arg: value}}The engine calls the same tool again with these arguments changed. It counts toward limit.
{"use": value}The value becomes the output of the failed step. It must have each path that a later step reads (use-type).
"skip"The output of the step is null. No argument can read the step (skip-ref). Read it only in a when that tests it.
"hold" or {"hold": reason}The run holds. This is the default.
{"finish": status, "report": text}The run ends with this status and report.

The steps of a case do stay visible after the step, as the steps of a when case do.

A failed require or expect is an error with the code require_failed or check_failed, and error.message is the message of the check. It goes to cases and else, never to retry.

Retry of a write

On a write step, each value of retry_with must come from a source that you trust (retry-unverified):

  • @error.<key> of a tool of your list, when its x-errors schema for that code declares <key>. Your system names the replacement.
  • A tool output, a table lookup, a literal, or the answer of an ask with "rung": ["person"].

A value that passed through a model answer, a decision model answer or a document extraction is not allowed. The compiler follows the value through code steps and expressions. A document value can select a row of a tool list (a find over the list): the value comes from the tool. When no value that you trust exists, hold with the reason, or ask a person in the case do.

else

else applies when no case matches:

  • "hold": the default.
  • {"classify": "decide"} or {"classify": "model"}: the decision model or the exception model picks one of the case codes of the step, or none. A pick goes back to the cases with that code.
  • {"patch": "model", "max": n}: the exception model writes only the arguments to change, under a grammar made from inputSchema. A patch that changes nothing fails the rung.
  • {"patch": "person", "max": n}: the run stops with a hold that can resume. A person sends the arguments to change.

The ladder

The engine applies the rungs in a fixed order:

  1. Transient retry, as above.
  2. Procedure branch: the first case that matches.
  3. Decide: else: {"classify": "decide"}.
  4. Model: else: {"patch": "model"} or {"classify": "model"}.
  5. Person: a hold with the error, the step and the receipts.

The run log marks each hold that a rung from 3 to 5 gives, each error that no case matched and each invariant hold. Read these marks to change the procedure.

When the exception model is off for a run (options.exception_model: "off"), or not available, each model rung goes to the next rung.

Unknown outcome

A call can start and give no result, for example after a crash. A read call and an idempotent call run again with the same idempotency key. The engine does not send a write call (with no idempotent) or an irreversible call again: the run holds with the code unknown_outcome.

Repeated writes

A write or irreversible step does not call the same tool with the same arguments two times in one run. The engine compares the arguments as JSON with sorted keys. A repeat does not run: the step fails with the code repeat_write, and the default is a hold. This catches a list that has the same item two times.

  • "allow_repeat": true on the step turns off the rule. Two equal items can be two orders.
  • distinct on a foreach skips the repeated items before a step runs.
  • retry_with and the transient retries are the same activation, not a repeat.

Compensation

compensate is allowed on write steps only (compensate-effect). When the run ends with aborted, the engine calls the compensations of the done steps, in the reverse order of completion. The log records each compensation. A failed compensation holds the run. A hold and a cancel do not compensate: a person decides.

Lints

The compiler gives one diagnostic per problem: {level, code, path, message}. The path is the place in the procedure, for example steps[3].do[1].args.amount. The message says what to change.

An error stops the compile. A warning does not, unless the request has "strict": true.

CodeLevelRule
shapeerrorThe document does not match the procedure schema: an unknown key, two kind keys or a bad name.
dup-id, reserved-iderrorIds are unique and not reserved.
unknown-toolerrorThe tool is not in the tool list or in the Paperwork tools.
ref-unknownerrorA reference or an expression names no step, input, table or loop item.
ref-patherrorA key or an index is not in the schema of that level. The message lists the keys that exist.
ref-untypederrorA reference reads into a tool with no output schema.
ref-ordererrorThe referenced step does not run before this place on every path.
ref-optionalwarningThe key is not in required, so it can be absent.
arg-missing, arg-unknown, arg-typeerrorThe arguments do not match inputSchema.
expr-compile, expr-nondeterministicerrorThe expression does not compile, or calls a function that is not deterministic.
when-elseerrorA when has no else.
irreversible-limiterrorAn irreversible step has no "limit": 1.
irreversible-retryerrorAn irreversible step can call again after a call that can have run: retry_with, timeout or network in retry.codes, or idempotent.
irreversible-uncheckederrorNo check runs before an irreversible step on every path: a require, a check step, an expect or a when before it.
write-uncheckederrorA write uses a value from file_extract or a model answer, and no check reads that value before the write.
ask-schemaerrorAn ask has no answer, or an empty one.
ask-decideerrorThe rung decide with an answer that is not an enum or a boolean.
ask-enumwarningA string answer with no enum and no pattern.
hold-reasonerrorA hold has no reason.
unreachableerrorA step after a hold or a finish in the same list, or a case for a code that the tool never answers.
error-codeerrorAn on_error code that the tool does not declare in x-errors.
retry-unverifiederrorOn a write, a retry_with value comes from a model answer or an extraction, or reads an @error key that the tool does not declare.
use-typeerrorA use value does not have a path that a later step reads.
skip-referrorskip on a step that an argument reads.
await-ordererrorA later input is read before its await.
compensate-effecterrorcompensate on a step that is not a write.
unused-outputwarningNothing reads the output of a read step, an ask or a code step.
foreach-maxwarningA foreach has no max_items.

The API adds these checks of the tool list and of the size:

CodeRule
tool-listThe tool list is not a list or {"tools": [...]}, or a tool has no name or no inputSchema.
tool-reserved-nameA tool name starts with machine_.
builtin-tool-nameA tool name is the name of a Paperwork tool. Remove the entry.
builtin-effectA step raises the effect of a Paperwork tool above read.
procedure-too-largeThe procedure is larger than 256 KiB.
too-deepThe procedure or the tool list has more than 128 levels of nesting.
too-many-stepsThe compiled program has more than 2,000 instructions.
ir-too-largeThe compiled program is larger than 1 MiB.
code-too-largeThe source of a code step is larger than 64 KiB.
code-timeout-too-largeThe timeout_ms of a code step is more than 1000.

Write a procedure

Before you save: the checklist of the compiler

  1. Each key that you read exists in the output schema of its tool, or in the extraction schema.
  2. Each when has an else.
  3. Each irreversible step (a payment, a submit, a release, an approval) has "limit": 1, no retry, and a check before it.
  4. Each write uses extracted values only after a check that reads the extraction. An expect on the extraction is enough.
  5. Each ask has an answer schema. Each hold has a reason.
  6. Each required argument of a tool has a value of the correct type.
  7. The report names the reference numbers that the process asks for: {{@close.invoice_number}}.

When the process text does not settle something

A run must finish the work for a normal input. An ask that no answerer can get right stops every run. Before you write an ask, name who answers it on every run, and from what data.

  1. A step with no rule. The text says “check the open rentals of the customer”, but gives no rule that blocks the work. Call the read tool and show its result in the report. Do not add an ask or a check that decides from it.
  2. A required argument that the text does not give:
    • A key of a record (an id, an account, a number): take it from a tool output, the document or the message. When nothing can give it, hold with a reason.
    • An amount, a quantity or a date: take it from the document or a tool output only. Never from an ask.
    • A free text label of a new record (a charge code, a category): ask the exception model with a pattern and the context that it needs. Then add a check step that reads the answer, before the write. Use "rung": ["model", "person"], not ["person"] alone.
  3. Hold only where the text says to stop: a refusal, a mismatch or a limit that the text gives.
  4. A retry of a write takes a value that your system gave. Read Retry of a write.

Worked examples

A lookup that can find nothing

{ "id": "customer", "tool": "rent_find_customer", "args": { "account_number": "@form.value.account_number" },
"on_error": { "cases": [{ "code": "customer_not_found", "then": "skip" }] } },
{ "id": "if_known", "when": [{ "if": "customer != null", "then": [
{ "id": "contract", "tool": "rent_create_contract", "args": { "customer_id": "@customer.customer_id" } } ] }],
"else": [
{ "id": "setup", "tool": "rent_request_account_setup", "args": { "company_name": "@form.value.company_name" } } ] }

After skip, read the step in an argument only inside a when whose if reads it.

Error recovery with another tool

{ "id": "unit", "tool": "fleet_find_unit", "args": { "unit_number": "@form.value.unit_number" },
"on_error": { "cases": [{ "code": "bad_format",
"do": [{ "id": "byplate", "tool": "fleet_search_by_plate", "args": { "plate": "@form.value.plate" } }],
"then": { "use": "@byplate" } }] } },
{ "id": "book", "tool": "rent_reserve_unit", "args": { "unit_number": "@form.value.unit_number" },
"on_error": { "cases": [{ "code": "unit_retired", "then": { "retry_with": { "unit_number": "@error.replacement_unit" } } }] } }

When the error output names the fix (replacement_unit), use @error.<key> in retry_with. No model is necessary. The x-errors schema of the code must declare the key.

A label that the model writes

{ "id": "charge_code", "ask": "A short charge code for a damage charge on contract {{@contract.contract_id}}.",
"context": ["@open_charges.charges"], "answer": { "type": "string", "pattern": "^[A-Z][A-Z0-9_-]{1,15}$" },
"rung": ["model", "person"] },
{ "id": "charge_code_ok",
"check": "!(open_charges.charges|map('value.code')|contains(charge_code))",
"message": "the charge code is new" },
{ "id": "charge", "tool": "rent_add_charge",
"args": { "contract_id": "@contract.contract_id", "fee_code": "@charge_code", "amount": "@form.value.damage_amount" } }

A value that an earlier step sent

{ "id": "close", "tool": "rent_close_day",
"args": { "depot": { "expr": "(sent.book|find('value != null')).depot", "schema": { "type": "string" } } } }

The tool rent_reserve_unit does not return the depot, but the step book sent it. Outside a loop, sent.book is a list.

Merge two lists, each person once

{ "id": "drivers",
"code": "export default function ({ primary, extra }) {\n const seen = new Set(); const out = [];\n for (const p of [...(primary ?? []), ...(extra ?? [])]) {\n const key = String(p.licence_number).trim().toLowerCase();\n if (!seen.has(key)) { seen.add(key); out.push({ full_name: p.full_name, licence_number: p.licence_number }); }\n }\n return out;\n}",
"input": { "primary": "@form.value.primary_drivers", "extra": "@addendum.value.additional_drivers" },
"returns": { "type": "array", "items": { "type": "object",
"properties": { "full_name": { "type": "string" }, "licence_number": { "type": "string" } },
"required": ["full_name", "licence_number"] } } }

Frequent compiler errors

Error (shortened)Fix
ref-path ... has no key "status". Keys: inspection_id, outcome, notesUse a key from the list. The tool list shows the output schema.
ref-path ... is a list, not an object: use [n] or [*]The step is in a loop, so outside the loop it is a list. Read it in the loop, or use an index.
write-unchecked ... uses "form" (an extraction)Add an expect to the extraction, for example result.value.total > 0.
write-unchecked ... uses "x" (a model answer)Add a check step that reads the answer. For an enum, use "rung": ["decide", "model", "person"] and min_confidence.
irreversible-limit ... set "limit": 1Add "limit": 1 to the step.
irreversible-unchecked ... no check runs before itAdd a require with the business rule, for example args.amount <= form.value.total.
ref-order ... runs only in some branches before this placeMove the step that reads it into the branch, or put it in a when whose if reads the value.
when-else ... has no elseAdd "else": [], or "else": {"hold": "reason"}.
arg-missing or arg-unknownGive each required argument. Use only the argument names of the tool.
error-code ... never answers the error code "not_found"Use a code from the list in the message.
retry-unverified ... takes a value of the document extractionRetry with @error.<key>, a tool output, a table or the answer of a person. Else hold.

A full example

This procedure closes a rental contract from a return form. It compiles with the tool list below it.

{
"language": "bm-procedure/2",
"procedure": "rental-return",
"description": "Close a rental contract from a return form, with its extra charges.",
"inputs": {
"user_message": { "type": "string" },
"f1": { "type": "file", "description": "the return form" }
},
"tables": { "fees": { "fuel": "FEE-FUEL", "cleaning": "FEE-CLEAN", "damage": "FEE-DAMAGE" } },
"steps": [
{
"id": "form",
"tool": "file_extract",
"args": {
"file_id": "@input.f1.file_id",
"schema": {
"type": "object",
"properties": {
"contract_number": { "type": "string" },
"charges": {
"type": "array",
"items": {
"type": "object",
"properties": { "category": { "type": "string" }, "amount": { "type": "number" } },
"required": ["category", "amount"]
}
}
},
"required": ["contract_number", "charges"]
}
},
"expect": [{ "check": "result.value.contract_number|length > 0", "message": "the form has a contract number" }]
},
{
"id": "contract",
"tool": "rent_find_contract",
"args": { "contract_number": "@form.value.contract_number" },
"on_error": {
"cases": [
{
"code": "contract_not_found",
"then": { "finish": "refused", "report": "No contract has the number {{@form.value.contract_number}}." }
}
]
}
},
{ "id": "is_open", "check": "contract.status == 'open'", "message": "the contract is open" },
{
"id": "each_charge",
"foreach": "@form.value.charges",
"as": "charge",
"where": "charge.amount > 0",
"max_items": 20,
"do": [
{
"id": "add",
"tool": "rent_add_charge",
"require": [{ "check": "args.amount <= 5000", "message": "one charge is at most 5,000" }],
"args": {
"contract_id": "@contract.contract_id",
"fee_code": { "lookup": "fees", "key": "@charge.category" },
"amount": "@charge.amount"
}
}
]
},
{
"id": "route",
"when": [
{
"if": "contract.balance > 1000",
"then": [{ "id": "hold_balance", "hold": "The balance is over 1,000. A person must approve the close.", "attach": ["@contract"] }]
}
],
"else": []
},
{
"id": "close",
"tool": "rent_close_contract",
"effect": "irreversible",
"limit": 1,
"require": [{ "check": "contract.balance <= 1000", "message": "the balance is at most 1,000" }],
"args": { "contract_id": "@contract.contract_id" }
}
],
"finish": {
"status": "done",
"report": "Contract {{@contract.contract_id}} is closed with invoice {{@close.invoice_number}}. Charges: {{@add[*].charge_id}}."
}
}
{
"tools": [
{
"name": "rent_find_contract",
"description": "Find a rental contract by its number.",
"inputSchema": { "type": "object", "properties": { "contract_number": { "type": "string" } }, "required": ["contract_number"] },
"outputSchema": {
"type": "object",
"properties": {
"contract_id": { "type": "string" },
"status": { "type": "string", "enum": ["open", "closed"] },
"balance": { "type": "number" }
},
"required": ["contract_id", "status", "balance"]
},
"annotations": { "readOnlyHint": true },
"x-errors": {
"contract_not_found": { "type": "object", "properties": { "code": { "const": "contract_not_found" }, "message": { "type": "string" } } }
}
},
{
"name": "rent_add_charge",
"description": "Add a charge to a contract.",
"inputSchema": {
"type": "object",
"properties": { "contract_id": { "type": "string" }, "fee_code": { "type": "string" }, "amount": { "type": "number" } },
"required": ["contract_id", "fee_code", "amount"]
},
"outputSchema": { "type": "object", "properties": { "charge_id": { "type": "string" } }, "required": ["charge_id"] }
},
{
"name": "rent_close_contract",
"description": "Close a contract and send the final invoice.",
"inputSchema": { "type": "object", "properties": { "contract_id": { "type": "string" } }, "required": ["contract_id"] },
"outputSchema": { "type": "object", "properties": { "invoice_number": { "type": "string" } }, "required": ["invoice_number"] },
"x-effect": "irreversible"
}
]
}

Limits

LimitValue
Procedure256 KiB
Tool list512 KiB and 200 tools
Nesting of the procedure or tool list128 levels
Compiled program1 MiB and 2,000 instructions
Code step source64 KiB
Code step input and output, each256 KiB
Code step timeout_ms1000