# Flows

A **flow** automates work across ConnectCloud: a graph of nodes started by a **trigger**. Triggers are module events
(a desk item was created), schedules (cron), manual starts and inbound webhooks; nodes call module actions, branch
(`if`, `switch`), set values, wait, ask people (`human_task`), run in parallel or in loops, call sub-flows, send mail
and use AI. A flow is stored as **YAML** – the portal's graphical builder edits the same document – so you can keep
flows in your own repository and deploy them through the API.

All routes live under `/api/flows/v1` ([reference](/reference/flows)).

## Permissions and ownership

| Permission | Grants |
|---|---|
| `tenant:flows:read` | see tenant flows, their versions, triggers and runs; the catalogue and validation |
| `tenant:flows:write` | create, edit, test, publish and start **your own personal** flows |
| `tenant:flows:admin` | everything for **tenant** flows; live test runs; see the metadata and YAML of everyone's personal flows |
| `tenant:flows:tasks` | the task inbox: approvals and forms flows assign to you |

- A **personal** flow (`owner: personal`) belongs to the person who created it and acts with **their** permissions.
  Only they edit, publish, start and cancel it; its runs are theirs alone (others, admins included, get `404`).
  Service-account keys own no personal flows: creating one answers `403 person_required`. Use a personal API key.
- A **tenant** flow (`owner: tenant`, `serviceAccountId` required) needs `tenant:flows:admin` and acts as the
  service account it names. A service-account key with `tenant:flows:admin` can manage tenant flows.
- A **scoped** flow belongs to a desk space or a forge project: create it with `owner: tenant`, a
  `serviceAccountId` and `scope` (`desk:space:<id>` or `forge:project:<id>`, the id as a lower-case UUID). It acts as
  its service account like every tenant flow, but who sees and manages it is decided by the module that owns the scope,
  live at every request – not by `tenant:flows:admin`: people who see the space or project (and hold a flows
  permission) read the flow and its runs; whoever the module lets manage it (a desk space: desk admins and the
  space's maintainers; a forge project: forge admins and the project's maintainers and admins while the project is
  active) creates, changes, publishes, starts and cancels it with `tenant:flows:write` or `tenant:flows:admin` –
  `tenant:flows:admin` alone is not enough. A live test run still needs `tenant:flows:admin`. Anyone else gets
  `404`; someone who sees but may not manage it `403`. When the owning module cannot answer, the routes of a scoped flow answer
  `503 scope_unavailable` (retry later). Scoped flows are listed with
  [`GET /flows?scope=…`](/reference/flows/listFlows), never in the plain list; their runs with `flowId`. They are
  hidden from service-account keys (no person the module could look up).
- Whoever may change a flow may also start and cancel its runs.

## The definition

```yaml
schemaVersion: 1
key: monitoring-incident        # lower case, digits, dashes; fixed after creation
name: Monitoring alert as incident
triggers:
  - { id: alarm, kind: webhook, auth: hmac, filter: "trigger.data.status == 'down'" }
nodes:
  incident:
    kind: action
    action: desk.item.create
    params:
      spaceId: SUP
      title: "Monitoring: {{ trigger.data.host }} unreachable"
      dedupeKey: "monitoring:{{ trigger.data.host }}"
edges:
  - alarm -> incident
```

- `triggers` (`event` | `schedule` | `manual` | `webhook`), `nodes` (id → node) and `edges` (`from -> to`, or
  `from.port -> to` for a node with several exits, e.g. `check.true -> notify`) form the graph; optional are
  `description`, `inputs` (a JSON schema of the start data of manual starts and sub-flows), `settings`, `vars` and
  `layout` (positions of the graphical builder, ignored when the flow runs).
- Parsing is strict: unknown and duplicate keys are errors with line and column.
- Fields such as `condition`, `filter` or `items` are expressions; every other string is a template, plain text unless
  it contains `{{ … }}`. Expressions read the namespaces `trigger`, `nodes` (outputs of upstream nodes),
  `vars`, `run`, `error`, and in loops `item` and `loop`. A failing expression fails the node – never a silent `false`.
