# Flows kit (TypeScript)

Reference for @omazyai/sdk/flows. Workflows whose steps are capabilities through the guard, ai tasks or actors, with every step in a ledger, and automations that start them on an event, a schedule or a condition. Runs on Cloudflare Workflows.

Source: https://docs.omazy.ai/build-on-omazy/kits/flows/

:::caution[Preview]
The kit is a preview in `@omazyai/sdk` 0.5.3. Its interface may change before 1.0, so pin the exact version. It is TypeScript only.
:::

```ts
import { automation, createAutomations, createFlows, flowEntrypoint, on, step, workflow } from '@omazyai/sdk/flows'
```

A workflow is a list of steps. Each step reads or changes something through a
[capability](/build-on-omazy/kits/capabilities/), runs an [AI](/build-on-omazy/kits/ai/) task, or
hands a conversation to an [actor](/build-on-omazy/kits/actors/). An automation starts a workflow
when something happens.

**The rules:**

- Every capability call goes through the [guard](/build-on-omazy/kits/guard/), and every step is
  in the ai kit's effects ledger: one ledger per run.
- A write is never retried. A failed write goes to a person, and the run waits for them.
- An R2 write runs only with `confirm: 'upstream'` on its step. Without it, it goes to a person.
- An R3 write creates its approval and the run waits until a person decides it.
- One run per key, such as `fulfil:<payment id>`.
- Dry run calls reads, and `guard.preview` for writes, and reports what it would have done.

The kit runs on Cloudflare Workflows. A memory runner that replays runs the way Workflows does is
there for tests. A Node runner comes later.

## Define a workflow

Joya's payment fulfilment (RFC-0901 W29): after a manual bank payment for billing is approved,
check it, find what was bought, apply the level, extend the term, open go-live and tell the owner.

```ts
export const paymentFulfil = workflow({
  id: 'payment_fulfil', version: 1,
  steps: [
    step.read('check', 'payment_get', {
      args: (s) => ({ payment_id: s.input.payment_id }),
      stop: (p) => (p.status !== 'paid' ? `payment ${p.id} is ${p.status}, not paid` : null),
    }),
    step.read('tenant', 'tenant_get', { args: (s) => ({ tenant_id: s.check.tenant_id }) }),
    step.read('order', 'billing_order_get', { args: (s) => ({ payment_id: s.input.payment_id }) }),
    step.write('invoice', 'invoice_mark_paid', {
      skipIf: 'not_built',
      todo: (s) => `Mark ${s.check.invoice_ref} paid in Business Brain.`,
    }),
    step.write('level', 'tenant_level_set', {
      when: (s) => s.order.level !== s.tenant.level,
      args: (s) => ({ tenant_id: s.tenant.id, level: s.order.level }),
    }),
    step.read('checks', 'go_live_checks', { args: (s) => ({ tenant_id: s.tenant.id }) }),
    step.write('go_live', 'tenant_go_live_approve', {
      when: (s) => s.checks.ready,
      args: (s) => ({ tenant_id: s.tenant.id, order_ref: s.check.invoice_ref }),
    }),
    step.notify('tell', 'payment_fulfilled', { data: (s) => ({ payment: s.input.payment_id }) }),
  ],
})
```

`s` holds the run's `input` and each earlier step's output by its id. `when`, `args`, `stop` and
the other functions must read only `s`: a run is replayed from its step results, so they run again.
A function that throws ends the run `failed` with its message.

| Step | What it does | Retries |
|---|---|---|
| `step.read(id, capability, opts)` | An R0 or R1 call. A refusal ends the run `stopped` | The runner's, or `retries` |
| `step.write(id, capability, opts)` | An R2 to R3 call. R3 waits for its approval | Never |
| `step.task(id, unit, { input })` | `ai.run` on a task unit; a task with a target saves through the guard | Never, when it saves |
| `step.actor(id, actor, { prefill })` | Starts an actor session and waits until it ends | Never |
| `step.notify(id, template, { data })` | The product's `notify` hook with a fixed template, never model text | Never |
| `step.bulk(id, capability, { items, args, chunk })` | One capability over many items, in chunks | Reads only |

