Skip to content

Workflows API

A workflow is a versioned, gateway-scoped DAG of typed steps — Trigger, Agent-Step, Condition, Human-Approval, Deliver — authored in the visual builder, rendered as a vertical chain/tree and stored as a directed acyclic graph (graph_json). A workflow is edited as a draft, then published to an immutable, semver-tagged snapshot (workflow_version); a run is bound to the exact version it started on, so a later publish never mutates a running or suspended run.

A manual run always executes the latest published version, never the unsaved draft. So the caller can tell when the draft has diverged, GET /admin/v1/gateways/{gateway_id}/workflows/{id} returns has_unpublished_changes (boolean): true when the draft graph_json differs from the published version a run would execute — publish first to run the edits. It is false when the draft is in sync or the workflow was never published. If the published version cannot be read, the detail answers 503 { "error": "temporarily unavailable; retry later" } (retry) — never a silent false.

Runs are executed by a dedicated runner process (scripts/workflow_runner.py) that claims pending runs via a compare-and-swap lease and persists progress after every step, so a resumed/replayed run in a fresh process resolves data-flow references from durable state.

Admin endpoints require an authenticated admin session. Base URL: https://ai-api-admin.myra.eu/admin/v1. The whole feature is gated per workspace by tenant.workflows_enabled (default off, fail-closed): every admin workflow route returns 403 { "error": "feature_disabled", "feature": "workflows" } until an Admin enables it (a failed read of the flag answers 503). Every gateway-scoped route first checks gateway access: a gateway of another tenant answers 404.

That workspace flag is flipped through its own route. It needs the WORKFLOWS_FEATURE_TOGGLE permission and the platform-admin role (role == "admin"): a tenant admin, or a custom role granted the permission, receives 403 — stricter than the require_author gate the workflow routes themselves use:

POST /admin/v1/gateways/{gateway_id}/workflows-feature with { "enabled": <boolean> } -> 200 { "enabled": <boolean> }. A body that is not valid JSON or not a JSON object is 400 malformed_body; an absent or blank body is read as no fields, so enabled is missing and the answer is 400 enabled (boolean) required (as for a non-boolean enabled). The SPA changes the same flag through the audited tenant PATCH (workflows_enabled); this route writes no audit record.


Authorization matrix (server-side; the client is never the authz boundary)

Action Who
create / seed example any authoring user — member, ki_manager, tenant_admin, admin (require_author; viewer/demouser → 403)
edit / publish / rollback / configure triggers (webhook, form, email) + schedule / re-enable (status published) owner-only: the workflow's creator (created_by). A same-tenant tenant_admin or a platform admin who can see the workflow gets 403 workflow_owner_only (admins can no longer edit); any other authoring user gets 404 not_found (never 403 — the id is not an existence oracle). Nothing is written in either case
delete / disable (status disabled) / cancel a run the workflow's owner, or a same-tenant tenant_admin / platform admin (a containment action). Anyone else gets 404; viewer/demouser → 403
read a workflow (list, detail with graph_json, versions, versions-diff, webhook/form/email/schedule config, copilot-validate) owner or admin only (require_author; viewer/demouser → 403). The list returns the caller's own workflows; a same-tenant tenant_admin and a platform admin get every workflow of the gateway. A workflow the caller may not see is 404 not_found, identical to an unknown id. List rows and the detail carry created_by and is_owner (the detail is { "workflow": { ..., "is_owner", "created_by" } })
trigger / run (manual) the workflow's owner or an admin (same visibility rule); anyone else gets 404. The run always executes as the workflow owner (created_by), whoever starts it (an admin's manual run included)
view runs (list + detail) run visibility equals workflow visibility: whoever may see the workflow sees all its runs (owner, same-tenant tenant_admin, platform admin); everyone else gets 404 (run_not_found for run detail). There is no per-run scoping and WORKFLOWS_RUN_VIEW_ALL is no longer consulted; a viewer/demouser → 403
enable / disable the feature for a tenant (workflows-feature) Platform admin only (role == "admin")
cancel a run the owner of the run's workflow, or a same-tenant tenant_admin / platform admin; anyone else gets 404 run_not_found (previously 403); requires an authoring session (require_author; viewer/demouser → 403)
approve / reject a suspended run only the node's named approver user (checked server-side); any authenticated user can be a named approver — the approver inbox is not KI-Manager-gated. Group approvers are a fast-follow.
referenced connectors at publish, rollback and copilot-validate every connector_id in a connector node must be a connector the workflow owner (created_by) may use (their own private connector, a tenant-shared one, or a group connector whose group the owner is a member of); otherwise 422 connector_not_usable. If the connector or group-membership read fails the answer is 503 (retry), never a 422. A connector_id that is not 1 to 36 characters of letters, digits and - is 422 invalid_connector_id (the same rule is enforced when a run executes the step)
referenced agents the workflow owner (created_by) must own every agent an Agent-Step references (see below)

Webhook, form, email and schedule triggers and published versions that already exist keep firing unchanged even if someone other than the owner set them up; they run as the owner.

Throughout this page, an "authoring" session / "any authoring user" (the require_author gate) means a caller holding the WORKFLOWS_AUTHOR permission. For the built-in roles that is member, ki_manager, tenant_admin, and admin; a tenant custom role granting WORKFLOWS_AUTHOR is admitted regardless of its base role. A viewer/demouser (or any role without the permission) is refused 403.

run-as-owner + agent ownership. A workflow runs as workflow.created_by; an Agent-Step invokes the referenced agent over the gateway service-token path, so the agent executes in the responsibility of the agent's owner. To prevent a confused-deputy, an Agent-Step may reference only an agent the workflow owner owns (ownership, not share-visibility). This is enforced at publish (a reference to a non-owned agent is a publish error) and re-checked at run-claim (ownership can change after publish → the run fails closed with agent_not_owned).

Restricted accounts at run-claim (GDPR Art. 18). Run-claim checks run in this order: the graph (including agent_not_owned), then the owner/creator account state, then the department gateway policy (department_gateway_not_allowed), so a deleted or disabled account is always reported as owner_unavailable. At run-claim the gateway reads the account row of the workflow owner and of the run creator (the user who triggered the run; one read when they are the same user, and the creator check is skipped when the run has no creator). If either account is restricted (processing restricted under Art. 18) the run ends failed with owner_processing_restricted; if either is deleted or disabled (or the owner is unknown) it ends failed with owner_unavailable. In both cases no further step runs and nothing leaves the gateway (the check also applies to the claim that resumes a suspended run). Triggers are still accepted and stored as pending: the claim fails the run closed. Runs claimed while the restriction applied stay failed (re-trigger them); runs still pending when the restriction is lifted, and new triggers, proceed normally. The claim refuses runs from every trigger kind. For inbound mail the mailbox poll itself pauses while the owner is restricted: nothing is fetched, mails stay unread and are ingested after the restriction is lifted (see Email-ingest triggers). While the organisation is suspended, a run is refused at the claim with tenant_suspended (see the error-code table) before the checks above, and no failure e-mail is sent (notified: false, reason: tenant_suspended). While the owner is restricted, the failure e-mail to the owner for failed scheduled runs is not sent (the internal notify route answers notified: false, reason: owner_processing_restricted); it resumes once the restriction is lifted. The PII "notice" mode of the deliver-email endpoint is unchanged by this check.

Recovery: a workflow's owner cannot be transferred and there is no clone endpoint (only the example-seeding call creates workflows for the caller). To keep a workflow running while its owner is restricted, an unrestricted author re-creates the workflow under their own account (copy the graph_json); otherwise lift the restriction. Agent-Steps still require the new owner to own every referenced agent.

Scope of the gate: the claim is the gate. A restriction takes effect at the next claim or resume and at the owner e-mail content send; steps already executing finish within the run deadline, and webhook and Mattermost deliveries of an already-running run are not re-checked.


Workflow CRUD

GET /admin/v1/gateways/{gateway_id}/workflows → { workflows: [ … ] } POST /admin/v1/gateways/{gateway_id}/workflows → create a draft.

Both routes require an authoring session (require_author — viewer/demouser → 403); listing definitions is not open to read-only roles.

Storage faults (every workflow route). A failed read answers 503 { "error": "temporarily unavailable; retry later" } — retry. A write answers that 503 only when it proves it wrote nothing (publish, rollback, trigger changes, an approval decision report this); every other write fault — create, update, delete, the feature toggle, status, enqueue, cancel, webhook / form trigger creation, a reject — answers 500 { "error": "internal error", "request_id": "<id>" }: the write may or may not have landed, so re-read before repeating it. The database's own text is never returned (see Storage faults).

Each list row carries the workflow's identity/status/version/timestamps plus three server-derived list metrics:

  • steps — count of actionable step nodes in the draft graph (excludes the singleton trigger entry).
  • agents — the distinct agent slugs the draft graph's Agent-Steps reference (a JSON array; [] when none).
  • runs_30d — number of runs of this workflow in the last 30 days.
  • deliver_issue_count — how many deliver-target problems the workflow's current published version has (the read-time check of Deliver targets at publish and read time: static and tenant rules, no DNS). Always an integer; 0 for a draft (drafts are checked at publish) and for a published / disabled workflow with nothing to report. All rows are computed from one batched version read and one tenant read; a read fault answers 503.

The list row does not include graph_json — the full definition is returned only by the detail GET …/{id}. steps/agents derive from the draft graph, so a published workflow whose draft has diverged shows its current edited structure.

Create body (accepted shape; anything else is rejected 400):

{ "name": "Presseschau mit Freigabe" }

A body that is not valid JSON or not a JSON object is 400 malformed_body; an absent or blank body is read as no fields; a missing, empty or non-string name is 400 name required; a name over 255 bytes is 400 name too long. The caller's department must allow the gateway (the workflow runs as its creator). The department check answers with { "error": "<code>", "code": "<code>", "message": "…" }:

Status code When
403 department_gateway_not_allowed the caller's department may not use this gateway, or the caller's account is not found
403 invalid_identity the caller's identity is not a valid user id
503 department_policy_unavailable the department policy cannot be read and no last-known-good copy exists (retry)

Success is 201 { "id": "…" }.

GET /admin/v1/gateways/{gateway_id}/workflows/{id} → the workflow + current draft graph. PATCH /admin/v1/gateways/{gateway_id}/workflows/{id} → edit the draft (autosave). DELETE /admin/v1/gateways/{gateway_id}/workflows/{id} → delete.

All three require an authoring session (require_author; viewer/demouser → 403) — the detail response returns the full graph_json definition.

The detail workflow object also carries:

  • deliver_issues — always a JSON array of { "step_key", "code", "field", "reason" }, one entry per deliver step of the current published version's graph (the graph a run executes, not the draft) that cannot deliver. Computed only for a published or disabled workflow ([] for a draft), with the static and tenant rules of Deliver targets at publish and read time — no DNS at read time. The codes and field values are those of the publish 422.
  • deliver_issues_fixed_in_draft — boolean; true only when deliver_issues is non-empty and the current draft graph has no deliver-target problem (publishing again fixes it).

A failed version or tenant read answers 503 (never an empty list). The published workflow is not unpublished or disabled: these fields only drive a warning, the runner still refuses such a step when a run reaches it.

Draft edit is optimistic-concurrency guarded (D12): the body MUST carry the updated_at the client last read (absent or not a number ≥ 0 → 400 updated_at precondition required; a body that is not valid JSON or not a JSON object → 400 malformed_body, an absent or blank body is read as no fields and so lacks updated_at; an unknown workflow → 404). A mismatch (another tab saved first) returns 409 { "error": "stale", "updated_at": <current> }; the client reloads and retries (if the current updated_at cannot be read for that answer, the save answers 503 { "error": "temporarily unavailable; retry later" } instead — nothing was written). A draft whose graph_json contains a number that cannot be stored (NaN / Infinity) is rejected 400 { "error": "graph_json is not storable (non-finite number)" } and nothing is written.

A draft's graph_json is stored as text of at most 16777215 bytes (the size of the storage column). The limit applies to the stored text, in which every number is written in full digits (for example 1e18 is stored as 1000000000000000000), so it can be larger than the request body. A draft over the limit is rejected 400 { "error": "graph_json too large (max 16777215 bytes)" } and nothing is written. A request body over the general admin body cap is answered first, 413 payload_too_large; the stored-text limit answers 400.

On success the response echoes the freshly stamped token — 200 { "ok": true, "updated_at": <new> } — which is the value the next save must send as its precondition. The client reads it straight from this response and needs no follow-up GET. (A GET read-back was previously required to learn the new token; it was a second failure surface that could misreport a persisted save and then self-409 the next save into a false "another tab saved" state — removed.)

{
  "name": "…",
  "run_budget_micros": 5000000,       // optional € budget (micros); a positive integer 1..1000000000000 sets it, `null` clears it (no cap), an absent key leaves it unchanged; anything else (string, `0`, negative, fraction, boolean, over the maximum) is `400 invalid_run_budget` and the stored cap does not change. Every change is audited as `workflow.run_budget_changed`
  "graph_json": { "steps": [ … ], "edges": [ … ] },
  "updated_at": 1752000000            // REQUIRED precondition
}

Amount input. Applies to the run budget (run_budget_micros, which the console shows in euro). The console's amount fields read what you type exactly; this is the console's input rule, not an API rule: the API takes JSON numbers. The console accepts plain digits with at most one decimal separator (50, 12.5, 12,5). It refuses, with a message under the field as you type and nothing sent: an ambiguous amount (10,000, 10.000), thousands grouping (1,234.50), more than six decimal places or 15 significant digits, anything that is not an amount (letters, currency symbols, exponents such as 1e3, signs), and an amount out of range. An empty field clears the budget. See Entering an amount.

Body validation. The whole body is validated before anything is written: one bad field means nothing is written (and no audit event). name: a string sets it; absent or null keeps it; anything else is 400 {"error":"name must be a string"}. graph_json: an object or a string sets it; absent or null keeps it; anything else is 400 {"error":"graph_json must be an object or a string"}.

Exact numbers. PATCH reads the request body's numbers exactly: a number that a double cannot hold exactly (for example a graph_json constant with more than about 17 significant digits, 3.14159265358979323846) is refused with 400 number_not_exact instead of being rounded silently. A number written in a non-JSON form (for example 0x10 or 05) is refused with 400 number_invalid. Send such values as strings.

Repeated keys. An object in the PATCH body that repeats a key at any depth (including inside graph_json) is refused with 400 duplicate_key and nothing is written; a JSON parser would otherwise keep only the last occurrence.

DELETE answers 200 { "ok": true }.

POST /admin/v1/gateways/{gateway_id}/workflows/{id}/status { "status": "disabled" } — enable/disable (published ⇄ disabled). Any other status is 400 status must be published|disabled; an unknown workflow is 404; success is 200 { "ok": true }.

Seed the example workflows

POST /admin/v1/gateways/{gateway_id}/workflows/seed-example → create two publish-clean example drafts owned by the caller and return their ids. This backs the empty-state example form ("Create example workflow") and the demo-tenant provisioning. Same authorization as create: any authoring user (require_author) + the workspace feature flag.

  • Press review with approval / Presseschau mit Freigabe — Trigger → Agent-Step → Human-Approval → Condition(true/else) → Deliver / Deliver (the full node vocabulary; the §demo flagship). The agent prompt asks it to mark urgent items with the condition's word (urgent / dringend), so the true branch is reachable in both languages.
  • PII test run / PII-Testlauf — Trigger → Agent-Step → Deliver. Its agent input carries a test personal-data record, so on a PII-protected gateway the request is masked, the run's PII latch is set and the Deliver egress trips the fail-closed PII gate → blocked_pii (run failed, error_code: "deliver_blocked_pii") and the owner gets the content-free notice mail. When the tenant has pii_internal_delivery_enabled (default 1), an email to the owner is delivered instead (the internal-recipient rule); Mattermost stays blocked.

The step keys (fassung, freigabe, pruefung, zustellung, verwerfen, analyse) and the graph shape are the same in both languages; only names, labels, prompts and texts follow locale.

The example runs out of the box. Both Agent-Steps reference an agent owned by the caller. When the caller owns none, a per-user example agent (beispiel-agent-<uid8>) is auto-provisioned with the gateway's default model — the tenant's Auto policy on this gateway (route_resolver.pick_for_gateway). An agent without a model cannot run (the agent step fails with agent has no model configured), so the model is resolved before anything is written. A reused example agent with no model (seeded by an older build) gets the resolved model on the next call (an audited agent.updated change by the caller, which resets an approved review like any model change); an agent that has a model is never changed. Every deliver step can deliver: the route runs the same deliver-target check as publish on each one before storing it (a failure is the internal 500 invalid_example), so a seeded example always publishes.

A database fault while looking the agent, the approver, the caller or the tenant up is 503 { "error": "temporarily unavailable; retry later" } (nothing written — retry); a failure creating the agent — or a failed read after this request created it — is the sanitised 500 { "error": "internal error", "request_id": "…" } (the agent may exist; a repeat reuses it).

Request body — all fields optional (accepted shape; anything else is rejected 400):