- **What you can use** – every module's actions (`action: <module>.<noun>.<verb>`) with their parameter and answer
  schemas, the events with their payload schemas, the node kinds with their ports, the namespaces and the functions
  of the expression language – comes from the catalogue
  [`GET /catalog`](/reference/flows/getFlowsCatalog). It lists what the platform offers; whether a flow may use an
  action is decided by its owner's permissions when you publish.

## From draft to live

1. **Create** – [`POST /flows`](/reference/flows/createFlow) with `name`, `owner` (`personal` or `tenant`) and
   optionally `key` and a first `yaml`, or the `template` key of a ready-made flow from
   [`GET /templates`](/reference/flows/listFlowTemplates) (not together with `yaml`; `available: false` means a module
   the template uses is not offered, so its draft would have errors); without either the draft is a skeleton with a
   manual trigger. A template lists its `params` – recipients, a priority, a time – with type, label and default:
   send their values as `params` (a parameter left out takes its default; a wrong value is `400 invalid` with the
   field `params.<key>`). [`POST /templates/{key}/render`](/reference/flows/renderFlowTemplate) returns the
   definition a template gives for your values without creating anything. Templates with a `scope` are made for a
   desk space or forge project and need a `scope` of that kind; templates with `profile: inline` are immediate
   automations of their module and are created there, not as flows. The answer is the flow and the validation of
   its draft.
2. **Save the draft** – [`PUT /flows/{id}/draft`](/reference/flows/saveFlowDraft) with `yaml` and the draft's
   `version` from [`GET /flows/{id}/draft`](/reference/flows/getFlowDraft) (`409 version_conflict` when someone saved
   in between). Invalid drafts are saved too; the answer lists their `diagnostics`.
3. **Validate** – [`POST /validate`](/reference/flows/validateFlowDefinition) checks any YAML without storing it.
   Each diagnostic has a `severity` (errors block publishing, warnings never), a stable `code`, a dotted `path`
   (`nodes.incident.params.title`) and `line`/`col`. `permissions` lists the any-of permission groups the flow needs.
4. **Test** – [`POST /flows/{id}/test-runs`](/reference/flows/testFlowDraft) runs the current draft without
   publishing or enabling it (`trigger` picks the trigger to act as, `input` is its `trigger.data`, e.g. a sample
   webhook body). Like a publish, it needs a valid draft (`422 invalid_definition`) and the owner's permissions
   (`422 permission_missing`).
   Tests are **dry** by default: write actions are not sent (their output is a sample of the answer, their input says
   `dryRun`), mail is resolved but not sent and human tasks ask only you; reads and AI nodes run for real. Dry tests
   are not billed. `live: true` acts like a real run and needs `tenant:flows:admin` (`403 live_test_forbidden`).
   The answer is `202 {runId}`; follow it like any run.
5. **Publish** – [`POST /flows/{id}/publish`](/reference/flows/publishFlow) with the draft `version` you reviewed and
   an optional `note`. The draft must be valid (`422 invalid_definition`, `details.diagnostics`) and differ from the
   live version (`409 no_changes`). HR then checks that the owner holds a permission of every group the flow needs
   (`422 permission_missing`, `details.groups`); for a tenant flow you must hold every permission of its service
   account (`403 forbidden_grant`). The confirmed permissions are stored with the version and are exactly what its
   runs act with. Publishing enables the flow and arms its triggers.