Options on read and write steps:

- `when(s)`: run the step only when it holds; otherwise `skipped` with code `condition`.
- `skipIf: 'not_built'`: when the capability is not in the registry yet, the step is `skipped`
  and `todo(s)` goes to a person through `handoff`.
- `stop(output, s)`: a reason here ends the run `stopped` after the step.
- `confirm: 'upstream'` on a write: the person already confirmed this R2 change. See below.

A workflow reaches R3 at most by default (`maxTier`). R4 belongs at the console with a person's
step-up.

### R2 writes need `confirm: 'upstream'`

An R2 change needs a person to confirm its preview. A workflow has nobody to show the preview to,
so it cannot confirm for anyone. The rule:

- With `confirm: 'upstream'` on the step, the R2 write runs. The guard still mints and checks the
  confirm token in one call, refuses `stale` when the target moved since the preview, and logs
  both steps. Put it on a step only when a person already confirmed this exact change before the
  run started: a form they submitted, an import they reviewed, a card they clicked.
- Without it, the guard answers `confirm_required`. The step is `refused` with code
  `confirm_required`, `handoff` gets kind `confirm` with `waits: true`, and the run waits for the
  person to settle it with `flows.resolve`.
- A dry run says which way it would go: `add: would go to a person to confirm: add Rashed`.
- R3 and above ignore `confirm: 'upstream'`: they always wait for an approval.
- On a bulk step, `confirm: 'upstream'` covers every R2 item; without it each item is refused and
  the chunk goes to a person.

## Wire it

```ts
const store = d1FlowStore(env.DB)              // FLOW_MIGRATIONS once; AI_MIGRATIONS for ai.runs
const deps: FlowDeps<AppCtx> = {
  ai, guard, registry, store,
  roles: (ctx) => rolesOf(ctx),                 // an automation's owner check
  notify: (ctx, n) => sendTemplate(n.template, n.data),
  handoff: (ctx, h) => financeInbox.add(h),     // failed writes, not built steps, expired approvals
  report: (ctx, r) => financeInbox.dryRun(r),   // a dry run's lines
}
const flows = createFlows({ store, runs: ai.runs, starter: cloudflareStarter({ payment_fulfil: env.PAYMENT_FULFIL }) })
const guard = createGuard({ ..., onApproval: (e) => flows.onApproval(e) })
```

On Cloudflare Workflows, pass Cloudflare's base class in. The kit never imports
`cloudflare:workers`, so it still loads in Node and Bun.

```ts
import { WorkflowEntrypoint } from 'cloudflare:workers'
export class PaymentFulfil extends flowEntrypoint(WorkflowEntrypoint, paymentFulfil, (env: Env) => depsFor(env)) {}
```

```toml
[[workflows]]
name = "payment-fulfil"
binding = "PAYMENT_FULFIL"
class_name = "PaymentFulfil"
```

Start a run by key. A second start with the same key answers `exists` and starts nothing.

```ts
await flows.start(ctx, paymentFulfil, `fulfil:${paymentId}`, { input: { payment_id: paymentId } })
```

Cloudflare refuses some characters in an instance id, such as `:`. `instanceIdFor(key)` keeps the
key's letters and adds a hash; the run keeps your key everywhere else.

## The ledger

A run's record is the ai kit's effects ledger (`ai_effects`), under an ai run with the run's key as
its id. There is no separate step table: `flow_runs`, `flow_links` and `flow_automations` hold
only what orchestration needs.

- A guard call is its own row, tagged with the step: `ok`, `pending_approval`, a refusal, `error`.
- What the run decides itself goes in through `ai.recordInRun`: `skipped`, `planned`, `waiting`,
  `failed`, `refused` (a budget, a refused or expired approval, a confirm a workflow cannot give),
  and `ok` for an approved change run later, a task or a notice.