{
  "locale": "en",                            // "en" | "de"; absent → user.locale → tenant.default_locale → "en"
  "delivery": { "kind": "email" },           // the default when absent: email to the owner (no `to`)
  // or: { "kind": "mattermost", "channel_id": "4xp9fdt7mjbx3qz8g1kc5ndw2a" }
  "agent_slug": "presseschau-agent",         // pin an OWNED agent that has a model (else auto-provisioned)
  "approver_email": "redaktion@example.org"  // a distinct in-tenant approver (else the caller)
}
  • locale — exactly "en" or "de" (case-sensitive; "EN", "de-DE", "", a number → 400 invalid_field, field: "locale"). Absent or null → the caller's language, else the tenant's default language, else English.
  • delivery — absent or null → email to the owner. Otherwise an object with exactly the keys of its kind. { "kind": "email" }: both deliver steps are email with a localized subject and no to, so the mail goes to the workflow owner (the caller) through the platform mailer. { "kind": "mattermost", "channel_id": … }: channel_id must match ^[a-z0-9]{26}$ (the runner's rule), and the tenant must have mattermost_delivery_enabled. Not an object → field: "delivery"; another kind (webhook, slack, EMAIL, a number, absent) → field: "delivery.kind"; a missing, empty, short, uppercase or null channel id → field: "delivery.channel_id"; any other key (to, a channel_id on an email delivery) → field: "delivery.<key>" — all 400 invalid_field, checked before anything is read or written.

Rejections (fail-closed, nothing written):

Status code When
400 invalid_field (+ field) a malformed locale, delivery, agent_slug or approver_email
400 mattermost_not_enabled delivery.kind is mattermost but the tenant's Mattermost delivery is off (0 or NULL)
400 agent_not_owned agent_slug is not owned by the caller
400 approver_not_found approver_email is not a live user in this workflow's tenant
422 no_default_model no agent_slug and the gateway resolves no model: { "error": "No model is available for this workspace. Ask your workspace admin to enable a model for this gateway.", "code": "no_default_model" } — no agent, no workflow is written
422 agent_no_model the pinned agent_slug has no model (the route never seeds an example that cannot run; the agent is not changed)
503 — the default-model lookup could not decide, the example agent was edited (or deleted) while its model was being set, a reused draft was edited while its deliver steps were being repaired, or the example lock could not be taken within 5 seconds (another seed call of the same user on the same gateway still held it, or the database was unreachable) — retry. When the example agent was already created by this call, that last case answers the generic 500 instead (retry is safe: the call is idempotent)
403 department codes the caller's department may not use the gateway (department_gateway_not_allowed, invalid_identity; 503 department_policy_unavailable), checked before the body is read
403 feature_disabled / — feature disabled; not an author (viewer/demouser)

Response 201:

{ "primary_id": "<press review id>", "workflows": [ { "id": "…", "name": "…" }, … ] }

Idempotent per the caller's own workflows by name, under the German or the English name: a repeat returns the existing ids (never duplicates, also when locale changes); it never returns another user's same-named workflow. This also holds for parallel calls (two tabs, or an English and a German call at the same time): the check for an existing example and its creation run under a lock per user and gateway, so a second call waits for the first and then returns the first call's ids. Calls of different users, or on different gateways, never wait for each other. In a reused example draft, every deliver step that cannot deliver — an older build's Mattermost step with an empty channel_id, a Mattermost step while the tenant's Mattermost delivery is off, a webhook without a URL, kind none — gets only its deliver target rewritten with the chosen delivery — its texts, labels and every other step stay as stored; a concurrent edit of that draft answers the retry 503. The examples are drafts — not auto-published — so the user can adjust before publishing.

Demo-tenant provisioning (§10): seed with the delivery the demo needs (email, or the real Mattermost channel_id) and, for the two-person Freigabe beat, the approver persona's approver_email, then POST …/{id}/publish each. No manual edit of the example is needed.

Account deactivated mid-request. If the acting user is disabled or erased while the example agent is created, seeding answers 401 { "error": "unauthenticated" } — nothing is created.

Example options

GET /admin/v1/gateways/{gateway_id}/workflows/seed-example/options → what the example form shows. Same authorization as the seed call. Read-only — it never writes, and it exposes only what the caller can already see (their own email address and language, their tenant's Mattermost flag, the default model of a gateway they may use).

{
  "locale": "en",
  "model": { "model": "qwen3.8-27b", "provider": "myra" },
  "model_status": "ok",
  "delivery": { "email": { "to": "anna.berg@example.org" }, "mattermost": true }
}
  • locale — the default of the seed call (user.locale → tenant.default_locale → "en").
  • model_status — ok (a model, shown read-only), none (no model; model is null and the seed call would answer 422 no_default_model), or unavailable (the lookup could not decide; model is null — retry, never read as "none").
  • delivery.mattermost — true only when the tenant's Mattermost delivery is on (exactly 1).

A database fault reading the caller or the tenant is 503; feature disabled or not an author → 403. The SPA treats the answer as untrusted: an unknown model_status reads as unavailable, a non-true mattermost hides the option.

graph_json shape

{
  "steps": [
    { "key": "trigger",  "node_type": "trigger",  "config": { "trigger_kind": "manual", "input_schema": { … } } },
    { "key": "classify", "node_type": "agent",    "config": { "agent_slug": "klassifizierer",
                                                              "input": "Klassifiziere: {{trigger.output.text}}" } },
    { "key": "notify",   "node_type": "deliver",  "config": { "kind": "mattermost", "channel_id": "…",
                                                              "text": "Ergebnis: {{classify.output.summary}}" } }
  ],
  "edges": [ { "from": "trigger", "to": "classify" }, { "from": "classify", "to": "notify" } ]
}

node_type ∈ trigger | agent | condition | loop | approval | deliver | fetch | code | connector. Edges may carry a branch slot ("true"/"else" on a Condition, "body" on a Loop, "error" on an Agent/Deliver node whose on_error is error_branch — see Error handling). key is a stable, immutable step id; display labels rename freely. At publish the referenced agents' response_schema + version are snapshotted into the version (drift guard).

Per-node config keys the runner consumes:

Node config keys
trigger (none read at run time — the trigger's output is the run's trigger input; trigger_kind and input_schema are builder/validation metadata). A run's trigger_kind records how it started: manual | webhook | schedule | form | email (an inbound email — see Email-ingest triggers)
agent agent_slug (an OWNED agent), input — the per-step task/prompt (a {{step.output.path}} template). input is required and must be a non-empty string: a missing, null or empty input is rejected at publish, rollback and copilot validate with input_required, and a present non-string input (a number, true, an object or an array) with invalid_input (the gateway refuses an empty invoke input, so such a step could never run). Like the Deliver target checks, this is not re-checked at run-claim: a version published before the check still runs, and a run that reaches such a step fails there (agent_failed), as does a template that resolves to an empty string at run time. It is distinct from the agent's own saved system prompt.
condition left_ref (a single {{…}} ref), op (eq\|ne\|contains\|gt\|lt\|is_empty), right_value (ignored for is_empty). A right key is rejected (condition_stray_right), never read as the value
loop items_ref (a single {{…}} ref to a JSON array, ≤ 10 items)
approval approver_kind (user), approver_id, timeout_policy (skip\|end), timeout_hours (1…8760)
deliver kind (mattermost\|webhook\|email), the per-kind target (channel_id | url | subject), text (a {{…}} template), and (email only) optional to — an EXTERNAL recipient, allowlist-gated (see below)
fetch url (a literal or a {{…}} template) — the document to download; allowed_content_types (optional, a non-empty array of MIME strings; a malformed value is rejected at publish, never treated as "any"); max_bytes (optional positive int, clamped to the ~6 MiB artifact cap); filename (optional — else derived from the URL path basename). Emits an artifact reference {{fetch_key.output.artifact}} ({handle, filename, mime_type, size_bytes, sha256}) for a later node. A network fetch is a RETRY node (retry/on_error accepted) — a transient failure retries; a deterministic one takes the error_branch or fails the run. See the Fetch node section below.
connector connector_id (an existing MCP/API connector of the tenant; 1 to 36 characters of letters, digits and -, anything else is rejected with 400 bad_connector_id), tool (the tools/call tool name), input (a JSON object template of arguments, or a single {{…}} ref that resolves to one; refs are JSON-encoded where they stand, see the Connector node section). Calls the connector mid-run as the workflow owner (the owner's credential / private connector; a tenant-shared connector ignores the user). Emits the scrubbed string result {{connector_key.output.result}}. Side-effecting + ambiguous-outcome → NOT a retry node: retry/on_error/an error-edge are rejected at publish, and any failure is terminal (never auto-retried — see the Connector node section).
code code (Python source, ≤ 64 KiB) — run in the network-isolated code-interpreter sandbox. The source is opaque: it is never template-resolved ({{…}} in the code is literal Python — an f-string f"{{x}}" or a set literal publishes clean), so run data reaches the program only as data, never spliced into source. Data channels: input_refs (optional array of ≤ 7 artifact-handle refs, typically {{prior_step.output.artifact.handle}}, staged as /input/<name>) and the always-present /input/_context.json (the run's trigger input as a JSON object — see the Code node section). output_filename (optional — selects the /output file by name and stores under it; else the sole output's own name, synthesized for a nameless image). Emits an artifact reference {{code_key.output.artifact}} for a later node. A RETRY node, but only a transient broker failure retries — a deterministic user-code failure does not. See the Code node section below.

Publish

POST /admin/v1/gateways/{gateway_id}/workflows/{id}/publish → 201 { "version_id": "…", "semver": "1.1.0", "updated_at": 1742551200, "warnings": [] }. The updated_at is the optimistic-concurrency token the next draft PATCH must echo. warnings is always an array (usually empty) of non-blocking findings in the same entry shape as the 422 errors — today only deliver_url_unverified (see Deliver targets at publish and read time).

Publish runs graph validation (below) and, on success, writes an immutable workflow_version and auto minor-bumps the semver. On validation failure the response is 422:

{ "error": "workflow graph failed validation",
  "code":     "invalid_graph",
  "errors":   [ { "step_key": "notify", "code": "template_unresolved" },
                { "step_key": "send", "code": "deliver_url_not_public", "field": "url",
                  "reason": "webhook host does not resolve to a public address" } ],
  "warnings": [] }

Each errors / warnings entry has step_key and code. Deliver-target entries also carry field (kind | channel_id | url | to — the deliver config key at fault) and reason (the runner's English sentence for the same input, for logs and technical details; branch on code, never parse reason). Both keys are optional and additive: other codes omit them.

Errors block publish (rendered as per-node red badges); warnings do not. (The validation model is block-only — references that could be unavailable at runtime are rejected at publish, never downgraded to warnings. The one warning is a webhook host that could not be looked up, deliver_url_unverified; the runner checks it again before every send.) A failed validation publishes nothing and writes no version.

Version assignment is atomic. The next version is assigned under the workflow's lock, in the same transaction that stores it: the numeric maximum of the workflow's current version and every stored version, with the minor bumped and the patch reset (1.9.0 → 1.10.0; the first publish is 1.0.0). Two concurrent publishes get two distinct versions (e.g. 1.1.0 and 1.2.0) — neither fails. A publish whose draft graph changed after it was validated (compared exactly, under the lock) answers 409 { "error": "stale" } and publishes nothing — reload the draft and publish again. A workflow deleted in the meantime → 404. A write fault that wrote nothing → 503 { "error": "temporarily unavailable; retry later" } (publish again); any other database fault → 500 { "error": "internal error", "request_id": "<id>" } (the version may or may not have been stored — reload the version list first).

Validation rules (also re-run at run-claim as a drift guard): the graph must be a DAG (a cycle is rejected); every edge must reference existing steps with type-compatible ports; every {{step.output.path}} reference must resolve to an upstream step's declared output schema (a dangling reference is template_unresolved); a reference into a Condition/Loop branch member from outside that branch is a hard publish block (dangling_ref — only ancestors on the same chain resolve, so a maybe-skipped value can never be referenced); every referenced agent must be owned by the workflow owner (agent_not_owned); malformed / oversize graph_json is rejected fail-closed. A {{}} reference to an output-less node (condition / deliver / approval — they route, egress, or gate but expose no output) is a publish block (ref_to_output_less); only trigger / agent / loop produce a referenceable value. An approval node must name a valid approver (approver_kind: "user" + an approver_id that is a live user in the workflow's tenant (an approver without a tenant is rejected too), else approver_required / invalid_approver / approver_not_in_tenant) and a valid timeout (timeout_policy ∈ {skip, end}, timeout_hours a finite number in [1, 8760], else bad_timeout). Every deliver node must be able to deliver (the deliver_* codes in Deliver targets at publish and read time); all failing deliver steps are reported in one 422, together with any connector_not_usable entries. A workflow with no valid owner (created_by erased or malformed) gets deliver_owner_missing on every deliver step whose kind is not none. A tenant read fault during this check answers 503 (never a guessed verdict).

GET /admin/v1/gateways/{gateway_id}/workflows/{id}/versions → the published versions (newest first, capped at the newest 100), each enriched with run_count (how many runs executed on that version — the run→version pin is permanent), is_current (semver == workflow.version), and published_by_name (the publisher's email, or the raw id if the user was deleted). Requires an authoring session (require_author; viewer/demouser → 403), then gateway access + the workspace feature flag. It exposes historical version config — the same config class as the current draft, never run-output — so it is author-gated exactly like the definition reads.

Diff two versions

GET /admin/v1/gateways/{gateway_id}/workflows/{id}/versions/diff?from={version_id}&to={version_id} -> 200 { "diff": { … }, "from": …, "to": … }. The diff is computed server-side from the two immutable graph snapshots; the response lists, per step (keyed by the immutable step key): added, removed, changed, unchanged, plus edge edges_added / edges_removed. Each changed step carries a fields list of { field, kind, before, after } where kind ∈ {added_field, removed_field, changed_field} (the absent side is JSON null). Every list is always a JSON array.

Requires an authoring session (require_author; viewer/demouser → 403) — same gate as the other definition reads. A missing, null or empty from / to answers 400 field_required and a repeated or non-string one 400 invalid_field, each with field set to the offending parameter (from is judged first).

Accepted / rejected: both from and to are required and non-blank (else 400); each must be a version of this workflow — a version id belonging to another workflow or tenant, or a nonexistent id, is 404 (the workflow itself is gateway/tenant-fenced first). A stored snapshot that fails to parse is 422 { "error": "diff_failed", "code": "<reason>" } (fail closed, never a 500). Diffing a version against itself returns an all-unchanged diff.

Roll back to a version

POST /admin/v1/gateways/{gateway_id}/workflows/{id}/versions/{version_id}/rollback -> 201 { "version_id": …, "semver": …, "updated_at": …, "rolled_back_from": …, "warnings": [ … ] } (warnings as on publish, usually empty). Rollback republishes the chosen version's graph as a NEW version — the history is append-only, old versions are never mutated, and runs stay pinned to the version that executed them. It runs the same validation as a normal publish, so a rollback to a version that now references a deleted agent (agent_not_owned) or a cross-tenant, deleted or tenant-less approver (approver_not_in_tenant), or a deliver step that can no longer deliver (the deliver_* codes, with field + reason, all failing steps), is rejected 422 invalid_graph and nothing is published. The workflow's current enabled/disabled status is preserved — the status as it is at the moment the rollback is stored (read under the workflow's lock), so rolling back a disabled workflow does not silently re-enable it, and a disable that raced the rollback is never undone. Rolling back to the already-current version is 409 { "error": "already_current" } — re-checked under the lock, so a concurrent publish or rollback cannot slip in between. The new version is assigned exactly as for a publish (atomic, distinct under concurrency), and a write fault answers the same way (503 when nothing was written, else the sanitised 500). The editable draft is not touched; rollback changes what is published (future runs use the rolled-back graph), not your draft. Requires an authoring session (require_author) — the publish authorization.


Test a single step (builder, no persisted run)

The builder's agent-step config panel offers "Diesen Schritt testen" — run just that one agent step in isolation, without executing the whole workflow. It reuses the agent invoke path (agents/{slug}/invoke via a short-lived playground token, run as the agent owner), so it does not create a workflow_run and does not appear in the run history. Because a mid-chain step has no upstream output at design time, the panel lists each {{step.output.path}} the step references and lets the author supply a sample value; those are substituted into the step input before the invoke. Fail-closed: a deleted/unavailable agent, an unresolved (dangling) reference, or an empty resolved input blocks the test with no invoke. The test-run cost is surfaced from the synchronous X-AIG-Cost-Micros response header and labelled as a test. Scope: agent steps only (Trigger / Condition / Loop / Approval / Deliver are not testable in isolation).


NL copilot — generate / fix / explain a draft graph

A natural-language assistant for the builder. Three modes: generate a draft graph from a process description, fix a graph from its validation errors, explain a graph in plain language. It never publishes — a human reviews and publishes, so the governance story is intact. The proposed graph is untrusted model output and is validated through the FULL publish validator before it may be applied (and again at publish).

The copilot is split into two calls, by concern:

1. Inference (metered) — /v1 pseudo-provider

POST /v1/{tenant}/{gateway}/workflows/copilot (inference host; Bearer a short-lived playground token, exactly like "Test a single step"). This rides the normal inference pipeline, so the run draws the tenant's normal metering (spend_ledger), PII scrubbing, EU-residency and model-allowlist clamps, and returns the cost in X-AIG-Cost-Micros. It is a passthrough (buffered, stream:false); for generate/fix the answer is constrained to the graph JSON schema and validated fail-closed (422 structured_output_failed on non-conforming output, billed first so a caller can't harvest free runs).

Authorization: the token must be user-bound and hold the WORKFLOWS_AUTHOR permission — the SAME permission the admin build/publish routes require, so the copilot admits exactly the users who may author a workflow, never a stale subset. For the built-in roles that is member, ki_manager, tenant_admin, and admin; a tenant custom role that grants WORKFLOWS_AUTHOR is admitted too, regardless of its base role. An unbound (service) token or a caller lacking WORKFLOWS_AUTHOR (e.g. viewer/demouser) is refused 403 {error.code: "forbidden"}. The feature must also be enabled for the workspace, else 403 {error.code: "workflows_disabled"} — a distinct code from the role refusal, so the client can prompt the user to ask an admin to enable Workflows rather than showing a generic permission error.

Accepted body (anything else is rejected 400 — validated at the trust boundary, Invariant 11):

{ "mode": "generate|fix|explain",
  "model": "<a runnable model id>",
  "description": "describe the process (required for generate, optional for fix)",
  "graph": { "steps": [ … ], "edges": [ … ] },
  "validation_errors": [ { "step_key": "…", "code": "…" } ] }
  • mode — must be one of the three; missing/unknown → 400.
  • model — required, non-empty; absent/empty → 400 (no model call). The pipeline clamps it to the gateway's allowlist/residency.
  • description — required for generate; capped at 4,000 bytes; larger → 400.
  • graph — required for fix and explain; the wire shape (see graph_json shape); capped at 64 KB for the prompt; malformed/oversized → 400.
  • validation_errors — optional array of {step_key, code}, only used to phrase the fix prompt; not an array → 400; entries after the first 200 are ignored.

For generate/fix the response's assistant content is the proposed graph as JSON; for explain it is plain-language text. To keep proposals publishable, the prompt is grounded in the caller's owned agent slugs (agent nodes must reference one) and the caller as the default approver. It names the config keys the runner reads, e.g. a Condition's comparison value is config.right_value; a proposal that writes config.right instead is refused by copilot-validate (condition_stray_right) and is not offered for apply.

2. Server-side validation + diff (before applying)

POST /admin/v1/gateways/{gateway_id}/workflows/{id}/copilot-validate (admin host; require_author; feature-gated). Runs the same "publishable" validator as publish (core.wf_validate + owner-agent fence + approver-in-tenant fence + connector fence + the deliver-target check, including the publish-time DNS lookup of webhook hosts) on the untrusted proposed graph, and computes the changed-nodes diff vs the current draft. Numbers in the graph keep every digit when validated; a graph that cannot be encoded exactly (for example a non-finite number) is refused 400 graph not encodable.

Accepted body:

{ "graph": { "steps": [ … ], "edges": [ … ] },
  "base_graph": { "steps": [ … ], "edges": [ … ] } }
  • graph — required object; not-an-object / not-encodable / >512 KB → 400.
  • base_graph — optional; defaults to an empty graph {"steps":[],"edges":[]} when absent (a fresh generate), so the diff never sees an absent side.

Response 200:

{ "ok": true,
  "errors": [],
  "warnings": [],
  "diff": { "added": [ … ], "removed": [ … ], "changed": [ … ], "unchanged": [ … ],
            "edges_added": [ … ], "edges_removed": [ … ] } }

ok:false returns the validation errors (step_key + code; deliver-target entries also field + reason, as on publish) and the client surfaces them without applying — a graph that fails validation is never applied as a partial graph. errors reflects wf_validate's phased short-circuit (up to the first failing phase, not exhaustive), so the fix UX re-runs validate → fix → validate. A DB failure during validation (including the tenant read of the deliver-target check) returns 503 (never a fake validation error). A deliver_url_unverified finding is in warnings and does not make ok false. If the diff cannot be computed, the response is 422 {"error":"diff_failed","code":"…"}. A body that is not valid JSON or not a JSON object is 400 {"error":"request body must be a JSON object","code":"malformed_body"} (or request body is not valid JSON); an absent or blank body is read as no fields. Applying an ok proposal is a normal draft PATCH (the client is never the boundary — publish re-validates regardless).


Trigger a run (manual)

POST /admin/v1/gateways/{gateway_id}/workflows/{id}/runs → 202 { "run_id": "…", "status": "pending", "was_existing": false }.

If the calling user's account no longer exists (erased or purged while the request was in flight), the run is not created and the answer is 401 { "error": "unauthenticated", "code": "unauthenticated" }. A database lock wait that runs out answers 503 (nothing written; retry).

The workflow must be published — an unpublished workflow returns 409 { "error": "workflow not published" }, and one whose versions have gone returns 409 { "error": "no published version" }. The run is bound to the workflow's current version: the version whose number is the workflow's version (the last version published — a rollback publishes the old graph as a new version) — every way of starting a run (manual, webhook, form, email, schedule) binds that same version, also when two publishes landed in the same second. A failed version read answers 503 { "error": "temporarily unavailable; retry later" } (retry), not the 409. The run starts as pending; the runner claims it within ~2 s. A manual run consumes only idempotency_key; it does not accept a trigger input payload (the run begins from the Trigger node with no supplied input, and no input_schema validation is applied on this route — an input field in the body is ignored). To pass a payload, fire the workflow through its webhook or email trigger.

{ "idempotency_key": "optional-client-uuid" }

Idempotency (fail-safe against double-clicks/retries): if idempotency_key is supplied, a second POST with the same key for this workflow returns the same run_id (and "was_existing": true) — never a second run, never double spend or double egress. Omitting the key (or sending null / "") means every POST is a distinct run.

idempotency_key, when present, must be an opaque token: a string of at most 64 characters drawn from A-Z a-z 0-9 - _ . :. Anything else — a longer key, other characters, or a non-string value — is rejected with 400 { "error": "invalid idempotency key", "code": "invalid_field", "field": "idempotency_key" }. This is the same key format the webhook fire path enforces on X-AIG-Idempotency-Key; the webhook path answers with its own codes (idempotency_key_too_long, invalid_idempotency_key), see Typed codes on the webhook receiver.


Schedule trigger (time triggers)

A workflow can fire on a schedule — a fixed interval, once a day at a set time (UTC), or once a week on a chosen weekday at a set time (UTC) — in addition to manual / webhook triggers. There is at most one schedule per workflow. It reuses the existing agent scheduler (no second scheduler): the schedule is a polymorphic agent_schedule row with workflow_id set; the scheduler's per-minute tick claims a due row via the same at-most-once compare-and-swap and, for a workflow row, asks the gateway to enqueue a pending workflow_run (trigger_kind = schedule, run-as-owner) instead of invoking an agent. The runner then executes it exactly like a manual/webhook run.

Saving a daily or weekly schedule arms its next run to the next occurrence of the chosen time (for weekly: on the chosen weekday), not to the moment of saving — so "daily at 10:00" created at 08:36 first fires at 10:00, never a spurious extra run right after save. An interval schedule starts promptly (its first run is due immediately). Editing only metadata (e.g. renaming, or switching a still-enabled schedule off) preserves the already-armed run time; the next run is recomputed only when the cadence itself changes (including changing only the weekday of a weekly schedule) or a disabled schedule is switched back on.

Authz: any authoring user (require_author; setting a schedule is a create/edit function), plus the per-workspace feature gate. All three routes are gateway-scoped.

Method / path Behaviour
GET …/workflows/{id}/schedule 200 { "schedule": false } when none is set, else { "schedule": { enabled, schedule_kind, interval_sec, daily_at, daily_dow, next_run_at, last_run_at, consecutive_failures, last_status, last_error } }. daily_dow is the weekly schedule's weekday, integer 0..6 (0 = Sunday … 6 = Saturday, UTC); absent/null for interval/daily rows. The three health fields let the UI show an auto-disabled (enabled: 0) or failing schedule instead of rendering it as healthy. For a workflow schedule, a backed-off (failing) state shows only as next_run_at pushed about 24 h ahead. last_status is ok / retrying / failed / paused / null; for a workflow schedule the current scheduler writes neither last_status nor last_error, so both are null; paused and an auto-disable last_error can only appear on legacy rows switched off by an older version, and saving the schedule with enabled: true clears both. last_error, where present (legacy rows only), is the fixed auto-disable sentence; the run error code embedded in it was restricted to [A-Za-z0-9_.-]{1,48} (else unknown) when it was written — never model output or PII. consecutive_failures is the streak toward the agent auto-pause threshold; on a workflow schedule the scheduler zeroes it on every fire, so it stays 0.
PUT …/workflows/{id}/schedule Create-or-replace (race-safe upsert). Returns the stored cadence, read back inside the same transaction. Saving it disabled cancels the workflow's still-pending schedule runs (payload cleared) in that same transaction.
DELETE …/workflows/{id}/schedule Remove the schedule + cancel its pending schedule runs (payload cleared), one transaction → 200 { "ok": true }.

Both writes are all or nothing: a failure leaves the schedule and the runs as they were — 503 { "error": "temporarily unavailable; retry later" } when nothing was written (send it again), any other database fault 500 { "error": "internal error", "request_id": "<id>" }. A workflow deleted in the meantime → 404.

PUT body — accepted shape (trust boundary, Invariant 11; validated by core.schedule_cadence, the one shared cadence validator):

{ "schedule_kind": "interval", "interval_sec": 3600, "enabled": true }
{ "schedule_kind": "daily",    "daily_at": "06:00",  "enabled": true }
{ "schedule_kind": "weekly",   "daily_at": "06:00",  "daily_dow": 3, "enabled": true }
  • schedule_kind — interval | daily | weekly (required; anything else → 400).
  • interval_sec — integer 60 … 366 days (required for interval). Below 60, above the cap, non-integer, or non-numeric → 400, no write.
  • daily_at — HH:MM in UTC, 24-hour (required for daily and weekly). 24:00, 12:60, a single-digit hour, an empty string, or a non-string → 400, no write.
  • daily_dow — integer 0 … 6 (0 = Sunday … 6 = Saturday, UTC; required for weekly — same contract as scheduled tasks). Out of range, fractional, non-numeric, boolean, or JSON null with weekly → 400, no write. For interval/daily the server stores NULL regardless of what was sent (the client never picks what persists).
  • enabled — strict JSON boolean (a governance toggle is never coerced from a truthy string). Absent → enabled. Any other type → 400.
  • All cadence fields are range/format-checked whenever present, even those the kind does not use (a garbage value in an unused field is rejected here rather than reaching the DB).

Fail-closed fire path (never a surprise run or double spend): the scheduler enqueues only when, at fire time, the workflow is published, its workspace feature is on, it has a published version, and no run is already in flight (any manual/webhook/schedule run in pending/running/suspended → the fire is skipped, at-most-once), the schedule still exists, and the schedule is still enabled. The checks and the run's insert are one transaction that locks the workflow, its version and the schedule row first, so a schedule disabled or deleted (or a workflow unpublished) before the fire commits never yields a run. A schedule row or lock held past the bound (or no database connection) skips the fire with reason busy — nothing is written and that cadence fire is missed, like any other skip. All identity (tenant / gateway / owner / version) is derived server-side from the workflow row — the scheduler is authenticated but never trusted for identity.

With the tenancy switch on, a fire for a suspended tenant's workflow is skipped with reason tenant_suspended: no run is enqueued and nothing counts as a failure or sends mail. Unlike other skips the fire is not lost: the schedule is put back to the claimed fire time, held while the workspace is suspended and fired once after the resume. Normally the scheduler does not select a suspended workspace's schedule; this skip covers a suspension that lands after the selection, and a run that still slips past is refused at the run claim (error_code tenant_suspended). A workspace row that cannot be read is still the feature-gate 500, unchanged. See Suspended tenants.

Failure backoff, and how to recover from it. A schedule is never switched off by failures. After 5 consecutive failed schedule runs since it was last enabled, an interval schedule stays enabled but makes at most one attempt per 24 hours (its normal interval if that is longer), to bound a broken schedule's spend. The 24 hours are measured from when the newest failed run started (its created_at, not when it finished). A run that succeeds ends the backoff and the normal cadence resumes. If the single attempt fails again, the next attempt is 24 hours after that attempt started (or at the normal interval if that is longer). The window starts when the schedule was last saved with enabled: true: fix the cause and save the schedule — that PUT re-arms the failure window and the normal cadence resumes at once. daily and weekly schedules keep their exact cadence and are not backed off. Runs refused with tenant_suspended are skipped by the count (neither failures nor successes), so a suspension never starts a backoff. The backoff writes no last_error and no last_status: "paused". Only a legacy schedule that an earlier version switched off (it still shows last_status: "paused") stays off until it is saved again.

Two operational notes:

  • Never re-enable a legacy stopped schedule with raw SQL. UPDATE agent_schedule SET enabled=1 does not move the failure-window watermark or clear last_status/last_error. The old failures still count: an interval schedule makes one attempt only once 24 hours have passed since the newest old failure started and, if that fails, is limited to one attempt per 24 hours instead of its normal interval. The API also keeps returning the stale last_status: "paused" while enabled is true. Use the PUT above.
  • A run that ended cancelled inside the window breaks the all-failed streak and defers the backoff until five newer failures accrue — disabling or deleting a schedule cancels its pending schedule runs, so this is the expected behaviour after a stop/start cycle.

Timezone: daily_at is UTC in the MVP (cron expressions and per-workflow timezones are a later roadmap item).


Runs

Both read routes require an authoring session (require_author — viewer/demouser get 403) plus the workspace feature flag. Run visibility equals workflow visibility: the workflow's owner, a same-tenant tenant_admin and a platform admin see every run of the workflow, whoever triggered it; for anyone else the workflow and its runs answer 404 (run_not_found for run detail), never 403, so a run id is no existence oracle. The client is never the authz boundary.

GET /admin/v1/gateways/{gateway_id}/workflows/{id}/runs → { "runs": [...] } with status, trigger_kind, cost_micros, tokens_used, pii_active, suspended_reason, approver_ref, started_at, finished_at, error_code, delivery_disposition, delivery_reasons (the delivery disposition: the level and an array of <source>:<where> strings; absent when the run never recorded one). The run detail below carries the same two fields. status ∈ pending | running | succeeded | failed | suspended | cancelled.

GET /admin/v1/gateways/{gateway_id}/workflows/runs/{run_id} → { "run": {...}, "steps": [...] } (404 if the run is not on this gateway). run adds the technical error string and run_state — a JSON string (a step_key → output object, bounded D15; absent on a run that has produced no output yet — NULL columns are dropped, so clients must treat it as optional), and outputs_withheld (an array of step keys, [] when none). The server decides what run_state carries: the trigger step's output (the raw trigger input) is reduced to its top-level field names, each with a null value ({"subject":null,"body":null}; null when the input is not an object), for every viewer (the approval confirmation page, GET /admin/v1/me/approvals/{run_id}, applies the same rules to its named approver). In a run that handled personal data (pii_active is anything but the number 0, fail closed; or the run's delivery_disposition is stricter than allow or not a known level, or delivery_reasons is not empty — for example a Connector result stored unmasked under Don't mask), a caller who is not the workflow's owner (workflow.created_by, strict; an admin is not the owner, and neither is an administrator in a View as user session) receives no other step's output: each such key is left out of run_state and listed, sorted, in outputs_withheld. Every value that is sent is the stored JSON text byte for byte. A stored run_state that is not a JSON object is not sent at all. For the same caller the free-text error columns are left out, because their writers can put model, provider, webhook or trigger text into them: run.error (it copies an agent or deliver failure and holds an approver's rejection reason), each step's error (an agent step's error is the provider's error body, which may quote the request) and delivery_error (a webhook's or Mattermost's error body, which may echo the delivered text). Each one left out is flagged with error_withheld: true (on run and on the step) or delivery_error_withheld: true; a flag is absent otherwise. A step error that is exactly content_withheld (a constant) is kept. The closed-set columns stay for every viewer: error_code, error_class, blocked_by, block_reason (only disclosable codes) and delivery_status. A fault reading the workflow (to find the owner) is the 503, never the outputs or the error texts. Per-step steps rows carry step_key, node_type, node_label, status, attempt, request_ref, cost_micros, tokens, error, delivery_status, delivery_error, started_at, finished_at. Deliver rows also carry their step's delivery release: release_id, release_status (pending | awaiting_second | approved | closed | denied | expired), release_count (1 | 2), release_done (0 | 1 | 2), release_channel ({kind, label}) and release_decided_by_name (who rejected it), each null without a release (or when it cannot be read; the run detail never fails on it). A Deliver step held for its release is a held row with delivery_status: waiting_release, superseded by the re-entered row once the release is decided (delivery_status delivered, release_denied, release_expired, …). The steps are listed in the order the run executes its graph, not by started_at (unix seconds, so the steps of a fast run tie): by the node's position in the workflow version's graph (its topological order); a loop's own row first, then its body steps iteration by iteration; a condition's not-taken steps (skipped) at their own place in the graph, after the condition. Rows of the same step are listed by attempt; among rows with the same step_key and attempt a held row comes first, then the rows in the order they were written. A row whose step is not in the graph is listed last. When the version graph cannot be read, the steps are listed by started_at, then in the order they were written. The approval confirmation page (GET /admin/v1/me/approvals/{run_id}) lists its steps in the same order. node_label is the step's friendly builder name — the run's pinned version-graph node label, resolved on read; it is absent when the node has no label (or the version cannot be resolved), and the UI then falls back to the translated node-type name (never the raw step_key). Step status ∈ pending | running | succeeded | failed | skipped | delivering | continued | held. continued marks a step whose final failure was absorbed by its on_error policy (continue or error_branch) — the run proceeded; the row keeps the underlying error (and for Deliver steps the delivery_status, e.g. an absorbed blocked_pii). When a step is retried, EVERY attempt persists its own row with the same step_key and an incrementing attempt (1-based) — each attempt row carries that attempt's cost_micros/tokens, so retry cost is attributed per attempt; the step's terminal disposition is the highest-attempt row. A Connector step that a tainted run held for the owner's approval is held (no finished_at) while the run is suspended; when the run resumes, the re-entered call writes a new row for the same step_key and attempt, and the superseded held row stays next to it. The run view shows only the latest row per (step_key, attempt) - the re-entered one - while the step-run list (and the GDPR export) lists both; a held row is always listed before the row that supersedes it. If the run ends while the step is held (cancelled, rejected, or the approval timed out), the held row is set to failed with error run_cancelled, approval_rejected or approval_timeout and a finished_at. That includes a run cancelled while it waits for a runner after its approval was decided (status pending) because its trigger was deleted, disabled or its token rotated, or the user who started it was erased: the run is cancelled with its own error_code (webhook_trigger_deleted, form_deleted, …, owner_unavailable), the held row reads run_cancelled. Exactly three refusals, all issued before any call to the connector, leave the Connector step row (first entry or re-entry) failed with that code in delivery_error: HTTP 403 untrusted_egress_refused (the owner denied), HTTP 422 untrusted_egress_approval_lapsed (the approval expired) and HTTP 422 untrusted_egress_refused (the approved decision could not be recorded or was not allow). Every other refusal or failure - including a spent approval (untrusted_egress_approval_used) and any error from the call itself - leaves the row delivering, because the call may already have run; the run then fails closed and is never re-fired. A Deliver step is written status: "delivering" before egress, then flipped to a terminal succeeded/failed (or continued when the failure is absorbed by the step's on_error policy) once the outcome is known; its detailed outcome is in delivery_status, so render Deliver rows from that field. A row still showing delivering means the egress outcome is unknown (a crash mid-send) — such a run fails closed on resume and is never re-delivered. pii_active is an integer (1/0), written by the runner at the run's terminal/suspend boundary and, mid-run, at each agent step's save once the runner has latched it (so the server's deliver-email fences read the current value, not a stale 0). The gateway additionally latches it to 1 on its own the moment it serves a PII-masked agent invoke bound to the run, independent of what the runner reports. 1 means the run handled PII fail-closed: it is set when any agent step did not explicitly report x-aig-pii-active: 0 — which includes agent errors and timeouts ("PII could not be ruled out this run"), matching the Deliver egress gate exactly; it does not mean "PII was provably masked". The flag is monotonic within a run (latched via GREATEST — once 1, a later terminal write can never lower it to 0, so a resume/late-fail never loses the signal). Known limitation: a run reaped mid-execution before any terminal/suspend write and before its first latching agent-step save reads 0 (the transient signal died with the crashed tick; no egress occurred). The approver provenance (approver_ref, rendered "freigegeben von X am Y") and the typed error_code (see Error codes) are on run.

Run-detail display. The runs UI derives the shown status from error_code, not the raw status: a deliver_blocked_pii run reads "Blockiert — Datenschutz" and a budget_exceeded run reads "Gestoppt — Budget erreicht", both in a protective amber tone — these guardrail terminal states are the platform working as designed, so alarm-red is reserved for a genuine failed. Because the runner stores the trigger node's output as the raw, unmasked trigger input, the run-detail view never renders that step's output in cleartext — it shows the submitted field names (or a redaction notice) instead. An agent step's output carries the personal data the gateway restored after the model, so a step listed in outputs_withheld shows "This step's output is shown only to the workflow owner: the run handled personal data, and the gateway put it back into the result." instead. The display never mutates the stored status/error_code; it is a read-time projection.

POST /admin/v1/gateways/{gateway_id}/workflows/runs/{run_id}/cancel → 200 { "cancelled": true }; 409 { "error": "already terminal" } (the CAS loser); 404 run_not_found (unknown/other-gateway run, or a workflow the caller may not see: not the owner, not a same-tenant tenant_admin / platform admin). Requires an authoring session (require_author; viewer/demouser → 403). The runner observes the cancel at its next step boundary and aborts before any further egress; every runner write is lease-fenced, so a step that completes after the cancel cannot write a phantom row.

Cost & budget (D10/D14). Per-step cost_micros (€ micros) is taken from the Agent-Step invoke's synchronous X-AIG-Cost-Micros response header (server-side pricing; the runner performs no pricing math). The run's cost_micros is the sum; request_log is the independent drill-down. If the run exceeds the workflow's run_budget_micros, the run aborts with error_code: "budget_exceeded" ("Budget erreicht").


Approval: the Approvals inbox ("Freigaben")

When a run reaches a Human-Approval node it is suspended (status: suspended, suspended_reason: awaiting_approval), its lease cleared (so the lease-reaper — which also excludes suspended runs — can never reap it), and the node's approver + timeout policy + the suspended step key are snapshotted onto the run. No resume token is minted (the token-link / notification path is a roadmap fast-follow); the approver decides in their in-app inbox.

The inbox routes are reachable by any authenticated user (a named approver need not be a KI-Manager) and are fenced server-side by the caller's tenant and identity — you see and decide only the runs where you are the named approver.

GET /admin/v1/me/approvals → { "approvals": [ { id, workflow_id, workflow_name, approval_step_key, approval_node_label, approval_deadline, cost_micros, created_at, requested_by_email, requested_by_name } ] } — my pending approvals (an empty inbox is { "approvals": [] }). requested_by_email / requested_by_name name the run-as-owner (workflow.created_by); both are always strings — "" when the owner is unknown or a deleted user (the UI shows "—"). approval_node_label is the approval step's friendly builder name (its version-graph node label, resolved on read); absent when the node has no label, and the UI then falls back to the translated "approval" type name — never the raw approval_step_key.

GET /admin/v1/me/approvals/{run_id} → { "approval": { … approval_node_label, run_state, outputs_withheld, requested_by_email, requested_by_name … }, "steps": [ … ] } — the confirm-page detail. run_state, outputs_withheld and the steps' error columns follow the run detail's rules for the named approver: the trigger output is reduced to its field names; in a run that handled personal data an approver who is not the workflow's owner receives no other step output (the keys are in outputs_withheld) and no step error / delivery_error text (flagged error_withheld / delivery_error_withheld). Its approval carries the same approval_node_label as the inbox, and each steps row carries the per-step node_label (see Runs) so the confirm page names every produced output by its friendly step name. It is identity-scoped: a caller who is not the named approver (or the run is not in their tenant / no longer suspended) gets 404 — run_state (which may carry PII) never leaks to a non-approver.

The decision is a POST after authentication (never a GET with a side-effect):

POST /admin/v1/me/approvals/{run_id}/decision

{ "decision": "approve" }
{ "decision": "reject", "reason": "Zahlen nicht plausibel — bitte prüfen." }

decision ∈ {approve, reject} (any other value → 400 decision must be approve|reject). Success answers 200 { "decision": "approve", "status": "pending" } or 200 { "decision": "reject", "status": "failed" }. A session without a tenant — or with an empty or malformed tenant or user id — answers 401 { "error": "unauthenticated" } on all three inbox routes; nothing is read. approve resumes the run (status: suspended → pending; the runner then carries it past the approval node and continues); reject fails it closed (status: failed, error_code: approval_rejected).

Reject requires an audit reason (public-sector audit trail). Accepted shape: a string of 1..1000 characters (Unicode codepoints) after trimming surrounding whitespace. It is validated at the trust boundary — after the 403/404 authz gate, before the state change — and anything else is rejected fail-closed with the run left suspended (never a partial reject): a missing, non-string or empty reason, or one with nothing visible (only whitespace, Unicode spaces, control, zero-width / format characters or the braille blank — see blank) → 400 reason required; invalid UTF-8 → 400 reason invalid; an over-1000-char reason → 400 reason too long. A reason made only of such characters (control characters included) is refused. The stored value is trimmed of surrounding ASCII whitespace. On approve, reason is ignored. The reason is stored (parameterized) in the run's error field alongside error_code: approval_rejected, so the run owner sees WHY it was rejected in the run detail.

Both approve and reject are a single atomic compare-and-swap gated on status = 'suspended' (and the caller's tenant_id + approver_id), so a second decision — or a timeout that fires concurrently — loses and receives 409 { "error": "already_decided" }. A caller who is not the named approver — or a run whose approver is not a user or carries no approver id — gets 403; a run absent from their tenant, 404. The approver provenance (approver_ref, the approver's email) is recorded on the run and rendered "freigegeben von X".

Approving past the deadline is refused. The approve CAS also requires the approval's deadline to be in the future (approval_deadline > now). An approve at or after the deadline answers 409 { "error": "expired" } (distinct from already_decided) and does not approve; the route then applies the node's timeout policy immediately (skip auto-proceeds, end fails the run with approval_timeout) instead of waiting for the runner scan. If that immediate apply fails, the 409 expired answer is unchanged and the scan applies it later. A reject past the deadline is still accepted. Runs past their deadline are omitted from the approver's inbox (GET /me/approvals).

Storage faults: a failed read (the approval list, the approval page, the decision's pre-check) answers 503 { "error": "temporarily unavailable; retry later" }. An approve that wrote nothing (a transient conflict) answers the same 503 — approve again; any other fault on the approve is 500 { "error": "internal error", "request_id": "…" } (the decision may or may not have landed — reload before deciding again). A reject whose write fails answers the 500 (re-read before rejecting again).

Approval timeout policy (skip | end, configured on the node; default end) is enforced by an expired-approval scan in the runner: past the deadline the run either auto-proceeds (skip — a Freigabe bypass when the approver is gone) or fails closed (end), per policy — never hangs indefinitely. The timeout apply and a human decision race on the same status = 'suspended' CAS, so exactly one wins.

The decision itself is also fenced in storage, not only in the route: an approve or reject is written only when the caller's id and the run's approver id are both non-empty and exactly equal (the comparison is made in code under the row lock, not by the database collation, which would ignore case and trailing spaces). A run whose approver id is empty is therefore never decidable by anyone, and the approver's inbox never lists it.


Deliver node — egress is fail-closed

A Deliver node reuses the existing run-delivery egress controls (one mechanism). Its outcome is the full delivery_status enum: delivered | failed | skipped_empty | blocked_pii | blocked_ssrf | blocked_tenant. PII gate (the §1 claim): if any Agent-Step in the run masked PII (X-AIG-PII-Active: 1, an X-AIG-Delivery level other than allow, or an absent X-AIG-PII-Active header — treated as active, fail-closed), external egress is refused and the Deliver step shows blocked_pii; if the gateway's own PII latch refuses a send the runner did not know to block, the outcome is the same: blocked_pii plus the content-free owner notice. This holds for all three channels: an email send is refused by POST /internal/workflow/deliver-email (403 blocked_pii / recipient_pii_blocked), and a webhook or Mattermost Deliver first asks the gateway POST /internal/workflow/deliver-clearance and sends nothing unless the answer is 200 {"cleared": true}. The clearance answer is fail-closed on the runner side: 403 blocked_pii gives blocked_pii; a 2xx whose disposition is present and not exactly "allow" (for example approval_1, null) also gives blocked_pii; any other 4xx gives failed_input; a 5xx, a transport error, a missing internal-API configuration or claim token, or a 2xx body without "cleared": true gives failed (never delivered). Both clearance answers and the deliver-email PII refusals carry the run's disposition and reasons (Delivery disposition).

Delivery release of a Deliver step. The runner names the asking step (step_key; for an email step to an external recipient also the resolved to), and the gateway applies the release approval: when the run's disposition is approval_1 / approval_2 and the step goes to an external channel (webhook, Mattermost, an email recipient that is not tenant-internal), the clearance answers 200 {"cleared": false, "held": "<release id>", "created": true|false, "disposition", "reasons"} instead of 403. Nothing is sent; the step row becomes held with delivery_status: waiting_release, the run is suspended (suspended_reason: awaiting_tool_approval) and, when the release was newly opened, the owner gets the content-free "waiting for release" notice (their own copy attached under the internal-delivery opt-in). A runner whose own PII gate would block a webhook / Mattermost / external email step asks the gateway first for that reason. /settle-tool-holds re-serves the run once the release is decided and the re-entered step asks again:

Release Clearance answer Step outcome
pending / awaiting_second 200 {"cleared": false, "held", "created": false} parked again
approved, destination unchanged, the re-check (the current level over the sources of every agent step, under every step agent's tightening) still permits it 200 {"cleared": true, "released": "<id>"} — the release is claimed (closed) delivered once through the remaining gates (no runner PII gate); a released Mattermost result is never e-mailed to the owner instead; a released email names the release (release_id + step_key) and is sent without its attachment (attachment_omitted_pii)
approved, but the re-check now blocks 403 blocked_pii blocked_pii + owner notice
approved, but the destination is not the released one (dest_hash) 403 release_changed failed_input
denied 403 {"error": "release_denied", "release_id"} release_denied + one content-free notice; run deliver_release_denied
expired 403 {"error": "release_expired", "release_id"} release_expired + one notice; run deliver_release_expired

The runner reads these answers strictly: released must be a 1..64 character [A-Za-z0-9-] id with cleared exactly true and disposition approval_1 / approval_2; a refusal without a well-formed release_id is no release refusal (failed_input). Like blocked_*, release_denied / release_expired are never retried. Steps after a held Deliver step run only after the release.

When X-AIG-PII-Active is 1. Personal data masked anywhere in an Agent-Step counts — its prompt, a page it fetched, a web search result or the search query, a file it read, a knowledge passage, a connector (MCP) result. A workflow whose agent reads the web (the press-review example) and finds a page naming a person therefore ends its webhook / Mattermost Deliver in blocked_pii with the owner notice, while an e-mail Deliver to the owner (or to a member of the tenant under the internal-delivery opt-in) still sends. The run row stores where the personal data was found as delivery_disposition + delivery_reasons (places only, never the data). Every attempt asks again (the answer is never cached), so a retry after the run latched PII is refused. The owner notice is the same content-free notice for every channel: it says the result was not delivered, never which channel and never the content. Known limit (same as the email fence): the runner process itself performs the webhook / Mattermost request, so a fully compromised runner could still skip the question; the gateway's latch makes the honest path and a runner that merely misreports PII safe, it does not turn the runner into a sandbox. A Deliver that does not reach delivered hard-fails the run (error_code: deliver_blocked_pii etc.); skipped_empty (nothing to send) is a success. The delivering step row is persisted before egress, so a replay refuses to re-fire a non-idempotent delivery with an unknown outcome (no doubled egress).

Deliver targets at publish and read time

Publish, rollback and copilot-validate refuse a deliver node that could never deliver (422 invalid_graph, or ok:false for copilot-validate), so the failure is reported to the author instead of at the first run. The check runs after the structural validation has passed, on every deliver node of the graph (loop bodies and branches included), and reports all failing nodes at once. The rules are the runner's own (core/wf_deliver_target.tl at publish / read time, scripts/wf_delivery.py deliver_target_error in the runner, bound by one corpus, tests/fixtures/wf_deliver_target_corpus.json). A config value counts as absent when it is missing, null, "", 0, false or an empty object / array (the runner's reading); any other value is judged as present. A config that is not an object is treated as having no kind.

code field Refused when (accepted shape) reason
deliver_bad_kind kind kind is absent, not a string, or not exactly one of mattermost, webhook, email, none (case-sensitive; none is an explicit no-op) unknown deliver kind
deliver_mattermost_not_enabled kind kind: "mattermost" and the tenant's mattermost_delivery_enabled is not exactly 1 (fail closed: absent, 0, true, "true", an unknown tenant → off). Checked before the channel. mattermost delivery not enabled for tenant <slug>
deliver_channel_required channel_id Mattermost, channel_id absent invalid mattermost channel_id
invalid_deliver_channel channel_id Mattermost, channel_id present but not a string matching ^[a-z0-9]{26}$ (a #name, uppercase, wrong length) invalid mattermost channel_id
deliver_url_required url kind: "webhook", url absent webhook url must be https
invalid_deliver_url url Webhook, url present but not an https URL with a host and without user name or password, or not parseable (Python urllib.parse semantics, as the runner reads it). Publish also refuses any non-ASCII byte in the authority (the runner's NFKC host check cannot be mirrored; write an internationalised host in its xn-- form) malformed webhook url / webhook url must be https / webhook url has no host / webhook url must not embed credentials / webhook url host must be ASCII (write an internationalised name in its xn-- form)
deliver_url_not_public url Webhook, publish only (DNS): the host name does not resolve (NXDOMAIN, or contains characters no host name can have), or any A / AAAA answer is not a public address (loopback, private, link-local, metadata, …), or an IP-literal host is not public webhook host does not resolve to a public address for a host NAME (one sentence for both cases, and the answer is never echoed, so publish and copilot-validate reveal nothing about internal DNS) / blocked private/internal address: <ip> for an IP literal
deliver_bad_recipient to kind: "email", to present but not a non-empty string, or neither a single {{…}} ref nor a valid literal address bad_recipient
deliver_owner_missing (none) the workflow has no valid owner (created_by erased or malformed); every deliver step whose kind is not none is refused at publish / rollback / copilot-validate; no tenant or DNS read is made (none)
deliver_recipient_not_allowed to Email, to is a valid literal address that the tenant's workflow_recipient_allowlist does not match (the same rule as the run-time /deliver-email fence; no / corrupt allowlist → nothing matches) recipient_not_allowed

Accepted without a verdict at publish (decided at run time):

  • Email to absent or null → the workflow owner. A to that is a single {{…}} ref → the resolved address is checked by the /deliver-email allowlist fence on every run.
  • A Mattermost node without a configured bot token — the runner falls back to emailing the owner.
  • Webhook DNS is resolved at publish (and copilot-validate) only, never at read time, with a fresh, uncached A + AAAA lookup (1 s timeout, one retransmit). A resolver error, timeout or a partly failed lookup is the warning deliver_url_unverified (field: "url", reason dns resolution failed: resolver error (checked again before every send)) — publish goes ahead, and the runner re-resolves and re-checks the address before every send (blocked_ssrf). At most 10 host names are looked up per publish (a repeated host is looked up once; an IP-literal host needs no lookup and does not count); every further one gets the warning with reason dns lookup skipped: too many webhook hosts in one publish (checked again before every send).

deliver_bad_recipient is also reported, without field / reason, by the structural validator (wf_validate) before this check runs.

Read time — published workflows are flagged, not unpublished. The workflow detail GET (deliver_issues, deliver_issues_fixed_in_draft) and list GET (deliver_issue_count) apply the same static and tenant rules (no DNS) to the current published version of a published or disabled workflow (see Workflow CRUD). A workflow published before this check, or one whose tenant later switched Mattermost delivery off or narrowed the allowlist, keeps running; the builder and list only show a warning.

Run time is unchanged. The runner applies the same rules when a run reaches the node: Mattermost not enabled → blocked_tenant; a missing or invalid channel → failed; a missing or invalid webhook URL, or one that resolves to a non-public address → blocked_ssrf; an email recipient is decided by the /deliver-email fence. An unknown kind on an old version published before this check is still a silent no-op (treated as none).

Tainted runs — the recipient is still the allowlist

An email-triggered run cannot send mail to an address the model chose. A Deliver to (see External recipient via the per-tenant allowlist) is checked by the server against the tenant allowlist on every run, tainted or not: an address that is not on it is refused with 403 recipient_not_allowed and nothing is sent. The same holds for an attachment_ref (it must be an artifact of the same run) and for a Code node's input_refs. No change is needed on those paths for a tainted run.

Tainted runs — no auto-loading media in the delivered answer

On a tainted run (a run started by an inbound email, a webhook or a form; see email triggers and webhook triggers; the taint is server-derived, never a request field, and only a literal untrusted_content: false is untainted) the Deliver text is neutralised before it leaves, so a prompt-injected answer cannot exfiltrate data through a rendered URL (zero clicks: a markdown image, an HTML <img>/<iframe>, or a mail client's remote content). The text is first canonicalised: it is Unicode-normalised (NFKC) and every HTML character reference is decoded (&lt;, &#60;, &#x3c;, nested or partly encoded references, fullwidth or compatibility look-alikes), repeatedly, until it no longer changes. The rules then apply to that canonical text, so no spelling of <, { or an image-opening ! can survive:

  • no ! survives. Every ! becomes ǃ (U+01C3, a look-alike letter that no markdown or HTML parser treats as syntax), including a ! inside a URL (before [, before a bare URL, a space, punctuation, the end of the text, Done!x, #!/, ...). No image marker can form in any spelling or after any number of render passes (including the autolink-then-html2text-then-render chain): ![x](https://host/p) becomes ǃ[x](https://host/p), which shows a link instead of loading an image, and https://maps/?data=!3m1!4b1 becomes https://maps/?data=ǃ3m1ǃ4b1. The rule is structural and does not inspect URLs, brackets, backslashes, code spans or emphasis;
  • percent-encoding is a decode level too: %21, %3c and %7b (any case, and also with the % itself re-encoded as %25, %2521, ...) become %C7%83, %E2%9D%AE and %E2%9D%B4 (the percent-encoded UTF-8 of ǃ, ❮, ❴), each counted, so a receiver that URL-decodes the text before rendering it still gets no !, < or {;
  • every { becomes ❴ (U+2774), because a markdown attribute list ({: style=… }, [x]{style=…}) can make a renderer emit a style attribute with a url() that loads without a click;
  • after the rules, a safety check follows every route by which a !, a < or a { could reappear (decoding a reference, NFKC, markdown backslash escapes, URL-decoding, in any order); text that still could takes the fallback;
  • every < becomes ❮ (U+276E), so no HTML tag can form. An exact <https://…> / <mailto:…> / <a@b.c> autolink instead loses its brackets and is delivered as the plain URL. Code spans are not exempt;
  • an xn-- punycode host label (any case) whose decoded or NFKC form holds !, <, {, [, ], (, ), &, %, \ or a transliteration ender, or that cannot be decoded, or is longer than 256 characters, loses its prefix: xn-- becomes xn⸺⸺ (U+2E3A twice), counted once per label; ordinary internationalised hosts stay byte-identical. Under glibc iconv ASCII//TRANSLIT the guard's own neutralised form no longer transliterates back to xn--; a model-written xn‐‐ (or any other x/n/dash producer) still reaches an iconv receiver as xn--, which falls under "ASCII-transliterating receivers: not covered";
  • the characters that glibc transliterates to a string ending in < («, ‹, ≪, ≮, ≹, ⋘, ⟨, ⟪, ⧼, 〈) become ❮ and those ending in ! (¡, ¬) become ǃ, so glibc iconv ASCII//TRANSLIT cannot rebuild an opener. Under glibc iconv ASCII//TRANSLIT the guard's own substitutes transliterate to ?; under unidecode / anyascii-style libraries they map back to markup (not covered: ASCII-only output alphabet or approval hold);
  • if the text does not settle within 8 rounds, or a rule would join fragments into a new reference, every & becomes ⅋ (U+214B) and every % becomes ٪ (U+066A) as a fail-closed fallback (counted once in n).

The count n is 0 exactly when the delivered text equals the input; decoding or folding the text counts once per text.

Receiver model: up to two standard markdown/HTML render rounds (CommonMark/GFM including markdown-it with linkify, python-markdown including extra, HTML5 parsing, html2text HTML-to-markdown), with HTML character-reference decoding, Unicode normalisation (NFKC), percent-decoding, punycode/IDNA decoding and markdown backslash-escapes in between. ASCII-transliterating receivers (iconv ascii//TRANSLIT, unidecode-style) are not covered; the substitutions below (for example ❮ for <) are a partial mitigation only, with no guarantee.

Not covered: ASCII-transliterating receivers (iconv ascii//TRANSLIT, unidecode-style), Org-mode [[url]], JavaScript %u0021, overlong UTF-8 %C0%A1, quoted-printable =21, an xn-- prefix split by a default-ignorable character (x, U+00AD, n--; also U+200B, U+034F: standard decoders such as Node URL, Python idna and punycode.js reject it, so only a non-standard strip-then-decode receiver is exposed; closing it would need an ASCII-only output alphabet or an approval hold), markup that is not markdown or HTML (reStructuredText .. image::, AsciiDoc image::, BBCode [img]), link unfurlers that fetch a plain URL a user or a chat tool shows, and more than two render rounds.

Cost on a tainted run only: every ! (including a ! inside a link and an ordinary sentence-ending Done!) is delivered as ǃ (a hashbang link https://x/#!/inbox arrives as https://x/#ǃ/inbox, which a single-page app that matches #!/ literally will not recognise), every < as ❮, every { as ❴, and a percent-encoded %21 / %3c / %7b as %C7%83 / %E2%9D%AE / %E2%9D%B4. ;-terminated and numeric references are delivered decoded (&amp; arrives as &, &#60; as ❮) and compatibility characters are folded (fi becomes fi, m² becomes m2, ™ becomes TM). Only ;-terminated named references and numeric references are decoded; a name without ; such as &region=eu or &copy=1 is left alone, so a link is delivered byte-identical apart from the ! / < / { rules above and one more case: a parameter that starts &lt, &LT, &amp or &AMP without ; gets its & replaced by ⅋ (a mail client would decode it to < or &). A link containing encoded or compatibility characters is delivered in their decoded form. As a partial mitigation only (ASCII-transliterating receivers are not covered), the characters that an ASCII transliteration turns into < («, ‹, ≪, ⟨, 〈 and similar) are shown as ❮, and ¡ and ¬ (which turn into !) as ǃ, so prose with «guillemets» arrives with ❮. A punycode host label (xn--…) whose decoded form holds !, <, {, brackets, &, % or \ loses its prefix (xn-- becomes xn⸺⸺, with U+2E3A), counted once per label; ordinary internationalised hosts such as xn--mnchen-3ya.de stay unchanged. Under glibc iconv ASCII//TRANSLIT the guard's own neutralised form no longer transliterates back to xn--; a model-written xn‐‐ (or any other x/n/dash producer) still reaches an iconv receiver as xn--, which falls under "ASCII-transliterating receivers: not covered". Under glibc iconv the guard's own substitutes transliterate to ?; under unidecode / anyascii-style libraries they map back to markup (not covered: ASCII-only output alphabet or approval hold). A legacy name without ; (&not, &laquo, &iexcl) gets its & replaced by ⅋, like &lt and &amp. If the safety check cannot settle a text, the fallback costs more: & becomes ⅋ and % becomes ٪ across the whole text, so links with query strings or percent-escapes then stop working. Input and delivered text (after decoding and NFKC, which can expand a character up to 18×) are each truncated at 1,048,576 characters; each cut is counted. Not covered: ASCII-transliterating receivers (iconv ascii//TRANSLIT, unidecode-style), model-written values in other node fields (the url of a Fetch node, Code node refs, Deliver attachment_ref / to) are not covered by this guard. A Mattermost delivery on a tainted run is posted as an attachment card, so the channel creates no link preview. When anything was changed (including a decoded reference, a folded character or a truncation) the step records external_media_neutralised:<n> in delivery_error (the delivery itself is still delivered). An untainted run (schedule, manual) is delivered byte-identical.

Email attachment

An email-kind Deliver node may attach a workflow_artifact (e.g. the filled PDF a code node produced) via one optional config key:

  • attachment_ref — a single {{step.output.artifact.handle}} reference to a prior node's artifact handle. It must be a single template ref; a literal handle is rejected at publish (deliver_bad_attachment_ref) because a handle is a run-scoped value minted at execution time. Absent → a plain email (unchanged behaviour).

At delivery the runner resolves the ref to a handle and the loopback /deliver-email endpoint loads that artifact scoped to the current run (a node can only attach an artifact of its own run) and composes a multipart/mixed message. Accepted / rejected (fail-closed, Inv. 11):

  • the handle is validated (present-but-empty / malformed → 400 bad_handle); an unknown or foreign handle → 404 attachment_not_found; a corrupt / sha-mismatched artifact → 422 attachment_corrupt; an over-cap artifact (the ~6 MiB artifact-store cap) → 413 attachment_too_large. Any load failure hard-fails the send — a requested attachment is never silently dropped.
  • the attachment filename is sanitized before they enter the MIME headers so a crafted name can never inject a header: / and \ become _; CR/LF/control, " and ; are removed, invalid UTF-8 is repaired (U+FFFD), and invisible control/format characters (bidi overrides, zero-width, BOM) are dropped. An ASCII name is sent as a plain filename="..."; any other name (non-ASCII, %, or containing =?) is sent only as an RFC 2231 filename*=UTF-8''... parameter (no plain filename= beside it). The Content-Type name= parameter is a lossy ASCII fallback (non-ASCII characters become _); the exact name is in filename*. A missing, empty, dots-only or longer-than-255-byte name becomes attachment.
  • Content-type: Must be a plain type/subtype token (letters, digits and !#$&^_.+-, at most 127 bytes, lower-cased); anything else (quotes, backslashes, control characters, spaces, non-ASCII, =? encoded words, other specials, oversize) and a NULL content-type fall back to application/octet-stream. Composite top-level types (multipart/*, message/*) are rejected the same way, because the attachment is always sent base64-encoded without a boundary (RFC 2045 §6.4); the filename and extension are kept.
  • a 4xx from the endpoint is a deterministic terminal outcome (failed_input, not retried); 5xx/transport stays retryable.
  • PII: on the PII-internal delivery path (a masked run delivering to the internal owner) the unmaskable binary attachment is omitted; the delivered row records attachment_omitted_pii (observable, never a silent drop). Only the message body (subject to the existing PII gate) is delivered there.

External recipient via the per-tenant allowlist

By default a deliver-email node sends to the workflow owner (resolved server-side; never from the request). An email deliver node may instead target an external recipient via one optional config key:

  • to — the external recipient: a single {{…}} template ref (resolved at runtime, e.g. {{trigger.output.recipient}}) OR a literal address (local@domain.tld, a single @, a dotted domain, no whitespace, no control character — C0, DEL or a C1 control U+0080–U+009F — and only well-formed UTF-8). Malformed at publish → deliver_bad_recipient. Absent → the owner recipient (unchanged behaviour).

The external send is permitted ONLY if the recipient is on the tenant's workflow_recipient_allowlist — a tenant-admin-curated JSON array of allowlist entries, each an exact address (vipwing@munich-airport.de) or a domain (@munich-airport.de). It is set on the tenant via the admin tenant PATCH (a member cannot curate it), DB-backed config, and GET /admin/v1/tenants/{id} returns it as the same JSON array (null when unset). Domain entries match by exact domain equality — @munich-airport.de matches x@munich-airport.de only, never a subdomain (x@evil.munich-airport.de) or suffix (x@munich-airport.de.evil.com). IDN/non-ASCII addresses are not allowlistable (fail-closed).

Fences at the loopback /deliver-email (fail-closed, Inv. 11):

  • the PII fences (below and the opt-in membership check) key on the run's persisted pii_active. The gateway latches it itself: when it serves an agent invoke bound to a workflow run (X-AIG-Workflow-Run-Id, honoured only for the unattended service-token invoke and only when it names a running workflow run of the same tenant and gateway; ignored for every other caller, except that a chat-bridge driver connection refuses it with INVALID_IDENTITY; an unresolved id from an unattended caller gets the call its own run, a malformed one a 400; a same-gateway unattended service token naming a running run is treated as that run's step only while the run's current agent step is the invoked agent; otherwise the call gets its own run) and the response is PII-masked (the same condition that emits X-AIG-PII-Active: 1), it sets workflow_run.pii_active = 1 before the response is sent, fenced by tenant and gateway. If that write fails, the invoke fails closed (500, masked body not sent). The runner's own reports (/save-step, /finish-run, /suspend) still latch too; a runner that never reports no longer leaves the fences open;
  • a restricted owner (GDPR Art. 18) → 403 owner_processing_restricted, no send, for every content send (body, attachment, any to). The PII notice mode is unchanged. The runner reports it as follows: on the Mattermost owner-e-mail fallback the node ends failed (bounded by the node's max_attempts); on the e-mail node kind it is a terminal failed_input (a 4xx is never retried);
  • a present-but-malformed to → 400 bad_recipient;
  • an external to on a PII-masked run → 403 recipient_pii_blocked, no send — an unmaskable body/attachment must never egress to a non-tenant address (the anti-exfiltration control is preserved; only the internal-owner relaxation applies on masked runs). The one exception is a released step: release_id + step_key (both or neither, else 400 bad_release_id; release_id a 1..64 character [A-Za-z0-9-] id, step_key a step key, else 400 bad_release_id / bad_step_key; only with a to, else 400 bad_release_id) naming the step's release that the clearance claimed (closed) for exactly this recipient — anything else is 403 invalid_release, no send. A released send never carries an attachment (handle: 400 attachment_not_released, no send — the release covers the composed result, not a binary nobody reviewed). The allowlist below still applies;
  • the release notices of a Deliver step: notice waiting_release | release_denied | release_expired with release_id + step_key (required, else 400 bad_release_id); only waiting_release may carry text (the owner's own copy, a non-empty string, else 400 bad_text; cut at the body cap; attached as result.txt only when the internal-delivery opt-in allows the owner the unmasked result and the owner's processing is not restricted). The step's release must be that id (404 release_not_found) in the mode's state (409 release_not_waiting / release_status_mismatch); a rejected / expired release is told once (a repeat answers 200 {"notified": false}). The notice is content-free, goes to the workflow owner, and links the release card while it waits, the workflow run once it was rejected or expired. 200 {"notified": true, "copy_attached"};
  • no allowlist configured, an unreadable/empty allowlist, or a recipient not on it → 403 recipient_not_allowed, no send (never a silent fall-back to the owner);
  • a matched external send is audited (workflow.deliver_external, with the recipient + matched entry). The subject stays server-built; a notice (blocked-PII) always goes to the owner. The record is written before the send (outcome=send_attempt, one row per attempt — a retry writes another) and is fail-closed: if it cannot be stored, nothing is sent and the call answers 500 { "error": "db" } instead of sending an unrecorded email.

An invalid allowlist entry at the admin write door → 400 recipient_allowlist_error.


Condition node — one comparator, an always-present else (D6)

A Condition routes the chain down one of two branch sub-chains. Its config is { "left_ref": "{{step.output.path}}", "op": "eq|ne|contains|gt|lt|is_empty", "right_value": "…" }. In the graph a Condition has three out-edges: a branch:"true" head, a branch:"else" head (the else branch is always present), and an optional plain "after" edge where the main chain resumes. Branch nesting is depth 1 (a branch may not contain another Condition/Loop), and the branch sub-chains never rejoin — no fan-in.

At run time the runner resolves left_ref and applies the comparator: eq/ne/ contains compare the value's string form against right_value; gt/lt are numeric (a non-numeric value or operand is a hard fail, condition_type_error); is_empty is true for "", [], or {} (the right_value is ignored). An absent right_value compares against "". The comparison value is only ever right_value: a config that carries a right key instead (or as well) is refused at publish, copilot-validate and run-claim with condition_stray_right (the run fails with that error_code before any step; the runner refuses the condition with the same code as a backstop), so a value under the wrong key can never silently compare against "". Such a run's error detail names the fix (enter the value under Compare with and publish again); it is also the reason in the owner's failure e-mail for a scheduled run. The taken branch executes; every step in the not-taken branch is marked skipped (no execution, no egress). A cjson null or a missing value on the compared path is a documented hard fail (template_null_path / template_unresolved) — never a silent else. A Condition produces no referenceable output ({{condition.output.…}} is a publish block). Replay-safe: the not-taken skipped rows are persisted before the Condition's own row, so a reaped run never re-runs a not-taken branch.

Loop-lite node — sequential, bounded, collect-all (D7)

A Loop iterates a JSON array. Its config is { "items_ref": "{{step.output.array}}" } and it has a branch:"body" sub-chain head plus a plain "after" edge. The array is resolved once and bounded before iteration one: a non-array is loop_not_array and more than 10 items is loop_too_many (rejected, never clamped). For each item (0- based) the body runs with the current item bound as {{loop.output.item}} and {{loop.output.index}}; each body step is persisted as an iteration row keyed step_key#i. The loop is collect-all: after the last item, loop.output is { "items": [ …one entry per iteration… ], "count": N }, referenceable by the after- chain. First failure fails the loop (fixed policy — the per-node on_error key described under Error handling below is not available inside loop bodies, and a body step always uses the error policy; per-step retry IS available in bodies).

A loop body may not deliver or ask for approval: deliver, approval and connector nodes are rejected in a loop body at publish AND run-claim (loop_body_side_effect). Body agents may be re-invoked after a crash (re-charging tokens), but nothing is delivered twice.

A Fetch in the loop body is allowed. On an untrusted run, a Fetch with a model-derived URL is held for review per iteration under the row key step#i, and the run suspends. When the run resumes, finished iterations are replayed from the stored state and never run again. Partial progress is stored in run_state under the loop key ({partial, items, count, current}) and is visible in the run detail. If the loop state is missing or malformed while body rows are already finished, the run fails closed as loop_state_invalid. If the hold state is too large to store, the run fails as loop_hold_state_too_large. Other loop body outputs are transient; the collected {items,count} is persisted when the loop completes.

Structural validation (blocks publish, re-checked at run-claim): a graph must have exactly one Trigger with no in-edges and every other node exactly one in-edge (no fan- in); at most one plain out-edge and one edge per branch slot per node; branch slots must match the container (condition → true/else, loop → body); branch depth ≤ 1; every node reachable from the Trigger; step keys [A-Za-z_][A-Za-z0-9_]*, ≤ 60 chars (so a #i iteration suffix fits). A {{}} ref to an output-less node (Condition, Deliver) is a block.


Error handling — per-step retry and on_error

Agent and Deliver nodes accept two optional config keys (absent = today's behavior, so existing graphs are untouched):

{ "retry":    { "max_attempts": 3, "backoff_seconds": 10 },
  "on_error": "error_branch" }
  • retry.max_attempts — integer 1..5 (default 1 = no retry). retry.backoff_seconds — number 0..30 (default 5), a fixed delay between attempts; additionally (max_attempts - 1) * backoff_seconds must be <= 120. Out-of-range values are a publish block (bad_retry_config).
  • Only known-transient failures retry, fail-closed: an Agent step retries on a transport error or HTTP 5xx/429; a Deliver step retries only a delivery_status: "failed" outcome. Policy blocks (blocked_pii / blocked_ssrf / blocked_tenant) and other 4xx are permanent and never retried, and so is an Agent step the gateway refused for the caller's own money or limits (a wallet-empty/frozen/disputed 429 carrying wallet_state, a 402 whose X-AIG-Error header is trial_expired, subscription_inactive, trial_budget_exhausted or wallet_insufficient, a 403 with plan_model_not_allowed or eu_gov_model_not_allowed, a member-cap 429 (user_budget_exceeded / team_budget_exceeded) with x-should-retry: false, an agent pause or spend-cap refusal). A caller refusal is never retried: it fails at once as agent_refused and records the gateway's own sentence (e.g. "This workspace has no remaining balance ... (http 429)") instead of a bare http 429. Every arm counts only when the gateway's own X-AIG-Error header names the code (and the body code agrees; the wallet 429 additionally needs a valid wallet_state). A provider's relayed 402/429 without that header stays a paged agent_failed: a 429 is retried per the step policy, a 402 is final at once. A 429 without a recognised wallet_state (rate limit, the retryable committed-quota refusal) still retries; an unknown or malformed wallet_state is treated as absent. And so is an Agent step whose turn is cut off mid-answer after its tools ran (an interrupted answer: the typed error carries x-should-retry: false, because the model call failed mid-turn; a cut with no tool round is an ordinary retryable 5xx; a 2xx carrying X-AIG-Error is read the same way as a defensive backstop; see Inference › Interrupted answers): the step fails (a typed 5xx records its own reason, e.g. http 502; the 2xx backstop records "interrupted: the answer was cut off (<code>)"), its partial never enters run state, and the step's on_error policy applies; every Deliver retry re-runs the full fail-closed gate chain (PII, SSRF pinning, tenant allowlist). Deliver retry is at-least-once: a failed outcome can be a timeout after the request was already received, so a retry can deliver twice — make webhook receivers idempotent. (failed also covers permanent causes, e.g. an invalid channel id, which retry pointlessly — bounded by max_attempts.)
  • Each attempt persists its own step row (attempt 1-based) with that attempt's cost/tokens; the lease is re-extended around every attempt and backoff sleep. Retries count against the run budget, and the run deadline/cancel/budget are checked before every attempt — under deadline pressure absorption is best-effort (a run_deadline/budget_exceeded abort wins over the policy).

on_error — what happens when the FINAL attempt fails ("error" default):

Policy Behavior
error the run fails with the step's error code — exactly today.
continue the step's final row becomes continued (failure absorbed, underlying error/delivery_status preserved); the run proceeds. The step produces no output, so {{}} references to it are publish-blocked (ref_to_fallible_step). Not allowed inside loop bodies (on_error_in_loop_body).
error_branch the node carries a second out-edge (branch: "error" — the catch chain). On final failure the entire after-chain is persisted skipped, the step becomes continued, and the catch chain runs; on success the catch chain is persisted skipped and never runs. Catch chains are linear (no Condition/Loop/nested error edges — branch_depth_exceeded); references to the failing step from its own catch chain are publish-blocked (ref_to_failed_source), while after-chain references stay legal (the after-chain only runs on success). Requires exactly one error edge (error_edge_required / error_edge_without_policy); not allowed inside containers (error_branch_in_branch).

A run whose failures were all absorbed finishes succeeded — the step rows carry the truth (the runs UI shows per-attempt rows, the continued disposition, and any preserved block outcome; a blocked_pii absorbed by continue still renders the PII block on its step row).

Publish-time validation codes added by this feature: bad_retry_config, bad_on_error, error_edge_required, error_edge_without_policy, error_branch_in_branch, on_error_in_loop_body, ref_to_fallible_step, ref_to_failed_source (all re-checked at run-claim like every other rule).

Node configuration codes

Publish and run-claim validation answer each node's config with one rule: a missing, null or empty required value answers <field>_required; a value that is present but wrong answers invalid_<field>. One entry per node and field, carried in the errors array of a 422 invalid_graph. A config that is present but not a JSON object (a string, number, true or array) on a node type with required fields answers a single invalid_config and skips that node's field checks; an absent or null config is treated as {}. The accepted and rejected graphs are unchanged; only the spelling differs.

Node Missing / null / empty Present but wrong
Agent agent_slug_required, input_required invalid_agent_slug (not a string); agent_not_owned; invalid_input (not a string)
Condition left_ref_required invalid_left_ref (not a single clean {{…}} ref); condition_stray_right (a right key is present, whatever its value, even null)
Loop items_ref_required invalid_items_ref (not a single clean {{…}} ref)
Approval approver_required invalid_approver (a wrong part wins over a missing one)
Fetch url_required invalid_url
Code code_required invalid_code
Connector connector_id_required, tool_required, connector_input_required invalid_connector_id, invalid_tool, invalid_connector_input
Deliver deliver_bad_kind (kind absent), deliver_channel_required, deliver_url_required deliver_bad_kind (unknown kind), deliver_mattermost_not_enabled, invalid_deliver_channel, invalid_deliver_url, deliver_url_not_public, deliver_bad_recipient, deliver_recipient_not_allowed, deliver_owner_missing; warning only: deliver_url_unverified

The Deliver codes carry field (kind | channel_id | url | to) and reason; they keep the deliver_ prefix of the existing deliver_bad_recipient / deliver_bad_attachment_ref. Unlike the other rows (except the Agent input_required / invalid_input) they are checked at publish, rollback and copilot-validate only, not at run-claim — the runner applies the same rules when a run reaches the node. Rules: Deliver targets at publish and read time.

Structural slots: condition_branch_required (a Condition lacks a branch), loop_body_required (a Loop has no body) and error_edge_required (an error_branch policy without its error edge).

Earlier spellings that are gone: agent_missing, condition_missing_ref, loop_missing_ref, approver_missing, condition_missing_branch, loop_missing_body, error_branch_missing_edge, fetch_missing_url, code_missing_source, connector_missing_field. Branch on the new codes. The builder still highlights the field for validation results that carry an old spelling; a run that failed at claim before this change keeps its old error_code and shows the generic run-error text, as before.

Typed codes on refusals

Every JSON error on the workflow routes (/admin/v1/gateways/{id}/workflows…, including webhook, form and email triggers, schedules, runs and versions) and on the approval inbox (/admin/v1/me/approvals…) carries a top-level code next to the unchanged HTTP status and error text. Branch on code; never parse error. (The shared sign-in 401 / 403 answered before a route runs are not part of this set.)

A refusal about one request field also carries field, the offending key. Absent and malformed are told apart: a missing, null or empty value answers field_required; a value that is present but wrong answers invalid_field. Both keep the same status and error sentence.

Group Codes (status)
Generic unauthenticated (401); forbidden, feature_disabled, platform_admin_only (403); not_found (404); malformed_body, invalid_request, field_required, invalid_field (400); rate_limited (429)
Workflows and versions version_not_found, run_not_found, trigger_not_found, user_not_found, group_not_found (404); graph_malformed, invalid_transition, no_published_version and workflow_not_published (the machine string is also the error text); invalid_graph (publish and rollback, 422; code is the machine string and error is the English sentence workflow graph failed validation; the earlier spelling graph_invalid is no longer sent, and clients may accept both during the change)
Publish and rollback stale (409, the draft changed since it was read), already_current (409); the deliver_* entries (including deliver_owner_missing) inside an invalid_graph errors array (422) and the deliver_url_unverified warning in warnings (201) — see Deliver targets at publish and read time
Triggers webhook_exists, form_exists, schedule_disabled, form_disabled, email_trigger_disabled, invalid_schedule
Runs run_already_terminal (409)
Approvals already_decided, expired (409); approver_not_found, approver_not_in_tenant (approver in another tenant, deleted, or without a tenant)

A decision that is neither approve nor reject answers 400 with invalid_field (field: "decision"), or field_required when it is missing.

Error codes

The run's typed error_code drives a translated message in the runs UI via the workflow.runErrors.* i18n namespace (kept separate from the builder's validation workflow.errors.* codes to avoid a key collision), with a generic fallback for an unrecognised code; the raw English error string is shown only in an expandable technical-details view (never verbatim on the main surface).

error_code Meaning
lease_expired the runner died mid-run; the lease reaper marked it failed (visible, never eternal "running"). Manual replay from the run detail.
budget_exceeded the run hit run_budget_micros; aborted at a step boundary.
the validator's first error code (for example invalid_step_key, invalid_connector_input, agent_not_owned), graph_malformed if it names none the bound version failed structural validation at run-claim (e.g. an agent's schema drifted, or a cycle). Re-validation happens at claim, before any step runs. The code is the first entry of the validator's errors list.
agent_not_owned an Agent-Step references an agent the workflow owner no longer owns (or that was deleted). Enforced at publish AND re-checked at run-claim — the run fails closed before any invoke, because the per-gateway service token could otherwise invoke any agent.
owner_processing_restricted the workflow owner's or the run creator's processing is restricted under GDPR Art. 18. Checked at run-claim, including the claim that resumes a suspended run: the run fails closed, no further step runs, no egress. Lifting the restriction takes effect on the next claim. Also returned by the loopback /deliver-email (403) for a content send when the owner is restricted.
owner_unavailable the workflow owner or the run creator is deleted or disabled, or the owner is unknown. This includes the erased-owner case: erasing a user clears workflow.created_by, so a workflow whose owner was erased has no owner and its runs fail closed at claim. It is also the cancel code for the pending runs of an erased user (the erasure and the tenant purge cancel them with the payload cleared). Checked at run-claim, including the claim that resumes a suspended run: no further step runs, no egress.
department_gateway_not_allowed the department of the workflow owner or the run creator does not allow the run's gateway. Checked at run-claim (including the claim that resumes a suspended run) after the account checks: the run fails closed, no further step runs, no egress.
tenant_suspended the run's organisation is suspended (tenant.suspended_at is non-null; only with the tenancy switch on, see Partner tenancy API). Checked first at every run-claim, before the graph and account checks, including the claim that resumes a suspended run: the run fails closed, no further step runs, no egress. A deliberate asymmetry with scheduled work, which the scheduler holds untouched until the resume: a refused workflow run stays failed and is not requeued after the resume (re-trigger it). No failure e-mail is sent to the owner (the internal notify route answers notified: false, reason: tenant_suspended), no ops triage row is written (neither paged nor queued), and it does not count towards the schedule failure backoff. A run already past its claim keeps running; an Agent-Step it calls after the suspension is refused by the gateway (403 tenant_suspended) and is not retried (a 4xx is permanent) and currently ends agent_failed; unless the step's on_error absorbs it (the run then goes on), the run ends failed with agent_failed, which is paged. Its non-agent steps (fetch, connector, sandbox, Deliver) are not fenced. MAP-4373 makes it agent_refused.
agent_refused the gateway refused an Agent-Step invoke because of the caller's own wallet, spend limits or agent pause (wallet 429 with wallet_state, a typed billing 402, plan-model 403, member-cap 429, 409/403 pause or spend cap). Never retried; a caller fault, so it does not page on-call. error carries the gateway's reason.
guardrail_blocked a guardrail of the run's gateway refused an Agent step (the gateway's block marker on the agent invoke, or a refusal whose marker was missing or malformed — fail closed). The step is failed (error_class, blocked_by, block_reason on its row), not retried (a temporary guardrail outage class follows the step's retry policy first), not absorbed by on_error; every later step is skipped (with error_class = guardrail_blocked on the skipped row) and nothing after the step is delivered. The run error names the step and the guardrail.
agent_failed an Agent-Step invoke returned a non-2xx at runtime (other than a caller refusal, see agent_refused) (the agent exists and is owned, but the model/provider call failed) and the step's retry/on_error policy did not absorb it. (Independent of configured retries, a single in-attempt retry fires on a 422 structured_output_failed response — stochastic and idempotent.)
agent_tool_rejected an Agent-Step's held tool call was rejected by the approver; the call never ran. Absorbable by on_error.
agent_approval_expired an Agent-Step's held tool call was not decided within the approval window; no further invoke. Absorbable by on_error.
agent_step_unknown_outcome an Agent-Step's agent run is in a state whose outcome cannot be established (a gated call may have executed). Never re-invoked and not absorbable by on_error. Also raised when a resume claim returns a missing, malformed or disagreeing decision.
run_deadline the run exceeded its wall-clock cap at a step boundary.
template_unresolved a {{step.output.path}} reference could not be resolved (missing/unfinished step) — a hard step error, never a silent empty string.
template_null_path a resolved path traversed a JSON null — documented hard fail (a Condition's compared path or any {{}} ref).
condition_type_error a Condition gt/lt comparison hit a non-numeric value or operand — fail-closed, never a silent else.
loop_not_array a Loop's items_ref did not resolve to a JSON array — rejected before iteration one.
loop_too_many a Loop's array exceeded the 10-iteration cap — rejected before iteration one (no silent clamp).
loop_state_invalid a Loop's stored state is missing or malformed while its body rows are already finished. The run fails closed, because restarting the loop could repeat a step that already ran.
loop_hold_state_too_large a Fetch in a loop body was held, but the loop's state is too large to store for the resume. The run fails with no further egress.
step_output_too_large a step's output exceeded the run_state cap (256 KB/run, 32 KB/step).
deliver_release_denied / deliver_release_expired a Deliver step's delivery release was rejected (Don't deliver) or expired; nothing was sent to its channel and the owner was told once.
deliver_hold_suspend_refused a Deliver step held for its release could not park the run (the gateway refused the suspend); nothing was sent.
deliver_blocked_pii / deliver_blocked_ssrf / deliver_blocked_tenant / deliver_failed a Deliver node did not reach delivered. The target rules behind blocked_tenant / failed / blocked_ssrf are also checked at publish (the builder-side deliver_* validation codes, see Deliver targets at publish and read time), so on a version published after that check these mostly mean the tenant setting, the allowlist or the webhook's DNS changed since.
schedule_deleted / schedule_disabled a still-pending schedule-triggered run was cancelled because its schedule was removed or disabled (kill-switch parity — no orphaned pending fire).
webhook_trigger_deleted a still-pending webhook-triggered run was cancelled because its webhook trigger was deleted (the same kill-switch parity as the schedule codes above).
fetch_failed a Fetch node's download failed transiently (network / timeout / redirect-loop / upstream 5xx / 429) and the step's retry/on_error policy did not absorb it. Retryable (mapped status 502).
fetch_blocked a Fetch node's URL was refused by the SSRF pin (private/link-local/loopback/metadata target, or an unsafe redirect). Deterministic — never retried.
fetch_http_<status> a Fetch node's upstream returned a non-2xx. A 4xx (except 429) is deterministic (not retried); a 5xx/429 is retryable.
fetch_too_large a Fetch node's body exceeded the fetch/artifact cap (~6 MiB). Deterministic.
fetch_empty a Fetch node got a 2xx with an empty body. Deterministic.
content_type_rejected / content_type_not_allowed a Fetch node's bytes failed the magic-authoritative content sniff, or the sniffed canonical MIME was not in the node's allowed_content_types. Deterministic.
egress_blocked_residency a Fetch or Connector node was refused because the gateway is residency-restricted — EU-residency enforced (per-gateway flag, tenant floor, or the deployment env) or all providers local. The node cannot egress to a third party at all. Deterministic (never retried); no call/download occurs.
url_pii_blocked a Fetch node's resolved URL carried protected structured PII (a checksum-valid national ID, IBAN, card number, a configured keyword, or — when the gateway's PII Protector enables dk_recognizers — a separated Danish CPR number such as 010190-1234, or a bare one under a CPR-named query parameter such as ?cpr=0101901234) on a PII-active / PII-masking-enforced gateway, or on any gateway whose Web pages source sets pii.input to block (not under allow; see Fetch node). A URL cannot be tokenized and stay fetchable, so the policy is refuse, not scrub. Deterministic; no download occurs.
url_keywords_blocked / url_keywords_unchecked a Fetch node's URL (or a held / approved off-origin redirect target) matched a keyword / regex detector the Web pages source's keywords.input cell refuses / the detector set could not be read, so the URL was not checked. Deterministic; no download occurs.
gateway_unresolved a Fetch node's gateway could not be resolved (soft-deleted or corrupt config). Deterministic fail-closed (no egress). A transient config read error instead returns a retryable db.
code_disabled a Code node ran on a gateway where the code-interpreter is not fleet-configured, or has been explicitly disabled (code_interpreter.enabled: false). Deterministic (501) — absorbable by on_error, never a transient tick-retry.
code_unavailable a Code node's sandbox call reached the broker but it was unavailable/saturated (no-isolation / busy / transport). Retryable (mapped status 502).
code_too_large a Code node's job exceeded the sandbox pre-flight size cap (the encoded {code,stdin,limits} body). Deterministic.
code_unsafe_input an input artifact of a Code node was refused by the sandbox staging safety check (the response's reason: dtd, unreadable_xml, bad_package, zip_bomb — see Inference › Files a sandbox tool will not open). Deterministic (422) — nothing was run. When the check itself cannot run, the step answers the retryable code_unavailable.
code_failed / code_timeout a Code node's program exited non-zero (or with an unknown exit) / hit the wall-clock limit (60 seconds per run). Deterministic. The response carries the exit_code only — never stderr (it would persist in workflow_step_run.error).
code_no_output / code_no_usable_output / code_ambiguous_output a Code node produced no /output artifact / only harvest-rejected outputs / more than one with no output_filename to disambiguate. Deterministic.
code_chromium_error_page the Code node's deliverable PDF is headless Chromium's own error page ("Your file couldn’t be accessed … ERR_FILE_NOT_FOUND" — what Chromium prints, with exit code 0, when told to print a file or URL it cannot open). The page is never stored. Returned when that page is the output_filename output or the only output; a stray error page next to a real output is dropped and the real output is used. Deterministic (422) — fix the input path in the code.
code_duplicate_input / input_not_found two input_refs resolved to the same /input filename / an input_refs handle is not an artifact of this run. Deterministic (422 / 404).
code_reserved_input an input_refs artifact's stored filename is the reserved _context.json (the always-staged trigger-context slot). Deterministic (422) — rejected before the run so a step cannot spoof/clobber the context.
code_output_too_large a Code node's /output exceeded the ~6 MiB artifact store cap. Deterministic.
input_required / invalid_input an Agent node's input was absent, null or empty / present but not a string (publish, rollback and copilot-validate only; not re-checked at run-claim — a run of an older version that reaches such a step fails with agent_failed). Deterministic.
connector_id_required / tool_required / connector_input_required a Connector node's connector_id, tool, or input was absent, null or empty (publish-time validation). Replaces the earlier single connector_missing_field. Deterministic.
invalid_connector_input a Connector node's input is not a valid JSON-with-refs template: not a JSON object (or a single {{…}} ref), a {{…}} ref in an object key, in a string escape, or split by a backslash, an invalid escape or a raw control character in a string, a duplicate key, or nesting deeper than 64 levels. Rejected at publish (and by copilot validate); a draft that was never published never runs. At run time the step fails with the same code and no call occurs. Deterministic.
template_bad_value a value substituted into a Connector input cannot be written as JSON: NaN or Infinity, a lone UTF-16 surrogate, or a structure nested deeper than 64 levels. The step fails and no call occurs. Deterministic.
connector_bad_input a Connector node's resolved input did not decode to a JSON object — a scalar, a non-empty array, or undecodable JSON, including a value nested more than 1000 levels (ABSENT≠MALFORMED: a value that arrives wrong is rejected, never degraded to "no args"). The workflow runner refuses it before the delivery is recorded; the gateway applies the same check. Deterministic; no call occurs.
connector_input_too_deep / connector_input_key_collision / connector_input_too_large a Connector node's input on a tainted run could not be neutralised: a value nested more than 64 levels below the top-level object (after the refs are substituted), two keys equal after neutralising, or the neutralised JSON exceeds the 64 KiB connector input cap (each <, {, ! or percent form grows, for example < from 1 to 3 bytes). Deterministic; no call occurs.
connector_input_invalid a Connector node's rendered input could not be read back as a UTF-8 JSON object (defence in depth: the template check and template_bad_value normally refuse such input first). The step fails and no call occurs. Deterministic.
connector_pii_blocked a Connector node's arguments carried protected structured PII (checksum ID / IBAN / card / configured keyword / on a dk_recognizers gateway a separated Danish CPR, or a bare one under a CPR-named key such as {"cpr": "0101901234"}) on a PII-active / PII-masking-enforced gateway and the connector's pii.input is mask (the default; a trusted_subprocessor reads as allow), or on any gateway when it is block. Refuse, not scrub. Deterministic; no call occurs. Arguments nested deeper than 8 levels or with more than 2000 values cannot be checked and are refused the same way; this check runs before the approval hold. See Connector node.
connector_keywords_blocked / connector_keywords_unchecked a Connector node's arguments matched a keyword / regex detector the connector's keywords.input cell refuses (arguments too deep or too many values to be checked whole count as a match) / the detector set could not be read, so the arguments were not checked. Deterministic; no call occurs.
connector_args_too_large a Connector node's arguments hold a value, key or bare string longer than 16,384 bytes under the same rule as connector_pii_blocked (pii.input mask on a PII-active / PII-masking-enforced gateway, or block). A value that long cannot be checked for protected personal data, so it is refused, not truncated. Deterministic; no call occurs. Send the content in smaller pieces.
connector_gateway_unresolved a Connector node's gateway could not be resolved (soft-deleted or corrupt config). Deterministic fail-closed (no call). A transient config read error instead returns a retryable db.
connector_call_failed a Connector node's tools/call failed — a definitive error (not_found / tool_blocked / arg_rejected — an argument outside a catalog bound / credential_required / credential_expired / init_error / access_denied — see access-layer refusals) or an AMBIGUOUS upstream outcome (timeout / reset / 5xx-after-send). Also when the run's delivery disposition for the connector's result could not be recorded (the result is discarded, see Connector node). Always terminal, NEVER auto-retried (D1 — a mutating call whose outcome is unknown must not re-fire). A crash mid-call instead surfaces the shared deliver_unknown_outcome on resume (the resume reap is node-agnostic).
connector_input_number_not_exact / connector_input_number_too_long a Connector node's input holds a number that cannot be sent exactly: a decimal with more than 17 significant digits (for example 1.00000000000000000001), one that does not survive a double, or one outside the double range, an integer a double cannot hold exactly or beyond ±2^63 (_not_exact), or an integer longer than 4300 digits (_too_long). The workflow runner fails the step before any call (tainted and untainted runs); the gateway refuses the same input with 422 (such integers are refused there too). No call occurs; see JSON numbers.
connector_input_number_invalid a Connector node's input holds NaN, Infinity or another number token that is not valid JSON. Refused with 422 before any call (the workflow runner can also fail the step with this code before any call; a literal NaN / Infinity in the template is normally refused first as invalid_connector_input).
connector_input_duplicate_key a Connector node's input repeats a key at any depth ({"a":1,"a":2}). A JSON parser would keep only the last occurrence, so the tool would receive a value different from the reviewed text. Refused with 422 before any call. Input that is not well-formed JSON at all stays connector_bad_input.
connector_args_unencodable a Connector node's arguments could not be encoded for the upstream call without changing a number. Refused with 422 before any call.
trigger_input_number_not_exact / trigger_input_number_invalid / trigger_input_number_too_long / trigger_input_invalid the stored trigger input of a run (for example a webhook payload) could not be read exactly: a number that is not exactly representable, NaN / Infinity, an integer of more than 4300 digits, or text that is not valid JSON. The run fails at claim with no step run and no egress; other runs are not affected.
run_state_invalid / graph_invalid the stored run state or the stored workflow graph of a run is not valid JSON; the run fails at claim with no step run and no egress. graph_invalid is also the code when the stored graph fails a run-time structural check (a cycle, a dangling branch, loop or error-branch member, a nested container or an illegal node such as a deliver step in a loop body).

Fetch node — SSRF-pinned download

A Fetch node downloads a URL to a binary workflow artifact (the /artifact store) and emits its handle ({{fetch_key.output.artifact}}) for a later node to consume. Because the Python runner has no HTTP-fetch and no SSRF pin, the download runs server-side in the gateway (the loopback /fetch endpoint, below) — making the gateway the single, audited egress authority for workflow downloads. The trust-boundary contract (Invariant 11):

  • url is untrusted: the SSRF pin (connection_plan/resolve_pinned_ip) fails closed — private/link-local/loopback/cloud-metadata targets, userinfo, control bytes, DNS-rebinding, and unsafe redirects are all blocked (fetch_blocked). The pin is re-validated on every redirect hop. A private target is accepted only when the workflow's tenant lists its exact host:port in its connector egress hosts; the deployment-wide AIG_SSRF_ALLOW is not consulted.
  • The fetched bytes are untrusted third-party content: the artifact's MIME is decided by a magic-byte sniff of the bytes (upload_sniff), never the response Content-Type header — a spoofed or absent header cannot smuggle a disallowed type past the gate. A node's optional allowed_content_types is enforced against the canonical (sniffed) MIME; a malformed allowed_content_types is rejected, never treated as "allow any".
  • Caps: the body is capped at max_bytes (clamped to the ~6 MiB artifact cap); an oversize body is fetch_too_large. A 2xx empty body is fetch_empty. Both deterministic.
  • Retry: transient failures (fetch_failed, upstream 5xx/429) retry per the node's retry config or take its error_branch; deterministic failures do not.
  • Audit: every egress attempt (blocked, failed, rejected, or stored) writes an audit_log row (action=workflow.fetch) with the authority only (scheme://host — never the path or query, which can carry a token) plus a SHA-256 of the full URL for correlation, the byte size, and the outcome. The per-outcome rows are best-effort (an audit failure never fails the fetch, and is logged at error level). The dial itself is fail-closed: before every outbound dial (and each redirect dial) one egress_attempt row is written with the run id (status 0, because it precedes the address checks; a redirect dial also records the redirect target's authority and URL hash). If that row cannot be stored, nothing is dialled and the call answers 500 { "error": "db" } (the runner retries on the next tick). After an approved (held) fetch has already claimed its approval, the same failure answers 422 { "error": "db" } and the owner's approval is spent, like approved_fetch_store_failed.
  • Tainted runs: the URL must be fixed. On a tainted run (an email, webhook or form run; the taint is server-derived, see the Deliver section above) a Fetch node whose URL a prompt-injected model could choose is refused before any download: the gateway answers 403 untrusted_egress_refused, the audit row records the refusal, and an untrusted_egress denial is recorded for the access log. A model-derived URL is held instead (see below). The gateway re-reads the node's url from the stored workflow graph (never from the request) and accepts only a URL whose destination is fixed by the author or by the trigger:

    • No {{ref}} at all (a literal URL): the request URL must equal the stored one exactly.
    • Only trigger references ({{trigger.output...}}): the content of the mail itself, which the sender already knows, so it is accepted.
    • A literal scheme://host[:port] followed by /, ? or #, with references only in the path or query (https://api.example.com/cases/{{hold.output.text}}): accepted, the resolved authority must still match the literal one, and redirects are confined to that origin (scheme, host and port) on every tainted run (email, webhook and form); a redirect to another origin is held for the owner (see "Redirect to another origin" below).
    • A model-derived URL (a reference in the scheme, host or port, such as {{agent.output.url}}) on the plain Fetch step of a run that has a workflow owner: held for the owner instead of refused (next section).
    • Anything else (a stored graph or node the gateway cannot read, a run without an owner): refused (fail closed). 401, 409 (lost lease) and the residency gate are unchanged.

    This describes email (strict) runs. Webhook and form runs are held the same way for a model-derived URL, with one difference described after the table below.

    Two edges worth knowing:

    • Only the trigger counts as fixed. A Fetch whose URL contains a reference to any other non-trigger step (including a model's output, {{hold.output.text}}) is held for the owner on a tainted run, even if the value happens to be harmless. The one exception is a reference inside a literal scheme://host/ prefix: there only the path or query is dynamic, and the URL is accepted with redirects confined to that origin. On any tainted run a Fetch on a run without an owner is refused, never held (see the webhook and form paragraph below). A Fetch inside a loop body ({{loop.output.item}}) is held per iteration like a plain step. This is fail closed on purpose for email runs.
    • Scheme and redirects. A non-http(s) scheme (ftp://host/{{trigger.output.subject}}) is refused before any connection is opened. The redirect confinement compares the origin (scheme, host and port, scheme and host case-insensitively); a redirect that leaves it is not followed, and no request is sent to the other origin until the owner has approved it (next paragraph).
  • Model-derived URL: held for the owner. On a tainted run, a Fetch whose URL a model chose is held: the gateway checks the residency and URL-PII gates first (a URL that could not be fetched anyway is never held), then opens one approval for the workflow owner and answers 202 {held, review_id, expires_at}. The run suspends with awaiting_tool_approval. The owner sees the exact URL on the tool-approvals card (/me), with the workflow name and run. The approval is a single approval (no second approver) and is valid for 7 days.

    • Approve: the Fetch is performed at most once, for that exact URL (compared byte for byte; any other URL is refused). The approved fetch is not confined to the URL's origin, because the owner approved this exact address. If the download or the store fails after the approval was taken, the step fails terminally and is not retried, which includes a crash between taking the approval and the download: the approval is spent.
    • Reject, expiry, or any other state: 403 untrusted_egress_refused; nothing is downloaded. A rejected or expired hold produces an approval_rejected / approval_expired access-decision record at decision time, and an untrusted_egress denial record each time the run re-enters and is refused (two distinct events).
    • Already spent / too late: 422 untrusted_egress_approval_used (the approval was already used) or 422 untrusted_egress_approval_lapsed (it was approved but not executed within the 7 days plus a 5-minute grace for an approval taken just before the window closes). An approval granted close to expiry therefore leaves the run 5 minutes to re-enter; past that the step fails with untrusted_egress_approval_lapsed.
    • There is no separate mail to the owner when a hold expires; the run is settled and the step fails with untrusted_egress_refused.
  • Redirect to another origin: held for the owner. A Fetch with a fixed origin is dialled once, confined to that origin. If the server answers with a redirect to a different origin, nothing is requested from the target: the gateway opens one approval for the workflow owner (202 {held, review_id, expires_at}, hold reason untrusted_egress) that shows the fetched URL and the redirect target. The target must pass the same address checks as any Fetch URL; one that is blocked (a private address, a URL carrying personal data, a URL the Web pages keyword cell refuses) is refused (403) and never held.

    • The approval binds the target's origin (scheme, host and port), not the exact target URL. Signed links may therefore change within the approved origin: after the approval the Fetch is performed at most once, and a redirect to the approved origin is followed even if its path or query differs from the one the owner saw.
    • Only the first redirect may leave the origin. A second redirect to a different origin is refused (after the approval: 422), including one back to the original origin. The Authorization bearer is not sent to the other origin.
    • What counts as the same origin. An upgrade on the same host from http to https counts as the same origin when the port moves from the http default to the https default (80 to 443) or stays the same explicit port (http://host:8080 to https://host:8080). A downgrade from https to http, and any other port change, is a different origin and is refused. This holds for the template's own origin as well: a Fetch whose server upgrades the same host to https is followed without an approval, and is still confined to the upgraded origin. After the approved redirect, the same upgrade of the approved host is followed once more (it cannot go back down to http).
    • After the approval, the residency, URL-PII and keyword checks run again on the actual target when it is dialled. A host that now redirects to a different origin than the approved one, or an approved target that fails, ends the step terminally with 422 (not retried; the approval is spent).
    • Reject, expiry and the already-spent states answer as for a model-derived URL above.
    URL template on a tainted run Result
    https://api.example.com/status accepted (literal, exact match)
    https://api.example.com/{{trigger.output.subject}} accepted (trigger reference)
    https://api.example.com/cases/{{hold.output.text}} accepted, redirects confined to https://api.example.com:443 (an off-origin redirect is held for the owner)
    {{hold.output.text}} held for the owner (model-derived URL)
    https://{{hold.output.text}}/x held for the owner (model-derived URL)
    https://api.example.com{{hold.output.text}} held for the owner's approval (model-derived: the literal authority is not ended by /, ? or #)
    any model-derived URL (e.g. {{loop.output.item}}) in a Fetch inside a loop body held for the owner, once per iteration
    ftp://files.example.com/{{trigger.output.subject}} refused at connect (not http/https)

    The refusal is terminal: it is not retried, and on_error: continue absorbs it like any other failed fetch. Webhook and form runs behave exactly like email runs: every tainted level holds a model-derived URL, and confines a fixed-origin URL to its origin, in the same way. A Fetch on a run without an owner is refused on every tainted run, webhook and form included (403 untrusted_egress_refused): there is no owner to hold it for; an ownerless Fetch with a fixed origin is dialled confined, and an off-origin redirect is refused (403, nothing held). A run without an owner cannot start or resume (see owner_unavailable in the error codes); only an owner removed while the run is already executing reaches this refusal. A Fetch inside a loop body is held per iteration on every run kind. Untainted runs (schedule, manual) are unchanged, until they become tainted mid-run (next paragraph). The Connector node has its own hold for a model-written call on a tainted run.

  • A run can become tainted mid-run. A schedule or manual run also becomes tainted when an attached agent step's tool result brings in outside content (for example the agent fetched a web page). The mark is latched on the run and only ever added, never removed, so it survives a suspend and resume. From then on the later Fetch, Connector, Deliver and agent steps of that run are treated like those of a webhook or form run: held for the owner and neutralised; a call on a run without an owner is refused, and an off-origin redirect of a Fetch is held for the owner. Steps that already ran are not re-judged.

  • Residency (fail-closed): on a residency-restricted gateway the Fetch node is refused before any download (egress_blocked_residency). "Restricted" means the gateway is EU-residency enforced (the per-gateway eu_region_routing flag, the tenant residency floor, or the deployment-wide enforcement) or every configured model provider is local — and, fail-closed, any gateway whose residency posture cannot be positively determined. A workflow run has no conversation/project context, so this binds to the gateway's own residency posture. (Code nodes are unaffected: their sandbox is network-isolated — no third-party egress on any gateway.)
  • Personal data in the URL (the Web pages source's cells, fail-closed): the gateway's web_pages built-in source decides, as it does for the chat fetch tools. A protected identifier means national ID, IBAN, card number, a configured keyword, or on a gateway with dk_recognizers a separated Danish CPR or a bare one under a CPR-named parameter (a URL cannot be tokenized and stay fetchable, so the policy is refuse, not scrub). Free-text names pass. A non-UTF-8 URL is rejected up front (bad_url).

    • pii.input mask (the default): on a PII-active or PII-masking-enforced gateway a url carrying a protected identifier is refused (url_pii_blocked) — mirroring the chat fetch tool and the Deliver node.
    • allow (Send as is): the URL is fetched; a workflow run has no masked values to restore. Under pii_masking_enforced it reads as mask.
    • block: a URL carrying a protected identifier is refused on every gateway (url_pii_blocked), and the refusal is recorded as an access decision (guardrail_input:pii, tool workflow.fetch, place url:<host> — the bare url when the host itself carries the value — the URL itself only as a SHA-256).
    • On a Fetch whose redirects are confined to its origin (an author-fixed origin on a run started by untrusted content, see the redirect hold below), both rules here (personal data and keywords) also vet an off-origin redirect target: it is refused like the URL itself, never held for approval, and an approved target is checked again right before it is dialled. Other redirects are followed without these checks. An approved target whose dial lands on a hop these rules refuse is answered with the same code as a refused URL (url_pii_blocked / url_keywords_*, 422 because the approval is spent) and the same access decision.
    • Keywords (keywords.input): the keyword / regex rules as they are defined (the gateway's, the baseline's and the extra rules of the workflow owner's role, as in the owner's own chat) are applied to the URL like in chat. A refusing match answers url_keywords_blocked (guardrail_input:keywords recorded); when the detector set cannot be read the URL is refused unchecked (url_keywords_unchecked). allow skips the detectors, flag only logs a match.
    • A gateway source_policy that cannot be read holds Web pages to the Untrusted class (never read as allow).
    • Egress reach: the fetch shares the process-wide operator egress allowlist (empty in int/prod → fully fail-closed). An allowlisted host short-circuits the private-IP block and is honored on redirect hops — set it only for operator-vouched hosts. A dedicated per-tenant workflow-egress allowlist is a planned hardening.

Code node — headless sandbox run

A Code node runs author-supplied Python in the network-isolated code-interpreter sandbox (--network none KVM micro-VM; pypdf/reportlab/openpyxl are available) over prior nodes' artifacts, and stores the program's /output as a new workflow artifact ({{code_key.output.artifact}}). The sandbox call runs server-side in the gateway (the loopback /code endpoint, below), reusing the same ctx-free broker the chat code-interpreter uses. The trust-boundary contract (Invariant 11):

  • Enablement (opt-out): the code-interpreter is on by default, so the node runs whenever it is fleet-configured and the run's gateway has not opted out (code_interpreter.enabled != false; absent / null → on). Only an explicit code_interpreter.enabled: false yields code_disabled (501, no sandbox call).
  • code is OPAQUE: the source is untrusted but runs only in the isolated sandbox (never in the gateway) — isolation is the control; it is size-bounded (≤ 64 KiB; the broker re-checks the encoded job against its 128 KiB cap → code_too_large). It is never template-resolved: a {{…}}-shaped token in the code is literal Python, so run data can never be spliced into executed source (a code-injection seam) and legit Python containing {{ (an f-string f"{{x}}", a set literal {{1,2}}) publishes clean. Run data reaches the program only as data, via /input/_context.json and input_refs.
  • /input/_context.json — the trigger context: every Code node's sandbox is staged with a /input/_context.json file carrying the run's consumed trigger output as a JSON object. Read it with json.load(open("/input/_context.json")). For a form run it is the validated {field_key: value} submission — and a file field carries the extracted, PII-masked text (identical to {{trigger.output.<field>}}), never the upload sentinel or its single-use submission_token. For a webhook run it is the webhook JSON payload. Every submitted trigger field lands in the sandbox (not only referenced ones). Values are data, not source — quotes, newlines, backslashes and non-ASCII round-trip because they are JSON-encoded. The file is always present and always a JSON object: a manual run with no input, or a trigger output that is absent / not an object / a JSON array, degrades fail-closed to {} (so json.load(...).get(...) never raises) — a data-only empty object, never a control bypass. A pathologically deep trigger payload that cannot be re-encoded also degrades to {} (fail-closed).
  • _context.json is a RESERVED name: an input_refs artifact whose stored filename is _context.json is rejected before the run (422 code_reserved_input) — a prior or malicious step cannot spoof or clobber the trigger context.
  • input_refs are artifact handles of this run: each is loaded run-scoped + lease-fenced + SHA-verified (a foreign/unknown handle → input_not_found, never a cross-run/tenant read), capped at 7 files (the sandbox holds 8; one slot is reserved for /input/_context.json) — enforced at both publish (code_bad_input_refs) and runtime (400 bad_input_refs), so there is no publish-clean/runtime-fail drift. They are staged as /input/<stored-filename>. Duplicate /input names are rejected (code_duplicate_input) before the run. The context file counts toward the shared 16 MiB input-files total, so a code node already staging near 16 MiB of input_refs can newly trip the total-size cap (code_bad_input).
  • Output: the /output artifact is magic-gated + capped by the sandbox harvest, then re-capped at the ~6 MiB artifact store. Selected by output_filename (or the sole output's own name); bytes come from the artifact's text (csv/txt/json/html) or bytes (pdf/xlsx/png) by kind. The file named by output_filename is admitted first, before any other file the code wrote (so side files never push it out of the per-run file budget). An .html written beside another output is not a candidate for an unnamed pick — without output_filename, or when the named file is a nameless chart picture — while a name that matches the .html selects it, and an .html alone is the output. Zero/ambiguous output is a deterministic code_no_output / code_ambiguous_output; when no output is left because every file was over the size cap the answer is 413 code_output_too_large, and when every file was rejected it is 422 code_no_usable_output.
  • Classification: a broker call that reaches the wire but fails (no-isolation / busy / transport) is the only retryable class (code_unavailable, 502). A pre-flight reject (never reached the sandbox — oversized job, unsafe input) and a program failure (code_failed / code_timeout, from a successful broker call with a non-zero/timeout result) are terminal.
  • Audit: every run attempt writes an audit_log row (action=workflow.code) with the input handle count, output size, and outcome — never the code source or stderr (they would persist and can embed secrets). Best-effort (an audit failure never fails the run, and is logged at error level): the run is sandboxed and its inputs and output stay in the tenant's own artifact store, so no customer-visible egress depends on the row.

Connector node — call an MCP/API connector mid-run

A Connector node calls an existing MCP/API connector's tools/call mid-run and maps the (PII-scrubbed, size-capped) result into run_state as {{connector_key.output.result}} for a later step. The Python runner has no MCP/credential/SSRF capability, so the call runs server-side in the gateway (the loopback /connector endpoint) — the same single, audited egress authority as Fetch. The trust-boundary contract (Invariant 11):

  • Run-as-owner. The call is made as the workflow owner (the workflow's created_by), using the owner's credential and resolving the owner's private connector. A cross-user private connector is invisible (not_found → connector_call_failed); a tenant-shared connector (created_by NULL) is tenant-fenced, not owner-fenced, so any author in the tenant may bind it. Trigger-supplied data (e.g. an inbound email) that flows through input into the owner's connector + credential is an accepted run-as-owner trust boundary, governed by the PII/residency gates below.
  • Tainted runs neutralise the input. On a tainted run the input JSON is parsed and every string value and object key is neutralised exactly as in the Deliver node before the call. Input that cannot be neutralised fails the step and no call occurs: two keys that become equal after neutralising → connector_input_key_collision; input nested too deeply → connector_input_too_deep; input that exceeds the 64 KiB connector input cap after neutralising (neutralising can lengthen text) → connector_input_too_large. (A literal NaN / Infinity or a duplicate literal key is already refused when the template is checked, as invalid_connector_input; a substituted value that cannot be written as JSON as template_bad_value.) What is sent is exactly the neutralised parse, re-serialised: number values are kept exactly (a decimal of at most 17 significant digits is written as its shortest double text, so 3.141592653589793 and 0.1 stay unchanged and 0.10000000000000001 becomes 0.1; integers keep every digit), only the spelling may be normalised (1.50 → 1.5, 1E2 → 100.0, -0 → 0). On every run, tainted or not, a number that could not be forwarded unchanged fails the step before any call: a decimal with more than 17 significant digits (for example 1.00000000000000000001) or outside the double range (1e400) → connector_input_number_not_exact, an integer longer than 4300 digits → connector_input_number_too_long; an integer a double cannot hold exactly or beyond ±2^63 is then refused by the gateway with the same connector_input_number_not_exact (see JSON numbers). An untainted run's input is not neutralised. The exact limits and refusal codes are listed in the error table above.
  • Refs are JSON-encoded where they stand. The input template is parsed as JSON in which {{…}} refs may stand inside a string or as a whole value; every substituted value is then encoded for that slot, so a value can never add, drop or replace an argument. A ref inside a string gets the value's text with the JSON escapes applied (", \, control characters). A ref as a whole value becomes one JSON value: a text value becomes a JSON string, any other value (number, boolean, object, list) keeps its type. Example: the subject x", "delete": true, "z": " in {"title": "{{trigger.output.subject}}"} reaches the tool as the single argument title carrying that whole text. A ref in an object key is refused at publish (invalid_connector_input). A value that cannot be written as JSON (NaN, Infinity, a lone surrogate) fails the step with template_bad_value. Behaviour change: a whole-input ref such as {{step.output.text}} whose text is itself JSON now yields a JSON string, which the step refuses as connector_bad_input before any call; build the object in the template instead ({"query": "{{step.output.text}}"}). A literal [] input is now refused at publish.
  • input is untrusted. The resolved input must decode to a JSON object; a single whole-input {{ref}} must resolve to an object. A scalar, a non-empty array, or undecodable JSON is rejected (connector_bad_input) — ABSENT and MALFORMED do not share a permissive path; a value that arrives wrong is rejected, never degraded to "no args". A non-UTF-8 input is rejected up front (bad_input).
  • Residency (fail-closed). On a residency-restricted gateway (EU-residency enforced, all providers local, or an indeterminate posture) the node is refused before any call (egress_blocked_residency). A workflow run has no conversation/project context, so this binds to the gateway's own residency posture.
  • Personal data in the arguments (the connector's source cells, fail-closed). The connector's source policy pii.input decides, with the same verdict as the chat / agent tool call. A protected identifier means national ID, IBAN, card number, a configured keyword, or on a gateway with dk_recognizers a separated Danish CPR or a bare one under a CPR-named key; such arguments are refused, not scrubbed (a token would break the tool). Free-text names pass.

    • mask (the default): on a PII-active or PII-masking-enforced gateway, arguments carrying a protected identifier are refused (connector_pii_blocked).
    • allow (Send as is): the arguments are sent unchanged (a workflow run has no masked values to restore), also under pii_masking_enforced. A connector marked a trusted_subprocessor (a vetted EU/DPA subprocessor; see MCP connectors) reads as allow unless its source sets pii.input itself — the exemption works as before.
    • block: arguments carrying a protected identifier are refused on every gateway (connector_pii_blocked), and the refusal is recorded as an access decision (guardrail_input:pii, place tool_args:<tool>, the arguments only as a SHA-256, the workflow as the actor).
    • Keywords (keywords.input): the keyword / regex rules as they are defined (the gateway's, the baseline's and the extra rules of the workflow owner's role) are applied to the arguments like in chat. A refusing match answers connector_keywords_blocked (guardrail_input:keywords recorded); when the detector set cannot be read the call is refused unchecked (connector_keywords_unchecked). Arguments nested deeper than 8 levels or with more than 2000 values cannot be checked whole, so on a gateway with a blocking keyword / regex rule (or a connector cell block) they are refused as connector_keywords_blocked, also on a gateway without PII protection.
    • A connector the run's organisation cannot read (deleted mid-run, a read fault) is held to its strictest cells (block).
    • These checks run before the approval hold. The same mcp_egress authority governs the chat agent tool path.
    • The result is the connector's (its Coming back cells). The result is checked as the connector's result, as the workflow owner (the owner's role rules and personal keywords apply, as in the owner's own chat):
    • Keyword and regex rules run as they are defined, on every gateway (also one that masks no personal data): the gateway's and the baseline's rules and the owner's role extras. With the connector's keywords.result cell unset each rule keeps its own action: a block rule withholds the result (the step gets the placeholder [tool result withheld: blocked by a gateway guardrail], audit outcome result_blocked), a scrub rule masks the term. withhold withholds on any match, flag only logs a match (a scrub rule still masks), allow skips the rules for this connector.
    • pii.result mask (the default): on a gateway with a PII masker the result is masked as described below. allow (Don't mask): the PII maskers skip the result, so the owner sees the real values in the run, never under the tenant's PII mandate (pii_masking_enforced: masked all the same).
    • Delivery and visibility. A result stored unmasked counts in the run's delivery disposition as an unmasked result of that connector, exactly as in chat: every Don't mask result counts (nothing scanned it, so it is never read as clean), under the connector's pii.delivery cell, so a Deliver step to an external address is held or blocked by that cell. The run's step outputs are then shown only to the workflow's owner (the run detail and the approval page, outputs_withheld); the tenant data export carries the stored run_state, as for an agent step's output. A masked result does not count: its placeholders are never put back, so it carries no personal data out. The disposition is recorded before the result reaches the run; if it cannot be recorded the step fails (connector_call_failed, audit outcome delivery_latch_failed) and the result is discarded — never stored without its delivery record. The connector is not called again.
    • The owner's identity is read before the connector is called; a fault reading it answers 500 (the runner ends the run as api_unreachable) and nothing is called.
    • A tool name that does not fit the place format (over 64 characters, or characters other than letters, digits, _ . : -) is recorded under the place tool_result:workflow_connector; the connector's cells apply all the same.
    • A connector the run's organisation cannot read is held to its strictest cells (keywords.result withhold).
    • Result is scrubbed + capped. The result is stringified, pre-capped to 20 KiB, then run through the strict persistence-leg PII fence (the same masker the form-file consume uses): on a PII-active gateway the result is masked with the gateway's own maskers (the ones it applies to chat). On this leg a masker error or timeout withholds, never forwards, whatever a detector's fail_open says; under a mandate with no pii_protector, or when the gateway's configuration cannot be loaded, the result is withheld too — each behind a safe placeholder (the cause table). On a gateway with a PII masker the raw result is persisted into run_state only under the connector's Don't mask (pii.result: allow, never under a PII mandate). An identifier the 20 KiB cut splits is masked with up to 256 bytes of the dropped text as context; if the PII engine is unavailable during that cut pass, the result is withheld as well (see PII Protector — Gateway cuts).
    • Identifiers after a line break are masked too. The result is stored as JSON text, where a newline, tab or carriage return inside a string is written \n, \t or \r. The PII masker reads the text as the model would see it, so an identifier directly behind such a break ("Konto\nIBAN DE89...", an e-mail after a tab, a phone number after a carriage return) is found and masked like any other. The stored result stays valid JSON with its structure and line breaks. A bare JSON number that is masked is stored as a quoted string holding the placeholder, so the result still decodes. If the masked result cannot be shown to be valid JSON, the whole result is withheld behind the safe placeholder, never stored raw. A plain-text result (not JSON) is masked as before.
    • No retry — ambiguity fails closed (D1). The connector node is not a retry node: it accepts no retry/on_error/error-edge (rejected at publish — bad_retry_config / bad_on_error / invalid_branch_slot) and may not sit inside a loop body (loop_body_side_effect). Because the MCP client collapses timeout / connection-reset / 5xx-after-send into one ambiguous upstream outcome with no pre-send-vs-post-send signal, a mutating call that ends ambiguous must not re-fire: every failure (definitive or ambiguous) is terminal (connector_call_failed). A crash mid-call leaves a delivering step row, which the node-agnostic resume reap fails closed as deliver_unknown_outcome (never a second call).
    • What the run shows for a refusal. The run fails with the gateway's code as its error_code, and the run error names it too: connector failed at <step>: connector_pii_blocked, connector failed at <step>: untrusted_egress_refused, and so on (the codes in the step error table above). The runner reads the code from a 403 or 422 answer. The body is untrusted: only a non-empty string error of at most 64 characters in a JSON object counts, and at most 64 KiB of the body is read. A malformed, over-long or truncated body gives connector failed at <step>: http_<status> instead. The step row itself keeps delivering and no error (D1, above), except for the provably pre-call approval refusals (untrusted_egress_refused, untrusted_egress_approval_lapsed), whose row turns failed with the code.
    • Audit. Every call attempt (every outcome) writes an audit_log row (action=workflow.connector) with the connector_id, tool, and outcome only — never the arguments or the result (both can carry the tenant's PII). Best-effort (an audit failure never fails the call, and is logged at error level). The per-call evidence is the access-decision record written before the call goes out; a non-interactive workflow caller whose allow decision cannot be recorded is denied (record_write_failed) and nothing is sent.
    • Model-written call: held for the owner. On a tainted run, a Connector call whose arguments a model wrote is held instead of sent. The gateway checks the lease, residency and structured-PII gates first (a call that could not be made anyway is never held), then opens one approval for the workflow owner and answers 202 {held, review_id, expires_at}. The run suspends with awaiting_tool_approval. The owner sees the connector, the tool and the exact arguments on the tool-approvals card (/me), with the workflow name and run. The approval is a single approval (no second approver, even if the connector is marked four-eyes) and is valid for 7 days.
    • Which arguments are not held. Arguments that are fixed by the workflow author run unattended: an input template with no refs (a literal), or one whose refs are all trigger refs and whose posted arguments match the template's shape exactly (same keys, same array/object kinds, trigger text only inside string values). A template that is a single whole-input ref is never fixed. A literal containing media that the Deliver-node neutraliser rewrites on a tainted run counts as changed and is held (fail safe).
    • Read tools. A call to a tool the connector classifies as read-only is not held.
    • Approve: the call is made at most once, with exactly the held connector, tool and arguments (compared in canonical form; any other call is refused). If the call fails after the approval was taken, the step fails terminally and is not retried; a crash between taking the approval and the call spends the approval.
    • Reject, expiry, or any other state: 403 untrusted_egress_refused; nothing is sent.
    • On a tainted run without an owner: refused (403 untrusted_egress_refused), never held, on every run kind. A run without an owner cannot start or resume (owner_unavailable); only an owner removed mid-run reaches this. A Connector node cannot be placed in a loop body (loop_body_side_effect), so there is no per-iteration Connector hold.
    • Coverage. Email-triggered (and unknown-trigger) runs and webhook and form runs are held. On a webhook or form run, a call on a run without an owner is refused, as on an email run. Schedule and manual runs are untainted.
    Status Code Meaning
    202 (held) {held, review_id, expires_at}: a hold is open; the run suspends until the owner decides
    403 untrusted_egress_refused rejected, expired, mismatching call or ownerless run; nothing is sent
    422 untrusted_egress_approval_used the approval was already used
    422 untrusted_egress_approval_lapsed approved but not executed within the window (7 days plus 5 minutes grace)
    422 untrusted_egress_refused the approved decision could not be recorded or was not allow; nothing is sent

Worked example — download, fill, and email a PDF form

The Fetch, Code, and Deliver nodes compose into the document-fill workflow the epic exists to enable: download a blank PDF form, fill it with the requester's data in the sandbox, and email the completed form as an attachment to an external recipient — behind a human approval. The builder exposes Fetch and Code in the node palette, so this is authored end to end in the UI, not only via the API.

The graph is trigger → fetch → code → approval → deliver:

  1. Fetch downloads the blank form (url, allowed_content_types: ["application/pdf"]) → {{f1.output.artifact}}.
  2. Code stages that artifact at /input/<name>, runs Python (pypdf) that fills the AcroForm text, checkbox, and radio fields from an embedded/parameterised profile, and writes /output/<output_filename> → {{fill.output.artifact}}. The fill sets both each field's value and every widget's /AS appearance state across all pages — a checkbox or radio widget can live on any page, and a stale /AS on a second widget silently defeats the fill.
  3. Approval suspends the run for a named approver to review before anything leaves the tenant.
  4. Deliver (kind: email) attaches the filled form via attachment_ref: "{{fill.output.artifact.handle}}" and sends it to an external to address — permitted only because the recipient's domain is on the tenant's workflow_recipient_allowlist (see External recipient). On a PII-masked run the external send is blocked fail-closed (recipient_pii_blocked).

A committed fixture of this workflow (a small AcroForm PDF, the fill program, and the graph) lives at tests/fixtures/vipwing/ and is driven end to end by case_vipwing_reservation in scripts/workflow_e2e.py (bash dev-instance.sh workflow-e2e).


JSON numbers — exact or refused

A number in untrusted JSON is either kept exactly or refused with a named error; it is never silently rounded. A number token is exact when it is an integer, or when it is a decimal of at most 17 significant digits that reads back as the same digits from the finite 64-bit double it parses to. 3.141592653589793, 0.1 and the non-shortest 0.10000000000000001 are exact; 1.00000000000000000001 (more than 17 digits), 1e400 (overflow) and 1e-400 (underflow) are not. A plain integer is judged by its spelling: 1e20 is accepted, but 100000000000000000000 is refused in a Connector input (double mode) because it lies beyond ±2^63, and 9007199254740993 because a double would hold 9007199254740992; 100000000000000000 is accepted.

  • Webhook payloads. The payload is stored as the original text. Integers reach {{trigger.output.*}} byte-exact, including integers of any length up to 4300 digits; a decimal resolves to the same value in its shortest form (0.10000000000000001 becomes 0.1). A payload with a number that is not exact is refused at the receiver with 400 and one of number_not_exact, number_invalid (NaN, Infinity, or a token that is not valid JSON) or number_too_long (an integer of more than 4300 digits). No run is created. If such a text still reaches a run, the run fails with trigger_input_number_not_exact, trigger_input_number_invalid, trigger_input_number_too_long or trigger_input_invalid (see Error codes).
  • Connector input. An integer in a Connector node's input must be held exactly by a 64-bit double and lie within ±2^63 (100000000000000000 passes, 9007199254740993 does not); other integers and decimals that are not exact are refused with 422 connector_input_number_not_exact, NaN / Infinity and invalid tokens with connector_input_number_invalid, and an argument set that cannot be encoded without changing a number with connector_args_unencodable. Nothing is sent upstream in any of these cases.
  • Connector results. A number in a connector result is stored exactly as the connector sent it; a result is never refused for its numbers. String escapes in the result are normalised to plain text (\u00fc becomes ü, \u0040 becomes @) so that masking and reading see the real text; numbers stay exactly as sent. A result with an invalid string escape or trailing bytes is refused as connector_call_failed. So is a result object that repeats a key ({"a":1,"a":2}): which value a reader would use is ambiguous, so the step fails with connector_call_failed (the same rule applies to MCP tool results on the agent path, see MCP tool results).
  • Agent JSON output. If an agent's JSON answer contains a number that is not exact, the whole answer is kept as text instead of being parsed. A {{node.field}} reference to a field of that answer then fails with the usual missing-field error.

Template resolution ({{ }}) — trust boundary (Invariant 11)

Data flows between steps via {{step_key.output.path}} references, inserted by the builder's picker (chips, not free-typed handlebars). Resolution is single-pass over graph-authored templates only: step outputs and trigger payloads are opaque data and are never re-scanned — a {{ }} sequence appearing inside a webhook payload or a model response is not expanded (closes the second-pass injection class). A missing or unfinished referenced step is a hard step error (template_unresolved), never a silent empty substitution; a cjson.null anywhere on the path is a documented hard fail (template_null_path). References into Condition/Loop branch members from outside the branch are impossible by construction — the publish-time ancestor rule (dangling_ref) rejects them, so no runtime "skipped reference" case exists. References to a step whose on_error is continue are likewise publish-blocked (ref_to_fallible_step); references to an error_branch step are legal from its after-chain (which only runs when the step succeeded) and publish-blocked from its own catch chain (ref_to_failed_source).


Internal runner seam (not public)

The loopback scheduler API (/internal/scheduler/*) shares the same strict-field validator; see Scheduled Tasks › Internal scheduler API.

The runner (scripts/workflow_runner.py) holds no DB credentials; it drives a loopback-only internal API (127.0.0.1:8083, location ~ ^/internal/workflow/), authenticated by the shared X-AIG-Scheduler-Secret. Endpoints: /reap, /due-runs, /claim, /load-run, /extend-lease, /save-step, /step-state, /step-cost, /finish-run, /suspend, /due-approvals, /apply-approval-timeout, /set-delivery, /release-run, /artifact, /artifact-get, /fetch, /code, /connector, /consume-file, /deliver-email, /deliver-clearance, /ingest-email (see Email triggers), /agent-run-start, /agent-run-finish, /agent-step-hold, /agent-run-claim-resume, /settle-tool-holds. Every runner-side mutation is lease-token fenced (claimed_by = token AND status = 'running'); a 409 { "error": "lease_lost" } tells the runner it was reaped and must abort with no further egress or overwrite. This surface is unreachable off-container and never called from a browser.

POST /internal/workflow/release-run {run_id, token, retry_at, tokens_used, cost_micros, pii_active?} hands a claimed run back to pending when its agent step found no gateway service token. The run is picked up again at retry_at. All fields are checked before any storage call: retry_at must be an integer from 1 to now + 3600 seconds (a past value means "due now"; else 400 bad_retry_at); tokens_used and cost_micros are required non-negative integers (400 bad_tokens_used / bad_cost_micros); pii_active follows the rule below (400 bad_pii_active). Success is 200 {"released": true}; a lost lease is 409 lease_lost; a storage fault is 500 db.

While the run's tenant is suspended, /deliver-email and /deliver-clearance answer 403 {"error": "tenant_suspended"} and send nothing; if the tenant's state cannot be read they answer 503 {"error": "tenant_state_unknown"}. The check follows the lease check and precedes workflows_disabled. The runner ends the delivery as failed_input on the 403 (including the Mattermost owner-mail fallback) and retries the 503. See Messages while suspended.

POST /internal/workflow/deliver-clearance {run_id, token} is the PII question for the webhook and Mattermost Deliver channels. It is lease-fenced like every other mutation route (409 lease_lost, 500 db, 403 workflows_disabled; 400 bad_run_id / bad_token for a missing or non-string field) and then answers from the run's own pii_active latch only: 403 {"error": "blocked_pii"} when the run is PII-active (the latch is read fail-closed: a NULL, absent or unparseable value counts as active), else 200 {"cleared": true}. It never reads the tenant's pii_internal_delivery_enabled opt-in, which only ever relaxes the owner's own email and never clears an external endpoint, and it sends no mail and takes no content. The optional channel (absent, null, or exactly webhook / mattermost / email; anything else 400 bad_channel) names the Deliver step's channel: when the organisation classed that channel internal (delivery channel class) a PII-active run is answered 200 {"cleared": true, "disposition", "reasons", "internal_channel": "<channel>"} (internal delivery is never limited). The runner sends its channel on every webhook / Mattermost clearance, and asks the same question before its own PII block for a webhook / Mattermost step and for an e-mail step with an explicit recipient; it accepts the answer only for the channel it is delivering to. An internal-classed e-mail send to an explicit recipient still needs the recipient allowlist and the tenant's internal-delivery opt-in at /deliver-email, and goes out without its attachment (as the owner's internal delivery of a masked run). The answer also carries the run's disposition and reasons. Optional body fields: step_key (the asking Deliver step: a step key of the run's published graph, never a loop row key#i; else 400 bad_step_key; a key that names no Deliver step is 400 bad_step_key once a release would apply) and to (an email step's resolved recipient; a valid address, only together with step_key, else 400 bad_recipient). ABSENT step_key = the answers above exactly. With a step_key the delivery release answers apply and the channel is taken from the run's published graph (the step's kind, url, channel_id), never from the runner (channel is then only compared); an internal-classed channel is answered internal_channel before any release is opened, while a step that already has a release keeps it. Content-free.

Although loopback-only and secret-authenticated, the runner is still treated as an untrusted-shape client (Invariant 11): every field is validated before any storage call. The optional pii_active field is validated by one rule on /save-step, /finish-run and /suspend (both shapes): absent or JSON null means "no latch" (0); an integer 0/1 (or an integral JSON number such as 1.0) is accepted; any other shape (true, "1", 2, -1, 1.5, an object or array) is rejected 400 { "error": "bad_pii_active" } with no storage call. The value is never trusted to lower the stored flag: storage latches it with GREATEST(pii_active, ?), so a 0 can only ever be a no-op. On /save-step, 1 is latched on the run row under the same lease fence, before the step row is inserted, and only after the fence and tenant checks pass; a failed or zero-row latch write fails the save (no step row).

With several invalid fields in one request, the first failing check (handler order) names the 400 code; pii_active is always checked before any run or hold lookup or storage call.

/save-step persists a workflow_step_run row, whose tenant_id scopes GDPR export (list_workflow_step_runs_for_export) and the erasure scrub. That tenant_id is DERIVED from the lease-fenced parent run, never from the body: the fence SELECT returns the run's tenant, and the INSERT stamps that value. A body tenant_id that is present and different from the run's tenant is a runner bug and is rejected 400 { "error": "tenant_mismatch" } with no write (fail-closed, loud); an absent or JSON-null tenant_id is treated as absent and derives silently; a run row whose own tenant is empty/NULL (schema-impossible corruption) is rejected 500 { "error": "db" } (run_tenant_missing), also with no write. Every field on the row-writing endpoints — /save-step, /set-delivery, /finish-run, /suspend — is validated column-true before the write: integers must be finite and inside the real column range (tokens [0, 2³¹); cost_micros/tokens_used/started_at/finished_at [0, 2⁵³) — a present-but-invalid value is 400, never a silent floor/zero; /suspend's approval_deadline is required on the awaiting_approval shape and is the same strict integral JSON number in [0, 2⁵³) — absent, null, a numeric string or a fraction is 400 bad_deadline, no storage call), identifier strings must be valid utf8mb4 within the column width (step_key/request_ref/ approval_step_key ≤ 64, node_type/status/delivery_status ≤ 16, suspended_reason ≤ 32, approver_id ≤ 36 codepoints, else 400), and free-text error/delivery_error are clamped to 16000 codepoints while error_code clamps to 48 (invalid utf8mb4 → 400 on all of them). On /save-step and /set-delivery an empty-string or JSON-null optional field is stored as SQL NULL, not ''. So no client shape can mint a 5xx from the write.

Timestamps and counters are strict. Every numeric field listed in the table below is a strict JSON integer: a numeric string ("100"), a fraction (1.5), a boolean, null, an object or array, NaN/Infinity or an out-of-range value is a named 400 with no storage call, and an absent required field is the same named 400 as an invalid one (on /claim: bad_now for now, bad_lease_until for lease_until) (optional fields such as the /save-step token counts or /finish-run tokens_used/cost_micros may be omitted). An integral JSON number such as 100.0 is accepted as 100. With several invalid fields the first failing check (handler order) names the code.

Route Field Accepted range Error code
/reap, /due-runs, /claim, /finish-run, /apply-approval-timeout, /due-approvals now [0, 2^53-1] bad_now
/due-runs limit [1, 1000] bad_limit
/due-runs gateway_id (optional) string, 1 to 64 characters of [A-Za-z0-9_-]; absent or null = all gateways bad_gateway_id
/claim, /extend-lease lease_until [0, 2^53-1] (on /claim also strictly greater than now) bad_lease_until
/step-cost cost_micros [0, 2^53-1] bad_cost
/step-cost tokens [0, 2^31-1] bad_tokens

Scoping /due-runs to one gateway. /due-runs takes an optional body field gateway_id. Absent or JSON null returns the due runs of every gateway (what the production timer sends). A present value must be a string of 1 to 64 characters from A-Z a-z 0-9 _ -; anything else (empty string, number, boolean, array, object, 65 characters, any other character) is 400 { "error": "bad_gateway_id" } with no storage call, so a malformed scope never widens to all gateways. The filter is applied before the limit. A well-formed id with no due runs is 200 with an empty list. The runner sets it with workflow_runner.py --gateway-id <id>; /reap, /due-approvals and /settle-tool-holds are not scoped.

/claim answers a bad or absent now with bad_now and a bad or absent lease_until with bad_lease_until; a negative now on /claim and /finish-run is 400 bad_now. A request body that repeats a key at any depth is refused with 400 duplicate_key, one with a non-finite number (NaN, Infinity, 1e400) or malformed JSON with 400 bad_json, and one with more than 2,097,152 structural elements with 413 body_too_complex; no storage call is made. A body the gateway cannot read back from its temporary spool is 500 body_unreadable (transient: the runner retries on its next tick). A /connector call whose input repeats a key is 422 connector_input_duplicate_key. The shipped runner sends integers everywhere.

Agent-step holds — /agent-run-start, /agent-run-finish, /agent-step-hold, /agent-run-claim-resume, /settle-tool-holds

These five routes let the runner drive an agent node whose agent run may be held for a tool approval. All but /settle-tool-holds are lease-fenced per run: the body carries run_id, token and step_key; a missing or non-string run_id/token is 400 bad_run_id/bad_token, a step_key that is not a valid step key is 400 bad_step_key, a storage error is 500 { "error": "db" } (no storage text is echoed) and a lost lease is 409 { "error": "lease_lost" }. The tenant and gateway always come from the loaded run, never from the body. Validation of the body shape happens before any write; a 400/409 never writes.

Route Body (beyond the fence fields) Success
/agent-run-start lease_secs integer 60..3600 (else 400 bad_lease_secs) 200 { agent_run_id }
/agent-run-finish ok boolean, http_status integer 0..999, optional request_ref (<= 64), error (<= 500), optional agent_version integer 0..2147483647, optional guardrail_block object (see below) 200 { applied, status }
/agent-step-hold none (pure read) 200 { hold: { agent_run_id, status, review_status, workflow_seq } } or { "hold": null }
/agent-run-claim-resume lease_secs integer 60..3600 200 { won, agent_run_id, review_status, workflow_seq }
/settle-tool-holds now integer 0..2^53-1 (no fence) 200 { released, orphaned }

Step-level refusals: /agent-run-start answers 422 step_not_agent when the step is not an agent node (or is a loop-body member), 422 agent_not_found when its agent slug is unknown in the run's gateway, and 422 step_hold_live when the step already has a running or suspended agent run. A running agent-run row left behind (for example after a runner crash) keeps blocking a new start with 422 step_hold_live until the scheduler's lease reaper fails it, lease_secs after the start. /agent-run-finish answers 404 no_agent_run (no run for this step) or 404 agent_run_gone. /agent-run-claim-resume answers 422 not_resumable unless the hold is suspended with a decided review (approved or denied). The run's own claim (/load-run), also taken when a run resumes after a hold, carries the tenant_suspended refusal; /agent-run-claim-resume itself is not fenced by the tenant suspension. A corrupt stored graph is 500 db.

Guardrail blocks (guardrail_block). When the gateway refused the step's invoke with a guardrail block (see Agents — guardrail-block marker), the runner sends guardrail_block on /agent-run-finish with ok: false; the agent run ends failed with error_class = guardrail_blocked and the optional blocked_by / block_reason. Accepted: absent or JSON null (no block), or a JSON object holding only blocked_by and/or block_reason (each optional; a block whose marker was malformed sends {}), each a valid UTF-8 string of at most 128 codepoints with no control character. Rejected with 400 bad_guardrail_block and no write: a non-object (string, number, array), an unknown key, a wrong-typed / over-long / control-character field, and any guardrail_block together with ok: true. /save-step takes the same facts for the step row: optional error_class (only guardrail_blocked is accepted, on a failed or a skipped row), and blocked_by / block_reason under the same string rule, accepted only together with error_class; anything else is 400 bad_block_fields. A blocked step fails the run guardrail_blocked: every step that has not run is written skipped with error_class = guardrail_blocked (a loop whose body step was blocked is written failed, without a class), nothing later runs, and the run detail returns error_class, blocked_by and block_reason on each step.

Tool-hold /suspend. /suspend additionally accepts the body field reason: "awaiting_tool_approval": the workflow run is parked behind a pending tool-approval review, not a person's approval step. In that shape the approver keys (approver_kind, approver_id, approval_deadline, timeout_policy) must be absent or JSON null, approval_step_key (a valid step key) is required, and the step's latest agent run must be a live hold (suspended) or a hold whose agent run failed with its review expired (review_status = expired), which /settle-tool-holds releases on its next tick A delivery release of the step (approval_step_key = the Deliver step) that the step has not claimed yet parks the run the same way — also one decided between the clearance and the suspend, which /settle-tool-holds re-serves at once so the step reads the decision; a claimed (closed) release parks nothing. When such a run ends while it waits (cancelled - also by a trigger change or the erasure of the user who started it while the decided run waits for a runner -, rejected, timed out), the held Deliver row is set to failed with the reason in error and its waiting_release marker cleared. (else 422 no_tool_hold; a malformed step key is 400 bad_approval_step_key). The pii_active rule above applies to this shape too and is checked before any run or hold lookup: a malformed value is 400 bad_pii_active. Such a run never appears in the Approvals inbox, cannot be approved or rejected through the workflow approval endpoints, and is never selected by the approval-timeout sweep; /settle-tool-holds releases it back to pending once its agent run's review is decided. awaiting_approval keeps its existing shape; any other reason is 400 bad_reason.

What the runner does with a held step. An Agent step on the top level, in a Condition branch or in an error-branch catch chain runs attached to an agent run, so a tool call that needs approval (a gated tool, an unattended write or destructive connector call held for the credential holder, or an outside_task call under on_outside_task: "approval") can be held:

  • The run is suspended (status: suspended, suspended_reason: awaiting_tool_approval) and no step row is written for the held step. Nothing from the held answer enters run_state.
  • When the owner decides the review, the next runner tick re-claims the run and resumes the step: an approved call runs exactly once, a rejected call is denied and never runs. The held step is not invoked a second time on any other path.
  • Retries are per attempt: each attempt (and each half of a retried step) is its own agent run, and a hold does not consume a retry.
  • A Loop body step is not run-attached, so a call there that needs an outside_task approval is refused as under on_outside_task: "block".

The run error codes for held steps (agent_tool_rejected, agent_approval_expired, agent_step_unknown_outcome) are listed in the Error codes table above; agent_step_unknown_outcome also covers a resume claim whose decision is missing, malformed or disagrees with the hold read.

An agent-run-start refusal (422 step_not_agent or 422 agent_not_found) fails the step like any other agent failure and follows its on_error policy.

/artifact and /artifact-get — binary artifact store

A workflow node produces a binary artifact (e.g. a fetched or filled document) that a later node consumes by handle, without ever putting bytes in run_state (JSON, 256 KB cap). Bytes live in exactly one row (workflow_artifact.data, LONGBLOB, FK → workflow_run ON DELETE CASCADE); run_state holds only a reference {"artifact": {"handle", "filename", "mime_type", "size_bytes", "sha256"}}. Both endpoints are lease-token fenced like every other runner mutation.

POST /artifact — {run_id, token, step_key, filename, mime_type, data_b64} → {handle, size_bytes, sha256}. Accepted/rejected shape (Invariant 11):

  • data_b64 is read raw and type()-checked, then base64-decoded, with the emptiness check on the decoded bytes (not the raw string, because a base64 decode of a padding-only string like "====" yields "", not nil): a non-string field → 400 missing_artifact_data; a decode == nil → 400 bad_artifact_b64; a decoded length of 0 (covering "", "=", "==", "====") → 400 empty_artifact. No 0-byte or wrong-size row is ever stored; size_bytes is the decoded length.
  • filename is basename-stripped (path separators removed) then re-checked empty ("../", "/", ".", ".." → 400), and filename/mime_type/step_key are utf8mb4-validated within their column widths (else 400, never a store-time 5xx). Note for the consuming node: basename does NOT strip NUL/control bytes — the artifact is stored opaque here, so the node that stages it at /input/<name> MUST sanitise NUL/control at that boundary before it reaches a C-based path handler.
  • tenant_id is DERIVED from the lease-fenced parent run, never from the body. The fence is an INSERT … SELECT … FROM workflow_run WHERE id = ? AND claimed_by = ? AND status = 'running'; rowcount 0 (reaped lease, or unknown run — no existence oracle) → 409 lease_lost with no write.
  • Per-artifact and per-run aggregate size caps are enforced before the insert (413 artifact_too_large / artifact_run_total_too_large); a MySQL max-packet refusal is mapped to the same 413, never a 500.

POST /artifact-get — {run_id, token, handle} → {filename, mime_type, size_bytes, sha256, data_b64}. Lease-fenced (lost → 409); the row lookup is scoped WHERE id = ? AND run_id = ?, so a handle belonging to another run/tenant → 404 not_found (a valid-lease holder cannot distinguish foreign-exists from not-exists). content_sha256 is recomputed over the stored bytes and compared on read — a mismatch fails closed (sha_mismatch, row withheld).

/fetch — SSRF-pinned server-side download

POST /fetch — {run_id, token, step_key, url, allowed_content_types?, max_bytes?, filename?} → {handle, size_bytes, sha256, content_type, filename}. The Fetch node's server-side worker (see the Fetch node section above for the full contract). Order, all fail-closed: validate shape (allowed_content_types an explicit array-of-strings — a malformed value → 400 bad_allowed_types, never allow-all; max_bytes clamped to the artifact cap; filename basename-sanitised, malformed → 400 bad_filename) → lease-fence the run FIRST (load_workflow_run; lost → 409, no egress) → fetch_bytes (SSRF-pinned) → audit the egress attempt (authority-only, no path/query) → empty-body → 422 → magic content sniff (415 on reject / not-allowed) → store via create_workflow_artifact (409 lost lease, 413 cap). Status map: SSRF 400; network/timeout/ redirect/upstream-5xx/429 502 (retryable); upstream other-4xx & empty 422; oversize 413. The runner's HttpWorkflowDb.fetch treats a 502 as retryable, a 500 as a loopback failure (TransportError, never a step outcome that on_error could absorb) and every other non-2xx as a terminal FetchError; a 409 is a lost lease (abort). For a 400, 403, 413, 415, 422 or 502 the runner reads the answer's error code (at most 64 KiB of body; a body that stalls past the fetch timeout is dropped), so the step error names it: fetch failed: url_pii_blocked, fetch failed: fetch_too_large, and so on (the codes in the step error table above). The body is untrusted: only a non-empty string error of at most 64 characters in a JSON object counts. A malformed, over-long, truncated or stalled body gives fetch failed: http_<status> instead, and the same status keeps the same retry rule.

/code — headless sandbox run

POST /code — {run_id, token, step_key, code, input_refs?, output_filename?, context?} → {handle, size_bytes, sha256, mime_type, filename}. The Code node's server-side worker (see the Code node section above for the full contract). context is an internal loopback field (not a persisted contract): the runner always sends the run's consumed trigger output (state[trigger_key]) as a nested JSON object — code is passed verbatim (never template-resolved). Order, all fail-closed: validate shape (code a non-empty string, else 400 bad_code; at most 64 KiB, else 400 code_too_long; input_refs an explicit array-of-strings capped at 7 — #input_refs + 1 > 8 reserves the /input/_context.json slot → 400 bad_input_refs; output_filename basename-sanitised) → lease-fence the run FIRST (load_workflow_run; lost → 409) → enablement gate (is_configured() + resolve_gateway_config_by_id + config_code_interpreter_enabled; disabled → 501 code_disabled, no sandbox call) → load each input_ref (get_workflow_artifact, run-scoped; unknown → 404 input_not_found) + reject the reserved name _context.json (422 code_reserved_input) + reject duplicate /input names (422 code_duplicate_input) → stage /input/_context.json from context (object-or-empty guard: a non-object / JSON array / un-encodable value → the literal {}, fail-closed) → run_code (ctx-free broker; artifact_max_bytes = the store cap) → classify by return shape: (nil,err,outcome≠nil) broker failure → 502 code_unavailable (retryable), (nil,err,nil-outcome) pre-flight → terminal 413 code_too_large / 422 code_bad_input, a RunResult with timed_out → 422 code_timeout / exit_code≠0|nil → 422 code_failed (exit_code only, no stderr) → select the output by art.name (bytes by kind) → store via create_workflow_artifact (409 lost lease, 413 code_output_too_large) → audit (metadata only). The runner's HttpWorkflowDb.code maps only 500 → TransportError (transient tick-retry); everything else — including 501 code_disabled — is a terminal CodeError (so on_error/error_branch can absorb it); 502 is node-retryable; 409 is a lost lease (abort).