Versions are immutable: [`GET /flows/{id}/versions`](/reference/flows/listFlowVersions), one with its YAML
[`GET /flows/{id}/versions/{number}`](/reference/flows/getFlowVersion), and
[`POST …/versions/{number}/restore`](/reference/flows/restoreFlowVersion) copies one back into the draft.
[`PATCH /flows/{id}`](/reference/flows/updateFlow) enables or disables a flow (with the flow's `version`);
[`DELETE /flows/{id}?version=…`](/reference/flows/archiveFlow) archives it. A flow can stop by itself –
`pausedReason` says why (`owner_inactive`, `permission_lost`, `tripped`); enable it again once the cause is fixed.

### Generate a draft from a description

[`POST /flows/generate`](/reference/flows/generateFlow) with a `description` in your own words (at most 4000
characters) and an optional `name` lets the AI write the YAML, using only actions and events you hold a permission
of, and corrects it with the validator (at most three attempts). It creates a new **personal** flow with that draft –
also when it is still invalid, so check `validation` – and never publishes it. 6 calls per minute; `503
ai_unavailable` / `ai_failed` when the AI is not available. Service-account keys get `403 person_required`.

## Mail

A `mail` node sends a message with its own `subject` (at most 200 characters) and `text` (at most 4000) through
comms. There are no message templates to reference: the text is part of the flow.

```yaml
nodes:
  info:
    kind: mail
    to: ["manager:{{ trigger.data.employeeId }}", "group:5b0d6c0e-2f0a-4d0b-9b1c-0e8f6a7d3c21", "channel:9a1f4c2e-6b7d-4e8f-a0b1-c2d3e4f5a6b7"]
    subject: "Absence requested: {{ trigger.data.employeeName ?? '' }}"
    text: "{{ trigger.data.startDate }} – {{ trigger.data.endDate }}"
```

| Entry in `to` | Reaches |
|---|---|
| `person:<e-mail>` or a bare address | that address |
| `employee:<id>` | an employee by HR id |
| `group:<id>`, `role:<id>` | the members of a group, the holders of a role – as they are when the node runs |
| `manager:<e-mail or employee id>` | the direct manager of that person |
| `channel:<id>` | a comms channel (Microsoft Teams or webhook): one message per channel, see [Webhooks](/guides/webhooks) |
| `{{ … }}` | whatever the expression yields: one of the above or a list of them |

- **Who:** groups, roles, employees and managers are resolved in HR for the flow's tenant only; an id that names
  nobody (someone who left, an empty group) is listed in the node's output `missing`, the others get the mail. In a
  **tenant flow** – with or without scope – an address that is no active employee's is mailed anyway and listed in
  `external` (at most 20 per node). In a **personal flow** nothing leaves the company: such an address is `missing`.
- **How many:** at most 50 entries in `to`, as written and after the expressions are rendered (a group or role counts
  once); the people they resolve to are sent in messages of 50, and more than 500 people fail the node. Errors:
  `too_many_recipients`, `no_recipient` (nobody is left), `invalid_recipient` (an entry that is no reference).
- **Output:** `recipients` (people mailed), `to` (employees), `external`, `channels`, `missing`.
- **`mandatory: true`** (people cannot switch the message off, digest it or pause it during an absence) and
  **`mailChannel: <id>`** (the comms e-mail channel to send through instead of the tenant's default) are reserved for
  **tenant flows without scope**, managed with `tenant:flows:admin`. A personal or scoped flow that sets one gets the
  diagnostic `mail_option_not_allowed` on its draft and cannot be published or test-run (`422 invalid_definition`).
  Without `mandatory` the recipients' personal notification settings apply.
- A `human_task`'s `assignTo` takes the same references except `channel:`; assignees are employees in every flow (an
  address that is no active employee's is `missing`).
- In a dry test run mail is resolved but not sent.

## Immediate automations in desk and forge

Desk and forge run automations written in **the same YAML** inside the change that triggers them – the answer of the
request already shows the ticket or item as its automations left it. They are stored by the module, not by flows:

| | Desk | Forge |
|---|---|---|
| Routes | [`/api/desk/v1/automations?scope=…`](/reference/desk/listDeskAutomations) | [`/api/forge/v1/projects/{key}/automations`](/reference/forge/listForgeAutomations) |
| Scope | `tenant` (every space) or `space:<space id>` | the project |
| Read | everyone with desk access; a space's: whoever sees the space | `tenant:forge:read` and a project the caller sees |
| Change | `tenant`: `desk:admin`; a space: `desk:admin` or a maintainer of the space | `tenant:forge:admin`, or `tenant:forge:write` and project role maintainer or admin |
| Triggers | desk's events and `manual` (the ticket's actions) | forge's events |

Both modules serve the same set of operations (the links are desk's; forge has the same with `Forge` in the name):
list ([`listDeskAutomations`](/reference/desk/listDeskAutomations), each with its newest execution `lastRun`), create
([`createDeskAutomation`](/reference/desk/createDeskAutomation): `{name}` for a skeleton or `{yaml, enabled,
blocking}`), read, change ([`patchDeskAutomation`](/reference/desk/patchDeskAutomation) with `version`), delete
(`?version=`), [`reorderDeskAutomations`](/reference/desk/reorderDeskAutomations) (`ids`: the order they run in),
the catalogue of what a definition may use ([`getDeskAutomationCatalog`](/reference/desk/getDeskAutomationCatalog)),
a check without storing ([`validateDeskAutomation`](/reference/desk/validateDeskAutomation)) and the last 50
executions ([`listDeskAutomationRuns`](/reference/desk/listDeskAutomationRuns)).

- **What a definition may use:** triggers `event` (the module's own events; `trigger.data` is the event's payload)
  and, in desk, `manual`; the nodes `if`, `switch`, `set`, `end`, `mail` and the module's actions marked for immediate
  use in the catalogue – at most 25 nodes. Everything else (`wait`, `human_task`, loops, `parallel`, `ai`, schedules,
  webhooks, other modules' actions and events, `group:`/`role:`/`manager:`/`employee:` recipients, `mandatory`,
  `mailChannel`) is the diagnostic `needs_durable`: create it as a flow scoped to the space or project instead
  (`POST /flows` with `scope`). An automation has no versions and no publish step: what is stored and `enabled` runs;
  a definition with errors is stored with `valid: false` and cannot be enabled (`422 invalid_definition`).
- **Scope rule:** an automation acts only inside its scope – a forge automation on items of its own project, a desk
  space's automation on tickets of that space; anything else fails the action with `out_of_scope`. Desk's `tenant`
  automations act on every ticket and run before the space's.
- **Failure:** a failing automation is rolled back as a whole and logged (`…/{id}/runs`: outcome, failing node,
  error code); the triggering change is kept. With `blocking: true` the change is refused instead with
  `422 automation_blocked` (`details.automation`, `details.reason`) – only for requests on the API; changes that
  arrive by mail, feeds, timers, the customer portal or from GitHub are never refused.
- **Loops:** a trigger ignores changes made by automations (flows included) unless it says `includeAutomated: true`;
  then automations start each other at most 4 levels deep, each once per ticket or item per change, at most 20 per
  event.
- **By hand (desk):** [`listItemActions`](/reference/desk/listItemActions) lists the enabled automations with a
  `manual` trigger that fit a ticket (the trigger's `filter` decides), and
  [`runItemAction`](/reference/desk/runItemAction) starts one (`422 not_applicable`; `422 automation_failed` when it
  failed – then nothing was changed). Forge starts no automation by hand.
- **Ready-made automations** are flow templates with `profile: inline`: render one with
  [`POST /templates/{key}/render`](/reference/flows/renderFlowTemplate) and post the returned `yaml` to the module's
  create route.
- **Ticket `version`:** an automation or flow may update a desk ticket or change its status without `version`
  (it then acts on the ticket as it is); everyone else must send it – see
  [Idempotency and concurrency](/guides/idempotency-and-concurrency).

Desk also evaluates expressions of the same language in two settings: the `match` of an SLA policy (over the
ticket's event payload) and the `condition` of a mail source's route (over the mail's `from`, `fromDomain`, `to`,
`subject`, `body`, `hasAttachments`, `mailbox`); [`getConditionCatalog`](/reference/desk/getConditionCatalog) lists
the fields. An SLA policy's escalation levels carry no actions: reaching one writes the event `desk.sla.escalated`,
which automations and flows react to.

## Start by hand

A flow with a `manual` trigger is started with [`POST /flows/{id}/runs`](/reference/flows/startFlowRun):

```bash
curl -X POST 'https://api.mbcom.cloud/api/flows/v1/flows/7d0c…/runs' \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -H 'Content-Type: application/json' \
  -H 'Idempotency-Key: 6c1f0a52-0d0e-4a43-9c55-8f6e1f2a0b7d' \
  --data '{"input": {"title": "Two monitors", "amount": 640}}'
```

`input` becomes `trigger.data`; `trigger` picks a manual trigger (default: the first). The answer is `202 {runId,
created}`. Repeating a start with the same `Idempotency-Key` answers the run it started first with `created: false` –
send one on every start you might retry. The flow must be published (`422 not_published`) and enabled
(`409 flow_disabled`); a trigger that is not manual answers `422 no_manual_trigger`.

## Runs

- [`GET /runs`](/reference/flows/listFlowRuns) lists runs newest first (`flowId`, `status` running | succeeded |
  failed | cancelled; keyset paging with `limit` and `cursor`, see [Pagination](/guides/pagination)). Test runs carry
  `testMode` (`dry` or `live`).
- [`GET /runs/{id}`](/reference/flows/getFlowRun) is the run with the YAML of the version it ran and its node history:
  per node its input, output, port, attempts and error (`status skipped` when no path reached it).
- [`POST /runs/{id}/cancel`](/reference/flows/cancelFlowRun) cancels a running run (`409 run_finished` when it has
  ended); a node that is calling a module finishes its call, nothing follows it.

A run is pinned to the version it started on; publishing again does not change running runs.

## Webhooks

A `webhook` trigger gives the flow its own address that external systems call **without any ConnectCloud token**:

```yaml
triggers:
  - { id: alarm, kind: webhook, auth: hmac }   # auth: token (default) or hmac
```

- **Credentials:** the publish that arms the trigger answers its `path` (`/api/flows/v1/hooks/{token}`), the `token`
  and, for `auth: hmac`, a signing `secret` in `webhooks`. They are shown **only once** – store them in your secret
  store. [`GET /flows/{id}/triggers`](/reference/flows/listFlowTriggers) never shows them again. The token is kept
  across later versions.
- **Call:** [`POST /api/flows/v1/hooks/{token}`](/reference/flows/receiveFlowWebhook) with a JSON body
  (`Content-Type: application/json`, at most 1 MiB); the body becomes `trigger.data`. The answer is
  `202 {runId, created}`; `runId` is `null` when the trigger's `filter` was false.
- **Signature (`auth: hmac`):** send `X-Flows-Signature: sha256=<hex>`, the lower-case hex HMAC-SHA256 of the exact
  raw body, keyed with the secret as you received it (its characters as bytes – do not hex-decode it). A missing or
  wrong signature answers `401 invalid_signature`.

  ```bash
  BODY='{"host":"db-01","status":"down"}'
  SIG=$(printf '%s' "$BODY" | openssl dgst -sha256 -hmac "$FLOWS_WEBHOOK_SECRET" -hex | sed 's/^.*= //')
  curl -X POST "https://api.mbcom.cloud/api/flows/v1/hooks/$FLOWS_WEBHOOK_TOKEN" \
    -H 'Content-Type: application/json' \
    -H "X-Flows-Signature: sha256=$SIG" \
    -H 'Idempotency-Key: alert-8812' \
    --data "$BODY"
  ```

- **Retries:** with an `Idempotency-Key` header a repeated call answers the same run (`created: false`).
- **Rotate:** [`POST /flows/{id}/triggers/{trigger}/rotate`](/reference/flows/rotateFlowWebhook) issues a new token
  (and secret); the old ones stop at once.
- **Limits:** calls are rate-limited per client IP (`429`). A flow started more than 60 times in a minute by events
  or webhooks pauses (`409 flow_tripped`, `pausedReason: tripped`) until someone enables it again. An unknown token,
  or a flow that is archived or not published, answers `404`; a disabled flow `409 flow_disabled`.

The token in the path is the credential: treat it like an API key and rotate it when it may have leaked.

## Tasks

`human_task` nodes ask people for an approval or a form and wait. The inbox needs `tenant:flows:tasks` and a
**person**: sign-in sessions and personal API keys work, service-account keys get `403 person_required`, and a flow
can never answer a task.

- [`GET /tasks`](/reference/flows/listFlowTasks) (`status` open | done, keyset paging) and
  [`GET /tasks/count`](/reference/flows/countFlowTasks) list your tasks; [`GET /tasks/{id}`](/reference/flows/getFlowTask)
  shows one (`canAnswer` when you are an assignee of the open task).
- [`POST /tasks/{id}/answer`](/reference/flows/answerFlowTask): an approval needs `outcome` `approved` or `rejected`, a
  form its required `values` (checked against the form, `400 invalid` with `field` `values.<key>`); `comment` is
  optional. The run continues on the outcome's port. Someone who is no assignee gets `404`, a task that is answered,
  timed out or cancelled `409 task_closed`.