- A dry run's write is a preview-only row (`planned`, `preview: true`) from `ai.previewInRun`.
- A bulk chunk is `<step>#<n>`: one guard row per item, then the chunk's summary row.

`flows.steps(key)` folds the rows into where each step stands: `planned`, `skipped`, `waiting`,
`ok`, `refused` or `failed`, with the latest row's outcome, code and message, and the approval
id, tier and ref from any of its rows. `ai.runs.effects(key)` gives every row.

`flows.run(key)` gives the run's status: `queued`, `running`, `waiting`, then `ok` (every step
ran or was skipped), `stopped`, `failed`, `refused` or `nothing`. A finished run and a finished
step are both `ok`, the same word the guard and the ai ledger use.

## Approvals

An R3 write asks the guard, which holds the change for a person. The step is `waiting` with the
approval id, the run is `waiting`, and the Workflow sleeps in `waitForEvent` at no cost.

- `flows.onApproval` as the guard's `onApproval` hook wakes the run when the approval is decided
  or expires, and when the approved change runs and ends `executed`, `failed` or `stale`.
- `flows.approvalSettled(approvalId)` is a fallback for a guard whose events cannot reach
  `flows.onApproval`, such as one in another Worker. With the hook wired you never call it.
- Approved and run: `ok` with the result. Refused by the approver: `refused`, and the run goes
  on to the next step. Expired, stale or failed: it goes to a person.

The approval's requester is the run's seat, so a four eyes policy keeps the automation's owner
from deciding its own run's changes.

## When a write fails

A write runs once. When it fails, or the guard refuses it, the step is `failed` or `refused`, the
`handoff` hook gets the message with `waits: true`, and the run waits. The person settles it:

```ts
await flows.resolve('fulfil:pay_42', 'level', { action: 'continue', output: { level: 'professional' }, by: 'u_rina' })
await flows.resolve('fulfil:pay_42', 'level', { action: 'stop', by: 'u_rina' })
```

`continue` gives later steps the output the person made by hand. Nobody within `resolveTimeout`
(7 days by default) ends the run `failed`.

## Bulk steps

```ts
step.bulk('purge', 'tenant_rows_purge', { items: (s) => s.list.ids, args: (id) => ({ id }), chunk: 50 })
```

Each chunk is one durable step, so it stays inside one Worker invocation and D1's 100 bound values
per statement. `chunk` is 25 by default, at most 100. A bulk step whose chunks would pass the run's
step cap (`maxSteps`, 1,000 by default) is refused before any item runs: split the work. A chunk
with failed writes goes to a person. Bulk steps are for R0 to R2.

## Dry run

In dry run, reads run, and every write goes to `guard.preview`: the switches, the arguments, the
tenant, your `can()`, the seat's tier ceiling and `readOnly`, then the capability's `preview`.
Nothing runs, no token is minted, no approval is asked for. A write that passes is `planned` with
the preview's sentence; one the guard refuses is `refused` with its code, so permission applies in
dry run too. Actors and notices are not started or sent. The run's `report` holds the lines, and
the `report` hook gets them:

```
level: would set tA from essential to professional
go_live: would make tA live on order INV-0042
tell: would send payment_fulfilled
add: would be refused (no_permission): You do not have permission to do this.
```

## Automations

```ts
export const fulfilOnApprove = automation({
  id: 'payment_fulfil',
  on: on.event('payment.approve', { rail: 'manual_bank', purpose: 'billing' }),
  run: paymentFulfil,
  instanceId: (e) => `fulfil:${e.payment_id}`,
  owner: 'finance_lead',
  budget: { runsPerDay: 50 },
  mode: 'dry_run',
})

const automations = createAutomations({ automations: [fulfilOnApprove], store, starter, roles })
await automations.enable(financeLeadCtx, 'payment_fulfil')                 // starts in dry run
await automations.setMode(financeLeadCtx, 'payment_fulfil', 'live')         // once finance signs off
await automations.dispatch({ type: 'payment.approve', tenant: null, data }) // from the event
await automations.tick(Date.now())                                          // from the scheduled handler
```

| Trigger | Example |
|---|---|
| `on.event(type, match)` | `payment.approve` for a billing manual bank payment |
| `on.schedule(cron, { tz })` | `0 9 * * 0`, Sundays at 09:00, in UTC by default |
| `on.condition(cron, check, { tz })` | `check(ctx, at)` returns the items to act on; each starts a run |

- **Owner.** An automation runs under the seat of the person who enabled it, who must hold the
  `owner` role. When they lose it, the next event or step turns the automation off
  (`owner_lost_role`) and its running runs stop. Someone holding the role turns it on again.
- **Budget.** `runsPerDay`, `runsPerMonth` and `usdPerMonth` (model spend by its task steps). A run
  past the budget is refused and recorded with the reason.
- **Switch.** `disable`, or a guard switch with key `automation:<id>` at global, tenant or person
  scope.
- **Nothing to report.** A condition that finds nothing records a `nothing` run and starts none.
  A workflow's `nothingToReport(s)` keeps its notices from being delivered.

### Schedules and time zones

Cron is five fields: `*`, lists, ranges and steps. Call `automations.tick()` every minute from the
Worker's scheduled handler (`* * * * *`); each automation reads its own cron.

A schedule is read in UTC unless you give `tz`:

- An IANA zone, such as `{ tz: 'Asia/Dhaka' }`, for every tenant.
- `{ tz: 'tenant' }` for each tenant's own zone, from `timeZone(tenant)` on `createAutomations`.
  "Sunday 09:00 tenant time" is then 03:00 UTC for a tenant in Dhaka and 14:00 or 13:00 UTC for
  one in New York, depending on the season.

```ts
const weekly = automation({ id: 'weekly_summary', on: on.schedule('0 9 * * 0', { tz: 'tenant' }), run: summary, owner: 'ops' })
const automations = createAutomations({ automations: [weekly], store, starter, roles, timeZone: (tenant) => tenantZone(tenant) })
```

Zones come from the runtime's `Intl` data, with no dependency. An unknown zone in `on.schedule`
throws `CronError` when the module loads. A tenant whose zone the runtime does not know gets a
`bad_time_zone` result from `tick` and no run.

Across a daylight saving change the fields are wall-clock time. A time in the skipped hour (02:30
on the night clocks go forward in New York) does not occur that day. A time in the repeated hour
(01:30 on the night they go back) matches twice, but a schedule's run key is the local minute,
such as `weekly_summary:tA:2026-11-08T09:00`, so the second tick finds the run and starts none.
Pick times outside 01:00 to 03:00 for zones that change their clocks. Asia/Dhaka has no daylight
saving time.

## Tests

`memoryRunner(deps, workflows)` runs workflows in memory the way Workflows does: it keeps each
step's result, replays the run from them on every wake, retries a step up to its limit, buffers
events and times waits out on its own clock.

```ts
const runner = memoryRunner(deps, [paymentFulfil])
const flows = createFlows({ store, runs: ai.runs, starter: runner })
await flows.start(ctx, paymentFulfil, 'fulfil:pay_1', { input: { payment_id: 'pay_1' } })
await runner.idle()
runner.status('fulfil:pay_1')            // 'waiting'; the run's status once it ends, such as 'ok'
runner.attempts('fulfil:pay_1', 'level') // 1: writes never retry
await runner.advance(25 * 3_600_000)     // time out the approval
```

The worked example, with its tests, is in the SDK repository:
`typescript/examples/flows-payment-fulfil.ts`, and on Workflows `examples/flows-worker.ts`.
